Lesson 10 of 27From idea to plan
Your Language's Interview Toolkit
Know the built-ins that turn ten lines into one, what each one really costs, and the traps in Python and JavaScript that cost candidates the round.
You have the right idea: count the letters, keep the top k in a heap, binary search the answer. Then you spend six minutes hand-writing a heap, or your grid of rows turns out to be one row repeated four times, and the clock eats the time you needed for testing. Interviewers do not give marks for typing. They give marks for a correct, clear solution and the time left to test and discuss it. Knowing your language's toolkit cold is how you buy that time.
This lesson is the toolkit for the two languages most people interview in, Python and JavaScript/TypeScript. It covers what to reach for, what each call costs underneath, and the handful of traps that produce wrong answers without any error.
Why fluency shows up on the scorecard
Most coding rubrics have a row for code quality or language fluency, separate from problem solving. A candidate who writes Counter(s) == Counter(t) for an anagram check reads as someone who writes real code every day. A candidate who writes twelve lines of manual dictionary counting reads as someone who solved it, but slowly.
Fluency also protects you from bugs. Every line you do not write is a line that cannot be off by one. bisect_left has been tested by millions of people; your hand-rolled binary search was written under stress four minutes ago.
There is one limit: use the built-in, but be able to explain it. If you call heapq.nlargest(k, nums), expect "what does that cost?" and "how would you do it without the library?" The library saves typing, not understanding. As you saw in Choosing Data Structures, you still pick the structure from the operations. This lesson is about writing that choice in one line.
Python: counting and grouping
Most array and string problems start with counting or grouping. Python has a tool for each.
Countercounts anything iterable. Missing keys return 0 instead of raisingKeyError.most_common(k)gives the top k. Two counters compare equal when every count matches, and subtracting one from another keeps only the positive leftovers, which answers "can I build this word from those letters?" in one line.defaultdict(list)creates an empty list the first time you touch a key, so grouping has noif key not in dbranch.defaultdict(int)is a lighter counter.dequeis the queue.append,appendleft,popandpopleftare all O(1). Withmaxlen, it drops the oldest item automatically, which is a free "last k items" window.
Press Run (⌘ Enter) to see what happens.What does this print?
from collections import Counter
print(Counter('aabbbc') - Counter('abc'))Python: heaps, binary search and sorting
heapq works on a plain list and is always a min-heap. heapify is O(n), heappush and heappop are O(log n), and h[0] is the smallest item. For a max-heap there are two answers, and you should know both:
- The portable way: push
-xand negate when you pop. It works on every Python version, which matters because many interview platforms do not run the newest release. - Python 3.14 and later:
heapqnow has public max-heap functions:heapify_max,heappush_max,heappop_max,heappushpop_maxandheapreplace_max. Say "this needs 3.14" if you use them, or check the version on the platform first.
heapq.nlargest(k, xs) and nsmallest answer "top k" in O(n log k) without a loop. When you push tuples, Python compares them element by element, so a tie on priority falls through to the next element. If that next element is a dict or a custom object, the comparison raises TypeError. The fix is a counter in the middle: (priority, i, item).
bisect is binary search you do not have to write. On a sorted list, bisect_left(a, x) is the first index where x could go, and bisect_right(a, x) is one past the last x. Their difference counts occurrences. Since Python 3.10 both take a key= argument, so you can search a list of tuples by its first field. Note that the value you search for is not passed through key; it is compared directly with key(item).
sorted(xs, key=...) sorts by whatever the key returns, and Python's sort is stable. To sort by age descending and then name ascending, return (-age, name). When the key cannot be negated (two strings, one each way), sort twice, least important key first, and stability does the rest.
Press Run (⌘ Enter) to see what happens.Remove the i from the task tuples and run it again. The two tasks with priority 2 tie, Python moves on to compare two dicts, and you get a TypeError.
Python: itertools, functools and math
These save the most time on combinatorics and DP.
functools.cache(3.9+) memoises a function in one line. It turns a recursive DP into top-down DP. The trap: Python's default recursion limit is 1000, and neither Python nor JavaScript does tail-call optimisation. A memoised recursion 10^4 deep crashes withRecursionError, so either raise the limit withsys.setrecursionlimit(and accept the risk of a hard crash) or write the loop version.lru_cache(maxsize=None)is the same thing on older versions.itertools.accumulategives prefix sums.combinations,permutationsandproductenumerate the brute force for you.pairwise(3.10+) yields neighbouring pairs, perfect for gaps between sorted values.itertools.groupbygroups consecutive equal items only. On unsorted input it gives the same key twice. Sort first if you want one group per key, or useCounter.math.comb(n, k),math.isqrt(n)(exact integer square root, no float rounding) andmath.infas the starting value for a running minimum.
Press Run (⌘ Enter) to see what happens.Look at the groupby line: a appears twice because the input was not sorted. That is exactly the bug it causes in interviews.
One more Python habit worth having: zip(a, b, strict=True) (3.10+) raises if the lists differ in length, instead of silently stopping at the shorter one.
JavaScript and TypeScript: what is missing, and what bites
JavaScript gives you less, and its traps are quieter.
sort() compares strings by default. With no comparator, Array.prototype.sort converts values to strings and compares those, so [10, 9, 1].sort() gives [1, 10, 9]. Always pass (a, b) => a - b for numbers. The sort is stable (required since ES2019) and it sorts in place. ES2023 added toSorted, toReversed and toSpliced, which return a copy and leave the original alone.
fill shares one object. new Array(3).fill([]) puts the same array in every slot. Push into row 0 and every row changes. Build rows with Array.from({ length: n }, () => []), which calls the function once per slot.
Map and Set use identity for objects. set.has([1, 2]) is false even after set.add([1, 2]), because the two arrays are different objects. For a visited set of coordinates, encode the pair: a number like r * cols + c (fast) or a string like `${r},${c}` (simple, slower). Map also keeps insertion order, which is handy for "first unique character" problems.
Numbers. There is one number type, a 64-bit float, so integers are exact only up to 2^53 − 1. Use BigInt beyond that. / never floors: use Math.floor for floor division and Math.trunc to round toward zero. And % is a remainder, not a modulo: -7 % 3 is -1 in JavaScript but 2 in Python.
Press Run (⌘ Enter) to see what happens.Python has the same sharing bug in a different spelling: [[0] * n] * m is m references to one row. Use [[0] * n for _ in range(m)].
fill evaluates [] once and stores that one array in all three slots. Three names, one object.
What does this print?
console.log([10, 9, 1, 100].sort().join(" "));No heap, so write one
JavaScript has no built-in heap or balanced tree. LeetCode's JavaScript environment includes the @datastructures-js/priority-queue package, but HackerRank, CodeSignal and a plain CoderPad do not, so do not depend on it. Practice writing this binary heap until it takes you under five minutes. It is about thirty lines, and the comparator makes it a max-heap or a heap of tuples without changes.
While you are here, note the other quiet cost: shift() removes the first element by moving every other one, so it is O(n). A BFS that calls queue.shift() on 10^5 nodes is O(n²). Keep a head index instead and read queue[head++].
Press Run (⌘ Enter) to see what happens.The last loop is the habit from Brute Force First: check your hand-written structure against something you trust (here, toSorted) on hundreds of random inputs.
What built-ins really cost
A one-line call can hide a loop. These are the costs interviewers ask about, and the ones that turn a correct O(n) plan into O(n²).
| Operation | Cost | Watch out for |
|---|---|---|
Python lst.append(x), lst.pop() | O(1) amortised | Fine |
Python lst.pop(0), lst.insert(0, x) | O(n) | Use deque.popleft / appendleft |
x in lst / JS arr.includes(x) | O(n) | Inside a loop it is O(n²). Use a set |
x in set / dict, JS set.has | O(1) average | Keys must be hashable (tuples yes, lists no) |
lst[a:b], JS arr.slice(a, b) | O(b − a) | A copy. Slicing in recursion adds up |
s += t in a loop | Up to O(n) each | Collect parts, then "".join(parts) |
sorted, list.sort, JS sort | O(n log n) | Sorting inside a loop is a hidden extra factor |
heapq.heapify / heappush / heappop | O(n) / O(log n) / O(log n) | nlargest(k) is O(n log k) |
bisect_left / bisect.insort | O(log n) / O(n) | Finding the spot is fast; inserting shifts items |
deque[i] in the middle | O(n) | A deque is fast only at its ends |
JS shift, unshift, splice(0, 1) | O(n) | Use a head index |
JS [...arr], Object.keys(obj) | O(n) | Do not rebuild these every iteration |
About s += t: CPython sometimes extends a string in place as an optimisation, but it is an implementation detail you cannot count on. join is the answer an interviewer expects.
Grids and visited sets
Grids come up constantly, so have one shape ready in each language: a DIRS list of four (dr, dc) pairs, a bounds check, and a visited structure.
You have three choices for "visited", and the trade-off is speed against simplicity:
- A set of tuples
(r, c)in Python is the clearest. Each insert builds a tuple and hashes it, which is fine for most interview sizes. - A 2D boolean grid
[[False] * cols for _ in range(rows)]is usually faster, because it indexes instead of hashing. Watch the comprehension: the* rowsversion shares rows, as you just saw. - A single integer
r * cols + cworks in both languages. In JavaScript it is the right default, because aSetcannot see two equal arrays as the same key. Decode withMath.floor(id / cols)andid % cols.
If the problem allows it, you can also mark visited cells in the input itself (for example, change "1" to "0" in Number of Islands). Say that you are mutating the input and ask if that is acceptable.
Fast input for online assessments
Live interviews give you a function signature. Some online assessments, especially HackerRank-style ones, give you raw standard input instead, and slow reading can cause a time limit failure on large tests. These snippets read stdin, so they do not run in the browser, but they are worth memorising.
import sys
# Read everything at once and split on whitespace (fastest)
data = sys.stdin.buffer.read().split()
n = int(data[0])
nums = list(map(int, data[1:1 + n]))
# Or line by line: keep the trailing newline in mind
# input = sys.stdin.readline
# n = int(input())const data = require("fs").readFileSync(0, "utf8").trim().split(/\s+/);
let pos = 0;
const n = Number(data[pos++]);
const nums = data.slice(pos, pos + n).map(Number);
console.log(nums.reduce((a, b) => a + b, 0));Also print once at the end: build a list of output lines and print("\n".join(out)), because thousands of separate print calls are slow on these platforms.
Which language to interview in
Pick the language you write fastest and most correctly, then stay in it for the whole loop.
- Python is the usual pick for algorithm rounds. It is short, its standard library has a heap, a deque, a counter and binary search, and integers never overflow. The cost: it is slower, which only matters on online assessments with tight limits.
- TypeScript or JavaScript makes sense for frontend roles, where interviewers may expect it and later rounds use it. Budget for the missing heap and the sort trap.
- Java, C++ or Go are fine if they are what you write every day. Do not switch to Python a month before the loop just because it is shorter; fluency beats brevity.
Never switch languages mid-interview. If you need a structure your language lacks, say so and write the small version, or ask "may I assume a priority queue with push and pop in O(log n)?" Many interviewers will say yes.
Match each need to the tool that does it in one line.
- Counter
- A Python dict subclass that counts items. Missing keys return 0, and counters can be compared, added and subtracted.
- defaultdict
- A dict that creates a default value (an empty list, 0) the first time a missing key is used.
- heapq
- Python's heap functions on a plain list. Always a min-heap; Python 3.14 added separate
_maxfunctions. - bisect
- Python's binary search on a sorted list:
bisect_leftfinds the first slot for x,bisect_rightthe slot after the last x. - comparator
- A function
(a, b) => numberthat tells JavaScript's sort the order. Without one, sort compares strings. - shared reference
- Several names or slots pointing at one object, as in
fill([])or[[0] * n] * m. Changing it through one changes it for all. - amortised cost
- The average cost per operation over a long run, like
appendbeing O(1) even though resizing is occasionally O(n).