Skip to content

About

269 LeetCode (Java) and 16 Codeforces (C++) solutions grouped by technique, each with its key idea and time/space complexity. Every file compiles in CI. Includes a hints-first coach skill for Claude Code and Codex.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

LeetCode Patterns in Java

LeetCode solutions in Java, plus a few Codeforces problems in C++, grouped by the technique each one uses, with the key idea and its time and space complexity on one line.

269 LeetCode (148 Easy · 103 Medium · 18 Hard) and 16 Codeforces solutions, organized by 21 techniques.

LeetCode Note stats

"The human whose code is written in this note shall pass the technical interview."

How to use this repo

  • Study one pattern at a time. Pick a technique from the table of contents below and work down its table: read the problem, try it, then compare your approach with the key idea and the solution.
  • Find a problem by number. Search this page for the number with your browser's find (Ctrl+F or Cmd+F).
  • Practise with an AI coding agent. Install the coach skill below: it gives hints one step at a time instead of the answer, reviews your attempt, and suggests what to solve next from this index.

Every LeetCode solution is written the way LeetCode expects it (a class Solution, or the class a design problem names), so you can paste it into the LeetCode editor unchanged.

The index

Each row links the problem number to its page on LeetCode or Codeforces and the title to the solution file. Difficulty is the platform's own rating. Time and space describe the code in the file; space is the extra memory it uses, not counting the returned output.

Technique Problems
Arrays & Hashing 30
Two Pointers 34
Sliding Window 10
Prefix Sum 10
Binary Search 8
Stack 12
Linked List 11
Trees 24
Heap / Priority Queue 19
Graphs 5
Backtracking 6
Dynamic Programming 4
Greedy 12
Intervals 4
Sorting 15
Bit Manipulation 7
Math 28
Strings 14
Simulation 7
Design 6
Union-Find 3
Codeforces 16

Arrays & Hashing

# Problem Difficulty Key idea Time Space
1 Two Sum Easy One pass with a value→index map; look up target − x before inserting x. O(n) O(n)
49 Group Anagrams Medium Sort each word's letters to form a key and group the words by key in a hash map. O(n·k log k) O(n·k)
128 Longest Consecutive Sequence Medium Put every number in a set; from each number with no predecessor, count upward while the next number exists. O(n) O(n)
169 Majority Element Easy Boyer-Moore voting: keep a candidate and a counter, +1 on a match and −1 otherwise, replacing the candidate at zero. O(n) O(1)
219 Contains Duplicate II Easy Map each value to its last index; seeing it again within k of that index means true. O(n) O(n)
229 Majority Element II Medium Boyer-Moore voting with two candidates and counters, then a second pass checks each appears more than n/3 times. O(n) O(1)
274 H-Index Medium Bucket papers by citation count, capped at n, then scan down from n until the papers counted reach the index. O(n) O(n)
383 Ransom Note Easy Count magazine letters in a map, then spend one per ransom-note letter, failing when a count runs out. O(m + n) O(m + n)
387 First Unique Character in a String Easy Count each char in a map, then return the first index whose char has count 1. O(n) O(1)
409 Longest Palindrome Easy Toggle chars in a set; each completed pair adds 2, and any unpaired char left adds 1 for the center. O(n) O(n)
448 Find All Numbers Disappeared in an Array Easy Mark each seen value by negating nums[value − 1]; indices left positive are the missing numbers. O(n) O(1)
485 Max Consecutive Ones Easy Count the current run of 1s, reset it at each 0, and keep the longest run. O(n) O(1)
771 Jewels and Stones Easy Count every stone type in a map, then sum the counts of the jewel types. O(m + n) O(1)
804 Unique Morse Code Words Easy Translate each word letter by letter into Morse code and count the distinct encodings in a set. O(S) O(S)
819 Most Common Word Easy Lowercase and split on non-letters, count non-banned words in a map, and track the most frequent one. O(n + m) O(n + m)
867 Transpose Matrix Easy Copy matrix[i][j] into result[j][i] of a new cols × rows matrix. O(m·n) O(1)
1207 Unique Number of Occurrences Easy Count occurrences in a map; the counts must all be distinct, checked by putting them in a set. O(n) O(n)
1470 Shuffle the Array Easy Interleave the halves: ans[2i] = nums[i] and ans[2i + 1] = nums[i + n]. O(n) O(1)
1572 Matrix Diagonal Sum Easy Add mat[i][i] and mat[i][n − 1 − i] for every row, skipping the second when it is the same cell. O(n) O(1)
1582 Special Positions in a Binary Matrix Easy Count the 1s in every row and column, then count cells holding 1 whose row and column counts are both 1. O(m·n) O(m + n)
1748 Sum of Unique Elements Easy Count every number in a map, then sum the keys whose count is 1. O(n) O(n)
1929 Concatenation of Array Easy Fill an array of length 2n with nums[i mod n]. O(n) O(1)
1941 Check if All Characters Have Equal Number of Occurrences Easy Count every char in a map and check that every count equals the first char's count. O(n) O(n)
2022 Convert 1D Array Into 2D Array Easy If the sizes match, place original[i] at row i / n, column i mod n. O(m·n) O(1)
2404 Most Frequent Even Element Easy Count even values in a map, then pick the highest count, breaking ties toward the smaller value. O(n) O(n)
2657 Find the Prefix Common Array of Two Arrays Medium Walk both permutations, adding each value to a seen set; a value already seen means it has just become common. O(n) O(n)
3005 Count Elements With Maximum Frequency Easy Count frequencies, then add up the frequencies of every element tied for the maximum. O(n) O(n)
3065 Minimum Operations to Exceed Threshold Value I Easy Count the elements below k; each one takes one removal. O(n) O(1)
3917 Count Indices With Opposite Parity Easy Brute force: for each index, count the elements from it onward with the opposite parity. O(n^2) O(1)
3925 Concatenate Array With Reverse Easy Copy nums into the first half, then copy it again in reverse into the second half. O(n) O(1)

Two Pointers

# Problem Difficulty Key idea Time Space
11 Container With Most Water Medium Start at both ends, record the area, then move the shorter wall inward because it caps the height. O(n) O(1)
15 3Sum Medium Sort, fix each distinct anchor, then move two pointers inward toward a zero sum, skipping duplicate values. O(n^2) O(log n)
19 Remove Nth Node From End of List Medium From a dummy node, move a fast pointer n + 1 steps ahead, advance both until fast ends, then unlink slow.next. O(sz) O(1)
26 Remove Duplicates from Sorted Array Easy A write index keeps one copy of each value, copying nums[i] only when it differs from nums[i − 1]. O(n) O(1)
27 Remove Element Easy Copy every element that is not val forward to a write index; the index is the new length. O(n) O(1)
42 Trapping Rain Water Hard Move the lower side inward, tracking its running max; water above a bar is that max minus its height. O(n) O(1)
75 Sort Colors Medium Dutch national flag: a cursor swaps 0s down to the low pointer and 2s up to the high pointer, skipping 1s. O(n) O(1)
80 Remove Duplicates from Sorted Array II Medium Write nums[i] only when it differs from the value two slots behind the write index, keeping at most two copies. O(n) O(1)
88 Merge Sorted Array Easy Fill nums1 from the back, taking the larger of the two tails until nums2 is used up. O(m + n) O(1)
125 Valid Palindrome Easy Move pointers inward from both ends, skipping non-alphanumerics, and compare chars case-insensitively. O(n) O(1)
141 Linked List Cycle Easy Floyd's tortoise and hare: a pointer moving two steps meets the one-step pointer only if there is a cycle. O(n) O(1)
142 Linked List Cycle II Medium Once fast and slow meet, restart slow at the head; stepping both singly, they meet at the cycle start. O(n) O(1)
160 Intersection of Two Linked Lists Easy One pointer walks A then B, the other B then A; equal total distance makes them meet at the intersection or null. O(m + n) O(1)
167 Two Sum II - Input Array Is Sorted Medium Pointers at both ends: move left up when the sum is too small and right down when it is too large. O(n) O(1)
189 Rotate Array Medium Reverse the whole array, then reverse the first k elements and the remaining n − k elements. O(n) O(1)
202 Happy Number Easy Floyd cycle detection on the digit-square-sum sequence; stop when fast reaches 1 or meets slow. O(log n) O(1)
283 Move Zeroes Easy Copy each non-zero forward to a write index, then fill the rest with zeros. O(n) O(1)
287 Find the Duplicate Number Medium Treat each value as a pointer to an index; Floyd's cycle detection finds the cycle entrance, which is the duplicate. O(n) O(1)
344 Reverse String Easy Swap the two ends and move both pointers inward until they meet. O(n) O(1)
345 Reverse Vowels of a String Easy Two pointers skip non-vowels from each end, then swap the vowels they stop on. O(n) O(n)
350 Intersection of Two Arrays II Easy Sort both arrays and walk them with two pointers, collecting values that match. O(m log m + n log n) O(min(m, n))
392 Is Subsequence Easy Scan t once, advancing a pointer in s on every match; s is a subsequence if it gets fully matched. O(|t|) O(1)
443 String Compression Medium A read pointer measures each run; a write pointer stores the char and, for runs longer than 1, the count's digits. O(n) O(1)
541 Reverse String II Easy Step through the string in chunks of 2k and reverse the first k chars of each chunk in place. O(n) O(n)
557 Reverse Words in a String III Easy Scan for spaces and reverse each word's chars in place between its start and the next space. O(n) O(n)
611 Valid Triangle Number Medium Sort; for each largest side i, two pointers count pairs summing above nums[i], adding b − a pairs at once. O(n^2) O(log n)
680 Valid Palindrome II Easy Move two pointers inward; at the first mismatch, check whether skipping the left or the right char leaves a palindrome. O(n) O(1)
905 Sort Array By Parity Easy Swap each even number forward to a write pointer. O(n) O(1)
922 Sort Array By Parity II Easy One pointer walks even slots past evens, another walks odd slots past odds; swap the misplaced values they find. O(n) O(1)
977 Squares of a Sorted Array Easy Compare absolute values at both ends and write the larger square into the answer from the back. O(n) O(1)
1089 Duplicate Zeros Easy Count zeros, then copy from the back with a write index shifted by that count, writing zeros twice when in bounds. O(n) O(1)
2161 Partition Array According to Given Pivot Medium With a write pointer, place the smaller values in order, then every pivot copy, then a second pass of larger values. O(n) O(1)
2465 Number of Distinct Averages Easy Sort, pair the smallest with the largest while moving inward, and count the distinct pair sums in a set. O(n log n) O(n)
2540 Minimum Common Value Easy Walk both sorted arrays, advancing the side with the smaller value; the first equal pair is the answer. O(m + n) O(1)

Sliding Window

# Problem Difficulty Key idea Time Space
3 Longest Substring Without Repeating Characters Medium Grow the window rightward; while the new char is already in the set, drop chars from the left; track the widest window. O(n) O(1)
239 Sliding Window Maximum Hard Monotonic deque of indices: drop indices that left the window and smaller values at the back; the front is the max. O(n) O(k)
325 Maximum Sum of Subarrays of Size K — Fixed-size window: add the new element; once the window holds k elements, record its sum and drop the leftmost. O(n) O(1)
424 Longest Repeating Character Replacement Medium Window with letter counts; shrink while its size minus the top letter frequency exceeds k; track the widest window. O(n) O(1)
594 Longest Harmonious Subsequence Easy Sort, then keep a window whose max − min is at most 1, recording its size when the difference is exactly 1. O(n log n) O(log n)
904 Fruit Into Baskets Medium A window of fruit counts that never shrinks: whenever it holds more than two types, slide its left edge one step. O(n) O(1)
1423 Maximum Points You Can Obtain from Cards Medium Start with the first k cards, then trade the prefix's last card for the next card from the end, k times. O(k) O(1)
1438 Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit Medium Two monotonic deques track the window's max and min; advance left while max − min exceeds limit. O(n) O(n)
1984 Minimum Difference Between Highest and Lowest of K Scores Easy Sort, then slide a window of k values and minimize its last minus first value. O(n log n) O(log n)
2461 Maximum Sum of Distinct Subarrays With Length K Medium Keep a set of the window's values: shrink past any duplicate; at size k, record the sum and drop the leftmost. O(n) O(k)

