Check if an Array Is Consecutive - Problem
Given an integer array nums, determine if the array contains consecutive integers that form a complete sequence.
An array is considered consecutive if it contains every number in the range [x, x + n - 1] (inclusive), where:
xis the minimum number in the arraynis the length of the array
Return true if the array is consecutive, false otherwise.
Example: The array [4, 2, 1, 3] is consecutive because it contains all numbers from 1 to 4. However, [1, 3, 4] is not consecutive because it's missing 2.
Input & Output
example_1.py โ Basic Consecutive Array
$
Input:
[1, 3, 2, 4]
โบ
Output:
true
๐ก Note:
The array contains all numbers from 1 to 4. After sorting: [1,2,3,4] - each adjacent pair differs by 1, forming a complete consecutive sequence.
example_2.py โ Missing Number
$
Input:
[1, 3, 4]
โบ
Output:
false
๐ก Note:
The minimum is 1 and length is 3, so we expect [1,2,3]. However, the number 2 is missing from the array, making it non-consecutive.
example_3.py โ Single Element
$
Input:
[5]
โบ
Output:
true
๐ก Note:
A single element is always consecutive. The expected range is [5,5] which contains only the number 5, and it exists in the array.
Visualization
Tap to expand
Understanding the Visualization
1
Catalog Your Books
Create a quick-lookup catalog (hash set) of all books you have
2
Determine Expected Range
Find the lowest volume number and calculate expected range
3
Check Each Volume
For each expected volume, instantly check if it exists in your catalog
Key Takeaway
๐ฏ Key Insight: Instead of searching for each expected number repeatedly, create a hash set for instant O(1) lookups. This transforms an O(nยฒ) search problem into an O(n) lookup problem.
Time & Space Complexity
Time Complexity
O(n)
O(n) to create hash set + O(n) to check all expected numbers = O(n)
โ Linear Growth
Space Complexity
O(n)
Hash set stores all n numbers from the input array
โก Linearithmic Space
Constraints
- 0 โค nums.length โค 105
- -109 โค nums[i] โค 109
- All elements in nums are integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code