KatInterview

Bits, Cache Eviction, and Vertex Degrees: Fundamentals Under Pressure

Data Structure DesignModel answer
MediumModel answerData Structure Designbit-manipulationcachinggraphs

Last 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.

  1. State the eviction rule for LRU and for LFU (including how ties are broken).
  2. Describe a realistic access pattern where LRU clearly beats LFU, and explain the failure mode.
  3. 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.

  1. Define in-degree and out-degree of a vertex.
  2. Given an adjacency matrix, what is the time cost to compute the in-degree of one vertex v?
  3. 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.