Prefix Sum

# Problem Difficulty Key idea Time Space
238 Product of Array Except Self Medium Fill ans with prefix products from the left, then multiply in a running suffix product from the right. O(n) O(1)
303 Range Sum Query - Immutable Easy Precompute prefix sums; a range sum is prefix[right + 1] − prefix[left]. O(n) build, O(1) query O(n)
304 Range Sum Query 2D - Immutable Medium Build 2D prefix sums by inclusion-exclusion; a region sum combines four corner values. O(m·n) build, O(1) query O(m·n)
370 Range Addition Medium Difference array: add the value at start, subtract it just after end, then prefix-sum the array once. O(length + k) O(1)
560 Subarray Sum Equals K Medium Keep a running prefix sum and a count map of earlier prefix sums; add the count of prefix − k each step. O(n) O(n)
862 Shortest Subarray with Sum at Least K Hard Prefix sums with a deque of increasing prefixes: pop the front while the sum reaches k, pop larger prefixes off the back. O(n) O(n)
1109 Corporate Flight Bookings Medium Difference array: add seats at first, subtract them after last, then a running total gives each flight's seats. O(n + m) O(n)
1674 Minimum Moves to Make Array Complementary Medium Per pair, mark on a difference array over target sums where it costs 0, 1 or 2 moves; prefix-sum, take the minimum. O(n + limit) O(limit)
1854 Maximum Population Year Easy Difference array over 1950–2050: +1 at birth, −1 at death; a running total finds the earliest peak year. O(n) O(1)
2536 Increment Submatrices by One Medium 2D difference array: mark four corners per query, then a 2D prefix sum yields every cell's count. O(n^2 + q) O(n^2)

Binary Search

# Problem Difficulty Key idea Time Space
69 Sqrt(x) Easy Binary search 0..x for the largest mid whose square, computed as a long, is at most x. O(log x) O(1)
153 Find Minimum in Rotated Sorted Array Medium If nums[mid] > nums[r] the minimum lies right of mid, otherwise at mid or left of it; shrink until l meets r. O(log n) O(1)
154 Find Minimum in Rotated Sorted Array II Hard Rotated-array binary search against nums[r]; when nums[mid] equals nums[r], drop r by one because duplicates hide the side. O(log n), O(n) worst O(1)
278 First Bad Version Easy Binary search for the leftmost bad version, remembering each bad mid and searching left of it. O(log n) O(1)
367 Valid Perfect Square Easy Binary search 0..num with longs; true if some mid squared equals num exactly. O(log num) O(1)
374 Guess Number Higher or Lower Easy Binary search 1..n, moving by the sign that guess returns until it returns 0. O(log n) O(1)
441 Arranging Coins Easy Binary search, with longs, for the largest row count k where k(k + 1)/2 ≤ n. O(log n) O(1)
1011 Capacity To Ship Packages Within D Days Medium Binary search the capacity between the heaviest package and the total, greedily counting the days each capacity needs. O(n log S) O(1)

Stack

# Problem Difficulty Key idea Time Space
20 Valid Parentheses Easy Push opening brackets; each closing bracket must match the top; the string is valid if the stack ends empty. O(n) O(n)
32 Longest Valid Parentheses Hard Stack indices over a -1 base; on ')' pop, then measure from the new top, or make i the base if empty. O(n) O(n)
150 Evaluate Reverse Polish Notation Medium Push numbers; on an operator pop two operands, apply it with the earlier operand on the left, and push the result. O(n) O(n)
234 Palindrome Linked List Easy Push first-half values while a fast pointer runs ahead, skip the middle if odd, then pop to compare with the second half. O(n) O(n)
394 Decode String Medium Two stacks hold repeat counts and outer builders; on ']' append the inner string count times to the popped outer one. O(n + L) O(n + L)
402 Remove K Digits Medium Monotonic stack: pop larger earlier digits while k remains, cut any leftover k from the end, strip leading zeros. O(n) O(n)
496 Next Greater Element I Easy A monotonic stack over nums2 maps each value to the first larger value after it; then look up each nums1 value. O(m + n) O(n)
503 Next Greater Element II Medium Monotonic stack of indices over two passes of the circular array; a larger value resolves every smaller index it pops. O(n) O(n)
739 Daily Temperatures Medium Scan right to left with a monotonic stack of indices, popping days that are not warmer; the top is the answer. O(n) O(n)
844 Backspace String Compare Easy Rebuild each string with a StringBuilder used as a stack, deleting the last char on '#', then compare them. O(m + n) O(m + n)
901 Online Stock Span Medium Monotonic stack of (price, span); pop every price at most today's and add its span into today's span. O(1) amortized O(n)
3660 Jump Game IX Medium Monotonic stack of blocks: a smaller value merges with larger earlier blocks; every index gets its block's maximum. O(n) O(n)

Linked List

