HireHireInterview Quizzes › Software Engineer

Software Engineer Interview Questions

Think you're ready? These are the questions that actually decide Software Engineer interviews. Warm up on Easy — then face the Hard round, where 95% of candidates crumble. 80 questions across 3 levels, instant score, completely free.

80Questions
3Difficulty levels
95%Fail the hard round
FreeInstant score
Easy
Warm-up · 20 Qs
Medium
Practical · 30 Qs
Hard
Brutal · 30 Qs
⚡ Take the Software Engineer quiz — get your score →

The Software Engineer interview questions

Below are the real questions, grouped by difficulty. Expand any one to reveal the correct answer and why — or take the timed quiz for a score you can share. Can you clear the Hard round?

Easy round 20 questions

A function has one loop over n items, and inside it another loop over the same n items. Roughly how does its running time grow as n gets large?
  • A. Linearly, about O(n)
  • B. Proportional to n squared, O(n²) ✓
  • C. Constant, O(1)
  • D. Logarithmically, O(log n)
Correct answer: B. A loop nested inside another loop over the same n elements runs n×n times, giving O(n²).
Binary search keeps returning the wrong result on an array. What is the most likely cause?
  • A. The array is not sorted ✓
  • B. The array contains duplicate values
  • C. The array length is not a power of two
  • D. The target is larger than the array's maximum element
Correct answer: A. Binary search only works correctly on a sorted array, since it decides which half to discard based on ordering.
You committed a bug and already pushed it to a shared branch others are using. Which Git command safely undoes it by adding a new commit?
  • A. git reset --hard
  • B. git revert ✓
  • C. git checkout
  • D. git stash
Correct answer: B. git revert creates a new commit that undoes the change without rewriting shared history.
An INNER JOIN between orders and customers is run. What happens to an order whose customer_id has no matching customer row?
  • A. It appears with NULL customer fields
  • B. It is excluded from the result ✓
  • C. It causes the query to error out
  • D. It is duplicated in the output
Correct answer: B. An INNER JOIN returns only rows that have a match on both sides, so unmatched orders are dropped.
A REST API successfully creates a brand-new user record via POST. Which status code best signals this outcome?
  • A. 200 OK
  • B. 201 Created ✓
  • C. 204 No Content
  • D. 302 Found
Correct answer: B. 201 Created specifically indicates a new resource was successfully created.
In Python, what is the result of the expression 7 // 2?
  • A. 3.5
  • B. 3 ✓
  • C. 4
  • D. 1
Correct answer: B. The // operator does floor (integer) division, so 7 // 2 is 3.
You need an 'undo' feature where the most recent action is reversed first. Which data structure fits best?
  • A. A queue
  • B. A stack ✓
  • C. A priority queue
  • D. A circular buffer
Correct answer: B. A stack is last-in-first-out, so the most recent action is the first one removed.
Looking up a value by its key in a well-distributed hash map takes, on average:
  • A. O(n) time
  • B. O(log n) time
  • C. O(1) time ✓
  • D. O(n log n) time
Correct answer: C. With good hashing and few collisions, hash-map lookups run in average constant time.
In JavaScript, what does the expression '5' == 5 evaluate to?
  • A. true ✓
  • B. false
  • C. NaN
  • D. a type error
Correct answer: A. The loose equality operator == performs type coercion, converting the string '5' to the number 5, so it is true.
A recursive function calls itself but has no condition that ever stops the recursion. What typically happens?
  • A. It is tail-call optimized into a harmless infinite loop
  • B. It loops forever with no error
  • C. It throws a stack overflow error ✓
  • D. It exhausts the heap, throwing an out-of-memory error
Correct answer: C. Without a base case each call adds a frame until the call stack is exhausted, causing a stack overflow.
In Java, calling a method on an object reference that is currently null causes:
  • A. A compile-time error
  • B. A NullPointerException at runtime ✓
  • C. The method to silently return null
  • D. The call to be skipped
