Skip to content

Instantly share code, notes, and snippets.

@apoorvanand
Forked from viveksyngh/DNUMS.py
Created July 17, 2022 14:43
Show Gist options
  • Select an option

  • Save apoorvanand/5bd2292303ecd0432af0a6a213a0e699 to your computer and use it in GitHub Desktop.

Select an option

Save apoorvanand/5bd2292303ecd0432af0a6a213a0e699 to your computer and use it in GitHub Desktop.
You are given an array of N integers, A1, A2 ,…, AN and an integer K. Return the of count of distinct numbers in all windows of size K. Formally, return an array of size N-K+1 where i’th element in this array contains number of distinct elements in sequence Ai, Ai+1 ,…, Ai+k-1.
class Solution:
# @param A : list of integers
# @param B : integer
# @return a list of integers
def dNums(self, A, B):
mapOfNums = {}
count = 0
ptr = -1
res = []
if B > len(A) :
return res
else :
for i in range(0, len(A)):
if mapOfNums.get(A[i], 0) == 0:
count = count + 1
mapOfNums[A[i]] = 1
else :
mapOfNums[A[i]] += 1
if i >= B :
ptr += 1
mapOfNums[A[ptr]] -= 1
if mapOfNums[A[ptr]] == 0 :
count -= 1
if i >= B - 1:
res.append(count)
return res
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment