DEV Community

Cover image for Day 97 of 100 days dsa coding challenge
Manasi Patil
Manasi Patil

Posted on

Day 97 of 100 days dsa coding challenge

Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! πŸ’»πŸ”₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! πŸš€

100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney

Problem:

https://www.geeksforgeeks.org/problems/subarrays-with-at-most-k-distinct-integers/1

Subarrays With At Most K Distinct Integers

Difficulty: Medium Accuracy: 62.09%

You are given an array arr[] of positive integers and an integer k, find the number of subarrays in arr[] where the count of distinct integers is at most k.
Note: A subarray is a contiguous part of an array.

Examples:
Input: arr[] = [1, 2, 2, 3], k = 2
Output: 9
Explanation: Subarrays with at most 2 distinct elements are: [1], [2], [2], [3], [1, 2], [2, 2], [2, 3], [1, 2, 2] and [2, 2, 3].
Input: arr[] = [1, 1, 1], k = 1
Output: 6
Explanation: Subarrays with at most 1 distinct element are: [1], [1], [1], [1, 1], [1, 1] and [1, 1, 1].
Input: arr[] = [1, 2, 1, 1, 3, 3, 4, 2, 1], k = 2
Output: 24
Explanation: There are 24 subarrays with at most 2 distinct elements.
Constraints:
1 ≀ arr.size() ≀ 2*104
1 ≀ k ≀ 2*104
1 ≀ arr[i] ≀ 109

Solution:
class Solution:
def countAtMostK(self, arr, k):
# Code here
from collections import Counter

    cnt = Counter()
    left = 0
    ans = 0

    for r, e in enumerate(arr):
        cnt[e] += 1
        while len(cnt) > k and left <= r:
            cnt[arr[left]] -= 1
            if cnt[arr[left]] == 0:
                cnt.pop(arr[left])
            left += 1
        ans += r-left+1
    return ans
Enter fullscreen mode Exit fullscreen mode

Top comments (0)