Skip to main content
Computer Science & Languages

Data Structures & Algorithms (DSA) Interview Questions

All Levels (Junior to Staff)16 Questions

Data Structures & Algorithms interview guide: time/space complexity analysis (Big-O), binary tree traversal, dynamic programming tabulation, and graph search algorithms.

26 min study timeIncludes Production Code & Pitfall TrapsActive Recall Practice Mode Available

Practice Data Structures & Algorithms (DSA) Interview Questions

Showing 16 of 16 technical questions with engineering explanations

Filter Level:
Question #1FundamentalJunior

How do hash tables achieve amortized O(1) lookup, and how do separate chaining and open addressing handle collisions?

Senior Engineering Answer

A hash table maps keys via a hash function mod bucket capacity. With separate chaining, each bucket holds a linked list (or balanced tree when long, as in Java HashMap) of colliding entries. With open addressing (linear probing, quadratic probing, or Robin Hood hashing, used in Python dicts and Rust HashMap), all entries live directly in a flat contiguous array—offering superior CPU cache locality but requiring tombstones on deletion and resizing when load factor nears ~0.7. Under adversarial hash collisions (HashDoS), lookups degrade to O(N) unless randomized SipHash/seed hashing or treeified buckets are used.

Production Code Example
# Amortized O(1) two-sum lookup via hash table
def two_sum(nums: list[int], target: int) -> tuple[int, int] | None:
    seen: dict[int, int] = {}
    for i, x in enumerate(nums):
        need = target - x
        if need in seen:
            return (seen[need], i)
        seen[x] = i
    return None
Common Interview Trap / Anti-Pattern:

Using mutable objects (lists, dicts) as hash keys or mutating a field used inside __hash__/hashCode() after insertion breaks bucket lookup permanently because the stored key no longer hashes to its original slot.

Question #2FundamentalJunior

When does the variable-size Sliding Window pattern apply, and how do you solve Longest Substring Without Repeating Characters in O(N)?

Senior Engineering Answer

Variable-size sliding window solves contiguous subarray/substring problems where expanding the right pointer monotonically pushes a constraint toward violation and shrinking the left pointer restores validity—so each pointer moves forward at most N times (O(N) total). For longest unique substring, store each character's most recent index in a map; when a duplicate appears at or after `left`, jump `left` directly to `last_seen[ch] + 1` instead of shrinking one step at a time.

Production Code Example
def length_of_longest_substring(s: str) -> int:
    last_seen: dict[str, int] = {}
    left = 0
    best = 0
    for right, ch in enumerate(s):
        if ch in last_seen and last_seen[ch] >= left:
            left = last_seen[ch] + 1
        last_seen[ch] = right
        best = max(best, right - left + 1)
    return best
Common Interview Trap / Anti-Pattern:

Applying sliding window to arrays containing negative numbers when summing to a target K fails because adding or removing negative numbers breaks monotonicity; use Prefix Sums + HashMap instead.

Question #3FundamentalJunior

How does Floyd's Tortoise and Hare algorithm detect a cycle AND locate the exact cycle entry node in O(1) space?

Senior Engineering Answer

Advance `slow` by 1 step and `fast` by 2 steps. If a cycle exists, `fast` closes the gap by 1 node per step and must meet `slow` inside the cycle. Suppose the head-to-entry distance is L, entry-to-meeting distance is X, and cycle length is C: at meeting, slow traveled L + X and fast traveled L + X + kC = 2(L + X), yielding L = kC - X. Resetting one pointer to head and advancing both by 1 step guarantees they collide at the exact cycle entry after L steps.

Production Code Example
def detect_cycle_entry(head):
    slow = fast = head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            ptr = head
            while ptr is not slow:
                ptr = ptr.next
                slow = slow.next
            return ptr
    return None
Common Interview Trap / Anti-Pattern:

Comparing node values (slow.val == fast.val) instead of node identity/pointers fails whenever duplicate values exist in an acyclic list.

Question #4FundamentalJunior

How do you write bug-free Binary Search on monotonic predicates (Binary Search on Answer) without off-by-one infinite loops?

Senior Engineering Answer

