Technical Interview Preparation

Technical Interview Preparation requires more than memorising definitions or practising questions. Interviewers look for structured reasoning: clarify the problem, choose an appropriate model, explain trade-offs, write correct code or queries, test edge cases and communicate honestly. This guide provides a structured study plan and practice bank for software engineering, data, database and general technical roles.

How Technical Interview Preparation Works

A typical process has an application screen, an online assessment, one or more technical interviews, a project or system discussion, and a behavioural or manager round. The exact sequence varies by employer and country. Read the job description, ask what language and tools are allowed, and never assume that a question bank predicts the interview.

A reliable answer loop

  1. Clarify: identify input shape, output, constraints, duplicates, ordering, nulls and failure behaviour.
  2. Plan: describe a simple baseline, then improve it only when the constraints justify the complexity.
  3. Prove: state an invariant or reason the algorithm is correct.
  4. Implement: use meaningful names and small helpers; narrate decisions without reading every character aloud.
  5. Test: use a normal case, an empty or minimal case, a boundary case and an adversarial case.
  6. Analyse: give time and auxiliary-space complexity and identify the dominant term.
  7. Reflect: mention a trade-off, alternative or production concern.

Example: for “find two values that sum to a target,” ask whether the same element may be reused and whether returning indices is required. A nested-loop baseline is O(n²) time and O(1) extra space. A hash-map solution stores previously seen values and is O(n) expected time and O(n) space. The answer is complete only after explaining duplicate values and the case where no pair exists.

2. Data structures and algorithms

A consistent Technical Interview Preparation routine should include solving problems, analysing time and space complexity, and explaining why a particular approach is suitable.

Effective Technical Interview Preparation involves practising coding problems regularly and explaining the time and space complexity of each solution.

Choose a data structure because of the operations it makes cheap, not because it is fashionable. Complexity describes how resource use grows with input size; it does not replace correctness, measurement or knowledge of constants.

Topic Intuition and operations Typical complexity Implementation/practice focus
Complexity analysis Count dominant operations as n grows; distinguish worst, average and amortised cost. Binary search O(log n); scan O(n); nested independent scans often O(n²). State time and auxiliary space, including recursion depth.
Arrays and strings Contiguous indexed storage; excellent random access, costly middle insertion. Index O(1), search O(n), append amortised O(1), insert/delete middle O(n). Use prefix sums, two pointers and in-place updates.
Hash maps and sets Map a key to a bucket for fast membership or association. Expected lookup/insert/delete O(1), worst case can degrade to O(n). Understand hashability, collisions, counts and duplicate handling.
Linked lists Nodes connect by references, so links move without shifting a block. Head access O(1), search O(n), insert after known node O(1). Track previous/current pointers; handle empty and one-node lists.
Stacks and queues Stack is last-in-first-out; queue is first-in-first-out. End operations O(1) with suitable representation. Parentheses, monotonic stack, BFS and task scheduling.
Recursion/backtracking Reduce a problem to smaller states; backtracking tries, records and undoes choices. Depends on branching; include call-stack and copied-state cost. Define base case, progress and undo step before coding.
Trees and BSTs Hierarchical nodes; a BST orders left values below and right values above. Balanced BST search O(log n); unbalanced worst case O(n). DFS/BFS, height, traversal order and validation bounds.
Heaps/priority queues Keep the smallest or largest priority at the root, not all values sorted. Peek O(1), push/pop O(log n), heapify O(n). Top-k, scheduling and merging sorted streams.
Graphs Vertices and edges model relationships; choose directed/undirected and weighted/unweighted explicitly. Adjacency list storage O(V+E); BFS/DFS O(V+E). Visited state, disconnected components and shortest-path assumptions.
Searching/sorting Search exploits order; sorting creates order at a cost. Merge sort O(n log n), quicksort average O(n log n), binary search O(log n). Stable sorting, comparator rules and sorted-input preconditions.
Greedy algorithms Commit to the best local choice when an exchange or cut argument supports it. Often O(n log n) after sorting. Explain why local choices cannot block an optimal solution.
Dynamic programming Cache overlapping subproblems and define a state recurrence. Usually states × transitions; space can be reduced if only prior rows are needed. State, transition, base case, order and reconstruction.
Two pointers Move boundaries through ordered or partitionable data rather than restarting scans. Usually O(n), often O(1) extra space. Sorted pair sums, partitions and linked-list fast/slow pointers.
Sliding window Maintain a valid contiguous interval while the right and left edges move. Usually O(n), because each edge moves at most n times. Know whether the window condition is monotonic.
Prefix sums Precompute cumulative totals so a range can be answered by subtraction. Build O(n), range query O(1), space O(n). Use a leading zero to avoid special-casing ranges from index zero.
Binary-search patterns Search a monotonic predicate, not only an exact value in a sorted list. O(log n) predicate checks. Define the invariant and decide whether the answer interval is closed or half-open.

