Interview questions and answers

80 questions in 8 topics. Read the short answer first: it's what you'd say out loud. Open a question for the full explanation.

Java

What is the difference between JDK, JRE and JVM?Easy

The JVM runs bytecode, the JRE is the JVM plus the standard libraries, and the JDK is the JRE plus development tools like the javac compiler.

  • JVM (Java Virtual Machine) loads .class bytecode and runs it, using a JIT compiler to turn hot code into fast machine code. It's why Java is "write once, run anywhere".
  • JRE (Java Runtime Environment) = JVM + core libraries (java.lang, java.util…). Enough to run programs.
  • JDK (Java Development Kit) = JRE + tools: javac, jar, jdb, javadoc. Needed to build programs.

Since Java 11, Oracle ships only the JDK, so developers just install the JDK.

What is the difference between == and equals() in Java?Easy

== compares references (whether two variables point to the same object), while equals() compares the content as defined by the class.

  • For primitives (int, char…), == compares values.
  • For objects, == checks whether both references point to the same object in memory.
  • equals() compares logical content. String, Integer and records override it; plain Object.equals() behaves like ==.

Common trap: two strings with the same text can be different objects, so always compare strings with .equals(). String literals may share one pooled object, which makes == sometimes work and hides the bug.

Why are Strings immutable in Java?Medium

For security, to allow the string pool to share literals safely, for thread safety, and so the hash code can be cached for fast HashMap lookups.

  1. Security: file paths, URLs, class names and credentials can't be changed after they're validated.
  2. String pool: identical literals can share one object, saving memory. This is only safe if nobody can change it.
  3. Thread safety: immutable objects can be shared between threads without synchronization.
  4. Hash caching: hashCode() is computed once and cached, so strings make fast HashMap keys.

To build text efficiently, use StringBuilder; repeated + in a loop creates many temporary strings.

How does HashMap work internally?Hard

The key's hashCode() picks a bucket in an array; collisions are stored in a list (or a tree once a bucket gets large), equals() finds the exact key, and the array doubles when it's 75% full.

  1. Hashing: hash(key) is turned into an index of an internal array of buckets.
  2. Collisions: different keys can land in the same bucket. They're stored in a linked list; since Java 8, a bucket with 8+ entries becomes a red-black tree (O(log n) instead of O(n)).
  3. Lookup: get() goes to the bucket, then uses equals() to find the exact key.
  4. Resizing: when size > capacity × load factor (0.75), the array doubles and entries are redistributed.

Average get/put is O(1). HashMap allows one null key and is not thread-safe; use ConcurrentHashMap for shared access.

What is the difference between an abstract class and an interface?Medium

An abstract class can hold state and constructors and a class can extend only one; an interface defines a contract, and a class can implement many.

Abstract classInterface
Fields (state), constructorsOnly public static final constants
Any access modifiersMethods public by default
A class extends oneA class implements many
Shares code in a family (IS-A)Describes a capability (Comparable, Runnable)

Since Java 8, interfaces can have default and static methods, and since Java 9, private helpers. So the main differences today are state and single vs multiple inheritance.

Rule of thumb: start with an interface; use an abstract class when subclasses share real state or code.

What is the difference between checked and unchecked exceptions?Easy

Checked exceptions must be caught or declared with throws and represent recoverable outside problems; unchecked exceptions extend RuntimeException and usually indicate bugs.

  • Checked (IOException, SQLException): the compiler forces you to handle them with try/catch or declare them with throws. They describe problems outside your control: missing files, network failures.
  • Unchecked (NullPointerException, IllegalArgumentException, IndexOutOfBoundsException): subclasses of RuntimeException. Not enforced by the compiler; they usually mean a programming mistake that should be fixed.
  • Errors (OutOfMemoryError) are serious JVM problems you normally don't catch.

Best practice: catch specific exceptions, never swallow them silently, and use try-with-resources for anything that must be closed.

What is the difference between Comparable and Comparator?Easy

Comparable defines a class's natural order inside the class with compareTo(); Comparator defines any custom order outside the class, so one class can be sorted many ways.

  • Comparable (java.lang): the class implements compareTo(T other). One "natural" order, e.g. String alphabetically, Integer numerically.
  • Comparator (java.util): a separate object with compare(a, b). Use it for extra orders or for classes you can't change.
  • Modern style: Comparator.comparing(Person::age).thenComparing(Person::name).reversed().
  • compareTo returns negative, zero or positive. Avoid a - b for ints, which can overflow; use Integer.compare(a, b).
What is the difference between synchronized and volatile?Hard

synchronized gives mutual exclusion and visibility, so only one thread runs the block at a time; volatile only guarantees that every thread sees the latest value of a variable, without making compound operations like count++ atomic.

synchronizedvolatile
Mutual exclusion (one thread at a time)✅❌
Visibility of latest value✅✅
Makes count++ safe✅❌
Can block threadsyesnever
  • Use volatile for simple flags read by many threads (volatile boolean running).
  • Use synchronized, ReentrantLock or AtomicInteger for read-modify-write operations.
  • count++ is three steps (read, add, write), so two threads can lose updates without a lock.
What are streams and lambdas in Java?Medium

A lambda is a short anonymous function for a functional interface; a stream is a pipeline that filters, transforms and collects data declaratively and lazily, without changing the source collection.

  • Lambda: (a, b) -> a + b, usable wherever a functional interface (one abstract method) is expected: Runnable, Comparator, Predicate.
  • Method reference: String::toUpperCase.
  • Stream pipeline: source → intermediate operations (filter, map, sorted) → terminal operation (collect, toList, count).
  • Intermediate operations are lazy: nothing runs until the terminal operation.
  • A stream can be consumed only once.
  • parallelStream() can use several cores, but only helps with large, CPU-heavy data.
How does garbage collection work in Java?Hard

The JVM automatically frees objects that are no longer reachable from GC roots; most collectors are generational, quickly cleaning the young generation where most objects die, and less often the old generation.

  • An object is garbage when no chain of references leads to it from a GC root (local variables, static fields, active threads).
  • Generational hypothesis: most objects die young. The heap has a young generation (Eden + survivor spaces), collected often and quickly, and an old generation for long-lived objects, collected less often.
  • Phases: mark reachable objects, sweep or compact the rest.
  • Modern collectors: G1 (default), ZGC and Shenandoah for very low pauses.
  • You can't force GC (System.gc() is only a hint). Memory leaks still happen when references are kept, e.g. in static collections or caches.

