vishal maurya

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

  1. 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.
  2. 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.
  3. Composition vs inheritance? Prefer composition: runtime flexibility, no fragile base class, better testing. Inheritance only for genuine is-a honoring LSP.
  4. Explain each SOLID letter with a smell. S: class with many reasons to change. O: if/else on type. L: override throws UnsupportedOperationException. I: stub methods in implementors. D: new ConcreteX() inside business class.
  5. What is Liskov violation example? Square extends Rectangle where setWidth also changes height; or FixedDeposit.withdraw() throwing. Callers using the base type break.
  6. DI vs DIP vs IoC? DIP: principle (depend on abstractions). DI: technique (pass dependencies in). IoC: framework controls object creation/wiring (Spring).
  7. 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).
  8. Cohesion and coupling? Aim high cohesion (focused class), low coupling (few abstract dependencies).
  9. Association, aggregation, composition? Uses; has-a with independent life; owns with same lifetime (delete parent -> delete child).
  10. Immutable object: how to build? final class, private final fields, no setters, defensive copies of mutable inputs/outputs, no this escape. Benefits: thread-safe, cache/hash-key safe.
  11. Why override equals and hashCode together? Contract: equal objects must have equal hashes, else HashMap/HashSet break. Use value-based fields; make keys immutable.
  12. Value object vs entity? Value object: no identity, immutable, equality by value (Money). Entity: identity + lifecycle (Account).
  13. Why not double for money? Binary floating point can't represent 0.1 exactly. Use BigDecimal (with scale + RoundingMode) or integer minor units (long paise); store currency with amount.
  14. 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.
  15. YAGNI vs extensibility? Build for stated requirements; place interfaces at known volatility points; describe, don't build, other extensions.
  16. 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.
  17. Why favor Optional return over null? Makes absence explicit; don't use it for fields/params.
  18. 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

  1. 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.
  2. 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.
  3. 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.
  4. 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).
  5. 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.
  6. Why volatile in DCL? Without it, object construction can be reordered so another thread sees a non-null but partially constructed instance.
  7. Command pattern use? Request as object: queue, log, retry, undo/redo. Needs execute/undo.
  8. Chain of Responsibility use? Pipeline of handlers, each handles or forwards: validators, middleware, ATM note dispensing, logger levels.
  9. Template Method vs Strategy? Template: inheritance, fixed skeleton, vary steps (compile-time). Strategy: composition, swap whole algorithm at runtime.
  10. 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.
  11. 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.
  12. Repository vs DAO? DAO is table/CRUD oriented; Repository is collection-like over aggregates in domain language. Practically similar.
  13. Flyweight / Prototype / Memento: one-liners? Flyweight: share immutable intrinsic state (chess pieces, glyphs). Prototype: clone existing object. Memento: snapshot state for undo.
  14. What is dependency injection types? Constructor (preferred, immutable, required deps), setter (optional), interface/field (avoid).

Java and collections

  1. 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.
  2. 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.
  3. LinkedHashMap for LRU? new LinkedHashMap(cap, 0.75f, true) with removeEldestEntry returning size() > cap; access-order. O(1). Manual alternative: HashMap + doubly linked list.
  4. 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 ArrayDeque for queues.
  5. PriorityQueue complexity and ordering? Binary heap: offer/poll O(log n), peek O(1); iteration order not sorted. Needs Comparable or Comparator; not thread-safe (use PriorityBlockingQueue).
  6. TreeMap use? Red-black tree, sorted keys, O(log n); floorKey/ceilingKey/subMap for range queries (e.g., interval/slab pricing).
  7. final vs finally vs finalize? Constant/non-overridable; always-run cleanup block; deprecated GC hook (use try-with-resources/Cleaner).
  8. String immutability and why? Safe sharing, hash caching, security, string pool. Use StringBuilder for concatenation loops.
  9. Streams: pitfalls? Don't mutate external state in lambdas, avoid parallel streams for small/IO tasks, don't reuse a stream, Collectors.toMap throws on duplicate keys.
  10. Generics: ? extends vs ? super? PECS: Producer Extends, Consumer Super. Type erasure: no new T(), no generic arrays.
  11. Equality: == vs equals? BigDecimal.equals gotcha? == reference. new BigDecimal("1.0").equals(new BigDecimal("1.00")) is false (scale differs); use compareTo.
  12. Functional interfaces and lambdas in design? Supplier/Function/Predicate make strategies and callbacks terse; single-method interface = lambda target.
  13. Serializable / transient / serialVersionUID? Marker for Java serialization; transient skips field; set serialVersionUID to control compat. Prefer JSON/Protobuf for APIs.

