Counter, defaultdict, sorted with key, heapq and slicing
Change the tie-break key to (-kv[1], -len(kv[0])) and see which word wins.
The Python idioms that save minutes in a coding round: Counter, defaultdict, heapq, bisect, deque, slicing, sorted with key, and itertools, plus the time complexity of every built-in you will lean on and how to talk through a solution.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write group_anagrams(words) that returns a list of groups, each sorted, with the groups sorted too.
Write kth_largest(nums, k) using heapq in O(n log k), keeping a min-heap of size k.
Write first_unique_char(s) that returns the index of the first character that appears only once, or -1.
Explain it without notes
Find the k most frequent words in a text, with ties broken alphabetically. State the time and space complexity.
Why is list.pop(0) slow and what do you use instead? What is the complexity of x in some_list versus x in some_set?
What is a stable sort, and how do you sort by one field descending and another ascending?
How does bisect_left differ from bisect_right? Give an example with duplicates.
How would you find the maximum of every window of size k in an array in O(n)?
Given a list of numbers and a target, return the indexes of two numbers that add up to the target, in O(n) time.
What goes wrong when you remove items from a list while looping over it, and what do you do instead?
Expected output
counts: {'the': 3, 'cat': 2, 'and': 2, 'dog': 1, 'bird': 1, 'saw': 1, 'a': 1}
most_common(2): [('the', 3), ('cat', 2)]
top 3: [('the', 3), ('and', 2), ('cat', 2)]
anagram groups: [['bat'], ['eat', 'tea', 'ate'], ['tan', 'nat']]
sorted by age desc, name asc: [('Asha', 31), ('Chitra', 31), ('Ben', 25), ('Dev', 25)]
stable sort keeps ties in order: ['a', 'd', 'bb', 'cc']
heap pops: [1, 2, 3]
3 largest: [5, 4, 3]
reversed slice: [3, 2, 4, 1, 5] | every 2nd: [5, 4, 3] | copy: True