C++

What is the difference between a pointer and a reference?Easy

A pointer stores an address, can be null and can be re-pointed; a reference is an alias that must refer to a valid object and can't be re-bound.

PointerReference
Can be nullptrMust refer to a real object
Can point somewhere else laterBound once, forever
Use with *p and p->memberUse like the variable itself
Can do pointer arithmeticNo arithmetic

When to use which: references for function parameters (const std::string&), pointers when "no object" is a valid value or for low-level work. For owning memory, use smart pointers, not raw pointers.

What is the difference between the stack and the heap?Easy

The stack holds local variables and is freed automatically and quickly; the heap holds memory requested at runtime, is larger, and must be released, ideally through RAII.

  • Stack: function locals and parameters. Allocation is just moving a pointer, so it's very fast. Freed automatically when the scope ends. Limited size (often 1–8 MB): deep recursion or huge local arrays cause a stack overflow.
  • Heap (free store): memory from new / std::make_unique. Large and flexible, lives until released. Slower to allocate, and can fragment.

Modern C++: avoid raw new/delete. Use std::vector, std::string and std::make_unique, which put data on the heap but free it automatically.

How do virtual functions work in C++?Hard

Each class with virtual functions has a vtable of function pointers, and each object has a hidden pointer to it, so calls through a base pointer or reference are resolved at runtime.

  • Marking a function virtual enables runtime polymorphism: the object's real type decides which function runs.
  • The compiler typically builds a vtable (virtual table) per class, and adds a hidden vptr to every object pointing to its class's vtable.
  • A call like base->draw() looks up draw in that table at runtime.
  • Use override in derived classes so the compiler checks the signature.

Cost: one extra pointer per object and an indirect call, which also prevents some inlining. Without virtual, the call is decided at compile time from the pointer's type.

Why should a base class have a virtual destructor?Medium

If you delete a derived object through a base pointer and the destructor isn't virtual, only the base destructor runs, which is undefined behaviour and usually leaks the derived part.

C++
Base* p = new Derived();
delete p;   // non-virtual ~Base(): ~Derived() never runs!
  • The derived class's members and resources aren't cleaned up, and the behaviour is officially undefined.
  • Making the destructor virtual ensures ~Derived() runs first, then ~Base().

Rule: any class meant to be used polymorphically (has virtual functions, is deleted through a base pointer) needs virtual ~Base() = default;. Classes that aren't meant to be inherited can be marked final instead.

What is the difference between unique_ptr, shared_ptr and weak_ptr?Medium

unique_ptr has one owner and can only be moved; shared_ptr allows shared ownership with a reference count; weak_ptr observes a shared_ptr without owning it, breaking cycles.

Smart pointerOwnershipNotes
std::unique_ptrexactly one ownermove-only, no overhead; the default choice
std::shared_ptrsharedatomic reference count; freed when the last owner goes
std::weak_ptrnonelock() to get a shared_ptr if the object still exists

Reference cycles: if A and B hold shared_ptrs to each other, neither count reaches zero, so both leak. Make one direction a weak_ptr.

Create them with std::make_unique / std::make_shared (exception-safe and, for shared, a single allocation).

What are move semantics and what does std::move do?Hard

Move semantics let an object take over the resources of a temporary instead of copying them; std::move doesn't move anything itself, it casts to an rvalue so the move constructor can be chosen.

  • Copying a std::vector of a million items copies every item. Moving just transfers the internal pointer, which is O(1).
  • A move constructor has the signature T(T&& other) noexcept. T&& is an rvalue reference, which binds to temporaries.
  • std::move(x) is a cast. After moving, x is valid but in an unspecified state; don't rely on its value.
  • Mark move operations noexcept, or std::vector will copy instead of move when it grows.
  • Don't write return std::move(local);: plain return local; already benefits from copy elision.
What does const correctness mean in C++?Easy

Using const wherever something should not change: const variables, const references for read-only parameters, and const member functions, so the compiler catches accidental modifications.

  • const int max = 10;: a value that never changes.
  • void print(const std::string& s): no copy, and the function can't modify s.
  • int size() const;: a const member function that promises not to modify the object. Only const member functions can be called on const objects.
  • const int* p (pointer to const) vs int* const p (const pointer). Read right to left.

Benefits: clearer intent, fewer bugs, and the compiler enforces the rules.

Explain the rule of three, five and zero.Medium

If a class manages a resource and needs a custom destructor, it usually needs custom copy operations (three) and move operations (five); the rule of zero says to avoid all of them by using members that manage themselves.

  • Rule of three: destructor, copy constructor, copy assignment. If you write one, you probably need all three, or copies will share (and double-free) the same resource.
  • Rule of five: add the move constructor and move assignment (C++11) for efficient transfers.
  • Rule of zero (preferred): use std::string, std::vector and std::unique_ptr as members, and write none of these functions; the compiler-generated ones are correct.
  • Use = default and = delete to be explicit, e.g. make a class non-copyable.
What is the difference between std::map and std::unordered_map?Easy

std::map is a balanced binary tree with sorted keys and O(log n) operations; std::unordered_map is a hash table with no order and O(1) average operations.

std::mapstd::unordered_map
Structurered-black treehash table
Key ordersortednone
Lookup / insertO(log n)O(1) average, O(n) worst
Key needsoperator<std::hash and ==
Range queries (lower_bound)✅❌

Use unordered_map for fast lookups and map when you need sorted iteration or range queries.

What is undefined behaviour in C++?Medium

Code whose behaviour the C++ standard does not define, such as out-of-bounds access or using a dangling pointer, so the program may crash, give wrong results, or appear to work.

Common causes:

  • Reading or writing outside an array or vector.
  • Using a dangling pointer or reference (freed memory, a destroyed local).
  • Signed integer overflow.
  • Uninitialised variables.
  • Data races between threads.
  • Deleting memory twice, or with the wrong form (delete vs delete[]).

