Problems
- 1 Two SumFree Given a list of integers and a target value, return the positions of the two numbers that add up to the target. Exactly one pair works, you may not use the same element twice, and the positions can be returned in either order. The list is not sorted.
- 2 Logger Rate LimiterFree · sign up Design a logger that receives a stream of (timestamp, message) calls in non-decreasing time order. should_print(timestamp, message) returns True if the message should be printed, and False if the same message was printed less than 10 seconds ago. A message printed at time t blocks repeats until t...
- 3 Group AnagramsFree Given a list of lowercase words, put words that are anagrams of each other into the same group and return the groups. Two words are anagrams if one is a rearrangement of the other's letters ("listen" and "silent"). Groups, and the words inside them, can be returned in any order.
- 4 Product of Array Except SelfFree · sign up Given an integer array nums, return an array out where out[i] is the product of every element except nums[i]. Do it in O(n) time without using division. Follow-up: use O(1) extra space, not counting the output array. You may assume every such product fits in a 32-bit integer.
- 5 Subarray Sum Equals KFree Given an array of integers and a number k, count how many contiguous subarrays add up to exactly k. The array can contain negative numbers and zeros. Subarrays at different positions count separately, even if they hold the same values.
- 6 Insert Delete GetRandom O(1)Free · sign up Design a set of integers with three operations, each in O(1) average time: insert(val) adds val and returns true if it was not already present; remove(val) deletes val and returns true if it was present; getRandom() returns a uniformly random element of the current set. getRandom is only called w...
- 7 Find Duplicate File in SystemFree · sign up You are given a list of directory listings. Each string is a directory path followed by one or more files written as name(content), separated by single spaces. Return every group of two or more files that have identical content, as lists of full paths (directory/name). Files with unique content a...
- 8 Count PrimesFree · sign up Given an integer n, return how many prime numbers are strictly less than n. A prime is an integer greater than 1 whose only divisors are 1 and itself. n can be as large as 5 million.
- 9 Valid PalindromeFree · sign up Given a string, decide whether it reads the same forwards and backwards once you keep only letters and digits and ignore upper/lower case. Spaces, punctuation and every other character are skipped. An empty string, or one with no letters or digits at all, counts as a palindrome.
- 10 Valid Palindrome IIFree Given a string, return true if it can be made into a palindrome by deleting at most one character. A palindrome reads the same forwards and backwards. A string that is already a palindrome counts as true.
- 11 3SumFree · sign up Given an array of integers, return every distinct triple of values that adds up to zero. The three values must come from three different positions, and the same triple of values must not appear twice in the answer. The order of triples, and of values inside a triple, doesn't matter.
- 12 Container With Most WaterFree · sign up You get n vertical walls of heights height[0..n−1], standing at x = 0, 1, …, n − 1. Choose two walls; together with the ground they hold water up to the height of the shorter wall. Return the largest amount of water any pair can hold: (j − i) · min(height[i], height[j]). The walls in between don'...
- 13 Sort ColorsFree · sign up An array contains only the values 0, 1 and 2. Sort it in place so that all 0s come first, then all 1s, then all 2s, without using a library sort. Aim for a single pass and O(1) extra space.
- 14 String CompressionFree · sign up Compress an array of characters in place. Replace every run of the same character with the character followed by the run's length, but only write the length when the run is longer than 1. A length of 10 or more takes one array cell per digit. Return the new length; only the first that many cells ...
- 15 Trapping Rain WaterFree · sign up You are given the heights of bars of width 1 standing side by side. After it rains, how many units of water are trapped between them? Water above a bar can rise only as high as the shorter of the tallest bars to its left and right; water at the ends runs off.
- 16 Best Time to Buy and Sell StockFree · sign up You are given a list of daily prices for one stock. Choose one day to buy and a later day to sell to make the largest profit, and return that profit. If no profit is possible, return 0. You must buy before you sell, and you make exactly one transaction at most.
- 17 Longest Substring Without Repeating CharactersFree · sign up Given a string, return the length of the longest substring that contains no repeated character. A substring is a contiguous run of characters, so "pwke" picked from "pwwkew" doesn't count.
- 18 Longest Repeating Character ReplacementFree · sign up Given a string of uppercase letters and an integer k, you may change at most k characters to any other uppercase letter. Return the length of the longest substring that can be made of a single repeated letter.
- 19 Max Consecutive Ones IIIFree · sign up Given a binary array and an integer k, return the length of the longest run of consecutive 1s you can get by flipping at most k zeros to 1.
- 20 Design Hit CounterFree · sign up Build a counter that records hits and reports how many hits happened in the last 5 minutes (300 seconds). hit(timestamp) records one hit at that second. getHits(timestamp) returns the number of hits in the window (timestamp − 300, timestamp]. Timestamps are in seconds and never decrease between c...
- 21 Minimum Window SubstringFree · sign up Given two strings s and t, return the shortest contiguous substring of s that contains every character of t, including repeats. If t has two A's, the window needs at least two A's. If no such window exists, return an empty string.
- 22 Sliding Window MaximumFree · sign up Given an array of integers nums and a window size k, return the maximum of every contiguous window of length k, from left to right. There are n − k + 1 windows. A frequent second part: return the length of the longest subarray in which the largest and smallest values differ by at most limit.
- 23 Search in Rotated Sorted ArrayFree · sign up A sorted array of distinct integers has been rotated at some unknown position (for example [0, 1, 2, 4, 5, 6, 7] became [4, 5, 6, 7, 0, 1, 2]). Given the rotated array and a target, return the target's index, or −1 if it isn't there, in O(log n) time.
- 24 Find First and Last Position of Element in Sorted ArrayFree · sign up Given an array of integers sorted in non-decreasing order and a target value, return the first and last index at which the target appears, as [first, last]. If the target isn't in the array, return [-1, -1]. The solution must run in O(log n) time.
- 25 Find Peak ElementFree · sign up Given an array where no two neighbours are equal, return the index of any peak: an element strictly greater than its neighbours. Positions outside the array count as −∞, so the first and last elements can be peaks. Your algorithm must run in O(log n) time.
- 26 Koko Eating BananasFree · sign up There are several piles of bananas and h hours before the guards return. Each hour, Koko picks one pile and eats up to k bananas from it; if the pile has fewer than k, she finishes it and waits for the next hour. Return the smallest integer speed k that lets her finish every pile within h hours. ...
- 27 Time Based Key-Value StoreFree · sign up Design a key-value store that remembers every version of a value. set(key, value, timestamp) stores value for key at time timestamp. get(key, timestamp) returns the value whose timestamp is the largest one at or before timestamp, or an empty string if the key had no value yet. For each key, set i...
- 28 Random Pick with WeightFree · sign up You are given an array of positive integer weights w. Implement pickIndex(), which returns a random index i with probability w[i] / sum(w). pickIndex will be called many times, so it must be fast after a one-time setup.
- 29 Median of Two Sorted ArraysFree · sign up Given two sorted arrays of sizes m and n, return the median of all their numbers combined, in O(log(min(m, n))) time. With an odd total the median is the middle number; with an even total it is the average of the two middle numbers. Either array may be empty, but not both.
- 30 Merge IntervalsFree · sign up Given a list of intervals, merge every group of overlapping intervals and return the result. Each interval is a pair [start, end] with start ≤ end. Two intervals overlap if they share at least one point, so [1, 3] and [3, 5] merge into [1, 5]. The input is not sorted.
- 31 Insert IntervalFree · sign up You have a list of non-overlapping intervals sorted by start, and one new interval. Insert the new interval so the list stays sorted and non-overlapping, merging wherever it overlaps, and return the result. Intervals are closed: [1, 3] and [3, 5] overlap.
- 32 Non-overlapping IntervalsFree · sign up Given a list of intervals [start, end], return the minimum number of intervals to remove so that the remaining ones don't overlap. Intervals that only touch, such as [4, 6] and [6, 8], do not overlap.
- 33 Meeting Rooms IIFree · sign up Given a list of meetings as [start, end] times, return the minimum number of conference rooms needed so that no two meetings in the same room overlap. A meeting that ends at time t frees its room for a meeting that starts at t.
- 34 Design Memory AllocatorFree · sign up Simulate a memory of n units, all free at the start. allocate(size, id) finds the leftmost run of size consecutive free units, marks them as owned by id and returns the start index, or −1 if no such run exists. free(id) releases every unit owned by id and returns how many units it freed. The same...
- 35 Valid ParenthesesFree · sign up Given a string containing only the characters ( ) [ ] { }, decide whether it is valid: every opening bracket is closed by a bracket of the same type, and brackets close in the correct order. An empty string is valid.
- 36 Min StackFree · sign up Design a stack that supports push(x), pop(), top() and getMin(), all in O(1) time. getMin returns the smallest value currently in the stack. You may assume pop, top and getMin are only called on a non-empty stack.
- 37 Minimum Remove to Make Valid ParenthesesFree · sign up Given a string of lowercase letters and the characters ( and ), remove the fewest brackets so that the brackets in the result are balanced, and return any such result. Letters are never removed.
- 38 Evaluate Reverse Polish NotationFree · sign up Evaluate an arithmetic expression written in Reverse Polish Notation (postfix) and return its integer value. The input is a list of tokens: integers (possibly negative) and the operators +, -, *, /. Each operator applies to the two values produced just before it. Division truncates toward zero. T...
- 39 Daily TemperaturesFree · sign up Given a list of daily temperatures, return for each day how many days you must wait for a strictly warmer day. If no warmer day comes later, the answer for that day is 0.
- 40 Decode StringFree · sign up Expand a compressed string. In the input, k[text] means "text repeated k times", where k is a positive integer and can have several digits. Brackets can be nested, and plain letters can appear anywhere. The input is always well formed. Return the fully expanded string.
- 41 Basic Calculator IIFree · sign up Given a string with non-negative integers, the operators + − * / and spaces (no brackets), evaluate it with the usual precedence and return the result. Integer division truncates toward zero. The expression is always valid, and you may not use a built-in expression evaluator.
- 42 Simplify PathFree · sign up Given an absolute Unix-style path, return its shortest equivalent form. In the input, . means the current directory, .. means the parent directory (at the root it stays at the root), and several slashes in a row count as one. Any other name, including ..., is an ordinary directory name. The resul...
- 43 Largest Rectangle in HistogramFree · sign up Given the heights of bars in a histogram, each bar 1 unit wide and standing next to each other, return the area of the largest rectangle that fits entirely under the bars.
- 44 Reverse Linked ListFree · sign up Given the head of a singly linked list, reverse the list and return the new head. Change the links, not the values, and use O(1) extra space for the iterative version.
- 45 Merge Two Sorted ListsFree · sign up Given the heads of two sorted singly linked lists, merge them into one sorted list by splicing their nodes together, and return its head. Reuse the existing nodes; either list may be empty.
- 46 Add Two NumbersFree · sign up Two non-negative integers are stored as linked lists of digits, lowest digit first. Return their sum as a list in the same format. Each node holds one digit 0–9. The numbers have no leading zeros, except the number 0 itself, which is a single node [0].
- 47 Copy List with Random PointerFree · sign up Each node of a linked list has a value, a next pointer and a random pointer that can point at any node in the list or be null. Return a deep copy: brand-new nodes with the same values, whose next and random pointers mirror the original structure. No pointer in the copy may point into the original...
- 48 Kth Largest Element in an ArrayFree · sign up Given an unsorted array of integers and a number k, return the k-th largest element. This means the k-th largest in sorted order, not the k-th distinct value: in [3, 3, 1], the 2nd largest is 3. Try to do better than sorting the whole array.
- 49 Top K Frequent ElementsFree · sign up Given an array of integers and a number k, return the k values that occur most often. The answer is guaranteed to be unique, and it can be returned in any order. Aim for better than O(n log n).
- 50 K Closest Points to OriginFree · sign up Given a list of points [x, y] on a plane and an integer k, return the k points closest to the origin (0, 0). Distance is ordinary straight-line (Euclidean) distance. The answer may be in any order, and you may assume it is unique (no tie at the k-th place), or ask what to do with ties.
- 51 Task SchedulerFree · sign up A CPU must run a list of tasks, each labelled with a letter A–Z; every task takes one time unit. Tasks may run in any order, but two runs of the same letter must have at least n time units between them, during which the CPU runs other tasks or sits idle. Return the minimum number of time units ne...
- 52 Merge k Sorted ListsFree · sign up Given k sorted linked lists, merge them all into one sorted linked list and return its head. Any of the lists may be empty, and k may be zero.
- 53 Find Median from Data StreamFree · sign up Numbers arrive one at a time. After any of them, you may be asked for the median of everything seen so far. Implement addNum(num) and findMedian(). With an odd count the median is the middle value; with an even count it is the average of the two middle values.
- 54 Sliding Window MedianFree · sign up Given an array of numbers and a window size k, return the median of every window of k consecutive numbers as the window slides from left to right. With an even k, the median is the average of the two middle values. Return the medians as floating-point numbers.
- 55 Maximum Depth of Binary TreeFree · sign up Given the root of a binary tree, return its maximum depth: the number of nodes on the longest path from the root down to a leaf. An empty tree has depth 0, and a tree with just a root has depth 1.
- 56 Diameter of Binary TreeFree · sign up Given the root of a binary tree, return the length of its diameter: the number of edges on the longest path between any two nodes. The path may or may not pass through the root. An empty tree or a single node has diameter 0.
- 57 Validate Binary Search TreeFree · sign up Given the root of a binary tree, decide whether it is a valid binary search tree: for every node, all values in its left subtree are strictly smaller and all values in its right subtree are strictly larger. Duplicates are not allowed.
- 58 Lowest Common Ancestor of a Binary TreeFree · sign up Given a binary tree and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both p and q as descendants. A node counts as a descendant of itself. Both nodes are guaranteed to be in the tree, and values are unique.
- 59 Construct Binary Tree from Preorder and Inorder TraversalFree · sign up Given two integer arrays preorder and inorder that are the preorder and inorder traversals of the same binary tree with distinct values, rebuild and return the tree. A common warm-up in the same round: build a tree from a level-order list such as [8, 3, 10, 1, 6, null, 14], then return its preord...
- 60 Flatten a Nested JSON ObjectFree · sign up Part 1: write flatten(obj), which turns a nested JSON-style object into a single-level map from path to value. Paths join keys with "."; list elements use their index as the key. Leaf values (strings, numbers, booleans, null) are copied as they are, and an empty object or list is kept as a leaf s...
- 61 Binary Tree Maximum Path SumFree · sign up Given the root of a binary tree, return the largest sum of any path in it. A path is a chain of nodes where each pair of neighbors is joined by an edge, and no node appears twice. It must contain at least one node, it can start and end anywhere, and it does not have to pass through the root. Node...
- 62 Serialize and Deserialize Binary TreeFree · sign up Design two functions for a binary tree: serialize turns a tree into a string, and deserialize turns that string back into a tree with exactly the same shape and values. You choose the string format. Node values are integers and may be negative. The tree can be empty.
- 63 Binary Tree Level Order TraversalFree · sign up Given the root of a binary tree, return its values level by level: a list of lists, where each inner list holds one level's values from left to right.
- 64 Binary Tree Right Side ViewFree · sign up Given the root of a binary tree, imagine standing to its right and looking left. Return the values you can see, from top to bottom. On each level you see exactly one node: the one furthest to the right on that level.
- 65 All Nodes Distance K in Binary TreeFree · sign up Given the root of a binary tree, a target node in it, and an integer k, return the values of all nodes that are exactly k edges away from the target. Paths may go up through parents as well as down through children. Node values are unique; return them in any order.
- 66 Implement Trie (Prefix Tree)Free · sign up Build a trie (prefix tree) class with three methods: insert(word) adds a word, search(word) returns true if that exact word was inserted, and startsWith(prefix) returns true if any inserted word begins with the prefix. Words use lowercase English letters.
- 67 Design Add and Search Words Data StructureFree · sign up Design a word dictionary with two operations. addWord(word) stores a lowercase word. search(pattern) returns true if any stored word matches the pattern exactly, where each . in the pattern matches any single letter. The match must cover the whole word, not just a prefix.
- 68 Search Suggestions SystemFree · sign up Given a list of product names and a search word typed one letter at a time, return, after each letter, up to three product names that start with the typed prefix, in alphabetical order. If fewer than three match, return those that do; if none match, return an empty list for that letter.
- 69 Word Search IIFree · sign up You get a grid of letters and a list of words. Return every word from the list that can be traced on the grid. A word is traced by starting at any cell and moving up, down, left or right to the next letter, without using the same cell twice in that word. Return each found word once, in any order.
- 70 Design In-Memory File SystemFree · sign up Build an in-memory file system that works with absolute paths such as /courses/system-design/cache.md. Support four operations. mkdir(path) creates the folder and any missing parent folders. addContentToFile(path, content) creates the file if needed (and its parent folders) and appends content. r...
- 71 Number of IslandsFree · sign up Given a grid of "1" (land) and "0" (water), count the islands. An island is a group of land cells connected horizontally or vertically; diagonal neighbours don't connect. Everything outside the grid is water.
- 72 Clone GraphFree · sign up Given a reference to one node of a connected undirected graph, return a deep copy of the whole graph. Each node has a value and a list of neighbours. The copy must use only new nodes, with the same values and the same connections.
- 73 Rotting OrangesFree · sign up A grid holds empty cells (0), fresh oranges (1) and rotten oranges (2). Every minute, each rotten orange rots the fresh oranges directly above, below, left and right of it. Return the number of minutes until no fresh orange remains, or −1 if that never happens.
- 74 Shortest Path in Binary MatrixFree · sign up Given an n × n grid of 0s (open) and 1s (blocked), return the number of cells on the shortest path from the top-left cell to the bottom-right cell, moving through open cells only. From a cell you may step to any of its 8 neighbours (including diagonals). If either corner is blocked or no path exi...
- 75 Network Delay TimeFree · sign up A network has n nodes labeled 1 to n and directed links (u, v, w): a signal sent from u reaches v after w time units. A signal starts at node k at time 0. Return the time when every node has received it, or −1 if some node never does. Delays are non-negative.
- 76 Evaluate DivisionFree · sign up You know some exchange rates and must answer conversion queries. Each rate (a, b, r) means one unit of currency a buys r units of b (r > 0), and all rates are consistent with each other. For each query (x, y), return how many units of y one unit of x buys, or -1.0 if it can't be worked out from t...
- 77 Web Crawler MultithreadedFree · sign up Write a crawler that, starting from one URL, returns every page reachable on the same host. You are given getUrls(url), which downloads a page and returns the links on it. It is slow (a network call of about 200 ms) but safe to call from several threads at once. Follow only links whose host match...
- 78 Word LadderFree · sign up Given a start word, a target word and a dictionary, return the number of words in the shortest sequence that turns the start word into the target. Each step changes exactly one letter, and every word after the start must be in the dictionary. All words have the same length. If no sequence exists,...
- 79 Bus RoutesFree · sign up A city has bus routes; routes[i] lists the stops that bus i visits, and each bus runs its loop forever in both directions. You are at stop source and want to reach stop target. Return the fewest buses you must board, or −1 if it can't be done. Riding further on a bus you're already on costs nothi...
- 80 Course ScheduleFree · sign up There are n courses labelled 0 to n − 1 and a list of prerequisite pairs [a, b], meaning you must take b before a. Return true if it is possible to finish every course.
- 81 Course Schedule IIFree · sign up There are n courses labelled 0 to n − 1 and a list of pairs [course, pre], meaning pre must be taken before course. Return any order in which all courses can be taken, or an empty list if that is impossible. A common second part: if you may take any number of courses in one semester as long as th...
- 82 Alien DictionaryFree · sign up An alien language uses lowercase English letters, but in an unknown order. You get a list of words that is already sorted in that alien order. Return a string of all letters that appear, in an order consistent with the list. If no order can produce this sorting, return an empty string. If several...
- 83 Longest Increasing Path in a MatrixFree · sign up Given an R × C grid of integers, return the length of the longest path in which each step moves up, down, left or right to a strictly larger value. The length counts cells. Diagonal moves and wrapping around the edges are not allowed; the path may start anywhere.
- 84 Number of Connected Components in an Undirected GraphFree · sign up You get n nodes labeled 0 to n − 1 and a list of undirected edges. Return the number of connected components: groups of nodes where every node can reach every other node in the group through edges. A node with no edges is a component by itself.
- 85 Accounts MergeFree · sign up You get a list of accounts. Each account is a name followed by one or more email addresses. Two accounts belong to the same person if they share at least one email, and this is transitive: if A shares an email with B and B with C, all three are one person. Merge the accounts and return each perso...
- 86 Number of Islands IIFree · sign up An m × n grid starts as all water. A list of positions turns cells into land, one at a time. After each addition, report the number of islands, where an island is a group of land cells connected horizontally or vertically. A position may be added more than once.
- 87 SubsetsFree · sign up Given a list of distinct integers, return all of its subsets (the power set). Each subset is a list of some of the numbers, including the empty subset and the full list. The result must not contain the same subset twice, and subsets and their contents may be in any order.
- 88 PermutationsFree · sign up Given a list of distinct integers, return every possible ordering of them. The orderings can be returned in any order. With n numbers there are n! of them, so n is small (at most about 8).
- 89 Combination SumFree · sign up Given an array of distinct positive integers candidates and a positive target, return every unique combination of candidates whose sum is exactly target. Each number may be used any number of times. Two combinations are the same if they use the same numbers the same number of times, in any order,...
- 90 Word SearchFree · sign up Given a grid of letters and a word, decide whether the word can be spelled by a path through the grid. The path moves one cell up, down, left or right at each step (no diagonals), and no cell may be used twice in the same path.
- 91 N-QueensFree · sign up Place n queens on an n × n chessboard so that no two queens attack each other: no two may share a row, a column or a diagonal. Return every distinct arrangement, each as a list of n strings where Q marks a queen and . an empty square.
- 92 Optimal Account BalancingFree · sign up A group of friends recorded who lent money to whom. Each record is [lender, borrower, amount]. Return the minimum number of payments needed so that everyone ends up even. Any person may pay any other person any amount.
- 93 Maximum SubarrayFree · sign up Given an array of integers, find the contiguous subarray (at least one element) with the largest sum, and return that sum. The numbers can be negative.
- 94 House RobberFree · sign up A row of houses each holds some money (a non-negative integer). Choose houses to take money from so that no two chosen houses are next to each other, and return the largest total you can collect.
- 95 Coin ChangeFree · sign up Given a list of coin values and a target amount, return the smallest number of coins that add up to exactly that amount, or −1 if it can't be done. You have an unlimited supply of each coin value.
- 96 Word BreakFree · sign up Given a string and a list of dictionary words, decide whether the string can be cut into a sequence of one or more dictionary words. Each word can be used any number of times, and every letter must belong to exactly one word.
- 97 Longest Increasing SubsequenceFree · sign up Given a list of integers, return the length of its longest strictly increasing subsequence. A subsequence keeps the original order but may skip any elements; it does not need to be contiguous.
- 98 Longest Common SubsequenceFree · sign up Given two strings text1 and text2, return the length of their longest common subsequence, or 0 if they share no characters. A subsequence keeps the original order of characters but may skip any of them: "one" is a subsequence of "stone", while "eno" is not.
- 99 Longest Palindromic SubstringFree · sign up Given a string, return its longest contiguous substring that reads the same forwards and backwards. If several have the same maximum length, any one of them is accepted.
- 100 Partition Equal Subset SumFree · sign up Given an array of positive integers, decide whether it can be split into two groups with equal sums. Every number goes into exactly one group. The same question is often asked in its general form: is there a subset whose sum is exactly target? Partition is that question with target = sum / 2.
- Maximal SquareFree · sign up Given an m × n grid of '0' and '1' characters, return the area of the largest square that contains only '1's. The square's sides are parallel to the grid. If the grid has no '1' at all, return 0.
- Edit DistanceFree · sign up Given two strings, return the smallest number of single-character edits that turn the first into the second. An edit is inserting one character, deleting one character, or replacing one character with another.
- Jump GameFree · sign up You start at index 0 of an array of non-negative integers. Each value is the longest jump you may take from that position (any shorter jump is also allowed). Return whether you can reach the last index.
- Jump Game IIFree · sign up You start at index 0 of an array of non-negative integers. The value at each index is the longest jump you may make from there (you can also jump shorter). Return the minimum number of jumps needed to reach the last index. The input guarantees the last index is reachable.
- Gas StationFree · sign up n gas stations stand on a circular road. At station i you can pick up gas[i] units of fuel, and driving from station i to station i + 1 (from the last station back to station 0) burns cost[i] units. Your car starts with an empty tank of unlimited size. Return the index of a station from which you...
- Partition LabelsFree · sign up Split a string of lowercase letters into as many pieces as possible so that every letter appears in at most one piece. Return the sizes of the pieces in order. Joining the pieces must give back the original string.
- CandyFree · sign up Children stand in a line, each with a rating. Give each child at least one candy, and give any child with a higher rating than a direct neighbour more candies than that neighbour. Return the minimum total number of candies. Neighbours with equal ratings have no constraint between them.
- Rotate ImageFree · sign up Given an n × n matrix, rotate it 90 degrees clockwise in place. You must change the input matrix directly; allocating a second n × n matrix is not allowed.
- Spiral MatrixFree · sign up Given an m × n matrix, return all of its elements in spiral order: start at the top-left corner, go right along the top row, down the right column, left along the bottom row, up the left column, and keep going inward ring by ring until every element has been visited once.
- Game of LifeFree · sign up A grid of cells, each alive (1) or dead (0), moves forward one generation. Every cell looks at its eight neighbours (horizontal, vertical, diagonal). A live cell with 2 or 3 live neighbours stays alive; any other live cell dies. A dead cell with exactly 3 live neighbours comes alive. All cells ch...
- Text JustificationFree · sign up Given a list of words and a line width, lay the words out in lines of exactly that width. Put as many words on each line as fit with at least one space between them. Then spread the line's spaces as evenly as possible between its words; if they don't divide evenly, the gaps on the left get the ex...
- LRU CacheFree · sign up Design a cache with a fixed capacity that supports get(key) and put(key, value), both in O(1) average time. get returns the value or −1 if the key is missing. put inserts or updates a key; if that pushes the cache over capacity, it first removes the least recently used key. Both get and put count...
- Design Circular QueueFree · sign up Implement a queue with a fixed capacity k on top of an array, reusing slots as items leave. Support enQueue(value) (false if full), deQueue() (false if empty), Front() and Rear() (−1 if empty), isEmpty() and isFull(), all in O(1) time without moving elements.
- Design Tic-Tac-ToeFree · sign up Design a tic-tac-toe game for two players on an n × n board. move(row, col, player) places the player's mark and returns the winner after that move: 1 or 2, or 0 if nobody has won yet. A player wins by filling a whole row, a whole column, or either diagonal. Moves are always valid (the cell is em...
- Implement a Rate LimiterFree · sign up Build an in-process rate limiter. allow(client_id, timestamp) returns true if the request may go through and false if it must be rejected. Part 1: each client may make at most N requests in any window of W seconds (a sliding window, not fixed buckets). Part 2: support several rules at once, for e...
- Resumable IteratorFree · sign up Build an iterator that can save and restore its position. It supports has_next(), next(), get_state() and set_state(state). get_state() returns a plain value (something you could write as JSON); passing it to set_state later, even on a fresh iterator over the same data in a new process, makes the...
- Implement an In-Memory Key-Value StoreFree · sign up Build an in-memory key-value store, one level at a time. Every call receives the current time now as an integer, so the store never reads a clock.
- Simple Bank SystemFree · sign up Build a small bank with accounts numbered 1 to n and their starting balances. Every request carries a time t that never decreases.
- LFU CacheFree · sign up Design a cache with a fixed capacity that supports get(key) and put(key, value) in O(1) average time. get returns the value or −1. put inserts or updates a key. When the cache is full and a new key arrives, evict the key that has been used the fewest times; if several keys tie, evict the one whos...
- Design SpreadsheetFree · sign up Build a small spreadsheet engine. Cells are named like A1 or C7. set(cell, text) stores either a number ("12") or a formula that adds cells and numbers ("=A1+B1+5"). get(cell) returns the cell's current value; an empty cell is 0. When a cell changes, every formula that depends on it, directly or ...