All puzzles › Classic DSA
Classic DSA Practice Problems
220 puzzles (69 easy, 97 medium, 54 hard), 8 free, in Python, JavaScript and C++.
Classic data-structure and algorithm puzzles.
The puzzles, easiest first
- Binary Search (Easy, free): Given a sorted array and a target, return the target's index, or -1 if it isn't there.
- Reverse Linked List (Easy, free): Given a linked list, passed in as its values from front to back, return its values in reverse order.
- Two Sum (Easy, free): Given an array of numbers and a target, return the indices of the two numbers that add up to the target.
- Valid Palindrome (Easy, free): Given a string, return true if it reads the same forwards and backwards, ignoring case and anything that isn't a letter or number.
- Valid Parentheses (Easy, free): Given a string of brackets ( ) [ ] { }, return true if they all close in the right order.
- Add Up the Digits (Easy): Given a number, return the sum of its digits, using recursion.
- Best Time to Buy & Sell Stock (Easy): Given a list of daily prices, return the most money you can make by buying on one day and selling on a later day.
- Biggest in the Chain (Easy): Given a linked list, passed in as its values, return the biggest value, or null if it's empty.
- Biggest in the Tree (Easy): Given a binary tree, return its biggest value, or null if it's empty.
- Climbing Stairs (Easy): Given n stairs, return how many different ways you can climb to the top taking 1 or 2 steps at a time.
- Contains Duplicate (Easy): Given an array, return true if any value appears more than once, or false if every value is different.
- Content Children (Easy): Given each child's minimum cookie size and the sizes of the cookies, return the most children you can make happy, one cookie each.
- Count a Value (Easy): Given a linked list, passed in as its values, and a target, return how many nodes hold the target.
- Count Land Cells (Easy): Given a grid of "1"s and "0"s, return how many cells are "1".
- Count Trailing Zeros (Easy): Given a number, return how many 0 bits come after its last 1 bit.
- Count Tree Nodes (Easy): Given a binary tree, return how many nodes it has.
- Deepest Nesting (Easy): Given a string of parentheses, return how deeply they nest.
- Drop the Last One (Easy): Given a number, return it with its lowest 1 bit turned off and everything else the same.
- Evens to the Front (Easy): Given an array, rearrange it so every even number comes before every odd one.
- Exactly One Bit (Easy): Given a number, return true if exactly one of its bits is 1.
- Find the Children (Easy): Given an index i in a heap stored as an array, and the heap's size, return [left child, right child].
- Find the Parent (Easy): Given an index i in a heap stored as an array, return its parent's index, or -1 for the root at index 0.
- First Unique Character (Easy): Given a string, return the index of the first character that appears only once, or -1 if there isn't one.
- Flip One Bit (Easy): Given a number n and a position i, return n with bit i flipped and every other bit left alone.
- Full Nodes (Easy): Given a binary tree, return how many nodes have BOTH a left and a right child.
- Guess the Number (Easy): Given n and a secret target between 1 and n, return how many guesses it takes if you always guess the middle of what's left.
- Heap After Pops (Easy): Given a min-heap and a number n, pop the smallest value n times and return what's left, smallest first.
- Is It a Min-Heap? (Easy): Given an array, return true if it's a valid min-heap.
- Is It In There? (Easy): Given a sorted array and a target, return true if the target is in it.
- Is Subsequence (Easy): Given strings s and t, return true if you can find the letters of s inside t, in order, possibly with other letters in between.
- Is the Chain Sorted? (Easy): Given a linked list, passed in as its values, return true if it's sorted from smallest to largest.
- Isolate the Last One (Easy): Given a number, return just its lowest 1 bit, with every other bit cleared.
- Kth Largest (Easy): Given an array and k, return the kth largest value.
- Kth Smallest (Easy): Given an array and k, return the kth smallest value.
- Leaderboard Top K (Easy): Given a list of names, their scores, and k, return the names of the top k scorers, highest first.
- Leftmost Value (Easy): Given a binary search tree, return its smallest value, or null if it's empty.
- Length of the Chain (Easy): Given a linked list, passed in as its values, return how many nodes it has.
- Level Order (Easy): Given a binary tree, return every value level by level, top to bottom and left to right.
- Majority Element (Easy): Given an array where one value appears more than half the time, return that value.
- Max Consecutive Ones (Easy): Given an array of 1s and 0s, return the length of the longest run of 1s in a row.
- Middle of the Linked List (Easy): Given a linked list, passed in as its values, return the middle value.
- Missing Number (Easy): Given n different numbers from 0 to n, with exactly one missing, return the missing one.
- Move Zeroes (Easy): Given an array, move every 0 to the end and keep the other values in their original order.
- Moving Average (Easy): Given a stream of readings and a window size, return the average of the most recent readings after each one, rounded to 2 decimals.
- Peek the Minimum (Easy): Given a min-heap stored as an array, return its smallest value, or null if it's empty.
- Perfect Square? (Easy): Given n, return true if it's a perfect square, like 16.
- Plus One (Easy): Given an array of digits that spells out a number, add one and return the new digits.
- Power by Halving (Easy): Given a base and an exponent, return base to that power using O(log n) multiplications.
- Read One Bit (Easy): Given a number n and a position i, return 1 if bit i is set, or 0 if it isn't.
- Read the Root (Easy): Given a binary tree, return the root's value, or null if the tree is empty.
- Recent Pings (Easy): Given a list of ping times in milliseconds, oldest first, and the current time, return how many pings landed in the last 3000 milliseconds, counting exactly 3000 ago.
- Remove Duplicates from Sorted List (Easy): Given a sorted linked list, passed in as its values, remove the duplicates so each value appears once.
- Remove Every Match (Easy): Given a linked list, passed in as its values, and a target, remove every node holding the target and return what's left, in order.
- Reverse It In Place (Easy): Given a string, reverse it by swapping characters from both ends inward.
- Reverse With a Stack (Easy): Given a list, return it reversed using a stack.
- Running Sum (Easy): Given an array, return a new array where each spot holds the total of everything up to and including it.
- Search a BST (Easy): Given a binary search tree and a target, return true if the target is in it.
- Single Number (Easy): Given an array where every value appears twice except one, return the one that appears once.
- Smallest Free Seat (Easy): Given a list of seat numbers that are already taken, return the lowest seat number that's free.
- Splice a Node In (Easy): Given a linked list, passed in as its values, a position n, and a value, insert the value right after position n and return the new list.
- Squeeze Out Repeats (Easy): Given a sorted array, remove the duplicates and return what's left.
- Strip Out a Value (Easy): Given an array and a value, remove every copy of that value and return what's left, in order.
- Sum of Tree Nodes (Easy): Given a binary tree, return the sum of every node's value.
- Swap Without a Spare (Easy): Given two numbers, swap them without a temporary variable, using XOR three times: x = x ^ y, then y = x ^ y, then x = x ^ y.
- Top K Largest (Easy): Given an array and k, return the k largest values, biggest first.
- Valid Anagram (Easy): Given two strings s and t, return true if t uses exactly the same letters as s, the same number of times.
- Weave Two Words (Easy): Given two words, weave them together one letter at a time, starting with the first word.
- What's Left on the Stack (Easy): Given a list of commands, return what's left on the stack, bottom first.
- Where Would It Go? (Easy): Given a sorted array and a target, return the target's index, or the index where it would go to keep the array sorted.
- Longest Unique Substring (Medium, free): Given a string, return the length of the longest stretch with no repeated characters.
- Max Depth of Binary Tree (Medium, free): Given a binary tree, return how many levels deep it goes.
- Maximum Subarray (Medium, free): Given an array of numbers, return the largest sum of any contiguous run.
- A Gap of Exactly d (Medium): Given a sorted array and a number d, return true if two different items are exactly d apart.
- Backspace Compare (Medium): Given two strings where "#" means backspace, return true if they end up as the same text.
- Balanced Tags (Medium): Given a list of tags like "div" and "/div", return true if they're properly nested and every tag gets closed.
- Beat the Deadlines (Medium): Given job deadlines, where each job takes one time slot and must finish by its deadline, return the most jobs you can finish.
- Biggest Power That Fits (Medium): Given n, return the biggest power of two that's n or less.
- Burst Every Balloon (Medium): Given balloons as [start, end] spans on a line, return the fewest arrows to pop them all.
- Busiest Task Count (Medium): Given a list of tasks, return how many times the most common task appears.
- Can You Reach the End? (Medium): Given an array where each value is the farthest you can jump from that spot, return true if you can get from the first index to the last.
- Cancel Neighbours (Medium): Given a string, keep removing any two identical letters that sit side by side until there are none left, and return what's left.
- Cheapest Rope Join (Medium): Given a list of rope lengths, join them all into one rope for the lowest total cost.
- Choose k of n (Medium): Given n and k, return every way to choose k numbers from 1 to n, where order doesn't matter.
- Circular Queue (Medium): Given a list of values and a buffer size, return what's in the buffer at the end, oldest first.
- Closest Value (Medium): Given a sorted array and a target, return the value closest to the target.
- Closest Without Going Over (Medium): Given a list of weights and a limit, return the biggest total you can make from some of them without going over the limit.
- Complete Coin Rows (Medium): Given n coins, return how many complete rows you can build when row 1 needs 1 coin, row 2 needs 2, and so on.
- Container With Most Water (Medium): Given a list of wall heights, pick two walls that hold the most water between them and return that amount.
- Count the Copies (Medium): Given a sorted array and a target, return how many times the target appears.
- Count the Leaves (Medium): Given a binary tree, return how many leaves it has, where a leaf is a node with no children.
- Days Until Warmer (Medium): Given daily temperatures, return for each day how many days until a warmer one, or 0 if none comes.
- Decode a Repeat (Medium): Given a compressed string like "3[a]2[bc]", expand it to "aaabcbc".
- Drop the Nth Node (Medium): Given a linked list, passed in as its values, and a position n (starting from 0), remove the node at n and return the values left.
- Every Capitalisation (Medium): Given a string, return every version of it with each letter in lowercase or uppercase.
- Every Subset (Medium): Given a list, return every subset of it, including the empty one.
- Fewest Coins (Medium): Given coin values from biggest to smallest and an amount, return how many coins the greedy approach uses, or -1 if it can't make the amount exactly.
- Find a Peak (Medium): Given an array, return the index of a peak, a value bigger than its neighbors.
- First Bad Build (Medium): Given a list of builds where false is good and true is broken, and once a build breaks every later one is broken too, return the index of the first broken one, or -1.
- First Occurrence (Medium): Given a sorted array and a target, return the index of its FIRST appearance, or -1.
- Fit the Most In (Medium): Given a list of [start, end] events, return the most you can attend without any overlap.
- How Far Rotated? (Medium): Given a sorted array that was rotated, return how many places it was rotated.
- How Many Bits Differ? (Medium): Given two numbers, return how many bit positions they differ in.
- How Many Rooms? (Medium): Given meetings as [start, end], return the fewest rooms needed to hold them all.
- Inorder Walk (Medium): Given a binary tree, return its values in inorder: the left subtree first, then the node, then the right subtree.
- Integer Square Root (Medium): Given n, return the biggest whole number whose square is n or less.
- Invert Binary Tree (Medium): Given a binary tree, mirror it so every left child swaps places with its right child, and return it.
- K Closest to a Target (Medium): Given an array, a target, and k, return the k values closest to the target, sorted from smallest to largest.
- Last Occurrence (Medium): Given a sorted array and a target, return the index of its LAST appearance, or -1.
- Last Stone Standing (Medium): Given a pile of stone weights, keep smashing the two heaviest together.
- Load the Truck (Medium): Given box types as [count, unitsPerBox] and how many boxes the truck holds, return the most units you can load.
- Longest Zigzag (Medium): Given a list of numbers, return the length of the longest zigzag you can pick out of it, where the steps go up, down, up, down (or the other way).
- Making Change (Medium): Given a line of customers each paying 5, 10, or 20 for a 5 drink, and starting with no change, return true if you can give everyone the right change.
- Max Area of Island (Medium): Given a grid of land ("1") and water ("0"), return the size of the biggest island, counted in cells.
- Median of a Window (Medium): Given a list of numbers, return the median, rounded to 2 decimals.
- Merge Backwards (Medium): Given a sorted array a with empty space at the end, the number of real values m, and a second sorted array b, merge b into a and return it.
- Merge Sorted Piles (Medium): Given several sorted lists, merge them into one sorted list.
- Merge Two Sorted Lists (Medium): Given two sorted lists, merge them into one sorted list.
- Mirror Image (Medium): Given a binary tree, return true if it's a mirror image of itself.
- Most Used Words (Medium): Given a list of words and k, return the k most common words.
- Multiply With Shifts (Medium): Given two numbers a and b, multiply them using only shifts and addition.
- Negatives to the Left (Medium): Given an array, move every negative number in front of every other number.
- Next Greater Element (Medium): Given an array, return for each value the next bigger value to its right, or -1 if there isn't one.
- Next Letter Around (Medium): Given a sorted list of letters and a target letter, return the first letter that comes strictly after the target.
- No Two Ones Together (Medium): Given n, return every binary string of length n with no two 1s next to each other.
- Nth From the End (Medium): Given a linked list, passed in as its values, and n, return the value n places from the end, or null if the list is shorter than n.
- Number of Islands (Medium): Given a grid of land ("1") and water ("0"), return how many separate islands there are.
- Odd and Even Positions (Medium): Given a linked list, passed in as its values, return the nodes at odd positions first (1st, 3rd, 5th), followed by the ones at even positions (2nd, 4th), each group keeping its order.
- Pairs Under the Limit (Medium): Given an array and a limit, return how many pairs add up to less than the limit.
- Palindrome Chain (Medium): Given a linked list, passed in as its values, return true if it reads the same forwards and backwards.
- Partition Around a Value (Medium): Given a linked list, passed in as its values, and a pivot, move every value below the pivot ahead of every value at or above it.
- Paths Across the Grid (Medium): Given a grid's rows and columns, return how many paths go from the top-left to the bottom-right moving only right or down.
- Postorder Walk (Medium): Given a binary tree, return its values in postorder: the left subtree, then the right subtree, then the node.
- Preorder Walk (Medium): Given a binary tree, return its values in preorder: the node first, then its left subtree, then its right subtree.
- Product of Array Except Self (Medium): Given an array, return a new array where each spot holds the product of every other number, without using division.
- Queue From Two Stacks (Medium): Given values pushed in order onto a stack, return the order they'd come out if it worked like a queue.
- Range of a Value (Medium): Given a sorted array and a target, return [first index, last index] of the target, or [-1, -1] if it isn't there.
- Reverse Only the Vowels (Medium): Given a string, reverse only its vowels and leave every other character where it is.
- Rotate Array (Medium): Given an array and k, shift every item k places to the right, with items that fall off the end wrapping around to the front.
- Rotate the Chain (Medium): Given a linked list, passed in as its values, and k, rotate it right so the last k nodes move to the front.
- Same Tree? (Medium): Given two binary trees, return true only if they have the same shape and the same values in the same places.
- Scoreboard Ops (Medium): Given a list of scoreboard commands, return the total.
- Search a Sorted Grid (Medium): Given a grid where every row is sorted and each row starts after the last one ends, return true if the target is in it.
- Set Bits for Everyone (Medium): Given n, return an array with the number of 1 bits in every number from 0 to n.
- Shallowest Leaf (Medium): Given a binary tree, return the number of levels from the root down to the CLOSEST leaf.
- Sift Up (Medium): Given a min-heap and a new value, add the value and return the fixed heap.
- Simplify a Path (Medium): Given a messy file path like "/a/./b/../../c/", return the clean version, "/c".
- Squares, Still Sorted (Medium): Given a sorted array that may have negatives, return the squares of every number, sorted.
- Subsets by Counting (Medium): Given a list, return every subset by counting from 0 to 2^n - 1.
- Sum Each Level (Medium): Given a binary tree, return the sum of each level, top to bottom.
- Swap Every Pair (Medium): Given a linked list, passed in as its values, swap every pair of neighbors and return the result.
- Swap Neighbouring Bits (Medium): Given a byte, swap every pair of neighboring bits and return the result.
- The Middle Node (Medium): Given a linked list, passed in as its values, return the middle value.
- The Missing Number (Medium): Given n different numbers from 0 to n, with exactly one missing, return the missing one.
- The Right-Side View (Medium): Given a binary tree, return what you'd see standing on its right side: the rightmost value on each level, top to bottom.
- Time to Buy (Medium): Given how many tickets each person in line wants and a position k, return how many seconds until person k is done.
- Top K Frequent (Medium): Given an array and k, return the k values that show up most often, most frequent first.
- Towers of Hanoi (Medium): Given n disks on peg A, return the moves, like "A->C", that move them all to peg C.
- Track the Minimum (Medium): Given a list of stack commands, where a number is a push and "pop" removes the top, return the smallest value left on the stack at the end, or null if it's empty.
- Two Sum (Sorted) (Medium): Given a sorted array and a target, return the indices of the two numbers that add up to the target.
- Two to a Boat (Medium): Given people's weights and a boat's weight limit, where a boat holds at most two people, return the fewest boats needed.
- Undo a Gray Code (Medium): Given a Gray code value, return the normal binary number it stands for.
- Unique Grid Paths (Medium): Given an m by n grid, return how many routes a robot can take from the top-left corner to the bottom-right if it can only move right or down.
- Weave Two Chains (Medium): Given two linked lists, passed in as their values, weave them together one node at a time, starting with the first list.
- What They Share (Medium): Given two sorted arrays, return the values that are in both, with no repeats.
- Where They Join (Medium): Given two linked lists that join and share the same tail, passed in as their values, return the first value of that shared tail, or null if they don't share one.
- XOR Everything to n (Medium): Given n, return 0 XOR 1 XOR 2 XOR ...
- Add Two Chains (Hard): Given two numbers stored as linked lists, one digit per node with the ones digit first, return their sum in the same format.
- Add Up to the Target (Hard): Given a list of numbers and a target, return every combination that adds up to the target, where each number can be used as many times as you want.
- Addition Without Adding (Hard): Given two numbers, add them without using +.
- As Close As You Can (Hard): Given an array and a target, return the sum of the three numbers that comes closest to the target.
- Asteroid Collision (Hard): Given a row of asteroids, where positive ones fly right and negative ones fly left, return what's left after every crash.
- Biggest Number (Hard): Given a list of numbers, arrange them so that joining them together makes the biggest possible number, and return it as a string.
- Count Every Mirror (Hard): Given a string, return how many of its substrings are palindromes, counting every single letter.
- Cut Into Mirrors (Hard): Given a string, return how many ways you can cut it into pieces that are all palindromes.
- Cut the String (Hard): Given a string, cut it into as many pieces as you can so no letter shows up in more than one piece, and return the piece lengths.
- Decode the Message (Hard): Given a string of digits where 1 means A and 26 means Z, return how many ways it can be decoded.
- Does It Loop? (Hard): Given a list where next[i] is the index node i points to, and -1 means the end, return true if following the links from node 0 loops forever.
- Drop Every Duplicate (Hard): Given a sorted linked list, passed in as its values, remove EVERY value that appears more than once, keeping only the values that showed up exactly once.
- Every Order (Hard): Given a list, return every possible ordering of it.
- Fairest Split (Hard): Given an array and k, split it into k chunks in a row so the biggest chunk sum is as small as possible, and return that sum.
- Fewest Jumps (Hard): Given an array where each value is the farthest you can jump from that spot, return the FEWEST jumps to reach the last index.
- Fewest Top-Ups (Hard): Given gas stations as [position, fuel], your starting fuel, and a target distance, return the fewest stops to reach the target, or -1 if you can't.
- Find the Word (Hard): Given a grid of letters and a word, return true if you can spell the word by moving up, down, left, or right, without using any cell twice.
- Handing Out Sweets (Hard): Given kids' ratings in a row, give each kid at least one candy, and give any kid rated higher than a neighbor more candy than that neighbor.
- Is It a Search Tree? (Hard): Given a binary tree, return true if it's a valid binary search tree, where everything on the left is smaller and everything on the right is bigger.
- Is It Balanced? (Hard): Given a binary tree, return true if at every node, the left and right subtrees' heights differ by at most 1.
- Letters on the Keypad (Hard): Given a string of phone keypad digits from 2 to 9, return every letter combination they could spell.
- Longest Mirror Inside (Hard): Given a string, return its longest palindrome substring.
- Lowest Common Ancestor (Hard): Given a binary tree and two values p and q, return the value of their lowest common ancestor, the deepest node that has both below it (or is one of them).
- Merge Intervals (Hard): Given a list of [start, end] intervals, merge every pair that overlaps and return the result.
- Minimum Path Sum (Hard): Given a grid of costs, return the cheapest total to get from the top-left to the bottom-right, moving only right or down.
- N Queens (Hard): Given n, return how many ways you can place n queens on an n by n chessboard so no two attack each other.
- Nearest to Nothing (Hard): Given an array, return the sum of the pair that comes closest to 0.
- Never Decreasing (Hard): Given n, return the biggest number no larger than n whose digits never go down from left to right.
- One Deletion Allowed (Hard): Given a string, return true if deleting at most one character makes it a palindrome.
- Path to a Target (Hard): Given a binary tree and a target, return true if some path from the root down to a LEAF adds up to exactly the target.
- Plus or Minus (Hard): Given a list of numbers and a target, return how many ways you can put a + or - in front of each number so they add up to the target.
- Rebuild the Address (Hard): Given a string of digits, return every valid IP address you can make by adding three dots.
- Reverse a Section (Hard): Given a linked list, passed in as its values, and two positions left and right (starting from 0), reverse just the part from left to right and leave the rest alone.
- Round the Loop (Hard): Given the gas at each station around a loop and the cost to drive to the next one, return the station you can start from to make it all the way around, or -1.
- Shrink the Number (Hard): Given a number as a string and k, remove k digits to make the smallest possible number, with no leading zeros, and return it.
- Sliding Window Maximum (Hard): Given an array and a window size k, return the biggest number in every run of k numbers in a row.
- Slowest Safe Speed (Hard): Given pile sizes and a number of hours, return the slowest eating speed that finishes every pile in time.
- Smallest in a Rotated List (Hard): Given a sorted array that's been rotated, like [3, 4, 5, 1, 2], return its smallest value.
- Smallest Ship (Hard): Given parcel weights in order and a number of days, return the smallest ship capacity that ships everything in time.
- Sort Using a Stack (Hard): Given a stack, sort it using only one extra stack, and return it from smallest at the bottom to largest on top.
- Spiral Matrix Order (Hard): Given a matrix, return its values in spiral order: across the top, down the right side, back along the bottom, up the left side, then inward.
- Split It Evenly (Hard): Given a list of numbers, return true if you can split them into two groups with equal sums.
- Split the Loot (Hard): Given item weights, item values, and a capacity, return the most value you can carry when you can take part of an item, rounded to 2 decimals.
- Split the Trip (Hard): Given each person's cost to fly to city A or city B, send exactly half to each and return the smallest total.
- Stock Span (Hard): Given daily stock prices, return each day's span: how many days in a row, ending today, the price was less than or equal to today's.
- The Gray Code Walk (Hard): Given n, return the n-bit Gray code sequence, where each number differs from the one before by exactly one bit.
- The One That Came Once (Hard): Given a list where every value appears three times except one, return the one that appears once.
- The Part That Is Wrong (Hard): Given an array, return the length of the shortest stretch that, if you sorted just that stretch, would make the whole array sorted.
- The Two That Came Once (Hard): Given a list where every value appears twice except two, return those two, smaller first.
- Three Buckets, One Pass (Hard): Given an array of 0s, 1s, and 2s, sort it in ONE pass.
- Three That Cancel (Hard): Given an array, return every unique set of three numbers that adds up to 0.
- Trapping Rain Water (Hard): Given a list of bar heights, return how much rainwater gets trapped between them.
- Well-Formed Brackets (Hard): Given n, return every balanced string of n pairs of parentheses.
- Widest Span (Hard): Given a binary tree, return the length, in edges, of the longest path between any two nodes.
Practice another pattern
Or browse by subject
Browse all 676 puzzles