Problem Description
Given an integer array nums, determine whether nums is consecutive. 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.
Key Insights
- The array must contain exactly n distinct numbers.
- The numbers should form a continuous sequence without any gaps.
- Using the minimum (x) and the maximum (max) values, we can quickly verify if the range matches the array length.
- A set is an effective data structure to detect duplicates and allow O(1) membership checks.
Space and Time Complexity
Time Complexity: O(n) – We scan the array to compute min, max, and build the set. Space Complexity: O(n) – The set used for storing unique elements takes O(n) space.
Solution
The solution begins by identifying the minimum value in nums and computing the maximum value, then checking if (max - min + 1) equals the length of the array. If not, the array cannot be consecutive. Next, we convert the array into a set to eliminate duplicates. If the size of the set is equal to the length of the array and the range is appropriate, then all consecutive numbers are present, and we return true. Otherwise, we return false.