Skip to content

Latest commit

 

History

History
50 lines (34 loc) · 897 Bytes

File metadata and controls

50 lines (34 loc) · 897 Bytes

Count Complete Subarrays

Problem Link

https://leetcode.com/problems/count-complete-subarrays-by-the-number-of-distinct-integers/


Pattern

  • Sliding Window

Approach

Count elements with distinct count equal to total distinct in array.


Time Complexity

O(n)

Space Complexity

O(n)


Java Solution

import java.util.*;
class Solution {
    public int countCompleteSubarrays(int[] nums) {
        Set<Integer> distinct = new HashSet<>();
        for (int n : nums) distinct.add(n);
        int target = distinct.size(), ans = 0;
        for (int left = 0; left < nums.length; left++) {
            Set<Integer> window = new HashSet<>();
            for (int right = left; right < nums.length; right++) {
                window.add(nums[right]);
                if (window.size() == target) ans++;
            }
        }
        return ans;
    }
}