# Problem Difficulty Key idea Time Space
2 Add Two Numbers Medium Walk both lists digit by digit with a carry, appending each sum mod 10 to a dummy-headed result list. O(max(m, n)) O(1)
21 Merge Two Sorted Lists Easy Splice the smaller head onto a dummy tail until one list runs out, then attach the remainder. O(m + n) O(1)
24 Swap Nodes in Pairs Medium From a dummy node, rewire each pair A→B into B→A→rest, then step past the pair. O(n) O(1)
25 Reverse Nodes in k-Group Hard Find each group's k-th node; if it exists, reverse the group in place and splice it after the previous group. O(n) O(1)
61 Rotate List Medium Measure the length, close the list into a ring, then cut it after node number length − (k mod length). O(n) O(1)
86 Partition List Medium Route nodes into two dummy-headed lists, below x and at least x, then join them and cut the tail. O(n) O(1)
92 Reverse Linked List II Medium Walk to the node before left, then repeatedly move the node after the sublist's tail to the sublist's front. O(n) O(1)
143 Reorder List Medium Find the middle with slow and fast pointers, reverse the second half, then interleave the two halves. O(n) O(1)
203 Remove Linked List Elements Easy Recursively clean the rest of the list first, then skip the current node if it holds val. O(n) O(n)
206 Reverse Linked List Easy Recursively point each node back at its predecessor and return the old tail as the new head. O(n) O(n)
237 Delete Node in a Linked List Medium Copy the next node's value into this node, then unlink the next node. O(1) O(1)

Trees

# Problem Difficulty Key idea Time Space
98 Validate Binary Search Tree Medium Recurse with an open (min, max) range kept as longs; every node must lie strictly inside its range. O(n) O(h)
101 Symmetric Tree Easy Compare the two subtrees as mirrors: equal values, outer children mirror each other, inner children mirror each other. O(n) O(h)
102 Binary Tree Level Order Traversal Medium BFS with a queue, draining exactly the current queue size each round to collect one level. O(n) O(n)
103 Binary Tree Zigzag Level Order Traversal Medium Level-order BFS that inserts values at the front of the level list on every other level. O(n^2) O(n)
104 Maximum Depth of Binary Tree Easy Depth is 1 plus the larger depth of the two subtrees; an empty tree has depth 0. O(n) O(h)
105 Construct Binary Tree from Preorder and Inorder Traversal Medium Preorder's first value is the root; its inorder index, from a value→index map, splits both ranges into subtrees. O(n) O(n)
107 Binary Tree Level Order Traversal II Medium Level-order BFS that inserts each finished level at the front of the result list. O(n^2) O(n)
110 Balanced Binary Tree Easy Post-order DFS returns each subtree's height and flags imbalance when child heights differ by more than 1. O(n) O(h)
112 Path Sum Easy Subtract each node's value on the way down; a leaf succeeds when the remaining sum is zero. O(n) O(h)
113 Path Sum II Medium DFS keeping the root-to-node path; copy it at leaves matching the remaining sum, then remove the node on return. O(n·h) O(h)
199 Binary Tree Right Side View Medium Level-order BFS that keeps the last node of each level. O(n) O(n)
226 Invert Binary Tree Easy Recursively invert both subtrees, then swap them. O(n) O(h)
235 Lowest Common Ancestor of a Binary Search Tree Medium Walk down from the root: left if both values are smaller, right if both are larger, otherwise this node splits them. O(h) O(1)
236 Lowest Common Ancestor of a Binary Tree Medium Return the node if it is null, p or q; a node whose left and right searches both succeed is the LCA. O(n) O(h)
257 Binary Tree Paths Easy DFS that appends each value to a path string and records the finished path at every leaf. O(n·h) O(h^2)
404 Sum of Left Leaves Easy If a node's left child is a leaf add its value, otherwise recurse into it; always recurse into the right child. O(n) O(h)
437 Path Sum III Medium DFS holding the root-to-node path; at each node sum backward along the path and count suffixes equal to targetSum. O(n·h) O(h)
450 Delete Node in a BST Medium Find key by BST order; with two children, copy in the right subtree's minimum and delete that value from the right. O(h) O(h)
563 Binary Tree Tilt Easy Post-order DFS returns each subtree's sum and adds |left sum − right sum| to a running total. O(n) O(h)
700 Search in a Binary Search Tree Easy Follow BST order from the root, left when val is smaller and right when larger, until it matches or runs out. O(h) O(h)
783 Minimum Distance Between BST Nodes Easy In-order traversal visits values in sorted order; track the smallest gap between consecutive values. O(n) O(h)
987 Vertical Order Traversal of a Binary Tree Hard BFS records (row, value) per column in a TreeMap, then each column is sorted by row and value. O(n log n) O(n)
993 Cousins in Binary Tree Easy Level-order BFS: fail if x and y are children of one parent, succeed if both appear on the same level. O(n) O(n)
2415 Reverse Odd Levels of Binary Tree Medium Level-order BFS collects each level's nodes; on odd levels swap values from both ends inward. O(n) O(n)

Heap / Priority Queue

# Problem Difficulty Key idea Time Space
23 Merge k Sorted Lists Hard Seed a min-heap with every list head; pop the smallest node, append it, and push its successor. O(N log k) O(k)
295 Find Median from Data Stream Hard A max-heap holds the lower half and a min-heap the upper; rebalance so the lower has equal or one more. O(log n) add, O(1) median O(n)
347 Top K Frequent Elements Medium Count frequencies, keep a size-k min-heap by count, then pop it into the answer from the back. O(n log k) O(n)
451 Sort Characters By Frequency Medium Count chars, push them into a max-heap ordered by count, then append each char count times as it pops. O(n + k log k) O(n)
480 Sliding Window Median Hard Two heaps with lazy deletion: a balance counter tracks live sizes, and outgoing values are discarded once they reach a heap top. O(n log n) O(n)
506 Relative Ranks Easy Pop scores from a max-heap to assign medals and ranks in a score→rank map, then read ranks in input order. O(n log n) O(n)
621 Task Scheduler Medium Simulate each time unit: run the most frequent task from a max-heap, then park it in a cooldown queue for n units. O(m·n) O(1)
630 Course Schedule III Hard Sort by deadline and take each course; if time passes the deadline, drop the longest course taken, kept in a max-heap. O(n log n) O(n)
659 Split Array into Consecutive Subsequences Medium Min-heap of (chain end, length): extend the shortest chain ending at num − 1; fail on any closed chain shorter than 3. O(n log n) O(n)
692 Top K Frequent Words Medium Count words, keep a size-k min-heap (lower count first, then later word first), then pop and reverse. O(n log k) O(n)
703 Kth Largest Element in a Stream Easy Keep only the k largest values in a min-heap; its top is the k-th largest after each add. O(log k) per add O(k)
857 Minimum Cost to Hire K Workers Hard Sort workers by wage/quality; keep the k smallest qualities in a max-heap and price each group at the current ratio. O(n log n) O(n)
1046 Last Stone Weight Easy Max-heap of stones: smash the two heaviest and push back their difference until at most one remains. O(n log n) O(n)
1337 The K Weakest Rows in a Matrix Easy Count each row's leading soldiers, then poll a min-heap ordered by (count, index) k times. O(m·n + m log m) O(m)
1464 Maximum Product of Two Elements in an Array Easy Push every number into a max-heap, pop the two largest, and multiply each minus one. O(n log n) O(n)
1792 Maximum Average Pass Ratio Medium A max-heap ordered by the ratio gain of one more passing student; give each extra student to the top class. O((n + k) log n) O(n)
2099 Find Subsequence of Length K With the Largest Sum Easy Keep the k largest (value, index) pairs in a min-heap, then sort them by index to restore the original order. O(n log k) O(k)
2335 Minimum Amount of Time to Fill Cups Easy Each second, fill one cup from each of the two largest remaining amounts in a max-heap; a lone amount adds itself. O(S) O(1)
2974 Minimum Number Game Easy Each round, pop the two smallest from a min-heap and write them back in swapped order. O(n log n) O(n)

Graphs

# Problem Difficulty Key idea Time Space
721 Accounts Merge Medium Link each account's emails to its first email in an adjacency map, then DFS each unseen component and sort its emails. O(N log N) O(N)
994 Rotting Oranges Medium Multi-source BFS from every rotten orange, one minute per level, until no fresh oranges remain. O(m·n) O(m·n)
1306 Jump Game III Medium DFS from start, marking visited indices by negating them; succeed on reaching a zero. O(n) O(n)
1345 Jump Game IV Hard BFS over indices using i ± 1 and same-value portals, deleting each value's portal list after its first use. O(n) O(n)
3629 Minimum Jumps to Reach End via Prime Teleportation Medium BFS over indices: step ±1, and from a prime value jump once to every index whose value it divides. O(n·√M) O(n log M)

Backtracking

# Problem Difficulty Key idea Time Space
22 Generate Parentheses Medium Build strings char by char, adding '(' while fewer than n are open and ')' while it stays balanced. O(n·4^n / √n) O(n^2)
37 Sudoku Solver Hard Fill the first empty cell with each digit valid for its row, column and box; recurse and undo on failure. O(9^m) O(m)
46 Permutations Medium Extend the current list with each number not already in it, recurse, then remove it. O(n^2·n!) O(n)
51 N-Queens Hard Place one queen per row, skipping columns and both diagonals already marked in boolean arrays, then unmark. O(n·n!) O(n^2)
77 Combinations Medium Choose numbers in increasing order from start to n, recurse with k − 1 left, then undo the choice. O(k·C(n, k)) O(k)
698 Partition to K Equal Sum Subsets Medium Sort descending, place each number into a bucket with room, undo on failure, and stop trying after an empty bucket. O(k^n) O(n + k)

Dynamic Programming

# Problem Difficulty Key idea Time Space
84 Largest Rectangle in Histogram Hard For each bar, find the nearest shorter bar on each side by jumping through boundaries already computed; area = height × gap. O(n) O(n)
118 Pascal's Triangle Easy Each row starts and ends with 1; every inner entry is the sum of the two entries above it. O(numRows^2) O(1)
509 Fibonacci Number Easy Top-down memoized recursion: f[n] = fib(n − 1) + fib(n − 2), cached in an array. O(n) O(n)
2770 Maximum Number of Jumps to Reach the Last Index Medium dp[j] = most jumps to reach j: try every earlier reachable i within target of nums[j] and take dp[i] + 1. O(n^2) O(n)

Greedy

# Problem Difficulty Key idea Time Space
45 Jump Game II Medium Treat reach as BFS levels: track the farthest jump, and when i hits the current level's end, jump and extend it. O(n) O(1)
55 Jump Game Medium Track the farthest reachable index; fail if i ever passes it, succeed once it covers the last index. O(n) O(1)
121 Best Time to Buy and Sell Stock Easy Track the lowest price so far and the best profit from selling at today's price. O(n) O(1)
122 Best Time to Buy and Sell Stock II Medium Find each local valley and the peak after it, adding every valley-to-peak rise to the profit. O(n) O(1)
134 Gas Station Medium When the running tank goes negative, restart after that station; a non-negative total surplus means that start works. O(n) O(1)
455 Assign Cookies Easy Sort both arrays; hand out cookies in increasing size, each to the least greedy child it can satisfy. O(n log n + m log m) O(log n + log m)
860 Lemonade Change Easy Count fives and tens; for a 20, prefer giving a ten and a five over three fives. O(n) O(1)
1403 Minimum Subsequence in Non-Increasing Order Easy Sort, then take the largest values until their sum exceeds the sum of the rest. O(n log n) O(log n)
1488 Avoid Flood in The City Medium Remember each lake's last rain day; when it rains there again, dry it on the first later dry day from a TreeSet. O(n log n) O(n)
1665 Minimum Initial Energy to Finish Tasks Hard Sort by minimum − actual descending, then go backward from the last task keeping max(energy + actual, minimum). O(n log n) O(n)
1775 Equal Sum Arrays With Minimum Number of Operations Medium Collect each element's possible gain toward closing the sum gap in a max-heap and apply the largest gains first. O((m + n) log(m + n)) O(m + n)
2833 Furthest Point From Origin Easy Send every '_' in the dominant direction: the answer is |R count − L count| plus the '_' count. O(n) O(n)