Python reference implementations

from collections import Counter, deque
import heapq

def two_sum(values, target):
    seen = {}
    for index, value in enumerate(values):
        needed = target - value
        if needed in seen:
            return seen[needed], index
        seen[value] = index
    return None

def bfs(graph, start):
    visited = {start}
    queue = deque([start])
    order = []
    while queue:
        node = queue.popleft()
        order.append(node)
        for neighbour in graph.get(node, []):
            if neighbour not in visited:
                visited.add(neighbour)
                queue.append(neighbour)
    return order

def lower_bound(values, target):
    left, right = 0, len(values)
    while left < right:
        middle = (left + right) // 2
        if values[middle] < target:
            left = middle + 1
        else:
            right = middle
    return left

Walk-through: two_sum stores each prior value and its index; checking before inserting prevents reusing the current element. BFS marks a node when enqueued, so cycles do not cause repeated work. lower_bound maintains the invariant that every index below left is too small and every index at or above right may be the answer. Each runs in expected O(n), O(V+E), and O(log n) time respectively.

Interview exercise ladder

  1. Easy: remove duplicates from a sorted array in place; validate parentheses with a stack; find the first non-repeating character.
  2. Intermediate: longest substring without repeated characters; merge overlapping intervals; level-order traversal; top-k frequent values; number of islands.
  3. Advanced: word search with backtracking; course schedule using cycle detection; minimum window substring; coin change; serialize and deserialize a binary tree.
  4. Pattern drills: range-sum queries with prefix sums, rotated-array binary search, maximum subarray, house robber DP, interval scheduling and median of two sorted arrays.

Common traps: saying O(1) for hashing without mentioning expected behaviour, forgetting recursion space, sorting when an O(n) counting solution is possible, using BFS for weighted shortest paths without qualification, and changing a window rule without proving that the left pointer can safely advance.

3. Object-oriented programming

A class describes behaviour and state; an object is a concrete instance. A constructor establishes a valid initial state. Encapsulation keeps representation changes behind a stable interface. Abstraction exposes what a client needs while hiding implementation detail. Inheritance is an “is-a” relationship; composition builds an object from collaborators and is often safer when behaviour changes independently.

from abc import ABC, abstractmethod

class Notifier(ABC):
    @abstractmethod
    def send(self, message):
        pass

class EmailNotifier(Notifier):
    def __init__(self, address):
        self._address = address

    def send(self, message):
        return f"Sending {message} to {self._address}"

class OrderService:
    def __init__(self, notifier):
        self._notifier = notifier

    def confirm(self, order_id):
        return self._notifier.send(f"order {order_id} confirmed")

The service depends on the Notifier abstraction, not a concrete email library. That is composition and dependency inversion: a test can inject a fake notifier. Polymorphism lets every notifier honour the same send contract. An interface in languages with explicit interfaces and an abstract base class in Python express a similar contract, but neither automatically guarantees good design.

SOLID principle Interview explanation Practical signal
Single Responsibility A module should have one reason to change. Separate persistence, validation and notification.
Open/Closed Extend behaviour without repeatedly editing stable code. Strategy or registry instead of a growing conditional.
Liskov Substitution Subtypes must preserve the promises clients rely on. Do not make a subclass reject valid base-class inputs.
Interface Segregation Clients should not depend on methods they do not use. Prefer focused interfaces.
Dependency Inversion High-level policy depends on abstractions. Inject repositories, clocks and gateways.

Exercises: design a parking-lot model, refactor a large payment conditional with Strategy, model a library with composition, and explain why a square subclass of a mutable rectangle can violate substitutability. Mention coupling, cohesion, testability and the cost of unnecessary abstraction.

4. DBMS and SQL

Technical Interview Preparation for database roles should include practical SQL queries, indexing, transactions, normalization and the ability to explain database design decisions.

A DBMS stores, retrieves and protects data; a relational DBMS represents related facts in tables and enforces constraints. Start with entity grain: one row in orders is one order, while one row in order_items is one product line. Primary keys identify rows, foreign keys preserve relationships, unique constraints prevent duplicate business identifiers, and check constraints reject invalid states.

Normalization reduces update anomalies: 1NF uses atomic values, 2NF removes dependencies on part of a composite key, and 3NF removes non-key dependencies on another non-key attribute. Denormalization can be justified for read performance, but document the source of truth and refresh strategy.

WITH monthly AS (
    SELECT customer_id,
           DATE_FORMAT(order_date, '%Y-%m-01') AS month_start,
           SUM(total_amount) AS revenue
    FROM orders
    WHERE status = 'paid'
    GROUP BY customer_id, DATE_FORMAT(order_date, '%Y-%m-01')
)
SELECT customer_id, month_start, revenue,
       SUM(revenue) OVER (
           PARTITION BY customer_id
           ORDER BY month_start
       ) AS running_revenue,
       LAG(revenue) OVER (
           PARTITION BY customer_id
           ORDER BY month_start
       ) AS previous_month
FROM monthly
ORDER BY customer_id, month_start;

The CTE establishes monthly grain before the window functions run. PARTITION BY resets calculations per customer and ORDER BY defines sequence. A left join finds customers with no orders; WHERE orders.id IS NULL must be applied after the join, while putting a right-table filter in WHERE can accidentally turn it into an inner join.

Transactions and optimization

ACID means atomicity, consistency, isolation and durability. Use BEGIN, validate, update related rows, then COMMIT; rollback on an error. Isolation controls what concurrent transactions can observe. Deadlocks are possible even with correct transactions, so keep transactions short, lock resources in a consistent order, and retry safely where the application contract permits. Index columns used by selective predicates, joins and ordering, but remember write cost, storage and low-cardinality limitations. Use EXPLAIN to inspect access type, estimated rows, chosen indexes and extra sorting/materialization; never optimize from an index list alone.

SQL exercises: find the second-highest salary with DENSE_RANK; return products never ordered using NOT EXISTS; calculate department ranking with a window; detect duplicate emails before a cleanup; find seven-day consecutive activity; and explain why a many-to-many join inflated revenue. For every answer state null behaviour, duplicate behaviour, expected indexes and the table grain.

5. Operating systems

A process owns an address space and resources; a thread is an execution path within a process and shares much of that process state. Context switching saves one execution context and restores another, which enables concurrency but has scheduling and cache cost. Preemptive scheduling interrupts work; common policies include first-come-first-served, shortest-job, priority and round-robin. Discuss throughput, latency, fairness and starvation rather than claiming one policy is universally best.

A race occurs when the result depends on timing. A mutex gives exclusive ownership; a semaphore controls permits or signals availability. A deadlock requires mutual exclusion, hold-and-wait, no pre-emption and circular wait. Prevent it by ordering locks, reducing lock scope or using timeouts; detection and recovery are alternatives. A condition variable lets a thread sleep until a predicate becomes true and must be checked in a loop.

Virtual memory maps virtual addresses to physical frames. Paging uses fixed-size pages and can incur page faults; segmentation uses logical variable-sized regions and can create external fragmentation. The file system maps names and metadata to blocks, enforces permissions and aims for durable updates. A system call is the controlled boundary through which a process requests kernel services such as opening a file, creating a process or sending data.

Practice: trace a producer-consumer buffer with a mutex and two counting semaphores; compare a process and thread for isolation and communication; explain a page fault; identify a deadlock from a lock-order diagram; and calculate round-robin waiting time for three processes. Common traps include calling every parallel task a process, confusing virtual with physical memory, and treating a semaphore as merely a faster mutex.

6. Computer networks

