HackerRank problems look diverse on the surface, but most of them use the same underlying patterns. Learn to recognise which pattern applies, and the solution becomes straightforward.
Pattern 1: Hash Map Lookup
When to use: "Find pairs," "count occurrences," "check for duplicates."
Build a frequency map or a lookup table. O(n) time instead of O(n²).
Pattern 2: Sliding Window
When to use: "Maximum/minimum sum of subarray," "longest substring with K distinct characters."
def max_subarray_sum(arr, k):
window = sum(arr[:k])
best = window
for i in range(k, len(arr)):
window += arr[i] - arr[i - k]
best = max(best, window)
return best
Pattern 3: Two Pointers
When to use: Sorted array problems, "pair with target sum," "remove duplicates."
Start from both ends, move inward based on the comparison.
Pattern 4: BFS/DFS (Graph Traversal)
When to use: "Shortest path," "connected components," "flood fill," anything on a grid or tree.
BFS for shortest path (use a queue). DFS for exhaustive search (use recursion or a stack).
Pattern 5: Dynamic Programming
When to use: "Count ways," "minimum cost," "longest/shortest" with overlapping subproblems.
Identify the state, write the recurrence, memoise or tabulate.
Pattern 6: Greedy
When to use: "Minimum number of X to cover Y," interval scheduling, making change.
Sort by the right criterion, then take the locally optimal choice at each step.
Pattern 7: Sorting as Preprocessing
When to use: Problems that become trivial after sorting — "find the closest pair," "merge intervals," "find the median."
The Recognition Strategy
- Read the problem. What's the input shape? (Array, string, graph, tree?)
- What's being asked? (Count, find, optimise, check?)
- Match to a pattern from the list above.
- Implement the pattern with the problem's specific constraints.
Practice 3-5 problems per pattern, and you'll recognise them instantly in interviews.
Want pattern recognition during live challenges? CodeSage Pro identifies the optimal approach in real-time.