How to Attack a New Problem

Six steps

  1. Understand. Read twice. Work the example by hand. What exactly is the input and the output?
  2. Size it up. Look at the limits. About 100 million simple steps per second is a good guide (see the table below).
  3. Brute force first. What's the simplest correct idea, even if slow? Write it down in words.
  4. Find the waste. Where does the brute force repeat work? That points to the tool: sorting, a HashMap, two pointers, a heap, BFS, DP…
  5. Code it cleanly. Small methods, clear names, long for big totals.
  6. Test the edges. n = 1, all equal, already sorted, negative numbers, nothing found.
Biggest nAim for
≤ 10O(n!) or O(2ⁿ) – backtracking is fine
≤ 20O(2ⁿ)
≤ 500O(n³)
≤ 5,000O(n²)
≤ 1,000,000O(n log n) or O(n)
huge (10⁹+)O(log n) or O(1) – a formula or binary search

Spot the pattern from the words

The problem says…Think about…
“sorted”binary search, two pointers
“in a row”, “subarray”, “substring”sliding window, prefix sums
“have we seen”, “count”, “pair that sums to”HashSet / HashMap
“next greater”, “matching brackets”, “undo”stack
“k largest”, “closest k”, “always the smallest next”heap / PriorityQueue
“fewest steps”, “nearest”BFS
“shortest distance” with lengthsDijkstra
“all ways”, “every arrangement”backtracking
“number of ways”, “best total” with overlapping choicesdynamic programming

Think of it like this: A doctor doesn't try every medicine: they check the symptoms first. The words in a problem are its symptoms.

Common mistake: Starting to type before you understand the problem. Five minutes with pen and paper saves thirty minutes of debugging.

What next?

You now know the core of DSA in Java. Keep practising: re-solve these challenges without looking, then try problems on sites like LeetCode or HackerRank, filtering by topic. Speed comes from recognising patterns – and that comes from practice.

HOME LABS COMMUNITY DASHBOARD