Intervals

# Problem Difficulty Key idea Time Space
56 Merge Intervals Medium Sort by start; extend the last merged interval while the next overlaps it, otherwise start a new one. O(n log n) O(n)
57 Insert Interval Medium Copy intervals that end before the new one, absorb every overlapping interval into it, then copy the rest. O(n) O(1)
435 Non-overlapping Intervals Medium Sort by end; keep each interval starting at or after the last kept end and count the rest as removals. O(n log n) O(n)
495 Teemo Attacking Easy Each attack adds the smaller of the gap to the next attack and duration; the last attack adds a full duration. O(n) O(1)

Sorting

# Problem Difficulty Key idea Time Space
147 Insertion Sort List Medium Insert each node into a sorted list behind a dummy, scanning from the front for its position. O(n^2) O(1)
215 Kth Largest Element in an Array Medium Sort the whole array with randomized quicksort that skips runs equal to the pivot, then read index n − k. O(n log n) expected O(log n) expected
242 Valid Anagram Easy Sort the characters of both strings and compare the arrays. O(n log n) O(n)
315 Count of Smaller Numbers After Self Hard Merge sort (value, index) pairs; each right element placed before left ones adds to those left elements' counts. O(n log n) O(n)
324 Wiggle Sort II Medium Quickselect the median, then put smaller values on even slots from the back, larger on odd slots from the front, median elsewhere. O(n) expected O(n)
414 Third Maximum Number Easy Sort, then walk down from the largest counting distinct values; return the third, or the maximum if there are fewer. O(n log n) O(log n)
561 Array Partition Easy Sort, then pair neighbours; the answer is the sum of the elements at even indices. O(n log n) O(log n)
645 Set Mismatch Easy Sort, then scan with an expected counter: a repeat of the previous value is the duplicate, a jump reveals the missing one. O(n log n) O(log n)
912 Sort an Array Medium Randomized quicksort that skips runs equal to the pivot on both sides before recursing. O(n log n) expected O(log n) expected
973 K Closest Points to Origin Medium Quickselect (squared distance, index) pairs so the k smallest end up first, then copy those points. O(n) expected O(n)
1200 Minimum Absolute Difference Easy Sort, then scan adjacent pairs, resetting the answer when a smaller gap appears and appending on ties. O(n log n) O(log n)
1365 How Many Numbers Are Smaller Than the Current Number Easy Sort a copy; each value's first index in the sorted copy is how many numbers are smaller than it. O(n log n) O(n)
1913 Maximum Product Difference Between Two Pairs Easy Counting sort the values; the answer is the product of the two largest minus the product of the two smallest. O(n + V) O(V)
2164 Sort Even and Odd Indices Independently Easy Split the values at even and odd indices, sort evens ascending and odds descending, then write them back. O(n log n) O(n)
2500 Delete Greatest Value in Each Row Easy Sort each row, then for each column from the right add the maximum across all rows. O(m·n log n) O(log n)

Bit Manipulation

# Problem Difficulty Key idea Time Space
136 Single Number Easy XOR all numbers; equal pairs cancel to zero, leaving the single one. O(n) O(1)
190 Reverse Bits Easy For every set bit i of n, set bit 31 − i of the result. O(1) O(1)
191 Number of 1 Bits Easy Test bits 0 to 30 with a shifting mask and count the set ones. O(1) O(1)
461 Hamming Distance Easy XOR the two numbers so differing bits become 1, then count them with Integer.bitCount. O(1) O(1)
476 Number Complement Easy Build a mask of 1s as wide as num's binary form and XOR num with it. O(1) O(1)
693 Binary Number with Alternating Bits Easy n XOR (n >> 1) is all 1s exactly when bits alternate; x & (x + 1) being zero confirms all 1s. O(1) O(1)
1009 Complement of Base 10 Integer Easy Extract n's bits into a list, flip each one, and rebuild the number with powers of two. O(log n) O(log n)

Math

