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 mx = ranges::max(nums);
    const int mn = ranges::min(nums);
    return mx - mn + 1 == n &&
           unordered_set<int>{nums.begin(), nums.end()}.size() == n;
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public boolean isConsecutive(int[] nums) {
    final int n = nums.length;
    final int mx = Arrays.stream(nums).max().getAsInt();
    final int mn = Arrays.stream(nums).min().getAsInt();
    return mx - mn + 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)