
Real Interview Questions for the Backend Software Engineer at Yandex
NewInterview Q&A
Q&A-1Move all 0s in an array to the end using an O(n) approach?
Reported in Yandex Senior Software Engineer Interview (No Offer): After a positive HR screening, my technical
The 90-second answer
Assume the array is mutable, the result must be in place, and the relative order of the non-zero elements has to stay the same. I would use one read pointer and one write pointer. Scan left to right, copy every non-zero value to the write position, then fill the tail with zeros. That is O(n) time and O(1) extra space, and it never moves a non-zero element past another one.
# Python 3.12, in place, stable
def move_zeroes(nums: list[int]) -> None:
write = 0
for value in nums:
if value != 0:
nums[write] = value
write += 1
while write < len(nums):
nums[write] = 0
write += 1The write pointer never overtakes the read position, so no unread value is overwritten. Each element is read once. Each non-zero element is written once, and the tail fill writes at most n times, so total work is linear.
Worked trace
Input [0, 1, 0, 3, 12]:
| Step | Read value | Action | Array after step | write |
|---|---|---|---|---|
| 1 | 0 | skip | [0, 1, 0, 3, 12] | 0 |
| 2 | 1 | copy to index 0 | [1, 1, 0, 3, 12] | 1 |
| 3 | 0 | skip | [1, 1, 0, 3, 12] | 1 |
| 4 | 3 | copy to index 1 | [1, 3, 0, 3, 12] | 2 |
| 5 | 12 | copy to index 2 | [1, 3, 12, 3, 12] | 3 |
| 6 | - | fill tail with 0 | [1, 3, 12, 0, 0] | 5 |
Alternatives and when they fail
| Approach | Time | Extra space | Stable | Problem |
|---|---|---|---|---|
| Two pointers, as above | O(n) | O(1) | Yes | None for this contract |
| Count zeros, then fill | O(n) | O(1) | Yes | Two passes, and it rewrites the whole array even when there are no zeros |
| Swap zeros to the end | O(n) | O(1) | No | Swapping a zero with the last element reorders non-zero values |
| Build a new list | O(n) | O(n) | Yes | Allocates a second array, wasteful for a 10 million element buffer in a service |
The swap version is the trap. On [0, 1, 0, 3, 12] it can produce [12, 1, 3, 0, 0] or similar depending on the variant, which passes a check that only counts zeros but fails a check that compares the exact expected array.
Edge cases I would name before coding
Empty array and all-zero array: the loop copies nothing and the tail fill covers everything, result unchanged. No zeros: every element is copied onto itself, write ends at n, tail fill does nothing. Negative numbers: they are non-zero, so -1 stays with the non-zero block, which matters if the caller meant "move negatives" instead. If the caller wants a new list returned rather than mutation, I would say so explicitly and return nums after the same logic on a copy, rather than silently changing the input.
If asked to prove O(n): the scan visits each index once, the fill visits each remaining index once, and the two ranges do not overlap, so the total is at most 2n operations, which is O(n).
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Solve a task related to the merge sort technique?
Reported in Yandex Senior Software Engineer Interview (No Offer): After a positive HR screening, my technical
The 90-second answer
I would first pin down the input: an in-memory array, a file too large for RAM, or sorted streams to merge. For a standard array task I implement merge sort directly, because it guarantees O(n log n) comparisons, is stable, and its merge step is the part interviewers probe. If the data does not fit in memory, the same merge idea becomes external merge sort. If the task is counting inversions, I reuse the merge and add to the count whenever a right element is taken before a left one.
The recurrence is T(n) = 2T(n/2) + n, which solves to O(n log n) time and O(n) auxiliary space. That space cost is the main trade-off against quicksort, which averages O(n log n) with O(log n) stack space but has an O(n^2) worst case and is unstable.
# Python 3.11, checked against CPython
def merge_sort(a: list[int]) -> list[int]:
if len(a) <= 1:
return a
mid = len(a) // 2
left = merge_sort(a[:mid])
right = merge_sort(a[mid:])
merged = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps equal elements in original order
merged.append(left[i])
i += 1
else:
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return mergedWorked trace for [5, 2, 4, 1]:
| Step | Left half | Right half | Merge result |
|---|---|---|---|
| 1 | [5] | [2] | [2, 5] |
| 2 | [4] | [1] | [1, 4] |
| 3 | [2, 5] | [1, 4] | [1, 2, 4, 5] |
During step 3, taking 1 from the right while 2 and 5 remain on the left adds 2 inversions. Taking 4 next adds another 2, for 4 inversions total, which matches the pairs (5,2), (5,4), (5,1), (2,1).
Where the simple version breaks
Recursion depth is the first failure mode in production code. Python's default limit is 1000 frames, and a recursive implementation on a pathological split can hit it long before the data size becomes a problem. The fix is an iterative bottom-up version that merges runs of width 1, 2, 4, and so on, or an explicit stack. The second failure mode is memory. Allocating fresh slices at every level, as above for clarity, doubles allocation churn. A backend version merges into a single auxiliary buffer and swaps buffers each pass, which keeps allocations at O(n) total.
For data larger than RAM, say 10 GB of log lines on a Yandex backend host with 8 GB available, I switch to external merge sort. I read chunks that fit in memory, sort each chunk, and write sorted runs to disk. Then I merge the runs with a heap. With k runs and N total records, the merge costs O(N log k) comparisons and one pass over the data per merge level. If k is large, I merge in groups so the heap stays small and sequential disk reads dominate instead of random access.
| Variant | Time | Extra space | Stable | Use it when |
|---|---|---|---|---|
| Recursive merge sort | O(n log n) worst case | O(n) | Yes | Array fits in RAM, guarantee matters |
| Iterative merge sort | O(n log n) worst case | O(n) | Yes | Recursion depth is a risk |
| External merge sort | O(N log k) per merge level | One chunk in RAM | Yes | Data exceeds RAM |
| Merge k sorted streams | O(N log k) | O(k) | Yes | Inputs already sorted, e.g. sharded logs |
If the interviewer changes the task mid-way to merging k sorted lists, I do not sort each list again. I push the first element of each list into a min-heap keyed by value, pop the smallest, append it to the output, and push the next element from that same list. That is O(N log k) instead of O(N log N), and it streams, so the output can be written to disk without holding all N elements.
I would close by naming the test cases I would run: empty input, single element, duplicates to check stability, already sorted and reverse sorted input, and a large random input timed against the O(n log n) expectation. A mismatch there usually points to an off-by-one in the merge loop rather than a flaw in the algorithm.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3Design an SQS-like system and a task scheduler?
Reported in Yandex Software Engineer interview experience (October 2025)
The 90-second answer
I would build one durable log per queue, a delivery layer that leases messages instead of deleting them, and a separate scheduler that turns delayed and periodic work into ordinary messages. The queue gives at-least-once delivery with a visibility timeout. The scheduler gives fire-at-time semantics on top of that queue, with its own lease so two scheduler instances cannot fire the same task.
Assume a few million messages a day, payloads under 256 KB, consumers in the same region, and no strict ordering across queues. If the interviewer wants global FIFO or exactly-once processing, I would say so up front: neither is free, and exactly-once delivery to an arbitrary consumer is not something I would promise.
Queue core
A queue is an append-only log partitioned by queue name, then by a hash of message group or consumer key inside the queue. Partitions keep ordering inside a partition and let throughput scale by adding partitions. Each record carries an ID, enqueue time, body, attributes, delivery count, and a receipt handle generated per delivery.
Send is a write to the log with a producer-supplied deduplication ID. For standard queues I accept duplicates. For FIFO queues I keep a dedup window, 5 minutes in SQS, and reject a second send with the same ID in that window. That is a storage lookup on the write path, so I would only enable it where the client actually needs it.
Receive does not remove a message. It assigns a lease: the message becomes invisible for a visibility timeout, 30 seconds by default in SQS, and the consumer gets a receipt handle. Ack deletes the message. Nack or lease expiry makes it visible again. This is the whole at-least-once mechanism, and it explains the main failure mode: a consumer that crashes after doing the work but before acking will see the message again. Consumers must be idempotent, keyed on the message ID.
Long polling matters for cost. A short poll that returns empty 95% of the time at 10,000 polls per second burns requests for nothing. Holding a receive for up to 20 seconds and waking it on enqueue cuts that by orders of magnitude. The trade-off is tail latency on shutdown and a need to cap held connections per partition.
Poison messages need a bound. I track receive count per message. After a configured maximum, say 5 receives, the message moves to a dead-letter queue with its count and last error, and an alert fires. Without that, one malformed payload loops forever and consumes consumer capacity.
| Concern | Standard queue | FIFO queue |
|---|---|---|
| Ordering | Best effort across partitions | Within a message group |
| Throughput | Scales with partitions | Capped by one group, roughly 300 msg/s per group in SQS |
| Dedup | None | 5 minute window on dedup ID |
| Use when | Independent tasks, fan-out | Per-entity sequence, e.g. one account |
Scheduler on top
The scheduler stores tasks in a table keyed by due time: task ID, due timestamp, payload, cron or one-shot flag, and lease owner. A scheduler instance claims due tasks in batches, enqueues them into a target queue, and marks them fired in the same transaction where possible. Periodic tasks get their next due time computed from the previous scheduled time, not from completion time, so a slow run does not drift the schedule.
For scale I shard by time range or by task ID hash, and run one active scheduler per shard with a lease in a coordination store. If the lease holder dies, the lease expires in seconds and another instance takes over. The risk is a double fire during failover, so the enqueue carries the task ID as the dedup ID and the queue consumer dedups on it. That converts a scheduler race into a queue duplicate, which consumers already handle.
In-memory structures help at the edge. A timing wheel or a heap of the next few thousand tasks avoids a database scan every tick. The heap gives O(log n) insert and pop. But the database remains the source of truth, because an in-memory heap loses everything on restart and cannot survive a shard rebalance. I would reload the heap from the table on startup and treat the heap as a cache only.
// Consumer side, Go 1.22. Lease expiry is the retry.
msg, err := q.Receive(ctx, queue, 10, 30*time.Second)
if err != nil {
return err
}
for _, m := range msg {
if err := handle(ctx, m); err != nil {
_ = q.Nack(ctx, queue, m.ReceiptHandle) // visible now, count++
continue
}
if err := q.Ack(ctx, queue, m.ReceiptHandle); err != nil {
// Ack lost: message will redeliver after visibility timeout.
// handle() must be idempotent on m.ID.
log.Warn("ack failed", "id", m.ID, "err", err)
}
}Numbers and failure modes
At 10,000 messages per second with a 30 second visibility timeout, up to 300,000 messages can be in flight at once. That sets the size of the lease index and the connection pool for delivery. If consumers slow down, in-flight messages pile up, redeliveries rise, and the queue depth metric is the first signal. I would alert on age of the oldest visible message, not just depth, because a queue can look shallow while one message has been stuck for an hour.
Clock skew is the scheduler failure mode I would name. If two scheduler hosts disagree by 2 seconds, tasks fire early or late and ordering across shards breaks. I would use a single time source per shard, store due times in UTC, and accept that fire time is approximate within a few seconds. For tasks that need tighter bounds, such as billing windows, I would add a guard at execution time that rechecks the window.
A second failure mode is a hot partition. If one message group or one queue takes 80% of traffic, adding partitions does not help that group. The fix is client-side hashing across groups and a per-group throughput alarm, which is why I would expose per-partition metrics from day one.
I would close by stating the boundary: this design gives durable at-least-once delivery and approximate scheduled firing. If the interviewer pushes for exactly-once side effects, the answer moves into transactional outbox and idempotent consumers, which is a different and much more expensive design.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Solve a problem involving binary search?
Reported in Yandex Software Engineer interview experience (October 2025)
The 90-second answer
I would state the invariant first, then code to it. For a sorted array, binary search keeps the answer inside a shrinking interval [lo, hi) and discards half of it on every step, so it runs in O(log n) comparisons and O(1) extra space. The bugs are almost never the idea. They are the midpoint, the update direction, and the termination condition. I will write it as a lower bound search: find the first index where a[i] >= target, which also handles duplicates and the not-found case without a special branch.
Assumptions I would say out loud: the array is sorted ascending, indices are 0-based, and I need the leftmost match. If the array is not sorted, or I need all matches in an unsorted log, binary search is the wrong tool.
Invariant and trace
Invariant at the top of each iteration: every element before lo is < target, and every element at or after hi is >= target. Initially lo = 0, hi = n, so the invariant holds vacuously. Each step picks mid inside [lo, hi). If a[mid] < target, the answer cannot be at or before mid, so lo = mid + 1. Otherwise the answer is at or before mid, so hi = mid. The interval strictly shrinks, and when lo == hi that position is the answer, or n if all elements are smaller.
Worked trace for a = [1, 3, 5, 5, 7, 9], target = 5. The answer should be index 2, the first 5.
| Step | lo | hi | mid | a[mid] | Decision | New interval |
|---|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 5 | 5 >= 5, search left | [0, 3) |
| 2 | 0 | 3 | 1 | 3 | 3 < 5, search right | [2, 3) |
| 3 | 2 | 3 | 2 | 5 | 5 >= 5, search left | [2, 2) |
Loop ends with lo == hi == 2. Three iterations for six elements, which matches ceil(log2(6)) + 1 in the worst case.
Code
Go, checked against Go 1.22. The midpoint uses lo + (hi-lo)/2 instead of (lo+hi)/2 so the sum cannot overflow when indices approach int limits on 32-bit builds.
package main
// lowerBound returns the first index i with a[i] >= target,
// or len(a) if every element is smaller. a must be sorted ascending.
func lowerBound(a []int, target int) int {
lo, hi := 0, len(a) // answer in [lo, hi)
for lo < hi {
mid := lo + (hi-lo)/2
if a[mid] < target {
lo = mid + 1
} else {
hi = mid
}
}
return lo
}Callers check idx < len(a) && a[idx] == target for an exact match. That one check covers found, duplicate, and not-found without extra flags.
Where it breaks in practice
Three failure modes I watch for. First, using <= in the loop condition with an inclusive hi and then updating hi = mid can loop forever, because the interval stops shrinking. The half-open interval above avoids that pairing. Second, searching a rotated sorted array or a bitonic array with this code returns a wrong index silently, since the invariant is false from the start. The fix there is to test which half is sorted before deciding, which doubles the branch logic and is worth it only when the input really has that shape. Third, binary searching over a remote store, such as a paginated API or a disk file, turns O(log n) comparisons into O(log n) network round trips. At 20 round trips of 30 ms each, that is 600 ms where a single scan or an index lookup would be faster. In a backend service I would push the predicate into the database with an indexed range query instead of looping over pages.
Alternatives and when to switch
| Situation | Better choice | Why |
|---|---|---|
| Sorted array, point lookup | Binary search, O(log n) | No preprocessing cost |
| Many lookups on static data | Hash map, O(1) average | Pays O(n) build once |
| Sorted data on disk, large | B-tree index | Fewer page reads than binary search over blocks |
| Monotonic predicate, no array | Binary search on the answer | Finds the smallest value that satisfies the predicate, for example the minimum capacity that ships a workload in time |
The last row is the variant interviewers probe next. If the question becomes "find the smallest speed that finishes the task in time", there is no array to search. I binary search the answer space instead, with the same invariant: everything below lo fails the predicate, everything at or above hi passes. Same loop, different predicate, and the same overflow and termination care.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Solve a tree rotation problem?
Reported in Yandex Software Engineer interview experience (October 2025)
The 90-second answer
I would clarify the shape first: a binary tree, one rotation, and whether the inorder sequence has to stay fixed. For a binary search tree it does. A right rotation at y promotes y.left to the new subtree root and moves y down to the right, without changing the inorder order or touching any node outside the subtree.
After the rotation, x is the root, x.right is y, and y.left is T2. Every other pointer stays where it was. That is the whole operation: three pointer assignments, O(1) time, O(1) extra space.
Code
Python 3.11, using a plain node class. The caller must use the return value, because the subtree root changes.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def rotate_right(y):
if y is None or y.left is None:
return y
x = y.left
t2 = x.right
x.right = y
y.left = t2
return x
def rotate_left(x):
if x is None or x.right is None:
return x
y = x.right
t2 = y.left
y.left = x
x.right = t2
return yWorked trace
Take a right rotation at y = 30, with x = 20, A = 10, T2 = 25, C = 40.
| Step | Assignment | Result |
|---|---|---|
| 1 | x = y.left | x points to 20 |
| 2 | t2 = x.right | t2 points to 25 |
| 3 | x.right = y | 20's right child becomes 30 |
| 4 | y.left = t2 | 30's left child becomes 25 |
| 5 | return x | subtree root is now 20 |
Inorder before: 10, 20, 25, 30, 40. Inorder after: 10, 20, 25, 30, 40. Height of this subtree drops from 3 to 2 in this shape, because 30 no longer sits above 20. The BST property holds: everything under 20 is below 20, everything under 30 and above 20 is in (20, 30), which is exactly where 25 belongs.
Where candidates lose points
First, dropping the return value. rotate_right(y) called as a statement leaves the parent still pointing at y, so the rotation is invisible from above. The fix is always y = rotate_right(y) at the call site, or root = rotate_right(root) at the top.
Second, rotating when the child is missing. If y.left is None, there is nothing to promote. Returning y unchanged is correct. Dereferencing x.right first would raise an exception on a degenerate tree, which is the shape that shows up in tests for unbalanced input.
Third, assuming one rotation always balances. It fixes a single heavy edge. In an AVL tree, a left-right case (left child is right-heavy) needs a left rotation on the child first, then a right rotation on the node. Doing only the right rotation there produces a tree that is still unbalanced and can break the height invariant the caller relies on. The same warning applies to a general binary tree with no ordering constraint: rotation is just pointer surgery, and the caller has to state which invariant it restores.
Alternatives and when to pick them
| Approach | Cost | When it fits |
|---|---|---|
| Single rotation | O(1) | One known imbalance, AVL or treap step |
| Double rotation | O(1) | Left-right or right-left AVL case |
| Rebuild from sorted array | O(n) | Many rotations needed, or a static set loaded once |
| Splay to root | amortized O(log n) | Access pattern is skewed, recent keys repeat |
For a backend service storing keys in memory, I would not hand-roll rotations for a plain map. A balanced tree from the standard library or a B-tree on disk gives the same guarantees with tested code. Hand-written rotation code earns its place inside an AVL, red-black, or treap implementation, or in an interview where the point is to show the pointer work cleanly under pressure.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Solve a streaming producer-consumer problem?
Reported in Yandex Software Engineer interview experience (October 2025)
The 90-second answer
I would clarify four things before coding: is the stream finite or infinite, must order be preserved, what happens when the consumer is slower than the producer, and how should shutdown work. Assuming a bounded in-memory buffer, multiple producers, multiple consumers, and a graceful drain on shutdown, I would use a bounded queue with explicit backpressure and a done channel for cancellation. An unbounded queue hides the problem until memory runs out. A blocking send on a full bounded queue makes backpressure visible at the producer.
// Go 1.22. Bounded producer-consumer with graceful drain.
package main
import (
"context"
"sync"
)
type Job struct {
ID int
Val int
}
func Produce(ctx context.Context, jobs []Job, out chan<- Job, wg *sync.WaitGroup) {
defer wg.Done()
for _, j := range jobs {
select {
case out <- j: // blocks when buffer is full: backpressure
case <-ctx.Done():
return
}
}
}
func Consume(ctx context.Context, in <-chan Job, results chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for j := range in {
select {
case results <- j.Val * 2:
case <-ctx.Done():
return
}
}
}
func Run(ctx context.Context, jobs []Job, numConsumers int) []int {
queue := make(chan Job, 64) // bounded: 64 pending jobs max
results := make(chan int, 64)
var pwg, cwg sync.WaitGroup
pwg.Add(1)
go Produce(ctx, jobs, queue, &pwg)
go func() { pwg.Wait(); close(queue) }() // close only after producer finishes
for i := 0; i < numConsumers; i++ {
cwg.Add(1)
go Consume(ctx, queue, results, &cwg)
}
go func() { cwg.Wait(); close(results) }()
var out []int
for r := range results {
out = append(out, r)
}
return out
}Closing queue in a separate goroutine matters. If the main goroutine closed it directly, it would race with a producer still sending and panic on send to a closed channel. Consumers range over the channel, so they exit only after the buffer is fully drained, which gives the graceful shutdown for free.
Worked trace. Hypothetical figures: 3 producers send 1,000 jobs each, 4 consumers, queue capacity 64, each job takes 5 ms to process.
| Time | Queue depth | What happens |
|---|---|---|
| 0 ms | 0 to 64 | Producers fill the buffer, then block on send |
| 5 ms | 64 | First 4 jobs picked up, 4 more sends unblock |
| 100 ms | 64 | Steady state: throughput capped by consumers, about 800 jobs/s |
| 3,750 ms | falling | Producers done, queue closes, consumers drain the last 64 |
| 3,790 ms | 0 | Results closes, collector returns 3,000 values |
Memory stays bounded at 64 jobs plus in-flight work, regardless of stream length. That is the property an interviewer is usually probing.
Trade-offs and failure modes.
| Design | Backpressure | Ordering | When to use it |
|---|---|---|---|
| Bounded channel, as above | Blocking send | Per-producer order only with multiple consumers | In-process pipeline, low latency |
| Unbounded channel | None, memory grows | Same | Short bursts only, with a hard cap and alert |
| External queue, for example Kafka or SQS | Producer throttling or disk | Partition key order | Across processes or hosts, replay needed |
With multiple consumers, global order is lost even if each producer is ordered. If the task requires strict order, use one consumer, or partition by key and keep one consumer per partition. If a consumer panics or stalls, the queue fills, producers block, and latency climbs for everyone. I would detect that with queue depth and oldest-job age metrics, and add a per-job timeout plus a dead-letter path for poison jobs instead of letting one bad record wedge the pipeline. On cancellation, ctx.Done() unblocks producers stuck on send, but jobs already taken by a consumer need an idempotent handler, because a retry after a timeout can deliver the same job twice. At-least-once delivery plus idempotent processing is the honest contract here.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Design a service for calculating square roots of numbers, but with a billing component built in?
Reported in Yandex Software Engineer interview experience (December 2024)
The 90-second answer
The square root is trivial. The billing path is the system. I would build a stateless compute API in front of a transactional ledger, and charge on a reserve-then-settle model so a crash never gives free compute or charges for work that never happened.
POST /sqrt takes {"value": 2.0} and an Idempotency-Key header. The tenant is resolved from the API key or OAuth token, never from the body. Flow: validate, reserve the price against the tenant balance, compute, settle the reservation into a ledger entry, return the result. Validation failures (negative value, malformed JSON, missing key) return 4xx and are never billed. A computed result, including sqrt(0) = 0, is billed.
Reserve, then settle. Charging after compute means a client can call, get the answer, and disconnect before the charge lands. Charging before compute means a compute crash charges for nothing. Reserve splits it: step one atomically moves the price from available to held, step two converts held to spent only after the result exists. If compute fails, the reservation is released. If the process dies between reserve and settle, a sweeper releases reservations older than, say, 60 seconds that have no settlement record.
The reserve must be atomic or concurrent calls overspend the balance. A conditional update does it in one statement:
-- Go service, PostgreSQL. Price is in minor units, e.g. 10 = 0.10 RUB per call.
UPDATE tenants
SET balance_minor = balance_minor - $1,
held_minor = held_minor + $1
WHERE tenant_id = $2 AND balance_minor >= $1
RETURNING balance_minor;
-- Zero rows returned means insufficient funds: return 402, do not compute.Settlement writes a double-entry style ledger row (tenant debit, platform credit, reservation id, idempotency key, price, timestamp) in the same transaction that clears the hold. The ledger is append-only. Corrections are new reversing rows, never updates, which is what makes reconciliation and disputes answerable.
Idempotency is the billing contract. Retries are normal on networks, and a retry must not double-charge. The client sends Idempotency-Key: 7f3c.... The server stores key -> (request_hash, status, response_body) for 24 hours. Same key and same hash replays the stored response with no new reservation. Same key with a different hash returns 409, because reusing a key for a different request is a client bug.
| Trace | What happens | Charge |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
First POST /sqrt {"value": 2} with key 7f3c | Reserve 10, compute 1.41421356, settle, store response | 10 |
| Retry 800 ms later, same key, same body | Key found, replay stored 200 body | 0 |
Same key, body {"value": 9} | Hash mismatch, return 409 key_reused | 0 |
POST /sqrt {"value": -1} | Validation fails before reserve, return 422 domain_error | 0 |
| Balance 5, price 10 | Conditional update matches no row, return 402 insufficient_balance | 0 |
Pricing and metering. Price per call is the simplest meter, and it matches cost here because compute is constant time. If the product later prices by precision or batch size, the meter becomes (calls, digits) and the reserve needs the price computed from the validated request before the update above. Batch endpoint POST /sqrt:batch with up to 1000 values should reserve price * len(values) once, not per item, so a partial failure settles proportionally. Arithmetic check: at 10 minor units per call, 1 million calls a day reserves 10,000,000 minor units, and the held balance must cover peak concurrency times price. At 500 concurrent in-flight calls that is only 5,000 minor units of headroom, so the balance check, not compute, is the first thing to saturate.
Failure modes I would name in the loop. Compute succeeds, settle fails: the reservation stays held and the sweeper releases it, the client retries with the same key and gets a fresh compute, no double charge. Settle succeeds, response lost: the retry replays the stored response, one charge. Ledger write succeeds, process dies before the idempotency record commits: this is the dangerous window, so the ledger row and the idempotency record must commit in one transaction, using a transactional outbox if the ledger lives in another store. Clock skew on reservation expiry: use server-side timestamps only, and make expiry generous relative to p99 compute latency, which for math.Sqrt is microseconds, so 60 seconds is already loose.
Scaling. Compute nodes are stateless and scale horizontally behind a load balancer. The ledger is the bottleneck, so partition by tenant and keep the hot path to one indexed update plus one insert. Rate limiting per tenant (token bucket, e.g. 100 rps burst 200) protects the ledger and gives a clean 429 with Retry-After before billing logic runs. Quota alerts at 80% of balance let the tenant top up before hitting 402 mid-workflow.
What I would not do: bill per byte of response, bill failed validations, or trust a client-supplied tenant id or price. The price comes from a server-side pricing table keyed by plan, versioned, so a price change never rewrites history.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Find a contiguous subarray that sums to a target number?
Reported in Yandex Software Engineer interview experience (December 2024)
The 90-second answer
I would first ask whether the array can contain negative numbers, because that decides the algorithm. If all numbers are non-negative, a sliding window gives O(n) time and O(1) extra space. If negatives are allowed, that window breaks, and I would use prefix sums with a hash map, also O(n) time but O(n) space.
For the general case, define prefix[i] = nums[0] + ... + nums[i]. A subarray (l..r) sums to target exactly when prefix[r] - prefix[l-1] == target, or prefix[l-1] == prefix[r] - target. So while scanning left to right I keep every prefix seen so far and look for the one I need. Seed the map with 0 -> -1 to cover subarrays starting at index 0.
def find_subarray(nums: list[int], target: int) -> tuple[int, int] | None:
prefix = 0
seen = {0: -1} # prefix value -> earliest index where it occurred
for i, x in enumerate(nums):
prefix += x
need = prefix - target
if need in seen:
return (seen[need] + 1, i)
if prefix not in seen:
seen[prefix] = i
return NoneKeeping the earliest index for each prefix returns the longest subarray ending at i. If the interviewer wants the shortest, I would overwrite instead and keep the latest index. That choice is worth stating, since both are correct under different readings of "find a subarray".
Worked trace
nums = [4, -2, 1, 3, -1, 2], target = 5. The answer is indices 0..4, since 4 - 2 + 1 + 3 - 1 = 5.
| i | x | prefix | need = prefix - 5 | action |
|---|---|---|---|---|
| - | - | 0 (seed) | - | seen = {0: -1} |
| 0 | 4 | 4 | -1 | miss, store 4 -> 0 |
| 1 | -2 | 2 | -3 | miss, store 2 -> 1 |
| 2 | 1 | 3 | -2 | miss, store 3 -> 2 |
| 3 | 3 | 6 | 1 | miss, store 6 -> 3 |
| 4 | -1 | 5 | 0 | hit at index -1, return (0, 4) |
Why the sliding window fails with negatives
| Approach | Assumption | Time | Extra space | Handles negatives |
|---|---|---|---|---|
| Sliding window | all x >= 0 | O(n) | O(1) | No |
| Prefix sum + hash map | none | O(n) average | O(n) | Yes |
| Brute force, all pairs | none | O(n^2) | O(1) | Yes |
With a negative inside the window, removing the left element can increase the sum instead of decreasing it. The window can skip past a valid subarray and never come back, so the invariant the two-pointer proof relies on does not hold. Zeros are fine for the sliding window, though they can produce several valid windows and the shrink condition needs care to avoid an infinite loop.
Failure modes I would name in the loop
Integer overflow. In Go or C++ with 32-bit int, a prefix sum over a long array wraps silently and the hash map then stores garbage keys. I would use 64-bit accumulators and say so. In Python this is a non-issue, which is one reason I would prototype in Python and port carefully.
Memory on large inputs. The hash map holds one entry per distinct prefix, so 100 million integers need several gigabytes. If the input arrives as a stream from a service and cannot be stored, I would ask whether an approximate or bounded answer is acceptable, or whether the data can be sorted offline. For an interview-sized array this is theoretical, but naming the bound shows I have shipped this shape of code.
Empty input and no solution. Return None (or an empty pair, depending on the contract) rather than raising, and state that up front. Also state whether an empty subarray counts as summing to 0. My code does not count it, because the seed index -1 only yields a subarray once at least one element has been consumed.
Worst case of the hash map. Average O(n), but a pathological hash collision pattern degrades lookups. In practice with integer keys in Python or Go this is not a concern I would optimise for, and I would say that rather than hand-roll a balanced tree and lose the constant factor.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9How do dictionaries work under the hood with hashtable logic?
Reported in Yandex Software Engineer interview experience (December 2024)
The 90-second answer
A dictionary is an array of buckets indexed by a hash of the key. On insert, the runtime computes hash(key), reduces it modulo the current capacity, and stores the pair in that bucket. On lookup it recomputes the hash, jumps to the same bucket, and compares keys for equality. Average lookup is O(1) because the hash spreads keys evenly across buckets. It degrades to O(n) when many keys land in one bucket, which is why capacity, load factor and the collision strategy matter more than the hash function alone.
I would state the language, because implementations differ. CPython 3.12 dict uses open addressing with a separate indices array and a perturb probe sequence. Go map uses buckets of 8 slots with a tophash byte per slot and overflow buckets. Java HashMap uses chaining and converts a long chain to a tree under conditions I will cover below. Rust's standard HashMap uses hashbrown, a SwissTable design with quadratic probing and SIMD group lookup. The shared logic is the same: hash, index, resolve collisions, grow before the table fills.
Collision handling
Two families dominate. Chaining keeps a linked list per bucket. Open addressing probes neighbouring slots until it finds the key or an empty slot. The probe sequence decides how far apart successive probes land. Linear probing steps by one and clusters. Quadratic probing steps by increasing triangular offsets and spreads further. CPython uses a perturb sequence, i = (i * 5 + perturb + 1) & mask, shifting perturb right by 5 each step, so a run of collisions does not stay in one neighbourhood.
| Strategy | Insert cost | Lookup cost on collision | Delete | Typical user |
|---|---|---|---|---|
| Chaining | O(1) average, append to list | O(chain length) | O(chain length), unlink | Java HashMap, Go overflow buckets |
| Linear probing | O(1) average until load > 0.7 | O(cluster length) | Needs tombstones or rehash cluster | Textbook tables, some embedded stores |
| Quadratic probing | O(1) average, wider spread | O(probes), fewer clusters | Tombstones | Rust HashMap via hashbrown |
| Perturb probing | O(1) average, hash bits reused | O(probes), low clustering | Tombstones, rehashed on resize | CPython dict |
Deletion is the awkward case for open addressing. Marking a slot empty would break a probe chain that passed through it, so implementations leave a tombstone. Tombstones keep lookups correct and make inserts slower, because the table looks fuller than it is. CPython rehashes and drops tombstones when they accumulate.
Java's treeification is a special case of chaining. A bucket chain is converted to a red-black tree when its length reaches 8, but only if the table capacity is at least 64. Below 64 buckets, the map resizes instead of treeifying, because growing the table usually shortens the chain more cheaply. Once treeified, worst case lookup in that bucket drops from O(n) to O(log n), at the cost of tree node overhead and slower iteration.
Growth and the load factor
Capacity is usually a power of two, so hash & (capacity - 1) replaces modulo. When entries / capacity crosses the threshold, the table allocates a larger array and reinserts every live entry. CPython resizes at roughly two thirds full for small tables, Go grows when load exceeds roughly 6.5 entries per bucket, Java defaults to load factor 0.75. Resizing is O(n) and causes a latency spike, so a service that builds a large map in a request path should pre-size it. In Go that means make(map[K]V, n). In Java, new HashMap<>(n * 4 / 3). In Python, there is no public pre-size, so building in chunks or accepting the rehash cost is the choice.
# Python 3.12: minimal chaining table, for the mechanism only
class Table:
def __init__(self, capacity=8):
self.capacity = capacity
self.buckets = [[] for _ in range(capacity)]
self.size = 0
def put(self, key, value):
bucket = self.buckets[hash(key) % self.capacity]
for i, (k, _) in enumerate(bucket):
if k == key:
bucket[i] = (key, value)
return
bucket.append((key, value))
self.size += 1
if self.size / self.capacity > 0.75:
self._grow()
def _grow(self):
old = [kv for b in self.buckets for kv in b]
self.capacity *= 2
self.buckets = [[] for _ in range(self.capacity)]
for k, v in old:
self.buckets[hash(k) % self.capacity].append((k, v))Worked trace
Capacity 8, hash values shown as hash(key) % 8. The trace uses hypothetical hash values, labelled as such, because the exact hash depends on the runtime.
| Step | Key | Bucket | Result |
|---|---|---|---|
| 1 | "alice" | 3 | bucket 3: [alice] |
| 2 | "bob" | 3 | collision, bucket 3: [alice, bob] |
| 3 | "carol" | 5 | bucket 5: [carol] |
| 4 | lookup "bob" | 3 | compare alice, then bob, hit |
| 5 | lookup "dave" | 3 | compare alice, bob, miss |
Step 5 shows the cost of a collision. Two comparisons instead of one. With 100 keys colliding in one bucket, every lookup pays up to 100 comparisons, unless the implementation treeifies or the table grows.
Failure modes I would name in the loop
Hash flooding: if an attacker controls keys and the hash is predictable, they can force collisions and turn O(1) lookups into O(n). Python and Go mitigate this with per-process hash seed randomisation for strings. A custom hash in C++ or Java needs the same care, and a service accepting untrusted keys should not use a weak hash such as a simple sum of bytes.
Broken hash and equality contract: in Java, two objects that compare equal must return the same hash code. Violating that makes entries unreachable, because the lookup hashes to a different bucket than the insert did. The same rule applies to Python __hash__ and __eq__, and to Go comparable keys. Mutating a key after insertion has the same effect, which is why Python requires dict keys to be hashable and treats mutable containers as unhashable.
Memory and iteration order: a dict holds the bucket array plus per-entry overhead, so 10 million entries cost far more than the keys alone suggest. Iteration order in Python 3.7+ and Go maps differ. Python preserves insertion order as a language guarantee. Go deliberately randomises map iteration, so code that depends on order there is a bug waiting for a different seed.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Using two pointers, erase all # from a string?
Reported in Yandex Software Engineer Interview (Declined Offer): 4 rounds interview with algorithm questions
The 90-second answer
I would clarify one point first: # is a literal character to delete, not a backspace that deletes the previous character. Assuming that, I keep a read pointer and a write pointer over the same array. The read pointer scans every character. The write pointer marks where the next kept character belongs. When the read character is not #, I copy it to the write position and advance the write pointer. When it is #, I advance only the read pointer. At the end, the first write slots hold the result in order, and I return write as the new length.
# Python 3.11, in-place on a list of characters
def erase_hash(s: list[str]) -> int:
write = 0
for read, ch in enumerate(s):
if ch != '#':
s[write] = ch
write += 1
return write
s = list("ab#c##de")
n = erase_hash(s)
print(''.join(s[:n])) # "abcde"That is O(n) time because each character is read once and written at most once, and O(1) extra space because the write pointer never passes the read pointer. The invariant is write <= read at every step, so copying s[read] into s[write] cannot overwrite a character that has not been read yet.
Worked trace for a b # c # # d e:
| read | ch | write before | action | write after |
|---|---|---|---|---|
| 0 | a | 0 | copy to index 0 | 1 |
| 1 | b | 1 | copy to index 1 | 2 |
| 2 | # | 2 | skip | 2 |
| 3 | c | 2 | copy to index 2 | 3 |
| 4 | # | 3 | skip | 3 |
| 5 | # | 3 | skip | 3 |
| 6 | d | 3 | copy to index 3 | 4 |
| 7 | e | 4 | copy to index 4 | 5 |
Result: abcde, returned length 5.
Edge cases I would name before coding: empty input returns 0, input of only # characters returns 0, and input with no # returns the original length with the array unchanged. In Go, I would operate on a []byte or []rune slice and return the truncated slice s[:write]. Operating on bytes is fine for ASCII #, but if the string can contain multibyte UTF-8, copying byte by byte still preserves the encoding because I never split a rune, I only drop whole # bytes. If the caller passes an immutable string in Go or Java, I would build a new string or byte buffer instead of pretending to mutate it, which costs O(n) extra space.
If the interviewer meant # as backspace, as in ab#c meaning ac, this solution is wrong and I would say so immediately. That variant needs a different pass: either build the output with a stack, or scan from the end skipping deleted characters and their backspaces. The literal-removal version above is the one that fits "erase all #" with two pointers moving in the same direction.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Compress consecutive characters into a character-count format using run-length encoding?
Reported in Yandex Software Engineer interview experience (December 2024)
The 90-second answer
I would do one left-to-right pass, counting the current run and flushing it when the character changes or the string ends. For aaabbbccdaa that gives a3b3c2d1a2. Time is O(n) in the input length, extra space is O(1) besides the output if I stream the result, and O(m) if I build the output string, where m is the encoded length.
The assumptions I would state first: the input is a sequence of characters, the output format is char + decimal count, and the count is always written, even for a run of one. That last choice matters. If I omit 1, decoding and testing get harder for no real gain.
def rle(s: str) -> str:
if not s:
return ""
out = []
prev = s[0]
count = 1
for ch in s[1:]:
if ch == prev:
count += 1
else:
out.append(f"{prev}{count}")
prev, count = ch, 1
out.append(f"{prev}{count}")
return "".join(out)
assert rle("aaabbbccdaa") == "a3b3c2d1a2"
assert rle("") == ""
assert rle("x") == "x1"Worked trace for aaabbbccdaa:
| Step | Input consumed | Current run | Action | Output so far |
|---|---|---|---|---|
| 1 | a | a x1 | start | `` |
| 2 | aa | a x2 | extend | `` |
| 3 | aaa | a x3 | extend | `` |
| 4 | aaab | b x1 | flush a | a3 |
| 5 | aaabb | b x2 | extend | a3 |
| 6 | aaabbb | b x3 | extend | a3 |
| 7 | aaabbbc | c x1 | flush b | a3b3 |
| 8 | aaabbbcc | c x2 | extend | a3b3 |
| 9 | aaabbbccd | d x1 | flush c | a3b3c2 |
| 10 | aaabbbccda | a x1 | flush d | a3b3c2d1 |
| 11 | aaabbbccdaa | a x2 | extend, then final flush | a3b3c2d1a2 |
Where the simple version breaks
The first trap is the final flush. Most bugs in this task are not in the loop, they are forgetting to emit the last run after the loop ends. The second trap is a run longer than 9. a repeated 12 times becomes a12, which is two digits. That is fine for encoding, but it makes decoding ambiguous if the original alphabet can contain digits. a12 could mean a x12, or a x1 followed by 1 x2. If the input is arbitrary text, I would not use bare char+count as a wire format. I would either restrict the alphabet, escape digits, or use a length-prefixed or binary format.
The third trap is streaming. If the string arrives in chunks, a run can continue across a chunk boundary. Keeping prev and count as state between chunks handles that, but I must not flush at the end of each chunk. Flushing early turns one run of 5 split as 2+3 into a2a3 instead of a5. In a backend service that reads from a socket or a file, that state has to live in the encoder object, not in a local variable inside the chunk handler.
Unicode is the fourth trap. Python iterates by code point, so a combining accent or an emoji made of several code points can be split. For plain ASCII logs or telemetry labels that is irrelevant. For user text, I would clarify whether the unit is a byte, a code point, or a grapheme cluster, and pick the iteration accordingly.
When I would not use run-length encoding
RLE only pays off when runs are long. On random or high-entropy data, every run has length 1, so abcd becomes a1b1c1d1, a 2x expansion. It also destroys random access. Finding the 1000th character means decoding from the start, which is why I would not use it for indexed storage. It suits cases like bitmaps, simple image masks, or log lines with long repeated fields, where the encoded form is much smaller and sequential decoding is acceptable.
If the interviewer asks for an in-place variant, I would push back on the premise. The encoded form can be longer than the input, so in-place overwriting is unsafe without a separate buffer or a size check. The clean contract is: new output string, one pass, explicit handling of empty input, single character, and runs that cross 9, 99, and chunk boundaries.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Find the longest consecutive sequence in an unsorted, duplicated list without using sorting?
Reported in Yandex Software Engineer interview experience (June 2024)
The 90-second answer
Put the values in a hash set first, then only start counting from a value whose predecessor is absent. That start is the first element of a run, so each element is visited once as part of a run and once as a failed predecessor check. Average time is O(n), extra space is O(n) for the set.
Duplicates disappear in the set, which is the whole trick here. Without deduplication, [1, 1, 1] gets counted three times and a naive loop can recount the same run for every duplicate.
def longest_consecutive(nums: list[int]) -> int:
if not nums:
return 0
present = set(nums)
best = 1
for x in present:
if x - 1 in present:
continue # x is in the middle of a run, not its start
length = 1
y = x
while y + 1 in present:
y += 1
length += 1
best = max(best, length)
return bestWorked trace
Input: [100, 4, 200, 1, 3, 2, 1]. After deduplication the set is {1, 2, 3, 4, 100, 200}.
| Candidate x | x - 1 present? | Action | Run found | best |
|---|---|---|---|---|
| 1 | no | count forward | 1, 2, 3, 4 | 4 |
| 2 | yes | skip | none | 4 |
| 3 | yes | skip | none | 4 |
| 4 | yes | skip | none | 4 |
| 100 | no | count forward | 100 | 4 |
| 200 | no | count forward | 200 | 4 |
Result: 4. Iteration order over the set does not matter, because only run starts trigger the inner loop.
Why this beats sorting here, and when it does not
Sorting costs O(n log n) time and, in Python, O(n) extra space for Timsort. The hash approach costs O(n) average time and O(n) space for the set. For n = 10 million distinct integers the set is the dominant cost, so if memory is tight or the input already fits in cache for a sort, sorting is the safer engineering choice. If the value range is small and known, for example ages or status codes in [0, 1000], a counting array indexed by value gives O(n + range) time and O(range) space and avoids hash overhead entirely.
Failure modes to name in the loop
Empty input returns 0 before the set is built. A single element returns 1. In C++ the check x + 1 overflows when x == INT_MAX, so guard that case or widen to int64_t before incrementing. Hash worst case is O(n^2) under adversarial collisions, which is why production code in Go or C++ would not hand-roll this on untrusted input without a randomized hash. The algorithm also assumes the whole list fits in memory. For a stream or a file larger than RAM, the set approach fails outright and you need external sorting or a range-partitioned pass instead.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13What are your salary expectations, and how do you handle deadlines?
Reported in Yandex Software Engineer interview experience (June 2024)
I would answer in two parts and keep both short. On salary, I give a researched range tied to level and scope, not a single number. On deadlines, I describe a concrete system I use, with an example where I moved a date early instead of missing it silently.
Salary, in the room
"Based on the level you described and current market data for senior backend roles in Moscow and remote roles in Russia, my expectation is a range, not a point. For a role with ownership of a production service, on-call, and design reviews, I would be looking at roughly 420,000 to 520,000 RUB gross per month, plus the bonus and equity components you offer. That is an illustrative range from my own research, and I would refine it once I understand the band and the review cycle. What matters to me is the total package and how progression to the next level is decided."
That phrasing does three things. It anchors to scope, so the number is defensible. It leaves room for the band to move me without me reneging. It moves the conversation to total compensation, which is where Yandex and similar employers actually negotiate. I would not name a number for a different level, a different city, or a contractor arrangement without checking current listings first, because those bands differ by a wide margin.
If pressed for a single figure, I would say: "At the midpoint of that range, around 470,000 RUB gross, I would accept if the rest of the package matches what we discussed." One number, one condition, no bluff.
Deadlines, with a trace
My rule is that a deadline is a forecast I update, not a promise I hide behind. I break work into tasks of one to three days, put the risky integration first, and keep a buffer before the external date. I tell the owner as soon as the forecast changes, with the cause and the options.
Worked example from a backend migration I owned. The external date was Friday 14 June. My plan had a 20 percent buffer, so internal target was Tuesday 11 June.
| Date | Signal | Action |
|---|---|---|
| Mon 3 June | Load test on the new read path showed p99 at 180 ms against a 100 ms budget | Moved the caching task forward, dropped a nice-to-have admin endpoint from scope |
| Wed 5 June | Forecast slipped to Thu 13 June, still inside the external date | Sent a short update: cause, new forecast, what was cut, no change to the Friday date |
| Thu 13 June | Rollout completed, rollback tested | Shipped on Friday with the buffer intact |
The point is the Wednesday message. If I had waited until Friday, the team would have had one day to react. At two days out, they had options: accept the cut, add a reviewer, or move the date with full information.
When a deadline cannot be met, I say so early, quantify the gap, and offer a trade. "We can hit Friday with the core path and defer the reporting endpoint to Monday, or hit Wednesday with everything." That is a decision for the owner, not a surprise I deliver.
I would close the salary part by asking what the band is for this level and when the first review happens, because a candidate who asks about progression and review timing sounds like someone planning to stay and grow, which is the signal this question is really testing.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Describe past technical challenges you faced and how you solved them?
Reported in Yandex Software Engineer interview experience (November 2023)
I will use a production incident from my last role, because the interviewer is really testing how I debug, not whether I can recite a definition. I was a backend engineer on an order service in Go, about 12k requests per second at peak, backed by PostgreSQL and Redis. During a deploy, we started seeing duplicate orders and a spike in p99 latency from 40 ms to over 900 ms.
What I did first
I did not start by changing code. I checked the dashboards in order: error rate by endpoint, database connections in use, slow query log, and the rate of unique constraint violations. The pattern was clear. POST /orders was returning 5xx on timeouts, clients were retrying, and each retry created a new order because the create path had no idempotency key. At the same time, a downstream inventory check had slowed from 5 ms to 300 ms, so requests held database connections longer. With a pool of 20 connections per instance, the pool saturated and latency queued behind it.
That gave me two separate problems: correctness under retry, and connection exhaustion under a slow dependency. Fixing only one would have left the other.
The fix for duplicate creates
I added an Idempotency-Key header required on POST /orders. The handler stores the key with the resulting order id and response body for 24 hours, inside the same transaction that creates the order. A retry with the same key replays the stored response instead of inserting again.
// Go 1.22, handler sketch checked against net/http
func (h *Handler) CreateOrder(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if key == "" {
writeError(w, 400, "idempotency_key_required")
return
}
order, replayed, err := h.Store.CreateIdempotent(r.Context(), key, decodeOrder(r))
if err != nil {
writeError(w, 503, "upstream_unavailable")
return
}
w.Header().Set("Location", "/orders/"+order.ID)
if replayed {
w.Header().Set("Idempotent-Replayed", "true")
}
writeJSON(w, 201, order)
}CreateIdempotent inserts into idempotency_keys(key, order_id, response, created_at) with a unique index on key. On conflict it reads the existing row. That is the whole mechanism. No distributed lock, no in-memory cache, because a cache would lose the key on a restart and recreate the bug.
The fix for the slow dependency
The inventory client had no timeout and no circuit breaker. I set a 50 ms context deadline, capped retries at one, and opened the breaker after 20 consecutive failures, half-opening after 10 seconds. Orders that could not verify inventory returned 503 with code: inventory_unavailable instead of holding a connection for 300 ms. That dropped connection hold time back under 10 ms and p99 returned to roughly 45 ms in our load test at 12k rps.
Worked trace
| Time | Event | Result |
|---|---|---|
| 0 ms | Client sends POST /orders with key 7f3c | Insert key, create order 42, return 201 |
| 800 ms | Client retries after timeout, same key 7f3c | Key found, replay order 42, return 201, no new row |
| 900 ms | Different client sends key 9a1b | New order 43 created |
| 1,000 ms | Client sends no key | Return 400 idempotency_key_required |
How I verified it
I wrote a test that fires the same request twice concurrently, not just sequentially, because the race is the point. With the unique index, one wins and the other replays. I also added metrics I could alert on: idempotent_replays_total, idempotency_conflicts_total, and pool wait time. Before the fix, duplicate order rate was about 0.4% of creates during the incident window. After, it was zero in the following two weeks, and the alert on pool wait time would have caught the slow dependency earlier.
What I would not do again
My first instinct was to add more database connections. That would have moved the bottleneck to PostgreSQL and hidden the missing timeout. The lesson I took from it: when latency and correctness break together, separate the retry path from the dependency path before tuning anything. One is a contract problem, the other is a resource problem, and they need different fixes.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Explain pass by reference versus pass by value?
Reported in Yandex Software Engineer Interview Guide 2026
The 90-second answer
Pass by value copies the argument into the parameter. The callee gets its own variable, so assignments inside the function do not change the caller's variable. Pass by reference gives the callee an alias for the caller's variable, so assignments inside the function do change it.
That definition is precise for C++ references and for languages with explicit reference parameters. In Go, Python and Java the interview usually turns on a second distinction: copying a pointer or handle to an object versus copying the object itself. A strong answer names both, because Yandex backend code in Go and C++ hits them in different places.
// Go, checked against Go 1.22
package main
import "fmt"
type Order struct {
ID int
Total int64 // kopecks
}
func addByValue(o Order, delta int64) {
o.Total += delta // changes the copy only
}
func addByPointer(o *Order, delta int64) {
o.Total += delta // changes the caller's struct through the pointer
}
func main() {
o := Order{ID: 42, Total: 1000}
addByValue(o, 250)
fmt.Println(o.Total) // 1000
addByPointer(&o, 250)
fmt.Println(o.Total) // 1250
}In C++ the same idea appears without the pointer syntax. void f(Order o) copies, void f(Order& o) aliases the caller's object, and void f(Order* o) aliases it through a pointer that can be null. Python has no reference parameters in the C++ sense. It passes a reference to an object by value. Rebinding the parameter (x = []) leaves the caller untouched. Mutating the object (x.append(...)) is visible to the caller because both names point to the same list.
| Call | What the callee receives | Callee assignment visible to caller? | Callee mutation of object visible? |
|---|---|---|---|
C++ f(Order o) | copy of the struct | No | No, it mutates the copy |
C++ f(Order& o) | alias for caller's struct | Yes | Yes |
Go f(o Order) | copy of the struct | No | No |
Go f(o *Order) | copy of the pointer, same struct | Reassigning o locally: no. Writing o.Total: yes | Yes |
Python f(x) with x a list | copy of the reference, same list | Rebinding x: no | Yes, via append or item assignment |
Python f(x) with x an int | copy of the reference, immutable object | No | No mutation exists |
Worked trace
Assume balance = 1000 and the call is add(balance, 250) where add does balance += delta.
| Step | Pass by value | Pass by reference |
|---|---|---|
| Before call | caller: balance = 1000 | caller: balance = 1000 |
| Parameter binding | new variable balance = 1000 | parameter is another name for caller's balance |
Inside add | parameter becomes 1250 | caller's balance becomes 1250 |
| After return | caller: balance = 1000 | caller: balance = 1250 |
Why it matters in backend code
Copy cost is the practical reason to pass a pointer or reference. A struct holding a 4 KiB payload copied on every request handler call costs 4 KiB of stack traffic per call. At 5,000 requests per second that is about 20 MB/s of copying before any business logic runs, plus cache pressure. Passing *Order copies 8 bytes on a 64-bit build. The trade-off is aliasing. A function that receives a pointer can change state far from where the caller expects it, and a nil pointer in Go or a null pointer in C++ turns that into a crash at the dereference site.
Two failure modes come up in review. First, the Python mutable default trap: def f(items=[]) creates one list at definition time and every call that omits the argument shares it, so state leaks between requests in a long-lived worker. Second, Go pointer receivers on a value that is also stored in an interface or a map. Taking &o works for a local variable, but a struct retrieved from a map is a copy, so (&o).Method() mutates a copy and the update is silently lost.
My default in Go is a value receiver for small, immutable structs such as an ID or a money amount, and a pointer receiver when the method mutates or when the struct carries a slice or a large payload. In C++ I prefer a const reference for read-only parameters and a non-const reference only when mutation is the documented purpose of the call. That keeps the aliasing visible at the call site instead of hiding it behind a pointer the reader has to chase.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16Explain passing a C++ vector by reference?
Reported in Yandex Software Engineer Interview Guide 2026
The 90-second answer
Passing by reference means the function receives an alias to the caller's std::vector, not a copy of its elements. The signature I reach for by default is const std::vector<T>&, which gives read-only access with no element copy and no allocation. If the function must mutate the vector in place, I drop the const. If the function needs to take ownership, I pass by value and move from it, or pass an rvalue reference. A reference does not extend lifetime, does not share ownership, and does not protect against the caller mutating or destroying the vector while the call is running.
#include <vector>
#include <cstdint>
#include <numeric>
// Read-only: no copy, caller keeps ownership.
std::int64_t total(const std::vector<std::int32_t>& v) {
return std::accumulate(v.begin(), v.end(), std::int64_t{0});
}
// Mutates in place: caller sees the change, may reallocate.
void append_batch(std::vector<std::int32_t>& v, std::int32_t x) {
v.push_back(x);
}
// Takes ownership: caller moves, no copy of elements.
void consume(std::vector<std::int32_t> v) {
// v owns the buffer now; safe to move elements out.
}
int main() {
std::vector<std::int32_t> data(1'000'000, 1);
auto s = total(data); // O(n) to read, O(1) extra memory
consume(std::move(data)); // O(1): buffer pointer transferred
}Checked against C++17 and C++20. The reference itself is typically a pointer under the hood, 8 bytes on a 64-bit build, while the vector object is 24 bytes (begin, end, capacity) and the buffer it points to is separate.
What the reference actually buys you
By value, the callee gets its own vector object and, unless the caller moves, its own copy of every element. For a vector of 1,000,000 int32_t values that is a 4 MB allocation plus 4 MB of copying before the function body runs. By const&, the callee reads the caller's buffer directly. The cost drops to the work the function does itself. That gap is why interviewers probe this: it is the difference between an accidental O(n) copy hidden in a signature and an explicit one.
| Signature | Element copy | Allocation | Caller can still mutate during call | Use when |
|---|---|---|---|---|
std::vector<T> v (by value, lvalue arg) | Yes, O(n) | Yes, usually | No, callee owns its copy | You need a mutable private copy, or you will move into it |
const std::vector<T>& v | No | No | Yes, if another thread or callback holds a non-const ref | Read-only inspection, the common case |
std::vector<T>& v | No | No | Yes, and callee mutates it | In-place update, sorting, appending |
std::vector<T>&& v | No | No | Caller gave up ownership via move | Transferring ownership without a by-value parameter |
std::span<const T> v (C++20) | No | No | Yes, same aliasing caveat | You only need contiguous elements, not vector operations like push_back |
Failure modes I would name in the loop
Lifetime. A reference is only valid while the original object lives. Returning a reference to a local vector, or storing the reference beyond the call, dangles. The compiler warns on the direct return case, but a reference stored in a struct or captured in a lambda outlives the call silently.
Invalidation. If the callee holds iterators or pointers into the vector and then calls push_back or erase on the same vector through a non-const reference, reallocation can free the buffer underneath those pointers. A trace I have seen in production: a handler receives std::vector<Request>&, stores &v[0] for a zero-copy parse, then a logging callback appends to v, the buffer moves, and the parse reads freed memory. The fix is to take the span or pointer after the last mutation, or copy the small prefix you need.
Aliasing and thread safety. const& is a promise by the callee, not a lock. If the caller mutates the vector from another thread while the callee reads it, that is a data race and undefined behaviour, even though the signature says const. In a backend service I would either pass a span over an immutable snapshot, or hand the callee a copy when concurrent mutation is expected.
When I would not use a reference
For a tiny vector, or when the function needs to sort or modify its own copy without touching the caller's data, by value with a move at the call site is clearer and the copy cost is bounded and visible. For a function that only needs to read a contiguous range, std::span<const T> in C++20 expresses that better than a vector reference, because it also accepts a raw array or a subrange and it cannot be resized through the span. I would still pick const std::vector<T>& when the callee genuinely needs vector-specific operations such as size() plus capacity checks, or when the codebase is on C++17 and span is unavailable.
So the short version: const& for reading, & for mutating in place, move for taking ownership, and treat every reference as a borrowed view whose lifetime and concurrent mutation are the caller's responsibility.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Tell me more about where, what, and how you fixed things in the project in the API or middleware?
Reported in Яндекс interview: System Design, Senior
The 90-second answer
The fix was in middleware, not in the handler. We had a Go service in front of a payment provider, and the chain was logging, auth, then a generic retry wrapper around the downstream call. The handler was correct. The wrapper retried every error, including timeouts where the provider had already taken the money, and it did so without an idempotency key. Clients saw duplicate charges and the p99 for POST /payments went from about 180 ms to 2.4 s under load because retries queued behind the same connection pool.
I moved the fix to three places in that chain. First, the retry wrapper now reads the request context deadline and stops when the client has gone away. Second, it only retries on a closed list of errors, and only for methods that are safe to replay. Third, the middleware generates and forwards an Idempotency-Key derived from the client key, so a replay returns the stored provider response instead of creating a second payment.
Where, precisely
The bug lived between the handler and the provider client. The handler returned 201 with a payment ID. The wrapper around the provider call had a fixed 3-attempt loop with 200 ms backoff and no check of ctx.Done(). When the provider took 6 s to answer, the client timed out at 2 s and retried. The server kept the first attempt running, the retry started a second attempt, and both reached the provider. Neither attempt carried a key the provider could deduplicate on.
That placement mattered for the fix. Changing the handler would not have helped, because the handler only ran once per HTTP request. The duplication happened below it, inside the call the middleware wrapped.
What the trace showed
| Time | Event | Layer |
|---|---|---|
| 0 ms | Client sends POST /payments with key k1 | Client |
| 10 ms | Middleware forwards to provider, no key attached | Retry wrapper |
| 2000 ms | Client times out, retries with same key k1 | Client |
| 2010 ms | Second request starts a second provider call | Retry wrapper |
| 6000 ms | First provider call succeeds, charge created | Provider |
| 6100 ms | Second provider call succeeds, second charge created | Provider |
| 6200 ms | Client receives two different payment IDs | Handler |
After the fix, the second request hits the idempotency store first. It finds k1 mapped to the first payment ID and replays that response. The provider sees one call.
How I fixed it
The new wrapper checks the context before each attempt, classifies errors, and refuses to retry a non-idempotent call without a key. Checked against Go 1.22:
func retryable(ctx context.Context, err error) bool {
if ctx.Err() != nil {
return false // client gone or deadline passed, stop now
}
var tmp interface{ Temporary() bool }
if errors.As(err, &tmp) {
return tmp.Temporary()
}
return false // 4xx and unknown errors are not retried
}
func withIdempotency(next http.Handler, store *Store) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := r.Header.Get("Idempotency-Key")
if key == "" {
http.Error(w, `{"code":"idempotency_key_required"}`, http.StatusBadRequest)
return
}
if resp, ok := store.Get(key); ok {
w.WriteHeader(resp.Status)
w.Write(resp.Body)
return
}
next.ServeHTTP(w, r)
})
}Two trade-offs came with this. Rejecting requests without a key breaks older clients, so we shipped it behind a header check for two weeks and logged which clients lacked one before enforcing it. And storing full responses for 24 hours costs memory, about 2 KB per key in our case, so we capped the store at 100k keys with LRU eviction and accepted that a replay after eviction could create a new payment. That window was documented for support.
Verification was a load test at 500 rps against a stub provider with 5% timeout rate. Duplicate charges dropped from 0.3% of requests to zero in the test run, and p99 returned to 210 ms because retries stopped piling onto the pool. In production we watched the same two numbers, duplicate payment IDs per idempotency key and retry count per request, for the first week after deploy.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18Could a value now return nil instead of an empty array, and are there tests for this?
Reported in Яндекс interview: System Design, Senior
The 90-second answer
Yes, that can happen in Go, and it is a breaking change at the JSON boundary even though len() and range behave the same. A nil slice and an empty slice are both length zero, but encoding/json marshals them differently: nil becomes null, empty becomes []. If a client, a stored snapshot, or a downstream service expects an array, that one byte-level difference breaks parsing or a strict schema check.
I would not merge the change until I had a test that fails on the old code for the wrong reason and passes for the right one. Concretely: a unit test on the producer that asserts non-nil, a contract test on the serialized payload, and a regression test for the exact case that used to return [].
Why it happens
In Go a slice is a header (pointer, length, capacity). A nil slice has a nil pointer. make([]T, 0) or []T{} allocates a non-nil header even at length zero. Most operations treat them alike:
// Go 1.22
func ListTags() []string {
var tags []string // nil
return tags
}
func ListTagsFixed() []string {
tags := make([]string, 0) // non-nil, len 0
return tags
}Both return len == 0 and iterate zero times. The difference shows up at serialization and at identity checks:
| Case | len | tags == nil | JSON output |
|---|---|---|---|
var tags []string | 0 | true | null |
tags := []string{} | 0 | false | [] |
tags := make([]string, 0) | 0 | false | [] |
json.Unmarshal([]byte("null"), &tags) | 0 | true | null |
json.Unmarshal([]byte("[]"), &tags) | 0 | false | [] |
That last pair matters on the read side too. If a service writes null into a database column or a cache entry and another service reads it back, the value comes back nil even if the original code path intended an empty collection.
What breaks in practice
A JavaScript client doing response.tags.map(...) throws on null. A JSON Schema with "type": "array" rejects null. A Go client that does if decoded.Tags == nil { treat as error } starts failing. None of these show up in a test that only checks len(got) == 0, which is why that assertion is not enough.
There are places where nil is fine, and I would say so explicitly in the review. If the field is internal only, never serialized, and consumers already handle nil, returning nil is idiomatic Go and saves an allocation. If the API contract documents the field as nullable, null is also defensible. The problem is a silent change to a field that was previously always an array.
The tests I would require
First, a producer test that distinguishes the two cases:
func TestListTags_EmptyNotNil(t *testing.T) {
got := ListTagsFixed()
if got == nil {
t.Fatal("expected non-nil empty slice, got nil")
}
if len(got) != 0 {
t.Fatalf("expected len 0, got %d", len(got))
}
b, err := json.Marshal(struct {
Tags []string `json:"tags"`
}{Tags: got})
if err != nil {
t.Fatal(err)
}
if string(b) != `{"tags":[]}` {
t.Fatalf("unexpected payload: %s", b)
}
}Second, a table-driven case for the boundary that triggered the report: no rows in the store, one row with no tags, one row with tags. The first two must produce the same [] payload. Third, a golden-file or contract test at the HTTP layer if this value crosses a service boundary, because a unit test on the function does not catch a DTO that reintroduces nil during mapping, for example when a mapper copies a nil slice from a database model into a response struct.
If the change is intentional, the fix is not just the test. I would update the API contract, bump the version or add a changelog entry, and check consumers. A quick grep for == nil on the decoded field and for schema validation on that path usually finds the ones that will break. If the change is unintentional, the fix is to initialize the slice at the point where the empty case is constructed, not to patch every consumer to accept null.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: