DSA Interview Questions by Pattern: Arrays, Trees, Graphs and Complexity

Work through four DSA interview patterns: pair sum, level-order traversal, unweighted shortest path and honest complexity analysis. Each trace explains the supporting data structure, time cost and auxiliary space.

KnowledgeGate Team

Exam prep & CS education

Updated 27 Aug 20266 min read

The difficult part of a DSA interview is usually not typing code but recognising which repeated work makes the first solution slow. Array lookup, tree level order, unweighted graph shortest path, and complexity derivation each move from a correct baseline to a measured improvement. A valid optimisation must identify the data structure that removes repeated work and account for both time and auxiliary space. Sorting, recursion, dynamic programming, and backtracking form the next layer in the DSA interview patterns for placements.

1. Start Every DSA Question with Baseline, Bottleneck, Pattern

Map each baseline to its repeated work and the structure that removes it.

Question

Correct baseline

Bottleneck

Useful pattern

Pair sum in an array

Compare every pair

Repeated search for a complement

Hash map

Level-order tree traversal

Rescan the tree for every depth

Upper nodes are revisited

Queue

Unweighted shortest path

Enumerate candidate paths

Repeated states and explosive path count

Adjacency list, queue and visited set

Runtime analysis

Say “one loop”

Nested or repeated work is missed

Count operations, then simplify

Speak through this sequence in an interview: clarify the input and expected output, state a correct baseline, calculate its cost, identify the repeated operation, then choose a structure whose operations remove that repetition. Call the answer optimised only after stating both its time and auxiliary-space costs.

The Coding and DSA learning path provides the sequence around these patterns. A hash map, queue, or any other structure is not universally best. The input constraints and required operations decide whether its trade-off is useful.

2. Array Question: Find Two Values Whose Sum Is 10

Let A = [8, 1, 6, 2, 9, 4], target 10, with zero-based indices. A baseline compares every unordered pair. Six elements have

6 x 5 / 2 = 30 / 2 = 15

possible pairs in the worst case. For this ordering, the nested scan checks (8,1), (8,6), then (8,2). The third comparison succeeds and returns indices (0,3). The worst-case time is O(n^2), while the extra space is O(1).

A hash map avoids searching earlier elements again without changing the input order. At index 0, value 8 needs 2; 2 is absent, so store 8 -> 0. At index 1, value 1 needs 9; store 1 -> 1. At index 2, value 6 needs 4; store 6 -> 2. At index 3, value 2 needs 8. The map contains 8 -> 0, so return (0,3). This takes average O(n) time overall and O(n) auxiliary space. The average qualifier matters because hash-table operations are not an unconditional worst-case constant-time guarantee.

For A = [5, 5] and target 10, look for the complement before inserting the current value. The second 5 then finds index 0, producing two distinct indices. Empty and one-element arrays have no solution.

Hash-map trace for the array [8, 1, 6, 2, 9, 4] with target 10, ending in a match on indices 0 and 3.

3. Tree Question: Return Nodes Level by Level

Use one binary search tree: root 8; 8 has children 3 and 10; 3 has children 1 and 6; 10 has right child 14; 6 has children 4 and 7; and 14 has left child 13. Its level-order output is [[8], [3,10], [1,6,14], [4,7,13]].

A repeated-depth baseline calls printLevel(root, d) for every depth d. It revisits upper nodes and can reach O(n^2) time when a tree is skewed into n levels. A queue instead makes one pass. Start with [8]. After 8, it is [3,10]; after 3, [10,1,6]; after 10, [1,6,14]. Processing 1 leaves [6,14]; after 6, it is [14,4,7]; after 14, [4,7,13]; and it becomes empty after processing the last three nodes.

All 9 nodes enter and leave the queue once, so time is O(n). Auxiliary space is O(w) for maximum width w; here the largest level has 3 nodes. Recursive DFS uses O(h) stack space, but it does not naturally preserve level order because it follows a branch before its peers.

4. Graph Question: Find an Unweighted Shortest Path from A to F

Take vertices {A,B,C,D,E,F} and undirected edges {A-B, A-C, B-D, C-D, C-E, D-F, E-F}. Enumerating all simple paths is a correct baseline idea, but it branches unnecessarily. Breadth-first search works because every edge has equal cost.

Fix neighbours in alphabetical order. Begin with queue [A] and visited set {A}. Pop A, then enqueue B and C, recording B <- A and C <- A. Pop B and enqueue D, recording D <- B. Pop C, skip already visited D, and enqueue E. Pop D and enqueue F, recording F <- D. The complete parent chain gives A -> B -> D -> F, a path of 3 edges. A -> C -> E -> F also has length 3, so the first returned route need not be unique, but BFS still guarantees the true minimum edge count.

Each structure has one job. The adjacency list stores neighbours. The FIFO queue expands distance 0 before 1, then 2. The visited set prevents cycles and repeat enqueues. The parent map reconstructs the route. The result is O(V+E) time and O(V) auxiliary space. See BFS, DFS and shortest-path patterns for the wider comparison.

Six-vertex undirected graph with the BFS shortest path from A to B to D to F highlighted and distance labels.

5. Derive Complexity from the Work, Not from the Algorithm Name

Start with exact work, then keep the fastest-growing term. Pair enumeration has n(n-1)/2 = (n^2-n)/2 candidates. Dropping the constant factor and lower-order term leaves quadratic growth. The worked hash scan performs four complement lookups before success, with at most n iterations. The tree queue processes 9 nodes once. The graph has 6 vertices and 7 undirected edges, so its adjacency list contains 2 x 7 = 14 entries; BFS processes each vertex and inspects those 14 entries once.

Approach

Time

Auxiliary space

Nested pair scan

O(n^2)

O(1)

Hash-map pair sum

Average O(n)

O(n)

Tree level order

O(n)

O(w)

Adjacency-list BFS

O(V+E)

O(V)

Representation can change the count. With an adjacency matrix, BFS scans a row of V possible neighbours for each reached vertex, giving O(V^2) time even for a sparse graph. A recursive traversal of a skewed tree still takes O(n) time but can consume O(n) call-stack space. For another operation-by-operation comparison, review the sorting algorithms and complexity trade-offs.

6. Follow-ups and Traps That Change an Otherwise Correct Answer

For the array problem, duplicates still require distinct indices, and returning values is not the same contract as returning indices. If the input is already sorted, two pointers can solve pair sum with O(1) extra space. Sorting an unsorted input first costs O(n log n) and changes the original indices unless a copy and original-position data are handled.

An ordinary tree needs no visited set because each node has one path from the root. Add one only if the input may contain parent links or cycles. The undirected graph does require it. Mark a vertex visited when enqueuing, not when dequeuing, so D is not queued once from B and again from C.

Communication errors also weaken a correct algorithm. State the brute-force solution before the improvement, name the extra-space trade-off, and distinguish balanced-tree height from a skewed worst case. Finally, BFS guarantees a minimum-edge path here because all edges have equal cost. It does not generally find a minimum-weight path when edge weights differ.

7. Short Version and the Next Practice Step

  • Arrays often replace repeated search with hashing or, for ordered input, two pointers.

  • Level-order tree traversal needs a queue.

  • Unweighted shortest paths need BFS with visited and parent state.

  • Complexity comes from counting the actual repeated operations.

Rehearse once without code: explain the array baseline and improvement aloud in 90 seconds, redraw the tree queue states without notes, then reproduce the graph parent map and all four time and space bounds. Your goal is to explain why each structure is present, not merely recite a solution.

For interview-focused practice, continue with DSA Using Java. Coding for Placements is the broader option when you want multi-language placement preparation alongside DSA.