Pick an option and check it. The explanation shows after each answer. Take as long as you like; nothing is timed and nothing is sent.
20 questions
Question 1 · easy
What does this Python 3.12 program print?
def reverse_words(s):
return " ".join(reversed(s.split()))
print(reverse_words("keep calm and code"))
s.split() breaks the sentence into a list of words, reversed walks that list from the end, and " ".join glues the words back into one string. Only the order of the words changes; the letters inside each word stay as they are. Reversing the characters instead would be s[::-1], which is a different interview question.
Question 2 · medium
What does this Python 3.12 program print?
def move_zeros(nums):
w = 0
for i in range(len(nums)):
if nums[i] != 0:
nums[w] = nums[i]
w += 1
for i in range(w, len(nums)):
nums[i] = 0
return w
nums = [0, 1, 0, 3, 12]
w = move_zeros(nums)
print(w, nums)
The write pointer w copies each non-zero value forward in its original order, so after the first loop the front holds 1, 3, 12 and w is 3, the count of non-zero values. The second loop overwrites the leftover tail with zeros. This is the standard O(n) time, O(1) extra space answer to move-zeros, and it keeps the relative order of the non-zero elements.
Question 3 · easy
What does this Python 3.12 program print?
def is_pal(s):
t = [c.lower() for c in s if c.isalnum()]
return t == t[::-1]
print(is_pal("Never odd or even"), is_pal("Python"))
Before comparing, the function drops spaces and punctuation with isalnum() and lowercases every character, so "Never odd or even" becomes neveroddoreven, which reads the same both ways. Comparing a sequence with its reverse t[::-1] is the simplest palindrome check. Forgetting the clean-up step is the usual mistake: the raw string with its capital N and spaces is not a palindrome.
Question 4 · medium
This function should reverse a list in place, but it prints ['a', 'b', 'c', 'd'] unchanged. Which fix is right?
def reverse_in_place(chars):
n = len(chars)
for i in range(n):
chars[i], chars[n - 1 - i] = chars[n - 1 - i], chars[i]
return chars
print(reverse_in_place(list("abcd")))
Walking the whole list swaps every pair twice: once from the left half and once again from the right half, which puts everything back where it started. Stopping at the middle with range(n // 2) swaps each pair once; for an odd length the middle element stays where it is. Using chars[n - i] would read chars[n] on the first step and raise IndexError.
Question 5 · hard
What does this Python 3.12 program print?
def max_sub(nums):
best = cur = nums[0]
for x in nums[1:]:
cur = max(x, cur + x)
best = max(best, cur)
return best
print(max_sub([-2, 1, -3, 4, -1, 2, 1, -5, 4]), max_sub([-3, -1, -2]))
This is Kadane's algorithm: cur is the best sum of a subarray ending at the current element, and it restarts at x whenever carrying the previous sum would only drag it down. The best run in the first list is 4, -1, 2, 1 with sum 6. Seeding with nums[0] instead of 0 matters for an all-negative list: the answer is the largest single element, -1, not 0 (an empty subarray is not allowed).
Question 6 · medium
What does this Python 3.12 program print?
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []
print(two_sum([3, 2, 4], 6))
The dict maps each value already seen to its index, so the complement target - x is found in O(1) on average and the whole scan is O(n). Checking for the complement before storing x is what stops the 3 at index 0 from pairing with itself to make 6. The match is found at index 2 (value 4), and the earlier index comes first in the returned list.
Question 7 · easy
What does this Python 3.12 program print?
from collections import Counter
def first_unique(s):
counts = Counter(s)
for i, c in enumerate(s):
if counts[c] == 1:
return i
return -1
print(first_unique("swiss"), first_unique("aabb"))
The first pass counts every character with Counter; the second pass walks the string in its original order and returns the first index whose count is 1. In "swiss" the letter s appears three times, so the first unique character is w at index 1. Every character in "aabb" repeats, so the function returns -1. Two passes keep it O(n) instead of calling s.count(c) for every character, which is O(n^2).
Question 8 · easy
This anagram check prints True, but "aab" and "abb" are not anagrams. Which fix is right?
Anagrams must use the same letters the same number of times, and a set throws the counts away, so {'a', 'b'} equals {'a', 'b'}. Comparing two Counter objects compares every letter's count in O(n); sorted(a) == sorted(b) also works in O(n log n). Adding a length check does not help here because both strings have length 3.
Question 9 · medium
In the group-anagrams problem you write groups[key].append(word), where groups is a defaultdict(list). Why does key = tuple(sorted(word)) work while key = sorted(word) raises TypeError?
A dict finds a key by its hash, so the hash must never change while the key is stored; that is why mutable lists define no hash and raise TypeError: unhashable type: 'list'. A tuple of hashable items is hashable, and two anagrams sort to equal tuples, so they share one key. "".join(sorted(word)) is an equally good key.
Question 10 · hard
Given an unsorted list of integers, return the length of the longest run of consecutive values (for [100, 4, 200, 1, 3, 2] the answer is 4, from 1, 2, 3, 4). The interviewer asks for O(n) average time. Which approach meets it?
Set membership is O(1) on average, and counting only from the start of a run (where x - 1 is missing) means each number is stepped over by an inner count at most once, so the total work is O(n). Sorting or a heap gives a correct answer in O(n log n), which misses the stated bound. Using in on a list costs O(n) per lookup and makes the scan quadratic or worse.
Question 11 · medium
What does this Python 3.12 program print?
def longest_unique(s):
last = {}
start = best = 0
for i, c in enumerate(s):
if c in last and last[c] >= start:
start = last[c] + 1
last[c] = i
best = max(best, i - start + 1)
return best
print(longest_unique("pwwkew"), longest_unique("abba"))
The window s[start:i + 1] never holds a repeated character: when c was last seen inside the window, start jumps just past that position. In "pwwkew" the longest such substring is wke (pwke is a subsequence, not a substring). The check last[c] >= start matters for "abba": the old a at index 0 is already outside the window, so start must not move back, and the answer is 2.
Question 12 · easy
What does this Python 3.12 program print?
def count_pairs(nums, target):
i, j, count = 0, len(nums) - 1, 0
while i < j:
s = nums[i] + nums[j]
if s == target:
count += 1
i += 1
j -= 1
elif s < target:
i += 1
else:
j -= 1
return count
print(count_pairs([1, 2, 3, 4, 5, 6, 7], 8))
On a sorted list of distinct values the two pointers start at both ends and move inward, finding (1, 7), (2, 6) and (3, 5). The loop condition i < j stops before an element is paired with itself, so 4 + 4 is not counted, and each unordered pair is counted once. Every step moves at least one pointer, so the scan is O(n) with O(1) extra space.
Question 13 · medium
This should return the largest sum of any 3 consecutive elements (16, from 1, 7, 8 or 7, 8, 1), but it prints 19. Which fix is right?
def max_sum_k(nums, k):
window = sum(nums[:k])
best = window
for i in range(k, len(nums)):
window += nums[i] - nums[i - k + 1]
best = max(best, window)
return best
print(max_sum_k([4, 2, 1, 7, 8, 1, 2, 8, 1, 0], 3))
When the window slides so that it ends at index i, it covers i - k + 1 to i, so the element that just left is at i - k. Subtracting nums[i - k + 1] removes an element that is still inside the window and keeps the one that left, so the running sum drifts. With the correct index each step is O(1) and the whole scan is O(n).
Question 14 · easy
A list of integers is sorted in ascending order. You must say whether any two of them add up to target in O(n) time and O(1) extra space. Which approach fits?
Sorted input is the signal for two pointers: if the sum is too small, only moving the left pointer right can raise it, and if too large, only moving the right pointer left can lower it, so no pair is skipped. Each step discards one element, giving O(n) time with two integer variables. The set version is O(n) time but O(n) space, binary search is O(n log n), and nested loops are O(n^2).
Question 15 · medium
This sliding-window solution has a while loop inside a for loop. Why is it still O(n) for a string of length n?
def longest_unique(s):
window = set()
left = best = 0
for right, c in enumerate(s):
while c in window:
window.remove(s[left])
left += 1
window.add(c)
best = max(best, right - left + 1)
return best
Count the total work instead of multiplying loop bounds: left only moves forward and never passes right, so across the whole run the inner loop executes at most n times. Each set operation is O(1) on average, so the total is O(n). This amortised argument is what interviewers expect for any shrink-and-grow window.
Question 16 · medium
list.append in CPython is described as amortised O(1). What does that mean?
A Python list is a dynamic array: it keeps spare capacity, and when that runs out it allocates a larger block and copies the elements over. Because the extra room grows with the size of the list, the expensive copies become rarer as the list grows, and their total cost over n appends is O(n). Amortised is a guarantee about any sequence of operations, not an average over inputs.
Question 17 · medium
What is the time complexity of this function for a list of n numbers?
def total(nums):
if not nums:
return 0
return nums[0] + total(nums[1:])
A slice builds a new list, so nums[1:] costs O(k) for k remaining elements. The calls copy n - 1, n - 2, ..., 1 elements, which adds up to about n^2 / 2. Passing an index such as total(nums, i + 1) instead of slicing brings it down to O(n) time.
Question 18 · hard
What does this Python 3.12 program print?
n = 16
count = 0
i = 1
while i < n:
for j in range(i):
count += 1
i *= 2
print(count)
The outer loop runs for i = 1, 2, 4 and 8, and the inner loop runs i times, so the count is 1 + 2 + 4 + 8 = 15. A geometric series like this sums to less than 2n, so the code is O(n), not O(n log n): multiplying the outer count (log n) by the largest inner count (n) overestimates. Nested loops have to be summed, not just multiplied.
Question 19 · easy
This duplicate check gives the right answer but times out on a list of 100,000 numbers. Which change makes it O(n) on average?
def has_duplicate(nums):
seen = []
for x in nums:
if x in seen:
return True
seen.append(x)
return False
x in seen on a list compares against every stored element, which is O(n), so the loop is O(n^2) overall. A set hashes the value and checks one bucket, which is O(1) on average, making the whole function O(n). count still scans the whole list, and insert(0, x) adds an O(n) shift on every call.
Question 20 · easy
A breadth-first search over a graph with 100,000 nodes uses queue = [start] and takes the next node with queue.pop(0). It is slow. Which change makes both adding and removing a node O(1)?
list.pop(0) shifts every remaining element one place left, so it is O(n) per call and BFS becomes quadratic. A deque is built for both ends and gives O(1) append and popleft. Taking from the end with pop() turns the queue into a stack and changes the search into depth-first order, while a heap costs O(log n) per operation and orders nodes by value, not by arrival.
Your answers stay in this browser tab. Nothing is sent or saved.