Classifying 2 - There Are 55 Coding Interview Problems

In There Are 75 Famous Problems we saw Skiena write an Input and an Output for every problem. No algorithm name appears, so you can find an entry knowing only what you have and what you want.

You cannot use those 75 for a coding interview as they are. Voronoi Diagrams and Medial-Axis Transform do not come up in interviews. Different problems do.

So I built the list for interviews the same way. I went back through about 3,000 problems I had solved on LeetCode.

1. In and Out Alone Do Not Tell Them Apart

At first I followed Skiena exactly and wrote only the two fields. Then this happened.

  Largest run                      the contiguous run with the largest sum
                                   array -> one number
  Longest increasing subsequence   the longest increasing subsequence
                                   array -> one number

You cannot tell them apart. Contiguous or skipping is what decides the method, and it does not show up in In or Out. So I added one more field.

  In                    what goes in
  Out                   what comes out
  Splitting question    In and Out are the same, but the method changes here

Those two split right here — does it have to be contiguous?

  yes   Largest run
  no    Longest increasing subsequence

The third field is the one you actually use. Read the problem, and if you can answer the splitting question, the method is settled.

2. Nine Categories, 55 Problems

  Skiena      categories 7    problems 75      all of computer science
  this list   categories 9    problems 55      what shows up in interviews

There is no reason behind the number 55. It is a starting point. All I fixed were the rules for growing and shrinking it.

  split    when the difference changes the method or the "why is this correct"
  merge    when two entries produce the same reasoning
  add      when you keep getting something wrong in review and no entry covers it

Arrays and Ranges

ProblemInOutSplitting questionExamples
Window over a sequencenumbers or letters in a row, and one conditionthe shortest or longest run that satisfies the conditiondoes the condition change monotonically as you widen and shrink the window. if the condition is about a sum, one negative number breaks itLongest Substring Without Repeating Characters · Minimum Size Subarray Sum
Largest runnumbers in a rowthe run with the largest sum or productit must be contiguous. picking non-adjacent items is a different problemMaximum Subarray · Maximum Product Subarray
Longest increasing subsequencenumbers or items in a rowthe length of the longest subsequence that only goes upmust it be contiguous. if you may skip, keep only the tail values and binary searchLongest Increasing Subsequence · Russian Doll Envelopes
Next greater elementnumbers in a rowfor each position, the first larger or smaller value it meets, or the range those values defineif an earlier element is smaller than the current one, is it useless foreverDaily Temperatures · Largest Rectangle in Histogram
Prefix and rangea sequence or a matrix, plus repeated range questionsthe sum or minimum of each rangedo values change in between. if not, prefix sums; if so, a treeRange Sum Query - Immutable · Range Sum Query 2D - Mutable
Kth elementunsorted values and kthe kth largest or smallest valuedo you need just the kth one, or all k of themKth Largest Element in an Array · Top K Frequent Elements
Count and tallyvalueshow many times, is there a majority, which value is missingis the range of values narrow. if it is, counting alone is enoughMajority Element · First Missing Positive
Pair with targetnumbers and a targetthe two or three that sum to the targetmay you sort. if yes, two ends; if no, a hashTwo Sum · 3Sum

Order and Priority

ProblemInOutSplitting questionExamples
Boundary by monotonicitysomething sorted or monotone, and a true/false testthe point where the test first turns trueis the answer itself monotone. then binary search on the valueSearch in Rotated Sorted Array · Koko Eating Bananas
Two ends moving ina row that is sorted, or that you may sorta pair, an area, or a count you get by closing in from both endsdo you close in from both ends, or fix one side and close inTwo Sum II - Input Array Is Sorted · Valid Triangle Number
Intervalsintervals with a start and an endmerged, maximum overlap, or the most you can picksort by start or sort by end. it depends on what you wantMerge Intervals · Non-overlapping Intervals
Pull the best one nexta situation where you must take the best or worst each timethe result after processing everythingdo the candidates change after each pull. if not, just sortMerge k Sorted Lists · Meeting Rooms II
Sort then scanitems you must decide a sort order forthe answer you get from one sort and one passdoes fixing one criterion make the rest simpleLargest Number · Queue Reconstruction by Height