# Problem Difficulty Key idea Time Space
7 Reverse Integer Medium Pop the last digit and push it onto a long accumulator, returning 0 as soon as it leaves the int range. O(log x) O(1)
9 Palindrome Number Easy Write the digits in reverse order into a string and compare it with the number's own string. O(log x) O(log x)
48 Rotate Image Medium Transpose across the main diagonal, then reverse each row; together they rotate the matrix 90° clockwise. O(n^2) O(1)
50 Pow(x, n) Medium Fast exponentiation: square x and halve the exponent, multiplying in one extra x when it is odd; negative n uses 1/x. O(log n) O(log n)
67 Add Binary Easy Add digits from the right with a carry, appending sum mod 2, then reverse the built string. O(max(m, n)) O(1)
231 Power of Two Easy Halve n while it is even; it is a power of two only if it reaches exactly 1. O(log n) O(1)
258 Add Digits Easy Digital root: 0 stays 0, multiples of 9 give 9, everything else gives num mod 9. O(1) O(1)
263 Ugly Number Easy Divide out every factor of 2, 3 and 5; the number is ugly if 1 remains. O(log n) O(1)
268 Missing Number Easy Subtract the array's sum from n(n + 1)/2, the sum of 0 to n. O(n) O(1)
292 Nim Game Easy You lose exactly when n is a multiple of 4, because the opponent can always restore that. O(1) O(1)
326 Power of Three Easy Divide by 3 while divisible; it is a power of three only if it reaches exactly 1. O(log n) O(1)
342 Power of Four Easy Divide by 4 while divisible; it is a power of four only if it reaches exactly 1. O(log n) O(1)
389 Find the Difference Easy Sum t's char codes and subtract s's; what is left is the added character. O(n) O(n)
396 Rotate Function Medium Compute F(0) and the total sum, then derive each rotation as F(i) = F(i − 1) + sum − n·nums[n − i]. O(n) O(1)
788 Rotated Digits Medium Check each number up to n digit by digit: no 3, 4 or 7, plus some 2, 5, 6 or 9. O(n log n) O(1)
1185 Day of the Week Easy Count days elapsed since Friday 1971-01-01, including leap days, and pick the weekday by total mod 7. O(year − 1971) O(1)
1217 Minimum Cost to Move Chips to The Same Position Easy Moving by 2 is free, so chips gather by parity; the cost is the smaller of the even and odd counts. O(n) O(1)
1304 Find N Unique Integers Sum up to Zero Easy Write the pairs −i and i for i from 1 to n/2, plus a 0 when n is odd. O(n) O(1)
1523 Count Odd Numbers in an Interval Range Easy (high − low) / 2 odd numbers fit in the gap; add one more if either end is odd. O(1) O(1)
1716 Calculate Money in Leetcode Bank Easy Full weeks form an arithmetic series: recurse on the earlier weeks and add the partial week with a closed formula. O(n) O(n)
1952 Three Divisors Easy Count the divisors of n below n; n has exactly three divisors when that count is two. O(n) O(1)
1979 Find Greatest Common Divisor of Array Easy Find the minimum and maximum, then run Euclid's algorithm on the pair. O(n) O(1)
2180 Count Integers With Even Digit Sum Easy Brute force: sum the digits of every number up to num and count the even sums. O(num log num) O(1)
2553 Separate the Digits in an Array Easy Peel each number's digits with mod 10, inserting at the front to keep their order, and flatten them into one array. O(D) O(D)
3658 GCD of Odd and Even Sums Easy The odd sum is n² and the even sum is n(n + 1), so their GCD is always n. O(1) O(1)
3918 Sum of Primes Between Number and Its Reverse Medium Reverse n's digits, then sum every prime between the two numbers using 6k ± 1 trial division. O(R·√R) O(1)
3932 Count K-th Roots in a Range Medium Count powers i^k, for i from 0 upward, that land in [l, r], stopping once past r; k = 1 is special-cased. O(r^(1/k)) O(1)
3959 Check Good Integer Easy Sum the digits and the squared digits in two passes; n is good when the difference is at least 50. O(log n) O(1)

Strings

# Problem Difficulty Key idea Time Space
13 Roman to Integer Easy Add each symbol's value, but subtract it when the next symbol is larger. O(n) O(1)
14 Longest Common Prefix Easy Take the first word as the prefix and trim its last char until every other word starts with it. O((n + m)·m^2) O(m)
434 Number of Segments in a String Easy Count positions holding a non-space char whose previous char is a space or the string start. O(n) O(1)
696 Count Binary Substrings Easy Track the lengths of the previous and current runs of equal chars; each run boundary adds min(previous, current). O(n) O(1)
796 Rotate String Easy goal is a rotation of s exactly when the lengths match and goal appears inside s + s. O(n^2) O(n)
1507 Reformat Date Easy Split into day, month and year; map the month name to its number, strip the day's suffix, zero-pad both. O(1) O(1)
1592 Rearrange Spaces Between Words Easy Split into words and count spaces; put total / (words − 1) spaces between words and the remainder at the end. O(n) O(n)
1903 Largest Odd Number in String Easy Return the prefix that ends at the rightmost odd digit, or an empty string if there is none. O(n) O(1)
1967 Number of Strings That Appear as Substrings in Word Easy Count the patterns that word.contains finds. O(n·P) O(1)
2000 Reverse Prefix of Word Easy Find the first ch, reverse the prefix up to and including it, and append the rest. O(n) O(n)
3258 Count Substrings That Satisfy K-Constraint I Easy Brute force every substring, counting zeros and ones as it grows, and keep those with either count at most k. O(n^2) O(1)
3582 Generate Tag for Video Caption Easy Split into words, lowercase the first, capitalize the rest, prefix '#', and cut the result to 100 chars. O(n) O(n)
3926 Count Valid Word Occurrences Medium Join the chunks, split on whitespace, trim edge hyphens, split on double hyphens, and count words in a map. O(L + q) O(L)
3931 Check Adjacent Digit Differences Easy Check each adjacent digit pair and fail as soon as two neighbours differ by more than 2. O(n) O(1)

Simulation

# Problem Difficulty Key idea Time Space
54 Spiral Matrix Medium Walk the top, right, bottom and left edges, shrinking each bound after its edge and stopping when bounds cross. O(m·n) O(1)
806 Number of Lines To Write String Easy Add each letter's width to the current line, starting a new line whenever it would pass 100 pixels. O(n) O(1)
1389 Create Target Array in the Given Order Easy Insert each nums[i] at position index[i] of an ArrayList, then copy the list into an array. O(n^2) O(n)
1861 Rotating the Box Medium In each row let stones fall right toward the nearest obstacle, then write the rows into a rotated cols × rows grid. O(m·n) O(1)
1914 Cyclically Rotating a Grid Medium Peel each layer into a list, rotate the list by k mod its length, and write it back in the same order. O(m·n) O(m + n)
2810 Faulty Keyboard Easy Append chars to a StringBuilder and reverse the whole builder on every 'i'. O(n^2) O(n)
3248 Snake in Matrix Easy Track the cell number directly: UP and DOWN move it by n, LEFT and RIGHT by 1. O(m) O(1)

Design

