Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 17.4 — Interview Deep Dive: Coding Rounds in Python
Python · Example 1 of 3

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.

01

Write group_anagrams(words) that returns a list of groups, each sorted, with the groups sorted too.

02

Write kth_largest(nums, k) using heapq in O(n log k), keeping a min-heap of size k.

03

Write first_unique_char(s) that returns the index of the first character that appears only once, or -1.

Explain it without notes

01

Find the k most frequent words in a text, with ties broken alphabetically. State the time and space complexity.

02

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?

03

What is a stable sort, and how do you sort by one field descending and another ascending?

04

How does bisect_left differ from bisect_right? Give an example with duplicates.

05

How would you find the maximum of every window of size k in an array in O(n)?

06

Given a list of numbers and a target, return the indexes of two numbers that add up to the target, in O(n) time.

07

What goes wrong when you remove items from a list while looping over it, and what do you do instead?

Counter, defaultdict, sorted with key, heapq and slicing
Sign in to run this example in your browser.

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