Correct answer: B. Dereferencing a null reference at runtime throws a NullPointerException.
How many times does the loop body run: for (int i = 1; i <= 5; i++) { ... }?
  • A. 4
  • B. 5 ✓
  • C. 6
  • D. It runs forever
Correct answer: B. The loop runs for i = 1,2,3,4,5, which is exactly 5 iterations.
Two developers edit the same line of the same file on different branches, then those branches are merged. Git will most likely:
  • A. Pick the newer change automatically
  • B. Report a merge conflict to resolve manually ✓
  • C. Keep the version from the target branch automatically
  • D. Keep both versions of the line silently
Correct answer: B. When the same line is changed differently on both branches, Git cannot auto-merge and reports a conflict.
Running the statement DELETE FROM employees; with no WHERE clause will:
  • A. Delete only the most recently inserted row
  • B. Delete every row in the table ✓
  • C. Fail unless a WHERE clause is provided
  • D. Drop the table structure entirely
Correct answer: B. Without a WHERE clause the DELETE applies to all rows, emptying the table.
You want an API call a client can safely retry after a network timeout without creating duplicate records. Which method is designed to be idempotent?
  • A. POST
  • B. PUT ✓
  • C. POST with a random ID
  • D. PATCH, since repeating a partial update is always safe
Correct answer: B. PUT is idempotent: repeating it with the same data leaves the resource in the same final state.
An array has 5 elements at indexes 0 through 4. Accessing element at index 5 will most likely:
  • A. Return the last element
  • B. Return null safely
  • C. Cause an out-of-bounds error or undefined ✓
  • D. Wrap around to index 0
Correct answer: C. Index 5 is past the valid range 0–4, so it throws an out-of-bounds error or returns undefined depending on the language.
In the expression a() && b(), if a() returns false, what happens to b()?
  • A. b() still runs
  • B. b() is skipped and never called ✓
  • C. b() is evaluated first, then a()
  • D. The expression still returns b()'s return value
Correct answer: B. Logical AND short-circuits: once the left side is false the result is already false, so b() is not evaluated.
Inserting a new node at the head of a singly linked list takes about:
  • A. O(n) time
  • B. O(1) time ✓
  • C. O(log n) time
  • D. O(n²) time
Correct answer: B. You only update the new node's next pointer and the head reference, which is constant time.
In a try/catch/finally block where the try throws an exception that the catch handles, when does the finally block run?
  • A. Only if no exception occurs
  • B. Always, after the try/catch completes ✓
  • C. Never, once an exception is caught
  • D. Only if the program exits
Correct answer: B. The finally block runs regardless of whether an exception was thrown or caught.
Your code references a variable that was never declared, and the language rejects the program before it runs. This is a:
  • A. Runtime error
  • B. Compile-time (syntax) error ✓
  • C. Logic error
  • D. A linker error
Correct answer: B. Errors caught before execution, like an undeclared variable in a compiled language, are compile-time errors.

Medium round 30 questions

You accidentally committed a file with API credentials and pushed the branch to the shared remote. What is the correct remediation?
  • A. Add the file to .gitignore and push again, which removes it from earlier commits
  • B. Run `git rm --cached secrets.env`, commit, and push; the secret is now safe
  • C. Rewrite the history to purge the file, force-push, and rotate the leaked credentials ✓
  • D. Delete the file locally and push, since Git only keeps the latest version of each file
Correct answer: C. Because the secret already exists in pushed history you must purge it from history, force-push, and rotate the exposed credentials since they should be treated as compromised.
A REST endpoint creates a new resource successfully. Which HTTP status code is the most appropriate to return?
  • A. 200 OK
  • B. 201 Created ✓
  • C. 202 Accepted
  • D. 204 No Content
Correct answer: B. 201 Created specifically indicates that a request succeeded and a new resource was created as a result.
In a relational database, a query filtering `WHERE email = ?` on a large users table is slow. What is the most effective first fix?
  • A. Add an index on the email column ✓
  • B. Add an ORDER BY email clause so the engine can binary-search the rows
  • C. Increase the connection pool size
  • D. Wrap the query in a transaction
