Interview Questions, Answered by Running Them

The questions actually asked about strings, lists and dictionaries - each with the code, run in your browser.

71 modules Free, no login Updated 13 November 2026

About this track

Interview answers are not recall problems. "Why is this O(n²)?" is answered properly by showing the count, and "which is faster?" by measuring both - which is what every page here does. Each question gets its own page: the answer in prose, a visualisation that steps through the mechanism, and a real Python interpreter with the implementation already in it.

The track is organised the way the questions are asked - strings, then lists and arrays, then dictionaries, hashing and the complexity traps that catch most candidates. Conceptual questions and coding problems sit side by side, because interviews mix them.

Every other track is organised around ideas. This one is organised around questions, because that is the shape the pressure arrives in: someone asks why your loop is quadratic, and you have thirty seconds. Each page is one question, answered in full and then demonstrated by code you can run.

What you will be able to do

How the track is ordered

The track runs strings, then lists and arrays, then dictionaries, hashing and the crossover problems, finishing on the complexity traps. Within each group the conceptual questions come before the coding problems that lean on them, because "why is `in` slow on a list?" is the answer to half the coding questions that follow it. Nothing here assumes you have read the rest of the site, though the algorithms track covers the same techniques at more length.

Where this leads

The Algorithms and Data Structures track is the long-form version of this one: same techniques, one page per algorithm rather than one page per question, with the visualisation carrying more of the explanation. If a question here lands on something unfamiliar - binary search bounds, hash collisions, dynamic programming - that track has the full treatment.

