Skip to content
Tech Interview Prep

Top 100 Software Engineer Practice MCQs

Every question on one page: open one, choose an answer, and see why at once. Signed in, your latest answer to each question counts, and you can answer again after 24 hours.

Curated: · Written: · Reviewed:

Reviewed 100Review pending 0

Answers to reviewed questions count toward this role and the overall leaderboard; your latest answer to each one is the one that counts.

100 questions

MCQ-1A Java 17 service uses a client-supplied header as the key in a `HashMap<String, Session>`. An attacker sends 500,000 requests whose header values all hash to the same bucket, so that one bin holds 500,000 entries. What is the cost of a `get` that lands in that bin?
MCQ-2An interviewer is shown this two-sum submission: ```python def two_sum(nums, target): seen = {} for i, x in enumerate(nums): seen[x] = i for i, x in enumerate(nums): need = target - x if need in seen: return [i, seen[need]] return [] ``` The interviewer says the two-pass version can hand back an element as the complement of itself. Each call below passes an array whose values are all different. On which one does it return a pair whose two entries are the same index?
MCQ-3Two pointers is run on the sorted array nums = [-7, -3, 1, 4, 6, 9] with target = 5. The loop starts at L=0 and R=5, increments L when nums[L] + nums[R] < target, decrements R when the sum > target, and stops when the sum equals target or L >= R. Which statement describes this run?
MCQ-4A log-analysis job must return the longest substring with at most 2 distinct characters from each 4×10^5-character line. The nested start/end scan took 14 minutes per file; the team needs under 2 seconds, so they ship a window that keeps a count map and a distinct counter, advancing R every step and moving L only while distinct > 2. On the line "abacbc", what does the window return, and what is the longest valid substring?
MCQ-5A metrics service builds `prefix` once at startup and answers inclusive range sums with `prefix[j+1] - prefix[i]`. A late-correction job then runs `nums[k] += delta` for each corrected event but never touches `prefix`. ```python nums = [3, 1, 4, 1, 5] prefix = [0, 3, 4, 8, 9, 14] # built once, at startup nums[2] += 6 # late correction; nums is now [3, 1, 10, 1, 5] def range_sum(i, j): # inclusive return prefix[j + 1] - prefix[i] ``` The dashboard calls `range_sum(1, 3)`. What value does it display?
MCQ-8A log-processing worker walks a singly linked list of nine records. A bug makes record 9's next pointer point back to record 4, so the chain reads 1→2→3→4→5→6→7→8→9→4→5→… A reviewer runs the standard two-pointer check: slow and fast both start at record 1, slow advances one record per iteration, fast advances two, and the loop stops at the first iteration where they land on the same record, then walks one pointer from record 1 and one from that meeting record, one step each, until they land on the same record. Which pair does the run produce: the record where the pointers first meet, and the record where the cycle actually begins?
MCQ-9A log service reverses a singly linked list of events before emitting them. After a refactor, a four-event batch 1→2→3→4→None is emitted as 3→2→1→None and the fourth event never appears. The current code is: ```python def reverse(head): prev = None curr = head while curr.next: nxt = curr.next curr.next = prev prev = curr curr = nxt return prev ``` Which diagnosis and fix is correct?
MCQ-6A service computes for each index the next strictly greater value to the right, or -1 if none exists. The implementation uses `while stack and nums[stack[-1]] <= x: ans[stack.pop()] = x`. For which input does this produce an output that differs from the correct strict-greater output?
MCQ-7An overnight batch drainer is configured with piles = [30, 11, 23, 4, 20] and a hard limit of H = 6 hours. It drains at an integer rate k items per hour, finishing a pile in ceil(p/k) hours, and can start the next pile only on the next hour boundary. A junior engineer runs this Python 3 code: lo = 1 hi = max(piles) while lo < hi: mid = (lo + hi) // 2 if sum((p + mid - 1) // mid for p in piles) <= H: hi = mid else: lo = mid + 1 return lo The code is believed correct. What value does it return for these inputs?
MCQ-10A service-mesh tool answers minimum-hop queries over a directed, unweighted dependency graph. Its adjacency lists, in the order the code walks them, are: S: A, B A: X X: Y Y: Z Z: T B: T min_hops(src, dst) is a recursive DFS that marks a node visited when it enters it, walks that node's neighbours in adjacency-list order, and returns as soon as it enters dst. Its contract is to return the minimum hop count between the two services. min_hops(S, T) returns 5. Which statement is correct?
MCQ-14A robot navigates a 4×4 grid of unit-cost cells, rows and columns numbered 0–3. It starts at (0,0) and must reach (0,3). Cells (0,1), (1,1) and (2,1) are blocked; every other cell is open. The planner uses BFS with a FIFO queue, marking a cell visited when it is first enqueued, and returns the distance of the target when it is dequeued. What distance does the planner return?
MCQ-11An in-memory ordered index is a binary tree, and lookups use the standard rule: at each node, go left if target < node.val, otherwise go right. The tree holds these values: ``` 20 / \ 10 30 / \ 5 25 ``` A lookup for 25 returns 'not found', even though a node with value 25 is present. Which diagnosis is correct?
MCQ-13A metrics service reports the 3rd-largest request latency seen so far. It must handle 10^7 events within a few hundred bytes of tracker state, so it keeps a min-heap capped at k=3: ```python import heapq def kth_largest(stream, k): h = [] for x in stream: if len(h) <= k: heapq.heappush(h, x) elif x > h[0]: heapq.heapreplace(h, x) return h[0] ``` A canary replays the stream [9, 4, 7, 1, 8, 6, 3, 5]. What does kth_largest(stream, 3) return?
MCQ-12An autocomplete service answers from an in-memory trie of 250,000 words: each node holds a character-to-child map plus an is_word flag, and children are stored in descending word-frequency order so the first completions reached are the ones to show. The handler walks the entire subtree under the typed prefix, collects every completion, then returns the first 8. Instrumentation on the staging corpus shows the prefix "co" visiting 41,300 nodes and building 9,600 completion strings to produce those 8 suggestions, with p50 of 4 ms and p99 of 180 ms; 2-4 character prefixes make up most of the traffic. The p99 budget is 50 ms, the host runs at 0.3 load on 8 cores, the trie occupies 38 MB of an 8 GB heap, and 9% of requests name a prefix the process already served in the last minute. Which change meets the budget?
MCQ-17Seven tasks A through G are scheduled by Kahn's algorithm: the queue is seeded by scanning the task list in alphabetical order, and each pop emits its task. The dependency edges are A->B, B->C, C->D, D->B, D->G and E->F. The run prints the tasks it placed, in order, then the tasks it could not place. What does it print?
MCQ-16A union-find over 10^6 nodes (IDs 0–999999) uses path compression in `find` and union-by-rank in `union`. The rank array is initialized to 0 but never incremented, so every union sees equal ranks and executes `parent[find(a)] = find(b)`. The input is the chain of unions (0,1), (1,2), (2,3), …, (999998, 999999), in that order. How many edges lie on the path from node 0 to its root after all unions complete?
MCQ-15A delivery router stores a road network as a directed graph where each edge weight is the average travel time in minutes. From depot S to terminal T the only routes are S→A→T (edges 10 and 10), S→B→C→T (edges 2, 1 and 1), and S→D→E→F→T (edges 1, 1, 1 and 2). The team runs BFS from S and Dijkstra from S, each stopping as soon as T is dequeued. Which pair of routes do the two searches return?
MCQ-25A service appends 2^20 records per batch to a hand-rolled dynamic array that starts at capacity 1 and, when full, allocates 2× the capacity and copies every existing record before inserting. A teammate proposes changing the growth to a fixed +1024 slots per resize, arguing it will cut the worst-case pause at the largest resize. What does that change do to the total number of record copies for one batch?
MCQ-26A batch job drains a worklist and writes results, and items must be processed in the order they were loaded: ```python work = load_items() # 100_000 items results = [] while work: item = work.pop(0) results.append(transform(item)) ``` `transform` is O(1) and does no I/O. The run takes 4.8 s; the same code on 50,000 items takes 1.2 s. Which change removes the superlinear growth?
MCQ-19A service computes `ways(n)`, the number of distinct sequences of 1- and 2-step moves that climb exactly n stairs, for n up to 10^6. The implementation (Python 3) is: ```python def ways(n): if n <= 1: return 1 a, b = 1, 1 for i in range(2, n): a, b = b, a + b return b ``` A test asserts `ways(6) == 13` and fails. Which statement about the failure is correct?
MCQ-20A 2D DP counts paths on a 3×4 grid (rows 0–2, cols 0–3) with obstacles at (0,2) and (1,1). It sets dp[0][0]=1, fills the first row and column with 1 until an obstacle is hit (after which the rest of that row or column is 0), and for every other cell uses dp[r][c] = 0 if blocked else dp[r-1][c] + dp[r][c-1]. What is dp[2][3]?
MCQ-21A parking-meter firmware makes change for every amount from 0 to 10000 using denominations [1, 5, 12]. Its loop takes the largest denomination that fits, subtracts it, and repeats until the amount reaches zero. A log for the amount 15 shows the coins 12, 1, 1, 1. The team's spec says the loop always returns the fewest possible coins. Which reading of that log is correct?
MCQ-22A scheduling service merges a user's busy blocks before listing free slots. The blocks arrive in this order: [4,7], [1,9], [2,3], [10,12], [12,14]. Two blocks are treated as overlapping when they share any point, including a single endpoint, so [10,12] and [12,14] are one merged block rather than two. The service returns merged blocks in ascending order of start. Which list does it return?
MCQ-23A Java 17 service packs a user's 64 feature flags into a `long bits`. `set(int f)` runs `bits |= 1 << f` for f in 0..63, and `count()` returns `Long.bitCount(bits)`. A test enables features 0 through 63 and asserts `count() == 64`; it fails with 32. Which statement identifies the cause and the fix?
MCQ-24A thumbnail service reduces width/height ratios with: ```python def norm(a, b): while a != b: if a > b: a -= b else: b -= a return a ``` Normal traffic costs 0.2 ms of CPU inside norm(). Since a partner started sending banners with aspect ratios past 30000:1, with the larger side up to 1000000000, that cohort measures 4.0 s of CPU inside a single norm() call and requests are being killed at the 5 s deadline. Every affected call has a/b > 30000; calls whose two operands are within 2x of each other still return in well under a millisecond. Which statement names the cost and the smallest change that removes it?
MCQ-18A backtracking N-queens solver places one queen per row: it marks the chosen column, recurses to the next row, and unmarks that column on return. A refactor deleted both diagonal checks, so a placement is now rejected only when its column is already marked. Columns are tried 0 to n-1 left to right at every row, so each completed column vector is produced exactly once. Before the diagonal checks are restored, what does the solver's solution counter report for n = 4?
MCQ-27A nightly job walks a tree with a recursive function. On CPython 3.12 (default recursion limit 1000) it completes on a 200,000-node tree whose deepest root-to-leaf path is 60, but raises RecursionError on a 1,500-node linked list. A teammate concludes the function is 'safe for trees, broken for lists.' Which explanation accounts for both results?
MCQ-28A Python 3.12 service on 64-bit CPython keeps `a`, a module-level list of 9,000,000 event codes, 8,000,000 of them non-zero. Every code is above 256, so each is a distinct 28-byte PyLong, and the list's slot array costs 8 bytes per element. A background thread runs `for x in a:` over that list; it is pre-existing code that cannot be changed and takes no lock. A compaction pass must hand the non-zero codes, in their original relative order, to an exporter. The worker runs under a 512 MiB cgroup limit and sits at 340 MiB RSS when the pass starts. Which implementation gets the export out without the reader thread observing a corrupted list?
MCQ-29A Go 1.22 service builds a nightly export. Orders come back from the database into a slice that is already in arrival order, the order the customer site accepted them, 250,000 rows, about 200 per region: type Order struct { Region string; Amount int } orders []Order The export must write rows grouped by region, and inside a region in arrival order. The only ordering step is: sort.Slice(orders, func(i, j int) bool { return orders[i].Region < orders[j].Region }) Last night's file has every region in the right place, but diffing it against the input slice shows 49% of rows sitting in a different position inside their own region. Which change fixes the export?
MCQ-30An overnight de-dupe job builds a `set` of `User` objects and writes it back. The source has 250,000 rows, 31,000 of which repeat an email, yet the output still has 250,000 rows; a second pass that checks `if u in seen` before inserting reports False for users it inserted earlier in the same run. The class is: ```python class User: def __init__(self, uid, email): self.uid = uid self.email = email def __eq__(self, other): return self.email == other.email def __hash__(self): return hash(self.uid) ``` A three-row repro of the same class: ```python a = User(1, "sam@x.com") b = User(2, "sam@x.com") seen = {a, b} print(len(seen), User(3, "sam@x.com") in seen) ``` What does the repro print?
MCQ-31A service stores a connected directed graph with n = 100,000 vertices and m = 300,000 weighted edges as a dense adjacency matrix with one byte per cell, and the container is OOM-killed at its 512 MB limit. The workload is 5,000 full BFS/DFS traversals from random sources, and there are no edge-existence queries. Which replacement should the team make?
MCQ-33A service runs a correct LRU cache with capacity 3, keyed by user ID. Recency is refreshed on every read and every write, and a new key arriving at capacity evicts the least recently used entry. The request log for one window is: 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5. How many of the 12 requests are cache hits?
MCQ-32An exchange gateway keeps its live order book in a binary min-heap keyed by (price, sequence), backed by a pre-allocated 24 MB array of 1,000,000 entries that is full at peak, plus a HashMap from orderId to the Order object. get-min is a read of index 0 and is called 500,000 times per second; it measures 40 ns against a 100 ns budget. Cancel-by-id scans the backing array for the order and then repairs the hole with a sift: the scan measures 0.6 ms on average and 1.2 ms worst case, 20,000 cancels per second burn 12 core-seconds every second, and cancel p99 is 190 ms. A prototype balanced BST keyed by (price, sequence) with an id-to-node map measured 260 ns per get-min and 96 MB. A cancel must take effect before the order can be matched, and it must free its array slot immediately. Which change fixes the cancel path?
MCQ-34A log-scanning service searches for a 1,000-character signature, 999 'a' characters followed by one 'b', in 2 MB (2×10^6-character) log lines that are entirely 'a' characters. The naive search performs roughly 2×10^9 character comparisons and the request times out. Which statement about this run is correct?
MCQ-35A service returns every unique triple of array values that sums to zero. The implementation sorts the array and then, for each fixed index i, runs a two-pointer scan over the suffix: ```python nums.sort() res = [] for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i-1]: continue L, R = i + 1, len(nums) - 1 while L < R: s = nums[i] + nums[L] + nums[R] if s == 0: res.append([nums[i], nums[L], nums[R]]) L += 1 R -= 1 elif s < 0: L += 1 else: R -= 1 ``` On `[-2, 0, 0, 2, 2]` it returns `[[-2,0,2],[-2,0,2]]`, but the contract requires each triple exactly once. Which change makes the output correct?
MCQ-36A build system holds a static dependency tree of 200,000 packages. Each CI run issues 10,000 lowest-common-ancestor queries against the same unchanged tree, and the LCA stage must finish in under 5 seconds. The current implementation walks both nodes up to the root, comparing ancestor sets, and takes about 14 minutes per run. Which change meets the budget?
MCQ-37A PR adds a cache codec for expression trees. `serialize` writes preorder values only, comma-joined, with no markers for absent children; `deserialize` reads the values back and rebuilds a complete tree, filling level by level left to right. The PR's test suite passes on a corpus of 40,000 trees because it compares the sorted value list, not the shape. Reviewing the diff, you trace the round trip for the tree `1` with left child `2`, right child `3`, and `3` with left child `4`. Which review comment is correct?
MCQ-38A build service validates a directed dependency graph before scheduling. Its checker runs DFS from each unvisited node, marks a node visited on entry, and returns CYCLE as soon as it reaches any node already marked visited. On a valid diamond DAG A→B, A→C, B→D, C→D it reports CYCLE when the second path reaches D. In production it rejects 3% of valid graphs; a package installer blocked for 8 minutes on such a false positive. Which change fixes the false positives without missing real cycles?
MCQ-39An engineering team needs a 0/1 solver: every item (weight, value) may be taken at most once. The implementation under review, in Python 3, is: items = [(10, 60), (20, 100), (30, 120)] W = 50 dp = [0] * (W + 1) for wt, val in items: for w in range(wt, W + 1): dp[w] = max(dp[w], dp[w - wt] + val) print(dp[W]) It runs without error on that fixture. What value does it print, and why?
MCQ-40A binary search over a sorted array of int indices computes `mid = (lo + hi) / 2`. With `lo = 2_000_000_000` and `hi = 2_000_000_002` the sum overflows int32, `mid` comes out negative, and the loop never terminates. The index type is fixed at 32-bit signed int and the platform has no wider integer type; the fix must return the same midpoint as `(lo + hi) / 2` for every in-range `lo` and `hi`. Which change does that?
MCQ-41A partner's invoice file and the internal ledger are compared each night by this Python 3 helper: ```python def reconcile(expected, booked): missing = list(set(expected) - set(booked)) extra = list(set(booked) - set(expected)) return missing, extra ``` Finance hand-audited one night and found line 1041 short-paid once and line 2077 paid twice. The two lists the helper received that night were (ids are illustrative): expected = [1041, 1041, 2077] booked = [1041, 2077, 2077] What did reconcile return for those two lists?
MCQ-42A Python 3.12 service stores sessions in a dict. At 14:00 the dict holds 250,000 live sessions; 1,842 of them have expired == True. The sweeper runs every 30 seconds: ```python for sid in sessions: if sessions[sid].expired: del sessions[sid] ``` The first sweep after 14:00 begins. The keys are in insertion order, and the first expired session is reached after 180,000 live sessions. What happens in that sweep?
MCQ-43A nightly job in a Java service sorts 800,000 `Record` objects with `records.sort((a, b) -> a.score - b.score)`, where `score` is an `int` drawn from [-1_500_000_000, 1_500_000_000]. The job fails with `java.lang.IllegalArgumentException: Comparison method violates its general contract!` thrown from `Arrays.sort` on most nights; on the nights it completes, a downstream diff finds a few records out of order. A unit test that sorts 20 records passes on every run. Which diagnosis explains both the failure and the passing test?
MCQ-44A code review traces this lower-bound search before merge. It returns the first index i where arr[i] >= target. ```python lo, hi = 0, len(arr) - 1 while lo <= hi: mid = (lo + hi) // 2 if arr[mid] >= target: hi = mid else: lo = mid + 1 return lo ``` For arr = [2, 4, 4, 4, 7, 9] and target = 4, what is the outcome of the call?
MCQ-45A team replaced recursive inorder with Morris traversal to avoid stack overflow on a 1.5×10^6-node skewed tree. Their loop is: ```python cur = root while cur is not None: if cur.left is None: visit(cur) cur = cur.right else: pred = cur.left while pred.right is not None and pred.right is not cur: pred = pred.right if pred.right is None: pred.right = cur cur = cur.left else: visit(cur) cur = cur.right ``` On the tree ``` 3 / \ 1 5 \ 2 ``` the traversal prints 1 2 3 5 and passes the inorder test. A standard BST search (left if target < node, right if target > node) is then run on the same tree. Which search never terminates?
MCQ-46A service loads a sparse graph with n = 40,000 nodes and m = 50,000 edges at startup using g = [[0] * n for _ in range(n)], running CPython 3.12 in a 2 GB container. It is OOM-killed before serving any request. Which diagnosis explains the kill?
MCQ-47A grid pathfinder returns the minimum cost to cross a 40×40 grid, where the solver may remove at most k walls. It memoizes every state it computes. On a test grid with k=2 it returns 12; a brute-force search confirms the true minimum is 19. Instrumentation shows the memo holds exactly 1,600 entries, and the same value 12 comes back for k=0, k=1 and k=2. Which explanation fits these numbers?
MCQ-48A nightly pricing job solves 0/1 knapsack: 1,000 items with arbitrary integer weights up to 200,000, capacity W = 200,000, item values up to 10^6, each item usable at most once, and the exact optimum is required, since a value even one unit too high fails reconciliation downstream. It builds dp as a Python list of n+1 rows of W+1 ints, and the 512 MB container kills it while the table is still being allocated. The O(n * W) work, about 2e8 cells, is accepted. Which change lets it finish with the same optimum?
MCQ-49A nightly job sorts two datasets of 50 million records each, both already resident in memory on a 32 GB node, and the team wants the fewest elementary operations per sort. Dataset A is keyed by a 10-bit status code (values 0 through 1023, heavily duplicated). Dataset B is keyed by a unique random 64-bit request id. Both datasets must come out ordered by their key, and counting sort and Timsort are the two candidates. Which plan is correct?
MCQ-50A service keeps a uniform sample of k=2 events from a stream of unknown length. It fills the first two slots, then for each 0-indexed position i ≥ 2 draws j = random.randrange(i) and, if j < 2, sets res[j] = a[i]. A reviewer runs it on a stream of exactly four events and finds the event at position 2 (the third event) in the output far more often than the event at position 0. What is the probability that the event at position 2 is in the final sample?
MCQ-51A finance reconciliation query runs on PostgreSQL 16: ```sql SELECT c.region, COUNT(*) AS orders FROM orders o LEFT JOIN customers c ON c.id = o.customer_id WHERE c.region <> 'EU' GROUP BY c.region; ``` orders holds 250,000 rows; 6,000 of them reference customer_ids that were deleted from customers. Of the 244,000 orders with a live customer, 90,000 are EU. The report totals 154,000, but the ledger expects 160,000 non-EU orders. Which option correctly explains the 6,000-row gap and makes the report return 160,000?
MCQ-52orders in PostgreSQL 16 holds 2,100,000 rows across 48,000 distinct user_id values, and its created_at timestamps are nearly all unique, so almost every (user_id, created_at) pair in the table exists only once. A nightly export must write exactly one row per user, carrying that user's most recent created_at, and the loader that consumes the file rejects any file above 100,000 rows. The job currently runs SELECT DISTINCT user_id, created_at FROM orders; it writes 2,100,000 rows in 92 s and the loader rejects the file. Which change gets the loader a file it accepts?
MCQ-53A `users` table holds 2,000,000 rows with a primary key index on `id`. `GET /users?page=50000&size=20` runs `SELECT * FROM users ORDER BY id OFFSET 999980 LIMIT 20` and its p99 is 380 ms. A pull request replaces it with `SELECT * FROM (SELECT u.*, ROW_NUMBER() OVER (ORDER BY id) rn FROM users u) t WHERE rn BETWEEN 999981 AND 1000000`; `EXPLAIN ANALYZE` on the new query shows an Index Scan on the primary key reading 2,000,000 rows, a WindowAgg, and 20 rows returned. What should the review conclude?
MCQ-54An `orders` table has 61M rows and takes about 4M UPDATEs a day, since every order changes status several times. This query returns 1,240 rows and runs at 44.9 ms p95: ```sql SELECT customer_id, total_cents FROM orders WHERE org_id = 812 AND created_at >= now() - interval '7 days'; ``` The covering index is `CREATE INDEX orders_org_created_idx ON orders (org_id, created_at) INCLUDE (customer_id, total_cents)`, and EXPLAIN (ANALYZE, BUFFERS) reports: ``` Index Only Scan using orders_org_created_idx on orders Index Cond: ((org_id = 812) AND (created_at >= (now() - '7 days'::interval))) Heap Fetches: 1231 Buffers: shared hit=1290 Execution Time: 44.9 ms ``` The same query with `org_id = 11`, a tenant whose orders were last written two years ago, reports `Heap Fetches: 0` and 3.2 ms on the same index. Autovacuum is at its defaults, and `pg_stat_user_tables` shows orders last autovacuumed 9 hours ago. The database serves read-write traffic with no maintenance window. Which action should the team take first?
MCQ-55PostgreSQL 16 with default cost settings (seq_page_cost = 1.0, random_page_cost = 4.0) holds a 4,000,000-row events table in 100,000 heap pages of 8 kB. Column status has three values: 'ok' with 3,600,000 rows, 'warn' with 380,000, and 'fail' with 20,000. idx_events_status is a b-tree on (status), pg_stats.correlation for status is near 0, and ANALYZE has just run. The application runs SELECT id, payload FROM events WHERE status = $1, once with 'ok' and once with 'fail'. Which pair of plans will EXPLAIN show?
MCQ-57A `users` table on PostgreSQL 14 is `CREATE TABLE users (id bigint PRIMARY KEY, email text UNIQUE);`. SSO signups insert a NULL email, and 1,104 rows (3% of the table) now hold NULL: the constraint accepted every one. Before a later `SET NOT NULL` migration, the team wants the table to hold at most one NULL email. Which statement achieves that on this server?
MCQ-58PostgreSQL 15. Table on_call(doctor_id int primary key, on_duty boolean); the invariant is at least one doctor on duty. Two sessions run this interleaving, both at REPEATABLE READ: T1: SELECT count(*) FROM on_call WHERE on_duty; -- 2 T2: SELECT count(*) FROM on_call WHERE on_duty; -- 2 T1: UPDATE on_call SET on_duty = false WHERE doctor_id = 1; COMMIT; T2: UPDATE on_call SET on_duty = false WHERE doctor_id = 2; COMMIT; Both commit, and count(*) WHERE on_duty is now 0. Which change makes the invariant hold under this same interleaving?
MCQ-59Three sessions run concurrently against `wallets` (id is the primary key). Each statement takes about 2 ms and holds its row lock until COMMIT; `deadlock_timeout` is at its 1 s default. All three issue their first UPDATE at t=0. ``` T1: BEGIN; UPDATE wallets SET balance = balance - 10 WHERE id = 5; UPDATE wallets SET balance = balance + 10 WHERE id = 2; COMMIT; T2: BEGIN; UPDATE wallets SET balance = balance - 10 WHERE id = 2; UPDATE wallets SET balance = balance + 10 WHERE id = 9; COMMIT; T3: BEGIN; UPDATE wallets SET balance = balance - 10 WHERE id = 9; UPDATE wallets SET balance = balance + 10 WHERE id = 5; COMMIT; ``` What does PostgreSQL do?
MCQ-60A dashboard reports unique users per day from an events table that takes 2×10^8 rows per day, with ~4.8×10^7 distinct user_id values in a day. The exact query `SELECT COUNT(DISTINCT user_id) FROM events WHERE day = current_date` takes 14 minutes, spills 2.4 GB of work_mem to disk, and holds a replica long enough to block other readers. The dashboard must refresh every 5 minutes, and the product owner accepts up to 2% error. Which approach meets the refresh budget?
MCQ-61A nightly job counts users with no orders: `SELECT count(*) FROM users u WHERE u.id NOT IN (SELECT user_id FROM orders)`. `users` holds 50,000 rows; `orders` holds 2,000,000 rows, 300 of which are guest checkouts with `user_id IS NULL`. The job reports 0, while the analytics team expects 12,431. Which conclusion should the review accept?
MCQ-62PostgreSQL 16. A team is tightening a schema before a GDPR deletion job goes live: ```sql CREATE TABLE customers (id bigint PRIMARY KEY); CREATE TABLE orders ( id bigint PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customers(id) ON DELETE SET NULL ); CREATE TABLE session_tokens ( id bigint PRIMARY KEY, customer_id bigint REFERENCES customers(id) ON DELETE CASCADE ); ``` Customer 42 has 1,200 orders and 3 session tokens. The job runs `DELETE FROM customers WHERE id = 42;` as a single statement. What happens?
MCQ-63Postgres 16. A jobs table holds 30,000,000 rows: 300,000 with state = 'queued', 400,000 with state = 'running', the rest terminal. Apart from the primary key, its only index is CREATE INDEX jobs_queued_run_at_idx ON jobs (run_at) WHERE state = 'queued', measured at 11 MB. The dispatcher poll SELECT id FROM jobs WHERE state = 'queued' ORDER BY run_at LIMIT 100 ran at 6 ms p99 on that index. The poll was changed to WHERE state IN ('queued','running') and now runs at 2.3 s p99; EXPLAIN (ANALYZE, BUFFERS) shows Seq Scan on jobs reading 30,000,000 rows, then a top-N heapsort, then Limit. Which diagnosis and next step fit these measurements?
MCQ-64Release 4.2 moved the hot `accounts.settings` keys out of relational columns into one `settings JSONB` column: 20M rows, 12 GB of heap, about 600 bytes per document. The support dashboard runs the prepared statement `SELECT id, email FROM accounts WHERE settings->>'theme' = $1`; its p95 went from 8 ms before the release to 12 s after it, and `EXPLAIN (ANALYZE)` on that statement shows a Seq Scan over all 20M rows. The value bound to `$1` matches about 4,000 accounts. Which change removes the sequential scan for this query?
MCQ-66A service issues about 40 queries that filter orders on country and status in different combinations. orders holds 12,000,000 rows; country has 200 distinct values with 'DE' at 5% of rows, and status has 4 values with 'pending' at 0.5%; 54,000 of the 60,000 pending rows are German. For WHERE country='DE' AND status='pending', EXPLAIN ANALYZE shows the orders node with rows=3000 estimated and rows=54000 actual, and the plan is a Nested Loop probing order_items once per outer row; p99 is 4.2 s, and the same statement with the plan forced to a hash join runs in 280 ms. pg_stat_user_tables.last_analyze for orders is 4 minutes old and pg_statistic_ext is empty. Which change lets the planner size the query correctly for the whole workload?
MCQ-67PostgreSQL 16 is running a payout worker at its default isolation level, read committed, as one transaction: at t=0 it runs SELECT balance FROM accounts WHERE id = 42 and gets 500, spends 250 ms on fraud checks with no database calls, then at t=250 ms runs UPDATE accounts SET balance = balance - 500 WHERE id = 42 AND balance >= 500. A second session ran UPDATE accounts SET balance = balance - 200 WHERE id = 42 at t=10 ms, holds that row's lock, and commits at t=400 ms; the payout worker's UPDATE is still waiting for the lock at that moment. What does the payout worker's UPDATE report, and what is id = 42's balance after both transactions finish?
MCQ-68A nightly batch builds a Python list of 100,000 events, oldest at index 0, one append per event, then drains it with `while q: event = q.pop(0)`. Every stage except the drain together measures 3 s; the drain measures 42 s. Events must be handled oldest-first. When an event fails it is re-queued and must be handled after every event already in the queue. The whole batch has a 10 s budget. Which change fits?
MCQ-69An order service deduplicates event IDs before writing a JSON payload, and the payload must list each ID in the order it was first seen. The helper is `list(set(ids))`. The test `assert dedupe(["e3", "e1", "e2"]) == ["e3", "e1", "e2"]` passes locally but fails on roughly one in eight CI shards, where it reports `["e1", "e3", "e2"]`. The service runs on CPython 3.11. Which change makes the test pass on every shard while keeping the required order?
MCQ-70A nightly job streams 12M JSON lines from an HTTP response (`resp.iter_lines()`), which cannot be replayed. It aggregates with: ```python def aggregate(lines): rows = (json.loads(l) for l in lines) total = sum(r["bytes"] for r in rows) n = sum(1 for r in rows) return total, n ``` `total` comes out right but `n` is 0; peak RSS is 180 MB and the run takes 41 s. Materializing the rows would hold about 1.9 GB. Which change makes both `total` and `n` correct while keeping peak RSS under 300 MB?
MCQ-71A nightly aggregation runs on a 4-core machine on CPython 3.12. It has 8 independent chunks, and each chunk is a pure-Python numeric loop that takes 6 s, doing no I/O and calling no C extension that releases the GIL. Version A submits all 8 chunks to ThreadPoolExecutor(max_workers=4); version B submits the same function to ProcessPoolExecutor(max_workers=2). Which pair of wall-clock times should the team expect?
MCQ-72A worker dedupes retried uploads in a module-level set, and its size has climbed for two weeks: `len(pending)` reports 41,300 while the tracker has seen 25,800 distinct job ids. One job reproduces it locally: ```python @dataclass(unsafe_hash=True) class Job: job_id: str attempts: int pending = set() j = Job("job-7", 1) pending.add(j) j.attempts += 1 print(j in pending) # False pending.add(j) print(len(pending)) # 2 ``` Which change stops the set from accumulating an entry per retry?
MCQ-73A payments service caches handler results in a module-level dict. After a refactor the two handlers below are stacked like this: ```python cache = {} def cache_by_name(fn): def wrapper(*args, **kwargs): key = (fn.__name__, args, tuple(kwargs.items())) if key not in cache: cache[key] = fn(*args, **kwargs) return cache[key] return wrapper def timed(fn): def wrapper(*args, **kwargs): t0 = time.perf_counter() try: return fn(*args, **kwargs) finally: metrics.observe(fn.__name__, time.perf_counter() - t0) return wrapper @cache_by_name @timed def get_user(user_id: int) -> dict: ... @cache_by_name @timed def get_order(order_id: int) -> dict: ... ``` GET /users/7 now returns the order payload for id 7, and the generated schema declares both handlers as (*args, **kwargs). Both symptoms reproduce on a single-process dev server. Which change clears both?
MCQ-74An order service wraps each database transaction in this context manager (Python 3.12): ```python class Tx: def __enter__(self): self.conn.begin() return self.conn def __exit__(self, exc_type, exc, tb): if exc_type is None: self.conn.commit() else: self.conn.rollback() return True ``` A duplicate order raises `IntegrityError` inside the block. The API returns HTTP 200 with a freshly generated order id, no row is written, and the caller's `except IntegrityError` never runs. A dropped connection last Tuesday failed the same way: 200 with stale data. What is the correct fix?
MCQ-75A Python 3.12 service assigns per-process sequence numbers with: ```python def next_seq(prefix, counter=[0]): counter[0] += 1 return f'{prefix}-{counter[0]}' ``` It calls `next_seq('a')`, then `next_seq('b')`, then `next_seq('a')`, and logs each return value. What does the log show?
MCQ-76A client classifies responses with identity checks against module constants: ```python OK, NOT_FOUND = 200, 404 code = int(resp.headers["status"]) if code is OK: return parse(resp) if code is NOT_FOUND: return None raise Unexpected(code) ``` Tests that send 200 pass; a 404 response raises `Unexpected(404)` instead of returning `None`. What explains the 404 miss?
MCQ-77A crawler fetches 2,000 URLs with aiohttp at concurrency 100 (each round trip about 50 ms) and parses every body with a pure-Python parser that costs 25 ms of CPU. All of it runs in one asyncio task loop on a 4-core box. The batch takes about 52 s, the loop's blocked-time p99 is 900 ms, and one core is pinned at 100% while the other three idle. Which change should the review accept?
MCQ-78`score.py` holds a 400 MB model in a module global: ```python MODEL = None def init(): global MODEL MODEL = load_model() # 400 MB, ~6 s def score(row_id): return MODEL.predict(row_id) ``` `run_job.py` imports it, calls `init()` in the parent, then inside `main()` under the `if __name__ == "__main__":` guard runs `ctx = multiprocessing.get_context("spawn")` and `ctx.Pool(8).map(score, ids)` over 2,000,000 ids. On the developer's Linux laptop, where the job runs with the fork context, it finishes in 38 s. In the container, where it runs with spawn, all 8 workers raise `TypeError: 'NoneType' object is not callable` on their first task. The container has 16 GB of RAM; the process that runs the job also serves gRPC on 32 threads, imports `score.py` for the row schema, and must stay under 200 MB RSS. Which change fixes the job?
MCQ-79A nightly job in Python 3.12 ingests a 1,200,000-row CSV (410 MB) inside a container limited to 512 MB. Each row is a dict with 12 keys, measured at about 600 bytes. The pipeline is: ```python rows = iter_csv(path) # generator yielding one dict per row validate(rows) # iterates rows, counts them, checks the schema load(rows) # iterates rows, prints one line per row, inserts ``` validate() runs to completion before load() is called. Last night validate() counted 1,200,000 rows, load() printed none of its per-row lines, 0 rows were inserted, and the job exited 0. What is the correct diagnosis and fix?
MCQ-80A worker wraps gateway failures: ```python try: gateway.charge(order_id) except ConnectionError as e: raise AppError("charge failed") from None ``` On-call sees only `AppError: charge failed` in the log. A test catches the AppError as `err`. Which set of attribute values does `err` have?
MCQ-81A nightly dedup job (Python 3) builds a key per event and adds it to a set: ```python seen = set() for e in events: key = (e["id"], e["tags"]) # e["tags"] is a list of strings if key in seen: continue seen.add(key) ``` It raises `TypeError: unhashable type: 'list'` on the first event whose `tags` is non-empty and processes 0 of the 50,000 events; events with `tags == []` pass. The job must treat `["a","b"]` and `["b","a"]` as different events. Which replacement for the `key = ...` line makes the job run and keeps that distinction?
MCQ-82A Go 1.22 service builds the grade report. Rows must come out with Grade ascending, and within one grade with Name ascending. The builder makes two passes: sort.SliceStable(rows, func(i, j int) bool { return rows[i].Name < rows[j].Name }) sort.Slice(rows, func(i, j int) bool { return rows[i].Grade < rows[j].Grade }) On the 400-row staging fixture, two rows that share grade 3 print as Zoe, Ann in 2 of 3 runs, where Ann should come first. Which change fixes the ordering?
MCQ-83A Python 3.12 pricing service keeps one parsed catalog dict in memory: a "lines" list of 40 line dicts plus nested metadata, about 2 MB, with prices held as Decimal. Every request reads that cached dict, sets qty on each line, and serialises the result. A 10-minute replay of production traffic produced 1,240 of 40,000 responses carrying the quantities set by the previous request. Rebuilding the catalog from the database costs 400 ms, end-to-end p99 must stay under 20 ms, a deepcopy of the cached structure measures 250 ms, a copy that duplicates only the top level and the 40 line dicts measures 3 ms, and the leak reproduces with a single worker process. Which change should the team ship?
MCQ-84CPython 3.12, 64-bit. A batch job builds 4,000,000 Trade objects and keeps every one alive until the end of the run. Base is a plain class, defined as class Base: pass, whose only base is object; Trade is class Trade(Base) with __slots__ = ('symbol', 'qty') and an __init__ that sets self.symbol and self.qty. Before the __slots__ line was added, the tracemalloc snapshot for the same input put the Trade.__init__ call site at the top of the list with 640 MB; after the change the same line reads 704 MB, and repeating the run reproduces both numbers. 640 MB / 4,000,000 is 160 bytes per live instance. Which change should the team make?
MCQ-85A payments service parses webhooks with `payload = json.loads(request.body)` and calls the handler as `credit(payload["account_id"], payload["amount_cents"])`: ```python def credit(account_id: str, amount_cents: int) -> None: ledger.add(account_id, amount_cents) # ledger.add runs balance + amount_cents ``` CI runs `mypy --strict` over the file and passes. In staging, 8% of webhooks return 500 with `TypeError: unsupported operand type(s) for +: 'int' and 'str'`; every failing payload sends `"amount_cents": "2500"` as a JSON string, while the 92% that succeed send `2500`. Which change stops the 500s?
MCQ-86A product feed is served cache-aside from a single Redis key, feed:home, with a 300 s TTL. On a miss the handler runs a 700 ms Postgres query and then SETs the key. The service runs on 12 instances behind a load balancer, and feed:home takes 800 req/s in total, spread evenly across them, so each instance sees about 67 req/s for it; every request reads Redis first. The team has just replaced the miss path with a per-process single-flight map keyed by the cache key: the first request in a process to miss Redis starts the query and stores its promise in the map, every other miss in that same process awaits the promise and uses the value the loader writes, and the entry is removed once the loader finishes. How many Postgres queries does one expiry of feed:home trigger?
MCQ-87A payments service keeps account balances in Redis in front of Postgres. At peak it applies 3,000 balance updates per second. Write-through adds 6 ms to each update; the service's p99 is 22 ms against a 40 ms budget. Write-back flushes to Postgres every 1 s, and a cache node restart discards everything not yet flushed. Which choice fits this workload?
MCQ-88A product-page cache stores rendered HTML in Redis under `page:{product_id}:{session_id}:{utm_source}`. The catalog has 50,000 products and each page renders in one of 3 locales (language and currency differ); `utm_source` is a free-form affiliate string with about 40,000 distinct values seen in the last week. During a flash sale Redis hit 40 GB and OOM'd after 18 minutes; `INFO keyspace` showed 4.2×10^7 keys and the hit rate was 12%. Which change addresses the cause?
MCQ-89A PostgreSQL 16 signup endpoint INSERTs the user row on the primary and then, 80 ms later, builds its response from SELECT id, email FROM users WHERE id = $1, issued through a pool that round-robins over four asynchronously replicated standbys in the same subnet. Lag measured on all four across the last hour: p50 25 ms, p90 95 ms, p99 250 ms. About 12% of signups come back "user not found"; those clients re-POST the form and the second INSERT hits the unique index on email, around 3,900 duplicate-key errors a day. The endpoint's p99 budget is 150 ms and it currently measures 120 ms. Which change to the follow-up read should the team make?
MCQ-90An 8-shard write path is keyed on tenant_id and runs at 80k QPS. One tenant, ACME, produces 40% of all writes; its shard's p99 is 1.8s and it returned 429s for 14 minutes while the other seven shards sat near 7k QPS each. Reads are tenant-scoped range scans over recent orders. What should the team do?
MCQ-91POST /v1/charges runs on six pods behind a load balancer, each request in its own READ COMMITTED transaction, keys stored in idempotency_keys(key text PRIMARY KEY, response jsonb). The handler is exactly: 1. SELECT response FROM idempotency_keys WHERE key = $1 2. if a row exists and response is not null, return 200 with that response 3. charge_id = processor.charge(account, amount) // external HTTPS call, 380 ms at p50 4. INSERT INTO idempotency_keys (key, response) VALUES ($1, $2) 5. return 201 with charge_id The handler has no exception handling, the framework turns an unhandled exception into HTTP 500, and the processor has no duplicate detection of its own. A replay test opens 20 connections and sends Idempotency-Key k7f2 for the same $49.00 order on all of them; all twenty SELECTs at line 1 finish within 12 ms of the first. What does the test observe?
MCQ-92A feed endpoint uses SELECT id, created_at FROM posts ORDER BY created_at DESC, id DESC LIMIT 20 OFFSET (page-1)*20. A client loads page 1 at 10:00. Between 10:00 and 10:01, 150 posts are inserted, all with created_at later than every post on page 1. At 10:01 the client requests the 20 posts that followed page 1. Which change returns exactly those 20 posts?
MCQ-93A client calls a downstream API with this retry policy: base delay 250 ms, doubling on each successive retry; full jitter, so the actual sleep is drawn uniformly from 0 to the current bound; cap 8 s; at most 5 attempts. When a response carries `Retry-After`, that value replaces the computed delay for that retry. One request's attempts go: attempt 1 returns `429` with `Retry-After: 3`; attempt 2 returns `429` with no `Retry-After`; attempt 3 returns `200 OK`. What is the total time the client spends sleeping between attempt 1 and attempt 3?
MCQ-94An API issues access tokens as HS256 JWTs with exp=60m and keeps no server-side state for them. Refresh tokens are opaque 256-bit strings; each session has one row in Redis with a 30-day TTL, and logout deletes that row. At 09:00 an attacker copies both tokens from a compromised laptop. The user logs out at 09:20. The attacker keeps calling the API with the copied access token and, when it stops working, presents the copied refresh token to the token endpoint. What does the attacker get?
MCQ-95A payments service receives webhooks from a provider that signs each request as `HMAC-SHA256(secret, t + "." + raw_body)` and sends the result in `X-Sig: t=1735689600,v1=<hex>`. The handler is: ```python raw = await request.body() data = json.loads(raw) t, v1 = parse_sig(request.headers["X-Sig"]) # t=1735689600, v1=<hex> expected = hmac.new(secret, json.dumps(data).encode(), hashlib.sha256).hexdigest() if v1 == expected: handle(data) ``` In production, 8% of valid webhooks return 401; every one of them has a body containing `\u` escapes or keys in an order `json.dumps` does not reproduce. A pentest replayed a captured webhook 40 minutes after it was sent and the service processed it. Which change fixes both failures?
MCQ-96A payments consumer reads from a queue with at-least-once delivery. Its handler writes a charge row, calls the provider's POST /charges, then acks. p99 handler time is 12 s and the queue's visibility timeout is 10 s. In a 14-minute burst of 80,000 charges, 6% were billed twice; the review found duplicates both where two handlers ran at once and where a handler was killed after POST /charges returned but before the ack. Which change removes the double billing?
MCQ-97A worker fleet consumes an SQS standard queue configured with a 30 s visibility timeout, maxReceiveCount=3, and a dead-letter queue with an alarm. Each message runs a report job that takes 12 s at p50 and 100 s at p99; the worker calls DeleteMessage only after the job returns. The downstream service is healthy. The DLQ alarm has been firing all week, and every message in the DLQ also appears in the completed-jobs log. What is the cause?
MCQ-98A ledger service runs three PostgreSQL nodes: a primary and a synchronous replica in us-east, and a synchronous replica in us-west. An automated agent promotes a replica after 30 s without a heartbeat from the primary. During a 90-second partition that isolated us-east from us-west, the agent promoted the us-west replica while the us-east primary kept serving writes; on heal the two primaries had accepted 1,200 and 340 writes, producing 340 double-debits. Past partitions between the regions have lasted up to 12 minutes, and the business requires us-east to keep accepting writes even when us-west is unreachable. Which change actually prevents the split-brain?
MCQ-99An order-history endpoint on Django 4.2 and PostgreSQL 16 loads the user's last 200 orders with Order.objects.filter(user=user)[:200] and then, inside the template loop, calls order.items.all() for each order; items is a reverse FK from OrderItem. The database is 4 ms away, each per-order items query costs that round trip plus 1 ms of parse, plan and execute, and the orders select itself takes 10 ms. A single SELECT ... WHERE order_id = ANY(%s) over the same 200 order ids returns all 1,400 item rows in 12 ms of server time. The load test ramps 200 distinct users with cold caches and reports p95 = 1.02 s, with pg_stat_statements showing 201 calls to the items query per request. The page's p95 budget is 150 ms. Which change meets the budget, and what does the request cost in queries and time?
MCQ-100A Python service runs 8 uvicorn workers, each with one async SQLAlchemy engine configured pool_size=5, max_overflow=5, pool_timeout=30. Postgres runs with max_connections=100. Every request checks out a connection, runs a SELECT, awaits a 300 ms call to a partner API, then runs an UPDATE and commits. During a spike each worker serves 50 concurrent requests and the logs fill with 'QueuePool limit of size 5 overflow 5 reached, connection timed out after 30.00 seconds'. Which change removes those timeouts?
MCQ-56An order-confirmation request renders the shipping address and sends the email in the same call: its query p99 is 40 ms against a 100 ms budget. The call already joins customers on customer_id to get the timezone used to schedule the send, and that join is 2 ms of the 40 ms p99; today it takes the shipping address from orders.ship_email. orders holds 40 million rows, and ship_email is a denormalized copy of customers.email added in 2021 for a nightly fulfillment report that now runs off a replica and no longer reads the column. The identity service applies address changes immediately, 300 a day, and a customer averages 26 orders. Support logged 340 tickets last week, every one a confirmation sent to an address the customer had changed a median of 4 days earlier. Which change makes the confirmation carry the address on file when it is sent?
MCQ-65A booking service merges overlapping windows before billing at $40 per window, so a wrong merge over-bills. Its merge function sorts intervals by start ascending, keeps one open block, and merges the next interval when its start is <= the end of the interval processed immediately before it in the sorted order, extending the open block's end to max(open.end, iv.end); otherwise it closes the open block and opens a new one. Given the input [[1,10],[2,3],[4,5],[6,7]], what does the function return?