The compiler may optimise assuming UB never happens, which makes bugs confusing. Tools that help: -Wall -Wextra, AddressSanitizer and UBSan (-fsanitize=address,undefined), and vector::at() for checked access.

Python

What is the difference between a list and a tuple?Easy

Lists are mutable and tuples are immutable; tuples are slightly faster, can be dictionary keys, and signal fixed data.

ListTuple
[1, 2, 3](1, 2, 3)
Mutable: append, remove, sortImmutable after creation
Not hashableHashable (if items are), so usable as dict keys
For collections that changeFor fixed records: coordinates, RGB, DB rows

Tuples use a little less memory and are a bit faster to create. A one-item tuple needs a comma: (5,).

What is the mutable default argument problem?Medium

Default values are created once when the function is defined, so a mutable default like a list is shared and keeps growing across calls; use None and create the list inside.

Python
def add(item, items=[]):   # ❌ one list shared by every call
    items.append(item)
    return items

add(1) → [1], then add(2) → [1, 2]. The default object was built once, at definition time.

Fix:

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

The same applies to dicts, sets and other mutable defaults.

What is the GIL and how does it affect multithreading?Hard

The Global Interpreter Lock lets only one thread run Python bytecode at a time in CPython, so threads help with I/O-bound work but not CPU-bound work, which needs multiprocessing.

  • The GIL is a lock in CPython that protects the interpreter's internals, especially reference counting.
  • I/O-bound tasks (network, disk) release the GIL while waiting, so threading and asyncio speed them up well.
  • CPU-bound tasks (maths, image processing) don't run in parallel across threads. Use multiprocessing / ProcessPoolExecutor, or libraries like NumPy that release the GIL in C code.
  • Python 3.13 introduced an experimental free-threaded build without the GIL, but the default build still has it.
What are generators and why use yield?Medium

A generator is a function that uses yield to produce values lazily, one at a time, keeping its state between calls, which saves memory for large or infinite sequences.

  • Calling a generator function returns a generator object; nothing runs until you iterate.
  • Each yield hands back a value and pauses the function; next() resumes it.
  • Values are produced on demand, so a generator can process a huge file line by line or an infinite stream using constant memory.
  • A generator can be iterated only once.
  • Generator expressions use parentheses: sum(x * x for x in range(10**6)).
What is a decorator in Python?Medium

A decorator is a function that takes another function and returns a wrapped version, adding behaviour like logging, timing or caching without changing the original code.

  • @timer above def f is shorthand for f = timer(f).
  • The wrapper usually accepts *args, **kwargs and returns the original result.
  • Use functools.wraps to keep the original name and docstring.
  • Built-in examples: @property, @staticmethod, @classmethod, @functools.lru_cache, @dataclass.
  • Decorators can take arguments by adding one more level of function (@retry(times=3)).
What is the difference between a shallow copy and a deep copy?Medium

A shallow copy creates a new outer container but shares the inner objects; a deep copy recursively copies everything, so nested changes don't affect the original.

  • Assignment (b = a) copies nothing: both names point to the same object.
  • Shallow copy (a.copy(), list(a), copy.copy(a), a[:]): new outer object, same inner objects.
  • Deep copy (copy.deepcopy(a)): copies nested objects too.

This matters for nested structures such as lists of lists or dicts of lists.

What are *args and **kwargs?Easy

*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dict, letting a function accept a flexible number of arguments.

  • *args gathers extra positional arguments into a tuple.
  • **kwargs gathers extra keyword arguments into a dict.
  • Order in a definition: normal parameters, *args, keyword-only parameters, **kwargs.
  • The same symbols unpack when calling: f(*my_list, **my_dict).
  • Common in decorators and wrappers that pass arguments through.
What is the difference between is and ==?Easy

== checks whether two values are equal, while is checks whether two names point to the exact same object in memory.

  • == calls __eq__: same value.
  • is compares identity: same object (id(a) == id(b)).
  • Use is only for singletons: if x is None:, is True, is False.
  • Small integers and some strings are cached by CPython, so is can seem to work for them. Don't rely on it.
What is the difference between a list comprehension and a generator expression?Medium

A list comprehension builds the whole list in memory immediately; a generator expression uses parentheses and produces items lazily one at a time, saving memory.

[x*x for x in data](x*x for x in data)
Resultlistgenerator
Memoryall items at onceone item at a time
Reusableyesonly once
Indexing, len()✅❌

Use a generator for big data or when you only loop once, e.g. sum(x*x for x in range(10**7)). Use a list when you need indexing, length or several passes.

How does Python manage memory?Hard

CPython uses reference counting to free objects as soon as nothing refers to them, plus a cyclic garbage collector for reference cycles, with memory managed in private heaps and small-object pools.

  • Reference counting: every object counts its references, and when the count hits 0 it's freed immediately (sys.getrefcount(obj)).
  • Cycle collector: objects referencing each other never reach 0, so a generational garbage collector (gc module) finds and frees these cycles periodically.
  • pymalloc: an allocator optimised for many small objects.
  • del x removes a name, not necessarily the object.
  • Leaks still happen through long-lived references: global lists, caches, closures. weakref helps for caches.

DSA

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

Arrays store elements contiguously for O(1) index access but costly middle inserts; linked lists store nodes with pointers for cheap inserts at a known node but O(n) access.

OperationArray / dynamic arrayLinked list
Access by indexO(1)O(n)
Insert/delete at endO(1) amortisedO(1) with a tail pointer
Insert/delete in middleO(n) (shift items)O(1) once you have the node
Memorycompact, cache-friendlyextra pointer per node

In practice arrays (ArrayList, std::vector, Python list) are usually faster because of CPU caching. Choose a linked list when you constantly insert and remove in the middle and already hold references to the nodes.

What is Big O notation?Easy

Big O describes how an algorithm's running time or memory grows as the input size grows, focusing on the worst case and ignoring constants.

Big OExample1,000,000 items
O(1)hash lookup1 step
O(log n)binary search~20
O(n)single loop10⁶
O(n log n)good sorting~2 × 10⁷
O(n²)nested loops10¹²

Rules: drop constants (3n → O(n)), keep the dominant term (n² + n → O(n²)), nested loops multiply, sequential steps add. Also mention space complexity, the extra memory used.

