Find out K most frequent numbers from a given stream of numbers on the fly.
Answer / Suneel Kumar Singjh
To find out the K most frequent numbers from a given stream of numbers on the fly, you can use a data structure like a min-heap or a sliding window. Here's an example using a min-heap:nn```pythonnimport heapqnclass FrequentNumberCounter:n def __init__(self, k):n self.k = kn self.counter = {}
self.min_heap = []nn def add(self, num):n if num not in self.counter:n heapq.heappush(self.min_heap, (-num, 0))n self.counter[-num] = 0n self.counter[num] += 1n heapq.heapify(self.min_heap)n self.min_heap = sorted(self.min_heap, key=lambda x:x[0])[:self.k]nn def most_frequent_number(self):n if not self.counter:n return Nonen most_freq, freq = set(), 0n for num, count in self.counter.items():n if count > freq:n freq = countn most_freq.clear()n most_freq.add(num)n elif count == freq:n most_freq.add(num)n return list(most_freq)[0]
| Is This Answer Correct ? | 0 Yes | 0 No |
How can you check if a data set or time series is random?
Can you explain difference between data modeling and database design?
Burn two ropes, one needs 60 minutes of time to burn and the other needs 30 minutes of time. How will you achieve this in 45 minutes of time ?
What are essential skills and training needed in data Science?
Why is dimensional reduction performed before fitting a support vector machine (svm)?
A certain couple tells you that they have two children, at least one of which is a girl. What is the probability that they have two girls?
How can you select k for k-means?
Can you cite some examples where a false negative important than a false positive?
What is logistic and linear regression?
Is it possible to perform logistic regression with Microsoft Excel?
What are Random Forests?
Give a large dataset, find the median.
AI Algorithms (74)
AI Natural Language Processing (96)
AI Knowledge Representation Reasoning (12)
AI Robotics (183)
AI Computer Vision (13)
AI Neural Networks (66)
AI Fuzzy Logic (31)
AI Games (8)
AI Languages (141)
AI Tools (11)
AI Machine Learning (659)
Data Science (671)
Data Mining (120)
AI Deep Learning (111)
Generative AI (153)
AI Frameworks Libraries (197)
AI Ethics Safety (100)
AI Applications (427)
AI General (197)
AI AllOther (6)