Skip to content

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.

17 min read0/4 questions

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.

  • Counter counts anything iterable. Missing keys return 0 instead of raising KeyError. 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 no if key not in d branch. defaultdict(int) is a lighter counter.
  • deque is the queue. append, appendleft, pop and popleft are all O(1). With maxlen, it drops the oldest item automatically, which is a free "last k items" window.
Python
from collections import Counter, defaultdict, deque # Counter: counting in one linewords = "the cat and the hat and the bat".split()c = Counter(words)print(c.most_common(2)) # top 2 by countprint(c["dog"]) # missing key is 0, no KeyError # Anagram check and "can I build ransom from magazine?"print(Counter("listen") == Counter("silent"))need, have = Counter("aab"), Counter("abcab")print(need - have) # empty means have covers needprint(not (need - have)) # defaultdict: group without "if key not in d"groups = defaultdict(list)for w in ["eat", "tea", "tan", "ate", "nat"]: groups["".join(sorted(w))].append(w)print(list(groups.values())) # deque: O(1) at both ends, and a sliding window with maxlenq = deque([1, 2, 3])q.appendleft(0)print(q.popleft(), q.pop(), list(q))recent = deque(maxlen=3)for x in range(6): recent.append(x)print(list(recent))
Output
Press Run (⌘ Enter) to see what happens.
Predict the outputPython

What does this print?

from collections import Counter
print(Counter('aabbbc') - Counter('abc'))
Need a nudge? Hints walk you through it.

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 -x and 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: heapq now has public max-heap functions: heapify_max, heappush_max, heappop_max, heappushpop_max and heapreplace_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.

Python
import heapq, sysfrom bisect import bisect_left, bisect_right nums = [5, 1, 8, 3, 9, 2] # heapq is a MIN-heaph = nums[:]heapq.heapify(h) # O(n)print(heapq.heappop(h), heapq.heappop(h)) # Max-heap, the portable way: push negativesmx = []for x in nums: heapq.heappush(mx, -x)print(-heapq.heappop(mx)) # Max-heap, Python 3.14+ onlyif sys.version_info >= (3, 14): mx2 = nums[:] heapq.heapify_max(mx2) print(heapq.heappop_max(mx2)) # Top k without writing a heap loopprint(heapq.nlargest(3, nums), heapq.nsmallest(2, nums)) # Tie-breakers: (priority, counter, item) so items are never comparedtasks = []for i, (pri, name) in enumerate([(2, "b"), (1, "a"), (2, "c")]): heapq.heappush(tasks, (pri, i, {"name": name}))print([heapq.heappop(tasks)[2]["name"] for _ in range(3)]) # bisect: binary search you do not have to writes = [1, 3, 3, 3, 7]print(bisect_left(s, 3), bisect_right(s, 3)) # first 3, one past last 3print(bisect_right(s, 3) - bisect_left(s, 3)) # how many 3sevents = [(1, "boot"), (4, "login"), (9, "logout")]print(bisect_right(events, 5, key=lambda e: e[0])) # key= needs 3.10+
Output
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 with RecursionError, so either raise the limit with sys.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.accumulate gives prefix sums. combinations, permutations and product enumerate the brute force for you. pairwise (3.10+) yields neighbouring pairs, perfect for gaps between sorted values.
  • itertools.groupby groups consecutive equal items only. On unsorted input it gives the same key twice. Sort first if you want one group per key, or use Counter.
  • math.comb(n, k), math.isqrt(n) (exact integer square root, no float rounding) and math.inf as the starting value for a running minimum.
Python
from functools import cachefrom itertools import accumulate, combinations, pairwise, groupby, productfrom math import comb, isqrt, inf @cachedef ways(n): # climbing stairs, memoised return 1 if n <= 1 else ways(n - 1) + ways(n - 2)print(ways(40)) print(list(accumulate([3, 1, 4, 1]))) # prefix sumsprint(list(combinations("abc", 2)))print(len(list(product(range(3), repeat=2)))) # 3 * 3 pairsprint([b - a for a, b in pairwise([1, 4, 9, 16])]) # gapsprint([(k, len(list(g))) for k, g in groupby("aaabccaa")])print(comb(5, 2), isqrt(17), min(inf, 42)) people = [("ana", 31), ("bo", 25), ("cy", 31)]print(sorted(people, key=lambda p: (-p[1], p[0]))) # age desc, name asc
Output
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.