All 71 modules, in teaching order

  1. 01Why are Python strings immutable?See why Python strings cannot change in place. Trace what happens when you concatenate, check the object id, and understand the hashing guarantee.
  2. 02What does slicing a string cost?Slice a Python string and measure the cost. See that slicing copies the data every time, count the bytes moved, and spot when it hides an O(n) hit.
  3. 03Does len() count characters or bytes?Test len() on str, bytes and emoji. See when it counts characters, when it counts bytes, and why a single emoji can give you more than one.
  4. 04What is the difference between str and bytes?Compare str and bytes objects side by side. Encode a string to bytes, decode it back, and see where the boundary between text and binary sits.
  5. 05Why does `is` sometimes work on strings?See which strings Python interns and which it does not. Test is on literals and computed strings, and learn why the result is unpredictable.
  6. 06find() vs index() vs `in` — which one?Compare str.find, str.index and the in operator side by side. See which raises, which returns -1, and pick the right one for each situation.
  7. 07Reverse a stringReverse a string with slicing, then do it in place on a character list with O(1) extra memory. Compare both approaches step by step.
  8. 08Check whether a string is a palindromeCheck whether a string is a palindrome after stripping punctuation and lowering case. Walk two pointers inward and compare characters one by one.
  9. 09Are two strings anagrams?Check whether two strings are anagrams by counting every character in a dictionary. Compare the sorted approach to the counted one and time both.
  10. 10Group anagrams togetherGroup words that are anagrams of each other. Sort each word into a canonical key, collect matches in a dictionary, and see the cost of each step.
  11. 11Longest substring without repeating charactersSlide a window across the string, tracking seen characters in a set. Shrink on repeats, grow on new ones, and record the longest span found.
  12. 12First non-repeating characterFind the first character in a string that appears only once. Compare a two-pass dictionary approach to an ordered-dict single-pass solution.
  13. 13Valid parenthesesPush openers onto a stack and pop when a closer arrives. Walk through balanced and unbalanced bracket strings to see every edge case handled.
  14. 14Run-length string compressionCompress aabcccccaaa into a2b1c5a3 with a single scan. Count consecutive runs, build the result, and return the original when compression is longer.
  15. 15Longest common prefixFind the longest common prefix shared by a list of strings. Compare vertical scanning to sorting-based approaches and see which finishes first.
  16. 16Implement substring search (strStr)Implement strStr without the built-in. Slide a window across the text, compare character by character, and measure the brute-force cost.
  17. 17Isomorphic stringsCheck whether two strings share the same character-to-character pattern. Map characters in both directions, catch conflicts, and handle edge cases.
  18. 18Longest palindromic substringExpand around every centre to find the longest palindromic substring. Handle both odd and even lengths and see why this beats brute-force checking.
  19. 19Edit distance (Levenshtein)Fill in the edit-distance table for two strings. Watch insertions, deletions and substitutions compete, and trace back the cheapest transformation.
  20. 20Minimum window substringShrink and expand a sliding window until it holds every character of t. Track character counts in a dictionary and record the smallest valid span.
  21. 21What is a Python list underneath?Look inside CPython's list: a resizable array of pointers. See why append is amortized O(1), insert(0, x) is O(n), and indexing is constant-time.
  22. 22Why does [[0]*3]*3 break?Create [[0]*3]*3, write to one cell, and watch every row change. See the shared-reference diagram and build the grid the safe way instead.
  23. 23Why is `in` slow on a list but fast on a set?Time x in my_list versus x in my_set as the collection grows. See the O(n) scan, the O(1) hash lookup, and know when to switch to a set.
  24. 24Two SumSolve Two Sum in one pass with a hash map. Store each number's index, check for its complement, and return the pair the moment it appears.
  25. 25Maximum subarray sum (Kadane)Run Kadane's algorithm step by step. Decide at each element whether to extend or restart, and watch the maximum subarray sum update in real time.
  26. 26Remove duplicates from a sorted array in placeWalk a slow and fast pointer through a sorted array, overwriting duplicates in place. Return the new length and handle every edge case.
  27. 27Rotate an array by kRotate an array right by k positions in place using three reverses. Trace each reverse and see why the trick works without extra memory.
  28. 28Product of array except selfBuild prefix and suffix products in two passes to get the product of every other element, with no division and O(1) extra space.
  29. 29Merge overlapping intervalsSort intervals by start time, then merge overlaps in one pass. Trace through examples and see why sorting first makes the rest straightforward.
  30. 30Find the duplicate numberFind the one duplicate in an array of n+1 integers from 1 to n without extra space. Apply Floyd's cycle detection and see why it works here.
  31. 31Kth largest elementFind the kth largest element with a min-heap and with quickselect. Compare both approaches and see when each one wins on time and space.
  32. 32Trapping rain waterCalculate trapped water bar by bar. Precompute left and right maxima in two passes, then shrink to O(1) space with two converging pointers.
  33. 33Sort an array of 0s, 1s and 2sPartition an array of 0s, 1s and 2s in one pass using three pointers. Watch low, mid and high converge until the array is sorted in place.
  34. 343SumFind every unique triple that sums to zero. Sort the array, fix one element, and sweep two pointers inward while skipping duplicates at each step.
  35. 35Search in a rotated sorted arraySearch a rotated sorted array in O(log n). Identify which half is sorted at each step, decide where the target can hide, and narrow the window.
  36. 36Sliding window maximumTrack the maximum in a sliding window using a monotonic deque. Watch old and small values drop as the window advances, keeping every lookup O(1).
  37. 37list vs tuple vs deque vs array — which and why?Compare list, tuple, deque and array side by side. See the memory layout, the time cost of each operation, and when to reach for which one.
  38. 38How does a Python dict work?Look inside CPython's dict: a hash table with open addressing. See the probe sequence, the compact layout, and why average-case lookup costs O(1).
  39. 39Why must dictionary keys be hashable?Try a list as a dictionary key and watch it fail. See why hash consistency matters for lookups, what makes tuples work, and which objects qualify.
  40. 40Count things with a dictionaryCount item frequencies with a plain dict, then with Counter. Find the k most common elements and see how the data structure choice changes the cost.
  41. 41What is the complexity of this code?Spot the hidden quadratic cost in four common loop patterns. Step through each one, count the real operations, and learn to catch the trap fast.
  42. 42Design an LRU cacheBuild an LRU cache with O(1) get and put using a hash map and a doubly linked list. Step through insertions, lookups and evictions one by one.
  43. 43Longest consecutive sequenceFind the longest run of consecutive integers in an unsorted array in O(n). Use a set to start only at sequence beginnings and skip the rest.
  44. 44Subarray sum equals kCount subarrays that sum to k using a running prefix sum and a hash map. See why brute force costs O(n squared) and the hash approach costs O(n).
  45. 45When should you use a set instead of a list?Switch from a list to a set and watch membership checks drop from O(n) to O(1). Deduplicate a sequence while preserving order with dict.fromkeys.
  46. 46Modifying a Collection While Iterating Over ItSee what breaks when you delete from a list or dict mid-loop. Trace the iterator state, watch the error, and learn the safe alternatives.
  47. 47Memoisation: caching with a dictionaryCache recursive results in a dictionary to kill recomputation. Watch the call tree shrink from exponential to linear, then switch to lru_cache.
  48. 48Implement a hash map from scratchBuild a hash map from scratch with put, get and remove. Choose a hash function, handle collisions with chaining, and test it against edge cases.
  49. 49Group records and invert a dictionaryGroup records by a shared field and invert a dictionary so values become keys. See both operations in plain Python and with defaultdict.
  50. 50Design a stack that reports its minimum in O(1)Design a stack that reports its minimum in O(1). Track the minimum at every push and see why a single extra variable is not enough.
  51. 51Evaluate reverse Polish notationEvaluate a postfix expression with a stack. Push operands, pop for each operator, and trace through examples like 4 13 5 / + step by step.
  52. 52Daily temperatures, and the monotonic stackSolve daily temperatures with a monotonic stack. Watch the stack shrink as each warmer day resolves earlier entries, and see why one pass is enough.
  53. 53Implement a queue using two stacksBuild a FIFO queue from two stacks. Push onto one, pop from the other, and see why every element moves at most twice for amortized O(1) cost.
  54. 54Top k frequent elementsFind the k most frequent elements using a heap and using bucket sort. Compare both approaches and see when each one gives a better time bound.
  55. 55Merge k sorted sequencesMerge k sorted lists with a min-heap. Push one element per list, pop the smallest, refill, and see why the total cost is O(n log k).
  56. 56Find the median of a data streamKeep two heaps as numbers arrive: a max-heap for the lower half and a min-heap for the upper. Report the median after every insertion in O(log n).
  57. 57Write binary search without an off-by-oneWrite binary search that terminates correctly every time. Trace the loop invariant, see where off-by-one errors hide, and fix them before they bite.
  58. 58First and last position of a targetFind the first and last index of a target in a sorted array with duplicates. Run two binary searches and see how each boundary is located.
  59. 59Binary search on the answer, not the arrayBinary-search the answer space instead of an array. Solve the ship-capacity problem step by step and learn the template that fits dozens of variants.
  60. 60Climbing stairs: the DP that is FibonacciCount the ways to climb n stairs taking 1 or 2 steps at a time. Build the recurrence, spot the Fibonacci pattern, and reduce space to O(1).
  61. 61Coin change, and why greedy is wrongFind the fewest coins that make a target amount. See why greedy fails on certain denominations, build the DP table cell by cell, and trace back.
  62. 62Longest increasing subsequence, twiceFind the longest increasing subsequence with O(n squared) DP, then speed it up to O(n log n) with patience sorting and binary search.
  63. 63House robber: the 0-1 choicePick houses to rob without choosing two in a row. Build the DP recurrence, compare rob-or-skip at every step, and read off the maximum take.
  64. 64What does `yield` actually do?Step through a generator function one yield at a time. See the suspended frame, compare memory use to a list, and chain generators with yield from.
  65. 65Why does this default argument remember?Call a function with a default list twice and watch the list remember. See why Python evaluates defaults once, and three clean ways to fix it.
  66. 66`is` vs `==`, and why 257 is not 257Test is vs == on integers, strings and lists. See the object id behind each, learn the small-integer cache rule, and know when identity matters.
  67. 67Shallow copy vs deep copyCopy a nested list with list(), copy() and deepcopy(). Mutate an inner list and see which copies notice the change and which stay independent.
  68. 68Why do all these functions return the same value?Run the classic closure trap: a list of lambdas that all return the same value. See why Python binds late and three clean ways to fix it.
  69. 69What does a decorator actually replace?See what the @ line does to a function object. Trace the replacement, add functools.wraps, and understand why the original name disappears without it.
  70. 70What does `with` guarantee when the body raises?Trace a with block that raises an exception. See the __enter__ and __exit__ calls, check whether the error propagates, and know what is guaranteed.
  71. 71Why is a comprehension faster than the same loop?Time a list comprehension against the equivalent for-loop. Read the bytecode, count the attribute lookups saved, and see where the speedup lives.

Other tracks