Tricky Computer Science interview questions

75 questions with answers (CSE-426 to CSE-500). Try each one aloud before reading the answer.

Data Structures

CSE-426 · "Hash map lookup is always O(1)." Can it be O(n)?

Trap: O(1) is the average case, not a guarantee. If many keys collide, for example with a poor hash function or a hash-flooding attack, a chained bucket degrades to O(n). Java 8+ converts long chains into balanced trees, bounding the worst case at O(log n).

CSE-427 · "Reversing a singly linked list needs a stack or extra memory." True?

Trap: No. It can be done iteratively in O(n) time and O(1) space with three pointers.

prev, curr = None, head
while curr:
    curr.next, prev, curr = prev, curr, curr.next
return prev

CSE-428 · Why are arrays 0-indexed? Is it just tradition?

Trap: It is not arbitrary. An index is an offset from the base address: addr = base + i × size, so the first element is at offset 0. Starting at 1 would need a subtraction on every access or a wasted slot.

CSE-429 · "Use a linked list when you have frequent insertions." Always?

Trap: O(1) insertion applies only once you already hold the node; finding the position is O(n). Linked nodes are scattered in memory and cause cache misses, so a contiguous dynamic array often outperforms a linked list even for insert-heavy workloads.

CSE-430 · "Searching a binary search tree is O(log n)." Is that guaranteed?

Trap: Only if the tree is balanced. Inserting sorted keys into a plain BST creates a linked-list shape with height n, making search O(n). Self-balancing trees such as AVL or red-black guarantee O(log n).

CSE-431 · "A heap stores elements in sorted order." Right?

Trap: No. A heap is only partially ordered: each parent beats its children, but siblings and levels are not sorted. Only the root is known to be min or max, and searching for an arbitrary element is O(n).

CSE-432 · "Building a heap from n elements takes O(n log n)." Correct?

Trap: Inserting elements one by one does, but bottom-up heapify (sift-down from the last internal node to the root) is O(n), because most nodes are near the bottom and sift down only a short distance.

Algorithms & Complexity

CSE-433 · "An O(1) algorithm is always faster than an O(n) one." True?

Trap: Big-O describes growth and ignores constants. For small n, a linear scan of a cache-friendly array can beat a hash lookup with a costly hash computation and pointer chasing. Asymptotic order only guarantees the comparison for sufficiently large n.

CSE-434 · "mid = (lo + hi) / 2 is a correct binary search midpoint." Any problem?

Trap: With fixed-width integers, lo + hi can overflow for large arrays, producing a negative index; this bug once existed in Java's standard library. Use mid = lo + (hi − lo) / 2, or an unsigned shift in Java.

CSE-435 · "Naive recursive Fibonacci is O(n) because it computes n numbers." Correct?

Trap: Each call spawns two more, recomputing the same subproblems, so time grows exponentially, about O(φⁿ) with φ ≈ 1.618. Memoization or iteration reduces it to O(n), and matrix exponentiation to O(log n).

CSE-436 · "Quicksort is always the best general-purpose sort." Is it?

Trap: Quicksort has an O(n²) worst case and is not stable. Standard libraries use hybrids: introsort (quicksort that falls back to heap sort, with insertion sort for small runs) in C++, and Timsort (stable merge/insertion hybrid) in Python and for Java objects.

CSE-437 · "Dijkstra's algorithm works with negative edges as long as there are no negative cycles." True?

Trap: No. Dijkstra finalizes a vertex when it is popped, assuming no later path can be shorter, which a negative edge can violate. Use Bellman-Ford, or Johnson's reweighting for all-pairs.

CSE-438 · "An O(n²) algorithm is too slow." Is it, for n = 1000?

Trap: Feasibility depends on actual n and constants, not just the order. n² = 10⁶ simple operations runs in milliseconds; O(n²) only becomes a problem around n of 10⁵ or more, where it reaches 10¹⁰ operations.

CSE-439 · "The O(nW) knapsack DP is polynomial, so knapsack is in P." Right?

Trap: O(nW) is pseudo-polynomial: W is a numeric value, and the input size is about log W bits, so the runtime is exponential in input length. 0/1 knapsack remains NP-complete in its decision form.

OOP & Design Patterns

CSE-440 · "Marking a field private keeps the data secure." Does it?

