Skip to content

2799. Count Complete Subarrays in an Array 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int countCompleteSubarrays(vector<int>& nums) {
    constexpr int kMax = 2000;
    const int totalDistinct =
        unordered_set<int>(nums.begin(), nums.end()).size();
    int ans = 0;
    int distinct = 0;
    vector<int> count(kMax + 1);

    int l = 0;
    for (const int num : nums) {
      if (++count[num] == 1)
        ++distinct;
      while (distinct == totalDistinct)
        if (--count[nums[l++]] == 0)
          --distinct;
      // Assume nums[r] = num,
      // nums[0..r], nums[1..r], ..., nums[l - 1..r] have k different values.
      ans += l;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int countCompleteSubarrays(int[] nums) {
    final int kMax = 2000;
    final int totalDistinct = Arrays.stream(nums).boxed().collect(Collectors.toSet()).size();
    int ans = 0;
    int distinct = 0;
    int[] count = new int[kMax + 1];

    int l = 0;
    for (final int num : nums) {
      if (++count[num] == 1)
        ++distinct;
      while (distinct == totalDistinct)
        if (--count[nums[l++]] == 0)
          --distinct;
      // Assume nums[r] = num,
      // nums[0..r], nums[1..r], ..., nums[l - 1..r] have k different values.
      ans += l;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def countCompleteSubarrays(self, nums: list[int]) -> int:
    ans = 0
    distinct = len(set(nums))
    count = collections.Counter()

    l = 0
    for num in nums:
      count[num] += 1
      while len(count) == distinct:
        count[nums[l]] -= 1
        if count[nums[l]] == 0:
          del count[nums[l]]
        l += 1
      # Assume nums[r] = num,
      # nums[0..r], nums[1..r], ..., nums[l - 1..r] have k different values.
      ans += l

    return ans