Correct answer: A. An index on the filtered column lets the database avoid a full table scan, which is the primary cause of slow equality lookups on large tables.
You wrote a unit test that occasionally fails without any code change. What is the most likely root cause of this 'flaky' test?
  • A. The test uses exact floating-point equality in an assertion
  • B. The test depends on timing, ordering, or shared external state ✓
  • C. The test runs slower on CI than on the developer's machine
  • D. The test uses mocks instead of real objects
Correct answer: B. Flaky tests typically fail intermittently because they rely on non-deterministic factors like timing, execution order, or shared mutable state.
In JavaScript, what does `console.log(0.1 + 0.2 === 0.3)` print, and why?
  • A. true, because the numbers are exact
  • B. false, because floating-point arithmetic introduces rounding error ✓
  • C. true, because JavaScript rounds automatically
  • D. It throws a TypeError
Correct answer: B. IEEE-754 floating-point cannot represent 0.1 and 0.2 exactly, so their sum is slightly off from 0.3 and the strict comparison is false.
Your service calls a flaky third-party API that sometimes times out. Which pattern best prevents these failures from cascading and overloading the downstream service?
  • A. Retrying indefinitely until it succeeds
  • B. A circuit breaker that stops calls after repeated failures ✓
  • C. Increasing the request timeout to several minutes
  • D. Caching all responses forever
Correct answer: B. A circuit breaker trips after repeated failures to stop sending requests for a period, preventing cascading failures and giving the downstream service time to recover.
What is the primary purpose of using a prepared statement (parameterized query) instead of string-concatenating user input into SQL?
  • A. It makes queries run faster in all cases
  • B. It prevents SQL injection by separating code from data ✓
  • C. It automatically escapes HTML in query results
  • D. It encrypts the data sent over the database connection
Correct answer: B. Parameterized queries send SQL structure and user data separately so input can never be interpreted as executable SQL, preventing injection.
In Git, what is the practical difference between `git merge` and `git rebase` when integrating your feature branch with `main`?
  • A. Rebase deletes the feature branch; merge keeps it
  • B. Merge creates a merge commit preserving history; rebase rewrites your commits onto the tip of main for a linear history ✓
  • C. Merge only works on remote branches; rebase only works locally
  • D. Both produce identical commit graphs; only the command name differs
Correct answer: B. Merge combines histories with a merge commit and preserves the original branch structure, while rebase replays your commits on top of main to produce a linear history.
An HTTP request from your browser JavaScript to a different domain's API is blocked by the browser. Which mechanism controls whether this cross-origin request is allowed?
  • A. CORS (Cross-Origin Resource Sharing) headers set by the server ✓
  • B. The Content-Type request header
  • C. The server's TLS/SSL certificate
  • D. The Referer header sent by the browser
Correct answer: A. The browser's same-origin policy blocks cross-origin requests unless the target server returns appropriate CORS headers permitting the requesting origin.
You need to look up values by key millions of times in a tight loop. Which data structure gives the best average-case lookup time?
  • A. A sorted array with binary search
  • B. A linked list
  • C. A hash map (dictionary) ✓
  • D. A balanced binary search tree
Correct answer: C. A hash map provides average O(1) key lookups, which is faster than the O(n) linear scan of a list or array for repeated random-access lookups.
A hash map has average O(1) lookup. What primarily causes lookups to degrade toward O(n)?
  • A. Using string keys instead of integer keys
  • B. Excessive hash collisions in a single bucket ✓
  • C. Keeping the load factor well below 1
  • D. Resizing the underlying table too often
Correct answer: B. When many keys collide into one bucket, that bucket becomes a linear structure, degrading lookups to O(n).
Which SQL clause runs AFTER GROUP BY to filter aggregated groups?
  • A. WHERE
  • B. HAVING ✓
  • C. ORDER BY
  • D. LIMIT
Correct answer: B. HAVING filters rows after grouping and aggregation, whereas WHERE filters before grouping.
In REST, which HTTP method is idempotent AND typically used to fully replace a resource?
  • A. POST
  • B. PUT ✓
  • C. PATCH
  • D. DELETE
