{x}
blog image

Check if an Array Is Consecutive

Solution Explanation: Check if an Array Is Consecutive

This problem asks whether a given integer array nums is consecutive. An array is considered consecutive if it contains all numbers within the range from its minimum element to its maximum element, inclusive.

Approach: Using a Hash Set (or Set) and Efficient Checks

The most efficient approach leverages a hash set (or set in languages like Python) to quickly check for duplicates and to determine if all numbers within the expected range are present.

  1. Find Minimum and Maximum: First, find the minimum (mi) and maximum (mx) values in the input array nums.

  2. Check for Duplicates and Range: A hash set (s) is used to store each element encountered while iterating through nums. If a duplicate is found (an element already exists in s), the array is not consecutive, and false is returned. Simultaneously, update mi and mx.

  3. Consecutive Check: After iterating through the entire array, check if the number of unique elements (the size of the hash set s) is equal to the expected range size (mx - mi + 1). If it is, and this also equals the length of the input array (ensuring no missing elements), the array is consecutive, and true is returned. Otherwise, it's not consecutive, and false is returned.

Time and Space Complexity Analysis

  • Time Complexity: O(n), where n is the length of the input array nums. This is because we iterate through the array once to find the minimum and maximum and to populate the hash set. Hash set lookups (checking for duplicates) are on average O(1).

  • Space Complexity: O(n) in the worst case. This is because the hash set could potentially store all n elements of the input array if there are no duplicates and if the array is indeed consecutive.

Code Implementation in Multiple Languages

The solutions below implement the described approach in various programming languages. Note the slight variations in syntax and built-in functions for sets/hash sets across languages.

class Solution:
    def isConsecutive(self, nums: List[int]) -> bool:
        mi, mx = min(nums), max(nums)
        return len(set(nums)) == mx - mi + 1 == len(nums)
 
class Solution {
    public boolean isConsecutive(int[] nums) {
        int mi = nums[0], mx = nums[0];
        Set<Integer> s = new HashSet<>();
        for (int x : nums) {
            if (!s.add(x)) { //Efficient duplicate check using set.add()
                return false;
            }
            mi = Math.min(mi, x);
            mx = Math.max(mx, x);
        }
        return mx - mi + 1 == nums.length;
    }
}
class Solution {
public:
    bool isConsecutive(vector<int>& nums) {
        unordered_set<int> s;
        int mi = nums[0], mx = nums[0];
        for (int x : nums) {
            if (s.count(x)) { //Efficient duplicate check using unordered_set.count()
                return false;
            }
            s.insert(x);
            mi = min(mi, x);
            mx = max(mx, x);
        }
        return mx - mi + 1 == nums.size();
    }
};
func isConsecutive(nums []int) bool {
	s := map[int]bool{}
	mi, mx := nums[0], nums[0]
	for _, x := range nums {
		if s[x] {
			return false
		}
		s[x] = true
		if x < mi {
			mi = x
		}
		if x > mx {
			mx = x
		}
	}
	return mx-mi+1 == len(nums)
}
 
function isConsecutive(nums: number[]): boolean {
    let mi = nums[0], mx = nums[0];
    const s = new Set<number>();
    for (const x of nums) {
        if (s.has(x)) {
            return false;
        }
        s.add(x);
        mi = Math.min(mi, x);
        mx = Math.max(mx, x);
    }
    return mx - mi + 1 === nums.length;
}
/**
 * @param {number[]} nums
 * @return {boolean}
 */
var isConsecutive = function (nums) {
    let mi = nums[0], mx = nums[0];
    const s = new Set();
    for (const x of nums) {
        if (s.has(x)) {
            return false;
        }
        s.add(x);
        mi = Math.min(mi, x);
        mx = Math.max(mx, x);
    }
    return mx - mi + 1 === nums.length;
};

These code snippets all efficiently solve the problem with the same time and space complexity. The choice of language depends on your preference and the context of your application.