A useful interview answer has three parts: the concept, the consequence, and a situation where a tempting shortcut fails. Rehearse these answers in your own words.
Object-oriented design
1. What does encapsulation protect?
Model answer: Encapsulation puts state changes behind operations that preserve invariants. A loan service exposes borrowing and returning rather than a writable availability flag.
Counterexample: Public setters for every field can still permit impossible combinations.
Follow-up: Where would you validate a transfer between two accounts?
2. How is abstraction different?
Model answer: Abstraction exposes needed behavior while hiding mechanisms. A payment interface offers charging without exposing connection pools. Encapsulation protects state; abstraction chooses the external vocabulary.
Counterexample: An interface that requires vendor-specific tokens leaks its implementation.
Follow-up: Which errors belong in the public contract?
3. When should composition replace inheritance?
Model answer: Use composition when behavior varies independently of identity: inject a parking allocation function instead of subclassing the whole lot. Inheritance fits a stable substitutable relationship, not merely shared implementation.
Counterexample: A square that inherits mutable rectangle width and height can break caller expectations.
Follow-up: What invariant makes substitution safe?
4. What is runtime polymorphism?
Model answer: A common operation dispatches to the receiver’s concrete implementation, such as email or SMS delivery. Overriding differs from signature overloading. Oracle demonstrates this in its polymorphism tutorial.
Counterexample: Switching on type names in every caller centralizes variation poorly.
Follow-up: How would you test a sender without sending a message?
5. What does dependency inversion buy?
Model answer: Business policy depends on a small capability contract rather than constructing infrastructure clients. Injected clocks make expiry tests deterministic; injected storage permits failure simulation.
Counterexample: An interface with fifty unrelated methods adds coupling despite its abstraction.
Follow-up: When is a function sufficient instead of an interface?
6. What is a useful single responsibility?
Model answer: Keep together behavior that changes for the same business reason. Lending rules and loan state belong together; receipt formatting changes separately.
Counterexample: Splitting each field into a separate service makes one invariant harder to enforce.
Follow-up: What evidence would justify extracting a component?
Database management
7. Why distinguish primary and foreign keys?
Model answer: A primary key identifies a row; a foreign key constrains a relationship. A loan needs its own identity plus member and copy references.
Counterexample: A member's display name is neither necessarily unique nor stable.
Follow-up: Should deleting a member delete loan history?
8. What problem does normalization solve?
Model answer: Normalization separates facts according to dependencies, avoiding inconsistent repeated updates. Store titles separately from physical copies. Denormalization can improve measured read performance but requires maintaining duplicated facts consistently.
Counterexample: Repeating a publisher address in every loan creates update anomalies.
Follow-up: What would you deliberately duplicate in an analytics table?
9. Explain ACID with a concrete operation.
Model answer: For a transfer, atomicity groups debit and credit; consistency preserves invariants; isolation controls concurrent observations; durability retains committed results under database guarantees.
Counterexample: Two individually committed updates can leave half a transfer after failure.
Follow-up: Which constraints detect an overdraft?
10. What does isolation actually change?
Model answer: Isolation controls concurrent observations and interleavings. PostgreSQL Read Committed uses statement snapshots; Serializable may require retries. Name the database and anomaly: labels do not guarantee identical implementations. See PostgreSQL isolation.
Counterexample: Reading availability and later inserting a booking can race.
Follow-up: How would a unique constraint close that race?
11. Why can an index make writes slower?
Model answer: Indexes maintain additional search structures, reducing examined rows for suitable predicates while adding maintenance to writes. Match composite ordering to access patterns; inspect plans and measure workloads before assuming improvement.
Counterexample: Indexing a tiny table's nearly universal boolean value may save little.
Follow-up: Would an owner-and-date index help date-only queries?
12. Why is NULL dangerous in interview queries?
Model answer: NULL represents missing information. Many comparisons become unknown, which WHERE excludes. Distinguish counting rows from counting known values and use explicit null tests. See SQLite’s expression documentation.
Counterexample: salary = NULL does not locate unknown salaries.
Follow-up: What happens when a NOT IN subquery contains NULL?
13. How can a left join accidentally lose rows?
Model answer: A left join retains unmatched left rows with missing right values. A right-side WHERE predicate may reject them. Put qualification in the join condition when every left record must survive.
Counterexample: Filtering an empty department's employee salary removes the department.
Follow-up: Why does counting the employee key differ from counting all rows?
Operating systems
14. Process or thread: what is shared?
Model answer: A process supplies resources and an address space; threads execute within it. They share heap and globals but have individual stacks and execution state. Linux describes these distinctions in pthreads.
Counterexample: A thread-local variable is not automatically shared because it belongs to one process.
Follow-up: How can separate processes communicate?
15. Concurrency or parallelism?
Model answer: Concurrency organizes overlapping progress; parallelism executes simultaneously. A single-core event loop handles waiting connections concurrently. CPU-intensive computation needs execution resources that actually run in parallel.
Counterexample: Starting ten tasks does not imply ten cores execute them.
Follow-up: Why might asynchronous I/O improve throughput?
16. What creates a race condition?
Model answer: A race makes correctness depend on uncontrolled access ordering. Two clerks can observe one free copy before recording loans. Synchronize the complete check-and-mutation sequence or enforce the invariant transactionally.
Counterexample: Individually safe dictionary operations do not make a sequence atomic.
Follow-up: Which state belongs under the same lock?
17. Mutex versus semaphore?
Model answer: A mutex protects exclusive access; a counting semaphore represents multiple permits, such as five simultaneous downloads. Choose from the invariant: one state owner differs from bounded resource capacity.
Counterexample: Five semaphore permits do not protect a single shared counter from conflicting updates.
Follow-up: What happens if an exception skips permit release?
18. What are deadlock's conditions?
Model answer: Mutual exclusion, holding while waiting, no forced preemption, and circular waiting can create deadlock. Consistent lock ordering breaks circular waiting. Reducing lock scope helps only if intermediate state remains valid.
Counterexample: Two transfers locking source then destination in opposite directions can block forever.
Follow-up: How would you distinguish deadlock from starvation?
19. What is virtual memory?
Model answer: Virtual addresses map to physical storage through page mappings, enabling isolation and flexible allocation. A page fault may establish a mapping or load data; it need not involve disk access.
Counterexample: Reserving a large virtual range does not imply equally large physical residency.
Follow-up: Why can frequent page replacement hurt performance?
20. Why can a context switch be expensive?
Model answer: Context switches save and restore execution state. Indirect costs include disrupted caches and translation working sets.
Counterexample: More threads do not always increase throughput.
Follow-up: Which metrics would reveal scheduler pressure?
Computer networks
21. What does DNS resolve?
Model answer: DNS resolves names to typed records, including addresses and aliases, using queries and caching. It does not resolve URL paths or render pages.
Counterexample: Changing a DNS record does not instantly invalidate every client's cache.
Follow-up: What is the role of a recursive resolver?
22. TCP versus UDP?
Model answer: TCP offers a reliable ordered byte stream, not message boundaries. UDP provides datagrams without guaranteed delivery or order; applications can add reliability. Choose based on protocol needs rather than blanket speed claims.
Counterexample: One TCP write need not match one receiver read.
Follow-up: How would you frame multiple messages in a stream?
23. What does TLS authenticate?
Model answer: Typical HTTPS authenticates the server certificate and hostname while negotiating encrypted transport. Encryption protects confidentiality and integrity, not business trustworthiness.
Counterexample: A fraudulent website can still have a valid certificate.
Follow-up: Where does TLS terminate when a reverse proxy is present?
24. Is HTTP stateless?
Model answer: HTTP requests carry interpretation context; applications implement sessions through identifiers, tokens, and stored state. Stateless protocol semantics do not forbid server storage.
Counterexample: Keeping a connection open does not itself identify a logged-in user.
Follow-up: Which requests can be retried safely?
25. Why do caches need validation?
Model answer: Caches trade repeated work for possible staleness. Freshness rules permit reuse; validators check whether representations changed. Specify public versus personalized data and tolerated staleness before choosing a cache duration.
Counterexample: Sharing an authenticated response across users can expose private content.
Follow-up: How would you invalidate a changed article?
26. What happens after entering a real URL?
Model answer: For https://example.com/docs?q=sql#joins, parse the address, check caches, and resolve the hostname if needed. A new HTTP/1.1 or HTTP/2 connection establishes TCP and TLS, then sends the path and query; the fragment stays local. A proxy may forward to an application and database. Returned HTML triggers parsing, resource fetching, layout, and paint. Redirects and connection reuse change this sequence. See MDN’s lifecycle; HTTP/3 uses QUIC instead of TCP.
Counterexample: A cached response can avoid the assumed full network journey.
Follow-up: Where would you measure DNS, server, and rendering latency separately?
Next practice
For each answer, invent a failure case and describe its repair. Review OOP, databases, operating systems, and computer networks. Apply the ideas in SQL practice, databases and SQL, and system design fundamentals.
Continue in the SDE preparation track with SQL interview challenges, library system design, parking lot design.