Top N Frequent Words in a File
Updated
Problem statement
You are given the contents of a text file as a string text and an integer n.
Extract every word from text. A word is a full run of one or more consecutive ASCII letters. Convert words to lowercase, and treat every other character as a separator.
Return at most n distinct words ordered by decreasing frequency. When two words have the same count, put them in alphabetical order. If n exceeds the number of distinct words, return all distinct words. If the text contains no words, return an empty array.
Function
topNWords(text: String, n: int) → String[]Examples
Example 1
text = "Cat dog cat, DOG bird!"n = 2return = ["cat","dog"]cat and dog each appear twice. Their frequencies tie, so lexicographic order places cat first.
Example 2
text = "pear apple pear banana apple"n = 3return = ["apple","pear","banana"]apple and pear both appear twice, so the tie is resolved lexicographically. banana appears once.
Example 3
text = "One one two"n = 5return = ["one","two"]Only two distinct normalized words exist, so both are returned even though n = 5.
Constraints
0 <= text.length <= 2 * 10^5.1 <= n <= 10^5.- Every character in
textis an ASCII character.
More Meta Phone Screen questions
- Convert a Sorted Linked List to a Balanced BSTPHONE SCREEN · Seen Nov 2026
- Fuzzy Word Lookup With One Misspelled LetterPHONE SCREEN · Seen Nov 2026
- Multi-Head Attention Forward PassPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Run-Length Encoded Vector Dot ProductPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Mutual-Friend RecommendationsPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Best Time to Buy and Sell StockPHONE SCREEN · Seen Nov 2026
- First Element Greater Than KPHONE SCREEN · Seen Nov 2026
- Count Events in Rolling Minute WindowsPHONE SCREEN · Seen Oct 2026
- Valid Word AbbreviationPHONE SCREEN · Seen Oct 2026
- Shortest Path in a Binary MatrixPHONE SCREEN · Seen Sep 2026
Similar questions at other companies
- Top K Movies by Play Count from CSV DataTubi · PHONE SCREEN
- Time-Aware Search AutocompleteRoblox · PHONE SCREENRoblox interview questions
- Insert an Employee into an Organization HierarchyWaymo · PHONE SCREENWaymo interview questions
- Stable Top K Frequent WordsGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Brazilian Receivables Part 3 — Partial ContractsStripe · PHONE SCREENStripe interview questions
- Sort Characters by How Often They AppearAdobe · PHONE SCREENAdobe interview questions
- Summarize Server Healthcheck LogsNVIDIA · PHONE SCREENNVIDIA interview questions
- Transform Dotted Keys into a Nested MapProofpoint · ONSITE INTERVIEW
- Serialize and Deserialize a String Key-Value StoreByteDance · ONSITE INTERVIEWByteDance interview questions
- Deep Merge with a Conflict ResolverAutodesk · ONSITE INTERVIEWAutodesk interview questions