Check if an Array Is Consecutive - 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.

Input & Output

Example 1 — Consecutive Array
$ Input: nums = [1,3,2,5,4]
Output: true
💡 Note: The minimum is 1, array length is 5. Expected range [1,2,3,4,5] - all numbers present, so it's consecutive.
Example 2 — Missing Number
$ Input: nums = [1,0,3]
Output: false
💡 Note: The minimum is 0, array length is 3. Expected range [0,1,2] but we have [0,1,3] - missing 2, so not consecutive.
Example 3 — Duplicate Numbers
$ Input: nums = [1,1,2,3]
Output: false
💡 Note: Contains duplicates. For consecutive array [1,2,3,4], we need unique numbers 1,2,3,4 but have 1,1,2,3.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -106 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Check if Array Is Consecutive INPUT nums = [1, 3, 2, 5, 4] 1 idx 0 3 idx 1 2 idx 2 5 idx 3 4 idx 4 Input Values n = 5 (array length) min = 1 max = 5 Expected range: [1, 2, 3, 4, 5] ALGORITHM STEPS 1 Create Hash Set Add all elements to set Set: {1, 3, 2, 5, 4} Size: 5 (no duplicates) 2 Find Min and Max min=1, max=5 3 Check Range max - min + 1 == n? 5 - 1 + 1 = 5 5 == 5 (OK) 4 Verify All Present Check each in range 1 in set? OK 2 in set? OK 3 in set? OK 4 in set? OK 5 in set? OK FINAL RESULT Sorted view of array: 1 2 3 4 5 All numbers from 1 to 5 present Output: true Confirmation - No duplicates: OK - Range valid: OK - All present: OK Key Insight: For an array to be consecutive, it must have exactly n unique elements spanning from min to max where max - min + 1 equals n. Using a Hash Set allows O(n) time complexity by avoiding sorting and enabling O(1) lookups for membership checks. TutorialsPoint - Check if an Array Is Consecutive | Hash Set Approach
Asked in
Google 15 Amazon 12 Microsoft 8
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen