30 questions from every round of the set, in 40 minutes. This is practice: your answers are marked in your browser, and the score is yours alone.
30 questions · 40 minutes
Before you start
30 questions in 40 minutes. The clock starts when you press Start and does not pause.
You can change an answer until you submit. Nothing is marked before that.
When you submit, or when the time runs out, every question shows the right answer and its explanation.
No marks are taken off for a wrong answer.
Question 1 · hard
What does this Python 3.12 program print?
t = ([1, 2], 3)
try:
t[0] += [4]
status = "ok"
except TypeError:
status = "TypeError"
print(status, t)
t[0] += [4] runs in two steps: list.__iadd__ extends the list in place, then Python stores the result back with t[0] = ..., which fails because a tuple does not support item assignment. The exception is raised after the list was already changed, so both the error and the mutation happen. A tuple fixes which objects it refers to, not the contents of those objects.
Question 2 · easy
Given this Python 3.12 signature:
def f(a, *args, b=10, **kwargs):
...
What is true about the parameter b?
*args collects all remaining positional arguments into a tuple, so any parameter written after it can only be filled by keyword; these are keyword-only parameters. f(1, 2, 3) gives a=1, args=(2, 3) and leaves b at 10, while f(1, b=5) sets b. **kwargs only receives keyword arguments that match no named parameter.
Question 3 · medium
What is the difference between __new__ and __init__ in a Python 3.12 class?
Cls(...) first calls Cls.__new__(Cls, ...) to build the object, then, if it returned an instance of Cls, calls __init__ on it with the same arguments. Most classes only need __init__. You override __new__ when the object itself must be chosen at creation time, such as subclassing an immutable type like tuple or str, or returning a cached instance.
Question 4 · easy
What does this Python 3.12 program print?
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __str__(self):
return f"({self.x}, {self.y})"
p = Point(1, 2)
print(p, [p])
print calls str() on each argument, which uses __str__. A list's string form is built from the repr() of each element, so inside the brackets you see __repr__. Write __repr__ for developers (ideally looking like the constructor call) and __str__ for end users; when only __repr__ is defined, str() falls back to it.
Question 5 · medium
What does this Python 3.12 program print?
class Dog:
tricks = []
legs = 4
def __init__(self, name):
self.name = name
a, b = Dog("Rex"), Dog("Bo")
a.tricks.append("sit")
a.legs = 3
print(b.tricks, b.legs, Dog.legs)
tricks is a class attribute, and a.tricks.append(...) mutates that one shared list, so every Dog sees it. a.legs = 3 is an assignment, which creates an instance attribute on a that shadows the class attribute without touching Dog.legs. Per-object mutable state belongs in __init__, as self.tricks = [].
Question 6 · hard
What does this Python 3.12 program print?
class A:
def hello(self):
return "A"
class B(A):
def hello(self):
return "B" + super().hello()
class C(A):
def hello(self):
return "C" + super().hello()
class D(B, C):
def hello(self):
return "D" + super().hello()
print(D().hello(), [k.__name__ for k in D.__mro__])
Python orders the classes with C3 linearization: a class comes before its parents and the parents keep the order they are listed in, so the MRO is D, B, C, A, object. super() means the next class in the MRO of the instance, not the parent of the current class, so super() inside B reaches C. That is why A runs only once in a diamond and why cooperative super() calls are safe.
Question 7 · medium
In Python 3.12, what happens when the last line of this program runs?
Equal objects must have equal hashes, and an identity hash would break that rule once __eq__ compares values, so Python sets __hash__ = None on such a class. Its instances cannot go into sets or be dictionary keys until you define __hash__ from the same fields __eq__ uses, for example hash(self.uid), and those fields should not change afterwards. @dataclass(frozen=True) generates a matching pair for you.
map, like filter, zip and every generator, returns a one-pass iterator rather than a list. The first list() consumes all its values, so the second finds the iterator exhausted and returns an empty list; list() handles the final StopIteration silently. Convert to a list once if you need the values twice.
Calling a generator function runs none of its body; it only creates a generator object, so created prints first. next(g) runs the body up to the first yield, printing start and handing back 1. The code after that yield waits for another next() call that never comes, so middle is never printed.
Question 10 · 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 11 · 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 12 · 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 13 · 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 14 · 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 15 · 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 16 · 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 17 · 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 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
What does this Python 3.12 program print?
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE leads(id INTEGER, city TEXT);
INSERT INTO leads VALUES (1, 'Puri'), (2, 'Puri'), (3, NULL), (4, 'Cuttack'), (5, NULL);
""")
sql = "SELECT COUNT(*), COUNT(city), COUNT(DISTINCT city) FROM leads"
print(con.execute(sql).fetchone())
COUNT(*) counts rows, NULLs included, so it is 5. COUNT(city) counts only non-NULL values (3), and COUNT(DISTINCT city) counts the distinct non-NULL values, Puri and Cuttack, so 2. Every aggregate except COUNT(*) ignores NULLs.
Question 20 · easy
What does this Python 3.12 program print?
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE users(id INTEGER, email TEXT);
INSERT INTO users VALUES (1, 'a@x.in'), (2, 'b@x.in'), (3, 'a@x.in'),
(4, 'c@x.in'), (5, 'c@x.in'), (6, 'c@x.in');
""")
sql = """SELECT email, COUNT(*) FROM users
GROUP BY email HAVING COUNT(*) > 1 ORDER BY email"""
print(con.execute(sql).fetchall())
GROUP BY email makes one group per address and COUNT(*) counts all rows in it, so a@x.in has 2 and c@x.in has 3. HAVING COUNT(*) > 1 then keeps only the groups that occur more than once, which is the standard way to find duplicate values. b@x.in appears once and is filtered out.
Question 21 · medium
Table sales has columns (region, amount) with rows ('east', 50), ('east', 200), ('east', 150), ('west', 400), ('north', 90), ('north', 95), ('north', 180), ('south', 110) and ('south', 120).
SELECT region, SUM(amount)
FROM sales
WHERE amount > 100
GROUP BY region
HAVING SUM(amount) > 300;
How many rows does the query return?
WHERE removes rows first, so only sales above 100 are summed: east 350, west 400, north 180 and south 230. HAVING then keeps groups whose sum is above 300, which leaves east and west. Applying HAVING to the unfiltered totals would wrongly include north (365) as well.
Question 22 · medium
What does this Python 3.12 program print?
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE orders(customer TEXT, status TEXT, amount INTEGER);
INSERT INTO orders VALUES ('asha', 'paid', 300), ('asha', 'refunded', 100),
('ravi', 'paid', 150), ('ravi', 'paid', 50), ('meena', 'refunded', 400);
""")
sql = """SELECT customer, COUNT(*),
SUM(CASE WHEN status = 'paid' THEN amount ELSE 0 END)
FROM orders GROUP BY customer HAVING COUNT(*) >= 2 ORDER BY customer"""
print(con.execute(sql).fetchall())
COUNT(*) counts every order in the group, refunded ones included, while the CASE expression adds an amount only when the status is paid, so asha's paid total is 300. This conditional aggregation computes several filtered totals in one pass over the table. meena has a single order, so HAVING COUNT(*) >= 2 removes her group.
Question 23 · medium
What does this Python 3.12 program print?
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE emp(name TEXT, salary INTEGER);
INSERT INTO emp VALUES ('anil', 90), ('bina', 90), ('chetan', 80), ('divya', 70);
""")
q1 = "SELECT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET 1"
q2 = "SELECT MAX(salary) FROM emp WHERE salary < (SELECT MAX(salary) FROM emp)"
print(con.execute(q1).fetchone()[0], con.execute(q2).fetchone()[0])
LIMIT 1 OFFSET 1 returns the second row, and with two employees tied at 90 that row is still 90. The subquery version first finds the top salary (90) and then takes the largest salary below it, 80, so it gives the second-highest distinct salary and returns NULL when there is none. SELECT DISTINCT salary ... LIMIT 1 OFFSET 1 or DENSE_RANK() also handle ties.
Question 24 · hard
Table customers has a column id with rows 1, 2 and 3. Table orders has a column customer_id with rows 1 and NULL (a guest checkout).
SELECT id
FROM customers
WHERE id NOT IN (SELECT customer_id FROM orders)
ORDER BY id;
What does the query return?
2 NOT IN (1, NULL) means 2 <> 1 AND 2 <> NULL, and any comparison with NULL is unknown, so the whole condition is unknown and the row is dropped; the same happens for every id. One NULL in a NOT IN list therefore empties the result. Use NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id), or filter customer_id IS NOT NULL in the subquery.
Question 25 · easy
A user resource has name, email and phone. The client wants to change only the phone number. How do PUT /users/7 and PATCH /users/7 differ for this?
PUT means "make the resource at this URL equal to this body", so fields left out may be cleared and a one-field update must still send the full object. PATCH carries a set of changes and is the method for partial updates. PUT is idempotent by definition; PATCH is not guaranteed to be (an "append to this list" patch adds again on every retry).
Question 26 · easy
A teammate proposes adding an index on every column of the orders table, which takes thousands of inserts per minute, "so that every query is fast". What is the best advice?
An index speeds up lookups, joins and sorts on its columns, but it is a second data structure the database keeps in sync on every write, and it takes storage. On a write-heavy table each extra index slows inserts and updates. Add indexes for the queries the app really runs and check in the query plan that they are used.
Question 27 · medium
A page lists 50 orders. The code runs one query to fetch the orders and then, inside a loop, one query per order to fetch its customer. The page is slow. What is the problem, and what is the fix?
N+1 means one query for the list plus one per row, so the cost grows with the page size and every query pays a network round trip. Fetch the related rows in one go: a join, or a second query with IN over the collected ids, which is what eager loading in an ORM does. Caching or a bigger server hides the symptom without removing the extra round trips.
Question 28 · medium
What does this Python 3.12 program print?
from functools import lru_cache
@lru_cache(maxsize=2)
def price(item):
return len(item) * 10
for item in ["pen", "book", "pen", "bag", "book"]:
price(item)
print(price.cache_info())
lru_cache(maxsize=2) keeps the two most recently used results. pen and book miss; the second pen is a hit and makes pen the most recent, so bag evicts book, the least recently used, and the final book misses again. That is 1 hit and 4 misses; a FIFO cache, which evicts by insertion order, would have evicted pen instead and scored 2 hits.
Question 29 · hard
Product prices are cached with cache-aside and a 10-minute TTL. When an admin changes a price, the service writes the new price to the database. What should it do with the cache so that reads stay correct with the least risk of serving a stale price?
Deleting the key after the commit means the next read misses and loads the committed value. Writing the cache first can leave a price in the cache that the database never accepted if the write fails, and with concurrent writers the two can end up disagreeing. Relying on the TTL alone serves the old price for up to 10 minutes, and flushing everything sends every read to the database at once; the TTL is still useful as a backstop for a missed invalidation.
Question 30 · medium
You scale a web app from one server to three behind a round-robin load balancer. Login sessions are kept in each server's process memory. Users now get logged out at random. What is the best fix?
With round-robin, a user's requests reach different servers, and a server that did not create the session does not know it. Moving session state out of the app servers, to a shared store or into a signed token, makes them stateless, so servers can be added, removed or restarted freely. Sticky sessions also hide the problem, but a user loses the session when that server dies and the load becomes uneven.
Your answers and your score stay in this browser tab. Nothing is sent or saved.