Software Engineer | 367 questions | 2026
Software Engineer interview questions for freshers
Python
FresherMost askedAnswerHideWhat is the difference between a list and a tuple in Python?
A list is mutable and a tuple is immutable. That is the core difference, and everything else follows from it.
| list | tuple | |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutable | Yes (append, remove, assign by index) | No |
| Hashable | No | Yes, if all items are hashable |
| Use as dict key or set member | No | Yes |
| Typical use | Homogeneous collection that changes | Fixed record, e.g. (x, y) or a function return of several values |
- Tuples are slightly smaller and faster to create, and they signal "this does not change".
- A tuple containing a list is still not fully frozen:
t = (1, [2])allowst[1].append(3). - A single-item tuple needs a comma:
(5,).
What they are checking: Whether you know mutability matters (hashing, dict keys), not just the bracket style
FresherMost askedAnswerHideWhat are mutable and immutable types in Python? Give examples.
A mutable object can be changed in place after creation, an immutable one cannot. Changing an immutable value really creates a new object.
- Immutable:
int,float,bool,str,tuple,frozenset,bytes. - Mutable:
list,dict,set,bytearray, and most user-defined class instances.
s = "abc"
print(id(s))
s += "d" # new string object, id changes
print(id(s))
l = [1, 2]
print(id(l))
l.append(3) # same object, id unchanged
print(id(l))
Why it matters: Mutable objects can be changed by anyone who holds them. This causes hard-to-find bugs (for example mutable default arguments). Immutable objects are safe to share and can be dict keys.
What they are checking: Understanding of object identity, and what it means for function arguments and hashing
FresherMost askedAnswerHideWhat is the difference between `is` and `==` in Python?
== compares values (it calls __eq__). is compares identity: do both names point to the same object in memory?
a = [1, 2]
b = [1, 2]
print(a == b) # True, equal values
print(a is b) # False, two different objects
c = a
print(c is a) # True
- Use
==for value comparison almost always. - Use
isfor singletons:x is None,x is True. - Do not use
isfor numbers or strings. CPython keeps small integers (-5 to 256) and some strings in a cache. Soismay seem to work, then fail on larger values.
What they are checking: Whether you avoid the small-integer cache trap and know to use
is None
FresherMost askedAnswerHideWhat are `*args` and `**kwargs`?
They let a function accept a variable number of arguments. *args collects extra positional arguments into a tuple, and **kwargs collects extra keyword arguments into a dict. The names are convention, the stars are the syntax.
def show(a, *args, **kwargs):
print(a, args, kwargs)
show(1, 2, 3, x=10, y=20) # 1 (2, 3) {'x': 10, 'y': 20}
nums = [1, 2, 3]
opts = {"sep": "-"}
print(*nums, **opts) # unpacking at the call site: 1-2-3
Order in a signature: positional parameters, *args, keyword-only parameters, **kwargs. They are common in decorators and wrappers that must forward any arguments to the wrapped function.
What they are checking: Can you use packing and unpacking, and do you know the parameter order
FresherMost askedAnswerHideWhat is a decorator in Python and how does it work?
A decorator is a callable that takes a function and returns a new function. It usually adds work before or after the original call. @decorator above a function is shorthand for func = decorator(func).
import functools, time
def timed(fn):
@functools.wraps(fn)
def wrapper(*args, **kwargs):
start = time.perf_counter()
try:
return fn(*args, **kwargs)
finally:
print(f"{fn.__name__} took {time.perf_counter() - start:.4f}s")
return wrapper
@timed
def work(n):
return sum(range(n))
work(1_000_000)
Points to mention: closures keep a reference to fn. functools.wraps preserves the name and docstring. Decorators are applied at definition time. Typical uses are logging, timing, caching, auth checks and retries.
What they are checking: Closures, first-class functions and whether you remember functools.wraps
FresherMost askedAnswerHideWhat are generators in Python? How is `yield` different from `return`?
A generator is a function that contains yield. Calling it returns a generator object (an iterator). It gives values lazily, one at a time. It pauses between values and keeps its local state. return ends the function for good, yield suspends it and can be resumed.
def countdown(n):
while n > 0:
yield n
n -= 1
g = countdown(3)
print(next(g)) # 3
print(list(g)) # [2, 1]
- Memory use stays small, so generators suit large or endless streams, such as reading a huge file line by line.
- A generator is exhausted after one pass. Iterating again gives nothing.
- A generator expression
(x*x for x in range(10))is the compact form.
What they are checking: Lazy evaluation and memory benefits, plus the one-pass trap
FresherMost askedAnswerHideWhat is the difference between shallow copy and deep copy?
A shallow copy creates a new outer container but reuses references to the inner objects. A deep copy recursively copies everything, so the result shares nothing with the original.
import copy
a = [[1, 2], [3, 4]]
s = copy.copy(a) # shallow, same as a[:] or list(a)
d = copy.deepcopy(a)
a[0].append(99)
print(s) # [[1, 2, 99], [3, 4]] inner list is shared
print(d) # [[1, 2], [3, 4]] independent
- Plain assignment
b = ais not a copy. It is a second name for the same object. - Shallow copy is fine for flat structures of immutable items.
- Deep copy is slower and handles cycles through a memo dict; classes can change it with
__deepcopy__.
What they are checking: Whether nested mutable objects are understood, not only the vocabulary
FresherMost askedAnswerHideWhat are dunder (magic) methods? Explain `__str__` vs `__repr__`.
Dunder methods are special methods with double underscores. Python calls them to run built-in behaviour: __init__ (construction), __len__ (len()), __getitem__ (indexing), __eq__ (==), __add__ (+), __enter__/__exit__ (with).
__str__ is the readable, user-facing text used by print() and str(). __repr__ is clear text for developers, used in the REPL, logs and containers. It should ideally let you rebuild the object.
class P:
def __init__(self, x): self.x = x
def __repr__(self): return f"P(x={self.x!r})"
def __str__(self): return f"Point at {self.x}"
p = P(3)
print(p) # Point at 3
print([p]) # [P(x=3)] containers use repr
If only __repr__ is defined, str() falls back to it, so define __repr__ first.
What they are checking: Operator overloading awareness and the repr/str purpose
FresherMost askedFree with sign-inAnswerHideHow does exception handling work in Python? Explain try, except, else and finally.
Code that may fail goes in try. A matching except handles the error. else runs only if no exception happened. finally always runs, for cleanup.
FresherMost askedFree with sign-inAnswerHideWhat is a virtual environment in Python and why do you use one?
A virtual environment is an isolated folder with its own Python and its own installed packages. Each project keeps its own package versions. Other projects and the system Python are not affected.
FresherMost askedFree with sign-inAnswerHideWhat is the output of this code, and why? `def add(x, items=[]): items.append(x); return items` called as `add(1)`, `add(2)`.
It returns [1] and then [1, 2]. The default list is created once, when the function is defined, not on each call. So every call without the argument shares the same list.
FresherMost askedFree with sign-inAnswerHideWhat are the built-in data types in Python?
Python has these core built-in types:
- Numeric:
int(any size),float,complex, plusbool(a subclass of int). - Text:
str(immutable Unicode), and binarybytes,bytearray. - Sequences:
list,tuple,range. - Mappings:
dict. - Sets:
set,frozenset. - None:
NoneType, the single valueNone.
FresherMost askedFree with sign-inAnswerHideWhat does `if __name__ == '__main__':` do?
It runs a block only when the file is run directly (python script.py). It does not run when the file is imported as a module. When Python runs a file as the entry point it sets __name__ to "__main__". When imported, __name__ is the module's name.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between an iterable and an iterator?
An iterable is any object you can loop over: it implements __iter__ which returns an iterator. An iterator is the object that does the traversal: it implements __next__ (and __iter__ returning itself) and raises StopIteration when finished.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a list comprehension and a generator expression?
A list comprehension builds the whole list in memory at once. A generator expression makes items lazily, one by one. The syntax differs only in brackets.
FresherMost askedFree with sign-inAnswerHideWhat are lambda, map and filter in Python? Show how they relate to comprehensions.
A lambda is a small anonymous function limited to a single expression. map(func, iterable) applies a function to every item, and filter(func, iterable) keeps items where the function returns truthy. Both return lazy iterators in Python 3.
FresherMost askedFree with sign-inAnswerHideWhat are the time complexities of common operations on lists, sets and dicts?
Typical CPython average cases:
FresherMost askedFree with sign-inAnswerHideWhat is the difference between `@staticmethod`, `@classmethod` and an instance method?
- Instance method: takes
self, works on one object's data. @classmethod: takescls, works on the class itself, commonly used as alternative constructors.@staticmethod: takes neither, is just a function namespaced inside the class.
FresherMost askedFree with sign-inAnswerHideAre arguments passed by value or by reference in Python?
Neither exactly. Python passes object references by value, often called "pass by assignment" or "pass by object reference". The parameter becomes a new name bound to the same object.
FresherMost askedFree with sign-inAnswerHideHow do properties work in Python? How do you achieve encapsulation?
Python has no strict private members, so privacy is by convention. @property lets you expose an attribute through getter and setter logic. Callers still use plain attribute syntax.
FresherMost askedFree with sign-inAnswerHideIs Python interpreted or compiled? What is bytecode and what is CPython?
Both, in a sense. CPython (the reference implementation) first compiles source code into bytecode (.pyc files cached in __pycache__). Then the Python Virtual Machine runs that bytecode.
FresherMost askedFree with sign-inAnswerHideWhy does `print(0.1 + 0.2 == 0.3)` print False, and how do you compare floats properly?
Floats use binary (IEEE 754) representation, and values like 0.1 and 0.2 cannot be stored exactly. The sum is 0.30000000000000004, which differs slightly from 0.3.
FresherMost askedFree with sign-inAnswerHideExplain how `sort()` and `sorted()` differ and how the `key` parameter works.
list.sort() sorts the list in place and returns None. sorted() works on any iterable and returns a new list, leaving the original unchanged. Both are stable (equal items keep their original order) and use Timsort, O(n log n).
FresherMost askedFree with sign-inAnswerHideWhat is the difference between list.sort() and sorted() in Python?
list.sort() sorts the list in place and returns None. sorted() returns a new sorted list and works on any iterable, leaving the original unchanged.
FresherMost askedFree with sign-inAnswerHideHow do you sort a dictionary by its values, or by a key inside nested values?
Sort the dictionary's items with a key function and rebuild a dictionary from the result. Since Python 3.7 dictionaries keep insertion order, so the rebuilt dictionary stays sorted.
JavaScript
FresherMost askedAnswerHideWhat is the difference between var, let and const in JavaScript?
All three declare variables, but they differ in scope, hoisting and reassignment.
| var | let | const | |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisting | Hoisted, initialised as undefined | Hoisted, but in the temporal dead zone until declared | Same as let |
| Redeclare in same scope | Allowed | Error | Error |
| Reassign | Yes | Yes | No |
conststops reassignment of the binding, not mutation of the value:const a = []; a.push(1)works.- Prefer
constby default,letwhen you must reassign, and avoidvarin new code. - A
vardeclared at the top level of a script becomes a property of the global object;letandconstdo not.
What they are checking: Whether you understand scope and the temporal dead zone, not only the table
FresherMost askedAnswerHideWhat is hoisting in JavaScript?
Hoisting means declarations are processed before the code runs. So names are known in their scope before the line that declares them.
varis hoisted and initialised withundefined, so reading it early givesundefined.letandconstare hoisted but not initialised. Accessing them before the declaration throws aReferenceError(the temporal dead zone).- Function declarations are hoisted with their body, so you can call them before they appear.
- Function expressions and arrow functions follow the rule of the variable that holds them.
console.log(a); // undefined
var a = 1;
sayHi(); // works
function sayHi() { console.log("hi"); }
console.log(b); // ReferenceError
let b = 2;
What they are checking: Whether you know the difference between var, let and function hoisting
FresherMost askedAnswerHideWhat is a closure? Give a practical example.
A closure is a function together with the variables from the scope where it was created. The function keeps access to those variables even after the outer function has returned.
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2
count is private: nothing outside can change it except through the returned function.
Common uses: data privacy, function factories, partial application, memoisation, and event handlers or callbacks that remember state. A common trap is capturing a loop variable declared with var. Also, a closure that holds a large object can keep it in memory longer than you expect.
What they are checking: Whether you can explain it simply and name real uses
FresherMost askedAnswerHideHow does the this keyword work in JavaScript?
this is decided by how a function is called, not where it is written. Arrow functions are the exception.
- Method call
obj.fn():thisisobj. - Plain call
fn():thisisundefinedin strict mode and modules, the global object in sloppy mode. new Fn():thisis the new object.call,apply,bind: you setthisyourself.- Arrow functions have no own
this; they use the one from the enclosing scope. - In a DOM event handler (regular function),
thisis the element.
const user = { name: "Asha", hi() { return this.name; } };
user.hi(); // "Asha"
const f = user.hi;
f(); // this lost: undefined or error in strict mode
What they are checking: Whether you can predict this from the call site
FresherMost askedAnswerHideWhat is the difference between call, apply and bind?
All three set this for a function. They differ in when the function runs and how arguments are passed.
fn.call(thisArg, a, b): runs now, arguments listed one by one.fn.apply(thisArg, [a, b]): runs now, arguments as an array.fn.bind(thisArg, a): does not run; returns a new function withthis(and optionally leading arguments) fixed.
function intro(city, country) { return `${this.name}, ${city}, ${country}`; }
const p = { name: "Sita" };
intro.call(p, "Pokhara", "Nepal");
intro.apply(p, ["Pokhara", "Nepal"]);
const bound = intro.bind(p, "Pokhara");
bound("Nepal");
A bound function cannot be re-bound to a different this.
What they are checking: Whether you know each one's timing and argument style
FresherMost askedAnswerHideWhat is the difference between == and === in JavaScript?
=== (strict equality) compares value and type with no conversion. == (loose equality) first converts both sides to a common type. This gives unexpected results.
0 == "0" // true
0 === "0" // false
null == undefined // true
null === undefined // false
NaN === NaN // false
[] == false // true
Use === by default. The one accepted use of == is value == null to test for both null and undefined. For NaN use Number.isNaN, and Object.is treats NaN as equal to itself and distinguishes +0 from -0.
What they are checking: Whether you know type coercion and default to strict equality
FresherMost askedAnswerHideWhat is the output of this loop, and how do you fix it?
for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 0); }
It prints 3 3 3.
var is function scoped, so there is one shared i. The timeout callbacks run after the loop ends, when i is already 3.
Fixes:
// 1. let creates a new binding per iteration
for (let i = 0; i < 3; i++) setTimeout(() => console.log(i), 0); // 0 1 2
// 2. IIFE capturing the value
for (var i = 0; i < 3; i++) {
((j) => setTimeout(() => console.log(j), 0))(i);
}
This is the classic closure-in-loop question. The key point is that closures capture variables, not values.
What they are checking: Whether you connect closures and scope to a real bug
FresherMost askedAnswerHideWhat is a Promise and what are its states?
A Promise is an object representing the eventual result of an async operation. It has three states:
- pending: the initial state.
- fulfilled: finished with a value.
- rejected: failed with a reason.
Once settled (fulfilled or rejected) it never changes. You consume it with .then(), .catch() and .finally(), and each returns a new promise, so calls chain.
const wait = (ms) => new Promise((res) => setTimeout(res, ms));
wait(100)
.then(() => "done")
.then(console.log)
.catch(console.error)
.finally(() => console.log("cleanup"));
An error thrown inside .then becomes a rejection of the returned promise. A missing .catch gives an unhandled rejection.
What they are checking: Whether you know the states and how chaining works
FresherMost askedFree with sign-inAnswerHideWhat are prototypes and how does prototypal inheritance work?
Every object has an internal link ([[Prototype]], readable with Object.getPrototypeOf) to another object. When you read a property that is not on the object, the engine follows this chain. It stops when it finds the property or reaches null.
FresherMost askedFree with sign-inAnswerHideWhat are the spread and rest operators?
Both use ..., but they do opposite jobs.
- Spread expands an iterable or object into individual elements.
- Rest collects remaining items into an array or object.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between null and undefined?
undefined means a value has not been assigned: an uninitialised variable, a missing property, a missing argument, or a function with no return. null is a "no value" that a developer sets on purpose.
FresherMost askedFree with sign-inAnswerHideWhat are the data types in JavaScript, and how does type coercion work?
Seven primitives: string, number, bigint, boolean, undefined, null and symbol. Everything else is an object (arrays, functions, dates, maps).
Primitives are immutable and compared by value; objects are compared by reference.
FresherMost askedFree with sign-inAnswerHideExplain map, filter and reduce with examples.
They are array methods that return results without mutating the original array.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between localStorage, sessionStorage and cookies?
| localStorage | sessionStorage | Cookies | |
|---|---|---|---|
| Lifetime | Until cleared | Until the tab closes | Until expiry |
| Size | About 5 MB | About 5 MB | About 4 KB |
| Sent to server | No | No | Yes, on every matching request |
| Access | JS only | JS only | JS, or HttpOnly (not JS) |
| Scope | Origin | ... |
FresherMost askedFree with sign-inAnswerHideWhat are optional chaining and nullish coalescing?
- Optional chaining
?.stops and returnsundefinedif the value before it isnullorundefined. It does not throw. - Nullish coalescing
??returns the right side only when the left isnullorundefined.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between forEach and map?
map returns a new array built from the callback's return values. forEach returns undefined and is used only for side effects.
FresherMost askedFree with sign-inAnswerHideWhat is the temporal dead zone? What does this print?
console.log(a);
var a = 5;
console.log(b);
let b = 6;
The first console.log(a) prints undefined because var is hoisted and initialised to undefined. The second throws ReferenceError: Cannot access 'b' before initialization.
FresherMost askedFree with sign-inAnswerHideExplain destructuring and default parameters.
Destructuring unpacks values from arrays or objects into variables.
FresherMost askedFree with sign-inAnswerHideWhat is the output?
console.log(0.1 + 0.2 === 0.3);
console.log(typeof NaN);
console.log([10, 9, 1].sort());
console.log([] + []);
false: numbers are IEEE 754 doubles, and0.1 + 0.2is0.30000000000000004. Compare with a tolerance:Math.abs(a - b) < Number.EPSILON, or use integers (cents)."number":NaNis a number type.[1, 10, 9]:sort()without a comparator converts items to strings and compares them. Usesort((a, b) => a - b)for numbers.""(empty string): both arrays convert to empty strings, then concatenate.
FresherMost askedFree with sign-inAnswerHideWhat are higher-order functions and first-class functions?
Functions are first-class in JavaScript: they can be stored in variables, passed as arguments, and returned from other functions. A higher-order function either takes a function as an argument, returns one, or both.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a function declaration and a function expression?
A declaration is a statement with a name; a function expression produces a value and can be anonymous or named.
FresherMost askedFree with sign-inAnswerHideWhat is a pure function, and why does it matter?
A pure function returns the same output for the same input and has no side effects. It does not modify external state or its arguments, and it does no I/O.
FresherFree with sign-inAnswerHideWhat is strict mode and what does it change?
Strict mode is an opt-in version of JavaScript. You turn it on with "use strict"; at the top of a script or function. ES modules and class bodies are strict automatically.
SQL
FresherMost askedAnswerHideWhat are the different types of SQL joins? Explain with an example.
A join combines rows from two tables on a related column. Take two tables:
employees(id, name, dept_id) and departments(id, dept_name).
| Join | Returns |
|---|---|
| INNER JOIN | Only rows that match in both tables |
| LEFT JOIN | All rows from the left table, NULL where the right has no match |
| RIGHT JOIN | All rows from the right table, NULL where the left has no match |
| FULL OUTER JOIN | All rows from both (PostgreSQL yes, MySQL has no direct support) |
| CROSS JOIN | Every combination (cartesian product) |
SELECT e.name, d.dept_name
FROM employees e
LEFT JOIN departments d ON d.id = e.dept_id;
This lists every employee, and dept_name is NULL for an employee with no department. With INNER JOIN that employee would disappear. A self join joins a table to itself, for example to find an employee's manager.
What they are checking: Whether you know what happens to unmatched rows, not just the names
FresherMost askedAnswerHideWhat is the difference between WHERE and HAVING?
WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY and can use aggregate functions.
SELECT dept_id, COUNT(*) AS headcount, AVG(salary) AS avg_salary
FROM employees
WHERE salary > 20000 -- row filter, runs first
GROUP BY dept_id
HAVING COUNT(*) > 5; -- group filter, runs after aggregation
- WHERE cannot contain aggregates such as
COUNT(*)orAVG(). - Put conditions in WHERE whenever possible, because it reduces rows before grouping and is faster.
- Logical order: FROM, WHERE, GROUP BY, HAVING, SELECT, ORDER BY, LIMIT.
What they are checking: Understanding of SQL's logical execution order
FresherMost askedAnswerHideWhat is the difference between a primary key and a foreign key?
A primary key uniquely identifies each row in its own table. A foreign key is a column that points to the primary key of another table. It enforces the link between them.
| Primary key | Foreign key | |
|---|---|---|
| Purpose | Identify a row | Link to a row in another table |
| NULLs | Not allowed | Allowed (unless declared NOT NULL) |
| Duplicates | Not allowed | Allowed |
| Per table | Exactly one (can be composite) | Many |
CREATE TABLE departments (id INT PRIMARY KEY, name VARCHAR(50));
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(50),
dept_id INT,
FOREIGN KEY (dept_id) REFERENCES departments(id)
);
The foreign key blocks adding an employee with a department that does not exist. It also controls what happens on delete (ON DELETE CASCADE, SET NULL, or restrict).
What they are checking: Referential integrity basics
FresherMost askedAnswerHideWhat is the difference between DELETE, TRUNCATE and DROP?
DELETE removes selected rows, TRUNCATE empties the whole table, DROP removes the table itself.
| DELETE | TRUNCATE | DROP | |
|---|---|---|---|
| Type | DML | DDL | DDL |
| WHERE clause | Yes | No | No |
| Removes | Chosen rows | All rows | Table and structure |
| Triggers fire | Yes | No | No |
| Speed | Slower (row by row, logged) | Fast | Fast |
| Rollback | Yes | PostgreSQL yes (inside a transaction), MySQL no (implicit commit) | MySQL no, PostgreSQL yes in a transaction |
DELETE FROM orders WHERE status = 'cancelled';
TRUNCATE TABLE temp_logs;
DROP TABLE temp_logs;
TRUNCATE also resets auto-increment counters in MySQL.
What they are checking: DML vs DDL and the side effects
FresherMost askedAnswerHideHow do you find the Nth highest salary in SQL?
Use DENSE_RANK so ties are handled correctly, or LIMIT with OFFSET on distinct values.
-- 3rd highest salary (change 3 to N)
SELECT salary
FROM (
SELECT salary, DENSE_RANK() OVER (ORDER BY salary DESC) AS rnk
FROM employees
) t
WHERE rnk = 3
LIMIT 1;
Alternative without window functions:
SELECT DISTINCT salary
FROM employees
ORDER BY salary DESC
LIMIT 1 OFFSET 2; -- OFFSET is N - 1
ROW_NUMBERwould count tied salaries as separate ranks, which is wrong here.RANKleaves gaps after ties, so the 3rd rank may not exist.- If fewer than N distinct salaries exist, both queries return no row.
What they are checking: Handling of ties and knowing rank functions
FresherMost askedAnswerHideHow do you find the highest salary in each department (max per group)?
Group by department to get just the value. Or join back, or use a window function, to get the full row.
-- Only the max value
SELECT dept_id, MAX(salary) AS max_salary
FROM employees
GROUP BY dept_id;
-- Whole row of the top earner (ties return all)
SELECT e.*
FROM employees e
JOIN (
SELECT dept_id, MAX(salary) AS max_salary
FROM employees
GROUP BY dept_id
) m ON m.dept_id = e.dept_id AND m.max_salary = e.salary;
-- Same with a window function
SELECT * FROM (
SELECT e.*, RANK() OVER (PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM employees e
) t WHERE rnk = 1;
The common mistake is selecting name together with MAX(salary) in a GROUP BY query. Name is not aggregated, so PostgreSQL rejects it and MySQL with ONLY_FULL_GROUP_BY does too.
What they are checking: The classic 'greatest-n-per-group' pattern
FresherMost askedAnswerHideHow do you delete duplicate rows from a table while keeping one copy?
Keep the row with the smallest id for each duplicate key and delete the rest.
DELETE FROM contacts
WHERE id NOT IN (
SELECT min_id FROM (
SELECT MIN(id) AS min_id
FROM contacts
GROUP BY email
) keep
);
The extra derived table (keep) is needed in MySQL. MySQL refuses to read and delete from the same table in one subquery. It also works in PostgreSQL.
First find duplicates to verify:
SELECT email, COUNT(*) FROM contacts GROUP BY email HAVING COUNT(*) > 1;
Run it inside a transaction or on a backup first. To prevent the problem permanently, add ALTER TABLE contacts ADD CONSTRAINT uq_email UNIQUE (email);.
What they are checking: Safe data cleanup and prevention
FresherMost askedAnswerHideWhat is an index and how does it speed up queries? What is the downside?
An index is a separate sorted structure (usually a B-tree). It lets the database find rows without scanning the whole table, like a book index.
CREATE INDEX idx_orders_customer ON orders (customer_id);
Benefits: fast lookups, joins, sorting and range queries on the indexed column.
Costs:
- Extra disk space.
- Slower INSERT, UPDATE and DELETE, since every index must be maintained.
- Too many indexes confuse the planner and waste memory.
Good candidates are columns used in WHERE, JOIN, ORDER BY and foreign keys with high selectivity. Poor candidates are tiny tables and low-cardinality columns such as a boolean. A composite index (a, b) helps queries that filter on a, or on a and b. It does not help a filter on b alone (leftmost prefix rule).
What they are checking: Costs and benefits, not just definitions
FresherMost askedAnswerHideExplain ACID properties with an example.
ACID is the set of guarantees of a database transaction.
- Atomicity: all steps happen or none do.
- Consistency: a transaction moves the database from one valid state to another, respecting constraints.
- Isolation: concurrent transactions do not see each other's half-finished work.
- Durability: once committed, data survives a crash (through the write-ahead log).
Example, transferring 500 from account A to B:
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 1;
UPDATE accounts SET balance = balance + 500 WHERE id = 2;
COMMIT;
If the second update fails, ROLLBACK restores the first, so money never disappears (atomicity). Constraints such as balance >= 0 keep it consistent. Another session reading mid-transfer does not see a partial state (isolation). After COMMIT a power cut does not lose it (durability).
What they are checking: Concepts tied to a concrete example
FresherMost askedFree with sign-inAnswerHideExplain normalization and the first three normal forms.
Normalization organizes tables to reduce redundancy and update anomalies.
FresherMost askedScenarioFree with sign-inAnswerHideHow do you find duplicate records in a table?
Group by the columns that define a duplicate and keep groups with more than one row.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between UNION and UNION ALL?
UNION combines result sets and removes duplicate rows. UNION ALL combines them and keeps every row.
FresherMost askedFree with sign-inAnswerHideWhat is a stored procedure and how is it different from a function?
A stored procedure is a named block of SQL, already compiled, saved in the database. You run it with CALL. A function returns a value and can be used inside queries.
FresherMost askedFree with sign-inAnswerHideWhat is a view? What is a materialized view?
A view is a saved query that behaves like a virtual table. It stores no data, and the query runs each time it is read.
FresherMost askedScenarioFree with sign-inAnswerHideWrite a query to find customers who have never placed an order.
Use an anti join: LEFT JOIN and keep rows with no match, or NOT EXISTS.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between COUNT(*), COUNT(column) and COUNT(DISTINCT column)?
COUNT(*)counts all rows, including those with NULLs.COUNT(column)counts rows where that column is not NULL.COUNT(DISTINCT column)counts unique non-NULL values.
FresherMost askedFree with sign-inAnswerHideExplain a self join with an example, such as finding each employee's manager.
A self join joins a table to itself using two aliases. It fits hierarchies stored in one table.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a primary key and a unique key?
Both enforce uniqueness, but they differ in purpose and NULL rules.
FresherMost askedFree with sign-inAnswerHideHow do you handle NULL values in SQL? What do COALESCE and IS NULL do?
NULL means unknown or missing, not zero or an empty string. Any comparison with NULL (= NULL) yields unknown, so you must use IS NULL or IS NOT NULL.
FresherMost askedScenarioFree with sign-inAnswerHideHow do you design tables for a many-to-many relationship, such as students and courses?
Use a junction (bridge) table. It holds the foreign keys of both sides, plus any attributes of the relationship itself.
FresherMost askedFree with sign-inAnswerHideWhat are SQL injection attacks and how do you prevent them?
SQL injection happens when user input is concatenated into a query, letting an attacker change its meaning.
FresherMost askedFree with sign-inAnswerHideWhat types of constraints does SQL support?
Constraints enforce rules on data at the database level:
FresherMost askedFree with sign-inAnswerHideWhat is a trigger? Give a use case and a downside.
A trigger is code that the database runs by itself before or after an INSERT, UPDATE or DELETE on a table.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between VARCHAR and CHAR, and when would you use each?
CHAR(n) is fixed length and pads shorter values with spaces. VARCHAR(n) is variable length and stores only what is needed plus a small length prefix.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a database transaction commit, rollback and savepoint?
COMMITmakes all changes of the transaction permanent and visible to others.ROLLBACKdiscards all changes sinceBEGIN.SAVEPOINTmarks a point inside a transaction so you can roll back only part of the work.
Java
FresherMost askedAnswerHideWhat is the difference between JDK, JRE and JVM?
The JVM runs bytecode. The JRE is the JVM plus the standard libraries needed to run a program. The JDK is the JRE plus the tools needed to build one.
- JVM: the virtual machine that loads classes, checks bytecode, and runs it with an interpreter and a JIT compiler. It is platform specific, which is what makes compiled Java portable.
- JRE: JVM + core class libraries (
java.lang,java.utiland so on). Since Java 11 Oracle no longer ships a separate JRE, but the idea is still useful. - JDK: JRE +
javac,jar,jlink,jshell, debuggers and profilers.
Flow: .java source -> javac -> .class bytecode -> JVM -> machine code. "Write once, run anywhere" works because only the JVM is platform specific.
What they are checking: Whether you understand the build and run pipeline, not just three acronyms
FresherMost askedAnswerHideWhy is String immutable in Java?
A String cannot change after it is created. Java does this on purpose, for safety, caching and speed.
- String pool: identical literals share one object, which only works if nobody can modify it.
- Thread safety: immutable objects can be shared between threads without locking.
- Security: strings carry class names, file paths, URLs and credentials. If they could change after validation, checks could be bypassed.
- Hash caching:
hashCode()is computed once and cached, so Strings are fast HashMap keys.
String s = "java";
s.concat(" 21"); // returns a new String, s is unchanged
System.out.println(s); // java
Every "modification" such as concat, replace or toUpperCase returns a new object. So changing a string again and again in a loop creates a lot of garbage. This is why StringBuilder exists.
What they are checking: Whether you can explain a design decision and what it leads to
FresherMost askedAnswerHideWhat is the difference between String, StringBuilder and StringBuffer?
String is immutable, StringBuilder is mutable and not thread safe, StringBuffer is mutable and synchronized.
| String | StringBuilder | StringBuffer | |
|---|---|---|---|
| Mutable | No | Yes | Yes |
| Thread safe | Yes (immutable) | No | Yes (synchronized methods) |
| Speed for repeated edits | Slow | Fastest | Slower than StringBuilder |
Use StringBuilder when building text in a loop inside one thread. Use StringBuffer only in old code that shares one buffer between threads (rare, since you can usually avoid sharing).
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 5; i++) sb.append(i).append(',');
sb.setLength(sb.length() - 1);
System.out.println(sb); // 0,1,2,3,4
For a one-line concatenation the compiler already optimises +, so do not replace it with a builder.
What they are checking: Whether you choose the right tool for building strings and know the thread safety cost
FresherMost askedAnswerHideWhat is the difference between == and equals() in Java?
== compares references for objects (and values for primitives). equals() compares the content when the class overrides it.
String a = new String("hi");
String b = new String("hi");
System.out.println(a == b); // false, two objects
System.out.println(a.equals(b)); // true, same characters
String c = "hi", d = "hi";
System.out.println(c == d); // true, same pooled literal
- The default
Object.equals()behaves like==. String, wrapper classes,List, and records overrideequals.- Never compare strings with
==. Useequals, orObjects.equals(a, b)when either may be null. - Beware
Integercaching:Integer.valueOf(127) == Integer.valueOf(127)is true but 1000 is not.
What they are checking: Whether you know reference vs value comparison and the string pool trap
FresherMost askedAnswerHideExplain the contract between equals() and hashCode(). What happens if you override only one?
If two objects are equal according to equals(), they must return the same hashCode(). The reverse is not required (collisions are allowed).
If you override equals without hashCode, equal objects usually get different hash codes, so hash-based collections break:
class P { String n; P(String n){this.n=n;}
@Override public boolean equals(Object o){ return o instanceof P p && p.n.equals(n); } }
Set<P> s = new HashSet<>();
s.add(new P("a"));
System.out.println(s.contains(new P("a"))); // usually false
The lookup computes a different bucket, so the equal element is never found.
Rules for equals: reflexive, symmetric, transitive, consistent, and x.equals(null) is false. A correct pair:
@Override public int hashCode(){ return java.util.Objects.hash(n); }
Prefer records or IDE generated methods. Use only fields that do not change while the object is a map key.
What they are checking: Whether you understand why hash collections need both methods
FresherMost askedAnswerHideWhat is the difference between ArrayList and LinkedList?
ArrayList is backed by a resizable array and LinkedList by a doubly linked list. ArrayList wins for almost every real workload.
| Operation | ArrayList | LinkedList |
|---|---|---|
| get(i) | O(1) | O(n) |
| add at end | amortised O(1) | O(1) |
| insert/remove in middle | O(n) shift | O(1) once positioned, but finding the node is O(n) |
| Memory | compact | extra object and two pointers per element |
| CPU cache | friendly | poor |
LinkedList also implements Deque, so it works as a queue, but ArrayDeque is usually faster. In practice use ArrayList by default. Use LinkedList only for frequent insertions through an Iterator or ListIterator at known positions.
Tip: pass an initial capacity (new ArrayList<>(10_000)) when you know the size to avoid repeated array copies.
What they are checking: Whether you reason about speed and memory, and do not repeat the myth that linked lists are faster for inserts
FresherMost askedAnswerHideHow does HashMap work internally?
HashMap stores entries in an array of buckets. The key's hash decides the bucket, and collisions are chained.
Steps for put(key, value):
- Compute
hashCode()of the key and spread the bits (h ^ (h >>> 16)). - Bucket index =
(n - 1) & hash, where n is the table size (a power of two). - If the bucket is empty, store a new node. Otherwise walk the chain, comparing with
equals, and replace the value if the key exists, else append. - Since Java 8, a chain longer than 8 (when the table size is at least 64) turns into a red-black tree. The worst case is then O(log n).
- When size exceeds
capacity * 0.75(the load factor), the table doubles and entries are redistributed.
Facts to mention: default capacity 16, one null key allowed, not thread safe, iteration order not guaranteed. get is average O(1). Keys should be immutable, and a good hashCode keeps chains short.
What they are checking: The most common Java collections question: depth on hashing, collisions and resizing
FresherMost askedAnswerHideWhat is the difference between checked and unchecked exceptions?
Checked exceptions are verified by the compiler and must be caught or declared. Unchecked exceptions (subclasses of RuntimeException and Error) are not.
- Checked:
IOException,SQLException. They represent recoverable conditions outside the program's control. You must writetry/catchorthrows. - Unchecked:
NullPointerException,IllegalArgumentException,IndexOutOfBoundsException. They usually signal programming bugs. - Error:
OutOfMemoryError,StackOverflowError. Do not catch them in normal code.
void read() throws java.io.IOException {
try (var r = java.nio.file.Files.newBufferedReader(java.nio.file.Path.of("a.txt"))) {
System.out.println(r.readLine());
}
}
Modern guidance: use unchecked exceptions for most business errors. Keep checked ones where the caller can really recover. Never ignore an exception silently. Keep the cause with new MyException("msg", e).
What they are checking: Whether you know the hierarchy and a sensible exception design philosophy
FresherMost askedAnswerHideWhat is the difference between final, finally and finalize?
They are unrelated: final is a modifier, finally is a block, and finalize() is a deprecated method.
- final: a final variable cannot be reassigned. A final method cannot be overridden. A final class cannot be extended (
Stringis final). A final reference can still point to a mutable object. - finally: a block after
try/catchthat runs whether or not an exception occurred. It is used for cleanup. It does not run if the JVM exits (System.exit) or crashes. - finalize(): a method the GC could call before reclaiming an object. It has been deprecated for removal since Java 18 because it is unpredictable and slow. Use try-with-resources or
Cleanerinstead.
try { return 1; } finally { System.out.println("cleanup"); }
The finally block above still prints before the method returns.
What they are checking: A classic wording trap: checks that you can separate the three terms
FresherMost askedAnswerHideWhat is the difference between an abstract class and an interface in Java?
An interface defines a contract (what), an abstract class gives partial implementation plus state (how).
| Abstract class | Interface | |
|---|---|---|
| Instance fields | Yes | No (only constants) |
| Constructors | Yes | No |
| Inheritance | Single | A class can implement many |
| Methods | Abstract and concrete, any access | Abstract, default, static, private |
Since Java 8, interfaces can have default methods, so the line is less clear. But interfaces still cannot hold instance state.
Choose an interface for capabilities that unrelated classes share (Comparable, Runnable). Choose an abstract class when subclasses share fields and common code (a template-method base class). Java 17+ adds sealed interfaces to restrict which classes may implement them.
What they are checking: Whether you can choose between them using design reasons
FresherMost askedFree with sign-inAnswerHideWhat is the difference between method overloading and overriding?
Overloading is multiple methods with the same name and different parameters in one class (compile-time polymorphism). Overriding is a subclass redefining a superclass method with the same signature (runtime polymorphism).
FresherMost askedFree with sign-inAnswerHideWhat is synchronized in Java and how does it work?
synchronized gives mutual exclusion and memory visibility: only one thread at a time can run a block guarded by the same monitor lock.
FresherMost askedFree with sign-inAnswerHideWhat does the volatile keyword do? How is it different from synchronized?
volatile guarantees visibility and ordering of a single variable across threads. It does not make compound actions atomic.
FresherMost askedFree with sign-inAnswerHideWhat are lambda expressions and functional interfaces in Java?
A lambda is a short anonymous function. It can be used wherever a functional interface (an interface with exactly one abstract method) is expected.
FresherMost askedFree with sign-inAnswerHideWhat are Java Streams? Explain map, filter, reduce and collect with an example.
A Stream is a pipeline for processing a sequence of elements declaratively. It has a source, zero or more lazy intermediate operations, and one terminal operation that triggers execution.
FresherMost askedFree with sign-inAnswerHideHow does garbage collection work in Java? What are the main collectors?
The garbage collector frees heap memory by itself. It frees objects that can no longer be reached from GC roots (thread stacks, static fields, JNI references).
FresherMost askedFree with sign-inAnswerHideWhat is Dependency Injection and Inversion of Control in Spring?
IoC means the framework creates and wires objects instead of your code calling new. Dependency Injection is how it supplies a class its collaborators.
FresherMost askedFree with sign-inAnswerHideWrite a simple REST controller in Spring Boot and explain the annotations.
@RestController
@RequestMapping("/api/books")
public class BookController {
private final BookService service;
public BookController(BookService service) { this.service = service; }
@GetMapping("/{id}")
public ResponseEntity<Book> get(@PathVariable Long id) {
return...
FresherMost askedFree with sign-inAnswerHideWhat are the OOP principles in Java? Explain with a short example.
The four pillars are encapsulation, inheritance, polymorphism and abstraction.
FresherMost askedFree with sign-inAnswerHideIs Java pass by value or pass by reference?
Java is always pass by value. For objects, the value that is copied is the reference.
FresherMost askedFree with sign-inAnswerHideWhat are the different ways to create a thread in Java?
Extend Thread, implement Runnable (or Callable), or, in modern code, submit tasks to an executor.
FresherMost askedFree with sign-inAnswerHideWhat are Java records and when should you use them?
A record (final since Java 16) is a compact immutable data carrier. The compiler generates the constructor, accessors, equals, hashCode and toString from the component list.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between @RestController and @Controller, and between @RequestParam, @PathVariable and @RequestBody?
@Controller returns view names by default (for server-rendered pages). @RestController adds @ResponseBody, so return values are written to the HTTP body as JSON.
FresherMost askedScenarioFree with sign-inAnswerHideYou get a ConcurrentModificationException while iterating a list. Why does it happen and how do you fix it?
It happens when a collection is structurally modified during iteration by anything other than the iterator itself. The fail-fast iterator compares a modCount and throws.
React
FresherMost askedAnswerHideWhat is React, and why use it?
React is a JavaScript library for building user interfaces from small reusable components. You describe what the UI should look like for a given state. When the state changes, React updates the DOM efficiently.
Why teams use it:
- Declarative, component-based code that is easy to reason about and reuse.
- A virtual DOM and reconciliation that avoid manual DOM updates.
- One-way data flow, which makes bugs easier to trace.
- A large ecosystem (routing, data fetching, testing) and frameworks like Next.js on top.
- The same model for web and mobile (React Native).
React is a library, not a full framework: routing, data fetching and build setup come from other tools.
What they are checking: Whether you can state the core idea beyond 'it is fast'
FresherMost askedAnswerHideWhat is the virtual DOM and how does reconciliation work?
The virtual DOM is a lightweight JavaScript representation of the UI. When state changes, React renders a new tree and compares it with the previous one (diffing). Then it applies only the needed changes to the real DOM.
The diffing rules keep it linear in cost:
- Elements of different types are replaced, and their subtrees are rebuilt.
- Same type: update only changed attributes and recurse into children.
- Lists use
keyto match old and new children.
It is not magic speed: the real benefit is a declarative model with batched, minimal DOM updates. React's Fiber architecture splits rendering into units of work, which allows concurrent features like transitions and Suspense.
What they are checking: Whether you understand diffing and the role of keys
FresherMost askedAnswerHideWhat is the difference between props and state?
Props are inputs passed from a parent to a child; they are read-only inside the child. State is data a component owns and can change over time, and changing it triggers a re-render.
| Props | State | |
|---|---|---|
| Owner | Parent | The component itself |
| Mutable by the component | No | Yes, via setter |
| Purpose | Configure the component | Remember changing data |
- Data flows down through props; events flow up through callback props.
- Do not copy props into state without a reason. The copy can become out of date.
- If two components need the same state, lift it to their closest common parent.
What they are checking: Whether you understand one-way data flow
FresherMost askedAnswerHideHow does useState work, and what is the functional update form?
useState(initial) returns [value, setValue]. Calling the setter schedules a re-render with the new value. State is kept between renders by React, per component instance.
const [count, setCount] = useState(0);
// wrong when updating multiple times from the same value
setCount(count + 1);
setCount(count + 1); // still +1 in total
// right: derive from the latest state
setCount(c => c + 1);
setCount(c => c + 1); // +2
Other points:
- Updates are batched and asynchronous; the variable keeps its old value in the current render.
- Never change objects or arrays directly: create new ones (
setItems([...items, x])). - Pass a function for expensive initial values:
useState(() => compute()). - Setting the same value (by
Object.is) bails out.
What they are checking: Whether you know about batching and out-of-date values
FresherMost askedAnswerHideHow does useEffect work? Explain the dependency array and cleanup.
useEffect runs side effects (fetching, subscriptions, timers, DOM work) after React commits a render.
- No array: runs after every render.
[]: runs once after mount (twice in development with Strict Mode).[a, b]: runs after mount and wheneveraorbchange.- The returned function is cleanup. It runs before the next effect and on unmount.
useEffect(() => {
const id = setInterval(() => setSeconds(s => s + 1), 1000);
return () => clearInterval(id);
}, []);
List every reactive value you use in the array (the lint rule react-hooks/exhaustive-deps helps). Do not use effects for things you can compute during render or in event handlers.
What they are checking: Whether you handle cleanup and dependencies correctly
FresherMost askedAnswerHideWhy are keys needed in lists, and why is using the array index as a key a problem?
Keys let React match items between renders. So it can reorder, add or remove the right elements and keep their state.
{todos.map(t => <TodoItem key={t.id} todo={t} />)}
Index keys are fine for static lists that never reorder. If items can be inserted, deleted or sorted, an index key makes React reuse the wrong component instance. This causes wrong input values, lost focus or old state.
Rules for keys:
- Unique among siblings, stable, and not generated during render (
Math.random()forces a remount every time). - Use a database id or a stable unique field.
- Changing a component's
keydeliberately resets its state.
What they are checking: Whether you understand identity in reconciliation
FresherMost askedFree with sign-inAnswerHideWhat is JSX?
JSX is a syntax extension that lets you write HTML-like markup inside JavaScript. A compiler (Babel, SWC, TypeScript) turns it into function calls (jsx()), producing React elements.
FresherMost askedFree with sign-inAnswerHideWhat is useRef and when would you use it?
useRef(initial) returns a mutable object { current } that stays the same across renders. Changing ref.current does not cause a re-render.
Uses:
- Access a DOM node:
<input ref={inputRef} />theninputRef.current.focus(). - Store values that should not trigger renders (timer ids, previous value, mutable flags).
FresherMost askedFree with sign-inAnswerHideWhat is the Context API and how does useContext work?
Context lets you pass data through the component tree without passing props at every level (avoiding prop drilling). Use it for things like theme, locale or the current user.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between controlled and uncontrolled components?
In a controlled component, React state is the single source of truth for the input value. In an uncontrolled one, the DOM holds the value. You read it with a ref or on submit.
FresherMost askedFree with sign-inAnswerHideWhat does React.memo do, and when is it useful?
React.memo(Component) skips re-rendering a component when its props are shallowly equal to the previous props.
FresherMost askedFree with sign-inAnswerHideWhat are the rules of hooks, and why do they exist?
Two rules:
- Call hooks only at the top level of a component or custom hook: never inside loops, conditions or nested functions.
- Call hooks only from React function components or other hooks.
FresherMost askedFree with sign-inAnswerHideWhat is a custom hook? Write one.
A custom hook is a function whose name starts with use and that calls other hooks. It lets components reuse stateful logic. Each call gets its own independent state.
FresherMost askedFree with sign-inAnswerHideWhy should you not mutate state directly, and how do you update arrays and objects immutably?
React detects changes by comparing references. If you change an object or array directly and pass the same reference to the setter, React sees no change. Memoised children skip updates too, so the UI does not update correctly.
FresherMost askedFree with sign-inAnswerHideWhat does 'lifting state up' mean?
When two or more components need the same changing data, move the state to their closest common parent. Pass it down as props (plus callbacks to update it).
FresherMost askedFree with sign-inAnswerHideWhat is prop drilling and how do you avoid it?
Prop drilling is passing props through several middle components that do not use them, just to reach a deep child. It makes code brittle and noisy.
FresherMost askedFree with sign-inAnswerHideWhat is React Strict Mode, and why do effects run twice in development?
<StrictMode> is a development-only wrapper that highlights problems. In development it renders components twice. Since React 18, it also mounts, unmounts and remounts each component once, to check that effects clean up properly. It has no effect in production.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between class components and function components? Map lifecycle methods to hooks.
Class components use this.state, setState and lifecycle methods. Function components with hooks do the same with less code and easier logic reuse. New code uses function components; classes remain for error boundaries.
FresherMost askedFree with sign-inAnswerHideBuild a countdown timer component in React that counts down from a given number of seconds, with start, pause and reset.
Keep the remaining seconds and a running flag in state. Run a setInterval inside useEffect and clear it on cleanup. Use the functional form of the state setter so the interval never reads an old value.
FresherFree with sign-inAnswerHideWhat are Fragments and Portals?
A Fragment lets a component return several elements without adding an extra DOM node: <>...</> or <Fragment key={id}> when a key is needed.
A Portal renders children into a different DOM node outside the parent's hierarchy. React tree rules still apply: context and event bubbling follow the React tree.
FresherFree with sign-inAnswerHideWhat are synthetic events in React?
Synthetic events are React's cross-browser wrapper around native DOM events. They expose the same interface (target, preventDefault(), stopPropagation()) in every browser.
TypeScript
FresherMost askedAnswerHideWhat is TypeScript, and why would you use it instead of plain JavaScript?
TypeScript is JavaScript with added types. It compiles to plain JavaScript. Every valid JS file is valid TS, and the type checker runs at build time only.
Why teams use it:
- Bugs such as typos in property names, wrong argument types and missing null checks are caught before the code runs.
- Editors give accurate autocomplete, go-to-definition and safe rename across the whole project.
- Types act as living documentation for function signatures and API shapes.
- Large refactors are safer because the compiler lists every place that breaks.
function total(price: number, qty: number): number {
return price * qty;
}
// @ts-expect-error: a string is not a number
total("10", 2);
Types are erased in the output, so they add no runtime cost and no runtime validation either. The trade-off is extra setup and a learning curve.
What they are checking: Whether you understand that TypeScript is a compile-time tool and can name concrete benefits
FresherMost askedAnswerHideWhat is the difference between type and interface in TypeScript?
Both describe the shape of data, and for plain object shapes they are almost interchangeable. The practical differences:
interface | type | |
|---|---|---|
| Object shapes | Yes | Yes |
| Unions, tuples, primitives, mapped/conditional types | No | Yes |
| Extending | extends | Intersection & |
| Declaration merging | Yes (same name merges) | No (duplicate name is an error) |
implements in a class | Yes | Yes, if it is an object type |
interface User { id: number; name: string }
interface Admin extends User { role: "admin" }
type Id = string | number; // only a type alias can do this
type Point = [number, number];
A common convention: use interface for public object shapes and class contracts (it can merge and gives clearer error messages). Use type for unions, tuples and computed types. Pick one rule per codebase and stay consistent.
What they are checking: Whether you know the real differences (merging, unions) and not just 'they are the same'
FresherMost askedAnswerHideWhat is the difference between any, unknown and never?
anyturns off type checking for a value. You can do anything with it and the compiler stays silent. It spreads unsafety.unknownis the type-safe version of any. Anything can be assigned to it, but you must narrow it before using it.neveris the type with no values. It is the return type of functions that never return (they throw or loop forever). It is also the type left over after every case has been narrowed out.
let a: any = "hi";
a.toFixed(); // compiles, crashes at runtime
let u: unknown = "hi";
// @ts-expect-error: must narrow first
u.toUpperCase();
if (typeof u === "string") u.toUpperCase(); // ok
function fail(msg: string): never {
throw new Error(msg);
}
Prefer unknown for data you do not control (JSON, catch clauses, third-party input). Avoid any unless nothing else works.
What they are checking: Whether you reach for unknown instead of any and understand never as the empty type
FresherMost askedAnswerHideWhat are generics in TypeScript and why are they useful?
Generics let you write a function, class or type that works with many types. They keep the link between the input type and the output type. Think of a type parameter as a variable for a type.
function first<T>(items: T[]): T | undefined {
return items[0];
}
const n = first([1, 2, 3]); // number | undefined
const s = first(["a", "b"]); // string | undefined
interface ApiResponse<TData> {
data: TData;
status: number;
}
const res: ApiResponse<{ id: number }> = { data: { id: 1 }, status: 200 };
Without generics you would either duplicate the function per type or return any and lose safety. Typical uses are collections, API response wrappers, React hooks and utility types. TypeScript usually works out T from the arguments, so callers rarely write it.
What they are checking: Whether you can explain generics as type variables that preserve type relationships
FresherMost askedAnswerHideExplain the common utility types Partial, Pick, Omit, Required and Record with examples.
Utility types are built-in generic types that transform other types.
interface User { id: number; name: string; email: string }
type Draft = Partial<User>; // all optional
type Full = Required<Draft>; // all required again
type Preview = Pick<User, "id" | "name">; // only these keys
type NoEmail = Omit<User, "email">; // everything except
type Roles = Record<"admin" | "user", string[]>; // fixed keys to value type
const patch: Partial<User> = { name: "Asha" }; // update payload
const roles: Roles = { admin: ["a"], user: [] };
Partial<T>: update/patch payloads, form drafts.Pick<T, K>andOmit<T, K>: derive smaller shapes without repeating fields (for example removing a password before sending a user to the client).Record<K, V>: dictionaries and lookup tables with known keys.Readonly<T>: makes all properties read-only.
They are plain mapped types under the hood, so you can write your own the same way.
What they are checking: Whether you reach for utility types instead of copy-pasting interfaces
FresherMost askedAnswerHideWhat is type narrowing, and what are type guards?
Narrowing is when TypeScript changes a broad type to a more specific one inside a code branch, after a check. A type guard is the check (or function) that triggers it.
Built-in narrowing: typeof, instanceof, in, equality, truthiness.
function show(x: string | number | Date) {
if (typeof x === "string") return x.toUpperCase();
if (x instanceof Date) return x.toISOString();
return x.toFixed(2); // number
}
interface Cat { meow(): void }
interface Dog { bark(): void }
function isCat(a: Cat | Dog): a is Cat { // user-defined guard
return "meow" in a;
}
function talk(a: Cat | Dog) {
if (isCat(a)) a.meow(); else a.bark();
}
A function returning a is Cat is a type predicate: when it returns true, the argument is treated as Cat in that branch. Assertion functions (asserts x is T) narrow after the call by throwing on failure. Be honest in predicates: the compiler trusts you.
What they are checking: Whether you can narrow safely and write a custom type predicate
FresherMost askedAnswerHideWhat does strict mode in tsconfig.json turn on, and why should it be enabled?
"strict": true enables a group of checks. The important ones:
strictNullChecks:nullandundefinedcannot be assigned to other types. This stops most "cannot read property of undefined" bugs.noImplicitAny: variables and parameters with no inferable type are errors instead of silentlyany.strictFunctionTypes,strictBindCallApply,strictPropertyInitialization,noImplicitThis,useUnknownInCatchVariables,alwaysStrict.
{
"compilerOptions": {
"target": "ES2022",
"module": "esnext",
"moduleResolution": "bundler",
"strict": true,
"noUncheckedIndexedAccess": true,
"skipLibCheck": true
}
}
Without strict, much of TypeScript's value is lost. Gaps remain, like hidden any and values that can be null anywhere. New projects should start strict. noUncheckedIndexedAccess is not part of strict but is worth adding because array and record lookups become T | undefined.
What they are checking: Whether you know strict is a family of flags and can name the key ones
FresherMost askedAnswerHideHow do you type props for a React component in TypeScript?
Declare an interface or type for the props and annotate the destructured parameter. Typing the function directly is preferred over React.FC in modern code.
import type { ReactNode } from "react";
interface ButtonProps {
label: string;
variant?: "primary" | "ghost";
disabled?: boolean;
onClick: (id: number) => void;
children?: ReactNode;
}
export function Button({ label, variant = "primary", disabled, onClick, children }: ButtonProps) {
return (
<button className={variant} disabled={disabled} onClick={() => onClick(1)}>
{label}
{children}
</button>
);
}
- Use
?for optional props and default values in destructuring. - Use
ReactNodefor anything renderable (children), andReactElementonly when an element is required. - Extend native element props with
React.ComponentProps<"button">orComponentPropsWithoutRef<"button">so your component acceptstype,aria-*and so on. - Type callbacks precisely instead of
Function.
What they are checking: Whether you can type props, optional props, children and callbacks cleanly
FresherMost askedScenarioFree with sign-inAnswerHideYou get the error "Property 'x' does not exist on type 'A | B'". What causes it and how do you fix it?
When a value has a union type, you can only access properties that exist on every member. TypeScript does not know yet which member you have. So using a property that exists on only one of them is an error.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between union and intersection types?
A union (A | B) means a value is either A or B. An intersection (A & B) means a value is both A and B at once.
FresherMost askedFree with sign-inAnswerHideEnums versus union literal types: which would you choose and why?
In most modern code I prefer string literal unions. I use enums only when I need a runtime object or must match existing code.
FresherMost askedFree with sign-inAnswerHideWhat do keyof and typeof do in TypeScript?
Both are used in type positions to build types from existing things.
keyof Tproduces a union of the property names of type T.typeof value(in a type position) gets the type of a variable or object value. It is different from the runtimetypeofoperator that returns a string.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a type annotation, a type assertion (as) and the non-null assertion (!)?
- Annotation (
x: T): you declare the type, and the compiler checks the value matches. - Assertion (
x as T): you tell the compiler to treat a value as T. No runtime check or conversion happens. It only works when the types overlap enough. Otherwise you needas unknown as T. - Non-null assertion (
x!): tells the compiler the value is not null or undefined.
FresherMost askedFree with sign-inAnswerHideWhat is type inference, and when should you write the types yourself?
Type inference is TypeScript working out types from values and usage, so you do not write them everywhere.
FresherMost askedFree with sign-inAnswerHideWhat is a declaration file (.d.ts), and what is DefinitelyTyped (@types)?
A .d.ts file contains only type declarations, no implementation. It describes the shape of JavaScript code so TypeScript can type-check calls to it.
FresherMost askedFree with sign-inAnswerHideWhat does readonly do, and how does it differ from const?
const stops you from assigning a new value to a variable. readonly stops you from assigning a new value to a property (or array elements) through that type. Neither makes an object deeply immutable at runtime.
FresherMost askedFree with sign-inAnswerHideWhat are tuples in TypeScript, and when would you use one?
A tuple is an array with a fixed length where each position has its own type.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between void, undefined and null as return types?
undefinedis a value and a type: the variable exists but has no value.nullis a "no value" that you assign on purpose.voidis the return type of a function whose result you are not supposed to use. Such a function returnsundefinedat runtime.
FresherFree with sign-inAnswerHideWhat is the difference between object, {} and Object as types in TypeScript?
objectmeans any non-primitive value (objects, arrays, functions), but notstring,number,boolean,nullorundefined. Use it when you want "some object" and will narrow later.{}means any value that is notnullorundefined, so it accepts primitives like5and"a"too. It almost never means what people expect.Objectis the type of the globalObjectinterface, which also includes primitives that are boxed. It should be avoided.
Next.js
FresherMost askedAnswerHideWhat is the difference between the App Router and the Pages Router in Next.js?
The Pages Router (pages/) is the original file-based router. The App Router (app/) is the newer one, built on React Server Components. It is the best choice for new projects. Both can coexist during a migration.
| Pages Router | App Router | |
|---|---|---|
| Folder | pages/ | app/ |
| Components | Client-rendered (hydrated) by default | Server Components by default |
| Data fetching | getStaticProps, getServerSideProps | async components and fetch / direct DB calls |
| Layouts | _app.tsx / _document.tsx | Nested layout.tsx, preserved across navigation |
| Special files | none | loading.tsx, error.tsx, not-found.tsx, route.ts |
| Streaming | Limited | Built in with Suspense |
| Metadata | next/head | metadata / generateMetadata |
Main benefit of the App Router: less JavaScript goes to the browser, because server components never send their code. Each route segment can also stream on its own. A route lives in a folder whose page.tsx makes it public.
What they are checking: Whether you know the mental-model shift to server-first rendering
FresherMost askedAnswerHideWhat is the difference between Server Components and Client Components in Next.js?
In the App Router every component is a Server Component unless the file starts with the "use client" directive.
| Server Component | Client Component | |
|---|---|---|
| Runs | On the server only (build or request time) | Server for first HTML, then hydrated in the browser |
| JS sent to browser | None for the component itself | Yes |
| Can use | async/await, DB, secrets, fs | useState, useEffect, event handlers, browser APIs |
| Cannot use | Hooks like useState, onClick | Server-only code and secrets |
// app/page.tsx (server component)
import Counter from "./Counter";
export default async function Page() {
const res = await fetch("https://example.com/api/items");
const items: { id: number; name: string }[] = await res.json();
return (
<main>
<ul>{items.map((i) => <li key={i.id}>{i.name}</li>)}</ul>
<Counter />
</main>
);
}
// app/Counter.tsx
"use client";
import { useState } from "react";
export default function Counter() {
const [n, setN] = useState(0);
return <button onClick={() => setN(n + 1)}>{n}</button>;
}
Default to server components and push "use client" down to the small interactive leaves.
What they are checking: Whether you can decide which side a component belongs on
FresherMost askedAnswerHideExplain SSR, SSG and ISR in Next.js. When would you use each?
- SSG (static site generation): HTML is built once at build time and served from a CDN. Fastest and cheapest. Use for content that rarely changes (docs, marketing pages).
- SSR (server-side rendering): HTML is generated on every request. Use for per-user or always-fresh data (dashboards, search results).
- ISR (incremental static regeneration): a static page is served, then regenerated in the background after a time window or on demand. Use for large content sites where pages change occasionally (blogs, product pages).
In the App Router you do not choose with special functions. The mode follows what the route uses:
// ISR: regenerate at most every 60 seconds
export const revalidate = 60;
export default async function Page() {
const res = await fetch("https://example.com/api/posts");
const posts: { id: number; title: string }[] = await res.json();
return <ul>{posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul>;
}
Using request-time APIs such as cookies(), headers() or searchParams (or export const dynamic = "force-dynamic") makes the route dynamic (SSR). Static is the default when nothing forces dynamic rendering.
What they are checking: Whether you can map rendering strategies to real content types
FresherMost askedAnswerHideHow do you fetch data in the Next.js App Router?
In a Server Component you make the component async and fetch directly. No useEffect, no API route needed for your own data.
// app/products/page.tsx
interface Product { id: number; name: string }
async function getProducts(): Promise<Product[]> {
const res = await fetch("https://example.com/api/products", {
next: { revalidate: 300 },
});
if (!res.ok) throw new Error("Failed to load products");
return res.json();
}
export default async function Page() {
const products = await getProducts();
return <ul>{products.map((p) => <li key={p.id}>{p.name}</li>)}</ul>;
}
- You can also call a database or ORM directly, since this code never reaches the browser.
- Fire independent requests in parallel with
Promise.allto avoid waterfalls. - Throwing triggers the nearest
error.tsx; callingnotFound()triggersnot-found.tsx. - For needs in the browser (polling, mutations, refetch by the user), use a Client Component with SWR or TanStack Query. For mutations, you can also use a Server Action.
What they are checking: Whether you fetch on the server first and avoid needless client fetching
FresherMost askedFree with sign-inAnswerHideWhat are Route Handlers in Next.js, and when would you use them instead of Server Actions?
Route Handlers create HTTP endpoints in the App Router. You use a route.ts file that exports functions named after HTTP methods. They replace Pages Router pages/api.
FresherMost askedFree with sign-inAnswerHideHow do dynamic routes work in the App Router? Explain [id], [...slug] and [[...slug]].
Wrap a folder name in square brackets to make a URL segment dynamic.
FresherMost askedFree with sign-inAnswerHideHow do you handle metadata and SEO in the Next.js App Router?
Export a static metadata object or an async generateMetadata function from a layout.tsx or page.tsx. Next renders the tags on the server.
FresherMost askedFree with sign-inAnswerHideHow does next/image optimise images, and what props do you have to set?
next/image serves resized images in modern formats (WebP or AVIF where supported). It loads them only when needed, and keeps space for them to avoid layout shift (CLS).
FresherMost askedFree with sign-inAnswerHideWhat are layout.tsx, loading.tsx, error.tsx and not-found.tsx used for?
They are special files in the App Router. They give each route segment shared UI and states with no extra setup.
FresherMost askedFree with sign-inAnswerHideHow do environment variables work in Next.js? What does NEXT_PUBLIC_ do?
Next loads variables from .env, .env.local, .env.development and .env.production (with .env.local for secrets, never committed).
FresherMost askedFree with sign-inAnswerHideWhat are the ways to deploy a Next.js application?
- Vercel: zero-config, supports all features (ISR, middleware, image optimisation, edge).
- Node.js server:
next buildthennext starton a VM, container or PaaS. Supports every feature. - Docker: build an image, ideally using
output: "standalone"for a small runtime image. - Static export:
output: "export"...
FresherMost askedFree with sign-inAnswerHideWhat is hydration in React and Next.js?
Hydration is the step where React attaches event handlers and state to HTML that the server already rendered. The user sees content immediately from the HTML, and the page becomes interactive once the JavaScript loads and hydrates.
FresherMost askedFree with sign-inAnswerHideHow did data fetching work in the Pages Router (getStaticProps, getServerSideProps, getStaticPaths)?
In the Pages Router, page-level functions run on the server and pass props to the page component.
FresherMost askedFree with sign-inAnswerHideWhat makes a Next.js route dynamically rendered instead of static?
A route is static by default. It switches to dynamic rendering (per request) when it uses something only known at request time.
FresherMost askedFree with sign-inAnswerHideHow do next/font and next/script improve performance?
next/font downloads font files at build time and serves them from your own site (Google fonts or local). So there are no extra requests to a font CDN at runtime. It applies size-adjust fallbacks to avoid layout shift.
FresherMost askedFree with sign-inAnswerHideHow does navigation work in Next.js? Explain the Link component, prefetching and useRouter.
next/link renders an <a> and does client-side navigation: it fetches only the needed RSC payload and swaps the page without a full reload.
FresherMost askedFree with sign-inAnswerHideHow do redirects, rewrites and custom headers work in next.config?
All three are async functions in next.config that return rules.
FresherMost askedFree with sign-inAnswerHideHow do you handle styling in Next.js, and what are the limits with Server Components?
Common options:
FresherFree with sign-inAnswerHideWhat is Turbopack, and how does it differ from webpack in Next.js?
Turbopack is Next.js's Rust-based bundler, designed to be faster than webpack through incremental computation: it recomputes only what changed. In Next 16 it is the default bundler for development and production builds. Webpack is still available with an opt-in flag.
FresherFree with sign-inAnswerHideHow do you test a Next.js application?
Use a pyramid, adapted to server and client code.
Angular
FresherMost askedAnswerHideWhat is Angular and what are its main building blocks?
Angular is a TypeScript framework from Google for building single-page applications. It has routing, forms, an HTTP client, dependency injection and a CLI built in.
Main building blocks:
- Components: a class, a template and styles that control a piece of UI.
- Directives: add behaviour to elements (
*ngIf,[ngClass], custom ones). - Services: reusable logic and data access, shared through dependency injection.
- Pipes: transform values in templates (
date,async). - Router: maps URLs to components.
- Modules or standalone components: group what a piece of the app needs.
Unlike React, which is a view library, Angular is opinionated and gives you the full toolkit.
What they are checking: Whether you see Angular as a complete framework and can name its parts
FresherMost askedAnswerHideWhat is the difference between a component and a directive?
A component is a directive that has its own template. A directive has no template and only changes the behaviour or appearance of an existing element.
- Component:
@Component, has a template, owns a view, appears as its own tag. - Attribute directive: changes look or behaviour of its host, for example
[ngClass]or a custom highlight directive. - Structural directive: changes the DOM layout by adding or removing elements, for example
*ngIf,*ngFor.
@Directive({ selector: '[appHighlight]', standalone: true })
export class HighlightDirective {
constructor(el: ElementRef<HTMLElement>) {
el.nativeElement.style.background = 'yellow';
}
}
What they are checking: Whether you know a component is a directive with a view
FresherMost askedAnswerHideWhat is the difference between NgModules and standalone components? Which should new code use?
A standalone component lists its own dependencies in its imports array. An NgModule groups declarations, imports and providers for a set of components. New code should use standalone components. They are the default since Angular 19 and fully supported in Angular 18.
@Component({
selector: 'app-user-card',
standalone: true,
imports: [NgOptimizedImage, RouterLink],
template: `<a routerLink="/users">Users</a>`,
})
export class UserCardComponent {}
Benefits: less repeated setup code, no module to keep in sync, easier lazy loading with loadComponent, and better tree-shaking. App bootstrap uses bootstrapApplication(AppComponent, appConfig) with providers such as provideRouter and provideHttpClient. Old NgModule code still works and can be migrated gradually.
What they are checking: Whether you are current with the standalone-first direction of Angular
FresherMost askedAnswerHideWhat are the types of data binding in Angular?
Angular has four forms of binding between the component class and the template.
| Type | Syntax | Direction |
|---|---|---|
| Interpolation | {{ title }} | class to view |
| Property binding | [disabled]="isBusy" | class to view |
| Event binding | (click)="save()" | view to class |
| Two-way binding | [(ngModel)]="name" | both |
Two-way binding is just a property binding plus an event binding: [(x)]="v" expands to [x]="v" (xChange)="v=$event". With signals you can build two-way inputs using model().
What they are checking: Whether you can name and distinguish the binding syntaxes
FresherMost askedAnswerHideWhat are pipes in Angular? What is the difference between pure and impure pipes?
Pipes transform a value inside a template, for example {{ price | currency }}. A pure pipe runs only when its input reference changes. An impure pipe runs on every change detection cycle.
- Pure (default): cheap, gives the same output for the same input, safe for formatting.
- Impure (
pure: false): re-evaluated constantly, so it can be slow. The built-inasyncpipe is impure by design because it must watch a stream.
@Pipe({ name: 'initials', standalone: true })
export class InitialsPipe implements PipeTransform {
transform(name: string): string {
return name.split(' ').map(p => p[0]).join('').toUpperCase();
}
}
Pitfall: a pure pipe will not notice an array mutated in place, because the reference is the same.
What they are checking: Whether you understand when pipes re-run and the cost of impure pipes
FresherMost askedAnswerHideWhat are services and dependency injection in Angular?
A service is a class that holds shared logic or state. Dependency injection (DI) is how Angular creates it and gives it to the classes that need it. So you do not call new yourself.
@Injectable({ providedIn: 'root' })
export class UserService {
private http = inject(HttpClient);
getUsers() { return this.http.get<User[]>('/api/users'); }
}
@Component({ selector: 'app-users', standalone: true, template: '' })
export class UsersComponent {
private users = inject(UserService);
}
providedIn: 'root' registers a single app-wide instance that is tree-shakable. DI makes code easy to test because you can replace a service with a mock in the providers.
What they are checking: Whether you understand DI as a design benefit and not just syntax
FresherMost askedAnswerHideList the Angular component lifecycle hooks in the order they run.
The main hooks, in order:
constructor: class created, only DI wiring.ngOnChanges: when an@Inputchanges (before init and on every change).ngOnInit: once, after the first inputs are set; put initialisation and first data load here.ngDoCheck: every change detection run, for custom checks.ngAfterContentInitandngAfterContentChecked: projected content is ready.ngAfterViewInitandngAfterViewChecked: the component view and children are ready (@ViewChildis available).ngOnDestroy: cleanup before removal, unsubscribe and clear timers.
Newer code can also use afterNextRender and afterRender for DOM work that must run in the browser only.
What they are checking: Whether you know the order and what each hook is for
FresherMost askedAnswerHideWhat is the difference between the constructor and ngOnInit?
The constructor is a TypeScript feature. It runs when the class is created, and it should only set up dependencies. ngOnInit is an Angular hook. It runs after inputs are set, so it is the place for starting logic.
- In the constructor,
@Inputvalues are not set yet. ngOnInitruns once, after the firstngOnChanges.- Keep constructors free of HTTP calls and side effects; this also makes unit tests simpler.
export class DetailComponent implements OnInit {
@Input() id!: string;
constructor(private api: ApiService) {} // id is undefined here
ngOnInit() { this.api.load(this.id).subscribe(); } // id is set
}
What they are checking: Whether you separate object construction from Angular initialisation
FresherMost askedFree with sign-inAnswerHideWhat is the difference between an Observable and a Promise?
A Promise is a single future value, and it starts running at once. An Observable is a stream of zero or more values over time, and it does nothing until you subscribe.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between Subject, BehaviorSubject and ReplaySubject?
A Subject is both an observable and an observer. It multicasts values to current subscribers. BehaviorSubject also holds a current value and gives it to new subscribers immediately. ReplaySubject replays a number of past values.
FresherMost askedFree with sign-inAnswerHideHow does routing work in Angular, and how do you define routes?
The Angular Router maps URL paths to components and renders them in a <router-outlet>. Routes are defined in a Routes array and registered with provideRouter.
FresherMost askedFree with sign-inAnswerHideWhat is lazy loading in Angular and how do you implement it?
Lazy loading downloads a part of the app only when the user goes to it. This makes the first bundle smaller and the first load faster.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between template-driven and reactive forms?
Template-driven forms define the form in the HTML with ngModel. They are simple and quick. Reactive forms define the form model in the TypeScript class with FormGroup and FormControl. This is clearer, easier to test, and grows better.
FresherMost askedFree with sign-inAnswerHideHow do you pass data between components?
Use @Input/@Output for parent and child, a shared service for unrelated components, and the router for page-to-page data.
FresherMost askedFree with sign-inAnswerHideWhat are structural directives, and what is the new built-in control flow in Angular 17+?
Structural directives change the DOM structure by adding or removing elements (*ngIf, *ngFor, *ngSwitch). Angular 17 introduced built-in control flow blocks that replace them in templates and need no imports.
FresherMost askedFree with sign-inAnswerHideWhy is trackBy (or track in @for) important?
It tells Angular how to identify each item in a list. Then Angular can reuse existing DOM nodes instead of deleting and creating them again when the array changes.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between ng-container, ng-template and ng-content?
All three are Angular helpers that do not appear as real elements, but each does something different.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between AOT and JIT compilation in Angular?
AOT (ahead-of-time) compiles templates and TypeScript to JavaScript at build time. JIT compiles them in the browser at run time. AOT is the default in modern Angular.
Node.js
FresherMost askedAnswerHideWhat is Node.js, and why is it called single-threaded and non-blocking?
Node.js is a JavaScript runtime built on Chrome's V8 engine. It lets you run JavaScript outside the browser, mostly for servers and tools.
Your JavaScript runs on one main thread, driven by an event loop. "Non-blocking" means slow operations (file, network, database) are handed to the operating system or libuv's thread pool. A callback or promise continues the work when they finish. The main thread stays free to serve other requests.
This makes Node good for I/O-heavy workloads: APIs, real-time chat, streaming, proxies. It is a poor fit for long CPU-heavy work (image processing, heavy maths) on the main thread. That work blocks every request. For that use worker threads, a job queue or another service.
What they are checking: Whether you understand the model, including its weakness
FresherMost askedAnswerHideWhat is middleware in Express? How does it work?
Middleware is a function (req, res, next) that runs between receiving a request and sending the response. It can read or modify req and res, end the response, or call next() to pass control on.
const express = require("express");
const app = express();
app.use(express.json()); // parse JSON body
app.use((req, res, next) => { // logger
console.log(req.method, req.url);
next();
});
app.get("/users/:id", auth, (req, res) => res.json({ id: req.params.id }));
app.use((err, req, res, next) => { // error middleware (4 args)
res.status(500).json({ error: "Server error" });
});
Order matters: middleware runs in the order it is registered. Types: application level, router level, built-in, third-party (helmet, cors, morgan) and error handling (four parameters). Forgetting next() leaves the request hanging.
What they are checking: Whether you understand the request pipeline and ordering
FresherMost askedAnswerHideWhat is the difference between blocking and non-blocking code, and synchronous and asynchronous APIs in Node?
Blocking code stops the thread until it finishes; nothing else on that thread can run. Non-blocking code starts the work and continues, with a callback, promise or event handling the result.
const fs = require("fs");
const data = fs.readFileSync("big.txt"); // blocks every request
fs.readFile("big.txt", (err, data) => {}); // callback
const d2 = await fs.promises.readFile("big.txt"); // promise
On a server, synchronous calls like readFileSync, pbkdf2Sync or a heavy JSON.parse stall all clients. They are acceptable at startup (loading config). Prefer the async versions in request handlers, and move CPU-heavy tasks to worker threads.
What they are checking: Whether you avoid blocking the loop
FresherMost askedFree with sign-inAnswerHideWhat is the difference between CommonJS and ES modules in Node.js?
CommonJS (CJS) uses require() and module.exports, loads synchronously, and is the traditional Node format. ES modules (ESM) use import/export, are statically analysed, load asynchronously and are the language standard.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between package.json and package-lock.json? What do npm install and npm ci do?
package.json lists your direct dependencies with version ranges plus scripts and metadata. package-lock.json records the exact version of every dependency (including indirect ones) and integrity hashes. So every install gives the same tree.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between authentication and authorisation, and between sessions and tokens?
Authentication verifies who you are (login). Authorisation decides what you may do (roles, permissions, ownership).
FresherMost askedFree with sign-inAnswerHideWhat is npm, and what are npm scripts and npx?
npm is Node's package manager and registry: it installs packages, runs scripts and publishes modules.
FresherMost askedFree with sign-inAnswerHideWhat is a Buffer in Node.js?
A Buffer is a fixed-size chunk of raw binary data allocated outside the V8 heap. It is used for files, network packets, images and crypto, where data is bytes rather than strings.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between dependencies and devDependencies, and what do ^ and ~ mean?
dependencies are packages needed at run time (express, pg). devDependencies are only needed for development and build (jest, eslint, typescript). npm install --omit=dev skips the latter in production. peerDependencies declare packages the host project must supply (common in plugins).
FresherMost askedFree with sign-inAnswerHideWhat is EventEmitter in Node.js?
EventEmitter (from the events module) is the base of Node's event-driven pattern. Objects emit named events and listeners react to them. Streams, HTTP servers and sockets all extend it.
FresherMost askedFree with sign-inAnswerHideHow do you read a file in Node.js, and what is the difference between readFile and createReadStream?
const fs = require("fs/promises");
const text = await fs.readFile("data.txt", "utf8"); // whole file in memory
const stream = require("fs").createReadStream("big.csv", "utf8"); // chunks
readFileloads the full file into memory, which is simple and fine for small files such as config. -...
FresherMost askedFree with sign-inAnswerHideHow do you manage configuration and environment variables in Node.js?
Keep configuration out of the code and read it from process.env, following the twelve-factor approach.
FresherMost askedFree with sign-inAnswerHideWhat is CORS, and how do you enable it in Express?
CORS (Cross-Origin Resource Sharing) is a browser mechanism. By default a page from one origin cannot read responses from another origin. The server opts in with headers such as Access-Control-Allow-Origin. For non-simple requests the browser first sends an OPTIONS preflight.
FresherMost askedFree with sign-inAnswerHideWhen would you choose Node.js over other backend technologies, and when not?
Choose Node.js for:
- I/O-bound APIs and microservices with many concurrent connections.
- Real-time features: chat, notifications, live dashboards (WebSocket, Server-Sent Events).
- Teams that already use JavaScript or TypeScript across frontend and backend, sharing types and code.
- Backends for frontends, serverless functions, proxies and tooling.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between module.exports and exports?
exports is a shortcut variable that initially points to the same object as module.exports. require() always returns module.exports.
FresherMost askedFree with sign-inAnswerHideHow do you create an HTTP server without Express?
Use the built-in http module.
FresherMost askedFree with sign-inAnswerHideHow do routing, route parameters and query strings work in Express?
Routes map an HTTP method and path to a handler. Use express.Router() to group related routes.
FresherMost askedFree with sign-inAnswerHideWhat is the process object in Node.js and what do you use it for?
process is a global object that represents the running Node process.
FresherMost askedFree with sign-inAnswerHideHow do you convert a callback-style function to use promises in Node.js?
Use util.promisify for functions that follow the Node convention (error first, callback last), or use the built-in promise APIs.
FresherMost askedFree with sign-inAnswerHideHow would you deploy a Node.js application to a Linux server without Docker?
Run the app as a managed process behind a reverse proxy, with the code delivered by a repeatable script.
C# and .NET
FresherMost askedAnswerHideWhat is the CLR and how does a C# program run on .NET?
The Common Language Runtime (CLR) is the execution engine of .NET. It loads, verifies and runs managed code and provides memory management, type safety and exception handling.
Flow: C# source -> compiler (Roslyn) -> CIL (intermediate language) in a DLL or EXE with metadata. At runtime: the JIT compiler turns CIL into native machine code -> the CLR runs it.
What the CLR provides:
- Garbage collection and memory management.
- CTS (Common Type System) and CLS so languages like C#, F# and VB interoperate.
- Assembly loading, type checking, security boundaries and threading.
- Tiered JIT and optional ahead-of-time (ReadyToRun, Native AOT) to cut startup time.
Managed code runs under the CLR. Unmanaged code (native DLLs) runs outside it and is reached through P/Invoke.
What they are checking: Whether you understand the runtime beyond writing C# syntax
FresherMost askedAnswerHideWhat is the difference between value types and reference types in C#?
Value types hold their data directly. Reference types hold a reference to an object on the managed heap.
| Value type | Reference type | |
|---|---|---|
| Examples | int, bool, double, struct, enum, DateTime | class, string, array, delegate, interface, record |
| Stored | Where declared (stack or inside the owning object) | Heap, variable holds a pointer |
| Assignment | Copies the value | Copies the reference |
| Default | Zero / false | null |
int a = 1; int b = a; b = 5;
Console.WriteLine(a); // 1, independent copies
var p = new Person { Name = "A" };
var q = p; q.Name = "B";
Console.WriteLine(p.Name); // B, same object
class Person { public string Name = ""; }
string is a reference type but behaves like a value because it is immutable. A value type inside a class lives on the heap with its owner. So "value types live on the stack" is only partly true.
What they are checking: Core memory model understanding, often the first question
FresherMost askedAnswerHideWhat are boxing and unboxing? Why do they hurt performance?
Boxing converts a value type to object (or an interface), allocating a heap object to hold a copy. Unboxing takes the value back out and needs a cast you write yourself.
int i = 42;
object o = i; // boxing: heap allocation + copy
int j = (int)o; // unboxing: type check + copy
// long k = (long)o; // InvalidCastException: the box holds an int
Cost: each box allocates memory, which increases garbage collection work, and the cast adds a type check. Hidden boxing happens when:
- Using non-generic collections such as
ArrayList. - Passing a struct to a method taking
objector a non-constrained interface. - Calling
string.FormatorConsole.WriteLine("{0}", i)with value types in older style.
Avoid it with generics (List<int>), generic constraints (where T : IComparable<T>), and Span<T>.
What they are checking: Whether you can reason about hidden allocations
FresherMost askedAnswerHideWhat is the difference between a class and a struct in C#?
A class is a reference type allocated on the heap. A struct is a value type copied on assignment.
| class | struct | |
|---|---|---|
| Type kind | Reference | Value |
| Inheritance | Yes (single) | No (interfaces only) |
| Default | null | All fields zeroed |
| Parameterless constructor | Yes | Allowed since C# 10 |
| Equality default | Reference | Field by field |
Use a struct when it is small (about 16 bytes) and stands for a single value (point, money, coordinates). It should also be immutable (cannot change after creation). Mutable structs cause surprising bugs because methods work on copies.
public readonly struct Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } }
public readonly record struct Money(decimal Amount, string Currency); // C# 10
Choose a class for everything else, including anything with identity or large state. Mutating a struct stored in a List<T> indexer does not compile, a typical trap.
What they are checking: Whether you choose a type kind on design and performance grounds
FresherMost askedAnswerHideWhat is the difference between an interface and an abstract class in C#?
An interface defines a contract. An abstract class defines a partially implemented base with shared state.
| Interface | Abstract class | |
|---|---|---|
| Multiple inheritance | A class can implement many | Only one base |
| Fields | No instance state | Yes |
| Constructors | No | Yes |
| Members | Default interface methods allowed since C# 8 | Abstract and concrete |
| Access modifiers | Public by default | Any |
public interface IRepository<T> { T? Get(int id); void Add(T item); }
public abstract class Report {
public void Run() { Load(); Render(); } // template method
protected abstract void Load();
protected abstract void Render();
}
Use interfaces for capabilities and for dependency injection and mocking. Use an abstract class when derived types share state or a skeleton algorithm. You can combine both: an interface for consumers and an abstract base for convenience.
What they are checking: Whether you know when to pick each, with DI and testing in mind
FresherMost askedAnswerHideExplain async and await in C#. What is a Task?
async/await lets you write asynchronous code that reads like synchronous code, freeing the thread while waiting for I/O.
A Task (or Task<T>) represents an ongoing operation that will complete later. await suspends the method without blocking the thread and resumes it when the task finishes. The compiler turns the method into a state machine.
using var http = new HttpClient();
string html = await GetLengthAsync(http);
Console.WriteLine(html);
static async Task<string> GetLengthAsync(HttpClient http)
{
string body = await http.GetStringAsync("https://example.com"); // thread is released here
return $"Length: {body.Length}";
}
Key points:
- Async is about scalability for I/O-bound work (database, HTTP, files), not about making CPU work faster. For CPU-bound work use
Task.Run. - Return
Task, notvoid, so callers can await and observe exceptions. - Name methods with the
Asyncsuffix. - Exceptions are thrown at the
awaitpoint.
What they are checking: The most asked C# topic: whether you understand it conceptually and not just the keywords
FresherMost askedAnswerHideExplain LINQ deferred execution with an example.
Most LINQ operators such as Where and Select do not run when you write them. They build a query that executes only when you enumerate it (foreach, ToList(), Count(), First()).
var numbers = new List<int> { 1, 2, 3 };
var query = numbers.Where(n => n > 1); // nothing executed yet
numbers.Add(10); // source changes
Console.WriteLine(string.Join(",", query)); // 2,3,10 (runs now, sees 10)
var snapshot = numbers.Where(n => n > 1).ToList(); // immediate execution
numbers.Add(20);
Console.WriteLine(snapshot.Count); // 3, unaffected
Consequences:
- The query always sees the latest data at enumeration time.
- Enumerating twice runs it twice, which can mean two database calls or repeated side effects. Materialise with
ToList()when you need a stable result. - Immediate operators:
ToList,ToArray,Count,Sum,First,Any. - With EF Core, a deferred query held past the
DbContextlifetime throws on enumeration.
What they are checking: Whether you know when LINQ actually runs
FresherMost askedAnswerHideWhat is the difference between IEnumerable and IQueryable?
IEnumerable<T> runs queries in memory using delegates. IQueryable<T> builds an expression tree that a provider (EF Core) translates into SQL and runs at the data source.
// IQueryable: filtering becomes SQL: SELECT ... WHERE Price > 100
IQueryable<Product> q = db.Products.Where(p => p.Price > 100);
// IEnumerable: AsEnumerable() switches to memory, loading ALL products first
IEnumerable<Product> bad = db.Products.AsEnumerable().Where(p => p.Price > 100);
| IEnumerable | IQueryable | |
|---|---|---|
| Executes | In process | In the data source |
| Lambdas | Func<T,bool> | Expression<Func<T,bool>> |
| Use for | In-memory collections | Database queries |
Pitfalls: returning IQueryable from a repository leaks database details to the caller. Also, a C# method that EF cannot translate to SQL may throw an error or silently run in memory instead. Keep filtering, sorting and paging on IQueryable, and call ToListAsync() last.
What they are checking: Whether you know where filtering runs, which decides performance
FresherMost askedAnswerHideWhat is dependency injection in ASP.NET Core and what are the service lifetimes?
DI is built into ASP.NET Core. You register services with a lifetime, and the container creates and injects them through constructors.
- Transient: a new instance every time it is requested. For lightweight, stateless services.
- Scoped: one instance per scope, which is one HTTP request. Used for
DbContextand unit-of-work style services. - Singleton: one instance for the app lifetime. Must be thread safe.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddTransient<IEmailBuilder, EmailBuilder>();
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddSingleton<IClock, SystemClock>();
var app = builder.Build();
app.MapGet("/", (IOrderService s) => s.Hello());
app.Run();
public interface IEmailBuilder {} public class EmailBuilder : IEmailBuilder {}
public interface IOrderService { string Hello(); }
public class OrderService : IOrderService { public string Hello() => "hi"; }
public interface IClock {} public class SystemClock : IClock {}
.NET 8 also adds keyed services (AddKeyedSingleton, [FromKeyedServices("x")]). Prefer constructor injection.
What they are checking: Fundamental ASP.NET Core knowledge
FresherMost askedFree with sign-inAnswerHideWhat is middleware in ASP.NET Core and why does the order matter?
Middleware are components in the request pipeline. Each receives the request, can act before and after calling the next component, or short-circuit the pipeline.
FresherMost askedFree with sign-inAnswerHideExplain the MVC pattern in ASP.NET Core. How is it different from Web API?
MVC splits an application into three parts. The Model holds data and business rules. The View makes the HTML with Razor. The Controller handles requests, calls the model and chooses a view.
FresherMost askedFree with sign-inAnswerHideWhat is Entity Framework Core? What is change tracking and when would you use AsNoTracking?
EF Core is an ORM (a tool that maps C# classes to database tables). It turns LINQ into SQL and tracks changes so it can save them.
FresherMost askedFree with sign-inAnswerHideHow does garbage collection work in .NET? What are generations and the LOH?
The .NET GC automatically frees managed memory for objects that are no longer reachable from roots. It is generational, based on most objects dying young.
FresherMost askedFree with sign-inAnswerHideWhat is IDisposable and the using statement? How do you implement the dispose pattern?
IDisposable is the contract for freeing unmanaged resources (file handles, sockets, DB connections) at a known time. using guarantees Dispose() runs even if an exception occurs.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between inner join, left join and right join in SQL Server? Write a query joining Orders and Customers.
- INNER JOIN: rows with matches in both tables.
- LEFT JOIN: all rows from the left table, matched rows from the right, NULL where no match.
- RIGHT JOIN: the mirror image.
- FULL OUTER JOIN: all rows from both.
FresherMost askedFree with sign-inAnswerHideWrite a SQL query to find the second highest salary, and the top earner per department.
Use window functions for flexibility. DENSE_RANK handles ties correctly.
FresherMost askedFree with sign-inAnswerHideWrite C# to find duplicate elements in a list and the first non-repeating character in a string.
LINQ with grouping, or a dictionary for counts, solves both in O(n).
FresherMost askedFree with sign-inAnswerHideExplain virtual, override, new and sealed in C#.
virtual allows a method to be overridden. override replaces it in a child class. new hides it. sealed stops any more overriding.
FresherMost askedFree with sign-inAnswerHideWhat are delegates and events in C#? What is the difference?
A delegate is a type-safe reference to a method. An event is a limited delegate field that lets a class publish notifications. Outside code can only subscribe or unsubscribe. It cannot call the event or overwrite it.
FresherMost askedFree with sign-inAnswerHideWhat are generics in C# and why use them? What are generic constraints?
Generics let you write type-safe code parameterised by type, with no casting and no boxing for value types.
FresherMost askedFree with sign-inAnswerHideHow do EF Core migrations work? How do you apply them safely in production?
A migration is a generated C# class that records a schema change (Up and Down). EF compares your model with the last snapshot to create it, and stores applied migrations in the __EFMigrationsHistory table.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between const, readonly and static readonly?
const is a compile-time constant. readonly is assigned at runtime once, in a declaration or constructor.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between .NET Framework, .NET Core and .NET 8?
They are generations of Microsoft's platform.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between IEnumerable, ICollection, IList and List<T>?
They form a hierarchy of increasing capability.
IEnumerable<T>: forward-only iteration (foreach). Possibly lazy.ICollection<T>: addsCount,Add,Remove,Contains.IList<T>: adds index access and insert at a position.List<T>: the concrete resizable array implementing all of them.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between string and StringBuilder in C#? What is string interpolation?
string is immutable, so each concatenation creates a new string. StringBuilder is a mutable buffer for repeated modification.
FresherMost askedFree with sign-inAnswerHideWrite a C# program to check whether a string is a palindrome, ignoring case and non-alphanumeric characters.
Use two pointers, skipping characters that are not letters or digits. This is O(n) time and O(1) extra space.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between ref, out and in parameters?
All pass by reference instead of by value, differing in initialisation and write rules.
OOP
FresherMost askedAnswerHideWhat are the four pillars of OOP?
The four pillars are encapsulation, abstraction, inheritance and polymorphism.
- Encapsulation: keep data and the methods that work on it in one class. Hide the internal state behind a controlled interface.
- Abstraction: expose only what a caller needs (the "what") and hide the implementation (the "how").
- Inheritance: a child class reuses and extends the fields and behaviour of a parent class.
- Polymorphism: one interface, many forms. The same call behaves differently depending on the object (overloading at compile time, overriding at run time).
class Shape:
def area(self): raise NotImplementedError
class Circle(Shape):
def __init__(self, r): self._r = r # encapsulated state
def area(self): return 3.14159 * self._r ** 2
for s in [Circle(1), Circle(2)]:
print(s.area()) # polymorphic call
What they are checking: Whether you know the four terms and can attach a one-line meaning and example to each
FresherMost askedAnswerHideWhat is the difference between a class and an object?
A class is a blueprint (a type definition with fields and methods). An object is a concrete instance of that class that exists in memory with its own state.
- Class: defined once, no memory for instance data until used. Example:
Car. - Object: created with
new(Java) or by calling the class (Python). Many objects can come from one class, each with its own field values.
class Car { String color; void drive() { System.out.println(color + " car moves"); } }
Car a = new Car(); a.color = "red";
Car b = new Car(); b.color = "blue"; // two objects, one class
class Car:
def __init__(self, color): self.color = color
a, b = Car("red"), Car("blue")
What they are checking: Basic clarity on type versus instance
FresherMost askedAnswerHideWhat is the difference between an abstract class and an interface?
Both define a contract, but they differ in what they can hold and how they are used.
| Abstract class | Interface | |
|---|---|---|
| State | Can have instance fields | Only constants (public static final) |
| Methods | Abstract and concrete, any access modifier | Abstract, default, static, private (Java 8+/9+) |
| Constructor | Yes | No |
| Inheritance | A class extends only one | A class implements many |
| Use | "is-a" with shared code and state | A capability or role (Comparable, Runnable) |
Pick an abstract class when subclasses share fields and a partial implementation. Pick an interface when unrelated classes should offer the same behaviour or you need multiple inheritance of type.
In Python, use abc.ABC for both ideas: a class with only abstract methods acts like an interface.
What they are checking: Whether you can choose between them and not just list syntax
FresherMost askedAnswerHideWhat is the difference between method overloading and method overriding?
Overloading: same method name in the same class with different parameter lists. It is resolved at compile time (static polymorphism). Overriding: a subclass provides its own body for a method with the same signature as in its parent. It is resolved at run time (dynamic polymorphism).
| Overloading | Overriding | |
|---|---|---|
| Where | Same class (or subclass) | Parent and child class |
| Signature | Must differ | Must match |
| Return type | Can differ | Same or covariant |
| Binding | Compile time | Run time |
class A { void show(int x) {} void show(String s) {} } // overloading
class B { void run() { System.out.println("B"); } }
class C extends B { @Override void run() { System.out.println("C"); } }
Python has no true overloading (the last def wins); use default arguments or functools.singledispatch.
What they are checking: Core polymorphism knowledge and awareness of compile time versus run time
FresherMost askedAnswerHideWhat is encapsulation? Give an example.
Encapsulation means keeping data private inside a class and giving access only through methods. So the class controls how its state changes and can protect its rules (invariants).
public class Account {
private double balance; // hidden
public void deposit(double amt) {
if (amt <= 0) throw new IllegalArgumentException("amount must be positive");
balance += amt;
}
public double getBalance() { return balance; }
}
Benefits: validation in one place, freedom to change internals without breaking callers, and fewer bugs from outside code touching fields directly. In Python, a single underscore (_balance) is a convention for "internal" and @property gives controlled access.
What they are checking: Whether you link encapsulation to protecting rules that must always be true, not just private fields
FresherMost askedAnswerHideWhat is polymorphism? Explain compile-time and run-time polymorphism.
Polymorphism means one name or interface, many behaviours.
- Compile-time (static): method overloading and operator overloading. The compiler picks the method from the argument types.
- Run-time (dynamic): method overriding. A parent reference holding a child object calls the child's version, chosen at run time.
abstract class Shape { abstract double area(); }
class Square extends Shape { double s = 2; double area() { return s * s; } }
class Circle extends Shape { double r = 1; double area() { return Math.PI * r * r; } }
Shape sh = new Circle();
System.out.println(sh.area()); // Circle's area, decided at run time
The payoff: callers depend on the abstraction (Shape) and new subclasses plug in without changing them.
What they are checking: Whether you can give a real example of dynamic dispatch
FresherMost askedAnswerHideWhat are the SOLID principles?
SOLID is five design principles for maintainable object-oriented code.
- S, Single Responsibility: a class should have one reason to change.
- O, Open/Closed: open for extension, closed for modification. Add behaviour by adding code, not editing tested code.
- L, Liskov Substitution: a subclass must be usable wherever its parent is expected without breaking correctness.
- I, Interface Segregation: prefer several small interfaces to one fat interface.
- D, Dependency Inversion: depend on abstractions, not concrete classes. High-level code should not import low-level details.
Quick example: an OrderService that builds PDF invoices, sends email and writes to the database breaks S. Split it, and inject an InvoiceSender interface (D) so you can add SMS later without editing the service (O).
What they are checking: Whether you can state all five and tie them to practice
FresherMost askedAnswerHideWhat is the contract between equals() and hashCode() in Java?
Rules:
- If
a.equals(b)is true, thena.hashCode() == b.hashCode(). - If hash codes are equal, the objects may or may not be equal (collisions).
equalsmust be reflexive, symmetric, transitive, consistent and return false for null.
If you override equals but not hashCode, equal objects can land in different buckets, so HashMap/HashSet fail to find them.
public final class Point {
private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
return o instanceof Point p && x == p.x && y == p.y;
}
@Override public int hashCode() { return java.util.Objects.hash(x, y); }
}
Do not use mutable fields in hashCode for keys: mutating a key after inserting it loses the entry. Records generate both methods for you.
What they are checking: A very common follow-up; checks hashing fundamentals
FresherMost askedAnswerHideWhat is inheritance, and what are its types?
Inheritance lets a class (child) get the fields and methods of another class (parent). Common code is written once, and the child adds or changes behaviour.
Types:
- Single: B extends A.
- Multilevel: C extends B extends A.
- Hierarchical: B and C both extend A.
- Multiple: a class has more than one parent. Java allows it only through interfaces; Python and C++ allow it for classes.
- Hybrid: a mix of the above.
class Animal { void eat() { System.out.println("eats"); } }
class Dog extends Animal { void bark() { System.out.println("barks"); } }
Use it for real "is-a" relationships only. For code reuse alone, prefer composition.
What they are checking: Vocabulary plus judgement about when to use it
FresherMost askedAnswerHideWhat is abstraction, and how is it different from encapsulation?
Abstraction hides complexity by showing only essential behaviour (design level: what a thing does). Encapsulation hides data by limiting access to a class's internals (implementation level: how state is protected).
- Abstraction is achieved with abstract classes and interfaces. Example: you call
list.sort()without knowing the algorithm. - Encapsulation is achieved with access modifiers and getters/setters. Example: a private
balancewith a validateddeposit.
They work together: an interface gives the abstract view, and encapsulation keeps the concrete class's state safe behind it.
What they are checking: The common confusion between these two pillars
FresherMost askedFree with sign-inAnswerHideWhat is the Singleton pattern, and how do you implement it thread-safely?
Singleton guarantees one instance of a class and a global access point. Typical uses: configuration, logger, connection pool.
Thread-safe Java options:
FresherMost askedFree with sign-inAnswerHideWhat is the Factory pattern, and when would you use it?
A factory creates objects without the caller naming the concrete class. The caller asks for a type and gets something that implements an interface.
FresherMost askedFree with sign-inAnswerHideWhat is a constructor? How is it different from a method?
A constructor is a special block that runs when an object is created and initialises its state.
FresherMost askedFree with sign-inAnswerHideWhat are the access modifiers in Java and what does each allow?
Java has four levels of visibility:
FresherMost askedFree with sign-inAnswerHideExplain the Single Responsibility Principle with an example.
A class should have one reason to change, meaning it serves one actor or concern.
Example of breaking it: an Employee class that calculates pay, saves itself to the database and prints reports. A change in tax rules, in the schema or in report layout all force edits to the same class.
FresherMost askedFree with sign-inAnswerHideExplain the Open/Closed Principle with an example.
Software entities should be open for extension but closed for modification: add new behaviour without editing code that already works.
Example of breaking it: a discount function with an if/elif per customer type. Every new type edits it.
FresherMost askedFree with sign-inAnswerHideHow does OOP in Python differ from Java?
- Typing: Python is dynamically typed and relies on duck typing (if it has
quack(), it works). Java is statically typed and needs types and interfaces written out. - Access control: Python has none enforced;
_xis a convention and__xis name-mangled. Java hasprivate,protected,public. -...
FresherMost askedFree with sign-inAnswerHideHow do you create an abstract class in Python?
Use the abc module: inherit from ABC and mark methods with @abstractmethod. A class with unimplemented abstract methods cannot be instantiated.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between instance, class and static methods in Python?
| Type | First argument | Access to | Typical use |
|---|---|---|---|
| Instance method | self | Object and class | Normal behaviour |
@classmethod | cls | Class only | Alternative constructors, class-level state |
@staticmethod | none | Neither | Utility tied to the class by topic |
class User:...
FresherMost askedFree with sign-inAnswerHideWhat do the this and super keywords do?
this refers to the current object. super refers to the parent class part of it.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between static and instance members?
Static members belong to the class and are shared by all objects. Instance members belong to each object.
- Static: one copy, accessed as
ClassName.member, loaded with the class. A static method cannot usethisor instance fields directly. - Instance: each object has its own copy.
FresherMost askedFree with sign-inAnswerHideWhat are default and static methods in interfaces?
Since Java 8, an interface can contain method bodies.
FresherMost askedFree with sign-inAnswerHideCan you override a static or private method?
No. Static methods belong to the class. So a subclass method with the same signature only hides the parent's method (method hiding). The call is resolved at compile time by the reference type. Private methods are not visible to subclasses. So a child method with the same name is a new method, not an override.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between tight coupling and loose coupling, and what is cohesion?
Coupling is how much one class depends on another. Cohesion is how closely the parts of a single class belong together.
Data Structures and Algorithms
FresherMost askedAnswerHideWhat is the difference between an array and a linked list?
An array stores elements in contiguous memory, so index access is O(1). A linked list stores nodes anywhere in memory, each pointing to the next, so reaching the k-th element takes O(k).
| Array | Linked list | |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert/delete at start | O(n) (shift) | O(1) |
| Insert/delete in middle (position known) | O(n) | O(1) |
| Search | O(n), O(log n) if sorted | O(n) |
| Memory | Compact, cache friendly | Extra pointer per node |
| Size | Fixed (or resized) | Grows freely |
Choose an array for fast random access and iteration. Choose a linked list for frequent insertions and deletions at known positions, such as the nodes behind an LRU cache. In practice arrays (or dynamic arrays) win most benchmarks because of CPU cache locality.
What they are checking: Trade-offs, not just definitions
FresherMost askedAnswerHideWhat is a stack and a queue? How do they differ?
A stack is LIFO (last in, first out): push and pop at the same end. A queue is FIFO (first in, first out): enqueue at the rear, dequeue from the front.
- Stack uses: function call stack, undo, expression evaluation, balanced brackets, DFS.
- Queue uses: task scheduling, BFS, buffering, print jobs.
from collections import deque
stack = []
stack.append(1); stack.append(2); print(stack.pop()) # 2
queue = deque()
queue.append(1); queue.append(2); print(queue.popleft()) # 1
Use deque for queues in Python: list.pop(0) is O(n). All push, pop, enqueue and dequeue operations are O(1).
What they are checking: Core structures and where they are used
FresherMost askedAnswerHideWhat is Big O notation? Explain O(1), O(log n), O(n), O(n log n) and O(n^2) with examples.
Big O describes how running time (or memory) grows with input size n in the worst case, ignoring constants. It lets you compare algorithms independent of hardware.
| Class | Example |
|---|---|
| O(1) | Array index, hash lookup (average) |
| O(log n) | Binary search, balanced BST lookup |
| O(n) | Linear search, one pass through a list |
| O(n log n) | Merge sort, heap sort, sorted() in Python |
| O(n^2) | Nested loops, bubble sort, insertion sort worst case |
| O(2^n) | Naive recursive Fibonacci, subsets |
Rules: drop constants and lower terms (3n + 10 becomes O(n)), add sequential steps, multiply nested ones. Big O is an upper bound; Omega is a lower bound and Theta a tight bound.
What they are checking: Fluency in complexity language
FresherMost askedAnswerHideHow does a hash table work, and how are collisions handled?
A hash table stores key-value pairs. A hash function converts the key into an integer, which is reduced to an index (hash(key) % capacity) pointing at a bucket. Lookup, insert and delete are O(1) on average.
A collision happens when two keys map to the same bucket. Common fixes:
- Chaining: each bucket holds a list (or tree) of entries. Java
HashMapdoes this. - Open addressing: probe for another free slot (linear probing, quadratic probing, double hashing). Python
dictuses this.
The load factor (entries / buckets) controls speed. When it passes a threshold (0.75 in Java), the table resizes and rehashes all keys. A bad hash function or an attacker choosing colliding keys can degrade operations to O(n).
Keys must be hashable and, if mutable, never changed while stored.
What they are checking: One of the most asked topics; checks you know the internals
FresherMost askedAnswerHideExplain binary search. What are its prerequisites and complexity?
Binary search finds a target in a sorted collection. It compares with the middle element again and again. Each time it throws away the half that cannot contain the target. Time is O(log n), extra space O(1) iterative.
Prerequisite: the data must be sorted and support O(1) random access (an array, not a linked list).
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2 # avoids overflow in fixed-width ints
if a[mid] == target: return mid
if a[mid] < target: lo = mid + 1
else: hi = mid - 1
return -1
print(binary_search([1, 3, 5, 7, 9], 7)) # 3
Python's bisect module provides it ready-made. The idea also applies to "binary search on the answer" problems.
What they are checking: Can you code it and get off-by-one details right
FresherMost askedAnswerHideWhat is a binary search tree (BST)? What are its operations and complexity?
A BST is a binary tree with one rule for every node. All keys in the left subtree are smaller. All keys in the right subtree are larger. This allows search, insert and delete by comparing and going left or right.
| Operation | Average (balanced) | Worst (skewed) |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
Inserting sorted data into a plain BST makes it a linked list (worst case). Self-balancing trees (AVL, Red-Black) keep height O(log n) with rotations.
In-order traversal of a BST returns the keys in sorted order, which is also the standard way to validate one.
What they are checking: Tree fundamentals and degenerate case awareness
FresherMost askedAnswerHideWhat is the difference between BFS and DFS? When do you use each?
Both visit every node of a graph or tree in O(V + E).
| BFS | DFS | |
|---|---|---|
| Order | Level by level | Go deep, then backtrack |
| Structure | Queue | Stack or recursion |
| Finds shortest path (unweighted) | Yes | No |
| Memory | Width of the graph | Depth of the graph |
Use BFS for shortest path in unweighted graphs, level-order traversal, "minimum steps" problems. Use DFS for cycle detection, topological sort, connected components, backtracking and path existence.
from collections import deque
def bfs(graph, start):
seen, q = {start}, deque([start])
order = []
while q:
n = q.popleft(); order.append(n)
for nb in graph[n]:
if nb not in seen:
seen.add(nb); q.append(nb)
return order
print(bfs({1: [2, 3], 2: [4], 3: [4], 4: []}, 1)) # [1, 2, 3, 4]
What they are checking: Graph traversal fundamentals
FresherMost askedAnswerHideCompare common sorting algorithms and their complexities.
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble | O(n) | O(n^2) | O(n^2) | O(1) | Yes |
| Insertion | O(n) | O(n^2) | O(n^2) | O(1) | Yes |
| Selection | O(n^2) | O(n^2) | O(n^2) | O(1) | No |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick | O(n log n) | O(n log n) | O(n^2) | O(log n) | No |
| Heap | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting | O(n + k) | O(n + k) | O(n + k) | O(k) | Yes |
Comparison sorts cannot beat O(n log n). Insertion sort is good for small or nearly sorted data. This is why real libraries (Python's Timsort, Java's Arrays.sort for objects) mix merge sort and insertion sort.
What they are checking: Whether you know the table and the reasons behind it
FresherMost askedAnswerHideQuick sort vs merge sort: which would you choose and why?
Both are divide and conquer with O(n log n) average time.
- Merge sort: guaranteed O(n log n), stable, needs O(n) extra space, good for linked lists and external (disk) sorting.
- Quick sort: average O(n log n), worst O(n^2) with poor pivots (reduced by random or median-of-three pivots). It sorts in place with O(log n) stack. It is usually faster on arrays because of cache locality. It is not stable.
Choose merge sort when stability or worst-case guarantees matter (sorting records by multiple keys, large files). Choose quick sort for in-memory primitive arrays where speed and memory matter.
What they are checking: Reasoning about trade-offs
FresherMost askedFree with sign-inAnswerHideWhat is a heap? How does a priority queue use it?
A binary heap is a complete binary tree stored in an array. Every parent is ordered against its children: in a min-heap the parent is smaller, in a max-heap larger. The root is always the min (or max).
FresherMost askedFree with sign-inAnswerHideWhat is dynamic programming? How is it different from recursion and greedy?
Dynamic programming (DP) solves problems that have overlapping subproblems and optimal substructure by storing sub-results so each is computed once.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between an array and a dynamic array (ArrayList, Python list)? What is amortized O(1)?
A dynamic array wraps a fixed array and grows when full: it allocates a bigger array (often 1.5x to 2x), copies the elements and continues. Append is O(1) amortized: occasional O(n) resizes are spread over many cheap appends, so the average cost per append stays constant.
FresherMost askedFree with sign-inAnswerHideExplain tree traversals: preorder, inorder, postorder and level-order.
For a binary tree:
- Preorder: node, left, right. Useful to copy a tree or serialise it.
- Inorder: left, node, right. Gives sorted order for a BST.
- Postorder: left, right, node. Useful to delete a tree or evaluate expression trees.
- Level-order: by depth, using a queue (BFS).
FresherMost askedFree with sign-inAnswerHideHow do you represent a graph? Adjacency list vs adjacency matrix.
- Adjacency list: a map from each vertex to its neighbours. Space O(V + E). Iterating neighbours is fast. Best for sparse graphs (most real ones).
- Adjacency matrix: a V x V grid where cell (i, j) marks an edge. Space O(V^2). Edge check is O(1). Best for dense graphs or when you need constant-time edge lookups.
FresherMost askedFree with sign-inAnswerHideCompare list, set, dict and deque complexities in Python.
| Operation | list | set | dict | deque |
|---|---|---|---|---|
Index a[i] | O(1) | n/a | O(1) by key | O(n) in middle |
| Append | O(1) amortized | add O(1) | set O(1) | O(1) both ends |
| Insert/pop at front | O(n) | n/a | n/a | O(1) |
x in c | O(n) | O(1) avg | O(1) avg | O(n) |
| Remove value | O(n) | O(1)... |
FresherMost askedFree with sign-inAnswerHideExplain memoization vs tabulation in dynamic programming.
Both avoid recomputing subproblems.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between time complexity and space complexity?
Time complexity measures how the number of operations grows with input size. Space complexity measures how extra memory grows with input size (usually excluding the input itself, called auxiliary space).
FresherMost askedFree with sign-inAnswerHideWhat is the difference between singly and doubly linked lists?
A singly linked list node has data and next. A doubly linked list node also has prev.
FresherMost askedFree with sign-inAnswerHideWhat is a stable sorting algorithm and why does it matter?
A sort is stable if elements with equal keys keep their original relative order.
FresherMost askedFree with sign-inAnswerHideWhat is recursion? What is a base case and what causes stack overflow?
Recursion is when a function calls itself on a smaller version of the problem. It needs:
- A base case that returns without recursing.
- A recursive case that moves toward the base case.
Coding
FresherMost askedAnswerHideHow do you reverse a string in Python (and without slicing)?
Slicing is the normal way to do it in Python. Without it, build the result from the end or swap characters from both ends of a list.
def reverse(s):
return s[::-1]
def reverse_manual(s):
chars = list(s)
i, j = 0, len(chars) - 1
while i < j:
chars[i], chars[j] = chars[j], chars[i]
i += 1; j -= 1
return "".join(chars)
print(reverse("hello"), reverse_manual("hello")) # olleh olleh
Strings are immutable, so a copy is needed. Complexity: O(n) time, O(n) space.
What they are checking: Basic string handling and awareness of immutability
FresherMost askedAnswerHideWrite a function to check whether a string is a palindrome.
Compare the cleaned string with its reverse, or use two pointers moving inward to avoid the extra copy. For sentences, ignore case and non-alphanumeric characters.
def is_palindrome(s):
i, j = 0, len(s) - 1
while i < j:
if not s[i].isalnum(): i += 1
elif not s[j].isalnum(): j -= 1
else:
if s[i].lower() != s[j].lower(): return False
i += 1; j -= 1
return True
print(is_palindrome("A man, a plan, a canal: Panama"), is_palindrome("hello")) # True False
Complexity: O(n) time, O(1) space.
What they are checking: Two pointer basics and edge cases (case, punctuation)
FresherMost askedAnswerHideWrite the FizzBuzz program.
Print numbers 1 to n; multiples of 3 print Fizz, multiples of 5 print Buzz, multiples of both print FizzBuzz. Check the combined case first (or build the string).
def fizzbuzz(n):
out = []
for i in range(1, n + 1):
s = ("Fizz" if i % 3 == 0 else "") + ("Buzz" if i % 5 == 0 else "")
out.append(s or str(i))
return out
print(fizzbuzz(15))
Complexity: O(n) time. The common mistake is testing 3 and 5 before 15, so 15 prints only Fizz.
What they are checking: Basic control flow and ordering of conditions
FresherMost askedAnswerHideTwo Sum: find two numbers in an array that add up to a target.
Use a hash map from value to index. For each number, check whether target - x has been seen. One pass instead of a nested loop.
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
if target - x in seen:
return [seen[target - x], i]
seen[x] = i
return []
print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
Complexity: O(n) time, O(n) space. Brute force is O(n^2) time and O(1) space. If the array is sorted, two pointers give O(n) time with O(1) space.
What they are checking: The classic hash map optimisation
FresherMost askedAnswerHideHow do you check whether two strings are anagrams?
Two strings are anagrams if they have the same characters with the same counts. Compare sorted strings, or compare character counts (faster).
from collections import Counter
def is_anagram(a, b):
return Counter(a) == Counter(b)
def is_anagram_sorted(a, b):
return sorted(a) == sorted(b)
print(is_anagram("listen", "silent"), is_anagram("abc", "abd")) # True False
Counter: O(n) time, O(k) space for k distinct characters. Sorting: O(n log n). Clarify with the interviewer whether case and spaces matter.
What they are checking: Frequency counting
FresherMost askedAnswerHideWrite a function to return the n-th Fibonacci number. How do you make it efficient?
The naive recursion repeats work and is O(2^n). Use iteration with two variables, or memoization.
from functools import lru_cache
def fib(n): # iterative
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
@lru_cache(maxsize=None)
def fib_memo(n):
return n if n < 2 else fib_memo(n - 1) + fib_memo(n - 2)
print(fib(10), fib_memo(10)) # 55 55
Iterative: O(n) time, O(1) space. Memoized: O(n) time and space. A matrix or fast-doubling method gives O(log n).
What they are checking: Recursion, repeated subproblems and DP awareness
FresherMost askedAnswerHideFind the second largest element in an array.
Track the largest and second largest in one pass, no sorting needed. Handle duplicates by requiring a strictly smaller value.
def second_largest(nums):
first = second = float("-inf")
for x in nums:
if x > first:
first, second = x, first
elif first > x > second:
second = x
return None if second == float("-inf") else second
print(second_largest([5, 9, 2, 9, 7])) # 7
Complexity: O(n) time, O(1) space. Sorting works but costs O(n log n). Edge cases: fewer than two distinct values.
What they are checking: One-pass thinking and edge cases
FresherMost askedAnswerHideHow do you find duplicates in an array?
Use a set to remember what you have seen. A value already present is a duplicate.
def find_duplicates(nums):
seen, dups = set(), set()
for x in nums:
if x in seen: dups.add(x)
else: seen.add(x)
return list(dups)
print(sorted(find_duplicates([1, 2, 3, 2, 4, 1]))) # [1, 2]
Complexity: O(n) time, O(n) space. Alternatives: sort and compare neighbours (O(n log n), O(1) extra space), or if values are 1..n, use index marking in place.
What they are checking: Set usage and space-time trade-off
FresherMost askedAnswerHideCheck if a string of brackets is valid (Valid Parentheses).
Use a stack. Push opening brackets; on a closing bracket, the top of the stack must be its matching opener. At the end the stack must be empty.
def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
else:
stack.append(ch)
return not stack
print(is_valid("{[()]}"), is_valid("(]")) # True False
Complexity: O(n) time, O(n) space.
What they are checking: Stack usage
FresherMost askedAnswerHideMerge two sorted arrays into one sorted array.
Use two pointers, always taking the smaller current element. Append what remains.
def merge(a, b):
i = j = 0
out = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
out.extend(a[i:]); out.extend(b[j:])
return out
print(merge([1, 3, 5], [2, 4, 6, 8])) # [1, 2, 3, 4, 5, 6, 8]
Complexity: O(m + n) time, O(m + n) space. This is the merge step of merge sort. If one array has spare room at the end (merge in place), fill from the back.
What they are checking: Two pointers and merge sort foundation
FresherMost askedFree with sign-inAnswerHideWrite a program to check whether a number is prime.
A prime has no divisors other than 1 and itself. You only need to test divisors up to the square root.
FresherMost askedFree with sign-inAnswerHideCount the frequency of each character or word in a string.
Use a dictionary (or Counter) mapping each item to its count.
FresherMost askedFree with sign-inAnswerHideImplement binary search (iterative) and return the index of the target.
Keep lo and hi bounds; compare the middle value and throw away half each time. The array must be sorted.
FresherMost askedFree with sign-inAnswerHideReverse a singly linked list.
Walk the list while reversing each next pointer, keeping track of the previous node.
FresherMost askedFree with sign-inAnswerHideDetect a cycle in a linked list.
Floyd's tortoise and hare: move one pointer by 1 and another by 2. If there is a cycle they meet; otherwise the fast pointer reaches the end.
FresherMost askedFree with sign-inAnswerHideFind the missing number in an array containing 1 to n with one number missing.
The expected sum of 1..n is n(n+1)/2. Subtract the actual sum. XOR also works and avoids overflow in fixed-width languages.
FresherMost askedFree with sign-inAnswerHideFind the first non-repeating character in a string.
Count characters in the first pass, then return the first character whose count is 1 in a second pass.
FresherMost askedFree with sign-inAnswerHideMove all zeros to the end of an array while keeping the order of other elements.
Use a write pointer: copy each non-zero value forward, then fill the rest with zeros. This works in place.
FresherMost askedFree with sign-inAnswerHideRotate an array to the right by k positions.
Take k modulo n, then use slicing for clarity, or three reversals for O(1) extra space.
FresherMost askedFree with sign-inAnswerHideReverse the words in a sentence.
Split on whitespace, reverse the list, join with a single space. Using split() without arguments also collapses extra spaces.
FresherMost askedFree with sign-inAnswerHideCompute the GCD and LCM of two numbers.
Euclid's algorithm: gcd(a, b) = gcd(b, a % b) until b is 0. LCM follows from lcm = a * b / gcd.
FresherMost askedFree with sign-inAnswerHideWhat is the time and space complexity of common solutions: sorting, hash lookup, nested loops over an array of n items?
- Sorting with a comparison sort (
sorted,Arrays.sort): O(n log n) time. - Hash map or set lookup, insert, delete: O(1) on average, O(n) worst case.
- Single loop over the array: O(n).
- Two nested loops over the array: O(n^2).
- Binary search on sorted data: O(log n).
- Generating all subsets: O(2^n); all permutations: O(n!).
FresherMost askedFree with sign-inAnswerHideWhat is the complexity of checking membership in a Python list versus a set?
x in some_list scans the list: O(n). x in some_set hashes x and looks it up: O(1) on average. For repeated membership tests, first turn the list into a set (O(n) once). This changes an O(n * m) algorithm into O(n + m).
FresherMost askedFree with sign-inAnswerHideWrite a function that compresses a string by counting repeated characters, for example aaabbc becomes a3b2c1.
Walk the string once. Keep the current character and its run length. When the run ends, add the character and the count to the result. Use a list and join at the end, because repeated string concatenation is slower.
FresherMost askedFree with sign-inAnswerHideHow do you flatten a nested list or array with any depth?
Use recursion when the depth is small. Use your own stack when the nesting could be very deep and you want to avoid the recursion limit.
FresherMost askedFree with sign-inAnswerHideGiven a list of invoice lines, each with a customer and an amount, group them by customer. Return each customer's total and line count.
Use a dictionary keyed by customer and update it in one pass. This is O(n) and does not need sorting.
FresherMost askedFree with sign-inAnswerHideReturn the intersection of two arrays.
Put one array into a set and keep elements of the other that are in it. For duplicates counted multiple times, use Counter.
REST API
FresherMost askedAnswerHideWhat is a REST API and what are the REST principles?
REST (Representational State Transfer) is a style for building APIs. Each resource has a URL, and you use standard HTTP methods to work with it.
Core constraints:
- Client-server: UI and data storage are separated.
- Stateless: each request carries everything needed. The server keeps no session between calls.
- Cacheable: responses declare whether they can be cached.
- Uniform interface: resource URIs, standard methods, representations such as JSON, and (ideally) hypermedia links.
- Layered system: proxies, gateways and load balancers can sit between the client and the server.
- Code on demand (optional): the server can send code to run on the client.
Example: GET /users/42 returns user 42, DELETE /users/42 removes it. Use nouns in URLs and let the HTTP method express the action.
What they are checking: Whether you know the constraints, not only 'it uses JSON over HTTP'
FresherMost askedAnswerHideWhat are the main HTTP methods and what is each used for?
| Method | Purpose | Safe | Idempotent |
|---|---|---|---|
| GET | Read a resource | Yes | Yes |
| POST | Create a resource or trigger an action | No | No |
| PUT | Replace a resource entirely | No | Yes |
| PATCH | Partially update a resource | No | Not guaranteed |
| DELETE | Remove a resource | No | Yes |
| HEAD | Like GET but headers only | Yes | Yes |
| OPTIONS | Describe allowed methods (used by CORS preflight) | Yes | Yes |
Example mapping for a books collection:
GET /bookslist,POST /bookscreateGET /books/7read,PUT /books/7replace,PATCH /books/7update fields,DELETE /books/7remove
Safe means it does not change server state. Idempotent means repeating the call has the same effect as calling it once.
What they are checking: What each method means, including safe and idempotent
FresherMost askedAnswerHideWhat is the difference between PUT and PATCH?
PUT replaces the whole resource with the body you send. PATCH applies a partial change to only the fields you send.
Existing user: {"name": "Asha", "email": "[email protected]", "city": "Pune"}
PUT /users/1
{"name": "Asha K", "email": "[email protected]"}
Result: city is gone (the resource is now exactly what was sent), so clients must send the full representation.
PATCH /users/1
{"name": "Asha K"}
Result: only name changes, email and city stay.
- PUT is idempotent by definition.
- PATCH can be idempotent (for example, set a field to a value). But it is not guaranteed (for example, an "increment by 1" operation).
- Prefer PATCH for small edits to large objects. It saves bandwidth and avoids overwriting other people's changes.
What they are checking: Replace vs partial update with an example
FresherMost askedAnswerHideWhat is the difference between PUT and POST?
POST creates a subordinate resource and the server usually chooses the id. PUT creates or replaces a resource at a URL the client specifies.
| POST | PUT | |
|---|---|---|
| Target URL | Collection (/orders) | Specific resource (/orders/15) |
| Idempotent | No: two calls create two orders | Yes: two calls leave one result |
| Typical response | 201 Created with Location header | 200 OK or 204, or 201 if created |
| Use for | Create, actions, non-CRUD operations | Full replace, upsert with a client-known id |
Because POST is not idempotent, a client retry after a timeout can create duplicates. That is why payment APIs accept an idempotency key with POST.
What they are checking: Idempotency and who chooses the id
FresherMost askedAnswerHideWhat does idempotent mean in REST and which methods are idempotent?
An operation is idempotent if performing it once or many times leaves the server in the same state. The response may be different, but the effect must be the same.
- Idempotent: GET, HEAD, OPTIONS, PUT, DELETE.
- Not idempotent: POST, and PATCH in general.
Example: DELETE /users/5 the first time returns 204 and removes the user. The second time returns 404. But the end state is the same: user 5 does not exist. POST /orders twice creates two orders.
Why it matters: networks fail, so clients and gateways retry. Idempotent calls are safe to retry. For POST, make retries safe with an Idempotency-Key header: the server saves the key with the result. If the same key comes again, it returns the saved result.
What they are checking: Retry-safety reasoning
FresherMost askedAnswerHideWhat are the common HTTP status codes and what do they mean?
Grouped by class:
- 1xx informational:
101 Switching Protocols(WebSocket upgrade). - 2xx success:
200 OK,201 Created,202 Accepted(queued for async work),204 No Content. - 3xx redirection:
301 Moved Permanently,302 Found,304 Not Modified(cached copy valid). - 4xx client error:
400 Bad Request,401 Unauthorized(not authenticated),403 Forbidden(authenticated but not allowed),404 Not Found. Also405 Method Not Allowed,409 Conflict,422 Unprocessable Content(valid syntax, failed validation),429 Too Many Requests. - 5xx server error:
500 Internal Server Error,502 Bad Gateway,503 Service Unavailable,504 Gateway Timeout.
Return the most specific code. Never return 200 with an error in the body, because clients and monitoring tools rely on the status.
What they are checking: Precise use of codes
FresherMost askedAnswerHideWhat is the difference between 401 and 403?
401 Unauthorized means the request lacks valid authentication: no token, an expired token, or wrong credentials. The client should authenticate and retry. Include a WWW-Authenticate header.
403 Forbidden means the server knows who you are but you are not allowed to do this. Logging in again will not help.
Examples:
- Calling
/orderswith noAuthorizationheader: 401. - A normal user calling
DELETE /users/9: 403. - Some APIs return 404 instead of 403 when a user should not even know the resource exists. This hides that it exists.
What they are checking: Authn vs authz mapped to codes
FresherMost askedAnswerHideWhat is the difference between authentication and authorization?
Authentication proves who you are. Authorization decides what you are allowed to do.
| Authentication | Authorization | |
|---|---|---|
| Question | Who are you? | What can you access? |
| Happens | First | After authentication |
| Mechanisms | Passwords, MFA, tokens, certificates | Roles, permissions, scopes, ACLs, policies |
| Failure code | 401 | 403 |
Analogy: showing your ID at the building entrance is authentication; the badge that opens only certain floors is authorization.
In an API, the token proves identity (authentication). Then the code checks that the user's role or scope allows DELETE /projects/3 and that they own that project (authorization).
What they are checking: Core security distinction
FresherMost askedAnswerHideWhat is a JWT and how does it work?
A JSON Web Token (JWT) is a small, signed token that carries information (claims) between two parties. It has three Base64URL parts separated by dots: header.payload.signature.
- Header: algorithm and type, for example
{"alg": "RS256", "typ": "JWT"}. - Payload: claims such as
sub(user id),exp(expiry),iss,aud, roles. - Signature: made from the header and payload with a secret (HMAC) or a private key (RSA/ECDSA).
Flow: the user logs in and the server gives back a JWT. The client sends Authorization: Bearer <token> on later calls. The server checks the signature and expiry, with no session lookup.
Important points:
- The payload is encoded, not encrypted: never put secrets in it.
- Always check the signature,
exp,issandaud. Allow only the algorithm you expect. - Tokens are hard to cancel before they expire. So keep access tokens short-lived (5 to 15 minutes) and use refresh tokens.
What they are checking: Understanding structure and pitfalls
FresherMost askedFree with sign-inAnswerHideHow do you implement pagination in a REST API?
Never return an unbounded list. Common styles:
FresherMost askedFree with sign-inAnswerHideWhat is CORS and why does it exist?
Cross-Origin Resource Sharing (CORS) is a browser rule. It controls which other origins can call your API from JavaScript. An origin is scheme plus host plus port. By default, the same-origin policy stops a page on https://app.com from reading responses from https://api.com.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between hashing, encryption and encoding? Which one do you use for passwords?
They solve different problems:
FresherMost askedFree with sign-inAnswerHideWhat makes a good REST URL design? Give naming conventions.
Use nouns for resources, plural collections, and let the HTTP method be the verb.
Good:
GET /usersandGET /users/42GET /users/42/orders(nested only one or two levels deep)POST /users,DELETE /users/42
FresherMost askedFree with sign-inAnswerHideWhat is the difference between stateless and stateful, and why is REST stateless?
In a stateful service, the server remembers the client between requests (a server-side session). In a stateless service, every request has all the information needed, such as an auth token and parameters. The server stores nothing about the previous call.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between SOAP and REST?
| SOAP | REST | |
|---|---|---|
| Type | Protocol with strict rules | Architectural style |
| Format | XML only | JSON, XML, others (JSON typical) |
| Contract | WSDL | OpenAPI (optional) |
| Transport | HTTP, SMTP, others | HTTP |
| Weight | Heavier, long XML envelope | Lightweight |
| Security | WS-Security built in... |
FresherMost askedFree with sign-inAnswerHideWhat are webhooks and how are they different from polling?
A webhook is an HTTP callback. When an event happens, the provider sends a POST to a URL you registered. Polling means your client keeps asking "anything new?".
FresherMost askedFree with sign-inAnswerHideHow do you document and test a REST API?
Documentation: describe the API with an OpenAPI (Swagger) spec. It lists endpoints, parameters, schemas, auth and error responses. Make interactive docs (Swagger UI, Redoc) and client SDKs from it. Keep the spec in version control. Ideally, create or check it from the code so it stays correct.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between an API key, a bearer token and basic authentication?
- Basic auth: the client sends
Authorization: Basic base64(user:password)on every request. It is only Base64 encoded, so you must use HTTPS. The password is sent on every call. It is fine for simple internal tools. - API key: a long random string that identifies the calling application. It is sent in a header...
FresherMost askedFree with sign-inAnswerHideWhat are the differences between query parameters, path parameters and request body? When should each be used?
- A path parameter identifies one resource:
GET /users/42. It is required. - A query parameter filters, sorts or pages a list:
GET /users?role=admin&sort=name&limit=20. Usually optional. - The request body carries the data to create or update:
POST /userswith JSON. It is used with POST, PUT and PATCH. - Headers carry extra information such as auth, content type, idempotency key and version.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between synchronous and asynchronous APIs?
A synchronous API holds the connection until the work is done and returns the final result. The client waits.
An asynchronous API accepts the request and replies at once (usually 202 Accepted). The result comes later through polling, a webhook, or a stream.
Django and FastAPI
FresherMost askedAnswerHideExplain the Django MVT architecture. How is it different from MVC?
Django uses Model, View, Template (MVT).
- Model: Python classes that define data and map to database tables through the ORM.
- View: a function or class that receives an HTTP request, talks to models, and returns a response. This is the logic, similar to a controller in MVC.
- Template: the HTML presentation layer with Django template language.
The "controller" role in MVC is played by the framework itself: the URL dispatcher (urls.py) routes a request to the right view.
# urls.py
path("posts/", views.post_list)
# views.py
def post_list(request):
posts = Post.objects.order_by("-created")[:10]
return render(request, "posts.html", {"posts": posts})
So MVT is MVC with different names: Django's view is MVC's controller and Django's template is MVC's view. In a REST API setup, templates are replaced by serializers returning JSON.
What they are checking: Whether you can map Django's terms to MVC without confusion
FresherMost askedAnswerHideWhat is Django ORM? Show basic create, read, update and delete operations.
The ORM (Object Relational Mapper) lets you use database rows as Python objects. It writes the SQL for you. Each model class maps to a table and each field to a column.
class Book(models.Model):
title = models.CharField(max_length=200)
price = models.DecimalField(max_digits=8, decimal_places=2)
author = models.ForeignKey("Author", on_delete=models.CASCADE)
b = Book.objects.create(title="Dune", price=9.99, author=a) # create
Book.objects.filter(price__lt=10).order_by("title") # read
Book.objects.filter(id=b.id).update(price=12) # update
b.delete() # delete
Benefits: it works with many databases, it escapes values to stop SQL injection, and it has migrations. Limits: complex report queries may need .raw() or raw SQL. Careless use makes slow queries (see N+1).
What they are checking: Comfort with the ORM and awareness of its limits
FresherMost askedAnswerHideWhat is the difference between `select_related` and `prefetch_related`?
Both avoid extra queries when you access related objects, but they work differently.
| select_related | prefetch_related | |
|---|---|---|
| Relations | ForeignKey, OneToOne (single-valued) | ManyToMany, reverse FK, generic relations |
| How | SQL JOIN, one query | One extra query per relation, joined in Python |
| Result | Related objects come in the same row | Saved on each object from an IN (...) query |
# one query with JOIN
books = Book.objects.select_related("author")
# two queries: books, then authors' tags
authors = Author.objects.prefetch_related("books")
# fine-tune the prefetch
from django.db.models import Prefetch
Author.objects.prefetch_related(
Prefetch("books", queryset=Book.objects.filter(published=True))
)
Use select_related for "one" side joins and prefetch_related for "many" side. Check with django-debug-toolbar or len(connection.queries).
What they are checking: The join versus second-query distinction
FresherMost askedAnswerHideWhat are Django migrations and how do they work?
Migrations are Python files, kept in version control, that describe changes to your database schema (create model, add field, change field). Django creates them from your model changes.
python manage.py makemigrations # detect model changes, write migration files
python manage.py migrate # apply unapplied migrations
python manage.py showmigrations # list applied state
python manage.py sqlmigrate app 0003 # preview SQL
- Applied migrations are recorded in the
django_migrationstable. - Each migration lists its
dependencies, so they form a graph. - Migrations can also change data with
RunPythonand run raw SQL withRunSQL. - Commit migration files to git. Never edit an applied one; create a new migration.
- If two branches create the same migration number, fix it with
makemigrations --merge.
What they are checking: Practical workflow and not editing applied migrations
FresherMost askedAnswerHideWhat is the difference between Django, Flask and FastAPI? When would you choose each?
| Django | Flask | FastAPI | |
|---|---|---|---|
| Style | Everything included, full-stack | Small framework, you add the pieces | Modern async API framework |
| Built-in | ORM, admin, auth, forms, migrations | Routing, templating (Jinja) | Routing, validation, OpenAPI docs |
| Protocol | WSGI, ASGI supported | WSGI (async limited) | ASGI, async first |
| Validation | Forms, DRF serializers | Extensions | Pydantic from type hints |
| Best for | Content sites, admin-heavy apps, single big apps | Small services, prototypes | High-performance JSON APIs, microservices |
Choose Django when you want a complete, convention-driven stack and an admin panel quickly. Choose Flask for small, flexible apps where you pick every library. Choose FastAPI for API-only services where automatic docs, type-driven validation and async I/O matter. They can coexist: a Django monolith plus FastAPI microservices is common.
What they are checking: Reasons for each choice, not just a favourite
FresherMost askedAnswerHideWhat is a serializer in Django REST Framework? How do `Serializer` and `ModelSerializer` differ?
A serializer turns complex objects (model instances, querysets) into plain Python types for JSON output. It also checks incoming data and turns it back into objects.
Serializer: you declare every field and implementcreate/updateyourself.ModelSerializer: makes the fields and defaultcreateandupdatefrom a model.
class BookSerializer(serializers.ModelSerializer):
author_name = serializers.CharField(source="author.name", read_only=True)
class Meta:
model = Book
fields = ["id", "title", "price", "author", "author_name"]
def validate_price(self, value):
if value <= 0:
raise serializers.ValidationError("must be positive")
return value
Use validate_<field> for single-field rules and validate() for cross-field rules. Call serializer.is_valid(raise_exception=True) then serializer.save(). Avoid fields = "__all__" in public APIs, because new model fields would be shown automatically.
What they are checking: Validation hooks and controlling what is shown
FresherMost askedAnswerHideWhat is Pydantic and how does FastAPI use it?
Pydantic is a data validation library that uses Python type hints. You define a model. It reads and checks the input, changes types where it makes sense, and gives clear errors. FastAPI uses Pydantic models for request bodies and responses, and to build the OpenAPI schema.
from fastapi import FastAPI
from pydantic import BaseModel, Field, EmailStr
class UserIn(BaseModel):
name: str = Field(min_length=2)
age: int = Field(ge=0, le=120)
email: EmailStr # requires email-validator package
class UserOut(BaseModel):
id: int
name: str
app = FastAPI()
@app.post("/users", response_model=UserOut, status_code=201)
def create(user: UserIn):
return {"id": 1, "name": user.name}
Invalid input returns an automatic 422 with details. response_model removes fields like passwords. Pydantic v2 (written in Rust) is much faster than v1 and uses model_validate, model_dump, and field_validator.
What they are checking: Validation and response filtering in FastAPI
FresherMost askedFree with sign-inAnswerHideAre Django QuerySets lazy? Explain when the database is actually hit.
Yes. Building or chaining a QuerySet does not run SQL. The query runs only when the results are needed.
FresherMost askedFree with sign-inAnswerHideExplain model relationships in Django: ForeignKey, OneToOne and ManyToMany.
ForeignKey: many-to-one. Many books belong to one author.OneToOneField: one-to-one, e.g. aProfileextending a user.ManyToManyField: many-to-many, e.g. students and courses. Django creates a hidden join table, or you define athroughmodel to store extra fields.
FresherMost askedFree with sign-inAnswerHideHow do path parameters, query parameters and request bodies work in FastAPI?
FastAPI decides by where the parameter appears and by its type.
- In the path string: path parameter.
- Simple types not in the path: query parameter.
- A Pydantic model: JSON request body.
FresherMost askedFree with sign-inAnswerHideDescribe the request-response lifecycle in Django.
- The web server (through WSGI or ASGI) gives the request to Django, which builds an
HttpRequest. - Request middleware runs in the order listed in
MIDDLEWARE(security, sessions, CSRF, authentication). - The URL resolver matches the path against
urlpatternsand picks a view. - The view runs. It may query the...
FresherMost askedFree with sign-inAnswerHideWhat is middleware in Django? How do you write a custom one?
Middleware is a chain of hooks. They process every request before the view and every response after it. Built-ins handle security headers, sessions, CSRF protection and authentication.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between authentication and authorization (permissions) in DRF?
Authentication finds out who the caller is. Authorization decides what they may do. In DRF they are separate parts.
authentication_classessetrequest.userandrequest.auth. Failure gives 401.permission_classescheck access. Failure gives 403.
FresherMost askedFree with sign-inAnswerHideHow does CSRF protection work in Django?
CSRF (Cross-Site Request Forgery) tricks a logged-in user's browser into sending a request the user did not want. Django stops this with a secret token that a bad site cannot read.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between `get()` and `filter()` in Django ORM?
get() returns exactly one object, and raises an error if there are none or many. filter() returns a QuerySet (it may be empty) and never raises an error for no results.
FresherMost askedFree with sign-inAnswerHideHow do you manage settings and secrets for multiple environments in Django?
Keep configuration out of the code and read it from environment variables. Use one settings module per environment, or one module that reads env vars.
FresherMost askedFree with sign-inAnswerHideWhat is FastAPI's automatic documentation and how is it generated?
FastAPI builds an OpenAPI schema from your routes, type hints and Pydantic models. It serves interactive docs with no extra work.
- Swagger UI at
/docs, where you can try requests. - ReDoc at
/redoc. - Raw schema at
/openapi.json.
FresherMost askedFree with sign-inAnswerHideWhat built-in security features does Django provide and what settings should you check before going live?
Django protects against several common attacks by default:
FresherMost askedFree with sign-inAnswerHideHow are static files and media files handled in Django?
Static files are assets that come with the code (CSS, JS, images). Media files are uploads from users.
FresherMost askedFree with sign-inAnswerHideWhat are Django admin and ModelAdmin? How would you customise it?
The Django admin is a back-office website that Django makes for you. It manages model data and comes from django.contrib.admin. You register models and change the screen with a ModelAdmin.
NestJS
FresherMost askedAnswerHideWhat is NestJS and why would you choose it over plain Express?
NestJS is a TypeScript-first Node.js framework for server-side apps. It adds structure (modules, controllers, providers) and dependency injection on top of Express or Fastify.
Why choose it:
- Enforced architecture, so large teams write code the same way.
- Built-in DI makes services easy to test and swap.
- First-class support for validation, config, OpenAPI, GraphQL, WebSockets and microservices.
- Decorators for routing, guards and pipes keep controllers thin.
Downsides: more repeated setup code and a learning curve compared with a 50-line Express app. For tiny scripts, plain Express or Fastify is fine.
What they are checking: Whether you can explain a framework choice with its pros and cons
FresherMost askedAnswerHideWhat is a module in NestJS and what does it contain?
A module is a class decorated with @Module() that groups related controllers and providers together. Every app has at least a root module.
@Module({
imports: [DatabaseModule], // other modules whose exports we need
controllers: [UsersController],
providers: [UsersService],
exports: [UsersService], // what other modules may inject
})
export class UsersModule {}
- Providers are private to a module unless listed in
exports. - A module must import another module to use its exported providers.
- Modules are singletons by default, so a shared module is instantiated once.
What they are checking: Whether you understand encapsulation between modules
FresherMost askedAnswerHideWhat is the role of a controller in NestJS?
A controller handles incoming requests, extracts input, calls a service, and returns the response; it should contain no business logic.
@Controller('users')
export class UsersController {
constructor(private readonly users: UsersService) {}
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return this.users.findOne(id);
}
@Post()
@HttpCode(201)
create(@Body() dto: CreateUserDto) {
return this.users.create(dto);
}
}
Decorators such as @Get, @Post, @Param, @Query, @Body and @Headers map HTTP to method arguments. Return a value or a promise, and Nest serialises it.
What they are checking: Whether you keep controllers thin and know the routing decorators
FresherMost askedAnswerHideWhat are providers in NestJS and what does @Injectable do?
A provider is any class (service, repository, factory, helper) that Nest can inject as a dependency. @Injectable() marks the class so Nest's DI container can manage it and read its constructor metadata.
@Injectable()
export class UsersService {
constructor(private readonly repo: UsersRepository) {}
findOne(id: number) { return this.repo.findById(id); }
}
Register it in the providers array of a module. By default it is a singleton shared across the module graph. Business logic belongs in providers, which makes it reusable and easy to unit test with a mock.
What they are checking: Whether you understand providers as the home of business logic
FresherMost askedAnswerHideHow does dependency injection work in NestJS?
Nest has an IoC container. It reads the types of constructor parameters (from TypeScript metadata). It finds the provider registered under that token, creates it once, and injects it.
@Injectable()
export class OrdersService {
constructor(
private readonly users: UsersService, // class token
@Inject('PAYMENT_CLIENT') private readonly pay: PaymentClient, // string token
) {}
}
Steps: build a dependency graph from modules, resolve providers in order, instantiate singletons, then inject. Interfaces vanish at runtime, so inject them with a string, symbol or class token using @Inject(). Benefits: loose coupling and simple mocking in tests.
What they are checking: Whether you know tokens and how Nest resolves the graph
FresherMost askedAnswerHideWhat is the difference between middleware, guards, interceptors, pipes and exception filters?
Each handles a different concern at a different point of the request lifecycle.
| Building block | Runs | Typical job |
|---|---|---|
| Middleware | First, before routing context | Logging, CORS, body parsing, request id |
| Guard | Before the handler | Authentication, authorisation (returns true or false) |
| Interceptor | Around the handler | Transform response, cache, timing, map errors |
| Pipe | Before the handler, per argument | Validate and transform input |
| Exception filter | On thrown errors | Shape error responses, log |
Key difference: middleware does not know which handler will run. Guards, interceptors and pipes have an ExecutionContext and know which controller and method will run. Pick the narrowest tool: validation in pipes, permissions in guards, and shared before-and-after logic in interceptors.
What they are checking: Whether you pick the right layer for each concern
FresherMost askedFree with sign-inAnswerHideHow do you validate request bodies with DTOs and class-validator?
Define a DTO class with class-validator decorators and enable the global ValidationPipe. It checks incoming data. If the check fails, it returns a 400 with messages.
FresherMost askedFree with sign-inAnswerHideHow do you integrate a database in NestJS using TypeORM?
Install @nestjs/typeorm and typeorm, configure TypeOrmModule.forRootAsync with your config. Define entities. Then register repositories in each feature module with forFeature.
FresherMost askedFree with sign-inAnswerHideHow do you manage configuration and environment variables in NestJS?
Use @nestjs/config: ConfigModule.forRoot loads .env files and gives values through ConfigService. Add validation, so the app stops at once if a setting is missing.
FresherMost askedFree with sign-inAnswerHideHow do you unit test a NestJS service?
Build a testing module with Test.createTestingModule. Provide the service under test plus mocks for its dependencies. Then check its behaviour.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between pipes and exception filters?
Pipes work on input before the handler (they check or change arguments). Exception filters work on errors after something throws, and turn them into responses.
FresherMost askedFree with sign-inAnswerHideWhat are interceptors used for in NestJS? Give an example.
Interceptors wrap the handler using RxJS. So they can run logic before and after it, change the result, add caching, measure time, or change errors.
FresherMost askedScenarioFree with sign-inAnswerHideTwo services are circularly dependent in your NestJS codebase and the app fails to boot. How do you refactor it properly?
Find why each one needs the other. Then break the cycle by moving shared logic or reversing one direction, instead of leaving forwardRef everywhere.
FresherMost askedFree with sign-inAnswerHideWhat does the @Global decorator do and when should you avoid it?
@Global() makes a module's exported providers available everywhere without importing the module in each consumer.
FresherMost askedFree with sign-inAnswerHideHow do you document a NestJS API with Swagger (OpenAPI)?
Install @nestjs/swagger, build a document in main.ts with DocumentBuilder, and expose it with SwaggerModule.setup. Decorators or the CLI plugin describe the DTOs and endpoints.
System Design
FresherMost askedAnswerHideWhat is the difference between horizontal and vertical scaling?
Vertical scaling (scale up) means giving one machine more CPU, RAM or disk. Horizontal scaling (scale out) means adding more machines and spreading the load across them.
| Vertical | Horizontal | |
|---|---|---|
| Effort | Easy, often no code change | Needs stateless design, load balancing |
| Limit | Hardware ceiling, gets very expensive | Nearly unlimited |
| Availability | Single point of failure | Survives node loss |
| Downtime | Often needed for upgrades | Rolling, none |
| Data layer | Simple | Needs replication or sharding |
Practical approach:
- Start vertical for simplicity (one bigger database server goes a long way).
- Make the app servers stateless (keep sessions in Redis or in tokens). Add more servers behind a load balancer.
- Scale the database with read replicas first, then caching, then sharding only when needed.
Mention that horizontal scaling adds complexity: consistency, distributed debugging, and network failures.
What they are checking: Whether you know the pros and cons and a sensible order of scaling
FresherMost askedAnswerHideWhat is a load balancer and which algorithms does it use?
A load balancer distributes incoming requests across multiple servers to improve throughput, availability and fault tolerance. It health-checks backends and stops sending traffic to failed ones.
Common algorithms:
- Round robin: rotate through servers in order.
- Weighted round robin: bigger servers get more requests.
- Least connections: send to the server with the fewest active connections (good for long requests).
- Least response time: pick the fastest responder.
- IP hash / consistent hashing: the same client or key goes to the same server (sticky behaviour, cache locality).
Types:
- Layer 4 (TCP/UDP): fast, routes by IP and port.
- Layer 7 (HTTP): routes by path, host or header, terminates TLS, can do redirects.
Examples: NGINX, HAProxy, AWS ALB/NLB. The load balancer must not be a single point of failure. Run a pair of them, or use a managed service.
What they are checking: Algorithm choice and L4 vs L7
FresherMost askedAnswerHideWhat is caching and what are the common caching strategies?
Caching stores frequently used data in a fast layer (memory) to reduce latency and database load.
Where: browser, CDN, application memory, distributed cache (Redis, Memcached), database buffer.
Strategies:
- Cache-aside (lazy loading): the app checks the cache; on a miss it reads the database and fills the cache. Most common.
- Read-through: the cache itself loads data on a miss.
- Write-through: writes go to the cache and database together; consistent but slower writes.
- Write-back (write-behind): write to cache first, flush to the database later; fast but risks data loss.
- Write-around: write to the database only, cache fills on read.
Eviction: LRU, LFU, TTL expiry.
Challenges: old data, cache stampede (many misses at once, fix with locking or by merging requests), and removing old entries, which is famously hard. Always set a TTL as a safety net.
What they are checking: Strategy names and pros and cons
FresherMost askedAnswerHideWhat is the CAP theorem?
In a distributed data store, during a network partition you can guarantee only two of three properties:
- Consistency: every read sees the latest write.
- Availability: every request gets a (non-error) response.
- Partition tolerance: the system keeps working when messages between nodes are lost.
Network splits (partitions) happen in real networks. So the real choice is between C and A when a split happens:
- CP systems refuse or delay some requests to stay consistent (ZooKeeper, etcd, HBase, MongoDB with majority writes).
- AP systems keep answering but may return stale data and reconcile later (Cassandra, DynamoDB default, Couchbase).
Without a partition, you can have both; the PACELC extension adds that, even without a split, you still trade latency against consistency.
Example: a bank balance prefers consistency. A social feed like count prefers availability and eventual consistency.
What they are checking: The correct view: the choice is C vs A under partition
FresherMost askedAnswerHideWhat is the difference between SQL and NoSQL databases, and how do you choose?
SQL (relational) databases use tables, a fixed schema, joins and ACID transactions. NoSQL includes document (MongoDB), key-value (Redis, DynamoDB), wide-column (Cassandra) and graph (Neo4j) stores. They usually have flexible schemas and are easier to spread over many servers.
Choose SQL when:
- Data is relational and integrity matters (payments, inventory).
- You need complex queries, joins and reporting.
- Strong consistency is required.
Choose NoSQL when:
- You need massive scale or write throughput across many nodes.
- Access is simple by key, or the data is nested and schema changes often.
- Eventual consistency is acceptable.
Often the answer is both (polyglot persistence): PostgreSQL for orders, Redis for sessions and cache, Elasticsearch for search, object storage for files. Do not pick NoSQL just because it sounds scalable; a single well-indexed PostgreSQL instance handles a large workload.
What they are checking: Reasoning from requirements
FresherMost askedAnswerHideWhat is a message queue and why would you use one?
A message queue is a buffer between a producer and a consumer. The producer publishes a message and moves on; consumers process it asynchronously. Examples: RabbitMQ, Amazon SQS, Kafka (log-based streaming), Redis Streams.
Benefits:
- Decoupling: services do not need to be up at the same time.
- Load leveling: absorb traffic spikes and process at a steady pace.
- Reliability: messages persist and are retried after failures.
- Scalability: add more consumers to drain faster.
- Offload slow work (emails, image processing) from the request path.
Things to design for:
- Delivery guarantees: at-most-once, at-least-once (most common), exactly-once (hard). Make consumers idempotent.
- Ordering, which is only guaranteed per partition or queue.
- Dead-letter queue for poison messages.
- Backpressure and monitoring of queue depth.
Queue (one consumer gets each message) differs from pub/sub (every subscriber gets a copy).
What they are checking: Guarantees and idempotency
FresherMost askedAnswerHideWhat is the difference between a monolith and microservices?
A monolith is one deployable application containing all features. Microservices split the system into small, independently deployable services, each owning its data and a business capability.
| Monolith | Microservices | |
|---|---|---|
| Deployment | Single unit | Per service |
| Scaling | Scale everything together | Scale only hot services |
| Complexity | Simple to build and debug | Distributed system complexity |
| Tech choice | One stack | Per service |
| Failures | Can take down all | Isolated if designed well |
| Data | One shared database | Database per service |
Microservices cost you network calls, eventual consistency, distributed tracing, versioning and a platform team. They pay off with large teams and independent scaling needs.
Good advice: start with a well-structured (modular) monolith, and extract services along clear boundaries when a real need appears. Many "microservice" migrations create a distributed monolith that is worse than before.
What they are checking: Judgement, not hype
FresherMost askedFree with sign-inAnswerHideWhat is the difference between replication and sharding?
Replication copies the same data to multiple nodes. Sharding splits different data across nodes.
FresherMost askedFree with sign-inAnswerHideWhat is a CDN and how does it improve performance?
A Content Delivery Network (CDN) is a group of edge servers in many places. They keep copies of content close to users.
FresherMost askedFree with sign-inAnswerHideWhat is eventual consistency? Give an example.
Eventual consistency means that, if no new updates are made, all copies end up with the same value after some time. Reads in the meantime may return stale data.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between latency and throughput?
Latency is the time one request takes from start to finish (milliseconds). Throughput is how many requests the system handles per unit of time (requests per second).
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a stateless and a stateful service, and why does it matter for scaling?
A stateless service keeps no per-client data between requests, so any instance can serve any request. A stateful service stores data in its own memory or disk that later requests depend on.
FresherMost askedFree with sign-inAnswerHideWhat is a reverse proxy and how is it different from a forward proxy?
A forward proxy sits in front of clients. It sends requests to the internet for them (hides who the client is, filters content, caches). A reverse proxy sits in front of servers and receives requests on their behalf (hides backend servers).
FresherMost askedFree with sign-inAnswerHideWhat is the difference between synchronous and asynchronous communication between services?
Synchronous communication (REST, gRPC) means the caller waits for the response. It is simple and immediate, but it couples the services in time: if the called service is slow or down, the caller suffers. Long chains of calls add up delay and failures.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a load balancer, a reverse proxy and an API gateway?
They overlap, and one product (NGINX, Envoy) can play all three roles, but the focus differs.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between SQL ACID and NoSQL BASE?
ACID (Atomicity, Consistency, Isolation, Durability) gives strict transactional guarantees, typical of relational databases.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a cache and a database, and when can a cache cause problems?
A cache holds a temporary, disposable copy of data in fast memory to speed up reads. A database is the durable source of truth.
FresherMost askedFree with sign-inAnswerHideWhat is the difference between a process and a thread, and how does it affect server design?
A process has its own memory space; a thread is a lightweight unit of execution inside a process sharing its memory.
FresherMost askedFree with sign-inAnswerHideWhat are SLA, SLO and SLI?
- SLI (Service Level Indicator): a measured number for service quality, for example the percentage of requests that succeed or the p99 latency.
- SLO (Service Level Objective): the internal target for an SLI, for example 99.9 percent of requests succeed over 30 days.
- SLA (Service Level Agreement): the contract with customers that states consequences, such as credits, if the target is missed. It is usually looser than the SLO.