Grids and Matrices

ProblemInOutSplitting questionExamples
Walk a grida grid and a starting cellthe cells you reach, the number of blobs, or the fewest stepsis there one start or many. with many you spread from all of them at onceNumber of Islands · Walls and Gates
Transform in placea matrixrotated, transposed, or markedmust you use no extra space. then swap in layersRotate Image · Set Matrix Zeroes
Grid DPa grid and a cost per cellthe best value from one corner to the opposite onedoes it only move one way. if you can come back, first check there is no cycleMinimum Path Sum · Longest Increasing Path in a Matrix
Search a sorted grida matrix sorted by row and column, and a value to findis it thereis it still sorted if you flatten it into one row. if not, start from a cornerSearch a 2D Matrix · Search a 2D Matrix II
Simulate on a grida grid and a rule that changes itthe next state, or the result of applying the rule until nothing changesdo the updates happen all at once or one after anotherGame of Life · Candy Crush

Strings

ProblemInOutSplitting questionExamples
Palindromea stringis it a palindrome, or the longest palindromic piecedo you expand from the middle or close in from both endsLongest Palindromic Substring · Valid Palindrome
Brackets and expressionsa string with brackets or operatorsis it valid, the computed value, or the expanded resultis there nesting. if yes, a stack; if no, counting aloneMinimum Add to Make Parentheses Valid · Basic Calculator
Edit distancetwo stringsthe fewest operations to turn one into the otherwhich operations are allowed. remove the replace operation and it becomes a different problemEdit Distance · Delete Operation for Two Strings
Common subsequencetwo strings or two arraysthe longest thing contained in bothmust it be contiguous. if you may skip, it is a subsequenceLongest Common Subsequence · Maximum Length of Repeated Subarray
Pattern in texta long text and one or more pieces to findwhere the pieces occuris there more than one piece. with many, a trie or a hashFind All Anagrams in a String · Add Bold Tag in String
Prefix setseveral wordsfinding the words that share a prefixare the queries repeated. for a single one a trie is not worth buildingLongest Common Prefix · Word Search II
Same lettersone string or severalare the letter counts the same, grouping the ones that matchare you only checking whether two match, or grouping all of themValid Anagram · Group Anagrams
Rewrite a stringa string with a rule written in itthe result of applying the ruledoes the rule finish in one pass, or apply again to what came outDecode String · Count and Say

Trees

ProblemInOutSplitting questionExamples
Walk a treea treethe visiting order, or a value gathered on the waydo you carry something down, or gather something upPath Sum · Maximum Depth of Binary Tree
Tree DPa tree and a value per nodethe best value collected from the subtrees belowis one value enough to send up from a child, or do you need severalBinary Tree Maximum Path Sum · House Robber III
Build a treetraversal output or a serialized stringthe original treewhere in the input is the rootConstruct Binary Tree from Preorder and Inorder Traversal · Construct Binary Tree from Inorder and Postorder Traversal
Binary search treea tree with the sorted propertyinsert, delete, kth, or validatedo you build a tree from a sorted sequence, or pull a sorted sequence out of a treeConvert Sorted Array to Binary Search Tree · Kth Smallest Element in a BST
Lowest common ancestora tree and two nodestheir nearest common ancestorcan you use the sorted property. in a binary search tree one walk down from the root solves itLowest Common Ancestor of a Binary Search Tree · Lowest Common Ancestor of a Binary Tree

Graphs

ProblemInOutSplitting questionExamples
Connected componentsvertices and edges, or a gridhow many blobs, are these two in the same blob, which edge closes a cycledo the edges arrive all at once or one at a timeNumber of Connected Components in an Undirected Graph · Redundant Connection
Topological ordertasks with precedencean execution order, or whether such an order exists at allwith a cycle there is no answer. checking for one is half the problemCourse Schedule · Course Schedule II
Shortest patha graph and a start, plus a target if neededthe least cost or the fewest stepsare all weights 1, are any negative. the method splits three waysWord Ladder · Network Delay Time
Cyclea graph or a linked listis there a cycle, where does it start, which parts never reach a cycleis there one next, or several branches. with branches you need a separate in-progress markLinked List Cycle II · Find Eventual Safe States
Spanning and flowa graph with weights or capacitiesthe cheapest way to connect everything, the most you can push through, the largest matchingdoes it split into two sides. if it does, it becomes a matching problemMin Cost to Connect All Points · Maximum Number of Accepted Invitations

