Read a problem statement

Turn a wall of text into input, output, rules and edge cases, and ask the right questions before you code.

Pattern: Problem solving25 min read
Quick recall2 questions
  1. 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.

  2. 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.

Each number marks a phrase that changes the code. The list below explains each one.
  1. Second largest. The maximum is not enough. You need the next value below it.
  2. Value. Return a number from the array, not its position.
  3. Does not exist. The answer can be missing. Find out when.
  4. Return -1. The value that means "no answer".
  5. n can be 1. One item has no second largest. And n up to 10⁵ means O(n log n) or faster.
  6. Negative values. Any trick that assumes positive numbers will break.
  7. 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.

PartAsk yourselfSecond Largest
InputWhat do I get?an array of integers
OutputWhat do I return?one value, or -1
RulesWhat must hold?below the max, duplicates count once
ExamplesDo I get them by hand?[8, 8, 7, 6, 5] gives 7
LimitsHow big? How small?n up to 10⁵, values from -10⁴ to 10⁴
Edge casesWhat 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:

Problem: Second Largest Elementn ≤ 10⁵
it asks
Return the largest value that is smaller than the maximum. If no such value exists, return -1.
example 1
in nums = [8, 8, 7, 6, 5] out 7

8 is the largest. The next smaller value is 7.

example 2
in nums = [10, 10, 10, 10, 10] out -1

Only one distinct value, so there is no second largest.

limits
  • 1 ≤ n ≤ 10⁵
  • −10⁴ ≤ nums[i] ≤ 10⁴
  • duplicates allowed
budget
About 10⁸ steps run in one second. With n up to 10⁵, aim for O(n log n) or faster.
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.

InputExpectedWhy this one
[8, 8, 7, 6, 5]7the given example
[5]-1the smallest n
[3, 9]3the smallest normal case
[1, 7, 7, 5]5the largest value repeats
[-2, -4, -9, -6]-4all 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.

top two values, start second at -1
-2
0
-4
1
-9
2
-6
3
largest, second{-2-1}

1/8Start largest at the first item, -2, and second at -1.

The same idea twice. Only the starting value of second changes.

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 < largest skips copies of the maximum, so [8, 8, 7] gives 7.
  • If second never moved, no second value exists, so return -1.
  • Both start below every real value: -Infinity in TypeScript, float("-inf") in Python. Java's int has no infinity, so it uses Integer.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.

CaseExampleWhat 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 valuesvalues 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.

PartTwo Sum
Inputan array nums and a number target
Outputthe indices of two items, in any order
Rulesexactly one answer; the same item cannot be used twice
Examples[1, 6, 2, 10, 3], target 7, gives [0, 1]
Limitsn up to 10⁵, so O(n log n) or faster
Edge casesnegatives, 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 + 3 is 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 saysTry 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.

take U forwardYouTube
Second Largest Element: Striver's A2Z DSA Course
Remember4 points
  1. 01

    Read every statement for six parts: input, output, rules, examples, limits and edge cases.

  2. 02

    Underline the words that change the code: value or index, distinct, negative, does not exist.

  3. 03

    Write your own small examples and their answers before the code, then dry run your idea on them.

  4. 04

    Ask about size, values, output, the "no answer" case, and whether you may change the input.

Read more

Next: constraints decide the approach. The largest n tells you which Big O can pass, before you think of an idea.

Practice

Solve these on the sheet after the lesson. Try each one for 20 minutes before you open its solution.

Striver's A2Z sheet0/2 solved
Open the sheet