Advanced Computer Science interview questions
125 questions with answers (CSE-301 to CSE-425). Try each one aloud before reading the answer.
Data Structures
CSE-301 · Design a set supporting insert, delete and getRandom, all in O(1).
Keep a dynamic array of values and a hash map from value to its array index. Insert appends and records the index. Delete swaps the target with the last element, updates the moved element's index and pops. getRandom picks a random array index.
CSE-302 · How do you find the running median of a data stream?
Keep a max-heap for the lower half and a min-heap for the upper half, rebalancing so their sizes differ by at most one. Insertion is O(log n), and the median is the top of the larger heap or the average of both tops, in O(1).
CSE-303 · How can a hash table resize without a long latency spike?
Use incremental rehashing: allocate the new table, keep both, and migrate a few buckets on each subsequent operation. Lookups check both tables until migration completes; Redis uses this approach to avoid pauses.
CSE-304 · Size a Bloom filter for 1% false positives on 10 million items.
False-positive rate p ≈ (1 − e^(−kn/m))^k, with optimal k = (m/n) ln 2. Bits needed m = −n ln p / (ln 2)² ≈ 9.6 bits per item, so about 96 million bits (≈12 MB) with k ≈ 7 hash functions. Bloom filters give no false negatives.
CSE-305 · When would you choose a balanced BST over a hash table?
When you need ordered iteration, range queries, floor/ceiling or min/max lookups, or guaranteed O(log n) worst-case performance without hash-flooding risk. Hash tables win for pure point lookups with average O(1).
CSE-306 · Compare memory for an adjacency matrix and list on a graph with 10⁶ vertices and 10⁷ directed edges.
A matrix needs 10¹² entries, about 125 GB even at one bit each. A compressed adjacency list (CSR) needs about 10⁷ × 4 B for targets plus 10⁶ × 4 B for offsets, roughly 44 MB. Sparse graphs should use lists.
CSE-307 · When would you use a Fenwick tree instead of a segment tree?
A Fenwick (binary indexed) tree handles prefix sums and point updates in O(log n) with n + 1 integers and very little code. A segment tree is needed for non-invertible aggregates such as min/max, or for range updates with lazy propagation.
CSE-308 · What is a persistent data structure and how is it implemented efficiently?
One that preserves previous versions after updates. Path copying in trees copies only the O(log n) nodes on the path to the change and shares the rest, so each version costs O(log n) extra space; functional languages and Git-like systems rely on this.
CSE-309 · How does an LSM tree differ from a B-tree?
An LSM tree buffers writes in an in-memory memtable, flushes sorted immutable SSTables to disk and merges them by compaction, giving high write throughput. Reads may check several levels, mitigated by Bloom filters. B-trees update in place, favouring reads; RocksDB and Cassandra use LSM trees.
CSE-310 · Design a time-based key-value store with get(key, timestamp).
Map each key to a list of (timestamp, value) pairs appended in increasing time order. A get binary-searches for the largest timestamp ≤ the query, so set is O(1) and get is O(log n) per key.
CSE-311 · Why do dynamic arrays grow geometrically rather than by a fixed amount?
Multiplying capacity by a factor such as 2 makes total copying across n appends at most about 2n, so append is amortized O(1). Growing by a constant c causes O(n²/c) total copying. A factor like 1.5 trades a little more copying for better memory reuse.
Algorithms & Complexity
CSE-312 · How do you find the kth largest element in an unsorted array?
Quickselect partitions around a pivot and recurses into one side, giving average O(n) and worst case O(n²). A min-heap of size k gives O(n log k) and suits streams. Median-of-medians guarantees O(n) worst case but has large constants.
CSE-313 · How do you compute the longest common subsequence of two strings?
DP: if a[i] = b[j], L[i][j] = L[i−1][j−1] + 1; otherwise L[i][j] = max(L[i−1][j], L[i][j−1]). It takes O(mn) time and O(mn) space, reducible to O(min(m, n)) if only the length is needed.
CSE-314 · What is the recurrence for edit (Levenshtein) distance?
D[i][j] = D[i−1][j−1] if a[i] = b[j]; otherwise 1 + min(D[i−1][j] (delete), D[i][j−1] (insert), D[i−1][j−1] (substitute)), with D[i][0] = i and D[0][j] = j. It runs in O(mn).
CSE-315 · When must you use Bellman-Ford instead of Dijkstra?
When edges can have negative weights. Bellman-Ford relaxes all edges V − 1 times in O(VE); if any edge still relaxes on a further pass, a negative cycle is reachable. Dijkstra's greedy finalization fails with negative edges.
CSE-316 · How does Floyd-Warshall work and when is it appropriate?
It computes all-pairs shortest paths with dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for each intermediate k, in O(V³) time and O(V²) space. It suits dense graphs with a few hundred vertices and handles negative edges without negative cycles.
CSE-317 · What do P, NP, NP-complete and NP-hard mean?
P: solvable in polynomial time. NP: solutions verifiable in polynomial time. NP-hard: every NP problem reduces to it in polynomial time. NP-complete: both in NP and NP-hard, such as SAT, 3-coloring and the decision version of TSP. Whether P = NP is open.
CSE-318 · Solve T(n) = 2T(n/2) + n log n.
Here n^(log₂2) = n and f(n) = n log n is larger only by a log factor, not polynomially, so basic Master Theorem case 3 does not apply. Each of the log n recursion levels costs about n log n, giving T(n) = Θ(n log² n).
CSE-319 · How would you sort a 10 GB file with 1 GB of RAM?
External merge sort. Read about 1 GB at a time, sort it in memory and write a sorted run, producing about 10 runs. Then do a 10-way merge using a min-heap with buffered reads and writes. Total I/O is about two passes over the data.
CSE-320 · How do you find the top-K frequent items in a huge stream?
If distinct keys fit in memory, count with a hash map and keep a min-heap of size K, giving O(n log K). Otherwise, use approximate structures such as Count-Min Sketch with a heap, or the Misra-Gries algorithm, trading exactness for bounded memory.
CSE-321 · How do you detect a cycle in a directed graph?
Run DFS with three colours: white (unvisited), gray (on the current recursion stack) and black (finished). Encountering a gray vertex is a back edge, which means a cycle. Alternatively, Kahn's algorithm finds a cycle if it cannot remove every vertex. Both are O(V + E).
CSE-322 · How does Kadane's algorithm find the maximum subarray sum?
It tracks the best sum ending at each position and the global best, in O(n) time and O(1) space.
best = cur = a[0]
for x in a[1:]:
cur = max(x, cur + x)
best = max(best, cur)OOP & Design Patterns
CSE-323 · Design the classes for a parking-lot system.
ParkingLot contains Levels, which contain ParkingSpots typed by size. Vehicle subtypes (Car, Bike, Truck) declare the spot size they need. A Ticket records the spot and entry time, and a pluggable PricingStrategy computes fees. A SpotAllocator finds free spots, guarded for concurrent entry gates.
CSE-324 · Design an elevator control system.
Model Elevator (state, direction, floor, request queue), Request (floor, direction), and a Dispatcher that assigns hall calls using a strategy such as nearest suitable car. Each car serves stops with the LOOK/SCAN algorithm, continuing in one direction while requests remain. The State pattern handles Idle, Moving and DoorsOpen.
CSE-325 · When does inheritance become harmful?
When subclasses depend on base-class internals (the fragile base class problem), when hierarchies grow deep or when "is-a" is forced where behaviour differs, violating LSP. Prefer composition and interfaces, and keep inheritance shallow and designed for extension.
CSE-326 · How would you implement undo/redo in an editor?
Use the Command pattern: each action is an object with execute() and undo(). Executing pushes onto an undo stack and clears the redo stack; undo pops, calls undo() and pushes to redo; redo reverses that. Memento can snapshot state when inverse operations are hard.
CSE-327 · Why use the State pattern instead of a large switch statement?
Each state becomes a class implementing the same interface, such as Idle, HasCoin and Dispensing in a vending machine, and transitions swap the current state object. This removes scattered conditionals, follows Open/Closed and makes each state's behaviour testable.
CSE-328 · What is hexagonal (ports and adapters) architecture?
The domain core defines ports (interfaces) for what it needs and offers. Adapters implement them for databases, HTTP, queues or UIs. Dependencies point inward, so business logic can be tested without infrastructure and adapters can be swapped, applying Dependency Inversion at the architecture level.
CSE-329 · What is the difference between the Proxy and Decorator patterns?
Both wrap an object behind the same interface. A Proxy controls access, for lazy loading, permissions, remoting or caching, and usually manages the real object's lifecycle. A Decorator adds responsibilities and is designed to be stacked by the client.
CSE-330 · When would you prefer Strategy over Template Method?
Template Method fixes an algorithm's skeleton in a base class and lets subclasses override steps, using inheritance, with the choice fixed at compile time. Strategy injects the varying behaviour as an object, using composition, so it can change at run time and is easier to test.
CSE-331 · What is the Chain of Responsibility pattern and where is it used?
Requests pass along a chain of handlers, each of which processes the request or forwards it to the next. Web middleware pipelines (authentication, logging, compression), servlet filters and event bubbling all use it, keeping handlers decoupled and reorderable.
CSE-332 · How do you design an immutable class in Java?
Declare the class final, make all fields private final, provide no setters, initialize everything in the constructor, make defensive copies of mutable inputs and outputs, and return new instances for modifications. Java records cover the simple cases.
CSE-333 · What are common OOP anti-patterns?
God object (one class doing everything), anemic domain model (data classes with logic elsewhere), singleton overuse as hidden global state, deep inheritance hierarchies, and circular dependencies between modules. They raise coupling and make testing difficult.
Programming Languages (C/C++/Java/Python)
CSE-334 · How is virtual dispatch implemented in C++ and what does it cost?
Each polymorphic class has a vtable of function pointers, and each object holds a hidden vptr to its class's vtable. A virtual call loads the vptr, indexes the table and calls indirectly. The cost is one pointer per object, an indirect branch and usually lost inlining.
CSE-335 · What are the Rule of Three, Five and Zero in C++?
If a class defines a destructor, copy constructor or copy assignment, it probably needs all three. C++11 adds move constructor and move assignment, making five. The Rule of Zero says to rely on RAII members such as smart pointers so the compiler-generated defaults suffice.
CSE-336 · What do move semantics and rvalue references provide?
An rvalue reference T&& binds to temporaries, letting a move constructor steal their resources (for example a buffer pointer) instead of deep-copying, leaving the source valid but unspecified. std::move casts to an rvalue; this makes returning and reallocating containers of large objects cheap.
CSE-337 · What is the happens-before relationship in the Java Memory Model?
A guarantee that writes before an action are visible to code after another action. Edges include program order within a thread, unlocking then locking the same monitor, writing then reading a volatile, and Thread.start() and join(). Without such edges, threads may see stale or reordered values.
CSE-338 · How does generational garbage collection work in the JVM?
Most objects die young, so the heap is split into a young generation, collected frequently by copying survivors, and an old generation, collected less often. Objects surviving several minor GCs are promoted. Collectors like G1 use regions and pause-time goals; ZGC and Shenandoah collect concurrently for very short pauses.
CSE-339 · How does CPython manage memory?
Primarily through reference counting: each object tracks references and is freed immediately when the count reaches zero. A generational cyclic garbage collector, the gc module, finds and frees reference cycles that counting cannot. Small objects come from the pymalloc arena allocator.
CSE-340 · Why is undefined behaviour in C dangerous beyond just crashing?
The compiler may assume undefined behaviour never happens and optimize accordingly, for example deleting a check for signed overflow or a null test after a dereference. The program can appear to work in testing and fail silently under other compilers or flags. Sanitizers such as UBSan and ASan help detect it.
CSE-341 · How do C++ templates differ from Java generics?
C++ templates are instantiated per type at compile time (monomorphization), generating specialized code that works with primitives and allows metaprogramming but increases binary size. Java generics use type erasure: one compiled class, casts inserted, no primitive type arguments and no run-time type information.
CSE-342 · In Python, when would you choose asyncio, threads or multiprocessing?
asyncio suits many concurrent I/O-bound tasks, such as thousands of sockets, with cooperative scheduling. Threads suit blocking I/O libraries. Multiprocessing suits CPU-bound work because each process has its own interpreter and GIL, at the cost of inter-process communication.
CSE-343 · What is sizeof this struct on a typical 64-bit compiler, and how do you shrink it?
struct S { char a; int b; char c; };a takes 1 byte plus 3 padding so b is 4-byte aligned, b takes 4, and c takes 1 plus 3 tail padding: 12 bytes. Reordering to int b; char a; char c; gives 8 bytes.
CSE-344 · How can a Java program leak memory despite garbage collection?
By keeping unwanted objects reachable: ever-growing static collections or caches, unremoved listeners, ThreadLocal values in pooled threads, and class-loader leaks on redeployment. Diagnose with heap dumps and tools like Eclipse MAT, and fix with bounded caches or weak references.
Operating Systems
CSE-345 · What are the four Coffman conditions for deadlock?
Mutual exclusion, hold-and-wait, no preemption and circular wait must all hold at once. Breaking any one prevents deadlock; the most practical is imposing a global lock-acquisition order to eliminate circular wait.
CSE-346 · How does the Banker's algorithm avoid deadlock?
Each process declares its maximum need. Before granting a request, the OS simulates the allocation and checks whether a safe sequence exists in which every process can obtain its remaining need and finish. If not, the request waits. It is O(m × n²) and rarely used in general-purpose OSes.
CSE-347 · Compute effective memory access time with a TLB.
With a 100 ns memory access, negligible TLB lookup time, a single-level page table and a 90% TLB hit ratio: EAT = 0.9 × 100 + 0.1 × (100 + 100) = 110 ns. A miss costs one extra memory access for the page-table entry.
CSE-348 · How large is a flat page table for a 32-bit address space with 4 KiB pages and 4-byte entries?
2³² / 2¹² = 2²⁰ pages, and 2²⁰ × 4 B = 4 MiB per process, mostly unused. Multi-level page tables allocate only the inner tables actually needed, and 64-bit systems use four or five levels.
CSE-349 · What is priority inversion and how is it fixed?
A high-priority task waits on a lock held by a low-priority task, which a medium-priority task preempts, so the high task is blocked indefinitely. The Mars Pathfinder resets were a famous case. Priority inheritance temporarily raises the lock holder to the waiter's priority; priority ceiling is an alternative.
CSE-350 · Four processes arrive at time 0 with bursts 6, 8, 7 and 3. What is the average waiting time under non-preemptive SJF?
Run order is 3, 6, 7, 8. Waiting times are 0, 3, 9 and 16, so the average is 28 / 4 = 7 time units. FCFS in arrival order (6, 8, 7, 3) would give (0 + 6 + 14 + 21) / 4 = 10.25.
CSE-351 · Why is epoll more scalable than select or poll?
select and poll pass the entire descriptor set to the kernel on every call and scan it, costing O(n) per call. epoll registers descriptors once and returns only ready ones, so cost scales with active events, which suits servers with tens of thousands of connections. It supports level- and edge-triggered modes.
CSE-352 · How does copy-on-write make fork() efficient?
Parent and child initially share all physical pages, marked read-only. Only when either writes to a page does a fault occur and the kernel copies that single page. Since fork() is often followed by exec(), most pages are never copied.
CSE-353 · When is a spinlock better than a blocking mutex?
On multicore systems when critical sections are very short and the holder is running, because spinning avoids the cost of sleeping and a context switch. On single-core systems, or with long or blocking critical sections, spinning wastes CPU. Many mutexes spin briefly before sleeping.
CSE-354 · What problem can a readers-writer lock cause and how is it handled?
With reader preference, a steady stream of readers can starve writers indefinitely. Writer-preferring or fair (queue-ordered) implementations block new readers once a writer is waiting, trading some read concurrency for bounded writer latency.
CSE-355 · A production Linux process is stuck at 100% CPU. How do you investigate?
Find the hot process and threads with top -H or htop, then sample stacks with perf top/perf record and flame graphs, or language tools like jstack and py-spy. Correlate with recent deploys and logs, and check for busy loops, lock spinning, GC thrashing or regex backtracking.
DBMS & SQL
CSE-356 · When should you use optimistic versus pessimistic locking?
Optimistic locking reads without locks and, at commit, checks a version column (UPDATE … WHERE version = v), retrying on conflict; it suits low contention. Pessimistic locking takes locks up front, such as SELECT … FOR UPDATE; it suits high contention where retries would be costly.
CSE-357 · How does MVCC work, for example in PostgreSQL?
Each update creates a new row version stamped with transaction IDs, and each transaction reads from a snapshot of versions committed before it began. Readers never block writers and vice versa. Old versions are removed later by VACUUM.
CSE-358 · A query became slow in production. How do you diagnose it?
Run EXPLAIN ANALYZE to compare estimated and actual rows and find sequential scans, bad join orders or sorts that spill to disk. Check for missing or unused indexes, stale statistics (ANALYZE), lock waits, parameter-sensitive plans and N+1 query patterns in the application.
CSE-359 · How should you order columns in a composite index?
A B-tree index on (a, b, c) serves queries filtering on a leftmost prefix: a; a and b; or a, b and c. Put equality-filtered columns first and range or sort columns last, and favour columns that the most queries filter on.
CSE-360 · What is a covering index?
An index that contains every column a query needs, either as keys or included columns, so the database can answer from the index alone in an index-only scan without visiting the table. It speeds hot read queries at the cost of larger indexes and slower writes.
CSE-361 · What is write skew and how do you prevent it?
Under snapshot isolation, two transactions read overlapping data, make disjoint writes and together break an invariant, such as two on-call doctors each going off call after seeing the other on call. Prevent it with Serializable isolation, SELECT … FOR UPDATE on the rows read, or a materialized conflict row.
CSE-362 · How do you model a many-to-many relationship such as students and courses?
Create a junction table enrollment(student_id, course_id, …) with foreign keys to both tables and a composite primary key (student_id, course_id). Add an index on (course_id, student_id) for reverse lookups and store relationship attributes such as grade there.
CSE-363 · How do databases handle deadlocks between transactions?
They detect cycles in a wait-for graph, or use lock timeouts, and abort a victim transaction, usually the one with the least work done, which the application must retry. Applications reduce deadlocks by accessing rows in a consistent order and keeping transactions short.
CSE-364 · When is denormalization justified?
In read-heavy systems where joins dominate latency, such as reporting or feeds. Duplicating data or storing precomputed aggregates speeds reads at the cost of extra storage, more complex writes and the risk of inconsistency, which needs triggers, application logic or asynchronous jobs to manage.
CSE-365 · Estimate the height of a B+ tree indexing 1 billion rows with fan-out 500.
Height ≈ ⌈log₅₀₀(10⁹)⌉. Since 500³ = 1.25 × 10⁸ and 500⁴ = 6.25 × 10¹⁰, four levels suffice. With the upper levels cached in memory, a lookup typically needs only one or two disk reads.
Computer Networks
CSE-366 · What happens when you type a URL and press Enter?
The browser parses the URL and checks caches, then resolves DNS. It opens a TCP connection (three-way handshake) and a TLS handshake, sends the HTTP request, and the server, often behind load balancers and CDNs, processes it and responds. The browser parses HTML into the DOM and CSSOM, fetches subresources, runs JavaScript, lays out and paints.
CSE-367 · A 100 Mbps link has 50 ms RTT. What window size is needed for full utilization?
The bandwidth-delay product is 100 × 10⁶ b/s × 0.05 s = 5 × 10⁶ bits ≈ 625 KB. A classic 64 KB window caps throughput at 64 KB / 0.05 s ≈ 1.3 MB/s (≈10.5 Mbps), so TCP window scaling is required.
CSE-368 · Compute transmission and propagation delay for a 1500-byte packet over a 10 Mbps, 2000 km fibre link.
Transmission delay = 1500 × 8 bits / 10⁷ b/s = 1.2 ms. Propagation delay = 2 × 10⁶ m / (2 × 10⁸ m/s) = 10 ms, so propagation dominates on long links.
CSE-369 · Split 192.168.10.0/24 into four equal subnets.
Borrow two bits to get /26 (mask 255.255.255.192): 192.168.10.0, .64, .128 and .192. Each has 62 usable hosts; for example, the first spans .1–.62 with broadcast .63.
CSE-370 · Why was QUIC (HTTP/3) developed?
TCP delivers bytes in order, so one lost packet stalls all multiplexed HTTP/2 streams. QUIC runs over UDP with independent streams, integrates TLS 1.3 for 1-RTT setup (0-RTT on resumption), and supports connection migration across network changes using connection IDs.
CSE-371 · How does TCP congestion control behave after packet loss?
In slow start the congestion window doubles each RTT until a threshold, then grows linearly in congestion avoidance. On triple duplicate ACKs, Reno halves the window (fast recovery); on timeout it falls to one segment. CUBIC grows via a cubic function, and BBR models bottleneck bandwidth and RTT instead of reacting to loss.
CSE-372 · Users report intermittent high latency to a service. How do you troubleshoot the network?
Use mtr or traceroute to locate where latency or loss begins, ping for baseline RTT, and tcpdump or Wireshark to look for retransmissions, zero windows or resets. Check interface errors, DNS resolution times, MTU issues and load balancer health, and correlate with time-of-day traffic.
CSE-373 · What is the difference between OSPF and BGP?
OSPF is a link-state interior gateway protocol: routers flood link states and run Dijkstra to compute shortest paths within one autonomous system. BGP is a path-vector exterior protocol that exchanges reachability between autonomous systems and selects routes by policy and attributes, not just cost.
CSE-374 · What is anycast and where is it used?
The same IP address is advertised from multiple locations, and BGP routes each client to the topologically nearest one. DNS root servers, public resolvers and CDNs use it for low latency and DDoS absorption. It suits short or stateless exchanges, since route changes can move a flow to a different site.
CSE-375 · How can Nagle's algorithm and delayed ACKs together add latency?
Nagle holds small segments until earlier data is acknowledged, while the receiver delays ACKs hoping to piggyback them. For request-response traffic with small writes, each waits on the other, adding delays up to the delayed-ACK timer. Setting TCP_NODELAY or coalescing writes fixes it.
System Design
CSE-376 · Design a URL shortener.
Generate IDs from a distributed counter or range allocator and encode them in base62; 7 characters give 62⁷ ≈ 3.5 × 10¹² codes. Store code → URL in a key-value store, cache hot entries, and redirect with 301 (cacheable) or 302 (trackable). Add rate limiting, custom aliases, expiry and asynchronous click analytics.
CSE-377 · Design a rate limiter for a distributed API.
Identify clients by API key or IP and keep counters in a shared store such as Redis, using a token bucket or sliding-window counter updated atomically with a Lua script. Enforce at the API gateway, return 429 with Retry-After, and choose fail-open or fail-closed behaviour if the store is unavailable.
CSE-378 · How do you design a social news feed?
Fan-out on write pushes each post into followers' precomputed feed caches, giving fast reads but expensive writes for users with millions of followers. Fan-out on read assembles feeds at request time. A hybrid pushes for normal users and pulls celebrity posts at read time, then merges and ranks.
CSE-379 · Design a one-to-one chat system.
Clients hold WebSocket connections to gateway servers, with a presence service mapping users to gateways. Messages get per-conversation sequence IDs, are persisted in a wide-column store partitioned by conversation, and are routed to the recipient's gateway or queued for push notification if offline. Sent, delivered and read receipts are acknowledgements.
CSE-380 · How do you prevent a cache stampede when a hot key expires?
Coalesce requests so only one fetches from the database while others wait (a per-key lock or single-flight). Add random jitter to TTLs, refresh hot keys early in the background, or serve stale data while revalidating.
CSE-381 · Estimate yearly storage for 10 million photo uploads per day at 2 MB each.
10⁷ × 2 MB = 20 TB per day, so about 20 × 365 ≈ 7.3 PB per year. With three-way replication that is about 22 PB; thumbnails and metadata add more, while erasure coding can cut the replication overhead.
CSE-382 · Design a notification service for email, SMS and push.
An API accepts events and writes them to a queue. A router applies user preferences, templates and rate limits, then publishes to per-channel queues consumed by workers that call providers. Use retries with exponential backoff, dead-letter queues, idempotency keys to avoid duplicates and delivery-status tracking.
CSE-383 · Design a search autocomplete service.
Build a trie (or prefix map) offline from query logs, storing the top-k completions at each node so a lookup is O(prefix length). Shard by prefix, cache popular prefixes at the edge, debounce client requests and rebuild or incrementally update rankings periodically.
CSE-384 · Design a web crawler.
Seed a URL frontier with priority and per-host politeness queues. Fetchers respect robots.txt and crawl delays, parse pages and extract links. Deduplicate URLs with a Bloom filter or hash set and content with checksums or SimHash, store pages in object storage, and distribute work by hashing hostnames to workers.
CSE-385 · Two components each have 99.9% availability. What is the combined availability in series and in parallel?
In series both must work: 0.999 × 0.999 ≈ 99.8%. In redundant parallel, the system fails only if both fail: 1 − (0.001)² = 99.9999%, assuming independent failures.
Software Engineering & Testing
CSE-386 · Design a CI/CD pipeline for a microservice.
On each commit: lint, unit tests and static analysis, build an immutable container image tagged with the commit SHA, run integration and contract tests, and scan for vulnerabilities. Deploy to staging, run smoke tests, then promote the same image to production via canary with automatic rollback on SLO breaches.
CSE-387 · Compare blue-green, canary and rolling deployments.
Blue-green runs two full environments and switches traffic at once, enabling instant rollback at double the capacity. Canary sends a small percentage of traffic to the new version and ramps up while monitoring metrics. Rolling replaces instances in batches with no extra capacity, but runs mixed versions during rollout.
CSE-388 · What are the benefits and risks of feature flags?
They decouple deployment from release, enabling trunk-based development, gradual rollouts, A/B tests and kill switches. Risks include combinatorial testing complexity, stale flags becoming technical debt and configuration errors in production, so give flags owners and expiry dates.
CSE-389 · How do you deal with flaky tests?
Track flakiness by re-running and recording failures, quarantine flaky tests so they do not block merges, and fix root causes: timing assumptions, shared state, test-order dependence, real network calls or nondeterministic data. Replace sleeps with explicit waits and isolate test data.
CSE-390 · How would you test a payment processing service?
Unit-test calculation and state-transition logic, contract-test provider APIs with the provider's sandbox, and test idempotency by replaying requests. Include failure-injection tests for timeouts and partial failures, reconciliation checks, concurrency tests for double-spend and security tests for authorization and input handling.
CSE-391 · What is consumer-driven contract testing?
Each consumer records the requests it makes and the responses it expects as a contract, using tools such as Pact. The provider's CI verifies it still satisfies all consumer contracts, catching breaking API changes without running full end-to-end environments.
CSE-392 · What is mutation testing?
A tool introduces small code changes (mutants), such as flipping < to <= or deleting a statement, and runs the test suite. A good suite fails, or "kills", each mutant. The mutation score measures test effectiveness better than line coverage, but runs are expensive.
CSE-393 · What is property-based testing?
Instead of hand-picked examples, you state properties that should hold for all inputs, such as "sorting is idempotent and preserves length", and the framework (Hypothesis, QuickCheck) generates many random inputs and shrinks failures to minimal counterexamples.
CSE-394 · A service has a 99.9% monthly availability SLO. What is its error budget?
A 30-day month has 43,200 minutes, so the budget is 0.1% × 43,200 ≈ 43.2 minutes of downtime, or 0.1% of requests failing. When the budget is exhausted, teams prioritize reliability work over new features.
CSE-395 · How do you safely refactor legacy code with no tests?
First write characterization tests capturing current behaviour at seams, then refactor in small steps behind those tests. For large systems, apply the strangler-fig pattern: route functionality incrementally to new components until the old system can be retired.
Computer Security
CSE-396 · How do you design secure session management for a web app?
Generate long random session IDs server-side and rotate them on login and privilege change. Use cookies with Secure, HttpOnly and SameSite set, enforce idle and absolute timeouts, invalidate sessions server-side on logout, and protect state-changing requests against CSRF.
CSE-397 · How should an application manage secrets such as database passwords and API keys?
Keep them out of source code and images. Store them in a secrets manager (Vault, AWS Secrets Manager) encrypted with KMS keys, inject them at run time with least-privilege identity-based access, rotate them automatically, audit access and scan repositories for leaked credentials.
CSE-398 · What is STRIDE threat modelling?
A framework for enumerating threats per component and data flow: Spoofing, Tampering, Repudiation, Information disclosure, Denial of service and Elevation of privilege. Each maps to a property to protect: authentication, integrity, non-repudiation, confidentiality, availability and authorization.
CSE-399 · Show how to prevent SQL injection in code.
Use parameterized queries so input is bound as data, never concatenated into SQL. Add least-privilege database accounts and allow-list validation for identifiers that cannot be parameterized, such as column names.
cur.execute("SELECT * FROM users WHERE email = %s", (email,))CSE-400 · Design a secure password reset flow.
Respond identically whether or not the account exists. Email a single-use, high-entropy token, store only its hash with a short expiry, and rate-limit requests. On reset, require a strong new password, invalidate the token and existing sessions, and notify the user.
CSE-401 · What is forward secrecy?
A property where compromise of a server's long-term private key does not expose past session traffic, because each session's keys come from ephemeral Diffie-Hellman exchanges (DHE/ECDHE) and are discarded afterwards. TLS 1.3 requires it.
CSE-402 · How do you defend a login endpoint against credential stuffing and brute force?
Rate-limit per account and per IP with progressive delays, require MFA, check passwords against breached-password lists, use bot detection and device fingerprinting, monitor for anomalous login patterns, and avoid revealing whether the username or the password was wrong.
CSE-403 · Why is revoking JWTs difficult and how is it handled?
Stateless JWTs remain valid until expiry because servers do not look them up. Mitigations are short-lived access tokens with refresh tokens that can be revoked server-side, a denylist of token IDs (jti) checked on each request, and rotating signing keys for mass invalidation.
CSE-404 · What is zero-trust architecture?
A model that assumes no implicit trust based on network location. Every request is authenticated, authorized and encrypted based on user and device identity and context, with least privilege, micro-segmentation and continuous monitoring, replacing the perimeter "trusted LAN" model.
CSE-405 · What is SSRF and how is it mitigated?
Server-Side Request Forgery tricks a server into making requests to attacker-chosen URLs, often internal services or the cloud metadata endpoint at 169.254.169.254, to steal credentials. Mitigate with allow-lists of destinations, blocking private and link-local ranges after DNS resolution, egress filtering and IMDSv2-style metadata protection.
Computer Architecture
CSE-406 · Split a 32-bit address for a 32 KiB, 4-way set-associative cache with 64-byte lines.
Lines = 32,768 / 64 = 512; sets = 512 / 4 = 128. The offset is log₂64 = 6 bits, the index log₂128 = 7 bits and the tag 32 − 6 − 7 = 19 bits.
CSE-407 · What speedup does a 5-stage pipeline give for 1000 instructions with no stalls?
Non-pipelined: 1000 × 5 = 5000 cycles. Pipelined: 5 + (1000 − 1) = 1004 cycles. Speedup = 5000 / 1004 ≈ 4.98, approaching the stage count for long instruction streams.
CSE-408 · What is false sharing?
When threads on different cores write to different variables that share the same cache line, the coherence protocol bounces the line between cores, severely slowing both even though no data is truly shared. Fix it by padding or aligning per-thread data to cache-line boundaries.
CSE-409 · Why can loop order change matrix code performance by an order of magnitude?
C stores arrays in row-major order, so iterating for i … for j … a[i][j] accesses consecutive addresses and uses each cache line fully. Swapping the loops strides across rows, causing a cache miss per access. Loop interchange and tiling (blocking) exploit spatial locality.
CSE-410 · What does the roofline model tell you?
Attainable performance = min(peak FLOP/s, memory bandwidth × arithmetic intensity), where intensity is FLOPs per byte moved. Kernels left of the ridge point are memory-bound and gain from better data reuse; those right of it are compute-bound and gain from vectorization and parallelism.
CSE-411 · How does out-of-order execution work?
Instructions are decoded in order, their registers renamed to remove false dependencies (WAR, WAW), and they wait in reservation stations until operands are ready, then execute out of order, as in Tomasulo's algorithm. A reorder buffer retires results in program order, preserving precise exceptions.
CSE-412 · What made Spectre and Meltdown possible?
Speculative execution runs instructions before branches or permission checks resolve. Though results are discarded, their effects on the cache remain, so attackers can infer secret data through cache-timing side channels. Mitigations include kernel page-table isolation, speculation barriers, retpolines and microcode updates.
CSE-413 · What is NUMA and why does it matter for performance?
In Non-Uniform Memory Access systems, each socket has local memory that is faster to reach than another socket's memory. Performance-sensitive software pins threads and allocates memory on the same node, using tools such as numactl, to avoid remote-access latency and interconnect bandwidth limits.
CSE-414 · Why are memory barriers needed?
CPUs and compilers reorder loads and stores for performance. x86 uses a fairly strong model (TSO, which allows store-load reordering), while ARM and POWER allow more reordering. Barriers or language atomics with acquire/release semantics enforce the ordering that lock-free code and synchronization require.
CSE-415 · Compute effective CPI given base CPI 1.0, 1.5 memory references per instruction, a 2% miss rate and a 100-cycle miss penalty.
Memory stall cycles per instruction = 1.5 × 0.02 × 100 = 3. Effective CPI = 1.0 + 3 = 4.0, so the processor runs four times slower than its ideal, showing why cache misses dominate.
Cloud & Distributed Systems
CSE-416 · Explain the CAP theorem.
In a distributed system, during a network partition you must choose between consistency (every read sees the latest write) and availability (every request to a non-failed node gets a response). CP systems such as ZooKeeper reject some requests; AP systems such as Cassandra (at low consistency levels) stay up and reconcile later.
CSE-417 · What does PACELC add to CAP?
If there is a Partition, choose Availability or Consistency; Else, even when healthy, choose between Latency and Consistency. For example, DynamoDB-style stores are PA/EL, while strongly consistent systems like Spanner are PC/EC.
CSE-418 · How does the Raft consensus algorithm work?
Nodes are followers, candidates or a leader. A follower that times out becomes a candidate and requests votes; a majority makes it leader for that term. The leader appends client commands to its log and replicates them; an entry is committed once stored on a majority. Election restrictions ensure leaders hold all committed entries.
CSE-419 · Why is two-phase commit problematic and what is the alternative?
In 2PC a coordinator asks participants to prepare, then commit. If the coordinator fails after prepare, participants block holding locks until it recovers. Microservices often use Sagas instead: a sequence of local transactions with compensating actions to undo completed steps on failure, accepting eventual consistency.
CSE-420 · How can you achieve effectively-once message processing?
Networks only provide at-most-once or at-least-once delivery. Use at-least-once delivery with idempotent consumers that deduplicate by message ID, or atomically commit outputs together with consumer offsets, as Kafka transactions do.
CSE-421 · What are the challenges of an active-active multi-region database?
Concurrent writes in different regions conflict and must be resolved by last-writer-wins, CRDTs or application merge logic, or avoided by assigning each record a home region. Cross-region latency makes synchronous consensus slow, so designs trade consistency for local write latency.
CSE-422 · How do leases and fencing tokens make leader election safe?
A leader holds a time-limited lease from a coordination service and must renew it. Because a paused old leader may still think it is leader, each grant carries a monotonically increasing fencing token, and storage rejects writes carrying a token lower than the highest it has seen.
CSE-423 · What is the transactional outbox pattern?
To update a database and publish an event atomically, the service writes the event into an outbox table in the same local transaction. A relay process or change-data-capture then publishes outbox rows to the broker, avoiding the dual-write problem where one succeeds and the other fails.
CSE-424 · How do circuit breakers, bulkheads and retries improve resilience?
A circuit breaker stops calling a failing dependency after an error threshold and probes it later. Bulkheads isolate resources such as thread pools per dependency so one slow service cannot exhaust everything. Retries use exponential backoff with jitter and limits to avoid retry storms.
CSE-425 · A Kubernetes deployment has 4 pods at 90% average CPU with a 60% HPA target. How many pods will it scale to?
The HPA computes desired = ⌈current × currentMetric / target⌉ = ⌈4 × 90 / 60⌉ = 6 pods, bounded by the configured min and max replicas.
Other levels: Basic · Intermediate · Tricky · All Computer Science questions