Correct answer: B. PUT is idempotent and replaces the target resource entirely with the request payload.
What is the main advantage of a binary search over linear search on the same dataset?
  • A. It works on unsorted data
  • B. It runs in O(log n) instead of O(n) ✓
  • C. It uses less memory always
  • D. It handles duplicates better
Correct answer: B. Binary search halves the search space each step, giving O(log n) versus linear search's O(n), but requires sorted data.
In Git, what does 'git rebase main' do to your feature branch?
  • A. Merges main into your branch with a merge commit
  • B. Replays your branch commits on top of the latest main ✓
  • C. Deletes commits not in main
  • D. Pushes your branch to main
Correct answer: B. Rebase reapplies your branch's commits onto the tip of main, producing a linear history.
A function makes a network call and returns a Promise. What does 'await' do inside an async function?
  • A. Blocks the entire CPU until resolved
  • B. Pauses the async function until the Promise settles, yielding control ✓
  • C. Converts the Promise to a callback
  • D. Cancels the Promise on timeout
Correct answer: B. await suspends the async function until the Promise settles, without blocking the event loop.
Which index would best speed up a query filtering on 'WHERE last_name = ? AND first_name = ?'?
  • A. Separate index on first_name only
  • B. Composite index on (last_name, first_name) ✓
  • C. Full-text index on last_name
  • D. No index; the optimizer handles it
Correct answer: B. A composite index on (last_name, first_name) matches the filter's leading columns and serves both predicates.
In a producer-consumer scenario with multiple threads, which construct prevents race conditions on a shared queue?
  • A. Declaring the queue field volatile
  • B. A mutex/lock around queue operations ✓
  • C. Giving each thread its own thread-local copy of the queue
  • D. Marking the queue variable as final
Correct answer: B. A mutex serializes access so only one thread mutates the shared queue at a time, preventing races.
What does the 'N+1 query problem' describe in ORMs?
  • A. Running one query that returns N+1 rows
  • B. Executing one query then N additional queries for related data ✓
  • C. A query that fails after N retries
  • D. An index missing on N+1 columns
Correct answer: B. The N+1 problem is issuing one query for a list then one extra query per item to load its relations.
Which caching strategy writes to the cache and the database simultaneously on every write?
  • A. Write-back
  • B. Write-through ✓
  • C. Cache-aside on read only
  • D. Write-around
Correct answer: B. Write-through updates cache and backing store together, keeping them consistent at write time.
What is the worst-case time complexity of quicksort?
  • A. O(n)
  • B. O(n log n)
  • C. O(n^2) ✓
  • D. O(log n)
Correct answer: C. With poor pivot choices (e.g., already-sorted input), quicksort degrades to O(n^2).
In a relational database, which isolation level prevents dirty reads but still allows non-repeatable reads?
  • A. Read Uncommitted
  • B. Read Committed ✓
  • C. Serializable
  • D. Snapshot
Correct answer: B. Read Committed forbids reading uncommitted data but does not guarantee the same row reads identically twice.
What does a HTTP 301 response signal to a client?
  • A. Temporary redirect
  • B. Permanent redirect ✓
  • C. Not modified
  • D. Bad gateway
Correct answer: B. 301 is a permanent redirect, telling clients to update the URL for future requests.
In Git, what does 'git rebase' do that 'git merge' does not?
  • A. Combines histories with a merge commit
  • B. Rewrites commits onto a new base for linear history ✓
  • C. Deletes the source branch
  • D. Reverts the last commit
Correct answer: B. Rebase replays commits onto a new base, producing a linear history without a merge commit.
Which HTTP method is expected to be idempotent AND is used to fully replace a resource?
  • A. POST
  • B. PATCH
  • C. PUT ✓
  • D. GET
Correct answer: C. PUT replaces a resource fully and repeating it yields the same state, making it idempotent.
What problem does a database index primarily solve, at what cost?
  • A. Speeds writes at the cost of reads
  • B. Speeds reads at the cost of slower writes and extra storage ✓
  • C. Reduces disk usage at the cost of accuracy
  • D. Enforces transactions at the cost of concurrency
