LLD / Java / OOP Interview Questions Bank
Overview
Part of the Interview Prep series. Dotted-underline words are glossary terms: hover for the meaning or open the Glossary. Track your progress on the Interview Prep tracker. Series index: Start here.
Part A: 60 conceptual questions with crisp answers. Part B: 30 LLD problems with difficulty and patterns.
Part A: Conceptual Q&A
OOP and design principles
- Abstract class vs interface? Interface: contract/capability, multiple implementation, no instance state (default/static methods allowed). Abstract class: shared state + partial implementation, single inheritance. Start with an interface; add an abstract skeleton (
AbstractX) if sharing code. - Overloading vs overriding? Overloading: same name, different params, resolved at compile time. Overriding: subclass redefines inherited method, resolved at runtime (dynamic dispatch); same signature, covariant return allowed, no narrower access, no broader checked exceptions.
- Composition vs inheritance? Prefer composition: runtime flexibility, no fragile base class, better testing. Inheritance only for genuine is-a honoring LSP.
- Explain each SOLID letter with a smell. S: class with many reasons to change. O:
if/elseon type. L: override throwsUnsupportedOperationException. I: stub methods in implementors. D:new ConcreteX()inside business class. - What is Liskov violation example?
Square extends RectanglewheresetWidthalso changes height; orFixedDeposit.withdraw()throwing. Callers using the base type break. - DI vs DIP vs IoC? DIP: principle (depend on abstractions). DI: technique (pass dependencies in). IoC: framework controls object creation/wiring (Spring).
- Tell, Don't Ask / Law of Demeter? Ask objects to do work rather than reading their state to decide externally; only talk to immediate collaborators (
a.b().c().d()is a smell). - Cohesion and coupling? Aim high cohesion (focused class), low coupling (few abstract dependencies).
- Association, aggregation, composition? Uses; has-a with independent life; owns with same lifetime (delete parent -> delete child).
- Immutable object: how to build?
finalclass,private finalfields, no setters, defensive copies of mutable inputs/outputs, nothisescape. Benefits: thread-safe, cache/hash-key safe. - Why override
equalsandhashCodetogether? Contract: equal objects must have equal hashes, elseHashMap/HashSetbreak. Use value-based fields; make keys immutable. - Value object vs entity? Value object: no identity, immutable, equality by value (
Money). Entity: identity + lifecycle (Account). - Why not
doublefor money? Binary floating point can't represent 0.1 exactly. UseBigDecimal(with scale +RoundingMode) or integer minor units (longpaise); store currency with amount. - What is an anemic domain model and why avoid? Entities with only getters/setters and logic in services; loses encapsulation and invariants. Put behavior with data.
- YAGNI vs extensibility? Build for stated requirements; place interfaces at known volatility points; describe, don't build, other extensions.
- Checked vs unchecked exceptions in domain design? Checked for recoverable business failures the caller must handle (
InsufficientFundsException); unchecked for programming errors/invalid args. Never swallow; preserve cause; no exceptions for control flow in hot paths. - Why favor
Optionalreturn over null? Makes absence explicit; don't use it for fields/params. - What is the Open/Closed principle in practice? Add a new class implementing an interface and register it; no edits to existing tested code.
Design patterns
- Strategy vs State? Both delegate to a polymorphic object. Strategy: client chooses interchangeable algorithms, strategies don't know each other. State: the context transitions between states itself; states know the next states.
- Factory vs Abstract Factory vs Builder? Factory: creates one product by input. Abstract Factory: families of related products. Builder: assembles one complex object step by step.
- Decorator vs Proxy vs Adapter vs Facade? Decorator adds behavior (same interface). Proxy controls access (same interface). Adapter converts interface. Facade simplifies a subsystem with a new, simpler interface.
- Observer vs Pub-Sub? Observer: subject holds direct references to observers (in-process). Pub-Sub: broker/topic decouples publisher from subscriber (often async, cross-process).
- Thread-safe Singleton options? Enum; static holder (lazy, lock-free); eager static final; DCL with
volatile. Mention reflection/serialization (enum immune), testability cost, prefer DI. - Why
volatilein DCL? Without it, object construction can be reordered so another thread sees a non-null but partially constructed instance. - Command pattern use? Request as object: queue, log, retry, undo/redo. Needs
execute/undo. - Chain of Responsibility use? Pipeline of handlers, each handles or forwards: validators, middleware, ATM note dispensing, logger levels.
- Template Method vs Strategy? Template: inheritance, fixed skeleton, vary steps (compile-time). Strategy: composition, swap whole algorithm at runtime.
- When is Singleton an anti-pattern? Hidden global state, hard to mock, concurrency/lifecycle issues, couples classes. Use only for stateless/shared infra; otherwise inject a single instance.
- Visitor: when? Adding operations over a stable class hierarchy without modifying it (AST, tax rules by item type). Cost: adding new element types is hard.
- Repository vs DAO? DAO is table/CRUD oriented; Repository is collection-like over aggregates in domain language. Practically similar.
- Flyweight / Prototype / Memento: one-liners? Flyweight: share immutable intrinsic state (chess pieces, glyphs). Prototype: clone existing object. Memento: snapshot state for undo.
- What is dependency injection types? Constructor (preferred, immutable, required deps), setter (optional), interface/field (avoid).
Java and collections
- HashMap internals? Array of buckets,
hash(key) & (n-1), collisions as linked list -> tree (>=8, Java 8). Resize at load 0.75, doubling. Average O(1); not thread-safe. - HashMap vs ConcurrentHashMap vs Hashtable vs synchronizedMap? HashMap: fast, unsafe. Hashtable: whole-table lock, legacy. synchronizedMap: one mutex, compound ops still need external sync. CHM: CAS + per-bin locks, atomic
compute/merge, no nulls. - LinkedHashMap for LRU?
new LinkedHashMap(cap, 0.75f, true)withremoveEldestEntryreturningsize() > cap; access-order. O(1). Manual alternative: HashMap + doubly linked list. - ArrayList vs LinkedList? ArrayList: O(1) random access, amortized O(1) append, cache-friendly. LinkedList: O(1) insert at known node, O(n) index; rarely better; use
ArrayDequefor queues. - PriorityQueue complexity and ordering? Binary heap: offer/poll O(log n), peek O(1); iteration order not sorted. Needs
ComparableorComparator; not thread-safe (usePriorityBlockingQueue). - TreeMap use? Red-black tree, sorted keys, O(log n);
floorKey/ceilingKey/subMapfor range queries (e.g., interval/slab pricing). finalvsfinallyvsfinalize? Constant/non-overridable; always-run cleanup block; deprecated GC hook (use try-with-resources/Cleaner).- String immutability and why? Safe sharing, hash caching, security, string pool. Use
StringBuilderfor concatenation loops. - Streams: pitfalls? Don't mutate external state in lambdas, avoid parallel streams for small/IO tasks, don't reuse a stream,
Collectors.toMapthrows on duplicate keys. - Generics:
? extendsvs? super? PECS: Producer Extends, Consumer Super. Type erasure: nonew T(), no generic arrays. - Equality:
==vsequals?BigDecimal.equalsgotcha?==reference.new BigDecimal("1.0").equals(new BigDecimal("1.00"))is false (scale differs); usecompareTo. - Functional interfaces and lambdas in design?
Supplier/Function/Predicatemake strategies and callbacks terse; single-method interface = lambda target. - Serializable /
transient/serialVersionUID? Marker for Java serialization;transientskips field; setserialVersionUIDto control compat. Prefer JSON/Protobuf for APIs.
Concurrency
- synchronized vs ReentrantLock? synchronized: simple, auto-release. Lock: tryLock/timeouts, interruptible, fair, multiple Conditions, manual unlock in
finally. - volatile vs atomic vs synchronized? volatile: visibility only. Atomic: lock-free single-variable atomic ops (CAS). synchronized: compound atomicity + visibility.
- How does deadlock occur and how to prevent? Circular wait on locks. Fix: global lock ordering,
tryLock+ back-off, fewer locks, lock-free structures, one lock per transfer in DB with orderedFOR UPDATE. - Race condition vs data race? Data race: unsynchronized conflicting accesses. Race condition: outcome depends on timing (check-then-act), possible even with atomic ops.
- How do you make a wallet debit thread-safe? Per-wallet lock around check+update, or CAS loop on an
AtomicLong, or DB conditionalUPDATE ... WHERE balance >= :amt. Transfers: ordered double-locking. - Optimistic vs pessimistic locking? Optimistic: version check at commit, retry on conflict (low contention). Pessimistic: lock upfront (high contention, must not fail).
- ReadWriteLock when? Read-mostly data (config, rate cache). Not useful when writes are frequent or reads are trivially short.
- Thread pool sizing? CPU-bound: ~cores. I/O-bound: cores x (1 + wait/compute). Use bounded queues and a rejection policy; separate pools per workload (bulkheads).
- What does
ConcurrentHashMap.computeIfAbsentguarantee? The mapping function runs at most once per key atomically; it must be short and not touch the map. - BlockingQueue use cases? Producer-consumer, work queues, back-pressure via bounded capacity; poison pill for shutdown.
- CompletableFuture vs Future? Future blocks on
get(). CF composes callbacks (thenApply/thenCompose/allOf/exceptionally) and completes manually. - What is idempotency and how to implement? Same request repeated yields the same effect. Idempotency key + atomic claim (DB unique constraint /
putIfAbsent) + stored response; dedupe at-least-once messages. - ThreadLocal pitfalls? Leaks in pools if not
remove()d; don't rely on it for business state. - Semaphore vs CountDownLatch vs CyclicBarrier? Semaphore: N permits (throttle). Latch: one-shot wait for N events. Barrier: reusable rendezvous of N threads.
- Happens-before examples? unlock -> subsequent lock; volatile write -> subsequent read;
Thread.start-> thread actions; thread end ->joinreturn;Future.getafter task completion.
System-flavored LLD questions
- How do you ensure a payment isn't charged twice? Idempotency key, unique DB constraint, state machine preventing re-capture, outbox/ledger reconciliation.
- How to model money movement? Double-entry ledger (debit one account, credit another, sums to zero), immutable transaction rows, balances derived or updated atomically with the entry.
- Handling partial failure in multi-step payment? Saga/compensation (release hold, refund), status states (PENDING/SUCCESS/FAILED/UNKNOWN), retries with idempotency, reconciliation job for UNKNOWN.
- Where do you put retries and timeouts? At the gateway adapter (Decorator/Proxy) with exponential back-off + jitter, circuit breaker; only retry idempotent operations.
- How would you make the in-memory design persistent/distributed? Repository interface -> DB; unique constraints and conditional updates for atomicity; distributed locks (Redis/DB) sparingly; partition by account id; outbox for events.
Part B: 30 LLD Problems
Difficulty: E easy, M medium, H hard (for a 60-min round). Files in this folder cover the first 14.
| # | Problem | Diff | Key patterns / concepts | Doc |
|---|---|---|---|---|
| 1 | Parking Lot | M | Strategy (pricing, slot allocation), Factory (vehicle), Singleton, State | 01-parking-lot.md |
| 2 | ATM | M | State, Chain of Responsibility (cash dispenser), Command, Facade | 02-atm.md |
| 3 | Splitwise (expense sharing) | M | Strategy (split types), Observer, simplify-debts graph | 03-splitwise.md |
| 4 | Digital Wallet | M | Repository, Command/ledger, concurrency (ordered locks), idempotency | 04-digital-wallet.md |
| 5 | Vending Machine | E-M | State, Factory, Inventory | 05-vending-machine.md |
| 6 | Payment Gateway / Routing | H | Strategy (routing), Chain, Adapter, Circuit breaker, State | 06-payment-gateway-routing.md |
| 7 | Rate Limiter | M | Strategy (token bucket, sliding window), Factory, concurrency | 07-rate-limiter.md |
| 8 | LRU / LFU Cache | M | HashMap + DLL, Strategy (eviction), generics, thread safety | 08-lru-lfu-cache.md |
| 9 | Elevator System | H | State, Strategy (scheduling), Observer, Command | 09-elevator-system.md |
| 10 | BookMyShow | M-H | Concurrency (seat locking), Repository, Strategy (pricing), Observer | 10-bookmyshow.md |
| 11 | Notification Service | M | Strategy/Factory (channels), Observer, Chain (retry), Template | 11-notification-service.md |
| 12 | Logger Framework | M | Singleton, Chain of Responsibility, Strategy (appenders), Decorator/Factory | 12-logger-framework.md |
| 13 | Pub-Sub / Message Queue | H | Observer, BlockingQueue, concurrency, consumer groups | 13-pub-sub.md |
| 14 | Hotel Booking | M | Strategy, Repository, date-range overlap, concurrency | 14-hotel-booking.md |
| 15 | Library Management | E-M | Observer (due alerts), Factory, Strategy (fines) | - |
| 16 | Tic-Tac-Toe / Chess | E / H | Strategy (player), State, Command (undo), polymorphic pieces | - |
| 17 | Snake and Ladder | E | Strategy (dice), Factory, queue of players | - |
| 18 | Food Delivery (Swiggy/Zomato) | H | Strategy (matching), Observer, State (order), Repository | - |
| 19 | Ride Sharing (Uber/Ola) | H | Strategy (driver match, pricing), State, Observer | - |
| 20 | Stock Exchange / Order Book | H | PriorityQueue matching, Observer, Command, concurrency | - |
| 21 | Online Shopping Cart / E-commerce | M | Builder, Strategy (discounts), Decorator (coupons), State | - |
| 22 | Cab/Hotel/Flight Search Aggregator | M | Strategy (filter/sort), Adapter (providers), CompletableFuture | - |
| 23 | Chat Application (WhatsApp) | M-H | Observer, Repository, Mediator, State (delivery status) | - |
| 24 | URL Shortener | E-M | Strategy (ID gen), Repository, base62, concurrency (counter) | - |
| 25 | Task Scheduler / Cron | H | PriorityQueue/DelayQueue, Command, ScheduledExecutor | - |
| 26 | In-memory Key-Value Store / Redis-lite | M | TTL, Strategy (eviction), Command (transactions), ReadWriteLock | - |
| 27 | Coupon / Reward / Loyalty Engine | M | Chain/Specification, Strategy, Decorator, Rule engine | - |
| 28 | Credit Card Management / Statement | M | State (card), Strategy (interest), Observer, BigDecimal | - |
| 29 | UPI Payment System (NPCI-style) | H | Facade, Adapter (banks), State, Command, idempotency, Saga | - |
| 30 | Ledger / Double-Entry Accounting | H | Command, Repository, immutability, ordered locking, idempotency | - |
Fintech-targeted shortlist (Visa/Mastercard/NPCI/Amex/PayU): 4, 6, 7, 29, 30, 28, 2, 3, 27, 8, 11. Prepare these with concurrency + idempotency angles.
Common follow-ups on any problem: "make it thread-safe", "add a new type X", "how to persist", "how to scale to many nodes", "how to test it", "what if two requests arrive together", "how to handle failure midway".