Skip to content

Latest commit

 

History

History
76 lines (57 loc) · 1.91 KB

_1852. Distinct Numbers in Each Subarray.md

File metadata and controls

76 lines (57 loc) · 1.91 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 27, 2024

Last updated : February 01, 2025


Related Topics : Array, Hash Table, Sliding Window

Acceptance Rate : 76.9 %


Solutions

Java

class Solution {
    public int[] distinctNumbers(int[] nums, int k) {
        int[] output = new int[nums.length - k + 1];
        HashMap<Integer, Integer> window = new HashMap<>();

        for (int i = 0; i < k - 1; i++) {
            window.put(nums[i], window.getOrDefault(nums[i], 0) + 1);
        }

        for (int i = k - 1; i < nums.length; i++) {
            window.put(nums[i], window.getOrDefault(nums[i], 0) + 1);

            output[i - k + 1] = window.size();

            if (window.get(nums[i - k + 1]) == 1) {
                window.remove(nums[i - k + 1]);
            } else {
                window.put(nums[i - k + 1], window.get(nums[i - k + 1]) - 1);
            }
        }

        return output;
    }
}

Python

class Solution:
    def distinctNumbers(self, nums: List[int], k: int) -> List[int]:
        output = []
        arr = deque([-1] + nums[:k - 1])
        cnt = Counter(arr)
        for val in nums[k - 1:] :
            rem = arr.popleft()
            if cnt[rem] == 1 :
                cnt.pop(rem)
            else :
                cnt[rem] -= 1

            arr.append(val)
            cnt[val] += 1
            output.append(len(cnt))

        return output