Created
April 24, 2025 20:58
-
-
Save tatsuyax25/598c19b9f994497f9720bcdb2b7e277f to your computer and use it in GitHub Desktop.
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 a
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Counts the number of subarrays that contain all distinct elements from the input array. | |
* @param {number[]} nums - The input array of numbers. | |
* @return {number} - The count of complete subarrays. | |
*/ | |
var countCompleteSubarrays = function(nums) { | |
let count = 0; // Keeps track of the number of complete subarrays | |
let set = new Set(); | |
// Determine the number of distinct elements in the array | |
for (let num of nums) { | |
set.add(num); | |
} | |
const numDistinct = set.size; // Stores total number of unique elements | |
set.clear(); // Clear set for re-use | |
// Iterate through all possible subarrays | |
for (let i = 0; i < nums.length; i++) { | |
for (let j = i; j < nums.length; j++) { | |
set.add(nums[j]); // Add elements to the set | |
// If the set size matches the number of distinct elements, it's a complete subarray | |
if (set.size === numDistinct) { | |
count++; | |
} | |
} | |
set.clear(); // Reset the set for the next starting position | |
} | |
return count; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment