Practice problems
Where to solve problems, and which problems go with each lesson. Everything here is free to use and opens on its own site.
Problem-solving sites
- Interview practice · Mostly freeLeetCodeThe standard place for interview-style problems; start with the Easy problems tagged with the lesson you just read.
- Basics · FreeHackerRankGentle, guided tracks where the starter code is already written; begin with the Data Structures track.
- Contests · FreeCSES Problem SetA short, carefully ordered list of classic problems with strict time limits; begin with Introductory Problems, then Sorting and Searching.
- Interview practice · Mostly freeNeetCodeA roadmap that groups well-known interview problems by pattern; follow the roadmap in order and solve each one yourself first.
- Interview practice · Mostly freeGeeksforGeeks PracticeA huge bank of small problems where you write only one function; filter by topic and pick Basic or Easy.
- Contests · FreeCodeforcesThe biggest contest site, with a rating on every problem; sort the problem set by rating and start at 800.
- Contests · FreeAtCoderClean, short problem statements; try problems A and B of the Beginner Contests, and the Educational DP Contest when you reach dynamic programming.
- Contests · FreeTophA Bangladeshi judge, with many statements in Bangla too; start with the most-solved problems.
- Contests · FreeLightOJA Bangladeshi judge with problems grouped by topic; start with the beginner problems, then pick the topic you just learned.
- Basics · FreebeecrowdFormerly URI Online Judge and a common first judge in Bangladesh; sign up free and start in the Beginner category.
- Contests · Mostly freeCodeChefPractice paths by topic plus weekly contests; start with the beginner path of the language you use.
- Basics · FreeExercismSmall exercises for learning a language well; pick the track of your language before moving to harder judges.
- Basics · Mostly freeCodewarsShort puzzles ranked from 8 kyu (easiest) upward; start at 8 kyu and read other people's answers after you solve one.
- Basics · FreeHackerEarthTopic pages that pair a short tutorial with problems; open the Data Structures section and follow one topic at a time.
- Interview practice · Mostly freeInterviewBitInterview problems arranged as a topic-by-topic path; start with the Arrays topic.
- Contests · FreeUSACO GuideA free, ordered curriculum for contest programming that links to problems on many judges; start at the Bronze section.
- Contests · FreeKattisProblems from real university contests, each with a difficulty score; sort by difficulty and start with the lowest scores.
- Contests · FreeSPOJAn old, very large archive of classic problems; sort by the number of users who solved a problem and start from the top.
- Basics · FreeProject EulerMaths-flavoured puzzles where you submit only the final number; the first 20 are good practice for thinking about growth.
- Basics · FreeAdvent of CodeStory puzzles released every December, in any language you like; try the first few days of an earlier year.
Data Structures
Arrays and Strings
- MaximumRead values into an array and scan it once.
- Arrays - DSReverse an array using nothing but index reads and writes.
- Way Too Long WordsA string is ordered data: use its length, first and last characters.
- Reverse StringSwap values in place by index, without a second array.
- RepetitionsScan a string once while comparing each character with the one before it.
- Move ZeroesShift values inside one array, the same moving the lesson counts for insert and delete.
- Left RotationWork out where each index lands instead of shifting everything one step at a time.
- Rotate ArrayShifting k times is too slow; count the moves and find a way to do fewer.
Linked Lists
- Print the Elements of a Linked ListWalk the list node by node until the pointer runs out.
- Length of Linked ListThe same walk, this time counting nodes: a list does not know its own length.
- Insert a node at the head of a linked listThe O(1) insert at the front that makes linked lists worth having.
- Reverse Linked ListRe-point every next pointer without losing the rest of the list.
- Remove Linked List ElementsRemove nodes by making the node before them skip over them.
- Merge Two Sorted ListsBuild one list from two by re-linking nodes, not copying values.
- Design Linked ListWrite the whole structure yourself: get, add at head, tail or index, and delete.
- Add Two NumbersWalk two lists together while building a third, one new node per step.
Stacks and Queues
- Valid ParenthesesThe classic stack job: the last bracket opened must be the first one closed.
- Number of Recent CallsA queue in real use: new items join the back, old ones leave the front.
- Maximum ElementPush and pop, plus answering "what is the largest right now?" without rescanning.
- Implement Queue using StacksTwo LIFO stacks together give FIFO order; see why the order flips.
- Double Ended QueueBuild a queue that adds and removes at both ends, with a size limit to respect.
- Min StackKeep push, pop and "current minimum" all O(1) by storing a little extra.
- Evaluate Reverse Polish NotationA stack as a calculator: push numbers, pop two when an operator arrives.
Hash Tables
- Contains DuplicateA hash set answers "have I seen this before?" in O(1).
- Is AnagramCount each letter with a key-to-count table and compare the two tables.
- Two SumThe lesson's main example: one hash map turns an O(n²) pair search into O(n).
- Hash Tables: Ransom NoteCount words in a hash map, then use the counts up one by one.
- Design HashMapBuild the buckets yourself: hash the key, pick a bucket, handle collisions.
- Registration SystemA map from name to count, with up to 100,000 names so a list search is too slow.
- Group AnagramsChoose a key that is the same for every word in a group.
- Longest Consecutive SequenceUse O(1) set lookups to avoid sorting and still finish in O(n).
Binary Search Trees
- Search in a Binary Search TreeGo left or right at each node, exactly as the lesson traces it.
- Binary Search Tree : InsertionSearch until you fall off the tree, then attach the new node there.
- Tree: Height of a Binary TreeMeasure the height, the number that decides the cost of every operation.
- Minimum in BSTKeep going left: the sorted shape tells you where the smallest value lives.
- Binary Tree Inorder TraversalLeft, node, right: the walk that reads a search tree in sorted order.
- Validate Binary Search TreeCheck the ordering rule for whole subtrees, not just a node and its children.
- Kth Smallest Element in a BSTRead in order and stop at the k-th value.
- Delete Node in a BSTAll three removal cases: no child, one child, two children.
Heaps and Priority Queues
- Last Stone WeightKeep taking out the two largest values and putting one back: a max-heap's job.
- QHEAP1The basic heap operations: add a value, remove a value, print the smallest.
- Jesse and CookiesPull out the two smallest, push one combined value back, repeat.
- Kth Largest Element in a StreamA min-heap that never holds more than k values keeps the answer on top.
- Powerful Discount TicketsAlways act on the current largest value, which keeps changing: a heap, not a re-sort.
- Kth Largest Element in an ArrayFind the k-th largest without sorting everything.
- Merge k Sorted ListsA heap holding the front node of each list always knows the next smallest.
- Find Median from Data StreamTwo heaps, one for each half of the values, keep the middle on top.
Tries (Prefix Trees)
- Longest Common PrefixWhat a shared prefix is, before you build a structure around it.
- Implement Trie (Prefix Tree)Build the structure itself: insert, search and starts-with.
- ContactsStore a count on every node to answer "how many words start with this?"
- Consistency CheckerDetect when one number is a prefix of another while inserting into a trie.
- Replace WordsWalk each word down the trie and stop at the first complete root.
- Design Add and Search Words Data StructureA wildcard character means trying every child at that step.
- Word Search IISearch a grid for many words at once by walking the grid and a trie together.
Algorithms
Big O
- Theatre SquareSizes go up to a billion, so no loop survives: find the O(1) formula.
- Missing NumberChecking each number against the whole list is O(n²); one pass with a sum is O(n).
- Best Time to Buy and Sell StockTrying every buy and sell day is a nested loop; one loop that remembers the lowest price is enough.
- Trailing ZerosThe factorial is far too big to compute; count something that grows like log n instead.
- Maximum SubarrayEvery start and end is O(n²) or worse; keeping a running best brings it to O(n).
- Sum of Two ValuesWith 200,000 values, all pairs is about 20 billion steps; work out what shape will fit.
- Count PrimesTesting each number on its own is too slow; a sieve does the work once for all of them.
Binary Search
- Binary SearchThe lesson's lo, mid, hi loop, exactly as written.
- Search Insert PositionWhat lo points at when the value is not there.
- First Bad VersionFind the first position where the answer flips from no to yes.
- Sqrt(x)Halve a range of numbers, not an array; mind the off-by-one at the end.
- Interesting drinkSort once, then answer each query by counting values up to a limit with one search.
- Closest StationSearch a sorted list for a value that may be missing, then compare its two neighbours.
- Find First and Last Position of Element in Sorted ArrayThe "value appears twice" section: one search for the left edge, one for the right.
- Search a 2D MatrixTreat a sorted grid as one long sorted list and halve it.
Sorting
- Helpful MathsA tiny input where any sort you write by hand is fast enough.
- Sorting: Bubble SortWrite bubble sort and count the swaps it makes.
- Insertion Sort - Part 2Print the array after every pass, the same trace the lesson does by hand.
- Merge Sorted ArrayOnly the merge step of merge sort: join two sorted runs into one.
- Sort an ArrayThe O(n²) sorts time out here; write the full merge sort.
- Sort ListMerge sort again, on a linked list: split in the middle, sort the halves, merge.
- Merge Sort: Counting InversionsCount bubble sort's swaps without doing them, by counting inside the merge step.
Graph Traversal
- Find if Path Exists in GraphBuild the neighbour lists and run plain BFS or DFS from the start node.
- Flood FillA grid is a graph: each cell's neighbours are the four cells beside it.
- Counting RoomsStart a traversal from every unvisited floor cell and count how many you start.
- Guilty PrinceCount the cells you can reach from one starting cell on a small grid.
- Number of IslandsCount connected groups by marking cells visited as you go.
- Rotting OrangesBFS from several starting cells at once; the number of rounds is the answer.
- Message RouteBFS finds the shortest path; remember where each node was reached from to print it.
- LabyrinthThe same shortest path with rebuilding, on a grid of up to a million cells.
Dynamic Programming
- Climbing StairsThe smallest example: each answer is built from the two answers before it.
- Frog 1The best cost to reach a stone comes from the best costs of the two stones before it.
- Dice CombinationsCount the ways to reach a total by adding up the ways to reach the six totals before it.
- House RobberTake it or skip it: write the choice as a rule over earlier answers.
- VacationThe stored answer needs one more detail: what you did the day before.
- Minimizing CoinsThe fewest coins for each amount, built from smaller amounts; taking the biggest coin first fails.
- Knapsack 1A table over items and remaining capacity: the classic knapsack.
- Longest Common SubsequenceA table over two strings, each cell filled from its neighbours.
Interview Patterns
Two Pointers
- Valid PalindromeOne pointer at each end, moving inward and comparing as they go.
- Remove Duplicates from Sorted ArrayTwo pointers moving the same way: one reads, one writes.
- Squares of a Sorted ArrayThe largest square is always at one of the two ends; pick it and move that pointer in.
- Two Sum II - Input Array Is SortedThe lesson's own problem: the sum tells you which pointer to move.
- Ferris WheelSort first, then pair the lightest with the heaviest that still fits.
- Alice, Bob and ChocolateTwo pointers walking toward each other, each with its own running total.
- Container With Most WaterExplain why moving the shorter side can never skip the best answer.
- 3SumFix one value, then run the two-pointer pair search on the rest.
Sliding Window
- Maximum Average Subarray IA fixed-size window: add the value entering, subtract the value leaving.
- FenceThe same fixed window, this time looking for the smallest sum and where it starts.
- Maximum Number of Vowels in a Substring of Given LengthA fixed window over a string, keeping a count instead of a sum.
- Minimum Size Subarray SumA window that grows on the right and shrinks from the left while it still qualifies.
- Subarray Sums IAll values are positive, so the window sum only grows when you extend and only falls when you shrink.
- Longest Substring Without Repeating CharactersA flexible window plus a set of what is inside it.
- PlaylistThe same idea on numbers with 200,000 values, so every step must be O(1).
- Minimum Window SubstringGrow until the window covers everything needed, then shrink while it still does.
Fast and Slow Pointers
- Middle of the Linked ListWhen the fast pointer reaches the end, the slow one is at the middle.
- Linked List CycleThe lesson's main problem: the two pointers meet only if there is a loop.
- Happy NumberNo list at all: a sequence of numbers can loop too, and the same two speeds catch it.
- Palindrome Linked ListFind the middle with two speeds, then compare the two halves.
- Cycle DetectionLoop detection again, with the empty and one-node lists to get right.
- Cycle Length in Linked ListAfter the pointers meet, walk once around the loop and count the nodes.
- Linked List Cycle IIFind the node where the loop begins, using O(1) memory.
- Find the Duplicate NumberSee an array as a linked list where each value points to an index; the duplicate is where the loop starts.
Prefix Sums
- Running Sum of 1d ArrayBuild the running totals, the first half of the pattern.
- Range Sum Query - ImmutableBuild once, then answer sum(l..r) with one subtraction; mind the r + 1.
- Find Pivot IndexLeft sum and right sum at every index, both read from running totals.
- Static Range Sum Queries200,000 range queries: adding each range up again times out, the prefix array does not.
- Ilya and QueriesA prefix count instead of a prefix sum: count matching neighbours up to each position.
- Kuriyama Mirai's StonesTwo prefix arrays, one over the original order and one over the sorted order.
- Subarray Sum Equals KTwo running totals that differ by k mark a stretch that sums to k; count them with a hash map.
- Forest QueriesPrefix sums on a grid: any rectangle from four lookups.