Object identity and the hash contract
Explain == vs equals() vs hashCode(). What exactly breaks in a HashMap when you override equals but not hashCode?
Must coverReflexive/symmetric/transitive/consistent contract; unequal hashCodes send equal objects to different buckets so get() returns null; mutable key fields after insert strand the entry permanently.
StudyHashMap API + implementation notes →Do a back-of-envelope capacity estimate for a service with 1M DAU, 20 requests/user/day, 500-byte records, 3-year retention. Derive QPS, peak QPS, storage, bandwidth.
Must coverKnow the latency ladder cold: L1 ~1ns, RAM ~100ns, SSD random ~100us, same-DC RTT ~0.5ms, cross-continent ~150ms. Peak = 2-3x average. Always state read:write ratio before choosing storage.
StudySystem Design Primer →What actually happens between calling setState and the DOM updating? Walk through render phase vs commit phase and automatic batching.
Must coversetState enqueues an update and schedules work; render phase is pure and interruptible, produces a new element tree, diffs it; commit phase applies mutations synchronously then runs layout effects, then paints, then passive effects. React 18 batches across promises/timeouts too.
Studyreact.dev — Render and commit →Start by separating the three. == compares references — are these the same object in memory. equals() compares logical equality — do these two objects represent the same value, and it is yours to define. hashCode() returns an int used to place the object into a bucket in hash-based collections; it is a placement function, not an equality function.
The contract binds them: if two objects are equal, they must return the same hashCode. The converse is not required — unequal objects may collide, and hash collections handle that by chaining. The full equals contract is reflexive, symmetric, transitive, consistent, and x.equals(null) is false.
Now the actual failure. Override equals without hashCode and you inherit Object.hashCode, which is identity-based. So map.put(new Key(1), "v") hashes to bucket A. Later map.get(new Key(1)) creates a different object, hashes to bucket B, HashMap searches bucket B, finds nothing, and returns null. The entry is not lost — it is sitting in bucket A, permanently unreachable and un-removable, because every lookup will compute the wrong bucket. It is simultaneously a correctness bug and a memory leak.
The second, subtler failure is mutating a key after insertion. The entry stays physically in the old bucket while the key now hashes elsewhere. Same result. This is why HashMap keys should be immutable, and why String — immutable with a cached hash — is the ideal key.
class Key {
final int id;
Key(int id) { this.id = id; }
@Override public boolean equals(Object o) { return o instanceof Key k && k.id == id; }
// hashCode deliberately NOT overridden
}
Map<Key,String> m = new HashMap<>();
m.put(new Key(1), "value");
m.get(new Key(1)); // null - equal, but a different bucket
m.containsKey(new Key(1)); // false
// correct pairing
@Override public int hashCode() { return Objects.hash(id); }Does a hashCode need to be unique?
No — it needs to be well distributed. A constant hashCode is legal and turns the map into a linked list with O(n) lookups. HashMap defends against poor hashes by spreading bits with h ^ (h >>> 16) and by converting a bucket's chain into a red-black tree at 8 entries when capacity is at least 64.
getClass() or instanceof in equals?
getClass() guarantees symmetry but breaks with proxies and Hibernate subclasses. instanceof works with proxies but needs the class to be final, otherwise a subclass adding a field breaks symmetry. For JPA entities the usual compromise is instanceof plus comparing only a stable business key.
Why is String a good key?
Immutable, so the hash cannot change after insertion; the hash is cached after first computation, so repeated lookups are cheap; and it is safely shareable across threads with no synchronization.
Do this out loud and write the numbers down — the interviewer is scoring whether you quantify before designing. Traffic: 1M DAU × 20 requests = 20M requests/day. 20M ÷ 86,400 ≈ 230 QPS average. Traffic is never flat, so apply a peak multiplier of 2–3x → ~600 QPS peak. State the multiplier as an assumption rather than hiding it.
Storage: if every request writes a 500-byte record, that is 20M × 500B = 10 GB/day. Over 3 years: 10 GB × 365 × 3 ≈ 11 TB. Add replication (×3) and indexes/overhead (roughly ×1.3) and you are budgeting for 40–45 TB. That number immediately tells you this is not a single-node database.
Bandwidth: 230 QPS × 500 B ≈ 115 KB/s average, ~350 KB/s at peak. Trivially small — which is itself the useful conclusion: bandwidth is not your constraint, storage and QPS are.
Then state the number that actually drives the design: the read:write ratio. At 100:1 reads you design around caching and read replicas. At 1:1 you design around write throughput, partitioning, and possibly an LSM-based store. Ask for it if it was not given — asking is a positive signal, not a gap.
Finally, anchor with the latency ladder so your estimates are grounded: L1 ~1 ns, main memory ~100 ns, SSD random read ~100 µs, same-datacentre round trip ~0.5 ms, cross-continent ~150 ms. A cache hit versus a cross-region call is a factor of a hundred thousand, and that is what justifies most caching decisions.
DAU 1,000,000
req/user/day 20
-> req/day 20,000,000
-> avg QPS 20e6 / 86400 = 231
-> peak QPS 231 x 3 = ~700
record 500 B
-> per day 20e6 x 500 = 10 GB/day
-> 3 years 10 x 365 x 3 = 11 TB (x3 replication, x1.3 index) = ~43 TB
bandwidth 231 x 500 = 115 KB/s (not the bottleneck)Why round so aggressively?
Because the decision you are making is "one box or a hundred", and that survives a 2x error. Precision beyond one significant figure is false confidence and wastes interview time.
Where does the peak multiplier come from?
Daily and weekly cycles. Most consumer traffic peaks 2–3x the daily average; a system with a scheduled event (payroll, market open, a flash sale) can peak 10–50x, and you must ask which kind you are designing for.
What do you do with the 43 TB number?
It rules out a single Postgres instance and forces a conversation about partitioning, retention tiering (hot 90 days, cold to object storage), and whether all of it needs to be online at all.
Answer in the two phases React actually uses. Calling setState does not update anything — it enqueues an update on the component's fiber and schedules work. Your local variable is unchanged for the rest of that function, because state is a snapshot of that render.
Render phase: React calls your component function to produce a new element tree, and diffs it against the previous one. This phase must be pure — no side effects, no mutation — because React may pause, abandon, or restart it under concurrent rendering. Nothing is on screen yet.
Commit phase: React applies the computed mutations to the DOM in one synchronous pass, then runs layout effects (useLayoutEffect, refs) before the browser paints. The browser paints. Then passive effects (useEffect) run asynchronously afterwards. That ordering is exactly why measuring layout belongs in useLayoutEffect — doing it in useEffect means you measure after paint and cause a visible flicker when you correct it.
Batching: multiple setState calls in the same tick produce one re-render. Before React 18 this only happened inside React event handlers; automatic batching now covers promises, setTimeout and native handlers too. So three setState calls in an async function now cause one render, not three.
The practical consequence worth stating: because state is a snapshot, setCount(count + 1) three times in a row increments once. Use the functional form setCount(c => c + 1) when the next value depends on the previous one.
function Counter() {
const [count, setCount] = useState(0);
function handle() {
setCount(count + 1);
setCount(count + 1); // count is still 0 in this render -> ends at 1
console.log(count); // 0 - state is a snapshot of this render
}
function handleCorrect() {
setCount(c => c + 1);
setCount(c => c + 1); // queued updaters -> ends at 2
}
}What breaks if the render phase is not pure?
Under concurrent rendering React can render, discard, and re-render. A side effect in render therefore runs an unpredictable number of times. StrictMode double-invokes components in development specifically to surface this.
Why does useEffect run after paint but useLayoutEffect before?
useEffect is deliberately deferred so it never blocks the browser from painting. useLayoutEffect runs synchronously after DOM mutation but before paint, so you can measure and adjust without the user seeing an intermediate frame — at the cost of blocking paint.
Does setState always re-render?
No. If the new value is Object.is-equal to the current one, React bails out — though it may still render once before bailing. That is also why mutating an object and setting the same reference appears to do nothing.
Count how the work grows as the input grows, ignoring constants. O(n) means doubling the input doubles the work; O(log n) means doubling the input adds one step.
n <= 20 -> O(2^n) backtracking or bitmask n <= 500 -> O(n^3) triple loop is fine n <= 5000 -> O(n^2) n <= 1e5 -> O(n log n) (sort, heap, binary search) n <= 1e7 -> O(n) only # ~1e8 simple operations runs in about a second. # Read the constraint FIRST - it tells you the intended complexity.
The order-of-magnitude cost of every operation a system can do. Every capacity estimate and every architecture argument is built on these numbers.
L1 cache reference 0.5 ns Branch mispredict 5 ns L2 cache reference 7 ns Mutex lock/unlock 25 ns Main memory reference 100 ns <- 200x L1 Compress 1KB with Snappy 3,000 ns Send 1KB over 1 Gbps net 10,000 ns SSD random read 150,000 ns <- 1,500x RAM Read 1MB sequentially from RAM 250,000 ns Round trip within same DC 500,000 ns = 0.5 ms Read 1MB sequentially from SSD 1,000,000 ns = 1 ms Disk seek (spinning) 10,000,000 ns = 10 ms Read 1MB from disk 20,000,000 ns = 20 ms Packet India -> US -> India 150,000,000 ns = 150 ms THE RATIOS THAT MATTER RAM is ~1000x faster than SSD Same-DC network is ~5x slower than SSD read Cross-continent is ~300x a same-DC round trip -> this is why you cache, and why you do not go cross-region per request