Correct answer: B. Indexes accelerate lookups but add overhead to inserts/updates and consume storage.
In concurrency, what is a race condition?
  • A. A thread finishing before it starts
  • B. Outcome depending on non-deterministic timing of thread access to shared state ✓
  • C. A deadlock between two locks
  • D. A thread exceeding its stack size
Correct answer: B. A race condition occurs when correctness depends on the unpredictable interleaving of threads accessing shared data.
What is the main advantage of a hash table over a balanced BST for lookups?
  • A. Guaranteed O(log n) lookups
  • B. Average O(1) lookups ✓
  • C. Keys are kept in sorted order
  • D. Lower memory usage always
Correct answer: B. Hash tables offer average constant-time lookups, unlike the logarithmic time of a BST.
In REST, which status code best indicates a successfully created resource?
  • A. 200 OK
  • B. 201 Created ✓
  • C. 204 No Content
  • D. 202 Accepted
Correct answer: B. 201 Created signals that the request succeeded and a new resource was created.
What does the 'volatile' keyword typically guarantee in languages like Java?
  • A. Atomicity of compound operations
  • B. Visibility of a variable's latest value across threads ✓
  • C. Thread mutual exclusion
  • D. Immutability of the variable
Correct answer: B. volatile ensures reads/writes go to main memory so other threads see the latest value, but it does not make compound operations atomic.

Hard round 30 questions

A read-heavy service caches product data in Redis with a 60s TTL. A single hot product gets 50k req/s. At the TTL boundary, latency spikes and the primary DB briefly saturates every minute. Which mitigation BOTH prevents the DB dogpile AND avoids serving stale data for the full extra TTL?
  • A. Increase the TTL to 600s so expiries happen less often
  • B. Use a per-key mutex/lock so only one request recomputes on miss while others wait or serve the last value ✓
  • C. Switch the cache eviction policy from LRU to LFU
  • D. Add a random 0-60s jitter to each key's TTL at write time
Correct answer: B. A recompute lock (single-flight) collapses the stampede so only one request hits the DB while others wait, without extending staleness like a longer TTL would.
A Kafka consumer reads a record, processes it (charges a card), then commits its offset. It crashes AFTER the side effect but BEFORE the offset commit. On restart, what happens and what is the correct fix?
  • A. The record is skipped because Kafka auto-advances offsets on crash; enable auto-commit
  • B. The record is reprocessed (double charge); make processing idempotent using a dedup key so replays are safe ✓
  • C. Kafka's exactly-once transaction on the consumer poll guarantees no reprocessing; no fix needed
  • D. The consumer group rebalance drops the partition permanently; increase session.timeout.ms
Correct answer: B. With at-least-once semantics an uncommitted offset causes redelivery, so the side effect must be made idempotent (e.g., a unique transaction key) to tolerate replays.
Client A acquires a distributed lock in Redis (TTL 10s), then stalls for 15s on a stop-the-world GC pause. The lock expires and Client B acquires it and writes to shared storage. A wakes up believing it still holds the lock and also writes. Which mechanism prevents the resulting corruption?
  • A. A longer lock TTL of 60s so GC pauses fit inside it
  • B. Fencing tokens: each lock grant carries a monotonically increasing number that the storage layer rejects if lower than the last accepted ✓
  • C. Redlock across five Redis nodes to increase lock durability
  • D. Setting the Redis lock with NX and a random value checked at release time
Correct answer: B. Only a fencing token enforced at the resource makes the stale writer's request rejected, since any time-based TTL can still be violated by an arbitrarily long pause.
A payments table is sharded by shard = user_id % N. Analytics runs SELECT SUM(amount) WHERE merchant_id = ? for a merchant whose transactions are spread across all shards. What is the fundamental problem and the standard remedy?
  • A. The query is fine; each shard has an index on merchant_id so it is a single-shard lookup
  • B. It is a cross-shard scatter-gather; maintain a secondary index or read model keyed by merchant_id (e.g., via CQRS/materialized view) ✓
  • C. Rehash the whole cluster using consistent hashing to co-locate the merchant
  • D. Wrap the aggregate in a 2PC transaction so all shards return a consistent sum
