ayushsalampuriya.xyz Revise

DSA · Foundations

How to Approach Any DSA Question

A simple 5-step flow you can use in practice and in interviews. Follow the same steps every time so you do not have to guess what to do next.

Simple summary: Clarify the problem, explain a basic solution, find a useful pattern, write the improved solution, and test it out loud. Example: For Two Sum on [2, 7, 11, 15] with target 9, start with nested loops (O(n²)), then switch to a hash map that stores each value seen so far (O(n)).

1. Understand the problem (2 minutes)

Read the question twice. Describe the input and expected output in your own words.

Example — Two Sum:

Write one or two small examples, including an edge case such as an empty array or an array with only two elements.

2. Brute force first (3 minutes)

Start with the slow but obvious solution. Once it is correct, you have a clear baseline to improve.

Two Sum brute force: for i in 0..n-1: for j in i+1..n-1: if nums[i] + nums[j] == target: return [i, j] Time: O(n²) Space: O(1)

Tell the interviewer: "This works. Now I want to remove the inner loop."

3. Find the pattern (5 minutes)

Ask: What am I searching for repeatedly?

If you see…Try…
Sorted array + pair/tripletTwo pointers
Subarray / substring with a limitSliding window
"Find if exists" / count / complementHash map
Sorted data + searchBinary search
Tree / graph traversalBFS or DFS
Many overlapping subproblemsDynamic programming

For Two Sum, at index i we need target - nums[i]. A hash map stores the values already visited.

4. Optimize and code (10 minutes)

Two Sum optimized: map = {} for i, num in enumerate(nums): need = target - num if need in map: return [map[need], i] map[num] = i Time: O(n) Space: O(n)

Use clear names. State what happens when no valid answer exists.

5. Test out loud (2 minutes)

  1. Normal: [2,7,11,15], target=9[0,1]
  2. Two elements: [3,3], target=6[0,1]
  3. No solution (if allowed): return empty or -1 — state what you chose

One more worked example — maximum value

Given [4, 1, 9, 3], return the largest value. Brute force is already optimal: inspect each item once while keeping the largest value seen so far. First confirm that the input is non-empty.

largest = nums[0] for num in nums[1:]: largest = max(largest, num) return largest Time: O(n) Space: O(1)

You cannot do better than O(n), because an unseen element could be the largest.

What interviewers watch for

Quick revision

  • 1. Understand — input, output, edge cases, examples.
  • 2. Brute force — prove you can solve it.
  • 3. Pattern — hash map, two pointers, window, BFS/DFS, DP.
  • 4. Code optimized solution + state the complexity.
  • 5. Test — normal, small, edge.