synopsis · Java for DSA · chapter 3
OOP for DSA & Design Rounds
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
A class is the blueprint, an object one instance on the heap. Instance fields: one copy per object.
staticfields: one copy per class. - template
private static class Node { int val; Node next; Node(int v) { val = v; } }inside your class: no hidden outer reference. - use it when
"Design / Implement the X class": private fields for state, a constructor, one method per operation that checks, updates, returns.
- cost
HashMap lookups are O(1) only if
hashCodespreads the keys. A constant hashCode puts every key in one bucket: up to O(n) per lookup. - trap
Override
equalswithouthashCodeand HashSet/HashMap stop finding equal keys. Override both, from the same fields. - trap
staticcounters in a design class are shared by every object the judge creates. Per-object state = instance fields. - pro tip
Pairs, cells, composite keys:
record Cell(int r, int c) {}gives equals, hashCode and toString for free (Java 16+). - pro tip
A fixed set of options (directions, states) → an enum.
==is safe on enum constants; cachevalues(). - what it is
Interfaces say what (
Deque,Map,Comparable), classes say how. Declare by interface:Deque<Integer> st = new ArrayDeque<>();
Shaky on a card? Open the chapter or flip its recall cards.