We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Check if an Array Is Consecutive

Number: 1416

Difficulty: Easy

Paid? Yes

Companies: N/A


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.


Code Solutions

# Function to check if array nums is consecutive
def isConsecutive(nums):
    # Calculate the minimum and maximum values in the array
    minimum = min(nums)
    maximum = max(nums)
    
    # Check if the range [minimum, maximum] contains exactly len(nums) numbers
    # If not, array cannot be consecutive
    if maximum - minimum + 1 != len(nums):
        return False
    
    # Create a set from the array to remove duplicates and quickly check membership.
    unique_nums = set(nums)
    
    # If the size of the set is equal to len(nums), then no duplicates exist;
    # hence, all numbers in the range must be present.
    return len(unique_nums) == len(nums)

# Example usage:
print(isConsecutive([1,3,4,2]))  # Expected output: True
print(isConsecutive([1,3]))      # Expected output: False
print(isConsecutive([3,5,4]))    # Expected output: True
← Back to All Questions