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.
[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:
- Input: array of numbers + target number
- Output: indices of two numbers that add up to target
- Can the same element be used twice? No.
- Is there exactly one answer? Ask the interviewer or read the constraint.
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.
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/triplet | Two pointers |
| Subarray / substring with a limit | Sliding window |
| "Find if exists" / count / complement | Hash map |
| Sorted data + search | Binary search |
| Tree / graph traversal | BFS or DFS |
| Many overlapping subproblems | Dynamic 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)
Use clear names. State what happens when no valid answer exists.
5. Test out loud (2 minutes)
- Normal:
[2,7,11,15], target=9→[0,1] - Two elements:
[3,3], target=6→[0,1] - 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.
You cannot do better than O(n), because an unseen element could be the largest.
What interviewers watch for
- You clarify before coding, not after you get stuck
- You explain trade-offs (time vs space)
- You test with an example, not "looks fine"
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.