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 2 of 3

bisect, a monotonic deque and itertools

groupby only groups neighbours. Try it on 'abab' and see four groups.

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?

bisect, a monotonic deque and itertools
Sign in to run this example in your browser.

Expected output

bisect_left(20): 1 | bisect_right(20): 3
after insort(25): [10, 20, 20, 25, 30, 50]
sliding window max: [3, 3, 5, 5, 6, 7]
pairwise: [(1, 2), (2, 4), (4, 7)]
accumulate: [1, 3, 6, 10]
combinations: [('a', 'b'), ('a', 'c'), ('b', 'c')]
product: [(0, 0), (0, 1), (1, 0), (1, 1)]
groupby: [('a', 3), ('b', 2), ('c', 1)]
deque maxlen=3 after append(4): [2, 3, 4]
rotate(1): [4, 2, 3]