Interview Q&A · Python · 45 questions in this topic
Python Coding Interview Questions — Python Interview Q&A
45 classic coding problems with the expected approach, a step-by-step walkthrough, an idiomatic Python solution and its complexity — the rounds where you write code. Part of Python Coding Interview Questions · 375 questions in the Python bank.
Reverse a String
Answer
Problem: Given a string s, return the string reversed.
Expected approach: Python slicing (s[::-1]) is the idiomatic one-liner. If asked to do it "manually," use two pointers swapping from both ends, or build the result with a loop.
Complexity — time O(n) · space O(n) (a new string/list is created; O(1) extra space if mutating an in-place character array in a language that allows it)
Key points
- 1If slicing is allowed, s[::-1] walks the string backward from the last character to the first.
- 2For a manual approach: convert to a list (strings are immutable), swap characters at positions i and len(s)-1-i while i moves inward, then rejoin.
Example
def reverse_string(s: str) -> str: return s[::-1] # Manual, two-pointer version (what an interviewer often wants to see live) def reverse_string_manual(s: str) -> str: chars = list(s) left, right = 0, len(chars) - 1 while left < right: chars[left], chars[right] = chars[right], chars[left] left += 1 right -= 1 return "".join(chars) # Example run # Input: "hello" # Output: "olleh"
💡 If you reach straight for s[::-1], immediately offer the manual two-pointer version too — interviewers ask this specifically to see whether you can implement the underlying logic, not just recall the idiom.
Check if a String Is a Palindrome
Answer
Problem: Given a string s, determine whether it reads the same forwards and backwards.
Expected approach: Compare the string to its reverse, or use two pointers converging from both ends — the two-pointer approach is what interviewers usually want, since it generalizes to the "ignore punctuation/case" variant (Q289).
Complexity — time O(n) · space O(1) for the two-pointer version; O(n) for the slicing version (creates a reversed copy)
Key points
- 1Set left = 0 and right = len(s) -
- 2While left < right: if s[left]!= s[right], return False; otherwise move both pointers inward.
- 3If the loop completes without mismatches, the string is a palindrome.
Example
def is_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left < right: if s[left] != s[right]: return False left += 1 right -= 1 return True # One-liner equivalent def is_palindrome_simple(s: str) -> bool: return s == s[::-1] # Example run # Input: "racecar" # Output: True # Input: "hello" # Output: False
💡 Mention the space complexity difference between the two versions explicitly — it's a common, easy way to demonstrate you think about trade-offs even for "trivial" problems.
Find Duplicate Elements in a List
Answer
Problem: Given a list, return all elements that appear more than once.
Expected approach: Track seen elements in a set as you iterate; anything seen a second time is a duplicate. This is O(n), versus an O(n²) nested-loop comparison.
Complexity — time O(n) · space O(n)
Key points
- 1Create an empty seen set and an empty duplicates set.
- 2For each element: if it's already in seen, add it to duplicates; otherwise add it to seen.
- 3Return duplicates (as a list, if order or a specific type is required).
Example
def find_duplicates(items): seen = set() duplicates = set() for item in items: if item in seen: duplicates.add(item) else: seen.add(item) return list(duplicates) # Example run # Input: [1, 2, 3, 2, 4, 1, 5] # Output: [1, 2] (order may vary, since sets are unordered)
💡 If asked for the count of each duplicate rather than just which ones exist, pivot immediately to collections.Counter — it's the more idiomatic tool for that specific variant.
Find the Missing Number in a Sequence
Answer
Problem: Given a list containing n distinct numbers from 0 to n (inclusive) with exactly one missing, find the missing number.
Expected approach: Use the mathematical formula for the sum of the first n natural numbers: the expected total minus the actual total of the list equals the missing number. This avoids sorting or using extra space for a set.
Complexity — time O(n) · space O(1)
Key points
- 1If the full range 0 to n were present, the sum would be n * (n + 1) /
- 2Compute the actual sum of the given list.
- 3The missing number is expected_sum - actual_sum.
Example
def find_missing_number(nums): n = len(nums) # one number is missing from range 0..n expected_sum = n * (n + 1) // 2 actual_sum = sum(nums) return expected_sum - actual_sum # Example run # Input: [3, 0, 1] (n = 3, range should be 0..3) # Output: 2
💡 The sum-formula trick is the expected O(1)-space answer here — if you only know the sorting or set-based approach, mention the formula anyway to show awareness, even if you implement the more general version.
Count Character Frequency in a String
Answer
Problem: Given a string, return a mapping of each character to how many times it appears.
Expected approach: collections.Counter solves this directly and is the expected idiomatic answer; a manual dict with.get() or defaultdict(int) demonstrates the underlying mechanism if asked to avoid the standard library shortcut.
Complexity — time O(n) · space O(k), where k is the number of distinct characters
Key points
- 1Iterate over every character in the string.
- 2For each character, increment its count in a dictionary (defaulting to 0 if not yet seen).
- 3Return the completed dictionary (or Counter object).
Example
from collections import Counter def char_frequency(s: str) -> dict: return dict(Counter(s)) # Manual version, without Counter def char_frequency_manual(s: str) -> dict: freq = {} for char in s: freq[char] = freq.get(char, 0) + 1 return freq # Example run # Input: "hello" # Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
💡 Counter.most_common(n) is worth mentioning unprompted — it directly answers the very common follow-up "what's the most frequent character?" without writing any extra sorting logic.
Find the First Non-Repeating Character
Answer
Problem: Given a string, return the first character that does not repeat anywhere else in the string. Return None if every character repeats.
Expected approach: Count all character frequencies first (one pass), then scan the string again in order and return the first character whose count is 1 — two O(n) passes, but still O(n) overall and simpler than nested loops.
Complexity — time O(n) · space O(k), where k is the number of distinct characters
Key points
- 1Build a frequency map of every character (as in Q260).
- 2Iterate over the string a second time, in original order.
- 3Return the first character whose frequency is exactly
- 4If none is found after the full scan, return None.
Example
from collections import Counter def first_non_repeating(s: str): freq = Counter(s) for char in s: # second pass, preserves original order if freq[char] == 1: return char return None # Example run: first_non_repeating("swiss") -> "w" # ('s' and 'i' each repeat; 'w' is the first character appearing only once)
Two Sum
Answer
Problem: Given a list of integers nums and a target integer, return the indices of the two numbers that add up to the target. Assume exactly one valid solution exists, and you cannot use the same element twice.
Expected approach: A brute-force nested loop is O(n²). The expected optimal solution uses a hash map: for each number, check whether target - number has already been seen, giving O(n) time.
Complexity — time O(n) · space O(n)
Key points
- 1Create an empty dictionary mapping value → index, for numbers already visited.
- 2For each number at index i: compute complement = target - nums[i].
- 3If complement is already a key in the dictionary, return [dictionary[complement], i].
- 4Otherwise, store nums[i]: i in the dictionary and continue.
Example
def two_sum(nums, target): seen = {} # value -> index for i, num in enumerate(nums): complement = target - num if complement in seen: return [seen[complement], i] seen[num] = i return [] # no valid pair found # Example run # Input: nums = [2, 7, 11, 15], target = 9 # Output: [0, 1] (nums[0] + nums[1] == 2 + 7 == 9)
💡 This is one of the most famous coding interview questions specifically because it tests whether you recognize the O(n²) → O(n) hash map optimization — always start by naming the brute-force approach, then explain exactly why the hash map improves it.
Fibonacci Sequence
Answer
Problem: Given n, return the n th Fibonacci number (0-indexed: fib(0) = 0, fib(1) = 1, fib(n) = fib(n-1) + fib(n-2)).
Expected approach: Naive recursion is exponential (O(2^n)) due to massively repeated sub-calculations. The expected optimal answers are either iterative (O(n) time, O(1) space) or memoized recursion (O(n) time, O(n) space).
Complexity — time O(2^n) naive; O(n) iterative or memoized · space O(1) iterative; O(n) memoized (cache + call stack)
Key points
- 1Naive recursive version: directly translate the recurrence, but it recomputes the same sub-problems exponentially many times.
- 2Iterative version: track only the last two values, updating them in a loop — no recomputation, constant space.
- 3Memoized version: cache each fib(k) the first time it's computed, using functools.lru_cache.
Example
# Naive recursive -- O(2^n), for illustration of the problem only def fib_naive(n): if n < 2: return n return fib_naive(n - 1) + fib_naive(n - 2) # Iterative -- the expected optimal solution def fib_iterative(n): if n < 2: return n a, b = 0, 1 for _ in range(2, n + 1): a, b = b, a + b return b # Memoized recursive -- also O(n), demonstrates caching explicitly from functools import lru_cache @lru_cache(maxsize=None) def fib_memo(n): if n < 2: return n return fib_memo(n - 1) + fib_memo(n - 2) # Example run # Input: n = 10 # Output: 55
💡 Always mention the naive version's exponential blowup by name (repeated overlapping subproblems) before presenting the optimal solution — it's exactly the insight that motivates dynamic programming as a technique, not just this one problem.
Factorial of a Number
Answer
Problem: Given a non-negative integer n, compute n! (the product of all positive integers up to n; 0! = 1).
Expected approach: Either a simple iterative loop or straightforward recursion with a clear base case — this problem is usually a warmup to check basic control flow and recursion mechanics rather than algorithmic insight.
Complexity — time O(n) · space O(1) iterative; O(n) recursive (call stack)
Key points
- 1Handle the base case: 0! = 1 and 1! =
- 2Iteratively (or recursively) multiply together every integer from 2 up to n.
Example
def factorial_iterative(n): result = 1 for i in range(2, n + 1): result *= i return result def factorial_recursive(n): if n <= 1: return 1 return n * factorial_recursive(n - 1) # Example run # Input: n = 5 # Output: 120 (5 * 4 * 3 * 2 * 1)
💡 Mention that Python's math.factorial(n) already exists and is implemented in optimized C — in real code you'd use that directly; implementing it by hand here is purely to demonstrate the underlying logic.
Check if a Number Is Prime
Answer
Problem: Given an integer n, determine whether it's a prime number (greater than 1, with no positive divisors other than 1 and itself).
Expected approach: Rather than checking every number up to n, you only need to check divisors up to sqrt(n) — if n has a factor larger than its square root, it must also have a corresponding factor smaller than the square root.
Complexity — time O(√n) · space O(1)
Key points
- 1Numbers less than 2 are not prime.
- 2Check divisibility by every integer from 2 up to and including sqrt(n).
- 3If any of them evenly divides n, it's not prime; otherwise, it is.
Example
import math def is_prime(n): if n < 2: return False for i in range(2, int(math.sqrt(n)) + 1): if n % i == 0: return False return True # Example run # Input: n = 17 # Output: True # Input: n = 18 # Output: False
Anagram Detection
Answer
Problem: Given two strings, determine whether one is an anagram of the other (contains exactly the same characters, with the same frequencies, in any order).
Expected approach: Either sort both strings and compare (O(n log n)), or compare character frequency counts using Counter (O(n)) — the Counter approach is the more efficient, expected answer.
Complexity — time O(n) with Counter; O(n log n) with sorting · space O(n)
Key points
- 1If the two strings have different lengths, they can't be anagrams — return False immediately as a fast check.
- 2Build a frequency count of each string's characters.
- 3Return whether the two frequency counts are exactly equal.
Example
from collections import Counter def is_anagram(s1: str, s2: str) -> bool: if len(s1) != len(s2): return False return Counter(s1) == Counter(s2) # Alternative: sorting-based approach def is_anagram_sort(s1: str, s2: str) -> bool: return sorted(s1) == sorted(s2) # Example run # Input: s1 = "listen", s2 = "silent" # Output: True
💡 Presenting both approaches and explicitly stating the Counter version is asymptotically faster (O(n) vs. O(n log n)) shows you compare solutions by complexity rather than just picking the first one that works.
Flatten a Nested List
Answer
Problem: Given a list that may contain other lists nested to arbitrary depth, return a single flat list of all the non-list elements, in order.
Expected approach: Recursion is the natural fit: for each element, if it's a list, recursively flatten it and extend the result; otherwise, append it directly. A generator-based version avoids building intermediate lists at each recursive level.
Complexity — time O(n), where n is the total number of elements across all nesting levels · space O(n) for the result, plus O(d) for the recursion stack, where d is the maximum nesting depth
Key points
- 1Iterate over each item in the input list.
- 2If the item is itself a list, recursively flatten it, and yield/extend each of its results.
- 3If the item is not a list, yield/append it directly.
Example
def flatten(nested_list): result = [] for item in nested_list: if isinstance(item, list): result.extend(flatten(item)) # recursive case else: result.append(item) # base case return result # Generator version -- more memory-efficient for very large/deep structures def flatten_gen(nested_list): for item in nested_list: if isinstance(item, list): yield from flatten_gen(item) else: yield item # Example run # Input: [1, [2, 3, [4, 5]], 6, [7]] # Output: [1, 2, 3, 4, 5, 6, 7]
💡 Mentioning the yield from generator variant and why it's more memory-efficient for very deep or large structures elevates this beyond a basic recursion exercise.
Merge Two Dictionaries
Answer
Problem: Given two dictionaries, merge them into one. If a key exists in both, the second dictionary's value should take precedence.
Expected approach: Modern Python offers several clean one-liners: the | operator (3.9+), dictionary unpacking ({**a, **b}), or.update() if mutating in place is acceptable.
Complexity — time O(n + m), where n and m are the sizes of the two dicts · space O(n + m)
Key points
- 1Choose a merge method based on whether a new dict or in-place mutation is wanted, and target Python version.
- 2Apply it: later arguments' keys overwrite earlier ones on conflict, in every approach shown.
Example
def merge_dicts(d1: dict, d2: dict) -> dict: return {**d1, **d2} # d2's values win on key conflicts; works on 3.5+ # Python 3.9+ alternative def merge_dicts_pipe(d1: dict, d2: dict) -> dict: return d1 | d2 # Example run # Input: d1 = {"a": 1, "b": 2}, d2 = {"b": 20, "c": 3} # Output: {"a": 1, "b": 20, "c": 3}
💡 Mentioning that d1 | d2 requires Python 3.9+ shows version-awareness — offer {**d1, **d2} as the more broadly compatible fallback if the interviewer's environment or constraints are unclear.
Sort a List Without Using Built-in Sort
Answer
Problem: Given a list of numbers, sort it in ascending order without using sorted() or.sort().
Expected approach: Implement a classic algorithm by hand — bubble sort or selection sort for simplicity (O(n²)), or quicksort/merge sort if the interviewer wants an efficient O(n log n) implementation (Q299 covers quicksort in depth). Step-by-Step Explanation (Bubble Sort) 1. Repeatedly step through the list, comparing each adjacent pair. 2. If a pair is out of order, swap them. 3. Repeat until a full pass completes with no swaps — the list is now sorted.
Complexity — time O(n²) worst/average case; O(n) best case (already sorted, with the early-exit check) · space O(n) for the copy (O(1) extra if sorting in place)
Example
def bubble_sort(nums): nums = nums.copy() # avoid mutating the caller's list n = len(nums) for i in range(n): swapped = False for j in range(0, n - i - 1): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] swapped = True if not swapped: # already sorted -- stop early break return nums # Example run # Input: [5, 2, 4, 1, 3] # Output: [1, 2, 3, 4, 5]
💡 Bubble sort is rarely what you'd use in real code, but the early-exit optimization (stopping once a pass makes no swaps) is worth including — it shows attention to the algorithm's actual behavior, not just a rote implementation.
Find the Second-Largest Number in a List
Answer
Problem: Given a list of numbers, find the second-largest distinct value.
Expected approach: A single pass tracking the largest and second-largest values seen so far is O(n) — much better than sorting the whole list (O(n log n)) just to read off the second element.
Complexity — time O(n) · space O(1)
Key points
- 1Initialize largest and second_largest to negative infinity.
- 2For each number: if it's greater than largest, shift largest down to second_largest, then update largest. Otherwise, if it's greater than second_largest (and not equal to largest, to handle duplicates correctly), update second_largest.
- 3Return second_largest once the pass is complete.
Example
def second_largest(nums): largest = second = float("-inf") for num in nums: if num > largest: largest, second = num, largest elif largest > num > second: second = num return second if second != float("-inf") else None # Example run: second_largest([10, 5, 8, 20, 20, 3]) -> 10 # (20 is largest; 10 is the largest distinct value below it)
Remove Duplicates from a List
Answer
Problem: Given a list, return a new list with duplicate values removed, preserving the original order of first appearance.
Expected approach: This is directly covered in, Q53 — the idiomatic modern answer is list(dict.fromkeys(items)), relying on dicts preserving insertion order.
Complexity — time O(n) · space O(n)
Key points
- 1dict.fromkeys(items) builds a dictionary using each item as a key (automatically deduplicating, since dict keys must be unique) with no meaningful values.
- 2Converting.keys() back to a list() recovers the deduplicated items in their original first-seen order.
Example
def remove_duplicates(items): return list(dict.fromkeys(items)) # Manual, explicit version def remove_duplicates_manual(items): seen = set() result = [] for item in items: if item not in seen: seen.add(item) result.append(item) return result # Example run # Input: [3, 1, 4, 1, 5, 3, 9] # Output: [3, 1, 4, 5, 9]
💡 Have the manual seen = set() version ready even if you lead with dict.fromkeys() — interviewers sometimes want to confirm you understand why it works (O(1) average membership checks), not just that you know the trick.
Find Common Elements Between Two Lists
Answer
Problem: Given two lists, return the elements that appear in both.
Expected approach: Convert both to sets and use set intersection (&) — O(n + m) instead of an O(n × m) nested-loop comparison.
Complexity — time O(n + m) · space O(n + m)
Key points
- 1Convert each list to a set.
- 2Compute the intersection of the two sets, which contains only elements present in both.
- 3Convert back to a list if the required output type is a list.
Example
def find_common(list1, list2): return list(set(list1) & set(list2)) # Example run # Input: list1 = [1, 2, 3, 4], list2 = [3, 4, 5, 6] # Output: [3, 4] (order may vary)
💡 If the interviewer asks for the result to preserve list1 's original order and to include duplicates matching their count in list1, that's a signal they want more than the basic set-intersection answer — clarify requirements before assuming sets are sufficient.
Implement a Stack
Answer
Problem: Implement a stack data structure supporting push, pop, peek, and is_empty, following LIFO (last-in, firstout) order.
Expected approach: A Python list already supports O(1) amortized append/pop from the end, making it a natural, efficient backing structure — wrap it in a small class for a clean interface.
Complexity — time O(1) for push, pop, peek, and is_empty · space O(n) for n stored items
Key points
- 1push(item) appends to the end of the internal list.
- 2pop() removes and returns the last item (raising an error if empty).
- 3peek() returns the last item without removing it.
- 4is_empty() checks whether the internal list has any items.
Example
class Stack: def __init__(self): self._items = [] def push(self, item): self._items.append(item) def pop(self): if self.is_empty(): raise IndexError("pop from empty stack") return self._items.pop() def peek(self): if self.is_empty(): raise IndexError("peek from empty stack") return self._items[-1] def is_empty(self): return len(self._items) == 0 # Example run s = Stack() s.push(1); s.push(2); s.push(3) s.pop() # 3 s.peek() # 2
💡 Explicitly justify using a list (append/pop from the end are both O(1) amortized) rather than insert(0,.) / pop(0), which would silently make this O(n) per operation.
Implement a Queue
Answer
Problem: Implement a queue data structure supporting enqueue, dequeue, and is_empty, following FIFO (first-in, first-out) order.
Expected approach: Use collections.deque rather than a plain list — deque.popleft() is O(1), while list.pop(0) is O(n) since every remaining element must shift, Q224).
Complexity — time O(1) for enqueue, dequeue, and is_empty · space O(n) for n stored items
Key points
- 1enqueue(item) appends to the right end of the deque.
- 2dequeue() removes and returns from the left end.
- 3is_empty() checks whether the deque has any items.
Example
from collections import deque class Queue: def __init__(self): self._items = deque() def enqueue(self, item): self._items.append(item) def dequeue(self): if self.is_empty(): raise IndexError("dequeue from empty queue") return self._items.popleft() def is_empty(self): return len(self._items) == 0 # Example run q = Queue() q.enqueue(1); q.enqueue(2); q.enqueue(3) q.dequeue() # 1 q.dequeue() # 2
Implement a Simple LRU Cache
Answer
Problem: Implement a cache with a fixed maximum size that evicts the least recently used item when it's full and a new item needs to be added.
Expected approach: collections.OrderedDict (or a regular dict, since 3.7+ preserves order) combined with moving accessed keys to the end gives O(1) get/put — the key insight is that "least recently used" corresponds to the front of an ordertracking structure, and any access should move that item to the back.
Complexity — time O(1) for both get and put · space O(capacity)
Key points
- 1On get(key): if present, move it to the end (marking it "recently used") and return its value; otherwise return a sentinel (e.g., -1 or None).
- 2On put(key, value): if the key already exists, update it and move it to the end. If it's new and the cache is full, remove the item at the front (least recently used) before inserting the new one at the end.
Example
from collections import OrderedDict class LRUCache: def __init__(self, capacity: int): self.capacity = capacity self.cache = OrderedDict() def get(self, key): if key not in self.cache: return -1 self.cache.move_to_end(key) # mark as recently used return self.cache[key] def put(self, key, value): if key in self.cache: self.cache.move_to_end(key) self.cache[key] = value if len(self.cache) > self.capacity: self.cache.popitem(last=False) # evict the least recently used (front) cache = LRUCache(2) cache.put(1, "a") cache.put(2, "b") cache.get(1) # "a" -- and 1 is now most recently used cache.put(3, "c") # evicts 2 (least recently used), not 1 # Example run cache = LRUCache(2) cache.put(1, "a"); cache.put(2, "b") cache.get(1) # "a" cache.put(3, "c") # evicts key 2 cache.get(2) # -1 (evicted)
💡 This is one of the most frequently asked "design a data structure" interview problems precisely because it combines a hash map (fast lookup) with an ordering mechanism (fast eviction) — naming OrderedDict.move_to_end() and.popitem(last=False) specifically shows fluency with the exact tools that make O(1) possible.
Word Frequency Counter
Answer
Problem: Given a block of text, return how many times each word appears, ignoring case and punctuation.
Expected approach: Normalize the text (lowercase, strip punctuation), split into words, and count with collections.Counter — the normalization step is what most naive solutions get wrong.
Complexity — time O(n), where n is the length of the text · space O(k), where k is the number of distinct words
Key points
- 1Lowercase the entire text so "The" and "the" count as the same word.
- 2Strip punctuation, typically with a regular expression that keeps only word characters and spaces.
- 3Split on whitespace to get individual words.
- 4Count with Counter.
Example
import re from collections import Counter def word_frequency(text: str) -> dict: text = text.lower() words = re.findall(r"[a-z0-9']+", text) # extracts words, ignoring punctuation return dict(Counter(words)) # Example run # Input: "The cat sat. The cat ran!" # Output: {'the': 2, 'cat': 2, 'sat': 1, 'ran': 1}
💡 Explicitly ask (or state your assumption) about how to handle contractions and hyphenated words ("don't", "well-known") — this is exactly the kind of edge case that separates a careful solution from a naive.split() call.
Check Balanced Parentheses
Answer
Problem: Given a string containing only[]{} characters, determine whether the brackets are properly balanced and correctly nested.
Expected approach: Use a stack (Q273): push opening brackets, and on each closing bracket, check that it matches the most recently pushed opening bracket (popped from the top of the stack).
Complexity — time O(n) · space O(n)
Key points
- 1Create an empty stack and a mapping of closing brackets to their matching opening brackets.
- 2For each character: if it's an opening bracket, push it. If it's a closing bracket, pop the stack and check the popped value matches the expected opening bracket — if the stack is empty or it doesn't match, the string is unbalanced.
- 3After processing every character, the string is balanced only if the stack is empty (no unmatched opening brackets remain).
Example
def is_balanced(s: str) -> bool: stack = [] pairs = {")": "(", "]": "[", "}": "{"} for char in s: if char in "([{": stack.append(char) elif char in ")]}": if not stack or stack.pop() != pairs[char]: return False return len(stack) == 0 # Example run # Input: "([{}])" # Output: True # Input: "([)]" # Output: False
💡 This is the canonical example for "when would you use a stack" — the LIFO property is exactly what correctly handles nested structures, since the most recently opened bracket must be the next one closed.
Binary Search
Answer
Problem: Given a sorted list and a target value, return the index of the target, or -1 if it isn't present.
Expected approach: Repeatedly halve the search space: compare the target to the middle element, and discard the half that can't possibly contain it — this is the fundamental O(log n) searching technique, only possible because the input is sorted.
Complexity — time O(log n) · space O(1) iterative; O(log n) if implemented recursively (call stack)
Key points
- 1Set low = 0 and high = len(nums) -
- 2While low <= high: compute mid = (low + high) //
- 3If nums[mid] == target, return mid. If nums[mid] < target, search the right half (low = mid + 1). Otherwise search the left half (high = mid - 1).
- 4If the loop ends without finding the target, return -1.
Example
def binary_search(nums, target): low, high = 0, len(nums) - 1 while low <= high: mid = (low + high) // 2 if nums[mid] == target: return mid elif nums[mid] < target: low = mid + 1 else: high = mid - 1 return -1 # Example run # Input: nums = [1, 3, 5, 7, 9, 11], target = 7 # Output: 3
FizzBuzz
Answer
Problem: Print the numbers from 1 to n, but for multiples of 3 print "Fizz", for multiples of 5 print "Buzz", and for multiples of both print "FizzBuzz".
Expected approach: Check the "both" condition (divisible by 15, or by both 3 and 5) before checking each individually — order of conditions matters here, since checking 3 or 5 first without also checking the other would produce the wrong output for multiples of 15.
Complexity — time O(n) · space O(n) for the result list (O(1) extra if printing directly instead of collecting)
Key points
- 1For each number from 1 to n: check divisibility by 15 first (or equivalently, by both 3 and 5).
- 2If not divisible by 15, check 3 alone, then 5 alone.
- 3If none apply, output the number itself.
Example
def fizzbuzz(n): result = [] for i in range(1, n + 1): if i % 15 == 0: result.append("FizzBuzz") elif i % 3 == 0: result.append("Fizz") elif i % 5 == 0: result.append("Buzz") else: result.append(str(i)) return result # Example run: fizzbuzz(15) -> ['1', '2', 'Fizz', '4', 'Buzz', 'Fizz', '7', # '8', 'Fizz', 'Buzz', '11', 'Fizz', '13', '14', 'FizzBuzz']
💡 FizzBuzz is famously used as a very basic filter question — the real signal isn't solving it (nearly everyone can), but doing so cleanly, correctly handling the "both" case, and not overengineering a trivial problem.
Find All Permutations of a String
Answer
Problem: Given a string of distinct characters, return all possible permutations (reorderings) of its characters.
Expected approach: Use backtracking: build permutations character by character, and at each step try every character not yet used, recursing until a full-length permutation is built, then backtrack to try other choices.
Complexity — time O(n × n!), since there are n! permutations each of length n · space O(n × n!) to store all results
Key points
- 1If the current partial permutation has the same length as the input, it's complete — add it to the results.
- 2Otherwise, try each character not yet used in the current permutation, add it, recurse, then remove it (backtrack) before trying the next option.
- 3itertools.permutations provides this directly in the standard library for production use.
Example
def permutations(s: str): result = [] def backtrack(current, remaining): if not remaining: result.append(current) return for i in range(len(remaining)): backtrack(current + remaining[i], remaining[:i] + remaining[i+1:]) backtrack("", s) return result # Standard-library equivalent, preferred in real code from itertools import permutations as itertools_permutations print(["".join(p) for p in itertools_permutations("abc")]) # Example run # Input: "abc" # Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
💡 Backtracking problems are a common "hard" category — always narrate the pattern explicitly ("choose, explore, un-choose") as you code, since interviewers are evaluating whether you understand the technique generally, not just this specific problem.
Find All Subsets of a Set (Power Set)
Answer
Problem: Given a list of distinct elements, return all possible subsets (the power set), including the empty set and the full set itself.
Expected approach: Backtracking (include/exclude each element) or an iterative "double the results so far" approach both work; for each of the n elements, there are 2 choices (include or exclude), giving 2^n total subsets.
Complexity — time O(n × 2^n), since there are 2^n subsets each of average length n/2 · space O(n × 2^n) to store all results
Key points
- 1Backtracking version: for each element, recursively branch into "include it" and "exclude it," building up subsets as you go.
- 2Iterative version: start with just the empty set; for each new element, take every existing subset and add a copy of it with the new element included, doubling the result list's size each time.
Example
def subsets_backtracking(nums): result = [] def backtrack(index, current): if index == len(nums): result.append(current[:]) return # Exclude nums[index] backtrack(index + 1, current) # Include nums[index] current.append(nums[index]) backtrack(index + 1, current) current.pop() # backtrack backtrack(0, []) return result def subsets_iterative(nums): result = [[]] for num in nums: result += [subset + [num] for subset in result] return result # Example run: subsets_iterative([1, 2, 3]) -> # [[], [3], [2], [2,3], [1], [1,3], [1,2], [1,2,3]] (order varies)
💡 The iterative "doubling" approach is a nice, less obvious alternative to backtracking worth mentioning — it demonstrates recognizing the same 2^n structure from a different angle.
Merge Two Sorted Lists
Answer
Problem: Given two sorted lists, merge them into a single sorted list.
Expected approach: Use two pointers, one for each list, always advancing whichever pointer currently points to the smaller value — this is the core merge step from merge sort, and runs in linear time since each element is examined exactly once.
Complexity — time O(n + m) · space O(n + m)
Key points
- 1Initialize two pointers, i and j, at the start of each list, and an empty result list.
- 2While both pointers are within bounds: compare list1[i] and list2[j], append the smaller one to the result, and advance that pointer.
- 3Once one list is exhausted, append whatever remains of the other list directly (it's already sorted).
Example
def merge_sorted_lists(list1, list2): result = [] i = j = 0 while i < len(list1) and j < len(list2): if list1[i] <= list2[j]: result.append(list1[i]) i += 1 else: result.append(list2[j]) j += 1 result.extend(list1[i:]) # append any remaining tail result.extend(list2[j:]) return result # Example run # Input: list1 = [1, 3, 5], list2 = [2, 4, 6] # Output: [1, 2, 3, 4, 5, 6]
💡 This exact merge step is the foundation of merge sort's O(n log n) divide-and-conquer algorithm — mentioning that connection shows you see this as more than an isolated problem.
Find the Longest Substring Without Repeating Characters
Answer
Problem: Given a string, find the length of the longest substring that contains no repeating characters.
Expected approach: The "sliding window" technique: maintain a window (a range of indices) that always contains no duplicates, expanding the right edge and shrinking the left edge as needed, tracked with a set or a dict of last-seen positions.
Complexity — time O(n), since each character is added and removed from the window at most once · space O(min(n, alphabet size))
Key points
- 1Maintain a set of characters currently in the window, and two pointers, left and right, both starting at
- 2Expand right one character at a time. If that character is already in the window, shrink from left (removing characters from the set) until the duplicate is gone.
- 3After each expansion, update the maximum window size seen so far.
Example
def longest_unique_substring(s: str) -> int: seen = set() left = 0 max_length = 0 for right in range(len(s)): while s[right] in seen: seen.remove(s[left]) left += 1 seen.add(s[right]) max_length = max(max_length, right - left + 1) return max_length # Example run # Input: "abcabcbb" # Output: 3 ("abc" is the longest substring without repeats)
💡 The sliding window pattern is one of the highest-value techniques to have fluent — it solves an entire family of "longest/shortest substring/subarray satisfying some condition" problems, not just this one.
Group Anagrams
Answer
Problem: Given a list of strings, group the ones that are anagrams of each other.
Expected approach: Use each string's sorted-character form (or a character-frequency signature) as a dictionary key — all anagrams share the same key, so grouping is just a matter of bucketing by that key.
Complexity — time O(n × k log k), where n is the number of words and k is the max word length (sorting each word) · space O(n × k)
Key points
- 1Create a defaultdict(list) to collect groups.
- 2For each string, compute a canonical key (its sorted character sequence).
- 3Append the original string to the list stored under that key.
- 4Return the dictionary's values as the final groups.
Example
from collections import defaultdict def group_anagrams(words): groups = defaultdict(list) for word in words: key = "".join(sorted(word)) # canonical form -- all anagrams share this groups[key].append(word) return list(groups.values()) # Example run # Input: ["eat", "tea", "tan", "ate", "nat", "bat"] # Output: [["eat", "tea", "ate"], ["tan", "nat"], ["bat"]] (group order may vary)
💡 Mention that using a sorted-character-tuple key versus a Counter -based signature is a real trade-off — sorting is O(k log k) per word, while a character-count-based key can be built in O(k), which matters for very long words.
Implement a Binary Search Tree: Insert and Search
Answer
Problem: Implement a binary search tree (BST) supporting insert and search, where every left subtree contains only smaller values and every right subtree contains only larger values.
Expected approach: Recursive insertion and search, comparing the target value to the current node and moving left or right accordingly — both operations run in O(log n) on a balanced tree, degrading to O(n) on a skewed one.
Complexity — time O(log n) average (balanced tree); O(n) worst case (skewed tree) for both insert and search · space O(n) for the tree; O(log n) to O(n) recursion stack depending on balance
Key points
- 1insert(value): starting at the root, compare value to the current node; go left if smaller, right if larger, until an empty spot is found, then place a new node there.
- 2search(value): same traversal logic, returning True if a matching node is found, False if an empty spot is reached first.
Example
class TreeNode: def __init__(self, value): self.value = value self.left = None self.right = None class BST: def __init__(self): self.root = None def insert(self, value): self.root = self._insert(self.root, value) def _insert(self, node, value): if node is None: return TreeNode(value) if value < node.value: node.left = self._insert(node.left, value) elif value > node.value: node.right = self._insert(node.right, value) return node def search(self, value): return self._search(self.root, value) def _search(self, node, value): if node is None: return False if node.value == value: return True if value < node.value: return self._search(node.left, value) return self._search(node.right, value) # Example run: tree = BST() for v in [5, 3, 8, 1, 4]: tree.insert(v) tree.search(4) # True tree.search(10) # False
💡 Always mention the balanced-vs-skewed distinction explicitly — a BST built by inserting already-sorted data degrades to a linked list (O(n) operations), which is exactly why self-balancing variants (AVL, red-black trees) exist.
Reverse a Linked List
Answer
Problem: Given the head of a singly linked list, reverse it and return the new head.
Expected approach: Iterate through the list once, reversing each node's next pointer to point backward instead of forward, using three tracking pointers (previous, current, next) to avoid losing the rest of the list.
Complexity — time O(n) · space O(1) iterative; O(n) if implemented recursively (call stack)
Key points
- 1Set previous = None and current = head.
- 2While current is not None: save current.next before overwriting it, point current.next back to previous, then advance both previous and current forward by one node.
- 3Once the loop ends, previous is the new head of the reversed list.
Example
class ListNode: def __init__(self, value, next=None): self.value = value self.next = next def reverse_linked_list(head): previous = None current = head while current is not None: next_node = current.next # save before overwriting current.next = previous # reverse the pointer previous = current # advance previous current = next_node # advance current return previous # new head # Example run: reverse_linked_list(1 -> 2 -> 3 -> None) -> 3 -> 2 -> 1 -> None
💡 Drawing the three pointers (previous, current, next_node) on a whiteboard, one step at a time, is the expected way to walk through this — reversing linked list pointers is notoriously easy to get subtly wrong without visualizing each step.
Detect a Cycle in a Linked List
Answer
Problem: Given the head of a linked list, determine whether it contains a cycle (a node's next pointer eventually loops back to a previous node).
Expected approach: Floyd's "tortoise and hare" algorithm: use two pointers moving at different speeds (one step and two steps per iteration) — if there's a cycle, the faster pointer will eventually catch up to and meet the slower one; if not, it will reach the end (None) first.
Complexity — time O(n) · space O(1) — this is the key advantage over a hash-set-based approach, which would use O(n) space
Key points
- 1Initialize slow = head and fast = head.
- 2Repeatedly move slow forward by one node and fast forward by two nodes.
- 3If fast (or fast.next) becomes None, there's no cycle — return False.
- 4If slow and fast ever point to the same node, a cycle exists — return True.
Example
def has_cycle(head) -> bool: slow = fast = head while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next if slow is fast: return True return False # Example run # Input: 1 -> 2 -> 3 -> 4 -> back to 2 (cycle) # Output: True
💡 Explicitly contrast this with the simpler (but O(n)-space) alternative of storing every visited node in a set — Floyd's algorithm is specifically valued for solving the same problem in O(1) space, which is exactly what makes it a favorite "clever trick" interview question.
Find the Kth Largest Element
Answer
Problem: Given a list of numbers and an integer k, find the k-th largest element (not necessarily distinct).
Expected approach: Sorting the whole list is O(n log n) but simple. A min-heap of size k (via heapq) achieves O(n log k), which is better when k is much smaller than n; Python's heapq.nlargest provides this directly.
Complexity — time O(n log n) sorting; O(n log k) heap-based · space O(n) sorting; O(k) heapbased
Key points
- 1Simple approach: sort the list in descending order and index into position k -
- 2Heap approach: maintain a min-heap of the k largest elements seen so far — for each new number, push it, and if the heap exceeds size k, pop the smallest. At the end, the heap's smallest element (the top) is the k-th largest overall.
Example
import heapq def kth_largest_sort(nums, k): return sorted(nums, reverse=True)[k - 1] def kth_largest_heap(nums, k): heap = [] for num in nums: heapq.heappush(heap, num) if len(heap) > k: heapq.heappop(heap) # discard the smallest, keeping only the top k return heap[0] # the smallest of the top k IS the k-th largest # Even simpler, using the standard library directly: def kth_largest_builtin(nums, k): return heapq.nlargest(k, nums)[-1] # Example run # Input: nums = [3, 2, 1, 5, 6, 4], k = 2 # Output: 5
💡 When k is small relative to n, explicitly justify the heap approach's advantage (O(n log k) vs O(n log n)) — this is exactly the kind of complexity-aware reasoning interviewers want to see beyond "it works."
Valid Palindrome, Ignoring Non-Alphanumeric Characters
Answer
Problem: Given a string that may contain spaces, punctuation, and mixed case, determine whether it's a palindrome when considering only alphanumeric characters, case-insensitively.
Expected approach: Two pointers converging from both ends, skipping over non-alphanumeric characters on either side before comparing — this avoids the extra O(n) space of first building a fully cleaned copy of the string.
Complexity — time O(n) · space O(1)
Key points
- 1Set left = 0 and right = len(s) -
- 2While left < right: advance left past any nonalphanumeric characters, and move right backward past any non-alphanumeric characters.
- 3Compare s[left].lower() and s[right].lower() — if they differ, it's not a palindrome. Otherwise, move both pointers inward and continue.
Example
def is_valid_palindrome(s: str) -> bool: left, right = 0, len(s) - 1 while left < right: while left < right and not s[left].isalnum(): left += 1 while left < right and not s[right].isalnum(): right -= 1 if s[left].lower() != s[right].lower(): return False left += 1 right -= 1 return True # Example run # Input: "A man, a plan, a canal: Panama" # Output: True
💡 Explicitly compare this to the naive "clean the string first, then check s == s[::-1] " approach — that works too, but uses O(n) extra space for the cleaned copy, while the two-pointer version does it in O(1) space, which is worth stating as a deliberate trade-off.
Matrix Transpose
Answer
Problem: Given a 2D matrix (a list of lists), return its transpose (rows become columns and vice versa).
Expected approach: Python's zip(*matrix) unpacks each row as a separate argument to zip, which then groups elements by their original column position — an elegant, idiomatic one-liner for this exact operation.
Complexity — time O(rows × cols) · space O(rows × cols)
Key points
- 1*matrix unpacks the list of rows into separate positional arguments.
- 2zip() then groups the first elements of each row together, the second elements together, and so on — exactly the columns of the original matrix.
- 3Convert each resulting tuple back to a list if a list-of-lists output is required.
Example
def transpose(matrix): return [list(row) for row in zip(*matrix)] # Manual version, without zip def transpose_manual(matrix): rows, cols = len(matrix), len(matrix[0]) result = [[0] * rows for _ in range(cols)] for i in range(rows): for j in range(cols): result[j][i] = matrix[i][j] return result # Example run # Input: [[1, 2, 3], [4, 5, 6]] # Output: [[1, 4], [2, 5], [3, 6]]
💡 The zip(*matrix) idiom is a favorite "do you know Python's tricks" check — lead with it, but be ready to explain (or implement) the manual nested-loop version too, since that's what's actually testing algorithmic understanding.
Rotate a List
Answer
Problem: Given a list and an integer k, rotate the list to the right by k positions.
Expected approach: Slicing gives a clean O(n) solution: split the list at the appropriate point (accounting for k potentially being larger than the list's length via modulo) and swap the two halves' order.
Complexity — time O(n) · space O(n) for the new list (an in-place three-reversal trick can achieve O(1) extra space)
Key points
- 1Normalize k with k = k % len(nums) to handle rotations larger than the list itself.
- 2The last k elements become the new front; the remaining elements follow after them.
- 3Concatenate: nums[-k:] + nums[:-k] (handling k == 0 as a special case, since nums[-0:] is the whole list, not empty).
Example
def rotate_right(nums, k): if not nums: return nums k = k % len(nums) if k == 0: return nums[:] return nums[-k:] + nums[:-k] # Example run # Input: nums = [1, 2, 3, 4, 5], k = 2 # Output: [4, 5, 1, 2, 3]
Binary Search on a Rotated Sorted Array
Answer
Problem: Given a sorted array that has been rotated at an unknown pivot (e.g., [4,5,6,7,0,1,2]), find the index of a target value, or -1 if it isn't present — in O(log n) time.
Expected approach: Modified binary search: at each step, determine which half of the current range is properly sorted, then check whether the target falls within that sorted half's range — narrowing the search accordingly, exactly like standard binary search, just with an extra "which half is sorted" check.
Complexity — time O(log n) · space O(1)
Key points
- 1Compute mid as usual. If nums[mid] == target, return mid.
- 2Determine whether the left half (low to mid) or the right half (mid to high) is properly sorted, by comparing nums[low] and nums[mid].
- 3If the target falls within the sorted half's value range, search that half; otherwise search the other half.
Example
def search_rotated(nums, target): low, high = 0, len(nums) - 1 while low <= high: mid = (low + high) // 2 if nums[mid] == target: return mid if nums[low] <= nums[mid]: # left half is sorted if nums[low] <= target < nums[mid]: high = mid - 1 else: low = mid + 1 else: # right half is sorted if nums[mid] < target <= nums[high]: low = mid + 1 else: high = mid - 1 return -1 # Example run # Input: nums = [4, 5, 6, 7, 0, 1, 2], target = 0 # Output: 4
💡 Draw the array and explicitly identify which half is sorted at each step before writing any code — this problem is much more about careful case analysis than complex logic, and narrating your reasoning out loud is exactly what's being evaluated.
Maximum Sum Subarray of Fixed Size k
Answer
Problem: Given a list of numbers and an integer k, find the maximum sum of any contiguous subarray of exactly size k.
Expected approach: A naive approach recomputes the sum of every window from scratch (O(n × k)). The sliding window technique computes the first window's sum once, then updates it incrementally as the window slides (subtract the element leaving, add the element entering) — O(n) overall.
Complexity — time O(n) · space O(1)
Key points
- 1Compute the sum of the first k elements as the initial window sum.
- 2Slide the window one position at a time: subtract the element leaving the window (at the left) and add the element entering it (at the right).
- 3Track the maximum window sum seen throughout.
Example
def max_sum_subarray(nums, k): window_sum = sum(nums[:k]) max_sum = window_sum for i in range(k, len(nums)): window_sum += nums[i] - nums[i - k] # slide: add new, remove old max_sum = max(max_sum, window_sum) return max_sum # Example run # Input: nums = [2, 1, 5, 1, 3, 2], k = 3 # Output: 9 (subarray [5, 1, 3])
💡 Explicitly naming the naive O(n × k) approach and explaining exactly why sliding the window (rather than recomputing each sum) drops it to O(n) demonstrates the core insight interviewers are checking for with sliding-window problems generally.
Find Pairs with a Given Sum in a Sorted Array
Answer
Problem: Given a sorted list of numbers and a target sum, find all pairs of numbers that add up to the target.
Expected approach: Two pointers starting at opposite ends of the sorted array: if the current pair's sum is too small, move the left pointer up; if too large, move the right pointer down; if it matches, record the pair and move both — this exploits the sorted order to avoid the O(n²) brute force.
Complexity — time O(n) · space O(1) extra, beyond the output list
Key points
- 1Set left = 0 and right = len(nums) -
- 2While left < right: compute the current pair's sum.
- 3If it equals the target, record the pair and move both pointers inward. If it's less than the target, move left up (to increase the sum). If greater, move right down (to decrease the sum).
Example
def find_pairs_with_sum(nums, target): left, right = 0, len(nums) - 1 pairs = [] while left < right: current_sum = nums[left] + nums[right] if current_sum == target: pairs.append((nums[left], nums[right])) left += 1 right -= 1 elif current_sum < target: left += 1 else: right -= 1 return pairs # Example run # Input: nums = [1, 2, 3, 4, 5, 6], target = 7 # Output: [(1, 6), (2, 5), (3, 4)]
💡 Explicitly contrast this with Q262's Two Sum (hash-map approach, O(n), works on unsorted input) — this two-pointer version specifically requires and exploits the sorted property, giving O(1) extra space instead of Two Sum's O(n).
Check if Two Strings Are Rotations of Each Other
Answer
Problem: Given two strings, determine whether one is a rotation of the other (e.g., "waterbottle" and "erbottlewat").
Expected approach: A clever trick: if s2 is a rotation of s1, then s2 must be a substring of s1 + s1 (concatenating s1 with itself covers every possible rotation point).
Complexity — time O(n) on average (Python's substring search is highly optimized; worst case O(n²) for pathological inputs) · space O(n) for the concatenated string
Key points
- 1If the two strings have different lengths, they can't be rotations of each other.
- 2Concatenate s1 with itself.
- 3Check whether s2 appears anywhere within that concatenation using the in operator.
Example
def is_rotation(s1: str, s2: str) -> bool: if len(s1) != len(s2): return False return s2 in (s1 + s1) # Example run # Input: s1 = "waterbottle", s2 = "erbottlewat" # Output: True
💡 This "concatenate and search" trick is a classic example of reframing a problem into one Python already solves efficiently — explaining why s1 + s1 covers every rotation point is the actual insight being tested, not just knowing the trick exists.
Implement a Simple Trie (Prefix Tree)
Answer
Problem: Implement a trie supporting insert(word) and search(word), and starts_with(prefix) to check whether any inserted word begins with a given prefix.
Expected approach: Each trie node holds a dictionary of child nodes keyed by character, plus a flag marking whether a complete word ends at that node — inserting and searching both walk character by character down the tree.
Complexity — time O(m) for insert/search/starts_with, where m is the word/prefix length · space O(total characters across all inserted words)
Key points
- 1insert(word): starting at the root, for each character, create a child node if it doesn't already exist, then move into it. Mark the final node as the end of a word.
- 2search(word): walk the same path; if any character is missing along the way, the word isn't present. If the full path exists, check the final node's "end of word" flag.
- 3starts_with(prefix): identical traversal to search, but without requiring the final node to be marked as an end-of-word.
Example
class TrieNode: def __init__(self): self.children = {} self.is_end_of_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word: str): node = self.root for char in word: node = node.children.setdefault(char, TrieNode()) node.is_end_of_word = True def search(self, word: str) -> bool: node = self._find_node(word) return node is not None and node.is_end_of_word def starts_with(self, prefix: str) -> bool: return self._find_node(prefix) is not None def _find_node(self, s: str): node = self.root for char in s: if char not in node.children: return None node = node.children[char] return node # Example run trie = Trie() trie.insert("apple") trie.search("apple") # True trie.search("app") # False -- "app" was never inserted as a complete word trie.starts_with("app") # True -- "apple" starts with "app"
💡 Tries are the standard tool behind autocomplete and spell-checking features — mentioning that real-world use case grounds this otherwise abstract data structure in something concrete and recognizable.
Count Vowels and Consonants in a String
Answer
Problem: Given a string, count how many characters are vowels and how many are consonants (letters only — ignore digits, spaces, and punctuation).
Expected approach: Iterate through the string once, classifying each alphabetic character as a vowel or consonant based on membership in a fixed vowel set, skipping non-letter characters entirely.
Complexity — time O(n) · space O(1)
Key points
- 1Define a set of vowels for O(1) membership checks: {"a", "e", "i", "o", "u"}.
- 2For each character (after lowercasing), skip it if it's not alphabetic.
- 3Otherwise, increment the vowel count if it's in the vowel set, or the consonant count if not.
Example
def count_vowels_consonants(s: str): vowels = set("aeiou") vowel_count = consonant_count = 0 for char in s.lower(): if not char.isalpha(): continue if char in vowels: vowel_count += 1 else: consonant_count += 1 return vowel_count, consonant_count # Example run # Input: "Hello, World! 123" # Output: (3, 7) (vowels: e, o, o; consonants: H, l, l, W, r, l, d)
💡 Using a set for vowel lookups instead of char in "aeiou" (a string) is a small but real optimization worth mentioning — set membership is O(1) average versus O(k) for a short string, though the practical difference here is negligible at this scale.
Find the Longest Common Prefix Among Strings
Answer
Problem: Given a list of strings, find the longest string that is a prefix of every string in the list.
Expected approach: Compare characters column by column across all strings simultaneously, stopping at the first mismatch or the first string that's too short — alternatively, use Python's min / max on the sorted list, since the common prefix of the whole list must match the common prefix of its alphabetically first and last elements.
Complexity — time O(n log n) for sorting, plus O(m) for the comparison, where m is the shortest string's length · space O(n) for the sorted copy
Key points
- 1Sorting-based trick: sort the list of strings alphabetically. The longest common prefix of the entire list is the same as the common prefix between just the first and last strings after sorting (since sorting groups similar prefixes together).
- 2Compare the first and last sorted strings character by character until a mismatch, and return everything matched so far.
Example
def longest_common_prefix(strs): if not strs: return "" strs = sorted(strs) first, last = strs[0], strs[-1] i = 0 while i < len(first) and i < len(last) and first[i] == last[i]: i += 1 return first[:i] # Example run # Input: ["flower", "flow", "flight"] # Output: "fl"
💡 The "sort first, then only compare the first and last elements" trick is a clever but non-obvious insight worth explaining clearly — it reduces what looks like an all-pairs comparison problem to a single pairwise comparison.
Implement Quicksort
Answer
Problem: Implement the quicksort algorithm to sort a list of numbers in ascending order.
Expected approach: Pick a pivot element, partition the remaining elements into those less than and greater than the pivot, then recursively sort each partition — the classic divide-and-conquer sorting algorithm.
Complexity — time O(n log n) average; O(n²) worst case (poor pivot choices, e.g., always picking the smallest/ largest element) · space O(n) for this list-based version; O(log n) extra for an in-place version's recursion stack
Key points
- 1Base case: a list of 0 or 1 elements is already sorted.
- 2Choose a pivot (commonly the middle or a random element, to avoid worst-case behavior on already-sorted input).
- 3Partition the remaining elements into three groups: less than the pivot, equal to the pivot, and greater than the pivot.
- 4Recursively sort the "less than" and "greater than" groups, and concatenate: sorted_less + equal + sorted_greater.
Example
def quicksort(nums): if len(nums) <= 1: return nums pivot = nums[len(nums) // 2] less = [x for x in nums if x < pivot] equal = [x for x in nums if x == pivot] greater = [x for x in nums if x > pivot] return quicksort(less) + equal + quicksort(greater) # Example run # Input: [3, 6, 8, 10, 1, 2, 1] # Output: [1, 1, 2, 3, 6, 8, 10]
💡 This "list comprehension" version is clean and easy to write correctly under pressure, but mention explicitly that it isn't truly in-place (uses O(n) extra space) — offer to discuss the in-place partitioning version (Lomuto or Hoare partition schemes) if the interviewer wants to see that instead.
Merge Overlapping Intervals
Answer
Problem: Given a list of intervals (each a pair [start, end]), merge all overlapping intervals and return the resulting non-overlapping set.
Expected approach: Sort intervals by their start value first — once sorted, any overlap can only occur between an interval and the one immediately before it in the result, so a single linear pass through the sorted list is sufficient to merge everything correctly.
Complexity — time O(n log n), dominated by the initial sort · space O(n) for the sorted copy and result
Key points
- 1Sort the intervals by their starting value.
- 2Initialize the result with the first interval.
- 3For each subsequent interval: if it overlaps with the last interval in the result (its start is ≤ the last interval's end), merge them by extending the last interval's end if needed. Otherwise, add it as a new, separate interval.
Example
def merge_intervals(intervals): if not intervals: return [] intervals = sorted(intervals, key=lambda pair: pair[0]) merged = [intervals[0]] for start, end in intervals[1:]: last_start, last_end = merged[-1] if start <= last_end: # overlaps with the last merged interval merged[-1] = [last_start, max(last_end, end)] else: merged.append([start, end]) return merged # Example run # Input: [[1,3], [2,6], [8,10], [15,18]] # Output: [[1,6], [8,10], [15,18]]
💡 Explicitly justify why sorting first guarantees a single linear pass suffices — without sorting, an overlap could be "discovered" between any two arbitrary intervals in the list, requiring a much less efficient comparison of every pair.
Recommended resourcesAffiliate links · may earn us a commission