Coding practice
Coding problems with tests, learning cards and lessons.
Topic cards
- Getting Started — How EngiLipi Practice works, how to think about complexity, and two warm-up problems.
- Arrays 101 — The most fundamental data structure: indexing, inserting, deleting and in-place two-pointer techniques.
- Strings — Character manipulation, palindromes and the sliding-window pattern.
- Hash Table — O(1) average lookups with Map and Set — counting, de-duplication and the complement trick.
- Linked List — Nodes and pointers: traversal, reversal, the fast/slow technique and dummy heads.
- Queue & Stack — LIFO and FIFO structures, bracket matching, expression evaluation and monotonic stacks.
- Binary Search — Halve the search space every step: templates, lower bounds and rotated arrays.
- Binary Tree — Traversals, recursion on trees, BFS level order and classic depth/path problems.
- Dynamic Programming — Turn exponential recursion into polynomial time with memoisation and tabulation.
- Graph — Grids and networks: DFS, BFS, union-find, topological sort and shortest paths.
- Sorting — Comparison sorts, partitioning, quickselect and sorting as a problem-solving tool.
- Top Interview Questions — A curated collection of the most frequently asked coding-interview problems, grouped by difficulty.
- Binary Search Tree — Ordered trees: search, insert, inorder order, ancestors and in-place repairs.
- Matrix — 2-D arrays: traversal orders, in-place transformations and simulations.
- Two Pointers & Sliding Window — Linear-time patterns on arrays and strings: opposite-end pointers, k-Sum and variable windows.
- Heap / Priority Queue — Always know the smallest (or largest) element: top-k, streams, scheduling and greedy choices.
- Trie — Prefix trees for autocomplete, dictionaries and multi-word search.
- Backtracking — Systematically explore choices — subsets, permutations, combinations, grids and N-Queens.
- Greedy — Make the locally best choice and prove it never hurts: intervals, jumps, scheduling and change-making.
- Bit Manipulation — Work directly on binary: masks, XOR tricks, popcount and bit-by-bit construction.
- Math & Number Theory — Digits, primes, bases, exponentiation, big-number arithmetic and geometry.
- Data Structure Design — Build classes with guaranteed complexity: caches, hash maps, ring buffers and history stacks.
- Hard Challenges — Every hard problem in the library in one place — the final boss for each topic.
Lessons
- How Practice works — Lesson in the Getting Started card.
- Big-O in 5 minutes — Lesson in the Getting Started card.
- What is an array? — Lesson in the Arrays 101 card.
- Insertion and deletion costs — Lesson in the Arrays 101 card.
- The two-pointer technique — Lesson in the Arrays 101 card.
- Working with strings — Lesson in the Strings card.
- The sliding-window pattern — Lesson in the Strings card.
- How hash tables work — Lesson in the Hash Table card.
- Choosing a good key — Lesson in the Hash Table card.
- Nodes and pointers — Lesson in the Linked List card.
- Fast & slow pointers — Lesson in the Linked List card.
- Stacks and queues — Lesson in the Queue & Stack card.
- The monotonic stack — Lesson in the Queue & Stack card.
- How binary search works — Lesson in the Binary Search card.
- Lower bound and searching on answers — Lesson in the Binary Search card.
- Tree basics & traversals — Lesson in the Binary Tree card.
- Top-down and bottom-up thinking — Lesson in the Binary Tree card.
- What is dynamic programming? — Lesson in the Dynamic Programming card.
- Unbounded choice, grids and strings — Lesson in the Dynamic Programming card.
- Representing and traversing graphs — Lesson in the Graph card.
- Union-Find, topological sort, Dijkstra — Lesson in the Graph card.
- Sorting algorithms compared — Lesson in the Sorting card.
- Sort first, then sweep — Lesson in the Sorting card.
- How to approach an interview problem — Lesson in the Top Interview Questions card.
- What makes a BST — Lesson in the Binary Search Tree card.
- Working with 2-D arrays — Lesson in the Matrix card.
- Choosing which pointer to move — Lesson in the Two Pointers & Sliding Window card.
- Fixed vs variable windows — Lesson in the Two Pointers & Sliding Window card.
- Binary heaps in JavaScript — Lesson in the Heap / Priority Queue card.
- How a trie works — Lesson in the Trie card.
- Choose, explore, un-choose — Lesson in the Backtracking card.
- Why greedy works (and when it fails) — Lesson in the Greedy card.
- Bitwise operators and tricks — Lesson in the Bit Manipulation card.
- Math toolkit for coding problems — Lesson in the Math & Number Theory card.
- How design problems are judged — Lesson in the Data Structure Design card.
Easy problems
- Fizz Buzz — Given an integer n , return an array answer of length n (1-indexed) where: "FizzBuzz" if i is divisible by both 3 and 5, "Fizz" if i is divisible by 3, "Buzz" if i is divisible by
- Running Sum of 1D Array — Return the running sum of nums , where runningSum[i] = nums[0] + … + nums[i] .
- Max Consecutive Ones — Given a binary array nums , return the maximum number of consecutive 1 s in the array.
- Squares of a Sorted Array — Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number, also sorted in non-decreasing order.
- Remove Element — Remove all occurrences of val from nums in place and return k , the number of remaining elements. The first k elements of nums must hold the kept values (in any order); anything af
- Remove Duplicates from Sorted Array — Given a sorted array nums , remove the duplicates in place so each unique element appears once, keeping the original order. Return k , the number of unique elements; the first k el
- Move Zeroes — Move all 0 s to the end of nums while keeping the relative order of the non-zero elements. Do this in place — do not return anything.
- Merge Sorted Array — nums1 has length m + n : its first m elements are sorted values and the last n are zeros (space). nums2 holds n sorted values. Merge nums2 into nums1 in place so that nums1 is sort
- Find Pivot Index — The pivot index is the index where the sum of all numbers strictly to its left equals the sum strictly to its right. Return the left-most pivot index, or -1 if none exists.
- Reverse String — Reverse the array of characters s in place using O(1) extra memory.
- Valid Palindrome — A phrase is a palindrome if, after converting letters to lowercase and removing every non-alphanumeric character, it reads the same forwards and backwards. Return true if s is a pa
- Longest Common Prefix — Return the longest common prefix shared by all strings in strs . If there is none, return an empty string "" .
- Contains Duplicate — Return true if any value appears at least twice in nums , and false if every element is distinct.
- Two Sum — Given an array nums and an integer target , return the indices of the two numbers that add up to target . Exactly one solution exists, and you may not use the same element twice. R
- Valid Anagram — Return true if t is an anagram of s — that is, it uses exactly the same characters the same number of times.
- First Unique Character in a String — Return the index of the first character in s that appears exactly once, or -1 if there is none.
- Reverse Linked List — Given the head of a singly linked list, reverse the list and return the new head.
- Merge Two Sorted Lists — Merge two sorted linked lists into one sorted list by splicing their nodes together, and return its head.
- Middle of the Linked List — Return the middle node of the list (the output shows the list from that node onward). If there are two middle nodes, return the second .
- Linked List Cycle — Return true if the linked list contains a cycle — i.e. some node can be reached again by following next . Test input format: [values, pos] , where pos is the index the tail connect
- Valid Parentheses — Given a string containing only ()[]{} , determine if it is valid: every opening bracket is closed by the same type, in the correct order.
- Implement Queue using Stacks — Implement a FIFO queue using only two stacks (arrays with push and pop ). Support push(x) , pop() , peek() and empty() .
- Binary Search — Given a sorted array of distinct integers nums and a target , return the index of target or -1 if it is absent. Your algorithm must run in O(log n) .
- Search Insert Position — Return the index of target in the sorted array nums , or the index where it would be inserted to keep the array sorted. Use O(log n).
- Sqrt(x) — Return the square root of the non-negative integer x rounded down to the nearest integer — without using Math.sqrt or ** .
- Maximum Depth of Binary Tree — Return the maximum depth of a binary tree: the number of nodes on the longest path from the root down to a leaf.
- Binary Tree Inorder Traversal — Return the inorder traversal (left, node, right) of a binary tree’s values.
- Invert Binary Tree — Invert (mirror) a binary tree and return its root.
- Symmetric Tree — Check whether a binary tree is a mirror of itself (symmetric around its centre).
- Path Sum — Return true if the tree has a root-to-leaf path whose values add up to targetSum .
- Diameter of Binary Tree — The diameter of a binary tree is the number of edges on the longest path between any two nodes (the path may skip the root). Return it.
- Climbing Stairs — You are climbing a staircase with n steps. Each move climbs either 1 or 2 steps. In how many distinct ways can you reach the top?
- Best Time to Buy and Sell Stock — prices[i] is a stock’s price on day i . Choose one day to buy and a later day to sell to maximise profit. Return the maximum profit, or 0 if no profit is possible.
- Flood Fill — Starting from pixel (sr, sc) , recolour it and every 4-directionally connected pixel of the same original colour with color . Return the modified image.
- Majority Element — Return the element that appears more than ⌊n / 2⌋ times. It always exists.
- Plus One — A non-negative integer is stored as an array of digits, most significant first. Add one and return the resulting digits.
- Third Maximum Number — Return the third distinct maximum number in nums . If it does not exist, return the maximum.
- Find All Numbers Disappeared in an Array — nums has length n and values in [1, n] . Return, in ascending order, every number in [1, n] that does not appear.
- Height Checker — Students should stand in non-decreasing order of height. Return how many indices hold a different height from the sorted order.
- Replace Elements with Greatest Element on Right Side — Replace every element with the greatest element to its right, and replace the last element with -1 .
- Valid Mountain Array — Return true if arr strictly increases to a single peak and then strictly decreases (both parts non-empty).
- Check If N and Its Double Exist — Return true if there are two different indices i and j with arr[i] == 2 × arr[j] .
- Sort Array By Parity (Stable) — Return an array with all even numbers first, followed by all odd numbers, keeping the original relative order inside each group.
- Missing Number — nums contains n distinct numbers from [0, n] . Return the one number in the range that is missing.
- Find Numbers with Even Number of Digits — Return how many numbers in nums have an even number of digits.
- Duplicate Zeros — Duplicate every zero in the fixed-length array arr , shifting the remaining elements right. Elements pushed beyond the end are dropped. Modify in place .
- Length of Last Word — Return the length of the last word in s . Words are separated by spaces; there may be leading or trailing spaces.
- Find the Index of the First Occurrence in a String — Return the index of the first occurrence of needle in haystack , or -1 . Try it without indexOf .
- Roman to Integer — Convert a Roman numeral (I=1, V=5, X=10, L=50, C=100, D=500, M=1000; subtractive pairs like IV, IX, XL, XC, CD, CM) to an integer.
- Add Binary — Given two binary strings, return their sum as a binary string.
- Is Subsequence — Return true if s can be formed by deleting some (or no) characters of t without reordering the rest.
- Ransom Note — Return true if ransomNote can be built from the letters of magazine , each letter used at most once.
- Isomorphic Strings — Two strings are isomorphic if the characters of s can be replaced one-to-one to get t (no two characters map to the same character).
- Word Pattern — Return true if the words of s follow pattern with a one-to-one mapping between letters and words.
- Valid Palindrome II — Return true if s can be a palindrome after deleting at most one character.
- Contains Duplicate II — Return true if there are two distinct indices i and j with nums[i] == nums[j] and |i − j| ≤ k .
- Happy Number — Repeatedly replace n by the sum of the squares of its digits. n is happy if this process reaches 1; otherwise it loops forever. Return whether n is happy.
- Intersection of Two Arrays — Return the distinct values present in both arrays, in any order.
- Intersection of Two Arrays II — Return the intersection where each value appears as many times as it occurs in both arrays, in any order.
- Jewels and Stones — Each character in jewels is a type of jewel. Count how many characters of stones are jewels (case-sensitive).
- Single Number — Every element appears twice except one. Find it in O(n) time and O(1) extra space.
- Unique Number of Occurrences — Return true if the number of occurrences of each value in arr is unique.
- Longest Harmonious Subsequence — A harmonious array has max − min exactly 1. Return the length of the longest harmonious subsequence of nums .
- Remove Linked List Elements — Remove every node whose value equals val and return the new head.
- Remove Duplicates from Sorted List — Given a sorted linked list, delete duplicates so each value appears once. Return the head.
- Palindrome Linked List — Return true if the linked list reads the same forwards and backwards.
- Backspace String Compare — # means backspace. Return true if s and t produce the same text when typed into an empty editor.
- Remove All Adjacent Duplicates In String — Repeatedly remove two adjacent equal letters until no such pair remains. Return the final string.
- Next Greater Element I — nums1 is a subset of nums2 (distinct values). For each x in nums1 , return the first greater number to the right of x in nums2 , or -1 .
- Baseball Game — Process score operations: an integer records that score, "+" records the sum of the previous two, "D" doubles the previous, "C" removes the previous. Return the sum of all recorded
- Valid Perfect Square — Return true if the positive integer num is a perfect square, without using Math.sqrt .
- Arranging Coins — Build a staircase where row i has exactly i coins. Given n coins, return the number of complete rows.
- Count Negative Numbers in a Sorted Matrix — Every row and column of grid is sorted in non-increasing order. Return the number of negative values.
- Kth Missing Positive Number — arr is strictly increasing positive integers. Return the k -th positive integer missing from it.
- Binary Tree Preorder Traversal — Return the preorder traversal (node, left, right) of the tree’s values.
- Binary Tree Postorder Traversal — Return the postorder traversal (left, right, node) of the tree’s values.
- Same Tree — Return true if two binary trees have the same structure and values.
- Subtree of Another Tree — Return true if subRoot is identical to some node of root together with all of that node’s descendants.
- Minimum Depth of Binary Tree — Return the number of nodes on the shortest path from the root to the nearest leaf .
- Balanced Binary Tree — A tree is height-balanced if, at every node, the heights of the two subtrees differ by at most one. Return whether the tree is balanced.
- Binary Tree Paths — Return every root-to-leaf path as a string like "1->2->5" , in any order.
- Sum of Left Leaves — Return the sum of all leaves that are the left child of their parent.
- Search in a Binary Search Tree — Return the subtree rooted at the node with value val , or null if it does not exist.
- Convert Sorted Array to Binary Search Tree — Build a height-balanced BST from the sorted array. Use the element at index ⌊(lo + hi) / 2⌋ of each range as the root so the answer is unique.
- Two Sum IV — Input is a BST — Return true if two different nodes of the BST sum to k .
- Minimum Absolute Difference in BST — Return the minimum absolute difference between the values of any two different nodes in the BST.
- Range Sum of BST — Return the sum of all node values in the inclusive range [low, high] .
- Fibonacci Number — Return F(n) where F(0) = 0, F(1) = 1 and F(n) = F(n − 1) + F(n − 2).
- N-th Tribonacci Number — T(0) = 0, T(1) = 1, T(2) = 1 and T(n) = T(n − 1) + T(n − 2) + T(n − 3). Return T(n).
- Min Cost Climbing Stairs — cost[i] is paid when you step on stair i ; from there you may climb 1 or 2 stairs. You can start at index 0 or 1. Return the minimum cost to reach the top (past the last stair).
- Pascal's Triangle — Return the first numRows rows of Pascal’s triangle, where each value is the sum of the two values above it.
- Counting Bits — Return an array ans of length n + 1 where ans[i] is the number of 1 bits in i . Aim for O(n).
- Find Center of Star Graph — An undirected star graph has one centre node connected to every other node. Given its edges, return the centre.
- Find the Town Judge — People are labelled 1…n. [a, b] means a trusts b. The judge trusts nobody and is trusted by everyone else. Return the judge’s label or -1 .
- Find if Path Exists in Graph — Given an undirected graph with n nodes (0…n−1), return whether there is a path from source to destination .
- Relative Sort Array — Sort arr1 so its elements follow the order given by arr2 (distinct values, all present in arr1). Elements not in arr2 go at the end in ascending order.
- Transpose Matrix — Return the transpose of matrix (flip it over its main diagonal, swapping rows and columns).
- Matrix Diagonal Sum — Return the sum of the primary and secondary diagonals of a square matrix, counting the centre only once.
- Flipping an Image — Flip each row of the binary image horizontally, then invert it (0 ↔ 1). Return the result.
- Reshape the Matrix — Reshape mat into an r × c matrix filled in row-major order. If impossible, return the original matrix.
- Toeplitz Matrix — Return true if every top-left to bottom-right diagonal of the matrix has all-equal elements.
- Maximum Average Subarray I — Return the maximum average value of any contiguous subarray of length exactly k .
- Last Stone Weight — Repeatedly smash the two heaviest stones: equal stones both vanish, otherwise the lighter vanishes and the heavier loses that weight. Return the weight of the last stone, or 0.
- Kth Largest Element in a Stream — Design KthLargest(k, nums) whose add(val) adds a value to the stream and returns the current k -th largest element.
- Assign Cookies — Child i is content with a cookie of size ≥ g[i] ; each child gets at most one cookie. Return the maximum number of content children.
- Lemonade Change — Lemonade costs $5. Customers pay with $5, $10 or $20 bills in order, and you start with no change. Return true if you can give everyone correct change.
- Maximum Units on a Truck — boxTypes[i] = [count, unitsPerBox] . The truck holds at most truckSize boxes. Return the maximum total units.
- Number of 1 Bits — Return the number of set bits (1s) in the binary representation of the positive integer n .
- Reverse Bits — Reverse the bits of a 32-bit unsigned integer and return the result as an unsigned value.
- Power of Two — Return true if n is a power of two.
- Power of Four — Return true if n is a power of four.
- Hamming Distance — Return the number of bit positions at which x and y differ.
- Complement of Base 10 Integer — Flip every bit of n ’s binary representation (no leading zeros) and return the result. The complement of 0 is 1.
- Binary Gap — Return the longest distance between two adjacent 1 bits in n ’s binary form, or 0 if there are fewer than two 1s.
- Palindrome Number — Return true if the integer x reads the same backwards. Try it without converting to a string.
- Excel Sheet Column Number — Convert an Excel column title (A = 1, …, Z = 26, AA = 27, …) to its column number.
- Excel Sheet Column Title — Convert a positive column number to its Excel column title.
- Add Digits — Repeatedly add the digits of num until one digit remains. Can you do it in O(1)?
- Ugly Number — Return true if n is a positive integer whose only prime factors are 2, 3 and 5.
- Self Dividing Numbers — A number is self-dividing if it is divisible by each of its digits (and contains no 0). Return all self-dividing numbers in [left, right] .
- Greatest Common Divisor of Strings — String t divides s if s is t repeated some number of times. Return the largest string that divides both inputs.
- Design HashMap — Design a hash map without built-in hash tables: put(key, value) , get(key) (−1 if absent) and remove(key) . Keys are integers in [0, 10 6 ] .
Medium problems
- Product of Array Except Self — Return an array answer where answer[i] is the product of all elements of nums except nums[i] . Solve it in O(n) without division .
- Reverse Words in a String — Given a string s , reverse the order of its words . Words are separated by one or more spaces. The result must have single spaces between words and no leading or trailing spaces.
- Longest Substring Without Repeating Characters — Return the length of the longest substring of s that contains no repeated characters.
- Longest Palindromic Substring — Return the longest palindromic substring of s . If several have the maximum length, return the one that appears first .
- Group Anagrams — Group the strings in strs so that anagrams are together. Return the groups in any order; the strings inside each group may also be in any order.
- Top K Frequent Elements — Return the k most frequent elements of nums , in any order. The answer is guaranteed to be unique.
- Longest Consecutive Sequence — Given an unsorted array nums , return the length of the longest run of consecutive integers (e.g. 1, 2, 3, 4). Aim for O(n).
- Remove Nth Node From End of List — Remove the n -th node from the end of the list and return its head.
- Add Two Numbers — Two non-negative integers are stored as linked lists with digits in reverse order (ones digit first). Return their sum as a linked list in the same format.
- Min Stack — Design a stack supporting push , pop , top and retrieving the minimum element — all in O(1) . MinStack() creates the stack. push(val) , pop() , top() work as usual. getMin() return
- Daily Temperatures — For each day, return how many days you must wait for a warmer temperature. If no warmer day follows, use 0 .
- Evaluate Reverse Polish Notation — Evaluate an arithmetic expression in Reverse Polish (postfix) notation. Operators are + - * / ; division truncates toward zero.
- Find Minimum in Rotated Sorted Array — A sorted array of unique values was rotated at an unknown pivot (e.g. [0,1,2,4,5,6,7] → [4,5,6,7,0,1,2] ). Return its minimum element in O(log n).
- Search in Rotated Sorted Array — Search for target in a rotated sorted array of unique integers and return its index, or -1 . Run in O(log n).
- Find First and Last Position of Element — Given a sorted array nums , return [first, last] — the starting and ending positions of target — or [-1, -1] if it does not occur. O(log n) required.
- Binary Tree Level Order Traversal — Return the level-order traversal of a binary tree’s values: left to right, level by level.
- Validate Binary Search Tree — Determine whether a binary tree is a valid binary search tree : every node’s left subtree holds only smaller values, its right subtree only larger values, and both subtrees are BST
- Maximum Subarray — Find the contiguous, non-empty subarray with the largest sum and return that sum.
- House Robber — Houses on a street hold nums[i] money. You cannot take from two adjacent houses. Return the maximum amount you can collect.
- Coin Change — Return the fewest coins needed to make up amount using unlimited coins of the given denominations, or -1 if it cannot be made.
- Unique Paths — A robot starts at the top-left of an m × n grid and can only move right or down . How many distinct paths reach the bottom-right corner?
- Longest Increasing Subsequence — Return the length of the longest strictly increasing subsequence of nums (elements need not be adjacent).
- Number of Islands — Given a grid of "1" (land) and "0" (water), count the islands. An island is land connected horizontally or vertically, surrounded by water.
- Number of Provinces — isConnected[i][j] = 1 if cities i and j are directly connected. A province is a group of directly or indirectly connected cities. Return the number of provinces.
- Course Schedule — There are numCourses courses labelled 0…n−1 . [a, b] means you must take b before a . Return true if it is possible to finish every course (i.e. there is no dependency cycle).
- Rotting Oranges — Each cell is 0 (empty), 1 (fresh orange) or 2 (rotten). Every minute, fresh oranges next to a rotten one (4 directions) become rotten. Return the minutes until no fresh orange rema
- Network Delay Time — A network has n nodes (1…n). times[i] = [u, v, w] is a directed edge taking w time. A signal is sent from node k . Return the time for all nodes to receive it, or -1 if some node i
- Sort Colors — nums contains only 0 , 1 and 2 (red, white, blue). Sort it in place in one pass without using a library sort.
- Kth Largest Element in an Array — Return the k -th largest element of nums (in sorted order, not the k-th distinct). Can you do better than sorting?
- Merge Intervals — Merge all overlapping intervals and return the non-overlapping intervals that cover every input interval, sorted by start.
- Sort an Array — Sort nums in ascending order in O(n log n) time without using built-in sort functions.
- Rotate Array — Rotate nums to the right by k steps in place . k may be larger than the array length.
- Best Time to Buy and Sell Stock II — You may complete as many transactions as you like (buy then sell, holding at most one share at a time). Return the maximum total profit.
- Subarray Sum Equals K — Return the number of contiguous non-empty subarrays whose sum equals k . Values may be negative.
- Find the Duplicate Number — nums has n + 1 integers in [1, n] , so at least one value repeats. Return the repeated value without modifying the array and using O(1) extra space.
- Integer to Roman — Convert an integer in [1, 3999] to a Roman numeral.
- Zigzag Conversion — Write s in a zigzag pattern on numRows rows (down, then diagonally up, repeating) and return the rows read left to right, top to bottom.
- Count and Say — The sequence starts with "1" ; each next term describes the previous one by run-length (e.g. "21" → one 2, one 1 → "1211" ). Return the n -th term.
- String to Integer (atoi) — Convert s to a 32-bit signed integer: skip leading spaces, read an optional + / - , read digits until a non-digit, and clamp to [−2 31 , 2 31 − 1] . Return 0 if no digits are read.
- Longest Repeating Character Replacement — You may replace at most k characters of the uppercase string s . Return the length of the longest substring of one repeated letter you can obtain.
- 4Sum II — Given four arrays of equal length n , count tuples (i, j, k, l) with nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 .
- Valid Sudoku — Determine whether a partially filled 9 × 9 Sudoku board is valid: no digit repeats in any row, column or 3 × 3 box. Empty cells are "." . The board need not be solvable.
- Subarray Sums Divisible by K — Return the number of non-empty contiguous subarrays whose sum is divisible by k .
- Continuous Subarray Sum — Return true if nums has a contiguous subarray of length at least 2 whose sum is a multiple of k (0 counts as a multiple).
- Odd Even Linked List — Group all nodes at odd positions (1st, 3rd, …) followed by nodes at even positions, keeping relative order within each group. Use O(1) extra space.
- Swap Nodes in Pairs — Swap every two adjacent nodes (by relinking, not by changing values) and return the head.
- Rotate List — Rotate the list to the right by k places.
- Reorder List — Reorder L0 → L1 → … → Ln into L0 → Ln → L1 → Ln−1 → … in place. Return nothing.
- Partition List — Rearrange the list so all nodes with value less than x come before nodes with value ≥ x , preserving relative order in both parts.
- Reverse Linked List II — Reverse the nodes from position left to right (1-indexed, inclusive) and return the head.
- Simplify Path — Convert an absolute Unix path to its canonical form: single slashes, no trailing slash, . means current directory, .. moves up one level (not above root).
- Decode String — Decode strings encoded as k[text] , meaning text repeated k times. Encodings may be nested.
- Asteroid Collision — Asteroids move along a line: positive moves right, negative moves left, absolute value is size. When two meet, the smaller explodes (both if equal). Return the state after all coll
- Online Stock Span — Design StockSpanner whose next(price) returns the span : the number of consecutive days up to today (inclusive) with price ≤ today’s price.
- Basic Calculator II — Evaluate an expression containing non-negative integers, + - * / and spaces. Integer division truncates toward zero. Do not use eval .
- Peak Index in a Mountain Array — arr strictly increases then strictly decreases. Return the index of the peak in O(log n).
- Search a 2D Matrix — Each row is sorted and each row’s first value is greater than the previous row’s last value. Return whether target is present, in O(log(m·n)).
- Koko Eating Bananas — Koko eats up to k bananas per hour from a single pile (an unfinished pile’s remainder still takes a full hour). Return the minimum integer k to finish all piles within h hours.
- Capacity To Ship Packages Within D Days — Packages must ship in the given order. Each day the ship carries consecutive packages up to its capacity. Return the least capacity that ships everything within days days.
- Single Element in a Sorted Array — In a sorted array every element appears exactly twice except one. Find it in O(log n) time.
- Binary Tree Right Side View — Imagine standing on the right side of the tree. Return the values you can see, top to bottom.
- Binary Tree Zigzag Level Order Traversal — Return level-order values, alternating left-to-right and right-to-left on successive levels.
- Count Good Nodes in Binary Tree — A node is good if no node on the path from the root to it has a greater value. Return the number of good nodes.
- Lowest Common Ancestor of a Binary Tree — Return the lowest node that has both p and q as descendants (a node is a descendant of itself). All values are unique. In tests, p and q are given as values; your function receives
- Construct Binary Tree from Preorder and Inorder Traversal — Given the preorder and inorder traversals of a tree with unique values, rebuild and return the tree.
- Flatten Binary Tree to Linked List — Flatten the tree in place into a “linked list” that follows preorder, using right pointers and setting every left to null .
- Path Sum II — Return all root-to-leaf paths whose node values sum to targetSum (each path as a list of values; paths in any order).
- Insert into a Binary Search Tree — Insert val (not already present) as a new leaf using standard BST insertion and return the root.
- Kth Smallest Element in a BST — Return the k -th smallest value (1-indexed) in the BST.
- Lowest Common Ancestor of a Binary Search Tree — Return the lowest common ancestor of nodes p and q in a BST. Use the ordering property instead of searching both subtrees.
- Convert BST to Greater Tree — Replace every node’s value with the sum of all values greater than or equal to it, and return the root.
- Recover Binary Search Tree — Exactly two node values of a BST were swapped by mistake. Fix the tree in place without changing its structure.
- House Robber II — Same as House Robber, but the houses are arranged in a circle : the first and last houses are adjacent.
- Decode Ways — Letters are encoded as A → "1" … Z → "26" . Return the number of ways to decode the digit string s (leading zeros like "06" are invalid).
- Word Break — Return true if s can be split into a sequence of one or more dictionary words (words may be reused).
- Best Time to Buy and Sell Stock with Cooldown — You may make as many transactions as you like, but after selling you must wait one day before buying again. Return the maximum profit.
- Perfect Squares — Return the least number of perfect squares (1, 4, 9, 16, …) that sum to n .
- Coin Change II — Return the number of combinations of coins (unlimited supply) that make up amount . Order does not matter.
- Partition Equal Subset Sum — Return true if the array can be split into two subsets with equal sums.
- Target Sum — Put a + or - in front of every number. Return how many sign assignments make the expression equal target .
- Longest Common Subsequence — Return the length of the longest subsequence common to both strings (0 if none).
- Unique Paths II — Like Unique Paths, but cells with 1 are obstacles. Count paths from the top-left to the bottom-right moving only right or down.
- Minimum Path Sum — Find a path from the top-left to the bottom-right of a grid of non-negative numbers, moving only right or down, that minimises the sum of visited cells.
- Triangle — Return the minimum path sum from the top of the triangle to the bottom, moving to an adjacent number (index i or i + 1) on the row below at each step.
- Maximal Square — In a binary matrix of "0" and "1" , return the area of the largest square containing only 1s.
- Longest Palindromic Subsequence — Return the length of the longest palindromic subsequence of s .
- Max Area of Island — In a grid of 0s and 1s, an island is a 4-directionally connected group of 1s. Return the largest island area (0 if none).
- Pacific Atlantic Water Flow — The Pacific touches the top and left edges, the Atlantic the bottom and right. Water flows to neighbours of equal or lower height. Return all cells [r, c] from which water can reac
- Surrounded Regions — Capture every region of "O" that is completely surrounded by "X" by flipping it to "X" . Regions touching the border survive. Modify in place .
- Redundant Connection — A tree of n nodes (1…n) had one extra edge added. Return the edge that can be removed to restore a tree; if several qualify, return the one appearing last in the input.
- Keys and Rooms — Room 0 is unlocked; rooms[i] lists the keys found in room i . Return whether you can enter every room.
- Cheapest Flights Within K Stops — flights[i] = [from, to, price] . Return the cheapest price from src to dst using at most k stops (k + 1 flights), or -1 .
- Shortest Path in Binary Matrix — Return the number of cells on the shortest path from the top-left to the bottom-right through cells of value 0, moving in any of 8 directions, or -1 .
- Min Cost to Connect All Points — Connecting two points costs their Manhattan distance. Return the minimum total cost to connect all points (a minimum spanning tree).
- Largest Number — Arrange the non-negative integers to form the largest possible number and return it as a string.
- Insert Interval — intervals is sorted and non-overlapping. Insert newInterval , merging where necessary, and return the result.
- Non-overlapping Intervals — Return the minimum number of intervals to remove so the rest do not overlap (touching at an endpoint is allowed).
- Meeting Rooms II — Given meeting times [start, end) , return the minimum number of rooms needed so no two overlapping meetings share a room.
- H-Index — A researcher’s h-index is the largest h such that they have at least h papers with at least h citations each. Return it.
- Spiral Matrix — Return all elements of the matrix in clockwise spiral order, starting at the top-left.
- Spiral Matrix II — Return an n × n matrix filled with 1 … n² in clockwise spiral order.
- Rotate Image — Rotate the n × n matrix 90° clockwise in place .
- Set Matrix Zeroes — If an element is 0, set its entire row and column to 0, in place .
- Game of Life — Advance Conway’s Game of Life by one generation in place . A live cell with 2 or 3 live neighbours survives; a dead cell with exactly 3 becomes alive; all others die or stay dead.
- Two Sum II — Input Array Is Sorted — numbers is sorted ascending. Return the 1-indexed positions [i, j] (i < j) of the two numbers that add up to target . Exactly one answer exists; use O(1) extra space.
- 3Sum — Return all unique triplets [a, b, c] from nums with a + b + c = 0 (different indices). Triplets and their order do not matter.
- 3Sum Closest — Return the sum of three integers in nums that is closest to target . Exactly one closest sum exists.
- Container With Most Water — Vertical lines of height height[i] stand at x = i . Choose two lines that, with the x-axis, hold the most water. Return that area.
- 4Sum — Return all unique quadruplets that sum to target , in any order.
- Boats to Save People — Each boat carries at most two people with total weight ≤ limit . Return the minimum number of boats to carry everyone.
- Minimum Size Subarray Sum — Given positive integers nums , return the minimal length of a contiguous subarray whose sum is ≥ target , or 0 if there is none.
- Max Consecutive Ones III — Return the maximum number of consecutive 1s in the binary array if you may flip at most k zeros.
- Permutation in String — Return true if some permutation of s1 is a substring of s2 .
- Find All Anagrams in a String — Return all start indices (ascending) of substrings of s that are anagrams of p .
- Fruit Into Baskets — Walking left to right you may pick one fruit per tree, but you only have two baskets and each basket holds a single fruit type. Return the most fruit you can pick from one contiguo
- K Closest Points to Origin — Return the k points closest to the origin (Euclidean distance), in any order. The answer is unique.
- Top K Frequent Words — Return the k most frequent words, sorted by frequency (highest first); words with equal frequency are sorted alphabetically.
- Task Scheduler — Each task takes one time unit; identical tasks must be at least n units apart (idle slots allowed). Return the minimum total time to finish all tasks.
- Kth Smallest Element in a Sorted Matrix — Rows and columns of the n × n matrix are sorted ascending. Return the k -th smallest element (not k-th distinct).
- Ugly Number II — An ugly number has no prime factors other than 2, 3 and 5 (1 counts as ugly). Return the n -th ugly number.
- Furthest Building You Can Reach — Moving from building i to i + 1, climbing up by d needs d bricks or one ladder (going down is free). Return the furthest building index you can reach.
- Implement Trie (Prefix Tree) — Implement a trie with insert(word) , search(word) (exact match) and startsWith(prefix) .
- Design Add and Search Words Data Structure — Design WordDictionary with addWord(word) and search(word) , where "." in the search pattern matches any single letter.
- Longest Word in Dictionary — Return the longest word that can be built one character at a time, where every prefix is also in words . Break ties by the lexicographically smallest word; return "" if none.
- Replace Words — Replace every word in sentence by the shortest root from dictionary that is a prefix of it (leave the word if no root matches).
- Search Suggestions System — After each character typed of searchWord , suggest up to three products (lexicographically smallest) that start with the typed prefix.
- Subsets — Return all possible subsets (the power set) of the distinct integers in nums , in any order.
- Subsets II — nums may contain duplicates. Return all distinct subsets, in any order.
- Permutations — Return all permutations of the distinct integers in nums , in any order.
- Permutations II — nums may contain duplicates. Return all distinct permutations, in any order.
- Combinations — Return all combinations of k numbers chosen from 1 … n , in any order.
- Combination Sum — Return all unique combinations of candidates (distinct, each usable unlimited times) that sum to target .
- Combination Sum II — Each candidate may be used once and candidates may contain duplicates. Return all unique combinations summing to target .
- Combination Sum III — Find all combinations of k distinct numbers from 1–9 that sum to n .
- Letter Combinations of a Phone Number — Given digits 2–9, return all letter strings they could represent on a phone keypad (2 = abc, 3 = def, … 9 = wxyz). Return [] for an empty input.
- Generate Parentheses — Return all well-formed combinations of n pairs of parentheses.
- Word Search — Return true if word can be traced on the grid through horizontally or vertically adjacent cells, using each cell at most once.
- Palindrome Partitioning — Split s so that every piece is a palindrome. Return all such partitions (pieces in order), in any order.
- Restore IP Addresses — Insert three dots into the digit string s to form every valid IPv4 address: four parts, each 0–255, without leading zeros. Return them in any order.
- Jump Game — You start at index 0; nums[i] is your maximum jump length from i. Return whether you can reach the last index.
- Jump Game II — Return the minimum number of jumps to reach the last index (it is always reachable).
- Gas Station — Stations on a circular route give gas[i] ; driving to the next station costs cost[i] . Return the starting index that lets you complete the circuit once, or -1 . The answer is uniq
- Partition Labels — Split s into as many parts as possible so each letter appears in at most one part. Return the sizes of the parts in order.
- Valid Parenthesis String — The string contains ( , ) and * , where * may act as ( , ) or nothing. Return whether it can be valid.
- Minimum Number of Arrows to Burst Balloons — Balloons span horizontal intervals [xstart, xend] . A vertical arrow at x bursts every balloon whose interval contains x. Return the minimum number of arrows.
- Queue Reconstruction by Height — people[i] = [h, k] : person of height h has exactly k people of height ≥ h in front of them. Reconstruct and return the queue.
- Hand of Straights — Can the cards be rearranged into groups of groupSize consecutive values?
- Two City Scheduling — 2n people must be split evenly between cities A and B; costs[i] = [costA, costB] . Return the minimum total cost.
- Remove K Digits — Remove k digits from the number string num to make the smallest possible number. Return it without leading zeros ( "0" if empty).
- Single Number II — Every element appears three times except one, which appears once. Find it in O(n) time and O(1) space.
- Single Number III — Exactly two elements appear once and all others appear twice. Return the two single elements in any order, using O(1) extra space.
- Sum of Two Integers — Return a + b without using the + or - operators.
- Bitwise AND of Numbers Range — Return the bitwise AND of all integers in the inclusive range [left, right] .
- Maximum XOR of Two Numbers in an Array — Return the maximum value of nums[i] XOR nums[j] over all pairs.
- Reverse Integer — Reverse the digits of the 32-bit signed integer x . If the result overflows [−2 31 , 2 31 − 1] , return 0.
- Count Primes — Return the number of prime numbers strictly less than n .
- Factorial Trailing Zeroes — Return the number of trailing zeros in n! , in O(log n).
- Pow(x, n) — Implement x n without Math.pow or ** . n may be negative.
- Multiply Strings — Multiply two non-negative integers given as strings and return the product as a string, without converting the whole numbers to integers (they may be very long).
- Fraction to Recurring Decimal — Return numerator / denominator as a decimal string, enclosing a repeating fractional part in parentheses.
- LRU Cache — Design a least-recently-used cache of fixed capacity with O(1) get(key) (returns −1 if absent) and put(key, value) , which evicts the least recently used key when full.
- Design Circular Queue — Design a fixed-size circular queue with enQueue(v) , deQueue() (both return success as a boolean), Front() , Rear() (−1 if empty), isEmpty() and isFull() .
- Design Browser History — Start on homepage . visit(url) opens a page and clears forward history; back(steps) and forward(steps) move up to that many pages and return the current URL.
Hard problems
- Largest Rectangle in Histogram — Given bar heights of a histogram (each bar has width 1), return the area of the largest rectangle that fits inside it.
- Binary Tree Maximum Path Sum — A path is any sequence of connected nodes (each used at most once); it need not pass through the root. Return the maximum sum of node values over all non-empty paths.
- Edit Distance — Return the minimum number of single-character insertions, deletions or replacements needed to turn word1 into word2 (Levenshtein distance).
- Minimum Window Substring — Return the shortest substring of s that contains every character of t (including duplicates). If none exists, return "" . The answer is unique.
- Merge k Sorted Lists — Merge k sorted linked lists into one sorted list and return it.
- Sliding Window Maximum — A window of size k slides from left to right across nums . Return the maximum of each window.
- Median of Two Sorted Arrays — Return the median of the two sorted arrays combined. Aim for O(log(m + n)).
- Regular Expression Matching — Implement matching of the entire string s against pattern p , where . matches any single character and * matches zero or more of the preceding element.
- Word Ladder — Transform beginWord into endWord changing one letter at a time, where every intermediate word must be in wordList . Return the number of words in the shortest sequence (including b
- Trapping Rain Water — Given bar heights (width 1), compute how much rain water is trapped after raining.
- Subarrays with K Different Integers — Return the number of contiguous subarrays that contain exactly k distinct integers.
- Find Median from Data Stream — Design MedianFinder with addNum(num) and findMedian() , which returns the median of all numbers added so far (the mean of the two middle values when the count is even).
- IPO — You start with capital w and may finish at most k distinct projects. Project i needs capital[i] to start and adds profits[i] when done. Return the maximum final capital.
- Word Search II — Return every word from words that can be formed on the board by moving between horizontally or vertically adjacent cells, using each cell at most once per word.
- N-Queens — Place n queens on an n × n board so no two attack each other. Return every solution as a list of rows using "Q" and "." .
- Candy — Children stand in a line with ratings . Each child gets at least one candy, and a child with a higher rating than a neighbour must get more candy than that neighbour. Return the mi
- Max Points on a Line — Return the maximum number of the given (distinct) points that lie on the same straight line.
- Basic Calculator — Evaluate an expression containing integers, + , - , parentheses and spaces. Unary minus may appear (e.g. -(2+3) ). Do not use eval .
- LFU Cache — Design a least-frequently-used cache: when full, put evicts the key with the lowest use count, breaking ties by least recent use. get returns −1 if absent. Both operations should b