Back to guide home
Algorithm Patterns

Recognise the pattern before choosing blocks

Many problems change the story but keep the same core pattern. Ask what the problem wants, then decide what state to maintain.

Starter scans

Threshold count

Look for questions like “how many values are above 50” or “how many days are below the limit”. Scan once and increase a counter whenever the condition is true.

Maximum / minimum

When the task asks for the highest score, lowest reading, or best difference, keep the current best value while scanning and update it when a better value appears.

Any / all checks

Questions that ask “does any item fail” or “do all items pass” usually need a boolean flag. Flip the flag as soon as the important case is found.

Consecutive run

Words like “consecutive”, “longest streak”, or “in a row” are the signal. Track the current streak, reset it when broken, and keep the best streak seen so far.

Intermediate structures

Prefix sums

If the problem repeatedly asks for totals over ranges, precompute the total up to each position. A range answer can then be found by subtracting two prefix values.

Sorting + greedy

For scheduling, choosing the most tasks, or allocating resources, sorting often reveals the natural order. Then make the best local choice without blocking later choices.

Two pointers

Use this when values are sorted, paired, deduplicated, or checked from both ends. Move one pointer at a time based on the current sum, distance, or comparison.

Interval merge

Start/end times, coverage ranges, and bookings are interval clues. Sort by start point, merge overlapping intervals, and start a new interval when there is a gap.

Advanced algorithms

BFS shortest path

When every move has the same cost, such as grid movement or one-step state changes, expand with a queue level by level. The first time you reach the target is usually shortest.

Topological sort

Prerequisites, task dependencies, and “A must happen before B” point to a directed graph. Repeatedly remove nodes with no remaining prerequisites to detect a valid order or a cycle.

Dynamic programming

Use DP when a large answer can be built from smaller positions, days, capacities, or states. Define what each state means, then write how earlier states produce later ones.

Binary search answer

If feasibility is monotonic, such as more time making a task easier or larger capacity making a plan possible, guess an answer and shrink the range by checking it.

Practise in the problem bank