What is the difference between a stack and a queue?Easy

A stack is last-in-first-out (push and pop from the top); a queue is first-in-first-out (add at the back, remove from the front).

  • Stack (LIFO): like a pile of plates. Used for undo, the browser back button, function calls, bracket matching and DFS.
  • Queue (FIFO): like a line at a shop. Used for task scheduling, printers, message queues and BFS.
  • Both give O(1) push/pop when implemented properly.
  • Deque: double-ended, so it can act as both.
  • Priority queue: removes the highest-priority item first (usually a heap, O(log n)).
How does a hash table handle collisions?Medium

Two main ways: separate chaining, where each bucket holds a list of entries, and open addressing, where a colliding key probes for the next free slot; both rely on a good hash function and resizing.

  • Separate chaining: each bucket holds a list (or tree) of entries with the same index. Used by Java's HashMap.
  • Open addressing: on collision, probe other slots (linear, quadratic or double hashing). Used by Python's dict.
  • Load factor = items ÷ buckets. When it gets too high, the table resizes and rehashes to keep operations O(1) on average.
  • With a bad hash function, everything collides and operations degrade to O(n).
What is the difference between BFS and DFS?Medium

BFS explores level by level using a queue and finds the shortest path in unweighted graphs; DFS goes as deep as possible first using a stack or recursion and suits cycle detection, topological sort and exhaustive search.

BFSDFS
Data structurequeuestack / recursion
Orderlevel by leveldeep first, then backtrack
Shortest path (unweighted)✅ yes❌ not guaranteed
Memorycan be large for wide graphsproportional to depth
Typical usesshortest path, nearest neighbourscycles, topological sort, mazes, backtracking

Both run in O(V + E) time. Always keep a visited set to avoid infinite loops in graphs with cycles.

What is dynamic programming?Hard

Dynamic programming solves problems with overlapping subproblems and optimal substructure by solving each subproblem once and storing the result, either top-down with memoisation or bottom-up with a table.

When it applies

  1. Overlapping subproblems: the same smaller problem is solved again and again (naive Fibonacci).
  2. Optimal substructure: the best answer is built from best answers to subproblems.

Two styles

  • Top-down (memoisation): recursion plus a cache (@lru_cache).
  • Bottom-up (tabulation): fill a table from the smallest cases upward, usually iteratively.

Classic problems: Fibonacci, climbing stairs, coin change, longest common subsequence, 0/1 knapsack, edit distance.

How to explain your solution: define the state (what dp[i] means), the transition (how dp[i] uses smaller states), the base cases, and the final answer.

How does binary search work?Easy

On a sorted array, compare the target with the middle element and discard the half that can't contain it, repeating until found, which takes O(log n) time.

  1. Keep two indexes, lo and hi.
  2. Check mid = (lo + hi) // 2.
  3. Equal → found. Target bigger → search the right half (lo = mid + 1). Smaller → the left half (hi = mid - 1).
  4. Stop when lo > hi (not found).
  • Requires sorted data.
  • O(log n): a million items need about 20 steps.
  • Watch the off-by-one errors and the loop condition (lo <= hi).
  • Variants find the first or last occurrence, or the insertion point (Python bisect, C++ lower_bound).
Compare quick sort and merge sort.Medium

Both average O(n log n); merge sort is stable with a guaranteed O(n log n) but needs O(n) extra memory, while quick sort sorts in place and is usually faster in practice but has an O(n²) worst case.

Quick sortMerge sort
AverageO(n log n)O(n log n)
WorstO(n²) (bad pivots)O(n log n)
Extra memoryO(log n) stackO(n)
Stablenoyes
Strategypartition around a pivotsplit, sort halves, merge
  • Random or median-of-three pivots make quick sort's worst case unlikely.
  • Merge sort suits linked lists and external sorting (data larger than RAM).
  • Real libraries mix them: Python and Java use Timsort (merge + insertion); C++ std::sort uses introsort (quick + heap + insertion).
What is a heap and where is it used?Medium

A heap is a complete binary tree, usually stored in an array, where every parent is smaller (min-heap) or larger (max-heap) than its children, giving O(1) access to the min or max and O(log n) insert and remove.

  • Stored in an array: the children of index i are at 2i + 1 and 2i + 2.
  • peek O(1), push/pop O(log n), build from n items O(n).
  • Uses: priority queues, task schedulers, Dijkstra's shortest path, heap sort, "top K" problems, merging K sorted lists, the running median.
  • Python: heapq (min-heap). Java: PriorityQueue. C++: std::priority_queue (max-heap by default).

Top K trick: keep a min-heap of size K; if a new item is bigger than the top, pop and push. O(n log K).

What are the two-pointer and sliding-window techniques?Medium

Two pointers move through data from both ends or at different speeds to avoid nested loops; a sliding window keeps a moving range over an array or string and updates it incrementally, turning many O(n²) problems into O(n).

Two pointers

  • From both ends of a sorted array: pair sum, reversing, palindromes.
  • Fast and slow pointers: cycle detection, the middle of a linked list.

Sliding window

  • Fixed size: max sum of k consecutive items. Add the new item, remove the old one.
  • Variable size: longest substring without repeating characters. Expand the right edge, shrink the left while the rule is broken.

Both usually give O(n) time and O(1) or O(k) extra space.

DBMS & SQL

What is the difference between a primary key and a foreign key?Easy

A primary key uniquely identifies each row in its own table and can't be null; a foreign key is a column that references the primary key of another table to link related rows.

  • Primary key: unique, not null, one per table (it can span several columns). Example: users.id.
  • Foreign key: points to another table's primary key and enforces referential integrity, so you can't add an order for a user who doesn't exist. Example: orders.user_id → users.id.
  • Foreign keys can be null (if optional) and can repeat (one user, many orders).
  • ON DELETE CASCADE deletes child rows automatically when the parent is deleted.

Other keys you may be asked about: candidate key (any column that could be the primary key), unique key (unique but may allow null), composite key (several columns together).

What is normalization? Explain 1NF, 2NF and 3NF.Medium

