Skip to content

2229. Check if an Array Is Consecutive 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
 public:
  bool isConsecutive(vector<int>& nums) {
    const int n = nums.size();
    const int max = ranges::max(nums);
    const int min = ranges::min(nums);
    return max - min + 1 == n &&
           unordered_set<int>{nums.begin(), nums.end()}.size() == n;
  }
};
1
2
3
4
5
6
7
8
9
class Solution {
  public boolean isConsecutive(int[] nums) {
    final int n = nums.length;
    final int max = Arrays.stream(nums).max().getAsInt();
    final int min = Arrays.stream(nums).min().getAsInt();
    return max - min + 1 == n &&
        Arrays.stream(nums).boxed().collect(Collectors.toSet()).size() == n;
  }
}
1
2
3
class Solution:
  def isConsecutive(self, nums: List[int]) -> bool:
    return max(nums) - min(nums) + 1 == len(set(nums)) == len(nums)