Correct answer: B. The partition key is user_id, so a merchant query fans out to every shard; the fix is a separate index/read model partitioned by merchant_id, not a distributed transaction.
In Raft, a leader receives a client write and replicates the entry to a minority of followers before crashing. A new leader is elected from a node that never saw that entry. What is guaranteed about the un-replicated entry?
  • A. It is guaranteed committed because the old leader acknowledged writing it locally
  • B. It may be silently overwritten because it was never committed (never on a majority) and was not acked to the client ✓
  • C. It is automatically recovered from the old leader's disk during the next election
  • D. Raft blocks all new writes until the old leader rejoins and re-sends it
Correct answer: B. An entry is only committed once stored on a quorum; an entry present on only a minority can be overwritten by a new leader, which is why it was never acknowledged to the client.
Consider this Java snippet run by two threads sharing a long counter field `count` (no volatile, no lock): `count++;`. Beyond the obvious lost-update race, why is `count` specifically dangerous on a 32-bit JVM even for a single read?
  • A. Longs are always atomic in the JVM so there is no additional risk
  • B. Non-volatile 64-bit long/double reads and writes may be split into two 32-bit operations, so a reader can observe a torn value ✓
  • C. The JIT compiler promotes count to a register making it thread-local automatically
  • D. Garbage collection can relocate the long and corrupt its bytes
Correct answer: B. The JLS permits non-volatile long/double stores to be performed as two 32-bit writes, so a concurrent reader can see a word-tearing (half-updated) value.
You add a node to a load-balancing tier that uses plain `hash(key) % N` for routing to caches. After N goes from 8 to 9, what fraction of keys remap, and what does consistent hashing with virtual nodes fix?
  • A. About 1/9 remap; consistent hashing mainly reduces memory usage
  • B. Nearly all keys remap because the modulus changed; consistent hashing limits remapping to ~1/N of keys and virtual nodes smooth load distribution ✓
  • C. Exactly the keys on the new node remap; consistent hashing eliminates all remapping
  • D. No keys remap because hashing is deterministic; virtual nodes only help with replication
Correct answer: B. Changing the modulus reshuffles almost every key, whereas consistent hashing only moves keys near the added node (~1/N) and virtual nodes even out skew.
A service is on a G1 GC JVM with a 32GB heap and users report periodic multi-second stalls correlated with rising old-gen occupancy and eventual Full GCs. Heap dumps show a growing HashMap used as an in-process cache with no eviction. What is the most accurate diagnosis?
  • A. G1 is misconfigured; switch to the throughput (Parallel) collector to remove pauses
  • B. A memory leak: the unbounded cache retains objects, defeating generational collection until a Full GC compacts the whole heap ✓
  • C. The pauses are normal young-gen collections; increase Xmn to fix them
  • D. Network backpressure is stalling threads; the GC correlation is coincidental
Correct answer: B. An unbounded map holds strong references so objects are never reclaimed, old-gen fills, and G1 falls back to costly Full GCs — a classic leak, not a collector-tuning issue.
Two microservices, Orders and Inventory, must both succeed or both roll back when placing an order. The team wants high availability and avoids blocking. Between an orchestrated Saga and 2PC, which statement correctly captures the trade-off?
  • A. 2PC is preferred because Sagas cannot roll back once a step commits
  • B. A Saga uses compensating transactions and stays available under partition, but sacrifices isolation, allowing intermediate states other reads can observe ✓
  • C. 2PC and Saga both guarantee full ACID isolation across services
  • D. A Saga guarantees linearizability across both services without extra work