# Problem Difficulty Key idea Time Space
155 Min Stack Medium A hand-rolled linked stack whose every node stores its value and the minimum of everything beneath it. O(1) per operation O(n)
225 Implement Stack using Queues Easy Wraps java.util.Stack directly, delegating push, pop, top and empty to it instead of using queues. O(1) per operation O(n)
232 Implement Queue using Stacks Easy Push onto an in-stack; when the out-stack is empty, pour the in-stack into it so the oldest item is on top. O(1) amortized O(n)
641 Design Circular Deque Medium Wraps an ArrayDeque and enforces capacity k by checking its size before each insert. O(1) per operation O(k)
933 Number of Recent Calls Easy Keep ping times in a queue and drop those older than t − 3000; the queue size is the answer. O(1) amortized O(n)
1472 Design Browser History Medium Doubly linked list of pages: visit cuts off the forward chain, and back or forward walk up to steps nodes. O(steps) per move O(n)

Union-Find

# Problem Difficulty Key idea Time Space
990 Satisfiability of Equality Equations Medium Union the variables of every == equation; then any != equation whose variables share a root fails. O(n) O(1)
1202 Smallest String With Swaps Medium Union swappable indices, give each component a min-heap of its chars, then rebuild by polling each index's component. O((n + m) log n) O(n)
2316 Count Unreachable Pairs of Nodes in an Undirected Graph Medium Union by size over the edges; each component of size s pairs with every node not counted yet, adding s × remaining. O(n + E) O(n)

Codeforces

# Problem Rating Technique Key idea Time Space
1A Theatre Square 1000 Math Cover each side with ceil(side / a) flagstones and multiply the two counts. O(1) O(1)
4A Watermelon 800 Math The melon splits into two positive even parts exactly when w is even and greater than 2. O(1) O(1)
4C Registration System 1300 Arrays & Hashing A hash map of name → times seen; print OK on first sight, otherwise the name plus its current count. O(n·L) O(n·L)
25A IQ test 1300 Arrays & Hashing Count odds and evens, remembering the last index of each; the parity seen only once marks the answer. O(n) O(n)
58A Chat room 1000 Two Pointers Scan the word, advancing through the letters of "hello" on each match; succeed once all five match. O(n) O(1)
69A Young Physicist 1000 Math Sum the force vectors coordinate by coordinate; the body is in equilibrium when all three sums are 0. O(n) O(1)
71A Way Too Long Words 800 Strings A word longer than 10 becomes its first letter, the number of letters between, and its last letter. O(L) O(L)
118A String Task 1000 Strings Lowercase each letter, drop vowels (y included), and put '.' before every consonant. O(n) O(n)
122A Lucky Division 1000 Math Hard-code the 14 lucky numbers up to 1000 and check whether any of them divides n. O(1) O(1)
189A Cut Ribbon 1300 Dynamic Programming dp[i] = most pieces summing to i; from each reachable length, push dp[i] + 1 to i + a, b and c. O(n) O(n)
230B T-primes 1300 Math A T-prime is the square of a prime: sieve primes up to 10^6 and test whether √x is a prime integer. O(M log log M + n) O(M)
231A Team 800 Simulation Count the problems where at least two of the three friends are sure of the solution. O(n) O(1)
279B Books 1400 Sliding Window Grow a window of consecutive books and shrink it from the left while its total time exceeds t; keep the longest. O(n) O(n)
282A Bit++ 800 Simulation The middle character of each statement tells ++ from --; apply it to x. O(n) O(1)
455A Boredom 1500 Dynamic Programming Bucket points by value; dp[i] = max(dp[i − 1], dp[i − 2] + i × count[i]), like house robber. O(n + M) O(M)
479A Expression 1000 Math Evaluate the candidate ways to place + and × with brackets between a, b and c, and print the largest. O(1) O(1)

Practise with an AI coach

skills/leetcode-coach is an agent skill for Claude Code, Codex and other agents that read SKILL.md files. Tell it which problem you are on and it coaches instead of solving:

  • A hint ladder: understand the limits and the brute force, name the pattern, the key insight, a pseudocode skeleton, and the full solution only when you ask for it. One rung per reply.
  • A review of your attempt: traces your code on the edge cases that matter for the problem, finds the first failing input, and states the time and space of your code.
  • What to solve next: an easier problem with the same pattern as a worked example, and two follow-ups, picked from data/problems.json.

Claude Code

/plugin marketplace add elchibek5/leetcode-patterns-java
/plugin install leetcode-coach@elchibek5-leetcode

Then ask, for example: /leetcode-coach:leetcode-coach I'm stuck on 424, I tried brute force.

Codex and other agents

git clone https://github.com/elchibek5/leetcode-patterns-java
mkdir -p ~/.agents/skills && cp -r leetcode-patterns-java/skills/leetcode-coach ~/.agents/skills/

The skill reads the index from this repo when it is installed as a plugin, and from GitHub otherwise.

How solutions are checked

On every push and pull request, CI compiles each Java solution against Java 21 with the imports LeetCode adds and stand-ins for LeetCode's helper classes (ListNode, TreeNode, and so on), and syntax-checks each C++ solution with g++. On pull requests and branches it also verifies that data/problems.json, this README and the stats card match the files in the repo. On main, a second workflow regenerates the index after every change to solutions, data or scripts and commits the update.

Add a solution

  1. Name the file NNNN. Title.java, for example 0070. Climbing Stairs.java, and put it in LeetCode_Problems/Java/easy, medium or hard. Codeforces solutions go in Codeforces_Problems/ProblemSet/ named by problem code, for example 4A.cpp.
  2. Push to main. The index updates itself: the new problem appears under Unsorted with its official title, difficulty and link. For a pull request, run python3 scripts/build_index.py --write yourself first, because the pull request check expects the index to be up to date.
  3. Fill in pattern, key_idea, time and space for the new entry in data/problems.json, run python3 scripts/build_index.py --write, and push again.

To run the same checks as CI before pushing:

python3 -m unittest discover -s scripts
python3 scripts/build_index.py --check
python3 scripts/compile_check.py

License

MIT

About

269 LeetCode (Java) and 16 Codeforces (C++) solutions grouped by technique, each with its key idea and time/space complexity. Every file compiles in CI. Includes a hints-first coach skill for Claude Code and Codex.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages