Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Parts of array with n different elements in JavaScript
We are required to write a JavaScript function that takes in an array of literals, arr, as the first argument. The second argument to our function will be a number, num. Our function should count and return the number of subarrays of the array that contains exactly num distinct elements.
Problem Statement
Given an array and a number, find all subarrays that contain exactly that many distinct elements.
For example, if the input to the function is:
const arr = [12, 15, 12, 15, 18]; const num = 2;
Then the output should be:
7
Output Explanation
Subarrays formed with exactly 2 different elements:
[12,15], [15,12], [12,15], [15,18], [12,15,12], [15,12,15], [12,15,12,15]
Algorithm Approach
We use a sliding window technique with two helper functions:
- findDistinct(count): Counts subarrays with at most 'count' distinct elements
- Main logic: Subarrays with exactly 'num' distinct elements = subarrays with at most 'num' - subarrays with at most 'num-1'
Complete Solution
const arr = [12, 15, 12, 15, 18];
const num = 2;
const distinctSubarrays = (arr = [], num = 1) => {
const findDistinct = (count) => {
const map = {};
let ptr = 0;
let distinct = 0;
let res = 0;
for(let right = 0; right < arr.length; right++){
const currentNum = arr[right];
map[currentNum] = (map[currentNum] || 0) + 1;
if(map[currentNum] === 1){
distinct += 1;
}
while(distinct > count){
map[arr[ptr]] -= 1;
if(map[arr[ptr]] === 0){
distinct -= 1;
}
ptr += 1;
}
res += right - ptr + 1;
}
return res;
};
return findDistinct(num) - findDistinct(num - 1);
};
console.log("Array:", arr);
console.log("Target distinct elements:", num);
console.log("Number of subarrays:", distinctSubarrays(arr, num));
Array: [ 12, 15, 12, 15, 18 ] Target distinct elements: 2 Number of subarrays: 7
How It Works
The sliding window approach maintains:
- Map: Tracks frequency of each element in current window
- Distinct counter: Counts unique elements in current window
- Two pointers: Left (ptr) and right boundaries of the window
For each right position, we expand the window and shrink from left when distinct count exceeds the limit.
Testing with Different Examples
// Test case 1
console.log("Test 1:", distinctSubarrays([1, 2, 1, 2, 3], 2)); // Expected: 7
// Test case 2
console.log("Test 2:", distinctSubarrays([1, 2, 3], 1)); // Expected: 3
// Test case 3
console.log("Test 3:", distinctSubarrays([1, 1, 1], 1)); // Expected: 6
Test 1: 7 Test 2: 3 Test 3: 6
Conclusion
This sliding window solution efficiently counts subarrays with exactly n distinct elements using the difference between "at most n" and "at most n-1" counts. The time complexity is O(n) and space complexity is O(k) where k is the number of distinct elements.