Whenever a boolean feasibility check `ok(mid)` is monotonic (false, false, ..., true, true), use the half-open or closed-invariant template: set `lo, hi` to the full feasible range, compute `mid = lo + (hi - lo) // 2` (preventing 32-bit signed integer overflow), and consistently maintain the invariant that `hi` is always valid (or track `ans = mid` when shrinking). With `while lo < hi:` and `if ok(mid): hi = mid else: lo = mid + 1`, `lo` converges strictly to the minimum feasible answer with zero infinite loops.

Production Code Example
def min_eating_speed(piles: list[int], h: int) -> int:
    lo, hi = 1, max(piles)
    while lo < hi:
        mid = lo + (hi - lo) // 2
        hours = sum((p + mid - 1) // mid for p in piles)
        if hours <= h:
            hi = mid
        else:
            lo = mid + 1
    return lo
Common Interview Trap / Anti-Pattern:

Using `lo = mid` with `mid = (lo + hi) // 2` while `lo + 1 == hi` enters an infinite loop because integer floor division rounds `mid` down to `lo`.

Question #5IntermediateMid

How do Monotonic Stacks and Monotonic Deques solve Next Greater Element and Sliding Window Maximum in O(N) time?

Senior Engineering Answer

A monotonic stack maintains elements (usually indices) in strictly increasing or decreasing order: before pushing index `i`, pop all elements that violate monotonicity—each element is pushed once and popped at most once, guaranteeing O(N) amortized time. For Sliding Window Maximum, a monotonic decreasing deque (`collections.deque`) keeps candidate indices in the current window: pop smaller values from the back (they can never be the max while `nums[i]` is in the window) and pop expired out-of-window indices from the front.

Production Code Example
from collections import deque

def max_sliding_window(nums: list[int], k: int) -> list[int]:
    dq: deque[int] = deque()
    out: list[int] = []
    for i, val in enumerate(nums):
        while dq and dq[0] <= i - k:
            dq.popleft()
        while dq and nums[dq[-1]] <= val:
            dq.pop()
        dq.append(i)
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out
Common Interview Trap / Anti-Pattern:

Storing values instead of array indices in the monotonic deque prevents you from knowing when the front element has fallen out of the `i - k` window.

Question #6IntermediateMid

Why is checking only `node.left.val < node.val < node.right.val` insufficient to validate a Binary Search Tree, and how do you compute Lowest Common Ancestor (LCA)?

Senior Engineering Answer

A valid BST requires EVERY node in the left subtree to be strictly less than `node.val` and EVERY node in the right subtree strictly greater—checking only immediate children misses violations deeper down (e.g., a right-child's left grandchild smaller than the root). Pass recursive `(low, high)` bounds down the tree (or verify strictly increasing inorder traversal) in O(N) time. For general binary tree LCA(root, p, q), recurse left and right: if both subtrees return non-null, the current node is the LCA; otherwise bubble up whichever side is non-null.

Production Code Example
def is_valid_bst(node, low=float("-inf"), high=float("inf")) -> bool:
    if node is None:
        return True
    if not (low < node.val < high):
        return False
    return is_valid_bst(node.left, low, node.val) and is_valid_bst(node.right, node.val, high)
Common Interview Trap / Anti-Pattern:

In BST validation, allowing `<=` instead of `<` depends on whether duplicate keys are allowed; state your duplicate policy explicitly and never initialize bounds to 32-bit INT_MIN/INT_MAX if node values can equal them.

Question #7IntermediateMid

How does the Two-Heap pattern maintain a streaming Median in O(log N) per insertion and O(1) per query?

Senior Engineering Answer

Partition the stream into a max-heap `low` (holding the smaller half of numbers) and a min-heap `high` (holding the larger half), maintaining two invariants: (1) every element in `low` <= every element in `high`, and (2) `len(low)` equals `len(high)` or `len(high) + 1`. On `addNum(x)`, push to `low`, pop `low`'s max into `high` (guaranteeing order invariant), and if `len(high) > len(low)`, move `high`'s min back to `low` (restoring size balance). Median is `low[0]` if odd total count, or `(low[0] + high[0]) / 2` if even.

Production Code Example
import heapq

class MedianFinder:
    def __init__(self) -> None:
        self.low: list[int] = []   # max-heap (negated values)
        self.high: list[int] = []  # min-heap

    def add_num(self, num: int) -> None:
        heapq.heappush(self.low, -num)
        heapq.heappush(self.high, -heapq.heappop(self.low))
        if len(self.high) > len(self.low):
            heapq.heappush(self.low, -heapq.heappop(self.high))

    def find_median(self) -> float:
        if len(self.low) > len(self.high):
            return float(-self.low[0])
        return (-self.low[0] + self.high[0]) / 2.0
Common Interview Trap / Anti-Pattern:

Inserting directly into `low` or `high` via an `if num <= -low[0]` branch without rebalancing often leads to off-by-one edge cases on empty heaps; always pushing through `low` -> `high` and rebalancing is simpler and bug-free.

Question #8IntermediateMid

How do Kahn's BFS algorithm and 3-color DFS detect cycles in a Directed Graph and produce a Topological Sort?

Senior Engineering Answer

Topological ordering exists if and only if the directed graph is a DAG (acyclic). Kahn's algorithm tracks each node's `in_degree`, seeds a queue with all `in_degree == 0` nodes, and repeatedly pops a node, appends it to `order`, and decrements neighbors' `in_degree` (enqueuing any that reach 0). If `len(order) < V`, a cycle trapped the remaining nodes. Alternatively, DFS tracks 3 states (0=unvisited, 1=visiting on current recursion stack, 2=visited): encountering a state-1 neighbor proves a back-edge cycle.

Production Code Example
from collections import deque

def topo_sort(n: int, edges: list[tuple[int, int]]) -> list[int]:
    adj = [[] for _ in range(n)]
    indeg = [0] * n
    for u, v in edges:
        adj[u].append(v)
        indeg[v] += 1
    q = deque(i for i in range(n) if indeg[i] == 0)
    order = []
    while q:
        u = q.popleft()
        order.append(u)
        for v in adj[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                q.append(v)
    return order if len(order) == n else []
Common Interview Trap / Anti-Pattern:

Using a single `visited` boolean set in directed-graph DFS detects undirected-style visits instead of cycles—two branches converging on a diamond DAG node look visited without forming a cycle unless you distinguish 'on current path' (gray) from 'completed' (black).

Question #9SeniorSenior

How do Path Compression and Union by Size/Rank give Disjoint Set Union (Union-Find) near-O(1) amortized complexity?

Senior Engineering Answer

Without optimizations, Union-Find trees can degenerate into O(N) chains. Union by Size/Rank always attaches the smaller/shallower tree under the taller root, bounding tree height to O(log N). Path Compression during `find(x)` flattens the traversed path by pointing every visited node directly to the root. Together, Tarjan proved M operations on N elements take O(M * alpha(N)) time, where alpha(N) is the inverse Ackermann function (<= 4 for any realistic universe size).

Production Code Example
class DSU:
    def __init__(self, n: int) -> None:
        self.parent = list(range(n))
        self.size = [1] * n

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # path halving
            x = self.parent[x]
        return x

    def union(self, a: int, b: int) -> bool:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        return True
Common Interview Trap / Anti-Pattern:

Union-Find handles undirected edge additions dynamically, NOT edge deletions or directed reachability—for deletions, offline reverse-time processing or dynamic connectivity trees are required.

Question #10SeniorSenior

Compare Dijkstra's algorithm, 0-1 BFS, and Bellman-Ford for shortest paths, and explain why Dijkstra needs stale-entry skipping.

Senior Engineering Answer

Dijkstra computes single-source shortest paths in O((V + E) log V) for graphs with non-negative edge weights using a min-heap. Because standard library heaps lack O(log V) `decrease_key`, we push updated `(dist, node)` pairs lazily and discard stale entries upon pop whenever `d > dist[u]`. When edge weights are strictly {0, 1}, 0-1 BFS uses a deque (push 0-weight neighbors to front, 1-weight to back) in linear O(V + E) time. Bellman-Ford relaxes all edges V-1 times in O(V * E), handling negative weights and detecting negative-weight cycles.

Production Code Example
import heapq

def dijkstra(n: int, adj: list[list[tuple[int, int]]], src: int) -> list[int]:
    dist = [10**18] * n
    dist[src] = 0
    pq = [(0, src)]
    while pq:
        d, u = heapq.heappop(pq)
        if d > dist[u]:  # skip stale heap entry
            continue
        for v, w in adj[u]:
            if d + w < dist[v]:
                dist[v] = d + w
                heapq.heappush(pq, (dist[v], v))
    return dist
Common Interview Trap / Anti-Pattern:

Running Dijkstra on graphs with negative edge weights can fail silently because once a node is popped as 'settled', a later negative edge could still shorten its path.

Question #11SeniorSenior

In 1D space-optimized Dynamic Programming, why does 0/1 Knapsack iterate capacity backward while Unbounded Knapsack iterates forward?

Senior Engineering Answer

In 2D DP `dp[i][w]`, 0/1 Knapsack transitions from `dp[i-1][w - weight]` (the previous row, ensuring item `i` is used at most once), whereas Unbounded Knapsack transitions from `dp[i][w - weight]` (the current row, allowing item `i` to be reused). When collapsing to a single 1D array `dp[w]`, iterating `w` backward (`W` down to `weight`) guarantees `dp[w - weight]` still holds row `i-1`'s value when computing `dp[w]` (0/1). Iterating `w` forward (`weight` up to `W`) reads the already-updated row `i` value at `dp[w - weight]` (unbounded).

Production Code Example
def knapsack_01(weights: list[int], values: list[int], cap: int) -> int:
    dp = [0] * (cap + 1)
    for w, val in zip(weights, values):
        for c in range(cap, w - 1, -1):  # backward: each item used <= 1 time
            dp[c] = max(dp[c], dp[c - w] + val)
    return dp[cap]
Common Interview Trap / Anti-Pattern:

Reversing loop order blindly in coin-change permutations vs combinations changes what is counted: outer-coins / inner-amount-forward counts unique combinations, while outer-amount / inner-coins counts ordered permutations.

Question #12SeniorSenior

How do Tries and Radix (Compressed) Trees optimize prefix search and IP routing, and what are their memory trade-offs?

Senior Engineering Answer

A Trie stores strings character-by-character along tree edges, supporting O(L) insert, exact lookup, and prefix matching independent of dictionary size N. However, sparse tries allocate a node per character; storing a fixed 26-element array per node wastes huge memory on large Unicode alphabets, while hash-map children trade cache locality for space. A Radix Tree (Patricia Trie) compresses single-child chains into a single edge labeled with the substring (used in Linux routing tables, HTTP routers like Chi/Fastify, and Redis), drastically reducing pointer chasing and heap allocations.

Production Code Example
class TrieNode:
    __slots__ = ("children", "is_end")
    def __init__(self) -> None:
        self.children: dict[str, TrieNode] = {}
        self.is_end = False

class Trie:
    def __init__(self) -> None:
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        cur = self.root
        for ch in word:
            cur = cur.children.setdefault(ch, TrieNode())
        cur.is_end = True
Common Interview Trap / Anti-Pattern:

Building a naive Trie with unbounded per-node dicts over millions of long random strings triggers heavy GC pressure and pointer-chasing cache misses; compact arrays or Radix/DAWG structures are needed at scale.

Question #13PrincipalStaff

Compare Fenwick Trees (Binary Indexed Trees) and Segment Trees for dynamic range queries and range updates.

Senior Engineering Answer

Both answer point-update and range-query in O(log N) time. A Fenwick Tree uses an N+1 flat array exploiting `i & -i` (lowest set bit) to compute prefix sums/XORs with tiny constant factors and half the memory of a Segment Tree—but only works cleanly for invertible associative operations (sum, XOR, frequency counts). A Segment Tree (4N array or iterative 2N bottom-up array) handles non-invertible monoids like range min/max/GCD, custom merged intervals, and supports O(log N) range updates via Lazy Propagation.

Production Code Example
class Fenwick:
    def __init__(self, n: int) -> None:
        self.tree = [0] * (n + 1)

    def add(self, idx: int, delta: int) -> None:  # 1-indexed
        while idx < len(self.tree):
            self.tree[idx] += delta
            idx += idx & -idx

    def prefix_sum(self, idx: int) -> int:
        total = 0
        while idx > 0:
            total += self.tree[idx]
            idx -= idx & -idx
        return total
Common Interview Trap / Anti-Pattern:

Passing a 0-based index directly into Fenwick `idx & -idx` loops infinitely because `0 & 0 == 0`; always convert 0-based API indices to 1-based (`idx + 1`) internally.

Question #14PrincipalStaff

How do KMP and Rabin-Karp achieve linear-time substring matching, and when would you pick each?

Senior Engineering Answer

Naive substring matching degrades to O(N * M) on repetitive patterns like 'aaaaab'. KMP precomputes the Longest Proper Prefix-Suffix (LPS) table of the pattern in O(M) time so on a mismatch, the pattern shifts forward without ever backtracking the text pointer—giving guaranteed worst-case O(N + M) time. Rabin-Karp computes a polynomial rolling hash of the M-character window in O(1) per slide: while single-pattern worst case is O(N * M) on hash collisions, Rabin-Karp shines for multi-pattern search (matching K fixed-length signatures simultaneously against a hash set) and 2D/plagiarism chunk fingerprinting.

Production Code Example
def build_lps(pat: str) -> list[int]:
    lps = [0] * len(pat)
    j = 0
    for i in range(1, len(pat)):
        while j > 0 and pat[i] != pat[j]:
            j = lps[j - 1]
        if pat[i] == pat[j]:
            j += 1
            lps[i] = j
    return lps
Common Interview Trap / Anti-Pattern:

In Rabin-Karp, skipping exact character verification on hash matches (assuming no collisions) causes false positives; use double modular hashing or verify candidate matches explicitly.

Question #15PrincipalStaff

How do Bloom Filters, HyperLogLog, and Count-Min Sketch solve massive-scale streaming queries in bounded memory?

Senior Engineering Answer

When exact sets or maps exceed RAM, probabilistic structures trade bounded error for tiny fixed memory: (1) A Bloom Filter uses an m-bit array and k hash functions for O(1) membership checks with zero false negatives and tunable false positive rate `p ≈ (1 - e^(-kn/m))^k` (used in RocksDB/LSM SSTables to skip disk reads). Standard Bloom filters cannot delete—use Counting or Cuckoo Filters when deletion is needed. (2) HyperLogLog estimates unique cardinality (e.g., daily active users across billions of events) in ~1.5KB with <2% error by tracking leading zeros across hash buckets. (3) Count-Min Sketch estimates heavy-hitter frequencies using d hash rows of width w, returning `min` across rows so counts never underestimate.

Production Code Example
import hashlib

class SimpleBloom:
    def __init__(self, m_bits: int, k: int) -> None:
        self.m = m_bits
        self.k = k
        self.bits = bytearray((m_bits + 7) // 8)

    def _hashes(self, item: bytes):
        h1 = int.from_bytes(hashlib.blake2b(item, digest_size=8).digest(), "little")
        h2 = int.from_bytes(hashlib.sha256(item).digest()[:8], "little")
        for i in range(self.k):
            yield (h1 + i * h2) % self.m  # Kirsch-Mitzenmacher double hashing
Common Interview Trap / Anti-Pattern:

Sizing a Bloom Filter too small causes the bit array to saturate toward all 1s, spiking false positives toward 100%; size `m = -(n * ln(p)) / (ln(2)^2)` for expected capacity `n`.

Question #16PrincipalStaff

Design an O(1) LFU Cache and explain why databases choose B+Trees vs LSM-Trees for disk/SSD workloads.

Senior Engineering Answer

An O(1) LFU Cache combines a `key -> Node` map, a `freq -> DoublyLinkedList` map (for O(1) LRU tie-breaking within each frequency bucket), and a `min_freq` integer. On `get`/`put`, detach the node from `freq`, append to `freq + 1`, and increment `min_freq` only when the old `min_freq` bucket empties; evict from `min_freq`'s tail on capacity overflow. At the storage-engine layer, B+Trees (PostgreSQL, InnoDB) give predictable O(log_B N) read latency via in-place page updates, whereas LSM-Trees (RocksDB, Cassandra) buffer writes in a sorted MemTable and append sequentially to immutable SSTables—delivering huge write throughput at the cost of background compaction and read amplification (mitigated by Bloom Filters).

Production Code Example
from collections import OrderedDict, defaultdict

class LFUCache:
    def __init__(self, capacity: int) -> None:
        self.cap = capacity
        self.vals: dict[int, tuple[int, int]] = {}  # key -> (val, freq)
        self.buckets: dict[int, OrderedDict[int, None]] = defaultdict(OrderedDict)
        self.min_freq = 0

    def _touch(self, key: int) -> int:
        val, f = self.vals[key]
        del self.buckets[f][key]
        if not self.buckets[f] and f == self.min_freq:
            self.min_freq += 1
        self.vals[key] = (val, f + 1)
        self.buckets[f + 1][key] = None
        return val
Common Interview Trap / Anti-Pattern:

In an LFU cache, failing to handle `capacity == 0` or forgetting to reset `min_freq = 1` when inserting a brand-new key causes KeyError or wrong evictions.

Data Structures & Algorithms (DSA) Track Coverage & Difficulty Profile

16 of 16 prompts include code examples

This Data Structures & Algorithms (DSA) preparation set groups 16 prompts across Junior (4), Mid (4), Senior (4), Staff (4) roles with 4 fundamental, 4 intermediate, 4 senior, 4 principal exercises tailored to Computer Science & Languages.

JuniorFundamental

How do hash tables achieve amortized O(1) lookup, and how do separate chaining and open addressing handle collisions?

JuniorFundamental

When does the variable-size Sliding Window pattern apply, and how do you solve Longest Substring Without Repeating Characters in O(N)?

JuniorFundamental

How does Floyd's Tortoise and Hare algorithm detect a cycle AND locate the exact cycle entry node in O(1) space?

JuniorFundamental

How do you write bug-free Binary Search on monotonic predicates (Binary Search on Answer) without off-by-one infinite loops?

MidIntermediate

How do Monotonic Stacks and Monotonic Deques solve Next Greater Element and Sliding Window Maximum in O(N) time?

MidIntermediate

Why is checking only `node.left.val < node.val < node.right.val` insufficient to validate a Binary Search Tree, and how do you compute Lowest Common Ancestor (LCA)?

Frequently Asked Technical Interview Questions (Data Structures & Algorithms (DSA))

Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.

What is the difference between amortized time complexity and worst-case time complexity?
Worst-case complexity bounds the single slowest invocation (e.g., O(N) when a dynamic array doubles and copies). Amortized complexity averages cost across a sequence of operations, proving dynamic array append is O(1) amortized because O(N) resizes happen exponentially rarely.
How do Self-Balancing Binary Search Trees (Red-Black vs AVL) guarantee O(log N) operations?
AVL trees maintain strict height balance (subtree height difference <= 1) via rotations, yielding faster lookups. Red-Black trees enforce looser color invariants (maximum height <= 2 * log2(N + 1)), requiring fewer rotations during heavy insertions and deletions.
When should you use Dijkstra, A*, or Bellman-Ford for shortest paths?
Use Dijkstra with a min-heap for non-negative edge weights in O((V + E) log V). Use A* when an admissible heuristic h(n) can guide search toward a single target. Use Bellman-Ford in O(V * E) when negative edge weights exist or negative cycles must be detected.
What is the difference between Top-Down Memoization and Bottom-Up Tabulation in Dynamic Programming?
Top-down memoization recurses from the goal and caches only reachable subproblems, while bottom-up tabulation fills an iterative table from base cases—eliminating recursion stack overhead and enabling rolling-array space optimization.
Complete Learning Ecosystem

Pair Interview Prep with Cheat Sheets & Roadmaps

Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.

Want to practice other technologies?

Explore our comprehensive technical interview tracks across all core technology stacks.

Browse All Interview Tracks