짬뽕얼큰하게의 맨땅에 헤딩 :: Count Complete Subarrays in an Array

Leetcode Problem:

Summary

  • Count the number of complete subarrays in a given array of positive integers.

Approach

  • The solution uses a sliding window approach with two unordered maps
  • The first map stores the frequency of each element in the array, and the second map stores the frequency of each element in the current subarray
  • The time complexity is O(n^2) due to the nested loops, where n is the size of the array.

Complexity

  • O(n^2)

Explanation

  • The solution first counts the frequency of each element in the array and stores it in the first unordered map
  • Then, it iterates over the array with a sliding window approach
  • For each window, it creates a new unordered map to store the frequency of each element in the current subarray
  • If the size of the current subarray is equal to the size of the first unordered map, it increments the answer by the length of the current subarray plus one (to include the current element)
  • Finally, it returns the answer.

Solution Code:


class Solution {
public:
    unordered_map m;
    int countCompleteSubarrays(vector& nums) {
        
        for(int i = 0 ; i < nums.size(); i++){
            m[nums[i]] = true;
        }
        int ans = 0;
        for(int i = 0 ; i < nums.size(); i++){
            unordered_map m2;
            for(int j = i; j >= 0; j--){
                m2[nums[j]] = true;
                if(m2.size() == m.size()){
                    ans += j + 1;
                    break;
                }
            }
        }
        return ans;
    }
};

'알고리즘' 카테고리의 다른 글

Count Subarrays With Fixed Bounds  (0) 2025.04.26
Count of Interesting Subarrays  (0) 2025.04.25
Count Largest Group  (0) 2025.04.23
Count the Number of Ideal Arrays  (1) 2025.04.22
Count the Hidden Sequences  (0) 2025.04.21
블로그 이미지

짬뽕얼큰하게

,