01What are the six steps to attack a new problem?
Restate it, try small examples by hand, write the brute force, find the waste, code it, then dry run it.
02A problem allows n up to 100,000. Can an O(n²) answer pass?
No. That is about 10¹⁰ steps, and only about 10⁸ fit in one second. Aim for O(n log n) or better.
Many wrong answers in interviews come from good code that solves the wrong problem. The statement is short, but almost every word in it is a rule.
This lesson gives you one way to read any statement, so you know what to build before you write a line of code.
Mark the words that matter
Here is a real problem from the A2Z sheet, Second Largest Element. Read it slowly, and underline every word that changes what you must build.
┌───────────────────────────────────────────────┐ │ │ │ Given nums, return the second largest │ │ ──────┬─────── │ │ 1 │ │ value. If it does not exist, return -1. │ │ ──┬── ──────┬─────── ────┬──── │ │ 2 3 4 │ │ 1 <= n <= 10^5 -10^4 <= nums[i] <= 10^4 │ │ ──────┬─────── ───────────┬──────────── │ │ 5 6 │ │ nums may contain duplicates. │ │ ─────────────┬───────────── │ │ 7 │ │ │ └───────────────────────────────────────────────┘
- Second largest. The maximum is not enough. You need the next value below it.
- Value. Return a number from the array, not its position.
- Does not exist. The answer can be missing. Find out when.
- Return -1. The value that means "no answer".
- n can be 1. One item has no second largest. And n up to 10⁵ means O(n log n) or faster.
- Negative values. Any trick that assumes positive numbers will break.
- Duplicates. In
[8, 8, 7]the answer is 7, not 8.
Marks 3, 5 and 7 together answer "when does it not exist?": when the array has one item, or every item is the same.
The six-part read
Every statement, short or long, has the same six parts. Find each one before you think about a solution.
| Part | Ask yourself | Second Largest |
|---|---|---|
| Input | What do I get? | an array of integers |
| Output | What do I return? | one value, or -1 |
| Rules | What must hold? | below the max, duplicates count once |
| Examples | Do I get them by hand? | [8, 8, 7, 6, 5] gives 7 |
| Limits | How big? How small? | n up to 10⁵, values from -10⁴ to 10⁴ |
| Edge cases | What do the examples skip? | one item, all equal, negatives |
Then write the result down in your own words. In this course it becomes a problem card:
8 is the largest. The next smaller value is 7.
Only one distinct value, so there is no second largest.
- 1 ≤ n ≤ 10⁵
- −10⁴ ≤ nums[i] ≤ 10⁴
- duplicates allowed
Which pattern? Decide first, then open.
“second largest”track the top two values in one pass
“if it does not exist, return -1”edge cases: one item, or all items equal
pattern: Linear scan
The "it asks" line is the test. If you cannot say the problem in one plain sentence, read it again. Do not start coding yet.
Make your own examples
The given examples show the normal case. Bugs hide in the cases they skip. Write 4 to 6 small inputs of your own, each one chosen for a reason.
| Input | Expected | Why this one |
|---|---|---|
[8, 8, 7, 6, 5] | 7 | the given example |
[5] | -1 | the smallest n |
[3, 9] | 3 | the smallest normal case |
[1, 7, 7, 5] | 5 | the largest value repeats |
[-2, -4, -9, -6] | -4 | all values negative |
Write the expected answer before you write code. Then the code has something to be checked against.
Dry run before you code
A common first idea: keep largest and second, and start second at -1, the "no answer" value. Walk the all-negative example through it by hand.
1/8Start largest at the first item, -2, and second at -1.
The start value -1 was bigger than every real value, so nothing could ever replace it. Mark 6 in the statement warned about this. Your own example caught it, before any code ran.
The fixed version:
int secondLargest(int[] nums) {
int largest = Integer.MIN_VALUE; // the biggest value so far
int second = Integer.MIN_VALUE; // the biggest value below largest
for (int x : nums) {
if (x > largest) {
second = largest;
largest = x;
} else if (x < largest && x > second) {
second = x;
}
}
return second == Integer.MIN_VALUE ? -1 : second;
}- A new maximum pushes the old one down to
second. x < largestskips copies of the maximum, so[8, 8, 7]gives 7.- If
secondnever moved, no second value exists, so return -1. - Both start below every real value:
-Infinityin TypeScript,float("-inf")in Python. Java'sinthas no infinity, so it usesInteger.MIN_VALUE. That is safe here, because no value goes below -10⁴.
It returns the expected answer for all five inputs in the table. One pass, so O(n) time and O(1) extra space.
Edge cases and questions
The edge-case checklist
Run down this list for every problem. Most bugs in interviews come from one of these rows.
| Case | Example | What it breaks |
|---|---|---|
| Smallest input | [] or [5] | reading nums[1], "no answer" |
| All the same | [4, 4, 4] | logic that assumes two distinct values |
| Duplicates | [8, 8, 7] | counting a copy as a new value |
| Negatives and zero | [-2, -4], [0] | start values like 0 or -1 |
| Sorted either way | [1, 2, 3], [3, 2, 1] | a branch that runs every time, or never |
| Largest values | values near 10⁹ | sums that overflow (next lesson) |
Ask before you code
In an interview, the statement is often vaguer than on a sheet. Ask, and say your assumption out loud.
- Size: can the input be empty? How large can n get?
- Values: can they be negative? Can they repeat?
- Output: a value or an index? In what order?
- No answer: what should I return? Here, -1 can also be a real answer, as in
[5, -1]. Is that fine? - Meaning: in
[8, 8, 7], is the second largest 8 or 7? - Input: may I change or sort the array in place? If not, work on a copy.
Each answer removes a guess. Interviewers notice when you ask.
Practice the read: Two Sum
Try the six-part read on the most asked interview problem. Fill in the table yourself first, then compare.
| Part | Two Sum |
|---|---|
| Input | an array nums and a number target |
| Output | the indices of two items, in any order |
| Rules | exactly one answer; the same item cannot be used twice |
| Examples | [1, 6, 2, 10, 3], target 7, gives [0, 1] |
| Limits | n up to 10⁵, so O(n log n) or faster |
| Edge cases | negatives, target 0, a pair of equal values such as [3, 3] |
Two words in that table change the solution:
- Indices. Sorting the array loses the original positions. A sort-based idea must remember them.
- Not twice. With
[3, 2, 4]and target 6,3 + 3is not allowed. The answer is[1, 2].
You meet Two Sum again in the Moderate part. You already know its traps.
Words that point to a pattern
Some words in a statement hint at the pattern before you think. Learn these pairs; every later lesson adds more.
| The statement says | Try first |
|---|---|
| "sorted array" | binary search, two pointers |
| "pair or triplet with sum" | a hash map, or sort and two pointers |
| "subarray" or "substring" | sliding window, prefix sums |
| "all subsets", "all combinations" | recursion and backtracking |
| "k largest", "k closest" | a heap |
| "next greater element" | a monotonic stack |
| "shortest path in a grid" | breadth-first search |
| "number of ways", "minimum cost" | dynamic programming |
These are first guesses, not rules. The limits are the other half of the signal, and they are the next lesson's topic. The pattern recognition chapter puts both together.
- 01
Read every statement for six parts: input, output, rules, examples, limits and edge cases.
- 02
Underline the words that change the code: value or index, distinct, negative, does not exist.
- 03
Write your own small examples and their answers before the code, then dry run your idea on them.
- 04
Ask about size, values, output, the "no answer" case, and whether you may change the input.
Read more
- Second Largest Element on takeUforward, the full statement to practise on
- Coding interview techniques from the Tech Interview Handbook, on finding an approach and then a faster one
- Coding interview cheatsheet, with what to clarify before you code and what to test after
Next: constraints decide the approach. The largest n tells you which Big O can pass, before you think of an idea.