Your GPS before writing a single line of code
Imagine you're lost in a city and need to get somewhere fast. You wouldn't just start running in a random direction — you'd look at a map first, find your location, figure out the fastest route, and then move. DSA interviews are the same. Big-O complexity is your map. The constraint in the problem statement (n ≤ 10⁵) tells you exactly which "road" you're allowed to take before you've solved anything.
🧭 The navigator's reflex: Before writing any code, read
n. If n ≤ 10⁵ and time limit is 1 second, an O(n²) solution would need ~10¹⁰ operations — roughly 100 seconds. That's impossible. Your map says: take the O(n log n) road. This single reflex separates strong candidates from everyone else.
What SDE2 DSA actually tests
Not "do you know the trick" — it's: can you recognize the pattern, state the complexity, write clean code, handle edge cases, and communicate while doing it. Talk through the brute force, name the bottleneck, then optimize. A working O(n log n) you can explain beats a buggy O(n) you can't.
Big-O complexity: cheat sheet
| Complexity | Name | Typical source | Example |
|---|---|---|---|
| O(1) | constant | hash lookup, array index | dict[key], arr[i] |
| O(log n) | logarithmic | binary search, balanced tree, heap push/pop | Binary search on sorted array |
| O(n) | linear | single pass, two pointers | Finding max in array |
| O(n log n) | linearithmic | sorting, heap-based, divide & conquer | Merge sort, heap sort |
| O(n²) | quadratic | nested loops, naive pair comparison | Bubble sort, brute-force pairs |
| O(2ⁿ) | exponential | subsets, naive recursion without memo | All subsets of array |
| O(n!) | factorial | permutations | All arrangements of n items |
The input-size → complexity trick
The constraint tells you the target complexity before you've solved anything:
| n up to | Likely target | Example algorithm |
|---|---|---|
| ≤ 10–12 | O(n!) / O(2ⁿ) — backtracking/brute force is fine | All permutations |
| ≤ 20–25 | O(2ⁿ) bitmask DP | Bitmask DP over subsets |
| ≤ 500 | O(n³) | Floyd-Warshall |
| ≤ 5,000 | O(n²) | O(n²) DP |
| ≤ 10⁶ | O(n) or O(n log n) | Sorting, BFS, sliding window |
| ≥ 10⁸ | O(log n) or O(1) | Binary search, hash lookup |
"n is up to 10⁵, so an O(n²) ~10¹⁰ won't pass — I need O(n log n) or better." Saying this signals maturity and narrows your options immediately.
Pattern recognition — signal → technique
| If you see… | Reach for | Why |
|---|---|---|
| contiguous subarray/substring, "longest/at most K" | Sliding window | Grow/shrink a range without re-scanning |
| sorted array, pair/triplet summing to target | Two pointers | Move inward from both ends |
| "search space", "minimum X that works", monotonic | Binary search (on answer) | Feasibility flips once → binary search the threshold |
| grid/graph, shortest path (unweighted), levels | BFS | Level-by-level = shortest unweighted path |
| connectivity, all paths, cycles, components | DFS / Union-Find | Explore all neighbors recursively or track groups |
| "number of ways", "min/max cost", overlapping subproblems | DP | Sub-questions repeat → answer each once |
| top/smallest K, streaming median, merge K lists | Heap | Always O(log k) access to current best |
| all combinations/permutations/subsets | Backtracking | Choose → explore → un-choose |
| next greater/smaller, matching brackets | Monotonic stack | LIFO matches nesting and recency |
| prefix aggregates, range sum | Prefix sums | Precompute sums so any range is O(1) |
How to communicate while coding
- Restate the problem + ask about edge cases (empty, duplicates, negatives, overflow).
- State brute force + its complexity.
- Name the bottleneck and the pattern that removes it.
- Code, narrating invariants.
- Dry-run a small example; then state final time/space.
Complexity examples in code
# O(n) — single pass, two-pointer style
def two_sum_sorted(arr, target):
left, right = 0, len(arr) - 1
while left < right:
s = arr[left] + arr[right]
if s == target:
return [left, right]
elif s < target:
left += 1
else:
right -= 1
return []
# O(n log n) — sort then linear scan
def contains_duplicate(nums):
nums.sort() # O(n log n)
for i in range(len(nums) - 1): # O(n)
if nums[i] == nums[i + 1]:
return True
return False
// O(n) — hash map lookup
import java.util.HashMap;
public class TwoSum {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> seen = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (seen.containsKey(complement)) {
return new int[]{seen.get(complement), i};
}
seen.put(nums[i], i);
}
return new int[]{}; // guaranteed to have solution
}
}
// O(n log n) — sort + binary search
#include <vector>
#include <algorithm>
using namespace std;
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end()); // O(n log n)
for (int i = 0; i + 1 < (int)nums.size(); i++) {
if (nums[i] == nums[i + 1]) return true;
}
return false;
}
Think it through
Before solving anything, interviewers expect two instant reflexes: read the complexity of code you're looking at, and read the target complexity off the constraints. Practise both before revealing.
PROBLEMTwo quick judgments. (a) What's the time complexity of a loop where, for each i, you compare a[i] against every LATER element j? (b) If the problem says n ≤ 10⁵ with a 1-second limit, what complexity must your final solution hit?
- 1
Count the work (part a)
“The inner loop shrinks each time — how many comparisons total?”
- 2
Read the constraint backwards (part b)
“Rule of thumb: ~10⁸ simple operations per second. Plug in n = 10⁵.”
unlocks after the stage above - 3
From target to technique
“You must drop from O(n²) to O(n log n) / O(n). What does that point you toward?”
unlocks after the stage above - 4
Say it out loud
“What's the sentence that earns marks before you write code?”
unlocks after the stage above - 5
The takeaway
“Why is this a reflex worth drilling?”
unlocks after the stage above
Practice — climb the ladder
Climb in order — every rung assumes the one above it. Solve on LeetCode, then tick it here; progress is saved on this device.
Foundation
read complexity from codeHash set O(n) vs sort O(n log n) — understand the trade-off.
- Two SumEasy
Classic O(n²) → O(n) via hash map upgrade.
Pattern recognition
map clues to techniquesOne pass, track running min — O(n) vs O(n²) brute force.
- Valid AnagramEasy
Count arrays or sorting — two O(n log n) vs O(n) approaches.
Prefix + suffix passes — O(n) time O(1) space (beyond output).
Constraint reading
use n to pick your algorithmO(n) set-based vs O(n log n) sort — constraints demand O(n).
Check yourself — pattern recognition speed test
1. n = 5,000. Which complexity classes are feasible (< 1 second)?
2. A problem says 'return all subsets'. What complexity do you expect?
3. You see: 'Find the longest contiguous subarray with sum ≤ K'. Which pattern?
4. What's the 'talking out loud' sentence to say when you see n ≤ 10⁵?