Trap: Access modifiers are a compile-time encapsulation tool, not a security boundary. Reflection, serialization, debuggers and memory inspection can still read private data. Protect secrets with encryption and process or OS-level isolation.

CSE-441 · "A Square is a Rectangle, so Square should extend Rectangle." Good design?

Trap: Mathematically yes, behaviourally no. If Rectangle has independent setWidth and setHeight, code expecting area = w × h breaks when given a Square, violating Liskov Substitution. Use immutable shapes or a common Shape interface.

CSE-442 · Can you override a static method in Java?

Trap: No. A static method with the same signature in a subclass hides the parent's method; the call is resolved at compile time by the reference type, not the object's run-time type, so there is no polymorphism.

CSE-443 · Can you overload methods that differ only in return type?

Trap: Not in Java or C++. The compiler selects overloads by name and parameter types, and a call's return value can be ignored, so int f() and double f() would be ambiguous and are rejected as a compile error.

CSE-444 · "Calling a virtual function from a C++ base-class constructor invokes the derived override." True?

Trap: No. While the base constructor runs, the derived part does not yet exist and the vptr points to the base vtable, so the base version is called; a pure virtual call there is undefined behaviour. Java does dispatch to the override, which can see uninitialized fields.

CSE-445 · "Singleton is the right way to share state across an application." Is it?

Trap: A singleton is global mutable state in disguise: it hides dependencies, couples code, complicates concurrency and makes unit testing hard. Prefer creating one instance at the composition root and passing it through dependency injection.

CSE-446 · "Using more design patterns makes the code better." Agree?

Trap: Patterns solve specific recurring problems. Applying them where the problem does not exist adds indirection and classes without benefit, which is over-engineering. Start simple and introduce a pattern when the need, such as varying behaviour, actually appears (YAGNI).

Programming Languages (C/C++/Java/Python)

CSE-447 · "Java passes objects by reference." Correct?

Trap: Java is always pass-by-value; for objects, the value passed is a copy of the reference. A method can mutate the object, but reassigning the parameter, as in a swap function, does not affect the caller's variable.

CSE-448 · What is wrong with def add(item, items=[]) in Python?

Trap: Default arguments are evaluated once, at function definition, so every call without items shares and mutates the same list. Use None as the default.

def add(item, items=None):
    items = [] if items is None else items
    items.append(item); return items

CSE-449 · Does 0.1 + 0.2 == 0.3 evaluate to true?

Trap: No, in IEEE 754 binary floating point it is false. 0.1 and 0.2 cannot be represented exactly, and the sum is 0.30000000000000004. Compare with a tolerance (math.isclose) or use decimal or integer types for money.

CSE-450 · What does i = i++; do in C?

Trap: In C it is undefined behaviour, because i is modified twice without sequencing, so any result is allowed. In Java it is well defined and leaves i unchanged, and C++17 also defines it. Never write it.

CSE-451 · Inside a C function void f(int arr[]), does sizeof(arr) give the array's size?

Trap: No. An array parameter decays to a pointer, so sizeof(arr) is the pointer size, typically 8 bytes on 64-bit systems. Pass the length as a separate argument.

CSE-452 · In Python, a = 256; b = 256; a is b is True. So is compares values?

Trap: No. is compares object identity. CPython caches small integers from −5 to 256, so they share an object, but larger values or computed strings may not. This is an implementation detail; use == for value equality.

Operating Systems

CSE-453 · "Multithreading always makes a program faster." True?

Trap: No. Context switching, lock contention, false sharing and cache effects add overhead, and Amdahl's law caps speedup by the serial fraction. CPU-bound work gains only up to the number of cores, and in CPython the GIL blocks parallel bytecode; threads help I/O-bound work most.

CSE-454 · "Giving a process more page frames always reduces page faults." True?

Trap: Not for FIFO replacement. Bélády's anomaly shows that for the reference string 1,2,3,4,1,2,5,1,2,3,4,5, FIFO gives 9 faults with 3 frames but 10 with 4. Stack algorithms such as LRU and Optimal never show this anomaly.

CSE-455 · "A binary semaphore is the same as a mutex." Right?

Trap: They both admit one holder, but a mutex has ownership: only the locking thread may unlock it, which enables priority inheritance, recursion checks and error detection. A semaphore can be signalled by any thread, which suits signalling between threads, not just locking.

CSE-456 · "Declaring a shared variable volatile in C makes it thread-safe." True?

