cswork / patternsOpen the problem list

PATTERN FINDER · DECISION TREE

Not sure which pattern a problem needs? Answer yes or no.

Start with the shape of the input, then what the problem asks for. A few answers later you reach one of the 35 stops on Ling’s Curated 500: why it fits, its problems and a tutorial. It is a first guess, not a rule; some problems mix two patterns.

See all 39 questions
  1. Q01 Are you asked to build a class whose methods get called over and over?

    e.g. an LRU cache, a min stack, an iterator

  2. Q02 Do you need fast lookups by key or by timestamp, or must you keep up with a stream of incoming values (caches, snapshots, a running median, the k-th largest)?

    e.g. LRU Cache, Insert Delete GetRandom O(1), Time Based Key-Value Store, Find Median from Data Stream

    Yes

    Stop 33: Caches

    A hash map finds things in O(1) and a doubly linked list or swap-with-last removes them in O(1); look up by time with binary search over a sorted list, and keep a running median or the k-th largest in heaps.

  3. Q03 Do the operations revolve around string prefixes or file paths, or turning a structure into a string and back?

    e.g. a trie, an in-memory file system, serializing a binary tree

    Yes

    Stop 34: Trie & Codec

    Adding one node per character or path segment gives you a trie; when serializing, write out empty children too so decoding is unambiguous.

    No

    Stop 32: Iterators

    Assemble the interface from stacks, queues, arrays and lists; what matters is amortized cost and the empty and full edge cases.

  4. Q04 Does the input describe what connects to what: a tree, a graph, a grid, or “A depends on B”?

    you get a root, an edge list, an adjacency list, or a 2D board

  5. Q05 Is it a binary tree (you get a root, and each node has at most two children)?

    the node type is TreeNode

  6. Q06 Is it a binary search tree whose left-smaller, right-larger order you can use?

    e.g. Kth Smallest Element in a BST, Validate Binary Search Tree

    Yes

    Stop 13: BST

    An in-order walk of a BST is sorted, and search, insert and k-th smallest each follow a single path down.

  7. Q07 Do you build the tree from traversal orders, or reshape it into something else?

    e.g. Construct Binary Tree from Preorder and Inorder Traversal, Flatten Binary Tree to Linked List

    Yes

    Stop 12: Tree Building

    Preorder (or postorder) gives the root and inorder splits the subtrees, then recurse; when reshaping, decide where each node's pointers should end up first.

  8. Q08 Is the answer about paths: root to leaf, path sums, the lowest common ancestor, the best path between any two nodes?

    e.g. Path Sum III, Binary Tree Maximum Path Sum

    Yes

    Stop 11: Tree Paths

    Pass the current path's state down, return the subtree's best result up, and update the answer at the node where the two meet.

  9. Q09 Does every node make a take-or-skip choice that constrains its parent and children?

    e.g. House Robber III

    Yes

    Stop 31: Tree & Game DP

    Walk post-order and have each node return two values, with it and without it; the parent combines them. That is tree DP.

    No

    Stop 10: Tree Traversal

    Choose pre-, in-, post- or level-order, then decide what the recursive call returns; most problems are a single traversal.

  10. Q10 On a board or character grid, do you try placing values or tracing a path, and undo the move when it fails?

    e.g. Word Search, Word Search II, Sudoku Solver

    Yes

    Stop 21: Pruning

    Mark the cell before recursing and restore it when the branch fails, then try the next direction or digit; track what each row, column and box already uses in sets or bitmasks so you prune early.

  11. Q11 Is it a 2D grid where each cell touches only its four neighbours?

    e.g. Number of Islands, Rotting Oranges, Unique Paths

  12. Q12 Does each cell's answer depend only on the cells above and to its left (say you may only move right or down)?

    e.g. Unique Paths, Minimum Path Sum, Maximal Square

    Yes

    Stop 23: Grid DP

    dp[i][j] comes from the cell above and the cell to the left; fill row by row, and one row of memory is usually enough.

    No

    Stop 14: Grid Search

    Count regions by flooding each one with DFS or BFS; for fewest steps or things spreading at once, run (multi-source) BFS layer by layer.

  13. Q13 Do the edges mean “must come before”, and you need a valid order or need to detect a cycle?

    e.g. Course Schedule, Alien Dictionary

    Yes

    Stop 16: Topo Sort

    Repeatedly remove nodes with in-degree 0 (Kahn's algorithm); if some never come out, there is a cycle.

  14. Q14 Do you need the fewest steps or the lowest cost from a start to a target?

    e.g. Word Ladder, Network Delay Time, Cheapest Flights Within K Stops

    Yes

    Stop 17: Shortest Paths

    Equal edge weights mean BFS; non-negative weights mean Dijkstra. A state can be “position plus extra info”, such as stops left.

  15. Q15 Must you pick edges that connect every node at the lowest total cost?

    e.g. Min Cost to Connect All Points

    Yes

    Stop 18: Spanning Trees

    Sort edges by cost and add each one that joins two separate components, tracked with union-find (Kruskal); Prim suits dense graphs.

    No

    Stop 15: Union-Find

    When you only care who is connected, how many components there are, or edges arrive one at a time, use union-find; a single DFS often works too.

  16. Q16 Is the input a linked list?

    e.g. Reverse Linked List, Linked List Cycle, Remove Nth Node From End of List

    Yes

    Stop 09: Linked Lists

    A dummy head removes special cases, fast and slow pointers find the middle and cycles, and three pointers reverse in place. That covers nearly every list problem.

  17. Q17 Must you list every valid solution (subsets, permutations, combinations), not just count them?

    e.g. Subsets, Permutations, Combination Sum; picking two or three numbers that hit a target (3Sum) is a no

  18. Q18 Are you cutting a string into pieces, or assembling valid strings?

    e.g. Generate Parentheses, Palindrome Partitioning, Restore IP Addresses

    Yes

    Stop 20: Partitioning

    At each step choose how long the next piece is, and recurse only if that piece is valid.

  19. Q19 Are there many constraints, so you must prune as you search, like placing pieces on a board or making 24 from four cards?

    e.g. N-Queens, N-Queens II, 24 Game

    Yes

    Stop 21: Pruning

    Track used rows, columns and cells in sets or bitmasks and back out the moment something conflicts; pruning decides whether it finishes in time.

    No

    Stop 19: Enumeration

    Draw the recursion tree: for subsets each element is in or out, for permutations each slot gets one element. Sort first and skip equal neighbours to avoid duplicates.

  20. Q20 Is the input a list of intervals [start, end]?

    e.g. Merge Intervals, Insert Interval, Non-overlapping Intervals, Minimum Number of Arrows to Burst Balloons

    Yes

    Stop 05: Prefix & Ranges

    Sort by start (or end) and sweep once: merge what overlaps, keep the most non-overlapping ones greedily by end time, and to count overlaps at a moment add +1 / −1 at the endpoints, a difference array.

  21. Q21 Is the array sorted, or is the answer monotone (if x works, every larger x works too)?

    e.g. Two Sum II, 3Sum (sort first), Search in Rotated Sorted Array, Koko Eating Bananas

  22. Q22 Do you look for two or three values in the sorted array that hit a target sum, or close in from both ends?

    e.g. Two Sum II, 3Sum, Squares of a Sorted Array

    Yes

    Stop 04: Two Pointers

    Put one pointer at each end: move the left one up when the sum is too small and the right one down when it is too big, O(n) in all; for 3Sum fix one number and do the same on the rest.

    No

    Stop 06: Binary Search

    Sorted data deserves better than a linear scan: binary search for positions, and for “minimize the maximum” binary search the answer with an O(n) check.

  23. Q23 Is the question about a contiguous subarray or substring?

    e.g. Longest Substring Without Repeating Characters, Subarray Sum Equals K, Maximum Product Subarray

  24. Q24 Are you after palindromic substrings: the longest one, or how many there are?

    e.g. Longest Palindromic Substring, Palindromic Substrings

    Yes

    Stop 27: Palindromes

    Expand around every character and every gap between two, which is O(n²); or let dp[i][j] say whether s[i..j] is a palindrome and fill it from short ranges to long.

  25. Q25 Do you want the largest sum or product of a contiguous run, with both positive and negative values?

    e.g. Maximum Product Subarray, Maximum Sum Circular Subarray, Maximum Subarray Sum with One Deletion

    Yes

    Stop 28: State Machines

    Track the best result ending at i, which depends only on i−1; for products keep both the max and the min, since two negatives make a positive. Plain Maximum Subarray sits at stop 01.

  26. Q26 Can elements be negative, or must you count subarrays whose sum is exactly k?

    e.g. Subarray Sum Equals K, Contiguous Array

    Yes

    Stop 05: Prefix & Ranges

    Prefix sums turn a range sum into the difference of two values; keep earlier prefix sums in a hash map. For many range updates, use a difference array.

    No

    Stop 04: Two Pointers

    With non-negative values or character counts, grow the window on the right and shrink it on the left; each element enters and leaves once, O(n) overall.

  27. Q27 Do you need the k-th largest, the top k, or the next greater (or smaller) element for each item?

    e.g. Kth Largest Element in an Array, Daily Temperatures, Largest Rectangle in Histogram

    Yes

    Stop 07: Stacks & Heaps

    Use a size-k heap for the k-th largest and the top k; use a monotonic stack for the next greater element and the largest rectangle, pushing and popping each element once.

  28. Q28 Do you handle nested or paired structure (brackets, expressions, encoded strings), or always deal with the most recently added item first?

    e.g. Valid Parentheses, Decode String, Basic Calculator, Asteroid Collision

    Yes

    Stop 07: Stacks & Heaps

    Push on an opening bracket or a new level, and pop the most recent one to match or settle it on a closing one; to evaluate expressions keep a second stack for operators.

  29. Q29 Do you want a maximum, a minimum or a number of ways, where earlier choices limit later ones?

    e.g. Climbing Stairs, House Robber, Coin Change, Jump Game

  30. Q30 Do you compare two strings or sequences: matching, editing, or finding a common part?

    e.g. Longest Common Subsequence, Edit Distance, Interleaving String

    Yes

    Stop 26: String DP

    Let dp[i][j] answer the question for the first i characters of s and the first j of t, then handle whether the last characters match.

  31. Q31 Is it about palindromes, or is the answer built by merging or splitting a range [i, j]?

    e.g. Longest Palindromic Subsequence, Burst Balloons

    Yes

    Stop 27: Palindromes

    dp[i][j] depends only on shorter ranges, so fill it in order of increasing length.

  32. Q32 Do you pick items or numbers to reach a target sum or capacity, asking whether you can, how few you need, or how many ways?

    e.g. Coin Change, Partition Equal Subset Sum, Target Sum

    Yes

    Stop 24: Knapsack

    Loop over items outside and capacity inside; go through capacity downward if each item is used once, upward if it can repeat.

  33. Q33 Is each day in one of a few states, such as holding a stock, not holding one, or cooling down?

    e.g. the Best Time to Buy and Sell Stock series

    Yes

    Stop 29: Stock Trading

    Keep the best profit for each state (holding, not holding, cooling down) and move between states day by day.

  34. Q34 Can you skip elements as long as the ones you keep follow some order (the longest increasing subsequence family)?

    e.g. Longest Increasing Subsequence, Russian Doll Envelopes

    Yes

    Stop 25: Subsequences

    Let dp[i] be the best result ending at element i, built from every earlier j it can follow; the O(n log n) version uses greedy plus binary search.

  35. Q35 Do you cut the array into segments, or schedule non-overlapping jobs on a timeline?

    e.g. Minimum Cost For Tickets, Maximum Profit in Job Scheduling, Partition Array for Maximum Sum

    Yes

    Stop 30: Scheduling DP

    Let dp[i] be the best value after the first i elements (or by time i), and try every place the last segment could start.

  36. Q36 Can you argue that taking the best-looking option at every step never backfires?

    e.g. Jump Game, Gas Station, Candy

    Yes

    Stop 08: Greedy

    Sort, or keep track of how far you can reach so far, then use an exchange argument to show no other choice does better.

    No

    Stop 22: DP Basics

    Write down which earlier steps step i depends on; start with memoized recursion, then turn it into a loop.

  37. Q37 Are you looking for a pair with some relation, or grouping and counting by a key?

    e.g. Two Sum, Group Anagrams, Longest Consecutive Sequence

    Yes

    Stop 02: Hashing

    Store what you have seen in a hash map as you scan, or compute one shared key per group (such as the sorted string).

  38. Q38 Is it about binary digits, XOR, the number that appears once, or integer overflow limits?

    e.g. Single Number, Number of 1 Bits, Sqrt(x)

    Yes

    Stop 35: Bits & Math

    Learn a few tricks: x & (x − 1) clears the lowest set bit, a ^ a = 0, and watch out for 32-bit overflow.

  39. Q39 Is the main work parsing or matching a string by rules?

    e.g. String to Integer (atoi), Reverse Words in a String, Find the Index of the First Occurrence in a String

    Yes

    Stop 03: Strings

    Walk the string one character at a time, handling spaces, signs and overflow; for substring search, KMP is an option.

    No

    Stop 01: In-place Arrays

    Usually an in-place array job: read and write pointers, swaps, or sort first and scan once.