Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Count Frequent N-grams Efficiently

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Count Frequent N-grams Efficiently. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

Tiber Technologies processes large text streams for search and language features. Implement a one-pass algorithm that identifies the most frequent contiguous n-grams while using bounded memory.

Use the Misra-Gries heavy-hitter algorithm. It maintains at most k - 1 candidate n-grams, so its memory usage does not grow with the stream length. Counts returned are candidate estimates, not guaranteed exact counts.

Formal Specification

Implement count_frequent_ngrams(tokens, n, k):

  • tokens is an iterable of strings. It may be a list or a one-pass generator.
  • n is a positive integer specifying the n-gram length.
  • k is an integer greater than 1 specifying the accuracy and candidate capacity.
  • Return a list of at most k - 1 items. Each item is [ngram, estimated_count], where ngram is a list of n strings.
  • Sort results by decreasing estimated count, then lexicographically by the n-gram.

When a new n-gram arrives, increment its candidate count if present. Otherwise, insert it if capacity remains. If the candidate set is full, decrement every candidate and remove entries that reach zero.

Constraints

  • 0 <= number of tokens <= 10^6
  • 1 <= n <= 10^3
  • 2 <= k <= 10^4
  • Every token is a non-empty string
  • tokens may be a one-pass iterator

Function Signature

def count_frequent_ngrams(tokens, n, k):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output