Leetcode Problem 1852. Distinct Numbers in Each Subarray
1852. Distinct Numbers in Each Subarray
AI Mock Interview
Leetcode Solutions
Sliding Window with Frequency Map
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Initialize an empty frequency map (hash map) and an empty list
ans
to store the results.
Iterate over the first
k
elements of
nums
and update the frequency map with the count of each number.
Add the size of the frequency map to
ans
as it represents the number of distinct numbers in the first window.
Iterate over the rest of the elements in
nums
starting from index
k
.
Decrement the frequency of the element that is no longer in the window (element at index
i - k
).
If the frequency of that element becomes 0, remove it from the frequency map.
Increment the frequency of the new element (element at index
i
).
If the new element is not in the frequency map, add it with a frequency of 1.
Add the current size of the frequency map to
ans
.
Return the list
ans
.
Brute Force with Sliding Subarrays
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...