Normalization organises tables to remove duplicate data and update anomalies: 1NF has atomic values, 2NF removes partial dependencies on a composite key, and 3NF removes transitive dependencies between non-key columns.

  • 1NF: every cell holds a single (atomic) value, with no repeating groups like "math, physics" in one column.
  • 2NF: 1NF, plus every non-key column depends on the whole primary key, not just part of a composite key.
  • 3NF: 2NF, plus non-key columns don't depend on other non-key columns (no transitive dependencies). Example: zip → city should live in its own table.

Why: less duplication, and no update/insert/delete anomalies (changing a city in one row but not another).

Trade-off: more joins. Read-heavy systems sometimes denormalise deliberately for speed.

What are the ACID properties?Medium

Atomicity (all or nothing), Consistency (rules always hold), Isolation (concurrent transactions don't interfere), and Durability (committed data survives crashes).

  • Atomicity: a transaction fully happens or not at all. A bank transfer can't withdraw without depositing.
  • Consistency: every transaction moves the database from one valid state to another; constraints and rules always hold.
  • Isolation: concurrent transactions behave as if they ran one by one. Levels: read uncommitted, read committed, repeatable read, serializable.
  • Durability: once committed, data survives power loss, using write-ahead logs.

In SQL: BEGIN; … COMMIT; or ROLLBACK; on error.

What is the difference between INNER JOIN and LEFT JOIN?Easy

INNER JOIN returns only rows that match in both tables; LEFT JOIN returns every row from the left table, with NULLs where the right table has no match.

  • INNER JOIN: only matching pairs. Users without orders disappear.
  • LEFT (OUTER) JOIN: all rows from the left table; unmatched right-side columns are NULL. Great for "find users who have no orders" (WHERE o.id IS NULL).
  • RIGHT JOIN: the mirror image (rarely used; swap the tables instead).
  • FULL OUTER JOIN: all rows from both sides.
  • CROSS JOIN: every combination (cartesian product).
What is an index and what are its trade-offs?Medium

An index is a separate data structure, usually a B-tree, that lets the database find rows without scanning the whole table, speeding up reads at the cost of extra storage and slower writes.

  • Without an index, WHERE email = ? scans every row: O(n). A B-tree index makes it O(log n).
  • Indexes help WHERE, JOIN, ORDER BY and GROUP BY on the indexed columns.
  • Costs: extra disk space, and every INSERT/UPDATE/DELETE must also update the indexes.
  • Composite indexes follow the leftmost-prefix rule: an index on (last_name, first_name) helps queries on last_name alone, but not first_name alone.
  • Low-selectivity columns (like a boolean) rarely benefit.
  • Use EXPLAIN / EXPLAIN ANALYZE to check whether a query uses an index.
What is the difference between WHERE and HAVING?Easy

WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY, so it can use aggregates like COUNT or SUM.

  • Logical order of a query: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY → LIMIT.
  • WHERE can't use aggregate functions, because groups don't exist yet.
  • HAVING runs on the grouped results.
  • Filter as early as possible with WHERE; it's cheaper than filtering groups later.
What is the difference between DELETE, TRUNCATE and DROP?Easy

DELETE removes chosen rows and can be filtered and rolled back; TRUNCATE quickly removes all rows but keeps the table; DROP removes the whole table, structure and all.

DELETETRUNCATEDROP
Removesrows (with WHERE)all rowsthe whole table
Keeps the table structure✅✅❌
WHERE filter✅❌❌
Speed on big tablesslow (row by row)fastfast
Fires row triggers✅❌❌

Whether TRUNCATE and DROP can be rolled back depends on the database. PostgreSQL allows it inside a transaction; MySQL commits them immediately.

What is the difference between SQL and NoSQL databases?Medium

SQL databases store structured data in tables with a fixed schema, joins and strong ACID transactions; NoSQL databases (document, key-value, column, graph) use flexible schemas and scale horizontally, often trading some consistency for speed and scale.

SQL (PostgreSQL, MySQL)NoSQL (MongoDB, Redis, Cassandra)
Data modeltables, rowsdocuments, key-value, wide-column, graph
Schemafixed, enforcedflexible
Relationshipsjoins, foreign keysusually embedded or denormalised
Scalingmostly vertical (bigger server)horizontal (more servers)
Consistencystrong ACIDoften eventual (BASE), varies

Choose SQL for complex relationships and transactions, like banking and orders. Choose NoSQL for huge scale, flexible data, caching (Redis) or real-time feeds. Many apps use both.

What are transaction isolation levels?Hard

They control how much concurrent transactions can see of each other's changes: read uncommitted, read committed, repeatable read and serializable, each preventing more anomalies at the cost of concurrency.

LevelDirty readNon-repeatable readPhantom read
Read uncommittedpossiblepossiblepossible
Read committed✅ preventedpossiblepossible
Repeatable read✅✅ preventedpossible*
Serializable✅✅✅ prevented
  • Dirty read: reading another transaction's uncommitted change.
  • Non-repeatable read: the same row returns different values within one transaction.
  • Phantom read: re-running a query returns new rows.

*PostgreSQL's repeatable read also prevents phantoms. Its default is read committed; MySQL InnoDB's default is repeatable read.

How do you find the second highest salary?Medium

Skip the top distinct salary with ORDER BY ... DESC LIMIT 1 OFFSET 1, or use a window function like DENSE_RANK(), which also handles ties and the Nth-highest case.

Three common answers:

  1. Subquery: the max salary that is less than the overall max.
  2. LIMIT/OFFSET on distinct salaries.
  3. Window function DENSE_RANK(): the most flexible; it handles ties and works for any N.

Mention edge cases: fewer than 2 distinct salaries (return NULL), and ties (use DISTINCT or DENSE_RANK).

Operating Systems

What is the difference between a process and a thread?Easy

A process is a running program with its own memory space; threads are lighter units of execution inside a process that share its memory, so they communicate easily but need synchronization.

ProcessThread
Own address space (memory)Shares the process's memory
Heavy to create and switchLight to create and switch
Isolated: one crash doesn't kill othersA crashing thread can bring down the process
Communicates via IPC (pipes, sockets)Communicates through shared variables

Each thread still has its own stack, registers and program counter. Shared memory makes threads fast but needs locks to avoid race conditions.

What is a deadlock and what conditions cause it?Medium

A deadlock is when processes wait forever for resources held by each other; it needs four conditions at once: mutual exclusion, hold and wait, no preemption, and circular wait.

The four Coffman conditions (all must hold):

  1. Mutual exclusion: a resource can be held by only one process.
  2. Hold and wait: a process holds one resource while waiting for another.
  3. No preemption: resources can't be taken away forcibly.
  4. Circular wait: P1 waits for P2, which waits for P1.

Handling deadlocks

  • Prevention: break one condition, e.g. always acquire locks in a fixed global order.
  • Avoidance: grant requests only if the system stays safe (Banker's algorithm).
  • Detection & recovery: detect cycles, then kill or roll back a process.
  • Ignore it (the "ostrich algorithm"), which many general-purpose OSes do for user programs.
What are paging and virtual memory?Hard

Virtual memory gives each process its own large address space, mapped to physical memory in fixed-size pages through page tables; pages not in RAM can live on disk and are loaded on a page fault.

  • Memory is split into fixed-size pages (virtual) and frames (physical), often 4 KB.
  • A page table maps virtual pages to physical frames; the MMU translates addresses, and the TLB caches recent translations for speed.
  • If a page isn't in RAM, a page fault occurs and the OS loads it from disk (swap).
  • Benefits: process isolation, programs larger than RAM, no external fragmentation, shared libraries mapped once.
  • Thrashing: too many page faults because RAM is too small for the working set, so the system spends its time swapping.
  • Page replacement algorithms: FIFO, LRU, Optimal (theoretical), Clock.
What is the difference between a mutex and a semaphore?Medium

A mutex is a lock with ownership that lets exactly one thread into a critical section; a semaphore is a counter that allows up to N threads and is often used for signalling.

  • Mutex: binary lock with ownership. Only the thread that locked it should unlock it. Used to protect a critical section.
  • Counting semaphore: an integer counter. wait() (P) decrements and blocks at zero; signal() (V) increments. It limits access to N identical resources, like a pool of 5 database connections.
  • Binary semaphore: count 0 or 1. Similar to a mutex but without ownership, so it's useful for signalling between threads (producer → consumer).

Classic problems: producer–consumer, readers–writers, dining philosophers.

Explain common CPU scheduling algorithms.Medium

FCFS runs jobs in arrival order, SJF runs the shortest job first, Round Robin gives each process a fixed time slice, and Priority scheduling runs the most important first; each trades off waiting time, fairness and responsiveness.

AlgorithmIdeaPros / cons
FCFSfirst come, first servedsimple; one long job delays all (convoy effect)
SJF / SRTFshortest job (or remaining time) firstlowest average waiting time; needs burst estimates; long jobs can starve
Round Robineach process gets a time quantum in turnfair and responsive; too small a quantum means many context switches
Priorityhighest priority firstflexible; low priority can starve, fixed by aging
Multilevel feedback queueseveral queues, processes move between themused by real OSes; complex to tune

Key metrics: turnaround time, waiting time, response time, throughput.

What is a context switch?Medium

A context switch is when the CPU saves the state of the running process or thread and loads another's, which allows multitasking but costs time because no useful work happens during the switch.

  • The state saved in the PCB (process control block): registers, program counter, stack pointer and, for processes, memory-mapping information.
  • Triggers: time slice expiry, I/O waits, interrupts, higher-priority tasks, system calls.
  • Cost: pure overhead, plus cache and TLB misses afterwards. Process switches are more expensive than thread switches because the address space changes.
  • Too many switches (for example, a tiny Round Robin quantum) reduce throughput.
What is the difference between kernel mode and user mode?Medium

User mode runs applications with restricted access to hardware and memory; kernel mode runs the operating system core with full privileges, and programs switch into it through system calls.

  • User mode: normal apps. They can't touch hardware or other processes' memory directly, so a bug crashes only that app.
  • Kernel mode: the OS kernel (drivers, scheduler, memory manager) with unrestricted access.
  • The CPU enforces this with privilege levels (rings).
  • System calls (read, write, fork, open) are the controlled doors from user to kernel mode, and they cost a mode switch.
  • This separation gives stability and security.
What is a race condition and a critical section?Easy

A race condition is when the result depends on the unpredictable timing of threads accessing shared data; a critical section is the code that accesses that shared data and must run by one thread at a time.

  • Example: two threads run balance = balance + 100 at the same time. Both read the old value, so one update is lost.
  • The critical section is the code touching shared data.
  • Solutions must give mutual exclusion, progress and bounded waiting.
  • Tools: mutexes and locks, semaphores, atomic operations, monitors, or avoiding shared state (immutable data, message passing).
  • Race conditions are hard to reproduce because they depend on timing.
What is a system call? Give examples.Easy

A system call is how a program asks the operating system kernel to do privileged work for it, such as reading files, creating processes or allocating memory.

CategoryExamples (Linux)
Processesfork, exec, exit, wait
Filesopen, read, write, close
Memorymmap, brk
Devicesioctl
Communicationpipe, socket, send, recv

Programs usually call them through library functions (C's printf eventually calls write). Each call switches from user mode to kernel mode, which is why batching I/O (buffering) improves performance.

What is the difference between internal and external fragmentation?Medium

Internal fragmentation is wasted space inside an allocated block that is bigger than needed; external fragmentation is free memory split into small scattered gaps that are individually too small to use.

  • Internal: a process needs 18 KB but gets 20 KB (fixed-size blocks or pages), so 2 KB inside the block is wasted.
  • External: there's 50 KB free in total, but as 10 separate 5 KB holes, so a 20 KB request fails.

Fixes

  • Paging removes external fragmentation (any free frame works) but can cause a little internal fragmentation in the last page.
  • Compaction moves blocks together, but it's expensive.
  • Allocation strategies (best fit, first fit, buddy system) reduce gaps.

Computer Networks

Explain the OSI model and the TCP/IP model.Easy

The OSI model has 7 layers (physical, data link, network, transport, session, presentation, application) as a teaching reference; the TCP/IP model used on the internet merges them into 4 layers: link, internet, transport and application.

OSI layerExampleTCP/IP layer
7 ApplicationHTTP, DNS, SMTPApplication
6 PresentationTLS, encodingApplication
5 SessionsessionsApplication
4 TransportTCP, UDPTransport
3 NetworkIP, routersInternet
2 Data linkEthernet, Wi-Fi, switchesLink
1 Physicalcables, radioLink

Mnemonic (top-down): "All People Seem To Need Data Processing". Each layer adds its own header as data goes down the stack (encapsulation).

What is the difference between TCP and UDP?Easy

TCP is connection-oriented and reliable, with ordering, retransmission and congestion control; UDP is connectionless and faster, with no delivery guarantees.

TCPUDP
Connection set up with a 3-way handshake (SYN, SYN-ACK, ACK)No connection
Reliable: acknowledgements and retransmissionsBest effort; packets can be lost
Ordered deliveryNo ordering
Flow and congestion controlNone
Higher overheadLightweight, low latency
Web, email, file transferVideo calls, games, DNS, live streaming

HTTP/3 runs on QUIC, which is built on UDP and adds its own reliability.

What happens when you type a URL into a browser and press Enter?Hard

The browser resolves the domain to an IP with DNS, opens a TCP (or QUIC) connection, negotiates TLS for HTTPS, sends an HTTP request, the server responds, and the browser parses and renders the page, fetching more resources as needed.

  1. Parse the URL and check the browser cache, HSTS and so on.
  2. DNS lookup: browser cache → OS cache → resolver → root → TLD → authoritative server gives the IP address.
  3. Connection: TCP 3-way handshake (or QUIC over UDP for HTTP/3).
  4. TLS handshake (HTTPS): agree on encryption, the server proves its identity with a certificate.
  5. HTTP request: GET /path with headers and cookies.
  6. Server side: load balancer → web server → application → database → response (status code, headers, HTML).
  7. Rendering: parse HTML into the DOM and CSS into the CSSOM, run JavaScript, lay out and paint. More requests fetch images, CSS and JS.

This question checks breadth. Go deeper on any step the interviewer cares about.

What is the difference between HTTP and HTTPS?Medium

HTTPS is HTTP sent over TLS, which encrypts traffic, protects it from tampering, and proves the server's identity with a certificate; plain HTTP sends everything as readable text.

  • HTTP: plain text on port 80. Anyone on the network path can read or change it.
  • HTTPS: HTTP inside TLS, on port 443.
    • Encryption: eavesdroppers can't read passwords or cookies.
    • Integrity: data can't be modified in transit without detection.
    • Authentication: a certificate signed by a trusted Certificate Authority proves you're talking to the real site.
  • The TLS handshake uses asymmetric cryptography to agree on a shared key, then fast symmetric encryption for the data.
How does DNS work?Medium

DNS translates domain names into IP addresses through a hierarchy: a resolver asks root servers, then top-level-domain servers, then the domain's authoritative server, caching answers along the way.

  1. The app asks the OS resolver, which checks its cache.
  2. The query goes to a recursive resolver (your ISP's, or 8.8.8.8 / 1.1.1.1).
  3. Resolver → root server → "ask the .com servers".
  4. → TLD server → "ask this domain's authoritative server".
  5. → Authoritative server → returns the record.
  6. Answers are cached for their TTL (time to live).

Common records: A (IPv4), AAAA (IPv6), CNAME (alias), MX (mail), TXT (verification, SPF), NS (name servers).

What are the main HTTP methods and status codes?Easy

GET reads, POST creates, PUT replaces, PATCH updates partly and DELETE removes; status codes are grouped as 2xx success, 3xx redirect, 4xx client error and 5xx server error.

MethodUseIdempotent?
GETread✅
POSTcreate❌
PUTreplace✅
PATCHpartial updatenot necessarily
DELETEremove✅
CodeMeaning
200 OK, 201 Created, 204 No Contentsuccess
301 / 302redirect
400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found, 429 Too Many Requestsclient error
500 Internal Server Error, 502 Bad Gateway, 503 Service Unavailableserver error

Idempotent means repeating the request has the same effect as doing it once.

What is the difference between IPv4 and IPv6?Easy

IPv4 uses 32-bit addresses (about 4.3 billion, now exhausted) written as four numbers; IPv6 uses 128-bit addresses written in hexadecimal, providing a practically unlimited number and simpler routing.

IPv4IPv6
Size32 bits128 bits
Example192.168.1.102001:db8::1
Addresses~4.3 billion~3.4 × 10³⁸
NAT neededusuallynot needed
ConfigDHCP or manualauto-configuration (SLAAC) and DHCPv6
  • Private ranges (IPv4): 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16.
  • NAT lets many devices share one public IPv4 address.
  • Both run side by side today (dual stack).
Explain the TCP three-way handshake.Medium

The client sends SYN, the server replies SYN-ACK, and the client answers ACK; both sides agree on starting sequence numbers and the connection is open.

  1. SYN: the client says "I want to connect; my starting sequence number is x".
  2. SYN-ACK: the server says "OK; my sequence number is y, and I acknowledge x+1".
  3. ACK: the client acknowledges y+1, and data can flow.

Why three steps? Both sides must confirm they can send and receive, and agree on sequence numbers for reliable, ordered delivery.

Closing uses a four-way FIN / ACK exchange (each direction closes separately).

SYN flood attack: sending many SYNs without the final ACK fills the server's queue. SYN cookies defend against it.

What is a load balancer?Medium

A load balancer spreads incoming requests across several servers to improve performance and availability, and stops sending traffic to servers that fail health checks.

  • Why: handle more users, avoid a single point of failure, enable zero-downtime deployments.
  • Algorithms: round robin, least connections, IP hash (sticky sessions), weighted.
  • Layer 4 (TCP/UDP) balancers are fast and don't look at content. Layer 7 (HTTP) balancers can route by URL, header or cookie.
  • Health checks remove unhealthy servers automatically.
  • Examples: Nginx, HAProxy, AWS ELB/ALB, Cloudflare.
  • Often combined with horizontal scaling and stateless servers, with sessions stored in Redis or a database.
What is the difference between cookies, sessions and tokens (JWT)?Medium

A cookie is small data the browser stores and sends with requests; a session keeps user state on the server, referenced by a session ID in a cookie; a token like a JWT carries signed user claims itself, so the server can stay stateless.

Session (server-side)JWT (token)
State storedon the serverinside the token
Sent ascookie with a session IDAuthorization: Bearer … header or cookie
Logout / revokeeasy (delete the session)hard until expiry (needs a blocklist or short expiry)
Scalingneeds a shared session storestateless, easy to scale

Cookie security flags: HttpOnly (no JavaScript access), Secure (HTTPS only), SameSite (CSRF protection).

Never store sensitive data in a JWT payload: it's encoded, not encrypted.

HR & Behavioral

Tell me about yourself.Easy

Give a 60–90 second story: who you are now, the key experience or projects that got you here, and why this role is the right next step.

Use the Present → Past → Future structure:

  1. Present: "I'm a final-year computer science student focusing on mobile development."
  2. Past: one or two achievements with results: "I built a Flutter study app that reached 5,000 users and taught me Supabase and CI/CD."
  3. Future: connect to the role: "I'm excited about this role because you build products used by millions, and I want to grow as a mobile engineer."

Avoid: your life story, repeating your CV line by line, personal details, or speaking for more than 2 minutes.

💡 Practise out loud until it sounds natural, not memorised.

What are your strengths and weaknesses?Easy

Name a strength that matters for the job with a real example, and a genuine weakness you are actively improving, with the steps you are taking.

Strength: pick one relevant to the role and prove it:

Weakness: real, not fatal for the job, and show improvement:

Avoid: fake weaknesses ("I'm a perfectionist", "I work too hard") and anything that is a core requirement of the job.

Describe a challenging project and how you handled it.Medium

Answer with the STAR method: the Situation, your Task, the specific Actions you took, and the measurable Result, ending with what you learned.

STAR method

  • Situation: the context, briefly. "Our app crashed for 20% of users after an update."
  • Task: your responsibility. "I had to find and fix it before the weekend release."
  • Action: what you did; say "I", not just "we". "I reproduced it with crash logs, found a null value from the API, added validation and a test, and set up a staged rollout."
  • Result: numbers if possible. "Crashes dropped to under 0.1% and staged rollouts became our standard."

End with what you learned. Prepare 4–5 STAR stories in advance (a challenge, a failure, a conflict, leadership, a tight deadline) and adapt them to each question.

Why should we hire you?Easy

Match two or three of your strongest skills and results to the job's main requirements, then add what makes you different and show enthusiasm for the role.

  1. Read the job description and pick its top 2–3 needs.
  2. Match each need to proof from your experience:
  3. Add your difference: a rare skill, a domain you know, or strong ownership.
  4. Close with motivation: why this company and product specifically.

Keep it about their needs, not yours. Confident, specific and short beats a long list of adjectives.

How do you handle conflict with a teammate?Medium

Address it early and privately, listen to understand their view, focus on the shared goal and facts rather than the person, agree on a solution together, and escalate only if needed.

A good structure

  1. Talk early and in private: don't let it grow or happen in public.
  2. Listen first: understand their reasons; often it's a different priority, not a bad intention.
  3. Focus on facts and the goal: "We both want a stable release; let's compare the two approaches on that."
  4. Agree on a decision, sometimes by trying the other person's idea, prototyping both, or asking a lead to decide.
  5. Follow up and keep the relationship positive.

Give a real STAR example, and show you can disagree and commit: support the team's decision even when it wasn't your first choice.

Do you have any questions for us?Easy

Always say yes and ask two or three thoughtful questions about the team, the work and how success is measured; it shows genuine interest.

Good questions to ask

  • "What would success look like in the first 3 months?"
  • "What does a typical day or sprint look like for the team?"
  • "What's the biggest technical challenge the team is facing right now?"
  • "How do code reviews and mentoring work here?"
  • "How do you measure the impact of this role?"

Avoid as your first questions: salary, holidays, or anything easily found on their website.

💡 End warmly: thank them, and say briefly why you're excited about the role.

Where do you see yourself in five years?Easy

Show ambition that fits the role: growing deeper skills, taking more responsibility, and contributing to the company, without sounding like you plan to leave soon.

A good structure

  1. Skills: "I want to become a strong mobile engineer who can own features end to end."
  2. Impact: "I'd like to lead projects and mentor newer developers."
  3. Link to the company: "This role and your product give me exactly that path."

Avoid: "In your job", "running my own startup", "I don't know", or naming a totally different career.

Tell me about a time you failed.Medium

Pick a real but recoverable failure, take ownership without blaming others, explain what you did to fix it, and focus most of the answer on what you learned and changed.

Use STAR, with extra weight on the lesson:

  • Situation/Task: "I promised a feature in one week without checking the API was ready."
  • Action: "When it slipped, I told my lead early, split the work, and shipped a smaller version first."
  • Result: "We delivered two days late, with no surprise for users."
  • Lesson: "Now I check dependencies before estimating, and I share risks on day one."

The interviewer is checking honesty, ownership and growth, not whether you've never failed.

How do you handle pressure and tight deadlines?Easy

Stay calm, break the work down, prioritise what matters most, communicate early about risks, and give a real example where this worked.

  1. Clarify what's truly required for the deadline.
  2. Break down and prioritise the work: must-have first.
  3. Communicate early: flag risks and propose trade-offs (smaller scope, more help, a later date for extras).
  4. Focus: protect time and reduce distractions.
  5. Reflect afterwards on how to avoid the crunch next time.

Back it up with a short STAR story, such as finishing a project before an exam or fixing a release-day bug.

What are your salary expectations?Medium

Research the market range for the role and location beforehand, give a realistic range rather than one number, and show flexibility based on the whole package.

  1. Research first: salary sites, job posts and seniors in your network, for this role, level and city.
  2. Give a range, with your target near the bottom: "Based on my research, roles like this are around X–Y."
  3. Show flexibility: "I'm open to discussing the full package: learning budget, growth and benefits."
  4. If asked very early, you can say: "I'd like to understand the role better first, but my research suggests around X–Y."

Avoid: saying a number with no research, or underselling yourself out of nervousness.

The website teaches. The app makes it stick.

Read lessons offline, practise with daily quizzes and timed challenges, and keep your progress in your pocket.

Get it on Google Play