The OSI model is a teaching model of layers; TCP/IP is the practical suite. At a high level, an application creates data, transport provides ports and delivery semantics, IP routes packets between networks, and link/physical layers move frames. IP addresses identify interfaces or endpoints within a network; subnet masks determine which addresses are local. Ports identify services within a host.

Concept What to explain Trade-off or trap
DNS Resolves names through caches and authoritative records such as A/AAAA/CNAME. DNS success does not prove the application is healthy.
TCP vs UDP TCP establishes ordered, reliable byte-stream delivery; UDP is connectionless with application-managed reliability. UDP is not automatically faster for every workload.
HTTP/HTTPS HTTP defines requests, responses, methods and status codes; HTTPS adds TLS confidentiality, integrity and server authentication. TLS does not fix authorization or unsafe input handling.
Cookies/sessions A cookie is client-held data; a session commonly stores server-side state referenced by a cookie. Protect flags, expiry, rotation and CSRF boundaries.
REST APIs Use resource-oriented URLs, suitable methods, status codes, validation and idempotency where appropriate. “REST” is not a substitute for an API contract.

Routing chooses a next hop using network prefixes and routing tables. Basic network security includes least privilege, input validation, TLS certificate validation, rate limiting, secure secrets, logging without sensitive values and defence against injection, replay and denial-of-service. Practise explaining a browser request from DNS lookup through TCP/TLS, HTTP, load balancer, application and database.

7. Software engineering

SDLC activities include requirements, design, implementation, verification, release and maintenance; they are iterative in real teams. Waterfall can suit stable, regulated requirements with formal gates, while Agile favours short feedback loops. Scrum commonly uses a product backlog, sprint planning, daily coordination, review and retrospective; ceremonies are not a guarantee of good engineering.

Testing levels form a risk strategy: unit tests isolate small behaviour, integration tests check boundaries, end-to-end tests validate workflows, and acceptance tests check business expectations. A useful test is deterministic, focused and clear about failure. Version control provides history and collaboration; small commits, code review and protected branches reduce integration risk. CI runs automated checks on changes; CD automates delivery or deployment with approvals, observability and rollback.

Patterns: Factory centralizes object creation, Adapter translates an incompatible interface, Strategy selects interchangeable behaviour, Observer publishes events to subscribers, and Repository separates persistence access from domain logic. State the problem and cost before naming a pattern. Overusing patterns creates indirection and hides simple code.

8. Data Science interviews

Start with the business decision: what action changes if the result changes, what is the unit of analysis, and what is the cost of false positives and false negatives? Inspect data provenance, missingness, duplicates, leakage, time order and subgroup performance before choosing a model.

Area Interview-ready explanation
Statistics/probability Distinguish population from sample, correlation from causation, standard error from standard deviation, and uncertainty from a point estimate.
Python/SQL Use readable functions, tests and vectorized operations where appropriate; state table grain and null/duplicate semantics in SQL.
EDA Use distributions, group comparisons, missingness and outlier checks to generate and challenge hypotheses.
Feature engineering Transform information available at prediction time; fit learned transformations only on training data.
Model selection Choose a baseline and metric tied to the decision; compare cross-validated candidates without using the test set for tuning.
A/B testing Randomize treatment, define a primary metric and duration before looking, check power and guardrails, and interpret uncertainty.
Time series Respect chronological splits, inspect trend/seasonality/autocorrelation, and never let future values enter features for a past prediction.

Case framework: for churn, define churn window and observation cutoff, establish a majority-class or retention baseline, use precision/recall or expected cost, calibrate probabilities if interventions are prioritized, and inspect errors by tenure and plan. For forecasting, compare a seasonal-naive baseline, use rolling validation and report error by horizon. For an experiment, ask about randomization, interference, sample ratio mismatch, multiple metrics and practical effect size.

9. Project discussion

Use Context → Decision → Method → Evidence → Limitation → Next step. A strong answer is specific without inventing results.

