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 · easy
What does this Python 3.12 program print?
a = [1, 2]
b = a
b += [3]
c = a[:]
c.append(4)
print(a, len(c))
b = a binds a second name to the same list object, and += on a list extends it in place, so a sees the 3. The slice a[:] builds a new list, so appending to c leaves a alone. c started as a copy of [1, 2, 3] and gained one element, so its length is 4.
copy.copy makes a new outer list whose elements are the same inner list objects, so shallow[0][0] = 1 writes into a row that grid shares. copy.deepcopy copies nested objects recursively, so nothing done to deep reaches grid. Use a deep copy (or [row[:] for row in grid] for a list of flat rows) when nested data must be independent.
Question 3 · easy
In Python 3.12, consider:
a = [1, 2, 3]
b = [1, 2, 3]
Which statement about a == b and a is b is correct?
== calls __eq__, which for lists compares the elements one by one; is checks whether both names refer to the very same object. Every list literal creates a new list, so a is b is False. Use is only for identity checks such as x is None; small-integer and string caching is a CPython detail you must not rely on.
Question 4 · 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 5 · easy
Why can the tuple (1, 2) be used as a dictionary key in Python 3.12 while the list [1, 2] cannot?
A dictionary locates a key by its hash, so that hash must never change while the key is stored. Lists are mutable, so list.__hash__ is None and {[1, 2]: 'x'} raises TypeError: unhashable type: 'list'. A tuple hashes its elements, so it works as a key only if everything inside it is hashable: ([1], 2) is not.
Default values are evaluated once, when the def statement runs, so every call that omits tags appends to the same shared list and it keeps growing. tags=list() is evaluated once too, and returning a copy still leaves the shared default accumulating. The None sentinel builds a fresh list per call while still letting a caller pass their own.
Each call to make_counter creates a new count variable and a new inc closure over it, so c1 and c2 keep separate state. nonlocal count tells Python that count += 1 rebinds the enclosing function's variable instead of creating a new local one. c1 is on its third call and c2 on its first.
Question 8 · medium
Calling add(5) in this Python 3.12 program raises UnboundLocalError. What is the cause, and what is the cleanest fix?
total = 0
def add(n):
total += n
return total
add(5)
Scope is decided when the function is compiled: any assignment to a name inside a function makes that name local everywhere in the function, so the read happens before the local has a value. global total makes it work but ties the function to module state, while returning a value is easier to test. nonlocal only refers to an enclosing function's variables, so at module level it is a SyntaxError.
Question 9 · hard
The author expected this Python 3.12 program to print [0, 10, 20], but it prints [20, 20, 20]. What is the cause, and what is a correct fix?
funcs = []
for i in range(3):
funcs.append(lambda: i * 10)
print([f() for f in funcs])
Closures capture variables, not values: all three lambdas refer to the same i and read it only when called, after the loop has finished with i == 2. A default argument is evaluated when the lambda is created, so it freezes each iteration's value; functools.partial or a small factory function works too. A def inside the loop has exactly the same late-binding behaviour as the lambda.
Question 10 · 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 11 · 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 12 · 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 13 · 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 14 · 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 15 · 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 16 · 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 17 · 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 18 · 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 19 · easy
What does this Python 3.12 program print?
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE customers(id INTEGER, name TEXT);
CREATE TABLE orders(id INTEGER, customer_id INTEGER);
INSERT INTO customers VALUES (1, 'asha'), (2, 'ravi'), (3, 'meena');
INSERT INTO orders VALUES (10, 1), (11, 1), (12, 2), (13, 9);
""")
inner = "SELECT COUNT(*) FROM customers c JOIN orders o ON o.customer_id = c.id"
left = "SELECT COUNT(*) FROM customers c LEFT JOIN orders o ON o.customer_id = c.id"
print(con.execute(inner).fetchone()[0], con.execute(left).fetchone()[0])
The inner join keeps only matching pairs: asha's two orders and ravi's one give 3 rows, and order 13 points at no customer, so it is dropped. The LEFT JOIN keeps every customer, so meena appears once more with NULL order columns, giving 4. A left join never adds rows for unmatched rows of the right-hand table.
Question 20 · medium
Table orders has columns (id, customer_id) with rows (10, 1), (11, 1) and (12, 2). Table addresses has columns (customer_id, city) with rows (1, 'Puri'), (1, 'Cuttack') and (3, 'Rourkela').
SELECT o.id, a.city
FROM orders o
JOIN addresses a ON a.customer_id = o.customer_id;
How many rows does the query return?
A join pairs every matching left row with every matching right row. Customer 1 has two orders and two addresses, so it produces 2 x 2 = 4 rows, while customers 2 and 3 have no partner on the other side. This fan-out is why joining two one-to-many tables on the same key inflates counts and sums.
Question 21 · easy
What does this Python 3.12 program print?
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE emp(id INTEGER, name TEXT, salary INTEGER, manager_id INTEGER);
INSERT INTO emp VALUES (1, 'anil', 90, NULL), (2, 'bina', 95, 1),
(3, 'chetan', 60, 1), (4, 'divya', 70, 3), (5, 'esha', 50, 3);
""")
sql = """SELECT e.name, m.name FROM emp e
JOIN emp m ON e.manager_id = m.id
WHERE e.salary > m.salary ORDER BY e.name"""
print(con.execute(sql).fetchall())
A self join gives the same table two aliases: e is the employee and m is that employee's manager, matched on e.manager_id = m.id. bina (95) earns more than anil (90) and divya (70) more than chetan (60), while chetan and esha earn less than their managers. anil has no manager, so the inner join drops him.
Question 22 · medium
The report must list every department with its number of active employees, showing 0 where there are none. The Support department, whose employees are all inactive, is missing from the result.
SELECT d.name, COUNT(e.id) AS active_staff
FROM departments d
LEFT JOIN employees e ON e.dept_id = d.id
WHERE e.active = 1
GROUP BY d.name;
Why is Support missing?
WHERE runs after the join, so Support's joined rows (inactive employees, or NULL-padded rows for a department with no staff) all fail e.active = 1 and vanish before grouping. Writing LEFT JOIN employees e ON e.dept_id = d.id AND e.active = 1 filters which employees match while still keeping every department. COUNT(e.id) then reports 0 for departments with no active match.
Question 23 · hard
What does this Python 3.12 program print?
import sqlite3
con = sqlite3.connect(":memory:")
con.executescript("""
CREATE TABLE staff(name TEXT, dept_code TEXT);
CREATE TABLE depts(code TEXT, title TEXT);
INSERT INTO staff VALUES ('asha', 'HR'), ('ravi', NULL), ('meena', 'IT');
INSERT INTO depts VALUES ('HR', 'People'), (NULL, 'Unassigned');
""")
sql = """SELECT s.name, d.title FROM staff s
LEFT JOIN depts d ON d.code = s.dept_code ORDER BY s.name"""
print(con.execute(sql).fetchall())
In SQL NULL = NULL is unknown, not true, so ravi's NULL dept_code never matches the NULL code row and the 'Unassigned' department is never joined. The LEFT JOIN still keeps ravi and meena with a NULL title. To treat missing codes specially, use COALESCE(d.title, 'Unassigned') in the select list instead of a NULL key row.
Question 24 · medium
This query should list the departments whose average salary is above 50000, but the database rejects it (SQLite says misuse of aggregate: AVG()).
SELECT dept, AVG(salary) AS avg_salary
FROM employees
WHERE AVG(salary) > 50000
GROUP BY dept;
What is the correct fix?
WHERE filters individual rows before any groups exist, so an aggregate cannot appear there, and an alias that stands for the aggregate does not help. HAVING runs after GROUP BY and filters whole groups by their aggregates. Adding salary to GROUP BY would make a group per salary value and change the meaning of the average.
Question 25 · easy
In a REST API, which HTTP method is not idempotent by its definition in the HTTP standard (RFC 9110)?
A method is idempotent when sending the same request several times leaves the server in the same state as sending it once. GET, PUT and DELETE are idempotent: putting the same body twice or deleting an already deleted resource changes nothing more (the second DELETE may return 404, but the state is the same). POST is not, so two identical POST /orders calls can create two orders, which is why clients must not retry it blindly.
Question 26 · easy
A client sends POST /orders and the server creates order 981. What is the best response?
201 Created says a new resource now exists, and the Location header gives its URL so the client can fetch or link to it. 204 No Content drops the body, so the client never learns the server-assigned id. 202 Accepted means the work was only queued and is not done yet, which would mislead the client here.
Question 27 · medium
A student logs in and receives a valid token. With that token she calls GET /admin/reports, which only admins may see. Which status code should the API return?
401 means the request lacks valid credentials (missing, expired or wrong token) and the client should authenticate. Here the server knows exactly who she is but she lacks the permission, which is 403: logging in again will not help. Some APIs answer 404 on purpose to hide that a resource exists, but that is a privacy choice, and 400 is for a malformed request.
Question 28 · medium
What does this Python 3.12 program print?
IDEMPOTENT = {"GET", "PUT", "DELETE", "HEAD", "OPTIONS"}
def can_retry(method, status):
if status == 429 or status >= 500:
return method in IDEMPOTENT
return False
calls = [("GET", 503), ("POST", 503), ("PUT", 429),
("DELETE", 404), ("GET", 400)]
print([m for m, s in calls if can_retry(m, s)])
A retry only helps when the failure can be temporary: a 5xx server error, or 429 after waiting. It is only safe to do automatically for idempotent methods, so the POST that got 503 is skipped, since the first attempt may already have created the order. 404 and 400 are client errors, and the same request would fail again.
Question 29 · medium
The orders table has a composite index on (customer_id, created_at). Which query can not use this index efficiently to find its rows?
A composite index is sorted by its first column and then by the second within each first-column value, like a phone book sorted by surname, then first name. Queries that filter on the leftmost column, alone or together with the next one, seek straight to their rows and even get created_at order for free. A filter on created_at alone skips the leading column, so the database has to scan instead; put the equality-filtered column first.
Question 30 · hard
Transaction T1 reads an account balance of 1000. Transaction T2 then updates it to 800 and commits. T1, still open, reads the same row again and gets 800. What is this anomaly, and what is the lowest standard SQL isolation level that prevents it?
A dirty read is seeing another transaction's uncommitted change, but T2 had committed, so this is not one. Reading the same row twice in one transaction and getting two different committed values is a non-repeatable read: READ COMMITTED allows it and REPEATABLE READ forbids it. A phantom is about new rows appearing when a range query is repeated, not about a changed row.
Your answers and your score stay in this browser tab. Nothing is sent or saved.