Bits, Cache Eviction, and Vertex Degrees: Fundamentals Under Pressure
Data Structure DesignModel answerLast updated
Explain two's-complement shifts, compare LRU vs LFU eviction with trade-offs, and derive in-degree query costs across graph representations.
This is a rapid-fire fundamentals check with three independent parts. Answer each precisely and call out the edge cases that separate a careful engineer from a careless one.
Part 1 — Signedness and right shifts. For a 32-bit word, how does interpreting the top bit differ between an unsigned and a two's-complement signed value? Then: when the CPU right-shifts that word, how does the fill-in behavior differ between the signed and unsigned interpretation, and what does that mean for your source code in languages like C/C++, Java, or Python?
Part 2 — Cache eviction. You are building an in-memory cache for a latency-sensitive trading service.
- State the eviction rule for LRU and for LFU (including how ties are broken).
- Describe a realistic access pattern where LRU clearly beats LFU, and explain the failure mode.
- Compare the metadata overhead: per-entry storage, asymptotic cost of
get/put, and implementation complexity.
Part 3 — Directed graph degrees.
Let G = (V, E) be a directed graph.
- Define in-degree and out-degree of a vertex.
- Given an adjacency matrix, what is the time cost to compute the in-degree of one vertex
v? - Given an adjacency list, what is the cost? State your assumption about which direction the lists store, and say how the answer changes if you maintain extra structure.
The interviewer expects short, exact answers plus awareness of pitfalls (overflow, undefined behavior, stale counters, self-loops).
Hints
Hint 1
Two's complement makes the top bit carry weight −2^31; think about what that implies for the fill bits of a right shift.
Hint 2
For LFU, ask what happens when the popular keys change over time — counters only ever grow.
Hint 3
In-degree from an out-adjacency list is a full sweep of every edge; from a matrix it is a single column scan.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Two's complement and shift semantics
Interpretation of the top bit. In an unsigned 32-bit word every bit has positive weight, so bit 31 is worth +2^31 and the range is 0 … 2^32−1. In a signed two's-complement word the same bit is worth −2^31 while bits 0–30 keep positive weights, giving the range −2^31 … 2^31−1. The bit pattern is identical; only the meaning changes. That is the whole point of two's complement: add, subtract and multiply produce the same wire result, so one ALU serves both types. Only comparisons, division, widening conversions and right shifts must consult the type. Concretely, 0xFFFFFFFF reads as 4294967295 unsigned and −1 signed.
Right shift. A logical shift (x86 SHR) inserts zeros at the top; an arithmetic shift (x86 SAR) replicates the sign bit. So 0x80000000 >> 1 is 0x40000000 unsigned but 0xC0000000 signed. Language-level details worth mentioning:
- In C and C++, right-shifting a negative signed value was implementation-defined before C++20/C23; every mainstream compiler emitted an arithmetic shift anyway, and both standards now mandate it.
- Java and JavaScript make the distinction explicit:
>>is arithmetic,>>>is logical. - An arithmetic shift is floor division, not truncation.
−7 >> 1 == −4, but−7 / 2 == −3in C and Java. - Shifting by the width or more is undefined in C; left-shifting a signed value into the sign bit was also UB before C++20.
- Python ints are arbitrary precision, so
>>is always arithmetic and never overflows. For a 32-bit logical shift, mask first:(x & 0xFFFFFFFF) >> k. To emulate arithmetic on a masked value, sign-extend after shifting or subtract2^32when bit 31 is set.
Part 2: LRU versus LFU
Eviction rules. LRU evicts the key whose most recent access is furthest in the past — it bets on temporal locality. LFU evicts the key with the smallest access counter; ties are broken by recency (least recently used among the minimum-frequency set) so the policy is deterministic.
Where LRU wins. Suppose the cache holds order-book snapshots. In the morning, symbols A–J are hammered and each accumulates thousands of hits. At midday an index rebalance shifts all flow to a fresh set K–T. Under LFU, A–J retain their enormous counters and squat in the cache even though they are never read again, while every new symbol arrives with count 1 and is evicted by the next arrival. Hit rate collapses — this is cache pollution, and it is the classic LFU pathology because counters only grow. LRU lets A–J age out naturally, adapting within one cache-capacity worth of accesses. The mirror-image case favors LFU: a one-pass scan over thousands of cold keys will flush an LRU cache but barely disturb LFU, which is why production systems use hybrids such as W-TinyLFU, or add counter decay/windowed counting.
Metadata trade-offs. Both policies are O(n) space over n live entries, but constants differ.
| Policy | Structure | get/put | Per-entry overhead |
|---|---|---|---|
| LRU | hash map + doubly linked list | O(1) | two pointers, intrusive list nodes |
| LFU, naive | hash map + min-heap keyed by (freq, time) | O(log n) | counter + heap index |
| LFU, tuned | hash map + freq → doubly linked list buckets + min_freq pointer | O(1) | counter + two pointers |
The tuned LFU achieves O(1) because frequencies move by exactly one per access, so a key migrates to the adjacent bucket. But it keeps an extra map of buckets and a min_freq invariant to maintain, and the aging machinery on top. In a latency-critical service that extra indirection is real cost: more cache lines touched per operation, more code on the hot path, and more ways to get it subtly wrong. LRU is nearly always the right default; reach for LFU only with evidence of stable popularity skew.
Edge cases: capacity 0 stores nothing; put on an existing key should count as an access; an LRU-tie component keeps LFU from evicting arbitrarily among equal counts.
Part 3: Directed graph degrees
Definitions. For v ∈ V, in-degree is the count of edges (u, v) entering v; out-degree is the count of edges (v, w) leaving it. Globally Σ in-deg = Σ out-deg = |E|, which is a useful sanity check.
Adjacency matrix. With M[u][v] = 1 meaning an edge u → v, the in-degree of v is the sum of column v, which is Θ(V) regardless of edge count. Out-degree (row sum) is likewise Θ(V).
Adjacency list. Assume the standard layout where each vertex holds its outgoing neighbors. Out-degree is O(1) if the list stores its length, otherwise O(out-deg(v)). In-degree requires scanning every vertex's list, because v may appear anywhere: O(V + E). Computing all in-degrees in one pass is exactly the initialization step of Kahn's topological sort. If you also maintain a reverse adjacency list or a per-vertex in-degree counter, the query drops to O(1) at the cost of roughly doubling edge storage and updating the counter on every edge insert or delete.
Self-loops and multigraphs. A self-loop contributes once to both in-degree and out-degree of its endpoint. In a matrix for a multigraph, store counts rather than 0/1 so parallel edges and loops are counted correctly.