Question Answer structure Follow-up to prepare
What problem did your project solve? Name the user/business decision, input, output and success metric. Explain why the problem mattered. Who used it? What would change if it were wrong?
Why this approach? Compare a simple baseline with your chosen method and connect the choice to data, constraints and interpretability. What alternative did you reject and why?
What was your contribution? Separate your work from team work: design, code, analysis, tests, deployment and documentation. Show one commit or decision you owned.
What challenge did you face? Describe the symptom, diagnosis, change and verification; include a failed approach when useful. How would you detect it earlier?
Why that model/database? Discuss data shape, workload, consistency, latency, scale, operational skill and cost. What would make you migrate?
How did you evaluate? State split/design, baseline, metric, uncertainty and error analysis; never present an unmeasured claim as fact. Could leakage or class imbalance change the result?
What would you improve? Prioritize the next experiment by expected impact and measurement plan. What is the smallest safe change?

Two-minute template: “I built [system] for [user/problem]. Each [row/request] represented [grain]. I first made [baseline], then chose [method] because [constraint]. I owned [contribution]. The main challenge was [issue], which I diagnosed with [evidence] and fixed by [change]. I evaluated it with [metric/design] and found [measured result or limitation]. Next I would [specific experiment], while monitoring [risk].”

10. Interview simulations

Answer each question aloud, draw or write the smallest example, and then use the follow-up to test whether you understand the boundary rather than a memorized sentence.

Technical Interview Preparation becomes more effective when students practise under timed conditions and review their mistakes after each mock interview.

Beginner set

  1. Why is binary search O(log n)? Each comparison discards half of a sorted search interval, so after k steps at most n/2k candidates remain; k grows as log₂n. Follow-up: what precondition is required? A monotonic predicate or sorted/searchable order. Trap: using it on unsorted data.
  2. Array versus linked list? Arrays provide O(1) indexing and good locality; linked lists provide cheap insertion after a known node but O(n) search and extra references. Follow-up: why can an array append be amortised O(1)? Capacity is occasionally expanded and copied. Trap: saying linked lists are always faster to insert.
  3. What is a primary key? A constraint identifying each row; it is unique and not null in a relational design. Follow-up: can a table have multiple candidate keys? Yes, one is selected as primary and others may be unique. Trap: confusing a foreign key with uniqueness.
  4. Process versus thread? Processes have isolated address spaces and stronger failure boundaries; threads share process memory and are cheaper to coordinate but require synchronization. Follow-up: what is a race? Timing-dependent unsynchronized access. Trap: equating concurrency with parallel execution.
  5. What does HTTPS add? TLS authenticates the server and protects confidentiality and integrity in transit. Follow-up: does it prevent SQL injection? No; validation and parameterized queries are separate controls. Trap: treating the padlock as proof that the application is secure.

Intermediate set

  1. Find the longest substring without repeated characters. Maintain a set/map and a left boundary; move right once, and advance left past the previous occurrence. Each index enters and leaves the window at most once: O(n) time and O(k) space. Follow-up: what changes for Unicode or bytes? Define character semantics and memory assumptions. Trap: resetting the whole set for every right index.
  2. Explain a transaction anomaly. A dirty read observes uncommitted data; a non-repeatable read sees a changed row; a phantom read sees changed matching rows. Isolation levels trade concurrency against these anomalies. Follow-up: how can deadlocks be reduced? Consistent lock order and short transactions. Trap: claiming serializable is always the best production choice.
  3. How would you evaluate an imbalanced classifier? Start from business costs and a baseline; inspect precision, recall, PR-AUC, confusion matrix and threshold behaviour rather than accuracy alone. Tune threshold on validation data and preserve an untouched test set. Follow-up: how do you avoid leakage while oversampling? Apply it inside each training fold. Trap: oversampling before the split.
  4. Design a notification service with OOP. Define a notifier contract, inject email/SMS implementations, keep retry policy separate, and record idempotency keys. Composition and dependency inversion make providers replaceable. Follow-up: where do failures go? Explicit result/error policy plus durable retry or dead-letter handling. Trap: making one giant Notification class.
  5. Why use an index? It gives the optimizer an alternative access path, often reducing rows read for selective predicates or joins. It costs storage and slows writes. Follow-up: how verify benefit? Compare EXPLAIN and measured plans on representative data. Trap: indexing every column or wrapping an indexed column in a function without considering sargability.