JavaScript
// 1. sort() with no comparator compares stringsconsole.log([10, 9, 1].sort());console.log([10, 9, 1].sort((a, b) => a - b)); // toSorted (ES2023) returns a copy and leaves the original aloneconst scores = [3, 1, 2];console.log(scores.toSorted((a, b) => b - a), scores); // 2. fill([]) puts ONE array in every slotconst bad = new Array(3).fill([]);bad[0].push("x");console.log(JSON.stringify(bad));const good = Array.from({ length: 3 }, () => []);good[0].push("x");console.log(JSON.stringify(good)); // 3. Map and Set compare object keys by identityconst seen = new Set();seen.add([1, 2]);console.log(seen.has([1, 2])); // a different arrayseen.add("1,2");console.log(seen.has([1, 2].join(","))); // strings compare by value // Map keeps insertion order and counts cleanlyconst count = new Map();for (const ch of "banana") count.set(ch, (count.get(ch) ?? 0) + 1);console.log([...count]); // 4. Number trapsconsole.log(-7 % 3, ((-7 % 3) + 3) % 3); // JS remainder vs true moduloconsole.log(Math.trunc(7 / 2), Math.floor(-7 / 2));console.log(2 ** 53 + 1 === 2 ** 53, 2n ** 64n);
Output
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)].

Why one push changed every row
const bad = new Array(3).fill([]);
NamesObjects in memorybad[0]bad[1]bad[2]Array[]

fill evaluates [] once and stores that one array in all three slots. Three names, one object.

1/4
Predict the outputJavaScript

What does this print?

console.log([10, 9, 1, 100].sort().join(" "));
Need a nudge? Hints walk you through it.

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++].

JavaScript
class MinHeap { constructor(less = (a, b) => a < b) { this.a = []; this.less = less; } get size() { return this.a.length; } peek() { return this.a[0]; } push(x) { const a = this.a; a.push(x); let i = a.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (!this.less(a[i], a[p])) break; [a[i], a[p]] = [a[p], a[i]]; i = p; } } pop() { const a = this.a; const top = a[0]; const last = a.pop(); if (a.length > 0) { a[0] = last; let i = 0; while (true) { const l = 2 * i + 1, r = l + 1; let m = i; if (l < a.length && this.less(a[l], a[m])) m = l; if (r < a.length && this.less(a[r], a[m])) m = r; if (m === i) break; [a[i], a[m]] = [a[m], a[i]]; i = m; } } return top; }} // Min-heap of numbersconst h = new MinHeap();for (const x of [5, 1, 8, 3, 9, 2]) h.push(x);const out = [];while (h.size) out.push(h.pop());console.log(out.join(" ")); // Max-heap of [distance, name] pairs: flip the comparatorconst far = new MinHeap((a, b) => a[0] > b[0]);far.push([4, "b"]); far.push([9, "c"]); far.push([1, "a"]);console.log(far.pop()); // A queue without shift(): keep a head indexconst queue = [1, 2, 3];let head = 0;while (head < queue.length) { const x = queue[head++]; if (x < 3) queue.push(x + 10);}console.log(queue.join(" "), "| head =", head); // Stress check against sortfor (let t = 0; t < 500; t++) { const xs = Array.from({ length: 1 + (t % 20) }, () => Math.floor(Math.random() * 50)); const hp = new MinHeap(); xs.forEach((x) => hp.push(x)); const got = []; while (hp.size) got.push(hp.pop()); const want = xs.toSorted((a, b) => a - b); if (got.join() !== want.join()) throw new Error("mismatch " + xs);}console.log("500 random heaps match sort");
Output
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²).

OperationCostWatch out for
Python lst.append(x), lst.pop()O(1) amortisedFine
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.hasO(1) averageKeys 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 loopUp to O(n) eachCollect parts, then "".join(parts)
sorted, list.sort, JS sortO(n log n)Sorting inside a loop is a hidden extra factor
heapq.heapify / heappush / heappopO(n) / O(log n) / O(log n)nlargest(k) is O(n log k)
bisect_left / bisect.insortO(log n) / O(n)Finding the spot is fast; inserting shifts items
deque[i] in the middleO(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.

Quick check
A solution loops over n words and, for each, checks if word in seen_list: before appending it. With n = 10^5, what is the real cost and the fix?
Need a nudge? A hint rules out a wrong answer.

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 * rows version shares rows, as you just saw.
  • A single integer r * cols + c works in both languages. In JavaScript it is the right default, because a Set cannot see two equal arrays as the same key. Decode with Math.floor(id / cols) and id % 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.

fast_input.py
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())
fast-input.js
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 the pairs0/6 matched

Match each need to the tool that does it in one line.

Choose an item, then its match on the other side.
Key terms
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 _max functions.
bisect
Python's binary search on a sorted list: bisect_left finds the first slot for x, bisect_right the slot after the last x.
comparator
A function (a, b) => number that 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 append being O(1) even though resizing is occasionally O(n).