Skip to content

Latest commit

 

History

History
87 lines (79 loc) · 3.12 KB

README.md

File metadata and controls

87 lines (79 loc) · 3.12 KB

You are given an array nums consisting of positive integers.

We call a subarray of an array complete if the following condition is satisfied:

  • The number of distinct elements in the subarray is equal to the number of distinct elements in the whole array.

Return the number of complete subarrays.

A subarray is a contiguous non-empty part of an array.

 

Example 1:

Input: nums = [1,3,1,2,2]
Output: 4
Explanation: The complete subarrays are the following: [1,3,1,2], [1,3,1,2,2], [3,1,2] and [3,1,2,2].

Example 2:

Input: nums = [5,5,5,5]
Output: 10
Explanation: The array consists only of the integer 5, so any subarray is complete. The number of subarrays that we can choose is 10.

 

Constraints:

  • 1 <= nums.length <= 1000
  • 1 <= nums[i] <= 2000

Companies: TikTok

Related Topics:
Array, Hash Table, Sliding Window

Similar Questions:

Solution 1. Two Pointers

// OJ: https://leetcode.com/problems/count-complete-subarrays-in-an-array
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    int countCompleteSubarrays(vector<int>& A) {
        unordered_set<int> s(begin(A), end(A));
        int i = 0, j = 0, N = A.size(), ans = 0;
        unordered_map<int, int> m;
        for (; i < N; ++i) {
            while (j < N && m.size() < s.size()) m[A[j++]]++;
            if (m.size() < s.size()) break;
            ans += N - j + 1;
            if (--m[A[i]] == 0) m.erase(A[i]);
        }
        return ans;
    }
};

Solution 2. Find Minimum Sliding Window

// OJ: https://leetcode.com/problems/count-complete-subarrays-in-an-array
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
    int countCompleteSubarrays(vector<int>& A) {
        unordered_set<int> s(begin(A), end(A));
        int i = 0, j = 0, N = A.size(), ans = 0, last = -1;
        unordered_map<int, int> m;
        for (; j < N; ++j) {
            m[A[j]]++;
            while (m.size() == s.size()) {
                if (--m[A[i]] == 0) m.erase(A[i]);
                last = i;
                ++i;
            }
            if (last != -1) ans += last + 1;
        }
        return ans;
    }
};