Trap: In C and C++, volatile only stops the compiler from caching or eliding accesses; it is meant for memory-mapped I/O and signal handlers. It provides neither atomicity nor memory ordering. Use _Atomic/std::atomic or mutexes. Java's volatile has different, stronger semantics.

CSE-457 · Can you remove a zombie process with kill -9?

Trap: No. A zombie has already exited; only its process-table entry remains, so signals do nothing. The parent must call wait(), or the parent must be terminated so init (or a subreaper) adopts and reaps the zombie.

CSE-458 · "Calling free() returns the memory to the operating system." Does it?

Trap: Usually not immediately. The allocator typically keeps freed blocks in its own free lists for reuse, so the process's resident size may not shrink. Large allocations served by mmap are often returned on free, but this depends on the allocator.

DBMS & SQL

CSE-459 · "Adding an index always speeds up queries." True?

Trap: No. Indexes slow every insert, update and delete and use storage. For low-selectivity predicates, or queries that return a large fraction of rows, the optimizer may prefer a sequential scan. Wrapping a column in a function also prevents ordinary index use.

CSE-460 · Does WHERE col = NULL find rows where col is null?

Trap: No. Comparisons with NULL yield UNKNOWN, which is not true, so no rows match. Use IS NULL. Similarly, x NOT IN (subquery) returns no rows if the subquery contains a NULL; NOT EXISTS avoids this.

CSE-461 · "COUNT(*) and COUNT(column) return the same number." Do they?

Trap: Not when the column has NULLs. COUNT(*) counts all rows, while COUNT(column) counts only rows where that column is non-null, and COUNT(DISTINCT column) also removes duplicates.

CSE-462 · "Serializable isolation means transactions run one after another." True?

Trap: No. Serializable guarantees that the outcome is equivalent to some serial order, while transactions still execute concurrently using locking, or snapshot-based conflict detection that aborts conflicting transactions, which must then be retried.

CSE-463 · "Without ORDER BY, SELECT returns rows in insertion order." True?

Trap: SQL tables are unordered sets; without ORDER BY the order is unspecified and can change with execution plans, parallelism, updates or vacuuming. Always specify ORDER BY when order matters, especially with LIMIT.

CSE-464 · "NoSQL databases are faster and more scalable than SQL databases." Always?

Trap: It depends on the workload. NoSQL stores often scale horizontally by giving up joins or multi-row transactions, but relational databases with good indexing handle very large workloads, and distributed SQL systems scale horizontally too. Choose by access patterns and consistency needs, not labels.

Computer Networks

CSE-465 · "When send() succeeds over TCP, the receiver application has the data." True?

Trap: No. A successful send() means data was copied to the local kernel buffer; even a TCP ACK only means the remote kernel received it. The remote application may crash before reading it. Reliable systems need application-level acknowledgements.

CSE-466 · "UDP is unreliable, so it should never be used where reliability matters." Correct?

Trap: UDP's lack of built-in reliability lets applications add exactly the reliability they need. QUIC, which carries HTTP/3, builds reliable, ordered, encrypted streams on top of UDP, and DNS retries at the application level.

CSE-467 · "HTTPS hides which website I am visiting." Does it?

Trap: HTTPS encrypts the URL path, headers and content, but the destination IP is visible, and the hostname usually leaks through plaintext DNS queries and the TLS SNI field. Encrypted DNS (DoH/DoT) and Encrypted Client Hello reduce this.

CSE-468 · "Doubling bandwidth halves page load time." True?

Trap: Only for large, bandwidth-bound transfers. Web pages involve many small requests dominated by round trips for DNS, TCP and TLS handshakes and TCP slow start, so latency matters more. Reducing RTTs through CDNs, connection reuse and HTTP/2 or HTTP/3 often helps more.

CSE-469 · "127.0.0.1 is the only loopback address." Right?

Trap: The whole 127.0.0.0/8 block (over 16 million addresses) is reserved for loopback in IPv4; 127.0.0.1 is just the conventional one. IPv6 has a single loopback address, ::1.

CSE-470 · "A MAC address is permanent and globally unique, so it reliably identifies a device." True?

Trap: MAC addresses can be changed in software and spoofed trivially, and modern phones and laptops randomize them per network for privacy. They are also visible only within the local layer-2 segment, so they are weak identifiers.

System Design

CSE-471 · "Adding a cache always reduces database load." True?