States and Choices

ProblemInOutSplitting questionExamples
Carry state forwarda few states to choose from at each stepthe best value at the last stepdo you know the number of states in advance, or does it grow with the inputBest Time to Buy and Sell Stock · Best Time to Buy and Sell Stock IV
Count the waysa grid or steps, plus constraintshow many ways reach the endare the places you can go fixed from the start, or do you have to read the inputUnique Paths · Decode Ways
Interval DPa row, and an operation that works on intervalsthe best cost of merging the whole thingdoes it split on what you do lastBurst Balloons · Strange Printer
Knapsackitems with a size and a value, and a limitthe best value chosen against a limit or a targetdo you use the same item more than once. if so the loop runs the other wayOnes and Zeroes · Coin Change
List every arrangementa small n and constraintsevery arrangement that satisfies the constraintscan you prune. if not there are too many answersLetter Combinations of a Phone Number · Generate Parentheses
Small n, every subsetn around 20, a different value per subsetthe best value after trying everythingis the subset enough to describe the state, or must you also track where you areCan I Win · Android Unlock Patterns
Win or losea game with alternating movesdoes the first player windoes the board split into independent piles. if it does, Grundy numbersNim Game · Flip Game II

Numbers

ProblemInOutSplitting questionExamples
Digits and basesone number, or a number written as a stringdigits handled, or the base changeddoes it go past the type range. if so, treat it as a stringReverse Integer · Excel Sheet Column Title
Divisors and primesone number or a rangeis it prime, how many primes, what are the divisorsdo you look at one number or at a range. for a range, build a sievePrime Palindrome · Count Primes
Bit tricksnumbersa value you get with bit operationshow many of each are paired up. with two, one XOR solves itSingle Number · Single Number II
Combinatoricsn and a modulus, plus k if neededthe number of casesis there a division. if so you need an inverseCount All Valid Pickup and Delivery Options · Number of Ways to Reorder Array to Get Same BST
Chance and samplinga situation that needs randomnessa result where every choice is equally likelydo you know the total size in advance. if not, pick as the items go pastShuffle an Array · Linked List Random Node
Geometrypoints or shapesdistance, containment, or the enclosing shapedo you use floats. if so, rounding error is half the problemMax Points on a Line · Generate Random Point in a Circle

Data Structures

ProblemInOutSplitting questionExamples
Design a structurea list of operations and a time limita structure where all of them are fastdo you do the work on the way in, or on the way outTwo Sum III - Data structure design · Design Twitter
Cache and evictiona capacity limit and an access loga structure that decides what to keep and what to dropis the eviction rule time or countLRU Cache · LFU Cache
Stack and queue disciplinea rule where you push and pop at one end onlya structure that answers extra queries while keeping that ruledo they also ask for something like the minimumMin Stack · Implement Stack using Queues
Key to valuekeys and values, and the operations requireda structure where insert, delete and lookup are all constant timeis there also a random pick. if so, keep an array alongsideDesign HashMap · Insert Delete GetRandom O(1) - Duplicates allowed
Iterate on demandnested or compressed dataan iterator that hands them over one at a timemay you expand everything in advance. if not, make it lazyFlatten Nested List Iterator · Binary Search Tree Iterator
Linked list surgerya chain of nodesreverse, cut, merge, find a cycledo you know the length in advance. if not, use two pointersRemove Nth Node From End of List · Reverse Linked List II

3. How To Use It

Cover the right-hand side and look at the three fields on the left. When you read a problem and can answer the splitting question, that problem is solved. When no answer comes, that is what you need to study again.