Concurrency

  1. synchronized vs ReentrantLock? synchronized: simple, auto-release. Lock: tryLock/timeouts, interruptible, fair, multiple Conditions, manual unlock in finally.
  2. volatile vs atomic vs synchronized? volatile: visibility only. Atomic: lock-free single-variable atomic ops (CAS). synchronized: compound atomicity + visibility.
  3. 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 ordered FOR UPDATE.
  4. Race condition vs data race? Data race: unsynchronized conflicting accesses. Race condition: outcome depends on timing (check-then-act), possible even with atomic ops.
  5. How do you make a wallet debit thread-safe? Per-wallet lock around check+update, or CAS loop on an AtomicLong, or DB conditional UPDATE ... WHERE balance >= :amt. Transfers: ordered double-locking.
  6. Optimistic vs pessimistic locking? Optimistic: version check at commit, retry on conflict (low contention). Pessimistic: lock upfront (high contention, must not fail).
  7. ReadWriteLock when? Read-mostly data (config, rate cache). Not useful when writes are frequent or reads are trivially short.
  8. 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).
  9. What does ConcurrentHashMap.computeIfAbsent guarantee? The mapping function runs at most once per key atomically; it must be short and not touch the map.
  10. BlockingQueue use cases? Producer-consumer, work queues, back-pressure via bounded capacity; poison pill for shutdown.
  11. CompletableFuture vs Future? Future blocks on get(). CF composes callbacks (thenApply/thenCompose/allOf/exceptionally) and completes manually.
  12. 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.
  13. ThreadLocal pitfalls? Leaks in pools if not remove()d; don't rely on it for business state.
  14. Semaphore vs CountDownLatch vs CyclicBarrier? Semaphore: N permits (throttle). Latch: one-shot wait for N events. Barrier: reusable rendezvous of N threads.
  15. Happens-before examples? unlock -> subsequent lock; volatile write -> subsequent read; Thread.start -> thread actions; thread end -> join return; Future.get after task completion.

System-flavored LLD questions

  1. How do you ensure a payment isn't charged twice? Idempotency key, unique DB constraint, state machine preventing re-capture, outbox/ledger reconciliation.
  2. 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.
  3. 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.
  4. Where do you put retries and timeouts? At the gateway adapter (Decorator/Proxy) with exponential back-off + jitter, circuit breaker; only retry idempotent operations.
  5. 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.

#ProblemDiffKey patterns / conceptsDoc
1Parking LotMStrategy (pricing, slot allocation), Factory (vehicle), Singleton, State01-parking-lot.md
2ATMMState, Chain of Responsibility (cash dispenser), Command, Facade02-atm.md
3Splitwise (expense sharing)MStrategy (split types), Observer, simplify-debts graph03-splitwise.md
4Digital WalletMRepository, Command/ledger, concurrency (ordered locks), idempotency04-digital-wallet.md
5Vending MachineE-MState, Factory, Inventory05-vending-machine.md
6Payment Gateway / RoutingHStrategy (routing), Chain, Adapter, Circuit breaker, State06-payment-gateway-routing.md
7Rate LimiterMStrategy (token bucket, sliding window), Factory, concurrency07-rate-limiter.md
8LRU / LFU CacheMHashMap + DLL, Strategy (eviction), generics, thread safety08-lru-lfu-cache.md
9Elevator SystemHState, Strategy (scheduling), Observer, Command09-elevator-system.md
10BookMyShowM-HConcurrency (seat locking), Repository, Strategy (pricing), Observer10-bookmyshow.md
11Notification ServiceMStrategy/Factory (channels), Observer, Chain (retry), Template11-notification-service.md
12Logger FrameworkMSingleton, Chain of Responsibility, Strategy (appenders), Decorator/Factory12-logger-framework.md
13Pub-Sub / Message QueueHObserver, BlockingQueue, concurrency, consumer groups13-pub-sub.md
14Hotel BookingMStrategy, Repository, date-range overlap, concurrency14-hotel-booking.md
15Library ManagementE-MObserver (due alerts), Factory, Strategy (fines)-
16Tic-Tac-Toe / ChessE / HStrategy (player), State, Command (undo), polymorphic pieces-
17Snake and LadderEStrategy (dice), Factory, queue of players-
18Food Delivery (Swiggy/Zomato)HStrategy (matching), Observer, State (order), Repository-
19Ride Sharing (Uber/Ola)HStrategy (driver match, pricing), State, Observer-
20Stock Exchange / Order BookHPriorityQueue matching, Observer, Command, concurrency-
21Online Shopping Cart / E-commerceMBuilder, Strategy (discounts), Decorator (coupons), State-
22Cab/Hotel/Flight Search AggregatorMStrategy (filter/sort), Adapter (providers), CompletableFuture-
23Chat Application (WhatsApp)M-HObserver, Repository, Mediator, State (delivery status)-
24URL ShortenerE-MStrategy (ID gen), Repository, base62, concurrency (counter)-
25Task Scheduler / CronHPriorityQueue/DelayQueue, Command, ScheduledExecutor-
26In-memory Key-Value Store / Redis-liteMTTL, Strategy (eviction), Command (transactions), ReadWriteLock-
27Coupon / Reward / Loyalty EngineMChain/Specification, Strategy, Decorator, Rule engine-
28Credit Card Management / StatementMState (card), Strategy (interest), Observer, BigDecimal-
29UPI Payment System (NPCI-style)HFacade, Adapter (banks), State, Command, idempotency, Saga-
30Ledger / Double-Entry AccountingHCommand, 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".