Correct answer: B. Sagas trade global isolation for availability by using compensations per step, so intermediate uncommitted-looking states are visible, unlike blocking 2PC.
You must ship a breaking change to a shared Protobuf/JSON contract consumed by dozens of independently deployed services you cannot upgrade atomically. Which rollout strategy is safe?
  • A. Reuse the existing field number but change its type, then deploy producer and all consumers simultaneously
  • B. Add the new field as optional alongside the old, dual-write both, migrate consumers, then remove the old field in a later release ✓
  • C. Delete the old field immediately and rely on consumers to ignore unknown fields
  • D. Bump the top-level version and force every consumer to redeploy within the same maintenance window
Correct answer: B. Backward/forward-compatible evolution requires additive changes and an expand-migrate-contract sequence so old and new consumers coexist during rollout.
In the CAP theorem, a network partition occurs. A system that keeps serving reads/writes on both sides has chosen which trade-off?
  • A. Consistency over availability
  • B. Availability over consistency ✓
  • C. Partition tolerance over availability
  • D. Consistency and availability both
Correct answer: B. Serving both sides during a partition sacrifices strong consistency to preserve availability (AP).
Under SQL 'READ COMMITTED' isolation, which anomaly can still occur?
  • A. Dirty read
  • B. Non-repeatable read ✓
  • C. Dirty write
  • D. Cascading rollback
Correct answer: B. READ COMMITTED prevents dirty reads but still allows non-repeatable reads since rows can change between reads.
A recursive function has T(n) = 2T(n/2) + O(n). By the Master Theorem, its complexity is:
  • A. O(n)
  • B. O(n log n) ✓
  • C. O(n^2)
  • D. O(log n)
Correct answer: B. With a=2, b=2, f(n)=n, this is the balanced case giving O(n log n) (like merge sort).
Two threads acquire locks A and B in opposite orders. What classic problem can arise?
  • A. Livelock only
  • B. Deadlock ✓
  • C. Priority inversion only
  • D. Cache thrashing
Correct answer: B. Opposite lock-acquisition orders create a circular wait, the textbook condition for deadlock.
In a distributed system, what does an idempotency key primarily protect against?
  • A. Lost requests when the network drops packets
  • B. Duplicate processing from client retries ✓
  • C. Requests being processed out of order
  • D. Partial writes when a request crashes mid-transaction
Correct answer: B. An idempotency key lets the server detect and dedupe retried requests so the operation applies once.
Which garbage-collection issue does a generational collector specifically optimize for?
  • A. Memory fragmentation in the old generation
  • B. The fact that most objects die young ✓
  • C. Cyclic references never being freed
  • D. Manual free() calls being missed
Correct answer: B. Generational GC exploits the weak generational hypothesis: most objects become unreachable soon after allocation.
A B-tree database index has high fan-out. Why does this reduce disk I/O for lookups?
  • A. It stores data in RAM only
  • B. Higher fan-out means shallower tree, so fewer node reads per lookup ✓
  • C. It compresses the keys
  • D. It avoids sorting entirely
Correct answer: B. High fan-out keeps the tree shallow, so fewer levels (disk page reads) are traversed per lookup.
In eventual-consistency systems, what does a vector clock help determine?
  • A. The absolute wall-clock time of a write
  • B. Causal ordering and concurrency between events across nodes ✓
  • C. The fastest replica to read from
  • D. The total number of writes
Correct answer: B. Vector clocks capture causal relationships, letting nodes detect concurrent vs. ordered updates.
You must guarantee exactly-once semantics writing to a downstream service from a message queue. The most robust approach is:
  • A. Increase consumer retries
  • B. Combine at-least-once delivery with idempotent writes ✓
  • C. Switch to fire-and-forget delivery
  • D. Use a larger prefetch buffer
Correct answer: B. True exactly-once end-to-end is achieved by pairing at-least-once delivery with idempotent downstream operations.
A hot loop suffers frequent cache misses on a large array-of-structs. Which change most likely improves throughput?
  • A. Mark the array elements as const
  • B. Convert to struct-of-arrays for better spatial locality ✓
  • C. Iterate the loop in reverse order
  • D. Increase the thread pool size