Advanced set

  1. How do you design a rate limiter? Clarify identity, limit, window, burst behaviour and distributed deployment. A token bucket supports controlled bursts; store state atomically, use monotonic time, define fail-open/closed behaviour and monitor rejected requests. Follow-up: what about multiple regions? Choose consistency and routing strategy explicitly. Trap: ignoring clock, retry and hot-key issues.
  2. Explain DP state design. Define the smallest information needed to decide future choices, write base cases and a recurrence, prove each transition, then choose memoized recursion or bottom-up order. Follow-up: how reduce space? Keep only dependency rows/columns when reconstruction is not needed. Trap: memoizing a state that still contains the entire history.
  3. Debug a slow API. Establish a latency budget, correlate request IDs across logs and traces, separate queue, network, application and database time, inspect query plans and profile representative requests. Change one bottleneck, load-test and compare p50/p95/p99. Follow-up: what if averages improve but p99 worsens? Investigate tail causes rather than accepting the average. Trap: adding a cache before measuring.
  4. Design an experiment for a recommendation change. Define eligible population, randomization unit, treatment, primary metric, guardrails, duration, power and stopping rule. Check exposure, interference, novelty and segment effects. Follow-up: what if assignment is imbalanced? Investigate sample-ratio mismatch before interpreting results. Trap: changing the primary metric after seeing results.

Role-specific sets

Data Science: explain bias versus variance; choose a validation scheme for time series; derive precision, recall and Bayes’ rule; diagnose leakage; interpret a confidence interval; write a SQL retention query; and propose a churn intervention with cost-sensitive thresholds. Follow-ups should ask about assumptions, uncertainty, subgroup fairness and operational monitoring.

Software engineering: implement an LRU cache; explain dependency injection; design idempotent order creation; compare TCP and UDP for a workload; investigate a deadlock; write a unit/integration test boundary; and describe a CI rollback. Traps include ignoring failure modes, concurrency, observability and backward compatibility.

Database-focused: find the top three products per category with ROW_NUMBER; explain composite-index order; normalize an invoice schema; diagnose a deadlock; compare isolation levels; and read an EXPLAIN plan. Follow-ups should probe grain, nulls, duplicates, cardinality, write workload and transaction boundaries.

11. Structured eight-week preparation schedule

Week Focus Measurable deliverable
1 Interview method, complexity, arrays, strings, hash maps and sets 15 reviewed problems and five recorded explanations
2 Linked lists, stacks, queues, recursion, two pointers and windows 15 problems, edge-case log and one timed session
3 Trees, heaps, graphs, searching, sorting, greedy and DP 20 problems grouped by pattern; explain three proofs
4 OOP, SOLID, design patterns and project discussion One design exercise, one refactoring and a two-minute project story
5 DBMS, normalization, transactions, indexes, joins and windows 20 SQL queries, two EXPLAIN readings and one schema design
6 OS, networks, testing, Git and CI/CD Four concept maps, one debugging scenario and one pipeline outline
7 Role track: Data Science case studies or software/database design Two role-specific mocks, one project deep dive and corrected gaps
8 Full simulations, revision, resume and logistics Three timed mocks, final error log and question list for interviewers

Use a sustainable daily rhythm: 45 minutes concept study, 60 minutes solving, 20 minutes review and two longer mock sessions each week. Spend at least as much time correcting mistakes as collecting new questions. Do not claim completion based only on problem counts; require an explanation, tests and complexity analysis.

12. Mock interview checklist

  1. Choose a role, level, language and realistic time limit.
  2. Prepare a problem or case without seeing the solution.
  3. Start by clarifying assumptions and restating the task.
  4. State a baseline before optimizing.
  5. Use a small example and test edge cases aloud.
  6. Explain invariants, correctness and complexity.
  7. For SQL, state table grain, null semantics and duplicate behaviour.
  8. For Data Science, state the decision, split, baseline, metric, leakage controls and uncertainty.
  9. For design, cover requirements, API/data model, failure modes, scale, security and observability.
  10. Ask for feedback on correctness, communication, structure and time management.
  11. Record one knowledge gap, one recurring trap and one next exercise.
  12. Verify every resume claim and prepare two thoughtful interviewer questions.

Read the Programming Fundamentals, Python Interview, SQL Interview, Statistics, Machine Learning and Data Science Projects resources for deeper practice. A strong interview outcome is not memorized perfection; it is accurate reasoning, transparent assumptions, tested work and a demonstrated ability to learn.