Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Time Complexity: O(N * K)
- Space Complexity: O(K + number of distinct elements)
- Idea:
- We process the array one element at a time (streaming).
- We maintain:
- 1) A frequency map -> stores how many times each number has appeared so far.
- 2) A small array "top" of size K + 1:
- - top[0] to top[K-1] always store the current top K most frequent numbers.
- - top[K] is a temporary place to insert the current number.
- Process for each element:
- 1) Increase the frequency of the current number in the map.
- 2) Put the current number at position top[K].
- 3) Find where this number already exists in top[0..K-1] (if present).
- Since only the current number’s frequency changed,
- only this number can move to the left in the top list.
- 4) Move this number left by swapping while:
- - Its frequency is greater than the left neighbor, or
- - Frequency is same but the number is smaller.
- All other elements are already in correct order, so no full sorting is needed.
- After adjustment, top[0..K-1] always contains the current top K frequent numbers
- in correct order.
- */
- class Solution:
- def kTop(self, a, N, K):
- freq = {}
- top = [0] * (K + 1)
- result = []
- for i in range(N):
- x = a[i]
- # update frequency
- if x in freq:
- freq[x] += 1
- else:
- freq[x] = 1
- # put current element at last position
- top[K] = x
- # find first position of x in top[0..K-1]
- j = 0
- while j < K:
- if top[j] == x:
- break
- j += 1
- # move left while needed
- while j > 0:
- # if left side is empty (0), just swap
- if top[j-1] == 0:
- top[j], top[j-1] = top[j-1], top[j]
- # higher frequency first
- elif freq[top[j]] > freq[top[j-1]]:
- top[j], top[j-1] = top[j-1], top[j]
- # same frequency, smaller number first
- elif freq[top[j]] == freq[top[j-1]] and top[j] < top[j-1]:
- top[j], top[j-1] = top[j-1], top[j]
- else:
- break
- j -= 1
- # collect current top K instead of printing
- current = []
- for l in range(K):
- if top[l] != 0:
- current.append(top[l])
- result.append(current)
- return result
Advertisement
Add Comment
Please, Sign In to add comment