Correct answer: B. Struct-of-arrays packs fields the loop actually touches contiguously, improving cache-line locality and reducing misses.
In a system using optimistic concurrency control with version numbers, what happens when two transactions read version 5 and both try to write?
  • A. Both succeed and the last write wins silently
  • B. The second commit fails because the version no longer matches ✓
  • C. Both are blocked until a lock is released
  • D. The database merges them automatically
Correct answer: B. Optimistic concurrency detects the stale version on the second write and rejects it, requiring a retry.
Why can a hash map resize (rehash) cause a latency spike in a real-time system?
  • A. It changes the hash function seed
  • B. It must reallocate and rehash all existing entries into a larger table in one operation ✓
  • C. It must hold a global lock, blocking all other threads
  • D. It doubles memory use, forcing a swap to disk
Correct answer: B. Growing the table requires moving and re-hashing every entry, an O(n) burst that stalls a request.
In the CAP theorem, during a network partition, a system that remains available must sacrifice which property?
  • A. Consistency ✓
  • B. Partition tolerance
  • C. Durability
  • D. Isolation
Correct answer: A. Under a partition you choose between consistency and availability; staying available means giving up strong consistency.
What is the classic problem with using 'double-checked locking' for a singleton without proper memory barriers?
  • A. It always deadlocks
  • B. Another thread may observe a partially constructed object due to instruction reordering ✓
  • C. It creates two instances every time
  • D. It leaks the lock object
Correct answer: B. Without a memory barrier (e.g., volatile), reordering can publish a reference before the object is fully initialized.
In a write-ahead log (WAL) based database, what invariant must hold before a data page is flushed to disk?
  • A. The data page must be flushed before its log records
  • B. The corresponding log records must be durably written first ✓
  • C. The transaction must be aborted
  • D. The buffer pool must be empty
Correct answer: B. WAL requires log records to reach durable storage before the data page so recovery can redo/undo changes.
Why does tail-call optimization (TCO) matter for a recursive function processing a very deep list?
  • A. It converts recursion into a loop reusing the stack frame, avoiding stack overflow ✓
  • B. It memoizes results automatically
  • C. It parallelizes the recursion
  • D. It reduces the algorithm's Big-O complexity
Correct answer: A. TCO reuses the current stack frame for the tail call, preventing unbounded stack growth.
In distributed systems, what does an idempotency key prevent when a client retries a payment request after a timeout?
  • A. The client from timing out on the retry
  • B. Duplicate processing of the same logical operation ✓
  • C. Concurrent duplicate requests from deadlocking
  • D. The original response from being lost
Correct answer: B. The server recognizes the repeated key and returns the original result instead of charging twice.
What is a subtle danger of catching a broad exception and swallowing it in a loop that acquires resources?
  • A. It guarantees every acquired resource is still closed
  • B. It can mask resource leaks and continue in a corrupted state ✓
  • C. It converts checked exceptions into unchecked ones
  • D. It rethrows the exception once the loop finishes
Correct answer: B. Swallowing exceptions hides failures and can leak resources while letting the program proceed incorrectly.
In an LSM-tree storage engine, what is the purpose of compaction?
  • A. To sort incoming writes before they reach the memtable
  • B. To merge SSTables, discard overwritten/deleted keys, and reduce read amplification ✓
  • C. To build B-tree indexes
  • D. To flush the write-ahead log
Correct answer: B. Compaction merges sorted files, removing tombstones and stale versions so reads touch fewer files.
Why might adding more worker threads beyond the CPU core count HURT throughput for a CPU-bound workload?
  • A. The OS never schedules threads beyond the core count
  • B. Context-switching overhead and cache contention outweigh added parallelism ✓
  • C. Threads above the core count are automatically given lower priority
  • D. Hyper-threading shuts off once threads exceed physical cores
Correct answer: B. For CPU-bound work, extra threads just add context-switch and cache-thrash overhead without real parallelism gains.

Prep for another role

Questions are original, written and independently verified for HireHire's role interview quizzes. They reflect the kind of knowledge Software Engineer interviews test, not any specific company's questions. HireHire maps live tech & IT jobs across India, updated regularly. Last updated: August 2026.