Trap: Not necessarily. With a low hit ratio the cache adds latency and cost. Cold starts or a cache failure can send full traffic to the database, and synchronized expiry causes stampedes. Caches also introduce staleness and invalidation complexity.

CSE-472 · "Moving to microservices makes the system scalable." Automatically?

Trap: Microservices add network latency, partial failures, distributed data consistency and operational overhead. Services that share a database or must deploy together become a distributed monolith. They pay off when team size and independent scaling needs justify the complexity.

CSE-473 · "Adding more database replicas increases write throughput." Does it?

Trap: No. In leader-based replication every write still goes through the primary and must be applied on every replica, so replicas scale reads, not writes. Write capacity grows by sharding or partitioning data across multiple leaders.

CSE-474 · "99.99% availability is only slightly better than 99.9%." Is it?

Trap: It allows ten times less downtime: 99.9% permits about 8.76 hours per year, while 99.99% permits about 52.6 minutes. Each extra nine typically demands much more redundancy, automation and cost.

CSE-475 · "Round-robin load balancing spreads load evenly." True?

Trap: It spreads request counts evenly, not work. Requests vary in cost and servers vary in capacity, so some back ends overload. Least-connections, weighted algorithms, or "power of two choices" adapt better to uneven load.

CSE-476 · "Average latency is the best measure of user experience." Agree?

Trap: Averages hide the tail. A 50 ms mean can hide a p99 of 2 s, and when a page fans out to many services, the slowest call determines the response, so most page loads hit some service's tail. Track percentiles such as p95 and p99.

Software Engineering & Testing

CSE-477 · "100% code coverage means the code is bug-free." True?

Trap: Coverage shows which lines ran, not that results were checked correctly. Tests can execute every line without meaningful assertions, and coverage misses absent requirements, edge-case inputs and concurrency issues. Testing can show the presence of bugs, not their absence.

CSE-478 · "Adding more developers to a late project will speed it up." Will it?

Trap: Brooks's law says adding people to a late software project makes it later, because newcomers need ramp-up time and communication paths grow as n(n − 1)/2. Reducing scope or fixing process bottlenecks is usually more effective.

CSE-479 · "git revert deletes a commit from history." Does it?

Trap: No. git revert creates a new commit that undoes the changes, preserving history, which is safe on shared branches. git reset moves the branch pointer and can drop commits, which rewrites history and disrupts collaborators if pushed.

CSE-480 · "Agile means no documentation and no planning." True?

Trap: The Agile Manifesto values working software over comprehensive documentation, not instead of it. Agile teams plan continuously through backlogs, sprint planning and roadmaps, and keep documentation that is useful, lean and up to date.

CSE-481 · "The best unit tests mock every dependency." Agree?

Trap: Over-mocking couples tests to implementation details, so refactoring breaks them even when behaviour is correct, and the mocks can drift from real behaviour. Mock slow or external boundaries such as network and payment providers, and use real or in-memory collaborators otherwise.

CSE-482 · "This legacy code is messy; we should rewrite it from scratch." Good idea?

Trap: Full rewrites often take far longer than planned, lose hidden business rules embedded in the old code and freeze feature delivery. Incremental refactoring behind tests, or strangler-fig replacement, usually delivers value with much lower risk.

Computer Security

CSE-483 · "Base64-encoding a password protects it." Does it?

Trap: Base64 is an encoding, not encryption; it uses no key and anyone can decode it instantly. It only makes binary data text-safe. Protect data in transit with TLS and store passwords with a slow, salted hash.

CSE-484 · "Hashing passwords with SHA-256 is secure." Is it?

Trap: SHA-256 is designed to be fast, so GPUs can test billions of guesses per second, and unsalted hashes fall to rainbow tables. Use a salted, deliberately slow password-hashing function such as Argon2, bcrypt or scrypt.

CSE-485 · "The padlock icon means the website is safe." True?

Trap: The padlock means the connection is encrypted to whoever holds a certificate for that domain. Phishing sites obtain valid certificates easily, so HTTPS says nothing about the site owner's honesty or the security of its code.

CSE-486 · "If data is encrypted, attackers cannot tamper with it." True?

Trap: Encryption provides confidentiality, not integrity. Unauthenticated modes such as CBC or CTR let attackers flip bits or exploit padding oracles. Use authenticated encryption (AEAD) such as AES-GCM or ChaCha20-Poly1305, or add a MAC.

