Check if an Array Is Consecutive — LeetCode 2229 Python Solution

EasyLeetCode PremiumArrayHash TableSorting
Problem
#2229
Pattern
Sorting
Reading time
2 min

The problem

Given an integer array nums, return true if nums is consecutive, otherwise return false. An array is consecutive if it contains every number in the range [x, x + n - 1] (inclusive), where x is the minimum number in the array and n is the length of the array.

Example

Input
nums = [1,3,4,2]
Output
true
Explanation
The minimum value is 1 and the length of nums is 4.

Python solution

Python
class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        mi, mx = min(nums), max(nums)
        return len(set(nums)) == mx - mi + 1 == len(nums)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2229. Check if an Array Is Consecutive is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2229. Check if an Array Is Consecutive?
LeetCode 2229. Check if an Array Is Consecutive is rated Easy on LeetCode.
What is the time complexity of LeetCode 2229. Check if an Array Is Consecutive?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 2229. Check if an Array Is Consecutive?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 2229. Check if an Array Is Consecutive cover?
LeetCode 2229. Check if an Array Is Consecutive is tagged Array, Hash Table and Sorting on LeetCode.
Is LeetCode 2229. Check if an Array Is Consecutive a premium problem?
Yes. LeetCode 2229. Check if an Array Is Consecutive is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview