Placement Interview Questions and Answers

50 of the questions that come up most often in campus placement and fresher interviews, with clear answers you can explain in your own words. They cover coding, OOP, DBMS, operating systems, networking, system design basics and the HR round.

Data Structures & Algorithms

Most technical rounds open with one or two coding problems. Interviewers care less about the final code than about how you reach it: clarify the input, state a brute-force approach, then improve it and explain its time and space complexity.

How do you reverse a singly linked list?

Walk the list once with three pointers: prev (initially null), curr (head) and next. At each step save next = curr.next, point curr.next back to prev, then move prev and curr forward. When curr becomes null, prev is the new head. It runs in O(n) time and O(1) extra space. A recursive version is shorter but uses O(n) stack space.

How do you detect a cycle in a linked list?

Use Floyd's tortoise-and-hare: move a slow pointer one step and a fast pointer two steps at a time. If they ever meet, there is a cycle; if fast reaches null, there is none. To find where the cycle starts, reset one pointer to the head and advance both one step at a time — they meet at the cycle's entry. O(n) time, O(1) space.

Find two numbers in an array that add up to a target (Two Sum).

Brute force checks every pair in O(n²). The standard answer uses a hash map: for each element x, check whether target − x is already in the map; if not, store x with its index. This is O(n) time and O(n) space. If the array is sorted, two pointers from both ends give O(n) time with O(1) space.

What is the difference between an array and a linked list?

An array stores elements in contiguous memory, so index access is O(1) and it is cache-friendly, but inserting or deleting in the middle is O(n) because elements must shift. A linked list stores nodes anywhere in memory joined by pointers, so insertion and deletion at a known node are O(1), but reaching the k-th element is O(k) and every node pays extra memory for its pointer.

Explain how a hash map works internally.

A hash map is an array of buckets. A hash function turns the key into an integer, which is reduced to a bucket index. Two keys landing in the same bucket is a collision, handled by chaining (a list or tree per bucket) or open addressing (probing for another slot). When the load factor passes a threshold, the table is resized and entries are rehashed. Average lookup and insert are O(1); the worst case is O(n) when many keys collide.

When would you use a stack versus a queue?

A stack is last-in-first-out: use it for undo history, matching brackets, evaluating expressions and depth-first search (the call stack is one). A queue is first-in-first-out: use it for breadth-first search, task scheduling, and buffering requests in arrival order.

Check whether a string of brackets is balanced.

Scan left to right with a stack. Push every opening bracket. For a closing bracket, the stack must be non-empty and its top must be the matching opener — pop it, otherwise return false. At the end the string is balanced only if the stack is empty. O(n) time and O(n) space.

Explain binary search and its common pitfalls.

Binary search finds a value in a sorted array by comparing with the middle element and discarding half the range each step, giving O(log n). Common bugs are overflow in (low + high) / 2 (use low + (high − low) / 2), off-by-one errors in the loop condition (low <= high versus low < high), and infinite loops when the bounds do not shrink.

Compare merge sort and quick sort.

Merge sort always runs in O(n log n), is stable, and needs O(n) extra space; it suits linked lists and external sorting. Quick sort averages O(n log n) and sorts in place, so it is usually faster in practice thanks to cache locality, but it degrades to O(n²) with bad pivots — randomised or median-of-three pivots make that unlikely. Quick sort is not stable.

What is the difference between BFS and DFS?

Breadth-first search explores a graph level by level using a queue, so on an unweighted graph it finds the shortest path in edges. Depth-first search goes as deep as possible along one branch before backtracking, using recursion or a stack; it is the basis for topological sort, cycle detection and finding connected components. Both run in O(V + E).

What is dynamic programming? Explain with an example.

Dynamic programming solves problems that have overlapping subproblems and optimal substructure by solving each subproblem once and storing the result. Fibonacci is the classic example: naive recursion is exponential, but memoisation (top-down) or filling a table from the base cases (bottom-up) makes it O(n). Coin change, longest common subsequence and 0/1 knapsack follow the same pattern.

Find the maximum sum of a contiguous subarray.

Kadane's algorithm keeps a running sum: at each element choose the larger of the element alone or the element plus the running sum, and track the best value seen. That is O(n) time and O(1) space. Handle the all-negative case by initialising the answer with the first element rather than 0.

How would you find the k-th largest element in an array?

Keep a min-heap of size k: push each element and pop when the heap exceeds k; the top is the answer. This is O(n log k) time and O(k) space. Quickselect averages O(n) but is O(n²) in the worst case. Sorting first works too, at O(n log n).

What are the different ways to traverse a binary tree?

Depth-first traversals are inorder (left, root, right — gives sorted order for a binary search tree), preorder (root, left, right — useful for copying a tree) and postorder (left, right, root — useful for deleting or evaluating it). Level-order traversal visits nodes level by level using a queue.

Design an LRU cache with O(1) get and put.

Combine a hash map with a doubly linked list. The map points each key to its list node; the list keeps nodes in recency order. On get, move the node to the front. On put, insert or update at the front, and if capacity is exceeded remove the node at the tail and delete its key from the map. Every operation is O(1).

Object-Oriented Programming

OOP questions are near-universal in fresher interviews, especially at service companies. Answer with a short definition followed by a concrete example from Java, C++ or Python.

What are the four pillars of OOP?

Encapsulation bundles data with the methods that operate on it and hides internal state behind a public interface. Abstraction exposes what an object does while hiding how. Inheritance lets a class reuse and extend another class. Polymorphism lets one interface take many forms — a single method call behaves differently depending on the object’s actual type.

What is the difference between method overloading and overriding?

Overloading means several methods in the same class share a name but differ in parameter lists; the compiler picks one at compile time (static polymorphism). Overriding means a subclass provides its own implementation of a method already defined in its parent with the same signature; the version is chosen at runtime from the object’s actual type (dynamic polymorphism).

Abstract class versus interface — when do you use each?

An abstract class can hold state, constructors and implemented methods, and a class can extend only one. An interface defines a contract that many unrelated classes can implement, and a class can implement several. Use an abstract class to share code among closely related types; use an interface to describe a capability, such as Comparable or Runnable.

Explain the SOLID principles.

Single Responsibility: a class should have one reason to change. Open/Closed: open for extension, closed for modification. Liskov Substitution: subclasses must be usable wherever their parent is expected. Interface Segregation: prefer small, specific interfaces over one large one. Dependency Inversion: depend on abstractions, not concrete implementations.

What is the Singleton pattern and what are its drawbacks?

A Singleton ensures a class has exactly one instance and provides a global access point, typically through a private constructor and a static getInstance method (made thread-safe with double-checked locking or an enum in Java). Its drawbacks: it is effectively global state, it hides dependencies, and it makes unit testing harder. Dependency injection is often the better choice.

Composition versus inheritance — which should you prefer?

Inheritance models an “is-a” relationship and couples the subclass tightly to the parent’s implementation. Composition models “has-a” by holding other objects and delegating to them, which is more flexible and can change at runtime. The common guideline is to favour composition and use inheritance only for genuine is-a relationships.

DBMS & SQL

Expect at least one SQL query to write on paper or a shared editor, plus theory on normalisation, transactions and indexing.

What are the ACID properties?

Atomicity: a transaction completes fully or not at all. Consistency: a transaction moves the database from one valid state to another, respecting all constraints. Isolation: concurrent transactions do not see each other’s intermediate state. Durability: once committed, changes survive crashes, usually via a write-ahead log.

Explain normalisation and the first three normal forms.

1NF: every column holds atomic values and there are no repeating groups. 2NF: in 1NF and every non-key column depends on the whole primary key, not part of a composite key. 3NF: in 2NF and no non-key column depends on another non-key column (no transitive dependencies). Normalisation reduces redundancy and update anomalies; read-heavy systems sometimes denormalise deliberately for speed.

What is the difference between DELETE, TRUNCATE and DROP?

DELETE removes selected rows with a WHERE clause, is logged row by row, fires triggers and can be rolled back. TRUNCATE removes all rows quickly by deallocating pages, resets identity counters and usually cannot be filtered. DROP removes the whole table — structure, data, indexes and constraints.

Explain the types of SQL joins.

INNER JOIN returns only rows that match in both tables. LEFT JOIN returns every row from the left table, with NULLs where the right side has no match; RIGHT JOIN is the mirror image. FULL OUTER JOIN returns all rows from both sides. CROSS JOIN returns the Cartesian product. A self join joins a table to itself, for example to pair employees with their managers.

Write a query to find the second-highest salary.

One portable approach: SELECT MAX(salary) FROM employees WHERE salary < (SELECT MAX(salary) FROM employees). With window functions, use DENSE_RANK() OVER (ORDER BY salary DESC) and filter for rank 2 — this also generalises to the N-th highest and handles ties correctly.

What is an index and when can it hurt performance?

An index is a separate structure, usually a B+ tree, that lets the database find rows without scanning the whole table, turning lookups from O(n) into roughly O(log n). Indexes cost storage and slow down INSERT, UPDATE and DELETE because every index must be updated. They help little on low-cardinality columns or when a query has to read most of the table anyway.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping and cannot use aggregate functions. HAVING filters groups after GROUP BY and can use aggregates — for example, departments having COUNT(*) > 10.

Primary key versus unique key versus foreign key?

A primary key uniquely identifies each row, cannot be NULL, and a table has only one. A unique key also enforces uniqueness but typically allows a NULL, and a table can have several. A foreign key references a primary or unique key in another table to enforce referential integrity between them.

Operating Systems

OS questions test fundamentals rather than trivia. Processes, threads, scheduling, deadlocks and memory management cover most of what is asked.

What is the difference between a process and a thread?

A process is an independent program in execution with its own address space, file handles and resources. Threads live inside a process and share its memory and resources, but each has its own stack and registers. Threads are cheaper to create and switch between, but shared memory means they need synchronisation to avoid race conditions.

What is a deadlock and what conditions cause it?

A deadlock is when processes wait on each other forever. Four conditions must hold at once: mutual exclusion, hold and wait, no preemption, and circular wait. Breaking any one prevents deadlock — for example, always acquiring locks in a fixed global order removes circular wait. The Banker’s algorithm is the textbook avoidance technique.

Explain paging and virtual memory.

Virtual memory gives every process the illusion of a large private address space. Paging splits that space into fixed-size pages, mapped to physical frames through a page table, with a TLB caching recent translations. Pages not in RAM live on disk; touching one triggers a page fault and the OS loads it, evicting another page using a policy such as LRU.

What is the difference between a mutex and a semaphore?

A mutex is a lock with ownership: only the thread that locked it may unlock it, and it guards a critical section for one thread at a time. A semaphore is a counter that allows up to N concurrent holders and can be signalled by any thread, which makes it useful for limiting access to a pool of resources or for signalling between threads.

Name common CPU scheduling algorithms.

First-Come-First-Served is simple but suffers from the convoy effect. Shortest Job First minimises average waiting time but needs burst-time estimates and can starve long jobs. Round Robin gives each process a time quantum, which suits time-sharing systems. Priority scheduling can starve low-priority work, which ageing fixes. Multilevel feedback queues combine these ideas.

Computer Networks

Networking questions are common for backend and full-stack roles. Being able to explain what happens between typing a URL and seeing a page covers a lot of ground.

What is the difference between TCP and UDP?

TCP is connection-oriented: it uses a three-way handshake and guarantees ordered, reliable delivery with retransmission, flow control and congestion control. UDP is connectionless with no delivery or ordering guarantees, which makes it lighter and faster. Use TCP for web pages, email and file transfer; UDP for DNS lookups, video calls and online games, where speed matters more than a lost packet.

What happens when you type a URL into a browser?

The browser resolves the domain to an IP address through DNS (browser cache, OS cache, resolver, then root, TLD and authoritative servers). It opens a TCP connection, performs a TLS handshake for HTTPS, and sends an HTTP request. The server responds with HTML; the browser parses it, fetches CSS, JavaScript and images, builds the DOM and CSSOM, then lays out and paints the page.

Name the layers of the OSI model.

From bottom to top: Physical, Data Link, Network, Transport, Session, Presentation and Application. In practice the TCP/IP model is used, with four layers: Link, Internet (IP), Transport (TCP/UDP) and Application (HTTP, DNS and so on).

How is HTTPS different from HTTP?

HTTPS is HTTP over TLS. During the TLS handshake the server presents a certificate signed by a trusted certificate authority, and both sides agree on a symmetric session key using asymmetric cryptography. After that, all traffic is encrypted and integrity-protected, preventing eavesdropping and tampering.

What do the HTTP status code classes mean?

1xx are informational, 2xx success (200 OK, 201 Created), 3xx redirection (301 permanent, 302 temporary, 304 not modified), 4xx client errors (400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, 429 too many requests) and 5xx server errors (500 internal error, 502 bad gateway, 503 unavailable).

System Design Basics

Freshers are rarely asked for a full design, but product companies increasingly ask for basics. Start from requirements, estimate scale, sketch the components, then discuss trade-offs.

How would you design a URL shortener?

Requirements: create a short code for a long URL, and redirect from the code quickly. Generate codes by base62-encoding a unique ID from a counter or ID service, or by hashing the URL and handling collisions. Store code → URL in a key-value store, put a cache such as Redis in front because reads vastly outnumber writes, and redirect with 301 or 302 depending on whether you need click analytics.

What is the difference between horizontal and vertical scaling?

Vertical scaling adds more CPU or RAM to a single machine: simple, but limited and a single point of failure. Horizontal scaling adds more machines behind a load balancer: it scales much further and survives individual failures, but needs stateless services, shared or partitioned data, and more operational work.

What is caching and where can it be applied?

Caching keeps frequently used data in fast storage to cut latency and load. It can happen in the browser, at a CDN, in an application-level cache such as Redis, and inside the database. The hard parts are invalidation (TTL, write-through, write-behind or cache-aside) and choosing an eviction policy such as LRU.

Explain the CAP theorem.

When a network partition happens, a distributed data store must choose between consistency (every read sees the latest write) and availability (every request gets a response). Partitions cannot be ruled out in real networks, so systems are effectively CP (for example, many SQL setups and ZooKeeper) or AP (for example, Cassandra and DynamoDB in their default modes).

When would you use a message queue?

A message queue such as Kafka, RabbitMQ or SQS decouples producers from consumers. Use it to absorb traffic spikes, process slow work asynchronously (sending emails, resizing images), retry failures safely, and fan events out to several services. The costs are eventual consistency and having to handle duplicate or out-of-order messages.

HR & Behavioural

The HR round can reject an otherwise strong candidate. Prepare honest, specific stories in advance and structure them with STAR: Situation, Task, Action, Result.

Tell me about yourself.

Keep it to about 60–90 seconds and make it relevant to the role: your degree and college, one or two projects or internships with what you built and the outcome, the skills you are strongest in, and why you are interested in this role. Avoid repeating your resume line by line or sharing personal details nobody asked for.

Why do you want to join our company?

Research the company before the interview: what it builds, its clients or products, recent news, and the team you would join. Connect two or three specifics to your own skills and goals. A generic answer that would fit any company is a red flag; a specific one shows genuine interest.

What are your strengths and weaknesses?

Pick a strength that matters for the role and back it with a short example. For a weakness, choose something real but not disqualifying, and explain what you are actively doing about it — for example, “I used to underestimate tasks, so I now break work into smaller pieces and track estimates against actual time.” Avoid disguised boasts like “I work too hard.”

Describe a conflict in a team and how you handled it.

Use STAR. Describe the disagreement neutrally, explain how you listened to the other side and focused on the shared goal rather than on being right, what you did to resolve it (data, a quick prototype, involving a mentor), and the result. End with what you learned.

Are you willing to relocate or work in shifts?

Service companies often ask this because postings depend on project allocation. Answer honestly. If you are flexible, say so clearly; if you have a genuine constraint, state it calmly and mention what you can accommodate. An answer that changes after you join causes far more trouble than an honest one now.

Do you have any questions for us?

Always ask one or two. Good options: what a typical first six months looks like, how training or onboarding works, what technologies the team uses, or how performance is reviewed. Avoid opening with salary or leave policy in a technical or HR screening round.

Company question lists

These lists share a common core of questions and are being expanded with company-specific rounds, patterns and timelines. Start with the topics above, then use a company list for extra practice.