CSE-487 · "If attackers do not know how our algorithm works, it is secure." Sound reasoning?

Trap: Kerckhoffs's principle says a system should stay secure even if everything except the key is public. Secret designs are eventually reverse-engineered and lack expert review. Obscurity can add a thin extra layer but must never be the main defence.

CSE-488 · "We validate input with JavaScript in the browser, so the server is safe." Is it?

Trap: Attackers can bypass client-side checks by calling the API directly with tools like curl or an intercepting proxy. Client validation is only for user experience; all validation and authorization must be enforced on the server.

Computer Architecture

CSE-489 · "A CPU with a higher clock speed is always faster." True?

Trap: Performance = clock rate × instructions per cycle, further limited by memory latency, cache size and core count. A lower-clocked CPU with a wider, smarter microarchitecture and larger caches can outperform a higher-clocked one; this is why clock races ended.

CSE-490 · "A 64-bit build of a program is always faster than a 32-bit build." True?

Trap: Not always. 64-bit pointers double pointer sizes, increasing memory use and cache pressure for pointer-heavy data structures. On x86-64, gains come mostly from extra registers and a better calling convention, so results vary by workload.

CSE-491 · "Pipelining makes each instruction execute faster." Right?

Trap: No. Pipelining increases throughput by overlapping instructions; each instruction's latency stays the same or grows slightly because of pipeline-register overhead. Hazards and stalls further reduce the ideal speedup.

CSE-492 · "Doubling the cache size will halve the miss rate." True?

Trap: Miss rate shows diminishing returns, because compulsory misses remain and conflict misses depend on associativity. Larger caches also have longer hit times, so beyond the working-set size, extra capacity gives little benefit and can even slow hits.

CSE-493 · "1 KB is always 1024 bytes." Right?

Trap: In SI units, 1 kB = 1000 bytes, while 1 KiB = 1024 bytes (IEC binary prefixes). Drive makers use decimal units, which is why a "1 TB" disk shows about 931 GiB in an OS that reports binary units. Context and notation matter.

CSE-494 · "Since SRAM is faster, main memory should be made of SRAM." Why isn't it?

Trap: SRAM uses about six transistors per bit versus DRAM's one transistor and one capacitor, so it is much less dense, more expensive and uses more area per bit. That is why SRAM is used for small caches and registers while DRAM provides capacity.

Cloud & Distributed Systems

CSE-495 · "CAP means you pick any two of consistency, availability and partition tolerance." Correct?

Trap: Partitions are not optional in a real network, so you cannot choose to give up partition tolerance. The real choice is between consistency and availability while a partition is happening; when there is no partition, a system can provide both.

CSE-496 · "Moving to the cloud always reduces cost." True?

Trap: Cloud converts capital expense into operating expense and makes elasticity easy, but steady, predictable workloads, over-provisioned instances, data egress charges and unmanaged resources can cost more than on-premises. Savings require right-sizing, autoscaling, reserved pricing and governance.

CSE-497 · "Timestamps from synchronized server clocks can reliably order events across nodes." Can they?

Trap: NTP-synchronized clocks still drift and skew by milliseconds or more and can jump backwards, so timestamp order may contradict causality and last-writer-wins can lose data. Use logical or vector clocks, hybrid logical clocks, or bounded-uncertainty clocks like Spanner's TrueTime.

CSE-498 · "Containers are isolated just like virtual machines." True?

Trap: Containers share the host kernel, so a kernel vulnerability or misconfiguration (privileged mode, mounted Docker socket) can lead to host escape. VMs isolate at the hardware-virtualization level. Sandboxed runtimes such as gVisor or Kata Containers narrow the gap.

CSE-499 · "Adding a fourth node to a three-node Raft cluster improves fault tolerance." Does it?

Trap: No. A majority of 4 is 3, so the cluster still tolerates only one failure, the same as with three nodes, while adding replication overhead. A cluster of 2f + 1 nodes tolerates f failures, which is why odd sizes like 3, 5 or 7 are used.

CSE-500 · "Serverless means there are no servers to worry about." True?

Trap: Servers still exist; the provider manages them. You still face cold-start latency, execution-time and memory limits, concurrency limits that can throttle traffic, vendor lock-in, and costs that can exceed containers for steady high-volume workloads.

Other levels: Basic · Intermediate · Advanced · All Computer Science questions