Check if an Array Is Consecutive Problem
#2229
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2229.
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 1:
Input: nums = [1,3,4,2]
Output: true
Explanation:
The minimum value is 1 and the length of nums is 4.
All of the values in the range [x, x + n - 1] = [1, 1 + 4 - 1] = [1, 4] = (1, 2, 3, 4) occur in nums.
Therefore, nums is consecutive.
Example 2:
Input: nums = [1,3]
Output: false
Explanation:
The minimum value is 1 and the length of nums is 2.
The value 2 in the range [x, x + n - 1] = [1, 1 + 2 - 1], = [1, 2] = (1, 2) does not occur in nums.
Therefore, nums is not consecutive.
Example 3:
Input: nums = [3,5,4]
Output: true
Explanation:
The minimum value is 3 and the length of nums is 3.
All of the values in the range [x, x + n - 1] = [3, 3 + 3 - 1] = [3, 5] = (3, 4, 5) occur in nums.
Therefore, nums is consecutive.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^5
Solution
Approach: Hash Set
An array of length n is consecutive exactly when its values are all different and the largest minus the smallest is n - 1.
Put the values in a set and track the minimum and maximum. If the set has n elements (no duplicates) and max - min + 1 == n, return true; otherwise return false.
Complexity: O(n) time and O(n) space.
class Solution:
def isConsecutive(self, nums: List[int]) -> bool:
mi, mx = min(nums), max(nums)
return len(set(nums)) == mx - mi + 1 == len(nums)