| 1 |
Two Sum |
Nested Loops Check every pair of numbers to see if they sum to target. |
2D Matrix of Combinations |
Draw an array. Draw an 'i' arrow pointing to index 0, and a 'j' arrow hopping from i+1 to the end. Tally the hops as N+(N-1)+(N-2)... to show $O(N²)$. |
Hash Map (One Pass) |
"Bucket Lookup" Diagram |
Visualize numbers dropping into a bucket one by one. As a number drops, ask the bucket: "Do you contain (Target - Current)?" |
Draw the array on the left and a 2-column table (Key=Num, Value=Index) on the right. Draw a line from the current array element to the table looking for its complement. |
Flat Line + Branching Node |
Draw a single straight arrow (O(N) traversal). Draw a tiny box off each step representing the $O(1)$ map lookup. Total = $O(N)$. |
Just the 1D input array block (O(1) extra space). |
Draw a growing rectangular grid representing the Hash Map taking up $O(N)$ space as the loop progresses. |
| 2 |
Add Two Numbers |
List to Int Traverse both lists, convert to integers, add them, convert back to list (Fails for huge numbers). |
Data Type Pipeline |
Draw two chains of nodes. Draw a funnel combining them into a massive integer variable, then an arrow pushing that integer out into a new chain. |
Digit-by-Digit Math w/ Carry |
Vertical Addition with Carry Over |
Stack the linked lists vertically like primary school addition. Add top node + bottom node + carry, output modulo 10 to a new node, pass carry to next column. |
Draw L1 on top, L2 below it. Draw vertical boxes circling the nodes at index 'i'. Write a "+ Carry" bubble at the top of the next column. |
Parallel Traversal Lines |
Draw two parallel lines of length max(M,N). The complexity is strictly bounded by the longer line. $O(\text{max}(M,N)$). |
Draw giant variables (Strings/BigInts) holding the intermediate numbers. |
Draw a new chain of nodes (O(max(M,N)) length) mapping 1:1 with the longest input list plus one potential carry node. |
| 3 |
Longest Substring Without Repeating Characters |
Generate All Substrings 3 Nested loops to generate and check validity of all substrings. |
Expanding Triangle |
Draw a line. Below it, draw shorter and shorter lines representing every possible substring. Count them to show $O(N³)$ operations. |
Sliding Window (Hash Set) |
Caterpillar/Accordion |
Visualize a flexible box covering the string. The right edge stretches right to engulf unique letters. If a duplicate is hit, the left edge pulls in until the duplicate is evicted. |
Draw the string. Draw a bracket `[` for the left pointer and `]` for the right. Erase and redraw `]` moving right. Erase and redraw `[` moving right when a collision occurs. |
Two Chasing Pointers |
Draw a timeline. Show pointer R traversing 0 to N. Show pointer L traversing 0 to N. Emphasize that L and R only move *forward*, proving 2N steps = $O(N)$. |
Draw numerous separate arrays/strings taking up massive heap space if generating actual strings. |
Draw a fixed-size HashSet (max 26 for letters, or 128 for ASCII). Shade in boxes as characters enter the window, unshade as they leave. |
| 4 |
Median of Two Sorted Arrays |
Merge & Find Middle Merge both arrays into a new sorted array and pick the middle index. |
Two Funnels into One |
Draw Array A and Array B. Draw arrows from both pointing into a new, larger Array C. Count the sizes to show $O(M+N)$. |
Binary Search on Partitions |
Balanced See-Saw |
Visualize a vertical line cutting through both arrays. The goal is to move the cut left/right until the max on the left side is <= the min on the right side. |
Draw Array A on top of Array B. Draw a red vertical partition line through both. Write the boundary conditions (L1 <= R2 and L2 <= R1) explicitly next to the line. |
Halving Block |
Draw the smaller array. Draw a box around it, then cross out half the box, then cross out half of the remaining half. Write $O(\log(\text{min}(M,N)$)). |
Draw a massive new array block equal to the size of A + B (O(M+N) space). |
Draw just the two original arrays. Place a few pointer arrows (L, R, mid). Emphasize no new array is drawn (O(1) space). |
| 5 |
Longest Palindromic Substring |
Check All Substrings Generate $O(N²)$ substrings and spend $O(N)$ checking if each is a palindrome. |
Brute Force Grid + Scanner |
Draw the string. Bracket every possible substring. Draw a bidirectional scanner line moving outside-in for each bracketed section to show $O(N³)$. |
Expand Around Center |
Water Ripples |
Pick a letter (or space between letters) and drop a "pebble". Watch the pointers ripple outward in both directions as long as the letters match. |
Draw the string. Place an "X" on one character. Draw outward-facing arrows `<--` and `-->` originating from the "X" moving step-by-step. |
N Centers * N Expansions |
Draw N dots (centers). Draw expanding circles around each dot. Maximum circle size is N. N centers * N max expansion = $O(N²)$. |
Draw hundreds of separate string blocks allocated in memory for each substring check. |
Draw the single original string, and track memory using just two integer variables (Start Index, Max Length) to show $O(1)$ space. |
| 6 |
Zigzag Conversion |
2D Matrix Simulation Create a massive 2D matrix, physically place characters moving down and diagonally up, then read row by row. |
Sparse Grid Traversal |
Draw a large grid. Write the word moving down, then diagonally up. Cross out the massive amount of empty space to visualize the wasted $O(\text{numRows} \cdot N)$ memory and time. |
Math / Index Hopping |
Jumping Frogs (Cycle Length) |
Formula: cycle = 2 * numRows - 2. Jump forward by 'cycle' to find the next character for the top/bottom rows. Middle rows have a second inner jump. |
Write the string out linearly. Draw long arcs jumping over characters for the top row. Draw secondary, shorter alternating arcs for the middle rows. |
Single Linear Pass |
Draw a single straight arrow across the original string. No matrix traversal needed, making it mathematically $O(N)$. |
Draw a massive 2D grid taking up lots of screen space (O(numRows * N) space). |
Draw a single array of strings (one string builder per row) combined at the end (O(N) space). |
| 7 |
Reverse Integer |
String Conversion Convert integer to string, reverse the string characters, handle the minus sign, parse back to integer. |
String Pipeline |
Draw a box with a number, an arrow to an array of characters, reverse the arrows pointing to a new array, and an arrow parsing it back. |
Digit Extraction (Pop & Push) |
Modulo Machine |
Pop the last digit using `% 10`. Push it onto the new number by multiplying the new number by 10 and adding the popped digit. Divide original by 10. |
Draw two boxes: `X` and `Rev`. Draw a loop where the rightmost digit of `X` falls off, slides over, and attaches to the right side of `Rev`. |
Shrinking Digit Bar |
Draw a bar representing the number's length. Erase one segment per step. Time complexity is $O(\log10(x)$) — proportional to the number of digits. |
Draw an array of characters allocated in memory (O(log10(x)) space). |
Draw exactly two integer variables (`X` and `Rev`) updating in place (O(1) space). |
| 8 |
String to Integer (atoi) |
Regex / Multi-pass Filter Run multiple passes: strip whitespace, extract sign, extract valid digits into a new string, then parse. |
Conveyor Belt Filters |
Draw a string on a conveyor belt passing through three separate machines (Space Remover -> Sign Checker -> Number Extractor). |
Deterministic One-Pass (DFA) |
State Machine |
Read left to right. Maintain a "state" (1. Skipping spaces, 2. Reading sign, 3. Reading digits). Once in state 3, any non-digit stops the machine. |
Draw a timeline. Place a pointer moving left to right. Draw bubbles above it representing the current state transitioning: [Start] -> [Sign] -> [Digit Accumulation] -> [Done]. |
Single Scan Line |
Draw a single straight arrow from index 0 to N. Emphasize that we never step backward. $O(N)$ time. |
Draw intermediate string arrays being created for every filtering step (O(N) space). |
Draw a single integer accumulator and a few boolean flags (O(1) space). |
| 9 |
Palindrome Number |
String Reversal Convert the number to a string and use two pointers (Left and Right) moving inward to check for a match. |
Inward Pointers |
Draw an array of characters. Draw L arrow at index 0, R arrow at the end. Move them inward. Requires extra $O(n)$ space for string conversion. |
Revert Half the Number |
Paper Fold |
Extract the back half of the number digit by digit (like Q7) and build a `reversedHalf`. Stop when `originalNumber <= reversedHalf`. |
Draw a large number. Draw a scissor line in the middle. Show the right half flipping over and comparing itself to the left half. |
Half-Length Timeline |
Draw an arrow representing the digits, but stop the arrow exactly in the middle. Time complexity is $O(\log10(n)$ / 2). |
Draw a string array taking up memory proportional to the number of digits. |
Draw two integer variables (Original, ReversedHalf) (O(1) space). |
| 10 |
Regular Expression Matching |
Pure Recursion For every '*' character, branch into two paths: one where '*' matches zero characters, one where it matches one or more. |
Exploding Decision Tree |
Draw a root node. Draw two branches coming down. Draw two more from each of those. Keep splitting until it forms a massive tree. $O(2^N)$ time. |
Dynamic Programming (2D Table) |
Grid Filling |
Create a 2D matrix where dp[i][j] answers "does s[0..i] match p[0..j]?". Fill top-to-bottom, left-to-right based on previous cell answers. |
Draw a grid. String `s` on the left (Y axis), pattern `p` on top (X axis). Draw arrows showing that the current cell's True/False value is pulled from the cell above, left, or top-left. |
Matrix Area |
Draw a rectangle representing M x N dimensions. Shade it in row by row to show strict $O(M \cdot N)$ time boundaries (no exponential explosion). |
Draw a massive stack of recursive function calls eating up memory. |
Draw a fixed M x N grid representing the DP table (O(M * N) space). |
| 11 |
Container With Most Water |
All Pairs (Nested Loops) Check every possible pair of left and right lines to calculate the area. |
2D Matrix of Combinations |
Draw the array of heights. Point 'i' at the first line, and let 'j' iterate through all lines to its right. Tally N+(N-1)+... to show $O(N²)$. |
Two Pointers (Greedy Squeeze) |
Collapsing Walls |
Place pointers at the extreme ends. The width is maximized, so to find a bigger area, we MUST find a taller line. Always move the shorter line inward. |
Draw the array. Place an 'L' arrow at index 0 and 'R' at N-1. Draw a water block between them. Cross out the shorter line and draw its arrow stepping inward. |
Squeezing Timeline |
Draw a horizontal line of length N. Draw arrows from both ends moving strictly inward until they collide. Exactly N steps = $O(N)$ time. |
Draw a maxArea variable. $O(1)$ space. |
Draw three variables: L, R, and maxArea. Emphasize that no new arrays are built (O(1) space). |
| 12 |
Integer to Roman |
Massive If/Else Chains Hardcode conditions for every specific range (if > 1000, else if > 900...). |
Tangled Flowchart |
Draw a giant, messy decision tree checking value ranges, visually representing ugly and hard-to-maintain code. |
Greedy Subtraction (Coin Change) |
The Greedy Cashier |
Treat Roman symbols as coin denominations (1000, 900, 500...). Always hand back the largest "coin" possible until the number hits 0. |
Draw two parallel lists: Values [1000, 900, 500...] and Symbols [M, CM, D...]. Point at the largest value <= num. Subtract value, append symbol. |
Fixed-Length Steps |
Draw a loop executing at most 13 times (the number of specific Roman numeral symbols/combos). Constant time loop = $O(1)$ time complexity. |
$O(1)$ space. |
Draw two fixed-size arrays (size 13) acting as lookup tables. Because their size never changes regardless of input, space is $O(1)$. |
| 13 |
Roman to Integer |
Scan with Lookahead Scan left to right, using complex conditionals to check if the next character forms a special pair (like IV or IX). |
Clunky Peeking Pointers |
Draw a pointer at 'i'. Draw a secondary, dashed pointer peeking at 'i+1' with a question mark, representing the clunky edge-case checks. |
Compare Current vs Next |
"Smaller Before Larger" Rule |
Read left to right. If the current numeral's value is LESS than the next numeral's value, subtract it. Otherwise, add it. |
Write "MCMXCIV". Write the integer values below each letter. Draw an arrow from C(100) to M(1000). Since 100 < 1000, write a minus sign. |
Single Scan Line |
Draw a single straight arrow from left to right across the string. We look at each character exactly once. $O(N)$ time. |
$O(1)$ space. |
Draw a fixed Hash Map containing exactly 7 key-value pairs mapping Roman letters to integers (O(1) space). |
| 14 |
Longest Common Prefix |
Vertical Character Matching Check index 0 of all strings, then index 1 of all strings, until a mismatch occurs. |
Vertical Scanner |
Stack the strings vertically. Draw a tall, narrow box highlighting column 0, then column 1. Stop and draw an X when letters don't match. |
Horizontal Shrinking |
The Chopping Block |
Assume the first string is the prefix. Compare it to the next string. If it doesn't match, chop the last letter off the prefix and try again. |
Draw a `prefix` box initially holding String[0]. Draw scissors chopping off the rightmost letter of the `prefix` box until `String[i].startsWith(prefix)` is true. |
Total Character Count Line |
Draw a line representing S (total number of characters in all strings combined). In the worst case, every character is checked once. $O(S)$ time. |
$O(1)$ space. |
Draw a single string variable shrinking in place. No massive arrays are allocated (O(1) auxiliary space). |
| 15 |
3Sum |
Generate All Triplets Use three nested loops to check every possible combination of three numbers. |
3D Cube of Combinations |
Draw three nested rotating gears (i, j, k). Write out the formula N * (N-1) * (N-2) to explicitly show the disastrous $O(N³)$ complexity. |
Sort + Anchor & Squeeze |
The Pinned Thumbtack |
Sort the array. Pin pointer 'i' (the anchor). Use standard 2Sum II (L and R pointers squeezing inward) on the remaining right side of the array. Skip duplicates! |
Draw a sorted array. Stick a thumbtack on 'i'. Bracket the rest of the array. Put 'L' at the start of the bracket, 'R' at the end. Move L/R based on the sum. |
N * (Squeezing Line) |
Draw an $O(N \log N)$ box for sorting. Below it, draw an outer loop (N times). Inside it, draw a straight line representing the $O(N)$ L/R squeeze. Total = $O(N²)$. |
Generates massive duplicate sets in memory requiring expensive deduplication. |
Draw just three pointer variables (i, L, R) scanning the array in place. Space complexity is $O(1)$ or $O(N)$ depending purely on the sorting algorithm used. |
| 16 |
3Sum Closest |
Generate All Triplets Use three nested loops to find all sums and track the one with the minimum absolute difference to the target. |
3D Cube + Min Tracker |
Draw three nested rotating gears. Draw a side box holding `closest_sum`. Update it every time a new gear combo produces a smaller `abs(target - sum)`. |
Sort + Anchor & Squeeze |
The Magnetic Pointers |
Sort the array. Pin pointer 'i'. Move L and R inward just like 3Sum, but instead of looking for exactly 0, you move L right if sum < target, and R left if sum > target. |
Draw a sorted array. Pin 'i'. Place L and R. Write the `target`. Draw arrows pulling L or R inward trying to get the sum magnetically closer to the target value. |
N * (Squeezing Line) |
Draw an outer loop representing 'i' (O(N)). Inside, draw a straight line for the L/R squeeze (O(N)). Total time is $O(N²)$. |
$O(1)$ space, but $O(N³)$ time makes it unusable. |
Draw a single `closest_sum` integer variable. Space is $O(1)$ or $O(N)$ depending purely on the sorting algorithm. |
| 17 |
Letter Combinations of a Phone Number |
Iterative Cross-Product Create an array of strings. For every new digit, multiply the existing array size by 3 or 4 and append the new letters. |
Exploding Array |
Draw a small array `["a", "b", "c"]`. Draw an arrow to a massive new array where every element is copied 3 times to append the next letters. $O(4^N)$ space chaos. |
Backtracking (DFS) |
Decision Tree (Depth-First) |
Build combinations character by character. Go as deep as possible (length of input digits), record the word, then backtrack one step and try the next letter. |
Draw a root node. Branch out to 'a', 'b', 'c'. From 'a', branch to 'd', 'e', 'f'. Trace a line down to "ad", then back up to 'a', then down to "ae". |
Tree Leaf Counter |
Draw a tree with a branching factor of 4 (worst case for digits 7 and 9). Draw the depth as N. Note that you visit 4^N leaves. Time is $O(4^N \cdot N)$. |
Draw giant intermediate arrays taking up huge chunks of memory during the iterative build. |
Draw a single string builder (or character array) growing and shrinking. Also draw the recursion stack (depth N). Total space is $O(N)$. |
| 18 |
4Sum |
Generate All Quadruplets Four nested loops scanning every combination of four numbers. |
4D Hypercube |
Write out four nested loops (i, j, k, l). Note the complexity as N * (N-1) * (N-2) * (N-3). A massive $O(N⁴)$ time block. |
Sort + Two Anchors + Squeeze |
Dual Pinned Thumbtacks |
Sort the array. Pin pointer 'i'. Pin pointer 'j' just ahead of 'i'. Then use the L and R pointers to squeeze the remaining array. Skip duplicates at all levels! |
Draw a sorted array. Stick a red thumbtack on 'i' and a blue one on 'j'. Bracket the rest. Put L at j+1, R at the end. Move L/R to hit the target. |
N² * (Squeezing Line) |
Draw two nested outer loops for the anchors (O(N²)). Inside, draw a straight line for the L/R squeeze (O(N)). Total time is reduced to $O(N³)$. |
Generates massive duplicate sets requiring expensive hash sets for deduplication. |
Draw four pointer variables (i, j, L, R) scanning in place. Space complexity is mostly $O(1)$ or $O(N)$ depending on the sorting step. |
| 19 |
Remove Nth Node From End of List |
Two Passes Traverse the entire linked list to find its length L. Do a second traversal to stop at node (L - N) and remove the next node. |
Double Finish Line |
Draw a linked list. Draw an arrow running all the way to the end (Pass 1). Draw a second arrow stopping just before the target (Pass 2). |
Fast & Slow Pointers (One Pass) |
The Fixed-Gap Runners |
Send a 'Fast' pointer exactly N steps ahead. Then, move both 'Fast' and 'Slow' at the same speed. When 'Fast' hits the end, 'Slow' is right before the target node. |
Draw a linked list. Place 'Fast' 2 nodes ahead of 'Slow'. Draw a rigid stick connecting them. Slide both right until 'Fast' falls off the end. 'Slow' bypasses the next node. |
Single Segmented Line |
Draw a line of length L. Show the Fast pointer covering it in one go. Time is strictly $O(L)$ with only one traversal. |
$O(1)$ space. |
Draw exactly two pointer variables (Fast, Slow). No new nodes or data structures are created (O(1) space). |
| 20 |
Valid Parentheses |
String Replacement Repeatedly search for "()", "{}", and "[]" and replace them with empty strings. If the string becomes empty, it's valid. |
The Eraser |
Draw the string `"{[()]}"`. Erase the middle `()`. Then erase the `[]`. Then erase the `{}`. Emphasize that string shifting makes this $O(N²)$. |
Stack (LIFO) |
The Spring-Loaded Tube |
Read left to right. If it's an open bracket, push it into the tube. If it's a closed bracket, check if it matches the top of the tube. If yes, pop it. If no, invalid. |
Draw a vertical bucket. Push `(`, `[`, `{` down into it. When `}` arrives, check the top of the bucket. Since it's `{`, cross them both out. |
Single Pass + $O(1)$ Ops |
Draw a single straight arrow reading the string (O(N)). Next to it, draw a tiny push/pop box to show stack operations take $O(1)$. Total time $O(N)$. |
Draw multiple intermediate string copies being created during the replacement process. |
Draw a vertical Stack data structure. In the worst case (all open brackets), it grows to size $O(N)$. |
| 21 |
Merge Two Sorted Lists |
Array Extraction & Sort Traverse both lists, put all values into an array, sort the array $O(N \log N)$, and build a brand new linked list. |
The Sorting Funnel |
Draw two linked lists dumping their nodes into an unsorted bucket. Draw a sorting machine that spits out a clean, new list. Emphasize the wasted $O(N \log N)$ time. |
Two Pointers + Dummy Node |
The Zipper |
Create a `dummy` node. Place pointer P1 on List 1 and P2 on List 2. Compare P1 and P2. Attach the smaller node to the `dummy` tail, then advance that pointer. |
Draw List 1 and List 2. Draw a star (Dummy) with an arrow `current`. Point `current` to the smaller of P1/P2. Cross out the old pointer and move it forward. |
Parallel Tracks |
Draw two parallel lines of length M and N. Draw a zipper merging them perfectly in one pass. Time is strictly $O(M + N)$. |
Draw a completely new array of size M+N (O(M+N) space). |
Draw only a few pointer variables (Dummy, Current, P1, P2) weaving existing nodes together (O(1) space). |
| 22 |
Generate Parentheses |
Generate All & Validate Create every possible string of '(' and ')' of length 2N (which is 2^(2N) strings), then check if each string is valid. |
Massive Explosion Tree |
Draw a giant binary tree of height 2N where every node splits into '(' and ')'. At the bottom, draw a slow scanner checking every single leaf node for validity. |
Backtracking (Constrained DFS) |
The Guarded Gates |
Build the string recursively. You can only add '(' if `open < N`. You can only add ')' if `close < open`. If length is 2N, record the string. |
Draw a root node. Branch left for '(' and right for ')'. Put a lock icon on the right branch if `open == close` (meaning you can't add a closing bracket yet). |
Pruned Tree Counter |
Draw a tree but physically cross out entire branches early on. The time complexity is bounded by the Nth Catalan number, roughly $O(4^N / \text{sqrt}(N)$). |
Draw 2^(2N) strings taking up enormous memory space. |
Draw the recursion stack (max depth 2N) and a single string builder modifying in place. Space is $O(N)$. |
| 23 |
Merge k Sorted Lists |
Extract All & Sort Dump every single node from all K lists into one massive array, sort it, and recreate the list. |
The Giant Blender |
Draw K separate lists pouring into one massive array. Write $O(N \log N)$ where N is the TOTAL number of nodes across all lists. |
Min-Heap (Priority Queue) |
The Vending Machine |
Put the head node of all K lists into a Min-Heap. Pop the smallest node, attach it to the result, and push that node's `next` into the heap. |
Draw a funnel (Heap) holding K items. Drop the smallest item out the bottom. Immediately replace it with the next item from the list it came from. |
Logarithmic Extraction |
Draw an N-length timeline. At each step, draw a small $O(\log K)$ box representing the heap push/pop operation. Total Time: $O(N \log K)$. |
Draw a massive array of size N (Total nodes). $O(N)$ space. |
Draw a fixed-size Triangle (Min-Heap) that never holds more than K elements. Space is $O(K)$ for the heap. |
| 24 |
Swap Nodes in Pairs |
Value Swapping Traverse the list and simply swap the integer values inside the nodes (e.g., node.val = next.val). |
The Shell Game |
Draw nodes. Physically erase the numbers inside the boxes and swap them. Note that this is generally considered a bad practice in interview settings. |
Pointer Manipulation + Dummy Node |
The Leapfrog |
Use a dummy node pointing to the head. Grab a pair of nodes (A and B). Make Dummy point to B, B point to A, and A point to whatever comes after B. |
Draw `prev -> A -> B -> next`. Draw curved arrows overriding the straight ones: `prev` arcs to `B`, `B` arcs backward to `A`, `A` arcs to `next`. |
Segmented Line |
Draw a line. Chop it into segments of 2. Draw a quick rotation arrow over each segment. We touch every node exactly once. $O(N)$ time. |
$O(1)$ space, but alters data instead of structure. |
Draw three pointers (`prev`, `curr`, `next_pair`). We only manipulate existing links in memory, so space is strictly $O(1)$. |
| 25 |
Reverse Nodes in k-Group |
Array Extraction Extract K values into an array, reverse the array, put the values back into the nodes, repeat. |
The Data Shuffler |
Draw an array of size K below the linked list. Draw arrows pulling values down, shuffling them, and pushing them back up into the nodes. |
In-Place Pointer Reversal |
The Segment Flipper |
Find the Kth node. If it exists, sever the connection, reverse the sub-list of size K using standard list reversal, then reconnect the edges. |
Draw a list. Put a bracket around K nodes. Reverse the arrows inside the bracket. Draw the `prevGroupTail` pointing to the new head of this bracket. |
Chunked Timeline |
Draw a timeline. Divide it into blocks of K. Process each block linearly. Total time is exactly $O(N)$. |
Draw an array of size K allocating and deallocating in memory continuously. Space is $O(K)$. |
Draw standard reversal pointers (`prev`, `curr`, `next`). Since we just flip existing arrows in memory, it is perfectly $O(1)$ space. |
| 26 |
Remove Duplicates from Sorted Array |
New Array / Hash Set Iterate through the array, add unique elements to a new array or Hash Set, then copy them back. |
The Extra Bucket |
Draw the original array. Draw a separate empty array below it. Draw arrows moving only unique numbers into the bottom array, highlighting the $O(N)$ extra space. |
Two Pointers (Reader/Writer) |
The Overwriter |
Keep a 'Slow' pointer for where the next unique element should go, and a 'Fast' pointer to scan for new unique elements. When Fast finds a new number, Slow writes it and moves up. |
Draw an array. Place `S` (Slow) and `F` (Fast) at index 1. Slide `F` right until `arr[F] != arr[F-1]`. Draw a curved arrow from `F` overwriting the value at `S`, then step `S` forward. |
Single Parallel Track |
Draw a line from 0 to N representing the Fast pointer. Draw a shorter, segmented line beneath it for the Slow pointer. Total time is strictly $O(N)$. |
Draw a separate array of size N taking up extra memory. |
Draw only two variables (`Slow` and `Fast`) operating within the confines of the original array block. Perfectly $O(1)$ space. |
| 27 |
Remove Element |
Filter to New Array Create a brand new array of the same size, loop through the original, and only copy elements that don't match the `val`. |
The Sieve |
Draw a sieve or filter. Drop the array elements through it. Watch the target `val` get stuck while the rest fall into a new array block. |
Two Pointers (In-Place Write) |
The Garbage Compactor |
Similar to Q26. A 'Fast' pointer reads every element. If it's NOT the target value, the 'Slow' pointer writes it down and increments. The target values simply get left behind/overwritten. |
Draw the array. Put `S` and `F` at index 0. If `arr[F] == val`, move `F` right. If `arr[F] != val`, draw an arrow copying `arr[F]` to `arr[S]`, then move both right. |
Single Linear Pass |
Draw a single straight arrow from left to right. We look at each element exactly once. $O(N)$ time complexity. |
Draw a new array allocated in memory (O(N) space). |
Draw the original array with a physical line drawn at index `S` at the end, showing where the "valid" array stops. $O(1)$ space. |
| 28 |
Find the Index of the First Occurrence in a String |
Nested Loops (Sliding Window) For every character in the `haystack`, try to match the entire `needle` character by character. |
The Brute Scanner |
Draw the haystack. Draw a box the size of the needle. Slide the box one letter at a time. For every step, draw M smaller arrows checking the letters inside the box. $O(N\cdot M)$ time. |
KMP Algorithm (LPS Array) |
The Smart Skipper |
Preprocess the `needle` to create an LPS (Longest Proper Prefix which is also Suffix) array. When a mismatch occurs, use the LPS array to skip redundant character checks instead of resetting to the beginning. |
Draw the haystack and needle. When a mismatch hits at index `j`, look up `LPS[j-1]`. Draw a long sweeping arrow shifting the needle forward, bypassing already matched prefixes. |
Two Independent Linear Passes |
Draw a short line for building the LPS array $O(M)$. Draw a separate line for scanning the haystack $O(N)$. Since we never step backward in the haystack, time is $O(N+M)$. |
Draw no extra memory, but emphasize the terrible $O(N\cdot M)$ time overlap. |
Draw a small auxiliary array (LPS) of size M (length of the needle). Space is strictly $O(M)$. |
| 29 |
Divide Two Integers |
Repeated Subtraction Subtract the divisor from the dividend in a `while` loop, keeping a tally. Will Time Limit Exceed (TLE) for huge numbers (e.g., 2^31 / 1). |
The Tally Counter |
Draw a massive pile of blocks (Dividend). Draw a tiny bucket (Divisor) scooping them away one by one. Write out $O(N)$ where N is the final quotient. |
Bit Manipulation (Exponential Subtraction) |
The Doubling Scooper |
Shift the divisor left (`<< 1`), effectively doubling it, until it's larger than the dividend. Subtract that massive chunk, add the corresponding power of 2 to the quotient, and repeat with the remainder. |
Draw the Dividend block. Draw a Divisor block that visually doubles in size (1x, 2x, 4x, 8x) until it almost overflows the Dividend. Subtract the largest chunk, write down the multiplier, and restart. |
Logarithmic Steps |
Draw a timeline. At each step, cross out half of the remaining dividend. Time complexity is $O(\log(\text{Dividend})$^2) due to the inner doubling loop. |
$O(1)$ space, but functionally broken for extreme 32-bit limits. |
Draw two variables accumulating the quotient and the current power of 2. $O(1)$ extra space. |
| 30 |
Substring with Concatenation of All Words |
Generate Permutations Generate all possible mathematical permutations of the given words (O(W!)), combine them into strings, and search for them in the main string. |
The Factorial Explosion Tree |
Draw a tree generating all word permutations. Note the staggering $O(W!)$ complexity, meaning even 10 words will immediately crash the program. |
Sliding Window + Hash Maps |
The Chunked Window Scanner |
Count word frequencies in a map. Slide a window across the string. Inside the window, jump by `word_length` chunks, checking if the chunked words match the target map's frequencies. |
Draw the main string. Bracket a window of size `W * len`. Inside the bracket, draw vertical lines slicing it into individual words. Compare those slices to a drawn Hash Map of target words. |
Chunked Linear Scan |
Draw an outer loop looping `word_length` times (offset). Inside, draw a window sliding across the string $O(N)$. Total time is roughly $O(N \\text{cdot word}_\text{length})$. |
Draw gigabytes of permutations destroying the heap memory. |
Draw two Hash Maps (one for the target words, one for the current window's words) storing at most W keys. Space is strictly $O(W)$. |
| 31 |
Next Permutation |
Generate All Permutations Create a list of every single possible combination, sort them lexographically, find the current one, and pick the next one. |
The Factorial Mountain |
Draw a massive list of N! (factorial) rows. Highlight how searching through millions of rows for an array of just 10 elements takes catastrophic $O(N!)$ time. |
Find Dip, Swap, Reverse |
The Peak and Valley Graph |
Scan right-to-left to find the first "dip" (decreasing number). Find the smallest number to its right that is larger than the dip. Swap them. Reverse everything after the swap index. |
Draw the array as a 2D line graph. Scanning left from the end, draw an arrow pointing to the first drop in elevation (the dip). Swap it with a slightly higher peak to its right, then draw a flat line showing the rest being sorted (reversed). |
Three Segmented Lines |
Draw three straight horizontal arrows, representing the three distinct linear passes (find dip, find swap, reverse). 3 * $O(N)$ = $O(N)$ time. |
Allocates massive 2D arrays to hold N! permutations. $O(N!)$ space. |
Draw the single original array being modified perfectly in-place. No extra memory used. $O(1)$ space. |
| 32 |
Longest Valid Parentheses |
Check All Substrings Generate every possible even-length substring and use a stack to check if it's a valid parenthesis sequence. |
The Exhaustive Scanner |
Draw a massive string. Bracket every possible chunk. Draw a miniature stack checking every single chunk individually. $O(N³)$ time. |
Two Counters (Left/Right Passes) |
The Twin Scales |
Keep two counters: `left` and `right`. Scan left-to-right. If `right == left`, record length. If `right > left`, reset counters to 0. Do a second pass right-to-left (resetting if `left > right`). |
Draw the string. Draw two tally boxes (L and R). Scan forward. When L and R match, draw a "Max Length" box updating. If R exceeds L, draw a red "X" and zero out the tallies. Repeat backwards. |
Two Parallel Timelines |
Draw an arrow going left-to-right across the string, and another going right-to-left. 2 * $O(N)$ passes = $O(N)$ time. |
Draw heavy auxiliary strings or stack traces for every substring. |
Draw exactly three integer variables (`left`, `right`, `maxLength`). No stacks or arrays needed. $O(1)$ space. |
| 33 |
Search in Rotated Sorted Array |
Linear Scan Ignore the fact that it's partially sorted and just check every single element from index 0 to N. |
The Slow Walker |
Draw a pointer starting at 0 and moving step-by-step to the end. Write $O(N)$ overhead, completely wasting the "sorted" clue. |
Modified Binary Search |
The Fault Line |
Find `mid`. Because it's rotated, at least ONE half (left or right of mid) MUST be perfectly sorted. Check if the target falls within the strict bounds of that sorted half. If yes, search there; if no, search the other half. |
Draw a line graph that goes up, breaks, drops down, and goes up again. Draw a vertical line down the middle. Circle the half that is an unbroken straight line and write "Is Target Here?" |
Halving Block |
Draw an array. Cross out half. Cross out half of the remainder. Standard $O(\log N)$ time visual. |
$O(1)$ space. |
Draw exactly three pointer variables (`left`, `right`, `mid`) converging. Space is purely $O(1)$. |
| 34 |
Find First and Last Position of Element in Sorted Array |
Scan and Extend Do a linear scan to find the first target. Then keep moving right one by one until the target stops repeating. |
The Bleeding Marker |
Draw a sorted array with a block of identical numbers. Draw an arrow hitting the first one, then bleeding over one step at a time until the numbers change. Worst case (all same numbers) is $O(N)$. |
Double Binary Search |
The Left/Right Brackets |
Run standard binary search to find the target. To find the *first* occurrence, purposely squeeze the `right` pointer inward even if you find the target. To find the *last*, squeeze the `left` pointer. |
Draw an array. Draw one binary search tree converging to place a `[` on the leftmost target. Draw a completely separate binary search tree converging to place a `]` on the rightmost target. |
Two Halving Blocks |
Draw two separate array blocks. Show both getting chopped in half logarithmically. $O(\log N)$ + $O(\log N)$ = $O(\log N)$ total time. |
$O(1)$ space. |
Draw standard binary search pointers. Reused for both searches. Perfectly $O(1)$ space. |
| 35 |
Search Insert Position |
Linear Search Iterate through the array until you find the target OR a number greater than the target. |
The Tripwire |
Draw a pointer walking left to right. Draw a literal tripwire at the first element `>= target`. $O(N)$ time. |
Standard Binary Search |
The Closing Gap |
Standard binary search. If target is not found, the `left` pointer will naturally cross the `right` pointer and land on the exact correct insertion index. |
Draw a sorted array. Draw `L` and `R` pointers closing in. Draw the moment they cross: `R` is now behind `L`. Draw an arrow pointing at `L` saying "Insert Here". |
Halving Block |
Draw a single block getting halved step by step until it reduces to 0. $O(\log N)$ time. |
$O(1)$ space. |
Draw only three pointers (`L`, `R`, `mid`). $O(1)$ space. |
| 36 |
Valid Sudoku |
Triple Pass Filtering Scan the entire 9x9 board three separate times: once for rows, once for columns, and once for the 3x3 sub-boxes. |
The Clunky Scanner |
Draw a 9x9 grid. Draw an arrow scanning left-to-right 9 times. Then an arrow scanning top-to-bottom 9 times. Then 9 individual boxes scanning inside themselves. |
Single Pass (Hash Sets) |
The Triple Tally |
Iterate exactly once. As you read a number at `(row, col)`, check if it exists in `RowSet[row]`, `ColSet[col]`, or `BoxSet[(row/3)*3 + col/3]`. If not, add it to all three. |
Draw one cell at `(r, c)`. Draw three distinct buckets (Row, Col, Box) next to it. Drop the number into all three. If a bucket already has that number, draw a red "X" (Invalid). |
Single 9x9 Block |
Draw a single 81-cell square. Shade it in progressively from top-left to bottom-right exactly once. $O(1)$ time (since the board is strictly 9x9, it's a constant 81 operations). |
$O(1)$ space, but the time waste is the real issue. |
Draw 3 arrays of 9 HashSets. Since the board size is fixed (9x9), the space is technically bounded by a constant. $O(1)$ space complexity. |
| 37 |
Sudoku Solver |
Generate All Grids Fill every empty cell with every possible combination of numbers 1-9, generating 9^(empty cells) boards, then check which one is valid. |
The Universe Exploder |
Draw a blank Sudoku board. Draw 9 arrows splitting off the first empty cell, then 9 off each of those. The visual should look like an impossibly massive, chaotic web. |
Backtracking (DFS) |
The Dead-End Reverser |
Find an empty cell. Try placing 1-9. If a number is valid (using Valid Sudoku logic), place it and recursively call the solver for the next cell. If you hit a wall, erase the number (backtrack) and try the next one. |
Draw a mini 3x3 grid. Write a '2'. Draw an arrow to the next cell, write '5'. Hit a wall. Erase '5', write '6'. Erase '6', write '7'. Draw the "erase and rewrite" motion heavily. |
Pruned Decision Tree |
Draw a tree branching out 9 ways. But heavily cross out branches almost immediately as they break Sudoku rules. Time is $O(9^M)$ where M is empty cells, but vastly smaller in practice. |
Millions of full 9x9 boards held in memory simultaneously. |
Draw the original 9x9 board modifying in-place, plus a recursion stack depth of up to 81. Space is $O(1)$ (or $O(81)$ stack frames). |
| 38 |
Count and Say |
Heavy String Concatenation Iterate string by string, adding characters together using `str = str + count + char`. This creates massive memory overhead due to string immutability. |
The Garbage Generator |
Draw the string "11". Add "2" to make a new string "112". Add "1" to make "1121". Draw the old strings piling up in a "Garbage Collector" bin. |
Two Pointers + String Builder |
The Chunk Counter |
To generate the next sequence, read the current sequence using a 'Start' and 'End' pointer. Move 'End' until the character changes. The count is `End - Start`. Append `count + char` to a fast StringBuilder. |
Draw "111221". Put 'S' and 'E' at index 0. Slide 'E' right until it hits '2'. Bracket the "111". Write "Three 1s" -> append "31". Move 'S' to 'E'. |
Expanding Triangle |
Draw row 1 as a dot. Row 2 slightly longer. Row N much longer. Time is roughly $O(2^N)$ or bounded by the length of the strings generated at each step. |
Draw dozens of intermediate string variables taking up $O(2^N)$ space and forcing constant memory reallocation. |
Draw a single mutable StringBuilder. Space is $O(L)$ where L is the length of the maximum generated string. |
| 39 |
Combination Sum |
Generate All Subsets (With Repetition) Create a deeply nested loop to just brute-force every combination of numbers up to the target length, then filter those that match the sum. |
The Infinite Blender |
Draw numbers flying into a blender, pouring out thousands of arrays. Draw a filter at the bottom that only lets arrays summing to the `target` pass through. |
Backtracking (Include/Exclude) |
The Fork in the Road |
At each number, make a choice: Path A) Include this number again and subtract it from the target. Path B) Move on to the next number. Base case: Target hits 0 (Save) or < 0 (Backtrack). |
Draw a target number (e.g., 7). Draw a fork. Left: pick '2' (Target becomes 5, stay on '2'). Right: skip '2' (Target remains 7, move to '3'). |
Deep Left-Leaning Tree |
Draw a binary decision tree. Make the left branches (Include) go very deep (Target / min_element times), and right branches (Exclude) go shallow (Length of array). Time is $O(2^\text{target})$. |
Creates huge, unnecessary arrays of invalid sums before filtering them. |
Draw a single `current_combination` array that grows (push) and shrinks (pop) as it traverses the tree. Space is $O(\text{Target} / \text{Min Element})$ for the recursion stack. |
| 40 |
Combination Sum II |
Combination Sum 1 + Hash Set Treat it like the previous problem, but since the input has duplicates, dump all successful arrays into a Hash Set to remove identical combinations at the very end. |
The Duplicate Sieve |
Draw a backtracking tree spitting out arrays: `[1, 2, 5]`, `[1, 7]`, and another `[1, 2, 5]`. Draw them hitting a Hash Set wall where the duplicate bounces off. |
Sort + Backtracking (Skip Dupes) |
The Smart Skipper |
Sort the array first. In the backtracking loop, if `i > start` and `arr[i] == arr[i-1]`, skip it! This prevents generating duplicate branches at the exact same depth level entirely. |
Draw a sorted array: `[1, 1, 2, 5, 6]`. Start a branch with the first '1'. When the loop moves to the second '1', draw a giant red curved arrow jumping over it to '2'. |
Severed Tree Branches |
Draw the same backtracking tree, but draw thick red lines cutting off massive subtrees before they even start because of the `if` skip condition. Time is $O(2^N)$. |
Draw a massive Hash Set holding heavy array objects to deduplicate. |
Draw a single `current_combination` array and the recursion stack. Because we sorted and skipped, no Hash Set is needed. Space is $O(N)$. |
| 41 |
First Missing Positive |
Sort & Scan Sort the array first, then scan from left to right looking for the number 1, then 2, then 3, until a gap is found. |
The Snail Sort |
Draw an array. Draw a massive $O(N \log N)$ sorting machine above it, taking up unnecessary time. Below it, draw a scanner looking for a gap. |
Cyclic Sort (Index as Map) |
The Rightful Chair |
Every number `x` belongs in index `x-1` (e.g., the number 5 belongs at index 4). Swap numbers into their "rightful chairs" until they are out of bounds or already correct. Then find the first empty chair. |
Draw an array. Point at number '3' in index 0. Draw a curved arrow picking up '3' and swapping it with whatever is at index 2. Repeat until index 0 holds '1' or a useless number (like -5). |
The Swapping Chain |
Draw a timeline where each step is a swap. Emphasize that every number is swapped at most ONCE into its correct place. Total time strictly bounded to $O(N)$. |
Requires $O(N \log N)$ time overhead or an $O(N)$ Hash Set. |
Draw the original array shuffling elements in-place. Because we hijack the array's own indices to act as our Hash Map, space is $O(1)$. |
| 42 |
Trapping Rain Water |
Look Left, Look Right For every single bar, scan all the way to the left to find the max height, and all the way to the right to find the max height. |
The Exhaustive Radar |
Draw a bar chart. From the middle bar, draw a radar wave scanning all the way left, then all the way right. Repeat this for every single bar to show $O(N²)$ wasted time. |
Two Pointers (Inward Squeeze) |
The Leaking Buckets |
Maintain `left_max` and `right_max` variables. Place L and R pointers at the ends. Whichever max is smaller dictates the water level for its side. Calculate water for the smaller side, then move that pointer inward. |
Draw a bar chart. Put L on the left, R on the right. If L's max is shorter than R's max, draw a blue water block above L, and move L inward. Erase and redraw the max line as they climb. |
Squeezing Timeline |
Draw a horizontal line of length N. Draw arrows from both ends moving strictly inward until they collide. Exactly N steps = $O(N)$ time. |
Draw separate left_max and right_max arrays of size N taking up memory. |
Draw exactly four pointer variables (L, R, left_max, right_max). No arrays needed. Perfectly $O(1)$ space. |
| 43 |
Multiply Strings |
Language Defaults (BigInt) Just parse the strings into native big integers, multiply them, and turn them back into strings (which defeats the whole purpose of the problem). |
The Cheater's Box |
Draw a black box labeled "BigInt()". Put two strings in, get a string out. Draw a red "X" through it because interviewers hate this. |
Array Math (Grade School Multiplication) |
The Shifting Grid |
Multiply digit by digit from right to left. The product of `num1[i]` and `num2[j]` is placed at indices `[i + j, i + j + 1]` in a result array. |
Draw standard elementary school vertical multiplication. Draw arrows linking the top digit `i` and bottom digit `j` directly into a pre-sized array box at position `i+j+1` (holding the digit) and `i+j` (holding the carry). |
Matrix Area |
Draw a grid of M rows and N columns. Shade in every cell to show that every digit of `num1` must multiply with every digit of `num2`. $O(M \cdot N)$ time. |
Draw giant, memory-heavy BigInt objects being instantiated. |
Draw a single integer array of size `M + N` (the maximum possible length of the product). Space is $O(M + N)$. |
| 44 |
Wildcard Matching |
Pure Recursion Every time you see a `*`, branch the path: one path where `*` matches 0 characters, one where it matches 1, one where it matches 2, etc. |
The Infinite Splinter |
Draw a string and a pattern with a `*`. Draw a tree where the `*` node explodes into N branches (matching 0, 1, 2... letters). $O(2^N)$ time. |
Two Pointers + Greedy Backtrack |
The Anchor and Rubber Band |
Scan left-to-right. If you hit a `*`, "anchor" a pointer there. Assume it matches 0 characters and move on. If you hit a mismatch later, rubber-band back to the anchor, assume it matches 1 character, and try again. |
Draw string S and pattern P. Draw a star icon over the `*` in P. Draw a pointer moving right in S. When a mismatch hits, draw a curved arrow snapping the pointer back to the star icon, shifting it right by one. |
Single Scan Line (Mostly) |
Draw a line representing S. Draw small, occasional loops snapping back. Emphasize that in the average case, it's $O(N + M)$ time, far faster than DP. |
Draw a massive call stack or a full M x N DP table. |
Draw exactly four pointers (`s_idx`, `p_idx`, `star_idx`, `match_idx`). Extremely memory efficient at $O(1)$ space. |
| 45 |
Jump Game II |
DFS / Recursion From index 0, recursively try every single possible jump length. Keep a global minimum of jumps to reach the end. |
The Exhausting Tree |
Draw a tree where each node branches out equal to its jump value. Highlight how many overlapping paths calculate the exact same jumps. $O(N!)$ time. |
Greedy (BFS-Style Window) |
The Expanding Flashlight |
Keep track of the `current_jump_end` and the `farthest` you can reach. Iterate through the array. Update `farthest`. When you hit `current_jump_end`, you *must* jump, so increment jump count and update the end to `farthest`. |
Draw the array. Bracket index 0. That's Jump 0. Look at the values inside the bracket to find the furthest reach. Bracket that new range. That's Jump 1. Repeat until the bracket covers the end. |
Single Chunked Line |
Draw a single straight arrow from left to right. Draw vertical dividers representing the forced jumps. We only look at each element once. $O(N)$ time. |
Draw a deep recursion stack going all the way to the end of the array. |
Draw exactly three variables (`jumps`, `current_end`, `farthest`). We never look back and never store paths. $O(1)$ space. |
| 46 |
Permutations |
Array Copying DFS Build permutations by creating new arrays at every step, passing the remaining numbers down to the next recursive call. |
The Exploding Conveyor Belt |
Draw an initial array. Draw lines branching down where every branch creates a brand new physical copy of the array minus one element. $O(N \cdot N!)$ time due to heavy copying. |
Backtracking (In-Place Swap) |
The Swapping Tree |
Iterate through the array. Swap the current element with the `start` index, recursively call the function for the next index, and then backtrack by swapping them back. |
Draw an array `[1, 2, 3]`. Point at index 0. Swap `1` with itself, branch down. Swap `1` with `2`, branch down. Swap `1` with `3`, branch down. Always draw a curved arrow swapping them back when moving up. |
Factorial Splitting Node |
Draw a root node splitting into N branches. Each of those splits into N-1 branches. The total leaves exactly equal N!. Time is exactly $O(N \cdot N!)$. |
Draw N! separate arrays scattered across memory. Space is easily $O(N \cdot N!)$. |
Draw exactly ONE array. Emphasize that all branches of the tree just modify this single array in place. Space is $O(N)$ for the recursion stack! |
| 47 |
Permutations II |
Permutations 1 + Hash Set Run the exact same brute force algorithm as Q46, but push the final arrays into a global Hash Set to filter out the duplicates caused by repeating numbers. |
The Duplicate Funnel |
Draw the massive N! tree generating arrays. Show multiple identical arrays (like `[1, 1, 2]`) hitting a Hash Set wall, where the duplicates bounce off and die. |
Sort + Backtracking (Used Array / Skip) |
The Smart Branch Pruner |
Sort the array first. Keep a boolean `used` array. If you are about to use `arr[i]`, but `arr[i] == arr[i-1]` AND `!used[i-1]`, skip it! You already explored this exact path. |
Draw a sorted array `[1, 1, 2]`. Branch off the first `1`. When the loop reaches the second `1`, draw a thick red "X" through its branch, writing "Duplicate Sibling Skipped". |
Severed Factorial Tree |
Draw the N! tree, but physically cross out massive subtrees right at the root level. Time is $O(N \cdot N!)$ in the worst case (all unique), but drastically faster in reality. |
Draw a massive Hash Set holding thousands of redundant array copies. |
Draw the original array, a `used` boolean array of size N, and a recursion stack of size N. Space is strictly $O(N)$. |
| 48 |
Rotate Image |
New Matrix Map Create a brand new N x N matrix. Loop through the original matrix and place `matrix[i][j]` directly into `new_matrix[j][n - 1 - i]`. |
The Carbon Copy |
Draw the original grid. Draw an empty grid next to it. Draw arrows pulling cells from the first grid and dropping them into their new rotated homes in the second grid. |
Transpose + Reverse Rows |
The Flip and Fold |
Rotate 90 degrees in-place by doing two simple operations: 1) Transpose the matrix (swap `matrix[i][j]` with `matrix[j][i]`). 2) Reverse every row horizontally. |
Draw a square grid. Draw a diagonal line from top-left to bottom-right. Fold the numbers across the diagonal (Transpose). Then, draw a vertical line down the middle and flip the left and right sides (Reverse). |
Two Pass Matrix |
Draw a grid representing N x N. Shade the upper triangle (Transpose = $O(N²)$). Shade it row by row (Reverse = $O(N²)$). Total time = strictly $O(N²)$. |
Draw a completely separate N x N 2D array taking up memory. $O(N²)$ space. |
Draw a single temp variable used for swapping cells within the original matrix bounds. $O(1)$ extra space. |
| 49 |
Group Anagrams |
Nested Loop Comparisons For every string, compare it against every other string by sorting both of them. If they match, group them. |
The Exhaustive Sorter |
Draw N strings. Draw arrows pointing from string 1 to strings 2, 3, 4, sorting them every single time. Extremely slow: $O(N² \cdot K \log K)$. |
Hash Map (Sorted Key / Char Count) |
The Labeled Buckets |
Sort each string once and use it as a Hash Map key (e.g., "eat", "tea" -> "aet"). Append the original strings to the list at that key. Alternatively, use an array of 26 character counts as the key. |
Draw three buckets. Label one "aet", one "ant", one "abt". Draw strings ("eat", "tea", "ate") falling cleanly into the "aet" bucket. |
Linear Sorting Line |
Draw a single timeline representing N strings. Over each string, draw a small box representing the $O(K \log K)$ sort. Total time: $O(N \cdot K \log K)$. |
$O(N \cdot K)$ space, but the time limit will definitely exceed first. |
Draw a single Hash Map grouping pointers/references to the strings. The total size is exactly the sum of all string characters, $O(N \cdot K)$ space. |
| 50 |
Pow(x, n) |
Iterative Multiplication Run a standard `for` loop `n` times, multiplying `x` by itself. Will Time Limit Exceed (TLE) for massive powers (like n = 2^31). |
The Endless Loop |
Draw `x * x * x * x...` dragging out across the page. Write $O(N)$ time, explicitly noting that N can be billions, making it way too slow. |
Binary Exponentiation |
The Squaring Halver |
Instead of multiplying by `x`, square the base (`x = x * x`) and halve the exponent (`n = n / 2`). If `n` is odd, multiply the result by `x` once and decrement `n`. |
Draw a starting box `2^10`. Next arrow points to `4^5` (base squared, power halved). Next points to `4 * 16^2` (handled the odd power). Next points to `4 * 256^1`. |
Halving Block |
Draw a timeline representing exponent N. At each step, cross out half the remaining line. Logarithmic reduction guarantees $O(\log N)$ time. |
$O(1)$ space, but $O(N)$ time is unacceptable for production math libraries. |
Draw exactly two variables modifying in-place (the base and the current result). Completely $O(1)$ space. |
| 51 |
N-Queens |
Generate All Permutations Generate every possible way to place N queens on an N×N board (N² choose N) and check each board for validity. |
The Combinatorial Explosion |
Draw an empty grid. Note that for N=8, there are over 4 billion combinations. Draw a tiny "Check" box that fails almost every time. $O(N!)$ time. |
Backtracking (Row-by-Row + Bitsets) |
The Conflict Radar |
Place a queen in row 1, then row 2, etc. Use three boolean arrays (or bitsets) to track "locked" columns, positive diagonals, and negative diagonals. If a spot is locked, skip it. |
Draw an N×N board. Place a 'Q'. Draw vertical and diagonal red lines emanating from it. Move to the next row and only place a 'Q' in the white (unshaded) spaces. |
Pruned Recursive Tree |
Draw a tree where each level is a row. Show many branches ending early (pruning) because of diagonal conflicts. Time complexity is $O(N!)$. |
Generating and storing billions of invalid board configurations. |
Draw three small boolean arrays: `cols[N]`, `diag1[2N]`, `diag2[2N]`. Space is $O(N)$ for the stack and state tracking. |
| 52 |
N-Queens II |
N-Queens I + Result List Use the exact same code as Q51 to generate all full board layouts, then simply return the size of the final list. |
The Memory Waster |
Draw the solver from Q51. Show it building full 2D string arrays just to count them. Highlight the unnecessary memory allocation for strings. |
Backtracking (Counter Only) |
The Invisible Board |
Same logic as Q51, but instead of building a 2D grid of strings, just increment a single `count` variable whenever a valid placement reaches the last row. |
Draw a simple "counter" box next to a backtracking tree. Every time a "Leaf" node is reached (success), show the counter incrementing `+1`. No board is drawn. |
Pruned Decision Tree |
Identical to Q51. Time is $O(N!)$. The visualization shows that the branching factor reduces as queens are placed. |
$O(N²)$ space to store the full list of N×N boards (strings). |
Draw only the recursion stack and the 3 conflict-tracking arrays. Space is $O(N)$, significantly lighter than Q51. |
| 53 |
Maximum Subarray |
All Subarrays (Nested Loops) Check every possible starting index `i` and ending index `j`, calculating the sum of each. |
The 2D Sum Grid |
Draw an array. Draw a bracket for every possible start/end pair. Total pairs = N(N+1)/2. Calculating each sum takes $O(N)$, leading to $O(N³)$, or $O(N²)$ if optimized. |
Kadane’s Algorithm (Greedy/DP) |
The Fresh Start |
Iterate through the array. At each element, decide: "Is it better to add this to my current sum, or start a new sum from this element?" Keep track of the global maximum. |
Draw a running total box. As you move through the array, if the box becomes negative, "empty" it (reset to 0) and start fresh with the next number. |
Single Linear Scan |
Draw a single straight arrow from left to right. One pass. Exactly N operations. $O(N)$ time. |
Storing all subarray sums in a large table or matrix. |
Draw just two variables: `currentSum` and `maxSum`. $O(1)$ space. |
| 54 |
Spiral Matrix |
Simulation with Visited Matrix Move right until a wall or visited cell, then down, then left, then up. Repeat. Use a boolean matrix to track visited cells. |
The Redundancy Grid |
Draw an N×M matrix and an identical boolean "Visited" matrix. Show the pointer checking the Visited matrix before every single move. $O(N\cdot M)$ space. |
Boundary Shrinking |
The Closing Walls |
Define four boundaries: `top`, `bottom`, `left`, `right`. Traverse the top row, then increment `top`. Traverse the right col, then decrement `right`. Repeat until boundaries cross. |
Draw a grid. Draw four thick lines representing the borders. After each side is traversed, draw an arrow showing that border line physically moving inward. |
Total Cell Count |
Draw an N×M rectangle. Shade every cell exactly once in a spiral pattern. Time is strictly $O(N\cdot M)$. |
Draw an extra boolean matrix of size N*M. $O(N\cdot M)$ space. |
Draw exactly four integer variables representing the boundaries. No extra 2D arrays. $O(1)$ auxiliary space. |
| 55 |
Jump Game |
Backtracking / Recursion From index 0, try every possible jump distance. If any path reaches the end, return true. |
The Recursive Spiderweb |
Draw a tree where each node has `nums[i]` branches. Many branches overlap, leading to $O(2^N)$ or $O(N!)$ complexity. |
Greedy (Max Reach) |
The Moving Horizon |
Iterate through the array. Keep a variable `farthest`. At each step, if `i > farthest`, you're stuck (return false). Otherwise, update `farthest = max(farthest, i + nums[i])`. |
Draw the array. Draw a flag representing the `farthest` reachable point. As you walk forward, push the flag as far as the current spot allows. If you ever walk past the flag, you lose. |
Single Linear Pass |
Draw a straight arrow from 0 to N. One pass, constant work at each step. $O(N)$ time. |
Draw a massive recursion stack reaching depth N. |
Draw a single integer variable `farthest`. $O(1)$ space. |
| 56 |
Merge Intervals |
All-Pairs Comparison Compare every interval with every other interval. If they overlap, merge them into a new interval and restart the process until no more merges occur. |
The N² Bubble Merge |
Draw circles for intervals. Draw lines between every possible pair to check for overlaps. Tally the checks as $O(N²)$. |
Sorting + Linear Scan |
The Sweep Line (Timeline) |
Sort intervals by start time. Iterate through. If the current interval starts before the previous one ends, merge them by updating the end time to the max of both. |
Draw a horizontal timeline. Place intervals as segments above it. Draw a "Merge" bracket joining segments that physically touch or overlap. |
Sorting Log-Linearity |
Draw an $O(N \log N)$ box for sorting, followed by a single straight line $O(N)$ for the merge pass. Total = $O(N \log N)$. |
Storing multiple intermediate lists of partially merged intervals during the nested loop process. |
Draw a single output list. Because we only ever look at the "last merged" interval, space is $O(N)$ (or $O(\log N)$ for sorting). |
| 57 |
Insert Interval |
Append & Re-Merge Add the new interval to the existing list and then run the full "Merge Intervals" (Q56) logic on the whole set. |
The Pipeline Funnel |
Draw a list of intervals. Draw an arrow adding one more. Then draw the $O(N \log N)$ sorting machine from Q56. |
Three-Phase Linear Scan |
The Categorized Conveyor |
Iterate once. 1: Add all intervals that end before the new one starts. 2: Merge all overlapping intervals into one. 3: Add the merged result and all remaining intervals. |
Draw three shaded regions on a timeline: "Left (No Overlap)", "Middle (Merging Zone)", and "Right (Remaining)". Place the intervals into their respective regions. |
Single Linear Pass |
Draw a single straight arrow from index 0 to N. We decide the fate of each interval in a single check. $O(N)$ time. |
$O(N \log N)$ time/space overhead due to re-sorting an almost-sorted list. |
Draw a single result list. We build it element-by-element in one pass. $O(N)$ space. |
| 58 |
Length of Last Word |
Trim & Split Trim the string, split it by spaces into an array of strings, and return the length of the last element in that array. |
The Array Funnel |
Draw a long string. Draw a "Split" machine that breaks it into many smaller boxes. Point to the last box. Note the $O(N)$ space for the array. |
Backward Pointer Scan |
The Reverse Scanner |
Start a pointer at the end of the string. Move it left to skip any trailing spaces. Then, count characters until you hit a space or the start of the string. |
Draw the string with an arrow at the very end pointing left. Draw the arrow hopping over empty spaces, then dragging through the letters of the last word. |
Partial Scan Line |
Draw a line representing the string length N. Draw a shorter arrow starting from the end and stopping early. $O(N)$ worst case. |
Draw an array of all words in the string occupying heap memory. $O(N)$ space. |
Draw exactly one integer variable `length`. No extra arrays or strings. $O(1)$ space. |
| 59 |
Spiral Matrix II |
Hardcoded Directions Attempt to write if-else logic for every single turn based on fixed coordinate boundaries (difficult to generalize). |
The Manual Maze |
Draw a grid and manually trace a path. Note how complex the logic becomes without a systemic "boundary" approach. |
Boundary Contraction |
The Concentric Square Shrink |
Define Top, Bottom, Left, and Right boundaries. Fill the Top row and move the Top boundary down. Fill the Right col and move the Right boundary left. Repeat until full. |
Draw a square grid. Draw four arrows (T, B, L, R) pointing inward. As you finish a side, physically move that arrow's line one step toward the center. |
Perfect Grid Filling |
Draw an N x N grid. Shade every cell exactly once. Total operations = N². $O(N²)$ time. |
N/A - Standard simulation is required to build the output. |
Draw the resulting N x N matrix. No extra auxiliary data structures are used. $O(1)$ extra space (ignoring output). |
| 60 |
Permutation Sequence |
Generate & Sort Use backtracking to generate all N! permutations, sort them alphabetically, and return the k-th element. |
The Factorial Tree |
Draw a tree that branches N! times. Note that for N=9, this is 362,880 strings. Write $O(N! \cdot N)$ time. |
Factorial Number System (Math) |
The Bucket Selection |
Use math to determine which digit must be at each position. For the first position, there are (N-1)! permutations for each starting digit. Use `(k-1) / (n-1)!` to pick the digit. |
Draw a set of digits {1, 2, 3, 4}. Use the formula to "pluck" one number out and place it in the result. Repeat with the remaining smaller set. |
Iterative Calculation |
Draw N steps. At each step, show a small division operation and a digit removal. $O(N²)$ time (due to list removal). |
Draw a massive list in memory holding N! strings. $O(N! \cdot N)$ space. |
Draw a small list of N digits and the result string. $O(N)$ space. |
| 61 |
Rotate List |
Step-by-Step Rotation For each of the k rotations, find the second-to-last node, make it the new tail, and move the old tail to the head. |
The Repeating Cycle |
Draw a linked list. Draw an arrow circling from the end back to the start. Note that you traverse the whole list k times. Time: $O(N x K)$. |
The Circular Link (Ring) |
The Bracelet Snap |
Connect the tail to the head to form a circle. Calculate the effective rotation (k % length). Find the node at position (length - (k % length)), make it the new tail by setting its `next` to null, and return the node after it as the new head. |
Draw the list. Draw a curved line connecting the last node back to the first. Then, draw a "scissor" icon cutting the link at the specific index to turn the circle back into a line. |
Two-Pass Linear |
Draw one arrow measuring the length (O(N)) and a second arrow moving to the cut point (O(N)). Total time: $O(N)$. |
$O(1)$ space, but high time complexity due to redundant traversals. |
Draw exactly one circular structure in memory. Only pointer references are changed. Space: $O(1)$. |
| 62 |
Unique Paths |
Pure Recursion (DFS) From `(0,0)`, recursively call `moveRight()` and `moveDown()` until you hit the bottom-right corner. |
The Binary Explosion Tree |
Draw a root node `(0,0)`. It splits into two branches: `(0,1)` and `(1,0)`. Each of those splits again. Highlight the massive number of overlapping subproblems. Time: $O(2^m+n)$. |
Dynamic Programming (1D/2D) |
The Pascal Triangle Map |
The number of ways to reach a cell is the sum of ways to reach the cell above it and the cell to its left. Fill the grid row by row. |
Draw an M x N grid. Fill the first row and column with 1s. For cell `(1,1)`, look at the 1 above and 1 to the left; write '2' in the cell. Continue summing neighbors. |
Matrix Fill Area |
Draw a rectangle. Shade it in row by row. The time complexity is exactly the area of the rectangle. Time: $O(M x N)$. |
A massive recursion stack with 2^m+n calls. |
Draw a single 1D array (row) that gets updated M times. Space: $O(N)$. |
| 63 |
Unique Paths II |
Recursion with Check Same as Q62, but add an `if(grid[i][j] == 1) return 0;` condition in the recursive calls. |
The Blocked Tree |
Draw the recursion tree from Q62, but draw red "X"s on branches that lead to obstacles, showing how the search is terminated. |
DP with Obstacle Guard |
The Detour Grid |
Initialize a DP array. If a cell has an obstacle, set its DP value to 0. Otherwise, it is the sum of its top and left neighbors. |
Draw the grid with a blacked-out obstacle cell. When filling the grid, if you reach the black cell, write '0' and move on. Show how the sums "flow" around the obstacle. |
Single-Pass Grid |
Draw an M x N grid. Show a single traversal pass. Time: $O(M x N)$. |
Heavy recursion stack. |
Draw a single 1D array representing the current row being calculated. Space: $O(N)$. |
| 64 |
Minimum Path Sum |
Exhaustive Search (Recursion) Explore every possible path from top-left to bottom-right, calculating the total sum for each and tracking the minimum. |
The Path Finder Tree |
Draw a tree branching at every cell. Label each node with the path sum so far. Show how many branches are explored to find the winner. Time: $O(2^m+n)$. |
Dynamic Programming (In-Place) |
The Cost Accumulator |
Each cell in the DP table should store the minimum cost to reach it: `grid[i][j] += min(grid[i-1][j], grid[i][j-1])`. |
Draw the grid. For each cell, look at the values above and to the left. Pick the smaller one, add the current cell's value, and write it over the original number. |
Cell-by-Cell Calculation |
Draw a grid. Show a scanner moving through every cell once. Time: $O(M x N)$. |
Redundant path calculations filling memory. |
Draw the original grid being modified in-place. Space: $O(1)$ (if modifying input) or $O(N)$ for a 1D DP row. |
| 65 |
Valid Number |
Regex or Nested If-Else Try to use a very complex Regular Expression or a giant series of nested boolean checks for signs, dots, and exponents. |
The Spaghetti Logic |
Draw a flowchart with 20+ decision diamonds. Highlight how easily one edge case (like "0e") can break the entire logic. |
Deterministic Finite Automaton (DFA) |
The State Machine Rail |
Define states (e.g., "Start", "Sign", "Integer", "Dot", "Fraction", "Exponent"). Iterate through the string; each character triggers a transition to a new state. If you end in a "Valid" state, return true. |
Draw 6-8 circles (States). Draw arrows between them labeled with types (Digit, '.', 'e', '+/-'). Trace the string "3.14e-10" as a marble rolling from circle to circle. |
Finite State Transition |
Draw a single straight line representing the string length N. At each character, show a single lookup in a "state table." Time: $O(N)$. |
No significant extra memory, but the logic is extremely prone to human error. |
Draw a small 2D table (States x Inputs). The space is $O(1)$ because the table size is fixed regardless of string length. |
| 66 |
Plus One |
Int Conversion Convert the array of digits into a large integer, add 1, then convert it back into an array of digits. |
The Overflow Funnel |
Draw an array. Draw a funnel turning it into a single huge number. Note that for large arrays (100+ digits), this exceeds standard integer limits, causing a crash. |
Reverse Linear Scan |
The Ripple Effect |
Start from the last digit. If it's less than 9, increment and return. If it's 9, turn it to 0 and move left. If you reach the front and it's still 9, prepend a 1. |
Draw the array `[9, 9, 9]`. Start at the end. Change 9 to 0, move left. Change 9 to 0, move left. Change 9 to 0. Draw a "New Box" at the front and put '1' inside. |
Single Backward Arrow |
Draw a line of length N. Draw an arrow moving right-to-left. In the best case, it stops at the first step. Worst case, it touches every element once. $O(N)$. |
Allocating a massive BigInt or string to hold the intermediate number. |
Draw the original array. In most cases, it is modified in-place (O(1)). Only in the "all nines" case is a new array of size N+1 created (O(N)). |
| 67 |
Add Binary |
Base-2 to Base-10 Convert both binary strings to decimal integers, add them, and convert the result back to a binary string. |
The Base Converter |
Draw two binary strings. Draw a conversion machine outputting base-10 numbers. Note the overflow risk for strings longer than 64 bits. |
Two-Pointer Bitwise Addition |
The Vertical Adder |
Align strings by the end. Add bits digit-by-digit along with a `carry` variable (0 or 1). Use modulo for the bit and division for the carry. |
Stack "1010" and "1011". Draw vertical columns. 0+1=1, carry 0. 1+1=0, carry 1. 0+0+1=1, carry 0. 1+1=0, carry 1. Result: "10101". |
Parallel Linear Scan |
Draw two lines representing string lengths M and N. Draw a scanner moving from right to left once. Time: $O(\text{max}(M, N)$). |
Heavy memory usage for BigInt objects or intermediate decimal strings. |
Draw a StringBuilder or character array of size max(M, N) + 1. Space: $O(\text{max}(M, N)$). |
| 68 |
Text Justification |
Trial and Error Padding Try adding words to a line; if it exceeds `maxWidth`, try adding different amounts of spaces between words until it looks right. |
The Brute Force Typesetter |
Draw a box of width W. Try putting words in and drawing random space gaps, recalculating constantly. $O(N^2)$ or $O(N x W)$ complexity. |
Greedy Word Packing + Round Robin Spacing |
The Balanced Scale |
Pack as many words as possible. Calculate total spaces needed. Distribute spaces evenly. If there's a remainder, add extra spaces to the left-most gaps first. Handle the last line as left-justified. |
Draw a line with 3 words. Space needed = 7. Gaps = 2. 7 / 2 = 3 spaces each, with 1 remainder. Give 4 spaces to gap 1 and 3 spaces to gap 2. |
Linear Word Processing |
Draw a line of words. Show a pointer moving through the words once to group them into lines. Each word is processed exactly once. Time: $O(N)$. |
Storing multiple copies of strings during the padding/recalculation phase. |
Draw the final list of strings. Space is $O(N)$ to store the output text. No significant auxiliary structures are used. |
| 69 |
Sqrt(x) |
Linear Search Start from 1, 2, 3... and square each number until i x i > x. The answer is i-1. |
The Incrementing Bar |
Draw a number line. Draw a pointer starting at 1 and stepping right one unit at a time. The distance traveled can be up to √x. Time: $O(√x)$. |
Binary Search (Range [0, x]) |
The Half-Way Cut |
Search in the range [0, x]. If mid x mid > x, search the left half. If mid x mid <= x, record mid and search the right half to find a larger potential root. |
Draw a line from 0 to 100. Mark 50. 50^2 = 2500 (Too big). Cut range to [0, 49]. Mark 25. 25^2 = 625 (Too big). Repeat until range collapses. |
Logarithmic Halving |
Draw a block representing x. Draw a line cutting it in half, then half again. Total steps = log(x). Time: $O(\log x)$. |
$O(1)$ space. |
Draw exactly three variables: `low`, `high`, `mid`. $O(1)$ space. |
| 70 |
Climbing Stairs |
Recursion (DFS) To reach step n, you could have come from n-1 or n-2. f(n) = f(n-1) + f(n-2). |
The Exponential Tree |
Draw a root node N. Branch to N-1 and N-2. Each of those branches again. Highlight the massive redundancy (e.g., N-3 is calculated many times). Time: $O(2^N)$. |
Iterative DP (Fibonacci) |
The Staircase Build-up |
The number of ways to reach the current step is the sum of ways to reach the previous two steps. Use two variables to store only the last two results. |
Draw steps 1, 2, 3, 4, 5. Under step 1, write '1'. Under step 2, write '2'. For step 3, add 1+2=3. For step 4, add 2+3=5. |
Single Forward Arrow |
Draw a line of length N. Draw a pointer moving from 1 to N once. Time: $O(N)$. |
A recursion stack of depth N with 2^N total calls. |
Draw just two variables: `first` and `second`. No array or recursion used. Space: $O(1)$. |
| 71 |
Simplify Path |
Regex Substitution Use complex regular expressions to repeatedly replace "/./" with "/" and multiple "///" with "/", while trying to manually handle ".." via string searches. |
The Multi-Pass Filter |
Draw a string. Draw three separate machines it must pass through. Show how ".." requires the string to be "re-scanned" from the beginning multiple times. $O(N^2)$. |
Stack (Push/Pop on Chunks) |
The Directory Breadcrumb |
Split the string by "/". Iterate through the components. If it's a folder name, push to stack. If it's "..", pop from stack. If it's "." or empty, ignore it. Join at the end. |
Draw a vertical stack. For "/home/user/../docs/./", push "home", push "user". Encounter "..", pop "user". Encounter "docs", push "docs". Result: "/home/docs". |
Linear Token Scan |
Draw a line representing the path length N. Show a pointer moving through it exactly once. Time: $O(N)$. |
Creating multiple intermediate string copies for every ".." found. |
Draw a single stack containing only the final valid folder names. Space: $O(N)$. |
| 72 |
Edit Distance |
Brute Force Recursion For every character mismatch, recursively try all three operations: Insert, Delete, and Replace. Pick the path with the minimum count. |
The Ternary Explosion Tree |
Draw a root node. From it, draw 3 branches. From each of those, draw 3 more. Label branches as "Ins", "Del", "Rep". Highlight the overlapping subproblems. Time: $O(3^N)$. |
2D Dynamic Programming |
The Alignment Grid |
Create an (M+1) x (N+1) matrix. `dp[i][j]` represents the distance between `word1[0...i]` and `word2[0...j]`. If chars match, take diagonal value. If not, take `1 + min(top, left, diagonal)`. |
Draw a grid with "horse" on top and "ros" on left. Fill cell by cell. Show how each cell "looks" at its 3 neighbors to the top and left to find the cheapest path. |
Matrix Area Shade |
Draw a rectangle of size M x N. Shade every cell once. Time: $O(M x N)$. |
A massive recursion stack with 3^max(M,N) potential calls. |
Draw the (M x N) table. Note that you only need the previous row to calculate the current one, so space can be optimized to $O(\text{min}(M, N)$). |
| 73 |
Set Matrix Zeroes |
Additional Matrix Copy Create a clone of the original M x N matrix. Whenever you find a 0 in the original, set the entire row and column to 0 in the clone. |
The Double Grid |
Draw two identical M x N matrices side-by-side. Draw an arrow from a '0' in Grid A to a full cross of '0's in Grid B. Time: $O(M x N)$. |
In-Place State Marking |
The Flagship Rows |
Use the first row and first column of the matrix itself as markers. If `matrix[i][j]` is 0, set `matrix[i][0]` and `matrix[0][j]` to 0. Then, iterate again to fill zeroes based on those markers. |
Draw a grid. When you hit a 0 at `(2,3)`, draw an arrow pointing to the "0" at the start of Row 2 and the "0" at the top of Col 3. Those are your "flags". |
Two-Pass Grid Scan |
Draw a grid. Show one pass to set markers (O(MN)) and a second pass to apply markers (O(MN)). Time: $O(M x N)$. |
Draw a completely separate M x N array taking up extra memory. Space: $O(M x N)$. |
Draw the original grid. Highlight that only 2 extra boolean variables (for the first row/col) are needed. Space: $O(1)$. |
| 74 |
Search a 2D Matrix |
Linear Search Treat the 2D matrix like a list and check every single element one-by-one until the target is found. |
The Snaking Arrow |
Draw a grid. Draw a single long arrow snaking through every row from top to bottom. Time: $O(M x N)$. |
Binary Search (Flattened Index) |
The Virtual 1D Array |
Since the matrix is sorted, treat it as a single 1D array of size M x N. Use `mid / cols` for row and `mid % cols` for column index. Perform standard binary search. |
Draw a grid. Label cells from 0 to 11. Pick `mid = 5`. Draw the math: 5 / 4 = Row 1, 5 % 4 = Col 1. Target the cell `(1,1)` and split the virtual array. |
Halving Block |
Draw a line representing M x N elements. Show it being cut in half repeatedly. Time: $O(\log(M x N)$). |
$O(1)$ space. |
Draw three pointers (`low`, `high`, `mid`) and the column count variable. Space: $O(1)$. |
| 75 |
Sort Colors |
Standard Library Sort Simply call `Arrays.sort()` or `sort()`. While fast, it uses $O(N \log N)$ and doesn't exploit the fact that there are only 3 unique values. |
The Generic Sorter |
Draw a box labeled "QuickSort". Put `[2,0,2,1,1,0]` in, get `[0,0,1,1,2,2]` out. Note the $O(N \log N)$ cost. |
Dutch National Flag (3-Pointer) |
The Three-Zone Divider |
Maintain 3 pointers: `low` (boundary for 0s), `mid` (current element), and `high` (boundary for 2s). If `mid` is 0, swap with `low`. If 2, swap with `high`. If 1, just move `mid`. |
Draw an array. Place `L` at the start, `H` at the end, `M` in the middle. Show 0s being kicked to the left of `L` and 2s being kicked to the right of `H`. |
One-Pass Triple Pointer |
Draw a line of length N. Show the `mid` pointer traversing it exactly once. Time: $O(N)$. |
Depends on the library sort (O(N) or $O(\log N)$). |
Draw the array being modified in-place with just 3 integer pointers. Space: $O(1)$. |
| 76 |
Minimum Window Substring |
All Substrings + Map Check Generate every possible substring of S (O(N^2)) and for each one, check if it contains all characters of T (O(N)). |
The Cubic Scanner |
Draw a long string. Below it, draw hundreds of smaller lines representing every possible slice. For each slice, draw a "Search" arrow scanning for T. Time: $O(N^3)$. |
Sliding Window (Two Pointers + Map) |
The Elastic Band |
Expand the `right` pointer until the window is "valid" (contains all T). Then, contract the `left` pointer as much as possible while keeping it valid. Track the smallest such window. |
Draw string S and a frequency map for T. As `R` moves, subtract from map. If a map value hits 0, a character is "satisfied." When all are satisfied, move `L` to shrink. |
Two Chasing Pointers |
Draw a timeline. Show L and R pointers both moving 0 to N. Since each moves at most N times, it's $O(N+N)$ = $O(N)$. |
Creating thousands of substring objects in memory. |
Draw two frequency maps (Target and Current Window). Space is $O(K)$, where K is the size of the character set (e.g., 52 for A-Z, a-z). |
| 77 |
Combinations |
Permutation Filtering Generate all n! permutations of numbers 1 dots n, then filter out duplicates and keep only those of length k. |
The Factorial Filter |
Draw a massive tree of all permutations. Draw a "Sieve" at the bottom that only lets through unique combinations. Time: $O(N!)$. |
Backtracking (DFS + Lexicographic) |
The Growing Chain |
Build the combination one number at a time. To avoid duplicates, only pick numbers *larger* than the last one picked. If length hits k, save the result. |
Draw a tree starting at root. Branch to 1, 2, 3... From 1, branch only to 2, 3... (skipping 1). From 2, branch only to 3... (skipping 1, 2). |
Binomial Coefficient Tree |
Draw a tree where each level adds a digit. The number of leaf nodes is exactly (n Choose k). Time: $O((n \text{Choose} k)$ x k). |
Massive $O(N!)$ lists stored before filtering. |
Draw the recursion stack (depth k) and a single array `path` that is modified in-place. Space: $O(k)$. |
| 78 |
Subsets |
Recursion (All Paths) For every element, branch the recursion: "Include this element" vs "Exclude this element." |
The Power Set Tree |
Draw a binary tree. At each level, the tree doubles in size. By level N, there are 2^N nodes. Time: $O(2^N)$. |
Cascading / Bitmasking |
The Doubling List |
Start with an empty set `[[]]`. For every new number, take all existing subsets, add the new number to them, and merge them back into the list. |
Start: `[[]]`. Next (1): `[[], [1]]`. Next (2): Take existing, add 2: `[2], [1, 2]`. Result: `[[], [1], [2], [1, 2]]`. |
Exponential Growth Bar |
Draw a bar that doubles in length for every step. Total operations: 2^0 + 2^1 + dots + 2^N-1. Time: $O(N x 2^N)$. |
Recursive call stack depth of N. |
Draw the output list growing exponentially. Auxiliary space is just the current path: $O(N)$. |
| 79 |
Word Search |
BFS from Every Cell From every cell `(r, c)`, start a Breadth-First Search to find the word. (Harder to track "visited" cells across paths). |
The Exploding Ripple |
Draw a grid. From one cell, draw ripples spreading in all 4 directions. Show how keeping track of visited cells per path becomes a memory nightmare. |
Backtracking (DFS + In-Place Mark) |
The Ant on a Grid |
For each cell, start a DFS. If the char matches, mark the cell as "#" (visited), recurse to neighbors, then change it back (backtrack). |
Draw a 2D grid. Trace a path A to B to C. At C, if there's no match, "undo" the path C to B to A to try a different direction from B. |
Bounded 4-ary Tree |
Draw a tree where each node has 3 branches (can't go back). Depth is L (word length). Total time: $O(N x M x 3^L)$. |
$O(N x M)$ "visited" arrays for every single path explored. |
Draw the grid. Highlight that no extra matrix is used—only the recursion stack of depth L. Space: $O(L)$. |
| 80 |
Remove Duplicates from Sorted Array II |
Frequency Map + New Array Count the frequency of every element. Iterate through the map and add each element at most twice to a new array. |
The Counting Bucket |
Draw the array. Draw a "Tally" table next to it. Draw a new array below. Show elements being copied only if their tally is <= 2. |
Two Pointers (Slow/Fast with Offset) |
The Smart Overwriter |
A `slow` pointer marks where the next valid element goes. A `fast` pointer scans. If the current element is different from the element at `slow - 2`, it's valid. |
Draw an array. Place `S` at index 2, `F` at index 2. Compare `arr[F]` with `arr[S-2]`. If different, write `arr[F]` to `arr[S]` and move `S`. |
Single Linear Pass |
Draw a single straight arrow from left to right. One pass through the data. Time: $O(N)$. |
A Hash Map and a new array of size N. Space: $O(N)$. |
Draw the original array with two pointers. No extra structures. Space: $O(1)$. |
| 81 |
Search in Rotated Sorted Array II |
Linear Scan Since the array contains duplicates, simply iterate from index 0 to N-1 to find the target. |
The Constant Speed Walker |
Draw a pointer moving step-by-step from start to finish. $O(N)$ time. Point out that the "rotated" property is ignored. |
Binary Search (Shrinking Bound) |
The Shifting Pivot |
Use binary search. If `nums[L] == nums[mid] == nums[R]`, we can't tell which side is sorted. Shrink the window by L++ and R-- until they differ. Then apply standard rotated search logic. |
Draw a graph with two plateaus at the same height. Show that if the middle is also that height, we must "step in" from both sides until we find a slope to apply binary search. |
Halving with Linear "Worst-Case" |
Draw a binary search tree. At the root, draw a small horizontal arrow showing the boundary shrink. Total time: $O(\log N)$ on average, $O(N)$ worst case. |
$O(1)$ space. |
Draw three pointers (L, R, mid) and the shrinking movement of L/R. Space: $O(1)$. |
| 82 |
Remove Duplicates from Sorted List II |
Hash Map Frequency Count Traverse the list and store frequencies in a Map. Traverse again and only include nodes whose count is exactly 1. |
The Two-Pass Filter |
Draw a linked list. Draw a tally table next to it. Draw a new list being built by skipping any value with a tally > 1. $O(N)$ time, $O(N)$ space. |
Sentinel Node + Two Pointers |
The "Delete the Whole Block" Rule |
Use a dummy node. Maintain a `prev` pointer. If `curr` has a duplicate next to it, skip the *entire* block of duplicates by pointing `prev.next` to the first non-duplicate node found. |
Draw a list `1->2->2->3`. Use a `Dummy`. `prev` stays at 1. When it sees `2->2`, it jumps directly to `3`. Draw the pointer bypassing the entire "2" block. |
Single Forward Traverse |
Draw a line of length N. Show a pointer moving through it once. Even when skipping blocks, every node is visited at most twice. $O(N)$. |
Draw a Hash Map storing all values and counts. Space: $O(N)$. |
Draw a `Dummy` node and a few pointer variables. All work is done by re-linking existing nodes. Space: $O(1)$. |
| 83 |
Remove Duplicates from Sorted List |
Compare and Skip For every node, compare it with its `next`. If the values are the same, link the current node to `next.next`. |
The Local Comparison |
Draw two adjacent nodes. If they match, erase the link to the second one and draw a link to the third. $O(N)$ time. |
Single Pass (In-Place) |
The "Keep the First" Rule |
Iterate once. While `curr.next` has the same value as `curr`, delete `curr.next`. Only move the `curr` pointer forward when the next value is different. |
Draw `1->1->1->2`. Pointer stays at the first `1`. It deletes the second `1`, then the third `1`. Finally, it moves to `2`. |
Single Pass Line |
Draw a straight line. Every node is visited once. $O(N)$ time complexity. |
N/A - Usually done efficiently. |
Draw the list being modified in-place. Space: $O(1)$. |
| 84 |
Largest Rectangle in Histogram |
All Pairs (Nested Loops) For every pair of bars (i, j), find the minimum height between them and calculate the area. |
The Quadratic Area Checker |
Draw a histogram. Draw brackets between every possible start and end bar. For each bracket, draw a dashed line at the lowest bar height. $O(N^2)$ time. |
Monotonic Stack |
The Ascending Staircase |
Keep a stack of indices with increasing heights. When you see a bar shorter than the top, "pop" the top and calculate the area using the popped height as the minimum. |
Draw a stack. Push heights: `[2, 1, 5, 6]`. When `2` comes, it's smaller than the previous height? No. When `1` comes, it pops the taller ones, calculates area, and takes their place. |
Linear Stack Pass |
Draw a line of length N. Every element is pushed once and popped once. 2N operations = $O(N)$ time. |
Storing min-heights in a 2D matrix or nested loop values. |
Draw a vertical stack growing and shrinking. Max space is the number of bars. Space: $O(N)$. |
| 85 |
Maximal Rectangle |
All Possible Subgrids Check every possible rectangle (top-left to bottom-right) in the matrix to see if it consists only of 1s. |
The Brute Force Grid Scanner |
Draw a 2D grid. Highlight a small rectangle, then a bigger one, then a taller one. Total combinations: $O(N^2 M^2)$. Checking each takes $O(\text{NM})$. Total: $O(N^3 M^3)$. |
DP + Largest Histogram (Q84) |
The Rising Tide |
Treat each row as the "ground" for a histogram. For row i, the height of bar j is the number of consecutive 1s ending at `(i, j)`. Run the $O(M)$ histogram algorithm for each row. |
Draw a grid. For row 1, heights are `[1, 0, 1]`. For row 2, if there's a 1 below a 1, height becomes 2. Now run the "Histogram" visual on these heights. |
Row-by-Row Stack Pass |
Draw an N x M grid. For each of the N rows, you perform an $O(M)$ stack-based scan. Total time: $O(N x M)$. |
Storing every possible rectangle coordinate. |
Draw a 1D array of size M that stores the current "heights" as you move down the rows. Space: $O(M)$. |
| 86 |
Partition List |
Array Extraction Traverse the list, extract all values into an array, filter them into two lists (less than x and greater/equal to x), then rebuild the linked list. |
Two Parallel Buckets |
Draw a linked list. Draw two empty boxes labeled "Small" and "Large". Draw arrows moving numbers from the list into these boxes. Note the $O(N)$ extra space for the new nodes. |
Two Dummy Nodes (Merging Streams) |
The Hairline Splitter |
Create two dummy nodes: `lessHead` and `greaterHead`. Iterate through the list, attaching nodes to either the `less` tail or `greater` tail. Connect the `less` tail to `greaterHead.next` at the end. |
Draw the original list. Draw two stars (Dummies). As you move through the list, "sever" the arrow of the current node and point it to the tail of the appropriate dummy list. |
Single Linear Pass |
Draw a single straight line representing the list. Every node is visited once and its `next` pointer updated once. $O(N)$ time. |
Creating an intermediate array and brand new nodes. Space: $O(N)$. |
Draw the original nodes only. Emphasize that we are just rearranging existing memory links. Space: $O(1)$. |
| 87 |
Scramble String |
Pure Recursion For every possible split point i in the string, check if the two halves are scrambled versions of each other (including the case where they are swapped). |
The Exponential Tree of Splits |
Draw a string. Split it in the middle. From each split, draw two more branches (Stay vs Swap). The tree depth is N. Time: $O(4^N)$ or $O(N!)$ depending on implementation. |
3D Dynamic Programming / Memoization |
The Recursive Pruning Grid |
Use a Map to store `(s1, s2)` pairs that have already been checked. Before checking a split, verify that both strings have the same character counts (anagram check) to fail early. |
Draw a 3D grid where `dp[len][i][j]` represents if `s1[i...i+len]` is a scramble of `s2[j...j+len]`. Fill small lengths first and build up to length N. |
Pruned Recursive Depth |
Draw the recursion tree but draw thick red "X" marks over branches where character counts don't match. Time: $O(N^4)$ for DP. |
Deep recursive stack without any memory of previous results. |
Draw a Hash Map (Memoization table) storing string pairs. Space: $O(N^4)$ for the DP table. |
| 88 |
Merge Sorted Array |
Append and Sort Copy all elements of `nums2` into the empty slots of `nums1`, then call `sort()`. |
The Messy Pile Sorter |
Draw `nums1` with empty space at the end. Dump `nums2` into that space. Draw a big circle around it labeled "O(N log N) Sort". |
Three Pointers (Backward Fill) |
The Reverse Zipper |
Start three pointers: `p1` at the last actual element of `nums1`, `p2` at the end of `nums2`, and `p` at the very end of `nums1`'s memory. Fill `nums1` from right to left with the larger value. |
Draw `nums1` and `nums2`. Place `p` at the far right of `nums1`. Compare `p1` and `p2`. Whichever is bigger moves to `p`, then `p` and that pointer move left. |
Single Backward Pass |
Draw a line representing the total length M+N. Show the `p` pointer moving from right to left exactly once. Time: $O(M+N)$. |
$O(N \log N)$ or $O(N)$ depending on sorting overhead. |
Draw the `nums1` array being filled in place. No extra arrays are created. Space: $O(1)$. |
| 89 |
Gray Code |
Backtracking with Visited Set Generate all possible binary strings and use backtracking to find a sequence where each number differs by only one bit from the previous, avoiding the visited set. |
The Bit-Flip Maze |
Draw a graph where nodes are binary numbers and edges connect numbers with 1-bit difference. Trace a path that hits every node once (Hamiltonian path). $O(2^N)$ time. |
Iterative Mirroring / Bitwise Formula |
The Binary Reflective Symmetry |
Start with `[0]`. For each bit i from 0 to n-1, take the current list, reverse it, add 2^i to each element, and append it to the original list. Or use the formula: G(i) = i oplus (i gg 1). |
Draw a list: `0, 1`. Mirror it: `1, 0`. Add 2^1 (which is 2) to the mirrored part: `2, 3`. New list: `0, 1, 3, 2`. |
Exponential List Growth |
Draw a bar that doubles in length N times. Total elements = 2^N. Time: $O(2^N)$. |
Recursion stack and visited set taking up $O(2^N)$ space. |
Draw the final result list. The iterative logic uses no recursion or extra sets. Space: $O(2^N)$ (for the output) or $O(1)$ auxiliary. |
| 90 |
Subsets II |
Subsets I + Hash Set Generate all 2^N subsets using the standard recursion and put each one into a Hash Set to filter out duplicates. |
The Sieve of Power Sets |
Draw the binary tree from Q78. At the bottom, show duplicate sets (like `[1, 2]` and `[1, 2]`) hitting a wall that only lets one through. Time: $O(N \cdot 2^N)$. |
Sort + Backtracking (Sibling Skip) |
The Pruned Choice Tree |
Sort the array first. During recursion, if the current element is the same as the previous one at the same level, skip it. This ensures each duplicate is only used once to start a sequence. |
Draw a tree for `[1, 2, 2]`. From the root, branch to 1 and the *first* 2. Put a red "X" through the branch for the *second* 2, saying "Already picked a 2 here." |
Pruned Exponential Tree |
Draw a tree where many branches are cut off. The number of nodes is still bounded by 2^N, but much smaller for many duplicates. Time: $O(N \cdot 2^N)$. |
Storing 2^N subsets in a Hash Set for deduplication. |
Draw a single recursion stack (depth N) and one `path` array. No Hash Set needed. Space: $O(N)$. |
| 91 |
Decode Ways |
Pure Recursion At each index, branch into two paths: one taking a single digit, and one taking two digits (if valid). Count total leaf nodes. |
The Binary Branching Tree |
Draw a string like "121". Branch into '1' and '12'. From '1', branch into '2' and '21'. Note how many paths repeat the same sub-string calculations. $O(2^N)$. |
1D Dynamic Programming (Fibonacci-like) |
The Staircase with Conditions |
dp[i] is the number of ways to decode the prefix of length i. It’s the sum of dp[i-1] (if the last digit is
eq 0) and dp[i-2] (if the last two digits form a number 10-26). |
Draw a line of cells. For each cell, look back at the previous one and the one before that. Draw arrows showing the "flow" of counts, but only if the decoding rules allow it. |
Single Forward Scan |
Draw a straight arrow from index 0 to N. One pass, constant work per step. $O(N)$ time. |
A massive recursion stack with 2^N calls. |
Draw just two variables (`prev1`, `prev2`) storing the counts of the last two states. $O(1)$ auxiliary space. |
| 92 |
Reverse Linked List II |
Extract, Reverse, Rebuild Traverse to the sub-segment, copy the nodes into an array, reverse the array, and update the node values in the list. |
The Array Buffer |
Draw a linked list. Circle a middle section. Draw an arrow moving those nodes into a temporary box, flipping them, and shoving them back. $O(N)$ space. |
In-Place "Leapfrog" Reversal |
The Needle and Thread |
Use a `dummy` node and a `pre` pointer to the node before the reversal. Repeatedly move the `curr.next` node to the position right after `pre`. |
Draw `pre -> curr -> next -> ...`. Draw a "jump" arrow where `curr` skips `next` to point to `next.next`, and `next` is "re-threaded" to point to where `pre.next` was. |
Single Segment Pass |
Draw a line. Shade the specific segment [left, right]. Show the pointer traversing it once. $O(N)$ time. |
Draw an array or list of size (right - left) in the heap. Space: $O(N)$. |
Draw the list with 4 pointers (`pre`, `curr`, `then`, `dummy`). All work is done by re-linking existing memory. Space: $O(1)$. |
| 93 |
Restore IP Addresses |
3-Way Nested Loops Use three nested loops to place three dots in all possible positions. For each combination, check if all 4 resulting segments are valid (0-255, no leading zeros). |
The Dot Slicer |
Draw a string of 12 digits. Draw three vertical lines (dots) at every possible gap. Note that the number of checks is constant but logically $O(N^3)$. |
Backtracking with Pruning |
The 4-Level Decision Tree |
Recursively place a dot after 1, 2, or 3 digits. If a segment is invalid or you run out of string before placing 4 segments, backtrack immediately. |
Draw a tree with a maximum depth of 4. From the root, branch 1, 2, or 3 digits. If you branch "300", put a red "X" through it because it's > 255. |
Finite Branching Tree |
Draw a tree with 4 levels. Each node has max 3 branches. The total number of nodes is strictly limited. $O(1)$ time in practice, or $O(3^4)$. |
Storing every possible (even invalid) dot combination as strings. |
Draw the recursion stack (depth 4) and a list for the current segments. Space: $O(1)$ (bounded by IP rules). |
| 94 |
Binary Tree Inorder Traversal |
Standard Recursion Visit `left`, then current `node`, then `right`. The system stack handles the "waiting" nodes. |
The Depth-First Dive |
Draw a tree. Draw a line tracing the perimeter of the tree, starting at the root and hugging the left side until it can't go further, then recording the node. $O(N)$ time. |
Iterative with Stack (or Morris) |
The Manual LIFO Stack |
While `curr` is not null, push it to stack and move to `curr.left`. When null, pop from stack, record value, and move to `curr.right`. (Morris is $O(1)$ space). |
Draw a tree and a vertical bucket (Stack). Push the left spine of the tree into the bucket. Pop one, then look at its right child and repeat. |
Single Node Visit |
Draw a tree. Mark each node with a single dot. Total time is exactly the number of nodes. $O(N)$. |
Implicit recursion stack of depth H (height of tree). $O(H)$ space. |
Draw an explicit Stack structure. Max size is the height of the tree. If using Morris Traversal, draw temporary "threads" (pointers) back to ancestors. Space: $O(H)$ or $O(1)$. |
| 95 |
Unique Binary Search Trees II |
Recursive Generation For a range [1, n], pick i as root. Recursively generate all left subtrees from [1, i-1] and all right subtrees from [i+1, n]. Combine every left with every right. |
The Forest Generator |
Draw the number 1, 2, 3. Pick '2' as root. Draw the possible '1' on the left and '3' on the right. Note the massive repetition of building the same subtrees. $O(4^N/N^1.5)$. |
Recursion with Memoization |
The Pre-built Subtree Library |
Same as brute force, but store the result of `generate(start, end)` in a map. If you need the subtrees for range [1, 2] again, just pull the already-constructed list of trees. |
Draw a Map where the Key is the range (e.g., "1-3") and the Value is a list of root pointers. Show the algorithm "checking out" a tree from the library instead of building it. |
Catalan Complexity |
Draw the growth of Catalan numbers. Time is $O(\text{Catalan}(N)$ x N), which accounts for the cost of building each tree. |
Redundant creation of identical tree structures in the heap. |
Draw the memoization map. Note that many large trees actually share pointers to the same smaller subtree nodes in memory. Space: $O(\text{Catalan}(N)$ x N). |
| 96 |
Unique Binary Search Trees |
Pure Recursion For each number i from 1 to n, treat it as the root and recursively calculate the number of unique left subtrees and right subtrees, then multiply them. |
The Exploding Recursive Tree |
Draw a root node N=4. Branch into roots 1, 2, 3, 4. For root 3, show a left branch for N=2 and right for N=1. Point out how often G(2) is recalculated. $O(3^N)$. |
Dynamic Programming (Catalan Number) |
The Accumulating List |
G(n) depends on the results of G(0) dots G(n-1). Build the solution iteratively: G(n) = sum_i=1^n G(i-1) x G(n-i). |
Draw an array `dp` from 0 to N. Fill `dp[0]=1, dp[1]=1`. For `dp[3]`, show three pairs of multiplications: (dp[0] * dp[2]) + (dp[1] * dp[1]) + (dp[2] * dp[0]). |
Nested Summation Scan |
Draw two pointers (i and j) moving within an array of size N. i moves from 1 to N, and j scans 0 to i. Total operations = 1+2+dots+N. Time: $O(N^2)$. |
A massive recursion stack with 3^N depth and no memory. |
Draw a single 1D array of size N+1. Space: $O(N)$. |
| 97 |
Interleaving String |
Recursion with Backtracking Try matching the first char of s3 with s1. If it matches, recurse. If it doesn't work, backtrack and try matching with s2. |
The Binary Decision Path |
Draw three strings. Draw a decision tree where each node has two choices: "Take from s1" or "Take from s2". Note the exponential $O(2^M+N)$ paths. |
2D Dynamic Programming |
The Reachability Grid |
dp[i][j] is a boolean: "Can the first i chars of s1 and first j chars of s2 form the first i+j chars of s3?". Fill based on top/left neighbors. |
Draw a grid with s1 on top and s2 on left. Start at (0,0) as `T`. A cell is `T` if (left is `T` AND s1 matches s3) OR (top is `T` AND s2 matches s3). |
Matrix Area Shade |
Draw an M x N rectangle. Show a single pass through every cell. Time: $O(M x N)$. |
Exhaustive recursion stack of depth M+N. |
Draw a 1D array representing the current row. We only need the previous state to calculate the current. Space: $O(N)$. |
| 98 |
Validate Binary Search Tree |
Local Comparison Only Check if `node.left.val < node.val < node.right.val` for every node. (Fails if a far-left node is greater than a root ancestor). |
The Shallow Scanner |
Draw a tree where a leaf node violates a root's range but satisfies its parent. Draw a red "X" through the "Local" logic to show it misses the violation. |
Recursion with Range (Min/Max) |
The Descending Constraints |
Pass a `low` and `high` boundary down the tree. For a left child, update `high = node.val`. For a right child, update `low = node.val`. If a node is out of bounds, return false. |
Draw a tree. At the root, write (-infty, infty). For the left child, write (-infty, RootValue). For the right, (RootValue, infty). Keep narrowing the boxes. |
Single Node Visit |
Draw a tree. Show a single DFS path visiting every node exactly once. Time: $O(N)$. |
N/A - Simple recursion. |
Draw the recursion stack. The max depth is the tree height H. Space: $O(H)$. |
| 99 |
Recover Binary Search Tree |
Extract, Sort, Replace Perform an inorder traversal to get all values. Sort the values. Perform a second traversal and replace node values with the sorted ones. |
The Sort-and-Swap Funnel |
Draw a tree. Draw an arrow extracting values into an array. Draw a sorting machine. Draw arrows putting sorted values back into the tree. $O(N \log N)$. |
Morris Inorder Traversal |
The Temporary Thread |
Traverse the tree without a stack/recursion. If you find a spot where `prev.val > curr.val`, record the violation. After the full traversal, swap the two "violation" nodes. |
Draw a tree. Draw a "thread" (dashed line) from the right-most node of a left subtree back to the current root. Use this thread to return without a stack. |
Constant-Space Walk |
Draw a tree and trace the perimeter. Show that every node is visited at most twice. Time: $O(N)$. |
An array of size N to store node values. Space: $O(N)$. |
Draw the tree. Highlight that only 3 pointer variables (`first`, `second`, `prev`) are used. Space: $O(1)$. |
| 100 |
Same Tree |
String Serialization Convert both trees into strings (e.g., "1,2,#,3") and compare the strings for equality. |
The String Converter |
Draw two trees. Draw an arrow from each to a text box. Compare the text boxes character-by-character. $O(N)$ time but high constant factor. |
Recursive DFS (Structural Comparison) |
The Parallel Mirror |
Base cases: if both null, true; if one null, false; if values differ, false. Recurse: `isSame(p.left, q.left) && isSame(p.right, q.right)`. |
Draw two identical trees side-by-side. Point to the root of both simultaneously. Move both "fingers" to the left child, then right child, checking for a match at every stop. |
Simultaneous Traversal |
Draw two trees. Shade nodes in both trees in the same order. Time: $O(N)$ (where N is the smaller tree's size). |
Storing full string representations in the heap. Space: $O(N)$. |
Draw the recursion stack for one tree. Max depth is tree height H. Space: $O(H)$. |
| 101 |
Symmetric Tree |
Create a complete mirrored copy of the left subtree and compare it node-by-node with the right subtree. |
Two overlapping full binary tree structures compared at $O(N)$ operations. |
Draw the original tree, sketch a mirrored clone beside it, and draw straight lines connecting identical nodes to show the $O(N)$ verification work. |
Two-pointer recursive DFS (or BFS with queue). |
Two points of light originating at the root and moving outward symmetrically down the left and right branches. |
Trace the left pointer moving left while the right pointer moves right. Then left moves right while right moves left. |
Draw a single tree. Use two different colored pens (e.g., red and blue) to trace the mirrored paths simultaneously from the root downward. |
A single recursion tree where each node represents a pair of nodes being evaluated simultaneously, scaling linearly. |
Draw a recursion tree, but label each circle with a pair of nodes (e.g., `(2L, 2R)`). Count the pairs to prove $O(N)$ time. |
Visualize two completely separate tree structures occupying different blocks in heap memory. |
Visualize the call stack frames stacking up to the height of the tree $O(h)$, passing two pointers per frame. |
| 102 |
Binary Tree Level Order Traversal |
DFS to find max depth, then loop from depth 0 to max. Do a fresh DFS for each depth iteration to collect nodes at that specific level. |
Multiple overlapping paths from the root to the bottom, illustrating redundant $O(N^2)$ traversal paths. |
Draw the tree. Draw multiple arrows starting from the root down to depth k for each separate level lookup. |
BFS using a Queue. |
A horizontal scanning laser sweeping from the top of the tree to the bottom, highlighting one row at a time. |
Maintain a queue. Enqueue root. Loop through the current size of the queue, pop nodes, add to level list, and push children. |
Draw the tree. Draw horizontal dashed lines separating each level. Draw a box beside it representing the queue updating at each dashed line. |
A linear graph showing each node entering and exiting the queue exactly once (O(N)). |
Cross out each node with a single stroke as it is added to the result array, proving no node is visited twice. |
Visualize multiple deep call stacks $O(h)$ being created and destroyed for every single depth query. |
Visualize a Queue expanding and contracting like an accordion, reaching its maximum width at the tree's widest level $O(W)$. |
| 103 |
Binary Tree Zigzag Level Order Traversal |
Standard BFS traversal, followed by a manual loop over the result array to reverse every alternate level's list at the end. |
Standard BFS linear graph, followed by a block showing the extra array reversal operations adding overhead. |
Draw a standard level order output table, then explicitly draw looping flip-arrows over alternate rows to show the extra work. |
BFS with a Double-ended Queue (Deque) and a boolean direction flag. |
A snake-like traversal path wrapping left-to-right, then right-to-left down the tree. |
Track a leftToRight boolean. Based on the flag, either append or prepend the popped node's value to the current level's list. |
Draw the tree. Draw solid arrows moving left-to-right on row 1, right-to-left on row 2, alternating down. |
Single-pass linear processing (O(N)), identical to standard BFS but with a constant time conditional check. |
Same as Q102, cross off nodes linearly, but draw small directional arrows next to the crossed nodes to show insertion direction. |
Standard Queue memory + additional temporary array memory allocated specifically for the reversing step. |
Visualize a Deque structure showing rapid insertions occurring at both the head and the tail dynamically. |
| 104 |
Maximum Depth of Binary Tree |
Maintain a global max_depth variable. Do a DFS starting from root to every leaf, calculating path length and updating the global variable. |
Highlighting every single root-to-leaf path independently to show the aggregate search space. |
Draw separate lines tracing from every single leaf node all the way back up to the root. |
Post-order Traversal (Bottom-Up DFS). 1 + max(left, right) |
Integer values "bubbling up" from the leaf nodes to the root, combining at each parent. |
Start at leaves (return 1). Move to parent: take the max of the left and right returned values, add 1, and return up. |
Write '1' next to all leaf nodes. Draw arrows pointing up to parents, crossing out the parent and writing the max(children) + 1. |
Call stack depth matching the physical height of the tree. |
Trace the absolute longest path in the tree with a thick highlighter to represent the $O(N)$ time and $O(h)$ space bottleneck. |
Global heap variable alongside call stack frames for every possible path. |
Visualize call stack frames cleanly winding down to a leaf and immediately unwinding optimally $O(h)$. |
| 105 |
Construct Binary Tree from Preorder and Inorder Traversal |
For every element in the preorder array, do a linear scan through the inorder array to find it and split the subtrees. |
An $O(N^2)$ grid where every recursive tree split requires an $O(N)$ array search block. |
Write both arrays. Pick the first item from preorder, draw a long arrow traversing the inorder array to find it, split the array, repeat. |
Hash Map for $O(1)$ inorder index lookup + Recursive DFS. |
The preorder array acting as a steady drill, while a Hash Map instantly splits the inorder array into left/right blocks like a cleaver. |
Map inorder values to indices. Keep a pointer for preorder. Root is preorder[ptr]. Instantly get index from map. Recurse left/right. |
Draw the Hash Map explicitly. Cross off preorder elements sequentially, drawing them immediately as tree nodes. |
$O(N)$ constant mapping combined with a single $O(N)$ recursive pass to build the tree. |
Draw arrays side-by-side. Draw an instantaneous "lightning bolt" line from the preorder element to its inorder map index to show $O(1)$ lookup. |
$O(N)$ call stack space scaling with the height, but no extra data structures visualized. |
Visualize a Hash Map occupying $O(N)$ space in heap memory sitting right next to the $O(N)$ recursive call stack. |
| 106 |
Construct Binary Tree from Inorder and Postorder Traversal |
Linearly scan the inorder array for every popped element from the postorder array to find the root index and split subtrees. |
An $O(N^2)$ grid showing a linear array search triggered for every single node creation step. |
Write the inorder array. Pick the last element of postorder. Draw a long arrow scanning the inorder array from left to right until you find it. Repeat. |
Hash Map for $O(1)$ inorder index lookup + Recursive DFS (Process postorder backwards: Root, Right, Left). |
Postorder array acts as a reverse drill. Hash Map acts as an instant cleaver, splitting the inorder array immediately into right and left partitions. |
Map inorder values to indices. Pop from the end of postorder to get the root. Lookup its index instantly. Crucially, recurse RIGHT first, then LEFT. |
Draw the Hash Map. Cross off postorder elements from right-to-left. Draw the tree building downwards, strictly branching right before left. |
$O(N)$ linear mapping phase, followed by a single $O(N)$ recursive tree-building phase. |
Draw arrays. Draw instantaneous lines from the end of the postorder array directly to the mapped index in the inorder array, demonstrating $O(1)$ lookups. |
Show $O(N)$ call stack depth, with redundant linear scans consuming time but not extra memory. |
Visualize an $O(N)$ Hash Map in heap memory stabilizing the lookup time alongside the $O(H)$ recursive call stack. |
| 107 |
Binary Tree Level Order Traversal II |
Perform a standard top-down Level Order Traversal (BFS), store results in an array of arrays, and then manually reverse the entire outer array. |
A standard BFS linear graph followed by a block representing the $O(N)$ reversal of the output array. |
Draw standard level order output. Draw a large curved arrow flipping the entire structure upside down at the very end. |
BFS with a Queue + Prepending to a Deque/Linked List for the result (or standard array reversal, which is practically optimal in many languages). |
A horizontal scanning laser moving top-down, but the output blocks are stacked from the bottom up. |
Maintain a queue. Pop nodes for current level. Instead of appending the level's array to the result, insert it at index 0 (or push to the front of a Deque). |
Draw the tree. As you process a level, draw its resulting array box underneath the previously processed level's array box, pushing older ones up. |
$O(N)$ node processing + $O(N)$ insertion/reversal overhead, resolving to $O(N)$ total time. |
Cross out nodes as they leave the queue. Draw arrows pointing to the *front* of the result list for every new level completed. |
$O(W)$ Queue memory + $O(N)$ Result array memory + temporary reversal memory. |
Visualize an $O(W)$ Queue and a Result Linked List/Deque where new nodes are dynamically stitched to the head pointer. |
| 108 |
Convert Sorted Array to Binary Search Tree |
Sequentially insert array elements into a new BST. This results in a completely skewed, linked-list-like $O(N)$ height tree. |
A straight diagonal line of nodes leaning entirely to the right, showing $O(N)$ height degradation. |
Draw the array. Draw an arrow from the first element to a root node, next element to its right child, next to its right child, forming a straight line. |
Divide and Conquer / DFS. Find mid, make root, recurse left half, recurse right half. |
A balanced scale. Finding the exact center of the array to balance the left and right weights perfectly at every recursive step. |
Pass `left` and `right` pointers. Calculate `mid = left + (right - left) / 2`. `nums[mid]` is root. `root.left = recurse(left, mid-1)`. `root.right = recurse(mid+1, right)`. |
Draw the array. Circle the middle element. Draw arrows from the left half to a left child placeholder, and right half to a right child placeholder. Repeat. |
A perfectly symmetrical, balanced recursion tree with exactly $O(\log N)$ depth. |
Draw the recursion tree. Count the levels to physically demonstrate that a balanced division always yields a logarithmic height. |
Call stack reaching $O(N)$ depth for the skewed sequential insertion. |
Visualize the call stack cleanly expanding and contracting to a maximum depth of strictly $O(\log N)$. |
| 109 |
Convert Sorted List to Binary Search Tree |
Iterate the Linked List to convert it to an Array $O(N)$, then apply the exact Divide and Conquer algorithm from Q108 $O(N)$. |
Two separate $O(N)$ sequential blocks: List-to-Array conversion, followed by Array-to-BST conversion. |
Draw the Linked List. Draw arrows transferring each node into a drawn Array box. Then draw the Divide and Conquer tree below it. |
Inorder Simulation (DFS). Calculate list length. Build left subtree, assign current list node as root, advance list pointer, build right subtree. |
A zipper closing. The tree is built from the bottom-left up to the root and down to the bottom-right exactly as the Linked List is traversed linearly. |
Get length `L`. `recurse(0, L-1)`. Build left child: `left = recurse(...)`. Create root from global list pointer. Advance list pointer. Build right: `right = recurse(...)`. |
Draw the Linked List. Draw the empty tree structure. Trace the Inorder traversal path, filling in the empty tree nodes strictly in the order of the Linked List. |
$O(N)$ time for processing every node exactly once during the Inorder build. Space is $O(\log N)$ for the balanced call stack. |
Draw a linear graph showing the global list pointer moving one step to the right precisely when a node is finalized in the recursive tree build. |
$O(N)$ extra Heap space explicitly allocated to store the intermediate Array structure. |
Visualize $O(\log N)$ Call Stack space. No extra heap memory is allocated; the tree nodes are built directly from the list's progression. |
| 110 |
Balanced Binary Tree |
Top-down DFS. For every single node, calculate the full height of its left and right subtrees. Leads to redundant $O(N^2)$ height calculations. |
An overlapping web of paths where the bottom nodes are visited and measured repeatedly for every ancestor above them. |
Draw a tree. Pick a leaf node. Draw multiple distinct lines overlapping it, representing every time an ancestor requested its height. |
Bottom-Up DFS. Return the height of the subtree if it is balanced. If it is ever unbalanced, return -1 immediately to short-circuit. |
A circuit breaker system. Heights bubble up from the leaves. If any left/right difference exceeds 1, a "-1" breaker trips and instantly cascades to the top. |
Recurse to leaves. Leaves return 0. At each parent: `left = dfs()`, `right = dfs()`. If `abs(left - right) > 1` or either is -1, return -1. Else `return max(left, right) + 1`. |
Draw the tree. Write heights next to nodes starting from the bottom. If a parent sees a difference > 1, write "-1" boldly and strike through the rest of the path up. |
A single $O(N)$ traversal where every node is visited strictly once and passes a constant-sized integer up the chain. |
Draw the recursion tree. Cross out each node permanently once its height is returned to its parent, proving no redundant visits. |
Deep $O(N)$ call stacks triggered repeatedly, wasting CPU cycles though not necessarily heavy static memory. |
Visualize the call stack reaching $O(H)$ depth, instantly collapsing and bubbling up a -1 error state the moment an imbalance is detected. |
| 111 |
Minimum Depth of Binary Tree |
Standard DFS traversing every single root-to-leaf path to find all depths, then taking the minimum at the end. |
Highlighting every path to the absolute bottom of a skewed tree, showing wasted $O(N)$ traversal. |
Draw a highly unbalanced tree. Trace lines all the way down the longest branches even after finding a short branch. |
BFS (Level Order Traversal) with an early exit on the first leaf node encountered. |
A radar sweeping outwards from the root in concentric circles. The sweep instantly stops upon hitting the first leaf. |
Queue nodes with their depth. Pop node. Is it a leaf (no left/right children)? Return its depth immediately. Else, queue children. |
Draw horizontal lines for levels. Stop drawing and circle the very first node you see that lacks children. Cross out the rest of the tree below it. |
A graph showing time complexity strictly bounded by the level of the shallowest leaf, practically $O(1)$ in highly skewed favorable cases, worst $O(N)$. |
Draw a line slicing horizontally through the tree at the minimum depth, proving all nodes below that line remain unvisited. |
$O(H)$ call stack frames blindly stacking up for every deep branch. |
Queue in heap memory expanding only as wide as the shallowest leaf's level before terminating, saving massive memory on deep trees. |
| 112 |
Path Sum |
DFS generating arrays of all complete root-to-leaf paths, summing each array, and checking against the target. |
Large memory blocks forming to hold every path array in memory simultaneously. |
Write out the complete sequence of numbers for every path as separate lists, then write a sum equation next to each. |
DFS (Pre-order) with target subtraction (passing `target - node.val` down the recursion). |
A fuel gauge depleting. The target is the starting fuel, and each node consumes its value. Reaching exactly 0 fuel at a leaf is a success. |
Subtract current node value from target. Check if current is a leaf AND target == 0. If yes, return true. Else, recurse left and right with new target. |
Write the starting target at the root. Cross it out, write `target - root.val`, and draw an arrow passing this new number down to children. |
A single $O(N)$ recursion tree showing nodes visited once, with boolean `true` short-circuiting upwards. |
Draw the tree. When a path hits 0 at a leaf, draw a thick "TRUE" arrow zipping straight back up to the root, ignoring remaining branches. |
$O(N\cdot H)$ heap allocations to dynamically create and store path arrays. |
$O(H)$ call stack strictly holding primitives (pointers and integers) with zero heap allocation overhead. |
| 113 |
Path Sum II |
Similar to 112, but instantiating a completely new list clone at every single node step to pass down to children. |
A fractal explosion of duplicated lists in memory, demonstrating $O(N^2)$ space complexity overhead. |
Draw a node, then physically draw two separate, fully copied lists representing the path state being handed to the left and right children. |
DFS with Backtracking. Maintain a single shared path list: `push` node, recurse, `pop` node. |
A breadcrumb trail being laid down and then carefully picked back up (backtracking) as the explorer retreats from a dead end. |
Push current node to global list. If leaf & sum matches, append a COPY of list to results. Recurse left/right. Pop current node from list before returning up. |
Draw a single list box. Write a value in it (push), draw a downward arrow. Erase the value (pop), draw an upward arrow. Repeat. |
$O(N)$ traversal time, but the result array copying adds time proportional to the number of valid paths. |
Draw the single state list dynamically resizing. Only draw a "clone" operation (O(H) work) specifically when a valid leaf is hit. |
Heap fragmentation visualized as dozens of garbage-collected intermediate lists. |
A single list in heap memory acting like a stack (expanding and shrinking), plus the $O(H)$ recursion stack tracking the exact current path. |
| 114 |
Flatten Binary Tree to Linked List |
Standard Pre-order traversal to collect all nodes into an $O(N)$ array, then a second pass to re-wire all the `right` pointers. |
Two completely disconnected sequential blocks: an $O(N)$ Read phase and an $O(N)$ Write phase. |
Draw the tree, draw an arrow pulling all nodes into a linear array box, then draw loops linking array elements back together. |
Reverse Post-order Traversal (Right, Left, Root) maintaining a global `prev` pointer. |
Building a chain from the end backwards. The tail is secured first, and each preceding node hooks onto it dynamically. |
Keep global `prev = null`. Traverse Right child, then Left child. Set current node's `right` to `prev`, `left` to null. Update `prev = current`. |
Draw the tree. Start at the bottom-right-most node. Draw an arrow from its `right` pointer to `prev` (initially null). Update `prev` to point to it. Move backwards. |
In-place $O(N)$ single-pass structural mutation with $O(H)$ recursive space. |
Draw the nodes. Instead of crossing them out, draw the right-pointers instantly snapping into their final flattened positions sequentially from tail to head. |
$O(N)$ external heap memory strictly allocated to buffer the nodes before rewiring. |
In-place pointer manipulation. Visualize the $O(H)$ call stack navigating the tree while the heap structures physically warp into a linked list. |
| 115 |
Distinct Subsequences |
Generate all possible subsequences of string `s` using recursion (Include/Exclude char), and check if they equal `t`. |
A massive, unmanageable $O(2^N)$ binary decision tree branching out for every character inclusion/exclusion. |
Write the string `s`. Draw a bifurcating tree where each level represents taking or dropping the next character. It quickly runs off the page. |
2D Dynamic Programming (Bottom-Up Tabulation). |
A grid where previously calculated subsequence matches are pushed forward and accumulated to build larger matching patterns. |
`dp[i][j]` = matches of `t[0..j]` in `s[0..i]`. If `s[i] == t[j]`, `dp[i][j] = dp[i-1][j-1] (use char) + dp[i-1][j] (ignore char)`. Else, `dp[i][j] = dp[i-1][j]`. |
Draw a 2D matrix. `s` on rows, `t` on cols. Fill base cases (empty `t` = 1). Fill row by row, carrying values from the top and top-left cells. |
A perfectly structured $O(S \cdot T)$ grid filling sequentially, eliminating all redundant calculations. |
Draw the DP matrix. Highlight a cell, draw arrows pointing to it strictly from the cell directly above it and the cell diagonally top-left to show $O(1)$ transitions. |
$O(2^N)$ deep recursive call stack eventually leading to StackOverflow or Time Limit Exceeded. |
$O(S \cdot T)$ contiguous memory block for the 2D array. (Pro level: visualize it collapsing into a 1D $O(T)$ array for ultimate space optimization). |
| 116 |
Populating Next Right Pointers in Each Node |
Standard Level Order Traversal (BFS) using a Queue to link nodes level by level. |
A wide queue structure ballooning to hold N/2 nodes at the bottom level, showing $O(N)$ space. |
Draw a perfect binary tree. Draw a large box beside it (the queue). Cross out nodes as they enter and exit the queue, drawing arrows between them. |
Level-by-Level Linked List Traversal (using existing `next` pointers to traverse horizontally). |
A spider weaving a web. The spider crawls across the current level using `next` pointers while simultaneously spinning the thread connecting the level below. |
Start at root. While `left` exists: traverse current level via `next`. Link `curr.left.next = curr.right`. If `curr.next`, link `curr.right.next = curr.next.left`. Move `curr` to `curr.next`. |
Draw a tree. Use your finger to trace horizontally across level L. As your finger moves, draw straight dashed lines connecting the children on level L+1. |
$O(N)$ time with $O(1)$ space. A strictly horizontal scan that requires zero secondary data structures. |
Highlight the horizontal `next` pointers in a bright color to show that the tree itself has become the traversal mechanism. |
Visualize an $O(N)$ Queue actively allocating heap memory to store half the tree at once. |
Visualize purely in-place pointer manipulation. Memory stays flat at $O(1)$ constant space (ignoring recursive stack if done recursively, but iterative is truly $O(1)$). |
| 117 |
Populating Next Right Pointers in Each Node II |
Standard BFS with a Queue, identical to Q116, indiscriminately buffering all nodes at each level regardless of missing children. |
A standard BFS linear graph masking the structural gaps, using $O(N)$ memory to compensate. |
Draw an imperfect tree. Draw the Queue explicitly filling up with valid nodes to bridge the gaps across empty spaces. |
Linked List Traversal with a Dummy Head (tracking the start of the next level). |
A train track builder. A dummy engine sits at the start of the next level, hooking up carriages (nodes) as they are discovered from the level above. |
Maintain `dummy` and `tail` pointers for the next level. Traverse current level via `next`. If child exists, `tail.next = child; tail = tail.next`. When current level ends, move down to `dummy.next`. |
Draw the tree. Draw a "Dummy" circle on the left of an empty level. As you scan the level above, draw arrows from the dummy chain to the found children. |
$O(N)$ time and $O(1)$ space. The dummy node elegantly absorbs the complexity of missing branches without extra arrays. |
Draw the dummy node resetting its position to the far left at the start of every new depth phase, creating a perfectly localized $O(1)$ memory footprint. |
$O(W)$ Queue memory where W is the maximum width of the imperfect tree. |
A single Dummy Node and a Tail Pointer continuously reusing the same $O(1)$ memory space for every level. |
| 118 |
Pascal's Triangle |
Calculate the mathematical combination formula (nCr) using factorials for every single cell independently. |
An $O(N^3)$ explosion of redundant factorial calculations overlapping wildly for the center elements. |
Write out the full factorial expansion `n! / (r! * (n-r)!)` for a cell in row 5, showing the massive redundant arithmetic. |
Dynamic Programming (Tabulation). Building the current row iteratively from the directly previous row. |
Falling sand accumulating. Each block rests perfectly on the shoulders of the two blocks directly beneath it in the previous layer. |
Initialize a nested list. First row `[1]`. For row `i`: create array of size `i+1`, set ends to 1. For middle elements, `curr[j] = prev[j-1] + prev[j]`. |
Draw a staggered grid. Fill the edges with 1s. To fill an empty cell, draw two V-shaped arrows coming from the top-left and top-right cells, adding them together. |
$O(N^2)$ grid filling exactly one time per cell, representing the absolute minimum work required to generate the shape. |
Draw the triangle. Cross out each cell with a single slash as you calculate its sum, proving each of the N^2/2 cells is touched exactly once. |
Call stacks overflowing or massive integer overflows calculating factorials. |
An expanding array of arrays in heap memory, perfectly matching the physical geometry of the $O(N^2)$ triangle. |
| 119 |
Pascal's Triangle II |
Generate the entire Pascal's Triangle up to row `k` using the $O(N^2)$ space method from Q118, then just return the last row. |
A massive 2D pyramid built in memory just to extract the final base layer, wasting $O(k^2)$ space. |
Draw the full triangle. Box the final row. Erase the rest of the triangle to illustrate the wasted computation and memory. |
1D Dynamic Programming (Rolling Array) calculated strictly from right-to-left. |
A single row of blocks magically morphing its values in place to become the next row without needing a second canvas. |
Initialize array of size `k+1` with 1s. Loop rows 1 to `k`. Inner loop from `j = row_index - 1` down to 1: `arr[j] = arr[j] + arr[j-1]`. |
Draw a single 1D array. Update the values strictly from right to left using the old left value and the current value. Show how left-to-right overwrites data prematurely. |
$O(k^2)$ time with strictly $O(k)$ space. The in-place mutation graph loops back onto itself. |
Draw a single row of boxes. Draw curved arrows looping out of a box and back into itself, adding the neighbor's value, completing the $O(k)$ space proof. |
$O(k^2)$ full 2D array matrix allocated in heap. |
Visualize a single 1D $O(k)$ array constantly overwriting its own values backwards, maintaining an ultra-lean memory profile. |
| 120 |
Triangle |
Top-Down DFS recursion to explicitly explore every possible path from the top point to the bottom base, summing along the way. |
A sprawling $O(2^N)$ binary decision tree where middle paths overlap and duplicate calculations catastrophically. |
Draw the triangle. Trace a path down. Trace another. Show how the middle nodes are crossed out multiple times by different recursive branches. |
Bottom-Up Dynamic Programming (In-place or rolling 1D array). |
Water flowing uphill. Starting at the wide base, the minimum path values merge and flow upwards until they pool at the single top point. |
Start at the second-to-last row. For each cell `(i, j)`, add the minimum of its two children `(i+1, j)` and `(i+1, j+1)`. Propagate up to `(0, 0)`. |
Draw the triangle. Start at the bottom row. Move up one row. For each cell, look at the two cells directly below it, pick the smaller, and add it to the current cell. Cross out the bottom row. |
$O(N^2)$ time processing exactly matching the number of cells in the grid. |
Draw the triangle. Draw upwards-pointing V's merging the optimal choices layer by layer, squeezing the $O(N^2)$ state space up to a single $O(1)$ answer. |
$O(2^N)$ deep, redundant recursive call stacks dominating memory alongside the triangle data. |
$O(1)$ auxiliary space if mutating the input triangle in-place, or $O(N)$ heap space using a rolling 1D DP array for the base. |
| 121 |
Best Time to Buy and Sell Stock |
Nested loops comparing every single pair of days (i, j) where j > i to find the maximum price difference. |
A 2D upper-triangular coordinate grid showing $O(N²)$ comparisons. |
Draw a timeline. For day 1, draw arrows to all subsequent days. For day 2, do the same. Show the density of arrows increasing. |
One-pass Greedy / Kadane’s-like Sliding Window. |
A moving "low-water mark" tracking the deepest valley while a scanner looks for the highest peak relative to that valley. |
Initialize min_price as infinity and max_profit as 0. Traverse once: update min_price, then update max_profit based on current - min_price. |
Draw a line graph of prices. As you move left to right, keep a dotted horizontal line at the lowest point seen so far. Measure the vertical gap to the current point. |
A single linear horizontal scan line crossing through the price graph. |
Draw the array. Draw a single arrow moving from index 0 to N-1, never looking back, proving $O(N)$. |
Minimal memory, but the $O(N²)$ time complexity is the primary bottleneck visualized by redundant operations. |
Visualize two tiny registers in memory: min_p and max_p, updating in-place. $O(1)$ space. |
| 122 |
Best Time to Buy and Sell Stock II |
Recursion to explore every possible combination of buying, selling, or holding on every single day. |
A massive branching decision tree with $O(2^N)$ states. |
Draw a decision tree: "Day 1: Buy or Skip?", "Day 2: Sell, Hold, or Skip?". Show it exploding exponentially. |
Greedy Algorithm (Summing Positive Slopes). |
A mountain climber collecting only the upward inclines. If tomorrow is higher than today, take the profit immediately. |
Traverse prices from index 1. If prices[i] > prices[i-1], add the difference to total profit. |
Draw a price graph. Circle every upward-sloping line segment. Draw "+" signs over them and a total sum box at the end. |
Linear scan with no nested dependencies. |
Draw the array. Draw a single pass. Highlight only the adjacent pairs where the second element is larger. $O(N)$ time. |
$O(2^N)$ recursive call stack frames leading to total system exhaustion. |
A single $O(1)$ accumulator variable updating as you step through the list. |
| 123 |
Best Time to Buy and Sell Stock III |
Split the array at every index i. Solve Q121 for the left side and Q121 for the right side. Return the max sum of both. |
$O(N²)$ complexity: an $O(N)$ split-loop calling two $O(N)$ sub-operations. |
Draw an array. Draw a vertical line moving through it. Show how for every position of the line, you re-scan the entire left and right halves. |
Dynamic Programming (4-state variables) or Prefix/Suffix Profit Arrays. |
Two waves meeting in the middle. One wave calculates max profit from the left, another from the right. |
Track four variables: buy1, sell1, buy2, sell2. Update them sequentially to find the max profit with at most 2 trades. |
Draw a 2xN grid or two 1D arrays (Left-to-Right max profit and Right-to-Left max profit). Sum them up to find the peak. |
Two separate $O(N)$ linear passes. |
Draw two horizontal arrows: one starting from index 0, one from index N-1. They pass each other once. $O(N)$ total. |
Standard $O(N)$ temporary space for prefix/suffix profit arrays. |
Visualize 4 static registers in heap/stack memory if using the 4-variable state approach (O(1) space optimization). |
| 124 |
Binary Tree Maximum Path Sum |
For every node in the tree, find the max path that *ends* at that node, then try to join them to form the max path *through* that node. |
$O(N²)$ or $O(N \log N)$ overlapping height/path calculations for every subtree root. |
Draw a tree. For every node, draw all possible paths that could pass through it. Show the messy overlaps. |
Bottom-Up DFS (Post-order Traversal) with a Global Max tracker. |
A "heartbeat" monitor. Each node calculates its best "branch" to offer its parent, while secretly checking if the path *through* itself beats the global record. |
Recurse to leaves. A node returns node.val + max(left_gain, right_gain, 0). Inside the function, update global_max with node.val + left_gain + right_gain. |
Draw a tree. Write the "contribution" value (best path up) next to each node. Use a "Global Max" box in the corner to update as you see bigger combined paths. |
$O(N)$ single-pass traversal. Every node is visited once and its values are processed in constant time. |
Trace the post-order path (left, right, root). Cross out nodes as they return their single integer value to their parent. |
Multiple redundant recursive stacks or deep path-list storage. |
Visualize the $O(H)$ call stack where each frame only stores one or two integer variables and the return value. |
| 125 |
Valid Palindrome |
Clean the string (remove non-alphanumeric), reverse the cleaned string, and compare if cleaned == reversed. |
A three-pass approach: $O(N)$ Filter + $O(N)$ Reverse + $O(N)$ Compare. |
Write the string. Draw a second string below it. Draw arrows flipping the letters, then draw vertical lines comparing them. |
Two-Pointer Technique (Meeting in the center). |
Two pinchers closing in from both ends of the string, ignoring the "noise" (spaces/symbols) automatically. |
Left pointer at 0, Right at N-1. While Left < Right: skip non-alphanumeric. Compare chars. If mismatch, return false. Else, increment/decrement. |
Draw the string. Place a 'L' finger on the first letter and a 'R' finger on the last. Move them inward, skipping symbols until they point at letters. |
A single $O(N)$ pass where the total distance covered by both pointers equals the length of the string. |
Draw the string. Draw two arrows pointing inward. Mark each character with a small dot as it is "validated" by a pointer. |
$O(N)$ space to store the new cleaned and reversed string copies. |
Visualize zero extra heap memory. The pointers exist in $O(1)$ stack space and operate directly on the original input. |
| 126 |
Word Ladder II |
DFS to find all possible transformation paths from start to end, checking for the shortest length at the end. |
An exponential $O(N^L)$ decision tree where every word choice branches into N other words. |
Draw the start word. Draw arrows to every word in the dictionary that differs by one letter. Repeat until you hit the end. Show the chaos. |
BFS (to find shortest distances) + DFS/Backtracking (to reconstruct paths). |
A two-stage engine. BFS maps the terrain (distances), and DFS follows the map backward to find all "ideal" routes. |
Run BFS once to store the distance of each word from the start. Then, use DFS to find paths where each step W moves to a word V such that dist(V) = dist(W) + 1. |
Draw a level-order graph. Label each word with its level (0, 1, 2...). Only draw arrows that move from level k to k+1. |
$O(N \cdot 26 \cdot L + \text{paths})$ complexity showing localized work per word. |
Draw the graph once. Circle the shortest path segments and highlight the "backtracking" arrows that don't satisfy the level-up rule. |
Visualize millions of redundant path strings clogging the heap. |
Visualize an adjacency list (Graph) and a single Map (Distances) occupying $O(N \cdot L)$ space. |
| 127 |
Word Ladder |
BFS, but for every word, iterate through the entire dictionary of size N to find words with a 1-character difference. |
An $O(N^2 \cdot L)$ grid showing every word being compared to every other word redundantly. |
Draw a column of words. Draw lines from the top word to every other word below it to check for differences. Move to the next word. |
BFS with Character Mutation (a to z). |
A ripple in a pond. The start word "pulses" and changes each of its letters one-by-one, only "hooking" words that actually exist in the set. |
Queue the start word. For each char in current word, replace it with a..z. If the new word is in the Set, enqueue it and remove from Set. |
Draw the start word. Draw 26 small tick marks for the first letter. Circle only the tick marks that match a real word. Repeat. |
$O(N \cdot 26 \cdot L)$ linear sweep through the dictionary space. |
Draw a line representing the dictionary. Draw a focused laser beam moving from start to end, skipping all non-adjacent words. |
$O(N^2)$ comparison matrix storage (conceptual). |
A Hash Set in heap memory providing $O(1)$ lookups, drastically reducing search space. |
| 128 |
Longest Consecutive Sequence |
Sort the array and scan for the longest consecutive run of numbers. |
A sorting tree (like Merge Sort) showing $O(N \log N)$ overhead before the linear scan even starts. |
Draw the unsorted array. Draw the sorted array below it. Draw a single arrow scanning the sorted array to find sequences. |
Hash Set (Intelligent Starting Points). |
A series of islands. You only start building a bridge if there is no land immediately to your left. |
Add all numbers to a Set. For each X: if X-1 is NOT in the set, it's the start. Count X+1, X+2... until the run ends. |
Draw a number line. Circle the numbers you have. Put a "Start Here" flag only on the left-most number of each clustered island. |
$O(N)$ time. Each number is visited exactly twice (once to check if it's a start, once as part of a run). |
Draw the array. Draw a dot above each number. Draw a second dot only when that number is part of a "counting" sequence. No number has 3 dots. |
$O(N \log N)$ stack space for sorting algorithms like QuickSort. |
Visualize a Hash Set (Hash Map structure) taking up $O(N)$ heap space to facilitate instant lookups. |
| 129 |
Sum Root to Leaf Numbers |
DFS to find all paths. Store paths as strings (e.g., "123"). Convert strings to integers and sum them. |
Strings being concatenated and converted, adding $O(H)$ overhead to every path found. |
Draw the tree. Beside each leaf, write out the full string path, then draw a "plus" sign between them. |
DFS with Arithmetic Accumulation. |
A growing snowball. As you roll down the tree, the number shifts left (multiplies by 10) and adds the current node's value. |
Pass a `currentSum` to the child. `newSum = currentSum * 10 + node.val`. If leaf, return `newSum`. Else return `left_sum + right_sum`. |
Draw the tree. Write the running number *inside* each node as you go down (e.g., root is 1, left child is 12, its child is 123). |
$O(N)$ single-pass traversal where each node is visited once and its value is updated in constant time. |
Draw a standard DFS path. Cross out each node once it passes its accumulated integer to its parent. |
A pool of temporary string objects being created and destroyed in memory. |
Visualize a single integer being passed down the call stack frames $O(H)$. Zero heap allocation for paths. |
| 130 |
Surrounded Regions |
For every 'O' in the grid, run a DFS to check if it can reach the boundary. If not, flip it to 'X'. |
$O(M \cdot N \cdot (M+N)$) overlapping searches. Every interior 'O' might re-explore the whole board. |
Draw a grid. For an 'O' in the middle, draw search paths in all 4 directions. Repeat for the 'O' next to it. Show the overlap. |
Border-to-Interior DFS (Inverse Flood Fill). |
A firewall. Only 'O's connected to the borders are "safe." We mark the safe ones first, then flip everyone else. |
Iterate only border cells. If 'O', run DFS to mark all reachable 'O's as 'Safe' (or 'S'). Finally, scan grid: 'S' becomes 'O', everything else becomes 'X'. |
Draw the grid. Use a highlighter to "color in" every 'O' that touches the edge, and any 'O' touching those. Any 'O' without color gets turned into an 'X'. |
$O(M \cdot N)$ time. Each cell is visited at most twice. |
Draw the grid. Draw arrows starting only from the 4 edges and moving inward. No arrows originate from the center. |
Deep recursive stacks for every single cell search. |
Visualize the call stack depth limited to the total number of 'O's, with no redundant exploration. |
| 131 |
Palindrome Partitioning |
Generate every possible combination of substrings (partition points) and check if every substring in the partition is a palindrome. |
A massive $O(N \cdot 2^N)$ binary tree where every gap between characters is a "split" or "don't split" decision. |
Write the string. For every character gap, draw a fork. One branch is "Cut", one is "No Cut". Show the resulting 2^N leaf nodes. |
Backtracking with DP/Memoization (pre-checking palindromes). |
A pruning shears visualization. The recursion tree grows, but any branch that creates a non-palindrome is "snipped" immediately. |
Start at index 0. Try all possible end-indices i. If `s[0:i]` is a palindrome, recursively solve for `s[i+1:]`. If it hits the end, record the path. |
Draw a decision tree. On each arrow, write the substring chosen. If it's a palindrome, draw a green check; if not, draw a red X and stop that branch. |
A depth-first traversal of a pruned state space, bounded by $O(N \cdot 2^N)$ in the worst case but significantly faster in practice. |
Draw the recursion tree. For each node, draw a small horizontal bar representing the $O(N)$ palindrome check overhead. |
Visualise thousands of intermediate string slices $O(N^2)$ cluttering the heap. |
Visualize a single 2D $O(N^2)$ boolean matrix `isPalindrome[i][j]` that prevents redundant character comparisons. |
| 132 |
Palindrome Partitioning II |
Solve Q131 to find all valid partitions and then iterate through them to find the one with the minimum number of cuts. |
Exponential $O(2^N)$ results being buffered and then compared, showing massive computational waste. |
Draw all valid partitions from Q131 as separate rows. Count the commas (cuts) in each row and circle the smallest number. |
1D Dynamic Programming with 2D Palindrome Pre-processing. |
A "best-so-far" runner. A 1D array `dp[i]` stores the minimum cuts needed for the prefix `s[0..i]`. |
Iterate i from 0 to N. For each i, check all j <= i. If `s[j..i]` is a palindrome, `dp[i] = min(dp[i], dp[j-1] + 1)`. |
Draw the 1D DP array. For a cell `dp[i]`, draw several "look-back" arrows to previous cells j where a palindrome was found, picking the minimum. |
$O(N^2)$ grid filling. Every pair (i, j) is considered once for the palindrome property and once for the cut update. |
Draw a square N x N grid. Color it in row-by-row to show that exactly N^2 work-units are performed. |
Storage of 2^N lists of strings in memory. |
Two arrays: a 1D DP array $O(N)$ and a 2D boolean matrix $O(N^2)$ for palindrome lookups. |
| 133 |
Clone Graph |
Attempt to deep-copy nodes recursively without tracking visited nodes, leading to infinite loops in cyclic graphs. |
A spiral arrow that loops infinitely within a circle of three nodes, never reaching a termination state. |
Draw three circles in a triangle. Draw arrows connecting them. Trace your pen around the circle 10 times to show the infinite loop. |
DFS/BFS with a Hash Map (Mapping Original Nodes to Cloned Nodes). |
A parallel universe construction. As you step into a room in the "Original" graph, you build a "Clone" room and link it to the Map. |
Start at the root. If the node is in the Map, return the clone. Else, create a clone, put it in the Map, and recursively clone all neighbors. |
Draw the Original graph on the left and an empty space on the right. Draw a "Map" table in the middle. As you touch an Original node, draw the Clone and update the Map. |
$O(V + E)$ linear traversal where every node and every edge is visited and processed exactly once. |
Draw the graph. Mark each node with a '1' as it's visited and a '2' as its neighbors are finished, proving no redundant work. |
StackOverflow errors as the recursion depth exceeds memory limits due to cycles. |
Visualize a Hash Map in heap memory holding V pointers, alongside the recursion stack $O(V)$. |
| 134 |
Gas Station |
Start at every single station i and simulate the full circle. If you run out of gas at any point, reset and try station i+1. |
$O(N^2)$ simulation. For every station, you potentially visit every other station. |
Draw a circle of stations. Start at 1, draw an arrow to 2, 3... then an 'X'. Start at 2, draw to 3, 4... then an 'X'. Repeat N times. |
Greedy One-Pass (The Total Net Gain Rule). |
A mountain range of fuel levels. If the total height at the end is >= 0, a solution exists. The starting point is the station immediately after the deepest valley. |
Track `total_surplus` and `current_surplus`. If `current_surplus` < 0, reset start point to `i + 1` and reset `current_surplus = 0`. If `total_surplus` < 0 at end, return -1. |
Draw a line graph of the running fuel balance. Identify the lowest point (the "trough"). Draw a flag on the very next station to show the optimal start. |
A single $O(N)$ linear pass through the array. |
Draw the array. Draw a single arrow moving left to right once, never resetting to a previous index. |
Redundant state variables being re-initialized N times in the $O(N^2)$ loop. |
Three single integer variables in $O(1)$ stack space: `total`, `current`, and `start_index`. |
| 135 |
Candy |
Start all children with 1 candy. Repeatedly loop through the array and update a child's candy if they have a higher rating than a neighbor but fewer candies. Repeat until stable. |
A "bubble-sort" style $O(N^2)$ ripple effect where candy updates slowly propagate across the array. |
Draw a row of numbers. Change one, then check neighbors. Change neighbor, check their neighbors. Show how a change at index 10 might eventually force a change at index 1. |
Two-Pass Greedy (Left-to-Right and Right-to-Left). |
Two tectonic plates sliding past each other. The first pass ensures everyone is happier than their left neighbor; the second ensures they are happier than their right. |
Pass 1: if `ratings[i] > ratings[i-1]`, `candy[i] = candy[i-1] + 1`. Pass 2 (backwards): if `ratings[i] > ratings[i+1]`, `candy[i] = max(candy[i], candy[i+1] + 1)`. |
Draw the ratings. Draw the candy counts after the first pass. Draw a second row of candy counts after the backward pass, taking the max of the two states. |
Exactly 2 x $O(N)$ linear scans. |
Draw two horizontal arrows: one pointing right, one pointing left. Show that they never overlap or conflict, resulting in $O(N)$. |
Multiple full-array copies if not careful with the iterative updates. |
A single $O(N)$ integer array in heap memory to store the final candy counts. |
| 136 |
Single Number |
Iterate through the array; for each element, scan the rest of the array to see if a duplicate exists. |
Nested loops comparison grid (N x N) showing $O(N^2)$ checks. |
Draw an array. For index 0, draw arrows to all other indices. For index 1, repeat. Show the density of arrows. |
Bit Manipulation (XOR). |
A "Cancellation Field." Identical values collide and vanish, leaving only the unique value standing. |
Initialize result = 0. XOR every number. Since a oplus a = 0 and a oplus 0 = a, duplicates cancel. |
Write numbers in binary. Line them up. Cross out pairs of identical bit columns to show they result in 0. Circle the remaining bits. |
Linear $O(N)$ timeline where each element is "processed" by a single XOR gate. |
Draw a single horizontal line through the array. Mark each box with a oplus symbol to prove a single pass. |
Visualizing a "Seen" list growing to $O(N)$ in a Set-based brute force. |
A single 32-bit register (the result variable) in $O(1)$ stack memory. |
| 137 |
Single Number II |
Use a Hash Map to store the frequency of every number, then iterate through the map to find the key with value 1. |
A dual-structure map showing N keys and N values, illustrating $O(N)$ space overhead. |
Draw the array and a T-account table (Key | Count). Fill it row by row until the table is as long as the array. |
Bit Manipulation (Modulo 3 Summing). |
A vertical 32-slot sorter. Each slot counts how many times a '1' appears at that bit position across all numbers. |
For each bit position (0 to 31): sum the bits of all numbers at that position. sum % 3 gives the bit of the result. |
Draw a 32-row vertical stack. For each number, put a mark in the rows corresponding to its '1' bits. Write the total count next to each row. |
$O(32 \cdot N)$ which simplifies to $O(N)$. A grid of constant height (32) and width N. |
Draw a rectangle with a fixed height of 32 and a width of N. Color the interior to show total operations. |
A Hash Map ballooning in heap memory to hold every unique number. |
32 integer counters (or 2 bit-masks for the "Two-bit counter" approach) in $O(1)$ space. |
| 138 |
Copy List with Random Pointer |
Two passes: First pass creates a Map of (Old Node rightarrow New Node). Second pass sets next and random pointers using the Map. |
A bridging diagram showing N pointers connecting the "Old" world to the "New" world via a Map. |
Draw the original list. Draw a Map table. Draw the new list. Draw arrows going from Old rightarrow Map rightarrow New. |
Interweaving Nodes (In-place). |
A DNA double-helix being replicated. Each "base" (original node) creates a copy of itself and attaches to it locally. |
1. Insert copies between original nodes. 2. Copy random pointers: curr.next.random = curr.random.next. 3. Separate the lists. |
Draw the list. Draw a new node right next to each old node. Draw a "jump" arrow from an old node's random to the target's *adjacent* copy. |
Three sequential $O(N)$ passes over the modified list structure. |
Draw a single long list. Draw three horizontal arrows, each covering the whole length once, showing $O(N)$ time. |
$O(N)$ auxiliary space consumed by the Hash Map entries. |
Visualize $O(1)$ extra space (excluding the output list) because pointers are manipulated locally. |
| 139 |
Word Break |
Recursion with backtracking: Try every possible prefix of the string; if it's in the dictionary, recurse on the remainder. |
An $O(2^N)$ recursion tree where strings are repeatedly sliced, showing massive overlapping subproblems. |
Draw the string. Branch out for every word match found at the start. Show branches overlapping on the same substrings. |
1D Dynamic Programming (Tabulation). |
A bridge-building simulation. Each index in the string is a gap; a word is a plank. You can cross if a plank connects to a previous "reachable" spot. |
dp[i] is true if s[0:i] can be broken. For each i, check all j < i. If dp[j] is true and s[j:i] is in the dictionary, dp[i] = true. |
Draw the string and a boolean array below it. For a cell dp[i], draw arrows "looking back" to previous 'True' indices to find matching words. |
$O(N^2)$ grid filling where each of N indices checks up to N previous indices. |
Draw an N x N triangle. Shade it in to show the quadratic work performed during look-backs. |
Exploding call stack and multiple temporary string slices in heap memory. |
A single boolean array of size N+1 in $O(N)$ space. |
| 140 |
Word Break II |
Standard recursion to find all paths, generating all valid sentences without any result caching. |
A fractal-like $O(2^N)$ tree where many branches return identical results, recalculating everything. |
Draw the recursion tree. Circle identical sub-calls (e.g., "catsanddog" calling "dog" twice) to show wasted work. |
Backtracking + Memoization (Top-Down DP). |
A shared result library. Once a substring's valid partitions are found, they are stored in a catalog for any future branch to use. |
Recursive function returns a List of strings. Use a Map to store substring -> list_of_sentences. Check map before recursing. |
Draw a "Memo" table. As the recursion completes a branch, write the result list into the table. Draw arrows from future branches directly to that table entry. |
Complexity depends on the number of results, but the state-space visit is $O(N^2)$ while results could be exponential. |
Draw a graph where nodes are indices. Show that each node's result is computed once and reused by multiple parents. |
A massive recursion stack with no reuse, leading to redundant list allocations. |
Visualize the Hash Map storing lists of strings. Memory scales with the total length of all possible valid sentences. |
| 141 |
Linked List Cycle |
Use a Hash Set to store every node's reference. If a node is encountered that is already in the set, a cycle exists. |
A growing storage bucket (Set) filling up alongside the list traversal, showing $O(N)$ space. |
Draw a list. Draw a separate "Checklist" box. For every node you visit, draw an 'X' in the box. If you ever point to a node that already has an 'X', you're done. |
Floyd’s Cycle-Finding Algorithm (Tortoise and Hare). |
A race track. Two runners move at different speeds; the faster runner will eventually lap the slower runner if the track is a loop. |
Pointer `slow` moves 1 step. Pointer `fast` moves 2 steps. If `slow == fast`, return true. If `fast` hits null, return false. |
Draw a list with a loop. Place an 'S' and an 'F' at the start. Move 'S' one node and 'F' two nodes. Repeat until they occupy the same node. |
Linear $O(N)$ timeline. Even in a cycle, the gap between pointers closes by 1 each step, bounded by the list length. |
Draw a single line. Mark it once. Since no extra storage is created, the "work area" is just the line itself. |
Visualize a Hash Set in heap memory ballooning to store N memory addresses. |
Visualize two single pointers (64-bit variables) in $O(1)$ stack memory. No heap usage. |
| 142 |
Linked List Cycle II |
Store nodes in a Hash Map (Node rightarrow Index). The first node you see twice is the start of the cycle. |
A dictionary mapping showing N pairs of references and integers. |
Draw the list. Write the node's address and its position in a table. When you hit a duplicate address, circle the table entry. |
Two-Pointer Meeting Point + Distance Logic. |
A synchronization of two clocks. The distance from the head to the entry is equal to the distance from the meeting point to the entry. |
1. Find meeting point with Tortoise/Hare. 2. Place a new pointer at the head. 3. Move both (head-pointer and meeting-pointer) 1 step at a time; they meet at the entry. |
Draw the loop. Mark the meeting point 'M'. Draw an arrow from 'Head' and 'M' moving at the same speed. Mark the junction where they collide. |
$O(N)$ time. Two linear passes (one to find the cycle, one to find the junction). |
Draw a line that loops. Trace the pointers. Note that you traverse the "non-cycle" part twice at most. |
A Hash Map occupying $O(N)$ heap space to store node pointers. |
Pure $O(1)$ stack memory. No additional data structures; only pointer variables are used. |
| 143 |
Reorder List |
Copy all nodes into an array/list. Use two pointers on the array (start and end) to reconstruct the list by re-assigning next pointers. |
An $O(N)$ array buffer sitting parallel to the original list. |
Draw the list. Draw an array below it and copy the node values. Draw arrows from array index 0 to index N, then index N to index 1, etc. |
Find Middle + Reverse Second Half + Interweave. |
A deck of cards being split in half, the second half flipped, and then a "riffle shuffle" performed. |
1. Find mid (slow/fast). 2. Reverse list from mid.next. 3. Merge two halves (Node1 rightarrow NodeN rightarrow Node2 rightarrow NodeN-1...). |
Draw the list. Draw a line through the middle. Draw arrows reversing the second half. Then draw zigzag lines connecting nodes from the first and second sections. |
$O(N)$ time across three distinct linear phases (Find, Reverse, Merge). |
Draw the list as three segments. Show that each segment is processed once, resulting in 3 x $O(N)$ approx $O(N)$. |
An auxiliary array or list in heap memory taking $O(N)$ space. |
Visualize $O(1)$ auxiliary space. The pointers are re-wired in place; only a few temporary variables exist in the stack. |
| 144 |
Binary Tree Preorder Traversal |
Recursive DFS (Root, Left, Right). |
A recursion tree showing the call stack depth $O(H)$. |
Draw the tree. Draw a "Stack" box. For every node, write its value, then "call" its left, then its right. Show the frames stacking up. |
Iterative Traversal with a Stack. |
A "To-Do" list. You process the current node immediately, but you write down the "Right" child to remember for later before moving "Left." |
Push Root to Stack. While stack not empty: Pop node, add to result, Push Right child (if exists), then Push Left child (if exists). |
Draw the tree. Draw a vertical stack box. Put 'Root' in. Take it out, put its 'Right' then 'Left' in. Repeat. Order in result: 1, 2, 3... |
$O(N)$ time as every node is pushed and popped exactly once. Space is $O(H)$ for the stack. |
Draw the tree and cross out each node with one slash. The work is perfectly proportional to the number of nodes. |
Implicit system call stack memory used by recursion. |
Explicit stack in heap/stack memory, making the memory usage visible and manageable. |
| 145 |
Binary Tree Postorder Traversal |
Recursive DFS (Left, Right, Root). |
A "bottom-up" recursion graph where parents wait for both children to finish. |
Draw the tree. Draw arrows going down to leaves, then values "returning" up to the parent. The parent is the last to be recorded. |
Iterative Traversal using Two Stacks (or One Stack + Reverse). |
A "Reverse Preorder" (Root, Right, Left) which is then flipped backward to get (Left, Right, Root). |
Push Root to Stack1. While Stack1 not empty: Pop node, Push to Stack2. Push Left to Stack1, then Push Right to Stack1. Finally, pop all from Stack2. |
Draw two stack boxes. Move items from S1 to S2 in (Root-Right-Left) order. Draw the result of popping S2 to see the (Left-Right-Root) order. |
$O(N)$ time. Every node is moved between stacks in constant time. |
Draw the tree. Use two different colored pens: one for the "visit" order and one for the "result" order. |
Recursive call stack storage of $O(H)$ depth. |
Two stacks in memory, effectively doubling the space constant but remaining $O(H)$ in complexity. |
| 146 |
LRU Cache |
Use a standard array or list to store keys. For every get or put, perform a linear search to find/move the key. |
An $O(N)$ linear scan for every single operation, showing a slow search bar moving through a list. |
Draw a horizontal list. For every 'get', draw a finger moving from the first element to the last until the key is found. |
Hash Map + Doubly Linked List (DLL). |
An "Organized Library." The Hash Map is the index (tells you where the book is), and the DLL is the shelf (tracks which book was touched last). |
Search in Map for node address (O(1)). Move that node to the 'Head' of the DLL. If capacity exceeded, delete the 'Tail'. |
Draw a Map (Key rightarrow Node) and a DLL. When a key is accessed, draw an arrow moving that specific node to the front of the line. |
$O(1)$ constant time across all operations. A flat horizontal line on a graph. |
Draw a single dot. No matter how big the cache gets, the work to find or move an item is just one "hop." |
Visualise a single Array buffering elements, which is memory-efficient but time-intensive. |
Visualize a Map and a DLL together. Each key exists in both, using $O(\text{Capacity})$ space in heap memory. |
| 147 |
Insertion Sort List |
For every node, scan the entire sorted portion of the list from the very beginning to find the correct insertion spot. |
A nested loop visualization where the "inner" search length grows linearly with the outer loop (O(N^2)). |
Draw the list. For the 4th node, draw 3 separate arrows back to nodes 1, 2, and 3 to find its place. Repeat for the 5th node. |
Insertion Sort with Dummy Head and Predecessor Pointers. |
A "Sorting Rail." A dummy node acts as the start of the rail where nodes are slotted in one by one. |
Keep a sorted tail pointer. If the next node is smaller, search from the dummy head to find the insertion point and rewire pointers. |
Draw a 'Sorted' section and an 'Unsorted' section. Use a dashed line. Move nodes one by one across the line, drawing the new 'next' arrows. |
$O(N^2)$ time but $O(1)$ space. The area of a triangle (1+2+3...+N). |
Draw a lower-triangular matrix. Each filled cell represents a comparison made during the sorting process. |
An auxiliary array used to sort values before rebuilding the list (O(N) space). |
In-place pointer manipulation. Visualize the same nodes simply changing their "next" addresses in stack/heap. |
| 148 |
Sort List |
Convert the linked list to an array, sort the array using a built-in sort (O(N log N)), and convert it back to a list. |
A "Transfer" block: List rightarrow Array rightarrow List, adding $O(N)$ space overhead. |
Draw a list. Draw a box (Array). Write numbers in the box, sort them, then draw the list again. |
Merge Sort (Bottom-Up Iterative for $O(1)$ space, or Top-Down Recursive). |
"Divide and Conquer" zipper. The list is split into single-node pieces and zipped back together in sorted pairs. |
Use Fast/Slow pointers to find mid. Split list. Recurse. Merge two sorted halves by comparing heads and linking the smaller one. |
Draw the list. Draw a tree-like structure splitting it in half, then half again. Draw arrows merging the small pieces into larger sorted chains. |
$O(N \log N)$ recursion tree. The depth is log N and the work at each level is N. |
Draw a binary tree. Each level has a total width of N. There are log N levels. Shade the area to show N log N. |
$O(N)$ space for the temporary array buffer. |
Visualize the $O(\log N)$ recursive call stack (Top-Down) or $O(1)$ extra pointers (Bottom-Up). |
| 149 |
Max Points on a Line |
Triple nested loop: Pick two points to define a line (O(N^2)), then iterate through all other points to see if they lie on that line (O(N)). |
A massive $O(N^3)$ computational cube showing every possible combination of three points. |
Draw 4 points. Draw lines between all pairs (6 lines). For each line, check if the other points touch it. Count the checks. |
Hash Map for Slopes (per starting point). |
A "Radar Sweep." From one point, you look at every other point and categorize them by the angle (slope) they make with you. |
For each point P1: use a Map to count slopes (y2-y1)/(x2-x1) for all P2. The max count in the Map (+1 for P1) is the max for that point. |
Draw a central point. Draw rays coming out of it to other points. Group the rays that have the same angle. Write the count next to each group. |
$O(N^2)$ time. A 2D grid where every point is compared to every other point exactly once. |
Draw an N x N grid. Cross out each cell as you calculate the slope, proving you only touch each pair once. |
N/A (Nested loops only). |
A Hash Map that resets for every starting point, storing at most N slope-count pairs. |
| 150 |
Evaluate Reverse Polish Notation |
Scan the array for an operator. Once found, look backward to find the two nearest numbers, evaluate, and replace the three elements with the result. Repeat. |
A shrinking array where each operation triggers a "search and shift" $O(N^2)$ process. |
Write: ["2", "1", "+", "3", "*"]. Circle "2", "1", "+". Replace with "3". Shift everything over. |
Stack-based Evaluation. |
A "LIFO" processing plant. Numbers are stored in a silo (stack) until an operator arrives to consume the top two. |
If token is a number, push to Stack. If token is operator, pop B, pop A, calculate A [op] B, and push the result back. |
Draw a vertical bin. Drop numbers into it. When you see "+", take the top two out, add them, and drop the result back in. |
$O(N)$ linear pass. Every token is visited once and pushed/popped once. |
Draw a single horizontal arrow through the tokens. Mark each with a 'v' for visit, proving $O(N)$. |
Large strings and array-shifting overhead in heap memory. |
Visualize a single Stack in memory growing to a maximum height of N (or less, depending on operators). |
| 151 |
Reverse Words in a String |
Split the string by spaces into an array, reverse the array, and join with a single space. |
A three-stage conveyor belt: Split (O(N)) rightarrow Reverse (O(N)) rightarrow Join (O(N)). |
Draw the string. Draw a set of boxes (Array). Write words in boxes. Draw a new set of boxes in reverse order. Join them. |
Two-Pointer In-place Reverse (or String Builder). |
A "Mirror in Sections." First, reverse the entire string, then reverse each individual word back to its original spelling. |
1. Clean spaces. 2. Reverse the whole string. 3. Use two pointers to find word boundaries and reverse each word in-place. |
Write "blue is sky". Reverse the letters: "yks si eulb". Then circle "yks" and flip it to "sky", circle "si" to "is", etc. |
$O(N)$ single-pass (or constant number of passes) over the characters. |
Draw a single horizontal arrow through the string. Mark the points where it "doubles back" to flip a word. |
Visualise multiple temporary string objects and a full word array taking $O(N)$ heap space. |
Visualize a single character array (if mutable) or a single String Builder instance in $O(N)$ space. |
| 152 |
Maximum Product Subarray |
Nested loops to calculate the product of every possible subarray (i, j) and track the maximum found. |
An upper-triangular grid (N x N) where each cell represents a multiplication operation. |
Draw the array. For the first element, draw arrows for all subarrays starting there. For the second, do the same. Show the $O(N^2)$ density. |
Dynamic Programming (Kadane's variation with Min/Max tracking). |
A "Dual Tracker." Since two negatives make a positive, you track both the "current best" and the "current worst" (minimum) simultaneously. |
Maintain currMax and currMin. If number is negative, swap them. Update both using num and curr*num. |
Draw the array. Below it, draw two rows: 'Max' and 'Min'. Fill them as you move right. Use a swap arrow whenever you hit a negative number. |
A single $O(N)$ pass. The work is perfectly linear. |
Draw a single arrow moving left to right once. Highlight the cells where the max product is updated. |
$O(1)$ extra space logic, but $O(N^2)$ time results in significant CPU cycle overhead visualized by redundant math. |
Visualize three static integer variables in $O(1)$ stack memory: max_so_far, min_so_far, and result. |
| 153 |
Find Minimum in Rotated Sorted Array |
Linear scan through the array to find the point where the value decreases, or simply finding the overall minimum. |
A single $O(N)$ line scanning every element from left to right. |
Draw the rotated array. Draw a finger moving through every box until it hits the smallest number. |
Binary Search (O(log N)). |
A "Mountain Peak" detection. In a rotated array, you are looking for the "inflection point" where the sorted order breaks. |
Set low, high. If nums[mid] > nums[high], the min is in the right half. Otherwise, it's in the left (including mid). |
Draw two sorted lines shifted. Mark 'L', 'M', 'H'. Show how comparing 'M' to 'H' tells you which "slope" the minimum is on. |
Logarithmic $O(\log N)$ tree depth. The search space is halved at every step. |
Draw a binary tree structure. Shade only one path from the root to a leaf, showing that only log N elements are touched. |
N/A (Constant space for iteration). |
Visualize two pointers (low, high) moving towards each other in $O(1)$ stack space. |
| 154 |
Find Minimum in Rotated Sorted Array II |
Linear scan (identical to Q153), as duplicates don't change the brute force cost. |
A single $O(N)$ pass. |
Draw the array with duplicates. Draw the same finger scan as Q153. |
Binary Search with Duplicate Handling (O(log N) average, $O(N)$ worst). |
A "Foggy Search." When nums[mid] == nums[high], you can't tell which way to go, so you just "creep" inward by one step. |
Same as Q153, but add: if nums[mid] == nums[high]: high -= 1. This handles the ambiguity caused by duplicates. |
Draw an array like [2, 2, 2, 0, 2]. Show how L, M, and H are all the same, forcing the 'H' pointer to move just one step left. |
A graph that is $O(\log N)$ for most inputs but becomes $O(N)$ for arrays full of the same number. |
Draw the binary tree, but show one branch "branching" into a sequential line for the worst-case scenario. |
N/A. |
Visualize the same $O(1)$ pointers, but with more frequent "single-step" increments compared to "half-jumps." |
| 155 |
Min Stack |
For every getMin operation, iterate through the entire stack to find the smallest element (O(N)). |
An $O(N)$ vertical scan of the stack for every query. |
Draw a vertical stack. For 'getMin', draw an arrow checking every single item from the top to the bottom. |
Two Stacks (Data Stack + Min Stack) or One Stack with Pairs. |
A "Shadow Record." The second stack acts as a shadow that only remembers the minimum value at each "height" of the main stack. |
When pushing X: push to mainStack. Push min(X, currentMin) to minStack. When popping, pop from both. |
Draw two parallel stacks. When you drop a number in the left, drop the *lowest seen so far* in the right. Popping keeps them synchronized. |
$O(1)$ for all operations: push, pop, top, and getMin. |
Draw a single dot. Accessing the top of either stack is a constant time operation. |
Low time efficiency, but potentially saves memory by not storing a second stack. |
Visualize two $O(N)$ stack structures in heap memory. Space is $O(N)$. |
| 156 |
Binary Tree Upside Down |
Recursively traverse to the left-most leaf, then at each step, create new node objects to form the inverted tree structure. |
A "Mirror Explosion" diagram where multiple tree fragments are created in heap memory. |
Draw the original tree. For every left-child transition, draw a completely new set of circles and arrows to represent the new tree being built. |
Iterative Pointer Manipulation (Bottom-Up Logic). |
A "Rotating Pinwheel." As you move down the left spine, the parent and right-sibling are re-linked as children of the current left-child. |
Keep pointers for curr, next, tempParent, and tempRight. Move down the left side, rotating pointers at each step. |
Draw the tree. For each node on the left spine, erase its arrows and draw new ones pointing 'up' to the parent and 'left' to the sibling. |
$O(N)$ linear scan of the left spine (strictly proportional to tree height H). |
Draw a single line down the left edge of a tree. Mark it with a single stroke to show a single-pass visit. |
Visualise numerous temporary Node objects being allocated and garbage-collected. |
Visualize 4 static pointer variables (addresses) in $O(1)$ stack memory; no new nodes created. |
| 157 |
Read N Characters Given Read4 |
Repeatedly call read4 and copy characters one-by-one into the destination buffer without checking if n is exceeded mid-chunk. |
A "Leaky Bucket" visualization showing characters overflowing the destination array. |
Draw a box of size N. Draw a sequence of boxes of size 4. Show the 4th box partially spilling outside the N-sized box. |
Buffered Chunk Processing with Bound Checking. |
A "Sieve." 4-character blocks are poured in, but only the characters that "fit" the remaining count are allowed through to the target. |
While total read < n and last read == 4: read into internal buffer. Use min(remaining, charsRead) to copy into destination. |
Draw a target array and a 4-slot internal buffer. Draw arrows moving characters from buffer to array, stopping precisely at index N-1. |
$O(N)$ time where N is the number of characters requested to be read. |
Draw a single arrow moving linearly across the destination buffer indices. |
Copying every chunk into an intermediate large array before final output. |
Visualize a small, fixed-size 4-byte buffer in stack memory, reused for every cycle. |
| 158 |
Read N Characters Given Read4 II |
Re-reading from the source file for every call, ignoring the fact that previous calls might have left unused characters in the read4 buffer. |
A "Data Loss" diagram where characters 5-8 are discarded because the user only asked for 1-4. |
Draw a stream: [1,2,3,4,5,6,7,8]. Draw a call for 2 chars. Show 3,4 being "skipped" and the next call starting at 5. |
Global State Buffer (Persistent Pointer/Counter). |
A "Reservoir." The read4 fills a small tank. Calls from the user take from the tank. If empty, the tank refills from the source. |
Store internalBuffer, bufPtr, and bufSize as class members. Use these to track leftover data between method calls. |
Draw a persistent 4-slot box. Mark where the "last read" ended with a pointer. Show the next call starting from that exact pointer. |
$O(N)$ total across all calls; each character is read from the source exactly once. |
Draw a timeline. Mark segments of different lengths representing different calls, all fitting together into a single linear read. |
Creating new buffer arrays for every single class instance call. |
Visualize a single, static 4-byte buffer and two integer pointers sitting in the object's heap space. |
| 159 |
Longest Substring with At Most Two Distinct Characters |
Nested loops to check every single possible substring (i, j) and verify if it contains <= 2 distinct characters. |
An $O(N³)$ complexity cube (Subarrays x Distinct Count check). |
Draw a string. Draw brackets for every possible start and end point. For each bracket, draw a Hash Set to count unique letters. |
Sliding Window with Hash Map (Frequency Counter). |
An "Expanding/Contracting Caterpillar." The head moves right to add characters; the tail moves right to remove them if unique count > 2. |
Maintain Map. Move right pointer. If Map.size() > 2, increment left and decrement count until a key is removed. |
Draw a string. Draw a sliding box over it. Below, draw a small table. As the box expands, add letters to the table. If size > 2, shrink the box from the left. |
$O(N)$ time. Each character is visited by the left and right pointers at most once. |
Draw the string. Draw two parallel arrows (L and R). Both move only from left to right, never back, proving $O(N)$. |
Creating new substring copies or full sets for every window position. |
Visualize a Hash Map that never exceeds 3 entries (O(1) additional space if alphabet is constant). |
| 160 |
Intersection of Two Linked Lists |
For every node in List A, traverse the entirety of List B to see if the node references match (O(M x N)). |
A "Cross-Reference Grid" showing every node of A being compared to every node of B. |
Draw List A vertically and List B horizontally. Draw a dot at every intersection to show the M * N comparisons. |
Two-Pointer Sync (Head Switching). |
"Running the Same Distance." If two people run different routes, they will meet if they each run Path A + Path B total distance. |
Point pA to headA, pB to headB. When pA hits null, switch to headB. When pB hits null, switch to headA. They meet at intersection. |
Draw two lists merging. Trace pA through A and then through B. Trace pB through B and then through A. Show them landing on the same node simultaneously. |
$O(M + N)$ linear time. The pointers cover exactly the combined length of both lists. |
Draw a single line of length M+N. Mark the intersection point to show they reach it after exactly one total traversal. |
Storing one entire list in a Hash Set to perform $O(1)$ lookups (O(N) space). |
Visualize two single pointers in $O(1)$ stack memory. No extra structures. |
| 161 |
One Edit Distance |
Generate all possible strings that are one edit away from S and check if any equal T. |
An $O(N^2)$ branching tree of string transformations. |
Draw string S. Draw arrows for every possible char deletion, replacement, and insertion. It creates a massive web of strings. |
One-Pass String Comparison. |
A "Synchronization Scan." Two pointers scan both strings until they hit a mismatch, then they "jump" and check if the rest aligns perfectly. |
Iterate through shorter string. If `s[i] != t[i]`, if lengths equal: check `s[i+1:] == t[i+1:]`. If lengths differ: check `s[i:] == t[i+1:]`. |
Draw S and T parallel. Draw a vertical line through matching chars. At the mismatch, draw a box around the remaining parts and link them with an '=' sign. |
$O(N)$ linear time. The strings are traversed at most once. |
Draw a single straight arrow moving through both strings simultaneously, proving $O(N)$. |
Visualise $O(N^2)$ memory occupied by all potential edited string candidates. |
Visualize $O(1)$ space if using pointers, or $O(N)$ for a single substring slice. |
| 162 |
Find Peak Element |
Linear scan through the array to find an element that is strictly greater than its neighbors. |
An $O(N)$ horizontal sweep across a mountain range. |
Draw a line of numbers. Draw a finger visiting every single box until it finds a "summit." |
Binary Search on Slope. |
"Flashlight on a Ridge." You check the slope at your current position (Mid). If it's going up, the peak must be to the right; if down, to the left. |
Set `low`, `high`. If `nums[mid] < nums[mid+1]`, move `low = mid + 1`. Else, `high = mid`. Result is `low`. |
Draw a line chart. Mark L, R, and M. Draw an uphill arrow based on the comparison of M and M+1 to show the direction of search. |
$O(\log N)$ tree search. The search space is halved every time. |
Draw a binary tree. Shade only a single path from root to leaf to show that only log N elements are touched. |
N/A (Constant space). |
Visualize two pointers (`low`, `high`) in $O(1)$ stack memory. |
| 163 |
Missing Ranges |
Iterate through every integer from `lower` to `upper` and check if it exists in the input array. |
An $O(\text{Range})$ checklist, where the range can be much larger than the array size. |
Draw a long number line from 0 to 100. Check off the 3 numbers you have. Show the enormous amount of "empty" space checked. |
Linear Scan of Adjacent Elements. |
"Jumping Stepping Stones." You only look at the numbers you have and calculate the gap (distance) between them. |
Start with `prev = lower - 1`. For each `curr` in `nums` (plus a final `upper + 1`), if `curr - prev > 1`, add the range `[prev+1, curr-1]`. Update `prev = curr`. |
Draw array boxes. Draw arrows between them. Label the "missing" range values directly on the arrows between the boxes. |
$O(N)$ time where N is the length of the array, regardless of the numerical range. |
Draw a single arrow through the array. Mark each gap found with a '!' symbol. |
A massive boolean array or set to store the presence of every number in the range. |
Visualize $O(1)$ extra space (excluding the result list) to store the `prev` tracker. |
| 164 |
Maximum Gap |
Sort the array using $O(N \log N)$ and then perform a linear scan to find the max difference between adjacent elements. |
A sorting factory diagram followed by a single measurement pass. |
Draw an unsorted pile. Draw a sorted line below it. Draw small rulers between every sorted element to find the max gap. |
Bucket Sort (Pigeonhole Principle). |
"Birdhouses." By dividing numbers into buckets smaller than the average gap, you guarantee the max gap is *between* buckets, not within them. |
Find min/max. Calc bucket size. Place nums into N buckets (track min/max per bucket). Max gap = `max(max_gap, curr_bucket.min - prev_bucket.max)`. |
Draw N-1 buckets. Place the numbers into them. Draw a large arrow between the max of one bucket and the min of the next. |
$O(N)$ linear time. The sorting is bypassed by the bucket distribution. |
Draw a horizontal line. Mark bucket boundaries. Show that you only compare bucket edges, not every internal number. |
N/A (In-place sort might use $O(\log N)$). |
Visualize two $O(N)$ arrays in heap memory: `bucketMin` and `bucketMax`. |
| 165 |
Compare Version Numbers |
Split both strings by '.' into arrays, convert all segments to integers, and compare index by index. |
A dual-conveyor belt showing $O(N+M)$ space for split arrays. |
Draw two version strings. Draw two boxes below them containing the list of integers. Draw vertical lines comparing the boxes. |
Two-Pointer Integer Parsing. |
"Crawling through Dots." Two pointers move through the strings, stopping at each '.' to evaluate the integer value of the preceding segment. |
While i < len1 or j < len2: parse digits until dot to get `v1` and `v2`. If `v1 > v2` return 1, etc. Move pointers past the dot. |
Draw the strings. Draw two pointers. Circle the digits between the dots and write the integer value (e.g., "001" rightarrow 1) above the circle. |
$O(N+M)$ time. Each character in both strings is visited exactly once. |
Draw a single horizontal line through both strings. Mark each dot as a "checkpoint." |
$O(N+M)$ space for the split string arrays and converted integer lists. |
Visualize $O(1)$ space with two pointers and two temporary integer variables. |
| 166 |
Fraction to Recurring Decimal |
Perform long division. If it doesn't terminate quickly, keep adding digits until a limit is reached or a pattern is manually spotted. |
A "Linear Progression" that might extend infinitely if the fraction is irrational (not possible here) or very long. |
Draw a long division bar. Keep writing digits until you run out of paper, showing the lack of a stop condition. |
Long Division + Hash Map (Remainder Tracking). |
A "Cycle Detector." As you divide, you store the remainder in a map. If you see the same remainder twice, a loop has been found. |
Perform Numerator / Denominator. Store `remainder -> stringIndex` in a Map. If current remainder exists in Map, insert brackets `()` at the stored index. |
Draw the long division. Beside it, keep a "Remainder Log." When you write a remainder, check if it's already in the log. If yes, draw a loop arrow back to its first occurrence. |
$O(\text{Denominator})$ complexity. The number of unique remainders is limited by the value of the divisor. |
Draw a circle with D slots. Show that you must eventually land on a slot you've visited before, proving the bound. |
Unbounded string growth without memory of state. |
Visualize a Hash Map storing at most D integers (O(D) space). |
| 167 |
Two Sum II - Input Array Is Sorted |
Nested loops (i, j) to check every pair of numbers to see if they sum to the target (O(N^2)). |
An $O(N^2)$ upper-triangular coordinate grid showing redundant pairs. |
Draw the array. For the 1st number, draw arrows to all others. For the 2nd, do the same. Show the density of arrows. |
Two Pointers (Left and Right). |
A "Pincer Movement." One pointer at the start, one at the end. They move inward based on whether the current sum is too low or too high. |
While L < R: if Sum < Target, move L right. If Sum > Target, move R left. If equal, return [L+1, R+1]. |
Draw the sorted array. Put a finger on the first and last elements. Slide them inward, noting if the sum needs to "grow" or "shrink." |
$O(N)$ linear time. Both pointers together cover exactly N elements. |
Draw a single horizontal line. Mark each element with one dot as it is passed by a pointer, proving no node is visited twice. |
N/A (Nested loops only). |
Visualize two integer pointers (L, R) in $O(1)$ stack memory. Zero heap allocation. |
| 168 |
Excel Sheet Column Title |
Iteratively subtract 1 from the number and try to map it to A-Z, but failing to handle the "Base 26 without Zero" logic correctly. |
A "Broken Ladder" visualization where the transition from 'Z' to 'AA' fails. |
Draw a number line. Try to label them A, B... Z, then show the confusion when trying to figure out what comes after 26. |
Base-26 Conversion (with Offset Correction). |
"Reversing the Alphabet Clock." It’s like converting to binary or hex, but you subtract 1 at each step to align 1-26 with 0-25. |
While n > 0: n--; char is `(n % 26) + 'A'`. Prepend to result. n = n / 26. |
Write the number. Draw a box for "Remainder" and "Quotient." Perform the math, write the letter, and repeat with the new quotient. |
$O(\log_26 N)$ time. The number of digits is proportional to the logarithm of the value. |
Draw a shrinking bar. Each step reduces the size by a factor of 26, showing a very fast $O(\log N)$ termination. |
Manual list of every possible column title string stored in a table. |
Visualize a single string buffer or character array growing to a maximum of 7-10 characters for huge inputs. |
| 169 |
Majority Element |
Sort the array and pick the middle element (O(N log N)) or use a Hash Map to count frequencies of all elements (O(N) space). |
A sorting tree or a large "T-account" table taking up $O(N)$ space. |
Draw the array. Draw a Map table. Count every single number, then scan the table for the one with Count > N/2. |
Boyer-Moore Voting Algorithm. |
"The Last Man Standing." A battle where different numbers "fight" each other. The majority element has enough "soldiers" to outlast everyone else combined. |
Keep `candidate` and `count`. If `count == 0`, `candidate = num`. If `num == candidate`, `count++`, else `count--`. |
Draw the array. Use a "Battle Box." Put the first number in. If the next is same, add a +1. If different, do a -1. If box hits 0, clear and put the next number in. |
$O(N)$ linear time. A single pass with no extra data structures. |
Draw a single arrow through the array. Note that you never look back and never store more than two variables. |
A Hash Map ballooning in heap memory to store every unique number's frequency. |
Visualize two single integer variables (`candidate`, `count`) in $O(1)$ stack memory. |
| 170 |
Two Sum III - Data structure design |
Store all numbers in a list. For `find`, perform an $O(N^2)$ nested loop search or sort and use two pointers (O(N log N)). |
A "Heavy Search" visualization where adding data is fast but finding data is extremely slow and red-lined. |
Draw a list of numbers. For `find(7)`, show the searcher checking every single pair combination until it finds 3+4. |
Hash Map (Value rightarrow Frequency Count). |
A "Speedy Lookup Table." The `add` operation is $O(1)$, and the `find` operation is a single $O(N)$ pass through the unique keys in the map. |
`add`: increment count in Map. `find(T)`: for each `key` in Map: `complement = T - key`. If `complement` exists (handle same-key case), return true. |
Draw a Map. For `add`, just update the counts. For `find(10)`, iterate through the keys, subtract from 10, and do a quick "Is it in the map?" check. |
$O(N)$ for `find`, $O(1)$ for `add`. Optimized for heavy data insertion and moderate searching. |
Draw a single scan through the *unique* keys of the map, proving the work is proportional to the number of distinct elements. |
Storing full pairs or sorted copies of the data redundantly. |
Visualize a Hash Map in heap memory storing N unique keys and their counts. |
| 171 |
Excel Sheet Column Number |
Iterate through the string from right to left, manually calculating 26^0, 26^1, 26^2... using a power function for every character. |
A "Weighty Digit" diagram where each letter has a floating exponent block above it, showing redundant power calculations. |
Write "AB". Draw an arrow from 'B' to 2 x 26^0 and 'A' to 1 x 26^1. Show the power function calculation steps separately. |
Polynomial Rolling Sum (Base-26 conversion). |
An "Accumulator Tank." You start with 0, multiply the current total by 26 to "shift" it, and add the new character's value. |
Initialize result = 0. For each char c: result = result * 26 + (c - 'A' + 1). |
Draw a single box labeled 'Result'. As you read 'A', 'B', 'C', update the box: 0 to 1, 1 to (1 x 26 + 2) = 28, etc. |
$O(N)$ linear time where N is string length. One multiplication and one addition per char. |
Draw a single horizontal arrow through the string. Mark each char with a single dot to prove a single pass. |
Stacking multiple calls of a power function $O(N)$ or using large intermediate storage for powers. |
A single integer variable in $O(1)$ stack memory. |
| 172 |
Factorial Trailing Zeroes |
Calculate the actual factorial of n (n!), then count how many zeroes are at the end by repeatedly using modulo 10. |
A "Vertical Wall" representing the massive number of digits in n! that eventually cause an integer overflow. |
Write 5! = 120. Count 1 zero. Try to write 25! and show your paper running out of space for the digits. |
Count Factors of 5 (Legendre's Formula). |
A "Sieve for 5s." Since every zero is formed by 2 x 5, and 2s are abundant, you only need to count how many 5s are in the factors. |
While n > 0: count += n / 5; n /= 5;. This counts 5, 25, 125... contributions. |
Draw a number line up to n. Circle every multiple of 5. For 25, draw two circles (since it's 5^2). Count total circles. |
$O(\log_5 N)$ time. The input n is divided by 5 in each step. |
Draw a shrinking bar. Each section is 1/5th the size of the previous, showing logarithmic decay to zero. |
$O(N)$ memory to store the massive string representation of the factorial. |
A single integer counter in $O(1)$ stack memory. |
| 173 |
Binary Search Tree Iterator |
Perform a full In-order traversal (DFS) at initialization and store all node values in an $O(N)$ array/list. |
A "Pre-loaded Magazine." You load all bullets (nodes) into the clip at once before firing a single one. |
Draw the BST. Below it, draw a long horizontal array. Draw arrows from the tree into the array in sorted order. |
Controlled Stack-based DFS (Lazy Loading). |
A "Partial Path." Only the nodes along the current leftmost path are stored, mimicking a manual DFS walk. |
On next(): pop top node from stack. If it has a right child, "push all its left descendants" onto the stack. |
Draw the BST and a vertical stack. Draw an arrow down the left spine. As you pop a node, draw a small arrow to its right child and then down *that* node's left spine. |
Average $O(1)$ time per operation. $O(H)$ space, where H is the height of the tree. |
Draw a full traversal path. Note that each node is pushed and popped exactly once across N calls to next(). |
$O(N)$ heap space to store the flattened tree. |
Visualize a Stack in memory with a maximum height of $O(H)$. In a balanced tree, this is only $O(\log N)$. |
| 174 |
Dungeon Game |
Recursion with backtracking to explore every possible path from top-left to bottom-right, calculating minimum health needed for each. |
A sprawling $O(2^M+N)$ decision tree branching at every cell. |
Draw a 3 x 3 grid. From (0,0), draw arrows to (0,1) and (1,0). Repeat. Show the tree structure growing exponentially. |
Bottom-Up Dynamic Programming (Reverse Tabulation). |
"Planning for the Future." You start at the Princess (bottom-right) and calculate the health you *need to have* to survive the path to the exit. |
dp[i][j] = max(1, min(dp[i+1][j], dp[i][j+1]) - dungeon[i][j]). Base case: exit health = 1. |
Draw the grid. Start at the bottom-right corner with '1'. Move left and up, calculating health required based on the cell's damage/heal value. |
$O(M x N)$ time. Each cell in the grid is visited and calculated exactly once. |
Draw the grid. Shade it row-by-row starting from the bottom to show the single-pass filling. |
Massive $O(2^M+N)$ recursive call stack. |
$O(M x N)$ 2D array in heap memory (or $O(N)$ with a rolling 1D array optimization). |
| 175 |
Combine Two Tables |
Fetch all data from the Person table, then for each row, run a separate query to search the Address table for a matching personId. |
A "Nested Loop Query" (N query calls), visualizing multiple round-trips to the database. |
Draw two tables. Pick a row in Table A. Draw arrows to every row in Table B until a match is found. Repeat. |
SQL Left Outer Join. |
A "Selective Merge." Table A is the anchor; Table B is joined where possible, leaving 'NULL' holes where no match exists. |
SELECT FirstName, LastName, City, State FROM Person LEFT JOIN Address ON Person.personId = Address.personId. |
Draw Table A. Draw Table B. Draw lines connecting matching IDs. If a row in A has no line, draw a box with "NULL" in the B columns. |
$O(N + M)$ assuming the join column is indexed in the database. |
Draw a single merge line where two streams of data flow together based on a shared key. |
Temporary memory used to store N intermediate result sets from N separate queries. |
A single execution plan in database memory, mapping pointers to disk locations. |
| 176 |
Second Highest Salary |
Sort the unique salaries in descending order and pick the second one. Fails on edge cases where only one salary exists. |
A "Sorting Filter" diagram where N items are sorted, taking $O(N \log N)$ time. |
Draw a list of random numbers. Draw a sorted list. Circle the 2nd item. Draw a question mark if the list only has 1 item. |
Subquery with LIMIT 1 OFFSET 1 wrapped in IFNULL. |
A "Box within a Box." The inner box finds the 2nd value, the outer box ensures a NULL return if the inner one is empty. |
Select max salary. Select max salary again where salary is less than the first max. This handles the "second highest" logic perfectly. |
Draw Table A. Draw a smaller Table B (filtered for salaries < Max). Circle the highest value in Table B. |
$O(N)$ with a single scan if using `MAX()` twice, or index-based $O(\log N)$. |
Draw an Index Tree (B-Tree). Show the pointer jumping directly to the second-to-last leaf node. |
Visualise a full copy of the table being sorted in temp space (O(N)). |
Zero extra space beyond the pointer to the result (O(1)). |
| 177 |
Nth Highest Salary |
Generalization of Q176: Use a loop or a script to sort and offset by N-1. |
A "Linear Ranking" where you must scan N deep into a sorted set. |
Draw a ladder. Mark the N-th rung. Show the searcher climbing from the top down to rung N. |
Function with Local Variable Offset (N-1) and LIMIT. |
A "Slotted Viewport." A window that is exactly one row tall, positioned N-1 rows from the top of the sorted data. |
Set M = N-1. Run: SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET M. |
Draw a vertical sorted list. Draw a sliding window box that stops exactly at the N-th position. |
$O(N \log N)$ for the sort, or $O(N)$ if the database uses a heap-based selection. |
Draw the sort timeline. Mark a single point on the timeline representing the "pick" operation. |
Heap memory spikes as the database buffers the sorted results. |
Efficient index usage visualized by the database only loading the relevant block into buffer cache. |
| 178 |
Rank Scores |
For every score, perform a subquery to count how many unique scores are greater than or equal to it (O(N^2)). |
A "Cross-Check Matrix" where every row looks at every other row to find its relative rank. |
Draw 5 scores. For the first score, draw 5 checkmarks. For the second, 5 more. Show the N^2 work. |
Window Function: DENSE_RANK() OVER(ORDER BY Score DESC). |
A "Grouped Podium." Identical scores stand on the same level, and the next unique score is exactly one level below them. |
Sort scores. Assign '1' to the highest. If next score is same, keep '1'. If different, increment to '2'. |
Draw the scores. Group identical values with a circle. Assign a rank number to each circle. |
$O(N \log N)$ due to the internal sorting required by the window function. |
Draw a sort-then-scan timeline. One pass to sort, one pass to assign ranks. |
Nested loops creating a massive N x N logical comparison space. |
A single sorted copy of the unique scores stored in the database's temporary working memory. |
| 179 |
Largest Number |
Generate all possible permutations of the numbers (O(N!)) and find the maximum string. |
A "Fractal Explosion" showing the impossible number of combinations (10! = 3.6 million). |
Draw 3 numbers. Draw 6 arrows showing all ways to arrange them. Draw 4 numbers and try to draw all 24 arrows. |
Custom Greedy Sorting (Comparator: S1+S2 vs S2+S1). |
A "Chain Link Comparison." Two strings are tested as A+B and B+A. The "heavier" concatenation dictates the order. |
Take "3" and "30". 3+30=330, 30+3=303. 330 > 303, so "3" comes before "30". Repeat for all pairs. |
Draw two boxes. Put "9" in one, "91" in the other. Draw two combinations: "991" and "919". Circle the bigger one. |
$O(N \log N \cdot K)$ where K is the average length of the strings. |
Draw a sorting tree (Merge Sort). At each comparison node, show the A+B logic being applied. |
$O(N!)$ space to store all permutations. |
$O(N)$ space to store the string representations of the numbers for sorting. |
| 180 |
Consecutive Numbers |
Self-join the table three times to find rows where `Id`, `Id+1`, and `Id+2` all have the same value. |
A "Triple-Layer Table" visualization where the table is copied and shifted against itself. |
Draw Table T1. Draw T2 (shifted up 1). Draw T3 (shifted up 2). Draw a vertical line through them to find matching values. |
Window Functions: LEAD() or LAG(). |
"Ghost Rows." Every row "carries" the values of the row after it and the row after that, allowing for a single-pass check. |
For each row, look at the `Value` of the next 2 rows using `LEAD`. If `Val = Lead1 = Lead2`, it's a consecutive triplet. |
Draw the table columns. Add two virtual columns labeled "Next" and "Next+1". Fill them and circle rows where all three match. |
$O(N)$ linear scan after the data is sorted by ID. |
Draw a single arrow moving down the table. Show the "view" of the arrow covering 3 rows at a time. |
Massive Cartesian product overhead from triple joins (O(N^3) conceptual if not indexed). |
$O(N)$ memory for the result set and the temporary window function buffer. |
| 181 |
Employees Earning More Than Their Managers |
For every row in the Employee table, run a separate query to find the salary of the manager whose ID matches the current employee's ManagerId. |
A "Nested Loop" diagram where N external requests trigger N internal scans. |
Draw a table. Pick Employee A. Search the entire table again for Manager A. Repeat for Employee B. Count the total arrows (N^2). |
Self-Join on ManagerId = Id. |
A "Parallel Mirror." Two identical tables are placed side-by-side, and lines are drawn only between an employee and their specific manager. |
Match `Emp.ManagerId` with `Mgr.Id`. Filter rows where `Emp.Salary > Mgr.Salary`. |
Draw two boxes (Employee a, Employee b). Link them with an arrow based on ID. Write their salaries on the arrow and circle if the first is larger. |
$O(N)$ with indexing. A single pass over the join condition. |
Draw two vertical lines. Draw a single set of horizontal bridges between them, showing a 1-to-1 mapping. |
Large memory overhead for managing N separate query contexts. |
Visualize the Join Buffer in the database engine holding only relevant columns for the active join. |
| 182 |
Duplicate Emails |
For every email in the table, scan the rest of the table to see if it appears again (O(N^2)). |
A "Cross-check Grid" showing every email being compared to every other email. |
Draw a list of emails. Draw arrows from the first email to all others below it. Show the increasing density. |
GROUP BY with HAVING COUNT(*) > 1. |
A "Bucket Sort" visualization. Emails are tossed into buckets based on their name; buckets with more than one item are highlighted. |
Group all identical emails together. Count the size of each group. Only select groups where size > 1. |
Draw several buckets labeled with emails. Place dots in buckets. Circle buckets containing more than one dot. |
$O(N \log N)$ (sorting) or $O(N)$ (hashing). Linear scan of groups. |
Draw a single horizontal line. Group segments together and mark those longer than a unit length. |
Redundant storage of N comparison results in temp space. |
Visualize a Hash Map in memory where keys are emails and values are integers (counts). |
| 183 |
Customers Who Never Order |
Iterate through every customer. For each, perform a subquery to check if their ID exists in the entire Orders table. |
An $O(C x O)$ operation where C is customers and O is orders. |
Draw Table A (Customers) and Table B (Orders). For every row in A, draw a scan line through all of B. |
LEFT JOIN where Orders.Id IS NULL (or NOT IN with subquery). |
A "Ghost Match." The Customer table is matched with Orders; customers without orders appear with a "void" or "null" on the right side. |
Join `Customers` and `Orders` on `CustomerId`. Look for rows where the `OrderId` column is completely empty. |
Draw two tables. Draw connection lines for orders. Circle the customers in the first table that have no outgoing lines. |
$O(C + O)$ with proper indexing on the join key. |
Draw two streams merging. Highlight the elements in the first stream that did not find a partner in the second. |
Memory spikes for C separate sub-execution plans. |
A single execution hash table of Order IDs sitting in memory for a single-pass check. |
| 184 |
Department Highest Salary |
Join all tables, then for every row, check if that salary is the maximum in its specific department by querying the department again. |
A "Deep Nest" diagram where every row of the joined result triggers a department-wide aggregate scan. |
Draw the joined table. For row 1, draw a sub-table of its department and find the max. Repeat for every row. |
Join with a GROUP BY subquery or Window Function. |
"Champions of the Room." Each department (room) identifies its highest salary, and those individuals are then matched with the master list. |
1. Find max salary per `DepartmentId`. 2. Join this result back to the `Employee` table on both `DepartmentId` and `Salary`. |
Draw tables grouped by Dept. Highlight the top row in each. Draw an arrow from these top rows to the final result set. |
$O(N)$ assuming indexes on `DepartmentId` and `Salary`. |
Draw a partitioned line. Mark the peak point in each partition to show localized $O(N)$ work. |
Massive temp table creation for every individual row's max-check. |
Visualize a small Hash Table in memory storing only `DeptID -> MaxSalary` pairs. |
| 185 |
Department Top Three Salaries |
For every employee, count how many distinct salaries in their department are higher than their own. If count < 3, keep them. |
An $O(N^2)$ correlated subquery where every employee triggers a filtered scan of their own department. |
Draw the list. For the first person, count everyone in their dept who earns more. Write the count. Repeat for everyone. |
Window Function: DENSE_RANK(). |
"The Olympic Podium." People are ranked 1st, 2nd, 3rd. If two people tie for 1st, the next unique salary is still 2nd. |
Rank employees by salary within each department. Only select those with a rank <= 3. |
Draw columns representing departments. Within each, write salaries in order. Mark the first three unique value levels. |
$O(N \log N)$ due to partitioning and sorting requirements. |
Draw a set of sorted blocks. Show a single pass through each block that stops after the 3rd unique rank. |
High CPU and memory cost for N separate counting operations. |
Visualize a sorted buffer for each department being processed sequentially in memory. |
| 186 |
Reverse Words in a String II |
Copy words into a temporary array, reverse the array, and join them back into the original array. |
A "Temporary Warehouse" where all items are moved out of the room to be rearranged. |
Draw the array. Draw a separate set of boxes. Show arrows moving words from array to boxes in reverse. |
Double In-place Reversal (Reverse Whole + Reverse Words). |
"The Pancake Flip." You flip the entire sequence, then flip each individual "pancake" (word) back to its original orientation. |
1. Reverse the entire array in-place. 2. Iterate through: when you hit a space, reverse the characters between the last space and current. |
Write "sky is blue". Step 1: Write "eulb si yks". Step 2: Circle "eulb" and flip to "blue", "si" to "is", "yks" to "sky". |
$O(N)$ linear time. Every character is swapped exactly twice. |
Draw a horizontal line. Mark two passes: a full-length swap and a series of smaller internal segments. |
$O(N)$ heap memory used to buffer the list of words. |
Visualize $O(1)$ stack memory. Only three index pointers (left, right, start) are used. |
| 187 |
Repeated DNA Sequences |
Extract every possible 10-length substring (O(N)) and use a nested loop to check if it exists elsewhere in the string (O(N)). |
An $O(N^2)$ overlapping block comparison diagram. |
Draw a long string. Draw a 10-char bracket. For every position, draw a scan line through the rest of the string. |
Sliding Window + Hash Set (or Rolling Hash). |
"The DNA Scanner." A window of size 10 slides along the sequence; if the window's content is already in the "Database" (Set), it's a match. |
Use two Sets: `seen` and `duplicates`. Slide window by 1. If substring is in `seen`, add to `duplicates`. Add to `seen` regardless. |
Draw the string. Draw a sliding box of width 10. Below it, draw a table. As the box moves, write the content in the table; mark if you write a duplicate. |
$O(N)$ time. Each 10-char slice is hashed and checked in constant time. |
Draw a single horizontal line. Mark each starting index with a dot once to show a single-pass scan. |
$O(N^2)$ conceptual memory if results are stored as full strings in the brute force comparison. |
Visualize $O(N)$ heap memory for the Hash Set storing string references or 20-bit integers (if bitmasking). |
| 188 |
Best Time to Buy and Sell Stock IV |
Recursive backtracking: At every day, decide whether to buy, sell (if holding), or skip, keeping track of k transactions. |
A massive $O(2^N)$ binary decision tree. |
Draw "Day 1". Branch into "Buy" or "Skip". Repeat for N days. Show the tree exploding exponentially. |
Dynamic Programming (DP Table with State). |
"A Multi-Story Building." Each floor represents a transaction count (1 to k), and each room tracks the max profit for that state. |
dp[k][i] = max profit with k transactions up to day i. Use a rolling variable to track max(profit - price) to optimize. |
Draw a K x N grid. Fill it row by row. For each cell, look at the cell directly above it and the max value from the row above. |
$O(N x K)$ time. Every state in the grid is visited once. |
Draw a rectangular grid. Shade it in row-by-row to show that work is proportional to the area. |
$O(2^N)$ call stack memory leading to stack overflow. |
Visualize a K x N matrix (or two 1 x N rows for space optimization) in heap memory. |
| 189 |
Rotate Array |
Rotate the array by 1 step, k times. For each rotation, shift N-1 elements. |
An $O(N x K)$ diagram showing many small, redundant shifts. |
Draw the array. Draw an arrow shifting everyone right. Repeat this drawing k times. |
The Reversal Algorithm. |
"The Triple Flip." Reversing segments of the array logically moves the elements to their rotated positions without extra space. |
1. Reverse the whole array. 2. Reverse first k elements. 3. Reverse remaining n-k elements. |
[2, 4, 6, 8], k=1. Step 1: [8, 6, 4, 2]. Step 2: [8] (no change). Step 3: [8, 2, 4, 6]. |
$O(N)$ time. Two total passes over the array elements. |
Draw a single line. Mark it with three segments representing the three reversal operations. |
Minimal time efficiency, but potentially $O(N)$ if a copy array is used for the rotation. |
Visualize $O(1)$ stack memory. Only the `reverse` function pointers exist. |
| 190 |
Reverse Bits |
Convert the integer to a 32-bit binary string, reverse the string, and convert back to an integer. |
"Format Conversion Overhead." Showing the heavy processing required to switch data types. |
Draw the number. Draw a 32-cell box. Fill with 0/1. Draw a second box and copy the bits in reverse. |
Bit Manipulation (Extract and Shift). |
"The Bit Conveyor Belt." You pick a bit from the right end of the input and drop it onto the left end of the result. |
Loop 32 times: result = (result << 1) | (n & 1); n >>= 1;. |
Draw two 32-bit slots. Draw an arrow from the LSB of 'n' to the LSB of 'res'. Show 'res' shifting left and 'n' shifting right. |
$O(1)$ time (or $O(32)$). The number of operations is fixed and constant regardless of the value. |
Draw a single dot. In complexity analysis, a fixed number of operations (32) is constant time. |
$O(N)$ heap memory for string representations and object conversions. |
Visualize a single 32-bit register in $O(1)$ stack memory. |
| 191 |
Number of 1 Bits |
Convert the number to a binary string and loop through every character to count the '1's. |
A "Character Scanner" moving across 32 cells regardless of how many 1s exist. |
Draw 32 boxes. Draw an arrow pointing at the 1st, then 2nd, then 3rd... up to 32. Show it takes 32 steps for any number. |
Brian Kernighan’s Algorithm (n & (n-1)). |
"The Bit Eraser." Each operation targets and deletes the rightmost set bit (1) instantly, like a sniper. |
While n
eq 0: n = n & (n-1); count++. Each step reduces the number of 1s until the number hits 0. |
Write n = 101100. Draw an arrow to the rightmost 1. Erase it (n = 101000). Repeat. Count how many times you erased. |
$O(k)$ where k is the number of set bits. In a sparse number like 2^31, it takes only 1 step. |
Draw a sparse 32-bit row. Mark only the '1's with an 'X' to show that you only visit the bits that matter. |
$O(1)$ space, but $O(32)$ constant time overhead is higher in the string conversion. |
Visualize a single 32-bit integer register in $O(1)$ stack memory being modified in-place. |
| 192 |
Word Frequency |
Write a complex script that reads the file, splits words into an array, and uses nested loops to count occurrences. |
A "Messy Workshop" where data is scattered and checked multiple times manually. |
Draw a text file. Draw a list of words. Draw arrows from every word to every other word to find matches. $O(N^2)$. |
Unix Pipeline (cat | tr | sort | uniq -c | sort -nr). |
"The Assembly Line." Raw text goes in one end; it is cleaned, sorted, grouped, and counted in a linear flow. |
1. tr converts spaces to newlines. 2. sort groups identical words. 3. uniq -c counts adjacent duplicates. 4. sort -nr orders by count. |
Draw 5 boxes in a line connected by pipes (|). Label them: Clean rightarrow Sort rightarrow Count rightarrow Rank. Draw data moving through. |
$O(N \log N)$ primarily due to the sorting step, which is highly optimized in Unix. |
Draw a sorting tree. Note that the data volume decreases as it hits the uniq filter. |
Buffering the entire file content into an internal script variable (RAM heavy). |
Visualize "Streaming Memory." Only small chunks of data are in the pipe at any given time (O(1) relative to file size). |
| 193 |
Valid Phone Numbers |
Read line by line. For each line, check if length is 10 or 14, then check every character at specific indices for digits or parentheses. |
A "Hardcoded Stencil." Every line is measured against multiple static IF statements. |
Draw a phone number. Draw a list of 10 checks: "Is char 0 a '('? Is char 4 a ')'?". Show the rigidity. |
Regex Pattern Matching (grep -P or awk). |
"The Mold." A single pattern represents the shape of a valid number. Data that doesn't fit the mold is discarded immediately. |
Apply pattern: ^(\(\d{3}\) |\d{3}-)\d{3}-\d{4}. The engine scans the line in one pass. |
Draw a stencil with holes in the shape of (xxx) xxx-xxxx. Place it over a list of numbers; only the valid ones show through. |
$O(N \\text{times} L)$ where N is lines and L is length. A single-pass character scan per line. |
Draw a horizontal arrow through the file. Mark it with a single 'Scan' label to show it never backtracks. |
Storing all valid numbers in a list before printing. |
Visualize "Standard Out" (stdout). Characters are printed as soon as they match, using almost zero permanent memory. |
| 194 |
Transpose File |
Read the entire file into a 2D matrix in memory, then iterate through columns and rows in reverse order to print. |
A "Data Cube" taking up massive M \times N space in memory. |
Draw a grid. Draw arrows representing the "Read" phase. Then draw new arrows representing the "Print" phase (top-to-bottom). |
AWK Column Accumulation. |
"The Vertical Builder." As you read row 1, you start building N separate strings (one for each column). |
For each row: append field 1 to `res[1]`, field 2 to `res[2]`, etc. After the file is finished, print all `res[i]`. |
Draw 3 buckets labeled Col 1, Col 2, Col 3. Read a row (A B C). Drop A in bucket 1, B in 2, C in 3. Repeat. Then empty the buckets. |
$O(\\text{text}{\text{Total Chars}})$ time. Every character is touched exactly once during the read and once during the print. |
Draw a single pass through the file. Shade the result area to show it matches the input size. |
Full M \times N matrix overhead plus string object fragmentation. |
Visualize N string buffers in heap memory, where N is the number of columns. |
| 195 |
Tenth Line |
Read the file line by line using a counter variable. When count equals 10, print the line and continue (or stop). |
A "Blind Crawler" that must count every step even if it only cares about step 10. |
Draw a ladder. Draw a climber touching every rung: 1, 2, 3... 10. Show the climber stopping at 10. |
sed or tail + head. |
"The Jump Shot." Tools like sed can address a specific line index directly using the underlying file system's stream. |
sed -n '10p' file.txt. The '-n' suppresses output, and '10p' prints only line 10. |
Draw a stack of 20 papers. Draw a single arrow pointing directly to the 10th paper from the top. |
$O(L)$ where L is the number of lines to reach the 10th. It stops immediately after line 10. |
Draw a line representing the file. Cut it off at the 10th mark to show that lines 11+ are never processed. |
Storing the entire file in an array and then accessing `arr[9]`. |
Visualize a "Streaming Buffer." Only the current line being counted is in memory at any time (O(1) space). |
| 196 |
Delete Duplicate Emails |
Select all distinct emails into a temporary table, drop the original table, and rename the temporary table to the original. |
A "Copy and Replace" diagram showing double the storage requirement during the operation. |
Draw Table A. Draw an empty Table B. Copy only unique rows from A to B. Erase Table A. |
Self-Join Delete. |
"The Elimination Row." Two copies of the same table are compared; for every pair of identical emails, the one with the larger ID is "struck through." |
Use DELETE p1 FROM Person p1, Person p2 WHERE p1.Email = p2.Email AND p1.Id > p2.Id. |
Draw two identical lists. Connect identical emails. For each connection, put an 'X' over the row with the bigger number. |
$O(N^2)$ conceptual comparisons, but optimized by the DB engine to $O(N \log N)$ or $O(N)$ with indexing. |
Draw a single pass through the index tree. Mark the duplicate leaves that are pruned. |
Full duplication of the dataset in permanent disk/memory space. |
Visualize in-place deletion using a single set of row pointers in the database buffer. |
| 197 |
Rising Temperature |
Nested loops: For every date, scan the entire table to find the record for "yesterday" and compare temperatures. |
An $O(N^2)$ cross-reference grid where every day checks every other day. |
Draw a calendar. For each day, draw a search line through all other days to find the one that is exactly 24 hours prior. |
Self-Join with DATEDIFF. |
"The Sliding Mirror." The table is joined with itself, but the "Join Condition" shifts the second table forward by exactly one day. |
Join Weather w1 and w2 on DATEDIFF(w1.recordDate, w2.recordDate) = 1. Filter where w1.temp > w2.temp. |
Draw the table. Draw a second copy shifted down by one row. Align the rows and circle pairs where the top row temperature is higher. |
$O(N \log N)$ if sorting by date is required, otherwise $O(N)$ with a date index. |
Draw a single timeline arrow. Highlight only the "peaks" that are higher than the point immediately to their left. |
Redundant temporary storage for every possible date pair comparison. |
Visualize the Join Buffer holding only two adjacent days' worth of data at a time. |
| 198 |
House Robber |
Brute force recursion: For every house, you have two choices—rob it (and move to house i+2) or skip it (move to i+1). |
A massive $O(2^N)$ binary decision tree showing the explosion of possibilities. |
Draw "House 1". Branch into "Rob" and "Skip". For each, branch again for "House 2". Show overlapping subproblems. |
1D Dynamic Programming (Iterative Tabulation). |
"The Safety Gap." A single array where each house's value is the max of (current + 2-houses-ago) or (1-house-ago). |
dp[i] = max(dp[i-1], dp[i-2] + currentHouse). Use two variables (prev1, prev2) to optimize space. |
Draw a row of houses with values. Below, draw a row of "Max Profit" boxes. Fill each box by looking at the two boxes immediately to its left. |
$O(N)$ linear time. Every house is visited once. |
Draw a single horizontal arrow through the array. Mark each box with a check as you compute its value from its neighbors. |
$O(2^N)$ recursive call stack depth leading to total memory exhaustion. |
Visualize two integer variables in $O(1)$ stack memory. No heap array required for the optimized version. |
| 199 |
Binary Tree Right Side View |
Level-order traversal (BFS) to visit every node, storing all nodes by level and picking the last element from each level list. |
A "Full Tree Scan" highlighting every node in the tree to extract just a few. |
Draw the tree. Draw horizontal lines for levels. Circle only the node at the far right of each line. Show the work to find the inner nodes. |
Recursive DFS (Root \rightarrow Right \rightarrow Left). |
"The Sun Shadow." Imagine light coming from the right; only the first node hit at each depth is visible in the shadow. |
Keep a max_depth_seen tracker. Recurse Right first. If current_depth > max_depth_seen, add node to result and update tracker. |
Draw the tree. Trace your pen from the root strictly down the right-most branches first. When you hit a depth you haven't marked, write the number down. |
$O(N)$ time. In the worst case (skewed tree), you visit all nodes once. |
Draw a single traversal path. Mark each depth index on a vertical ruler to show you only record one node per level. |
Queue storage for the widest level of the tree, potentially $O(N/2)$. |
Visualize the recursion stack depth $O(H)$. Space is $O(H)$, which is $O(\log N)$ for a balanced tree. |
| 200 |
Number of Islands |
Iterate through every cell. If it's land ('1'), start a BFS/DFS to find all connected land and count it as one island. Replace '1's with '0's as you go. |
A "Flood Fill" visualization where the scanner stops at every '1' to trigger a ripple effect. |
Draw a grid of 1s and 0s. Circle a '1'. Draw arrows to all adjacent '1's. Cross them out. Increment count. Repeat. |
DFS with In-place Sink (or BFS/Union-Find). |
"Sinking Islands." Each island is "sunk" (turned to '0') as soon as it is discovered, preventing the scanner from counting the same island twice. |
Nested loop for (r, c). If grid[r][c] == '1': increment islands, then run dfs(r, c) which turns all reachable land into '0'. |
Draw the grid. Use a highlighter to color one island at a time. Each time you finish a "color," add 1 to your total island count. |
$O(M \\text{times} N)$ time. Every cell is visited at most twice (once by the loop, once by the DFS). |
Draw the grid. Shade it in a single pass to show that once a cell is visited, it is never re-processed. |
Storing a "Visited" boolean array of size M \times N. |
Visualize the $O(M \\text{times} N)$ recursion stack in the worst case (all land), or $O(1)$ if the grid itself is used as the visited marker. |
| 201 |
Bitwise AND of Numbers Range |
Iterate from left to right, applying bitwise AND iteratively to an accumulator. |
Linear Timeline Line Graph: $O(N)$ where N is the difference between left and right. |
Draw a number line. Mark start and end. Draw an arrow connecting each integer, writing "T=1 unit" per step to show linear growth. |
Bit Manipulation (Common Prefix Match) |
Bit-shift Grid / Binary Tree Masking |
Write left and right in binary stacked vertically. Highlight the leftmost matching bits. Shift both right until they equal, then shift left. |
Draw two 32-bit arrays on top of each other. Box the identical bits on the left. Cross out differing bits on the right. Replace crossed out with 0s. |
Constant Time Block Diagram: $O(1)$ or $O(\log2(\text{max}_\text{val})$). |
Draw a fixed box containing 32 slots. Show a loop arrow that maxes out at 32 iterations, concluding T ≤ 32 (O(1)). |
Single Accumulator Box: Erase and rewrite the integer state inside a single square. |
Two Register Boxes: Show `m` and `n` shifting their bits simultaneously until equal. |
| 202 |
Happy Number |
Recursive sum of squares, using a Hash Set to detect infinite loops. |
Tree Diagram with Recursion Depth: $O(\log N)$ for sum computation step. |
Draw nested function calls as descending bubbles. Point an arrow back up if a cycle hits, labeling it "Space: $O(\text{Cycles})$". |
Floyd’s Cycle-Finding Algorithm (Fast & Slow Pointers) |
Directed Graph with a Loop (Lasso shape) |
Draw circles for each generated number with arrows connecting them. Trace one finger 1 step at a time, another 2 steps at a time until they touch. |
Draw nodes connected by arrows. If it loops to 1, draw a straight path. If it cycles, draw a literal circle of numbers. Put a "Tortoise" and "Hare" marker on the nodes. |
Two-track Timeline: Shows pointer meeting points to prove $O(\log N)$ time. |
Draw two horizontal tracks. Track A (slow) moves 1 unit. Track B (fast) moves 2 units. Draw a vertical line where Track B catches Track A. |
Hash Set Hash Table Diagram: Draw an expanding dictionary table appending new keys. |
Two Memory Cells: Draw exactly two variables, `slow` and `fast`. Erase and update them without expanding the box. |
| 203 |
Remove Linked List Elements |
Iterate linearly. Check `head.next.val`, handle head removal separately. |
Linear Step Function: $O(N)$ Time. |
Draw a chain of blocks. Put an 'X' over the ones being skipped. Draw a timeline axis underneath mapping N blocks to N seconds. |
Dummy Node + Linear Traversal |
Linked List Node-and-Pointer Diagram |
Point finger at `curr`. If next is target, erase `curr.next` arrow and redraw it pointing to `curr.next.next`. |
Draw rectangles with [Val|Next] split. Draw curved arrows for pointers. Cross out arrows and draw new ones bypassing the target values. |
Pointer Traversal Graph: $O(N)$ Time, $O(1)$ Space. |
Draw N nodes. Draw an arrow underneath showing 1 full pass (O(N)). Draw a small constant box for space. |
List nodes with no extra space. Just standard memory heap boxes. |
One extra "Dummy" memory box at the start, pointing to the head. Constant pointer re-assignments. |
| 204 |
Count Primes |
Iterate 1 to N, for each number iterate 1 to sqrt(i) to check divisibility. |
Area under curve (Integration style): $O(N \\text{cdot sqrt}(N)$). |
Draw a graph with N on the X-axis and sqrt(N) on the Y-axis. Shade the area under the curve to represent total operations. |
Sieve of Eratosthenes |
Array Striking / Sieve Grid |
Write numbers 1 to N in a grid. Circle 2, cross out all multiples. Circle 3, cross out multiples. Repeat up to sqrt(N). |
Draw a 1D tape. Shade out the multiples using different colors or stroke styles (e.g., / for 2s, for 3s). |
Harmonic Series Graph: $O(N \log(\log N)$). |
Draw a bar chart where bar heights shrink rapidly (N/2, N/3, N/5...). Show that the sum converges tightly near linear. |
Call stack for prime checking. No complex data structure, just loop variables. |
Boolean Array Tape: Draw a long sequence of [T|T|T...]. Erase T and write F as you hit multiples. |
| 205 |
Isomorphic Strings |
Nested loops or `.indexOf()` checks comparing first occurrences of characters. |
Quadratic Grid: $O(N^2)$ Time. |
Draw an N x N matrix. Shade half the matrix to represent nested loops checking `indexOf` every time. |
Two Hash Maps / Two Frequency Arrays |
Bipartite Graph Mapping |
Write String S on top, String T on bottom. Draw lines connecting S[i] to T[i]. If a line from a letter ever diverges to two different targets, it fails. |
Draw two columns of nodes (S characters left, T characters right). Draw directional arrows from left to right. Ensure 1-to-1 mapping. |
Parallel Array Traversal Line: $O(N)$ Time. |
Draw a timeline of length N. Show constant $O(1)$ lookups at each step, making a flat $O(N)$ line. |
Recreated strings in memory per iteration. |
Two 256-slot Array Grids. Write the mapped character's ASCII index into the slots to show $O(1)$ spatial mapping. |
| 206 |
Reverse Linked List |
Store all values in an array/stack, then create a new linked list or overwrite values. |
Array / Stack Fill & Empty Diagram: $O(N)$ Time, $O(N)$ Space. |
Draw N nodes going into a bucket (stack), then draw them coming out into a new chain. Size of bucket = $O(N)$. |
Iterative In-Place Reversal (Three Pointers: prev, curr, next) |
Sliding Window of Pointers |
Place three fingers on nodes. Move `next` ahead, flip `curr`'s arrow to point to `prev`, then shift `prev` and `curr` forward. |
Draw 4 boxed nodes. Draw arrows pointing right. Use a red pen to cross out the right arrow and draw a left arrow one by one. |
Flat Timeline: $O(N)$ Time, $O(1)$ Space. |
Draw a timeline showing 1 pass over N elements. Below it, draw a tiny fixed box labeled "Space: 3 Pointers". |
Stack Array Box: Draw an array growing vertically up to N elements. |
Three Fixed Pointer Cells: Draw 3 small boxes (`prev`, `curr`, `next`). Just erase and rewrite the node addresses inside them. |
| 207 |
Course Schedule |
Pure Backtracking / DFS without memoization to find cycles. |
Exploding Tree Diagram: Exponential Time $O(V!)$. |
Draw a massive branching tree that duplicates paths. Show the width growing uncontrollably. |
Topological Sort (Kahn's Algorithm / BFS) |
Directed Graph with In-Degree Array |
Cross out courses with 0 prerequisites. Reduce the prerequisite count of dependent courses. Repeat until all crossed out or stuck. |
Draw circles with directional arrows. Draw a small box next to each circle (in-degree). Erase arrows and decrement boxes to 0. |
Graph Traversal Bar: $O(V + E)$ Time. |
Draw a bar representing Vertices + Edges. Shade it in one continuous sweep to show linear traversal of the graph. |
Call Stack Tower: Draw an infinitely growing stack frame for unmemoized paths. |
Queue Array + In-Degree Array: Draw a queue sliding window and a fixed array of integers decrementing. |
| 208 |
Implement Trie (Prefix Tree) |
Store all words in a standard Hash Set or List. Check prefixes by iterating through all words. |
Linear Scan / String Compare Matrix: $O(N \cdot M)$. |
Draw a list of words. Draw a line scanning every character of every word to match a prefix. Area = N words * M length. |
Trie (Prefix Tree) Node Structure |
N-ary Tree Diagram |
Start at root. For each letter, travel down the corresponding branch. If branch is missing, word/prefix doesn't exist. |
Draw a root circle. Draw branching lines labeled with letters. Mark end-of-word nodes with a double circle or a star. |
Depth Bar / Pointer Drop: $O(M)$ Time where M is word length. |
Draw a vertical line descending exactly M steps. Show that time depends strictly on word length, not total words in dictionary. |
Hash Set Table: Draw a massive expanding table of full strings. |
Nested Array/Map Nodes: Draw a node as a box with 26 slots, some filled with pointers to other identical 26-slot boxes. |
| 209 |
Minimum Size Subarray Sum |
Nested loops: For every starting index, iterate forward to find the sum. |
Stepped Triangle Graph: $O(N^2)$ Time. |
Draw a right-angled triangle grid. Each row represents the inner loop getting shorter as the start index moves right. |
Sliding Window (Two Pointers) |
Elastic Band Window |
Stretch right finger until sum is reached. Then pull left finger in to shrink the window while sum is still valid. Record smallest width. |
Draw an array. Draw a bracket `[ ]` around the elements. Expand the right side `]`, then shrink the left side `[` like an inchworm. |
Two-Lane Track: $O(N)$ Time. |
Draw two parallel lines (Left and Right pointers). Both lines only move forward to the end, never backward. 2N total steps = $O(N)$. |
Variables per loop iteration, no complex structure. |
Two Pointer Variables + 1 Sum Accumulator: Draw 3 small boxes that update values as the window shifts. |
| 210 |
Course Schedule II |
Brute force DFS without state tracking (visiting, visited), risking infinite loops. |
Infinite Loop Graph: $O(V!)$. |
Draw a node tree that circles back on itself endlessly. Add a "stack overflow" explosion. |
Topological Sort (DFS with 3 States or Kahn's BFS) |
State-Colored Directed Graph |
Start at any unvisited node. Paint it GRAY (visiting). Go deep. When hitting dead end, paint BLACK (visited) and add to result list. |
Draw graph nodes. Shade them lightly (visiting). When a path finishes, shade them darkly (visited) and write the node in an array. |
V+E Sweep Area: $O(V + E)$ Time. |
Draw a shape representing Vertices and Edges. Shade it once to represent a single complete traversal. |
Unbounded Recursion Stack. |
3-State Array + Result Stack: Draw an array with [0, 1, 2] (White, Gray, Black) and a separate output array filling up backwards. |
| 211 |
Design Add and Search Words Data Structure |
Store words in a standard Array or List. Linearly scan and use Regex matching for the '.' character. |
Rectangular Matrix Scan: $O(M \cdot N)$ Time. |
Draw an Array of N words. Draw an arrow checking all M characters of every word against the search string. |
Trie (Prefix Tree) + DFS Backtracking for '.' |
Branching Trie Diagram |
Trace down the tree. For normal letters, go down one path. For '.', put a finger on ALL child nodes simultaneously and explore them. |
Draw a tree root with letters as edges. Draw a dashed circle enclosing all children of a node when a '.' is encountered to show parallel search paths. |
Depth-Limited DFS Tree: $O(M)$ or $O(26^M)$ worst case for all dots. |
Draw a vertical line descending M steps. Expand the line outward horizontally only when hitting a dot, showing the branch factor up to 26. |
Flat Array Box: Draw an array expanding linearly as new words are added. |
Nested Array/Map Nodes: Draw a node as a 26-slot box. Fill slots with arrows pointing to new 26-slot boxes. |
| 212 |
Word Search II |
DFS from every board cell for every individual word in the dictionary independently. |
Exploding Star Graph: $O(W \cdot M \cdot N \cdot 4^L)$. |
Draw a grid. Draw multiple huge, tangled branching trees (DFS) exploding out of every cell for each separate word. |
Trie + Backtracking DFS on Grid |
Grid Overlay with Trie Traversal |
Keep one finger traversing the 2D matrix (Up/Down/Left/Right) and the other finger simultaneously moving down the Trie. Prune path if Trie branch ends. |
Draw the matrix on the left, Trie on the right. Draw a path in the matrix. Draw a parallel path descending the Trie. X out the matrix path if Trie hits a dead end. |
Pruned DFS Tree: $O(M \cdot N \cdot 4^L)$ Time. |
Draw a 4-ary tree representing grid directions. Draw thick red 'X's cutting off branches early when the Trie doesn't contain that prefix. |
Call Stack Tower: Draw an infinitely deep stack frame for unpruned paths. |
Matrix + Trie Map: Draw a 2D array next to a Tree map. Draw `#` signs overwriting matrix cells temporarily for visited states. |
| 213 |
House Robber II |
Recursively try all subsets, verifying circular adjacency constraint at the end. |
Full Binary Tree: $O(2^N)$ Time. |
Draw a binary tree branching into 'Rob' and 'Skip' at every house. Cross out valid branches that accidentally robbed the first and last house. |
Dynamic Programming (Two Passes) |
Two Parallel 1D Tapes |
Run the standard House Robber sliding window on houses [0 to N-2]. Run it again on [1 to N-1]. Take the maximum of both final values. |
Draw two horizontal arrays. One crosses out the last element, one crosses out the first. Trace the max(curr+prev2, prev1) formula across both. |
Parallel Timelines: $O(N)$ Time, $O(1)$ Space. |
Draw two horizontal lines representing the two linear passes. Total time is 2N, simplifying to $O(N)$. |
Recursive Call Tree: Expanding bubbles of function calls. |
Two Sliding Windows: Draw two sets of tiny boxes (`rob1`, `rob2`) that slide across the array tapes, replacing values dynamically. |
| 214 |
Shortest Palindrome |
Iterate from N down to 1. Check if prefix of length i is a palindrome by reversing it. |
Stepped Triangle Graph: $O(N^2)$ Time. |
Draw an N-length string. Draw arrows checking the whole string. Move right bound in by 1, check again. Forms an $O(N^2)$ shaded triangle. |
KMP Partial Match Table (LPS Array) |
Prefix-Suffix Matching Ribbon |
Create string `s + "#" + reverse(s)`. Slide a matching window to find the longest matching prefix and suffix using the KMP LPS array logic. |
Write the combined string horizontally. Below it, draw the LPS integer array. Draw arrows jumping back to previous LPS values when characters mismatch. |
Linear Scan Line: $O(N)$ Time. |
Draw a single straight line from start to finish over the combined string of length 2N, proving linear traversal. |
Recreated Strings in Memory: Draw multiple long strings being instantiated per iteration. |
LPS Array Tape: Draw a single 1D array of integers tracking the longest proper prefix lengths. |
| 215 |
Kth Largest Element in an Array |
Standard Array Sort and return the element at index N - K. |
Merge Sort Tree / $O(N \log N)$ Curve. |
Draw a full array splitting down to single elements and merging back up fully sorted. Select the target index. |
Quickselect (Hoare's Partition) OR Min-Heap |
Partitioning Array Pivot |
Pick a pivot. Move smaller elements left, larger elements right. If pivot ends up at index N-K, return it. If less, search right half. If more, search left half. |
Draw an array. Circle a pivot. Draw arrows sorting elements around it. Draw a vertical line at the N-K index to show which half you discard. |
Converging Funnel: $O(N)$ Average Time. |
Draw a bar of length N. Below it, draw a bar of N/2, then N/4. The sum is a geometric series bounded by 2N = $O(N)$. |
Full Array Copy for sorting. |
In-Place Swap Array: Draw curved arrows showing elements swapping indices within the same boundary box. No extra space used. |
| 216 |
Combination Sum III |
Generate all possible subsets of numbers 1-9, then filter for length K and sum N. |
Full Binary Decision Tree: $O(2^9)$ Time. |
Draw a complete binary tree where every level (1 to 9) has a "take" or "skip" branch, exploding into 512 leaves. |
Backtracking with Early Pruning |
Pruned N-ary Tree |
Pick a number. If the sum exceeds N or the count exceeds K, immediately stop and draw an 'X'. Move back up the tree. |
Draw a root node. Branch out to valid next numbers. Red cross out branches where `current_sum > N` or `depth > K`. Circle leaves that perfectly match. |
Bounded Depth Tree: $O(9! / (9-K)$!) Time. |
Draw a tree that strictly stops at depth K. Show the branching factor decreasing (9, then 8, then 7...) at each step. |
Call stack array copying every possible combination. |
Single Mutable Array (Path): Draw one array box. Write numbers in, erase the last number when backtracking, and write the next. |
| 217 |
Contains Duplicate |
Nested loops comparing every single element with every other element. |
N x N Matrix Grid: $O(N^2)$ Time. |
Draw a grid with array elements on both axes. Shade in the upper triangle to represent the inner loop checking pairs. |
Hash Set (Seen Filter) |
Filter Funnel / Bouncer List |
Read left to right. Throw each number into a bucket. If the bucket already has that number, blow a whistle (return true). |
Draw a circle representing a Set. Read numbers one by one. Draw an arrow pointing into the circle. If the number is already inside, draw a collision spark. |
Flat Line: $O(N)$ Time. |
Draw a single straight arrow over an array to represent one continuous pass. |
Just loop index pointers, no extra space. |
Expanding Hash Set Table: Draw a box that grows, inserting unique numbers one by one. |
| 218 |
The Skyline Problem |
Array representing every single X-coordinate. Iterate over all buildings and update the max height at every point. |
Overlapping Area Fill: $O(N \cdot W)$ where W is max width. |
Draw a long number line. For each building, heavily shade the entire interval. Multiple overlapping shades represent redundant work. |
Sweep Line Algorithm + Max Heap / TreeMap |
Vertical Scan Line |
Slide a vertical ruler left to right across building edges. When hitting a left edge, add height to heap. Right edge, remove. Record max height changes. |
Draw overlapping rectangles. Draw vertical dashed lines ONLY at the start and end of buildings. Put a dot wherever the highest active line changes horizontally. |
Event Sorting Line: $O(N \log N)$ Time. |
Draw a timeline. Plot N dots on it (events). Show a logarithmic sorting curve above it representing the event processing overhead. |
Massive 1D Array spanning the entire X-axis domain. |
Max Heap Tree: Draw a pyramid of active heights. Cross out heights when buildings end, bubble up new maxes. |
| 219 |
Contains Duplicate II |
For each element, iterate through the next K elements to look for a match. |
Stepped Triangle: $O(N \cdot K)$ Time. |
Draw an array. Under the first element, draw a line covering K steps. Repeat for every element, overlapping heavily. |
Sliding Window + Hash Set |
Fixed-Width Sliding Frame |
Place a cardboard frame of width K over the array. Slide it right. Check if the newly entering number is already inside the frame. |
Draw an array. Draw a bracket `[` and `]` enclosing K elements. Shift both brackets right by 1. Keep a mini-list of what's inside the brackets. |
Linear Scan Line: $O(N)$ Time. |
Draw a straight line from start to end of the array, showing constant time $O(1)$ checks per step. |
Just loop pointers, $O(1)$ space. |
Hash Set Ring Buffer: Draw a circular array of size K. When full, overwrite the oldest element as the window moves. |
| 220 |
Contains Duplicate III |
Nested loops checking the next K elements to see if the absolute difference is <= T. |
Stepped Triangle: $O(N \cdot K)$ Time. |
Draw an array. For each element, draw an arrow to the next K elements, checking the math difference each time. |
Bucket Sort / Sliding Window |
Categorization Bins |
Divide numbers by (T+1) to assign a bucket. Slide a window of size K. If a bucket is already occupied, or adjacent buckets have close values, return true. |
Draw a row of open boxes (buckets). Read a number, map it to a box. Check if the box has an item, or if immediate left/right neighbor boxes have close items. |
Constant Bin Lookups: $O(N)$ Time. |
Draw a straight timeline. At each step, draw 3 small arrows (checking current, left, and right buckets) to show $O(1)$ work per element. |
Loop pointers, $O(1)$ space. |
Hash Map of Buckets: Draw a dictionary mapped by Bucket ID. Erase keys when the sliding window moves past K elements. |
| 221 |
Maximal Square |
For every '1' in the matrix, check every possible square size by iterating through its sub-grid. |
Volume Cube Graph: $O((M\cdot N)$^2) or $O(\text{min}(M,N)$^3). |
Draw a 2D grid. Pick one cell. Draw expanding squares from it. Shade the "volume" of checks for that cell. Repeat for all cells. |
Dynamic Programming (2D Table or 1D Optimized) |
Heatmap Propagation |
Each cell (i, j) looks at its top, left, and top-left neighbors. If M[i][j] is 1, take min(neighbors) + 1. The value represents the side of the largest square ending there. |
Draw the original grid. Below it, draw an empty grid. Fill values cell-by-cell. For a '1', look at three neighbors, find min, add 1. Circle the max value. |
Linear Matrix Sweep: $O(M \cdot N)$ Time. |
Draw a single pass arrow snaking through every cell once. Mark T=1 for each step. Total = M * N. |
Nested Loop Indices: Just coordinate pointers. |
DP Grid/Tape: Draw a 2D matrix (Space: $O(\text{MN})$) or a single row "rolling" array (Space: $O(N)$). |
| 222 |
Count Complete Tree Nodes |
Standard DFS or BFS traversal, visiting every single node and incrementing a counter. |
Node Population Count: $O(N)$ Time. |
Draw a binary tree. Color every node one by one. The total number of colored nodes is N. |
Binary Search on Leaf Nodes + Tree Height Properties |
Subtree Depth Comparison |
Check left height and right height. If equal, left subtree is full. If not, right subtree is full (but one level shorter). Use formula 2^h - 1. |
Draw a tree. Draw a vertical line down the leftmost and rightmost paths. If paths are equal length, it's a perfect triangle. Use math instead of counting. |
Logarithmic Descent: $O((\log N)$^2) Time. |
Draw a tree path. At each level, show that you "skip" half the tree. Draw a height line (log N) times a descent (log N). |
Recursion Stack: Draw a stack of depth H. |
Narrow Path Stack: Draw a single line of function calls descending to the leaf level only. |
| 223 |
Rectangle Area |
Impossible to brute force via "counting pixels" for large coordinates. The mathematical approach is the default. |
Coordinate Geometry Plot. |
Draw two overlapping rectangles on a Cartesian plane. Shade the union. |
Inclusion-Exclusion Principle (Area1 + Area2 - Overlap) |
1D Projection Overlap |
Project both rectangles onto the X-axis and Y-axis. The intersection area is (overlapX * overlapY). |
Draw two horizontal lines (X-segments). Mark where they overlap. Do the same for vertical lines (Y-segments). The box formed by the overlaps is the intersection. |
Constant Time Block: $O(1)$. |
Draw a single box. No loops, just arithmetic operations. T = constant. |
8 Variable Boxes for coordinates. |
Fixed Variables: Draw 4 "max/min" boxes to calculate the overlap boundaries. |
| 224 |
Basic Calculator |
Recursively solve every sub-expression found within parentheses. |
Nested Contextual Bubbles: $O(N^2)$ in worst case (e.g., many nested parens). |
Draw nested circles. Each circle represents a new string being parsed and evaluated from scratch. |
Stack-Based Single Pass with Sign Tracking |
State-Machine Ribbon |
Maintain a `result`, a `sign` (1 or -1), and a `stack`. When you hit '(', push current result/sign. When ')', pop and combine. |
Draw a ribbon of the expression. Draw a "Stack" bucket. Put a result and sign into the bucket when '(' appears. Pour it back out at ')'. |
Linear Timeline: $O(N)$ Time. |
Draw a single line scanning the string from left to right. Each character is processed once. |
Multiple String Buffers: Draw multiple copies of the input string being sliced. |
Value/Sign Stack: Draw a vertical stack containing only integers (previous results and signs). |
| 225 |
Implement Stack using Queues |
Use two queues. For every `push`, move all elements between queues to maintain order. |
Data Migration Diagram: $O(N)$ per push. |
Draw two circles (Queue 1, Queue 2). For one new item, show all previous items jumping from Q1 to Q2 and back. |
Single Queue Rotation |
Circular Queue Loop |
When pushing a new element, add it to the end of the queue. Then, for (size - 1) times, dequeue the front and enqueue it to the back. |
Draw a circle with a gap (Queue). Put a new number in. Draw arrows showing the existing numbers "stepping over" the new one to get behind it. |
Rotational Cost: $O(N)$ Push, $O(1)$ Pop. |
Draw a circular arrow showing N-1 operations inside a single Push block. |
Two separate Queue structures. |
Single Queue structure: Draw one continuous ring or line where the "Front" pointer moves cyclically. |
| 226 |
Invert Binary Tree |
Create a brand new tree and mirror nodes while copying them. |
Tree Duplication Graph: $O(N)$ Time and Space. |
Draw a tree on the left. Draw an empty tree space on the right. Draw arrows showing each node being "copied and flipped" into a new memory location. |
Recursive or Iterative In-Place Swap (DFS) |
Mirror Line Pivot Visualization |
Start at root. Use two fingers to swap the left and right pointers. Dive into the children and repeat until you hit leaf nodes. |
Draw a tree. Draw a vertical dashed line through the root. Use curved arrows to show the left child moving to the right and vice versa at every level. |
Traversal Path Area: $O(N)$ Time. |
Draw a single continuous line snaking around every node (Euler Tour). Each node is visited once, resulting in linear time. |
Full Parallel Tree: Draw two complete trees in memory. |
Recursion Stack / Queue: Draw a single vertical column for the call stack or a horizontal pipe for BFS. Space is $O(\text{Height})$. |
| 227 |
Basic Calculator II |
Iterate multiple times: first pass for all multiplication/division, second pass for addition/subtraction. |
Multi-Pass Scan Lines: $O(2N)$ -> $O(N)$. |
Draw a string. Draw an arrow scanning it once. Draw a second arrow scanning the "intermediate" string. Total length = 2 scans. |
Single-Pass Stack (Precedence Handling) |
Value Accumulator & Sign State |
Keep a `currentNumber`. When you hit an operator, apply the *previous* operator to the `currentNumber` and push to stack. Sum stack at end. |
Draw the expression. Draw a stack. When you see '*' or '/', pop the top, multiply/divide with current, and push back. Addition just pushes the number. |
Single Linear Pass: $O(N)$ Time. |
Draw one straight line across the string. Mark $O(1)$ for each stack operation to show $O(N)$ total. |
String Buffers: Draw multiple copies of substrings. |
Integer Stack: Draw a vertical tube containing only calculated numbers (e.g., [10, -5, 12]). |
| 228 |
Summary Ranges |
Nested loops: for each element, scan ahead to see where the continuous sequence ends. |
Staircase Step Plot: $O(N^2)$ worst case. |
Draw an array. Draw an arrow from index 0 checking all others. Then from index 1, etc. Area under the arrows is a triangle. |
Two-Pointer / Sliding Boundary |
Elastic Segment Highlighting |
Keep a `start` pointer. Move a `curr` pointer forward as long as `nums[i] + 1 == nums[i+1]`. When the chain breaks, record `start->curr`. |
Draw the array. Draw a bracket `[` at the start. Move the `]` right until the gap is > 1. Write the range. Jump `[` to the next element. |
Linear Skip: $O(N)$ Time. |
Draw a timeline. Show the pointer moving in one direction only, never backtracking. |
Array of substrings for every check. |
String Builder / Result List: Draw a list filling up with strings like "0->2" as the pointer completes a segment. |
| 229 |
Majority Element II |
Use a Hash Map to count frequencies of all elements, then filter those > N/3. |
Frequency Histogram: $O(N)$ Time, $O(N)$ Space. |
Draw a table. List every unique number and a tally mark for each occurrence. Table size grows with unique elements. |
Boyer-Moore Voting Algorithm (Extended) |
Duel Elimination (2 Candidates) |
Keep two candidates and two counters. If match, increment. If no match and counter is 0, replace. If no match and counters > 0, decrement both. |
Draw two boxes (Candidate A, Candidate B). For each new number, show it "attacking" the boxes if it doesn't match, or "reinforcing" if it does. |
Two-Pass Linear Scan: $O(N)$ Time. |
Draw two lines across the array. Pass 1 finds candidates. Pass 2 verifies them. 2N total operations = $O(N)$. |
Expanding Hash Table: Draw a grid that grows vertically as more unique numbers are seen. |
Fixed Variable Cells: Draw exactly 4 variables (`c1, v1, c2, v2`). No extra space regardless of N. |
| 230 |
Kth Smallest Element in a BST |
Perform a full In-order traversal, store in a list, and return list[k-1]. |
Flattening Transformation: $O(N)$ Time and Space. |
Draw a tree. Draw an arrow flattening it into a sorted horizontal 1D array. Space used = N nodes. |
Iterative In-order Traversal with Early Stop |
Left-Leaning Stack Probe |
Go as far left as possible, pushing to stack. Pop, decrement K. If K=0, you found it. Else, move to the right child and repeat. |
Draw a tree. Draw a stack on the side. Trace the path: "Down-left, pop, check K, one-step-right." Stop the moment K hits 0. |
Partial Tree Coverage: $O(H + K)$ Time. |
Draw a tree. Shade only the leftmost "spine" and the first K nodes visited. Show that the right half of the tree is never touched. |
Full Array Copy: Draw an N-slot array. |
Recursive/Iterative Stack: Draw a vertical stack of height H (log N for balanced trees). |
| 231 |
Power of Two |
Repeatedly divide the number by 2. If you hit a remainder that isn't 0 (until you reach 1), it's not a power of 2. |
Logarithmic Staircase: $O(\log N)$ Time. |
Draw a number N. Show it shrinking by half at each step until it hits 1. Count the steps. |
Bit Manipulation: (n > 0) \text{ and } (n \& (n-1) == 0) |
Binary Bit-Flip Highlight |
Write the number in binary. For powers of 2 (e.g., 8 is 1000), show that subtracting 1 (7 is 0111) creates a perfect mask where no bits overlap. |
Draw two 8-bit registers. Top: `1000`. Bottom: `0111`. Draw a vertical line showing that no '1's share a column. |
Instant Check: $O(1)$ Time. |
Draw a single dot or a small box labeled "CPU Clock Cycle." Show that no matter how big N is, the AND operation takes 1 step. |
Variable Stack: One integer being overwritten. |
Zero Extra Space: A single logic gate comparison. |
| 232 |
Implement Queue using Stacks |
On every `push` operation, move all elements from stack1 to stack2, push new element, and move everything back. |
Shuffling Bucket: $O(N)$ per Push. |
Draw two vertical buckets. Show N balls being moved one by one to a second bucket just to put one new ball at the bottom. |
Two Stacks (Amortized $O(1)$ - "Lazy Transfer") |
Inbound/Outbound Portals |
Always push to `s1`. Only when `pop` is called and `s2` is empty, pour all of `s1` into `s2`. This reverses the order once and for all. |
Draw two buckets side-by-side. Label one "Input" and one "Output". Draw an arrow showing a one-way "pour" only when "Output" is dry. |
Amortized Cost Analysis: $O(1)$ per operation. |
Draw N items. Show that each item is moved from s1 to s2 exactly once in its lifetime. Total moves = 2N, so cost per item = 2 (Constant). |
Two full stacks being emptied/refilled constantly. |
Two stacks where elements sit quietly until needed. Draw them as stable memory segments. |
| 233 |
Number of Digit One |
Iterate from 1 to N, convert each number to a string, and count the '1' characters. |
Char-by-Char Scan: $O(N \cdot \log N)$. |
Draw a long list of numbers. For each number, draw multiple boxes representing its digits. Shade every '1'. |
Digit DP / Mathematical Counting (Digit-by-Digit) |
Positional Weight Table |
Calculate '1's at the units place, then tens, then hundreds. Use formula based on `prefix`, `current digit`, and `suffix`. |
Draw N as a set of slots (e.g., [1][2][3][4]). For each slot, calculate the "1-cycles" based on the power of 10 for that position. |
Logarithmic Digit Pass: $O(\log10 N)$ Time. |
Draw a horizontal line with length equal to the number of digits in N. Show a single calculation per digit. |
String conversion memory: $O(\log N)$. |
Constant Math Variables: Draw 4-5 integer boxes (`count`, `i`, `prefix`, etc.). |
| 234 |
Palindrome Linked List |
Copy the linked list into an array and use two pointers to check if the array is a palindrome. |
Array Copy Mirror: $O(N)$ Time, $O(N)$ Space. |
Draw a linked list. Draw an array below it. Show arrows copying values. Draw two pointers at the ends of the array moving inward. |
Slow/Fast Pointers + In-Place Reversal of Second Half |
Tortoise and Hare Halfway Split |
Use Slow/Fast pointers to find the middle. Reverse the second half of the list. Compare the first half and the reversed second half. |
Draw a long chain. Use a 'S' and 'F' pointer. At the midpoint, draw the arrows of the second half turning 180 degrees. |
Linear Pass with Constant Space: $O(N)$ Time, $O(1)$ Space. |
Draw a timeline showing 3 passes: 1. Find Mid, 2. Reverse, 3. Compare. Total is $O(1.5N)$ -> $O(N)$. |
Array Buffer: Draw an N-slot array in memory. |
Pointer Manipulation: Draw three small boxes for the `prev`, `curr`, and `next` pointers during reversal. |
| 235 |
Lowest Common Ancestor of a BST |
Standard LCA for a general tree (DFS traversing all nodes and returning matches). |
Full Tree Search: $O(N)$ Time. |
Draw a tree. Show the search visiting every single leaf to find the nodes P and Q. |
BST Property Traversal (Value Comparison) |
Directional Tree Descent |
Compare `root.val` with P and Q. If both are smaller, go left. If both are larger, go right. If they split (one smaller, one larger), the root is the LCA. |
Draw a BST. Highlight P and Q. Draw a single path from root. At each node, ask "Are they both on my left? Both right? Or do I split them?" |
Height-Limited Descent: $O(H)$ Time. |
Draw a single line descending from the root to the LCA node. Show that the length of this line is at most the height of the tree. |
Recursion stack for full traversal: $O(H)$. |
Iterative Pointers: Draw a single `curr` pointer box that updates its address as it moves down the tree. Space: $O(1)$. |
| 236 |
Lowest Common Ancestor of a Binary Tree |
Find paths from root to P and root to Q, store in two lists, then find the last common node. |
Path Comparison Graph: $O(N)$ Time, $O(N)$ Space. |
Draw a tree. Draw two different colored paths from root to nodes. Circle the point where the colors diverge. |
Recursive Backtracking (Post-Order Traversal) |
Bubbling-Up Search Flags |
If current node is P or Q, return self. Ask left child and right child for results. If both return non-null, I am the LCA. If only one, pass it up. |
Draw a tree. Use arrows pointing UP from P and Q. Where two arrows meet in a single node, that's your LCA. |
Traversal Path Area: $O(N)$ Time. |
Draw a single continuous line snaking through every node. Each node is visited once, $O(N)$. |
Two separate path lists (Arrays) storing node references. |
Implicit Recursion Stack: Draw a vertical stack of height H. |
| 237 |
Delete Node in a Linked List |
Traverse from head to find the node, but since head isn't given, this is "impossible" via traditional traversal. |
Linear Scan: $O(N)$. |
Draw a chain. Draw a finger scanning from start to finish looking for the target. |
Value Overwriting / "Node Identity Theft" |
Leapfrog Pointer Swap |
You only have access to the node itself. Copy the value of the *next* node into the current node, then delete the next node. |
Draw two nodes. Write '5' and '1'. Copy '1' over '5'. Erase the 'Next' arrow of node 1 and point it to node 3. |
Instant Execution: $O(1)$ Time. |
Draw a single dot. No loops, just two assignment operations. |
No extra memory. |
No extra memory. |
| 238 |
Product of Array Except Self |
For each index, run a loop through all other indices and multiply them. |
N x N Matrix Grid: $O(N^2)$ Time. |
Draw a grid. For each row `i`, shade every cell except where `column == i`. Area = $O(N^2)$. |
Two-Pass Prefix/Suffix Accumulation |
Running Product Tapes |
Pass 1: Go left to right, storing products of everything before `i`. Pass 2: Go right to left, multiplying by everything after `i`. |
Draw an array. Draw a line moving right, accumulating products. Below it, draw a line moving left doing the same. |
Parallel Timelines: $O(N)$ Time. |
Draw two straight arrows (one left-to-right, one right-to-left). Both are linear. |
Temporary intermediate lists. |
In-Place Result Array: Draw one result array being updated twice without extra structures. |
| 239 |
Sliding Window Maximum |
For every window of size K, iterate through all K elements to find the maximum. |
Stepped Rectangles: $O(N \cdot K)$ Time. |
Draw an array. Draw a box of width K. Shift it N times. Shade the total area covered by the moving box. |
Monotonic Deque (Double-Ended Queue) |
Declining Staircase Deque |
As you slide the window, remove elements from the back of the deque that are smaller than the new element. Keep indices at the front. |
Draw an array. Below it, draw a small box (Deque). Write numbers in the box, but erase any smaller numbers behind a new larger number. |
Amortized Analysis: $O(N)$ Time. |
Draw N elements. Show that each element enters and leaves the deque exactly once. Total ops = 2N. |
List of maximums per window. |
Deque structure: Draw a small variable-sized box that rarely exceeds size K. |
| 240 |
Search a 2D Matrix II |
Linear scan through every row and every column. |
Full Matrix Area: $O(M \cdot N)$ Time. |
Draw a grid and shade every single cell one by one. |
Staircase Search (Top-Right Start) |
Pathfinding Elimination |
Start at top-right. If target is smaller, move left (entire column is bigger). If target is larger, move down (entire row is smaller). |
Draw a grid. Place a pen at the top-right corner. Draw a jagged "staircase" path moving only Left or Down until target is hit. |
Manhattan Distance Line: $O(M + N)$ Time. |
Draw a line from the top-right corner to the bottom-left. Show that the max distance is the sum of rows and columns. |
Just two loop indices. |
Two Pointer variables (`row`, `col`). Draw two small boxes updating their values. |
| 241 |
Different Ways to Add Parentheses |
Recursively split the string at every operator and calculate all combinations without caching. |
Catalan Number Tree: $O(C_n)$. |
Draw a branching tree where each node splits into two sub-trees. Show the number of leaves growing like the Catalan series. |
Divide and Conquer + Memoization (Top-Down DP) |
Recursive Sub-problem Map |
Identify repeated substrings (e.g., "3+5"). Compute once, store in a map, and reuse whenever that substring reappears in the recursion. |
Draw a "Memo Table" box. Draw arrows from different branches of the recursion tree pointing to the same result in the table. |
Memoized Recursion Tree: $O(N^3 \cdot 2^N)$ (approximate). |
Draw the recursion tree but shade out redundant branches to show they are "cut off" by the cache. |
Recursion Stack: Multiple copies of substrings being passed. |
Hash Map Cache: Draw a table with `Key: Substring` and `Value: List of results`. |
| 242 |
Valid Anagram |
Sort both strings (O(N \log N)) and compare them character by character. |
Sorting Log-Curve: $O(N \log N)$. |
Draw two messy lists of characters. Show them being reorganized into alphabetical order, then compared. |
Frequency Counter (Fixed-size Array) |
Alphabet Balance Scale |
Create an array of 26 zeros. Increment for characters in S, decrement for characters in T. If all zeros at the end, it's an anagram. |
Draw an array with 26 slots ('a' to 'z'). For S, draw '+' marks in slots; for T, draw '-' marks. Show they cancel each other out. |
Linear Scan: $O(N)$. |
Draw a single straight arrow passing through both strings once. |
Copying strings to arrays: $O(N)$. |
Fixed Bucket Array: Draw a static box of 26 integers. $O(1)$ space (ignoring alphabet size). |
| 243 |
Shortest Word Distance |
Nested loops: for every occurrence of word1, iterate through the entire array to find word2 and calculate distance. |
Pairwise Matrix: $O(N^2)$. |
Draw a grid where rows are indices of word1 and columns are indices of word2. Area represents the total comparisons. |
Two-Pointer Index Tracking (One Pass) |
Sliding Index Markers |
Traverse the array once. Keep two variables: `idx1` and `idx2`. Every time you update one, calculate the absolute difference with the other. |
Draw the array. Place two distinct markers (arrows) that move right. Whenever one moves, draw a bridge between them and label it with the distance. |
Linear Timeline: $O(N)$. |
Draw one arrow from index 0 to N-1. Note that distance is calculated in $O(1)$ during the move. |
Minimal storage (indices). |
Two Integer Variable Boxes: Draw `p1` and `p2` updating their values as they slide. |
| 244 |
Shortest Word Distance II |
Run the $O(N)$ algorithm from Q243 every time a query is made. |
Repeated Linear Scans: $O(Q \cdot N)$. |
Draw Q arrows, each scanning the entire array of length N. Total work = Q \times N. |
Hash Map Pre-processing + Two Pointers |
Grouped Index Lists |
Store indices of each word in a Map: `word: [indices]`. For a query, perform a two-pointer merge-style scan on the two sorted index lists. |
Draw a dictionary. For "apple", show a sorted list `[1, 5, 10]`. For "banana", show `[2, 12]`. Use two pointers to find the closest pair. |
Optimized Query: $O(K + L)$ where K, L are frequency of words. |
Draw two short timelines (the index lists). Show two pointers moving together to find the minimum gap. |
Original Array: $O(N)$. |
Map of Lists: Draw a table where each key points to a sorted integer array. Total space = $O(N)$. |
| 245 |
Shortest Word Distance III |
Nested loops, adding logic to handle cases where word1 and word2 are the same. |
Pairwise Matrix: $O(N^2)$. |
Draw a grid. If words are same, skip the diagonal. Complexity remains quadratic. |
One-Pass with Toggle/Previous Tracking |
Sequential State Tracker |
Traverse once. If words are different, use the Q243 logic. If same, update `idx1` with the previous `idx2` before updating `idx2` with the current. |
Draw the array. If word1 == word2, show the "Lead" pointer moving to "Follow" and the "Lead" taking the new index. Measure the gap. |
Single Linear Pass: $O(N)$. |
Draw a single pass arrow. Mark the distance calculation at each hit. |
Minimal storage. |
Two Index Variables: Draw `prev` and `curr` updating as the scan finds occurrences. |
| 246 |
Strobogrammatic Number |
Reverse the string, replace characters manually with their rotated versions, and compare with original. |
String Copy & Flip: $O(N)$. |
Draw the string. Below it, draw its reverse. Shade the memory block used to store the second string. |
Two Pointers + Mirror Map |
Symmetry Check Mirror |
Place pointers at both ends. Check if the pair (left, right) exists in a valid "rotation map" (e.g., 6-9, 8-8). Move inward. |
Draw the number. Draw two arrows pointing at opposite ends. Connect them with a line if they "match" rotated, then move arrows in. |
Single Linear Pass: $O(N)$. |
Draw one straight line above the number string, showing only half the string needs to be traversed (N/2). |
Full String Reversal: $O(N)$ extra space. |
Static Map + Pointers: $O(1)$ extra space beyond input. Draw a tiny 5-entry table (0,1,6,8,9). |
| 247 |
Strobogrammatic Number II |
Generate all numbers of length N using recursion and check each one for strobogrammatic properties. |
Full Permutation Tree: $O(10^N)$. |
Draw a tree starting with 10 branches at the first level, 10 at the next. It explodes exponentially. |
Recursive Backtracking (Inside-Out Construction) |
Expanding Core Bubbles |
Start with base cases (length 0 or 1). Recursively wrap the results with valid pairs (e.g., "6" + result + "9"). |
Draw an empty center. Draw layers around it like an onion, adding "1-1", "6-9", etc., at each step until length N. |
Pruned Recursive Tree: $O(5 \cdot 5^{(N/2-1)$}). |
Draw a tree that branches by 5 at each level. Show the depth is fixed at N/2. |
Massive List of all N-digit numbers. |
Recursive Call Stack: Draw a stack of height N/2, each frame holding a list of partial strings. |
| 248 |
Strobogrammatic Number III |
Generate all strobogrammatic numbers of length N, then filter based on the range [low, high]. |
Full Generation & Filter: $O(\\text{text}{\text{Count}})$. |
Draw a set of all generated numbers. Draw a circle around the subset that falls between low and high. |
Recursive Generation with Range Pruning |
Range Bound Check |
Generate numbers from length L_{low} to L_{high}. Immediately discard (stop branching) if the current prefix cannot possibly be in range. |
Draw a number line. Show the recursive generator "skipping" entire branches that are outside the range markers. |
Exponential-to-Linear Shift: $O(5^{N/2})$. |
Draw a branching tree where some paths end in an 'X' (out of range). |
Storage for all numbers of specific length. |
DFS recursion stack: $O(N)$. Draw a vertical stack frame indicating the depth is proportional to the number of digits. |
| 249 |
Group Shifted Strings |
Nested loops: compare every string with every other string by checking if their relative character differences match. |
All-Pairs Comparison: $O(N^2 \cdot L)$. |
Draw a matrix where every cell represents a comparison. If N=1000, the grid has 1,000,000 cells. |
Hash Map with Canonical Form Key |
Bucket Sorting by DNA-like Sequence |
Convert each string into a "diff-key" (e.g., "abc" \rightarrow "1,1"). Strings with the same key go into the same bucket. |
Draw strings on top. Below, draw buckets labeled with numeric sequences like "1,1,1". Draw arrows putting strings into buckets. |
Linear String Scan: $O(N \cdot L)$. |
Draw one arrow scanning through the list of strings. Each string is hashed once and moved to its bucket. |
Temporary comparison strings: $O(L)$. |
Grouped Hash Map: Draw a table where each Key is a diff-sequence and Value is a list of original strings. |
| 250 |
Count Univalue Subtrees |
For every node in the tree, start a new DFS to check if all its descendants have the same value. |
Quadratic Tree Scan: $O(N^2)$. |
Draw a tree. Draw a circle around every node. Inside each circle, draw a small sub-tree search. |
Post-Order DFS (Bottom-Up Flagging) |
Status Bubble-Up |
Each node asks its children: "Are you univalue and do you match my value?" If both say yes, the current node is univalue. Increment global counter. |
Draw a tree. Use green/red "up" arrows. Green means "I am univalue", Red means "I am not". A node is Green if its children are Green and match. |
Single Tree Traversal: $O(N)$. |
Draw a single continuous line snaking around the tree (Euler Tour), touching each node exactly once. |
Deep recursive calls for every node's sub-search. |
Implicit Recursion Stack: Draw a vertical stack of height H. Space: $O(H)$. |
| 251 |
Flatten 2D Vector |
Copy all elements from the 2D vector into a 1D list during initialization. |
Linear Block Allocation: $O(N)$ Space. |
Draw a big 2D grid. Draw an arrow pouring all contents into a single long horizontal line. Shade the entire horizontal line as "Memory Used." |
Two-Pointer Iterators (Row & Col) |
Coordinate Crosshair |
Maintain `i` (row) and `j` (column). `next()` returns `vec[i][j]` and moves `j`. If `j` hits the end of a row, skip empty rows and reset `j=0`, `i++`. |
Draw the 2D grid. Place a "Pen" at `(0,0)`. Draw a dotted path moving right, then jumping down to the start of the next non-empty row. |
State-Based Pointer Move: $O(1)$ average for `next`. |
Draw a timeline. Mark small dots for `next()` calls. Show that the work is just an index increment. |
Full 1D List: Draw an N-length array box in memory. |
Zero Extra Structure: Draw just two small integer boxes, `r` and `c`. |
| 252 |
Meeting Rooms |
Compare every meeting interval with every other meeting interval to check for overlaps. |
All-Pairs Overlap Matrix: $O(N^2)$. |
Draw N intervals on a timeline. Draw arcs connecting every interval to every other interval. Count the arcs. |
Sorting by Start Time |
Linear Timeline Sweep |
Sort meetings by start time. Iterate once; if any meeting starts before the previous one ends (S_{i+1} < E_i), return false. |
Draw a horizontal line (time). Plot intervals one above another. Check if the "end tail" of one bar passes the "start head" of the next. |
Sort & Scan: $O(N \log N)$ Time. |
Draw the $O(N \log N)$ sorting "funnel" followed by a single straight $O(N)$ arrow. |
None (just loops). |
Sorting Space: $O(1)$ or $O(\log N)$ depending on sort implementation. Draw a tiny recursion stack for Quicksort. |
| 253 |
Meeting Rooms II |
Check every possible number of rooms (1 to N) and see if the schedule is valid. |
Incremental Simulation: $O(N^2)$. |
Draw N timelines. For each new meeting, try placing it in Timeline 1, then 2, etc., until it fits. |
Min-Heap (Priority Queue) of End Times |
Dynamic Room Allocation (Chronological) |
Sort by start time. Use a Min-Heap to track when rooms become free. If start time \ge heap top, reuse room (pop and push new end). Else, add new room. |
Draw a vertical "Room" axis and horizontal "Time" axis. Draw bars. When a new bar starts, if no existing bar has ended, draw it on a new row. |
Heap-Efficient Sweep: $O(N \log N)$. |
Draw the timeline. Above it, draw a "Heap" tree that changes shape as you move across the time axis. |
N/A. |
Heap Structure: Draw a binary tree containing end-times. Max size of tree = Max concurrent meetings. |
| 254 |
Factor Combinations |
Trial division for all numbers up to N, then recursively find all combinations of those factors. |
Explosive Decision Tree: $O(2^N)$. |
Draw a tree where each node is a division. Branching factor is the number of divisors. |
Backtracking with Path Tracking |
Recursive Divisor Tree |
Start from i=2. If n \% i == 0, add i to path and recursively solve for n/i, starting the next loop from i to avoid duplicates. |
Draw N at the top. Branch out to its factors. For each factor, branch out again. Highlight paths that end in a "1" or prime factor. |
Pruned Search Space. |
Draw a tree that gets significantly narrower as you go deeper (because the target number N shrinks rapidly). |
Recursion stack of all paths. |
Mutable Path List: Draw a single array. Add factor, recurse, remove factor (pop). $O(\log N)$ space. |
| 255 |
Verify Preorder Sequence in BST |
Reconstruct the BST from the preorder sequence and check if it’s valid. |
Full Reconstruction: $O(N)$ Time & Space. |
Draw an array. Draw the logic of building a tree node-by-node. Shade the memory used for the tree objects. |
Monotonic Stack (Simulation of DFS) |
Lower-Bound Barrier |
Traverse array. If current < last, it's a left child (push to stack). If current > last, it's a right child (pop to find its parent, update "low" bound). |
Draw the array. Draw a horizontal "Floor" line. As you pop from the stack, the floor rises. If any future number is below the floor, fail. |
Single Scan: $O(N)$ Time, $O(N)$ or $O(1)$ Space. |
Draw a straight arrow through the array. Note the $O(1)$ work per element if using the input array as the stack. |
Tree Objects: Draw many circles with "left" and "right" pointers. |
Stack / In-place Array: Draw a single 1D array where a pointer tracks the "top" of the stack. |
| 256 |
Paint House |
Recursive DFS exploring all possible color choices for N houses with no adjacent same colors. |
Tertiary Decision Tree: $O(3 \cdot 2^{N-1})$. |
Draw a root node splitting into 3 branches (R, G, B). Each subsequent level branches into 2. Show the tree width doubling at each level. |
Dynamic Programming (In-place or 1D) |
Cost Accumulation Matrix |
For house i, the cost to paint it Red is its own cost + min(\text{Green cost house } i-1, \text{Blue cost house } i-1). Repeat for all 3 colors. |
Draw a table with 3 columns (R, G, B). For row i, draw arrows from the two minimum values in row i-1 to the current cell. |
Linear Matrix Sweep: $O(N)$ Time. |
Draw a vertical arrow going down the 3-column table. Each step takes 3 comparisons (constant time). |
Recursion stack: $O(N)$ depth. |
Rolling Row: Draw exactly two 1x3 arrays. One for "Previous House Costs" and one for "Current House Costs." |
| 257 |
Binary Tree Paths |
Traverse the tree and for every leaf found, perform a full back-traversal to the root to build the string. |
Repeated Path Ascent: $O(N^2)$ (in skewed trees). |
Draw a tree. For every leaf, draw an arrow back up to the root. The sum of all arrows represents the quadratic complexity. |
DFS with Backtracking / String Builder |
Pre-Order Traversal Ribbon |
Pass the current path string down to children. When a leaf is reached, add the string to the result list. |
Draw a tree. Trace a line down the leftmost path. At each node, write the path "1->2". When moving back up, erase/pop the last node from your mental path list. |
Node-Visit Timeline: $O(N)$ Time. |
Draw a single line visiting every node once. Mark $O(L)$ for string creation at leaves (L = path length). Total is $O(N)$ nodes. |
Multiple full string copies in memory. |
Recursion Stack + Path List: Draw a vertical stack where each frame holds a reference to the same growing path array. |
| 258 |
Add Digits |
Loop while number \ge 10: convert to string, sum digits, and repeat. |
Iterative Reduction: $O(\log N)$. |
Draw N. Draw a smaller box below it for the first sum, then an even smaller box. Count the levels of reduction. |
Digital Root (Mathematical Modulo 9) |
Clock Arithmetic (Circle of 9) |
The result is 1 + (n-1) \% 9 for n > 0. It follows a repeating pattern of 1-9. |
Draw a circle with 9 points (1 to 9). Show that adding digits is equivalent to "spinning" around this circle. |
Constant Step: $O(1)$ Time. |
Draw a single point. No loops, no recursion. Just one math formula. |
String buffers for digit extraction. |
Zero Extra Space: A single register for the math result. |
| 259 |
3Sum Smaller |
Triple nested loops: for every i, j, k, check if nums[i] + nums[j] + nums[k] < target. |
Cubic Volume: $O(N^3)$. |
Draw a 3D cube. Shade the volume. Each cell in the cube represents one triplet check. |
Sort + Two Pointers (Left/Right) |
Scanning Boundary Pointers |
Sort the array. For each i, set left=i+1, right=N-1. If sum < target, all elements between left and right also satisfy the condition (count += right - left). |
Draw a sorted array. Circle index i. Place two arrows (L and R). If sum is small, draw a bracket covering everyone between L and R to show they are all counted instantly. |
Quadratic Scan: $O(N^2)$ Time. |
Draw a sorted array. Show the outer loop N times and the inner pointer move N times. Area = Triangle (N^2/2). |
No extra memory. |
Sorting Space: $O(\log N)$ or $O(1)$. Draw the Quicksort recursion stack. |
| 260 |
Single Number III |
Use a Hash Map to count occurrences. Return keys with value 1. |
Frequency Map: $O(N)$ Time, $O(N)$ Space. |
Draw a table. List every number. Increment tallies. Shade the table to show $O(N)$ space usage. |
Bit Manipulation (XOR + Rightmost Set Bit) |
Bitmask Partitioning |
XOR all numbers to get A \oplus B. Find the rightmost set bit in the result (this bit is different between A and B). Split array into two groups based on this bit; XOR each group. |
Draw the array. XOR everyone into one "Blob". Find a bit like `0010`. Separate the array into two piles: those with that bit and those without. XOR each pile to find A and B. |
Two-Pass Linear Scan: $O(N)$ Time. |
Draw two horizontal arrows across the array. Pass 1 finds the mask. Pass 2 finds the two numbers. |
Full Map Storage: Draw an expanding dictionary. |
Register Boxes: Draw exactly two variables, `x` and `y`, to hold the results. $O(1)$ extra space. |
| 261 |
Graph Valid Tree |
Check all possible paths to ensure no cycles and every node is reachable. |
Adjacency Matrix Scan: $O(V^2)$. |
Draw a grid V \times V. Shade every cell to represent checking every possible edge connection. |
Union Find with Path Compression |
Forest Disjoint-Set Clusters |
For each edge (u, v), check if find(u) == find(v). If yes, cycle detected. Otherwise, union them. Finally, check if total edges == n-1. |
Draw nodes. For each edge, draw a circle around the nodes to "group" them. If an edge connects nodes already in the same circle, draw a "Lightning Bolt" for cycle. |
Inverse Ackermann Curve: $O(E \cdot \\text{alpha}(V)$). |
Draw a line that is almost perfectly flat (near constant). Label it \alpha(N) to show it's basically $O(1)$ per operation. |
Full Adjacency Matrix: $O(V^2)$ storage. |
Parent Array: Draw a single 1D array where each index points to its representative. $O(V)$ space. |
| 262 |
Trips and Users (Algo Equivalent) |
Nested loops: For each trip, search the Users table to check if Client/Driver are banned. |
Nested Loop Join: $O(T \cdot U)$. |
Draw two lists (Trips and Users). Draw an arrow from every trip to every user. The "density" of arrows shows the $O(T \cdot U)$ complexity. |
Hash Join / Hash Map Filtering |
Filter-Map Pipeline |
Pre-process Users into a Set of "Banned IDs". Iterate through Trips once, filtering out any row where the Client or Driver ID exists in the Banned Set. |
Draw a small "Banned" box. Draw a "Trip" conveyor belt. As trips pass, a "Gatekeeper" checks IDs against the box and tosses out matches. |
Linear Split: $O(T + U)$ Time. |
Draw a timeline for U (building the hash set) and a separate timeline for T (streaming data). Total = sum of parts. |
None (In-memory scan). |
Hash Set: Draw a small hash table containing only Banned IDs. Space: $O(U)$. |
| 263 |
Ugly Number |
Attempt to find all prime factors of the number and check if any are > 5. |
Factorization Tree: $O(\\text{sqrt}{N})$. |
Draw N at top. Draw branches for every divisor. The tree depth/width represents the square root scan. |
Iterative Division (Prime Squeezing) |
Division Funnel |
Repeatedly divide N by 2, then 3, then 5 as long as the remainder is 0. If the final value is 1, it's ugly. |
Draw the number N inside a funnel. Mark "2, 3, 5" as the exit holes. If N can pass through completely to become "1", it succeeds. |
Logarithmic Reduction: $O(\log N)$. |
Draw N shrinking rapidly. Each step is a division, showing the "Height" of the operations is \log N. |
Factor list storage. |
Zero Extra Space: Just the input variable modified in-place. |
| 264 |
Ugly Number II |
Check every integer 1, 2, 3... using the Q263 method until the n^{th} ugly number is found. |
Linear Scan with Log Check: $O(M \cdot \log M)$ where M is the n^{th} ugly number. |
Draw a long number line. Put a mark on "1, 2, 3, 4, 5, 6, 8...". Show the gap between marks getting wider and wider. |
Three Pointers (Dynamic Programming) |
Parallel Multiplier Tapes |
Keep three pointers (p2, p3, p5). Next ugly number is min(ugly[p2]*2, ugly[p3]*3, ugly[p5]*5). Increment the pointer(s) that produced the min. |
Draw an array `U`. Place 3 fingers labeled "x2", "x3", and "x5". Move them forward independently like a race to generate the next value. |
Single Pass: $O(N)$ Time. |
Draw a straight timeline of length N. Each step involves exactly 3 multiplications and 1 comparison. |
N/A. |
DP Array: Draw a 1D array of size N that stores previously computed ugly numbers. |
| 265 |
Paint House II |
Recursive DFS checking all color combinations for N houses with K colors. |
Explosive Branching: $O(K \cdot (K-1)$^{N-1}). |
Draw a tree where each node has K-1 branches. Level 1 has K, level 2 has K(K-1). Show it filling the page instantly. |
DP with Minimum Tracking (Two-Minima Optimization) |
Rolling Min-State |
Instead of checking all previous K-1 colors, track the `min1` and `min2` costs of the previous house. If current color matches `min1`, use `min2`. Else, use `min1`. |
Draw a row of K costs. Highlight the two smallest numbers. For the next row, use these two "cached" values instead of rescanning the row. |
Reduced Matrix Scan: $O(N \cdot K)$ Time. |
Draw an N \times K grid. Show that each cell only looks at a "Global Min" box from the previous row instead of the whole row. |
Full N \times K recursion stack. |
Two Smallest Value Boxes: Draw exactly two variables, `m1` and `m2`, per row. Space: $O(1)$ extra (if in-place). |
| 266 |
Palindrome Permutation |
Generate all possible permutations of the string and check if any of them are palindromes. |
Factorial Explosion: $O(n!)$. |
Draw a root node. Branch it n times, then (n-1) times. Label it "The Permutation Tree of Doom." |
Frequency Counting (Odd Count Limit) |
Toggle-Switch Logic |
Iterate through chars. Add to a set if not present; remove if it is. At the end, the set size must be \le 1. |
Draw a string. Below it, draw a small box (Set). For each char, "drop" it in or "kick" it out. Check if 0 or 1 item remains. |
Linear Scan: $O(n)$. |
Draw a single straight line through the string. Mark each step as $O(1)$ set operation. |
Permutation List: Draw a massive pile of strings. |
Small Hash Set: Draw a box that holds at most 26 unique characters. |
| 267 |
Palindrome Permutation II |
Generate all permutations and filter out non-palindromes using a helper. |
Factorial Tree: $O(n!)$. |
Draw a tree where leaves are full strings. Shade the 99% of leaves that aren't palindromes to show wasted work. |
Backtracking (Half-String Construction) |
Mirror-Image Generation |
Count frequencies. If valid (from Q266), take half of each even-count char and generate all permutations. Mirror them around the odd char. |
Draw a "Half-Bank" of letters. Draw a backtracking tree for just those letters. For each leaf, draw a "Mirror" line and reflect it. |
Reduced Permutation: $O((\\text{frac}{n}{2})$!). |
Draw a tree for length n vs a tree for length n/2. The n/2 tree is significantly smaller. |
Massive String Array: $O(n \cdot n!)$. |
Recursion Stack: Draw a vertical stack of height n/2. Each frame holds a partial string. |
| 268 |
Missing Number |
Sort the array and check if `nums[i] != i`. |
Sorting Slope: $O(n \log n)$. |
Draw a messy list of numbers. Draw an arrow showing them being rearranged into a line. |
Gauss' Sum Formula OR XOR Gates |
Balance Scale / Bit Cancellation |
Math: ExpectedSum - ActualSum. XOR: XOR all indices and all numbers; the result is the missing one. |
Draw two lists: 0 to n and the input array. Use a "Zap" line to connect identical numbers. The one without a partner is the answer. |
Single Pass: $O(n)$. |
Draw a single arrow across the array. No extra data structures, just an accumulator. |
Sorted Copy: Draw a second array of size n. |
Accumulator Variable: Draw one single integer box (`sum` or `res`). |
| 269 |
Alien Dictionary |
Check every possible alphabet permutation (26!) against the word list until one works. |
Alphabet Permutation: $O(26! \cdot L)$. |
Draw 26 letters. Show an infinite loop trying to arrange them. It’s a cosmic-scale nightmare. |
Topological Sort (Kahn's or DFS) |
Directed Acyclic Graph (DAG) |
Compare adjacent words to find the first differing char (edge: a \to b). Run BFS on nodes with 0 in-degree. |
Draw letters as circles. Draw arrows based on word order (e.g., "wrt" < "wrf" means t \to f). Cross out nodes with no arrows pointing to them. |
Edge-Vertex Scan: $O(C)$ where C is total chars. |
Draw a graph. Shade each edge and vertex once to represent the $O(V+E)$ traversal. |
List of all 26! strings. |
Adjacency List + In-degree Array: Draw a map where letters point to lists of other letters. |
| 270 |
Closest BST Value |
In-order traversal to a list, then find the value with the minimum absolute difference. |
Full Traversal: $O(n)$. |
Draw a tree. Show an arrow visiting every single node, even if they are obviously too far away. |
Binary Search (Iterative Descent) |
Descending Path Funnel |
Compare target with `root.val`. Update `closest`. If `target < root.val`, go left; else go right. Stop at leaf. |
Draw a tree. Trace a single path from root to a leaf. At each node, write the current "Best Distance" in a box. |
Height-Limited: $O(h)$. |
Draw a single line down the tree. The length is proportional to the tree's height (log n if balanced). |
Full Node Array: Draw an array of size n. |
Constant Pointers: Draw two variables: `closest` and `curr_node`. |
| 271 |
Encode and Decode Strings |
Join strings using a special character (e.g., ",") and split them later. (Fails if strings contain the delimiter). |
Flat Scan: $O(N)$. |
Draw a series of boxes. Put a "," between them. Show how a box containing a "," breaks the logic. |
Chunked Transfer (Length + Delimiter) |
Encoded Frame Ribbon |
Prepend each string with its length and a '#' (e.g., "5#hello"). When decoding, read the number, skip the '#', and take exactly that many chars. |
Draw "hello", "hi". Transform into "5#hello2#hi". Draw a sliding window that reads '5', jumps over '#', and grabs 5 characters. |
Single Linear Pass: $O(N)$. |
Draw a timeline. Show the "Jump" logic where you skip the content and only process headers to find indices. |
Full String Buffer: $O(N)$. |
Zero Extra Structure: Logic resides in the string format itself. Draw a single long string buffer. |
| 272 |
Closest BST Value II |
Perform an In-order traversal to a list, then sort the list by distance to the target (O(N \log N)). |
Sorting Slope: $O(N \log N)$. |
Draw a tree. Flatten it into an array. Show a sorting algorithm moving elements around based on a math formula. |
Two Stacks (Predecessor & Successor) |
Clamped Range Expansion |
Use two stacks to find the closest element. One stack tracks nodes smaller than target, one tracks larger. Compare tops and "pop" the closest. |
Draw a BST. Draw two vertical tubes (Stacks). Fill them as you descend to the target. "Pop" values from the tubes like a dual-ended dispenser. |
Height-Limited: $O(H + K)$. |
Draw a path from root to target (Height H). Show K operations pulling from that path. Total is H+K. |
Full Array of Nodes: $O(N)$. |
Two-Stack Buffers: Draw two vertical stacks of max height H. Space: $O(H)$. |
| 273 |
Integer to English Words |
Massive `if-else` or `switch` block for every number from 1 to 2 Billion. |
Infinite Tree: $O(\\text{text}{\text{Impossible}})$. |
Draw a decision tree that never ends. Label it "The Hardcoded Nightmare." |
Recursive Triplet Grouping (Base 1000) |
Chunk Processing Pipeline |
Process the number in groups of three (Thousands, Millions, Billions). Solve for a 3-digit number once and apply the scale word. |
Draw "1,234,567,891". Draw brackets around each 3-digit group. Solve "891", then add nothing. Solve "567", add "Thousand", etc. |
Logarithmic Digit Pass: $O(\log_{10} N)$. |
Draw a line with 10 slots (max digits in 2B). Show the recursion depth is max 4 (for Billions, Millions, Thousands, Units). |
Manual Mapping Table. |
Recursive Stack: Draw 4 frames. Each frame holds the string result of a 3-digit segment. |
| 274 |
H-Index |
Sort the array and check for the point where `citations[i] >= i + 1`. |
Sorting Curve: $O(N \log N)$. |
Draw a bar chart of citations. Show them being reordered from highest to lowest. |
Bucket Sort (Counting Citations) |
Frequency Histogram |
Create buckets from 0 to N. Count how many papers have X citations. Sum from the back until the sum exceeds the bucket index. |
Draw boxes labeled 0, 1, 2... N. Place "papers" into boxes based on citation count. Scan right-to-left. Stop when papers \ge index. |
Linear Scan: $O(N)$. |
Draw a horizontal arrow scanning the original array (Pass 1) and then the buckets (Pass 2). Total = 2N. |
Sorted Copy: $O(N)$. |
Fixed Bucket Array: Draw an array of size N+1 in memory. |
| 275 |
H-Index II |
Linear scan since the array is already sorted (O(N)). |
Linear Pass: $O(N)$. |
Draw a sorted bar chart. Draw an arrow starting from the beginning checking every bar. |
Binary Search on H-Boundary |
Midpoint "Flip-Flop" search |
Calculate `mid`. If `citations[mid] >= n - mid`, the H-index is at least `n - mid`. Search left to find a larger h; else search right. |
Draw a sorted array. Point to the middle. If citations there are high, draw an arrow indicating "H-index might be bigger, look left." |
Logarithmic Search: $O(\log N)$. |
Draw a line. Divide it in half, then half again. Show that we only visit 3-4 points for an array of size 10. |
None (In-place). |
Three Pointers: Draw `low`, `high`, `mid`. Zero extra storage. |
| 276 |
Paint Fence |
Recursively explore all possible color assignments (k^n), checking if more than two adjacent posts have the same color. |
Exponential Branching Tree: $O(k^n)$. |
Draw a tree starting with k branches. Each level multiplies by k. Label it "The Unconstrained Combinatorial Explosion." |
Dynamic Programming (Two-State: Same/Different) |
Decision State Table |
Track `diff` (current color different from previous) and `same` (current color same as previous). `new_diff = (same + diff) * (k-1)`; `new_same = diff`. |
Draw two rows: "Same" and "Diff". For each post, draw arrows showing `new_same` comes from previous `diff`, and `new_diff` comes from the sum of both. |
Linear Pass: $O(n)$. |
Draw a horizontal timeline of length n. Each step consists of two additions and a multiplication. $O(n)$ total. |
Recursion stack: $O(n)$. |
Two Variables: Draw exactly two integer boxes, `same` and `diff`. Space: $O(1)$. |
| 277 |
Find the Celebrity |
Check every person against everyone else using N^2 queries to `knows(a, b)`. |
N \times N Query Grid: $O(n^2)$. |
Draw a grid of all people. Shade every cell to represent asking "Does Person A know Person B?" for every pair. |
Greedy Elimination (Two Pointers) |
Tournament Elimination Bracket |
Assume Person 0 is the celebrity. If 0 \text{ knows } 1, 0 cannot be the celebrity, so candidate becomes 1. Continue until only one candidate remains. Verify the candidate at the end. |
Draw n circles. Use a "Pointer" finger to jump from one to the next based on the `knows` result. The person you end on is the only "possible" star. |
Linear Query Scan: $O(n)$. |
Draw a line of n people. Show the pointer moving exactly n times to find the candidate, plus one pass to verify. Total: $O(3n)$ \rightarrow $O(n)$. |
None (just loops). |
Single Integer Variable: Draw a box labeled `candidate`. |
| 278 |
First Bad Version |
Linear scan from version 1 to n, calling `isBadVersion(i)` until it returns true. |
Linear Timeline: $O(n)$. |
Draw a long line. Put a "check" mark on every single version until you hit the first "X". |
Binary Search (Leftmost Boundary) |
Halving Search Range |
Check `mid`. If `isBadVersion(mid)` is true, the first bad version could be `mid` or earlier; move `high = mid`. If false, move `low = mid + 1`. |
Draw a number line. Draw a bracket covering the whole range. Move the brackets inward by halves until they meet at a single point. |
Logarithmic Search: $O(\log n)$. |
Draw a line. Divide it into 2, then 4, then 8. Show that for 1,000,000 versions, you only ask about 20 times. |
None. |
Two Pointers: Draw `left` and `right`. Space: $O(1)$. |
| 279 |
Perfect Squares |
Recursive backtracking: for n, try subtracting every perfect square i^2 < n and solve for the remainder. |
Exploding Recursive Tree: $O(n^{\\text{sqrt}{n}})$. |
Draw a tree where each node n has \sqrt{n} branches. The tree is extremely wide and deep. |
Dynamic Programming (1D) or BFS |
Staircase Fill (BFS Layers) |
DP: `dp[i] = min(dp[i - j*j] + 1)` for all j^2 \le i. BFS: Nodes are the remaining sum. Level 0 is n. Level 1 are n - j^2. First time you hit 0 is the answer. |
Draw an array from 0 to n. For each index i, draw arrows jumping back to i - 1, i - 4, i - 9... and find the smallest value there + 1. |
Weighted Graph Scan: $O(n\\text{sqrt}{n})$ Time. |
Draw an array of length n. For each element, draw \sqrt{n} check-arrows. Total complexity is the area n \times \sqrt{n}. |
Recursion stack without memoization. |
DP Array: Draw a 1D array of size n+1 in memory. Space: $O(n)$. |
| 280 |
Wiggle Sort |
Sort the array $O(n \log n)$ and then swap adjacent pairs (e.g., i=1 and i=2, i=3 and i=4). |
Sort-and-Swap: $O(n \log n)$. |
Draw a messy array. Show it becoming sorted. Then show pairs of elements swapping. |
One-Pass Greedy Swapping |
Local Wave Condition |
Iterate once. If i is odd and nums[i] < nums[i-1], swap. If i is even and nums[i] > nums[i-1], swap. |
Draw an array. Draw a zigzag line above it. Check if the current number follows the zigzag relative to its neighbor. If not, swap them. |
Single Scan: $O(n)$. |
Draw a single arrow moving left to right. Each swap is $O(1)$. Total: $O(n)$. |
Sorted Array Copy: $O(n)$. |
In-Place Swap: Draw the original array with no extra structures. Space: $O(1)$. |
| 281 |
Zigzag Iterator |
Copy all elements from both lists into a single 1D list in a zigzag fashion during the constructor. |
Pre-processing Block: $O(N_1 + N_2)$. |
Draw two separate lists. Draw arrows pouring them into a single long horizontal box. Shade the whole box as "Space Used." |
Queue of Iterators |
Cycling Conveyor Belt |
Store active iterators in a Queue. `next()` polls the front iterator, gets its value, and if it still has elements, offers it back to the end of the queue. |
Draw a circular queue. Put "List1 Iterator" and "List2 Iterator" inside. Draw an arrow showing one popping out to give a value, then jumping back to the end of the line. |
Lazy Evaluation: $O(1)$ per `next()`. |
Draw a timeline with single dots for each call. No data is moved until requested. |
Full 1D Copy: Draw an array of size N_1 + N_2. |
Active Iterators: Draw 2 small boxes holding only the current index/pointer for each list. |
| 282 |
Expression Add Operators |
Generate every possible string by inserting '+', '-', or '*' between every digit and evaluate each using a calculator. |
Operator Permutation Tree: $O(4^N)$. |
Draw a root node. Branch into 4 at every level (for each possible operator/no-operator). It becomes a dense web almost instantly. |
Backtracking with Evaluation-on-the-fly |
Recursive State Machine |
Recursively build the string. Keep track of current `value` and the `previousOperand` (to handle '*' precedence by reversing the previous addition). |
Draw the recursion tree. In each node, write three values: `current_sum`, `last_value`, and `index`. Show the multiplication branch "undoing" the last addition. |
Pruned Backtracking: $O(4^N)$ (Still high, but avoids the $O(N)$ string evaluation cost). |
Draw the same dense tree but note that evaluation happens in $O(1)$ at each node rather than a separate pass. |
Massive String List: Draw a mountain of string objects. |
String Builder / Recursion Stack: Draw a vertical stack of height N. Use one shared character array for the path. |
| 283 |
Move Zeroes |
Create a new array. Copy all non-zero elements over, then fill the remainder of the new array with zeros. |
Double Array Copy: $O(N)$ Time, $O(N)$ Space. |
Draw the original array on top and a blank array below. Draw arrows for each non-zero. Shade the second array. |
Two Pointers (Read & Write) |
Snowball / Sliding Wall |
One pointer `i` scans all elements. If `nums[i]` is non-zero, swap it with the element at the `lastNonZeroFoundAt` index. |
Draw an array. Place a 'Read' finger and a 'Write' finger. If Read finds a non-zero, it "throws" it to Write and both move. If zero, only Read moves. |
In-Place Linear Scan: $O(N)$ Time. |
Draw a single straight arrow. Note that each element is visited exactly once. |
Extra Buffer: Draw a second array of size N in memory. |
In-Place: Draw the original array with no extra structures. Space: $O(1)$. |
| 284 |
Peeking Iterator |
Convert the entire iterator into a list/array in the constructor. |
Linear Buffer: $O(N)$ Space. |
Draw an iterator box. Draw an arrow pouring every element into a new array. Label it "Space: $O(N)$." |
Look-Ahead (Caching) |
Staging Area / Lobby |
Store the `next` value in a private variable `nextElement`. `peek()` returns this variable. `next()` returns it and then refreshes it from the actual iterator. |
Draw the Iterator as a pipe. Draw a small "Shelf" next to the exit. Put the first item on the shelf. `peek` looks at the shelf; `next` takes from the shelf and pulls a new one from the pipe. |
Buffered Access: $O(1)$ for all operations. |
Draw a single dot for each call. No loops involved. |
Full Array Copy: Draw an N-slot array. |
Single Cache Variable: Draw one small box labeled `nextElement`. Space: $O(1)$. |
| 285 |
Inorder Successor in BST |
Perform a full Inorder traversal, store in a list, and find the element appearing immediately after the target. |
Traversal Flat-Map: $O(N)$ Time and Space. |
Draw a tree. Show an arrow visiting every node and writing values into an array. Circle the target and its neighbor. |
BST Property Navigation (Succ = smallest of right subtree) |
Binary Search Descent |
If `target.right` exists, successor is the leftmost node of the right child. Else, start from root; if `target < root`, root is a potential successor, move left. If `target > root`, move right. |
Draw a BST. Trace a path from root. If you turn Left, mark the current node as "Best So Far." The last marked node is your successor. |
Height-Limited Search: $O(H)$ Time. |
Draw a single path from the root to a leaf. Length is height H (log N if balanced). |
Full Node List: Draw an array of size N. |
Constant Pointers: Draw two variables: `successor` and `curr`. Space: $O(1)$. |
| 286 |
Walls and Gates |
For every empty room (0), start a separate BFS to find the nearest gate (G). |
Nested Grid Scans: $O(m^2 n^2)$. |
Draw a grid. Pick an empty cell. Draw concentric circles expanding until they hit a 'G'. Repeat this for *every* empty cell on the grid. |
Multi-Source BFS |
Wavefront Expansion |
Add ALL gates to the queue at once. Process level by level. When a gate's "wave" hits an empty room, that room gets the current level count and becomes a "source" for the next level. |
Draw a grid. Shade all 'G' cells simultaneously. Draw a "1" in all adjacent empty cells. Then a "2" in their neighbors. Show the waves merging without overlap. |
Linear Grid Scan: $O(m \\text{times} n)$ Time. |
Draw a single grid. Show each cell being visited exactly once as the BFS queue processes it. |
Individual BFS Queues: Multiple queue boxes. |
Single Queue Ribbon: Draw one long queue starting with all 'G' coordinates. Space: $O(m \\text{times} n)$. |
| 287 |
Find the Duplicate Number |
Sort the array $O(n \log n)$ or use a Hash Set to track seen numbers $O(n)$ space. |
Sorting Slope / Hash Table Grid. |
Draw a messy list. Draw it sorted. Or draw an array pointing into a growing Hash Map. |
Floyd’s Cycle Finding (Tortoise and Hare) |
Directed Graph Lasso |
Treat the array as a linked list where nums[i] is the pointer to the next index. Because there's a duplicate, there *must* be a cycle. Fast moves 2, Slow moves 1. Meet at intersection, reset Slow, then both move 1. |
Draw indices as nodes and values as pointers. For nums = [1,3,4,2,2], draw 0 \to 1 \to 3 \to 2 \to 4 \to 2. Highlight the "cycle" at the end. |
Linear Pointer Chase: $O(n)$ Time. |
Draw a timeline showing the two pointers moving. Mark the meeting point. No nested loops. |
Hash Set Table: $O(n)$ Space. |
Fixed Pointer Cells: Draw exactly two variables, `slow` and `fast`. $O(1)$ extra space. |
| 288 |
Unique Word Abbreviation |
For every `isUnique` call, iterate through the entire dictionary and compute abbreviations for every word on the fly. |
Repeated Linear Scans: $O(Q \\text{times} N)$. |
Draw a query word. Draw a long dictionary list. Show an arrow checking every word in the list for every single query. |
Hash Map Pre-processing |
Dictionary Mapping |
Pre-calculate abbreviations (e.g., "internationalization" \to "i18n"). Store in a map: `Map>`. |
Draw a Map table. Left column is abbreviations like "d3r", right column is a list of matching words like ["door", "dear"]. |
Constant Lookup: $O(1)$ per query. |
Draw a single arrow pointing directly to a specific row in your map table. T = 1 step. |
N/A (Calculated on the fly). |
Abbreviation Map: Draw a hash table structure. Space: $O(N)$ where N is total words in dictionary. |
| 289 |
Game of Life |
Create a complete copy of the m \times n matrix to store the next state while calculating it. |
Matrix Duplication: $O(m \\text{times} n)$ Space. |
Draw two identical grids. Show the first grid being read and the second grid being written to. Shade both. |
In-Place State Encoding (Bit Manipulation) |
State Transition Layering |
Use bits to store both current and next state. (00: dead\todead, 01: live\todead, 10: dead\tolive, 11: live\tolive). After calculating for all cells, shift bits to update. |
Draw a single cell. Write two numbers in it: "Old: 1, New: 0". Use a special symbol (like '2' or '3') to represent intermediate states on paper. |
Double Pass Grid: $O(m \\text{times} n)$ Time. |
Draw two arrows: one passing through the grid to calculate states, and another to finalize the transition. Total 2 \times (m \times n). |
Matrix Buffer: Draw a second m \times n grid. |
In-Place: Draw the original grid with small markings inside the cells. Space: $O(1)$. |
| 290 |
Word Pattern |
Split string into words. Use nested loops to check if every pattern char matches the same word and vice versa. |
Quadratic Search: $O(n^2)$. |
Draw a pattern "abba" and words "dog cat cat dog". Draw lines connecting every 'a' to 'dog', but then re-verify every 'a' again later. |
Two Hash Maps / One Map + Indexing |
Bi-directional Mapping |
Map `pattern[i]` to `words[i]` AND `words[i]` to `pattern[i]`. If either mapping conflicts (e.g., 'a' already points to 'fish' but now sees 'dog'), return false. |
Draw two tables side-by-side. Table A: `char -> word`. Table B: `word -> char`. Check for collisions in both tables during a single pass. |
Linear Scan: $O(n)$ where n is length of pattern. |
Draw a single arrow moving across both the pattern and the words simultaneously. |
Temporary word lists. |
Double Map Storage: Draw two small hash tables. Space: $O(W)$ where W is the number of unique words. |
| 291 |
Word Pattern II |
Try every possible substring mapping for every character in the pattern using standard backtracking without early pruning. |
Exploding Permutation Tree: $O(N^M)$ where M is pattern length. |
Draw a root. Branch out for every possible substring of the input. Each branch splits again. Label it "The Recursive Maze." |
Backtracking with Bi-directional Mapping |
Recursive Match-and-Prune Tree |
If pattern char is mapped, check if substring matches. If not mapped, try all possible substrings, check if they are already used. Backtrack if dead end. |
Draw pattern "abab". Draw string "redblueredblue". Draw arrows mapping 'a' to "red". Check if second 'a' matches. If not, erase and try 'a' to "redblue". |
Search Space Reduction Graph. |
Draw a tree. Show branches being cut (Pruning) the moment a mapping conflict occurs. |
Full stack of string copies. |
Two Hash Maps / Sets: Draw a map box for `char -> string` and a set for `seen_strings`. |
| 292 |
Nim Game |
Use recursion to check every possible move (taking 1, 2, or 3 stones) and see if any leads to a win. |
Game State Tree: $O(3^N)$. |
Draw a tree starting with N. Level 1 has N-1, N-2, N-3. It expands exponentially. |
Mathematical Modulo (Game Theory) |
Cycle of Four Pattern |
If the number of stones is a multiple of 4, you will always lose if the opponent plays optimally. Result: n \% 4 != 0. |
Draw numbers 1, 2, 3 (Win), 4 (Loss), 5, 6, 7 (Win), 8 (Loss). Circle the multiples of 4 to show the "Trap" states. |
Instant Logic: $O(1)$ Time. |
Draw a single dot. No loops, just a division check. |
Recursion stack: $O(N)$. |
Zero Extra Space: A single arithmetic operation. |
| 293 |
Flip Game |
Check every adjacent pair of characters and flip "++" to "--" if found. |
Linear String Scan: $O(N)$. |
Draw a string. Draw a sliding window of size 2. Shade each step. |
String Iteration / Simulation |
Sliding Window Flip |
Loop from 0 to len-2. If `s[i] == '+'` and `s[i+1] == '+'`, create a new string with those flipped and add to result list. |
Draw "++++". Mark indices 0-1, 1-2, 2-3. Draw the results "--++", "+--+", "++--" below the original. |
String Pass: $O(N^2)$ (due to string concatenation). |
Draw a timeline. Each "find" takes $O(N)$ to create a new string copy. Area = $O(N^2)$. |
Original string modification. |
List of Strings: Draw a box holding multiple string copies of length N. |
| 294 |
Flip Game II |
Recursively check every possible move. If you find a move that leaves the opponent with no winning moves, you win. |
Minimax Decision Tree: $O(2^N)$. |
Draw a tree where each node is a string state. Branch for every possible "++" flip. Width is massive. |
Backtracking + Memoization (Top-Down DP) |
State-Space Caching Tree |
Use a Hash Map to store whether a string state is a "Win" or "Loss". If you see a state again, return the cached result. |
Draw the game tree. Color nodes "Green" (Win) or "Red" (Loss). Draw arrows from duplicate states to a single "Cache" box. |
Memoized Tree: $O(2^N)$ (Still high, but avoids redundant branches). |
Draw the tree but cross out branches that have already been computed once. |
Deep Recursion Stack: $O(N)$. |
Memoization Map: Draw a table of `string -> boolean`. Space: $O(2^N)$ in worst case. |
| 295 |
Find Median from Data Stream |
Store all numbers in a list, sort it every time a new number is added (O(N \log N) per add). |
Sorting Staircase: $O(N^2 \log N)$ total. |
Draw an array growing. For every new element, draw a "Sorting" cloud above it. Shade the increasing work. |
Two Heaps (Min-Heap & Max-Heap) |
Balanced Balanced-Scales |
Use a Max-Heap for the smaller half and a Min-Heap for the larger half. Keep their sizes balanced (difference \le 1). Median is the top(s). |
Draw two triangles (Heaps) facing each other. Max-Heap on left, Min-Heap on right. Numbers enter Max, bubble to top, jump to Min. Median is where they meet. |
Heap Balancing: $O(\log N)$ per Add, $O(1)$ per Find. |
Draw a height-line ( \log N) representing the bubble-up/down cost for each addition. |
One long sorted array. |
Two Binary Tree Heaps: Draw two complete binary trees. Total space: $O(N)$. |
| 296 |
Best Meeting Point |
Iterate through every single cell in the grid. For each cell, calculate the Manhattan distance to all 1s. |
Grid Surface Map: $O(M^2 N^2)$. |
Draw a grid. Pick a point. Draw lines from it to all '1's. Repeat for every point. The "ink" density shows the complexity. |
Median Property (Independent Dimensions) |
Projected Number Lines |
Collect X-coordinates and Y-coordinates of all 1s separately. Sort them. The meeting point's X and Y are the medians of their respective lists. |
Draw a horizontal line for X and a vertical line for Y. Mark dots where houses are. The "Best X" is the middle dot on the horizontal line. |
Linear Sorting Pass: $O(\text{MN} \\text{log MN})$ or $O(\text{MN})$ with selection. |
Draw two separate timelines (one for sorting X, one for Y). Total work is the sum of these linear-logarithmic steps. |
Full Grid Copy: $O(\text{MN})$. |
Two Coordinate Lists: Draw two small 1D arrays for X and Y coordinates. Space: $O(\\text{text}{\text{Number of Houses}})$. |
| 297 |
Serialize and Deserialize Binary Tree |
Level-order traversal (BFS) that includes "null" markers for every possible missing child in a full binary tree. |
Expanding Level-Order Map: $O(2^H)$. |
Draw a tree. Draw boxes for every null spot. In a skewed tree, show the empty space growing exponentially. |
Pre-Order Traversal (DFS) with Sentinel Markers |
Recursive String Ribbon |
Serialize: Pre-order DFS, appending values and '#' for nulls. Deserialize: Use a queue to pull the "front" of the string and build nodes recursively. |
Draw a tree. Trace the path (Root-Left-Right). Write values in a line. Use '#' for nulls. To rebuild, read the first value as root, then repeat for children. |
Single Tree Traversal: $O(N)$. |
Draw a single line snaking through the tree. Every node and null marker is visited exactly once. |
Array of pointers for all levels. |
Recursion Stack / String Queue: Draw a vertical stack of height H and a single queue of tokens. |
| 298 |
Binary Tree Longest Consecutive Sequence |
For every node, start a new DFS to find the longest consecutive path starting specifically at that node. |
Overlapping DFS Scans: $O(N^2)$ (skewed) or $O(N \log N)$. |
Draw a tree. From every circle, draw a path down. Shade all the paths to show they overlap significantly. |
Single-Pass Bottom-Up / Top-Down DFS |
State Bubbling |
Pass the current length to the children. If child's value is parent + 1, increment. Else, reset to 1. Track global max. |
Draw a tree. Next to each node, write its value and its "Current Streak" number. Arrows show the streak number increasing or resetting. |
Linear Visit: $O(N)$. |
Draw a single snaking line through the tree. Each node is touched once. |
Multiple sub-traversal stacks. |
Implicit Recursion Stack: Draw one vertical stack of max height H. Space: $O(H)$. |
| 299 |
Bulls and Cows |
Nested loops: For each character in the secret, search the entire guess for a match, then track used indices. |
Quadratic Comparison: $O(N^2)$. |
Draw two strings. Draw arrows from every char in top to every char in bottom. The intersection of arrows shows the N^2 work. |
Single-Pass Frequency Array |
Digit Bucket Balance |
If `secret[i] == guess[i]`, Bull++. Else, increment secret digit count and decrement guess digit count in an array. If counts cross, Cow++. |
Draw an array of 10 boxes (0-9). As you scan, put a '+' in the secret's box and a '-' in the guess's box. If you try to put a '-' where a '+' exists, it's a cow. |
Linear Scan: $O(N)$. |
Draw one straight arrow through both strings. No nested operations. |
Index tracking arrays. |
Fixed Frequency Map: Draw a static box of 10 integers. Space: $O(1)$ (constant for digits 0-9). |
| 300 |
Longest Increasing Subsequence |
Generate all possible subsequences (2^N) and check each for the "increasing" property. |
Subsequence Explosion: $O(2^N)$. |
Draw a root. For every number, branch "Include" or "Exclude". It forms a massive binary tree. |
Patience Sorting (Binary Search + Tails Array) |
Deck of Cards Stacks |
Maintain a `tails` list. For each x, find the smallest element in `tails` \ge x using binary search and replace it. If no such element exists, append x. |
Draw several piles of cards. If a new card is smaller than a pile's top, put it there. If larger than all, start a new pile on the right. Length = number of piles. |
Log-Linear Scan: $O(N \log N)$. |
Draw a timeline. Above it, draw a height-line representing the binary search ( \log N) for each of the N elements. |
Recursion stack for all subsets. |
Tails Array: Draw a single 1D array that stays sorted. Space: $O(N)$. |
| 301 |
Remove Invalid Parentheses |
Generate all possible subsets of the string by removing varying numbers of parentheses and checking validity. |
N-ary Recursion Tree (Exponential Growth) |
Draw a root node with the full string. Draw N branches downwards, each representing the string with one character removed. Label the depth to show 2^N growth. |
Breadth-First Search (BFS) / Level-order traversal with a Visited HashSet. |
State-Space Graph with Level Pruning |
Imagine a queue. Enqueue the starting string. Dequeue, check if valid. If valid, don't generate children (pruning). If not, generate all strings with 1 less char, check if in 'visited' set, and enqueue. |
Draw a Queue horizontally (boxes). Below it, draw strings in horizontal layers (levels). Circle the first valid string you hit; cross out branches that produce duplicate strings. |
Pruned Recursion Tree (Bounding Box) |
Draw the same N-ary tree, but put a large red "X" through branches that are stopped early due to the visited set or because a valid string was already found at an earlier level. |
Deep Call Stack visual: Draw tall, vertical stacked boxes representing recursive function calls, plus a giant unstructured box for the string pool. |
Queue Array + Hash Set Array: Draw a horizontal tape for the Queue. Draw a grid of hashed slots for the Visited Set to show $O(N)$ space constraint. |
| 302 |
Smallest Rectangle Enclosing Black Pixels |
Iterate through every single cell in the 2D grid. If it's black ('1'), update the min/max X and Y coordinates. |
2D Grid Traversal Array (Linear Search) |
Draw a matrix grid. Draw an arrow pointing to (0,0), then tracing through every single square row by row until the end. |
Binary Search (on 1D projections of the 2D grid) |
Orthogonal Projection / Shadow Casting |
Project the 2D grid onto the X-axis (array of booleans: does this column have a black pixel?) and Y-axis. Perform binary search on these 1D arrays to find the first and last 'true'. |
Draw the 2D grid. Below it, draw a 1D array representing the columns collapsed. Beside it, a 1D array for rows collapsed. Draw standard Binary Search L/R pointers on the 1D arrays. |
Logarithmic Search Space Halving |
Draw a wide bar. Underneath, draw a bar half the size. Underneath, half again. Do this for both horizontal (width) and vertical (height) searches. $O(M \log N + N \log M)$. |
A simple box holding 4 integer variables (min_row, max_row, min_col, max_col). $O(1)$ space. |
Same as brute force—just 4 integer boxes. No extra data structures are required for Binary Search. $O(1)$ space. |
| 303 |
Range Sum Query - Immutable |
On every sumRange(left, right) call, run a for-loop from 'left' to 'right' summing the elements sequentially. |
Linear Pointer Traversal |
Draw an array. Draw a pointer starting at L, and a curved arrow jumping to L+1, L+2, up to R. Label this "O(N) per query". |
Prefix Sum Array |
Parallel Arrays Alignment |
Visualize two arrays: Original and PrefixSum. To find sum(2, 5), look at PrefixSum[6] and subtract PrefixSum[2]. The intermediate numbers don't matter. |
Draw two horizontal array rows. Top is nums. Bottom is prefix_sums. Draw an arrow from prefix[L] and prefix[R+1] with a subtraction symbol (-) between them. |
$O(1)$ Direct Lookup Point |
Draw a massive $O(1)$ circle. Inside it, draw just two arrows pointing directly into an array. No loops. |
A single integer variable 'sum' accumulator box being overwritten over and over. $O(1)$ space. |
1D Array Block: Draw a new contiguous block of memory with length N+1. Shade it to indicate it persists across multiple queries. $O(N)$ space. |
| 304 |
Range Sum Query 2D - Immutable |
Nested loops iterating from row1 to row2, and col1 to col2, adding up matrix[r][c] for every single query. |
Sub-matrix Iteration Grid |
Draw a large grid. Outline a smaller rectangle inside. Draw a snake-like line winding through every single cell inside the smaller rectangle. $O(M\cdot N)$ per query. |
2D Prefix Sum (Inclusion-Exclusion Principle) |
Overlapping Area Rectangles (Venn Diagram logic) |
Sum = Prefix(r2, c2) - Prefix(r1-1, c2) - Prefix(r2, c1-1) + Prefix(r1-1, c1-1). Visualize taking the big rectangle from (0,0) and cutting out the top and left excess chunks, then adding back the doubly-subtracted corner. |
Draw the full matrix. Shade the target region. Draw dashed lines extending to the top and left to show the areas being subtracted. Draw a dark dot at the top-left overlapping corner being added back. |
Constant Time Block Access |
Draw 4 arrows pointing independently to 4 random cells in a grid, merging into a single math equation. $O(1)$ per query. |
$O(1)$ space, single variable accumulator box. |
2D Matrix Memory Block: Draw a grid of size (R+1) x (C+1). Shade it to indicate pre-computed $O(M\cdot N)$ space allocation. |
| 305 |
Number of Islands II |
After every new land is added, run a full DFS/BFS from scratch across the entire grid to count the connected islands. |
Repeated Graph Flooding |
Draw multiple identical grids. On grid 1, draw a DFS wave. On grid 2 (with one new cell), draw the same wave again. Label this $O(K \cdot M \cdot N)$. |
Disjoint Set Union (Union-Find) |
Forest of Trees (Component Merging) |
Grid starts as all water. When land appears, it's a new "tree" (root = itself), count++. Check 4 neighbors. If neighbor is land, union them. If roots are different, merge trees, count--. |
Draw land cells as circles. When a new land is added, draw it. If adjacent to existing circles, draw lines connecting them. Then draw an arrow from the new circle's root pointing to the old circle's root. |
Ackermann Inverse Amortization |
Draw a nearly flat, horizontal line graph to represent $O(α(N)$) time. Label it "Effectively $O(1)$ per operation". |
Large call stack (tall box) for DFS + 2D boolean Visited array per query. |
Two parallel 1D arrays: 'parent' and 'rank'. Draw them horizontally of size M*N. Draw arrows showing indices pointing to other indices in the 'parent' array. |
| 306 |
Additive Number |
Pure backtracking: recursively split the string into every possible combination of 3 or more numbers to check validity. |
Deep N-ary Recursion Tree |
Draw a root node with the full string. Draw branches representing the first split. From each, draw more branches for the second split. Show exponential explosion. |
Backtracking with Pruning / Iterative Prefix Checking |
State-Space Tree with Heavy Pruning |
Pick the 1st number. Pick the 2nd number. The 3rd number is mathematically locked (num1 + num2). Simply check if the remaining string starts with that sum. If yes, slide the window. If no, immediately prune. |
Draw an array of characters. Place 3 pointers: i, j, k. Lock i and j. Draw a curved arrow for k that jumps forward exactly by the length of (string[i] + string[j]). |
Narrow Linear Path (Bounding Box) |
Draw an N-ary tree, but immediately cross out 90% of the branches on the second level. Highlight a single straight path shooting down to the bottom. |
Deep vertical stacked boxes representing the recursive call stack for string subsets. $O(N)$ space. |
String slice allocation blocks, or $O(1)$ space if using index variables without creating substrings. Draw 3 small integer boxes for i, j, k. |
| 307 |
Range Sum Query - Mutable |
Update index in $O(1)$ by modifying the array. Sum range in $O(N)$ by looping from L to R. |
Linear Array Sweep |
Draw an array. Draw a pointer starting at L, stepping one box at a time to R. Label "O(N) Sum". |
Segment Tree or Binary Indexed Tree (Fenwick Tree) |
Hierarchical Tree over Array Ranges |
For Segment Tree: Array is at the bottom. Parents hold the sum of two children. To update, change leaf and walk up to root adding differences. To sum, pick the minimal set of parent nodes covering the range. |
Draw an array. Above it, draw a binary tree where each node has lines connecting it to its two child ranges. Shade the specific nodes needed to cover a query range [L, R]. |
Logarithmic Tree Traversal Path |
Draw a Binary Tree. Highlight a single path from a leaf to the root (Update $O(\log N)$), or a few paths from root to mid-level nodes (Query $O(\log N)$). |
A single 1D array tape. $O(N)$. |
Segment Tree Array: Draw an array of size 4N. Draw curved "jump" arrows from index `i` to `2i` and `2i+1` to show the implicit tree structure in memory. |
| 308 |
Range Sum Query 2D - Mutable |
Update cell in $O(1)$. Sum 2D range in $O(M\cdot N)$ by iterating through the sub-grid. |
2D Sub-matrix Iteration |
Draw a grid. Outline a smaller target rectangle. Draw a snake-like line traversing every cell inside the target rectangle. |
2D Binary Indexed Tree (Fenwick Tree) |
Hierarchical 2D Jump Pointers |
To update (r,c), add value, then jump right/down by adding the Least Significant Bit (LSB) to r and c. To query, start at bottom-right of range and jump up/left by subtracting LSB. |
Draw a matrix. From cell (3,3), draw an arrow jumping to (4,4), then (8,8) to represent binary jumps covering larger blocks of areas. |
2D Logarithmic Steps |
Draw a path on a grid starting at a cell, taking a small step of 1, then a step of 2, then 4, towards the origin (0,0). $O(\log M \cdot \log N)$. |
Standard 2D matrix block in memory. |
2D Matrix of exact same dimensions (M*N). Draw it as a grid, but shade it to indicate it holds cumulative BIT sums, not raw values. |
| 309 |
Best Time to Buy and Sell Stock with Cooldown |
Recursively explore 3 choices (Buy, Sell, Cooldown) on every single day. |
Ternary Recursion Tree |
Draw a root node. Draw 3 branches (Buy, Sell, Rest). From each, draw 3 more. Label the massive bottom width as $O(3^N)$. |
Dynamic Programming (State Machine) |
Finite State Machine (FSM) Graph |
Track 3 states: `Held`, `Sold`, `Reset`. On day i: `Held` comes from resting or buying from `Reset`. `Sold` comes strictly from selling `Held`. `Reset` comes from resting in `Reset` or coming from `Sold`. |
Draw 3 circles representing the states: Held, Sold, Reset. Draw directed arrows connecting them, labeling the transitions (e.g., arrow from Held to Sold labeled "+Price"). |
Linear State Transitions |
Draw a horizontal timeline array. Under each "day" slot, write three numbers stacked vertically representing the max profit for the 3 states. $O(N)$. |
Massive deep call stack box (O(N) height). |
State Variables Box: Draw just 3 integer boxes that get continually overwritten in a loop. $O(1)$ Space optimization. |
| 310 |
Minimum Height Trees |
For every single node (1 to N), run a full BFS/DFS to find the tree height. Return the nodes with the minimum height. |
Repeated Graph Flooding |
Draw a graph. Draw a BFS wave expanding from node A. Then redraw the graph and show the wave expanding from node B. Repeat N times. $O(N^2)$. |
Topological Sort / BFS from Leaves (Peeling the Onion) |
Concentric Graph Peeling |
Find all leaf nodes (degree == 1). Enqueue them. Dequeue leaves, remove them from the graph (update neighbor degrees). The new degree-1 nodes are the new leaves. Stop when 1 or 2 nodes remain. |
Draw an unrooted tree/graph. Circle the outermost layer of nodes (leaves) and cross them out. Circle the next newly exposed layer. Repeat until only the center is left. |
Linear Shrinking Space |
Draw a large blob. Inside it, draw a slightly smaller blob, and another smaller one inside that, converging on a center dot. Label it $O(N)$ Total Time. |
N separate Visited arrays or a huge queue accumulating N full traversals. $O(N^2)$ space overhead. |
Adjacency List + Degree Array + Queue. Draw a vertical array mapping to linked lists (Graph). Draw a 1D horizontal array for degrees. Draw a Queue tape holding leaf nodes. |
| 311 |
Sparse Matrix Multiplication |
Standard matrix multiplication (Dot Product). Iterate all rows of A, all cols of B, multiplying every single element regardless of whether it is zero. |
Triple Nested Loop Cube |
Draw Matrix A and Matrix B. Highlight a full row in A and a full col in B. Draw arrows combining them into a single cell in Matrix C. Label it $O(M \cdot K \cdot N)$. |
Zero-Skipping Sparse Traversal / Compressed Sparse Row (CSR) |
Bipartite Graph / Sparse Pointer Jump |
Iterate through A. If A[i][k] is zero, skip it immediately. If it's non-zero, iterate through row k of Matrix B. Multiply A[i][k] by B[k][j] and add to C[i][j]. |
Draw Matrix A and B. Circle only the non-zero numbers. Draw a targeted arrow from a circled number in A straight to the corresponding row in B. Cross out the rows filled with zeros entirely. |
Pruned Volume (Sparse Grid) |
Draw a 3D cube representing the $O(M\cdot K\cdot N)$ operations, but heavily shade/cross out 90% of the volume to show the time saved by skipping zeros. |
3 full massive 2D matrix grids (A, B, and C) taking $O(M\cdot K + K\cdot N + M\cdot N)$ space. |
Matrix C grid. For A and B, either the full grids or an Array of Lists where each list stores (col_index, non_zero_value) to drastically compress $O(\text{Memory})$. |
| 312 |
Burst Balloons |
Backtracking / Permutations. Try bursting balloon 1 first, then recurse. Try balloon 2, recurse. Generates all possible bursting sequences. |
N! Permutation Tree Explosion |
Draw a root node with N balloons. Draw N branches downward (representing the first burst). Below each, draw N-1 branches. Show the tree width exploding instantly to represent $O(N!)$. |
Dynamic Programming (Divide and Conquer with Memoization) |
Reverse Sub-problem Interval Merging |
Reverse your thinking: instead of picking the *first* balloon to burst, pick the *last* balloon to burst in the interval (i, j). Its neighbors are locked as nums[i] and nums[j]. Coins = nums[i]*nums[k]*nums[j] + left_subproblem + right_subproblem. |
Draw an array padded with 1s at the ends. Draw a bracket from index i to j. Pick a balloon k in the middle. Draw a curved line from i to k, and k to j. |
2D DP Matrix Filling |
Draw an N x N grid. Draw arrows showing how you fill the diagonal first (subproblems of length 1), then the next diagonal (length 2), up to the top right corner. $O(N^3)$. |
Deep call stack box of height N, but branching factor N! causing massive overhead. |
2D DP Matrix block: Draw an N x N grid. Shade the upper triangle of the matrix to show where the memoized answers are stored. $O(N^2)$ space. |
| 313 |
Super Ugly Number |
Iterate integers 1, 2, 3... to infinity. For each, divide by all given primes until the remainder is 1. If it is, keep it. |
Infinite Number Line Trial Division |
Draw a long number line. Below each number, draw a division symbol and the prime array. Cross out numbers that fail. Label "Extremely slow, infinite space." |
K-way Merge (Dynamic Programming with Multiple Pointers) |
Parallel Pointers Race |
Create an 'ugly' array starting with [1]. Create a pointer for each prime in the input. The next ugly number is the minimum of (prime[j] * ugly[pointer[j]]). Add the min to 'ugly', and advance the pointer(s) that produced it. |
Draw the 'ugly' array being built. Below it, draw the 'primes' array vertically. Beside each prime, draw an arrow pointing to an index in the 'ugly' array. Move the winning arrows to the right. |
Linear Multi-Pointer Sweep |
Draw K horizontal tracks (for K primes). Draw markers advancing to the right at different speeds, merging into a single sorted output tape. $O(N \cdot K)$. |
No structural memory needed, just constant CPU burn. |
Two 1D parallel arrays. Draw 'ugly' array of size N. Draw 'pointers' array of size K (or a Min-Heap of size K). |
| 314 |
Binary Tree Vertical Order Traversal |
Find the min and max column indices using DFS. Then, for every column from min to max, do a full DFS traversal just to pick out nodes in that column. |
Repeated Tree Scanning |
Draw the tree. Highlight column -2, scan whole tree. Highlight col -1, scan whole tree. Draw loop arrows to show $O(N^2)$ redundant scanning. |
Breadth-First Search (BFS) with Column Tracking (Hash Map) |
Orthogonal Projection / Plumb Line Drop |
Push (root, col=0) to a Queue. As you pop, add node to map[col]. Push left child (col-1) and right child (col+1). BFS naturally guarantees top-to-bottom row order within the same column. |
Draw a tree. Draw vertical dashed lines down through the nodes. Label root's line 0, left -1, right +1. Underneath the tree, draw buckets (Hash Map) collecting the nodes as they drop straight down. |
Single Sweep Linear Hash |
Draw a single wide arrow sweeping over the tree once, dropping nodes into a row of buckets below. $O(N)$ time complexity. |
Tall call stack box for recursive DFS. |
Hash Map of Lists + Queue: Draw a horizontal tape for the Queue. Draw vertical bucket columns (Hash Map) mapping to horizontal linked lists (the nodes). $O(N)$ space. |
| 315 |
Count of Smaller Numbers After Self |
Double nested for-loop. For every element at index i, iterate from i+1 to the end of the array and count how many are strictly smaller. |
Triangular Nested Loop (Rightward Sweep) |
Draw an array. Draw pointer i. Draw a second pointer j sweeping from i+1 to the end. Below it, draw tally marks. $O(N^2)$. |
Merge Sort (Divide & Conquer) tracking original indices |
Cross-Inversion Counting |
Store numbers as pairs (value, original_index). Do a Merge Sort descending. When merging left and right halves: if left[L] > right[R], then left[L] is greater than ALL remaining elements in the right half. Add the remaining size of the right half to the result for left[L]'s original index. |
Draw two sorted arrays being merged (Left and Right). If Left > Right, draw a thick, sweeping arrow from Left jumping over the entire remaining Right array, capturing its length as a count. |
Logarithmic Tree Resolution |
Draw a standard Merge Sort tree (inverted pyramid splitting the array, then combining). Highlight the $O(N)$ merge step at each $O(\log N)$ level. $O(N \log N)$. |
A single output array of size N. |
Array of Tuples + Temp Array. Draw the main array where each cell is split in two (Value, Original_Index). Draw an identical length Temp array for the merge steps. $O(N)$ space. |
| 316 |
Remove Duplicate Letters |
Generate every possible subsequence that contains all unique characters, then sort them lexicographically to find the smallest. |
Permutation Tree with Character Set Constraints |
Draw a tree where each level chooses one of the available unique characters. Cross out paths that don't use all unique letters. Label $O(2^N)$. |
Monotonic Stack + Greedy + Frequency Map |
Stack Pressure & Character Counter |
Use a stack. For each char, if it's smaller than the stack top and the stack top appears again later (check frequency map), pop the stack. Otherwise, push if not already in stack. |
Draw a horizontal stack. Write a frequency map below it. As you process a char, draw an arrow to the map. If frequency > 0 and char < stack_top, draw a "pop" arrow ejecting the top char. |
Linear Scan with Constant-Time Set Check |
Draw a single straight line through the string. Above it, draw a "Visited" set box and a "Stack" box. Show one pass. $O(N)$. |
Massive recursion depth boxes + array of all possible subsequences. |
A small stack (max size 26) + a frequency array (size 26) + a boolean 'seen' array (size 26). Draw three tiny fixed-size boxes. $O(1)$ extra space (ignoring output). |
| 317 |
Shortest Distance from All Buildings |
From every empty land cell '0', run a BFS to find the distance to all buildings '1'. Total the distances. |
Exhaustive Grid Search (Multiple BFS Starts) |
Draw a grid. For every single '0' cell, draw expanding concentric squares. Repeat for every '0'. Label $O((M\cdot N)$^2). |
BFS from Buildings (Multi-Source Distance Accumulation) |
Heatmap Overlay (Sum of Distances) |
Reverse the logic: Run BFS from each building ('1') only. For each '0' it reaches, add the distance to a `total_dist` grid and increment a `reach_count` grid. Finally, find the '0' that reached all buildings with the min distance. |
Draw a grid. Use different colored arrows originating from each '1'. In each '0' cell, write the sum of the colors. Shade the cell with the smallest sum. |
Grid-Bound Linear Traversal per Source |
Draw a grid with K buildings. Draw a circle around each building. Show K separate BFS passes. $O(K \cdot M \cdot N)$. |
A distance grid for every single empty cell. $O((M\cdot N)$^2) if not careful. |
Two grids of size M*N (Distance Sum and Reach Count). Draw two side-by-side grids. $O(M\cdot N)$. |
| 318 |
Maximum Product of Word Lengths |
Compare every pair of words (O(N^2)). For each pair, compare every character in word1 with every character in word2 (O(L1*L2)) to see if they share letters. |
Nested Loop with Character Set Intersection |
Draw word1 and word2. Draw a line from every letter in word1 to every letter in word2. Label $O(N^2 \cdot L^2)$. |
Bitmasking (Bitwise AND Comparison) |
Binary Signature Alignment |
Represent each word as a 26-bit integer (bit 0 is 'a', bit 1 is 'b'). To check if two words share letters, simply do `(mask1 & mask2) == 0`. It’s an $O(1)$ check. |
Draw a 26-bit binary string for "abc" (11100...). Draw another for "def" (000111...). Draw an 'AND' gate showing the result is 0. |
Quadratic Pairwise Check (Optimized Inner Loop) |
Draw an N x N matrix. Inside each cell, just write "AND". No internal loops. $O(N^2 + N\cdot L)$. |
Lists of character sets or hash sets for every word. |
1D Array of integers (Masks). Draw a single horizontal tape where each cell is a 32-bit integer box. $O(N)$. |
| 319 |
Bulb Switcher |
Simulate all n rounds. In round i, toggle every i-th bulb. Count how many are on at the end. |
Nested Simulation Loop |
Draw n bulbs. Draw a line for round 1 toggling all. Draw a line for round 2 toggling every 2nd. Label $O(N^2)$. |
Mathematical Pattern (Square Root) |
Factor Parity Observation |
A bulb ends up 'ON' only if it is toggled an odd number of times. Only perfect squares have an odd number of divisors (e.g., 36 has 1, 2, 3, 4, 6, 9, 12, 18, 36). The answer is simply \lfloor\sqrt{n}\rfloor. |
Draw the numbers 1 to 10. Circle 1, 4, 9. Underneath, write "Divisors: 1, 3, 3". Explain that squares have a middle divisor that isn't paired. |
Constant Time Math Operation |
Draw a single box with the formula \sqrt{n}. $O(1)$. |
A boolean array of size n to track bulb states. $O(N)$. |
No memory required. Draw a single variable box 'res'. $O(1)$. |
| 320 |
Generalized Abbreviation |
Generate every possible combination of letters and numbers that could represent the string, then validate them. |
Unconstrained String Permutation |
Draw a tree where every character can be itself, a '1', a '2', etc. Massive overlap and redundant strings. |
Backtracking (Keep or Abbreviate) |
Binary Decision Tree (Decision per Character) |
At each character, you have two choices: 1) Keep the character as is (and append any pending count). 2) Abbreviate it (increment current count). |
Draw a tree. At each node, branch left for "Letter" and right for "Number +1". At the bottom, write the resulting strings (e.g., "word", "wor1", "wo1d"...). |
Exponential State Space (Systematic) |
Draw a binary tree of depth n. Label the total leaves as 2^n. $O(2^n)$. |
Large set of strings and massive recursion depth. |
Recursion stack (O(N)) + StringBuilder/Buffer. Draw a single vertical stack and one horizontal buffer being modified. |
| 321 |
Create Maximum Number |
Exhaustively try every possible way to pick i elements from array1 and k-i elements from array2, then merge them into all possible permutations to find the max. |
Exponential Permutation Tree |
Draw a split point i. For each i, draw branches representing every possible interleaving of the two sub-sequences. Label it $O(2^{n+m})$. |
Monotonic Stack + Lexicographical Merge |
Parallel Monotonic Pipelines |
1. For each possible i, find the max sub-sequence of length i from nums1 and k-i from nums2 using a monotonic stack. 2. Merge these two sequences greedily (comparing suffixes). 3. Keep the overall maximum. |
Draw two horizontal stacks. Show elements being "kicked out" if a larger number appears. Draw a "Merge" box below with two pointers comparing the remainder of the strings at each step. |
Iterative Optimization Sweep |
Draw k horizontal bars, each representing a "try". Inside each, show two $O(N)$ operations. $O(k \cdot (n+m)$^2). |
Massive collection of string/array objects in a list. |
Two 1D arrays for stacks + one 1D array for the merged result. Draw three horizontal tape segments. $O(k)$. |
| 322 |
Coin Change |
Recursively try every coin for the current amount, branching out for every possibility until you hit 0 or go negative. |
N-ary Recursion Tree (Unbounded) |
Draw a root with 'Amount'. Draw N branches (one for each coin). Continue until leaves are 0. Show the massive width: $O(S^n)$ where S is amount. |
Dynamic Programming (Bottom-Up) |
1D Distance-to-Zero Map |
Initialize `dp[amount+1]` with infinity. `dp[0] = 0`. For each coin, update every amount i from `coin` to `target` as `min(dp[i], dp[i-coin] + 1)`. |
Draw a 1D array indexed 0 to S. For amount 11 with coin 5, draw an arrow jumping back 5 slots to index 6, taking that value, and adding 1. |
Linear Array Fill |
Draw a single 1D array. Draw a single loop arrow above it indicating a left-to-right pass for each coin. $O(S \\text{times} n)$. |
Explosive call stack height (up to S deep). |
1D DP Array Block: Draw a contiguous memory block of size S. Shade it to show incremental filling. $O(S)$. |
| 323 |
Number of Connected Components |
For every node i, run a full BFS/DFS to see which nodes it can reach, even if it was already part of a previously found component. |
Redundant Graph Traversal |
Draw a graph. Draw a circle around component 1. Then start a new search from a node *inside* that circle anyway. Show overlapping work. |
Disjoint Set Union (DSU) |
Dynamic Linkage / Forest of Trees |
Iterate through edges. For each edge (u, v), `union(u, v)`. If they were in different sets, decrement the component count (initially n). |
Draw n isolated dots. For each edge, draw a line connecting them. If they are already in the same "cloud" (set), do nothing. Count how many clouds remain. |
Amortized Linear Path Compression |
Draw a tree that is "squashed" (all nodes point to root). Label it $O(E \\text{alpha}(V)$) to show it's nearly constant time per edge. |
Adjacency list plus redundant visited sets for every node. |
1D 'Parent' Array: Draw a horizontal tape of size n. Draw pointers from index i to its parent index p. $O(V)$ space. |
| 324 |
Wiggle Sort II |
Sort the entire array. Then, create a new array and pick elements from the first and second halves to interleave them (small, large, small, large...). |
Full Sort & Interleave |
Draw an unsorted array. Draw a "Sorted" array below it. Draw zig-zag arrows moving elements from the sorted array into a third "Result" array. $O(n \log n)$. |
Quickselect + Virtual Indexing (3-way Partition) |
Median-Relative Color Sort |
Find the median in $O(n)$ using Quickselect. Use "Virtual Indexing" to map indices 0, 1, 2... to wiggle positions. Perform a 3-way partition (Dutch National Flag) to put numbers > median at odd slots and < median at even slots. |
Draw an array. Label indices with "Virtual" names (1, 3, 5... then 0, 2, 4...). Use three pointers (i, j, k) to swap elements into their virtual positions relative to the median. |
Linear Partitioning Wave |
Draw a single horizontal line representing the array. Mark the median point. Show three pointers moving inward. $O(n)$ time. |
A complete copy of the array for sorting. $O(n)$. |
In-place variables. Draw the original array memory block and 3 tiny integer boxes (L, M, R pointers). $O(1)$ extra space. |
| 325 |
Max Size Subarray Sum Equals k |
Use two nested loops to check every possible subarray (start i, end j), calculate the sum, and check if it equals k. |
Triangular Matrix Scan |
Draw an array. Draw a bracket that starts small [i, i] and expands to [i, n]. Then move i and repeat. $O(n^2)$. |
Prefix Sum + Hash Map (Two-Sum Variation) |
Reverse Complement Lookup |
Keep a running `prefix_sum`. At each index i, we want a `prev_sum` such that `prefix_sum - prev_sum = k`. This means `prev_sum = prefix_sum - k`. Check if this value is in the Map. If so, `max_len = max(max_len, i - map[prev_sum])`. |
Draw a running total variable. Draw a Hash Map beside it. For each step, draw an arrow to the Map asking "Have you seen (Current - k)?" If yes, draw a bracket between that index and the current one. |
Single-Pass Hash Mapping |
Draw a single straight arrow moving through the array. Above it, draw a "Hash Map" box being populated. $O(n)$. |
$O(1)$ space, just the result variable. |
Hash Map Block: Draw a table with two columns (Sum, Index). Show n entries being added. $O(n)$ space. |
| 326 |
Power of Three |
Repeatedly divide the number by 3. If the remainder is ever non-zero before reaching 1, it's not a power of three. |
Iterative Reduction Tape |
Draw a number in a box. Draw an arrow dividing it by 3, resulting in a smaller box. Repeat until the box contains 1 or a decimal. $O(\log₃ N)$. |
Mathematical Constant Division (Base-10 Log or Max Int) |
Direct Division check against Integer Limit |
For a prime base like 3, the largest power of 3 that fits in a 32-bit integer is 3^{19} = 1,162,261,467. Simply check if this max power is divisible by n using the modulo operator. |
Draw one giant "Master" box representing 3^{19}. Draw a smaller box n beside it. Draw a "modulo" symbol between them. If the result is 0, it's a match. |
Constant Step Logic |
Draw a single dot. No loops, no recursion. $O(1)$. |
A single 'current_n' variable box being updated. |
Zero extra memory. Draw an empty space or a single "n" input box. $O(1)$. |
| 327 |
Count of Range Sum |
Calculate all prefix sums, then use two nested loops to check every pair (i, j) to see if `sum[j] - sum[i]` falls within [lower, upper]. |
Triangular Matrix Comparison |
Draw a prefix sum array. Draw two pointers, i and j. For every i, sweep j to the end. $O(N²)$. |
Modified Merge Sort (Divide & Conquer) |
Recursive Split and Range-Count Merge |
During the merge step of Merge Sort on the prefix sum array, for each element in the left half, find the range of indices in the right half that satisfy the sum condition. Since both halves are sorted, you can use two pointers to find this range in linear time. |
Draw two sorted blocks. For an element L in the left block, draw two arrows into the right block pointing to the "start" and "end" of the valid range. Total count = end - start. |
Log-Linear Recursion Tree |
Draw a standard Merge Sort tree. At each "Merge" node, write "Two-Pointer Sweep" to show the $O(N)$ work at that level. $O(N \log N)$. |
$O(1)$ space if not counting the prefix sum array. |
Recursion stack + temporary merge array. Draw a vertical stack of boxes and a horizontal "buffer" tape. $O(N)$. |
| 328 |
Odd Even Linked List |
Iterate through the list and create two entirely new linked lists: one for odd-indexed nodes and one for even-indexed nodes. Join them at the end. |
List Duplication (Parallel) |
Draw the original list. Below it, draw two new list headers. Draw arrows copying values into the new nodes. $O(N)$. |
Two-Pointer In-Place Re-linking |
Alternating Pointer Jump |
Maintain `odd` and `even` pointers. Set `odd.next = even.next`, then move `odd` to that node. Set `even.next = odd.next`, then move `even` to that node. Finally, link the end of the odd list to the head of the even list. |
Draw a linked list. Use a red pen for 'odd' pointers and blue for 'even'. Draw the 'next' arrows "skipping" nodes to connect to their own kind. Label the final jump from Odd-tail to Even-head. |
Linear Single-Pass Linkage |
Draw a single line of nodes. Draw a single arrow path from start to end showing the re-wiring. $O(N)$. |
Two separate head nodes and N new nodes. $O(N)$. |
Just 4 pointer variables (`odd`, `even`, `oddHead`, `evenHead`). Draw four small pointer boxes. $O(1)$ extra space. |
| 329 |
Longest Increasing Path in a Matrix |
Start a DFS from every single cell (r, c). Explore all increasing paths without remembering previous results. |
Brute Force Exhaustive DFS Tree |
Draw a grid. Pick a cell. Draw a tree of all possible paths. Redraw for every cell. Show the exponential overlap. $O(4^{\text{MN}})$. |
DFS + Memoization (Topological Sort Pattern) |
Memoized Grid Heatmap |
Perform DFS from each cell. If a cell's longest path is already computed, return it from the `memo` table. Only move to neighbors with a strictly greater value. |
Draw a grid. In each cell, write the length of the longest path starting there. Use a different color to show "cached" values being pulled instead of re-calculating. |
State-Space Matrix Coverage |
Draw a grid. Draw a single arrow through each cell once. Label $O(\text{MN})$. |
Massive recursion depth boxes with redundant path strings. |
2D Memoization Matrix: Draw a grid of the same size as the input. Shade it as it fills with integers. $O(\text{MN})$. |
| 330 |
Patching Array |
Try all possible subset sums for every number from 1 to n. If a number cannot be formed, add it to the array and start over. |
Subset Sum Power Set Check |
Draw numbers 1 to n. For each, draw a tree of all current array combinations. If a gap is found, patch and repeat. $O(2^N)$. |
Greedy Range Expansion |
Sliding Reachable Window |
Track the current "reachable" range [1, miss). If the next array element is \le miss, extend the range to `miss + nums[i]`. If not, "patch" the array by adding `miss` itself, doubling the reach to `miss + miss`. |
Draw a number line. Draw a shaded bar representing the current reach. If a gap appears, draw a "patch" block that exactly doubles the length of the shaded bar. |
Logarithmic Growth Path |
Draw a bar that doubles in size at each step where a patch is added. Show it reaching n very quickly. $O(N)$ or $O(\log n)$. |
List of all possible subset sums. $O(2^N)$. |
A few long/int variables (`miss`, `added`, `i`). Draw three small boxes. $O(1)$. |
| 331 |
Verify Preorder Serialization of a Binary Tree |
Explicitly reconstruct the binary tree from the string. Use null nodes for '#' and throw an error or check if nodes remain at the end. |
Explicit Tree Growth (N-ary expansion) |
Draw a root. Branch out left/right. If you run out of string before filling the tree, or have leftovers, it's $O(N)$ but with high overhead. |
Graph Degree Logic (Out-degree vs In-degree) / Slot Counting |
Resource Slot Depletion |
Start with 1 slot. For every non-'#' node, it consumes 1 slot but creates 2 new ones (total +1). For every '#', it consumes 1 slot and creates 0 (total -1). If slots ever drop to 0 before the end, or aren't 0 at the finish, return false. |
Draw a box labeled "Slots". Put the number 1 in it. As you read the string, erase and update the number. Use arrows pointing from the string to the box. |
Net-Flow Balance Analysis |
Draw a balance scale. On one side, write "Out-degrees", on the other "In-degrees". Show them balancing to zero by the end of the scan. $O(N)$. |
Full Node objects and Tree pointers in memory. $O(N)$. |
A single integer variable 'slots'. Draw one small box. $O(1)$. |
| 332 |
Reconstruct Itinerary |
Generate all possible permutations of tickets and check if they form a continuous path starting from "JFK". Sort results to find the smallest lexicographically. |
Permutation Tree (Factorial Growth) |
Draw "JFK" at the top. Draw every possible ticket as a branch. Show the tree width expanding to $O(T!)$ where T is tickets. |
Hierholzer's Algorithm (Eulerian Path via DFS) |
Backtracking Post-order Path Reversal |
Use an Adjacency List with Priority Queues for lexicographical order. Run DFS. When a node has no more outgoing edges, "burn" the node by adding it to the result. Reverse the result at the end. |
Draw the airports as circles. Draw tickets as arrows. As you traverse an arrow, put a cross on it. When stuck, write the airport name in a list and "pop" back to the previous airport. |
Linear Edge Exhaustion |
Draw a single line that visits every edge exactly once. Mark each edge with a number representing the order it was "burned". $O(E \log E)$ due to sorting. |
Massive set of all possible path strings. |
Adjacency List + Recursion Stack. Draw a vertical map where keys are airports and values are sorted lists of destinations. $O(V + E)$. |
| 333 |
Largest BST Subtree |
For every node in the tree, run a separate function `isBST(node)` and `countNodes(node)`. Keep track of the maximum count found. |
Top-Down Redundant Scanning |
Draw a tree. Circle the root, scan all children. Circle the left child, scan all its children again. Draw overlapping circles to show $O(N^2)$. |
Post-order Traversal (Bottom-Up Information Passing) |
Hierarchical Property Propagation |
Each node returns four values to its parent: `[isBST, size, min_val, max_val]`. A parent is a BST only if both children are BSTs and `left_max < parent_val < right_min`. |
Draw a tree. Start at the leaves. Write the 4-tuple `[T, 1, val, val]` next to them. Move up to the parent and show the math comparing the tuples to form a new tuple. |
Single-Pass Tree Depth Scan |
Draw one large arrow starting from the bottom-left leaf, zig-zagging to the bottom-right, and ending at the root. $O(N)$. |
No extra memory besides the tree itself (recursion stack ignored). |
Recursion stack (O(H) where H is height). Draw a vertical column of "Return Tuple" boxes. $O(H)$. |
| 334 |
Increasing Triplet Subsequence |
Triple nested loop: `for i, for j > i, for k > j`. Check if `nums[i] < nums[j] < nums[k]`. |
Triangular Cubic Volume |
Draw an array. Draw three pointers i, j, k. Show k moving across the whole array for every j, and j moving for every i. $O(N^3)$. |
Greedy Candidate Maintenance (Two-Variable Sweep) |
Low-Water Mark Tracking |
Keep two variables: `first` (the smallest seen) and `second` (the smallest number > `first`). If you find a number `third` > `second`, you found your triplet. |
Draw two boxes labeled `Small` and `Mid`. Write \infty in both. As you scan the array, update the boxes. If you hit a number that fits nowhere, "winner" flag is raised. |
Linear Progression Line |
Draw a horizontal line with a single pointer moving from left to right. Label it $O(N)$. |
Zero memory; constant variables. |
Two integer boxes. Draw them side-by-side. $O(1)$. |
| 335 |
Self Crossing |
For every new segment i, check if it intersects with any segment from 0 to i-2 using coordinate geometry formulas. |
Exhaustive Segment Intersection Check |
Draw a spiral. For segment 10, draw lines connecting its endpoints to every other previous line to check for overlap. $O(N^2)$. |
Pattern Categorization (6-Segment Window) |
Geometric State Comparison |
A crossing only happens in three specific cases: 1. Fourth segment crosses first. 2. Fifth segment crosses first. 3. Sixth segment crosses first. Only check these specific relative distances. |
Draw three types of spirals: "Expanding", "Shrinking", and "Stalled". Mark the specific points where the "Shrinking" line hits the "Expanding" boundary. |
Constant-Window Rolling Scan |
Draw a sliding window covering 6 segments. Show the window moving along the spiral. $O(N)$. |
List of all previous (x, y) coordinates. $O(N)$. |
Zero extra memory; just use the input array. Draw a sliding bracket over the input array. $O(1)$. |
| 336 |
Palindrome Pairs |
For every word i, iterate through every other word j. Concatenate them as W_i + W_j and check if the result is a palindrome. |
Pairwise String Concatenation Matrix |
Draw an N \times N grid where N is the number of words. In each cell (i, j), write the combined string and a checkmark/cross. Label $O(N^2 \cdot K)$. |
Trie (Prefix/Suffix) or Hashing with Word Splitting |
Reverse Word Trie with Palindrome Suffixes |
Store all words in a Trie. For each word, split it into `prefix` and `suffix`. If `prefix` is a palindrome, check if `reversed(suffix)` exists in the Trie. If `suffix` is a palindrome, check if `reversed(prefix)` exists. |
Draw a Trie of reversed words. For a search word "abc", trace "c"->"b"->"a". At each node, check if the "remaining" part of the original word in the Trie is a palindrome. |
Prefix-Suffix Search Space Tree |
Draw a word as a split bar. Show one side being checked for "Palindromeness" and the other side being looked up in a Hash Map. $O(N \cdot K^2)$. |
List of all N^2 concatenated strings. $O(N^2 \cdot K)$. |
Trie nodes with integer lists. Draw a tree where each node has an array of 26 pointers and a list of indices. $O(N \cdot K)$. |
| 337 |
House Robber III |
Recursively decide to rob a node or not. If robbed, move to grandchildren. If not robbed, move to children. Repeat for every node without caching. |
Exponential Binary Decision Tree |
Draw the original tree. For the root, draw two branches: "Robbed" (sum grandchildren) and "Skipped" (sum children). Show these branches duplicating for every node. $O(2^N)$. |
Tree Dynamic Programming (Post-order Traversal) |
Bottom-Up State Propagation (Rob/Skip) |
Each node returns an array of two values: `[max_if_robbed, max_if_skipped]`. `max_if_robbed` = current_val + left_skipped + right_skipped. `max_if_skipped` = max(left) + max(right). |
Draw a tree. Starting from leaves, write a pair [1, 0] (if value is 1). For the parent, show the addition logic to create its own [rob, skip] pair. |
Single-Pass Tree Depth Scan |
Draw an arrow starting at the leaves and moving upward to the root. Label it $O(N)$. |
Massive recursion stack with redundant calls. |
Recursion stack + pair-array returns. Draw a vertical stack where each frame holds two integer variables. $O(H)$. |
| 338 |
Counting Bits |
For every number from 0 to n, count its set bits using a loop or a built-in function (Brian Kernighan’s algorithm). |
Bitwise Iteration Tape |
Draw a number line. Below each number, draw its binary form and count the 1s. Label $O(N \cdot \\text{text}{\text{bits}})$. |
Dynamic Programming (Most Significant Bit / Least Significant Bit) |
Sub-problem Bit Offset |
Observe the pattern: `count[i] = count[i >> 1] + (i & 1)`. The number of bits in i is the number of bits in i/2 plus 1 if i is odd. |
Draw a 1D array. For index 7 (111), show an arrow pointing to index 3 (011) and adding the +1 from the last bit. |
Linear Dependency Chain |
Draw a 1D array. Draw curved arrows pointing from i/2 to i. $O(N)$. |
N separate bit-counting function calls. |
1D Integer Array. Draw a horizontal tape of size n+1. $O(N)$. |
| 339 |
Nested List Weight Sum |
Recursive DFS that passes down the current depth level and multiplies the integer values by that depth. |
Recursive Nesting Depth Scan |
Draw a nested list like `[[1,1],2,[1,1]]`. Draw a tree where levels correspond to nesting. Show the multiplier increasing with depth. $O(N)$. |
Depth-First Search (DFS) or Breadth-First Search (BFS) |
Layered Level Traversal |
Use a Queue for BFS. In each level, sum all integers found. Add that sum to a total, and then add that same sum again for every subsequent deeper layer. |
Draw the nested list. Draw concentric circles around the deeper brackets. Write the "weight" as a multiplier next to each circle. |
Linear Hierarchical Summation |
Draw a single pass through the list. Label the "Depth" variable increasing and decreasing. $O(N)$. |
Deep recursion stack for heavily nested empty lists. |
Queue (BFS) or Stack (DFS). Draw a horizontal tape for the Queue. $O(D)$ where D is max depth. |
| 340 |
Longest Substring with At Most K Distinct Characters |
Generate every possible substring (i, j) and check if the number of unique characters in it is \le k. |
Triangular String Clipping |
Draw the string. Draw a bracket for every possible start and end point. Label $O(N^2)$ or $O(N^3)$. |
Sliding Window + Hash Map (Two Pointers) |
Expanding/Contracting Flexible Window |
Move `right` pointer to add characters to a Hash Map. If map size > k, move `left` pointer and decrement counts until map size \le k. Update max length at each step. |
Draw the string. Draw a sliding "box" (window). Below it, draw a small Hash Map table. Show the box expanding right until the map has k+1 entries, then show the left side "shrinking". |
Two-Pointer Linear Sweep |
Draw a string with two arrows (L and R). Show them both moving only from left to right. $O(N)$. |
List of all unique substrings. $O(N^2)$. |
Hash Map of characters. Draw a table with 2 columns (Char, Frequency). Max size of map is k+1. $O(K)$. |
| 341 |
Flatten Nested List Iterator |
Recursively traverse the entire nested list at the start and store all integers in a flat queue or list. |
Pre-computed Flat Array Tape |
Draw the nested structure like `[1, [4, [6]]]`. Draw an arrow to a flat array `[1, 4, 6]`. Label this $O(N)$ pre-processing. |
Lazy Iterator with Stack (Depth-First Search) |
Stack-Based Depth Navigation |
Push the list into a stack. In `hasNext()`, peek the top. If it's a list, pop it, and push its elements back onto the stack in reverse order. Repeat until the top is an integer. |
Draw a vertical stack. Put the initial list inside. Show the list "expanding" into its components within the stack. Use a "Pointer" arrow at the top of the stack. |
On-demand Recursive Expansion |
Draw a stack that grows and shrinks as you dive into brackets. Label the complexity as $O(1)$ per `next()` amortized. |
A complete copy of the flattened list. $O(N)$. |
A stack of iterators/lists. Draw a vertical column of boxes where each box is a reference to a nested level. $O(D)$ where D is depth. |
| 342 |
Power of Four |
Repeatedly divide the number by 4 as long as the remainder is 0. If you reach 1, it's a power of four. |
Iterative Reduction Tape |
Draw a box with n. Draw a loop arrow dividing by 4 until it hits 1 or fails. $O(\log₄ N)$. |
Bit Manipulation + Masking |
Bitwise Position Filter |
A power of four must: 1. Be a power of two (n \& (n-1) == 0). 2. The only set bit must be at an even position (use mask `0x55555555`). |
Draw a 32-bit binary string. Highlight positions 0, 2, 4, etc. Draw an AND operation with the input bit to show if the "1" falls in a valid slot. |
Constant-Time Bit Logic |
Draw three logic gates (AND, NOT, comparison) connected in series. No loops. $O(1)$. |
A single integer variable box. |
Zero extra memory. Draw one input box n. $O(1)$. |
| 343 |
Integer Break |
Use backtracking to find every possible set of integers that sum to n, multiply them, and keep the max. |
Partition Permutation Tree |
Draw a root n. Draw branches for every possible first split (1, 2, \dots, n-1). Show the tree width expanding exponentially. $O(2^N)$. |
Dynamic Programming or Mathematical Optimization (Rule of 3s) |
Greedy Factor Decomposition |
Math: To maximize the product, break n into as many 3s as possible. If the remainder is 1, use two 2s (since 3+1=4 and 3 \times 1 < 2 \times 2). If the remainder is 2, just multiply by that 2. |
Draw the number n as a long bar. Chop it into segments of length 3. If a small bit is left, show it merging into a 4 to be split into 2 \times 2. |
Linear DP Fill or Constant Math |
Draw a 1D DP array from 1 to n. Show dp[i] being calculated from previous values. $O(N)$ or $O(\log N)$. |
Recursive call stack depth of N. |
1D DP array or $O(1)$ if using the math formula. Draw a single result variable box. |
| 344 |
Reverse String |
Create a new array/string. Iterate from the end of the input and append each character to the new array. |
Parallel Array Copy |
Draw the original array. Below it, draw a second empty array. Draw arrows from original end to new start. $O(N)$. |
Two Pointers (In-place Swap) |
Converging Boundary Pointers |
Place a `left` pointer at 0 and a `right` pointer at n-1. Swap the characters and move pointers toward each other until they meet. |
Draw an array. Place two arrows at the ends. Draw a curved "swap" arrow between the letters they point to. Move arrows inward. |
Linear Convergence Scan |
Draw a single line. Draw two arrows moving toward the center point. $O(N/2)$ → $O(N)$. |
A secondary array of size N. $O(N)$. |
In-place modification. Draw the original array and two small integer boxes for the pointer indices. $O(1)$. |
| 345 |
Reverse Vowels of a String |
Find all vowels in the string, store them in a list, reverse the list, then traverse the string again replacing original vowels with the reversed list. |
Two-Pass Buffer Extraction |
Draw the string. Below it, draw a "Vowel List". Show a second pass where values are "poured" back in. $O(N)$. |
Two Pointers (Vowel-Selective Swap) |
Selective Boundary Convergence |
Same as Q344, but only perform the swap if both `left` and `right` point to vowels. If not, move the non-vowel pointer inward. |
Draw an array. Draw arrows at the ends. If an arrow points to 'b', move it. If both point to 'a' and 'e', draw a swap arc. |
Linear Selective Scan |
Draw a horizontal line. Draw two pointers skipping over non-vowel segments to meet at vowels. $O(N)$. |
A list/vector to store all vowels. $O(N)$. |
Constant pointers and in-place swaps. Draw the string buffer and 2 pointer boxes. $O(1)$ extra space. |
| 346 |
Moving Average from Data Stream |
Store every single incoming number in a list. Every time `next()` is called, iterate through the last size elements and calculate their sum. |
Sliding Window Summation (Naive) |
Draw a long tape of numbers. Draw a bracket covering the last 3. For the next number, move the bracket and redraw the addition symbols. $O(W)$ where W is window size. |
Double-Ended Queue (Deque) + Running Sum |
Circular Buffer / Floating Window |
Maintain a `sum` variable. When a new number arrives, add it to `sum`. If the queue exceeds `size`, pop the oldest number and subtract it from `sum`. The average is `sum / queue.size()`. |
Draw a fixed-size circular track with 3 slots. Show a number entering one side and another "falling out" the other side. Update a central "Sum" box. |
Constant-Time Update Logic |
Draw a single box for `Sum` and a small Deque. Label the operation $O(1)$. |
An ever-growing list of all numbers ever received. $O(N)$. |
A Deque of max size W. Draw a small fixed-length box. $O(W)$. |
| 347 |
Top K Frequent Elements |
Count the frequency of each element in a Hash Map. Convert the map entries to a list and sort the list by frequency in descending order. Pick the first k. |
Frequency Map + Global Sort |
Draw a frequency table. Then draw the table being rearranged from highest to lowest count. Label $O(N \log N)$. |
Bucket Sort or Min-Heap |
Frequency-Indexed Buckets |
Count frequencies in a Map. Create an array of lists where the index represents the frequency. Iterate from the end of the array to collect elements until you have k. |
Draw a Map (Key \rightarrow Count). Then draw a row of "buckets" indexed 1, 2, 3... Drop the keys into the bucket corresponding to their count. Scan buckets from right to left. |
Linear Frequency Distribution |
Draw a single sweep through the frequency map and then a single sweep through the buckets. Label $O(N)$. |
Sorting the entire set of unique elements. |
Frequency Map + Bucket Array. Draw a table and an array of linked lists. $O(N)$ space. |
| 348 |
Design Tic-Tac-Toe |
Store the entire n \times n board. After every move, scan the entire row, column, and both diagonals to check if the current player has won. |
Exhaustive Grid Scan |
Draw a 3 \times 3 grid. For every move, draw arrows scanning the whole row, then the whole column. Label $O(N)$. |
Row/Column/Diagonal Sum Counters |
Vectorized State Tracking |
Maintain two arrays: `rows` and `cols`, and two variables: `diag` and `antiDiag`. For Player 1, add 1; for Player 2, subtract 1. If any count reaches n or -n, that player wins. |
Draw a grid. Outside the grid, draw a vertical array for rows and a horizontal one for columns. When a move is made, just increment the corresponding array slot. |
Constant-Time State Check |
Draw four specific memory updates (Row, Col, Diag1, Diag2). No loops. Label $O(1)$. |
A full n \times n 2D array. $O(N^2)$. |
Two 1D arrays and two variables. Draw two horizontal tapes of size n. $O(N)$. |
| 349 |
Intersection of Two Arrays |
For every element in `nums1`, check if it exists in `nums2` by iterating through `nums2` entirely. Add matches to a set to handle uniqueness. |
Nested Membership Search |
Draw two arrays. Draw an arrow from the first element of `nums1` and point it at every element of `nums2` sequentially. Repeat for all. $O(N \cdot M)$. |
Two HashSets (Unique Intersection) |
[Image of Venn Diagram Intersection]
Set Membership Filtering |
Convert `nums1` into a HashSet. Iterate through `nums2`, and if an element exists in the set, add it to the result set and remove it from the first set (to avoid duplicates). |
Draw two circles (Sets). Show elements being moved from the arrays into the circles, then highlight the overlapping area. |
Dual-Pass Linear Scan |
Draw one arrow through `nums1` and one arrow through `nums2`. $O(N + M)$. |
A large result list that may contain many duplicates before the set handles them. |
A HashSet for one of the arrays. Draw a hash table with unique keys. $O(\\text{min}(N, M)$). |
| 350 |
Intersection of Two Arrays II |
Same as Q349, but don't use a set for the final result. If an element matches, "mark" it in `nums2` so it isn't used again. |
Nested Loop with Depletion |
Draw two arrays. When a match is found, draw an "X" over the element in `nums2`. $O(N \cdot M)$. |
Frequency Map or Sort + Two Pointers |
Multiplicity Alignment |
Use a Map to store frequencies of elements in `nums1`. Iterate through `nums2`; if an element is in the Map and count > 0, add to result and decrement the count in the Map. |
Draw a Frequency Map. For `nums2`, draw an arrow. If it hits a key in the map, "eat" one count from that key and add the number to the result tape. |
Sorted Linear Convergence |
(If using sorting) Draw two sorted arrays with pointers i and j. If nums[i] == nums[j], move both. Else, move the smaller one. $O(N \log N + M \log M)$. |
Nested loop overhead. |
Frequency Map. Draw a table with counts that decrease over time. $O(\\text{min}(N, M)$). |
| 351 |
Android Unlock Patterns |
Generate all possible permutations of lengths m to n from the numbers 1-9. Check if each jump is valid (no "jumping over" an unvisited node). |
N-ary Recursion Tree (Combinatorial) |
Draw a 3 \times 3 grid. From the center (5), draw arrows to all 8 neighbors. From a corner (1), draw arrows and highlight the "illegal" jump to 3 if 2 isn't visited. $O(9!)$. |
Backtracking with Pre-calculated Jump Table |
Skip-Table State Space |
Use a 2D array `skip[10][10]` to store which number is "jumped over" between two keys. Run DFS. If `skip[i][j]` is not 0, only allow the jump if `visited[skip[i][j]]` is true. Multiply symmetric starts (1, 2, 5) to save time. |
Draw the 3 \times 3 grid. Write the number of patterns starting at '1' and multiply by 4. Do the same for '2' (multiply by 4) and '5' (multiply by 1). |
Pruned Backtracking Tree |
Draw a tree where many branches are terminated early with a red "X" because the jump is invalid. $O(9!)$. |
Recursive stack depth of 9. Draw a tall vertical box. |
A 1D boolean array for `visited` and a 2D `skip` table. Draw a 9 \times 9 grid and a 9-slot tape. $O(1)$ constant auxiliary space. |
| 352 |
Data Stream as Disjoint Intervals |
Store every incoming number in a sorted list. When `getIntervals()` is called, iterate through the list and group consecutive numbers into ranges. |
Linear Array Compaction |
Draw a number line. Draw dots at 1, 2, 3, 5, 6. Circle the groups. For every call, you redraw these circles. $O(N)$. |
Ordered Map (TreeMap) / Balanced BST |
Dynamic Binary Search Segment Merging |
When adding x, find the interval starting at or before x using `floorKey`. Check if x can merge with the left interval, the right interval (`higherKey`), both, or neither. Update the map accordingly. |
Draw a number line with existing segments [1, 3] and [5, 6]. Place x=4. Draw arrows from 4 to the neighboring segments showing they all fuse into [1, 6]. |
Logarithmic Interval Search |
Draw a Binary Search Tree where each node is an interval. Highlight the path to find where a new number "lands". $O(\log N)$ per addition. |
A growing list of integers. $O(N)$. |
TreeMap of Intervals. Draw a BST where each node contains a pair `[start, end]`. $O(N)$. |
| 353 |
Design Snake Game |
Store the snake's body in a list. For every move, shift all elements in the list. Check the entire list to see if the head hit the body. |
List-based Body Simulation |
Draw a grid. Draw the snake as a list of coordinates. For a move, "erase" the whole list and redraw it one step forward. $O(\text{Body Length})$. |
Deque + HashSet (Constant-Time Movement and Collision) |
Sliding Window Body Queue |
Use a `Deque` to store body coordinates (add to front, remove from back). Use a `HashSet` to store the same coordinates for $O(1)$ collision checking. Note: handle the "tail moving out" logic specifically during the collision check. |
Draw a grid with a snake. Beside it, draw a Deque (horizontal tape) and a HashSet (scattered box). Show the tail "leaving" the HashSet at the same time the head "enters" it. |
Constant Time per Move |
Draw a single box for the move operation. No loops over the snake's body. $O(1)$. |
A grid representation or a full array copy of the snake. |
Deque + HashSet of size N (max snake length). Draw two parallel data structures of size N. $O(N)$. |
| 354 |
Russian Doll Envelopes |
Sort envelopes and use recursion with memoization to find the longest chain of envelopes that fit inside each other. |
Recursive Chain Exploration |
Draw various sized envelopes. Draw a tree where choosing envelope A leads to choosing B, C, etc. Label $O(2^N)$ or $O(N^2)$ with DP. |
Sort + Longest Increasing Subsequence (LIS) via Binary Search |
Dimension Reduction to 1D LIS |
Sort envelopes by width (ascending). If widths are equal, sort height (descending). Now, find the LIS of the heights. The descending height trick prevents picking two envelopes with the same width. |
Draw envelopes as pairs (w, h). Sort them. Then extract just the h values and draw the "Patience Sorting" piles used in the $O(N \log N)$ LIS algorithm. |
Log-Linear Sorting & Binary Search |
Draw the sorting step $O(N \log N)$ followed by the LIS step $O(N \log N)$. Label total as $O(N \log N)$. |
2D DP table for the LIS. $O(N)$. |
A 1D array `tails` used for binary search LIS. Draw a single horizontal tape of size N. $O(N)$. |
| 355 |
Design Twitter |
When `getNewsFeed()` is called, collect every single tweet from every user the person follows, sort the entire global list by timestamp, and pick the top 10. |
Global Sort on Retrieval |
Draw 3 users, each with a long list of tweets. Combine them into one giant pile. Draw a "Sorting Machine" and pick 10. $O(\text{Total Tweets})$. |
Max-Heap / K-way Merge (Pull Model) |
Multi-stream Timestamp Merge |
Store tweets in a Map (User \rightarrow List of Tweets). When fetching feed, put the *latest* tweet from each followed user into a Max-Heap. Extract max, and push the next tweet from that specific user's list into the heap. Repeat 10 times. |
Draw several vertical "stacks" of tweets (most recent on top). Draw a small Max-Heap box. Show one tweet from the top of each stack being "pulled" into the heap. |
Bounded Priority Merge |
Draw a heap of size F (number of followees). Label the operation $O(10 \cdot \log F)$. |
Copies of lists for sorting. |
HashMap for Users \rightarrow Tweets, HashMap for Users \rightarrow Following. Draw two large tables. $O(U + T)$ where U is users and T is tweets. |
| 356 |
Line Reflection |
For every point (x, y), calculate its potential reflection across every possible vertical line and check if the reflected point exists in the input set. |
Exhaustive Symmetric Search |
Draw a set of random dots. Pick a random vertical line. For every dot, draw a horizontal dashed line across the vertical line to see if it "hits" another dot. Repeat for all dots. $O(N^2)$. |
Hash Set + Extremity Midpoint |
Symmetry Axis Projection |
Find the minimum and maximum x-coordinates (minX, maxX). The only possible reflection line is x = (minX + maxX) / 2. Store all points in a Hash Set. For every point (x, y), check if (minX + maxX - x, y) is in the set. |
Draw a scatter plot. Identify the leftmost and rightmost points. Draw a bold dotted line exactly in the middle. Use arrows to "pair up" dots from the left and right. |
Linear Set Membership Check |
Draw a horizontal line. Draw two dots at the ends and one in the middle. Label the middle 'S' and the ends 'x1' and 'x2' where x1 + x2 = S. $O(N)$. |
A 2D matrix or list of points requiring redundant comparisons. |
Hash Set of Strings/Tuples. Draw a single hash table where each key is a string "x,y". $O(N)$ space. |
| 357 |
Count Numbers with Unique Digits |
Iterate through every integer from 0 to 10^n and check if each digit is unique by using a boolean array of size 10. |
Linear Scan with Digit Extraction |
Draw a long tape from 0 to 1000. Below it, draw a "Digit Checker" box that ticks every time it sees a number like 123 and crosses out 122. $O(10^N)$. |
Combinatorics (Permutations) |
Decision Slot Tree (Product Rule) |
For n=1, 10 unique digits. For n=2, it's (Previous) + 9 (first digit choice 1-9) * 9 (second digit choice 0-9 excluding first). For n=3, add 9 * 9 * 8. Sum these up for the given n. |
Draw n empty slots. Write the number of choices above each: 9, 9, 8, 7... Draw multiplication symbols between them. Underneath, draw a Plus sign to show you are adding results from previous n. |
Constant-Time Formulaic Iteration |
Draw a small loop from 1 to n. Inside, show a single multiplication step. Label it $O(N)$ where n \le 10. |
Boolean array or Hash Set for every single number processed. |
Zero extra memory. Draw one "result" variable box. $O(1)$ space. |
| 358 |
Rearrange String k Distance Apart |
Generate all possible permutations of the string and check if any of them satisfy the condition that identical characters are at least distance k apart. |
Permutation Tree with Distance Constraint |
Draw a root. Branch for every char. For level 2, check if char is valid based on its previous position. Show massive pruning or $O(N!)$. |
Max-Heap + Cooling Queue (Greedy) |
Resource Cooling / Priority Scheduling |
Count frequencies. Put chars in a Max-Heap. Extract the most frequent char and append to result. Put that char into a "Waiting Queue" with its next available index. Only move it back to the Max-Heap when index \ge k. |
Draw a "Ready" box (Max-Heap) and a "Waiting Room" (Queue). Show a character moving from the box to the string, then sitting in the waiting room for k steps before jumping back to the box. |
Bounded Heap Operations |
Draw a horizontal string being built. Above it, draw a small heap that grows/shrinks. Label it $O(N \log 26)$ → $O(N)$. |
Massive collection of string permutations in memory. |
Frequency Map + Max-Heap + Wait Queue. Draw a table, a triangle (heap), and a small tape (queue). $O(1)$ if character set is fixed (26). |
| 359 |
Logger Rate Limiter |
Store every single log message and its timestamp. When a new message comes, search through all previous logs to see if it appeared in the last 10 seconds. |
Unbounded History Search |
Draw a timeline. For every new log, draw arrows pointing back to every previous log. Label $O(N^2)$ over time. |
Hash Map with Expiration Timestamps |
Sliding Expiry Window |
Use a Map (message \rightarrow next_valid_timestamp). If message is new or current_time \ge map[message], update map[message] = current_time + 10 and return true. Else, return false. |
Draw a table with two columns: "Message" and "Available At". For a new entry, show a "Check" against the clock and an "Update" to the timestamp. |
Constant-Time Lookup |
Draw a single box representing a Map. Show one arrow going in and one boolean coming out. $O(1)$. |
A list growing infinitely with every single log event. |
A Hash Map. Draw a table. Note: $O(\text{Unique Messages})$ space. In production, you'd add a cleanup mechanism. |
| 360 |
Sort Transformed Array |
Apply the function f(x) = ax^2 + bx + c to every element, then use a standard sorting algorithm to sort the results. |
Transform then Global Sort |
Draw the original sorted array. Below it, draw the transformed (unsorted) array. Draw a "Sorting Machine" box. $O(N \log N)$. |
Two Pointers (Parabolic Extremity) |
Monotonic Concavity Merge |
Recognize that a parabola is monotonic starting from its vertex. If a > 0, the largest values are at the ends of the sorted input. If a < 0, the smallest values are at the ends. Use two pointers at the start and end to fill the result array. |
Draw a U-shaped parabola. Place points on the curve. Draw two pointers at the furthest left and right points. Show them "moving down" the curve to the center as you pick values. |
Linear Convergence Fill |
Draw an array. Draw two arrows at the ends. Show them moving toward each other as they fill a "Result" tape. $O(N)$. |
An intermediate array and sorting overhead. |
A single output array of size N. Draw one horizontal tape. $O(N)$ or $O(1)$ if ignoring output. |
| 361 |
Bomb Enemy |
For every empty cell '0', scan all four directions (Up, Down, Left, Right) until you hit a wall 'W', counting enemies 'E' along the way. |
2D Grid Ray-Casting Sweep |
Draw a grid. For one '0', draw four arrows extending to the grid boundaries or walls. Repeat for every '0'. Label it $O(M \cdot N \cdot (M+N)$). |
Dynamic Programming (Row & Column Pre-computation) |
Incremental Row/Col "Heat" Buffers |
Iterate through the grid. Only re-calculate the "row-enemy-count" when you hit the start of a row or a wall. Do the same for each column. Store these in a `rowCache` and a `colCache` array. |
Draw a grid. Next to it, draw a single variable `rowCount`. Above each column, draw a small box for `colCount[j]`. Show these numbers updating only when a 'W' is passed. |
Linear Scan with Buffered Lookups |
Draw a single arrow moving through the grid once. Label it $O(\text{MN})$. |
No extra memory; just local counters per cell. |
One 1D array for column caches. Draw a horizontal tape of size N. $O(N)$ space. |
| 362 |
Design Hit Counter |
Store every single "hit" timestamp in a dynamic list. To count hits in the last 5 minutes, iterate through the whole list and filter. |
Unbounded Timeline Array |
Draw a long line. Mark every hit as a dot. For a query, draw a 300-unit bracket and count the dots inside. Label $O(N)$ per query. |
Circular Buffer (Fixed-size Array) |
300-Slot Time-Bucketed Wheel |
Use an array of size 300. Each index i represents a second (timestamp \% 300). Store the timestamp and the hit count at that index. If the timestamp at that index is old, reset the count. |
Draw a circle divided into 300 segments. As a "second" pointer moves around, show old data being erased and replaced by the current second's hits. |
Constant-Time Bucketed Summation |
Draw a small fixed-size box (300 cells). Show a single loop through it. $O(300)$ \rightarrow $O(1)$. |
A list that grows infinitely with every hit. $O(N)$. |
Two arrays of size 300 (`times` and `counts`). Draw two small horizontal tapes. $O(1)$ auxiliary space. |
| 363 |
Max Sum of Rectangle No Larger Than K |
Check every possible sub-rectangle (r1, c1) to (r2, c2), calculate the sum, and see if it's \le k. |
4D Nested Coordinate Sweep |
Draw a grid. Draw an outer rectangle, then a slightly smaller one. Label the complexity $O(M^2 N^2)$. |
2D Prefix Sum + 1D TreeSet Range Search |
Dimension Reduction with Binary Search |
Fix the left and right column boundaries. Sum the rows between them to create a 1D array. Find the max subarray sum \le k in this 1D array using a `TreeSet` to find the smallest `prefix_sum >= (current_sum - k)`. |
Draw a grid with two vertical boundary lines. Show the rows between them collapsing into a single vertical 1D column. Beside it, draw a BST (TreeSet) storing cumulative sums. |
Log-Linear Row-Column Partition |
Draw a sorting/tree operation inside a triple loop. Label $O(N^2 \cdot M \log M)$. |
Constant-time variable if just storing the max. |
1D array for row sums + TreeSet. Draw a horizontal tape and a small tree. $O(M)$. |
| 364 |
Nested List Weight Sum II |
First, find the maximum depth of the nested list. Then, perform a second pass multiplying each integer by (max\_depth - current\_depth + 1). |
Two-Pass Depth Normalization |
Draw a tree. In pass 1, find the height. In pass 2, write multipliers next to each leaf. $O(N)$. |
Single-Pass Level Accumulation |
Cumulative "Weight" Snowball |
Use a BFS-style approach. Maintain two variables: `levelSum` and `totalSum`. At each level, add all integers in the current level to `levelSum`. Then, add `levelSum` to `totalSum`. The earlier levels get added to the total more times. |
Draw a nested structure. Below it, draw a "Bucket". Drop all integers from level 1 into it, then add the bucket to the total. Drop level 2 integers into the *same* bucket, then add the bucket again. |
Linear Layered Summation |
Draw a single pass through the list levels. $O(N)$. |
Stack/Queue for two separate traversals. |
Queue for BFS or constant variables if using recursion. Draw one horizontal tape for the current level's items. $O(N)$ worst-case. |
| 365 |
Water and Jug Problem |
Use BFS to explore every possible state (v1, v2) where v1 is water in jug 1 and v2 in jug 2. Transitions: Fill, Empty, Pour. |
State-Space BFS Graph |
Draw pairs of numbers (0,0), (x,0), (0,y), \dots with arrows connecting them. Show the graph expanding until you hit z. Label $O(x \cdot y)$. |
Number Theory (GCD / Bézout's Identity) |
Linear Diophantine Equation Visualization |
A volume z can be measured if and only if z is a multiple of the Greatest Common Divisor (GCD) of x and y, and z \le x + y. |
Draw two bars of lengths x and y. Draw a small block representing the \gcd(x, y). Show that any reachable z must be composed of an integer number of these small blocks. |
Logarithmic Euclidean Algorithm |
Draw the Euclidean division steps. Label $O(\log(\\text{min}(x, y)$)). |
A Hash Set to store all visited (v1, v2) states. $O(x \cdot y)$. |
Zero extra space beyond a few integer variables. Draw a single "GCD" box. $O(1)$. |
| 366 |
Find Leaves of Binary Tree |
Repeatedly traverse the tree, find all current leaf nodes, add them to a list, and remove them. Repeat until the root is removed. |
Iterative Tree Pruning (Multi-pass) |
Draw a tree. Circle the leaves and "pluck" them. Redraw the remaining tree. Repeat. Label it $O(N^2)$ in the worst case (skewed tree). |
DFS with Height-Based Grouping |
Inverse Height Mapping |
Use DFS to calculate the distance from the furthest leaf (height). Leaves have height 0. Their parents have height 1. Use the height as an index to a list of lists to group nodes. |
Draw a tree. At each node, write its height (Max(Left, Right) + 1). Draw arrows pointing from nodes to a vertical list of "buckets" indexed by those height numbers. |
Single-Pass DFS Traversal |
Draw a single DFS path through the tree. Label it $O(N)$. |
Creating new tree objects or list of lists per iteration. |
Recursion stack + Result list of lists. Draw a vertical stack and a set of growing horizontal tapes. $O(N)$. |
| 367 |
Valid Perfect Square |
Check every integer i from 1 up to num by calculating i \times i. |
Linear Square Search |
Draw a number line. Below it, write 1^2, 2^2, 3^2 \dots until you hit or pass the target. $O(N)$. |
Binary Search (Range [1, num]) |
Logarithmic Range Halving |
Set low=1, high=num. Check mid \times mid. If it's too high, move high; if too low, move low. |
Draw a bar from 1 to N. Draw a line in the middle. Show an arrow discarding the half that doesn't contain the root. Repeat. |
Step-wise Search Space Reduction |
Draw a decreasing sequence of bars: N, N/2, N/4 \dots Label it $O(\log N)$. |
Constant time variable. |
Single variable boxes for low, mid, high. $O(1)$. |
| 368 |
Largest Divisible Subset |
Generate every possible subset of the given numbers and check if every pair in the subset satisfies the divisibility condition. |
Exponential Power Set Explosion |
Draw a root. Branch for every element (include/exclude). Label the width $O(2^N)$. |
Dynamic Programming (Sort + Longest Path in DAG) |
Divisibility Dependency Chain |
Sort the array. dp[i] stores the size of the largest divisible subset ending with nums[i]. For each j < i, if nums[i] \% nums[j] == 0, dp[i] = \max(dp[i], dp[j] + 1). Track parent indices to reconstruct the set. |
Draw a sorted array. Draw arrows from each number to its divisors on the left. Write the length of the longest chain above each number. |
Quadratic Comparison Matrix |
Draw a nested loop structure. Label it $O(N^2)$. |
Massive collection of subset lists. |
Two 1D arrays: dp\_sizes and parent\_pointers. Draw two horizontal tapes of size N. $O(N)$. |
| 369 |
Plus One Linked List |
Reverse the linked list, add one (handling carries), then reverse it back. |
Double Reversal Sweep |
Draw a list: 1 \rightarrow 2 \rightarrow 9. Draw it reversed: 9 \rightarrow 2 \rightarrow 1. Add 1 to get 0 \rightarrow 3 \rightarrow 1. Reverse again. $O(N)$. |
Two-Pointer (Sentinel + Last Non-9) |
Iterative Static Point Tracking |
Use a dummy head. Find the rightmost node that is not a 9. Increment its value by 1, and set all nodes to its right (which are all 9s) to 0. |
Draw a list like 1 \rightarrow 2 \rightarrow 9 \rightarrow 9. Place a "Point" arrow on the '2'. Change 2 to 3, and then change all 9s after it to 0s in one pass. |
Single-Pass Linear Scan |
Draw a single arrow moving left to right once. $O(N)$. |
Recursive stack for reversing or temporary lists. |
Two pointer variables. Draw two small pointer boxes. $O(1)$. |
| 370 |
Range Addition |
For every update (start, end, inc), iterate through the array from start to end and add inc to each element. |
Nested Range Iteration |
Draw an array. For update 1, draw a bracket and add 2. For update 2, draw a second overlapping bracket and add 3. Label $O(k \cdot N)$. |
Difference Array (Prefix Sum Optimization) |
Boundary Impact Accumulation |
For each update, only modify two points: arr[start] += inc and arr[end+1] -= inc. After all updates, calculate the prefix sum of the array once. |
Draw an array. For an update [+3] on range [1, 3], put "+3" at index 1 and "-3" at index 4. Then draw a "Summing Wave" moving through the array to produce the final values. |
Linear Boundary Processing |
Draw k operations on a single array followed by one pass. $O(k + N)$. |
No extra memory besides the array. |
The same array of size N. Draw one horizontal tape. $O(1)$ extra (in-place). |
| 371 |
Sum of Two Integers |
Using the built-in + or - operators to perform the calculation directly. |
Constant-Time Scalar Operation |
Draw two boxes, an addition symbol, and a result box. Simple and direct. |
Bitwise XOR (Sum) & AND-Shift (Carry) Loop |
[Image of full adder logic circuit]
Logic Gate Simulation |
Think like a CPU: XOR gives the sum without carry. AND shifted left by 1 gives the carry bits. Repeat until carry is zero. |
Draw two binary strings. Underneath, draw the XOR result and the AND-Shift result. Show the shift "carrying" bits to the next column until the carry line is all zeros. |
Iterative State Transformation |
Draw a loop where variables a and b are updated. Label the complexity as $O(1)$ since integers are fixed width (32-bit). |
Single integer variable storage. |
Two 32-bit registers (a and b). Draw two horizontal bit-fields. $O(1)$ space. |
| 372 |
Super Pow |
Calculate a to the power of the huge number represented by the array b using large-integer math libraries. |
Direct Exponentiation Scan |
Draw a giant number a and a very long list of digits b. Draw an arrow attempting to multiply them. Label it $O(\\text{text}{\text{digits in} } b)$. |
Modular Exponentiation + Recursive Property |
Recursive Multi-Stage Power Splitting |
Use the property: a^{[1,2,3]} = a^3 \cdot (a^{[1,2]})^{10}. This allows you to process the array b digit by digit using $O(\log 10)$ modular exponentiation at each step. |
Draw a recursion tree where each node processes the last digit of the array and passes the remaining array up. Show the base^{10} and base^{digit} branches. |
Linear Array Traversal with Logarithmic Sub-steps |
Draw a single pass through the array b. Above each element, write "powMod(10)". Total $O(\\text{text}{\text{len}}(b)$). |
An enormous string or big-int variable. |
Recursion stack of depth proportional to the size of b. Draw a vertical stack of "digit-processing" frames. $O(\\text{text}{\text{len}}(b)$). |
| 373 |
Find K Pairs with Smallest Sums |
Generate every possible pair (u, v) from the two arrays, calculate their sums, sort the entire list, and take the first k. |
Exhaustive Cross-Product Sorting |
Draw an N \times M grid. In each cell, write the sum. Highlight all cells and draw them going into a "Sort" funnel. $O(\text{NM} \\text{log NM})$. |
Min-Heap (Priority Queue) with Dijkstra-like Expansion |
Multi-Pointer Priority Frontier |
Push (nums1[0], nums2[0]) into a Min-Heap. When you pop a pair (i, j), the next candidates are (i+1, j) and (i, j+1). Use a set to avoid duplicates or only increment one index to keep the flow one-directional. |
Draw a grid. Circle the top-left cell. Draw two arrows pointing right and down. Use a "Priority Queue" box to store the tips of these arrows, always picking the smallest. |
Bounded Heap Processing |
Draw a loop that runs k times. Inside, show one "Pop" and two "Pushes" into a heap of size k. $O(k \log k)$. |
A massive list of all N \times M pairs. |
A Min-Heap of size k. Draw a small binary tree (heap) and a result tape. $O(k)$ space. |
| 374 |
Guess Number Higher or Lower |
Iterate through every number from 1 to n and call the `guess(i)` API for each. |
Linear Search Sweep |
Draw a line of numbers. Draw an arrow checking them one by one. $O(n)$. |
Binary Search |
Decision Tree Halving |
Check the middle number. If the API says the target is lower, throw away the right half. If higher, throw away the left half. |
Draw a bar. Cut it in half. Shade the rejected half. Repeat until only one number remains. |
Logarithmic Depth Traversal |
Draw a tree of depth \log n. Label each level as one API call. $O(\log n)$. |
Constant-time variable. |
Three integer boxes (low, mid, high). Draw them side-by-side. $O(1)$. |
| 375 |
Guess Number Higher or Lower II |
Use recursion to try every possible guess x in range [1, n]. For each guess, recursively find the cost of the left and right halves and pick the maximum (worst case). |
Recursive Minimax Explosion |
Draw a root [1, n]. Draw n branches for every possible guess. Label it $O(n!)$. |
Interval Dynamic Programming (Minimax) |
Optimal Substructure Heatmap |
dp[i][j] is the minimum cost to guarantee a win for range [i, j]. To find dp[i][j], iterate through every k \in [i, j] and calculate k + \max(dp[i][k-1], dp[k+1][j]). Pick the k that minimizes this. |
Draw a 2D matrix where the axes are i and j. Show the diagonal (length 1) being 0, then compute length 2, then length 3, filling the upper triangle. |
Quadratic State Matrix with Linear Inner Loop |
Draw a 2D grid. Highlight one cell and show it checking a row and column of other cells. $O(n^3)$. |
Massive recursion stack with redundant interval calls. |
2D DP Matrix. Draw a n \times n grid. Shade the upper-right triangle. $O(n^2)$. |
| 376 |
Wiggle Subsequence |
Generate every possible subsequence (2^n) and check if it follows the "up-down-up" or "down-up-down" pattern. |
N-ary Subsequence Tree (Power Set) |
Draw a root. Branch for every inclusion/exclusion. Highlight the paths where the sign of differences alternates. Label $O(2^N)$. |
Greedy (One-Pass Peak-Valley Counting) |
Zig-Zag Waveform Tracking |
Scan the array. If `nums[i] > nums[i-1]`, you are on an "up" trend. If `nums[i] < nums[i-1]`, you are on a "down" trend. Only count a new element when the trend flips. |
Draw a series of dots on a graph. Draw a zig-zag line connecting them. Circle only the points where the line changes direction (peaks and valleys). |
Linear State-Change Scan |
Draw a single straight arrow through the array. Above it, draw a "toggle" switch that flips between Up and Down. $O(N)$. |
Massive collection of subsequence lists. |
Two integer variables (`up` and `down`). Draw two small boxes that increment based on the trend flip. $O(1)$. |
| 377 |
Combination Sum IV |
Recursively try every number in the array to see how many ways you can reach the target sum. |
N-ary Recursion Tree (Unbounded) |
Draw a root with 'Target'. Draw N branches (one for each number). Continue until leaves are 0. Show the massive width: $O(N^{\text{Target}})$. |
Dynamic Programming (Bottom-Up 1D) |
Cumulative Combination Tape |
`dp[i]` is the number of ways to reach sum `i`. For each sum i from 1 to target, `dp[i] = sum(dp[i - num])` for all numbers in the array. |
Draw a 1D array from 0 to Target. For index 4, draw arrows pointing back to (4-1), (4-2), etc., and sum their values into the current cell. |
Linear DP Fill with Inner Array Loop |
Draw an array. Draw a single loop arrow above it. Label it $O(\\text{text}{\text{Target}} \\text{times} N)$. |
Explosive call stack height. |
1D DP Array Block: Draw a contiguous memory block of size `Target + 1`. $O(\\text{text}{\text{Target}})$. |
| 378 |
Kth Smallest Element in a Sorted Matrix |
Flatten the 2D matrix into a 1D array, sort it globally, and pick the element at index k-1. |
Global Sorting Funnel |
Draw a grid. Draw an arrow pouring all numbers into a single list. Draw a "Sort" box. $O(N^2 \log N^2)$. |
Binary Search on Value Range |
Dual-Axis Partition (Staircase Search) |
Set `low` to min element and `high` to max. For `mid`, count how many elements are \le mid in $O(N)$ by starting at the bottom-left and moving right/up (staircase). Adjust `low`/`high` based on the count. |
Draw a grid. Draw a "staircase" line separating elements \le mid from those > mid. Show the binary search halving the value range. |
Logarithmic Value Range Search with Linear Step |
Draw a number line for values. Below it, draw the matrix staircase step. $O(N \log(\\text{text}{\text{Max}} - \\text{text}{\text{Min}})$). |
A full 1D copy of the matrix. $O(N^2)$. |
Constant-time pointers or a small Max-Heap if using the heap approach. Draw three integer boxes (low, high, count). $O(1)$ or $O(N)$. |
| 379 |
Design Phone Directory |
Use a boolean array to track if a number is used. For `get()`, iterate from 0 to max to find the first `false` value. |
Linear Membership Scan |
Draw a list of numbers. For `get()`, draw an arrow starting at 0 and checking every box until it finds an empty one. $O(N)$. |
Queue + HashSet (Available Pool) |
Recycled Resource Pool |
Initialize a Queue with all available numbers. For `get()`, pop from Queue and add to HashSet. For `release()`, remove from HashSet and push back to Queue. For `check()`, look in HashSet. |
Draw a "Waiting Line" (Queue) of numbers. Draw a "Busy Room" (HashSet). Show a number moving from the line to the room and back. |
Constant-Time Operation Set |
Draw a single box representing the operation. No loops. $O(1)$. |
Only the boolean array. $O(N)$. |
Queue and HashSet. Draw a horizontal tape and a scattered box. Both of size N. $O(N)$. |
| 380 |
Insert Delete GetRandom $O(1)$ |
Use a list to store elements. For `remove()`, find the element and shift all subsequent elements to fill the gap. |
Linear Array Shift |
Draw an array. To remove the middle element, draw arrows showing every element to its right moving one slot left. $O(N)$. |
HashMap + Dynamic Array (Swap with Last) |
Indexed Map with Tail-Swap Removal |
Store values in a List for $O(1)$ random access. Store value-to-index in a HashMap. To remove, swap the target element with the last element in the list, update the HashMap, and then pop the last element. |
Draw a List and a Map. To delete "B", show the last element "Z" moving into "B"'s slot. Update the Map to point "Z" to the new index. Erase the tail. |
Amortized Constant Logic |
Draw three single-step arrows (Map lookup, Swap, Pop). $O(1)$. |
Unordered list with fragmentation. |
Dynamic Array and Hash Map. Draw a contiguous tape and a table. $O(N)$. |
| 381 |
Insert Delete GetRandom $O(1)$ - Duplicates allowed |
Store all elements in a simple list. For removal, search the entire list for the value and remove it, shifting all subsequent elements. |
Linear List Search & Shift |
Draw an array containing [1, 2, 2, 3]. To remove a '2', draw arrows showing the '3' moving left into the '2's spot. Label $O(N)$. |
HashMap of Sets + Dynamic Array |
Multi-Index Map with Tail-Swap Removal |
Use a List to store values. Use a HashMap where the key is the value and the value is a **Set of indices** where that value appears in the list. To remove, pick any index from the Set, swap with the tail, and update the set for the moved tail element. |
Draw a List and a Map. If deleting '2', show the Map pointing to indices 1, 2. Pick index 1. Swap List[1] with the last element. Update the Map to show the last element's new index. |
Amortized Constant Logic |
Draw three discrete steps: 1. Set lookup/pop, 2. Array swap, 3. Tail pop. Label it $O(1)$. |
A raw list with potential fragmentation. |
Dynamic Array + Hash Map of Hash Sets. Draw a tape and a complex table where values point to small scattered boxes (Sets). $O(N)$. |
| 382 |
Linked List Random Node |
Traverse the list to find the total length L. Generate a random number between 0 and L-1, then traverse the list again to that index. |
Two-Pass Length Indexing |
Draw a linked list. Pass 1: Draw a counter incrementing. Pass 2: Draw an arrow jumping node-by-node to the target. Label $O(N)$. |
Reservoir Sampling |
Streaming Probability Selection |
Traverse the list once. For the i-th node, replace the current "chosen" node with the i-th node with probability 1/i. By the end, every node has an equal 1/N chance. |
Draw a list. As you move the pointer, draw a "Dice" icon. At node 1, you pick it. At node 2, you flip a coin to decide if you keep 1 or switch to 2. Label the "Current Winner" box. |
Single-Pass Probabilistic Sweep |
Draw a single line through the list. Above it, write the probability 1/i for each node. Label it $O(N)$. |
An array or list copy of all nodes for random indexing. $O(N)$. |
Only one "current_result" variable. Draw a single box holding the value of the currently selected node. $O(1)$ extra space. |
| 383 |
Ransom Note |
For every character in the ransom note, search the magazine string. If found, remove that character from the magazine so it can't be reused. |
Nested Character Search with Deletion |
Draw two strings. Draw an arrow from 'a' in Note to 'a' in Magazine. Draw an 'X' over the Magazine 'a'. Repeat. Label $O(N \cdot M)$. |
Frequency Array (Counting Sort Pattern) |
Character Inventory Histogram |
Count the occurrences of each of the 26 characters in the magazine using an integer array. Then, iterate through the ransom note and decrement the counts. If any count drops below zero, return false. |
Draw a 26-slot array (a-z). Fill it with counts from the magazine. For each letter in the note, show the number in the corresponding slot "dropping" by one. |
Dual Linear Scan |
Draw two horizontal paths (one for each string) and one small 26-slot box. Label it $O(N+M)$. |
Creating new strings or lists during deletions. |
A fixed-size integer array of size 26. Draw a small horizontal tape with 26 slots. $O(1)$ auxiliary space. |
| 384 |
Shuffle an Array |
Generate all N! permutations of the array, store them in a list, and pick one randomly. |
Permutation Factory Expansion |
Draw an array [1,2,3]. Draw branches for [1,2,3], [1,3,2], [2,1,3], etc. Label the width $O(N!)$. |
Fisher-Yates Shuffle Algorithm |
In-Place Random Swap Boundary |
Iterate from i=0 to n-1. Pick a random index j between i and n-1. Swap nums[i] and nums[j]. Everything to the left of i is now "shuffled". |
Draw an array. Draw a vertical dashed line (the boundary). To the left, "Shuffled". Pick a random element from the right, swap it to the boundary, and move the line. |
Linear Swap Sequence |
Draw an array. Draw a pointer i moving right. At each i, draw a swap arc to a random index to its right. Label $O(N)$. |
A massive list of N! arrays. |
Two arrays: `original` (to reset) and `current` (to shuffle). Draw two horizontal tapes. $O(N)$. |
| 385 |
Mini Parser |
Use heavy regex or manual string splitting to find every bracket and comma, then recursively build the NestedInteger structure. |
Recursive String Fragmenting |
Draw a string like "[123, [456]]". Draw a tree where each bracket pair creates a new level. Label $O(N^2)$ due to string slicing. |
Stack-Based Iterative Parsing |
Hierarchical Container Stacking |
Iterate through the string. When you see '[', push a new NestedInteger onto a stack. When you see a number, add it to the top NestedInteger. When you see ']', pop from the stack and add the popped item to the new top. |
Draw a string. Below it, draw a vertical Stack. As you hit '[', show a new "Box" being pushed onto the stack. When you hit ']', show the "Box" being placed inside the box below it. |
Single-Pass Tokenization |
Draw a single arrow moving through the string. Above it, show a stack growing and shrinking. Label it $O(N)$. |
Large number of intermediate substrings. |
Stack of NestedInteger references. Draw a vertical column of boxes pointing to deeper nested levels. $O(D)$ where D is max depth. |
| 386 |
Lexicographical Numbers |
Generate all numbers from 1 to n as strings, put them in a list, and sort them lexicographically. |
Global String Sorting Funnel |
Draw a box representing a list of numbers. Draw a "Sort" funnel that takes the list and reorders them like words in a dictionary. $O(N \log N)$. |
DFS (Pre-order Traversal of a 10-ary Tree) |
10-Way Digital Search Tree |
Visualize a tree where the root has 9 children (1-9). Each node has 10 children (0-9). Traverse the tree in pre-order (Node, then Child 0, then Child 1...). Stop when a number exceeds n. |
Draw a root node. Draw branches 1, 2, 3... Under 1, draw branches 0, 1, 2... (forming 10, 11, 12). Under 10, draw 0, 1... (forming 100, 101). Show the "DFS Path" line. |
Single-Pass Tree Depth Scan |
Draw a single line tracing the path through the 10-ary tree. Label it $O(N)$ since every number is visited exactly once. |
A list of N string objects. $O(N \cdot \\text{text}{\text{digits}})$. |
Recursion stack depth. Draw a vertical stack of boxes representing the "current prefix". $O(\log_{10} N)$ space. |
| 387 |
First Unique Character in a String |
For every character at index i, scan the rest of the string to see if that character appears again. |
Nested Pointer Sweep |
Draw a string. Place pointer i at the first char. Use a second pointer j to check all other positions. If no match, i is the answer. $O(N^2)$. |
Frequency Array (Hash Map Pattern) |
Character Histogram Bucket |
Perform two passes. Pass 1: Count occurrences of each character in an array of size 26. Pass 2: Iterate through the string again and return the index of the first character whose count in the array is 1. |
Draw a 26-slot array (a-z). As you scan the string, increment the counts. Then draw a pointer moving through the string again, checking the count in the array for each character. |
Dual-Pass Linear Scan |
Draw two parallel horizontal lines representing the two passes over the string. Label it $O(N)$. |
Constant time variables. |
A fixed-size integer array of size 26. Draw a small horizontal tape with 26 slots. $O(1)$ auxiliary space. |
| 388 |
Longest Absolute File Path |
Split the string by newlines. For each line, count the tabs to determine depth, and for every file found, reconstruct the full path by looking at all previous entries. |
Exhaustive Path Reconstruction |
Draw a list of split strings. For a file at depth 3, draw arrows to the most recent items at depth 2, 1, and 0 to build the string. $O(N^2)$. |
Stack / Array Depth Tracking |
Hierarchical Length Stack |
Maintain an array or stack `depth_lengths` where `depth_lengths[i]` is the length of the path up to level i. When moving to depth d, update `depth_lengths[d] = depth_lengths[d-1] + current_len + 1`. |
Draw a vertical stack. As you see a directory, push its length. If a new directory has a smaller tab count, pop until the stack matches the depth. When you see a dot (file), calculate the total. |
Single-Pass Tokenization |
Draw a single arrow moving through the input string. Above it, draw a stack that grows and shrinks. $O(N)$. |
List of all full path strings. $O(N^2)$. |
A stack of integers (lengths). Draw a vertical column of boxes where each box holds a "length" value. $O(\\text{text}{\text{Depth}})$. |
| 389 |
Find the Difference |
For every character in string t, search for it in string s. If found, remove it from s. The remaining character in t is the result. |
Nested Search with Deletion |
Draw two strings s and t. Pick a char in t, draw an arrow to its match in s, and cross both out. The one left in t is the winner. $O(N^2)$. |
Bit Manipulation (XOR) or Character Summation |
Bitwise Cancellation / Mathematical Residue |
XOR all characters in s and t. Since XOR is commutative and x \oplus x = 0, all duplicate characters will cancel out, leaving only the extra character. Alternatively, subtract the sum of s from the sum of t. |
Draw two strings. Draw one large XOR gate. Show all characters from both strings going into the gate. Show the single resulting character coming out. |
Linear Stream Accumulation |
Draw a single straight line representing a single pass over both strings combined. $O(N)$. |
A copy of string s for mutation. $O(N)$. |
A single integer variable for the XOR result or sum. Draw one small box. $O(1)$. |
| 390 |
Elimination Game |
Simulate the entire process using a list of numbers. In each step, remove every other element, alternating directions, until only one is left. |
Shrinking List Simulation |
Draw an array [1, 2, 3... n]. Draw "X" marks over every second number. Redraw the list with the remaining numbers and repeat. $O(N \log N)$. |
Recursive Pattern / Head-Pointer Tracking |
Logarithmic Range Folding |
Track the `head` of the remaining sequence, the `step` size, and the `remaining` count. Move the `head` forward when: 1. Moving left-to-right. 2. Moving right-to-left and the remaining count is odd. Double the `step` and halve the `remaining` count in each round. |
Draw a number line. Mark the `head` with an arrow. In each step, show the `head` jumping or staying put, while the distance between potential numbers (the step) doubles. |
Binary Logarithmic Reduction |
Draw a tree with \log N levels. Each level represents one elimination round. $O(\log N)$. |
An array of size N. $O(N)$. |
Three or four integer variables (`head`, `step`, `remaining`, `left`). Draw four small boxes. $O(1)$. |
| 391 |
Perfect Rectangle |
Check every pair of rectangles (N^2) for any overlap. Then, calculate the total area and compare it to the bounding box area. |
Pairwise Overlap Matrix |
Draw N rectangles. For each one, draw arrows to all others checking if their (x1, y1, x2, y2) boundaries cross. $O(N^2)$. |
Corner Count Set + Area Summation |
Boundary Corner Parity |
If it forms a perfect rectangle: 1. Total area of small rectangles = Area of the large bounding box. 2. All internal corners must appear an even number of times (canceling out), leaving only the 4 exterior corners of the bounding box. |
Draw 4 small rectangles forming one large one. Circle the points where they meet. Show that the meeting points have 2 or 4 corners overlapping, while the 4 outside corners only have 1. |
Linear Set State Tracking |
Draw a single pass through the rectangles. Above it, draw a "HashSet" where corners are added/removed. $O(N)$. |
N^2 comparison results. |
A HashSet of corner strings and 4 boundary variables. Draw a small table (the set) and 4 integer boxes. $O(N)$ space. |
| 392 |
Is Subsequence |
Generate every possible subsequence of string t (2^{|t|}) and check if s is among them. |
Exponential Power Set Tree |
Draw string t. At each char, branch for "include/exclude". Label the 2^N leaves. Impossible for large strings. |
Two Pointers (Greedy Matching) |
Sequential Character Hunt |
Place pointer i on s and j on t. Move j forward through every character. Only move i when s[i] == t[j]. If i reaches the end of s, it's a subsequence. |
Draw two horizontal strings. Draw an arrow i on s and j on t. Draw a vertical "match" line only when the letters are identical, then advance both. |
Linear Single-Pass Sweep |
Draw two parallel lines with arrows moving left-to-right. Label $O(|t|)$. |
All 2^N subsequences in memory. |
Just two integer pointers. Draw two small boxes (i and j). $O(1)$ extra space. |
| 393 |
UTF-8 Validation |
Convert every integer to an 8-bit binary string. Use complex regex or substring matching to check the prefix rules for 1-4 byte characters. |
Binary String Pattern Matching |
Draw each number as "110xxxxx". Use a "Pattern Matcher" box to check subsequent numbers. $O(N)$ but high overhead. |
Bit Manipulation (Bitmasking) |
Leading One Counter |
Iterate through the array. For the first byte, count the leading '1' bits using a mask (e.g., `0x80`, `0x40`). This tells you how many "continuation bytes" (starting with `10`) to expect. |
Draw an 8-bit box. Show an AND operation with `10000000` to check the first bit. Use a "Counter" variable to keep track of how many `10......` bytes are needed. |
Constant-Time Byte Window Scan |
Draw a single pass through the integers. Above it, draw a "Bytes Left" counter that decrements. $O(N)$. |
Strings of binary digits for every number. |
A single `numberOfBytesToProcess` variable. Draw one small integer box. $O(1)$. |
| 394 |
Decode String |
Use recursive regex or search-and-replace to find the innermost brackets, decode them, and replace the substring. Repeat until no brackets remain. |
Multi-pass String Substitution |
Draw a string like `3[a2[c]]`. Circle `2[c]`, replace with `cc`. Redraw the whole string. Repeat. $O(N^2)$. |
Two Stacks (Count Stack & String Stack) |
Nested Frame Context Stacking |
Iterate through the string. When you hit a number, build the count. When `[`: push current string and count to their stacks and reset. When `]`: pop count and prev_string, repeat current string count times and append to prev_string. |
Draw a vertical stack. As you hit `[`, show a "snapshot" of the current string being pushed. As you hit `]`, show the current working string being multiplied and "glued" to the one below it. |
Single-Pass Iterative Parsing |
Draw a single arrow through the string. Above it, show two stacks growing and shrinking. $O(\\text{text}{\text{Output Length}})$. |
Multiple intermediate string copies. |
Two stacks. Draw a "Count Stack" and a "String Stack" side-by-side. $O(N)$. |
| 395 |
Longest Substring with At Least K Repeating Characters |
Check every possible substring (O(N^2)) and for each, count character frequencies (O(26)) to see if all present characters meet the k requirement. |
Triangular Window Scan |
Draw a string. Draw a bracket for every start and end. For each bracket, draw a frequency table. $O(26 \cdot N^2)$. |
Divide and Conquer (Split on Invalid Characters) |
Recursive Pivot Pruning |
Find a character in the string that appears < k times. That character **cannot** be in the final substring. Use it as a pivot to split the string into parts and recurse on each part. |
Draw a long bar (the string). Find a "bad" character like 'z' in the middle. Draw a line through 'z', breaking the bar into two smaller bars. Repeat until all characters in a bar are valid. |
Recursive Sub-problem Tree |
Draw a tree where each node is a string. If a node has an invalid char, it branches into its left and right substrings. $O(N^2)$ worst, $O(N \log N)$ average. |
N^2 substring objects. |
Recursion stack depth. Draw a vertical stack of "String Fragment" boxes. $O(N)$. |
| 396 |
Rotate Function |
For every possible rotation k \in [0, n-1], manually shift the array and calculate the sum \sum_{i=0}^{n-1} i \cdot A[i]. |
2D Matrix of Indexed Multiplications |
Draw n rows. Each row shows the array shifted by one position. Draw n arrows per row representing the index-value multiplication. Label $O(n^2)$. |
Mathematical DP (Linear Recurrence) |
Arithmetic Progression Displacement |
Observe the relationship: F(k) - F(k-1) = \text{Sum}(A) - n \cdot A[n-k]. This allows you to compute the next rotation sum in $O(1)$ based on the previous one. |
Write the full formula for F(0) and F(1). Subtract them on paper to reveal that the entire array sum is added, while the last element is subtracted n times. |
Linear Incremental Update |
Draw a single horizontal line representing a one-pass loop from 0 to n. Label it $O(n)$. |
Temporary array copies for each rotation. Draw n parallel horizontal tapes. $O(n^2)$. |
Two variables: `totalSum` and `currentF`. Draw two small integer boxes. $O(1)$ extra space. |
| 397 |
Integer Replacement |
Recursively try both +1 and -1 for every odd number until you reach 1, exploring all possible paths. |
Binary Decision Tree (Unpruned) |
Draw a root n. For every odd node, branch into (n+1) and (n-1). For even, branch into n/2. Show the tree expanding. Label $O(2^{\log n})$ \approx $O(n)$. |
Greedy (Bit Manipulation) |
Bit-Trailing Zero Optimization |
For odd n: if (n+1) creates more trailing zeros than (n-1), choose (n+1) (exception for n=3). This maximizes the "speed" of the n/2 operations. |
Draw n in binary (e.g., 15 = 1111_2). Show that adding 1 makes it 10000_2, which allows 4 consecutive divisions, whereas subtracting 1 only allows one. |
Logarithmic Bit-Shift Scan |
Draw the binary string of n. Draw a pointer moving right-to-left, "clearing" bits. Label it $O(\log n)$. |
Deep recursion stack for all explored paths. $O(n)$. |
A few integer variables for counts. Draw a single "Steps" counter box. $O(1)$. |
| 398 |
Random Pick Index |
Store all indices for each number in a HashMap (e.g., `Map>`). For `pick(target)`, return a random element from the list. |
Pre-computed Index Map |
Draw a table where keys are numbers and values are lists of indices. Draw a "Dice" being rolled over the list. $O(n)$ space. |
Reservoir Sampling (Memory Efficient) |
Streaming Probability Selection |
Iterate through the array. When you find the `target`, increment a counter `count`. Replace the `result` with the current index with probability 1/count. |
Draw the array. Move a pointer. Every time it hits the target, draw a "Dice" and show the probability 1/k of updating the "Result" box. |
Single-Pass Probabilistic Sweep |
Draw a single straight line through the array. Above it, write the 1/k logic. Label it $O(n)$ time, $O(1)$ extra space. |
A complete Map of all indices in the array. Draw a massive table. $O(n)$. |
Zero extra memory beyond the input array. Draw one "result" and one "count" variable box. $O(1)$. |
| 399 |
Evaluate Division |
For every query a/b, search through all given equations and try to find a chain of multiplications/divisions that links a to b. |
Exhaustive Path Search |
Draw variables as nodes and ratios as edges. For each query, draw an arrow trying every possible neighbor. Label $O(Q \cdot E)$. |
Graph + BFS/DFS or Disjoint Set Union (DSU) with Weights |
Weighted Directed Graph Traversal |
Represent a/b = k as a directed edge a \xrightarrow{k} b and b \xrightarrow{1/k} a. Use DFS to find a path between query nodes, multiplying weights along the way. |
Draw nodes (A, B, C). Draw an edge A \to B with weight 2.0. Draw B \to C with weight 3.0. To find A/C, draw a path A \to B \to C and write 2.0 \times 3.0 = 6.0. |
Linear Graph Traversal per Query |
Draw the graph once. For each query, draw a single highlighted path from start to end. $O(Q \cdot (V+E)$). |
A list of all possible intermediate string combinations. |
Adjacency List + Visited Set. Draw a table mapping strings to lists of (string, double) pairs. $O(V+E)$. |
| 400 |
Nth Digit |
Form a giant string by concatenating numbers 1, 2, 3 \dots until the string length exceeds n. Return the char at index n-1. |
Brute Force String Concatenation |
Draw a tape: "12345678910111213...". Draw a pointer n units long. Label $O(n)$ space and time. |
Mathematical Interval Binary Search |
Digit-Group Skipping |
1. Determine how many digits the number has (1-9 is 9 digits, 10-99 is 90 \times 2 digits, etc.). 2. Find the actual number x. 3. Find the specific digit within x. |
Draw three horizontal bars labeled "1-digit", "2-digits", "3-digits". Show n "jumping" over the first two bars and landing in the middle of the third. |
Logarithmic Range Search |
Draw a number line. Draw large "leaps" representing groups of 10, 100, 1000. Label $O(\log n)$. |
A massive string of length n. $O(n)$. |
Three or four long/int variables. Draw four small boxes. $O(1)$. |
| 401 |
Binary Watch |
Iteration Check all 720 possible times (12 hrs * 60 mins). Count set bits. |
2D Grid |
Draw a 12x60 grid. Shade squares where bit-count == turnedOn. Write $O(1)$ next to it (constant bounded size). |
Backtracking Iterate through the 10 LEDs, choosing to turn them on/off until `turnedOn` is met. |
Decision Tree |
Draw root, branch left (LED off) and right (LED on). Stop branching when depth=10 or bits > turnedOn. |
Draw 10 circles (LEDs). Write '1' or '0' inside them. Keep a running tally of active LEDs. |
Pruned Tree |
Draw a wide tree, but draw thick red "X" marks on branches that exceed the required bit count to show pruning. $O(10 C k)$. |
Variables 2 integer counters for H and M. |
Call Stack Draw stacked blocks up to height 10 representing recursive states. |
| 402 |
Remove K Digits |
Combinations Generate all possible strings by removing K characters, convert to int, find min. |
Exploding Tree |
Draw a starting string. Branch out N times (for each removal). Show massive $O(N^K)$ expansion. |
Monotonic Stack Keep digits in increasing order. Pop if current digit < top of stack and K > 0. |
Array to Bucket |
Left: Input Array. Right: A vertical bucket (Stack). Move digits left to right. If right digit is smaller, "kick out" top of bucket. |
Draw a 'U' shape for the stack. Write numbers vertically. Physically scratch out the top number when popping. Keep a 'K' tally. |
Linear Scan Line |
Draw the array. Draw a single arrow passing over it left to right. Note max 2 touches per element (1 push, max 1 pop) = $O(N)$. |
String Pool Draw hundreds of strings floating to represent $O(N^K)$ space. |
1D Array Draw a single 1D array of size N filling up and emptying. $O(N)$ space. |
| 403 |
Frog Jump |
DFS Recursion At each stone, try jumping k-1, k, and k+1. |
Trinary Tree |
Draw a root node. Draw 3 branches (k-1, k, k+1) from EVERY node. Show exponential $O(3^N)$ growth. |
DP (Hash Map of Sets) Map each stone to a Set of jump lengths that reached it. |
Directed Graph |
Draw stones as nodes. Draw arrows between them labeled with the jump distance. Accumulate sets of distances at each node. |
Draw circles in a line for stones. Above each circle, draw a small box (the Set). Write incoming jump sizes into the box. |
Bounded Graph |
Draw nodes, but show that max edges between nodes is limited to N. Overall complexity $O(N^2)$. |
Call Stack Draw an infinitely deep stack of recursive calls. |
Map of Sets Draw a 2D table where Row = Stone, Column = possible jump sizes stored. $O(N^2)$ space. |
| 404 |
Sum of Left Leaves |
DFS Traversal Visit every node, pass a flag if it's a left child, sum if it's a leaf. |
Tree Traversal |
Draw a binary tree. Trace a line visiting every single node exactly once. $O(N)$. |
DFS/BFS Traversal (Same as Brute force, as you must visit every node to check). |
Flagged Tree |
Color left branches green and right branches red. If a node has a green incoming branch AND no children, circle it. |
Draw a binary tree. Mark left edges with 'L'. Circle nodes that have an incoming 'L' edge and no outgoing edges. |
Tree Traversal |
Draw a binary tree. Draw an arrow entering and leaving every node to show $O(N)$ time. |
Call Stack Draw stack frames equal to the height of the tree $O(H)$. |
Call Stack Draw stack frames equal to the height of the tree $O(H)$. |
| 405 |
Convert a Number to Hexadecimal |
Math Div/Mod Repeatedly modulo by 16 and divide by 16 (fails on negatives without offset). |
Loop Flowchart |
Draw a loop. Inside, write N / 16. Show it looping Log_16(N) times. $O(Log N)$. |
Bit Manipulation Group every 4 bits using bitwise AND (num & 15), then right shift by 4 (num >>> 4). |
Sliding Window over Bits |
Draw a 32-bit binary sequence. Put a 4-bit wide "window" over the rightmost bits. Map to hex, then slide window left. |
Draw 32 boxes (bits). Bracket them in groups of 4. Draw arrows from each group pointing to a Hex character. |
Fixed Loop |
Draw exactly 8 iterations (since 32 bits / 4 = 8 max iterations). Write $O(1)$ time. |
String Builder Draw a growing string. |
Char Array Draw an array of max 8 characters $O(1)$ space. |
| 406 |
Queue Reconstruction by Height |
Permutations Generate all N! line arrangements. Check each to see if the 'k' conditions hold true. |
Factorial Tree |
Draw a root branching to N, then N-1, N-2, showing a massive explosion of branches $O(N!)$. |
Sort + Insert Sort descending by height (h), then ascending by (k). Insert people into a list at index k. |
Cutting in Line |
Line up the tallest people first. Shorter people then "cut in" at their exact 'k' index without blocking the tall people. |
Draw boxes representing people (h, k). Draw the tallest array first. Draw arrows showing shorter boxes wedging between existing ones. |
Sort + Shift |
Draw an $O(N \log N)$ sorting block. Beside it, draw a right triangle representing $O(N^2)$ array element shifts during insertion. |
N! Arrays Massive grid of all possible arrays. |
Dynamic Array One single list resizing and shifting. $O(N)$ space. |
| 407 |
Trapping Rain Water II |
Exhaustive DFS For every inner cell, search all paths to the boundary to find the minimum max-height enclosing it. $O(M^2 N^2)$. |
Radiating Matrix |
Draw a grid. Pick a cell. Draw squiggly lines spreading out from it in all directions to the edges. Repeat for all cells. |
Min-Heap + BFS Push perimeter to min-heap. Pop lowest boundary, process neighbors, add to heap. "Shrinking perimeter". |
Rising Water Level |
Imagine a walled city. Water spills in over the lowest wall first. If an inner building is lower than the spillway, water fills it up to that height. |
Draw a 2D grid top-down. Circle perimeter cells. Cross out the lowest number, draw an arrow to an inner neighbor, calculate trapped water, circle neighbor. |
Heap Processing |
Draw an M*N matrix. Draw an arrow pointing to a logarithmic Tree (Heap) of size M*N. $O(\text{MN} \log(\text{MN})$). |
Call Stack Deep recursive maze stack. |
Priority Queue Draw a binary tree (heap) and a boolean visited grid $O(\text{MN})$. |
| 408 |
Valid Word Abbreviation |
String Expansion Read the abbreviation. If it has numbers, generate the fully expanded string with dummy characters, then compare. |
Expanding Box |
Draw a short string stretching out into a long array of asterisks, mapping 1-to-1 with the target word. $O(N)$. |
Two Pointers Pointer `i` traverses the word, `j` traverses abbreviation. Parse numbers to skip `i` forward. |
Sliding Rulers |
Place string and abbreviation parallel. Slide pointers together on chars. On a number, "jump" the word pointer forward by that amount. |
Write the word and abbreviation aligned. Draw arrows for `i` and `j` underneath. Draw a long arcing jump for `i` when `j` hits a digit. |
Linear Scan Line |
Draw two parallel timelines with a single vertical line scanning across them left to right. $O(N)$ time. |
String Pool Big chunk of memory for the new expanded string $O(N)$. |
Variables Just two integer arrows (pointers). $O(1)$ space. |
| 409 |
Longest Palindrome |
Powerset Generation Generate all possible combinations of characters, check if they can form a palindrome. Keep max length. |
Exponential Tree |
Draw a binary decision tree for each char (include vs exclude), leading to $O(2^N)$ leaf nodes. |
Hash Map / Frequency Array Count char frequencies. Add all even counts. Add (odd-1) for odd counts. Add 1 if any odd exists. |
Pairing Socks |
Dump all characters in a pile. Find matching pairs and place them on the left/right. If any singles are left, put exactly one in the middle. |
Write down letters. Tally them. Draw circles around pairs of 2. Draw one distinct box for a leftover character to sit in the center. |
Two-Phase Scan |
Draw a long line traversing the string $O(N)$. Followed by a short, fixed-length line scanning the 128 ASCII array $O(1)$. |
String Combos Massive pool of substring arrays. |
Fixed Array Draw a 128-slot pigeonhole box (ASCII map). $O(1)$ space. |
| 410 |
Split Array Largest Sum |
Backtracking (DFS) Try inserting `k-1` dividers into the array in every possible position. Find max sum of each configuration, keep the global minimum. |
Partition Tree |
Draw an array. Draw moving vertical walls. Branch the tree for every possible wall placement configuration. Combinatorial explosion. |
Binary Search on Answer Binary search the "max sum" (Low: max(arr), High: sum(arr)). Greedily count chunks needed for each guess. |
Capacity Buckets |
Guess a bucket size. Walk through the array pouring numbers into a bucket. If a bucket overflows the guess, grab a new bucket. If you need > k buckets, guess was too small. |
Draw a number line for Binary Search. Pick a Mid. Draw an array. Draw 'U' shaped buckets. Fill buckets with numbers up to Mid. Count buckets. |
Search inside Scan |
Draw a Binary Search tree (representing Log(Sum)). Inside each node, draw a linear array scan $O(N)$. Total $O(N \\text{cdot Log}(\text{Sum})$). |
Recursion Depth Stack frames K levels deep. |
Pointers Draw 4 integer boxes: low, high, mid, current_sum. $O(1)$ space. |
| 411 |
Minimum Unique Word Abbreviation |
Exhaustive Search Generate all 2^M abbreviations for the target word. Check each one against every dictionary word. |
Exponential Tree |
Draw a branching tree representing string subsets (2^M). From each leaf, draw lines to N dictionary words. $O(N \cdot 2^M)$. |
Bitmask + Backtracking Find character differences as bitmasks. Use DFS to find the shortest abbreviation mask that covers all difference constraints. |
Bitwise Filter Mask |
Stack the target and dict word. If chars differ, place a '1'. If same, '0'. You need an abbreviation mask that shares at least one '1' with every dict mask. |
Write the target word. Below it, write dict words. Draw vertical lines connecting differing chars. Write binary bits (1s and 0s) next to them to represent conflicts. |
Pruned State Space |
Draw a binary decision tree but heavily cross out branches with red X's where the mask fails a bitwise AND check early. |
String Array Pool Giant heap of all string combinations. |
Integer Array A small 1D array of bitmasks (integers). $O(N)$ space. |
| 412 |
Fizz Buzz |
If-Else Chain Iterate 1 to N. Check modulo 15, then 3, then 5, else stringify the number. |
Loop Flowchart |
Draw a simple loop box from 1 to N with a constant $O(1)$ decision diamond inside. $O(N)$. |
String Concatenation (Better for scale/many conditions). Append "Fizz" if mod 3, append "Buzz" if mod 5. Output if empty. |
Assembly Line |
An empty string moves down a conveyor belt. Station 3 stamps "Fizz". Station 5 stamps "Buzz". If it reaches the end blank, stamp the number. |
Draw a horizontal line (belt). Draw downward arrows labeled '3' and '5'. Write the resulting word building up block-by-block left to right. |
Linear Pipeline |
Draw a straight line for N iterations. $O(N)$ time. |
N Strings Draw N independent string blocks. |
Result Array Exact same, return structure requires $O(N)$ space. |
| 413 |
Arithmetic Slices |
All Subarrays Generate all $O(N^2)$ subarrays. Scan each to see if differences are uniform. $O(N^3)$. |
Nested Cubes |
Draw a 3D block representing i, j, and k nested loops. Huge $O(N^3)$ volume. |
1D DP / Two Pointers If arr[i]-arr[i-1] == arr[i-1]-arr[i-2], current slices = prev slices + 1. Add to total sum. |
Expanding Differences Window |
Look at the gaps between numbers. If you see consecutive identical gaps, your "combo multiplier" increases by 1 each step. |
Write the array. Draw 'V' shapes between numbers with the difference. When 'V' numbers match consecutively, underline them and write "+1, +2, +3". |
Single Array Scan |
Draw one continuous arrow left-to-right over the array. $O(N)$. |
Subarray Memory Large chunks of duplicated array slices. |
Two Variables Draw two small boxes: `curr` and `total`. $O(1)$ space. |
| 414 |
Third Maximum Number |
Sort & Scan Sort the array descending $O(N \log N)$. Iterate to find the 3rd distinct element. |
Sorting Funnel |
Draw an unsorted array tunneling through a wide $O(N \log N)$ sorting block, emerging ordered. |
Top-3 Variables Keep `first`, `second`, `third` initialized to -Infinity. Update them sequentially as you iterate $O(N)$. |
Podium Displacement |
Imagine a 3-step podium. A new high score comes in. 1st place steps down to 2nd, 2nd steps down to 3rd, 3rd gets kicked off. |
Draw 3 vertically stacked boxes. When a new number arrives, physically cross out the values and draw arrows pushing the old values down one box. |
Single Pass Stream |
Draw a stream of numbers hitting a 3-slot filter exactly once. $O(N)$ time. |
Array Copy Duplicated array of size N for sorting. |
3 Pointers Draw exactly three integer boxes. $O(1)$ space. |
| 415 |
Add Strings |
Parse to Int Use built-in parseInt() or Integer.valueOf(). Fails instantly on overflow > 64 bits. |
Overflow Bomb |
Draw a massively long string entering a small 64-bit integer box and drawing explosion lines (Overflow Error). |
Two Pointers (Right to Left) Traverse both strings backwards. Add digits plus carry. Append to StringBuilder and reverse. |
Primary School Addition |
Stack the two strings right-aligned exactly how you learned to add large numbers in elementary school. Process column by column. |
Draw strings stacked vertically. Draw vertical lines for columns. Circle the column sum. Draw a swooping left arrow to carry the '1' to the next column. |
Parallel Reverse Scan |
Draw two arrays. Draw an arrow starting at the end of each, moving backwards in tandem. Max(L1, L2) time. |
Large Int Object Memory allocated for a BigInt structure. |
String Builder Draw a growing character array. $O(\text{Max}(L1, L2)$) space. |
| 416 |
Partition Equal Subset Sum |
Recursive DFS For every number, choose to include it in "Subset A" or not. Check if sum == total/2. |
Binary Tree |
Draw a root. Each level represents a number in the array. Draw 2 branches from every node (Include/Exclude). $O(2^N)$. |
0/1 Knapsack DP (1D) Use a boolean array `dp` where `dp[i]` is true if sum `i` is possible. |
Staircase Filling |
Draw a row of boxes labeled 0 to TargetSum. Start with 0 as "True". For each number, "jump" forward and mark new boxes True. |
Draw a 1D horizontal grid. For each number in the input, draw arrows from existing 'T' cells to new 'T' cells. Write from right-to-left. |
Area Calculation |
Draw a rectangle with Width = TargetSum and Height = N. Complexity is the area $O(N \\text{cdot TargetSum})$. |
Call Stack Deep vertical stack of recursive decisions. |
Boolean Strip Draw a single 1D array of booleans. $O(\text{TargetSum})$ space. |
| 417 |
Pacific Atlantic Water Flow |
Cell-by-Cell DFS For every single cell in the grid, run a DFS to see if you can reach both oceans. |
Repeating Blobs |
Draw a grid. Pick a cell, draw a messy ink blob spreading. Pick the next cell, draw another blob. $O((\text{MN})$^2). |
Multi-source BFS/DFS Start from the Pacific edges and "flow uphill." Do the same for Atlantic. Find the intersection. |
Inverse Flood Fill |
Imagine the oceans are "rising." Paint the cells they can reach. The cells with both colors are your answer. |
Draw two empty grids. In Grid 1, shade everything reachable from top/left. In Grid 2, shade from bottom/right. Overlay them. |
Linear Grid Pass |
Draw the grid once. Show that each cell is visited max twice (once for each ocean). $O(M\cdot N)$. |
Call Stack Massive recursion depth for every cell. |
Two Bitmaps Draw two boolean grids (PacificReachable, AtlanticReachable). $O(M\cdot N)$. |
| 418 |
Sentence Screen Fitting |
Greedy Simulation Place words word-by-word, row-by-row. If a word doesn't fit, move to the next row. |
Scrolling Text |
Draw a screen. Write words until you hit the edge. Move down. Show $O(\text{Rows} \\text{cdot MaxWordsPerRow})$. |
DP / Pre-calculated Jumps Join sentence with spaces. At each screen column start, pre-calculate which word the next row will start with. |
Circular Loop Mapping |
Imagine the sentence as a repeating circular belt. Map each position on the belt to where the next "jump" lands. |
Draw a circle with words on the perimeter. Draw "jump" arrows from different starting points to their landing points after one 'Cols' length. |
Jump Table |
Draw a table of size 'SentenceLength'. Show one jump per Row. $O(\text{Rows} + \text{SentenceLength})$. |
Screen Buffer Not much, but the simulation process is slow. |
Jump Array Draw an array of integers representing "next index" pointers. $O(\text{SentenceLength})$. |
| 419 |
Battleships in a Board |
DFS / BFS Traversal When you find an 'X', trigger a DFS to sink the ship and increment count. |
Component Scan |
Draw a grid with ships. Draw a circle around each ship. Note that you visit each 'X' and its neighbors. $O(M\cdot N)$. |
Single Pass (Head Counting) Iterate through the grid. Only count an 'X' if it doesn't have an 'X' above it or to its left. |
Top-Left Anchor |
Scan like a laser. Only "beep" when you hit the very first (top-left) cell of a ship. Ignore the rest of the ship's body. |
Draw a grid. For an 'X', check the cell above and the cell to the left. If both are empty/off-board, circle it. If not, ignore. |
Scanline |
Draw a single horizontal line passing top-to-bottom over the grid once. $O(M\cdot N)$. |
Visited Matrix Draw a 2D boolean grid to track "sunk" parts. $O(M\cdot N)$. |
None Zero extra memory beyond the input. $O(1)$ space. |
| 420 |
Strong Password Checker |
BFS / State Search Treat the password as a start state. Each edit (ins, del, rep) is a transition. Find shortest path to "Strong". |
Massive State Space |
Draw a starting string. Branch into 3 directions for every single character position. Total $O(3^N)$ or worse. |
Greedy + Case Analysis Categorize by length: <6 (Insert), 6-20 (Replace), >20 (Delete then Replace). Priority on deleting from repeating triplets. |
Resource Balancing |
Imagine three "needs": Length, Types (Upper/Lower/Digit), and Repeating Chars. Use Deletions to solve Repeating Chars first. |
Draw three buckets labeled "Insert", "Delete", "Replace". Put counts in them based on 3 specific math rules for each length category. |
Constant Constraints |
Draw a logic flowchart. No nested loops. Time is strictly proportional to password length N. $O(N)$. |
Queue A BFS queue storing thousands of string variations. |
Variables Just a few integer counters for edits and repeats. $O(1)$. |
| 421 |
Max XOR of Two Numbers |
Nested Loops Compare every pair (i, j) and calculate i \oplus j. Keep max. |
2D Grid |
Draw an N \times N matrix. Shade the upper triangle. Label it $O(N^2)$. |
Bitwise Trie Insert all numbers into a Binary Trie. For each number, traverse the trie trying to pick the opposite bit. |
Decision Path Tunneling |
Imagine a 32-level deep tree. For each number, you "tunnel" down the path that gives you the most 1s in the result. |
Draw a binary tree where each node has only '0' and '1' branches. Trace a path for number X, trying to go left if X's bit is 1 and right if 0. |
Linear-Tree hybrid |
Draw N horizontal lines hitting a tree of height 32. Complexity: $O(N \\text{times} 32)$ \approx $O(N)$. |
Registers Two CPU registers for XORing. |
Trie Structure Draw many small linked nodes representing bits. $O(N)$ space. |
| 422 |
Valid Word Square |
Simulation For every character at [i][j], check if it matches the character at [j][i]. |
Matrix Mirror |
Draw a square grid. Draw a diagonal line from top-left to bottom-right. Check if colors match across the line. |
Direct Indexing Compare `words[i].charAt(j)` with `words[j].charAt(i)` with boundary checks. |
L-Shape Reflection |
Highlight the i-th row. Highlight the i-th column. They must be identical strings. |
Write words in a grid. Use a ruler to look at the 3rd row, then rotate the ruler 90 degrees to check the 3rd column. |
Grid Scan |
Draw a single pass through the total number of characters C. $O(C)$. |
Grid Copy Storing the words twice. |
None In-place comparison. $O(1)$ extra space. |
| 423 |
Reconstruct Digits from English |
Backtracking Try all combinations of number-words to see which matches the input string's character counts. |
Permutation Tree |
Draw a tree branching into 10 directions (0-9) at every step. Total $O(10^\text{StringLength}/3)$. |
Unique Char Counting Observe unique identifiers: 'z' is only in zero, 'w' in two, 'x' in six. Subtract counts in a specific order. |
Process of Elimination |
Imagine a bucket of letters. Pick out all 'z's and take their corresponding 'e', 'r', 'o' with them. Move to the next unique char. |
List numbers 0-9. Next to each, write its "Unique Character" (e.g., 0: 'z', 2: 'w', 4: 'u'). Draw arrows "subtracting" counts from a master frequency map. |
Dual Scan |
Draw a line over the input string (count chars) + a fixed 10-step loop. $O(N)$. |
Call Stack Massive recursion for string permutations. |
Count Array Draw a small 26-slot integer array. $O(1)$ space. |
| 424 |
Longest Repeating Char Replacement |
All Substrings Check every substring (i, j). Find most frequent char, see if (length - freq) \le k. |
Nested Substring Grid |
Draw a matrix where each cell is a substring. Show $O(N^2)$ cells, each taking $O(N)$ to check. $O(N^3)$. |
Sliding Window (Expand/Contract) Use two pointers. Keep track of `maxFreq` in current window. If `windowSize - maxFreq > k`, shrink left. |
Inchworm Movement |
The "head" (right) stretches forward. The "tail" (left) only pulls forward when the "stomach" (k) can't handle the variety of characters. |
Draw a string. Draw a bracket [ \dots ] over a section. Below, write a tally of chars. If (total - max) > k, shift the left bracket. |
Two-Pointer Scan |
Draw an array with two arrows moving left-to-right. Neither arrow ever moves back. $O(N)$. |
Substring Copies Massive memory for N^2 string slices. |
Frequency Map Draw a 26-slot array for current window counts. $O(1)$ space. |
| 425 |
Word Squares |
Brute Force Backtracking Try every possible word for every row in the square. Check validity at the end. |
Giant Choice Tree |
Draw a tree with N levels, where each node has W branches (W = \# of words). $O(W^N)$. |
Trie-Based Backtracking Use a Trie to instantly find all words that start with a specific prefix (the prefix being the current column's characters). |
Prefix Constraints |
Row 0 is "BALL". This means Row 1 MUST start with 'A', Row 2 with 'L', Row 3 with 'L'. Use the Trie to find these words instantly. |
Draw an empty 4 \times 4 grid. Write "BALL" in row 1. Draw arrows from Row 1's letters to the first letters of subsequent rows. |
Pruned Search Tree |
Draw the same tree but show most branches ending immediately because the Trie returns "No words with this prefix." |
Result List Storing thousands of invalid square attempts. |
Trie + Recursion Draw the Trie structure and the recursion stack of depth L (word length). |
| 426 |
Convert BST to Sorted DLL |
Traverse & Store Perform In-order traversal, store nodes in a List, then loop through list to connect pointers. |
Two-Pass Scan |
Draw a Tree. Below it, draw a separate Linear Array of nodes. Show arrows connecting the Array nodes. $O(N)$. |
In-Place In-order Maintain a `first` and `last` pointer. Connect `last.right = current` and `current.left = last` during traversal. |
Magnetic Pointer Snapping |
Imagine the BST nodes are magnets. As you visit in-order, they "snap" together horizontally. |
Draw a BST. Use a red pen to trace the in-order path. At each node, draw dotted lines to its predecessor and successor. |
Single Tree Walk |
Draw a single continuous line weaving through the tree $O(N)$. No extra structures. |
Extra List Draw a block of N node references in memory. $O(N)$. |
Call Stack Draw stack frames for tree height. $O(H)$. |
| 427 |
Construct Quad Tree |
Naive Check For every square, check every single pixel to see if they are the same value. If not, divide. |
Overlapping Grids |
Draw a grid. Draw many smaller boxes inside, with redundant arrows checking the same pixels repeatedly. $O(N^2 \log N)$. |
Divide & Conquer Recursively check if a quadrant is "leaf". If all 4 children are leaves and same value, merge. |
Recursive Box Splitting |
Draw a big square. If it's not uniform, draw a cross in the middle to make 4 squares. Repeat. |
Draw an 8x8 grid. Draw a cross splitting it to 4x4s. In one 4x4, if all bits are '1', write 'Leaf'. If mixed, split again. |
Grid Coverage |
Draw the grid. Show that each pixel is processed in a way that maps to the total pixels. $O(N^2)$. |
Redundant Objects Massive creation of temporary check arrays. |
Tree Nodes Draw a 4-ary tree where height is log(N). $O(N^2)$ space for nodes. |
| 428 |
Serialize/Deserialize N-ary Tree |
Parenthesis String Convert tree to string like `A(B,C(D,E),F)`. Hard to parse back with varying children. |
Recursive Stringify |
Draw a tree being "crushed" into a long string with many brackets. Complexity $O(N)$. |
Pre-order with Child Count Serialize as `Value, ChildCount`. E.g., `1,3,2,0,3,0,4,0` (Node 1 has 3 children...). |
Flattened Stream |
Imagine a tree being fed into a woodchipper and coming out as a perfectly ordered line of labeled blocks. |
Draw a tree. Next to each node, write the number of its children. Follow the pre-order path and write the pairs (Val, Count). |
Linear Sequence |
Draw an arrow moving through the tree once, then an arrow moving through the string once. $O(N)$. |
String Concatenation Many temporary string objects. |
String Builder/Queue A single buffer or queue for processing. $O(N)$. |
| 429 |
N-ary Tree Level Order Traversal |
DFS with Depth Use DFS and pass a 'depth' variable. Add node to the corresponding sub-list in results. |
Scattered Traversal |
Draw a tree. Show an arrow jumping deep, then back up, then deep again, filling buckets at the bottom. |
BFS (Queue) Use a Queue. Process all nodes in the current queue (one level) before moving to the next. |
Ripple Effect |
Imagine a stone dropped at the root. The "waves" move outward level by level. |
Draw a tree. Circle the root (Level 0). Draw a horizontal line. Circle all its children (Level 1). Draw another line. |
Level Scan |
Draw horizontal layers. Each node is touched exactly once. $O(N)$. |
Call Stack Stack depth equal to tree height. $O(H)$. |
Queue Buffer Draw a horizontal queue holding the widest level of the tree. $O(W)$. |
| 430 |
Flatten Multilevel DLL |
Recursive Collection DFS through all levels, store all nodes in a list, then rebuild all next/prev pointers. |
Two-Pass Build |
Draw a 3D-looking list. Below it, draw a single flat line. Show arrows from the 3D nodes to the line. |
Iterative Stack / Pointer Weaving When you hit a `child`, "insert" the child branch between `current` and `current.next`. |
Accordion Flattening |
Imagine the multilevel list is a folded accordion. You are pulling it from both ends until it is one straight line. |
Draw a list with a "down" branch. Draw an arrow from `current.next` to the end of the `child` branch, and from `current` to the `child` head. |
Edge Weaving |
Draw a list. Each "child" edge is moved exactly once. Total time $O(N)$. |
Extra List $O(N)$ space for the intermediate list. |
Stack Draw a stack of "return-to" pointers (the `next` nodes you skipped). $O(N)$ worst case. |
| 431 |
Encode N-ary Tree to Binary Tree |
Left-Child Right-Sibling (Basic) Map the first child of a node to the left child of the binary node, and siblings to the right. |
Tree Warp |
Draw an N-ary tree. Draw a "slanted" version where children are pushed left and siblings right. $O(N)$. |
LCRS (Recursive Pointer Re-assignment) Use a recursive DFS to transform pointers without creating new nodes. |
Skewed Perspective |
Imagine the N-ary tree is flexible. Tilt it 45° so siblings hang vertically from each other. |
Draw an N-ary tree. Connect siblings with red lines. Erase the original child-parent lines except for the first child. |
Linear Traversal |
Draw one arrow visiting every node in the N-ary tree once. $O(N)$. |
New Binary Nodes Create an entirely new $O(N)$ tree structure. |
Call Stack Height of the tree $O(H)$. |
| 432 |
All O`one Data Structure |
Hash Map + Sort Keep string counts in a Map. For `getMax/Min`, sort the map values. |
Sorting Spike |
Draw a Map. For every "Get" operation, draw a massive "Sort" wall $O(N \log N)$. |
Hash Map + Doubly Linked List of Buckets Map strings to nodes. Nodes are buckets of strings with the same count. Buckets are linked in order of count. |
Train of Buckets |
A train where each car is a "Count" (1, 2, 5). If a string's count increases, it jumps to the next car or creates a new one. |
Draw a horizontal DLL where each node contains a Set of strings. Use arrows from a separate Hash Map pointing into these Set nodes. |
Constant Horizon |
Draw a straight horizontal line for every operation (Inc, Dec, Get). $O(1)$ for all. |
Map Storage Just the string counts. |
Hybrid Structure Map (O(N)) + DLL (O(N)). Total $O(N)$. |
| 433 |
Minimum Genetic Mutation |
DFS (Exhaustive) Try all possible single-character mutations from the start gene, recurring until the end gene is found. |
Exploding Maze |
Draw a root string. Branch into all 24 possible 1-char mutations. Show the tree expanding exponentially. |
BFS (Shortest Path) Use a Queue. For each mutation, check if it's in the "bank". Use a visited set to avoid cycles. |
Level Ripples |
Start gene is the center. Each step (mutation) is a new circular wave. Stop as soon as the wave hits the end gene. |
Draw nodes for genes. Connect genes that differ by 1 letter. Trace the shortest hop-count path from Start to End. |
Graph Layering |
Draw levels 1, 2, 3... Complexity is $O(B \cdot L \cdot N)$ where B=bank size, L=gene length. |
Call Stack Recursion depth can be high with cycles. |
Queue + Set Draw a Queue and a "Visited" HashSet of strings. $O(B)$. |
| 434 |
Number of Segments in a String |
String Split Use built-in `.split("s+")` and count the resulting array length. |
Temporary Array |
Draw a string being cut into 5-10 small boxes. Total $O(N)$ time and $O(N)$ space. |
Single Pass Count Iterate through characters. Count a segment whenever you see a non-space character that follows a space (or is at index 0). |
Flag Sensor |
Imagine a sensor that "beeps" every time it transitions from "Empty Space" to "Solid Character." |
Draw a string. Draw a dot above every character that is NOT a space but HAS a space (or nothing) to its left. |
Linear Scan |
Draw one arrow passing over the string. $O(N)$. |
Array Storage $O(N)$ for the split string array. |
None Just one integer counter. $O(1)$. |
| 435 |
Non-overlapping Intervals |
Recursive Combinations Try every combination of removing/keeping intervals. Check for overlaps. $O(2^N)$. |
Binary Decision Tree |
Draw a tree where each node is "Keep interval i?" (Yes/No). Show 2^N leaf nodes. |
Greedy (Sort by End Time) Sort intervals by their end times. Always pick the one that ends earliest to leave maximum room for others. |
The Early Bird |
A timeline. Several meeting bars. Always pick the meeting that finishes first, then look for the next meeting that starts after it. |
Draw intervals on a timeline. Mark "X" through any interval that starts before the current "Last End Time." |
Sort + Scan |
Draw an $O(N \log N)$ sorting block followed by a single $O(N)$ scan line. Total $O(N \log N)$. |
Recursion Stack $O(N)$ depth. |
In-place Sort $O(1)$ extra space (or $O(\log N)$ for sort stack). |
| 436 |
Find Right Interval |
Nested Loops For each interval i, iterate through every other interval j to find the min j.start \ge i.end. |
Comparison Matrix |
Draw an N \times N grid of checkboxes. For each interval, you look at every other box. $O(N^2)$. |
Binary Search + Sort Store all `start` values in a sorted list with original indices. For each `end`, binary search the list. |
Sorted Pointer Array |
Draw the original intervals. Below, draw an array of just the `start` values in ascending order. "Probe" the array with each `end` value. |
Draw two horizontal lists. List A (unsorted intervals). List B (sorted starts). Draw an arrow from List A[i].end into List B using "High/Low" markers. |
Sort-Search Hybrid |
Draw an $O(N \log N)$ sorting block plus N small $O(\log N)$ search trees. Total $O(N \log N)$. |
Registers No extra storage beyond the result array. |
Map/Tuple Array Draw a sorted list of (start, index) pairs. $O(N)$. |
| 437 |
Path Sum III |
Double DFS For every node in the tree, start a new DFS to find all downward paths that sum to target. |
Radial Exploding Tree |
Draw a tree. From every single node, draw a secondary "mini-tree" of path explorations. $O(N^2)$ (skewed) or $O(N \log N)$ (balanced). |
Prefix Sum + DFS Use a Hash Map to store "Prefix Sum -> Frequency". If (CurrentSum - Target) exists in the map, a path is found. |
Backtracking Shadow |
Imagine a light shining from the root. The "shadow" is the sum accumulated so far. The Map keeps track of all shadows seen in the current branch. |
Draw a tree path. Next to each node, write the running sum. Maintain a small "Tally Table" (the Map) on the side. Strike out entries when you backtrack. |
Linear Depth Pass |
Draw one continuous line visiting every node once. $O(N)$. |
Call Stack $O(H)$ recursion depth. |
Hash Map + Stack Draw the Map and the Call Stack growing together. $O(H)$ space. |
| 438 |
Find All Anagrams in a String |
Substring Sort Extract every substring of length P. Sort it. Sort P itself. Compare. |
Nested Sorted Slices |
Draw a string. Draw many overlapping brackets. For each bracket, draw a mini sorting process $O(N \cdot P \log P)$. |
Sliding Window + Frequency Map Use an array of size 26. As the window moves, increment the "entering" char and decrement the "leaving" char. |
Balancing Scales |
Imagine two frequency "scales." One is fixed (Target P). The other shifts. If the scales match exactly, you found an anagram. |
Draw two 26-slot boxes. Write the target counts. Draw a sliding window over the string, updating the counts and checking for a match. |
Continuous Scan |
Draw one single scan line. Each step is $O(1)$. Total $O(N)$. |
String Pool Massive memory for extracted substrings. |
Two Fixed Arrays Draw two 26-slot integer arrays. $O(1)$ extra space. |
| 439 |
Ternary Expression Parser |
Recursive Evaluation Parse the first `T?` or `F?`, find the corresponding `:`, and recurse on the valid branch. |
Branching Maze |
Draw the expression. Show arrows jumping forward to find colons, then backward. Redundant scanning. $O(N^2)$. |
Stack (Right-to-Left) Scan the string backwards. If you hit a `?`, pop the next two values from the stack and push the result based on the condition. |
Reverse Collapsing |
Imagine the expression is a spring being compressed from right to left. Each `?` "eats" the two results behind it. |
Draw the string. Scan backwards. Draw a "Stack" bucket. Push numbers/chars. When you hit `?`, draw a circle around the top two stack items and replace them. |
Single Pass |
Draw one arrow moving from Right to Left. $O(N)$. |
Call Stack Depth of nested ternaries. |
Value Stack Draw a vertical stack of characters. $O(N)$. |
| 440 |
K-th Smallest in Lexicographical Order |
String Sort Generate all numbers from 1 to N, convert them to strings, and sort them lexicographically. |
Sorting Wall |
Draw a massive list of numbers. Show the $O(N \log N)$ sorting process. |
Denary Tree Traversal Visualize numbers as a 10-ary tree (1, 10, 100...). Calculate "steps" between prefixes to skip whole subtrees. |
Pyramid Skipping |
Imagine a 10-level pyramid. If K is larger than the number of nodes in a subtree, "jump" over the pyramid to the next sibling. |
Draw a root '1'. Draw 10 children. Label how many nodes are under '1' (e.g., 10, 11, 100...). Use subtraction to "jump" K across siblings. |
Logarithmic Tree Path |
Draw a path down a tree. $O(\log N \cdot \log N)$ as you traverse the depth and calculate widths. |
Full Number List Massive $O(N)$ space to hold all numbers. |
None Just a few integer variables (current, k, steps). $O(1)$. |
| 441 |
Arranging Coins |
Linear Iteration Subtract 1, then 2, then 3... from N until the remainder is less than the next row. |
Staircase Build |
Draw a staircase of coins. Each row adds 1. Show a linear scan of $O(N^{0.5})$. |
Binary Search / Math Search for k such that \frac{k(k+1)}{2} \le N or use the quadratic formula directly. |
Number Line Halving |
Draw a line from 1 to N. Check the midpoint. If too many coins, move left; if too few, move right. |
Draw a number line. Mark L, M, and R. Calculate the sum for M and cross out half the line in each step. |
Search Tree |
Draw a binary search tree of depth \log N. Total $O(\log N)$. (Or $O(1)$ for Math). |
Variable One integer remainder. |
Registers Constant space. $O(1)$. |
| 442 |
Find All Duplicates in an Array |
Nested Loops / Sort Check every pair or sort and check neighbors. |
Comparison Grid |
Draw an N \times N grid. Show checking every element against every other. $O(N^2)$. |
In-place Marking For each number x, go to index |x|-1 and flip the value to negative. If already negative, it's a duplicate. |
Index-Value Mirror |
Imagine the array values are "addresses." Visit each address and leave a "seen" flag (the negative sign). |
Draw an array. For index 0, look at its value (say 4). Go to index 4. Draw a circle around it and add a minus sign. |
Linear Pipeline |
Draw a single arrow moving left to right once. Each visit is $O(1)$. Total $O(N)$. |
HashSet Draw a "Bucket" taking up $O(N)$ extra space. |
None No extra space beyond result list. $O(1)$ (in-place). |
| 443 |
String Compression |
String Builder Iterate and append characters and their counts to a new string/list. |
Parallel Buffer |
Draw the original array. Below it, draw a second array being filled with characters and digits. $O(N)$. |
Two Pointers (Read/Write) Use `read` and `write` pointers. `read` finds the end of a group; `write` updates the array in-place. |
Trailing Shadow |
The `read` pointer is a scout. The `write` pointer is a builder following behind, overwriting old data. |
Draw an array. Draw an arrow R moving fast and an arrow W moving slow. Label W as the "New Length" tracker. |
Dual Pointer Scan |
Draw two arrows moving together. Each index is visited twice. $O(N)$. |
Result String Draw a second block of memory of size N. $O(N)$. |
None Draw two integer pointers in a small box. $O(1)$. |
| 444 |
Sequence Reconstruction |
Permutations Generate all possible valid sequences from the rules and see if only one exists. |
Factorial Tree |
Draw an explosion of possible number orderings. $O(N!)$. |
Topological Sort (Kahn's) Build a graph of dependencies. Check if at every step there is exactly 1 node with an in-degree of 0. |
Dependency Waterfall |
Imagine tasks with arrows between them. You can only pick a task if all arrows pointing to it are "cleared." |
Draw circles (numbers) and arrows (dependencies). Keep an "In-degree" table on the side. Scratch off counts as you process nodes. |
Graph Traversal |
Draw nodes (V) and edges (E). Time $O(V + E)$. Space $O(V + E)$. |
List of Lists Storing all permutations. |
Adjacency List Draw a map of numbers pointing to their next neighbors. $O(N)$. |
| 445 |
Add Two Numbers II |
Reverse and Add Reverse both linked lists, perform addition (like Q2), and reverse the result back. |
Tri-Phase Loop |
Draw two lists being flipped. Then added. Then flipped again. Total 3 passes. $O(N)$. |
Two Stacks Push all nodes of both lists onto two stacks. Pop from both to add from right-to-left. |
Vertical Collapsing |
Imagine the lists are being fed into two vertical "wells" (stacks). The numbers at the bottom of the wells are added first. |
Draw two vertical buckets. Fill them with numbers. Draw arrows popping from the top and summing them into a new Linked List. |
Linear Stack Flow |
Draw two passes to fill stacks, then one pass to empty. $O(N+M)$. |
Pointer Swap Very little extra space (if modifying input). |
Call Stack/Stack Structure Draw two vertical arrays of size N and M. $O(N+M)$. |
| 446 |
Arithmetic Slices II - Subsequence |
Exhaustive Subsequences Generate all 2^N subsequences and check if each is arithmetic. |
Exponential Decision Tree |
Draw a binary tree with N levels. Every leaf is a potential subsequence. $O(2^N \cdot N)$. |
DP with Map Matrix Use an array of HashMaps `dp[i]`, where `dp[i][diff]` stores count of slices ending at i with difference `diff`. |
Sparse Multi-Table |
Visualize as a sparse 2D table where Rows are Indices and Columns are "Differences." Each cell stores a count. |
Draw an array. Below each element, draw a small vertical list of (diff: count) pairs. Draw arrows from previous indices' lists to current. |
Area Calculation |
Draw a rectangle of N \times N (max possible differences). $O(N^2)$ time. |
Bitset Huge memory for all 2^N combinations. |
Map of Maps Draw N distinct hashmap "clouds" in memory. $O(N^2)$ space. |
| 447 |
Number of Boomerangs |
Triple Loop For every triple (i, j, k), calculate distance dist(i,j) and dist(i,k). If equal, increment. |
Nested Cubes |
Draw a 3D block representing i, j, k nested loops. $O(N^3)$. |
Hash Map of Distances For each point i, calculate distances to all other points j. Store counts in a Map `dist: count`. Result is \sum count \times (count - 1). |
Radial Grouping |
Imagine point i is a radar. Circles around i group points by distance. Any circle with >1 point forms boomerangs. |
Draw points on a plane. Pick one point. Draw concentric circles passing through other points. Count points per circle and apply n(n-1). |
Quadratic Scan |
Draw a 2D grid pass. One loop for i, one inner loop for j. $O(N^2)$ time. |
Register No extra space beyond loops. |
Frequency Map Draw a single Map that gets cleared and reused for each point i. $O(N)$ space. |
| 448 |
Find All Numbers Disappeared in an Array |
Sorting / HashSet Sort and find gaps, or add all to a HashSet and check for 1 to N. |
Sorting Wall |
Draw the sorting process $O(N \log N)$ or a large HashSet bucket $O(N)$. |
In-place Negation For each value x, treat |x|-1 as an index and make the value at that index negative. Positives remaining are the gaps. |
Internal Flagging |
Imagine the array is a row of lockers. Each number is a key. Go to the locker number on the key and "paint it red" (negative). |
Draw an array. For index 0, read value 4. Go to index 3 (4-1). Add a minus sign. Repeat. Circle indices that stay positive. |
Linear Pipeline |
Draw a single pass through the array. $O(N)$ time. |
HashSet Draw a second auxiliary structure of size N. |
None No extra space except result list. $O(1)$ (in-place). |
| 449 |
Serialize and Deserialize BST |
Standard Tree Traversal Convert to string with markers for nulls (e.g., Pre-order + "#" for null). |
Marked Stream |
Draw a tree and a string with many extra special characters. $O(N)$. |
Pre-order + Bounds Use Pre-order without null markers. Rebuild using BST property (current value must be within [min, max]). |
Flattened BST Stream |
Draw the tree being squashed into a compact string of numbers. |
Draw a BST. Write its pre-order sequence. Reconstruct by drawing nodes only if they fit between the parent's limits. |
Linear Pass |
One pass to stringify, one to parse. $O(N)$ time. |
String Pool Extra memory for null markers. |
String Builder / Queue Compact string representation. $O(N)$ space. |
| 450 |
Delete Node in a BST |
Rebuild Tree Store all nodes in a list (except the target), then rebuild a balanced BST from scratch. |
List Transformation |
Draw a tree \to Linear List \to New Tree. $O(N)$. |
Recursive Re-linking Find node. If it's a leaf, remove. If 1 child, replace with child. If 2 children, replace with In-order Successor (min in right subtree). |
Pointer Re-wiring |
Visualize the "Successor" climbing up the tree to take the empty seat. |
Draw a BST. Circle the node to delete. Find the smallest node in its right branch. Draw an arrow moving it into the deleted spot. |
Path Traverse |
Draw a single path from root to leaf. $O(H)$ where H is height. |
Extra List Memory for all N nodes. |
Call Stack Stack depth equal to $O(H)$. |
| 451 |
Sort Characters By Frequency |
Global Sort Count frequencies in a Map, convert Map entries to a List, and sort the list by frequency descending. |
Sorting Funnel |
Draw a Map. Show it dumping into a List. Draw the $O(N \log N)$ sorting block. Total $O(N \log N)$. |
Bucket Sort Use an array where the index is the frequency. Put characters into the bucket at `frequency[char]` index. |
Frequency Pigeonholes |
Imagine a shelf with numbered bins. If 'e' appears 3 times, toss it in Bin 3. Read bins from highest to lowest. |
Draw an array where indices are 0, 1, \dots, N. Write chars inside the boxes. Scan the array backwards to build the string. |
Linear Pipeline |
Draw one arrow for counting $O(N)$, one for bucketing $O(N)$, and one for building $O(N)$. Total $O(N)$. |
List of Tuples Draw a separate array of length N containing object pairs. |
Bucket Array Draw an array of Lists. The sum of lengths of all lists is $O(N)$. |
| 452 |
Minimum Number of Arrows to Burst Balloons |
Exhaustive Subsets Try every possible x-coordinate for an arrow and check how many balloons it hits. Combinatorial explosion. |
Infinite Laser Grid |
Draw a set of intervals. Show arrows being shot at every possible integer point. Infinite/Exponential search space. |
Greedy (Sort by End) Sort balloons by their end coordinates. Shoot one arrow at the end of the first balloon; skip all that overlap. |
Interval Overlap Strike |
Imagine horizontal bars on a graph. A vertical line (arrow) hits as many as possible. Always shoot at the "deadline" (end). |
Draw bars on a timeline. Sort by end. Draw a vertical line at the end of the first bar. Circle all bars hit. Repeat for the next uncircled bar. |
Sort + Scan |
Draw an $O(N \log N)$ sorting block + one $O(N)$ horizontal scan line. Total $O(N \log N)$. |
None No extra space beyond pointers. |
None Just one integer for arrow count and one for the current arrow position. $O(1)$ space. |
| 453 |
Minimum Moves to Equal Array Elements |
Simulation Increment n-1 elements in each step until all are equal. (Too slow for large differences). |
Incremental Stairs |
Draw a bar chart. In each step, n-1 bars grow by 1. Show the slow, linear crawl toward equality. $O(\text{Moves} \\text{times} N)$. |
Mathematical Reduction Incrementing n-1 elements is mathematically equivalent to decrementing 1 element. Sum up the distance of each element from the minimum. |
Floor Leveling |
Imagine several towers. To make them equal, just find the shortest tower and "cut off" the excess from all others. |
Draw towers of different heights. Draw a dotted line at the height of the shortest tower. Sum the lengths of the "cut off" sections. |
Linear Scan |
Draw one arrow finding the minimum, then one arrow summing differences. Total $O(N)$. |
Register One variable for the state. |
Registers Two variables: `min` and `sum`. $O(1)$ space. |
| 454 |
4Sum II |
Quadruple Loop Use four nested loops to check every combination of A[i] + B[j] + C[k] + D[l] == 0. |
Hyper-cube |
Draw a 4D grid (impossible, so draw 4 nested squares). $O(N^4)$. |
Hash Map (Meet-in-the-Middle) Calculate all A+B and store in a Map `sum: count`. Then iterate C+D and check for -(C+D) in the Map. |
Divided Bridge |
Split the 4 arrays into two pairs. Build a bridge (Map) for one pair. The other pair just checks if they can cross the bridge. |
Draw two groups of arrays. Group 1: Draw a Map of sums. Group 2: Draw arrows checking their negative sums against the Map. |
Dual Quadratic |
Draw two $O(N^2)$ blocks side-by-side. Total $O(N^2)$. |
Registers No extra space beyond loops. |
Frequency Map Draw a Map storing up to N^2 sums. $O(N^2)$ space. |
| 455 |
Assign Cookies |
Recursive Match Try every possible pairing of children and cookies to find the maximum satisfaction. |
Bipartite Matching Tree |
Draw children on left, cookies on right. Draw every possible line. Show $O(2^N)$ or factorial search. |
Two Pointers + Greedy Sort both arrays. Give the smallest cookie that satisfies the child with the smallest greed factor. |
Dual Ladder Climb |
Two lists. Two arrows. If the cookie arrow value \ge child arrow value, both move up. If not, only the cookie arrow moves to find a bigger one. |
Write both arrays. Sort them. Draw an arrow c (child) and k (cookie). Move them and tally matches. |
Sort + Scan |
Draw two $O(N \log N)$ sorting blocks followed by a single $O(N)$ scan. Total $O(N \log N)$. |
Call Stack High recursion depth. |
None Just two integer pointers. $O(1)$ space. |
| 456 |
132 Pattern |
Triple Loop Check every triplet (i, j, k) where i < j < k to see if nums[i] < nums[k] < nums[j]. |
Nested Cubes |
Draw three nested loops. Label the volume as $O(N^3)$. |
Monotonic Stack (Right-to-Left) Keep a stack of potential "2" values (middle magnitude) and track the largest "3" value found so far. |
Cliff and Valley Map |
Visualize the array as a mountain range. You are looking for a peak ("3") that has a slightly lower hill ("2") to its right and a deep valley ("1") to its left. |
Draw a line graph of the numbers. Use a vertical "Stack" bucket. As you scan left, pop smaller values to find the "next greater" value. |
Single Scan Line |
Draw one arrow scanning the array once. Each element enters and leaves the stack max once. $O(N)$. |
None Constant space beyond logic. |
Monotonic Stack Draw a vertical stack of numbers that always stays in sorted order. $O(N)$. |
| 457 |
Circular Array Loop |
Exhaustive DFS From every index i, follow the pointers to see if you return to i. Keep a "Visited" set for each start. |
Redundant Webs |
Draw a circle of nodes. From each node, draw a messy path. $O(N^2)$. |
Two Pointers (Slow/Fast) Use Floyd's Cycle-Finding algorithm. A fast pointer moves 2 steps, slow moves 1. Check for direction changes or single-node loops. |
Race Track |
Imagine two runners on a circular track. If there's a loop, the fast runner will eventually "lap" the slow runner. |
Draw a "Clock Face" with array indices. Draw jump arrows. Move a "S" and "F" marker. If they land on the same spot, a loop exists. |
Grid Coloring |
Draw the array once. Color nodes "Dead" as you finish checking them to ensure each node is visited only once. $O(N)$. |
HashSet Draw N different sets in memory. $O(N)$. |
None Use the array itself or one "State" array. $O(1)$ extra or $O(N)$ for state. |
| 458 |
Poor Pigs |
Simulation Try different combinations of pigs and buckets. Hard to simulate because it's a math/information limit. |
Search Space Tree |
Draw a tree of pigs drinking from buckets. Very confusing and non-linear. |
Information Theory (N-Dimensional Hypercube) Each pig represents a dimension. The number of states a pig can have is (Tests + 1). Solve (States)^{Pigs} \ge Buckets. |
Hypercube Coordinates |
Imagine a 3D cube. Each axis is a "round." A pig drinking from a "plane" of the cube identifies one coordinate of the poison bucket. |
Draw a 2D grid for 2 pigs. Label rows for Pig 1 and columns for Pig 2. Each cell is a bucket. Pig 1 drinks row 1 in round 1, etc. |
Constant Math |
Draw a simple log calculation: \lceil \log_{states}(Buckets) \rceil. $O(1)$ or $O(\log N)$ for the math. |
None Constant variables. |
Registers Just a few math variables. $O(1)$. |
| 459 |
Repeated Substring Pattern |
Prefix Testing Try every possible substring length L from 1 to N/2. See if it can be repeated to form S. |
Shrinking Substring Grid |
Draw the string. Below it, draw it broken into 2 pieces, then 3, then 4... $O(N^2)$. |
String Doubling Trick Concatenate S+S. Remove the first and last characters. If S is still a substring of the result, it has a repeated pattern. |
Telescopic Shift |
Imagine two identical rulers side-by-side. If you shift one ruler and the markings still line up perfectly, the pattern is repeating. |
Write the string S twice. Shift the second S by one character. If the internal sequence matches the original S, return true. |
String Search |
Draw two strings being compared. $O(N)$ using optimized string search (like KMP). |
String Buffer Storing many substring variations. |
Doubled String Draw one string of size 2N. $O(N)$ space. |
| 460 |
LFU Cache |
Map + Search Use a Map for key-value pairs and a second Map for frequencies. For eviction, scan for the minimum frequency. |
Linear Eviction Scan |
Draw a Map. Every time you evict, draw a line scanning through all N entries to find the min frequency. $O(N)$ per `put`. |
Hash Map + Linked List of DLLs Map keys to nodes. Have a second "Frequency Map" that points to a Doubly Linked List of all keys with that frequency. |
Train of Compartments |
A train where each car is a "Frequency" (1, 2, 3...). Inside each car is a list of keys. New keys go in Car 1. Used keys move to the next car. |
Draw a vertical DLL of frequencies. From each frequency node, draw a horizontal DLL of keys. Draw a separate Map pointing directly to key nodes. |
Constant Horizon |
Draw a straight line for `get` and `put`. Every move is just re-linking pointers. $O(1)$ time. |
Two Maps Storing keys and frequencies separately. |
Hybrid Structure Draw the complex Map + DLL of DLLs structure. $O(N)$ total space. |
| 461 |
Hamming Distance |
String Conversion Convert both integers to 32-bit binary strings and compare character by character. |
Parallel Scan |
Draw two 32-box arrays. Draw arrows comparing each pair. Label $O(1)$ (fixed size). |
Bitwise XOR + Bit Counting XOR the two numbers (x \oplus y). Count the set bits using Brian Kernighan’s algorithm. |
Difference Filter |
XOR highlights only bits that are different. Counting them gives the distance directly. |
Draw two binary rows. Draw a third row (XOR) where 1 marks a difference. Circle the 1s and tally. |
Bitwise Jump |
Draw a bit sequence. Show arrows "jumping" only over the 1-bits. $O(\\text{text}{\text{set bits}})$ which is \le 32. |
String Pool Extra memory for binary string representation. |
Registers Single integer register. $O(1)$. |
| 462 |
Min Moves to Equal Elements II |
Exhaustive Check Try every element in the array as the target value. Calculate total distance for each. |
Distance Matrix |
Draw an N \times N grid of distances. For each row (target), sum the columns. $O(N^2)$. |
Median Target (Greedy) The point that minimizes the sum of absolute differences is the median. Sort and find the middle. |
Central Convergence |
Visualize points on a number line. Moving toward the center reduces total distance until you hit the median. |
Draw a number line with dots. Draw arrows from outermost dots toward the center. Where they meet (median) is the goal. |
Sorting funnel |
Draw an $O(N \log N)$ sorting block + one $O(N)$ sum pass. Total $O(N \log N)$. |
None Constant variables. |
None In-place sort. $O(1)$ or $O(\log N)$ depending on sort. |
| 463 |
Island Perimeter |
Naive Neighbor Count For every '1' (land) cell, check all 4 neighbors. If neighbor is water or off-board, add 1. |
Scanning Laser |
Draw a grid. Pick a cell. Draw 4 radiating arrows. Total $O(M \\text{times} N \\text{times} 4)$. |
Single Pass (Shared Edge) Count land cells \times 4. Subtract 2 for every shared edge (horizontal or vertical neighbor). |
Jigsaw Mapping |
Every land cell starts with 4 edges. When you snap two "tiles" together, two edges disappear. |
Draw two adjacent boxes. Write "4" in each. Draw a thick line where they touch and write "-2". Total = 6. |
Grid Pass |
Draw a single horizontal scan line over the grid. $O(M \\text{times} N)$. |
None Zero extra storage. |
None Just one integer counter. $O(1)$. |
| 464 |
Can I Win |
Recursive Game Tree Try every possible number choice for Player 1, then for Player 2, until a winner is found. |
Exponential Tree |
Draw a tree branching M, M-1, M-2 \dots levels deep. $O(M!)$. |
Recursion + Bitmask Memoization Use an integer bitmask to represent which numbers are used. Cache result in a Map `mask: win/loss`. |
State Space Pruning |
The bitmask represents a "key" to a room. If you've been in the room (state) before, use the cached answer. |
Draw a binary bitmask (e.g., `1011`). Next to it, write "T/F". Show arrows from different branches leading to the same bitmask. |
State Count |
Complexity is the number of possible states. $O(2^M)$. |
Call Stack Massive factorial depth. |
Memo Table Draw a boolean array/map of size 2^M. $O(2^M)$. |
| 465 |
Optimal Account Balancing |
Recursive Permutations Try every possible sequence of transfers between people with positive and negative balances. |
Factorial Tree |
Draw people nodes. Draw all possible arrows. Massive $O(N!)$ exploration. |
Backtracking on Net Balances Flatten everyone into their net balance. Try to settle one person's balance with any other person of the opposite sign. |
Bucket Settlement |
Imagine "plus" buckets and "minus" buckets. Pour from one to another until a bucket is empty. Find the minimum pours needed. |
List net balances: `[10, -5, -2, -3]`. Start with 10. Give 5 to the second person. Update list and move to the next index. |
Pruned State Search |
Draw a tree where each node is a "settlement" action. Pruning happens when a balance hits zero. $O(N!)$. |
Graph Buffer Storing all transactions. |
Balance Array Draw a small 1D array of net balances. $O(N)$. |
| 466 |
Count The Repetitions |
Linear Scan Construct strings s_1 \times n_1 and s_2 \times n_2 and use two pointers to count matches. |
Mega-String Scan |
Draw two massive horizontal lines representing 10^6 characters. Show a pointer crawling $O(n_1 \cdot |s_1|)$. |
Cycle Detection (Pigeonhole) Record the `index` in s_2 after each s_1. If the same index repeats, a cycle is found. Calculate remainder math. |
Loop with Remainder |
Visualize a circle where each lap covers a fixed amount of s_2. Calculate full laps plus the final "broken" lap. |
Draw a timeline. Mark points where s_1 ends. Note the pointer position in s_2. Circle the repeating sequence of positions. |
Compressed Scan |
Draw a line that "short-circuits" once it hits a loop. $O(|s_1| \cdot |s_2|)$ to find the loop. |
String Buffer Massive memory for the giant concatenated string. |
State Map A small Map storing `index -> (countS1, countS2)`. $O(|s_2|)$ space. |
| 467 |
Unique Substrings in Wraparound String |
Exhaustive Substrings Generate all substrings of p. For each, check if it exists in the infinite 'abcd...z' wraparound. |
Substring Grid |
Draw an N \times N grid. Each cell is a substring check. $O(N^3)$ (with check). |
DP (Max Length per Char) Track the longest "consecutive" sequence ending at each character ('a' through 'z'). The sum of these 26 values is the result. |
26-Slot High Watermark |
Imagine 26 buckets labeled a-z. As you scan p, update a bucket if you find a longer consecutive sequence ending in that letter. |
Write the string p. Below it, write the "current run" length. Maintain an array of 26 max-lengths. Update the array only if current > existing. |
Linear Pipeline |
Draw one arrow scanning p once. Total $O(N)$. |
HashSet A set storing every unique substring found. $O(N^2)$. |
Fixed Array Draw one 26-slot integer array. $O(1)$ extra space. |
| 468 |
Validate IP Address |
String Split + Multi-IF Split by "." or ":" and run a gauntlet of manual checks (length, hex vs dec, leading zeros). |
Conditional Maze |
Draw a complex flowchart with dozens of "Yes/No" diamonds. $O(N)$ but error-prone. |
Regex or Modular Parsing Use pre-defined Regex patterns for IPv4 and IPv6 to handle boundaries and valid character ranges in one pass. |
Template Matching |
Overlay the input string on top of a "Ghost Template" for IPv4 and IPv6. If it doesn't align with either, reject. |
Draw the structure: `X.X.X.X` vs `X:X:X:X:X:X:X:X`. Below each segment, write its specific constraints (e.g., 0-255). |
Pattern Match |
Draw a single pass through the string. $O(N)$. |
String Pool Extra memory for split substrings. |
Regex Engine Negligible extra memory. $O(1)$. |
| 469 |
Convex Polygon |
Angle Summation Calculate all internal angles of the polygon. If sum is (n-2) \times 180^\circ and no angle > 180^\circ, it's convex. |
Trigonometric Grid |
Draw a polygon. Draw arcs for every angle. Label $O(N)$ with heavy floating-point math. |
Cross Product (Orientation) For every three consecutive points, calculate the cross product. All cross products must have the same sign (all positive or all negative). |
Consistent Turning |
Imagine driving a car around the polygon. To be convex, you must only ever turn "Left" or only ever turn "Right." Never both. |
Draw a polygon. Draw arrows between vertices. At each vertex, draw a small arc showing the "turn" direction. All arcs should curve the same way. |
Vector Scan |
Draw an arrow moving from vertex to vertex calculating a simple determinant. $O(N)$. |
Register Storing floating-point angles. |
None Just three integer variables for current/prev cross products. $O(1)$. |
| 470 |
Implement Rand10() Using Rand7() |
Naive Range Map Call `rand7()` twice. If sum > 10, discard and retry. (Doesn't produce uniform distribution). |
Skewed Distribution |
Draw a bell curve. Show that middle numbers appear more often than edges. Label "INCORRECT." |
Rejection Sampling (7x7 Matrix) Create a range of 1-49 using `7 * (rand7() - 1) + rand7()`. If the result is > 40, reject it. Otherwise, return `result % 10 + 1`. |
Grid Mapping |
Draw a 7 \times 7 grid (49 cells). Color the first 40 cells with 10 different colors (4 cells each). Color the last 9 "Discard." |
Draw a 7 \times 7 grid on paper. Label cells 1-49. Circle cells 41-49 and write "Reroll." |
Expected Call Value |
Draw a probability tree. The expected number of calls is 2 \times (49/40) = 2.45. Average $O(1)$. |
None Constant variables. |
None Just two variables for the coordinates. $O(1)$. |
| 471 |
Encode String with Shortest Length |
Exhaustive Recursion Try every possible split point and every possible repetition pattern for every substring. |
Exploding Tree |
Draw a string. Branch out for every split point k. Inside each branch, search for repetitions. $O(2^N)$. |
Interval DP `dp[i][j]` stores the shortest encoded string for `s[i...j]`. Check for patterns using `(s+s).indexOf(s, 1)`. |
Substring Matrix |
Fill a 2D table where cells represent substrings of increasing length. Use previously computed smaller cells to build larger ones. |
Draw an N \times N grid. Fill it diagonally starting from length 1. For `dp[0][4]`, show it checking `dp[0][k] + dp[k+1][4]`. |
Triangle Fill |
Draw the upper triangle of a grid. Total $O(N^3)$ or $O(N^4)$ depending on string search. |
Recursion Stack Deep tree of string fragments. |
String Matrix Draw a 2D grid where each cell holds a string. $O(N^2 \cdot N)$ space. |
| 472 |
Concatenated Words |
Nested Search For each word, try to split it into all possible prefixes and suffixes. Check if each exists in the original list. |
Factorial Splits |
Draw a word. Draw every possible "cut" line. For each cut, repeat. Total $O(N \cdot 2^L)$ where L is length. |
Trie + DFS/Memoization Sort words by length. Insert into a Trie. For each word, use DFS to see if it can be formed by existing Trie words. |
Prefix Tree Pathing |
Walk down the Trie. When you hit a "Word End," split and start a new walk from the root for the remainder. |
Draw a Trie. Trace a path for "catsdogcats". When you hit 'cats', circle the node and draw a second arrow starting back at the root for 'dog'. |
Pruned Graph |
Draw the Trie nodes visited. Complexity $O(N \cdot L^2)$ with memoization. |
HashSet Large set of all words. |
Trie Map Draw a tree of characters. $O(N \cdot L)$ space. |
| 473 |
Matchsticks to Square |
Exhaustive DFS Try placing each matchstick into one of 4 "sides". Check if all sides equal `TotalSum / 4`. |
4-ary Tree |
Draw a root. Branch into 4 directions for match 1, then 4 for match 2. Total $O(4^N)$. |
DFS with Pruning / Bitmask DP Sort matchsticks descending. Try placing in a side; if it exceeds `target`, backtrack immediately. |
Bucket Filling |
Imagine 4 identical buckets. Try to pour "lengths" (matchsticks) into them without any bucket overflowing. |
Draw 4 vertical bars. Write "Target" at the top. Draw matchsticks as blocks filling these bars. Cross out configurations that overflow. |
Pruned Search |
Draw the 4-ary tree but show most branches ending at level 1 or 2 due to "Sum > Target" checks. |
Call Stack Full depth N stack. |
Bitmask Table Draw an array of size 2^N. $O(2^N)$ space. |
| 474 |
Ones and Zeroes |
Subset Generation Generate all 2^N subsets of strings. Count total 0s and 1s for each. Keep the largest valid subset. |
Exponential Tree |
Draw a binary decision tree (Pick/Don't Pick) for each string. $O(2^N)$. |
2D Knapsack DP `dp[i][j]` is max strings using `i` zeros and `j` ones. Update backwards to save space. |
Constraint Matrix |
Imagine a 2D grid where X-axis is "Zeros Available" and Y-axis is "Ones Available." Each string is a "Cost" that lets you move in the grid. |
Draw a 2D grid (e.g., 5 \times 3). For a string "001", show moving from `dp[2][1]` to `dp[0][0]` and adding +1 to the count. |
Triple Loop Area |
Draw a 3D block: Strings \times MaxZeros \times MaxOnes. $O(L \cdot M \cdot N)$. |
Subsets Massive memory for all string combinations. |
2D Integer Grid Draw a single M \times N matrix of integers. $O(M \cdot N)$ space. |
| 475 |
Heaters |
Nested Scan For each house, find the distance to every heater. Take the min distance for that house. Then take the max of all those mins. |
Comparison Matrix |
Draw an H \times G grid (Houses \times Heaters). Show checking every pair. $O(H \cdot G)$. |
Binary Search (Sorted Heaters) Sort heaters. For each house, binary search for the two closest heaters (one left, one right). |
Proximity Tethers |
Draw dots for houses and stars for heaters on a number line. For each dot, draw an elastic tether to the nearest star. The longest tether is the answer. |
Draw a number line. Mark Heaters. For a House X, find the heater index i such that `Heaters[i]` is just above X. Compare with `Heaters[i-1]`. |
Search-per-House |
Draw H small binary search trees of height \log G. Total $O((H+G)$ \log G). |
Distance Array Storing all min-distances. |
None In-place sorting. $O(1)$ extra space. |
| 476 |
Number Complement |
String Conversion Convert integer to binary string, flip '0's to '1's and '1's to '0's, convert back. |
Char-by-Char Scan |
Draw a string of bits. Draw a second string below with flipped values. $O(\\text{text}{\text{Bits}})$. |
Bitwise Mask XOR Find the highest set bit. Create a mask of all 1s of that length. Result is `num ^ mask`. |
Light Switch Filter |
Imagine the 1s in the mask are "switches." XORing flips the state of the original bits only where the switches are ON. |
Write the number in binary. Write the mask (all 1s) directly below it. Draw vertical lines; if both are 1, write 0. If 1 and 0, write 1. |
Constant Jump |
Draw a single bitwise logic gate diagram. Total $O(1)$ (or $O(\\text{text}{\text{bits}})$ which is \le 32). |
String Pool Buffer for the binary string. |
Registers Single integer mask. $O(1)$. |
| 477 |
Total Hamming Distance |
Nested Loops Compare every pair of numbers (i, j), calculate their Hamming Distance, and sum them up. |
Comparison Grid |
Draw an N \times N grid. Each cell is a 32-bit XOR comparison. $O(N^2 \cdot 32)$. |
Bit-by-Bit Counting For each bit position (0-31), count how many numbers have a '1' (k) and how many have a '0' (n-k). Distance contribution is k \times (n-k). |
Column-wise Scan |
Stack all numbers vertically in binary. Scan column-by-column rather than row-by-row. |
Draw 3-4 numbers as 8-bit binary rows. For the first column, count total 1s and 0s. Multiply them. Repeat for all 8 columns. |
Linear-to-32 |
Draw a rectangle where Width = 32 and Height = N. Complexity $O(32 \cdot N)$. |
Register Sum variable. |
None Constant extra space. $O(1)$. |
| 478 |
Generate Random Point in a Circle |
Rejection Sampling Generate random x, y within the bounding box of the circle. If distance from center > R, discard and retry. |
Dartboard Misses |
Draw a square with a circle inside. Draw random dots. Cross out dots outside the circle. $O(1)$ average time. |
Inverse Transform (Polar) Generate \theta \in [0, 2\pi] and r = R \sqrt{\text{rand()}}. The square root is crucial for uniform density. |
Expanding Ripple |
Imagine the circle is made of thin rings. To keep density equal, outer rings must get more points than inner ones. \sqrt{r} scales this perfectly. |
Draw a circle. Draw two arrows: one for angle \theta, one for radius r. Write the formula x = r \cos \theta, y = r \sin \theta. |
Pure Math |
Draw a straight-line logic flow. Total $O(1)$. |
None Constant storage. |
None Constant variables. $O(1)$. |
| 479 |
Largest Palindrome Product |
Exhaustive Search Multiply every n-digit number by every other n-digit number. Check if the product is a palindrome. |
Quadratic Explosion |
Draw a multiplication table of size 10^n \times 10^n. Huge search space. $O(10^{2n})$. |
Greedy Palindrome Generation Start from the largest possible palindrome (e.g., 999999) and work downwards. For each, check if it has two n-digit factors. |
Descending Mirror |
Imagine a countdown. Create a palindrome by mirroring 999 \to 999999. Then 998 \to 998899. Stop as soon as you find valid factors. |
Write 999, 998, 997 \dots in a column. Next to each, draw its "mirror." For each mirror, show a short trial-division loop. |
Bounded Search |
Draw a downward arrow. The search space is significantly reduced. $O(10^n)$ average. |
None Product variables. |
None Constant space. $O(1)$. |
| 480 |
Sliding Window Median |
Sort every window For every window of size k, copy the elements into a new array, sort it, and find the middle. |
Repeated Sorting Wall |
Draw a sliding window. At each step, draw a full $O(k \log k)$ sorting process. Total $O(N \cdot k \log k)$. |
Two Heaps (Balance) / TreeSet Use a Max-Heap for the left half and a Min-Heap for the right half. Use "Lazy Removal" with a Hash Map to handle elements leaving the window. |
Balanced Scales |
Imagine two buckets. The left is heavy (Max), the right is light (Min). Keep them level. As the window slides, "lazy delete" elements that fell out. |
Draw two vertical buckets. Write "Small" and "Large". As you slide, draw a tally of "Pending Deletes" next to the buckets. Rebalance so |Small| \approx |Large|. |
Logarithmic Maintenance |
Draw a single horizontal scan. At each step, show a small $O(\log k)$ heap adjustment. Total $O(N \log k)$. |
Window Copies Full $O(k)$ array copies at every step. |
Heaps + Map Draw two binary heaps and a "Deletes" Map. $O(k)$ space. |
| 481 |
Magical String |
Manual String Build Use string concatenation to build the "12211..." sequence by checking the tail of the string repeatedly. |
Incremental Growth |
Draw a string. For every new char, draw an arrow back to an earlier index to see "how many" to add. $O(N^2)$ due to string immutability. |
Two Pointers (Generator/Consumer) Use an `int[]` or `char[]` and two pointers: `head` (reading how many) and `tail` (writing what's next). |
Self-Consuming Belt |
Imagine a conveyor belt. The "head" is a sensor reading a number, and the "tail" is a stamper adding that many 1s or 2s further down the belt. |
Draw a long horizontal array. Mark 'head' at index 2 and 'tail' at the end. Move 'head' forward, look at its value, and write that many characters at 'tail'. |
Linear Pipeline |
Draw a single pass from 1 to N. Each step is $O(1)$. Total $O(N)$. |
String Pool Massive overhead for immutable string objects. |
Fixed Array Draw one array of size N. $O(N)$ space. |
| 482 |
License Key Formatting |
Forward Simulation Remove dashes, convert to upper, then iterate forward and try to insert dashes at the right intervals. |
Shifting Array |
Draw a string. For every dash insertion, show all characters to the right being shifted. $O(N^2)$. |
Reverse Traversal Start from the end of the string. Collect K characters, add a dash, and repeat. Reverse the result at the end. |
Reverse Grouping |
Imagine filling boxes from right to left. Since the "first" group can be shorter, the end is the only stable anchor. |
Write the alphanumeric string. Draw an arrow starting at the last char, moving left. Every K steps, draw a vertical line (dash). |
Single Pass |
Draw one arrow scanning the string once. $O(N)$. |
Intermediate Strings Multiple copies of the string during split/join. |
StringBuilder Draw one buffer growing to size N. $O(N)$ space. |
| 483 |
Smallest Good Base |
Exhaustive Base Search Try every base k from 2 to n-1. For each k, check if n can be represented as 1+k+k^2... |
Linear Search Space |
Draw a line from 2 to n. Show a loop checking every single base. $O(N \log N)$. (Too slow for 10^{18}). |
Binary Search on Length The number of '1's can only be between 2 and 64. For each fixed length m, binary search for base k. |
Inverted Search Space |
Instead of searching millions of bases, search 60 possible lengths. For each length, the base k is found via binary search. |
Draw a column 2 to 64. For each row, draw a horizontal number line (Binary Search) to find k. |
Log-Squared Complexity |
Draw 60 small binary search trees. Total $O(\log^2 n)$. |
None Constant variables. |
None Constant variables. $O(1)$. |
| 484 |
Find Permutation |
Lexicographical Permutations Generate all N! permutations. Check each against the 'D' and 'I' pattern. Return the smallest. |
Factorial Tree |
Draw a root branching N, N-1 \dots levels. Label the explosion as $O(N! \cdot N)$. |
Stack-Based Reversal Use a stack to push 1, 2, 3 \dots If you see 'I', pop everything to the result. If you see 'D', keep pushing. |
Elastic Snap-Back |
Imagine a spring. As long as you see 'D' (Decrease), you stretch the spring (push to stack). When you hit 'I', the spring snaps back into the result. |
Draw a line 1, 2, 3, 4, 5. Above it, draw the pattern `DDI`. Use a bucket (Stack). Push 1, 2, 3. On 'I', empty the bucket: 3, 2, 1. |
Single Pass |
Draw one arrow scanning the pattern. Each number enters/leaves the stack once. $O(N)$. |
Permutation Pool Storing massive numbers of arrays. |
Stack Structure Draw a vertical bucket of size N. $O(N)$ space. |
| 485 |
Max Consecutive Ones |
All Subarrays Identify every subarray of 1s. Measure their lengths and find the max. |
Nested Subarray Scan |
Draw an array. Draw all possible brackets [i, j]. Check if all are 1. $O(N^2)$. |
Single Pass Counter Iterate through the array. Increment `count` if 1; if 0, update `max` and reset `count`. |
Streak Tracker |
Imagine a runner. Every '1' is a successful step. Every '0' is a trip where they have to start their "streak" over. |
Draw an array. Draw an arrow moving left-to-right. Write the current streak count below each element. Circle the largest number. |
Linear Scan |
Draw a straight line from 0 to N. $O(N)$. |
None Constant counters. |
Registers Two variables: `max` and `current`. $O(1)$ space. |
| 486 |
Predict the Winner |
Minimax Recursion Try picking from both ends, calculating max score diff for current player. |
Binary Decision Tree |
Draw a root. Branch left (pick front) and right (pick end). Show expansion to $O(2^n)$. |
DP (1D/2D) `dp[i][j]` stores max score diff from subarray i...j. `dp[i][j] = max(nums[i]-dp[i+1][j], nums[j]-dp[i][j-1])`. |
Interval DP Table |
Imagine a 2D table. Fill it diagonally starting from the main diagonal (length 1 arrays). Each cell depends on the cell below and to the left. |
Draw an n \times n grid. Fill `dp[i][i] = nums[i]`. Calculate `dp[i][i+1]` using neighboring cells until top-right corner is reached. |
Table Area |
Draw the upper triangle of a grid. Show total $O(n^2)$ cells. |
Call Stack Vertical stack of depth n. |
1D/2D Array One single array row. $O(n)$. |
| 487 |
Max Consecutive Ones II |
Nested Search For every index, try "flipping" it if it's a 0, then scan to find the longest streak. |
Repeated Scan Line |
Draw the array n times. For each, draw a line showing the scan. $O(n^2)$. |
Sliding Window (Expandable) Maintain a window with at most one '0'. If zeros > 1, shrink left pointer. |
Inchworm stretch |
A window [L, R] moves. It can "swallow" one zero. If it hits a second, the tail L must hop past the first zero. |
Draw an array. Draw bracket [L, R]. Keep a `zeroCount`. Shift R until `zeroCount > 1`, then move L. |
Linear Scan |
Draw one arrow passing over the array. $O(n)$. |
Variables Just L and R pointers. |
Registers Two integers for pointers. $O(1)$. |
| 488 |
Zuma Game |
Brute Force DFS Try placing every available color at every possible index in the string. |
Factorial Branching |
Draw a string. From each gap, draw arrows for every hand-color. Show $O(P!)$ where P is positions. |
DFS + Memoization + Pruning Use string compression (remove 3+ matches) and a Map to store "State: MinBalls". Skip redundant placements. |
State Reduction Tree |
Visualize the board as a string that "collapses" whenever a match is made. Each state is a `(board, hand)` pair. |
Draw the string. When placing a ball makes 3, scratch them out. Show the "vacuum" pulling remaining chars together. |
Pruned Graph Search |
Draw nodes for unique string/hand states. Complexity remains high but searchable. |
Call Stack Massive recursive depth. |
State Cache Map storing visited string configurations. $O(\text{States})$. |
| 489 |
Robot Room Cleaner |
Random Walk Move the robot randomly and turn when hitting a wall. (No guarantee of completion). |
Messy Scribble |
Draw a grid. Draw a chaotic, overlapping line. Inefficient and non-deterministic. |
Backtracking with Coordinate Set Maintain a `visited` Set of `(row, col)`. Always try to clean, move, recurse, then return and face original direction. |
Blind Explorer's Map |
Imagine the robot is in the dark. It leaves a "trail of breadcrumbs" (Set) and always follows its "right hand" (rotation logic) to return home. |
Draw a grid. Mark robot at (0,0). For each move, write the new relative coord. Use an "Undo" arrow showing the robot turning 180 and moving back. |
Grid Coverage |
Draw the grid. Show the robot visits each reachable cell once. $O(N)$ where N is total cells. |
None Constant variables. |
HashSet + Stack Draw a Set of coordinates and a recursive stack of size N. $O(N)$. |
| 490 |
The Maze |
Standard DFS Move one cell at a time like a normal maze. (Fails to simulate the "sliding" physics). |
Grid Scan |
Draw a grid with arrows moving one cell at a time. This doesn't match the "roll until wall" constraint. |
BFS/DFS with Sliding Logic From a cell, move in one direction using a `while` loop until hitting a wall. Treat the *stop point* as a graph node. |
Ice Skating Graph |
Imagine the floor is ice. You only stop at walls. The "nodes" in your graph are only the cells next to walls or the start/end. |
Draw a grid with walls. From start, draw a long arrow until a wall. Circle that stop point. From there, draw 4 new "sliding" arrows. |
Edge Traversing |
Draw nodes (stop points) and edges (sliding paths). $O(M \\text{times} N)$ since each cell is visited max 4 times. |
Call Stack DFS recursion depth. |
Queue + Visited Draw a BFS Queue and a 2D boolean visited grid. $O(\text{MN})$. |
| 491 |
Non-decreasing Subsequences |
Exhaustive Recursion Try pick/don't pick for every number. Filter for length \ge 2 and non-decreasing. |
Binary Decision Tree |
Draw a tree with N levels. Each node has two branches. Total $O(2^N)$. |
DFS with Local Set Use backtracking. At each recursive level, use a `HashSet` to skip duplicate numbers to avoid redundant subsequences. |
Pruned Decision Tree |
Visualize the tree. If you've already branched on a "4" at this depth, the second "4" branch is immediately cut off. |
Draw a tree. At each node, draw a small "Used" box. If a value is in the box, don't draw its branch. |
State Space Count |
Draw the tree but show many "cut" branches. $O(2^N)$ worst case but significantly faster. |
Result List Storing all 2^N combinations. |
Call Stack Vertical stack of size N. $O(N)$. |
| 492 |
Construct the Rectangle |
Linear Scan Iterate from W = 1 up to N. If N \% W == 0, calculate L = N/W. Keep if L \ge W. |
Linear Timeline |
Draw a line from 1 to N. Show an arrow checking every single point. $O(N)$. |
Start at Square Root Start W at \lfloor\sqrt{N}\rfloor and decrement until N \% W == 0. This ensures L and W are as close as possible. |
Shrinking Area Boundary |
Imagine a square. Slightly stretch one side and shrink the other until the area hits N exactly. |
Draw a number line from \sqrt{N} down to 1. Mark the first number that divides N. |
Sqrt Boundary |
Draw a line that only goes up to the \sqrt{N} mark. $O(\\text{sqrt}{N})$. |
None Constant variables. |
None Two integer variables. $O(1)$. |
| 493 |
Reverse Pairs |
Nested Loops Compare every pair (i, j) where i < j. Check if nums[i] > 2 \cdot nums[j]. |
Comparison Grid |
Draw an N \times N matrix. Shade the upper triangle. $O(N^2)$. |
Merge Sort (Divide & Conquer) During the merge step, both halves are sorted. Use two pointers to count reverse pairs before merging. |
Split and Count Tree |
Divide the array into two sorted blocks. For each element in the left, count how many elements in the right satisfy the condition. |
Draw a Merge Sort tree. At the merge step, draw two sorted arrays. Draw arrows from Left[i] to Right[j] to show the count. |
Recursive Tree depth |
Draw a tree with \log N levels. At each level, work is $O(N)$. Total $O(N \log N)$. |
None Constant space. |
Temporary Arrays Draw an auxiliary array used for the merge step. $O(N)$. |
| 494 |
Target Sum |
Exhaustive DFS Try adding '+' and '-' for every number in the input. Count paths that reach `target`. |
Binary Decision Tree |
Draw a tree with 2^N leaves. Each branch is a + or - operation. |
DP (Subset Sum) Transform to finding a subset with sum (S + \text{target})/2. Solve using 1D Knapsack DP. |
Staircase Filling |
Imagine a row of buckets labeled from 0 to NewTarget. Each number helps you "unlock" new bucket sums. |
Draw a 1D grid. For each number, show how it "activates" new sums by adding it to previous "True" or "Counted" cells. |
Area calculation |
Draw a grid of size N \times \text{TargetSum}. $O(N \cdot \\text{text}{\text{Sum}})$. |
Call Stack $O(N)$ depth. |
1D Array Draw a single 1D array of counts. $O(\\text{text}{\text{Sum}})$. |
| 495 |
Teemo Attacking |
Simulation (Second by Second) Create a massive boolean array for time. Mark seconds as "poisoned". Count true values. |
Dense Timeline |
Draw a long timeline. Color in seconds 1 to N. Huge $O(\\text{text}{\text{MaxTime}})$. |
One-Pass Greedy Iterate through attacks. If the gap between attacks < duration, add the gap. Else, add the full duration. |
Interval Overlap Strike |
Imagine a bar (poison duration). If a second bar starts before the first ends, the first bar is "cut short." |
Draw a timeline with rectangles for durations. If two rectangles overlap, draw a vertical line "clipping" the first one. |
Linear Scan |
Draw a single arrow passing through the attack array. $O(N)$. |
Time Array Memory of size `MaxTime`. |
None Just two integer variables. $O(1)$. |
| 496 |
Next Greater Element I |
Nested Search For each x in nums1, find its index in nums2, then scan right to find the first larger number. |
Repeated Scan Line |
Draw nums1 and nums2. For each nums1[i], draw a long arrow traversing nums2. $O(N \cdot M)$. |
Monotonic Stack + HashMap Pre-process nums2 using a stack to find all "Next Greater" pairs. Store in a Map `num: next_greater`. |
Falling Off a Cliff |
Imagine numbers walking. If a taller number appears, the smaller numbers behind it are "blocked" and paired with the tall one. |
Draw a "Stack" bucket. Push numbers. When a larger number comes, "pop" smaller ones and write the pair. Map the result. |
Linear Pipeline |
Draw a single pass through nums2 and a single pass through nums1. $O(N + M)$. |
None Constant pointers. |
Stack + Map Draw a vertical bucket and a 2-column table (Map). $O(M)$ space. |
| 497 |
Random Point in Non-overlapping Rectangles |
Uniform Rect Selection Pick a rectangle at random (1/N chance), then pick a point inside. (Fails: larger rectangles should be picked more often). |
Skewed Distribution |
Draw a tiny square and a giant rectangle. Show they have the same 1/2 chance. Label "INCORRECT". |
Prefix Sum + Binary Search Calculate areas of all rectangles. Create a prefix sum array. Randomly pick a "total area" value and binary search for the rect. |
Weighted Segment Line |
Imagine a long stick where each segment length is a rectangle's area. Throw a dart at the stick. The segment it hits is the rectangle to use. |
Draw a line divided into segments. Label each with its area. Draw a "random dart" hitting a segment. Show binary search to find that segment. |
Search Tree |
Draw a Binary Search tree of height \log N. Total $O(\log N)$ per pick. |
None Only the input. |
Prefix Sum Array Draw a 1D array of increasing sums. $O(N)$. |
| 498 |
Diagonal Traverse |
Diagonal Collection Group all elements where i+j is the same. Reverse every second group. |
Bucketing Map |
Draw a grid. Draw arrows for each diagonal. Collect into lists. $O(M \cdot N)$ plus extra space for lists. |
Simulation (Direction Flag) Use a direction flag (Up/Down). Calculate new i, j based on boundaries (e.g., if at last column, move down and flip direction). |
Bouncing Laser |
A laser beam moves diagonally. When it hits a "wall" (grid edge), it bounces off at a 90-degree angle and flips direction. |
Draw a grid. Draw a continuous zig-zag path. Label the "bounce" points where row or column boundaries are reached. |
Grid Pass |
Draw a single arrow visiting every cell exactly once. $O(M \cdot N)$. |
Map of Lists Draw a map where each key is a diagonal index. $O(M \cdot N)$. |
None Direct array result placement. $O(1)$ extra (ignoring output). |
| 499 |
The Maze III |
DFS (Exhaustive) Explore all paths to the hole. Keep track of current min-distance. (Too slow for large grids). |
Exploding State Space |
Draw a grid. From start, branch in 4 directions. Show recursive explosion. $O(4^{\text{MN}})$. |
Dijkstra with String Priority Use a Priority Queue. Store `(distance, path_string, x, y)`. Only update if distance is smaller OR distance is equal but string is lexicographically smaller. |
Shortest Labeling Tree |
Imagine every node in the maze has a "sticky note" with the shortest path and the word (e.g., "dlur"). Only overwrite if you find a "better" word. |
Draw a grid. At stop points, draw boxes with `(dist, path)`. Draw arrows representing "slides" and update boxes using Priority Queue rules. |
Log-Weighted Graph |
Draw nodes (stop points) and edges (paths). Complexity $O(\text{MN} \log(\text{MN})$). |
Call Stack Vertical stack of size MN. |
Priority Queue + 2D Dist Map Draw a PQ and a 2D grid of "Min Distances". $O(\text{MN})$. |
| 500 |
Keyboard Row |
Triple Set Check For every character of every word, iterate through three sets of row characters. |
Nested Scans |
Draw words on top. Draw 3 rows of keyboard below. Draw many overlapping arrows. $O(\text{WordLength} \cdot 3)$. |
Pre-mapped Char-to-Row Create a Map or Array of size 26 where `row[char]` is 1, 2, or 3. Check if all chars in a word return the same row ID. |
Pigeonhole Check |
Imagine 3 boxes (Row 1, 2, 3). For a word, every letter must "belong" to the exact same box. If you see a letter from a different box, throw the word out. |
Draw 3 buckets. For word "Hello", check 'H' (Row 2), 'e' (Row 1). Since they land in different buckets, mark as "Failed." |
Linear Scan |
Draw one arrow through the words. Each char is an $O(1)$ lookup. Total $O(\\text{text}{\text{Total Chars}})$. |
Sets Three sets of keyboard characters. |
Fixed Array Draw a small 26-slot integer array. $O(1)$ space. |
| 501 |
Find Mode in Binary Search Tree |
Traverse the tree, store counts of every node in a Hash Map, then iterate the map to find max frequency. |
Tree mapping into an expanding Hash Map table. $O(N)$ Time / $O(N)$ Space. |
Draw tree nodes funneling into a 2-column table (Key|Value), writing N rows. |
Inorder Traversal (Morris Traversal) with State Tracking variables. |
Number line with a sliding window counting consecutive identical values. |
Trace inorder path left-to-right. Update `curr_count`, `max_count`, and `modes` list when node values change. |
Draw the BST. Draw a colored line tracing the inorder path. Keep a side-box for 3 state variables updating sequentially. |
Flat sequence of nodes evaluated in a single pass. $O(N)$ Time / $O(1)$ Space. |
Draw N blocks in a line. Draw a single fixed-size box below it labeled $O(1)$ space. |
Large rectangle labeled "Hash Map" growing vertically as N increases. |
Three tiny, fixed-size squares (curr, max, previous) remaining static in size. |
| 502 |
IPO |
For K steps, iterate through all projects, find the maximum profit project where capital ≤ current capital. |
Nested loop grid: K rows multiplied by N columns per row. $O(K \cdot N)$. |
Draw K large horizontal boxes, inside each draw N smaller boxes showing a full scan. |
Two Heaps (Min-Heap for Capital, Max-Heap for Profit) / Greedy. |
Two funnels: Capital filters into Min-Heap, viable ones pour into Max-Heap. |
Pop from Min-Heap if capital affordable -> Push to Max-Heap -> Pop Max-Heap -> add to total capital -> Repeat K times. |
Draw two triangles (heaps). Write available projects in Min triangle. Draw arrows moving items to Max triangle when capital allows. |
Sorting phase followed by Heap operations. $O(N \log N + K \log N)$. |
Draw a sorting timeline, then K discrete steps pulling from a balanced tree (log N height). |
Array of N elements scanned repeatedly, static array size in memory. |
Two binary tree structures (Heaps) re-balancing as nodes transfer between them. |
| 503 |
Next Greater Element II |
Nested loop. For each element, search circularly (up to N-1 elements) to find the first greater element. |
Circular complete graph showing every node pointing to potentially all other nodes. $O(N^2)$. |
Draw a circle of N dots. Draw lines from one dot traversing the whole circle. Repeat for all dots. |
Monotonic Decreasing Stack (Looping 2N times). |
A physical stack of plates where a larger plate smashes all smaller plates below it. |
Iterate array twice. If current > stack top, pop stack top, map popped index to current value. Push current index. |
Draw array twice side-by-side. Draw a vertical bucket (stack). Push indices. Cross them out (pop) when a larger number appears. |
Linear pass over 2N items, each item pushed/popped at most once. $O(N)$. |
Draw a timeline of 2N length. Show push (+1) and pop (+1) operations summing to 4N max operations. |
Call stack mapping to N^2 nested local variable states. |
A single vertical cylinder (Stack) growing up to max size N. |
| 504 |
Base 7 |
Repeated division by 7, storing remainders, handling negative sign manually. (Basically the optimal approach). |
Division cascading downwards. $O(\log7 N)$. |
Draw the number, divide by 7, draw arrow to remainder. Repeat until quotient is 0. |
Math / Simulation (Repeated Division and Modulo). |
A factory machine splitting a number into quotient (recycled) and remainder (output string). |
Take N, N % 7 prepends to string, N = N / 7. Stop at 0. Add '-' if originally negative. |
Write number. Box the Modulo 7 result. Draw line connecting boxes bottom-up to form the final string. |
Logarithmic scale shrinking rapidly by factor of 7. $O(\log7 N)$. |
Draw a block of N size, next block is 1/7th the size, next is 1/49th, showing rapid collapse. |
List of string fragments forming in memory. |
String Builder / Array of characters dynamically growing up to log7(N) length. |
| 505 |
The Maze |
Standard DFS, but instead of moving 1 step, move in a direction until hitting a wall. Backtrack if dead end. |
Tree expanding drastically due to long paths and deep call stack. $O(M\cdot N)$ but high overhead. |
Draw a grid, draw a squiggly line branching infinitely at every wall collision, marking visited poorly. |
BFS (Shortest Path) using a Queue and a Distance 2D Array / Dijkstra. |
A radar ping expanding outwards, stopping only at walls before emitting the next ping. |
Pop node, slide ball in 4 directions until wall. If distance to wall < recorded distance, update and push to queue. |
Draw a grid map. Mark start. Draw straight arrows hitting walls. Circle wall-hit points, add them to a drawn Queue box. |
Grid traversal where each node is processed efficiently. $O(M\cdot N)$. |
Draw an M x N grid, shade cells as they are visited to show bounded processing time. |
Deep vertical stack of recursive function calls. |
2D Array (M x N) for tracking shortest distances + a horizontal Queue line. |
| 506 |
Relative Ranks |
Find the max, assign rank, remove it. Repeat N times for all elements. $O(N^2)$ Time. |
N iterations over a shrinking array of N elements. |
Draw N rows of the array, crossing out the highest number in each row. |
Sorting with Index Tracking / Max-Heap. |
A scoreboard that pairs original jersey numbers (indices) with their scores before sorting. |
Pair scores with indices -> Sort descending -> Assign Gold/Silver/Bronze to first 3 -> Assign "4", "5" to rest -> Map back to original indices. |
Draw unsorted array. Below it, draw sorted array of pairs (Score, Index). Draw arrows from sorted elements back to a final answer array. |
Tree structure (Heap/Sort) mapping to a linear array. $O(N \log N)$. |
Draw a balanced binary tree of height log N, followed by a flat N-length line. |
A second array of N size to hold rankings. |
Array of tuples/pairs taking up exactly $O(N)$ space. |
| 507 |
Perfect Number |
Iterate from 1 to N-1. Check if N % i == 0. If so, add to sum. Compare sum to N. $O(N)$. |
A long, flat number line iterating through every single integer up to N. |
Draw a line from 1 to N, placing a checkmark on every single number that divides evenly. |
Math / Pair Divisors up to Square Root of N. |
Folding a number line in half at the square root, where left factors instantly reveal right factors. |
Loop i from 1 to sqrt(num). If num % i == 0, sum += i. If i * i != num, sum += num / i. |
Draw a box for `num`. Draw a small loop 1 to sqrt(N). Connect factor pairs with an arc, dropping them into a "Sum Bucket". |
A line abruptly truncated at the square root. $O(\text{sqrt}(N)$). |
Draw a timeline, but cut it off very early (at the square root mark), indicating massive time saved. |
Just a single integer tracking the sum. $O(1)$. |
Just a single integer tracking the sum. $O(1)$. |
| 508 |
Most Frequent Subtree Sum |
For every node, initiate a full DFS to calculate its subtree sum. High redundancy. $O(N^2)$. |
Overlapping triangles (subtrees) evaluated repeatedly inside a larger triangle. |
Draw a tree, and draw circles around subtrees, showing how the root's circle fully overlaps the children's circles. |
Post-order Traversal (Bottom-Up DFS) + Hash Map. |
Water bubbles forming at the leaves and merging/growing as they float up to the root. |
Go left -> Go right -> Node sum = Left + Right + Node.val. Add sum to Hash Map, update global max frequency. Return sum to parent. |
Draw the BST. Start at leaves, write their sums beside them. Draw arrows pointing up to parents, adding the sums together. Keep a Map tally side-box. |
A single pass lighting up every node exactly once. $O(N)$. |
Draw the tree and shade every node a single color to represent one-time visitation. |
Massive call stack overhead due to redundant nested DFS. |
A Hash Map (Key=Sum, Val=Freq) expanding up to N entries, plus recursion stack of height H. |
| 509 |
Fibonacci Number |
Pure Recursion: `fib(N-1) + fib(N-2)`. Re-calculates the same values endlessly. $O(2^N)$. |
Exponentially exploding binary tree. |
Draw fib(5) splitting to fib(4) and fib(3). Split those down to 1s. Circle the multiple identical fib(2)s to show waste. |
Iterative Bottom-Up Dynamic Programming (State variables). |
Two physical sliders leap-frogging each other along a number line. |
Set a=0, b=1. Loop N-1 times: temp = a+b. a = b. b = temp. Return b. |
Draw three boxes: `a`, `b`, and `temp`. Erase and update them sequentially, moving left to right. |
A simple, flat, linear timeline. $O(N)$. |
Draw a straight line broken into N uniform segments. |
Deep vertical recursion stack of $O(N)$ depth taking up hidden memory. |
Two tiny, static boxes holding integers. $O(1)$ space. |
| 510 |
Inorder Successor in BST II |
Navigate to root using parent pointers, run full In-Order Traversal into an array, find target, get next. $O(N)$. |
Flattening a 2D tree into a 1D line completely. |
Draw the tree projecting downward into a horizontal array of size N. |
BST Traversal leveraging Parent Pointers. |
Following physical pipes: If right pipe exists, go down-right then slide all the way left. Else, climb up until turning right. |
If node has right child: step right, then while left child exists, go left. If no right child: while node is a right child, step to parent. |
Draw a tree. For Case 1, draw a blue zigzag going down-right-left-left. For Case 2, draw a red zigzag climbing up-left-up-left. |
Path strictly bounded by the height of the tree. $O(H)$. |
Draw a vertical zigzag line spanning from the root to the deepest leaf to represent height H. |
An Array of size N storing all traversed nodes. |
A single pointer. $O(1)$ auxiliary space. |
| 511 |
Game Play Analysis I (SQL) |
Self-join the table on matching player IDs and filter manually to find where no earlier date exists. |
Cartesian product matrix showing all possible row combinations per player. $O(N^2)$. |
Draw a large N x N grid connecting rows. Cross out intersections where the date is not the absolute minimum. |
SQL `GROUP BY` with Aggregate Function `MIN()`. |
Sorting bins. Records drop into player buckets, and a filter keeps only the top card. |
Scan rows -> Separate into piles by `player_id` -> Pick the card with the earliest date from each pile. |
Draw 3 circles (representing players). Draw dots (logins) inside them. Circle the dot furthest to the left (earliest date). |
Linear scan grouped by a hash map structure. $O(N)$. |
Draw a straight line mapping directly into discrete, non-overlapping buckets. |
Massive temporary table created in memory for the join. $O(N^2)$. |
Small hash table holding just `player_id` and a single date variable. $O(N)$. |
| 512 |
Game Play Analysis II (SQL) |
Use a subquery to find the min date per player, then join that result back to the main table to get `device_id`. |
Two separate tables connected by string lines (join operation) scanning multiple times. |
Draw main table, draw subquery table. Draw arrows linking matching (player_id, min_date) pairs. |
Window Function `ROW_NUMBER() OVER(PARTITION BY player_id ORDER BY event_date)`. |
A conveyor belt sorting items into lanes and immediately stamping them 1, 2, 3 based on date. |
Group by player -> Sort partition by date -> Assign row numbers -> Filter out everything except row number 1. |
Draw a table. Draw thick lines partitioning it by player. Number the rows 1, 2, 3 in each section. Highlight all the 1s. |
Sorting phase within bounded partitions. $O(N \log N)$. |
Draw N blocks breaking into smaller chunks, followed by sorting trees for each chunk. |
Extra temporary table allocation in database memory for subquery results. |
In-memory pointers sliding over sorted data blocks. |
| 513 |
Find Bottom Left Tree Value |
DFS recording depth. Constantly update a global "max depth" and "value" variable (Left traversed first). |
Deep plunging lines going down the left edges of subtrees. $O(N)$. |
Draw a tree. Trace the path deeply. Keep an eraser handy to constantly update the "max depth" box as you go deeper. |
BFS (Level Order Traversal) but strictly Right-to-Left. |
A sweeping laser beam scanning horizontally, dropping nodes onto a conveyor belt from right to left. |
Queue root. Pop. Push right child, then push left child. Repeat until queue is empty. Return the very last node popped. |
Draw tree. Draw a queue box. Put root in, take out, put Right child then Left child. Circle the final item remaining. |
Flat linear queue processing. $O(N)$. |
Draw N boxes uniformly entering and exiting a horizontal tube. |
Deep call stack representing tree height. Space $O(H)$. |
A wide horizontal queue holding at most N/2 nodes (the leaf level). Space $O(N)$. |
| 514 |
Freedom Trail |
Pure recursion. Try both clockwise and counter-clockwise rotations to match the next character. |
Rapidly branching binary tree of choices exploding in size. $O(2^K)$. |
Draw the ring. Draw branching paths of +1 and -1 steps. Calculate total steps at the bottom of a massive tree. |
Dynamic Programming (Top-Down Memoization or 2D Bottom-Up). |
A 2D grid that collapses redundant recursive branches into single, mathematically evaluated cells. |
State is (ring_idx, key_idx). For current key char, find all its positions in ring. Calculate min steps to get there + DP of next state. |
Draw a 2D matrix (Ring Indices x Key Characters). Fill cells right-to-left tracking minimum rotation costs. |
Filling a tightly bounded rectangle. $O(R^2 \cdot K)$ where R is ring length, K is key length. |
Draw a grid of R rows by K columns, shading squares one by one linearly. |
Massive call stack space of depth K, branching out exponentially. |
A static 2D Array/Matrix table of size R x K taking up predictable memory. |
| 515 |
Find Largest Value in Each Tree Row |
DFS passing depth, storing all values in a `Map>`, then looping map to find maxes. |
Nodes dropping into deep buckets based on depth, followed by scanning each bucket entirely. $O(N)$. |
Draw tree. Draw buckets labeled Depth 0, 1, 2. Toss node values into buckets. Run through buckets circling the max. |
BFS (Level Order Traversal) tracking max per level. |
A horizontal slicing blade cutting the tree layer by layer, picking the biggest fruit per slice. |
Queue holds level nodes. Loop `size` times: pop node, update level max, push children. Append max to result array. |
Draw tree. Draw horizontal dashed lines separating levels. Loop through each level left-to-right, writing the max on the dashed line. |
Linear scan layer by layer. $O(N)$. |
Draw a line of length N chopped into varying sized segments (levels), evaluated once. |
Hash Map containing all N nodes plus recursion stack depth overhead. |
Output array + Queue holding up to N/2 nodes at the bottom level. Max $O(N)$ space. |
| 516 |
Longest Palindromic Subsequence |
Pure Recursion. Test every subsequence by checking left and right pointers. If they match, add 2; else branch twice. |
Binary tree exploding downwards as every mismatch creates two new branches. $O(2^N)$. |
Write the string. Draw branching lines down, showing string shrinking by 1 char on left, then 1 char on right. |
2D Dynamic Programming (Bottom-Up). |
A triangular grid filling diagonally outward from the center (single characters) to the full string. |
If ends match, inner core + 2. If ends differ, max of (exclude left, exclude right). Fill table diagonally. |
Draw an N x N grid. Fill the main diagonal with 1s. Traverse diagonally upwards, writing the max lengths based on the cells below and left. |
A bounded N x N square grid filling up systematically. $O(N^2)$. |
Draw a square divided into a grid, shading half of it diagonally. |
Massive deep recursive call stack of height N holding string states. |
A 1D array of size N (space optimized from 2D), storing the previous length's results. |
| 517 |
Super Washing Machines |
Simulate passing items left and right iteratively until all machines match the average. Highly inefficient. |
Swirling arrows randomly tossing numbers back and forth endlessly. $O(N^2)$ or worse. |
Draw an array, draw arrows shifting +1 or -1 between neighbors. Repeat until identical. |
Math / Prefix Sum (Tracking flow and bottlenecks). |
A pipeline with pressure valves. The max pressure at any single valve dictates the time required. |
Calculate target average. Iterate array tracking a running `balance` (prefix sum of diffs). Max of `abs(balance)` or `val - target` is the answer. |
Draw array of current loads. Below it, write the target. Below that, write the running balance. Circle the largest absolute balance or individual excess. |
A single, straight line passing over the array exactly once. $O(N)$. |
Draw a timeline moving strictly left to right, processing N items. |
Arrays duplicating at each step of the simulation. |
A couple of integer variables (running balance, max pressure). $O(1)$ space. |
| 518 |
Coin Change II |
Recursion. For every coin, branch: either take the coin (stay on index) or skip the coin (move to next). |
A massive unbalanced binary tree where "take" branches repeat infinitely until sum exceeds target. $O(2^N)$. |
Draw target sum. Branch left (-coin value) and right (next coin). Stop when sum is 0 or negative. |
1D Dynamic Programming (Unbounded Knapsack). |
A row of buckets representing amounts, where each new coin pours combinations into higher buckets sequentially. |
Create `dp` array of size Amount+1. DP[0] = 1. For each coin, loop from coin_val to Amount: DP[i] += DP[i - coin_val]. |
Draw an array from 0 to Amount. Put 1 in index 0. Pick a coin. Point an arrow from `i - coin` to `i`, adding combinations. |
A grid of size Coins x Amount filled row by row. $O(C \cdot A)$. |
Draw a rectangle with C rows and A columns, shade it left to right, top to bottom. |
Extremely deep recursion stack, depth up to (Amount / min_coin). |
A simple 1D array of size Amount + 1. $O(A)$ space. |
| 519 |
Random Flip Matrix |
Create an actual 2D array of M x N or a list of all coordinates, randomly pick, and mark/remove. |
A giant grid of 10^4 x 10^4 elements mapped out completely. $O(M \cdot N)$. |
Draw a massive matrix. Throw a dart at it. Cross out the cell. |
Virtual 1D Array + Hash Map mapping (Fisher-Yates Shuffle). |
A deck of cards where a drawn card is swapped with the very last card in the deck, shrinking the deck size by 1. |
Pick random `idx` from 0 to `total - 1`. Read map for mapped value (or use `idx`). Map `idx` to value at `total - 1`. Decrement `total`. |
Draw a 1D array. Pick a random index. Swap it with the last element. Move the "end" boundary left by 1. Keep a Map to track swaps. |
Instant $O(1)$ operations pulling from a shrinking virtual range. |
Draw a single box representing a fast hash map lookup. $O(1)$ time per flip. |
Memory limit exceeded! A giant Matrix/Array holding up to 10^8 elements. |
A Hash Map holding only the exact coordinates that have been flipped. $O(K)$ where K is number of flips. |
| 520 |
Detect Capital |
Write complex regular expressions or three separate `for` loops checking each of the 3 rules individually. |
Multiple overlapping scans of the same word. $O(N)$ but messy. |
Write the word three times. Scan the first for ALL CAPS, second for all lower, third for Title Case. |
Single-Pass Character Counting. |
A turnstile counting exactly how many tall people (capitals) enter the room. |
Iterate word. If char is uppercase, `caps_count++`. If `caps_count` == len OR 0 OR (1 AND first char is upper), valid. |
Write the word. Point to each letter, incrementing a tally box if it's uppercase. Check the final tally against 3 simple rules. |
One smooth, uninterrupted scan across the word. $O(N)$. |
Draw a straight line broken into N uniform segments. |
Multiple string copies or complex Regex state machines in memory. |
A single integer counter. $O(1)$ space. |
| 521 |
Longest Uncommon Subsequence I |
Generate every single subsequence of both strings and compare them all to find the longest unique one. $O(2^N)$. |
Exploding binary tree showing every "include/exclude" character choice. |
Draw string A. Branch downwards creating every possible sub-string. Repeat for B. |
Brain Teaser / Math (Length Comparison). |
Two wooden planks side-by-side. If they aren't identical, the longer plank is the answer. |
Are strings identical? Return -1. Are they different? Return max(length of A, length of B). |
Draw two horizontal bars representing string lengths. If completely identical, write -1. If different, circle the longer bar. |
A single, instantaneous check. $O(1)$. |
Draw two boxes (A and B) flowing into a single decision diamond. |
Massive arrays of strings filling up memory with $O(2^N)$ combinations. |
Zero extra space. $O(1)$ auxiliary variables. |
| 522 |
Longest Uncommon Subsequence II |
Generate all subsequences for every string in the array, tally frequencies, return longest with freq=1. |
A forest of exploding binary trees, one for each string in the array. $O(N \cdot 2^L)$. |
Draw multiple strings. Below each, draw an expanding cone representing millions of subsequences. |
Custom Sort + Two Pointers (Subsequence Check). |
A waterfall filtering down by length. The first unique rock that doesn't fit inside any other rock wins. |
Sort descending by length. Pick string. Compare it against all others using two pointers. If it's not a subsequence of any, return its length. |
Draw strings stacked by length (longest on top). Take top string. Draw two arrows (pointers) checking if its letters exist in other strings. |
Sorting phase followed by nested traversal. $O(N^2 \cdot L)$. |
Draw a sorting timeline, then an N x N grid where each cell represents a quick linear scan. |
Hash Map exploding with 2^L string combinations. |
No extra data structures, just pointers. $O(1)$ space beyond sorting. |
| 523 |
Continuous Subarray Sum |
Nested loops. Outer loop picks start, inner loop extends to end, summing and checking `% k == 0`. $O(N^2)$. |
Overlapping horizontal brackets covering every possible segment of the array. |
Draw an array. Draw an arc from idx 0 to 1, 0 to 2, 0 to 3... then 1 to 2, 1 to 3... |
Prefix Sum + Modulo Hash Map. |
A clock face. As you add numbers, the hand spins. If it hits the exact same time twice (and distance > 1), you've done a full circle (multiple of k). |
Running sum % k. If this remainder exists in Map, check if `current index - map[remainder] > 1`. If yes, true! Else, add to Map. |
Draw array. Below, write running sum. Below that, write sum % k. Keep a side Map of (Remainder : Index). Circle matching remainders. |
A single, straight line passing over the array. $O(N)$. |
Draw a timeline moving strictly left to right, processing N items. |
Call stack mapping to N^2 loop states. |
A Hash Map growing up to size `k` to store remainder indices. $O(\text{min}(N, k)$). |
| 524 |
Longest Word in Dictionary through Deleting |
Generate all subsequences of string `s`, sort by length/lexicographically, find first that exists in dictionary. |
Generating a massive dictionary of permutations before searching. $O(2^N)$. |
Draw `s`, draw infinite branches generating every combo, point them at the dictionary. |
Sort Dictionary + Two Pointers. |
Sorting the dictionary first, then swiping two fingers across the target string and dictionary word to see if they mesh. |
Sort dict (desc length, asc lex). Iterate dict. Use pointer `i` for `s` and `j` for dict word. If chars match, `j++`. If `j == word.length`, return it. |
Write dict words in sorted order. Write string `s`. Draw an arrow under `s` and an arrow under current dict word. Advance arrows on match. |
Sorting the dict, then linear scans. $O(D \log D + D \cdot L)$. |
Draw a sorting box, then a series of parallel lines representing two-pointer checks. |
Massive array holding 2^N generated subsequences. |
$O(\log D)$ or $O(D)$ memory used entirely for sorting the dictionary. |
| 525 |
Contiguous Array |
Nested loops to check every possible subarray, counting 0s and 1s, updating max length when equal. $O(N^2)$. |
A triangle matrix where every cell represents the tally of a different subarray segment. |
Draw an array. Draw brackets covering size 2, then size 4, then size 6... recalculating 0s and 1s every time. |
Prefix Sum (Treat 0 as -1) + Hash Map. |
An altitude chart. 1 goes up a mountain, 0 goes down. If you return to an altitude you've been at before, the journey between was perfectly flat (equal 0s and 1s). |
Change 0s to -1s. Track running sum. If sum in Map, `maxLength = max(maxLength, i - map[sum])`. Else, `map[sum] = i`. |
Draw array (0s as -1s). Draw running sum below. Plot it on a line graph. Whenever the line hits the same Y-axis value, bracket that horizontal segment. |
A single pass lighting up every element exactly once. $O(N)$. |
Draw an array and a single arrow traversing left-to-right. |
$O(1)$ memory, just two loop counters, but terrible time limit. |
A Hash Map storing up to N unique altitude (prefix sum) records. $O(N)$. |
| 526 |
Beautiful Arrangement |
Generate every single permutation of numbers 1 to N, then check each fully built permutation against the modulo rules. |
A massive, unpruned N! factorial tree exploding outward. $O(N!)$. |
Draw branches for 1, then from 1 draw 2,3,4... multiplying at every level until the page is completely full. |
Backtracking with Pruning + Visited Array (or Bitmask). |
A labyrinth where paths that violate the rule immediately trigger a dead end, forcing an instant turn-around. |
Loop 1 to N. If unused and (`num % pos == 0` or `pos % num == 0`), mark used, recurse to `pos+1`. Unmark when returning. |
Draw a decision tree. If a branch fails the modulo check, draw a big red X on it immediately and do not draw any child nodes. |
A sparse tree with many short, terminated branches. Valid paths = K. $O(K)$. |
Draw a tree, but aggressively erase or cross out the middle branches to show paths dying early. |
Massive array allocations if storing all permutations. $O(N!)$. |
A simple boolean array of size N (or an integer bitmask) + recursion stack. $O(N)$. |
| 527 |
Word Abbreviation |
Create base abbreviations (e.g., i18n). If conflicts exist, expand prefix by 1 for all conflicts. Repeat until unique. $O(N^2 \cdot L)$. |
A chaotic room where everyone shouts their name, then repeatedly shouts a slightly longer version until distinct. |
List words, write "a2e", cross out duplicates, rewrite as "ap1e", cross out again, etc. |
Group by Length/Last Char + Trie for Longest Common Prefix (LCP). |
A filing cabinet grouping words into folders, inside which a Trie finds the exact diverging letter for each word. |
Group words. For each group, build a Trie. To abbreviate a word, traverse its Trie path until `node.count == 1`. That depth is the required prefix length. |
Draw buckets (groups). Inside a bucket, draw a Trie. Trace a word down the Trie until the node count is 1. Box that prefix. |
Parallel Tries processing small subsets independently. $O(N \cdot L)$. |
Draw multiple small trees instead of one giant nested loop structure. |
Arrays of strings continuously being overwritten and re-checked. |
Trie nodes storing character counts, bounded by total characters. $O(N \cdot L)$. |
| 528 |
Random Pick with Weight |
Create a literal array where index `i` is duplicated `weight[i]` times, then pick a random index from it. (Memory Limit Exceeded). |
A giant pie chart where a weight of 10,000 creates 10,000 individual tiny slices. $O(\text{Sum of weights})$. |
Draw a massive array filling up a page, writing "0" a hundred times, "1" fifty times, etc. |
Prefix Sum Array + Binary Search. |
A number line divided into segments of unequal lengths. A random dart lands on the line, and you quickly find which segment it hit. |
Init: Build prefix sum array. Pick: Generate random number `1` to `total_sum`. Binary search prefix array to find first value ≥ random number. |
Draw array [1, 3, 4]. Draw prefix sum: [1, 4, 8]. Write Random=6. Draw binary search arrows narrowing down to index 2 (value 8). |
Logarithmic halving of the prefix sum array. $O(N)$ Init, $O(\log N)$ Pick. |
Draw the prefix array, cut it in half, cut in half again, pointing to the target. |
An array of size equal to the total sum of all weights combined. |
A single array of size N storing the prefix sums. $O(N)$ space. |
| 529 |
Minesweeper |
Whenever a click happens, blindly scan the entire board or do unconstrained recursion across all tiles. $O(M \cdot N)$ repeatedly. |
Scanning every single tile on the board top-to-bottom regardless of the click location. |
Draw grid, iterate row 0 to M, col 0 to N checking everything unnecessarily. |
DFS / BFS from the click point with strict boundary/number checks. |
A ripple effect in a pond. The water spreads outward but instantly stops expanding the moment it hits a rock (a number > 0). |
If click is 'M', change to 'X'. Else, count adjacent mines. If count > 0, write count and STOP. If 0, write 'B' and recurse/queue to 8 neighbors. |
Draw 3x3 grid. Click center. Count mines. If 0, write 'B', draw 8 arrows outwards. If >0, write number, draw NO arrows. |
Bounded expansion filling only the empty 'B' space and its perimeter. $O(M \cdot N)$. |
Draw a grid with a localized shaded region that expands but stops firmly at a boundary of numbered cells. |
Duplicating the board or a huge, untracked call stack. |
Recursion stack or BFS Queue taking up to $O(M \cdot N)$ in the worst case (all 'B's). |
| 530 |
Minimum Absolute Difference in BST |
Store all node values in an array. Sort the array (ignoring BST properties), then find min diff between adjacent elements. $O(N \log N)$. |
Taking a perfectly structured tree, throwing it into a chaotic pile, and sorting it from scratch. |
Draw tree -> draw unsorted array -> draw sorting algorithm -> draw linear scan. |
In-Order Traversal (natively sorted) + Track `prev` Node. |
Walking up a neatly organized staircase, only ever comparing the step you are currently on to the one immediately below it. |
In-order traverse (Left, Node, Right). Track `prev` node. `min_diff = min(min_diff, curr.val - prev.val)`. `prev = curr`. |
Draw BST. Trace in-order line left-to-right. Keep two boxes: "Prev" and "MinDiff". Erase and update them as you hit each node sequentially. |
A single smooth string pulling through the tree exactly once left to right. $O(N)$. |
Trace the inorder path of the tree with a single, unbroken colored line. |
An explicit $O(N)$ list created just to hold all tree values. |
$O(H)$ recursion stack depth + $O(1)$ auxiliary pointers (`prev`, `min_diff`). |
| 531 |
Lonely Pixel I |
For every 'B' found in the matrix, scan its entire row and its entire column to see if any other 'B' exists. |
Grid scanning with repeated cross-hairs. $O(M \cdot N \cdot (M + N)$). |
Draw a grid. Circle a 'B', then draw a full horizontal and vertical line from it, counting overlaps. |
Row/Column Tally Arrays. |
Two separate buckets: One for rows, one for columns. As you scan, drop a "count" into the corresponding bucket index. |
Pass 1: Traverse grid, `row[r]++` and `col[c]++` for every 'B'. Pass 2: Traverse grid, check if `grid[r][c] == 'B'` and `row[r] == 1` and `col[c] == 1`. |
Draw the matrix. Outside the right edge, draw an array (Rows). Below the bottom edge, draw an array (Cols). Tally the 'B's in these margins. |
Two linear passes over the matrix. $O(M \cdot N)$. |
Draw a matrix with a single arrow weaving through every cell once, then a second arrow doing the same. |
$O(1)$ extra space but very slow time complexity. |
Two linear auxiliary arrays of size M and N. $O(M + N)$ space. |
| 532 |
K-diff Pairs in an Array |
Nested loops. For every element `nums[i]`, search the rest of the array for an element `nums[j]` where `|nums[i] - nums[j]| == k`. Use a Set for unique pairs. |
N x N comparison matrix where half the matrix is redundantly checked. $O(N^2)$. |
Draw N dots. Connect every dot to every other dot with a line, checking the difference of each connection. |
Frequency Hash Map or Sorted Two-Pointers. |
A dictionary/library index. For any number X, you check the shelf once to see if X+k or X-k exists. |
Count frequencies in Map. If k > 0, check if `val + k` exists in Map. If k == 0, check if `count > 1`. |
Write the numbers. Draw a Map table (Num : Freq). For each Key in the table, check if `Key + k` is also a Key in the table. Circle the pairs. |
Single pass to build Map + single pass over Map keys. $O(N)$. |
Draw a timeline (Pass 1) followed by a small static table scan (Pass 2). |
$O(N^2)$ potentially to store all unique pair strings in a set. |
A Hash Map with at most N unique entries. $O(N)$ space. |
| 533 |
Lonely Pixel II |
For every cell, check "Lonely Pixel I" conditions AND check every other row to see if they have the same 'B' pattern. |
Exponential scanning. $O(N^2 \cdot M)$ or worse. |
Draw a grid. For every 'B', compare its entire row string against every other row string in the grid. |
Hash Map for Row Patterns. |
A fingerprint scanner. Rows with the same sequence of 'B's are grouped together under a single "pattern" key. |
Map row strings to their frequency. Also track 'B' counts in columns. A pixel (r, c) is "Lonely II" if `col_count[c] == Target` and `row_map[row_str] == Target`. |
Draw the matrix. Write out each row as a string (e.g., "WBBW"). Put these strings in a Map tally. Below each column, write its total 'B' count. |
Grid traversal + string hashing. $O(M \cdot N)$. |
Draw the matrix being converted into a Map of row-strings, then a single scan of the columns. |
$O(1)$ excluding the input matrix. |
Map storing row strings. In worst case, $O(M \cdot N)$ space for string storage. |
| 534 |
Game Play Analysis III (SQL) |
Self-join the table where `t1.player_id = t2.player_id` and `t1.event_date >= t2.event_date`, then group and sum. |
A massive triangular join where each row connects to every "past" row. $O(N^2)$. |
Draw the table twice. Draw arrows from a row in Table A to all rows in Table B that occurred earlier for that user. |
Window Function: `SUM(games_played) OVER(PARTITION BY player_id ORDER BY event_date)`. |
A snow-ball rolling down a hill. As the ball passes each date (row), it picks up the value and carries it to the next. |
Group by Player. Sort by Date. For row N, value = current_val + sum of all previous rows in that partition. |
Draw a table. Group by player. Draw a running total column where each cell is the sum of the cell above it plus the current row's value. |
Single pass over sorted partitions. $O(N \log N)$ due to internal sorting. |
Draw a sorted timeline with a single aggregator moving left to right. |
Temporary Cartesian product table in memory. $O(N^2)$. |
$O(N)$ space for the result set/window state. |
| 535 |
Encode and Decode TinyURL |
Use a counter or the URL string itself. (Brute force isn't really applicable, but a poor way is to store full URLs in an array and use index). |
Searching an entire array for a URL to find its index. $O(N)$. |
Draw a long list. Scan from the top every time you need to decode a URL. |
Hash Map with Random Base62 Encoding. |
A luggage tag system. A long bag (URL) gets a tiny tag (6-char code). The tag points exactly to one bag in the storage room. |
Encode: Generate 6 random chars. If code exists in Map, retry. Map `code -> longURL`. Decode: Return `Map[code]`. |
Draw two boxes: "Short-to-Long Map" and "Long-to-Short Map". Draw an arrow from `tinyurl.com/aB123` pointing to its full address. |
Instant lookups. $O(1)$. |
Draw a direct arrow from a key to a value in one step. |
$O(N)$ searching through an array. |
$O(N)$ storage in a Hash Map for all URLs processed. |
| 536 |
Construct Binary Tree from String |
Recursively find matching parentheses pairs to split the string into root, left, and right substrings. $O(N^2)$ due to repeated string slicing. |
A fractal pattern where a line keeps breaking into smaller, redundant lines. |
Draw a string. Draw brackets over pairs. Draw new strings below. Repeat until all characters are processed. |
Stack-based Iterative Construction. |
A building site where you "stack" floors. A '(' means go up a floor, a ')' means finish that floor and go down. |
Scan string. If number, create Node. If '(', push current Node to Stack. If ')', pop from Stack (finished child) and attach to current Stack top. |
Draw a vertical stack box. As you read `4(2(3)(1))(6)`, push 4, then 2, then 3. On `)`, pop 3 and draw a line from 2 to 3. |
Single pass over the string length. $O(N)$. |
Draw a straight line with N marks, each processed once. |
Multiple temporary string copies for every recursive call. |
A stack holding at most the height of the tree. $O(H)$. |
| 537 |
Complex Number Multiplication |
Manual string parsing with complex regex or multiple index-of checks to separate 'a', 'b', and 'i'. |
A messy web of string slicing and index calculations. |
Draw the input strings. Draw arrows pointing to '+', then 'i'. Shade the substrings in between. |
Math (FOIL Method) + String Split. |
A 2x2 grid (Punnett square style) where (a+bi)(c+di) = ac + adi + bci + bdi^2. |
Split strings by '+' and 'i'. Calculate: Real = (a \cdot c) - (b \cdot d); Imaginary = (a \cdot d) + (b \cdot c). Concatenate with '+' and 'i'. |
Draw a 2x2 table. Columns: a, bi. Rows: c, di. Multiply intersections. Note that i^2 = -1. Sum real and imaginary parts. |
Constant number of math operations. $O(1)$ (relative to input string length N). |
Draw a single box with 4 internal multiplication steps. |
String buffers and intermediate substring objects. |
Minimal space for 4 integer variables. $O(1)$. |
| 538 |
Convert BST to Greater Tree |
For every node, traverse the entire tree to find all values greater than it and sum them up. $O(N^2)$. |
N nodes each performing an N-node scan. $O(N^2)$. |
Draw a tree. For each node, draw a shadow tree where you circle only the larger nodes. |
Reverse In-Order Traversal (Right → Root → Left). |
A "Rainfall" effect starting from the highest value (rightmost leaf) and flowing down/left, accumulating water (sum). |
Maintain global `sum`. Traverse Right, then current Node (`sum += node.val`, `node.val = sum`), then Left. |
Draw the BST. Start at the bottom-right node. Write its value. Move to parent, add child's value. Move to parent's left... follow the path like a snake. |
Linear scan of every node exactly once. $O(N)$. |
Draw a single line tracing the "Reverse In-Order" path through the tree. |
No extra data structures, but high time cost. |
Recursion stack proportional to tree height. $O(H)$. |
| 539 |
Minimum Time Difference |
Compare every time in the list with every other time, calculating the absolute difference and handling the 24h wrap-around. $O(N^2)$. |
An N x N comparison grid. |
Draw a list of times. Draw lines connecting every pair. Write the difference on the line. |
Sorting or Bucket Sort (Boolean Array). |
A 24-hour circular clock face with markers. The smallest gap between any two adjacent markers is the answer. |
Convert times to minutes (0-1439). Sort them. Check diff between neighbors + diff between first and last (wrap-around). |
Draw a circle with 1440 notches. Mark the given times. Draw an arc between the two closest notches. |
Sorting phase. $O(N \log N)$ or $O(1440)$ if using a fixed-size bucket array. |
Draw a sorting timeline or a fixed-length line of 1440 slots. |
$O(1)$ extra space but slow time. |
A boolean array of size 1440 or a sorted list of size N. $O(1)$ or $O(N)$. |
| 540 |
Single Element in a Sorted Array |
Linear scan through the array, checking pairs. If `nums[i] != nums[i+1]`, `nums[i]` is the single element. $O(N)$. |
A single, long arrow scanning from left to right. |
Draw the array. Draw brackets under every two elements. Stop when a bracket contains different numbers. |
Binary Search on Even Indices. |
A balance scale. By checking an even index, you can tell if the "hitch" (the single element) occurred before or after your midpoint. |
`mid = left + (right-left)/2`. Ensure `mid` is even. If `nums[mid] == nums[mid+1]`, left = mid+2. Else, right = mid. |
Draw array. Point to middle even index. Check if it matches its neighbor. If yes, the single element is to the right. Narrow the search space. |
Logarithmic halving of the array. $O(\log N)$. |
Draw the array, cut in half, cut in half again. |
$O(1)$ auxiliary space. |
$O(1)$ auxiliary space (pointers). |
| 541 |
Reverse String II |
Iterate through the string, and for every block of 2k characters, generate all possible substrings and reverse the first k manually. |
Fragmented string reconstructions. $O(N^2)$ due to repeated string concatenation. |
Draw a string. Draw a bracket every 2k chars. Inside each bracket, draw an arrow flipping the first half. |
Two-Pointer In-Place Swap (Jumping by 2k). |
A leap-frogging mechanic. A pointer jumps 2k steps at a time, and a mini-reversal occurs at each landing spot. |
Loop `i` from 0 to N, step `2*k`. Identify `start = i` and `end = min(i + k - 1, n - 1)`. Swap characters at `start` and `end` moving inward. |
Write the string. Mark chunks of 2k. Inside the first k of each chunk, draw two arrows at the edges pointing toward each other. |
Single pass with in-place swaps. $O(N)$. |
Draw a straight line with N segments, with small "loop-back" arcs every 2k units. |
Multiple string objects or character arrays created in each step. |
A single character array (if the language has immutable strings) or zero extra space. $O(N)$. |
| 542 |
01 Matrix |
For every cell with a 1, perform a full BFS/DFS to find the nearest 0. |
N x M nodes each starting an N x M search. $O((M\cdot N)$^2). |
Draw a grid. Circle a '1'. Draw expanding circles until you hit a '0'. Repeat for every '1'. |
Multi-Source BFS or 2-Pass DP. |
A flood-fill starting from all 0s simultaneously. The "water" reaches 1s at the shortest possible time. |
Add all 0-coordinates to a Queue. For each, check 4 neighbors. If neighbor is 1 and unvisited, set `dist = current + 1` and push to Queue. |
Draw a grid. Mark all 0s. Draw arrows from all 0s to adjacent 1s at once. Label those 1s with "1". Repeat for next layer. |
Every cell is processed exactly once. $O(M \cdot N)$. |
Draw a grid and shade it in concentric layers starting from the zeros. |
Redundant search paths stored in multiple recursion stacks. |
A 2D distance array and a Queue holding at most M*N elements. $O(M \cdot N)$. |
| 543 |
Diameter of Binary Tree |
For every node, calculate the max depth of the left subtree and the max depth of the right subtree. Sum them and find the global max. |
N nodes each performing a depth scan. $O(N^2)$. |
Draw a tree. For each node, draw two long lines reaching to the deepest leaves. |
Bottom-Up DFS (Post-order Traversal). |
A tape measure that reports the "max height" to its parent while secretly updating a global "longest path" record. |
DFS returns height. At each node, `left_h = dfs(left)`, `right_h = dfs(right)`. Update `global_max = max(global_max, left_h + right_h)`. Return `1 + max(left_h, right_h)`. |
Draw a tree. Write heights next to nodes. At each node, write the sum of its children's heights in a different color to track potential diameters. |
Every node visited once. $O(N)$. |
Draw the tree and trace a single path that lights up every node exactly once. |
Heavy recursion stack from repeated depth-first calls. |
Recursion stack proportional to tree height. $O(H)$. |
| 544 |
Output Contest Matches |
Iteratively simulate the tournament by creating new strings for each pair, searching for the "strongest" and "weakest" each time. |
Recursive string formatting with multiple internal scans. $O(N \log N)$. |
Draw 8 numbers. Draw lines connecting 1-8, 2-7, 3-6, 4-5. Rewrite them as strings and repeat. |
In-place Array Transformation. |
A folding piece of paper. You fold the right edge onto the left edge, merging the contents at each step. |
Initialize array with 1 to N. While `n > 1`: pair `arr[i]` with `arr[n-1-i]`, store in `arr[i]`. Set `n = n / 2`. |
Write [1, 2, 3, 4]. Draw an arrow from 4 to 1, and 3 to 2. Write the new list: [(1,4), (2,3)]. Repeat. |
Linear reduction of pairs. $O(N)$. |
Draw N points, then N/2 points, then N/4, until 1 point remains. |
Large number of intermediate string objects. |
A single array of strings being modified in place. $O(N)$. |
| 545 |
Boundary of Binary Tree |
Perform multiple full traversals to find all paths, then filter for the specific edges (left, leaves, right) and remove duplicates. |
Disorganized tree scans with heavy overlap and manual filtering. $O(N)$. |
Draw a tree. Trace every possible path and then highlight the outer shell. |
Pre-order / In-order / Post-order Coordination. |
A "shadow" cast on a tree. You walk down the left shadow, along the bottom floor (leaves), and up the right shadow. |
1. Add Root. 2. DFS Left Boundary (exclude leaves). 3. DFS all Leaves (Left to Right). 4. DFS Right Boundary (exclude leaves, reverse order). |
Draw a tree. Draw a blue line down the leftmost nodes, a green line across the bottom leaves, and a red line up the rightmost nodes. |
Three distinct linear passes. $O(N)$. |
Draw the outline of the tree with three different colored arrows in sequence. |
Arrays storing all possible paths for filtering. |
A list to store the boundary nodes + recursion stack. $O(N)$. |
| 546 |
Remove Boxes |
Exhaustively try every possible box removal sequence, recalculating the score for each branch. |
Exponentially branching tree of choices. $O(N!)$. |
Draw a row of colored boxes. Draw arrows for every possible "pop" sequence. It looks like an out-of-control bush. |
3D Dynamic Programming (Top-Down with Memoization). |
A multi-dimensional storage locker where each state is defined by (Left, Right, Consecutive Same-Colored Boxes on the Left). |
State: `dp(i, j, k)`. If boxes `i` and `i+1` are same, increment `k`. Either remove `i` now ( (k+1)^2 + dp(i+1, j, 0) ) or find another box `m` of same color to merge. |
Draw the array. Bracket index `i` to `j`. Draw a separate box for `k` (the "bonus" count of same colors). Use arrows to show jumping over different colors to merge same ones. |
Filled 3D Cube. $O(N^4)$. |
Draw a 3D cube grid. Shade in cells as they are computed to show the search space is bounded. |
Massive recursion stack without a way to "remember" already solved sub-problems. |
A 3D array of size N x N x N. $O(N^3)$ space. |
| 547 |
Number of Provinces |
For every person, scan the entire matrix to find friends, then friends-of-friends, without tracking who you've already visited. |
Infinite cycles or redundant path traversals. $O(N^3)$. |
Draw dots and lines. Trace paths that go in circles (A-B, B-A) indefinitely. |
DFS / BFS or Union-Find (Disjoint Set Union). |
A social network being grouped into "circles." Once you join a circle, everyone in it is colored the same. |
Iterate through each node. If unvisited, start a DFS/BFS to mark all reachable nodes as visited. Count how many times you had to start a new search. |
Draw dots (cities). Connect them based on the matrix. Use a highlighter to color each "island" of connected dots. The number of colors used is the answer. |
Single pass through the adjacency list/matrix. $O(N^2)$. |
Draw a matrix and a single arrow that visits each row once, triggering a localized "flare" (DFS). |
Deep recursion without a "visited" set. |
A "visited" array of size N and the recursion stack. $O(N)$. |
| 548 |
Split Array with Equal Sum |
Four nested loops to pick three indices (i, j, k) and manually sum the four resulting subarrays to check equality. |
N x N x N x N nested grid. $O(N^4)$. |
Draw an array. Draw 3 vertical lines moving through every possible position combination. |
Prefix Sum + Hash Set for Mid-Point Optimization. |
A balance scale with two arms. You find all possible "left-half" equal splits, store them, then check if the "right-half" can match them. |
Calculate Prefix Sums. Fix middle index `j`. Check for `i` such that `sum(0,i-1) == sum(i+1,j-1)`. Store these sums in a Set. Then check for `k` such that `sum(j+1,k-1) == sum(k+1,n-1)` and exists in Set. |
Draw the array with a fixed center line (j). Draw two moving sliders (i and k) on either side. Check if the "weights" in the 4 created sections match. |
Nested loops optimized by the Hash Set. $O(N^2)$. |
Draw two separate $O(N^2)$ loops that do not nest fully, showing a much smaller search space. |
$O(1)$ extra space but massive time overhead. |
A Hash Set to store intermediate sums and the Prefix Sum array. $O(N)$. |
| 549 |
Binary Tree Longest Consecutive Sequence II |
For every single node in the tree, start two separate DFS searches: one for increasing paths and one for decreasing paths. |
N nodes each performing a full tree search. $O(N^2)$. |
Draw a tree. From every node, draw two diverging paths looking for consecutive numbers. |
Bottom-Up DFS (returning pairs). |
Two relay runners passing batons. One baton tracks "longest increasing" and the other "longest decreasing" as they move up the tree. |
DFS returns `[inc, dec]`. If `child.val + 1 == parent.val`, `parent.inc = child.inc + 1`. If `child.val - 1 == parent.val`, `parent.dec = child.dec + 1`. `maxLen = max(maxLen, inc + dec - 1)`. |
Draw a tree. Next to each node, write two numbers: (UpCount, DownCount). Use these to calculate the total path length crossing through that node. |
Single post-order traversal. $O(N)$. |
Draw the tree and trace a single path that visits every node once from the bottom up. |
Heavy recursion stack from $O(N^2)$ repeated traversals. |
Recursion stack proportional to tree height. $O(H)$. |
| 550 |
Game Play Analysis IV (SQL) |
Find the first login for every player, then for each player, scan the whole table again to see if they logged in on `first_login + 1`. |
N users each scanning an N-row table. $O(N^2)$. |
Draw the table. For each unique ID, draw an arrow searching every other row for a specific date match. |
Subquery / CTE with Date Arithmetic. |
Two filter screens. The first catches "First Logins." The second catches "Day After First Login." The ratio of the two is the result. |
1. Find `MIN(event_date)` per player. 2. Join this with the original table on `player_id` and `event_date = min_date + 1`. 3. Count matching players / Count total players. |
Draw two tables side-by-side. Table A has only (ID, FirstDay). Table B has all data. Draw lines from Table A to Table B only if `B.Date = A.FirstDay + 1`. |
Sorting/Hashing by the database engine. $O(N \log N)$. |
Draw two lists being zipped together based on a common key. |
Massive temporary cross-join table. $O(N^2)$. |
Small intermediate tables for the CTE/Subquery. $O(N)$. |
| 551 |
Student Attendance Record I |
Using complex regular expressions or multiple passes to count 'A's and look for "LLL" substrings. |
Multiple overlapping scans of the same string. $O(N)$. |
Draw the string three times. Scan 1: Count A's. Scan 2: Search for 'LLL'. |
Single Pass State Tracking. |
A security guard watching a gate: keeping a tally for 'A' and a consecutive counter for 'L' that resets on 'P' or 'A'. |
Loop through string. If 'A', `absent++`. If `absent >= 2`, return False. If 'L', `late++`; if `late >= 3`, return False. If not 'L', `late = 0`. |
Write the string. Below it, draw two boxes: "Total A" and "Current L". Update them as you point to each letter; if "Current L" hits 3, draw a big X. |
One smooth, linear scan. $O(N)$. |
Draw a straight line with N segments, evaluated in one direction. |
Creating substring copies for "LLL" checks. |
Two integer variables. $O(1)$ space. |
| 552 |
Student Attendance Record II |
Recursive generation of all possible strings of length N (3^N combinations) and checking each against the rules. |
An exponentially exploding 3-ary tree. $O(3^N)$. |
Draw 'A', 'L', 'P' branches from the root, then 3 more from each, then 3 more... it becomes a solid wall of lines. |
Multi-Dimensional Dynamic Programming (State Compression). |
A control panel with 6 dials representing: (Total 'A' count: 0-1) x (Ending 'L' count: 0-2). Each day, the dials shift based on the new character. |
State `dp[i][j][k]` = ways for length `i` with `j` total 'A's and `k` trailing 'L's. Use transitions to fill for `i+1`. |
Draw a 2x3 grid (the 6 states). Draw arrows showing how an 'L' move, an 'A' move, and a 'P' move transitions you from one box to another. |
Linear progression through N days across 6 states. $O(N)$. |
Draw a timeline of N steps, where each step is a small fixed-size calculation of 6 numbers. |
Massive recursion stack and storage for 3^N strings. |
A 2D array of 2x3 (if only keeping the previous day's state). $O(1)$ or $O(N)$. |
| 553 |
Optimal Division |
Recursive backtracking to try every possible placement of parentheses to find the maximum result. |
Catalan number complexity based on parenthesis placement. $O(2^N)$. |
Draw numbers with brackets shifting in every possible way: `(a/b)/c`, `a/(b/c)`, etc. |
Math / Greedy Observation. |
A fraction where the numerator is as big as possible and the denominator is as small as possible. X_1 / (X_2 / X_3 / ... / X_n). |
The first number is always the numerator. To maximize, minimize the entire rest of the sequence by grouping everything after the first slash. |
Write the numbers. Draw a big bracket starting after the first number and ending at the very last number. |
Single string join operation. $O(N)$. |
Draw the array once and insert characters at fixed positions. |
Deep recursion tree with repeated floating-point divisions. |
String buffer to store the final formatted result. $O(N)$. |
| 554 |
Brick Wall |
Draw the wall on a grid and check every possible vertical line (every x-coordinate) to count how many bricks it cuts. |
Grid scan of Width x Height. $O(W \cdot H)$. |
Draw a brick wall. Draw 100 vertical lines through it. For each line, count how many bricks it intersects. |
Hash Map of Edge Frequencies. |
A map of "cracks." You are looking for the x-coordinate where the most brick edges align. The more edges, the fewer bricks cut. |
For each row, track running width (edge position). `Map[edge]++`. The answer is `Rows - Max(Map.values())`. |
Draw the wall. Below it, draw a number line. For every brick edge, draw a tally mark on the number line. Find the coordinate with the most tallies. |
Linear scan of every brick in the wall. $O(N)$ where N is total bricks. |
Draw a timeline representing the width of the wall, with a single pass filling a table. |
A 2D matrix representing the entire wall area (Width x Height). |
A Hash Map storing unique edge positions. $O(\text{Number of unique edges})$. |
| 555 |
Split Concatenated Strings |
For every string in the list, generate all 2^N combinations of normal/reversed versions, concatenate them, and check every possible split point. |
Exponential combinations x linear split points. $O(2^N \cdot L^2)$. |
Draw N strings. Branch each into (normal, reverse). Concatenate. Cut at index 0, 1, 2... repeat for all 2^N. |
Greedy Pre-reversal + Optimized Split Scan. |
A cycle of "best faces." First, flip all strings to their lexicographically larger version. Then, for each string, try it as the "split point" using both its normal and reversed form. |
1. Flip each `s[i]` to `max(s[i], reverse(s[i]))`. 2. For each `s[i]`, try both versions as the start/end string. Combine with the pre-flipped versions of others. Find the global max. |
Draw the list of strings in a circle. Highlight the pre-flipped versions. Pick one string, rotate the circle so it's the start, and test its split points. |
Linear scan of split points over N strings. $O(L^2)$ where L is total length. |
Draw a circular loop of strings with a sliding cut-point. |
Storing all 2^N concatenated combinations. |
String buffer for the current best result. $O(L)$. |
| 556 |
Next Greater Element III |
Generate all permutations of the digits of the given number, sort them, and find the one immediately larger than the input. |
Factorial growth of digit permutations. $O(D!)$. |
Draw the number (e.g., 123). Draw a tree branching into 132, 213, 231, 312, 321. Circle the one just above 123. |
Next Permutation Algorithm (Linear Scan). |
A mountain range. You walk from right-to-left looking for the first "dip" (decrease), then swap and reverse the "slope" to make it as small as possible. |
1. Find first digit `i` from right where `arr[i] < arr[i+1]`. 2. Find digit `j` from right where `arr[j] > arr[i]`. 3. Swap `i` and `j`. 4. Reverse everything after index `i`. |
Write the digits (e.g., 1 5 8 4 7 6 5 3 1). Draw a left-arrow until you hit 4. Draw a circle around 4 and the smallest number to its right that is larger (5). Swap them, then draw a "reverse" arc over the remaining tail. |
Two linear scans of the digits. $O(Log N)$ where N is the value (number of digits). |
Draw a straight line of digits with two or three pointers moving across it. |
An array/list to store all D! permutations. |
A small array of digits. $O(Log N)$ space. |
| 557 |
Reverse Words in a String III |
Split the string into an array of words, reverse each word string completely, then join them back together with spaces. |
Multiple string allocations and full-string reconstructions. $O(N)$. |
Draw the sentence. Draw a box around each word. Draw a new line with the boxes in the same order but letters flipped. |
Two-Pointer In-Place Swap. |
A "per-word" mirror. You move through the string, and every time you hit a space, you flip the section behind you. |
Maintain a `start` pointer. Iterate with `i`. When `s[i]` is a space, swap characters from `start` to `i-1` moving inward. Update `start = i + 1`. |
Write the sentence. Draw a bracket under the first word. Draw two arrows at the bracket edges pointing inward. Move to the next word and repeat. |
Single pass with in-place character swaps. $O(N)$. |
Draw a straight line with N segments and localized "swap" loops at each word boundary. |
Creating an array of strings and multiple reversed string objects. |
A character array (in languages with immutable strings) or zero extra space. $O(N)$. |
| 558 |
Logical OR of Two Quadtrees |
Convert both Quadtrees into full N x N grids, perform a cell-by-cell OR operation, and then re-construct a Quadtree from the result. |
Matrix explosion. $O(N^2)$ where N is the side length. |
Draw two 4x4 grids. Draw a third grid representing the OR result. Show the effort of checking 16 cells. |
Recursive Tree Merging (Divide & Conquer). |
Merging two square maps. If one map is "solid color" (leaf), the result for that whole area is immediately determined without looking at the other map's details. |
If `t1.isLeaf`: return `t1.val ? t1 : t2`. If `t2.isLeaf`: return `t2.val ? t2 : t1`. Else, recurse on all 4 children. If all 4 children are leaves and same value, merge them into one leaf. |
Draw two Quadtrees (squares divided into 4). Overlay them. If a solid-1 square hits a divided square, color the whole area 1. If two divided squares hit, divide the result square too. |
Traversal bounded by the number of nodes in the trees. $O(N)$ where N is total nodes. |
Draw two tree structures merging into one at the same depth levels. |
An N x N matrix in memory. |
Recursion stack proportional to the depth of the Quadtree. $O(Log N)$. |
| 559 |
Maximum Depth of N-ary Tree |
Perform a BFS level-order traversal, storing every single node in a list for each level, then counting the number of lists. |
Redundant storage of node values level by level. $O(N)$. |
Draw a tree. Draw horizontal boxes for Level 1, Level 2, etc. Fill boxes with node values. |
Simple DFS Recursion. |
A "depth-finder" probe. Each node asks its children "How deep are you?", takes the maximum answer, and adds 1 for itself. |
`if root is None: return 0`. `max_child_depth = max([maxDepth(c) for c in root.children] or [0])`. `return 1 + max_child_depth`. |
Draw the N-ary tree. Starting from leaves (height 1), write the height next to each parent as (1 + max height of children). |
Single visit to every node. $O(N)$. |
Draw a single arrow tracing a path down to every leaf and back up. |
Queue or List holding all N nodes during the level-order scan. |
Recursion stack proportional to the height of the tree. $O(H)$. |
| 560 |
Subarray Sum Equals K |
Nested loops. Outer loop `i` selects start, inner loop `j` selects end, calculate sum of `nums[i...j]` and compare to K. |
Triangle of subarray segments. $O(N^2)$. |
Draw the array. Draw brackets for every possible start and end point, calculating the sum for each. |
Prefix Sum + Hash Map. |
A "target-finder" in history. As you walk forward, you calculate your total distance. You look back at your "history map" to see how many times you were exactly `CurrentDistance - K` units away. |
Maintain `running_sum`. `count += Map[running_sum - k]`. `Map[running_sum]++`. Initialize `Map[0] = 1`. |
Draw the array. Below it, write the running sum. Keep a side-table (Map) of `(Sum : Occurrences)`. At each step, subtract K from the sum and look it up in the table. |
Single pass over the array. $O(N)$. |
Draw a straight timeline with a single pass filling a table. |
$O(1)$ auxiliary space (just loop variables) but slow time. |
A Hash Map storing up to N unique prefix sums. $O(N)$ space. |
| 561 |
Array Partition I |
Generate every possible combination of pairs, find the sum of minimums for each combination, and pick the maximum. |
Exponential growth of pair combinations. $O((2N)$! / (2^N * N!)). |
Draw 4 numbers. Draw lines connecting them in every possible pairing (1-2, 3-4; 1-3, 2-4; etc.). |
Sorting + Greedy Pairing. |
A buddy system where everyone stands in a line by height. To lose as little "height" as possible, you pair people with their closest height matches. |
Sort the array. Sum every element at an even index (0, 2, 4...). |
Write numbers. Sort them: [1, 2, 3, 4]. Circle the 1st and 3rd elements. Sum them. |
Sorting phase dominates. $O(N \log N)$. |
Draw a sorting timeline followed by a single pass jumping over every other element. |
A large list/set to store all possible pairing combinations. |
Sorting space, usually $O(\log N)$ or $O(N)$ depending on the sort implementation. |
| 562 |
Longest Line of Consecutive One in Matrix |
For every cell `(i, j)`, if it is 1, scan in all 8 directions to count consecutive ones. |
Grid scan where each cell triggers 4-8 linear scans. $O(M \cdot N \\text{cdot max}(M, N)$). |
Draw a grid. Pick a '1'. Draw lines extending horizontally, vertically, and diagonally until hitting a '0'. Repeat for all. |
3D Dynamic Programming (Spatial State). |
A radar screen tracking 4 different "streaks" simultaneously as it sweeps across the grid. |
State `dp[i][j][4]` stores max length for (Horiz, Vert, Diag, Anti-Diag) ending at `(i, j)`. `dp[i][j][dir] = dp[prev_i][prev_j][dir] + 1`. |
Draw the matrix. At each '1', write a small 4-tuple: `(H, V, D, AD)`. Calculate these based on the values of the neighbors above, left, and diagonally. |
Single pass over the grid. $O(M \cdot N)$. |
Draw a grid with a single arrow weaving through every cell once. |
Large recursion stack if using DFS or $O(1)$ space but very high time. |
A 3D DP array of size M x N x 4 (can be optimized to 2D). $O(M \cdot N)$. |
| 563 |
Binary Tree Tilt |
For every node, perform a full DFS to calculate the sum of its left subtree and another for the right. Calculate difference. |
N nodes each performing a subtree sum scan. $O(N^2)$. |
Draw a tree. For each node, draw two large circles around its subtrees to sum them up. |
Post-order Traversal (Bottom-Up Summing). |
A "weight-lifter" reporting back. Each child tells the parent their total weight. The parent calculates the "imbalance" (tilt) and reports the new total weight up. |
DFS returns the sum of the subtree. `tilt = abs(left_sum - right_sum)`. `total_tilt += tilt`. Return `node.val + left_sum + right_sum`. |
Draw a tree. Start at leaves. Write the sum of the subtree inside the node and the absolute difference (tilt) in a box next to it. |
Every node visited exactly once. $O(N)$. |
Draw the tree and trace a single "U-shaped" path from bottom to top. |
Heavy recursion stack from repeated nested traversals. |
Recursion stack proportional to tree height. $O(H)$. |
| 564 |
Find the Closest Palindrome |
Iterate upward and downward from the given number one by one until a palindrome is found. |
Linear search in a space that could be millions of numbers wide. $O(N)$. |
Draw a number line. Start at N and move left and right step-by-step, checking each number for symmetry. |
Prefix Manipulation + Candidate Testing. |
A "mirror" at the center. You take the first half of the number and reflect it. You also test the reflect of (prefix + 1) and (prefix - 1). |
1. Take first half as `prefix`. 2. Candidates: Reflected prefix, reflected `prefix+1`, reflected `prefix-1`, `10^(n-1)-1`, and `10^n+1`. 3. Pick the closest one. |
Write the number: `12345`. Take `123`. Mirror it: `12321`. Also try `124` mirrored: `12421` and `122` mirrored: `12221`. Compare distances. |
Constant number of string operations. $O(\log N)$ (number of digits). |
Draw a single box with 5 candidate paths branching out. |
Large string objects created during the linear search. |
A list of 5 candidate strings. $O(\log N)$ space. |
| 565 |
Array Nesting |
For every index `i`, follow the path `nums[i], nums[nums[i]], ...` until a cycle is formed, without tracking visited indices. |
N nodes each potentially traversing the same long cycle. $O(N^2)$. |
Draw an array. Draw arrows from each index to its value. Trace the path from every single starting point. |
Visited Set / In-Place Marking. |
A scavenger hunt where you mark each "clue" as found. Once you've been to a location, you never need to start a new search from there. |
Iterate through `nums`. If `nums[i]` is not marked, follow the cycle and mark each element as visited. Track the max cycle length. |
Draw the array. Pick an index, follow the arrow, and "cross out" the number. Count the steps. Move to the next "non-crossed" number. |
Each element is visited exactly once. $O(N)$. |
Draw a series of isolated circles (cycles), with a single arrow visiting each element once. |
$O(1)$ auxiliary space but $O(N^2)$ time. |
A boolean "visited" array or in-place modification of `nums`. $O(N)$ or $O(1)$. |
| 566 |
Reshape the Matrix |
Create a flat list of all M \times N elements by iterating through the original matrix, then iterate through the flat list to fill a new R \times C matrix. |
Double-pass traversal with intermediate storage. $O(M \\text{times} N)$. |
Draw a 2 \times 2 matrix. Draw an arrow pouring the numbers into a long pipe. Draw the pipe pouring numbers into a 1 \times 4 matrix. |
Direct Index Mapping (Modulo Arithmetic). |
A single conveyor belt. As items come off the old grid, they are immediately placed into the new grid without ever touching the floor (intermediate list). |
Check if M \times N == R \times C. Loop i from 0 to (M \times N - 1). Original element is `mat[i/N][i%N]`. Place it in `res[i/C][i%C]`. |
Write out the original matrix coordinates. Show the math: `index / total_cols` for row and `index % total_cols` for column. Map these directly to the new dimensions. |
Single pass with no intermediate storage. $O(M \\text{times} N)$. |
Draw a single arrow weaving through the original matrix and simultaneously appearing in the new one. |
A flat list/array of size M \times N. |
$O(1)$ auxiliary space (excluding the result matrix). |
| 567 |
Permutation in String |
Generate all N! permutations of string `s1` and check if any of them exist as a substring in `s2`. |
Factorial explosion $O(N! \\text{times} M)$. |
Draw `abc`. Draw a tree for `abc, acb, bac...`. For each, draw a sliding window across the second string. |
Sliding Window + Frequency Map (Fixed Size). |
Two "frequency buckets." You have a target bucket for `s1`. You slide a window of the same size across `s2`, adding a character to your current bucket and removing the oldest one. |
Create a frequency array (size 26) for `s1`. Slide a window of length `s1.length` over `s2`. If the frequency arrays match, return true. |
Write `s1`. Draw a frequency table (A:1, B:1). Write `s2`. Draw a box (window) over `s2`. As it slides, update a second frequency table and compare it to the first. |
Linear scan of both strings. $O(N + M)$. |
Draw two strings with a fixed-width box sliding over the longer one. |
An array/list to store all N! permutations. |
Two fixed-size arrays of length 26. $O(1)$ space. |
| 568 |
Maximum Vacation Days |
Exhaustively try every possible flight combination for every week to find the path that yields the most vacation days. |
Exponential branching $O(N^K)$ where N is cities and K is weeks. |
Draw a city. Draw N arrows to other cities for Week 1. From each of those, draw N more arrows for Week 2. |
2D Dynamic Programming (Bottom-Up). |
A "reverse itinerary" planner. You start at the last week and calculate the max vacation possible from each city, then move backward to the start. |
`dp[week][city]` is max days from this city/week. `dp[i][j] = max(vacation[j][i] + dp[i+1][next_city])` for all cities reachable from j. |
Draw a grid: Weeks (columns) by Cities (rows). Start at the last column. For each cell, look at the next column's reachable cities and take the max. |
Bounded grid filling. $O(K \\text{times} N^2)$. |
Draw a rectangle of K \times N and show each cell performing N checks. |
Massive recursion stack without memoization. |
A 2D DP table (or two 1D arrays for space optimization). $O(N \\text{times} K)$ or $O(N)$. |
| 569 |
Median Employee Salary (SQL) |
Sort the entire table, count the total rows, then manually calculate the middle index and select that row. |
Global sorting and manual row-by-row counting. $O(N \log N)$. |
Draw a giant list of employees. Sort them. Count to the middle and circle the names. |
Row Numbering / Window Functions. |
Two rank lists. One counts from the bottom, one counts from the top. The "Median" is where the ranks are nearly equal. |
`ROW_NUMBER() OVER(PARTITION BY company ORDER BY salary)` as `rk_asc` and `DESC` as `rk_desc`. Filter where `rk_asc` is in `(total/2, total/2 + 1)`. |
Draw a table. Add two columns: Rank-Up and Rank-Down. The median rows are those where the difference between these two ranks is 0 or 1. |
Partitioned sorting. $O(N \log N)$. |
Draw a table split into company-buckets, with a single sort applied to each bucket. |
Full table scan and multiple temporary tables. |
In-memory index pointers for window partitions. |
| 570 |
Managers with at Least 5 Direct Reports (SQL) |
For every employee, scan the entire table to count how many other employees have them listed as their manager. |
Nested loop table scan. $O(N^2)$. |
Draw a table. Point to person A. Scan every other row to see if "Manager = A". Repeat for everyone. |
Group By + Having Clause. |
A sorting facility. All employees are sorted into bins based on who their manager is. You then only look at bins with 5 or more items. |
`SELECT name FROM Employee WHERE id IN (SELECT managerId FROM Employee GROUP BY managerId HAVING COUNT(*) >= 5)`. |
Draw a pile of folders (employees). Sort them into stacks based on manager ID. Count the size of each stack. Circle the managers of the big stacks. |
Hash-based grouping. $O(N)$. |
Draw a table flowing into a Hash Map (ManagerID : Count). |
$O(1)$ extra space but very high time. |
A Hash Map to store counts per manager. $O(\text{Unique Managers})$. |
| 571 |
Find Median Given Frequency of Numbers (SQL) |
Expand the frequency table into a full list of individual numbers (e.g., 1:3 becomes 1,1,1), sort them, and pick the middle index. |
Memory explosion for large frequencies. $O(\\text{sum Frequency})$. |
Draw a small table: (Val 10, Freq 1000). Draw 1000 tiny dots to show the waste of space. |
Running Total (Cumulative Frequency) Analysis. |
A progress bar. The median is the point where the progress bar passes the 50% mark of the total population. |
Calculate total count N. Use a window function for cumulative frequency. The median exists where `cumulative_freq - frequency <= N/2` AND `cumulative_freq >= N/2`. |
Draw a table with columns: Value, Freq, and CumSum. Total items = 10. Draw a line at 5 and 6. See which "Value" row those numbers fall into. |
Single pass with window functions. $O(N \log N)$ (due to sort). |
Draw a staircase graph where each step's width is the frequency; the median is the step at the midpoint of the X-axis. |
Massive array holding every single occurrence of every number. |
$O(N)$ space for the cumulative sum table. |
| 572 |
Subtree of Another Tree |
For every node in the main tree, initiate a full recursive "isSameTree" check against the subRoot. |
N nodes each performing an M-node comparison. $O(N \\text{times} M)$. |
Draw a large tree. At every single node, draw a shadow of the small tree and check for a perfect match. |
Merkle Hashing or String Serialization (KMP). |
A fingerprint scanner. You give the small tree a unique ID (hash) and then check every node in the big tree to see if its "subtree ID" matches. |
Serialize both trees into strings (using markers for nulls). Use `string.contains()` or KMP to find if the small string exists in the large one. |
Draw both trees. Convert them into strings: `[#3[#4[#1][#2]][#5]]`. Check if the small string is a substring of the big one. |
Linear time serialization and search. $O(N + M)$. |
Draw two strings with a sliding window check (KMP style). |
Deep recursion stack for the $O(N \\text{times} M)$ approach. |
$O(N + M)$ space to store the serialized strings. |
| 573 |
Squirrel Simulation |
Try every possible permutation of nut-gathering orders (which nut to get first, which second, etc.). |
Factorial explosion $O(N!)$. |
Draw a squirrel and 5 nuts. Draw every possible path connecting the squirrel to all nuts and the tree. |
Greedy Distance Calculation (Total Distance - Max Saving). |
A delivery truck. The truck always goes from Tree to Nut and back (2 \times distance). The only "saving" is on the very first trip from the Squirrel's starting spot. |
Total Dist = \sum (2 \times \text{Dist(Nut, Tree)}). For each nut, calculate the "Saving": \text{Dist(Nut, Tree)} - \text{Dist(Nut, Squirrel)}. Subtract the max saving from Total Dist. |
Draw a map. Draw double-arrows between every nut and the tree. Then draw one single arrow from the squirrel to one nut. Calculate which nut makes that first trip shortest relative to the tree. |
Single pass through the nuts. $O(N)$. |
Draw a central hub (Tree) with spokes to all nuts. One spoke is replaced by a squirrel-to-nut path. |
Storing all path permutations in a list. |
$O(1)$ auxiliary space. |
| 574 |
Winning Candidate (SQL) |
For every candidate, scan the entire Vote table to count their votes, then sort the counts. |
Nested loop or full table scan with multiple passes. $O(N^2)$. |
Draw a table of candidates. For each, count lines in the Vote table. |
Join + Group By + Limit. |
A ballot box. Dump all votes into bins labeled with Candidate IDs. Pick the tallest bin. |
`SELECT Name FROM Candidate JOIN (SELECT CandidateId FROM Vote GROUP BY CandidateId ORDER BY COUNT(*) DESC LIMIT 1) AS Winner ON id = CandidateId`. |
Draw two tables. Group the Vote table into stacks. Sort the stacks by height. Use the top stack's ID to look up the Name in the Candidate table. |
Hash-based grouping. $O(N)$. |
Draw a Vote table flowing into a "Count Map," then a single lookup to the Candidate table. |
$O(1)$ extra space but very slow execution. |
A Hash Map for vote counts. $O(\\text{text}{\text{Unique Candidates}})$. |
| 575 |
Distribute Candies |
Generate every possible combination of N/2 candies and count the number of unique types in each combination. |
Combinatorial explosion O\binom{N}{N/2}. |
Draw 6 candies. List every possible set of 3 you could pick (1-2-3, 1-2-4, etc.) and count types in each. |
Set Size vs. Half-Length Comparison. |
A collector's limit. You want as many unique stamps as possible, but your album only holds N/2 pages. Your variety is limited by either the total stamps you own or the pages available. |
`UniqueTypes = count(Set(candies))`. `Result = min(UniqueTypes, candies.length / 2)`. |
Draw a pile of candies. Put one of each type into a "Unique Box." If the box size is bigger than half the total candies, cross out the extras until it fits. |
Single pass to count unique elements. $O(N)$. |
Draw a bag of candies flowing into a Set, then a comparison to a "Max Allowed" box. |
A list of all combinations in memory. |
A Hash Set to store unique types. $O(N)$. |
| 576 |
Out of Boundary Paths |
Recursive DFS exploring all 4 directions for every step until `maxMove` is reached, counting every time the coordinates go out of bounds. |
Exponential branching $O(4^N)$ where N is maxMove. |
Draw a grid. From the start point, draw 4 arrows. From each arrow, draw 4 more. Circle any arrow that leaves the grid. |
3D Dynamic Programming (Memoization). |
A "Heat Map" over time. Each "second" (move), the probability of being at a cell spreads to its neighbors. The "heat" that leaks off the edge is your answer. |
`dp[move][r][c]` is the number of ways to reach `(r, c)` in `move` steps. The count for `move + 1` is the sum of its neighbors' counts from `move`. |
Draw a 3 \times 3 grid. In each cell, write the number of ways to get there in 1 move, then 2, then 3. Any time you "move" off the paper, add that value to a "Total Out" box. |
Bounded grid filling over moves. $O(N \\text{times} M \\text{times} \\text{text}{\text{maxMove}})$. |
Draw a stack of grids (one for each move count) where each grid's values are derived from the one below it. |
Massive recursion stack with millions of redundant path calculations. |
Two 2D arrays (Current Move and Previous Move) of size M \times N. $O(M \\text{times} N)$. |
| 577 |
Employee Bonus (SQL) |
For every employee in the Employee table, search the entire Bonus table to see if they have a bonus entry and if it's less than 1000. |
Nested loop search across two tables. $O(E \\text{times} B)$. |
Draw two tables. Pick an ID from Table 1. Scan every row of Table 2 to find a match. Repeat. |
Left Join with Null/Value Filtering. |
A "Master List" where you attach sticky notes (bonuses) to names. You keep everyone who has a note < 1000 AND everyone who doesn't have a note at all. |
`SELECT name, bonus FROM Employee LEFT JOIN Bonus ON Employee.empId = Bonus.empId WHERE bonus < 1000 OR bonus IS NULL`. |
Draw the Employee table. Draw the Bonus table. Draw lines connecting matching IDs. If an Employee has no line, or the line leads to a value < 1000, circle them. |
Index-based join or Hash join. $O(E + B)$. |
Draw two tables being merged into one based on a shared ID column. |
$O(1)$ extra space but very slow execution. |
Temporary join buffer in memory. $O(E + B)$. |
| 578 |
Get Highest Answer Rate Question (SQL) |
Count all "show" events and "answer" events for every question separately, calculate the ratio for each, and sort. |
Multiple table scans and manual math per question. $O(N^2)$. |
Draw a log. For Question 1, count "shows" and "answers". Calculate. Repeat for Question 2. |
Group By + Aggregate Ratio + Order By. |
A scoreboard. Every time a question is shown, the "Possible" score goes up. Every time it's answered, the "Actual" score goes up. Rank by Actual/Possible. |
`SELECT question_id FROM survey_log GROUP BY question_id ORDER BY COUNT(answer_id) / COUNT(CASE WHEN action='show' THEN 1 END) DESC LIMIT 1`. |
Draw a tally sheet. Columns: Question ID, Show Count, Answer Count. For each log entry, add a tick mark. Finally, divide Answer/Show and pick the highest. |
Hash-based grouping. $O(N)$. |
Draw a log table flowing into a summarized Map of ratios. |
$O(1)$ extra space but very inefficient. |
Hash Map for question stats. $O(\\text{text}{\text{Unique Questions}})$. |
| 579 |
Find Cumulative Salary of an Employee (SQL) |
For every month, scan the table to find the current month and the two previous months for that employee and sum them. |
Nested loop self-join for every row. $O(N^2)$. |
Draw a table. For the row "March", search for "February" and "January" for the same ID and add them. |
Window Function (ROWS BETWEEN). |
A "Moving Window" of size 3. As you move down the months for an employee, the window slides with you, summing everything inside it. |
Exclude max month per ID. Use `SUM(salary) OVER(PARTITION BY id ORDER BY month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW)`. |
Draw an employee's salary history by month. Place a 3-month-long bracket over the current month and the two months above it. Sum them. |
Single pass over sorted partitions. $O(N \log N)$. |
Draw a timeline where a box of fixed width 3 slides forward one step at a time. |
Temporary Cartesian product from self-joins. $O(N^2)$. |
Buffer for the 3-row sliding window. $O(N)$. |
| 580 |
Count Student Number in Departments (SQL) |
For every department, iterate through the entire Student table to count how many students belong to it. |
Nested loop $O(\\text{text}{\text{Depts}} \\text{times} \\text{text}{\text{Students}})$. |
Draw Dept table. For Dept A, scan every row in Student table. Repeat for Dept B. |
Left Join + Group By. |
Empty bins with labels. You walk through the student list and drop each student into their labeled department bin. Even bins with 0 students are kept. |
`SELECT dept_name, COUNT(student_id) FROM department LEFT JOIN student ON department.dept_id = student.dept_id GROUP BY department.dept_id ORDER BY student_number DESC`. |
Draw the Department list. Draw the Student list. For each student, draw an arrow to their department. Count arrows per department. |
Hash-based join and grouping. $O(N)$. |
Draw two tables merging and then collapsing into a summary count table. |
$O(1)$ extra space but high time complexity. |
Hash Map for department counts. $O(\\text{text}{\text{Unique Departments}})$. |
| 581 |
Shortest Unsorted Continuous Subarray |
Generate every possible subarray, sort it, and check if the entire array becomes sorted. Find the shortest such subarray. |
Combination of subarrays $O(N^2)$ and sorting $O(N \log N)$. Total $O(N^3 \log N)$. |
Draw an array. Draw brackets over every segment. Draw a "sorted version" below each and compare it to the original. |
Two-Pass Monotonic Logic (Min/Max Tracking). |
A "disorder zone." You look from the left for the first dip and from the right for the first peak. The "damage" caused by these outliers defines the boundaries of the unsorted segment. |
Find the `min` value of the "unsorted" part (where nums[i] < nums[i-1]). Find the `max` of the same. Find the first index from the left bigger than `min`, and the first from the right smaller than `max`. |
Draw the array: `[2, 6, 4, 8, 10, 9, 15]`. Identify 4 and 9 as the "troublemakers." Find where 4 *should* have been (index 1) and where 9 *should* have been (index 5). The distance between is the answer. |
Four linear scans (or two passes). $O(N)$. |
Draw a straight line with two markers (left and right) closing in on the middle "messy" area. |
Storing all subarray combinations in a list. |
$O(1)$ auxiliary space. |
| 582 |
Kill Process |
For the target PID, scan the entire `ppid` list to find children. For each child found, repeat the scan to find grandchildren. |
Recursive list scanning. $O(N^2)$. |
Draw a list of IDs. For ID 5, look at every other ID to see if its parent is 5. Repeat for every result. |
Hash Map Adjacency List + BFS/DFS. |
A family tree. You convert the flat list into a proper tree structure using a Map, then simply "prune" the branch starting at the target PID. |
Build Map: `parent -> [children]`. Use a Queue (BFS) starting with `kill` PID. While queue not empty, pop PID, add to result, and push all its children from the Map to the queue. |
Draw a Map: `3: [1, 5], 5: [10]`. Draw a circle around 5. Follow the arrow to 10. All circled items are part of the "kill list." |
Single pass to build Map + single traversal. $O(N)$. |
Draw a tree and shade an entire branch starting from a specific node downward. |
Large recursion stack with repeated full-list iterations. |
Hash Map and a Queue/Stack. $O(N)$ space. |
| 583 |
Delete Operation for Two Strings |
Generate all subsequences of both strings and find the longest one they have in common (LCS), then calculate the remaining characters. |
Exponential subsequence generation $O(2^N)$. |
Draw `sea` and `eat`. List every combo: `s, e, a, se, sa, ea, sea...` and find the match. |
2D Dynamic Programming (LCS). |
An edit-distance grid. You find the "core" shared string. The number of deletions is simply the total length of both strings minus twice the length of that core. |
`dp[i][j]` is LCS of `s1[0...i]` and `s2[0...j]`. If `s1[i] == s2[j]`, `dp[i][j] = 1 + dp[i-1][j-1]`. Else, `max(dp[i-1][j], dp[i][j-1])`. Result: `len1 + len2 - 2*LCS`. |
Draw an N \times M grid. Fill it based on character matches. The bottom-right corner gives the length of the Longest Common Subsequence. |
Filling a bounded N \times M table. $O(N \\text{times} M)$. |
Draw a rectangle divided into a grid, shading cells one by one as they are computed. |
Recursion stack for 2^N branches. |
$O(N \\text{times} M)$ DP table (can be optimized to $O(\\text{min}(N, M)$)). |
| 584 |
Find Customer Referee (SQL) |
Scan every row and check if the `referee_id` is not equal to 2. (Common trap: missing NULL values). |
Linear scan $O(N)$. |
Draw a list. Look at the referee column. If you see a '2', cross it out. (Wait, what about the empty ones?) |
Filtered Select with Null Handling. |
A filter with three holes: one for "not 2", one for "is 2", and a "trapdoor" for NULL. You must explicitly tell the trapdoor to let the NULLs through. |
`SELECT name FROM customer WHERE referee_id <> 2 OR referee_id IS NULL`. |
Draw a table. Circle every row where the referee ID is blank or any number that isn't 2. |
Single pass over the table. $O(N)$. |
Draw a table flowing into a single filter box with two exit conditions. |
$O(1)$ extra space. |
$O(1)$ auxiliary space. |
| 585 |
Investments in 2016 (SQL) |
For every investment, scan the whole table to check if its `TIV_2015` matches someone else, and then scan again to check if its location is unique. |
Nested loop scans $O(N^2)$ or $O(N^3)$. |
Draw the table. For Row 1, search the whole table for a matching 2015 value. Then search the whole table again to ensure no one has the same Lat/Lon. |
Window Functions or Subqueries with Group By. |
Two checklists. Checklist 1: Is your 2015 value "popular" (shared by others)? Checklist 2: Is your location "exclusive" (held by only you)? If both are YES, you are counted. |
`WHERE TIV_2015 IN (SELECT TIV_2015 FROM insurance GROUP BY TIV_2015 HAVING COUNT(*) > 1) AND (LAT, LON) IN (SELECT LAT, LON FROM insurance GROUP BY LAT, LON HAVING COUNT(*) = 1)`. |
Draw a tally sheet for TIV_2015 and a tally sheet for (Lat, Lon). Circle IDs that have a count > 1 in the first sheet and a count = 1 in the second. |
Hash-based grouping and filtering. $O(N \log N)$. |
Draw the main table flowing into two separate "Filter Bins," then joining back to the original. |
$O(1)$ extra space but very high time complexity. |
Hash Map for grouping counts. $O(N)$. |
| 586 |
Customer Placing the Largest Number of Orders (SQL) |
For every customer in the orders table, count their occurrences individually, then sort and find the maximum. |
Manual tallying of a long list. $O(N \log N)$. |
Draw a list of Order IDs and Customer IDs. For each customer, count how many times they appear. Circle the one with the highest count. |
Group By + Order By Count + Limit 1. |
A sorting bin system. You throw every order into a bin labeled with the Customer Number. The tallest bin wins the prize. |
`SELECT customer_number FROM orders GROUP BY customer_number ORDER BY COUNT(*) DESC LIMIT 1`. |
Draw the Orders table. Group it into piles by Customer ID. Measure the height of each pile. Pick the top one and write down the ID. |
Hash-based grouping. $O(N)$. |
Draw the table flowing into a Hash Map (ID : Count) and then a single "Max" pointer. |
$O(1)$ extra space but slow for very large tables. |
A Hash Map for counts. $O(\\text{text}{\text{Unique Customers}})$. |
| 587 |
Erect the Fence |
Check every possible line segment between two points (P_i, P_j) to see if all other points lie on one side of that line. |
Brute force Convex Hull (All pairs). $O(N^3)$. |
Draw 10 dots. Draw a line between two. Check if all 8 other dots are on the left. Repeat for all 45 pairs. |
Monotone Chain Algorithm (Sorting + Cross Product). |
A rubber band effect. You sort the points and then wrap a "string" around the top half and then the bottom half, popping the string outward if it hits a "dent." |
1. Sort points by X-coordinate. 2. Build upper hull by adding points and checking cross product (turn direction); pop points that create a "right turn." 3. Repeat for lower hull. |
Draw dots. Move left to right. Connect three dots. If the middle one creates a "cave" (concave), erase it and connect the outer two. It should look like an expanding shell. |
Sorting + Two Linear Passes. $O(N \log N)$. |
Draw a sorting timeline followed by a string wrapping around a set of pins. |
Storing all possible line combinations. |
A list to store the perimeter points. $O(N)$. |
| 588 |
Design In-Memory File System |
Use a flat Hash Map where the Key is the full path string and the Value is the content. For `ls`, scan all keys and check for prefix matches. |
Full string prefix scanning for every directory listing. $O(N \\text{times} L)$. |
Draw a table with paths like "/a/b/c". For "ls /a", read every single entry in the table to see if it starts with "/a". |
Trie-based Directory Structure. |
A real filing cabinet. Every folder is a node that contains a map of its children (other folders or files). Navigating is just following the pointers. |
Create a `Node` class with `Map children` and `StringBuilder content`. For `ls`, traverse the path and return sorted keys of the target node's map. |
Draw a tree. The root is `/`. It has a branch to `a`. `a` has a branch to `b`. Inside `b` is a file node named `c`. To find `c`, you just follow the `a -> b -> c` path. |
Traversal proportional to path depth. $O(\\text{text}{\text{Path Depth}})$. |
Draw a Trie (prefix tree) where each edge is a directory name. |
Redundant string storage for every full path. |
$O(\\text{text}{\text{Total Chars in all names} + \text{Content}})$. Trie nodes minimize name redundancy. |
| 589 |
N-ary Tree Preorder Traversal |
Convert the tree into an adjacency list first, then perform a recursive traversal. |
Two-pass process with unnecessary intermediate storage. $O(N)$. |
Draw a tree. Write it as a list of lists. Then traverse that list. |
Recursive DFS or Iterative Stack. |
A "Deep Dive." You visit the parent, then immediately plunge into the first child, then its first child, until you hit a leaf, then move to the next sibling. |
Recursive: `Visit(root)`. For each `child` in `root.children`, `DFS(child)`. Iterative: Push root to stack. While stack not empty, pop, add to result, and push all children to stack in **reverse** order. |
Draw an N-ary tree. Trace a line starting from the root, going to the leftmost child, then its children, then back up slightly to the next sibling. |
Single visit to every node. $O(N)$. |
Draw a tree and follow a single arrow that hugs the "left side" of every branch. |
Storing the adjacency list explicitly. |
Recursion stack or Iterative stack. $O(H)$ or $O(N)$ in worst case. |
| 590 |
N-ary Tree Postorder Traversal |
Traverse the tree and store nodes in a list, then use a custom sorting algorithm based on depth and position to order them. |
Complex sorting logic after traversal. $O(N \log N)$. |
Draw a tree. Tag each node with a number, then sort those numbers based on postorder rules. |
Recursive DFS or Iterative "Reverse Preorder". |
A "Bottom-Up" finish. No parent is finished until all its children are completely done. It's like a supervisor who only signs off after all subordinates finish. |
Recursive: For each `child` in `root.children`, `DFS(child)`. `Visit(root)`. Iterative: Do Preorder (Root, Right, Left) and then reverse the final result list. |
Draw the tree. Start at the bottom-left leaf. Move to its siblings, then to their parent. Always finish the "floor" before the "ceiling." |
Single visit to every node. $O(N)$. |
Draw a tree and follow an arrow that loops under the bottom of the leaves before pointing to the parent. |
The overhead of sorting a full tree list. |
Recursion stack. $O(H)$ where H is the height of the tree. |
| 591 |
Tag Validator |
Use a massive, nested regular expression to try and validate the entire XML-like string in one go. (Extremely error-prone and hard to debug). |
Non-deterministic finite automaton (NFA) overhead. $O(N)$ but high constant factor. |
Draw a complex flow chart with 50+ decision diamonds for every possible character and state. |
Stack-based Parsing + State Machine. |
An industrial "Bracket Matcher." Every time you see a start tag ``, you push it onto a stack. Every time you see an end tag ``, you must pop the exact same name from the stack. |
Iterate string. 1. If starts with ``. 2. If starts with `` and pop stack. 3. If starts with `<`, find `>` and push stack. 4. Ensure stack never empty until the very end. |
Write ``. Draw a vertical stack box. Push 'a', then push 'b'. When you hit ``, pop 'b'. When you hit ``, pop 'a'. If stack is empty and string remains, fail. |
Single pass over the string. $O(N)$. |
Draw a straight line with a single pointer moving forward, and a stack growing/shrinking alongside it. |
Massive string copying and recursive regex backtracking. |
A stack to store open tag names. $O(N)$. |
| 592 |
Fraction Addition and Subtraction |
Parse the string manually, calculate each pair of fractions one by one, and simplify the result at every single step using GCD. |
Redundant simplification steps. $O(N \cdot \log(\text{max}_\text{val})$). |
Draw "1/3 + 1/2 - 1/6". Show the steps of 1/3+1/2=5/6, then 5/6-1/6=4/6, then simplify to 2/3. |
Common Denominator (LCM) + Final GCD. |
A shared "Measuring Cup." You convert every single fraction to use the same denominator (e.g., 60), add up the numerators, and only simplify at the very end. |
Parse all numerators and denominators. Use a running result `res_num / res_den`. For each new `n/d`: `res_num = res_num * d + n * res_den` and `res_den = res_den * d`. Simplify at the end. |
Write the fractions. Below, write them all with a shared denominator. Sum the new numerators. Draw a GCD "division box" to reduce the final fraction to its simplest form. |
Linear parsing and constant-time math. $O(N)$. |
Draw a timeline of fractions merging into one single final box. |
Creating numerous intermediate fraction objects. |
Storing a list of parsed integers. $O(N)$. |
| 593 |
Valid Square |
Check every possible permutation of the 4 points to see if they form four equal sides and two equal diagonals. |
4! = 24 permutations to check. $O(1)$ but messy. |
Draw 4 points. Draw lines connecting 1-2, 2-3, 3-4, 4-1. Measure them. Then measure 1-3 and 2-4. |
Distance Sorting / Hash Set of Lengths. |
A "Geometric Signature." In a square, if you calculate the distance between every pair of points (6 total), you should only ever see exactly two distinct values (side length and diagonal). |
Calculate squared distances between all 6 pairs of points. Put distances in a Set. The Set must have size 2, and the distances must be non-zero. |
Draw 4 points. Draw all 6 possible lines. Write the squared distance on each line. There should be four "small" equal numbers and two "large" equal numbers. |
Constant number of calculations (6 pairs). $O(1)$. |
Draw a single box that takes 4 points and outputs a Set of 2 values. |
Storing all permutations in a list. |
A Set to store up to 6 integers. $O(1)$. |
| 594 |
Longest Harmonious Subsequence |
Generate every possible subsequence, and for each, check if the max and min values differ by exactly 1. |
Exponential growth $O(2^N)$. |
Draw [1,3,2,2,5,2,3,7]. List combos like [1,2,2,2] and [3,2,2,2,3]. Check differences. |
Frequency Hash Map. |
A "Neighbor Search." A harmonious subsequence is just the count of a number `X` plus the count of its neighbor `X+1`. You just need to find which pair of neighbors has the highest combined count. |
Build a frequency map of all numbers. For each key `X`, if `X+1` exists in the map, `max_len = max(max_len, map[X] + map[X+1])`. |
Draw the array. Below it, draw a frequency table: `1:1, 2:3, 3:2, 5:1, 7:1`. Check pairs (1,2), (2,3), (3,4)... Sum the values of the pairs and pick the max. |
Two linear passes (one to build map, one to check). $O(N)$. |
Draw a horizontal line of numbers flowing into a table, followed by a simple pair-wise scan of that table. |
Recursive stack for subsequence generation. |
A Hash Map storing unique numbers and their counts. $O(N)$. |
| 595 |
Big Countries (SQL) |
Use a subquery for each condition (area and population) and then use a `UNION` or a `JOIN` to combine the results. |
Redundant scanning of the table. $O(N)$. |
Draw the table. Filter for Area > 3M. Then filter for Pop > 25M. Then merge the lists. |
Simple WHERE clause with OR. |
A "Dual Filter." As each row passes through the gate, it only needs to trigger one of the two sensors to be allowed through. |
`SELECT name, population, area FROM World WHERE area >= 3000000 OR population >= 25000000`. |
Draw the World table. Put a checkmark next to rows where the Area is huge OR the Population is huge. List only those checked rows. |
Single pass over the table. $O(N)$. |
Draw a table flowing into a single box with two parallel logical checks. |
$O(1)$ extra space. |
$O(1)$ auxiliary space beyond the result set. |
| 596 |
Classes More Than 5 Students (SQL) |
For every unique class, scan the entire table to count how many students are enrolled. |
Nested loop table scan. $O(N^2)$. |
Draw the Courses table. For 'Math', scan every row and tally. Repeat for 'English'. |
Group By + Having Clause. |
A "Classroom Counter." You sort all students into their respective rooms (classes) and only keep the rooms that have at least 5 people inside. |
`SELECT class FROM Courses GROUP BY class HAVING COUNT(student) >= 5`. |
Draw a set of buckets labeled by class name. Drop a "student" marble into each bucket. Count the marbles and circle the buckets with 5 or more. |
Hash-based grouping. $O(N)$. |
Draw the table flowing into a Hash Map (Class : Count) followed by a simple filter. |
$O(1)$ extra space but very inefficient. |
A Hash Map to store student counts per class. $O(\\text{text}{\text{Unique Classes}})$. |
| 597 |
Friend Requests I: Overall Acceptance Rate (SQL) |
Count every row in the Request table and every row in the Accept table, including duplicates, and divide. |
Overcounting due to re-sent or duplicate requests. $O(N)$. |
Draw two tables. Count 10 requests and 5 accepts. Get 0.50. (But what if the same person requested twice?) |
Distinct Counting + Null Handling. |
A "Unique Connection" tally. You only care about unique pairs of people. A request from A to B only counts once, no matter how many times it was sent. |
`SELECT ROUND(IFNULL(COUNT(DISTINCT requester_id, accepter_id) / COUNT(DISTINCT sender_id, send_to_id), 0), 2) AS accept_rate`. |
Draw two lists. Cross out any duplicate pairs. Count the unique pairs in the "Accept" list and divide by unique pairs in the "Request" list. Use `IFNULL` to handle the "0 requests" case. |
Linear scan with a Hash Set for duplicates. $O(N)$. |
Draw two streams flowing into two separate "Unique Sets," then a single division box. |
$O(1)$ extra space. |
Two Hash Sets to store unique pairs. $O(N)$. |
| 598 |
Range Addition II |
Initialize an M \times N matrix with zeros. For every operation [a, b], increment every cell in the a \times b sub-matrix. Finally, count the max values. |
Matrix explosion. $O(K \\text{times} M \\text{times} N)$ where K is the number of operations. |
Draw a 10 \times 10 grid. For an op [3,3], shade 9 cells. For [2,2], shade 4 cells. Count the ones shaded most. |
Minimum Boundary Tracking. |
A "Focus Area." Every operation starts from (0,0). The only cells that will be updated by *every* operation are those within the smallest width and smallest height provided. |
Maintain `min_a` and `min_b`. For each `[a, b]`: `min_a = min(min_a, a)` and `min_b = min(min_b, b)`. Result is `min_a * min_b`. |
Draw a large rectangle. Draw smaller rectangles inside it, all starting from the top-left corner. The area where all rectangles overlap is the answer. |
Single pass over the operations list. $O(K)$. |
Draw a list of operations flowing into two "Min" variables. |
A full M \times N matrix in memory. |
$O(1)$ auxiliary space. |
| 599 |
Minimum Index Sum of Two Lists |
Nested loops. For every restaurant in List 1, search the entire List 2. If found, calculate the index sum and track the minimum. |
Quadratic comparison. $O(N \\text{times} M)$. |
Draw two lists of 500 restaurants. For the first item in List A, scan all 500 items in List B. Repeat 500 times. |
Hash Map for Index Lookup. |
A "Fast-Check" Menu. You put List 1 into a digital directory (Map) so that when you look at List 2, you can instantly see if a restaurant is shared and what its "rank" (index) was. |
1. Map `List1` elements to their indices. 2. Iterate `List2`. If item in Map: `sum = i + Map[item]`. If `sum < min_sum`, clear result and add item. If `sum == min_sum`, add item. |
Draw a table: `Shogun: 0, KFC: 1, BurgerKing: 2`. Now read List 2. For each name, look at the table, add the current index, and keep track of the lowest total. |
Linear scan of both lists. $O(N + M)$. |
Draw two lists flowing into a single comparison box guided by a Map. |
$O(1)$ extra space but slow execution. |
A Hash Map storing one of the lists. $O(N)$. |
| 600 |
Non-negative Integers without Consecutive Ones |
Iterate from 0 to N, convert each number to binary, and check if it contains "11". |
Linear scan of N numbers. $O(N \log N)$. |
Draw numbers 1 to 10. Write binary: 1, 10, 11 (skip), 100, 101, 110 (skip)... count the valid ones. |
Digit DP / Fibonacci Pattern. |
A "Binary Tree of Choices." At each bit, you can choose 0 or 1, but if you chose 1 for the previous bit, you *must* choose 0 now. This follows the Fibonacci sequence. |
1. Precompute Fibonacci numbers up to 32. 2. Traverse bits of N from left to right. 3. If bit is 1, add `fib[k]` (all valid combos for this bit-length). 4. If "11" is encountered, stop and return. |
Draw a bitline: `1 0 1 0 1`. Starting from the left, if you see a '1', it means all combinations starting with '0' (for that length) are valid. Add that Fibonacci number to your total and move to the next bit. |
Logarithmic bit traversal. $O(\log N)$. |
Draw a binary tree where the "1" branch is pruned if the parent was "1". |
$O(1)$ extra space but very slow for large N. |
A small array of 32 Fibonacci numbers. $O(1)$. |
| 601 |
Human Traffic of Stadium (SQL) |
Cartesian Product / Multiple Self Joins checking all row combinations. |
3D Volume Grid (N x N x N intersections). |
Draw three overlapping circles (Venn diagram style) representing the table joined to itself thrice. Shade the tiny intersection in the middle representing valid matches. Write $O(N^3)$ next to it. |
Window Functions (id - ROW_NUMBER() grouping). |
Linear grouping timeline / Partition boxes. |
Scan rows. Only look at rows with people >= 100. Calculate (id - sequential_row_number). Rows with the same result belong to the same consecutive streak. Box streaks with count >= 3. |
Draw the table with a new column 'Diff'. Bracket rows sharing the same 'Diff' value together. Highlight brackets containing 3 or more rows. |
Single horizontal line representing a table scan with a sorting node. |
Draw a straight arrow spanning across N boxes. Add a small gear icon above it for 'Sort/Window', marking it $O(N \log N)$ for the window sorting step. |
Draw a massive grid representing a temporary table that holds all possible row combinations (Cartesian explosion). |
Draw small fixed-width boxes representing the 'current row' and 'previous row' pointers used by the SQL engine during the window function scan. |
| 602 |
Friend Requests II: Who Has the Most Friends (SQL) |
Subquery for requesters, subquery for accepters, Full Outer Join, then sum. |
Two disconnected lists mapped to a massive combined hash map. |
Draw list A and list B. Draw many tangled, crisscrossing lines connecting every ID to a central tally board. |
UNION ALL followed by GROUP BY and ORDER BY LIMIT 1. |
Data Funnel / Pipeline. |
Take 'requester_id' column, stack 'accepter_id' column directly underneath it. Group identical IDs into buckets. Count bucket sizes. Pick the biggest bucket. |
Draw two arrays vertically. Draw an arrow merging them into one long array. Draw circles around identical numbers, writing a tally count next to the circles. |
Two parallel lines merging into one, then a compression node. |
Draw two parallel arrows of length N and M joining into a single arrow (O(N+M)). Draw a funnel shape for the Group By step. |
Draw two separate memory blocks for intermediate tables, then a third larger block for the join results before aggregation. |
Draw a single stream of data flowing into a Hash Map (Key=ID, Value=Count), showing space is only proportional to unique users $O(U)$. |
| 603 |
Consecutive Available Seats (SQL) |
Cross join the cinema table with itself and check if a.seat_id = b.seat_id + 1 and both are free. |
N x N matrix grid highlighting the diagonal. |
Draw a grid. Fill the diagonal + 1 offset with checkmarks to represent matching `id + 1`. Cross out the rest of the grid. |
Self Join with absolute difference = 1 OR Window Functions (LAG/LEAD). |
Sliding Window Frame over a 1D Array. |
List all seats. Slide a 2-seat wide viewing frame down the list. If both seats in the frame are 'free' (1), color them green. |
Draw a horizontal array of 1s and 0s. Draw a bracket spanning 2 elements. Slide the bracket right. If it holds [1, 1], draw a star above it. |
Single linear scan line with a 2-step lookahead. |
Draw a single straight line. Draw small curved arrows hopping from one node to the very next node, writing $O(N)$. |
Draw a large N x N grid representing the intermediate table generated by a naive Cartesian join. |
Draw a 1D array representing the table, with two small pointer boxes (Current, Next) taking $O(1)$ auxiliary space. |
| 604 |
Design Compressed String Iterator |
Uncompress the entire string into a massive character array in memory upon initialization. |
Memory expansion chart (Small input -> Massive output block). |
Draw a short word "a10b5". Draw a diverging arrow expanding out to a massive, long array of individual characters [a,a,a...b,b]. Mark $O(\text{Total Chars})$. |
Lazy Evaluation / Two Pointers / State Machine. |
State Machine with Pointer & Counter. |
Given "L1e2t1". Pointer points to 'L', counter is 1. Call next(): return 'L', counter becomes 0. Pointer moves to 'e', reads counter 2. Call next(): return 'e', counter becomes 1. |
Write the compressed string. Draw an 'Up Arrow' under the current char. Write a floating box above it saying "Remaining: X". Erase and update X on each call. |
Step-function graph. State changes take $O(1)$, no massive pre-computation. |
Draw a simple dot with an arrow looping back to itself, labeling it $O(1)$ for next() and hasNext() operations. |
Draw a giant contiguous block of RAM boxes, completely filled with duplicate characters. |
Draw just two small variables in memory: [Char pointer_index] and [Integer current_count]. $O(1)$ space. |
| 605 |
Can Place Flowers |
Recursion/Backtracking: Try placing a flower at every valid empty spot, branch out, and check if N flowers can be placed. |
Exponential branching Tree structure. |
Draw a tree starting from an empty array. Branch left for 'Plant here', branch right for 'Skip'. The tree gets massively wide. Write $O(2^N)$. |
Greedy Algorithm / Single Pass Array Scan. |
Sliding 3-element inspection window. |
Look at [i-1, i, i+1]. If all are 0, plant a flower at i (change to 1), decrement N, and jump index by 2. If N hits 0, return true immediately. |
Draw an array [1,0,0,0,1]. Draw a sliding box covering 3 cells. If the box shows [0,0,0], cross out the middle 0, write 1, and tally N-1. |
A straight, unbroken timeline ending early. |
Draw a straight line. Put a stop-sign halfway through to signify early termination (when N=0). Write $O(N)$ max time. |
Draw a deep stack of frames representing the recursive call stack hitting depth N. |
Draw the original array in place. Draw one variable box for 'N', showing it decrementing. $O(1)$ extra space. |
| 606 |
Construct String from Binary Tree |
Standard Preorder DFS that blindly adds parentheses for every null child, followed by string replacement loops to clean up empty "()" pairs. |
A bloated tree with string manipulation loops appending to it. |
Draw a tree traversing left, right. At every empty spot, draw a heavy "()" block. Draw a big eraser scrubbing out the redundant blocks in a second pass. Write $O(N^2)$ for bad string concatenation. |
Preorder DFS with Conditional Appending. |
Recursive Call Stack with String Builder. |
Trace the tree. Add Node.val. If left child exists OR right child exists, add '('. Recurse left. Add ')'. If right child exists, add '('. Recurse right. Add ')'. |
Draw the binary tree. Trace the perimeter with a pencil. Write the number down. Only draw brackets when you dive into a subtree. Skip brackets if both children below are missing. |
Linear scan along the perimeter of the tree. |
Draw an outline wrapping around the entire binary tree structure exactly once. Write $O(N)$ along the outline. |
Draw massive, separate string blocks being created, copied, and destroyed in memory at every recursive step. |
Draw a single, expanding memory block (String Builder) and a tall, narrow stack of boxes representing $O(H)$ recursion height. |
| 607 |
Sales Person (SQL) |
Massive 3-way JOIN of SalesPerson, Company, and Orders tables, then filtering rows and selecting distinct names. |
Three overlapping huge circles (Venn Diagram) merging into one giant temporary table. |
Draw 3 separate grids. Draw thick lines blending them all into a giant 3x-wide grid. Cross out rows with "RED" and keep the rest. Mark $O(S \cdot C \cdot O)$. |
Subquery / NOT IN clause. |
Filter-First Pipeline. |
Subquery: Join Orders and Company where name='RED'. Output list of sales_id. Main query: Scan SalesPerson, if id is NOT in the subquery list, select name. |
Draw two small tables combining to output a short list of "Bad IDs". Draw the main Sales table and draw an arrow skipping any row that matches the "Bad IDs" list. |
Two separate, sequential pipelines instead of a massive cross-product. |
Draw a small funnel filtering bad IDs (O(O+C)), pointing to a simple linear scan of the SalesPerson array (O(S)). |
Draw a massive RAM block holding the intermediate joined table of all three relations before the WHERE clause filters it. |
Draw a small 1D array representing the subquery's integer list in memory, taking negligible space $O(K)$. |
| 608 |
Tree Node (SQL) |
Multiple self-joins or correlated subqueries running a COUNT() on children for every single node to determine its type. |
N separate tree-traversals happening simultaneously. |
Draw an array of nodes. From every single node, draw an arrow scanning the entire array again to count its children. Write $O(N^2)$. |
CASE WHEN with IN clause (Subquery). |
Decision Tree / Logic Gates applied per row. |
Look at a row. Is p_id NULL? It's 'Root'. Is its id present in a list of all p_ids? It's 'Inner'. Otherwise, it's 'Leaf'. |
Draw a row entering a sorting machine. Gate 1: No parent? -> Root bin. Gate 2: Has kids (check hashset)? -> Inner bin. Gate 3: Neither? -> Leaf bin. |
Single pass scan against a hashed look-up table. |
Draw a straight line for the table scan $O(N)$, intersecting with a tiny circle representing an $O(1)$ hash lookup for the `IN` clause. |
Draw multiple temporary tables spawned for each correlated subquery per row. |
Draw a single Hash Set holding all unique `p_id` values. Takes $O(N)$ space and enables instant lookups. |
| 609 |
Find Duplicate File in System |
Parse all paths into complete file strings. Compare every file's content with every other file's content using nested loops. |
N x N Matrix comparing long string blocks. |
Draw an N x N grid. In every cell, draw two long strings being compared character by character. Write $O(N^2 \cdot L)$ where L is string length. |
Hash Map grouping (Content -> List of Paths). |
Bucketing / Pigeonhole sorting. |
Read directory string. Extract filename and content. Go to hash map. If content exists, append path to the list. If not, create new bucket. Output buckets with size > 1. |
Draw several empty buckets. As you read files, look at the content. Draw lines dropping the file paths into the bucket labeled with matching content. |
Linear data flow into hash buckets. |
Draw an array of strings. Draw arrows from each string directing them into distinct buckets based on their text. Write $O(N \cdot L)$. |
Draw every file loaded into memory at once, duplicated inside temporary comparison variables. |
Draw a Hash Map. Keys are content strings, Values are arrays of path strings. Total space is bounded by $O(N \cdot L)$. |
| 610 |
Triangle Judgement (SQL) |
Heavy procedural looping or self-joins (though not practical in SQL, a conceptual brute force would be creating temporary tables for side combinations). |
Tangled logical flowchart with excessive branches. |
Draw a row. Draw three separate branching paths checking one condition each, merging back slowly. |
Simple conditional logic: IF or CASE WHEN. |
Single-pass logical gate check. |
Read row (x, y, z). Evaluate math condition: x+y>z AND x+z>y AND y+z>x. If true, append 'Yes', else 'No'. |
Draw a triangle. Label sides x, y, z. Write the triangle inequality theorem formula. Put a big checkmark or X next to the row. |
Straight, unbroken horizontal line (O(N) full table scan). |
Draw a straight arrow representing a single table scan. Place a tiny lightning bolt above it to represent $O(1)$ math logic per row. |
Draw unnecessary temporary tables holding partial boolean results. |
Draw a single stream of rows with a single new column attached directly in memory. $O(1)$ extra space per row. |
| 611 |
Valid Triangle Number |
Three nested loops picking every possible combination of 3 sides and checking x + y > z. |
3D volumetric grid of combinations (N x N x N). |
Draw an array. Point three fingers at indices 0, 1, and 2. Vigorously slide the third finger to the end, then move the second, repeating for every combination. Write $O(N^3)$. |
Sort + Two Pointers. |
Anchored Right Boundary with Squeezing Left/Mid Pointers. |
Sort array. Anchor 'k' at the very end. Place 'i' at start, 'j' at k-1. If arr[i]+arr[j] > arr[k], then ALL elements between i and j form valid triangles with j and k. Tally (j-i), move j left. Else move i right. |
Draw sorted array. Box the last element (Target). Place 'L' at start and 'R' right before Target. If L+R > Target, draw a sweeping arc from L to R showing all are valid. |
$O(N \log N)$ sorting phase + $O(N^2)$ two-pointer convergence. |
Draw a funnel representing sorting, followed by a wide square (O(N^2)) representing the two pointers sliding inward across N anchored positions. |
Draw a massive hypothetical list storing every evaluated triplet in memory. |
Draw the array modified in place (sorting space $O(1)$ to $O(\log N)$), with just three integer variables: i, j, k. |
| 612 |
Shortest Distance in a Plane (SQL) |
Unrestricted Cartesian Join (Cross Join) calculating the distance formula between every single point and every other point twice. |
Fully connected web (Every node connects to every node). |
Draw 5 dots scattered on paper. Draw a line from every single dot to every other dot, including lines bouncing back to themselves. Write $O(N^2)$. |
Cross Join with Duplicate Filtering (Upper Triangular Check). |
Directed Acyclic Graph / Triangle Matrix. |
Join table p1 and p2. Filter: `p1.x < p2.x OR (p1.x = p2.x AND p1.y < p2.y)`. This ensures we compare Point A to Point B, but strictly skip comparing Point B to Point A. Apply distance math, find MIN. |
Draw points on a grid. Only draw arrows going from left to right (or bottom to top for ties). Never draw an arrow going backward. |
$O(N^2 / 2)$ which simplifies to $O(N^2)$ but with half the constant factor. |
Draw an N x N grid. Cross out the bottom-left diagonal half completely, leaving only the top-right triangle of pairs to evaluate. |
Draw a massive temporary table of size N * N held in memory. |
Draw a half-sized temporary table, though practically SQL handles this via streaming row evaluations $O(1)$ space. |
| 613 |
Shortest Distance in a Line (SQL) |
Cross join comparing the absolute difference between every single coordinate on the number line. |
Matrix grid of absolute differences. |
Draw points randomly on a number line. Draw long, overlapping arcs connecting the far-left point to the far-right point and everything in between. |
Sorting / Window Functions (LEAD/LAG). |
Sorted Number Line with Adjacent Hops. |
Sort the table by 'x' value. Use LEAD(x) to look at the very next row. Subtract current x from next x. Keep the minimum difference across the table. |
Draw points sorted strictly left-to-right on a line. Draw tiny, discrete "hop" arrows strictly between immediate neighbors. Note the smallest hop. |
Linear scan after an $O(N \log N)$ sort operation. |
Draw a quick gear icon for 'Sort', followed by a straight, single-pass line with small hop increments $O(N)$. |
Draw a Cartesian explosion N x N table in RAM. |
Draw a single column of sorted data with a 2-row sliding window frame. |
| 614 |
Second Degree Follower (SQL) |
Correlated subqueries: for every followee, run a new independent query to see if they are also a follower, then count again. |
Fractal branching tree with redundant lookups. |
Draw a "User A". Draw arrows to 5 followers. For each follower, draw a separate lookup bubble verifying their status. Write $O(N^2)$ lookups. |
Inner Join or Group By with IN clause. |
Set Intersection & Aggregation. |
Isolate unique people who are followers. Filter the `followee` column to only include people from that unique list. Group by the remaining followees and COUNT their followers. |
Draw two lists: "Followees" and "Followers". Draw straight lines connecting matching names between the two lists. Group the connected names and tally them. |
Two linear passes passing through an $O(1)$ hash map/intersection. |
Draw two parallel data streams feeding into a single Venn Diagram intersection, merging into a count $O(N)$. |
Draw a deep stack of temporary tables spawned per row. |
Draw a single Hash Set in memory containing valid "follower" names, scaling at $O(U)$ unique users. |
| 615 |
Average Salary: Departments VS Company (SQL) |
Calculate the company average for the month, store it. Calculate the department average for the month, store it. Join them back to the original rows via subqueries. |
Looping back and forth between global tallies and local tallies. |
Draw a big circle (Company), then a small circle (Dept). Draw an arrow bringing data to the big circle, then taking it to the small circle, then back to the output row. |
Window Functions (AVG OVER PARTITION). |
Parallel Timelines / Matrix Columns. |
Use `AVG(amount) OVER (PARTITION BY pay_date)` for company avg. Use `AVG(amount) OVER (PARTITION BY pay_date, department_id)` for dept avg. Compare the two columns directly using a CASE statement. |
Draw a wide table. Fill a 'Company Avg' column with the exact same number all the way down. Fill a 'Dept Avg' column with numbers clustered by dept. Draw a `< > =` symbol between them. |
Simultaneous linear sweeps using partition bounds. |
Draw two straight lines running parallel downwards. One has markers every month, the other has markers every month+dept. Both finish in $O(N \log N)$ time. |
Draw three huge separate tables: Raw Data, Company Aggregates, and Dept Aggregates, taking up 3x space. |
Draw the original table with two extra 'virtual' columns streamed in place using $O(N)$ sort/window memory. |
| 616 |
Add Bold Tag in String |
For every index in S, check every word in the dictionary. If it matches, insert <b> and </b> immediately. Then use Regex to merge overlapping tags. |
Staggered, overlapping intervals with heavy string slicing. |
Draw a sentence. Draw 10 small "brackets" overlapping each other messily. Draw an eraser trying to fix the overlaps. $O(S \\text{cdot Words} \\text{cdot WordLen})$. |
Boolean Mask + Interval Merging. |
1D Binary Ribbon / Bitmask. |
Create a boolean array `bold` of same length as S. For each word in dict, find all occurrences in S and mark `bold[i...j]` as True. Finally, traverse S: if `bold[i]` starts being True, add <b>; when it turns False, add </b>. |
Draw the string. Underneath it, draw a row of empty checkboxes. Fill checkboxes with 'X' where words match. Draw one big box around consecutive 'X's. |
Linear scan of string after pre-marking. |
Draw a straight line for the string scan. Above it, draw a parallel "Mask" line. Mark $O(S \cdot Σ\text{Words})$ or $O(S \cdot L)$ with Aho-Corasick. |
Draw dozens of temporary string copies created during constant concatenation and slicing. |
Draw one boolean array of size N and one StringBuilder/List for the final output. $O(N)$. |
| 617 |
Merge Two Binary Trees |
Create a completely new third tree by traversing both trees simultaneously and copying values. |
Two source trees pointing to a third growing tree. |
Draw Tree A and Tree B. Draw a large empty space where you redraw every single node again from scratch. $O(N+M)$. |
Recursive In-Place Merge. |
Overlapping Transparency / Layer Merging. |
Imagine Tree A is on a transparency sheet. Lay it over Tree B. If nodes overlap, sum them. If only one exists, keep that branch. Update Tree A's pointers directly. |
Draw Tree A and Tree B. Use a red pen to write Tree B's values into Tree A's nodes. Draw arrows from Tree A to Tree B's "dangling" branches. |
Single traversal of the smaller/overlapping structure. |
Draw two trees with a single "Scanner" line moving through both in sync. $O(\text{min}(N, M)$). |
Draw a full set of new nodes in memory for the third tree, doubling the space requirement. |
Draw Tree A's existing nodes being updated. Memory only used for the recursion stack $O(\text{height})$. |
| 618 |
Students Report By Geography (SQL) |
Multiple self-joins on the Student table for each continent, attempting to align them by a dummy row index. |
Sparse, disconnected tables trying to "snap" together. |
Draw three vertical lists of different lengths. Try drawing horizontal lines to connect them, leaving massive gaps. |
Window Function (ROW_NUMBER) + Pivot (CASE WHEN). |
Categorical Bucket Alignment. |
Assign a row number to each student *within* their continent. Use the row number as the "Y-axis" and Continent as "X-axis". Group by row number and pick student name based on continent. |
Draw a grid. Label columns: America, Asia, Europe. Label rows: 1, 2, 3. Place names in cells like a game of Bingo. |
Sort-based partitioning followed by a single aggregation pass. |
Draw a funnel (sorting by continent/name) followed by a horizontal "stacking" motion into columns. $O(N \log N)$. |
Draw massive intermediate JOIN tables filled with NULLs. |
Draw a single sorted list being streamed into a 2D result buffer. |
| 619 |
Biggest Single Number (SQL) |
Select all numbers, sort them descending, then loop through to check if `count == 1`. |
Full sort followed by a conditional scan. |
Draw a long list of numbers. Sort them. Scan with a pointer, looking back and forward to see if the neighbor is the same. |
Subquery Grouping with HAVING count = 1. |
Bucket Filter & Max. |
Group all numbers. Throw away any bucket with more than one item. From the remaining buckets, pick the one with the highest label. |
Draw several buckets with numbers. Cross out any bucket containing >1 ball. Look at the remaining buckets and circle the largest number. |
Hash aggregation followed by a Scalar Max. |
Draw a parallel set of buckets (Hash Map). Mark it $O(N)$. Draw one final arrow to the MAX value. |
Draw a fully sorted copy of the table in memory. |
Draw a Hash Table (Number -> Count). If using an index, space is $O(1)$ extra beyond the result. |
| 620 |
Not Boring Movies (SQL) |
Fetch all rows, then use a programming loop to check `id % 2 != 0` and `description != 'boring'`, then sort. |
Entire table loaded into an application-level filter. |
Draw a giant table. Draw a "filter" box outside the database. Move all rows into the box, then discard half. |
Direct SQL WHERE Clause + ORDER BY. |
Indexing / Predicate Pushdown. |
The database engine scans the index. It immediately skips even IDs and rows with the 'boring' string at the storage level. Sorts the result. |
Draw a table. Put a "Filter" mask over it that only lets "Odd" and "Not Boring" rows through. Draw an arrow pointing to the "Rating" column for sorting. |
Scan (O(N)) + Sort (O(K log K)) where K is filtered result count. |
Draw a narrowing pipe. Most data is blocked at the start (O(N)), only a few rows reach the Sort stage. |
Draw a full application-side array holding all table data. |
Draw a single stream of rows being filtered on-the-fly, requiring minimal buffer space. |
| 621 |
Task Scheduler |
Simulate every single unit of time. Maintain a list of tasks and their cooldowns. At each second, pick the task with the highest frequency that isn't on cooldown. |
Timeline with many "Idle" gaps and repeated frequency scans. |
Draw a horizontal line. For every tick, draw a vertical line and search your "Task List" to see which is ready. Write $O(\text{TotalTime} \cdot 26)$. |
Greedy (Math-based Calculation). |
Box Filling / Slot Allocation. |
Find the max frequency (f). Create (f-1) groups. Each group has size (n+1). Total slots = (f-1)*(n+1) + number of tasks with max frequency. If result < tasks.length, return tasks.length. |
Draw a grid with (f-1) rows and (n+1) columns. Fill the first column with the most frequent task. Count the remaining empty cells. See if other tasks can fit. |
Single pass to count frequencies. |
Draw a frequency bar chart (A:3, B:3). Circle the max bars. Write $O(N)$ where N is number of tasks. |
Draw a list of all tasks plus a "cooldown" status for each task being tracked in real-time. |
Draw a small fixed-size array/map of size 26 to store counts. $O(1)$ auxiliary space. |
| 622 |
Design Circular Queue |
Use a standard Dynamic Array (like ArrayList). On every `deQueue`, shift every single remaining element one position to the left. |
Continuous "Slinky" motion where the whole array moves left. |
Draw an array [1, 2, 3]. Cross out 1. Draw arrows moving 2 and 3 into the slots 0 and 1. Write $O(N)$ per dequeue. |
Two-Pointer Array with Modulo Arithmetic. |
A clock face or a ring. |
Maintain `head` and `tail` pointers. When adding, `tail = (tail + 1) % size`. When removing, `head = (head + 1) % size`. Pointers just chase each other in a circle. |
Draw a circle with 5 slots. Place an 'H' (Head) and 'T' (Tail) pointer. Move them clockwise. Show how 'T' can wrap around behind 'H'. |
Constant time jumps for all operations. |
Draw a dot (operation) connecting directly to a slot without any scanning. Write $O(1)$. |
Draw a memory block that frequently resizes and re-copies data during shifts. |
Draw one fixed-size array of size K. No resizing, no moving data. |
| 623 |
Add One Row to Tree |
BFS to find all nodes at depth `d-1`. Store them in a list. Then iterate through the list to insert new nodes. |
Layer-by-layer scanning with a storage buffer. |
Draw a tree. Draw a circle around every node in a specific row. Draw a secondary "list" holding those nodes before acting. $O(N)$. |
Recursive DFS with Depth Tracking. |
Plugging a "Connector" into a socket. |
Pass `current_depth` in recursion. When `current_depth == d-1`, create new nodes, hook them to current children, and re-attach. Base case: `d=1` (special root case). |
Draw a tree. Trace a path down. At the target depth, draw two "interceptors" (the new nodes) and reroute the existing arrows through them. |
Direct tree traversal without auxiliary lists. |
Draw a single line snaking through the tree until it hits the "Depth Horizon." Write $O(N)$. |
Draw a Queue or List holding an entire level of the tree in memory. |
Draw the recursion stack. Space is $O(\text{Height})$ of the tree. |
| 624 |
Maximum Distance in Arrays |
Compare every element of every array with every element of every other array. |
Complete bipartite matching of all possible pairs. |
Draw 3 arrays. Draw lines from every number in Array 1 to every number in Array 2 and 3. Write $O(\text{Total}_\text{Elements}^2)$. |
Greedy Min/Max Tracking. |
Running Goalposts. |
Initialize `globalMin` and `globalMax` with the first array's ends. For each subsequent array: calc `abs(currMax - globalMin)` and `abs(globalMax - currMin)`. Update global values. |
Draw two horizontal lines (Min and Max bounds). For each new array, draw its "range bar" and see how much it stretches the existing bounds. |
Single pass through the list of arrays. |
Draw a horizontal arrow scanning across the "Arrays" list. Write $O(M)$ where M is the number of arrays. |
Draw a giant matrix storing all comparison results. |
Draw two integer variables: `min_val` and `max_val`. $O(1)$ space. |
| 625 |
Minimum Factorization |
Backtracking/Recursion to find every possible combination of factors that multiply to A, then find the smallest number among them. |
Massive multi-way branching factor tree. |
Draw number A. Branch out into every possible divisor (2 through 9). Branch again. It becomes an unmanageable explosion. |
Greedy Factorization (Divisors 9 down to 2). |
Reverse Digit Assembly. |
Try to divide A by 9, then 8... down to 2. Append the successful divisor to a result string. Since we want the *smallest* number, we use the largest divisors first and then reverse the string. |
Write the number A. Divide by 9 as many times as possible. Write the 9s at the end of your "Number-to-be". Move to 8, then 7. Read the digits from right to left. |
Linear scan of digits 9-2 per reduction step. |
Draw a countdown from 9 to 2. Write $O(\log A)$ because the number A shrinks exponentially. |
Draw a massive recursion tree in memory with many duplicate states. |
Draw a single string or long variable to store the digits. $O(1)$ relative to input magnitude. |
| 626 |
Exchange Seats (SQL) |
Self-join the table on `a.id = b.id + 1` and `a.id = b.id - 1`, then use UNION to combine odd/even results. |
Two separate result sets colliding and merging. |
Draw two copies of the table. Cross-link them with messy, diagonal arrows. Draw a big plus sign (+) for the UNION. $O(N)$. |
Bitwise Logic / CASE statement with ID manipulation. |
Index Shifting / Mathematical Remapping. |
If ID is odd and not last: ID+1. If ID is even: ID-1. Else (last odd): ID. The data doesn't move; only the "Label" changes. |
Draw a column of numbers [1, 2, 3, 4]. Draw arrows swapping only the numbers, while keeping the student names fixed in place. |
Single-pass table scan. |
Draw a straight arrow through the table. Above it, write the formula `(id-1)^1 + 1`. Write $O(N)$. |
Draw two full intermediate tables in memory for the JOIN and UNION operations. |
Draw the original table with a virtual "New ID" column. $O(1)$ extra space. |
| 627 |
Swap Sex of Employees |
Pulling all data into the app layer, iterating with an if/else, and running individual UPDATE statements for every row. |
Sequential Update Loop $O(N)$ |
Draw the table. For every row, draw a round-trip arrow to the database running a separate UPDATE query. |
SQL UPDATE + CASE WHEN |
The Inline Switcher |
Use `UPDATE table SET sex = CASE WHEN sex = 'm' THEN 'f' ELSE 'm' END`. The DB engine applies this to all rows internally. |
Draw the table column. Draw a "Flipper" mechanism that runs down the column, toggling M to F and F to M in a single continuous motion. |
Single Internal Pass $O(N)$ |
Draw a single, solid arrow moving through the table. |
App-side memory overhead. |
DB internal transaction buffer. $O(1)$ auxiliary space. |
| 628 |
Maximum Product of Three Numbers |
Three nested loops to find the product of every possible triplet in the array. |
3D Volume Grid (N x N x N). |
Draw an array. Point to 3 different numbers. Show how many combinations exist by drawing a dense cube of dots. $O(N^3)$. |
Sort OR Linear Scan for Top 3 and Bottom 2. |
Extreme Bound Tracking. |
Find 3 largest numbers and 2 smallest (most negative). Max product is either (Max1*Max2*Max3) or (Max1*Min1*Min2). |
Draw a horizontal line. Mark 3 dots at the far right and 2 dots at the far left. Draw two "product" bubbles comparing the results. |
$O(N \log N)$ for sorting or $O(N)$ for single-pass scan. |
Draw a scanner moving across the array once. Write "Min1, Min2, Max1, Max2, Max3" above it. $O(N)$. |
Draw a massive list of all calculated products. |
Draw exactly five integer variables. $O(1)$ space. |
| 629 |
K Inverse Pairs Array |
Generate all permutations of numbers 1 to N. For each permutation, count inverse pairs and check if they equal K. |
Explosive Permutation Tree (N!). |
Draw the number 1. Branch to (1,2) and (2,1). Branch again for 3. The tree becomes a chaotic mess of N! nodes. $O(N! \cdot N)$. |
DP with Sliding Window Sum. |
2D Grid Filling with Prefix Sum Optimization. |
`dp[i][j]` is the number of ways to arrange `i` numbers with `j` inverse pairs. Use the result of `dp[i-1]` to calculate `dp[i]` by adding a range of values (Sliding Window). |
Draw an N x K grid. To fill a cell, draw a bracket over a segment of the row above it. Slide the bracket to fill the next cell. |
$O(N \cdot K)$ time. |
Draw a grid and an arrow filling it row by row, with a small "Window" moving along each row. $O(\text{NK})$. |
Draw an N x K 2D array. |
Draw two rows of length K (Current and Previous). Space reduces to $O(K)$. |
| 630 |
Course Schedule III |
Try every possible subset of courses. For each subset, try all permutations to see if they can be completed by their deadlines. |
Exponential Subsets + Permutations (2^N * N!). |
Draw a list of courses. Draw a tree where every level is a choice to "take" or "skip". It's a massive, infinite-looking forest. |
Greedy with Max-Priority Queue. |
Timeline Displacement / "Regret" Strategy. |
Sort courses by deadline. Add courses to a timeline. If a course exceeds its deadline, look back at all courses taken so far. Remove the longest course (Priority Queue) to make room. |
Draw a timeline. Add blocks. When a block goes past the "Deadline" line, find the fattest block already on the timeline and throw it out. |
$O(N \log N)$ for sorting and heap operations. |
Draw a sorted list feeding into a small box (Heap). Write $O(N \log N)$. |
Draw all possible course sequences being stored in a recursion stack. |
Draw a single Priority Queue (Heap) containing at most N course durations. $O(N)$. |
| 631 |
Design Excel Sum Formula |
Recursive re-calculation: Every time a cell's value is requested, traverse all its dependencies and sum them up from scratch. |
Deep, redundant Dependency Tree. |
Draw cell A1. Draw arrows to B1, B2. From B1, draw arrows to C1, C2. Show the same cell being visited 100 times. Write $O(\text{Branching}^\text{Depth})$. |
Directed Acyclic Graph (DAG) with Topological Updates. |
Observer Pattern / Reactive Graph. |
When a cell value changes, only notify the cells that directly depend on it. Use a map to store "who depends on me" and "what do I depend on". Update values only when needed. |
Draw a node. Draw outgoing arrows to its "Parents" (formulas using it). When the node changes, follow the arrows and update parent values. |
Amortized updates based on graph edges. |
Draw a web where a single "Pulse" (update) travels along specific lines rather than flooding the whole system. $O(\text{Edges})$. |
Draw no storage—just massive overhead on the CPU stack during every `get` call. |
Draw a Hash Map where keys are cells and values are a list of dependent cell coordinates. $O(\text{Cells} + \text{Formulas})$. |
| 632 |
Smallest Range Covering Elements from K Lists |
Generate every possible range [min, max] using all numbers in all lists and check if it contains at least one number from each list. |
N x N Matrix of possible range boundaries. |
Draw a massive number line. Draw a bracket for every single possible pair of numbers. Check each bracket. $O(N^3)$. |
Sliding Window with Min-Heap. |
K-Way Pointer Convergence. |
Put the first element of each list into a Min-Heap. The range is [heap.min, max_of_elements_in_heap]. Pop the min, add the next element from that specific list, and update the range. |
Draw K parallel tracks. Put a "runner" (pointer) on each. Draw a box spanning from the furthest left runner to the furthest right. Move the slowest runner forward. |
$O(N \log K)$ where N is total elements. |
Draw a funnel (Heap) processing elements from K sources. Write $O(N \log K)$. |
Draw a list of all possible ranges being stored before sorting. |
Draw a Heap of size K and a few variables for `minRange`. $O(K)$ space. |
| 633 |
Sum of Square Numbers |
Two nested loops checking all combinations of `a` and `b` from 0 to `sqrt(c)` such that `a^2 + b^2 = c`. |
2D Coordinate Grid Search. |
Draw a square of dots. Check every dot to see if it lands on a circle of radius `sqrt(c)`. $O(C)$. |
Two Pointers or Fermat's Theorem. |
Binary Search Range Squeeze. |
Set `left = 0`, `right = sqrt(c)`. If `left^2 + right^2 < c`, increment left. If `> c`, decrement right. If `== c`, return true. |
Draw a horizontal line from 0 to `sqrt(c)`. Place fingers at both ends. Move them toward each other based on the sum of their squares. |
$O(\text{sqrt}(C)$) time. |
Draw a single line of length sqrt(C) with two pointers meeting in the middle. Write $O(\text{sqrt}(C)$). |
Draw a 2D table of all squares pre-calculated. |
Draw zero extra data structures. $O(1)$ space. |
| 634 |
Find the Derangement of An Array |
Generate all N! permutations and check each one to see if `A[i] == i` for any element. |
Factorial Permutation Tree. |
Draw [1, 2, 3]. List every shuffle. Cross out any where a number is in its original spot. $O(N! \cdot N)$. |
Dynamic Programming (Subproblem relation). |
Recursive Build-up with State Transition. |
A derangement of `n` elements can be formed from `n-1` or `n-2` elements. Formula: `D(n) = (n-1) * (D(n-1) + D(n-2))`. |
Draw a box for n=1, then n=2, then n=3. Show how the previous two boxes are used to calculate the current one with a simple multiplier. |
Linear iterative calculation. |
Draw a straight line of N steps. Each step only looks at the two previous steps. $O(N)$. |
Draw a recursion tree with N! nodes. |
Draw just two variables, `prev1` and `prev2`, to store the last two results. $O(1)$ space. |
| 635 |
Log Storage System |
Store all logs in a simple list. For every `retrieve` call, iterate through the entire list, parse the timestamps, and check if they fall in the range. |
Full scan per query. |
Draw a pile of logs. For every question, search the whole pile. Write $O(N \cdot Q)$. |
Ordered Map / TreeMap with Granularity Masking. |
Sorted Timeline with Range Query. |
Convert timestamps to a standardized string format based on the given granularity (e.g., Year: "2017:00:00..."). Use a sorted map to find all logs between the start and end keys. |
Draw a timeline. Mark logs on it. When a range is requested, draw two vertical bars and take everything in between. |
$O(\log N)$ for search + $O(K)$ for results. |
Draw a balanced tree (BST). Highlight a specific subtree within the range. Write $O(\log N)$. |
Draw the list as is. |
Draw a TreeMap or SkipList storing strings. $O(N)$ space. |
| 636 |
Exclusive Time of Functions |
Create a massive array of size `Max_Timestamp`. For every second, simulate which function is currently running by processing logs. |
High-resolution timeline expansion. |
Draw a line with 10,000 tick marks. Color each segment according to the function ID. Write $O(\text{Total}_\text{Duration})$. |
Stack-based Interval Calculation. |
Nested Activity Blocks (Gantt Chart style). |
Push `functionID` and `startTime` onto a stack. When an 'end' log comes, pop the stack, calculate duration, and subtract it from the previous function's "exclusive" time. |
Draw a vertical stack. Push a box "F0" at time 0. Push "F1" at time 2. On "F1 end", pop and write duration into F1's tally. |
Single pass through the logs $O(N)$. |
Draw a straight arrow spanning N log entries. Write $O(N)$. |
Draw a massive array whose length depends on the timestamps (O(T)). |
Draw a stack that only grows as deep as the nesting of function calls (O(N/2)). |
| 637 |
Average of Levels in Binary Tree |
DFS to visit every node, storing values in a Map where Key=Level and Value=List of nodes. Then iterate the map to calculate averages. |
Scattered data collection into a growing buffer. |
Draw a tree. Draw arrows from every node to a side-table. Write $O(N)$ to visit + $O(N)$ to store. |
BFS (Level Order Traversal). |
Layered Wavefront / Scanline. |
Use a Queue. While Queue is not empty, get current size (nodes in current level). Sum them up, divide by count, and move to next level. |
Draw a tree. Draw horizontal "water levels" cutting through it. Write the average value on each line. |
Single pass linear traversal. |
Draw a vertical arrow pointing down, crossing horizontal level lines. Write $O(N)$. |
Draw a Map containing every single node value organized by key. |
Draw a Queue that at most holds the width of the tree (O(W)). |
| 638 |
Shopping Offers |
Recursion without Memoization: Try every possible offer and every possible individual item purchase in a nested fashion. |
Deep, redundant decision tree. |
Draw the "Needs" vector. Branch out for Offer 1, Offer 2, and Single Items. Each branch creates a new "Needs" vector. $O(\text{Offers}^\text{Items})$. |
Backtracking with Memoization (DFS + Map). |
State-Space Pruning with Cached results. |
Pass the current "Needs" vector to a function. Check if this exact vector has been calculated before in a Map. If not, try all valid offers and cache the minimum cost. |
Draw a "Needs" box. Draw arrows to sub-boxes. If a sub-box is identical to one seen before, draw a dashed line back to the cached result instead of expanding. |
$O(N \cdot M^N)$ where N is items and M is needs, but heavily pruned. |
Draw a tree where many branches "snap" back to a central table of results. |
Draw the entire call stack hitting massive depths without reuse. |
Draw a Hash Map storing "Needs String" -> "Min Price". |
| 639 |
Decode Ways II |
Recursion without memoization to explore every possible 1-digit or 2-digit interpretation, especially with '*' (wildcards). |
Massive branching tree (up to 15 branches per '*' node). |
Draw '2*'. Branch for 2,1; 2,2... 2,9 and then the 2-digit cases like 21, 22... Write $O(2^N)$. |
Iterative Dynamic Programming (1D). |
Weighted Path Tally. |
`dp[i]` is ways to decode first `i` chars. Calculate based on `dp[i-1]` (1-char) and `dp[i-2]` (2-char). For '*', multiply by 9 or the specific number of 2-digit combos possible. |
Draw a row of numbers. Under each index, write the "Total Ways" so far. Draw arrows from `i-1` and `i-2` merging into `i`. |
Single pass $O(N)$. |
Draw a straight line with two "look-back" arrows at every step. Write $O(N)$. |
Draw an exponential tree structure in memory. |
Draw just three variables: `current`, `prev`, and `prev_prev`. $O(1)$ space. |
| 640 |
Solve the Equation |
Brute force checking every possible value of 'x' (from -infinity to infinity) to see which one makes the equation balanced. |
Infinite or very large range linear search. |
Draw a number line. Draw a pointer moving through every single integer. Write $O(\text{Range})$. |
Linear Expression Reduction (Parsing). |
Balance Scale Simplification. |
Split string by '='. For each side, parse terms. Sum coefficients of 'x' into `total_x` and constants into `total_val`. Subtract right side from left. Result is `x = -total_val / total_x`. |
Draw a balance scale. Move all 'x' terms to the left and all numbers to the right. Cross them out as you "move" them. |
Linear scan of the string $O(N)$. |
Draw a scanner moving across the string once, sorting terms into two "bins": X-bin and Num-bin. Write $O(N)$. |
Draw a list of all possible 'x' values being tested. |
Draw two integer variables for each side: `coeff` and `const`. $O(N)$ for string splitting. |
| 641 |
Design Circular Deque |
Using a dynamic list/array where `insertFront` and `deleteFront` trigger a full `O(N)` shift of all elements. |
Repetitive shifting "domino effect." |
Draw an array. Add a number at index 0. Draw arrows for every subsequent number moving one spot right. $O(N)$. |
Circular Buffer / Fixed-size Array with Head/Tail Pointers. |
Endless Loop / Ring Road. |
Maintain `front` and `rear` pointers. `front = (front - 1 + k) % k` for inserting at front. `rear = (rear + 1) % k` for inserting at back. Space is always full when `(rear + 1) % k == front`. |
Draw a circle divided into K segments. Draw 'F' and 'R' arrows. Move 'F' counter-clockwise and 'R' clockwise. Show how they never "cross" unless the buffer is empty. |
Constant time jumps for all operations. |
Draw a single dot for each action (Insert/Delete). Label it $O(1)$. |
Draw a memory block that resizes and shifts data constantly. |
Draw a static array block of size K. No movement of data, only movement of pointers. |
| 642 |
Design Search Autocomplete System |
Store all sentences in a list. Every time a user types a character, search the entire list using `startsWith()`, sort the matches by frequency, and return top 3. |
Full-text search on every keystroke. |
Draw a massive stack of papers. For every letter typed, flip through every page. Write $O(\text{Keystrokes} \cdot N \\text{cdot WordLen})$. |
Trie (Prefix Tree) + Min-Heap/Caching. |
Branching Path / Predictive Pathing. |
Traverse the Trie based on the prefix. Each node in the Trie can store a map of "Top 3 sentences" starting from this node. Update frequencies in the Trie when a sentence is finished. |
Draw a tree where each node is a letter. At each node, draw a small "sticky note" with the top 3 most frequent words under that branch. |
$O(\text{Keystrokes} \\text{cdot MaxWordLen})$. |
Draw a single path down a tree. Write $O(L)$ where L is length of prefix. |
Draw a flat list containing millions of redundant strings. |
Draw a Trie structure. Common prefixes share nodes. Space is $O(\text{Total unique characters in all sentences})$. |
| 643 |
Maximum Average Subarray I |
Nested loops: For every index `i`, calculate the sum of the next `k` elements, then find the max. |
Overlapping "Searchlight" scans. |
Draw an array. Draw a bracket of length K. Move the bracket one step. Re-calculate everything inside the bracket. $O(N \cdot K)$. |
Sliding Window (Fixed Size). |
Rolling Sum / Ribbon Slide. |
Calculate sum of first `k` elements. To move the window, subtract the element leaving the window and add the new element entering. Update `maxSum` if current sum is higher. |
Draw an array. Draw a bracket. Draw an arrow "ejecting" the leftmost number and an arrow "injecting" the rightmost number. |
Single pass linear scan. |
Draw a straight arrow spanning N. Write $O(N)$. |
Draw many temporary "sum" variables created and discarded. |
Draw one `currentSum` variable and one `maxSum` variable. $O(1)$ space. |
| 644 |
Maximum Average Subarray II |
Calculate every possible subarray of length `L >= k`, compute its average, and track the maximum. |
Explosive growth of subarray combinations. |
Draw an array. Draw brackets of length K, then K+1, up to N. For each, calculate average. Write $O(N^2)$. |
Binary Search on Answer + Sliding Window. |
Refining Range / Precision Converge. |
Binary search for the *value* of the average between `min_val` and `max_val`. For a mid-value, check if any subarray of length >= K has an average >= mid using a linear scan. |
Draw a number line of possible averages. Draw a "Check" box. If the check passes, discard the left half of the number line. Repeat. |
$O(N \cdot \log((\text{max}-\text{min})$/precision)). |
Draw a line (N) inside a loop that halves the search space (log). Write $O(N \log V)$. |
Draw a 2D matrix storing all subarray averages. |
Draw a single pass check. Space is $O(1)$ beyond the input array. |
| 645 |
Set Mismatch |
Sort the array and scan for duplicates and missing numbers. Alternatively, use a Hash Map to count frequencies. |
Sorting overhead or auxiliary storage mapping. |
Draw a list. Sort it. Scan for a number that equals its neighbor. Write $O(N \log N)$. |
Index-as-Hash / Negation Marker. |
In-place Checkmarks. |
Iterate through the array. For value `x`, go to `arr[abs(x)-1]`. If it's already negative, `x` is the duplicate. If not, make it negative. Finally, the only index with a positive value is the missing number. |
Draw an array. When you see '2', put a "tick" (negative sign) on the box at index 1. If you try to tick a box that already has one, you found your double. |
Linear scan, $O(N)$. |
Draw a straight line through the array. Write $O(N)$. |
Draw a Hash Map or a sorted copy of the array (O(N)). |
Draw the array being modified in-place. $O(1)$ extra space. |
| 646 |
Maximum Length of Pair Chain |
Recursion/Backtracking: For every pair, try either including it in the chain or skipping it, checking validity at each step. |
Exponential decision tree branches. |
Draw a list of pairs. Branch for "Take" and "Skip" for every pair. The tree explodes. Write $O(2^N)$. |
Greedy (Sort by End Time). |
Interval Scheduling / Timeline Stacking. |
Sort pairs by their second element. Pick the first pair. For every subsequent pair, if its start > the end of the last picked pair, add it to the chain. |
Draw a timeline. Place pairs as intervals. Always pick the interval that "finishes" earliest to leave the most room for others. |
$O(N \log N)$ for sorting, $O(N)$ for the scan. |
Draw a funnel (sort) followed by a straight line with "Check" marks. Write $O(N \log N)$. |
Draw a massive recursion stack. |
Draw the sorted array and one "Current End" variable. $O(1)$ extra space. |
| 647 |
Palindromic Substrings |
Generate every possible substring (N^2) and check if each is a palindrome (N). |
Nested scan volume (N x N x N). |
Draw a grid. For every cell (i, j), draw a mini-loop that checks if the characters match inwards. $O(N^3)$. |
Expand Around Center. |
Outward Ripples / Flashlight expansion. |
Iterate through each character (and each gap between characters). Treat it as a center and expand outwards as long as characters match. Each success is a count. |
Draw a string. Put a needle on a letter. Draw arrows pointing left and right simultaneously. Count how many steps you can take. |
Linear scan with local expansions. |
Draw a straight line with "V" shapes expanding from every point. Write $O(N^2)$. |
Draw a list storing all substring copies. |
Draw zero extra storage. $O(1)$ space. |
| 648 |
Replace Words |
For every word in the sentence, check every root in the dictionary to see if the word starts with that root. Pick the shortest root. |
Double nested comparison (Sentence Words x Dict Roots). |
Draw a sentence word. Draw a list of roots next to it. Draw lines comparing prefixes for every pair. $O(N \cdot M \cdot L)$. |
Trie (Prefix Tree). |
Tree Path Truncation. |
Insert all dictionary roots into a Trie. For each word in the sentence, walk down the Trie. If you hit a "Leaf" (end of root), replace the word with that path. |
Draw a letter tree. Walk down the tree using letters from the word. As soon as you hit a "Root" marker, stop and chop the word. |
$O(\text{Total characters in sentence} + \text{Total characters in dictionary})$. |
Draw a tree traversal path for each word. Write $O(N + M)$. |
Draw a redundant list of roots. |
Draw a Trie where common prefixes are merged. $O(\text{Dictionary Size})$. |
| 649 |
Dota2 Senate |
Repeatedly scan the string, marking "banned" senators, until only one party remains. Use a boolean array for "active" status. |
Circular multi-pass scan. |
Draw a circle of 'R' and 'D'. Cross one out, move forward, repeat until only one color is left. Write $O(N^2)$ for many passes. |
Two Queues (R_index, D_index). |
Queue-based Race / Index Bumping. |
Put indices of 'R' in `queueR` and 'D' in `queueD`. Compare front of both. Smaller index "wins" and is re-added to its queue with index + N. The loser is discarded. |
Draw two separate lines (Radiant and Dire). The person at the front of line R battles person at front of line D. The winner goes to the back of their line. |
Single pass through elements, re-queuing each at most once. |
Draw two parallel lines merging/looping. Write $O(N)$. |
Draw multiple copies of the string for state tracking. |
Draw two Queues storing integers (indices). $O(N)$ space. |
| 650 |
2 Keys Keyboard |
Backtracking/DFS: At each step, either "Copy All" or "Paste", exploring all paths to reach exactly `n` characters. |
Binary decision tree with redundant states. |
Draw the number 1. Branch to "Copy" then "Paste". Branch again. Write $O(2^N)$. |
Prime Factorization (Greedy/DP). |
Factor Summation. |
The minimum steps to get `n` characters is the sum of its prime factors. (e.g., for 6: 2+3=5. Copy1, Paste1, Paste1, Copy3, Paste3). |
Write the number `n`. Divide by the smallest possible factor (2, 3...). Add that factor to your total and update `n`. Repeat until `n` is 1. |
Linear reduction of `n`. |
Draw a division ladder. Write $O(\text{sqrt}(N)$). |
Draw a massive recursion tree. |
Draw zero extra space, just a loop variable. $O(1)$ space. |
| 651 |
4 Keys Keyboard |
Recursion without memoization: explore all 4 choices (A, Ctrl-A, Ctrl-C, Ctrl-V) at every step up to N. |
Quad-branching Decision Tree. |
Draw N levels. At each level, branch 4 ways. Note how most branches are invalid (can't Paste without Copy). $O(4^N)$. |
Dynamic Programming (1D Array). |
Exponential Multiplication Steps. |
`dp[i]` is max chars after `i` steps. To find `dp[i]`, look back at `j` (from 1 to i-3). You could have done Ctrl-A, Ctrl-C at `j`, then Ctrl-V `(i-j-1)` times. Formula: `dp[i] = max(dp[i-1]+1, dp[j]*(i-j-1))`. |
Draw a line 1..N. For a cell, draw arrows from previous cells representing "Copy-Paste" multipliers. Circle the highest result. |
Nested loop over N steps. |
Draw an N x N grid (Upper triangle). Write $O(N^2)$. |
Draw a recursive stack hitting depth N with massive redundancy. |
Draw a single 1D array of size N. $O(N)$. |
| 652 |
Find Duplicate Subtrees |
For every node, traverse its entire subtree to generate a string representation. Compare every string with every other string. |
N x N String Comparison Grid. |
Draw a tree. For every node, draw a bubble containing the subtree. Draw lines between identical bubbles. $O(N^2)$. |
Post-order Traversal + Serialization + Hash Map. |
Fingerprinting / Content Hashing. |
Recursively visit nodes. For each node, build a string: `val, left_subtree, right_subtree`. Store this string in a Map. If count becomes 2, add the node to results. |
Draw a tree. As you move up from leaves, write a "Code" on each node representing its structure. If you see the same "Code" twice, circle it. |
Single pass tree traversal with string hashing. |
Draw a straight scanline through the tree. Write $O(N^2)$ (due to string creation) or $O(N)$ (with ID-mapping). |
Draw a list storing all possible subtree structures independently. |
Draw a Hash Map storing serialized strings. $O(N)$ unique structures. |
| 653 |
Two Sum IV - Input is a BST |
In-order traversal to convert BST to a sorted array, then use Two Pointers. Or search the BST for `(k - node.val)` for every node. |
BST Search per Node / Linear Expansion. |
Draw a tree. For every node, draw a new "Search" arrow diving back into the tree. $O(N \log N)$ or $O(N)$. |
DFS + Hash Set. |
Single-Pass Neighborhood Check. |
Traverse the tree. For each node, check if `(k - val)` is in the Set. If yes, return True. If no, add `val` to Set and continue. |
Draw a tree. Next to it, draw a "Bag" (Set). As you touch a node, check the bag for the partner number. Then drop the node into the bag. |
Linear scan of tree nodes. |
Draw a single line passing through all nodes once. Write $O(N)$. |
Draw a full array copy of the tree (O(N)). |
Draw a Hash Set that grows up to $O(N)$. |
| 654 |
Maximum Binary Tree |
Recursively find the max element in the current range to create a root, then split the array into two halves and repeat. |
Recursive partitioning (like Quicksort). |
Draw an array. Find max. Split. Draw two arrows. Find max again. Write $O(N^2)$ in worst case (sorted array). |
Monotonic Stack. |
$O(N)$ Tree Construction / Structural Shadowing. |
Iterate through the array. Keep a stack of nodes in decreasing order. If current > stack.top, stack.top becomes the left child of current. Otherwise, current becomes the right child of stack.top. |
Draw numbers. Place a "Cap" on the highest number. For new numbers, see if they "Slide" under previous numbers or "Carry" them. |
Single pass through the array. |
Draw a straight arrow through the array. Write $O(N)$. |
Draw a recursion stack that can hit depth N. |
Draw a Stack that at most holds N elements. $O(N)$. |
| 655 |
Print Binary Tree |
Trial and error: place the root in the middle, then try to calculate the padding for each child level-by-level using multiple passes. |
Greedy placement with constant recalculation. |
Draw a grid. Draw the root. Try to guess where the children go. Erase and move when they overlap. $O(H \cdot 2^H)$. |
Recursive Matrix Filling (Height-based). |
Geometric Grid Subdivision. |
First, find height `H`. Create a matrix of size `H x (2^H - 1)`. Recursively place roots at `(low + high) / 2` and split the range for children. |
Draw a wide rectangle. Split it in half vertically. Put the root in the middle. Split the two halves into quarters. Put children in the quarter-midpoints. |
Filling every cell in the output matrix. |
Draw an H x W grid and a "Fill" motion. Write $O(H \cdot 2^H)$. |
Draw several temporary strings and buffers during layout attempts. |
Draw the final 2D result matrix. $O(H \cdot 2^H)$ space. |
| 656 |
Coin Path |
Recursion without memoization: explore every possible jump of length 1 to B at every index to find the cheapest path. |
Broad Multi-way Decision Tree. |
Draw an array. From index 0, draw B arrows. From each of those, draw B more. Write $O(B^N)$. |
Dynamic Programming (Right-to-Left). |
Value Iteration / Reverse Path Tracing. |
Start from the end. Calculate the minimum cost to reach the end from the current index by looking at the next B steps. Store the "Next Step" to reconstruct the path later. |
Draw the array. Write costs under each index. Draw a "Best Move" arrow from each cell to its cheapest neighbor within B range. |
$O(N \cdot B)$ time. |
Draw an N-length line where each point has a small local search of B. Write $O(\text{NB})$. |
Draw a massive recursion stack with duplicate paths. |
Draw two 1D arrays: `minCost[]` and `nextIndex[]`. $O(N)$ space. |
| 657 |
Robot Return to Origin |
Simulate the movement using a 2D coordinate grid, potentially checking if the robot hits a boundary or re-calculating position on a full map. |
Tracking a path on a Cartesian plane. |
Draw a grid. Draw a line moving from (0,0) step-by-step. Write $O(N)$. |
Net Displacement Counter. |
Zero-Sum Balance. |
Initialize `x = 0, y = 0`. Increment/Decrement based on U, D, L, R. Return true if `x == 0` and `y == 0` at the end. |
Draw two "Scales" labeled X and Y. For every move, put a weight on the left or right side. See if the scales are balanced at the end. |
Single pass $O(N)$. |
Draw a straight arrow through the string. Write $O(N)$. |
Draw a full trail of every coordinate visited. |
Draw exactly two integer variables. $O(1)$ space. |
| 658 |
Find K Closest Elements |
Sort the array based on absolute difference from `x`, then pick the first `k` elements and sort them again by value. |
Double-Sort Filter. |
Draw the array. Annotate each number with its distance to X. Re-sort the entire list. Write $O(N \log N)$. |
Binary Search + Two Pointers. |
Concentric Expansion / Range Squeeze. |
Use binary search to find the index of the element closest to `x`. Use two pointers (left and right) to expand outwards, picking the closer element until `k` elements are found. |
Draw a number line. Place a "Pin" at X. Place two fingers near the pin and move them apart like a set of calipers until they span k items. |
$O(\log N + k)$ time. |
Draw a small "Zoom" into a point on a line, followed by a local spread. Write $O(\log N + k)$. |
Draw a copy of the entire array with distance labels. |
Draw zero extra data structures beyond the output list. $O(1)$ auxiliary space. |
| 659 |
Split Array into Consecutive Subsequences |
Try every possible way to group the numbers into subsequences, using backtracking to ensure each group has length >= 3. |
Exponential Grouping Tree. |
Draw numbers. Try picking 1,2,3. Then try 1,2,3,4. The number of combinations of groups is massive. Write $O(2^N)$. |
Greedy with Frequency & Vacancy Maps. |
Chain Building / Need-vs-Supply. |
Track frequencies of numbers. Also track "Vacancy" (how many active chains end at `n-1`). If a chain exists, append `n`. If not, try starting a new chain of 3. |
Draw "Open Slots" for numbers. If you see a 4, check if a chain 1-2-3 is looking for a 4. If not, see if you can grab 5 and 6 to start a new chain. |
Two linear passes through the frequencies. |
Draw a frequency bar chart. "Eat" the bars from left to right in chunks of 3. Write $O(N)$. |
Draw all possible subset combinations in memory. |
Draw two Hash Maps (Count and Tail). $O(N)$ space. |
| 660 |
Remove 9 |
Count numbers from 1 upwards, skipping any number that contains the digit '9', until you reach the n-th valid number. |
Linear Scan with String Checks. |
Draw a counter. Check "1", "2"... "9" (Skip!). "10"... Write $O(N \cdot \log N)$. |
Base-9 Conversion. |
Numeral System Mapping. |
Removing the digit 9 effectively turns the decimal system (Base 10) into a Nonary system (Base 9). The n-th number is simply `n` converted to Base 9. |
Write the number N. Perform long division by 9 repeatedly. Keep the remainders. Read them bottom-to-top. |
Logarithmic time (number of digits in N). |
Draw a division ladder. Write $O(\log N)$. |
Draw a list of all numbers ever scanned. |
Draw a small string or list to hold the Base-9 digits. $O(1)$ relative to magnitude. |
| 661 |
Image Smoother |
For every cell in an M x N matrix, scan its 8 neighbors + itself, calculate the average, and store it in a new matrix. |
Nested Scanning Grid. |
Draw a large grid. In each cell, draw a small 3x3 window around it. Repeat for all cells. $O(M \cdot N)$. |
Single-Pass Iteration / In-Place Bit Manipulation. |
Sliding Kernel. |
Iterate through rows and columns. Use two nested loops (-1 to 1) to sum valid neighbor values. Divide by the count of neighbors. To do it in-place, store the result in higher bits. |
Draw a matrix. Draw a "Blur" filter box moving across each cell. Write the new number into a secondary grid. |
Strictly linear relative to grid size. |
Draw a single sweeping arrow through the grid. Write $O(M \cdot N)$. |
Draw a full secondary matrix of size M x N. |
Draw the original matrix. Use the upper 8 bits of each integer to store the new value. $O(1)$ extra space. |
| 662 |
Maximum Width of Binary Tree |
Perform a Level Order Traversal (BFS) and store every node, including NULLs, until the last non-null node in each level. Count the total elements. |
Sparse Array Level Filling. |
Draw a tree with one branch at depth 10. Draw a row with 1024 slots, most of which are empty. $O(2^H)$. |
BFS / DFS with Positional Indexing. |
Binary Heap Index Mapping. |
Assign an index to each node. Root is 1. Left child is `2*i`, right is `2*i + 1`. In each level, `width = maxIndex - minIndex + 1`. |
Draw a tree. Label root '1'. Label children '2' and '3'. Note that even if a middle node is missing, the index gap tells you the width. |
Linear scan of tree nodes. |
Draw a single line passing through all nodes once. Write $O(N)$. |
Draw a queue containing thousands of NULL markers for deep, sparse trees. |
Draw a queue of pairs (node, index). Only stores actual nodes. $O(\text{Width})$. |
| 663 |
Equal Tree Partition |
Try cutting every edge one by one. For each cut, perform a full tree traversal to sum the two resulting subtrees and check if they are equal. |
Edge-by-Edge Amputation. |
Draw a tree with N edges. Pick an edge, "cut" it, and sum the pieces. Repeat N times. $O(N^2)$. |
Post-order Subtree Sums + Hash Set. |
Subtree Accumulation. |
Calculate the total sum of the tree. Perform a DFS to find the sum of every possible subtree. Store these sums in a Hash Set. If `totalSum / 2` exists in the set, a partition is possible. |
Draw a tree. Write the sum of everything below it inside each node. Circle any node where the value is exactly half of the Root's value. |
Single pass through the tree. |
Draw a single scanline through the tree. Write $O(N)$. |
Draw N different copies of subtree structures during sum checks. |
Draw a Hash Set or List containing N integers. $O(N)$ space. |
| 664 |
Strange Printer |
Recursion without memoization: try every possible range and every possible character to "print" over that range. |
High-branching Range Decision Tree. |
Draw a string "aba". Branch into "print a", "print b", "print over". The combinations are staggering. $O(3^N)$. |
Dynamic Programming (Range DP). |
Interval Compression / Multi-layer Painting. |
`dp[i][j]` is the min turns to print `s[i...j]`. If `s[i] == s[k]`, we might save a turn. Iterate through all sub-intervals. |
Draw the string. Draw a bracket for each sub-segment. Show how overlapping segments can be "merged" if the endpoints match. |
Three nested loops over string length. |
Draw an N x N grid. Write $O(N^3)$. |
Draw a recursive stack with massive overlapping subproblems. |
Draw a 2D matrix of size N x N. $O(N^2)$. |
| 665 |
Non-decreasing Array |
For every element, try changing it to every possible integer and check if the resulting array is non-decreasing. |
Brute Force Mutation. |
Draw an array. Change one number to -infinity, then -infinity+1... until it works. Repeat for all indices. $O(N^2 \\text{cdot Range})$. |
Greedy Local Correction. |
Valley Correction / Peak Smoothing. |
Scan for `arr[i] > arr[i+1]`. You can only fix it ONCE. To fix, either lower `arr[i]` or raise `arr[i+1]`. Check which one keeps the non-decreasing property for the rest of the array. |
Draw a line graph. Identify a "dip". Try pushing the previous peak down or the current valley up. See which one makes the line stay flat or climb. |
Single pass through the array. |
Draw a straight arrow through the array. Write $O(N)$. |
Draw hundreds of modified array copies. |
Draw zero extra space, just one "modified" boolean flag. $O(1)$ space. |
| 666 |
Path Sum IV |
Reconstruct the entire tree into a nested object/pointer structure using the 3-digit coordinates, then run a standard Root-to-Leaf DFS. |
Layered Construction & Traversal. |
Draw the coordinates. For each, draw a new node circle and manually connect parents to children based on the (d, p) logic. $O(N)$. |
Hash Map Traversal / Parent-Child Mapping. |
Virtual Tree Traversal. |
Store data in a Map where Key = `depth*10 + position`. Start DFS at 11 (Root). Left child is at `(d+1, 2*p - 1)`, Right at `(d+1, 2*p)`. If neither exists, it's a leaf; add current sum to total. |
Write the numbers in a grid based on depth and position. Draw arrows directly on the grid following the 2p-1/2p formula without creating objects. |
Single DFS pass through the Map. |
Draw a single line snaking through the "Virtual" tree nodes. Write $O(N)$. |
Draw complex Node objects with Left/Right pointers and associated overhead. |
Draw a single Hash Map (Integer -> Integer). $O(N)$. |
| 667 |
Beautiful Arrangement II |
Generate all N! permutations and check if the number of unique absolute differences between adjacent elements equals K. |
Permutation Jungle. |
Draw 1,2,3. List [1,2,3], [1,3,2], etc. Calculate diffs for each. The branching is overwhelming. $O(N! \cdot N)$. |
Greedy Constructive Construction. |
Alternating "Zig-Zag" Pattern. |
Keep the first `n-k-1` numbers as `1, 2, 3...`. For the remaining `k+1` numbers, alternate between the largest and smallest available to create `k` distinct gaps. |
Draw two lists: 1,2,3... and ...10,9,8. Draw a line from 1 to 2, then jump to 10, then back to 3, then 9. Count the "gap" distances. |
Single pass linear construction. |
Draw a straight arrow through the numbers 1 to N. Write $O(N)$. |
Draw the entire permutation tree in memory. |
Draw a single output array of size N. $O(1)$ auxiliary space. |
| 668 |
Kth Smallest Number in Multiplication Table |
Generate all M * N products, put them in a list, sort the list, and pick the k-th element. |
Massive Grid Flattening. |
Draw an M x N grid. Write every multiplication result. Draw an arrow sorting them into one long line. $O(\text{MN} \\text{log MN})$. |
Binary Search on Answer. |
Frequency Counting / Matrix Step-Down. |
Guess a number `mid`. For each row `i`, the number of elements `<=` `mid` is `min(mid/i, n)`. Sum these counts. If sum >= k, `mid` could be our answer. |
Draw a number line of values. Pick a middle value. Draw a "Staircase" on the multiplication table showing which numbers are smaller than the guess. |
$O(M \cdot \log(M\cdot N)$). |
Draw a loop (Log) containing a single scan of rows (M). Write $O(M \log(\text{MN})$). |
Draw a massive list holding M*N integers in memory. |
Draw zero extra space beyond simple variables. $O(1)$ space. |
| 669 |
Trim a Binary Search Tree |
Traverse the tree and for every node, search if it is in range. If not, delete it and perform a full tree re-balance. |
Recursive Re-balancing / Heavy Grafting. |
Draw a tree. Cut a node. Move its entire bottom branch up. Check if the balance is ruined. Write $O(N \log N)$. |
Recursive Pointer Re-assignment. |
Pruning / Branch Grafting. |
If `node.val < low`, the whole left side is invalid; return `trim(node.right)`. If `node.val > high`, right side is invalid; return `trim(node.left)`. Else, trim both children. |
Draw a tree. Draw a "Fence" at Low and High. Any node outside the fence gets its "parent string" snipped and re-tied to its valid grandchild. |
Single pass tree traversal. |
Draw a single line passing through all nodes once. Write $O(N)$. |
Draw multiple temporary tree copies during re-balancing. |
Draw the recursion stack. Space is $O(\text{Height})$. |
| 670 |
Maximum Swap |
Try every possible swap of two digits in the number. Convert to integer each time and track the maximum. |
All-Pairs Digit Exchange. |
Write "2736". Swap (2,7), (2,3), (2,6), (7,3), etc. For each, write the new number. $O(D^2)$ where D is digits. |
Greedy / Last-Position Tracking. |
Right-to-Left Scanning / Opportunity Cost. |
Store the last occurrence index of each digit (0-9). Scan digits from left to right. For each digit, check if a larger digit (9 down to current+1) exists later in the number. Swap and break. |
Write the number. Write a small table: "Last 9 at index X, Last 8 at index Y...". Scan the number. At each spot, check the table for a better future. |
Single pass scan of digits. |
Draw a straight line for the number scan. Write $O(D)$. |
Draw all possible swapped number strings. |
Draw a fixed-size array of length 10 to store indices. $O(1)$ extra space. |
| 671 |
Second Minimum Node In a Binary Tree |
Traverse the entire tree and store all unique values in a Set. Sort the set and return the second smallest value. |
Exhaustive Collection & Sorting. |
Draw a tree. Draw a "Bucket" (Set) next to it. For every node, throw its value into the bucket. Sort the bucket. Write $O(N \log N)$. |
Recursive Branch Pruning. |
Tournament Elimination. |
The root is the minimum. If a child's value is greater than the root, that child is a candidate for the second minimum; don't search deeper. If equal, search deeper to find a value > root. |
Draw a tree. If a node value > Root, circle it and stop. If equal, keep diving. Compare all circled values at the end. |
Linear traversal with early exits. |
Draw a line passing through nodes, "bouncing off" nodes that are already greater than the root. Write $O(N)$. |
Draw a Hash Set containing N unique elements. |
Draw the recursion stack. Space is $O(\text{Height})$. |
| 672 |
Bulb Switcher II |
Simulate every possible combination of 4 button presses over M rounds for N bulbs. |
State-Space Explosion. |
Draw N bulbs. Branch for each button press. After M presses, count unique configurations. Write $O(2^M)$. |
Mathematical Pattern Reduction. |
Cycle Observation / Constraint Satisfaction. |
Observe that bulbs repeat every 6 units. With 4 buttons and M > 2, the number of states is strictly limited regardless of how large N is. Use a set to track combinations of the 4 button states. |
Draw a small truth table for 4 buttons. Note how N=1, N=2, and N>=3 behave. For large N, the answer is always capped (e.g., 8). |
Constant time logic. |
Draw a single decision point (Logic Gate). Write $O(1)$. |
Draw a massive matrix of all bulb states over time. |
Draw a small set of bitmasks (size 8 max). $O(1)$ space. |
| 673 |
Number of Longest Increasing Subsequence |
Generate every possible increasing subsequence and count those with the maximum length. |
Subsequence Permutation Tree. |
Draw an array. Branch into every valid increasing path. Count the longest ones. Write $O(2^N)$. |
Dynamic Programming (Two 1D Arrays). |
Length & Count Accumulation. |
Maintain two arrays: `lengths[i]` (LIS ending at i) and `counts[i]` (number of LIS ending at i). For each i, look back at j. Update length and sum counts. |
Draw the array. Under each number, write two values: (Max Length, Count). When looking back, if you find a new max length, reset the count. If equal, add the count. |
Nested loops over array length. |
Draw an N x N grid (Upper triangle). Write $O(N^2)$. |
Draw an exponential list of all subsequences. |
Draw two 1D arrays of size N. $O(N)$. |
| 674 |
Longest Continuous Increasing Subsequence |
Check every possible subarray (i, j) to see if it is increasing, and track the maximum length. |
Subarray Scan Volume. |
Draw an array. Draw brackets of all lengths. For each, scan to check "increasing." Write $O(N^2)$. |
Sliding Window / Greedy. |
Unbroken Streak Tracking. |
Iterate once. If `arr[i] > arr[i-1]`, increment the current streak. If not, reset the streak to 1. Track the max streak encountered. |
Draw an array. Draw a single arrow moving left to right. If the next number is higher, extend the arrow. If lower, start a new arrow. |
Single pass $O(N)$. |
Draw a straight arrow through the array. Write $O(N)$. |
Draw a list of all increasing subarrays. |
Draw exactly two integer variables: `current` and `max`. $O(1)$ space. |
| 675 |
Cut Off Trees for Golf Event |
Try every possible permutation of trees to find the shortest path that visits all of them in order. |
TSP-style Path Explosion. |
Draw a grid. Draw lines between trees in every possible order. Write $O(N!)$. |
BFS / Dijkstra on Sorted Checkpoints. |
Step-by-Step Shortest Path Sequence. |
Sort all trees by height. Use BFS to find the shortest distance from (0,0) to the shortest tree, then from that tree to the next shortest, and so on. Sum the distances. |
Draw a grid with numbers. Draw a line from 1 to 2, then 2 to 3. If any path is blocked by '0' (obstacle), return -1. |
$O(T \cdot R \cdot C)$ where T is number of trees. |
Draw a sequence of BFS "waves" (circles) expanding from one tree to the next. Write $O(M\cdot N \cdot T)$. |
Draw a factorial number of path combinations. |
Draw the BFS Queue and a sorted list of tree coordinates. $O(M\cdot N)$. |
| 676 |
Implement Magic Dictionary |
Store all words in a list. For a search word, iterate through the list and compare character-by-character, checking if exactly one character differs. |
Exhaustive String Comparison. |
Draw a word "hello". Draw a list of 100 words. Draw a line from "hello" to every word, checking every letter. Write $O(N \cdot L)$. |
Trie with DFS / Generalized Neighbors. |
Branching Search with "One-Mistake" tolerance. |
Build a Trie. For a search, traverse the Trie. At each level, you have a "magic coupon." You can use it to jump to a wrong character once. If you reach a leaf after using the coupon, return true. |
Draw a Trie. Trace a path. At one node, branch out to a "wrong" letter and continue. If the new path ends in a terminal node, it's a match. |
$O(L^2)$ per search or Trie traversal. |
Draw a Trie path with one "detour" arrow. Write $O(L^2)$ or $O(\text{Alphabet} \cdot L)$. |
Draw a flat list of strings. |
Draw a Trie where common prefixes share memory. $O(\text{Total Characters})$. |
| 677 |
Map Sum Pairs |
Store key-value pairs in a Hash Map. For `sum(prefix)`, iterate through the entire map and check if each key starts with the prefix; if so, add the value. |
Full Map Scan per Query. |
Draw a Hash Map. For every "sum" query, draw a scanner that visits every single entry. Write $O(N \cdot L)$. |
Trie with Weight Accumulation. |
Prefix-Based Aggregation. |
Each node in the Trie stores the current sum of all words passing through it. When inserting/updating, adjust the `delta` (new value - old value) for all nodes along the path. |
Draw a Trie. Inside each node, write a "Sum" number. When adding "apple:3", add +3 to every node from 'a' to 'e'. `sum("ap")` just reads the value at 'p'. |
$O(L)$ for both insert and sum. |
Draw a single straight path down a tree. Write $O(L)$. |
Draw a standard Hash Map. |
Draw a Trie where nodes store integers. $O(\text{Total characters})$. |
| 678 |
Valid Parenthesis String |
Backtracking: For every '*', try three possibilities: '(', ')', or empty. Check if the resulting string is valid. |
Exponential Branching Tree. |
Draw a string with three '*'. Branch 3x3x3 = 27 times. It becomes a massive tree. Write $O(3^N)$. |
Greedy (Min/Max Balance Tracking). |
Dynamic Range Boundaries. |
Maintain a range `[low, high]` of possible open-parenthesis counts. '(' increases both. ')' decreases both. '*' expands the range: `low--`, `high++`. Ensure `low` never goes below 0. Valid if `0` is in the range at the end. |
Draw a vertical line. As you read the string, draw a "Bracket" that expands or shrinks. If the bracket crosses the 0-line and contains it at the end, it's valid. |
Single pass $O(N)$. |
Draw a straight arrow through the string. Write $O(N)$. |
Draw a massive recursion stack. |
Draw exactly two integer variables: `minOpen` and `maxOpen`. $O(1)$ space. |
| 679 |
24 Game |
Brute force: try every permutation of the 4 numbers and every combination of the 4 operators (+, -, *, /) and all possible parenthesis placements. |
Exhaustive Permutation & Operator Tree. |
Draw 4 numbers. Branch into every possible math expression. Note the complexity of fractions and divisions. $O(\text{Constant but high})$. |
Backtracking / Divide and Conquer. |
Recursive Number Reduction. |
Pick any 2 numbers from the current list (6 pairs). Apply all 4 operations. Create a new list with the result and the remaining numbers. Repeat until 1 number is left. Check if it's 24. |
Draw 4 circles. Merge 2 circles into 1 using an operator. Repeat until 1 circle remains. Use a tree structure to track the "merges." |
$O(1)$ because the input size is always 4. |
Draw a small, fixed-depth decision tree. Write $O(9216 \text{combinations})$. |
Draw every intermediate expression string. |
Draw a recursion stack with a maximum depth of 4. $O(1)$ space. |
| 680 |
Valid Palindrome II |
Try deleting every character one by one. For each resulting string, check if it is a palindrome. |
N-fold Palindrome Checks. |
Draw a string. Delete char at index 0, check. Delete char at index 1, check. Write $O(N^2)$. |
Two Pointers with One-Time Divergence. |
Symmetrical Squeeze with a "Safety Valve." |
Use `left` and `right` pointers. If characters match, move inward. If they don't, you have one chance: check if `string[left+1...right]` OR `string[left...right-1]` is a palindrome. |
Draw a string. Move fingers from ends to middle. When they hit a mismatch, draw two "Sub-scans" from that point. If either finishes, it's valid. |
Single pass $O(N)$. |
Draw a straight line that forks once and immediately merges/ends. Write $O(N)$. |
Draw hundreds of string copies. |
Draw zero extra space, just pointer logic. $O(1)$ space. |
| 681 |
Next Closest Time |
Generate all 4^4 (256) possible time combinations using the digits from the input. Validate each and find the one with the smallest positive time difference. |
Exhaustive permutation list. |
Draw 4 slots. List 4 options for each slot. Draw lines connecting every combination. Write $O(1)$ (since the total is capped at 256). |
Simulation / Minute-by-Minute Increment. |
Circular 24-hour Clock Scan. |
Add 1 minute to the current time. Check if all digits in the new time exist in the original set. If yes, that's the answer. If you hit 1440 minutes, you've wrapped around. |
Draw a clock face. Mark the current time. Step forward minute-by-minute until your "Digit Filter" (a set of 4 digits) lets a time through. |
Constant time (max 1440 checks). |
Draw a circle (24h) with a small segment highlighted. Write $O(1)$. |
Draw a list of 256 time strings. |
Draw a small Hash Set of size 4. $O(1)$ space. |
| 682 |
Baseball Game |
Iterate through the operations. For "C", "D", or "+", search backwards in the original list to find valid previous scores, re-calculating indices every time. |
Backwards linear search per operation. |
Draw a list. For every "+", draw two long arrows pointing back to find the last two non-"C" numbers. Write $O(N^2)$. |
Stack Data Structure. |
LIFO (Last-In, First-Out) Tally. |
Maintain a stack. If it's a number, push. "C": pop. "D": push(2 * top). "+": push(top + second_top). Finally, sum the stack. |
Draw a vertical bucket. Drop numbers in. When "C" appears, erase the top number. When "+" appears, peek at the top two and drop their sum in. |
Single pass $O(N)$. |
Draw a straight arrow through the operations list. Write $O(N)$. |
Draw a complex list with many "deleted" flags or holes. |
Draw a contiguous stack of integers. $O(N)$ space. |
| 683 |
K Empty Slots |
For every new flower planted, scan K positions to the left and K to the right to see if another flower exists and if the space between is empty. |
Local Radius Scanning. |
Draw a garden. For every new flower, draw two "Scan Arms" extending K units. Write $O(N \cdot K)$. |
Sliding Window / Monotonic Queue. |
Inverse Mapping / Range Minimum. |
Create a `days` array where `days[i]` is the day flower at position `i` blooms. Find a window of size K+2 where the endpoints bloom earlier than all flowers inside. |
Draw the "Blooming Day" array. Draw a bracket of size K. If the two "Post" values are smaller than everything inside the bracket, you've found the day. |
Single pass $O(N)$. |
Draw a straight arrow with a sliding box. Write $O(N)$. |
Draw the garden state at every single day (N x N grid). |
Draw one 1D array of size N. $O(N)$. |
| 684 |
Redundant Connection |
For every edge, try removing it and perform a full DFS/BFS to see if the graph remains connected. |
Edge-by-Edge Graph Traversal. |
Draw a graph with a cycle. Cross out one edge. Run DFS to see if all nodes are reached. Repeat for every edge. Write $O(N^2)$. |
Union-Find (Disjoint Set Union). |
Group Merging / Cycle Detection. |
Iterate through edges. For each edge (u, v), check if u and v are already in the same set. If they are, this edge completes a cycle (it's redundant). If not, union them. |
Draw each node as a separate bubble. When an edge connects them, merge the bubbles. If an edge connects two nodes already in the same bubble, color it red. |
$O(N \cdot α(N)$), where α is the inverse Ackermann function (effectively constant). |
Draw a line of edges feeding into a "DSU Machine." Write $O(N)$. |
Draw an adjacency list for every edge removal attempt. |
Draw a single `parent` array of size N. $O(N)$. |
| 685 |
Redundant Connection II |
Similar to Q684, but with directed edges. Try removing every edge and check if the remaining structure is a valid rooted tree (one root, no cycles). |
Exhaustive Tree Validation. |
Draw a directed graph. Remove one arrow. Check if it's a tree. Repeat for all arrows. Write $O(N^2)$. |
DSU + In-degree Tracking. |
Two-Case Anomaly Detection. |
Case 1: A node has two parents (in-degree 2). Case 2: A cycle exists. Track parents. If a node gets a second parent, store those two edges. Use DSU to detect which edge causes a cycle. |
Draw nodes. If a node gets two arrows, put a "Question Mark" on them. Use the bubble-merging (DSU) logic to see which arrow creates a loop. |
$O(N \cdot α(N)$). |
Draw a funnel separating "Two-Parent" cases from "Cycle" cases. Write $O(N)$. |
Draw the whole graph in memory multiple times. |
Draw a parent array and two candidate edge variables. $O(N)$. |
| 686 |
Repeated String Match |
Keep appending string A to itself indefinitely and check `contains(B)` at every single step. |
Infinite or very long linear expansion. |
Draw string A. Draw an arrow looping back to append A again and again. Draw a search box for B underneath. $O(N \cdot M)$. |
Upper Bound Estimation + String Search. |
Minimal Envelope Fit. |
Repeat A until its length is at least B. Check `contains`. If not, repeat once more and check again. If still not there, it's impossible. (Max repeats: B/A + 2). |
Draw B. Draw segments of A next to it. See how many 'A' blocks you need to fully cover B's length. Add one extra block for potential overlap at the edges. |
$O(N + M)$ if using KMP or $O(N\cdot M)$ for basic search. |
Draw two horizontal bars (A_repeated and B). Write $O(\text{RepeatedLength})$. |
Draw a massive string buffer that grows without a clear exit condition. |
Draw a string buffer capped at $O(N + M)$ size. |
| 687 |
Longest Univalue Path |
For every node, start a new DFS to find the longest path of identical values passing through that specific node. |
Redundant Nested Tree Scans. |
Draw a tree. From every node, draw separate "Search Rays" branching out to its neighbors. Write $O(N^2)$. |
Post-order DFS (Bottom-Up). |
Recursive Path Contribution. |
Visit children first. Each node returns the longest univalue leg it can provide to its parent. At each node, check if `left_child.val == node.val` and update the global max with (left_leg + right_leg). |
Draw a tree. Write "Leg Length" numbers next to edges. At each node, sum the matching legs and update a "High Score" on the side of the paper. |
Single pass $O(N)$. |
Draw a single unbroken line tracing the tree's perimeter. Write $O(N)$. |
Draw multiple recursive call stacks for each starting node. |
Draw a single recursion stack with depth $O(\text{Height})$. |
| 688 |
Knight Probability in Chessboard |
Use recursion to simulate every possible sequence of K knight moves. Count how many end up inside the board. |
Exponential Branching (8^K). |
Draw a board. From one square, draw 8 arrows. From each of those, 8 more. After 3 moves, it's a mess of 512 lines. $O(8^K)$. |
Dynamic Programming (2D/3D). |
Probability Distribution Heatmap. |
Create a grid `dp[i][j]` representing the probability of being on that square. For each step, a square's probability is distributed equally (1/8) to its 8 legal knight-move neighbors. |
Draw a grid. Put "1.0" on the starting square. For step 1, erase it and put "0.125" on the 8 squares a knight reaches. Sum probabilities for squares that go off-board. |
$O(K \cdot N^2)$ time. |
Draw a stack of K grids. Write $O(K \cdot N^2)$. |
Draw an 8-way branching tree in memory. |
Draw two N x N matrices (Current and Next state). $O(N^2)$ space. |
| 689 |
Maximum Sum of 3 Non-Overlapping Subarrays |
Check every possible triplet of indices (i, j, k) that start 3 non-overlapping subarrays of length K. Sum them and find the max. |
Triple Nested Window Search. |
Draw an array. Draw 3 brackets. Slide them in all possible valid configurations. $O(N^3)$. |
DP with Sliding Window / Prefix-Suffix Max. |
Interval Partitioning. |
Pre-calculate all possible window sums of size K. For each middle window starting at `j`, pick the best left window in `[0...j-k]` and the best right window in `[j+k...end]`. |
Draw an array of window sums. For each "Middle" choice, look at a "Left-Max" table and a "Right-Max" table to instantly pick the best partners. |
Single pass after pre-processing $O(N)$. |
Draw three parallel data streams (Left, Mid, Right) merging. Write $O(N)$. |
Draw all triplet combinations in memory. |
Draw three 1D arrays of size N. $O(N)$ space. |
| 690 |
Employee Importance |
Search through the entire list of employees to find a specific ID, then repeat the search for every subordinate in the list. |
Linear Search inside a Recursion. |
Draw a list of names. To find a boss, scan the list. To find their 3 subordinates, scan the list 3 more times. $O(N^2)$. |
Hash Map + DFS/BFS. |
$O(1)$ Direct Access Adjacency Map. |
Store all employee objects in a Map (ID -> Employee). Start at the given ID. Recursively add its importance and the importance of all IDs in its `subordinates` list. |
Draw a "Directory" (Map). Look up the boss. Follow arrows directly to subordinates without searching the whole book. Tally values. |
Linear traversal of the hierarchy $O(N)$. |
Draw a tree structure where each edge is traversed once. Write $O(N)$. |
Draw the list being passed around and scanned repeatedly. |
Draw a Hash Map and the recursion stack. $O(N)$ space. |
| 691 |
Stickers to Spell Word |
Exhaustive Backtracking: Try applying every sticker in every possible sequence until all letters of the target word are covered. |
Explosive Multi-way Decision Tree. |
Draw target "BASIC". Branch for Sticker 1 (B,A), Sticker 2 (S,I,C). From (B,A), branch again. Tree width = number of stickers. $O(S^T)$. |
DP with Bitmask / Memoization. |
State Compression / Power Set Reduction. |
Represent the target word as a bitmask (11111). Each sticker used flips some bits from 1 to 0. Use a Map to store "min stickers for mask X". If you reach 00000, you're done. |
Draw a row of 5 bits. For a sticker, show it "blocking out" specific bits. Use arrows to link bit patterns to their minimum sticker count. |
$O(2^T \cdot S \cdot T)$ where T is target length and S is stickers. |
Draw a lattice (like a Hasse diagram) of all possible bitmasks. Write $O(2^T)$. |
Draw a recursion stack exploring millions of redundant character combinations. |
Draw a Hash Map storing 2^T possible state values. $O(2^T)$. |
| 692 |
Top K Frequent Words |
Count frequencies in a map, convert map to a list of pairs, and perform a full sort based on count (descending) and alphabetical order (ascending). |
Full-Array Sorting Overhead. |
Draw a list of 1000 words. Count them. Sort the entire 1000-word list even if you only need the top 2. Write $O(N \log N)$. |
Hash Map + Min-Heap (size K). |
Competitive Extraction / Bucket Sort. |
Use a Map for counts. Maintain a Min-Heap of size K. If a word's count > heap.top, pop and push the new word. Sorting only happens for K elements. |
Draw a Map. Draw a small "Bucket" (Heap) with only K slots. Only let the strongest words stay in the bucket as you scan. |
$O(N \log K)$ time. |
Draw a funnel (Heap) processing a stream of N items. Write $O(N \log K)$. |
Draw a full list of all unique words being sorted in memory. |
Draw a Map $O(N)$ and a small Heap $O(K)$. |
| 693 |
Binary Number with Alternating Bits |
Convert the number to a binary string and iterate through the characters to check if `s[i] != s[i-1]`. |
String conversion and linear scan. |
Write "5" -> "101". Scan. Write "7" -> "111" (Fail!). $O(Log N)$ for string conversion. |
Bit Manipulation (XOR Shift). |
Self-Alignment check. |
Let `n = n ^ (n >> 1)`. If bits were alternating, `n` becomes all 1s (e.g., 1010 ^ 0101 = 1111). Check if `(n & (n+1)) == 0`. |
Write a binary number. Write it again shifted right by 1. Draw a line for XOR. Check if the result is a solid block of 1s. |
$O(1)$ (Fixed number of bitwise operations). |
Draw a single logic gate diagram. Write $O(1)$. |
Draw a string object in memory. |
Draw zero extra space, just registers. $O(1)$. |
| 694 |
Number of Distinct Islands |
For every island, find its coordinates, store them in a list, and try to rotate/reflect/shift them to see if they match other islands. |
Coordinate transformation and set comparison. |
Draw two 'L' shapes. Write their coordinates. Manually subtract (min_x, min_y) from each to compare. $O(\text{Grid}^2)$. |
DFS + Path Serialization. |
Directional Signature / DNA Mapping. |
During DFS, record the direction of each move (U, D, L, R) and 'B' for backtracking. Each island gets a unique string signature. Add signatures to a Set. |
Draw an island. Trace it with a pen: "Down, Right, Back, Back". That string is its ID. If another island has the same ID, they are identical. |
Single pass $O(\text{Rows} \\text{cdot Cols})$. |
Draw a scanner moving across the grid with a side-list of signatures. Write $O(R \cdot C)$. |
Draw a list of coordinate sets for every island. |
Draw a Hash Set of strings. Space $O(R \cdot C)$. |
| 695 |
Max Area of Island |
For every cell, if it is '1', run a BFS/DFS to calculate the area. Repeat even for cells that were part of previous islands. |
Redundant redundant island scans. |
Draw a 5x5 island. Run a scan from the top-left cell, then the next, re-calculating the whole area every time. $O((R\cdot C)$^2). |
DFS with In-Place Sinking (Visited marking). |
Flood Fill / Area Tally. |
When you find '1', start DFS. Change '1' to '0' (sink it) as you visit so you don't count it again. Return count of recursion calls. Update global max. |
Draw a grid of land. Touch a cell. Color it and its neighbors blue. Tally the number of blue squares. Move to the next "dry" land. |
Single pass $O(\text{Rows} \\text{cdot Cols})$. |
Draw a single scanline that "blooms" into islands occasionally. Write $O(R \cdot C)$. |
Draw a separate `visited` matrix of size R x C. |
Modify the input grid in-place. Space $O(\text{Recursion Depth})$. |
| 696 |
Count Binary Substrings |
Find all possible substrings and for each, check if it has an equal number of consecutive 0s and 1s. |
N-squared substring checks. |
Draw a binary string. Draw every possible bracket. For each bracket, scan to count. Write $O(N^2)$. |
Group Consecutive Counts. |
Adjacency Compression. |
Convert "00110" to an array of counts: [2, 2, 1]. The answer is the sum of `min(groups[i], groups[i+1])`. (e.g., min(2,2) + min(2,1) = 3). |
Draw a string. Group identical neighbors. Write the size of each group underneath. Compare adjacent numbers and circle the smaller one. |
Single pass $O(N)$. |
Draw a straight arrow through the string. Write $O(N)$. |
Draw a list of all substrings generated. |
Draw an array of counts (at most N) or use two variables for $O(1)$ space. |
| 697 |
Degree of an Array |
For every possible subarray, calculate its degree (frequency of most common element) and compare it to the original array's degree. |
Nested subarray frequency scans. |
Draw an array. Draw all brackets. For each, build a frequency map. Write $O(N^3)$. |
Hash Map (First/Last/Count). |
Span Measurement. |
Store three things in a map for each number: its frequency, its first appearance index, and its last appearance index. The min length is `last - first + 1` for all numbers with max frequency. |
Draw a table: [Num | Freq | First | Last]. Fill it as you scan. Highlight rows with the highest Freq. Find the smallest (Last-First). |
Single pass $O(N)$. |
Draw a straight scan line. Write $O(N)$. |
Draw millions of temporary HashMaps. |
Draw one HashMap of unique elements. $O(N)$. |
| 698 |
Partition to K Equal Sum Subsets |
Generate every possible combination of elements into K buckets and check if all buckets have equal sums. |
Exponential Subsets (K^N). |
Draw N numbers. Branch K ways for the first, K for the second... it becomes a massive K-ary tree. Write $O(K^N)$. |
Backtracking with Pruning + State Compression. |
Bucket Filling / Bin Packing. |
Calculate `target = total/k`. Sort numbers descending. Try placing each number into a bucket. If a bucket exceeds target, backtrack. Use a bitmask to track used numbers. |
Draw K "Buckets." Pick the largest number, drop it in Bucket 1. Pick the next, try Bucket 1, if full, move to Bucket 2. Draw an "X" when a path fails. |
$O(K \cdot 2^N)$ with memoization. |
Draw a decision tree with many pruned (cut) branches. Write $O(K \cdot 2^N)$. |
Draw the entire K^N state tree. |
Draw the recursion stack and a bitmask/memo table. $O(2^N)$. |
| 699 |
Falling Squares |
For every new square, check every previous square to see if they overlap horizontally. If they do, the new height is `max(prev_height) + size`. |
Iterative Overlap Check. |
Draw a line. Add a square. Add a second. Check if it sits on the first. Add a third, check against 1 and 2. Write $O(N^2)$. |
Coordinate Compression + Segment Tree / Sparse Map. |
Skyline Profile Update. |
Map unique x-coordinates to integers. Use a Segment Tree to perform "Range Max" queries (what is the highest point between L and R?) and "Range Update" (set new height). |
Draw a skyline. When a block falls, look at the highest horizontal line beneath it. "Lift" that segment of the skyline to the new height. |
$O(N \log N)$. |
Draw a balanced tree (Segment Tree) with height values. Write $O(N \log N)$. |
Draw a list of all overlap results. |
Draw a Segment Tree or a TreeMap of intervals. $O(N)$. |
| 700 |
Search in a Binary Search Tree |
Perform a full tree traversal (DFS/BFS) without utilizing the BST property, checking every single node. |
Exhaustive Search. |
Draw a tree. Draw a circle around every single node. Write $O(N)$. |
BST Property Navigation (Binary Search). |
Directional Descent. |
If `val == root.val`, return root. If `val < root.val`, move to the left child. If `val > root.val`, move to the right child. Repeat until found or NULL. |
Draw a tree. Draw a single path from the root downwards. You only ever pick one branch at each step. |
$O(\text{Height})$ — $O(\log N)$ for balanced trees. |
Draw a single line diving into a tree. Write $O(H)$. |
Draw the recursion stack for all nodes. |
Draw a single recursion path or a single loop variable. $O(H)$ or $O(1)$. |
| 701 |
Insert into a Binary Search Tree |
Level-order traversal to find the first valid empty spot (not strictly BST rule compliant, but absolute brute). |
Breadth-First Expansion Tree |
Draw a tree, circle nodes level-by-level, showing $O(N)$ worst-case time to touch all nodes. |
BST Traversal (Iterative) |
Pointer Tracing on Binary Tree |
Draw the tree. Place a token (curr) at root. Move token Left if val < curr, Right if val > curr until hitting null. |
Draw circles for nodes. Use a colored arrow for `curr` jumping downwards. Draw dashed circle for the newly inserted node. |
Depth/Height Vector Path |
Draw a straight line downwards representing $O(H)$ time. Label nodes visited as steps 1 to H. |
Queue Array Blocks (for BFS level traversal memory). |
Single Variable Box for `curr` pointer (O(1) space). |
| 702 |
Search in a Sorted Array of Unknown Size |
Linear scan reading index 0, 1, 2... until hitting out of bounds or the target. |
Linear Timeline/Ruler |
Draw an open-ended array. Map an arrow jumping 1 box at a time. Write $O(T)$ where T is target index. |
Exponential Expansion + Binary Search |
Expanding Bounds window |
Draw an array. Start `left=0`, `right=1`. Double `right` until `arr[right] > target`. Then Binary Search between `left` and `right`. |
Draw a number line. Draw arcs expanding: 0->1, 1->2, 2->4, 4->8. Then draw a converging bracket [L, R] inside the final range. |
Logarithmic Convergence Funnel |
Draw a wide bracket that halves in width iteratively. Write $O(\log T)$ next to the halving steps. |
Single index counter variable box (O(1)). |
Two boxes for `Left` and `Right` pointers (O(1)). |
| 703 |
Kth Largest Element in a Stream |
Store stream in an array. Sort array in descending order on every single `add()` call. |
Sorting Bar Chart |
Draw a bar chart. Show all bars shuffling completely every time a new bar is added (O(N log N)). |
Min-Heap (Size K) |
Bounded Priority Queue / Funnel |
Draw a triangle (heap) with exactly K slots. When a number arrives, if it's larger than the top (minimum), replace top and sink it down. |
Draw a binary tree of max depth log(K). Use arrows to show a new number replacing the root and bubbling down. |
Logarithmic Tree Depth |
Draw a tree of height log(K). Show operation traversing from root to leaf to represent $O(\log K)$ time. |
Dynamic Array (expanding block) for stream history (O(N)). |
Fixed-size Array/Tree of exactly K nodes (O(K)). |
| 704 |
Binary Search |
Linear Scan (for loop from start to end). |
Linear Tape Reading |
Draw an array. Point an arrow at index 0, cross it out, move to index 1, repeat. Time: $O(N)$. |
Two-Pointer Binary Search |
Shrinking Window / Pincers |
Draw array. Place L at start, R at end. Calculate M. If target > arr[M], move L to M+1. Keep halving the visual space. |
Draw array boxes. Use brackets [ ] for L and R, and an arrow pointing down at M. Cross out the discarded half. |
Halving Segment Lines |
Draw a line of length N. Below it, a line of N/2. Below that, N/4, until length 1. Write $O(\log N)$. |
Single variable box for the loop counter. |
Three variable boxes: L, R, M. (O(1) space). |
| 705 |
Design HashSet |
A massive boolean array of size 1,000,001 (direct addressing). |
Massive Grid |
Draw a giant grid representing 10^6 slots. Shade in the index when `add(key)` is called. $O(1)$ time but huge space. |
Chaining (Array of Linked Lists / BSTs) |
Buckets and Chains |
Draw an array of buckets (e.g., size 10^4). Hash the key. Go to bucket. Traverse the linked list inside the bucket to add/check. |
Draw a vertical array. From an index, draw horizontal arrows linking squares (Linked List nodes) representing collisions. |
Average vs Worst-Case graph |
Draw $O(1)$ as a flat line for average. Draw $O(N)$ as a diagonal line for worst-case (all keys in one bucket). |
A massive contiguous block of memory (O(Max_Value)). |
Array of pointers + dynamically allocated node boxes (O(N + K)). |
| 706 |
Design HashMap |
Massive array of size 1,000,001 storing values at the exact index of the key. |
Massive Grid |
Draw a massive continuous array block. Time is $O(1)$ but space is $O(10^6)$. |
Array of Linked Lists (Chaining) |
Buckets and Chains |
Hash key to get bucket index. Go to array[index]. Traverse linked list. Update if key exists, append if it doesn't. |
Draw a vertical array. From an index, draw horizontal boxes connected by arrows (Linked List nodes: [key|val|next]). |
Average vs Worst-Case graph |
Draw a graph. X-axis = elements, Y-axis = time. Draw flat line for $O(1)$ average, and a diagonal spike for $O(N)$ worst-case. |
Giant continuous memory array (O(Max_Key)). |
Array of pointers + scattered heap-allocated node boxes (O(N + K)). |
| 707 |
Design Linked List |
Use a standard dynamic array. Inserting/deleting requires shifting all elements. |
Shifting Blocks |
Draw array boxes. Show arrows shifting all elements one space to the right to make room at the head. $O(N)$ time. |
Doubly Linked List w/ Dummy Nodes |
Node Chaining with Prev/Next |
Place pointers at dummy head/tail. To insert at index `k`, step forward `k` times. Rewire `prev` and `next` of surrounding nodes. |
Draw boxes with 3 compartments (prev, val, next). Draw arrows connecting them forward and backward. Cross out old arrows to rewire. |
Node Hopping Traversal |
Draw N nodes. Loop an arrow over `k` nodes to visually represent $O(k)$ traversal time to reach the index. |
Contiguous block with potentially unused capacity. |
Scattered individual heap blocks connected by reference lines (O(N)). |
| 708 |
Insert into a Sorted Circular Linked List |
Dump all nodes to an array, sort the array, and rebuild the entire circular list. |
Array Sorting Pipeline |
Draw circle breaking into an array -> sorting $O(N \log N)$ -> forming back into a circle. |
Two-Pointer Ring Traversal |
Circular Ring ClockFace |
Place `prev` and `curr` adjacent. Rotate clockwise. Stop when `prev <= insert <= curr` or at the max-to-min boundary drop-off. |
Draw nodes in a circle connected by arrows. Use two colored markers for `prev` and `curr` rotating clockwise until finding the insertion gap. |
Single Loop Arc |
Draw a circle and an arrow tracing its perimeter exactly once to show $O(N)$ worst-case time. |
Extra array block of size N. |
Single newly allocated node box (O(1) extra space). |
| 709 |
To Lower Case |
Hash map mapping every uppercase char to its lowercase equivalent. |
Dictionary Lookup Table |
Draw a 2-column table A->a, B->b. Draw string chars pointing to the table $O(N)$. |
ASCII Bit Manipulation / Offset |
ASCII Value Shift |
Iterate string. If char is between 'A' (65) and 'Z' (90), add 32 to its ASCII value (or bitwise OR with 32) to make it lowercase. |
Write the word. Draw a downward arrow from an uppercase letter with "+32" written next to it, pointing to the new lowercase letter. |
Linear Scanning Line |
Draw a flat line progressing left-to-right over characters representing $O(N)$ time. |
Hash map memory overhead. |
In-place mutation (if string is mutable) or a new string builder array. |
| 710 |
Random Pick with Blacklist |
Pick random number [0, N-1]. If it's in the blacklist, reject and pick again (rejection sampling). |
Rejection Spinning Wheel |
Draw a loop spinning repeatedly until a white-listed number is hit. Highly unpredictable time. |
Hash Map Remapping (Virtual Array) |
Bipartite Remapping |
Valid range is `[0, N - len(B)]`. Any blacklisted number in this safe zone is mapped in a Hash Map to a safe number at the end of the array. |
Draw a line `[0, N)`. Draw a divider at `N - len(B)`. Draw arcs from blacklisted numbers on the left to safe numbers on the right. |
Direct Access Hit |
Draw a single point landing on an index to represent $O(1)$ guaranteed random access time. |
Hash Set storing blacklist (O(B)). |
Hash Map storing only the remapped indices (O(B)). |
| 711 |
Number of Distinct Islands II |
DFS to find all islands, manually rotate/reflect each grid 8 ways, and compare every pair. |
Pairwise Bounding Box Match |
Draw grids of shapes. Draw lines connecting every shape to every other shape to represent $O(N^2)$ comparisons. |
Canonical Hashing (DFS + Sort) |
Shape Normalization Pipeline |
DFS to extract coordinates. Translate shape so top-left is (0,0). Generate all 8 transforms. Sort them lexicographically. Pick the "smallest" string representation and add to a HashSet. |
Draw an island shape. Draw 8 arrows pointing to rotated/mirrored versions. Circle the one that sorts first alphabetically, draw an arrow dropping it into a "Set" bucket. |
Set Insertion Hit |
Draw an $O(R\cdot C)$ grid traversal path, plus an $O(K \log K)$ sorting funnel for the coordinate transformation. |
Giant 3D array or List of Lists for grid states. |
HashSet box containing canonical string representations (O(R*C)). |
| 712 |
Minimum ASCII Delete Sum for Two Strings |
Recursively generate all subsequences of both strings to find common ones, track max ASCII sum. |
Exponential Decision Tree |
Draw a binary tree. Each node splits into "keep" or "delete" a character, branching out 2^N. |
Dynamic Programming (LCS Variant) |
2D DP Grid Fill |
Create a 2D array. `dp[i][j]` = min delete sum. If `s1[i] == s2[j]`, take diagonal `dp[i-1][j-1]`. Else, take `min(dp[i-1][j] + s1[i], dp[i][j-1] + s2[j])`. |
Draw a grid. s1 on top, s2 on left. Fill base cases (cumulative ASCII). Fill cells using arrows pointing from Top, Left, and Top-Left. |
Grid Area Shading |
Draw a rectangle of size M x N. Shade the entire area left-to-right, top-to-bottom to show $O(M\cdot N)$ time. |
Deep call stack memory frames $O(M+N)$. |
2D grid block $O(M\cdot N)$ or two 1D array rows $O(\text{min}(M,N)$). |
| 713 |
Subarray Product Less Than K |
Nested loops. For every starting index, multiply numbers sequentially until the product >= k. |
Nested Iteration Bracket |
Draw the array. Draw a bracket starting at 0 expanding right. Then a new bracket at 1 expanding right. $O(N^2)$. |
Sliding Window |
Caterpillar / Accordion Window |
Start Left=0, Right=0. Multiply `product *= arr[Right]`. While `product >= k`, divide by `arr[Left]` and move Left forward. Add `Right - Left + 1` to total. |
Draw the array. Draw a box around [L, R]. Use a green right-pointing arrow for R expanding, and a red right-pointing arrow for L contracting when the limit is breached. |
Two Independent Trackers |
Draw an array line of length N. Draw two markers (L, R) traversing it strictly left-to-right. $O(N)$ time. |
Single counter variable. |
Three integer boxes (Left, Right, Product) - $O(1)$ space. |
| 714 |
Best Time to Buy and Sell Stock with Transaction Fee |
Explore all possible daily decisions: Buy, Sell, or Skip, via recursion. |
Full State Space Tree |
Draw a tree starting at Day 1, branching into 3 options every single day. Time: $O(3^N)$. |
State Machine DP / Greedy |
Two-State Machine Diagram |
Track `cash` (max profit not holding) and `hold` (max profit holding). `cash = max(cash, hold + price - fee)`, `hold = max(hold, cash - price)`. Update daily. |
Draw two circles labeled "Holding" and "Not Holding". Draw looped arrows on them (skip), and arrows between them (+price-fee, -price). Write updated values next to them. |
Linear State Progression |
Draw a straight timeline. At each tick, update two values simultaneously showing $O(N)$ time. |
Massive call stack for recursion. |
Two integer variable boxes (`cash`, `hold`) - $O(1)$ space. |
| 715 |
Range Module |
A massive boolean array mapping out up to 10^9 values. True = tracked, False = not tracked. |
Infinite Tape |
Draw a giant array block. Shading/erasing ranges requires touching every index sequentially. $O(N)$ per query. |
Interval Merging / Segment Tree (TreeMap) |
Sweep Line / Overlapping Bars |
Use an Ordered Map (BST) where keys=left bound, values=right bound. On `add`, find overlapping intervals and merge left/right limits. On `remove`, split overlapping limits. |
Draw a number line. Draw horizontal bars for tracked ranges. When a new range is added, draw it overlapping, then erase the inner lines to merge them into one solid bar. |
Logarithmic Tree Update |
Draw a balanced Binary Search Tree. Highlight a path from root to node showing $O(\log N)$ lookup and update times. |
Memory Limit Exceeded (Boolean array of 10^9). |
Tree nodes representing disjoint intervals $O(K)$. |
| 716 |
Max Stack |
Use two standard arrays/stacks. For `popMax()`, pop elements to a temporary stack until max is found, remove it, then push back. |
Pancake Shuffling |
Draw a vertical stack of blocks. Draw arrows moving top blocks to a second stack, pulling out the max, and moving blocks back. $O(N)$. |
Doubly Linked List + TreeMap (or Lazy Deletion PQ) |
Dual-Indexed Structure |
Add elements to both a DLL (for strict insertion order) and a TreeMap (value -> list of DLL nodes). `popMax()` gets the max from TreeMap, removes the node from DLL directly in $O(\log N)$. |
Draw a horizontal DLL. Above it, draw a BST (TreeMap). Draw dashed lines from the BST nodes pointing directly to their corresponding DLL blocks. |
Logarithmic Map Lookup |
Draw a tree traversal path highlighting $O(\log N)$ time to find and delete the max element. |
Two standard arrays/stacks (O(N)). |
DLL nodes + TreeMap overhead (O(N) space, higher constant). |
| 717 |
1-bit and 2-bit Characters |
Backtracking to generate all valid groupings of `0`, `10`, and `11` to see if the string can end perfectly on a `0`. |
Decision Tree |
Draw a tree branching into 1-step (if 0) and 2-step (if 1) paths. Time: $O(2^N)$. |
Greedy Pointer / Linear Jump |
Array Hopping |
Start `i = 0`. If `arr[i] == 1`, jump `i += 2` (must be a 2-bit char). If `arr[i] == 0`, jump `i += 1`. Stop when `i >= n - 1`. If `i == n - 1`, the last char is isolated. |
Draw the array. Draw arcs hopping from index to index. A jump from '1' covers two boxes; a jump from '0' covers one box. Target the last index. |
Single Pass Flatline |
Draw a straight horizontal line touching indices sequentially, representing strict $O(N)$ time. |
Call stack memory for recursion $O(N)$. |
Single index pointer variable `i` (O(1)). |
| 718 |
Maximum Length of Repeated Subarray |
Generate all subarrays of A and check if they exist in B. |
Massive String Overlap |
Draw an exhaustive list of all N^2 subarrays of A, sliding them against M^2 subarrays of B. $O(N^3)$ time. |
Dynamic Programming (2D) |
2D Grid Diagonal Streaks |
Create `dp[N+1][M+1]`. If `A[i] == B[j]`, `dp[i][j] = dp[i-1][j-1] + 1`. Track the global maximum. The DP builds diagonal streaks of matches. |
Draw a grid. A on top, B on left. Whenever row == col char, draw an arrow from Top-Left diagonal, add 1. Highlight the longest uninterrupted diagonal chain. |
Grid Area Shading |
Shade the entire M x N grid exactly once to visually prove $O(M\cdot N)$ time complexity. |
Variables to hold thousands of temporary subarray strings. |
A 2D array matrix block (O(M*N)), optimizable to 1D array row (O(M)). |
| 719 |
Find K-th Smallest Pair Distance |
Nested loops to generate all pair distances, store them in a list, and sort them. |
Complete Graph to Funnel |
Draw dots for every array element. Draw lines connecting every single dot to every other dot. Pipe them into a sorting funnel. $O(N^2 \log N)$. |
Binary Search on Distance + Sliding Window |
Ruler Search + Caterpillar Window |
Sort array. Binary search the *answer* (distance from 0 to max_dist). For a mid distance, use a sliding window to count how many pairs have distance <= mid. Adjust bounds based on K. |
Draw a number line (0 to max diff) for Binary Search. Below it, draw the sorted array. Use a bracket [L, R] expanding as long as `arr[R] - arr[L] <= mid`, counting valid pairs. |
Log(W) x N Overlap |
Draw a halving line for distance range W (O(log W)). For each half, draw a flat $O(N)$ sweep line to represent the sliding window check. |
Massive array storing N(N-1)/2 distance values. |
In-place sorted array + counter variables (O(1) extra space). |
| 720 |
Longest Word in Dictionary |
Sort words. For each word, generate every single prefix and check if it exists in a HashSet. |
Prefix Chopping Block |
Draw a long word. Draw a knife chopping off the last letter repeatedly, checking a Set bucket every time. Time: $O(Σ(L^2)$). |
Trie (Prefix Tree) + DFS/BFS |
Branching Rooted Tree |
Insert all words into a Trie. Mark end of valid words. Run DFS/BFS from root. Only traverse down paths where every node is a valid "end of word". Keep track of the longest string found. |
Draw a root node. Draw branches dropping down, letter by letter. Color the nodes green if they complete a dictionary word. Trace the deepest path of all green nodes. |
Tree Depth Plumb Line |
Draw a line plunging from the root to the deepest valid leaf node to represent time proportional to word lengths $O(ΣL)$. |
HashSet of all words (O(ΣL)). |
Trie Node object tree (O(ΣL) space, but with shared prefix overlap saving some memory). |
| 721 |
Accounts Merge |
Compare every account against every other account for common emails, repeatedly until no more merges occur. |
Complete Bipartite Graph |
Draw N account boxes. Draw messy overlapping lines checking every string against every other string. $O(N^2 \cdot M^2)$ time. |
Disjoint Set Union (DSU) / Union-Find |
Connected Components Forest |
Map every email to an integer ID. Iterate accounts: union all emails in the same account. Group all emails by their DSU root, sort them, and attach the account name. |
Draw emails as circular nodes. Draw edges connecting emails from the same account. Circle the resulting disconnected clusters (components) to represent merged accounts. |
Inverse Ackermann Flatline |
Draw a nearly flat horizontal line for DSU operations, followed by an $O(\text{NK} \\text{log NK})$ sorting funnel for the final grouping. |
Massive nested arrays duplicating strings. |
Hash Maps for `email -> ID` and DSU parent arrays (O(NK)). |
| 722 |
Remove Comments |
Regex replacements or splitting the entire string by comment tags, which fails on complex overlapping cases. |
Text Block Blackout |
Draw a massive block of text. Draw thick black marker strokes aggressively crossing out chunks, missing overlapping edge cases. |
State Machine / Deterministic Parsing |
Toggle Switch State Diagram |
Read char by char. Track boolean `in_block`. If false, check for `//` (skip line) or `/*` (set `in_block = true`). If true, check for `*/` (set `in_block = false`). Else, append char. |
Draw two circles: "Normal" and "In Comment". Draw arrows between them triggered by `/*` and `*/`. Draw a trash can for the `//` line skip. |
Linear Tape Reading |
Draw a straight line representing the source code length. An arrow moves purely left-to-right representing $O(N)$ strict time. |
Deep copies of the entire file string per pass. |
Output string builder array and one boolean variable (O(N) space). |
| 723 |
Candy Crush |
Scan grid, crush any 3+, then do a full 2D array shift to drop candies. Repeat until stable. |
Multi-pass Grid Scan |
Draw a grid. Draw arrows looping over every cell horizontally, then vertically, over and over. Very slow $O((R\cdot C)$^2). |
In-place State Flagging & Two-Pointer Drop |
Falling Sand / Gravity Columns |
1. Scan rows/cols. If 3+ match, negate their values (mark). 2. For each column, use read/write pointers bottom-up. Keep positive numbers, skip negatives. Fill top with 0s. Repeat if board changed. |
Draw a single column. Write numbers. Circle negative values. Draw a heavy arrow pushing positive numbers to the bottom, leaving zeros at the top. |
Matrix Sweeps |
Draw the matrix. Draw horizontal sweep arrows, then vertical sweep arrows. Enclose in a loop arrow to represent worst-case $O((R\cdot C)$^2) time. |
Deep copies of the 2D grid for every single simulation step. |
In-place value negation (O(1) extra space). |
| 724 |
Find Pivot Index |
For every index, recalculate the sum of the entire left subarray and right subarray from scratch. |
Double Balance Scales |
Draw a balance scale for index 0, recalculate all blocks. Move to index 1, recalculate everything. $O(N^2)$ time. |
Prefix Sum / Total Sum Tracking |
Running Water / Transferable Weight |
Calculate `total_sum`. Track `left_sum = 0`. Iterate array. `right_sum = total_sum - left_sum - nums[i]`. If `left_sum == right_sum`, return index. Else `left_sum += nums[i]`. |
Draw an array. Write the total sum. Move an arrow `i`. Keep a running tally of the left side. Visually subtract (left + current) from total to find the right side. |
Single Pass Timeline |
Draw an array block with a single arrow sweeping exactly once left-to-right. $O(N)$ time. |
$O(1)$ space, but terrible $O(N^2)$ time profile. |
Two integer boxes: `left_sum` and `total_sum` (O(1) space). |
| 725 |
Split Linked List in Parts |
Dump list to an array, mathematically slice the array, and rebuild K brand new linked lists. |
Array Chopping Block |
Draw nodes mapping to an array, chopping the array into pieces, and drawing new arrows to rebuild. $O(N)$ space. |
Length Counting + Mathematical Chunking |
Measuring Tape & Scissors |
Count length `N`. Base size = `N / k`, Extra nodes = `N % k`. Iterate list. First `Extra` parts get `Base + 1` nodes. Remaining get `Base`. Snip the `next` pointers to `null`. |
Draw a linked list. Write N and K. Calculate Base and Remainder. Draw scissors cutting the links exactly at the calculated step counts to sever the lists. |
Two-Pass Track |
Draw the list. Draw one faint arrow traversing all the way (count), and a second bold arrow stopping and cutting (split). $O(N + K)$ time. |
$O(N)$ array allocation to store intermediate nodes. |
$O(K)$ output array holding the new head pointers, $O(1)$ extra auxiliary space. |
| 726 |
Number of Atoms |
String expansion: Replace `(H2O)2` with `H2OH2O` literally in the string, then count characters. |
Exploding String Balloons |
Draw a small string expanding into a massive, repetitive string. $O(\text{Exponential})$ for nested brackets. |
Recursion / Stack with HashMaps |
Nested Russian Dolls |
Use a stack of HashMaps. When `(` is met, push a new map. When `)` is met, pop current map, multiply all counts by the following number, and merge into the previous map. |
Draw vertical boxes (Stack). Inside each box, write a mini-table (Map). Use arrows to show "bubbling up" and multiplying counts when a box is removed. |
Parser Progression |
Draw a line through the formula string. Each character is processed once. $O(N^2)$ worst-case due to map merging. |
Massive expanded string (unbounded). |
Stack of Map objects proportional to nesting depth (O(N)). |
| 727 |
Minimum Window Subsequence |
Generate every possible substring of S and check if T is a subsequence within it using two pointers. |
Exhaustive Window Search |
Draw S. Draw brackets for every single possible `start` and `end` point. $O(N^3)$ check. |
Dynamic Programming (2D) or Two-Pointer Slide |
Synchronized Sliding Cogs |
Find a valid end-point for T in S. Then, work backwards from that end-point to find the best (rightmost) start-point. Compare lengths and slide forward. |
Draw two strings S and T. Draw a forward-moving arrow for S. When T is completed, draw a backward-moving arrow from the current S-position to minimize the window. |
Zig-Zag Scan |
Draw a line representing S. Draw "Z" shaped arrows moving forward then slightly back, showing $O(N \cdot T)$ total coverage. |
List of thousands of substring candidates. |
A 2D DP table (O(N*T)) or two 1D rows for space optimization (O(N)). |
| 728 |
Self Dividing Numbers |
Convert every number to a string to iterate through digits, check divisibility. |
Type Casting Pipeline |
Draw a number entering a "String Converter" box, then breaking into a char array. $O(N \\text{cdot Number of Digits})$. |
Modulo Digit Extraction |
Digit Stripping / Peeling |
For a number `val`, use `val % 10` to get the last digit and `val / 10` to remove it. Check `original % digit == 0` for each. |
Write a number (e.g., 128). Draw an arrow peeling off '8', then '2', then '1'. Check each against 128. |
Digit Bound Curve |
Draw a curve that flattens out (Logarithmic). Each number takes $O(\log10(N)$) time to check. Total $O(N \log N)$. |
String object creation per number. |
No extra space; integer arithmetic only (O(1) extra). |
| 729 |
My Calendar I |
Keep a list of pairs. For every new booking, check it against every existing booking for overlaps. |
Linear Collision Grid |
Draw a timeline. For each new segment, draw lines comparing it to every previous segment on the chart. $O(N^2)$. |
Balanced BST / TreeMap (Ordered Map) |
Interval Slotting |
Find the "floor" (booking starting before/at new) and "ceiling" (booking starting after). Check if the new interval overlaps with either neighbor. |
Draw a number line with existing bars. Draw the new bar. Draw arrows to the immediate left bar and immediate right bar only. |
Tree Depth Strike |
Draw a BST. Highlight the path to the insertion point, representing $O(\log N)$ search time. |
Standard Array/List (O(N)). |
Balanced Tree Structure (O(N) nodes, $O(\log N)$ access). |
| 730 |
Count Different Palindromic Subsequences |
Generate all possible subsequences of the string, check if each is a palindrome, and store in a HashSet to count unique ones. |
Exponential Subsequence Tree |
Draw a tree branching 2^N times. Each leaf represents a unique subsequence. $O(2^N \cdot N)$. |
Dynamic Programming (2D Range DP) |
Interval Expansion Matrix |
`dp[i][j]` counts unique palindromic subsequences in `S[i...j]`. If `S[i] == S[j]`, the count relates to the inner range `dp[i+1][j-1]` with boundary adjustments. |
Draw the string. Draw a square grid. Fill the diagonal (single letters). Fill the cells above the diagonal by looking at the "inner" range cells. |
Upper Triangle Shading |
Shade the upper-right triangle of a square matrix. Total operations $O(N^2)$. |
Massive HashSet storing millions of strings. |
2D DP matrix (O(N^2)) or optimized 3D for character sets (O(4 * N^2)). |
| 731 |
My Calendar II |
Maintain a list of all bookings. For a new booking, check if it triple-overlaps by comparing against every pair of existing overlaps. |
Nested Pairwise Comparison |
Draw a timeline with segments. Draw arcs connecting every pair of overlapping segments to the new entry. $O(N^2)$. |
Sweep Line Algorithm (TreeMap) |
Time-Point Delta Mapping |
Mark `start` as +1 and `end` as -1 in a sorted map. Iterate through the map, maintaining a `running_sum`. If it ever exceeds 2, the booking is invalid. |
Draw a horizontal line. Mark points with +1 and -1. Draw a "water level" line that rises and falls as you move right. |
Linear Scan of Sorted Map |
Draw a sorted set of X-coordinates. Show a single pass through these coordinates. $O(N)$. |
List of interval pairs. |
Balanced BST / TreeMap storing discrete time points (O(N)). |
| 732 |
My Calendar III |
Re-calculate the maximum overlap for the entire timeline every time a new booking is added. |
Brute Force Layering |
Draw a timeline. Every time a segment is added, re-scan the whole line to count the "tallest" stack of segments. $O(N^2)$. |
Segment Tree with Lazy Propagation |
Hierarchical Range Coverage |
Use a segment tree to represent the timeline. For each `book(start, end)`, update the range in the tree. The root always stores the max k-booking. |
Draw a tree where the root covers [0, 10^9]. Draw child nodes covering halves. Shade the paths representing the new interval. |
Logarithmic Range Update |
Draw a tree of height log(Range). Highlight the path from root to the specific range. $O(\log N)$. |
A massive array representing every possible time unit. |
Dynamic Segment Tree nodes (allocated only as needed) or TreeMap (O(N)). |
| 733 |
Flood Fill |
Iterate through every single pixel in the grid. If it has the starting color and is "reachable," change it. |
Full Grid Exhaustion |
Draw a grid. Draw an arrow touching every single cell (R*C) to check connectivity. |
Depth-First Search (DFS) / BFS |
Spreading Ripple / Infection |
Start at `(sr, sc)`. Visit 4-way neighbors. If neighbor color == original color, change it and recurse. Use a "visited" check. |
Draw a grid. Start at a cell. Draw arrows to neighbors. Color the cells as you go. Use an "X" for cells that don't match. |
Connected Component Traversal |
Draw an irregular shape within the grid. Trace a single path that visits each cell in the shape once. $O(N)$. |
Implicitly large grid copies. |
Recursion Stack frames (DFS) or Queue (BFS) - $O(N)$ where N is pixels. |
| 734 |
Sentence Similarity |
For every word pair in the sentences, iterate through the entire similarity list to find a match. |
Nested Search Loop |
Draw two sentences. For word index `i`, draw a loop searching through the whole dictionary. $O(N \cdot S)$. |
Hash Set of Pair Strings |
Instant Lookup Table |
Store all similar pairs in a HashSet as "word1#word2". For each index `i` in the sentences, check if `s1[i]==s2[i]` or if the set contains the pair. |
Draw two lists (sentences). Draw a "Black Box" (Set). Point word pairs to the box; it returns a green check or red X instantly. |
Parallel Linear Scan |
Draw two parallel lines (sentences). Draw vertical "lookups" at each point. Total time $O(N + S)$. |
Multiple copies of similarity lists. |
A single HashSet containing all unique similarity pairs (O(S)). |
| 735 |
Asteroid Collision |
Repeatedly scan the array for any `[positive, negative]` adjacent pairs and simulate their collision. Repeat until no pairs left. |
Scanning Collision Ripples |
Draw an array. Circle a pair, erase it, re-scan from the beginning. $O(N^2)$. |
Monotonic Stack |
One-Way Tunnel Simulation |
Iterate asteroids. If moving right (+), push to stack. If moving left (-), collide with stack top until stack is empty or asteroid explodes. |
Draw a vertical stack. Show asteroids entering. If a "left" asteroid hits a "right" asteroid on the stack, show one (or both) disappearing. |
Single Pass Amortized |
Draw a line of asteroids. Show each asteroid being "pushed" or "popped" exactly once. $O(N)$. |
Multiple temporary arrays for each "round" of collisions. |
A single stack storing the surviving asteroids (O(N)). |
| 736 |
Parse Lisp Expression |
String replacement of variables followed by multiple passes of evaluation. |
Recursive String Mutation |
Draw a string physically expanding and contracting as variables are "pasted" in. $O(N^2)$ or worse. |
Recursive Descent Parser + Scoped Symbol Table |
Abstract Syntax Tree (AST) with Scopes |
Parse tokens. Maintain a stack of HashMaps (scopes). If `let`, add to current map. If `evaluate`, look up in stack from top to bottom. |
Draw a tree of nodes (add, mult, let). Next to each node, draw a small box (HashMap) for variables valid only in that branch. |
Tree Traversal Linearization |
Draw a line through the expression. Each character is visited once by the parser. $O(N)$ time. |
Deep copies of strings for every sub-expression. |
Stack of Map objects representing lexical scoping (O(N)). |
| 737 |
Sentence Similarity II |
For every word pair, perform a full BFS/DFS on the similarity graph to see if they are connected. |
Repeated Graph Search |
Draw N word pairs. For each, draw a spider-web search across a graph of thousands of words. $O(N \cdot (V+E)$). |
Disjoint Set Union (DSU) |
Connected Island Groups |
Pre-process similarities. Union(word1, word2). For each word pair in sentences, check if `find(s1[i]) == find(s2[i])`. |
Draw words as dots. Draw lines for similarities. Circle each cluster. Check if two sentence words fall in the same circle. |
Inverse Ackermann Flatline |
Draw a flat line representing the nearly constant time $O(α(V)$) for DSU lookups. Total $O(N + V)$. |
Recursive call stack for every single word comparison. |
Parent array/map for DSU (O(V) where V is unique words). |
| 738 |
Monotone Increasing Digits |
Iterate backwards from N to 0, checking every single number to see if its digits are non-decreasing. |
Linear Count-Down |
Draw a number line. Start at N and tick backwards one by one, checking digits at every step. $O(N \cdot \log N)$. |
Greedy Digit Manipulation |
The "Cliff" Correction |
Scan digits left-to-right. Find the first "cliff" where `digits[i] > digits[i+1]`. Decrement `digits[i]`, then turn all following digits to '9'. Re-check back for cascading cliffs. |
Write the number. Circle the first digit that is larger than its neighbor. Draw an arrow changing it to -1 and arrows changing all right-side digits to 9. |
Single Pass Sweep |
Draw the digits as a line. Draw one arrow moving left-to-right to find the cliff, and one moving right-to-left to fix it. $O(Log N)$. |
$O(1)$ if not counting the string conversion. |
Char array of digits (O(Log N)). |
| 739 |
Daily Temperatures |
For each day, use a nested loop to look forward until a warmer temperature is found. |
Nested Forward Scanning |
Draw a temperature list. For the first item, draw an arrow looking right until a hit. Repeat for all items. $O(N^2)$. |
Monotonic Decreasing Stack |
Wait-List Management |
Iterate temperatures. While current temp > stack top, pop stack top and calculate difference (today - day_it_was_recorded). Push current day to stack. |
Draw a vertical stack. Place colder days inside. When a "hot" day comes, show it "kicking out" the colder days below it and writing the result. |
Amortized Linear Flow |
Draw a line of numbers. Show each number being pushed/popped once. Total time $O(N)$. |
N/A (Standard nested loop overhead). |
Stack of indices (O(N) worst case for strictly decreasing temps). |
| 740 |
Delete and Earn |
Recursively try taking or skipping every number, checking the constraints (delete x-1 and x+1) each time. |
Decision Tree Explosion |
Draw a binary tree. Each level is a number: "Take" or "Skip". Branching factor 2^N. |
Dynamic Programming (House Robber Variation) |
Bucket Progression |
Count frequencies of each number. Transform into a `sum` array where `index` is the number and `value` is `count * number`. Apply House Robber logic: `dp[i] = max(dp[i-1], dp[i-2] + sum[i])`. |
Draw buckets labeled 1, 2, 3... Fill with total points. Use arrows to show jumping to the next-next bucket to maximize points. |
Linear Array Shading |
Draw a horizontal array of point totals. Shade left-to-right exactly once. $O(N + \text{Max}_\text{Val})$. |
Massive recursion stack (O(N)). |
Frequency array/map and two DP variables (O(Max_Val)). |
| 741 |
Cherry Pickup |
Find the best path from (0,0) to (N-1,N-1), pick cherries, then find the best path back. |
Two-Pass Path Greedy |
Draw a grid. Trace one path with a pen, erase cherries, then trace a second path. $O(\text{Exponential})$ to find *global* max. |
3D Dynamic Programming (Simultaneous Path) |
Parallel Movement Sync |
Two people start at (0,0) and move `t` steps simultaneously. If they land on the same cell, cherries are counted once. Move state: `dp[t][r1][r2]`. |
Draw a grid. Draw two different colored dots. Move them together step by step (right/down). Write the cherry count sum at each "step" layer. |
Pruned State Cube |
Draw a cube representing N^3 states. Shade the volume representing valid (r1, r2, step) combinations. $O(N^3)$. |
Massive recursion stack for all path combinations. |
3D array (or 2D optimized) of size N \times N \times N. |
| 742 |
Closest Leaf in a Binary Tree |
Find the target node, then search all children for a leaf. For parent paths, re-traverse from root for every node. |
Multi-pass Tree Traversal |
Draw a tree. From target, draw arrows down. Then go back to root and scan other branches. $O(N^2)$. |
Graph Conversion + BFS |
Undirected Web Expansion |
Convert the tree into an undirected graph (nodes point to children AND parents). Start a BFS from the target node. The first leaf node reached is the closest. |
Draw the tree. Add "upward" arrows to parents. Start a "circular ripple" from the target node that expands to neighbors until it hits a leaf. |
Radial Ripple Search |
Draw the graph. Draw concentric circles around the target. Each circle represents a BFS level. $O(N)$. |
Adjacency list plus multiple recursion stacks. |
Adjacency Map + Queue for BFS (O(N)). |
| 743 |
Network Delay Time |
DFS to explore every single possible path from K to every other node, tracking the minimum time. |
Exponential Path Exploration |
Draw nodes and edges. Draw arrows spinning through every possible cycle and path. $O(V^V)$. |
Dijkstra’s Algorithm (Min-Priority Queue) |
Expanding Frontier / Dijkstra's Reach |
Maintain `dist` map. Use a Min-Heap of `(time, node)`. Always expand the node with the shortest known time. Update neighbors if a shorter path is found. |
Draw nodes with labels "∞". Start at K with "0". Circle the smallest neighbor, update its "∞" to a number, and repeat like a spreading stain. |
Logarithmic Expansion Curve |
Draw a graph where edges are processed. Write E \log V next to the priority queue operations. |
Set of all path strings. |
Min-Heap array and a distance dictionary (O(V + E)). |
| 744 |
Find Smallest Letter Greater Than Target |
Linear scan through the array until a character > target is found. |
Linear Tape Scan |
Draw a row of letters. Move an arrow one box at a time from left to right. $O(N)$. |
Binary Search (Left-most target) |
Shrinking Boundaries |
Use `low` and `high`. If `letters[mid] <= target`, `low = mid + 1`. Return `letters[low % n]` to handle the wrap-around case. |
Draw the array. Use two brackets `[ ]`. Show the brackets jumping to the middle and cutting the search space in half each time. |
Binary Search Funnel |
Draw a line of length N, then N/2, then N/4. Write $O(\log N)$ at the bottom. |
N/A (single loop counter). |
Two integer variables for pointers (O(1)). |
| 745 |
Prefix and Suffix Search |
For every query, loop through the dictionary and use `.startsWith()` and `.endsWith()` on every word. |
Dictionary Scan Pipeline |
Draw a dictionary book. For every query, flip through every page and check both ends of every word. $O(N\cdot L)$ per query. |
Trie of Combined Strings (suffix + \{ + prefix) |
Super-String Trie Index |
Insert each word multiple times: for "apple", insert "#apple", "e#apple", "le#apple"... into a Trie. Query for `suffix + # + prefix`. |
Draw a Trie. For word "apple", show nodes for "e#apple". When searching for prefix "ap" and suffix "e", look up "e#ap". |
Direct Trie Path Search |
Draw a single path down a Trie. The length is proportional to the query string, not the dictionary size. $O(L)$ per query. |
N/A (Simple list). |
A massive Trie structure storing L^2 combinations per word (O(N * L^2)). |
| 746 |
Min Cost Climbing Stairs |
Recursively explore every possible combination of 1-step and 2-step jumps to reach the top. |
Exponential Binary Tree |
Draw a tree starting at step 0, branching into (1, 2). Each node branches again. $O(2^N)$. |
Dynamic Programming (Space Optimized) |
Step-by-Step Accumulation |
Maintain two variables: `prev1` and `prev2`. For each new step, `curr = cost[i] + min(prev1, prev2)`. Slide the values forward. |
Draw a staircase. Write the cost on each step. Draw two arrows from the two previous steps to the current one, choosing the smaller number. |
Linear Accumulation Line |
Draw a straight line through the steps. Each step is visited once. $O(N)$. |
Deep recursion stack (O(N)). |
Two integer variable boxes (O(1)). |
| 747 |
Largest Number At Least Twice of Others |
Sort the array, check if the last element is at least double the second to last. |
Sorting Funnel |
Draw an unsorted array being poured into a "Sort" box. $O(N \log N)$. |
Single Pass Max Tracking |
King of the Hill |
Keep track of the `largest` and `secondLargest` numbers found so far in one loop. Finally, check if `largest >= 2 * secondLargest`. |
Draw a leaderboard with two slots. As you scan the array, update the slots. Draw a final "comparison" scale at the end. |
Single Linear Sweep |
Draw an array with a single arrow moving left to right. $O(N)$. |
Full copy of the array for sorting (O(N)). |
Two integer variables for indices/values (O(1)). |
| 748 |
Shortest Completing Word |
For every word in the dictionary, create a frequency map and compare it letter-by-letter with the license plate map. |
Nested Map Comparison |
Draw the license plate map. Draw a loop that creates and compares a map for every word. $O(\text{Words} \\text{cdot Avg}_\text{Length})$. |
Prime Product Hashing or Frequency Array |
Letter Inventory Check |
Convert license plate to a 26-slot frequency array. For each word, subtract its letters from a copy of the array. If all plate requirements are met, it's a candidate. |
Draw a checklist based on the license plate. For each word, check off letters. Circle the shortest word that finishes the checklist. |
Linear Scan with Constant Overhead |
Draw a list of words. Next to it, draw a fixed-size 26-box array being used repeatedly. $O(N)$. |
Multiple map objects (high overhead). |
A fixed 26-integer array (O(1) constant space relative to alphabet). |
| 749 |
Contain Virus |
Simulate the virus spread day by day. Check every region, identify the most dangerous, and wall it off. |
Iterative Simulation Grids |
Draw a series of grids (Day 1, Day 2...). For each, scan every cell to find connected components. $O((R\cdot C)$^2). |
Greedy Simulation with BFS/DFS |
Priority Infection Containment |
Use BFS to find all disconnected virus regions. For each, calculate "walls needed" and "uninfected neighbors". Contain the one with most neighbors. Repeat. |
Draw a grid with clusters of 'V'. Draw a thick boundary around the most "aggressive" cluster. Draw arrows showing other clusters expanding. |
Simulation Complexity Curve |
Draw a grid being filled. Each "Day" loop touches the grid multiple times. $O(\text{Days} \cdot R \cdot C)$. |
Multiple copies of the grid for each simulation step. |
Visited sets and queue for BFS (O(R*C)). |
| 750 |
Number Of Corner Rectangles |
Iterate through every possible combination of 4 cells and check if they all contain '1's. |
Combinatorial Search |
Draw a grid. Draw rectangles connecting any 4 points. $O(N^4)$ or $O(R^2 \cdot C^2)$. |
Row-Pair Comparison (DP-lite) |
Parallel Line Scanning |
Compare every pair of rows `(i, j)`. For each column `k`, if `grid[i][k] == 1` and `grid[j][k] == 1`, increment a counter `count`. Add `count * (count - 1) / 2` to total. |
Draw two horizontal rows. Highlight columns where both have a '1'. Count these "matches" and use the formula to find rectangles. |
Row-Pair Matrix Shading |
Draw the matrix. Draw two sliding horizontal bars (rows). For each position, scan columns. $O(R^2 \cdot C)$. |
N/A. |
$O(1)$ auxiliary space (excluding input). |
| 751 |
IP to CIDR |
Convert IP to long, increment one by one, and for each single IP, find the largest possible valid CIDR block. |
Step-by-Step Block Matching |
Draw a line of dots (IPs). Circle the first one, check size, move. Circle the next, check size. $O(N)$. |
Greedy Bit Manipulation (Trailing Zeros) |
Binary Alignment Partitioning |
Convert IP to `long`. Find the lowest set bit using `x & -x`. This tells you the largest block size possible at that boundary. Take `min(count, bit_limit)` and move IP. |
Write the IP in binary. Point an arrow to the rightmost '1'. Draw a box around the trailing zeros to show the block size capacity. |
Logarithmic Jump Line |
Draw a line from start IP to end. Draw large arcs for large blocks and small arcs for small blocks. $O(\log N)$. |
Array of strings for every individual IP. |
List of CIDR strings (O(log N)). |
| 752 |
Open the Lock |
DFS to explore every single possible combination of dials, ignoring dead-ends, to find the shortest path. |
Exponential Depth Tree |
Draw a tree starting at "0000". Each level branches into 8 possibilities (up/down for 4 dials). $O(10^4)$. |
Breadth-First Search (BFS) / Bidirectional BFS |
Radial Expansion Wavefront |
Start BFS from "0000". Add neighbors to queue. If neighbor is in `deadends`, skip. First time hitting `target` is the shortest path. |
Draw a circle "0000". Draw 8 lines out to level 1. From each, draw more lines. Cross out "dead" circles. Shade the layers until target hit. |
Level-Order Growth |
Draw concentric circles around the start. Each circle represents one "move." $O(10^D + B)$ where D is dials. |
Recursion stack frames (could hit limit). |
Queue for BFS + HashSet for visited/deadends (O(10,000)). |
| 753 |
Cracking the Safe |
Generate every possible string of length (k^n + n - 1) and check if all combinations exist. |
Random Search / Permutation Scan |
Draw a massive string. For every substring, check a list of all k^n permutations. $O(k^n!)$. |
Hierholzer’s Algorithm (Eulerian Path) |
Directed Graph Cycle Circuit |
Treat each sequence of length n-1 as a node. An edge exists for each digit 0..k-1. Find a path that visits every edge exactly once. |
Draw nodes (e.g., "00", "01"). Draw k arrows leaving each node. Follow arrows without repeating until all edges are used. |
Graph Edge Traversal |
Draw a graph with V=k^{n-1} nodes and E=k^n edges. Show the path touching each edge once. $O(k^n)$. |
Massive set of all possible string combinations. |
Recursive stack and a StringBuilder to store the path (O(k^n)). |
| 754 |
Reach a Number |
BFS to find the shortest path from 0 to target by moving +k or -k at each step k. |
Binary Decision Tree |
Draw a tree starting at 0. Step 1: (-1, 1). Step 2: (-1-2, -1+2, 1-2, 1+2). $O(2^N)$. |
Mathematical Greedy + Parity Check |
Target Overlap Calculation |
Sum integers 1+2+3...+k until the sum S \ge target. If (S - target) is even, k is the answer. If odd, increment k until it becomes even. |
Draw a number line. Draw arcs moving only right. Calculate the "gap" between current position and target. Check if gap is divisible by 2. |
Square Root Curve |
Draw a parabolic curve y = x^2/2. The solution is approximately $O(\text{sqrt}(\text{Target})$). |
Queue for BFS growing exponentially. |
$O(1)$ space (just mathematical variables). |
| 755 |
Pour Water |
Simulate water movement by checking every possible position in the array for every single drop. |
Exhaustive Scan Simulation |
Draw the heights. For each drop, draw an arrow scanning the entire array twice (left then right). $O(\text{Drops} \cdot N)$. |
Two-Pointer Greedy Simulation |
Gravity Pathfinding |
For each drop: 1. Move left as far as possible (downhill or flat). 2. If left is same as start, move right as far as possible. 3. Place drop at the best index found. |
Draw a bar chart. Use a pen to "trace" the path of a drop: slide down left slopes, if stuck, slide down right slopes. If trapped, stay. |
Linear Scan Per Drop |
Draw a bar chart with an arrow moving left then right for each drop. $O(\text{Drops} \cdot N)$. |
N/A. |
$O(1)$ auxiliary space beyond the input array. |
| 756 |
Pyramid Transition Matrix |
Try every possible allowed triple for every position in every row recursively. |
State Space Explosion Tree |
Draw a pyramid. At each block, branch out arrows for every possible color match. $O(A^N)$ where A is alphabet. |
Backtracking with Memoization (Bitmasking) |
Bottom-Up Level Validation |
Process row by row. For a row, find all valid next-rows. Cache the results of a row string to avoid re-calculating identical patterns. |
Draw a pyramid. Highlight one row. Draw a "Cache" box next to it. If the row pattern repeats elsewhere, draw an arrow back to the box. |
Pruned Search Tree |
Draw a tree where many branches are cut off (X) early due to the cache. $O(A^N)$ worst case, but average is much lower. |
Infinite recursion stack. |
HashMap for memoization of row strings (O(A^N)). |
| 757 |
Set Intersection Size At Least Two |
Generate all possible subsets of the total range and check the intersection with every interval. |
Power Set Scan |
Draw a range [0, Max]. List every combination of numbers. Check against intervals. $O(2^\text{Range})$. |
Greedy (Interval Sorting) |
Right-Edge Pinning |
Sort intervals by end time. Pick the two largest points from the first interval. For subsequent intervals, check how many points you already have; add 1 or 2 as needed. |
Draw horizontal bars (intervals) on a timeline. Draw two red dots at the end of the first bar. Move to the next; if it covers the dots, do nothing. Else, add dots at the end. |
Single Pass with Sort |
Draw a timeline. Show one pass through sorted intervals. $O(N \log N)$. |
Massive lists of integer subsets. |
A simple list/array of the chosen "set" points (O(N)). |
| 758 |
Bold Words in String |
For every word in the dictionary, find all occurrences in the string and wrap them individually in tags. |
Overlapping Tag Mess |
Draw a string. Draw tags like `` around overlapping parts, creating invalid nested HTML. $O(N\cdot W)$. |
Boolean Array Masking |
Binary Coverage Map |
Create a boolean array `bold[n]`. Use a Trie or `indexOf` to find all matches. Set `bold[i...j]` to true. Finally, iterate and insert tags where `bold` flips. |
Draw the string. Below it, draw a row of empty boxes. Fill boxes with '1' if the letter should be bold, '0' otherwise. Draw tags only at 0/1 transitions. |
Linear Pass with Trie |
Draw a line for the string. For each char, draw a Trie lookup path. Total $O(N \\text{cdot max}_\text{word}_\text{len})$. |
N/A. |
A boolean array of length N (O(N)). |
| 759 |
Employee Free Time |
Merge all employee intervals into one massive list, sort them, and then check gaps. |
Flat Interval Merge |
Draw all intervals on one line. Sort them. Find spaces between the end of one and start of next. $O(N \log N)$. |
Min-Heap (K-Way Merge) |
Timeline Sweep with Priority Queue |
Keep a pointer for each employee. Push the first interval of each into a Min-Heap. Pop the earliest, update "latest end time," and find gaps. |
Draw a row for each employee. Place a marker at their first interval. Use a "Time Line" moving right, always picking the marker that is furthest left. |
Efficient Heap Stream |
Draw a heap with K elements (K=employees). Total time $O(N \log K)$. |
List of all intervals (O(N)). |
Min-Heap of size K (O(K)). |
| 760 |
Find Anagram Mappings |
For every element in A, perform a linear search in B to find a matching value and record its index. |
Nested Loop Search |
Draw Array A and Array B. For each element in A, draw an arrow scanning every element in B until a match is found. $O(N^2)$. |
Hash Map Indexing |
Direct Address Mapping |
Store elements of B in a HashMap: `value -> list of indices`. For each element in A, pop an index from the map for that value. |
Draw Array A. Draw a HashMap. Draw an arrow from A[i] to the Map, then directly to its location in B. |
Linear Map Construction |
Draw two arrays. Show one pass to build the map and one pass to create the result. $O(N)$. |
N/A. |
HashMap storing N indices (O(N)). |
| 761 |
Special Binary String |
Generate all possible permutations of the string and check if they are "special" and lexicographically larger. |
Permutation Explosion |
Draw a string branching into N! possibilities. Most branches are crossed out (invalid). $O(N!)$. |
Recursion + String Sorting (Divide & Conquer) |
Recursive Mountain Parsing |
Treat '1' as up and '0' as down. Break string into "Special" components (mountain peaks). Recursively sort sub-mountains and join them back in descending order. |
Draw a line plot (1=up, 0=down). Identify separate peaks that touch the baseline. Extract each peak, recurse, and rearrange the peaks on the paper from largest to smallest. |
Recursive Tree Depth |
Draw a tree where each node is a substring being sorted. $O(N^2)$ due to repeated string concatenations. |
Massive set for permutations. |
Recursive call stack + list of strings $O(N)$. |
| 762 |
Prime Number of Set Bits in Binary Representation |
For each number in range, convert to binary string, count '1's, and perform a full primality test. |
String Conversion Pipeline |
Draw a number entering a box that outputs a long binary string. Then a second box checking all divisors. $O(N \\text{sqrt}{\log N})$. |
Bit Manipulation (bitCount) + Constant Set Check |
Binary PopCount Lookup |
Use `Integer.bitCount(i)`. Since max bits for 10^6 is 20, use a fixed set of primes \{2, 3, 5, 7, 11, 13, 17, 19\} for $O(1)$ checking. |
Write the number. Draw an arrow converting it to a small integer (count of 1s). Compare that integer against a tiny list of primes. |
Linear Scan with Constant Work |
Draw a flat line across the range. Each step has a small "constant" box above it. $O(N)$. |
Temporary binary strings for every number. |
$O(1)$ extra space (no strings needed). |
| 763 |
Partition Labels |
Generate all possible partitions and check if any character appears in more than one partition. |
Exhaustive Split Search |
Draw a string. Draw scissors at every possible index. $O(2^N)$ combinations. |
Greedy (Last Occurrence Map) |
Stretching Elastic Bands |
Pre-record the last index of every character. Iterate through the string; the current partition must extend to the "last index" of any character found within it. |
Draw the string. For the first letter, draw a line to its last occurrence. As you move, if you hit a letter whose "last" is further, stretch your boundary line. Cut when you reach the boundary. |
Two-Pass Linear Sweep |
Draw an array. Show one pass to build a map, one pass to partition. $O(N)$. |
List of all partition combinations. |
Hash Map/Array of size 26 (O(1) constant space). |
| 764 |
Largest Plus Sign |
For every '1' in the grid, expand in all 4 directions as far as possible to find the arm length. |
Radial Cell Expansion |
Draw a grid. For every cell, draw 4 long arrows until they hit a '0' or a wall. $O(N^3)$. |
Dynamic Programming (4-Directional Prefix) |
Directional Light Casting |
Create 4 DP passes (L-to-R, R-to-L, T-to-B, B-to-T). `dp[r][c]` stores the min of the continuous '1's seen from all 4 directions. |
Draw the grid. Draw 4 versions of it. In each, fill cells with the count of consecutive 1s from that direction. Layer them and find the max cell. |
Matrix Area Scan |
Draw the grid. Show 4 full-grid sweeps. $O(N^2)$. |
N/A. |
2D DP matrix or 4-direction tracking in one matrix $O(N^2)$. |
| 765 |
Couples Holding Hands |
Try every possible swap in every possible order to find the minimum to pair everyone. |
State Space Search Tree |
Draw the array. Each node branches into N^2 possible swaps. $O(N!)$ or exponential BFS. |
Greedy / Cycle Decomposition (DSU) |
Chain Snapping |
Look at pairs (2i, 2i+1). If they aren't a couple, swap the second person's partner into that spot. Alternatively, use DSU to find cycles; min swaps = (Total Couples - Number of Cycles). |
Draw people as nodes. Connect people sitting together. Draw a separate circle for the "ideal" couple. Count how many "seats" are incorrectly connected. |
Linear Grouping pass |
Draw the array of seats. Show one pass moving pair-by-pair and swapping. $O(N)$. |
Massive graph of all seat combinations. |
Position map or DSU parent array $O(N)$. |
| 766 |
Toeplitz Matrix |
For every element (r, c), find the start of its diagonal at the top/left edge and scan the entire diagonal to check for equality. |
Repeated Diagonal Scan |
Draw a grid. For every cell, draw a long diagonal arrow. Many arrows will overlap the same cells. $O(R \\text{times} C \\text{times} \\text{min}(R,C)$). |
One-Pass Neighbor Comparison |
Diagonal Shifting Match |
Iterate through the matrix from top-left. For each cell (r, c), simply check if it equals its top-left neighbor (r-1, c-1). |
Draw a grid. Draw small arrows from (0,0) to (1,1), (0,1) to (1,2), etc. Each cell is checked against exactly one neighbor. |
Grid Area Coverage |
Draw a grid and shade it in one single sweep. $O(R \\text{times} C)$. |
N/A. |
$O(1)$ extra space beyond input. |
| 767 |
Reorganize String |
Generate all permutations of the string and check which ones have no adjacent identical characters. |
Permutation Tree |
Draw a tree branching into N! possibilities. Most branches fail the "adjacent check." $O(N!)$. |
Max-Heap / Greedy with Interleaving |
Priority Bucket Filling |
Count character frequencies. Use a Max-Heap to always pick the most frequent character. Place it, then pick the *second* most frequent to "separate" the first. |
Draw a frequency table. Draw "slots" for the new string. Fill every other slot with the most common letter. Fill the gaps with others. |
Heap Operation Logarithm |
Draw a small heap (size 26). Show N extractions. Total time $O(N \log A)$ where A is alphabet size. |
Large set of string permutations. |
Frequency array and Max-Heap $O(A)$ or $O(1)$ if A=26. |
| 768 |
Max Chunks To Make Sorted II |
Try every possible split point, sort the chunks, and check if the merged result is sorted. |
Combinatorial Split & Sort |
Draw an array. Draw "cutting lines" at all 2^N positions. Sort each resulting piece. $O(2^N \\text{times} N \log N)$. |
Prefix Max & Suffix Min |
Balance Beam Boundaries |
Create two arrays: `leftMax` (max seen from left) and `rightMin` (min seen from right). A chunk can end at index i if `leftMax[i] <= rightMin[i+1]`. |
Draw the array. Below it, write the max-so-far. Below that, write the min-so-far from the right. Circle indices where the top number \le bottom number. |
Parallel Linear Sweeps |
Draw an array. Show one pass left, one pass right, one pass to count. $O(N)$. |
N/A. |
Two auxiliary arrays of size N (O(N)). |
| 769 |
Max Chunks To Make Sorted |
Same as 768; exhaustive search of all possible partitions. |
Exponential Partitioning |
Draw a small array (0-4). List all ways to group them. Check each. $O(2^N)$. |
Running Maximum Comparison |
Index Syncing |
Since elements are 0 \dots n-1, if the `max_seen_so_far` at index i is equal to i, all numbers up to i must be present. A chunk can end here. |
Draw the array. Move a pointer. Keep track of the highest number seen. When `max == current_index`, draw a vertical "cut" line. |
Single Pass Flatline |
Draw a line with a single pointer moving from 0 to N. $O(N)$. |
N/A. |
$O(1)$ space (single `max` variable). |
| 770 |
Basic Calculator IV |
Convert the expression to a string, substitute variables, and use a standard string-based math evaluator. |
String Substitution Mess |
Draw a formula. Show x becoming (a+b). The string grows exponentially with nested parentheses. $O(\\text{text}{\text{Exponential}})$. |
Polynomial Class / Map of Term-to-Coefficient |
Algebraic Object Expansion |
Represent each expression as a Map where keys are sorted variable lists (e.g., "a*b") and values are coefficients. Overload +, -, and * for these maps. |
Draw two maps: `"a": 1, "1": 2` and `"b": 1`. Show the distribution rule (1a + 2) \times (1b) = 1ab + 2b. Combine terms. |
Recursive Descent with Map Merging |
Draw a tree of operations. Each node merges two maps. Complexity depends on the number of terms. $O(2^N)$ in worst case, but efficient for real formulas. |
Massive intermediate strings. |
Recursive stack and Map-based term storage $O(N)$. |
| 771 |
Jewels and Stones |
For every stone, iterate through the entire "jewels" string to check if it's a match. |
Nested Loop Grid |
Draw "Stones" as rows and "Jewels" as columns. Put an 'X' at every intersection. $O(J \\text{times} S)$. |
Hash Set Lookup |
Filter Sieve |
Dump all characters of "Jewels" into a HashSet. Iterate "Stones" once; if a stone is in the Set, increment count. |
Draw a bucket labeled "Jewels Set". Draw stones falling toward it. If they match a shape in the bucket, they go to the "Count" pile. |
Parallel Linear Scan |
Draw two lines. One pass to fill the set, one pass to check stones. $O(J + S)$. |
N/A. |
HashSet of size up to 52 (O(1) constant relative to alphabet). |
| 772 |
Basic Calculator III |
Find the innermost parentheses using regex, evaluate the simple expression, replace it in the string, and repeat. |
Recursive String Reduction |
Draw a long string shrinking as chunks are replaced by numbers. $O(N^2)$ due to string copying. |
Recursive Descent with Operator Precedence |
Dual Stack (Values & Ops) |
Process characters. Use a stack for numbers and a stack for operators. When a ')' is met or a lower precedence op appears, pop and calculate. |
Draw two vertical boxes. As you read the math, push numbers into one and signs into the other. When a `*` hits a `+`, show the `*` triggering a calculation first. |
Linear Token Stream |
Draw a single arrow moving left-to-right across the formula. $O(N)$. |
Multiple intermediate string copies. |
Stack of numbers/operators proportional to depth (O(N)). |
| 773 |
Sliding Puzzle |
Try every possible swap of the '0' tile recursively to find the configuration `[[1,2,3],[4,5,0]]`. |
State Space Explosion |
Draw the 2x3 grid. Branch into all possible moves. $O(N!)$. |
Breadth-First Search (BFS) |
State Transition Graph |
Represent the board as a string. Use BFS to explore all reachable board states. The first time the target string is reached is the min steps. |
Draw the start board as a node. Draw lines to boards reachable by one move. Shade the "wavefront" of moves until the solved board appears. |
BFS Level-Order Expansion |
Draw concentric circles representing moves 1, 2, 3... until target. $O(V+E)$ where V=6!. |
Recursive call stack (risks cycles). |
Queue for BFS + HashSet for visited states (O(N!) but 6! is small). |
| 774 |
Minimize Max Distance to Gas Station |
Add gas stations one by one. Each time, find the largest gap and split it. |
Greedy Gap Splitting |
Draw a line with dots. Find the widest gap, add a dot in the middle. Repeat K times. $O(K \\text{times} N)$. |
Binary Search on Answer (Range) |
Threshold Guessing |
Binary search for the distance D. For a given D, calculate how many stations are needed to ensure no gap > D. Adjust D based on K. |
Draw a ruler. Guess a distance (e.g., 2.0). Count how many "dots" you'd need to fit that rule. If you need more than K, make the distance bigger. |
Logarithmic Precision Convergence |
Draw a range [0, 10^8]. Show it halving 100 times for precision. $O(N \log(\\text{text}{\text{Range}}/\\text{epsilon})$). |
N/A. |
$O(1)$ extra space. |
| 775 |
Global and Local Inversions |
Count all global inversions (i < j, A[i] > A[j]) and all local inversions (i, i+1, A[i] > A[i+1]) and compare. |
Nested Inversion Counting |
Draw an array. Draw lines between every pair to check for global inversions. $O(N^2)$. |
Running Maximum Property |
The "Too Far" Boundary |
All local inversions are global, so we only need to check if any non-local global inversions exist. This happens if A[i] > \min(A[i+2 \dots n-1]). |
Draw the array. Move an arrow i. If the current number is bigger than any number found 2 steps ahead or further, return false. |
Single Pass Flatline |
Draw an array with a single arrow and a "min-so-far" tracker from the right. $O(N)$. |
N/A. |
$O(1)$ space (tracking one max or min variable). |
| 776 |
Split BST |
Traverse the tree, copy all nodes \le V into one new tree and all nodes > V into another. |
Tree Duplication |
Draw a BST. Draw two empty trees next to it. Copy nodes one by one. $O(N)$. |
Recursive Post-Order Split |
Subtree Re-wiring |
Recurse down the tree. If `root.val <= V`, split the right child. Attach the "left" part of that split to `root.right` and return `[root, rightPart]`. |
Draw a BST. Draw a jagged line (the split). Show arrows being cut and re-pointed to new subtree heads. |
Recursive Depth Path |
Draw a single path from root to a leaf. Each node on this path is visited once. $O(H)$ where H is height. |
Full copy of the tree in memory (O(N)). |
Recursive stack frames (O(H)). No new nodes created. |
| 777 |
Swap Adjacent in LR String |
Use BFS to explore all possible 'XL' -> 'LX' and 'RX' -> 'XR' swaps to see if `start` can become `end`. |
State Transition Maze |
Draw a string as a node. Branch out for every possible swap. $O(2^N)$ potential states. |
Two-Pointer Position Invariant |
Relative Order Tracking |
Ignore 'X's and check if 'L' and 'R' appear in the same relative order. Then verify 'L' only moves left and 'R' only moves right. |
Draw two strings without 'X's. Match 'L's and 'R's with lines. If lines cross, or an 'L' in `end` is to the right of `start`, mark as invalid. |
Parallel String Scan |
Draw two strings with an arrow pointing to the current non-'X' char in each. $O(N)$. |
Huge HashSet of visited strings. |
$O(1)$ extra space (just pointers). |
| 778 |
Swim in Rising Water |
Backtracking to find all paths from (0,0) to (N-1,N-1) and taking the minimum of the maximum height on each path. |
Path Exploration Tree |
Draw a grid. Branch out every possible path. $O(4^{N^2})$. |
Modified Dijkstra / Min-Heap BFS |
Expanding Water Level |
Use a Min-Heap of `(height, r, c)`. Always expand the cell with the lowest height. The "time" to reach a cell is `max(current_time, grid[r][c])`. |
Draw a grid with numbers. Start at (0,0). Shade the neighbor with the smallest number. Keep shading the smallest "boundary" cell. |
Frontier Expansion |
Draw a circle expanding from the corner. Write N^2 \log N for heap operations. |
Infinite recursion stack. |
Min-Heap and Visited Set (O(N^2)). |
| 779 |
K-th Symbol in Grammar |
Physically generate each row: `0` -> `01`, `1` -> `10` until reaching row N. |
Exponential String Growth |
Draw row 1: 0. Row 2: 01. Row 3: 0110. Show the length doubling each time. $O(2^N)$. |
Binary Tree Symmetry / Recursion |
Parent-Child Relationship |
The first half of row N is row N-1. The second half is the flip of row N-1. If K is in the second half, it depends on K - (\text{half\_length}). |
Draw a tree of 0s and 1s. For any K, trace up to its parent in the previous row. Use the rule: `val = parent == K_is_even ? 1 : 0`. |
Logarithmic Traceback |
Draw a tree height N. Show a single path from row N up to row 1. $O(N)$. |
Massive strings of size 2^N. |
Recursive stack frames (O(N)). |
| 780 |
Reaching Points |
BFS/DFS starting from (sx, sy) and trying both (x+y, y) and (x, x+y) transitions. |
Forward Growth Tree |
Draw (sx, sy). Branch out two paths. Many paths exceed (tx, ty) quickly. $O(2^{\\text{max}(\text{tx}, \text{ty})$}). |
Modulo Backtracking (Reverse Engineering) |
Shrinking Target Path |
Start from (tx, ty). If tx > ty, then tx = tx \pmod{ty}. This simulates multiple steps of (x-y) in one go. Stop when tx, ty hit sx, sy. |
Draw (tx, ty). Draw a single arrow back to a smaller pair using the modulo operator. If a coordinate hits sx or sy, check the remainder. |
Euclidean Algorithm Flow |
Draw a single descending path. $O(\log(\\text{max}(\text{tx}, \text{ty})$)). |
Exponentially growing queue. |
$O(1)$ space (just two variables). |
| 781 |
Rabbits in Forest |
Generate every possible combination of rabbit colors that satisfy the "others said" constraints. |
Combinatorial Search |
Draw sets of rabbits and try to color them. Show $O(N!)$ or exponential backtracking. |
Greedy Grouping (HashMap) |
Color Bucket Filling |
If a rabbit says x, it belongs to a group of size x+1. If multiple rabbits say x, they can share a group until the group is full (x+1 rabbits). |
Draw circles for "claims". If three rabbits say "2", put them in one circle of size 3. If a fourth says "2", draw a new circle. |
Linear Scan with Map |
Draw an array of answers. Show one pass to fill groups. $O(N)$. |
List of all possible colorings. |
HashMap of rabbit claims $O(N)$. |
| 782 |
Transform to Chessboard |
Try every possible swap of rows and columns recursively to see if it becomes a chessboard. |
State Space Maze |
Draw the grid. Branch into all row/column swaps. $O(2^{(N+M)$}) states. |
Invariance & Hamming Distance |
Pattern XOR Masking |
Only two types of rows/columns can exist (opposites). Check if row 1 and row i are same or opposite. Calculate min swaps to make row 1 match "0101..." or "1010...". |
Draw the grid. Compare the first row to all others. If any row is not identical or exactly opposite, draw a "Big X" (impossible). |
Single Pass Grid Check |
Draw the grid. Show one horizontal scan and one vertical scan. $O(N^2)$. |
Recursive call stack of grids. |
$O(1)$ extra space (checking row/col patterns). |
| 783 |
Minimum Distance Between BST Nodes |
Calculate the difference between every single pair of nodes in the tree. |
Pairwise Nested Loop |
Draw a BST. Draw lines connecting every node to every other node. $O(N^2)$. |
In-Order Traversal (Sorted Property) |
Flattened Number Line |
An in-order traversal of a BST yields a sorted array. The minimum difference must be between two adjacent elements in the sorted sequence. |
Draw the BST. Draw a single snake-like arrow passing through nodes in order (Left -> Root -> Right). Record the "previous" node's value. |
Single Tree Sweep |
Draw the tree and trace the in-order path. $O(N)$. |
Full array of all node pairs. |
Recursive stack $O(H)$ and one variable for `prev_val`. |
| 784 |
Letter Case Permutation |
Nested loops to generate all variations by toggling each letter. |
Binary String Tree |
Draw the string. For each letter, branch into "lower" and "upper". $O(2^L \\text{times} N)$ where L is letter count. |
Backtracking / DFS |
Decision Permutation Tree |
Recurse through the string. If char is a digit, skip. If a letter, recurse with lowercase and again with uppercase. |
Draw the input string at the top. Draw two arrows down for the first letter. Repeat until leaves contain all variations. |
Exponential Leaf Count |
Draw a tree with 2^L leaf nodes. $O(2^L \\text{times} N)$. |
N/A. |
Recursive stack and result list $O(2^L \\text{times} N)$. |
| 785 |
Is Graph Bipartite? |
Try every possible way to split nodes into two sets and check for internal edges. |
Brute Force Partitioning |
Draw nodes. Try every combination of "Set A" and "Set B". $O(2^N)$. |
Graph Coloring (BFS/DFS) |
Two-Tone Node Coloring |
Start at a node, color it Red. Color all its neighbors Blue. Color their neighbors Red. If you ever try to color a node with the "wrong" color, it's not bipartite. |
Draw the graph. Pick a node and color it '1'. Color neighbors '-1'. If an edge connects two '1's or two '-1's, circle that edge in red. |
Standard Graph Traversal |
Draw a graph. Show each node and edge being visited once. $O(V+E)$. |
N/A. |
Color array of size V and BFS Queue $O(V)$. |
| 786 |
K-th Smallest Prime Fraction |
Generate every possible fraction pair `arr[i]/arr[j]`, store them in a list, and sort them. |
Fraction Matrix Sorting |
Draw a grid of all possible fractions. Pour them into a "Sort" funnel. $O(N^2 \log N)$. |
Binary Search on Value or Min-Heap Merge |
Sorted Matrix Diagonal Sweep |
Binary search the fraction value X between 0 and 1. Count how many fractions are \le X using two pointers. Adjust X until the count is exactly K. |
Draw a square grid where rows/cols are array indices. Draw a diagonal line Y=X. Count the "cells" (fractions) that fall below this line. |
Log-Linear Convergence |
Draw a line 0-1. Show it halving while a pointer sweeps the array. $O(N \log(\\text{text}{\text{precision}})$). |
Massive array of all N^2 fraction objects. |
$O(1)$ extra space for Binary Search; $O(N)$ for Min-Heap. |
| 787 |
Cheapest Flights Within K Stops |
DFS to find all paths from `src` to `dst` and filter those with \le K stops. |
Exhaustive Path Tree |
Draw nodes. Branch out all possible flights. Most paths go in circles or get too long. $O(V^K)$. |
Bellman-Ford / BFS (Level-based) |
Limited Layer Relaxation |
Run Bellman-Ford for exactly K+1 iterations. Each iteration i represents finding the cheapest path using exactly i flights. |
Draw nodes. Label each with "min cost". In each step, look at all flight edges and update the cost of the "destination" node. Stop after K+1 steps. |
Layered Edge Relaxation |
Draw K parallel layers of the graph. Show edges only going from layer i to i+1. $O(K \\text{times} E)$. |
Recursive stack frames. |
Two arrays of size V to store current and previous costs $O(V)$. |
| 788 |
Rotated Digits |
For every number from 1 to N, check if it is "good" by rotating each digit. |
Number Line Transformation |
Draw numbers 1 to N. Check each digit in each number. $O(N \log N)$. |
Digit Dynamic Programming |
State-Based Digit Stringing |
Count "good" numbers digit by digit. State: `(index, isLess, hasDifferentDigit)`. Avoid re-calculating sub-problems for similar number prefixes. |
Draw a decision tree for digits 0-9. Mark "invalid" digits (3, 4, 7). Mark "identity" digits (0, 1, 8). Mark "rotating" digits (2, 5, 6, 9). |
Logarithmic Digit Depth |
Draw a tree with depth equal to the number of digits in N. $O(\log N)$. |
N/A. |
Small memoization table $O(\\text{text}{\text{digits}} \\text{times} 2 \\text{times} 2)$. |
| 789 |
Escape The Ghosts |
Use BFS to simulate the player and all ghosts moving step-by-step to see if a ghost can intercept. |
Multi-Agent Grid Chase |
Draw a grid. Move player 1 step, then move all ghosts 1 step. $O(\\text{text}{\text{Grid Area}})$. |
Manhattan Distance Comparison |
Radial Reachability Circles |
The ghosts move optimally. If any ghost is closer (or equally close) to the target than the player, the player can be caught. Distance = |x1-x2| + |y1-y2|. |
Draw the player, target, and ghosts. Draw a straight dashed line representing the steps to the target for each. Compare the step counts. |
Single Linear Scan of Ghosts |
Draw a list of ghosts. Calculate distance for each. $O(\\text{text}{\text{Ghosts}})$. |
Large grid state representation. |
$O(1)$ extra space. |
| 790 |
Domino and Tromino Tiling |
Recursively try placing a domino or tromino at the first empty cell of the 2 \times N board. |
Brute Force Tiling Tree |
Draw a 2xN grid. Branch into all 4-5 ways to place a shape. $O(3^N)$. |
Dynamic Programming (Matrix Exponentiation) |
State Transition Tiling |
The board can be "Full", "Top-half protruding", or "Bottom-half protruding". Use DP to count ways to reach a full state based on previous partial states. |
Draw a 2x1 section. Show the 3 possible edge shapes. Draw arrows showing how adding a domino/tromino converts one edge shape to another. |
Linear State Progression |
Draw the N columns. Show a single pass through columns updating the 3 state variables. $O(N)$. |
Deep recursion stack. |
DP array or 3 variables $O(N)$ or $O(1)$. |
| 791 |
Custom Sort String |
Use a standard sorting algorithm with a custom comparator that searches for each character's index in the "order" string. |
Nested Search Sort |
Draw a string being sorted. Every time two characters are compared, draw an arrow scanning the entire "order" string. $O(N \log N \\text{times} \\text{text}{\text{Order}})$. |
Frequency Bucket Counting |
Priority Sorting Bins |
Count occurrences of each character in `s`. Iterate through `order`; for each character, append it to the result as many times as it appeared. Append remaining characters at the end. |
Draw a frequency map (table). Draw the "order" string. For the first letter in "order", pull all its matches from the table into the result string. |
Two-Pass Linear Scan |
Draw a line for the input string and a line for the order string. Show each being touched exactly once. $O(N + M)$. |
N/A. |
Fixed-size frequency array (O(1) relative to alphabet). |
| 792 |
Number of Matching Subsequences |
For every word in the dictionary, perform a full two-pointer subsequence check against the string `s`. |
Repeated Subsequence Scan |
Draw `s`. For every word, draw an arrow scanning `s` from start to finish. $O(\\text{text}{\text{Words}} \\text{times} S)$. |
Bucket Sort of Iterators / Waiting Lists |
Multi-Word Parallel Scan |
Create 26 buckets. Put each word into the bucket of its first character. Iterate through `s`; for each char, move all words in that bucket to the bucket of their next character. |
Draw 26 alphabet buckets. Write words inside. As you move through `s`, "jump" words from bucket to bucket like a race. If a word finishes, increment count. |
Single String Pass |
Draw the string `s`. Show a single arrow moving left-to-right, processing groups of words at each step. $O(S + \\text{sum} \\text{text}{\text{word}\_\text{lengths}})$. |
N/A. |
A list of word iterators/pointers organized by starting character $O(\\text{text}{\text{Words}})$. |
| 793 |
Preimage Size of Factorial Zeroes Function |
Iteratively calculate the number of trailing zeros for factorials 1!, 2!, 3! \dots until reaching K. |
Linear Zero Counting |
Draw a number line. At each step, count multiples of 5. $O(N \\text{times} \log N)$. |
Binary Search on Answer Range |
Zero-Count Threshold Search |
The number of trailing zeros is monotonic. Use binary search to find the smallest number with K zeros and the smallest with K+1 zeros. The answer is their difference (always 5 or 0). |
Draw a coordinate graph where X is the number and Y is the zero count. Use binary search brackets to home in on the X value where Y=K. |
Logarithmic Convergence |
Draw a range [0, 10^{10}]. Show it halving about 60 times. $O(\log^2 K)$. |
N/A. |
$O(1)$ space (just mathematical bounds). |
| 794 |
Valid Tic-Tac-Toe State |
Generate every possible sequence of moves from an empty board to see if the current board is reachable. |
Move Sequence Tree |
Draw an empty board. Branch into all 9 moves, then 8, then 7. $O(9!)$. |
Win-Condition Invariance Check |
Board State Audit |
Check counts: X must be equal to or one more than O. Check wins: if X wins, count must be O+1. If O wins, count must be equal. Both cannot win. |
Draw the board. Count X's and O's. Draw lines through any winning 3-in-a-row. Verify the rules against these visual tallies. |
Constant Rule Check |
Draw a list of 5 rules. Tick each one. $O(1)$ since board size is fixed at 3x3. |
Massive queue for BFS. |
$O(1)$ extra space. |
| 795 |
Number of Subarrays with Bounded Maximum |
Generate every possible subarray and find the maximum element in each, checking if it falls in [L, R]. |
Nested Subarray Scan |
Draw the array. Draw brackets for every possible start and end. For each, scan the contents. $O(N^3)$. |
Two-Pass Inclusion/Exclusion (At-Most K) |
Subarray Count subtraction |
Count subarrays where all elements are \le R. Subtract subarrays where all elements are \le L-1. Formula for contiguous elements: n(n+1)/2. |
Draw the array. Shade groups of elements \le R. Calculate counts. Then shade groups of elements \le L-1 and subtract. |
Linear Counting Pass |
Draw an array with a single arrow sweeping left-to-right. $O(N)$. |
List of all subarray objects. |
$O(1)$ extra space (tracking current contiguous length). |
| 796 |
Rotate String |
Perform all N possible rotations of string A and compare each one to string B. |
Cyclic Shift Scan |
Draw string A. Draw N arrows showing the first character moving to the end repeatedly. $O(N^2)$. |
String Concatenation (Double Check) |
Infinite Loop Window |
Concatenate A with itself (A + A). If B is a rotation of A, it must be a substring of this doubled string. Lengths must also match. |
Draw A twice side-by-side: `abcdeabcde`. Draw a box of length 5 and slide it across. If the box contents match B, return true. |
Substring Search Linearization |
Draw a single pass through the 2N length string. $O(N)$ using KMP or built-in `contains`. |
N/A. |
A single new string of length 2N (O(N)). |
| 797 |
All Paths From Source to Target |
Exhaustively search every possible path using DFS, including cycles (though DAGs have none). |
Exponential Path Tree |
Draw the graph. Branch into every possible neighbor. $O(2^N \\text{times} N)$. |
Backtracking (DFS for DAG) |
Recursive Depth Trace |
Use recursion to explore neighbors. Since it's a DAG, you don't need a "visited" set to prevent cycles, just a way to record the current path. |
Draw the graph nodes. Start at 0. Trace a path to N-1 with a pen. Backtrack to the last junction and take a different turn. |
Tree Leaf Count |
Draw a tree where each leaf is a unique path from source to target. $O(2^N \\text{times} N)$. |
N/A. |
Recursive stack and a list to store all paths (O(2^N \times N)). |
| 798 |
Smallest Rotation with Highest Score |
For every possible rotation K from 0 to N-1, calculate the total score by iterating through the array. |
Nested Score Re-calculation |
Draw the array. For each K, draw a loop that counts how many nums[i] \le i. $O(N^2)$. |
Difference Array / Sweep Line |
Score Interval Overlap |
For each number, calculate the range of K values for which it earns a point. Use a difference array `bad[N]` to mark where points are lost. Find the K with minimum losses. |
Draw a timeline from 0 to N. For each element, draw a horizontal bar representing the "win" interval. Find the vertical slice with the most bars. |
Single Pass Sweep |
Draw an array. Show one pass to calculate "bad" intervals and one prefix-sum pass. $O(N)$. |
N/A. |
A single difference array of size N (O(N)). |
| 799 |
Champagne Tower |
Simulate the flow of champagne drop by drop for every single unit poured. |
Individual Drop Simulation |
Draw the pyramid. For every drop, trace its path left or right down the glass. $O(\\text{text}{\text{poured}})$. |
Dynamic Programming (Pascal's Triangle Variation) |
Waterfall Overflow Distribution |
Create a 2D array for glasses. Pour all champagne into `glass[0][0]`. For each glass, if it exceeds 1.0, split the excess `(val - 1) / 2` to the two glasses below. |
Draw rows of circles. Write the volume in the top circle. Draw two arrows down, each carrying half of the "spillover" to the next row. |
Grid Area Filling |
Draw the pyramid. Show each glass being processed once. $O(R^2)$ where R is number of rows. |
N/A. |
2D array of size 101 \times 101 (O(R^2)). |
| 800 |
Similar RGB Color |
Check all 16 \times 16 \times 16 = 4096 shorthand colors and find the one with the minimum squared distance. |
Exhaustive Color Scan |
Draw the RGB space. Check every possible "double-digit" hex combination like #112233. $O(16^3)$. |
Greedy Component Rounding |
Nearest Neighbor Shorthand |
Each color component (RR, GG, BB) is independent. For each, find the shorthand value (like `0xAA`, `0xBB`) that is closest to its actual value. |
Draw a hex number line: 00, 11, 22... Find the target value (e.g., 0x24) and circle the nearest multiple of 0x11 (0x22). |
Constant Component Check |
Draw three boxes (R, G, B). For each, perform a simple math check. $O(1)$. |
N/A. |
$O(1)$ extra space. |
| 801 |
Minimum Swaps To Make Sequences Increasing |
Recursive Backtracking: At each index i, branch into two parallel universes (swap A[i] and B[i], or do not swap). |
Complete Binary Decision Tree. $O(2^n)$ time. |
Draw a root node. Draw two branches down (Left: Swap, Right: Keep). At each node, write out the current state of A and B. It explodes outwards like a fractal. |
Dynamic Programming (State Machine): 2 states per index (Swapped vs Not Swapped). |
State Transition Graph / 2xN Grid. |
Move index by index left to right. Only look at i and i-1. If A[i]>A[i-1] and B[i]>B[i-1], draw straight horizontal arrows. If A[i]>B[i-1] and B[i]>A[i-1], draw diagonal crossing arrows. |
Draw a grid with 2 rows ('Keep', 'Swap') and N columns. Fill boxes left to right with integer minimums based on the previous column's valid transitions. |
Linear Timeline / Domino chain. $O(N)$ time. |
Draw a single straight horizontal line crossing N vertical tick marks. Each tick represents $O(1)$ constant work. |
Deep Call Stack: Draw vertical overlapping boxes representing recursion depth mapping up to N frames. |
Two variables holding $O(1)$ space: Draw two small squares side-by-side that constantly overwrite their previous values. |
| 802 |
Find Eventual Safe States |
DFS from every single node. Keep a hashset of the current path to detect cycles for every node independently. |
Overlapping Redundant Directed Graphs. $O(V \cdot (V+E)$). |
Draw the whole graph 5 times. On each graph, trace a path with a thick marker until you hit a cycle or dead end. Notice how many edges you re-trace. |
Graph Coloring (3-Color DFS) OR Kahn's Algorithm (Topological Sort on reversed edges). |
Traffic Light System (White/Gray/Black). |
All nodes start white. When entering a node, color it gray (visiting). Traverse neighbors. If a neighbor is gray, a cycle is found. If all neighbors are safe, color it black (safe). |
Draw graph nodes as empty circles. Lightly shade a circle with pencil when entering (Gray). Firmly shade it in with pen when returning from DFS (Black). |
Single Unified Traversal Tree. $O(V+E)$ time. |
Draw an adjacency list and simply cross out each edge exactly once as you process it. |
Multiple separate stack towers, drawn side-by-side, representing independent memory allocations. |
A single 1D array of size V. Draw a strip of N boxes. Write 0 (White), 1 (Gray), or 2 (Black) in each box. |
| 803 |
Bricks Falling When Hit |
For each hit, remove the brick. Then run a full BFS/DFS from row 0 to find all connected components. Count unvisited components as 'fallen'. |
Repeated Grid Flood-Fills. $O(H \cdot M \cdot N)$. |
Draw multiple M x N grids. On the first grid, erase one block, shade the connected ones. On the next grid, erase another block, shade again. |
Reverse Time Union-Find (Disjoint Set). |
Forest merging into a 'Ceiling' Master Node. |
Remove ALL hit bricks first. Build the safe structure. Then, step backward in time: add a hit brick back. Merge it with neighbors. If it connects to the roof, count the new size of the cluster. |
Draw nodes like floating bubbles. Draw a giant box at the top called 'ROOF'. As you add bricks backward, draw lines connecting bubbles. Point arrows upward to the ROOF. |
Amortized Flat Trees. $O(H \cdot α(M \cdot N)$) time. |
Draw a very wide, shallow tree where almost all leaf nodes point directly to the root (representing Path Compression). |
Draw overlapping 2D matrices representing $O(M\cdot N)$ memory allocated per hit simulation. |
A 1D array of size M*N + 1 (for the dummy roof). Draw a single line of indexed boxes storing parent indices. |
| 804 |
Unique Morse Code Words |
Translate every word, append to an array, then use nested loops to compare every string against every other string to count uniques. |
Complete Bipartite Graph / Complete Web. $O(N^2 \cdot L)$ time. |
Draw a column of the translated words. Draw a line from the top word to every single other word below it, representing $O(N^2)$ comparison overhead. |
Hash Set. |
Funnel filtering into a bucket. |
Imagine a funnel. Drop a word in, it translates on the way down. If the bucket already contains that exact Morse shape, it evaporates. Otherwise, it stays. Count remaining items. |
Draw a large circle representing the Set. As you process a word, draw its Morse string inside. If it's a duplicate, draw an 'X' over the new one. |
Linear Scanning Pipeline. $O(S)$ time where S is total characters. |
Draw a single horizontal line passing through a "Translation Box" and directly into a "Set Box" in $O(1)$ time per string. |
Array of Strings: Draw a long list of overlapping rectangular boxes storing full strings. |
Hash Set: Draw a grid with random scattered slots filled in, showing $O(N)$ space optimized for quick lookups. |
| 805 |
Split Array With Same Average |
Generate every single possible combination of the array (all subsets), calculate their averages, and check if it matches the remainder's average. |
Complete Binary Subset Tree. $O(2^N)$ time. |
Draw a root. Branch left (Include), branch right (Exclude). Double the branches at every layer until it becomes an unreadable massive fractal at the bottom. |
Meet-in-the-Middle + Dynamic Programming / Math Pruning. |
Two Converging Triangles. |
Split the array physically in half. Generate subset sums for Left and Right halves. Look for a puzzle piece from the Left that perfectly fits a puzzle piece from the Right to match the target sum constraint. |
Draw two triangles whose points face each other in the middle. The wide bases represent the starting arrays, narrowing down to the combinations that meet in the center. |
Two Shallow Trees. $O(2^(N/2)$) time. |
Draw two binary trees next to each other, but cut them off at half the depth of the brute force tree. |
Huge Call Stack/Subset List: Draw a towering inverted pyramid of memory blocks that grows exponentially. |
Two Hash Maps / DP Sets: Draw two bounded rectangular boxes holding unique sum/count pairs. $O(2^(N/2)$) space. |
| 806 |
Number of Lines To Write String |
Build actual string objects in memory line by line. Keep adding characters to a string until its width exceeds 100, then push that string to an array and start a new one. Count array length. |
String Builder Accumulator. $O(N)$ time but heavy overhead. |
Draw a horizontal track. Stack blocks on it. When it overflows, draw an arrow pointing to a whole new physical track below it. |
Single-Pass Greedy Accumulation / Simulation. |
Typewriter Carriage Return. |
Imagine an old typewriter. Each letter moves the carriage. When you hear the "Ding!" (100 pixels), hit Enter (Lines + 1) and slide the carriage back to 0 + current letter width. |
Draw a ruler marked 0 to 100. Draw varying length blocks (letters) fitting into it. Once a block hangs past 100, draw a swoop arrow dropping it to the start of a new ruler. |
Linear Scan. $O(N)$ time. |
Draw a single continuous timeline. Mark small tick marks on it for each character processed. |
Array of Strings: Draw an array where each index holds a horizontal bar representing an allocated string. |
Two Integer Variables: Draw two small squares (like digital odometers or counters) labeled "Lines" and "Width" that just overwrite their numbers. $O(1)$ space. |
| 807 |
Max Increase to Keep City Skyline |
For every single building (cell), loop through its entire row and entire column right then and there to find the maximums, calculate difference, and add to a total. |
Repeated Raycasting / Crosshairs. $O(N^3)$ time. |
Draw a grid. Pick one cell. Draw an intersecting horizontal and vertical line stretching across the whole grid. Erase it. Pick the next cell. Draw the crosshairs again. Notice how many times you trace the same cells. |
Precomputation (2D Grid Greedy). |
Shadow Projection Screens (Top and Side Views). |
Project shadows to the North (column max) and West (row max). Look at a building. Look at its North shadow and West shadow. Grow the building vertically until it hits the *shorter* of the two shadows. |
Draw the main N x N grid. Above it, draw a 1D array (North skyline). To its left, draw a 1D array (West skyline). Draw arrows from a grid cell pointing up and left to find its limits. |
Two-Pass Sweep. $O(N^2)$ time. |
Draw a grid. First, sweep a highlighter down all columns, then across all rows (Precomputation). Second, dot each cell exactly once with a pen (Calculation). |
$O(1)$ space, but draw repeated local variables popping into existence and disappearing for every cell. |
Two 1D Arrays: Draw two standalone strips of boxes (size N) sitting strictly outside the main grid memory block. |
| 808 |
Soup Servings |
Pure 4-way recursion simulating every single pouring operation (4 choices) until both A and B are empty or just A is empty. |
Exploding Quad-Tree. $O(4^N)$ time. |
Draw a root node (A,B). Draw 4 branches branching down. At the next level, draw 4 branches from each of those 4 nodes. The tree gets impossibly wide almost instantly. |
2D Dynamic Programming with Memoization + Math Pruning (Probability limit). |
Converging Grid + A Giant "Skip" Button. |
Scale down by 25 (e.g., 100ml = 4 portions). Start at (N, N) on a grid. Pull probabilities from 4 specific cells closer to (0,0). If N > 192 (which is 4800ml), hit the "Skip" button: A empties first 99.999% of the time, so just return 1.0. |
Draw a Cartesian coordinate system. Start at a point top-right. Draw 4 arrows pointing down and left towards the origin (0,0). |
Capped 2D Bounded Traversal. $O(1)$ for large N, max $O(200^2)$ otherwise. |
Draw a 200x200 box and shade it in (DP work). Then draw an infinitely long line stretching out to the right with "O(1) Jump" written over it. |
Massive Call Stack: Draw a towering, teetering stack of recursion frames mapped directly to the depth of the tree. |
2D Memoization Matrix (Max 200x200): Draw a finite square grid storing decimal numbers, halting memory growth. |
| 809 |
Expressive Words |
Dynamically mutate strings by inserting characters with nested loops to see if a query word can physically transform into the target string. |
String Expansion / Mutation Chains. $O(W \cdot L^2)$ time. |
Draw a short word. Draw expanding bubbles pushing the letters apart to make room for new letters, repeatedly checking against a master template. |
Two Pointers / Run-Length Encoding (RLE) grouping. |
Zip-Matching Train Boxcars. |
Compress "heeellooo" into groups: [h:1, e:3, l:2, o:3]. Compress query "hello" into [h:1, e:1, l:2, o:1]. Compare cars sequentially. If the target car has 3+ of a letter, the query car's letter can "stretch" to match it. |
Draw two trains of boxcars side-by-side. Each boxcar holds a letter and a number count. Draw straight lines connecting matching boxcars between the two parallel trains. |
Parallel Linear Traversal. $O(S + W\cdot L)$ time. |
Draw two parallel timelines (String S, and Word W). Draw two pointers moving synchronously left to right, stopping only once at the end. |
Intermediate Heap Allocations: Draw dozens of overlapping, slightly different string blocks cluttering the memory space. |
Two Integer Pointers: Draw two small arrow icons (i and j) pointing at indices in the original immutable strings. $O(1)$ space. |
| 810 |
Chalkboard XOR Game |
Minimax Algorithm. Recursively simulate the game tree by having Alice and Bob try removing every single valid element one by one to find a forced win. |
Massive Game Decision Tree. $O(N!)$ time. |
Draw a root node (the whole array). Draw N branches for the first move. Then N-1 branches from each of those. The tree instantly becomes an unreadable, tangled mess of permutations. |
Mathematical Proof / Bit Manipulation (XOR properties). |
A Binary Toggle Switch & A Balancing Scale. |
Don't play the game. Just look at the board. If the total XOR of all numbers is exactly 0, Alice wins before touching anything. If it's not 0, count the numbers. If there's an EVEN amount of numbers, Alice is mathematically guaranteed to win. |
Draw an XOR logic gate. Feed all array elements into it. Draw a line out. If 0 -> Win. Next to it, draw a simple box that says "N % 2 == 0 -> Win". |
Single Linear Scan. $O(N)$ time. |
Draw a single, straight horizontal arrow piercing through all N elements of the array exactly once to calculate the XOR sum. |
Call Stack Tower: Draw a stack of memory frames N levels deep, representing the current game state at each turn. |
$O(1)$ Accumulator: Draw a single small box representing the running XOR sum that overwrites itself. |
| 811 |
Subdomain Visit Count |
For every string, parse it, split the domains, and linearly scan an accumulator array to see if the domain exists to update the count. |
Nested Linear Scanning. $O(N \cdot L^2)$. |
Draw a word splitting into 3 pieces. Draw arrows from each piece that must scan across a long, growing list of previously seen domains, getting slower over time. |
String Parsing + Hash Map (Frequency Counter). |
Sorting Mail into Pigeonhole Bins. |
Read "9001 discuss.leetcode.com". Split at spaces and dots. You have 9001. Drop 9001 into the "com" bin, the "leetcode.com" bin, and the "discuss.leetcode.com" bin. Add to whatever is already there. |
Draw a funnel at the top. Drop the full string in. Inside the funnel, it breaks into 2 or 3 substrings. Draw pipes routing these strings directly into Hash Map bucket squares, adding the integer value. |
Parallel $O(1)$ Lookups. $O(N \cdot L)$ time. |
Draw N timelines. Each timeline does 2 or 3 $O(1)$ hash jumps. Draw short, curved arrows representing instant teleportation to memory buckets. |
Unordered Array of Objects: Draw a long sequence of interconnected boxes. |
Hash Map: Draw a grid with random slots filled, labeled with domains and integer counts. $O(N)$ space. |
| 812 |
Largest Triangle Area |
Generate every single possible combination of 3 points (i, j, k) and calculate the area using the Shoelace formula. Keep the maximum. |
3D Combinatorial Web. $O(N^3)$ time. |
Draw N dots. Pick one dot, draw lines to all others. Pick a second dot on that line, draw lines to all remaining dots. Draw overlapping triangles until the paper is completely black. |
Convex Hull + 3 Pointers (Shoelace Formula). |
Rubber Band Wrapping. |
The largest triangle MUST have its vertices on the outermost boundary of the point cloud. Wrap a "rubber band" around the outer points (Convex Hull). Now, only run the brute-force 3-point check on the points touching the rubber band. |
Draw a scattered cloud of dots. Draw a tight boundary line connecting only the outermost dots. Erase all dots inside the shape. Draw triangles using only the boundary dots. |
Sorting Pipeline to Reduced Cubic. $O(N \log N + H^3)$. |
Draw a funnel (N log N sorting). Out comes a small subset H. Draw a small 3-layered nested loop block representing $O(H^3)$. |
Three index pointers: Draw three small arrows (i, j, k) over an array. $O(1)$ space. |
Convex Hull Array: Draw a new 1D array to store the coordinates of just the boundary points. $O(N)$ space. |
| 813 |
Largest Sum of Averages |
Recursion. Try placing the first partition wall at index 1, then solve for K-1 walls. Then try index 2, solve for K-1 walls, etc. |
Partition Tree Explosion. $O(2^N)$ time. |
Draw a long rectangular bar. Draw a cut line. From that cut, branch down and draw two more cut lines. The number of partitions grows exponentially. |
2D Dynamic Programming + Prefix Sums. |
Filling a Scorecard with Precomputed Windows. |
Precalculate all sum intervals using a Prefix Sum array. Create a DP grid: rows are "first i elements", columns are "k partitions". To fill cell (i, k), look at all previous split points (j, k-1) and add the average of the remaining chunk using the prefix sum. |
Draw a 1D Prefix Sum array at the top. Below it, draw a DP grid. To fill cell (i, k), draw arrows pointing from cells in the (k-1) column, plus an arrow pointing up to the Prefix sum to grab the $O(1)$ average. |
3 Nested Loops (Grid Traversal). $O(K \cdot N^2)$ time. |
Draw a grid (N x K). Inside one cell, draw an arrow sliding up a column N times. This visualizes the inner loop running for every cell in the grid. |
Deep Recursion Stack: Draw vertical overlapping boxes representing the $O(N)$ depth of the recursive calls. |
1D DP Array (Space Optimized): Draw a single row of N boxes that constantly overwrites itself K times. $O(N)$ space. |
| 814 |
Binary Tree Pruning |
For every single node, run a completely new DFS/BFS on its subtrees. If the subtree scan finds no '1', delete the node. |
Overlapping Subtree Scans. $O(N^2)$ time. |
Draw a tree. Highlight the whole tree (Root scan). Move to Left Child, highlight its tree (Child scan). Notice how the bottom leaves are highlighted over and over again. |
Post-Order Traversal (Bottom-Up DFS). |
Pruning Shears from the Roots Up. |
Go all the way to the bottom leaves first. Look at a leaf. Is it a '0'? Snip it off (return null to parent). Move up to the parent. Did both of its kids just get snipped off? Is the parent also a '0'? Snip it too. |
Draw a tree. Start at the bottommost '0' leaves. Cross them out with a red 'X'. Draw an arrow pointing UP to the parent. If the parent is a '0' and now childless, cross it out too. |
Single Pass Contour Trace. $O(N)$ time. |
Draw the tree. Trace a single continuous line down the left edge, looping under every single node exactly once, and traveling back up to the root. |
Heavy Call Stack: Multiple recursive stacks spawning other recursive stacks. |
$O(H)$ Call Stack: Draw a vertical stack of boxes that only ever grows as tall as the tree is deep (H). |
| 815 |
Bus Routes |
BFS treating every single bus STOP as a node. Edges connect every stop on a route to every other stop on that same route. |
Massive Dense Web (Clique Graph). $O(N^2 \cdot M)$ time. |
Draw a circle of dots (stops on a route). Draw a line from every single dot to every other dot. The graph instantly becomes a black smudge of overlapping lines. |
BFS on Busses/Routes (Bipartite-like Graph). |
Transfer Stations / Colored Train Lines. |
Instead of jumping stop-to-stop, you jump bus-to-bus. You get on the Red line. Does the Red line go to the target? No. What other lines intersect the Red line? Green and Blue. Jump to those. |
Draw big colored circles representing whole Bus Routes. Draw intersecting areas (transfer stops) linking two big circles. Count the number of circles you step into. |
Layered BFS Rings. $O(R \cdot S)$ time. |
Draw concentric ripples spreading out from a starting bus route, tracking the 'depth' or number of transfers. |
Adjacency Matrix / Gigantic Queue: Draw a massive grid tracking every single individual stop. |
Hash Map of Stop-to-Routes & Visited Set: Draw a mapping where a stop number points to a short list of bus IDs. |
| 816 |
Ambiguous Coordinates |
Nested loops to split the string into X and Y. Then nested loops to place a decimal everywhere in X, and everywhere in Y. Validate all generated strings. |
Combinatorial Explosion Forest. $O(N^4)$ time. |
Draw a string. Cut it in half. Under each half, draw every possible decimal variation. Then draw lines connecting every left variation to every right variation. |
String Parsing with Strict Validation Pruning. |
Filter Gates (Leading/Trailing Zero Rules). |
Split into X and Y. Pass X through a filter: If it has leading zeros, the decimal MUST go after the first zero. If it has trailing zeros, it CANNOT have a decimal. Generate only valid variants, then combine. |
Draw a string entering a fork (split point). Each half goes through a physical "Gate" marked with Zero-Rules. Only valid pieces come out the other side to be zipped together. |
Restricted Permutation. $O(N^3)$ time. |
Draw a small grid. The rows are valid X strings, the columns are valid Y strings. Fill the intersecting boxes. |
Massive Array of Strings: Draw huge blocks of memory holding thousands of invalid coordinate combinations before filtering. |
Small Temporary Lists: Draw two small boxes (List X, List Y) that hold a few valid strings, flushed clean on the next loop. |
| 817 |
Linked List Components |
For every node in subset G, traverse the entire linked list from the head to find it, then check if its neighbors are also in G. |
Repeated Linear Scans. $O(N \cdot M)$ time. |
Draw the linked list. Pick a number in G. Draw an arrow sliding all the way from the head to find it. Repeat for every number in G. |
Hash Set Lookup + Single Pass Traversal. |
Islands and Water. |
Put G into a Set. Walk down the linked list exactly once. If a node is in the Set, you are on "Land". If it's not, you hit "Water". Every time you transition from Land to Water, count 1 island. |
Draw a linked list. Color the nodes that exist in G green. Color the rest blue. Group the connected green nodes with a highlighter. Count the distinct highlighted groups. |
Single Straight Line + $O(1)$ checks. $O(N)$ time. |
Draw the linked list. Draw one straight arrow sweeping left to right, with tiny tick marks checking a Set box instantly. |
$O(1)$ extra space, but visualized as sluggish pointer movement overlapping constantly. |
Hash Set: Draw a bucket containing the elements of G. $O(M)$ space. |
| 818 |
Race Car |
Pure BFS. Queue holds (position, speed). Every step explores Accelerate (pos+speed, speed*2) and Reverse (pos, speed>0?-1:1). |
Infinite Binary Tree. $O(2^\text{Depth})$ time. |
Draw a car. Draw two branches (A and R). From each, draw two more. Some branches shoot off into negative infinity, creating an unbound, infinite tree. |
Dynamic Programming / BFS with Memoization & Pruning. |
Bouncing past the target and turning back. |
You want to hit target T. You accelerate A times until you cross T. Option 1: You stop, Reverse, and go back to T. Option 2: You stop right *before* T, Reverse, back up a bit, Reverse again, and go forward to T. |
Draw a number line. Draw long jumps forward past the target. Draw a U-turn arrow bouncing back. Draw another path stopping just short, backing up slightly, then jumping forward again. |
Capped State Space. $O(T \log T)$ time. |
Draw an array up to T. Draw recursive backward arrows that quickly hit pre-calculated base cases. |
Exploding Queue: Draw a horizontal tube getting endlessly stuffed with (pos, speed) tuples that never resolve. |
1D DP Array: Draw a simple array of size T+1 holding the minimum instructions to reach exactly that distance. $O(T)$ space. |
| 819 |
Most Common Word |
Iterate string, clean punctuation manually into a new string, split by space. Nested loop to check against banned words. Nested loop to count max frequency. |
Messy Nested String Manipulation. $O(N^2)$ time. |
Draw the paragraph. Draw boxes copying words char by char, scrubbing them, then scanning against a growing list of frequencies over and over. |
Regex/String Parsing + Hash Set + Hash Map. |
Word Sieve and Tally Counters. |
Pour the paragraph through a "lowercase & punctuation" sieve. Words fall out. If they match a banned word in the Set (a blocker), they are destroyed. Otherwise, they fall into a Tally Counter Map. |
Draw a text block. Draw arrows filtering it into clean words. Draw a wall (Banned Set). Valid words bypass the wall and stack up in bins. Point to the tallest bin. |
Linear Pipeline. $O(N + M)$ time. |
Draw a straight line broken into three distinct phases: Clean -> Filter -> Count. All $O(N)$. |
Multiple intermediate string arrays: Draw lots of fragmented string boxes scattered in memory. |
Hash Map (Freq) & Hash Set (Banned): Draw two neat grids holding word counts and banned strings. $O(N)$ space. |
| 820 |
Short Encoding of Words |
Sort words by length descending. For each word, check if it already exists as a suffix in our encoding string. If not, append it. |
String-in-String Search Web. $O(N^2 \cdot L)$ time. |
Draw a growing string. For every new word, draw arrows comparing it to every possible substring starting position in the master string. |
Suffix Trie (Inverted Prefix Tree). |
Nested Branching Tree (Roots at the End). |
Reverse every word ("time" -> "emit"). Insert into a Trie. Every leaf node represents a word that can't be a suffix of another. Total length = sum of (depth of leaf nodes + 1). |
Draw a root node. Draw branches for 'e' -> 'm' -> 'i' -> 't'. If "me" ("em") comes, it's already on the path, so no new leaf. Total the depth of only terminal leaves. |
Linear Character Scan. $O(Σ \text{Words})$ time. |
Draw a single path through the Trie for each character in the input exactly once. No backtracking. |
Massive String Buffer: Draw one giant continuous block of memory that keeps getting re-allocated and copied. |
Trie Nodes (Hash Maps/Arrays): Draw a tree of small interconnected node boxes. $O(Σ \text{Words})$ space. |
| 821 |
Shortest Distance to a Character |
For every index i, loop through the entire string to find all occurrences of character C, calculate distances, and take the minimum. |
Radial Scan from every point. $O(N^2)$ time. |
Draw a string. At each index, draw arrows pointing to every 'C' in the string. Repeat N times. The arrows overlap so much it becomes a blur. |
Two-Pass Min-Sweep (Left-to-Right + Right-to-Left). |
Shadows from Streetlights. |
Imagine 'C' is a streetlight. Walk Left to Right: record distance from the last light seen. Walk Right to Left: record distance from the next light. For each spot, keep the shorter distance. |
Draw the string. Sweep a pen left to right, writing distances (0, 1, 2, 0...). Sweep right to left, writing distances (2, 1, 0, 0...). Circle the smaller number in each column. |
Double Linear Pass. $O(N)$ time. |
Draw two parallel straight lines, one left-facing and one right-facing, spanning the length of the string. |
Multiple temporary distance lists: Draw overlapping arrays for each independent scan. |
One Result Array: Draw a single 1D strip of N boxes being updated in place. $O(1)$ extra space excluding result. |
| 822 |
Card Flipping Game |
Try every possible configuration of flips (2^N) and for each, find the minimum value that doesn't appear on the back of any card. |
Binary Flip Tree. $O(2^N)$ time. |
Draw a card. Branch into "Flip" and "Stay". For each branch, do it again for the next card. It becomes a standard massive decision tree. |
Hash Set (Impossible Value Filtering). |
Blacklist and Candidate Sieve. |
If a card has the SAME number on front and back, that number is "Cursed" (cannot be the answer). Put all cursed numbers in a Set. Now, scan all other numbers on all cards. The smallest one not in the Cursed Set wins. |
Draw two rows (Front/Back). Circle numbers that match vertically. Cross them out everywhere else they appear. Pick the smallest remaining number. |
Two Linear Scans. $O(N)$ time. |
Draw two horizontal lines passing through the Front and Back arrays once each. |
Recursive Stack: Draw a stack N levels deep representing the state of every card flip. |
Hash Set: Draw a single small box representing the "Blacklist" of numbers. $O(N)$ space. |
| 823 |
Binary Trees With Factors |
Recursively try to build every possible tree. For each number x, check every combination of other numbers to see if their product is x. |
Exhaustive Tree Construction. $O(\text{Exponential})$. |
Draw a number. Below it, draw all pairs that multiply to it. For each of those, draw their factors. The tree branches out wildly with many duplicate subproblems. |
DP with Hash Map + Sorting. |
Building a Pyramid from Bottom Up. |
Sort numbers. Smallest numbers are the base (1 tree each). For a larger number, look at its factors (which are already solved). Trees(x) = sum of (Trees(factor1) * Trees(factor2)) for all factor pairs. |
Draw numbers in ascending order. Draw arrows from smaller numbers pointing to their multiples. Accumulate products in a table. |
Nested Frequency Accumulation. $O(N^2)$ time. |
Draw a Half-Matrix (Triangle). Each cell (i, j) represents checking if number j is a factor of number i. |
Infinite Recursion Memory: Draw a tree of calls that duplicates the same calculations thousands of times. |
Hash Map: Draw a table with 'Number' in column 1 and 'Count of Trees' in column 2. $O(N)$ space. |
| 824 |
Goat Latin |
Split string into words. For each word, use string concatenation to move the first letter, add "ma", and then run a loop to add 'a' repeatedly. |
$O(N^2)$ String Reconstruction. |
Draw a word. Draw it being copied letter-by-letter, then a new block for "ma", then a growing block of "aaaa". Show the memory overhead for each intermediate word. |
StringBuilder / String Join with Index-based Suffix. |
Assembly Line Word Processing. |
Treat each word as a car on a belt. If it starts with a vowel, tack on "ma". If a consonant, move the first letter to the back and tack on "ma". Append "a" based on the car's position index. |
Draw words moving through a "Latin Machine". Word 1 gets "a", Word 2 gets "aa". Show the letters being appended in-place or in a single buffer. |
Linear Scan with Quadratic Suffix growth. $O(N^2)$ total due to 'a's. |
Draw a timeline that gets slightly thicker as it moves to the right, representing the increasing 'a' suffixes. |
Heap Fragmentation: Draw many small, temporary string boxes being discarded by the Garbage Collector. |
StringBuilder Buffer: Draw one long, expandable rectangular block that collects all parts in a single pass. $O(N^2)$ space for result. |
| 825 |
Friends Of Appropriate Ages |
Nested loops comparing every person i with every person j (N^2) to check the three age conditions. |
Full All-Pairs Matrix. $O(N^2)$. |
Draw a square grid of size N \times N. Shade in every single cell to represent checking every combination. |
Frequency Map + Binary Search or Sliding Window. |
Age Bucket Histogram with Range Sums. |
Group people into 120 age buckets. For each age A, calculate the valid range [0.5A+7, A]. Multiply count of age A by count of people in that range. |
Draw a bar chart (histogram) of ages 1-120. For one bar, draw a bracket over the other bars it can "friend." |
Linear Bucket Scan. $O(N + 120)$. |
Draw a short line of 120 ticks. This represents constant time work regardless of how many thousands of people (N) there are. |
$O(1)$ pointers, but draw two arrows (i, j) scanning a massive array over and over. |
120-size Int Array: Draw a small fixed-size strip of boxes labeled 1 to 120. |
| 826 |
Most Profit Assigning Work |
For every worker, loop through the entire list of jobs to find the one they can do that yields the highest profit. |
Bipartite Search Web. $O(W \\text{times} J)$. |
Draw a column of workers and a column of jobs. Draw lines from every worker to every job they are capable of doing. |
Sorting + Two Pointers (Greedy). |
Ascending Skill-to-Profit Escalator. |
Sort jobs by difficulty. Sort workers by skill. Move through jobs once; as worker skill increases, the "best profit seen so far" only ever goes up. |
Draw two parallel sorted lists. Draw a pointer on the jobs that moves forward as the worker pointer moves forward. Never move backward. |
Sorting Bottleneck. $O(J \log J + W \log W)$. |
Draw two "Sorting Funnels" followed by a single parallel linear scan. |
No extra space, but visualized as highly redundant CPU cycles. |
Sorted Pair Array: Draw an array where each cell is a (Difficulty, Profit) tuple. |
| 827 |
Making A Large Island |
For every '0' in the grid, flip it to '1' and run a full BFS/DFS to calculate the size of the resulting island. |
Grid-wide Flood Fill per Cell. $O(N^4)$. |
Draw a grid. For every empty cell, draw a "splash" that fills the whole grid. Do this for every single empty cell. |
Component Labeling (Island ID) + Hash Map. |
Color-Coded Map Regions. |
Pre-calculate all island sizes and give each a unique ID (Color). Then, for each '0', check its 4 neighbors, sum the sizes of *unique* adjacent colors, plus 1. |
Draw a grid with clusters colored Red, Blue, Green. Pick a '0'. If it touches Red and Blue, Result = Size(Red) + Size(Blue) + 1. |
Two-Pass Linear Scan. $O(N^2)$. |
Draw the grid once with a highlighter (labeling) and a second time with a pen (checking zeros). |
Recursive Stack: Draw a stack depth of N^2 for every single '0' cell. |
ID Map: Draw a 2D grid storing integers (IDs) and a Map storing `ID -> Size`. |
| 828 |
Count Unique Characters of All Substrings |
Generate every substring (N^2), and for each, loop through to count characters that appear exactly once (N). |
Substring Cubic Scan. $O(N^3)$. |
Draw a string. Draw every possible bracket range. Inside each bracket, draw a tally mark for every character. |
Contribution of Each Character (Index tracking). |
Broadcast Range of Uniqueness. |
A character at index i is unique for all substrings starting after its *previous* occurrence and ending before its *next* occurrence. Count = (i - prev) \times (next - i). |
Draw a string. Pick a letter 'A'. Draw an arrow back to the last 'A' and forward to the next 'A'. The distance defines its "Contribution Zone." |
Single Pass with Map. $O(N)$. |
Draw a single straight line through the string, with letters "contributing" their calculated values to a total sum. |
Massive list of strings: Draw thousands of small string blocks representing every substring. |
Index Map: Draw a Map where each key is a char and value is a list of its 2 most recent indices. |
| 829 |
Consecutive Numbers Sum |
For every starting number i, keep adding i+(i+1)+(i+2)... until you hit N (match) or exceed N (fail). |
Arithmetic Expansion Search. $O(N^2)$. |
Draw a number line. Draw a bracket of length 2, then length 3, sliding them across the whole line until you reach N. |
Algebraic Factorization (N = kx + \frac{k(k-1)}{2}). |
Triangular Number Offset. |
For a sequence of length k, the sum is k numbers plus the k-th triangular number. Subtract the triangular number from N; if the remainder is divisible by k, a sequence exists. |
Draw N as a pile of blocks. Remove a triangle of blocks from the top. Can the remaining blocks be divided into k equal columns? |
Square Root Math. $O(\\text{sqrt}{N})$. |
Draw a timeline that stops very early (at \sqrt{2N}), showing the loop terminates much before N. |
Accumulator variables: Draw a "Sum" box that gets reset millions of times. |
$O(1)$ Space: Draw 2-3 integer variables doing simple arithmetic. |
| 830 |
Positions of Large Groups |
Check every possible substring to see if it consists of the same character and has a length \ge 3. |
Nested Range Scanner. $O(N^2)$. |
Draw a string. Draw brackets of size 3, 4, 5... starting at every index, checking each letter inside. |
Two Pointers (Start and End of Run). |
Accordion Stretch. |
Place a 'start' pointer at index 0. Move an 'end' pointer forward until the character changes. If `end - start >= 3`, record the group. Jump 'start' to 'end'. |
Draw a string. Draw a bracket that expands as long as letters match. When it hits a different letter, "snip" the bracket and start a new one. |
Single Linear Scan. $O(N)$. |
Draw one straight horizontal line that never backtracks, with markers where groups are found. |
Intermediate strings: Draw multiple copies of substrings being stored in memory temporarily. |
$O(1)$ Pointers: Draw two small arrow icons (i and j) hovering over the original string. |
| 831 |
Masking Personal Information |
Use complex, multi-layered nested `if-else` blocks and string concatenations to handle every specific character edge case for both email and phone. |
Spaghetti Logic Flow. $O(N)$. |
Draw a flowchart with 20 different branching paths that loop back and overlap, making logic tracing difficult. |
Standardization via Pre-filtering + Template Mapping. |
The "Identity Shredder." |
Check for '@'. If present (Email): lowercase everything, keep first/last char of name, and middle is `*****`. If absent (Phone): strip all non-digits, keep last 4, and prefix based on digit count. |
Draw a box labeled "Sieve." Email goes in one pipe, Phone in another. Out comes a uniform, pre-defined template string. |
Linear Scan/Replace. $O(N)$. |
Draw a timeline. One pass to clean/identify, one pass to build the result string. |
Multiple temporary string fragments: Draw scattered blocks of memory for each partial mask. |
Single StringBuilder: Draw one expandable buffer that builds the final masked string in one go. |
| 832 |
Flipping an Image |
Create a brand new matrix. Iterate through the old matrix, calculate new indices, and then run a second loop to invert 0s and 1s. |
Multi-Pass Grid Copy. $O(N^2)$. |
Draw two grids. Draw arrows from row 1 of Grid A to row 1 of Grid B in reverse. Then draw a "flip switch" over every cell in Grid B. |
Two Pointers In-Place (Symmetry Swap). |
Reflective Mirror Fold. |
For each row, use two pointers (Left, Right). If they point to the same value, invert both (XOR 1). If different, they cancel out during the flip/invert, so do nothing. |
Draw a grid. Draw a vertical dotted line down the center. Fold the paper at the line and imagine 0s turning into 1s where they overlap. |
Single Pass In-Place. $O(N^2)$. |
Draw a grid. Draw one arrow across each row that processes both ends of the row simultaneously. |
Full N \times N Copy: Draw two identical large memory blocks side-by-side. |
In-Place Modification: Draw one grid with small 'i' and 'j' arrows inside the rows. $O(1)$ extra space. |
| 833 |
Find And Replace in String |
Iteratively find a match, use string slicing to remove the old part and insert the new part. Repeat for every replacement. |
$O(N \cdot K \cdot L)$ String Shifting. |
Draw a string. For every replace, erase a chunk and push all remaining letters to the right to make space. Note how many times you move the tail. |
Descending Order Sorting or Single-Pass Mapping. |
"Post-it Note" Overlay. |
Identify all valid matches first. Store them in a map `index -> length, replacement`. Build a new string by scanning the original; if an index has a "post-it," use the replacement and skip `length` chars. |
Draw the original string. Draw "post-it notes" above the specific indices that need replacement. Copy everything to a new line, using notes where they exist. |
Linear Building. $O(N + \\text{text}{\text{Replacements}})$. |
Draw a timeline. Each character or replacement is visited exactly once from left to right. |
Repeated Re-allocations: Draw dozens of shrinking and growing memory blocks. |
Index Map + StringBuilder: Draw a Map for lookup and one final large buffer for construction. |
| 834 |
Sum of Distances in Tree |
For every node i, run a full BFS or DFS to calculate the distance to every other node j, and sum them. |
Repetitive Graph Traversal. $O(N^2)$. |
Draw a tree. Pick node 1, highlight the whole tree. Pick node 2, highlight the whole tree again. Repeat N times. |
Re-rooting DP (Post-order + Pre-order DFS). |
Centrifugal Force / Balancing Scales. |
1. Bottom-up: Count subtree sizes and sum distances for root. 2. Top-down: As you move from parent to child, `Dist(child) = Dist(parent) - Count(child_subtree) + (N - Count(child_subtree))`. |
Draw a tree. Calculate total distance for the Root. As you "slide" the root to a child, visualize the child's side getting closer (-1 per node) and the rest of the tree getting further (+1 per node). |
Two-Pass DFS. $O(N)$. |
Draw the tree with one green arrow going UP (post-order) and one blue arrow going DOWN (pre-order). |
Adjacency List + BFS Queues: Draw a large graph structure plus N separate queue frames. |
Two Result Arrays + Recursion Stack: Draw three N-sized strips (Count, Sum, Result) and a stack of height H. |
| 835 |
Image Overlap |
Try every possible shift (dx, dy) in range [-N, N]. For each shift, iterate through the overlapping area and count matching 1s. |
Sliding Glass Overlap. $O(N^4)$. |
Draw two N \times N squares. Shift the top one pixel by pixel. For every single pixel shift, draw a grid of dots representing the nested check loops. |
List of Coordinates + Delta Frequency Map. |
Vector Offset Tallies. |
Extract coordinates of all '1's in Matrix A and Matrix B. Calculate the vector distance (delta) between every pair (a, b). The delta that appears most frequently is the optimal shift. |
Draw two sparse grids. List coordinates of 1s. Draw arrows (vectors) connecting every point in A to every point in B. Circle the arrows that have the same length and direction. |
Coordinate Product Scan. $O(N^2 + L_A \\text{times} L_B)$. |
Draw a timeline for extracting 1s, then a nested loop visualization restricted only to the number of 1s (L), not the grid size (N). |
$O(1)$ excluding input, but massive CPU cycles visualizing nested index arithmetic. |
Hash Map of Deltas: Draw a map where keys are "(dx, dy)" and values are counts. $O(N^2)$ max space. |
| 836 |
Rectangle Overlap |
Check if any corner of rectangle 1 is inside rectangle 2, OR if any edge of rectangle 1 intersects any edge of rectangle 2. |
Point-in-Polygon Check. $O(1)$ but logically messy. |
Draw two boxes. Draw a flowchart with 8 different conditional checks for corners and edges. |
1D Projection (Interval Overlap). |
Shadow Alignment. |
Project both rectangles onto the X-axis and Y-axis. They overlap IF and ONLY IF their X-shadows overlap AND their Y-shadows overlap. |
Draw two rectangles. Draw a light source above them to cast shadows on the ground (X) and a light on the side for the wall (Y). Check for overlap on both lines. |
Constant Time Logic. $O(1)$. |
Draw a single "Logic Gate" symbol. Input 4 coordinates, output 1 boolean. |
Temporary coordinate variables: Draw a few small integer boxes. |
$O(1)$ Space: Draw four simple comparison variables. |
| 837 |
New 21 Game |
Recursion with Memoization: For every state (current points), calculate the probability by summing probabilities of all possible next draws (1 to W). |
Wide Probability Tree. $O(N \\text{times} W)$. |
Draw a root (0). Branch out W times. From each child, branch out W times again. Show the repetitive states overlapping. |
Sliding Window DP. |
Running Water Reservoir. |
Keep a "window sum" of the previous W probabilities. As you move to the next point, subtract the probability that fell out of the window and add the new one. This calculates the average in $O(1)$. |
Draw a 1D DP array. Draw a sliding bracket of width W. As the bracket slides right, the value in the next cell is `windowSum / W`. |
Linear Probability Pass. $O(N)$. |
Draw a single horizontal line. Each point is calculated using a sliding window that moves forward exactly once. |
Memoization Table: Draw a large N-sized array. |
DP Array + Window Sum: Draw a single N-sized strip of floats and one "Sum" variable. |
| 838 |
Push Dominoes |
Simulate second-by-second. In each second, look at every domino and decide if it falls based on its neighbors' state from the *previous* second. |
Time-Step Simulation. $O(N \\text{times} \\text{text}{\text{Time}})$. |
Draw the dominoes. Draw a new row for T=1, T=2... showing the ripple effect until no more changes occur. |
Two-Pass Force Calculation or Two-Pointer Segmenting. |
"Gravity Fields" from L and R. |
Calculate the "Force" from the nearest 'R' on the left (decays with distance) and 'L' on the right. Sum the forces: positive is 'R', negative is 'L', zero is vertical. |
Draw the dominoes. Draw green arrows pointing right from every 'R' that get smaller. Draw blue arrows pointing left from every 'L'. Subtract the arrow sizes at each dot. |
Two-Pass Linear Scan. $O(N)$. |
Draw two parallel timelines (Left-Pass and Right-Pass) merged into a final result timeline. |
Grid of Time-Steps: Draw multiple N-sized arrays for each second of simulation. |
One Force Array: Draw a single 1D strip of N integers being updated. |
| 839 |
Similar String Groups |
For every string, compare it with every other string (N^2). For each comparison, check similarity by counting character mismatches (L). Use BFS to find groups. |
All-Pairs Similarity Matrix. $O(N^2 \\text{times} L)$. |
Draw a column of strings. Draw lines between all pairs. For every line, draw a sub-timeline comparing letters one-by-one. |
Union-Find with Optimized Similarity Check. |
Bubble Merging. |
Treat each string as a node. If two strings are "similar" (mismatch count 0 or 2), Union them. The answer is the number of disjoint sets (roots) remaining. |
Draw strings as floating bubbles. When a similarity is found, draw a string connecting the bubbles. Use a "Master Parent" pointer for each cluster. |
Amortized Graph Clustering. $O(N^2 \\text{times} L)$. |
Draw a grid where you only fill cells if a similarity test is needed, with "Path Compression" shortcutting the lookups. |
Adjacency List + Queue: Draw a massive graph and a growing BFS queue. |
Parent Array (DSU): Draw a single N-sized array storing integer indices. |
| 840 |
Magic Squares In Grid |
Iterate through every possible 3x3 subgrid. For each, use nested loops to calculate row sums, column sums, and diagonal sums. Also check if digits 1-9 are unique. |
Overlapping Sliding Window Scan. $O(R \\text{times} C)$. |
Draw a large grid. Draw a small 3x3 red square. Shift it right one pixel at a time. Inside each square, draw 8 arrows (3 horizontal, 3 vertical, 2 diagonal). |
Pruning + Constant-Time Symmetry Check. |
Center-Outward Filtering. |
A magic square's center MUST be 5. Scan the grid for 5s. For every 5 found, check if its 8 neighbors contain only digits 1-9 (excluding 5) and if the corners are even/edges are odd. |
Draw the grid. Circle every '5'. Draw a crosshair (+) and an 'X' over the 5 to quickly sum the opposing neighbors. They must all sum to 10 (5 \times 2). |
Filtered Linear Scan. $O(R \\text{times} C)$. |
Draw a grid. Draw a single path that only "pauses" and does work when it hits a cell containing 5. |
$O(1)$ extra variables, but visualized as heavy repetitive arithmetic overhead. |
$O(1)$ Checksum: Draw a boolean array of size 10 to track digits 1-9. |
| 841 |
Keys and Rooms |
Start in room 0. For every key you find, restart a full scan of the rooms array to see if you can now enter any previously locked room. Repeat until no new rooms are found. |
Restarted Linear Scans. $O(N^2)$. |
Draw rooms as boxes. Draw an arrow from room 0 to its keys. Then redraw the whole diagram from scratch for the next key found. |
Graph Traversal (BFS or DFS) with Visited Set. |
Unlocking a Chain Reaction. |
Start at Room 0. Put keys into a Stack. Pop a key, enter that room. If not visited, mark visited and add its keys to the Stack. At the end, check if Visited Count == Total Rooms. |
Draw a line of rooms. Draw a "Visited" checkbox under each. Draw arrows from room-to-room representing the keys. Color a room green once visited. |
Single Pass Traversal. $O(N + E)$ where E is keys. |
Draw the graph. Trace each edge (key) exactly once. No backtracks or restarts. |
List of lists: Draw multiple overlapping lists of "newly opened" rooms. |
Stack + Visited Set: Draw a vertical "Key Bucket" (Stack) and a bit-strip (Visited) of size N. |
| 842 |
Split Array into Fibonacci Sequence |
Use backtracking to try splitting the string at every possible index to form the first number, then every possible second number, then check if the rest follows the rule. |
Exponential Partition Tree. $O(10^N)$. |
Draw a string. Branch out to try splitting "1", "12", "123". From each, branch again. The tree grows based on string length. |
Backtracking with Fibonacci Pruning & Integer Overflow check. |
The "Rule of Two" Dominoes. |
You only need to pick the first two numbers. Once A and B are picked, the third MUST be A+B. Search the remaining string for exactly A+B. If it's there, continue; if not, backtrack the first two numbers. |
Draw a string. Draw two brackets for the first two numbers. Use a calculator icon to sum them, and draw a "searchlight" looking for that sum in the remaining string. |
Polynomial Backtracking. $O(N^2)$. |
Draw a grid where rows are possible lengths of first number and columns are lengths of second number. The work only happens on the valid "edges." |
Massive recursion stack: Draw a stack N levels deep with hundreds of string fragments. |
Result List: Draw a single 1D array of integers that grows and shrinks as you backtrack. |
| 843 |
Guess the Word |
Pick a word at random. Guess it. If not the answer, remove just that one word and repeat. |
Linear Elimination. $O(N \\text{times} 10)$. |
Draw a list of 1000 words. Cross out one. Pick another. Cross out another. This would take too many guesses (limit is 10). |
Minimax / Information Theory (Heuristic Guessing). |
Shrinking the Search Space (Sieve). |
Pick the word that has the most matches with others (highest overlap). Guess it. If the master returns k matches, throw away all words that DON'T have exactly k matches with your guess. |
Draw a large circle of dots. Pick one dot. Draw lines to all dots that match it in k places. Erase all dots NOT connected by those lines. The circle shrinks rapidly. |
Probability-weighted Reduction. $O(10 \\text{times} N)$. |
Draw a funnel. 1000 words enter. 1 guess pass = 100 words left. 2 guess passes = 10 words left. |
Full list scan: Draw the original array repeatedly. |
Candidate List: Draw a list that gets filtered and replaced in each iteration. |
| 844 |
Backspace String Compare |
Iterate through both strings and build two new strings using a Stack. If you see '#', pop. At the end, compare the two built strings. |
Simulation via Stack. $O(N)$. |
Draw two strings. For each, draw a "Result" box. Draw letters jumping into the box and being erased by #. Compare the two final boxes. |
Two Pointers (Reverse Scanning). |
The "Reverse Eraser." |
Start from the END of both strings. If you see '#', increment a "skip" counter. Skip letters while skip > 0. Compare the first non-skipped letters. Move backward. |
Draw two strings. Place pointers at the last indices. Draw a "Skip Counter" bubble next to each. Move pointers left, decrementing counter for letters and incrementing for #. |
Single Pass In-Place. $O(N)$. |
Draw two parallel timelines with arrows moving from right to left, stopping at the same points. |
Extra Strings/Stacks: Draw two new memory blocks of size N. |
$O(1)$ Space: Draw two integer pointers (i, j) and two "Skip" variables. |
| 845 |
Longest Mountain in Array |
For every index i, expand outward to the left (decreasing) and right (decreasing) to check if it forms a mountain. Keep the max length. |
Radial Expansion from every Peak. $O(N^2)$. |
Draw an array. At every single element, draw two arrows pointing outward. Note how the arrows overlap and re-scan the same values repeatedly. |
Two-Pass Precomputation OR One-Pass State Machine. |
Mountain Peak Detection (Up-Down Counter). |
Scan for a slope increase. Once it starts, keep going (Upwards). If you hit a peak followed by a decrease, keep going (Downwards). If it's up AND down, it's a mountain. |
Draw the array as a line graph. Use a highlighter to mark the "up-slope" segments and a different color for "down-slope." Mountains are where the colors touch. |
Linear Scan. $O(N)$. |
Draw one straight horizontal line with "Up" and "Down" state labels above specific segments. No backtracking. |
$O(1)$ pointers, but draw redundant CPU cycles as multiple overlapping scan arrows. |
Two 1D Arrays (Up/Down) or $O(1)$ Space: Draw two counters that reset on flat ground. |
| 846 |
Hand of Straights |
Sort the array. For every card, search the rest of the array for the next (groupSize - 1) consecutive numbers and remove them. Repeat until empty. |
Sorted Search and Erase. $O(N^2)$. |
Draw a list of numbers. Pick the smallest. Scan the entire list to find the next number, erase it, and start over. Every erasure requires a full scan. |
TreeMap / Frequency Map + Smallest Element Processing. |
Deck Tally and Subtraction. |
Count all cards. Start with the smallest card X. It *must* be part of a group [X, X+1, ... X+W-1]. Subtract the count of X from all cards in that range. If any count goes below zero, return false. |
Draw a bar chart of card counts. Pick the first non-zero bar. Draw a "Group Box" that covers W bars and lowers their heights by the height of the first bar. |
Sorting + Linear Map Scan. $O(N \log N)$. |
Draw a Sorting Funnel, then a single pass through the sorted keys of the Map. |
$O(1)$ extra space but visualized as a "Swiss Cheese" array with holes (nulls) everywhere. |
Frequency Map: Draw a table of Card Value -> Count. $O(N)$ space. |
| 847 |
Shortest Path Visiting All Nodes |
Generate every permutation of nodes and calculate the shortest path to traverse them in that specific order. |
Traveling Salesperson Explosion. $O(N!)$. |
Draw N nodes. Draw paths for [1,2,3,4], then [1,2,4,3], then [1,3,2,4]... The list of permutations becomes a massive, dense block of text. |
BFS on (CurrentNode, VisitedMask) State Space. |
Multi-Source Ripple in 2D State Space. |
Use a bitmask to represent visited nodes. State = (node, mask). Start BFS from all nodes simultaneously with their initial masks. The first state to reach mask `(1 << N) - 1` is the shortest path. |
Draw a grid where rows are Nodes and columns are Bitmasks (0-2^N). Draw arrows showing transitions between "states" as you move and update masks. |
Capped State Space. $O(N \\text{times} 2^N)$. |
Draw a 2D matrix of size N \times 2^N. Each cell is visited exactly once in the BFS. |
Massive permutation list: Draw a stack N! levels high. |
Visited 2D Array / Set: Draw a grid of size 12 \times 4096 (for max N=12). |
| 848 |
Shifting Letters |
For every shift at index i, run a loop from 0 to i and shift each character by the given amount. |
Nested Prefix Shifts. $O(N^2)$. |
Draw a string. For the first shift, update 1 char. For the second, update 2. For the N-th, update N. Draw the overlapping work as a triangle of arrows. |
Suffix Sum of Shifts. |
Cumulative Downstream Force. |
The total shift for character i is the sum of all shifts from i to N-1. Calculate these sums from right to left (Suffix Sum), then apply them in one pass. |
Draw the string. Above it, draw the "Shifts" array. Draw a "Rolling Total" bubble that moves from right to left, picking up shift values and adding them to the total. |
Two Linear Passes. $O(N)$. |
Draw two straight parallel timelines. One for the suffix sum, one for the character rotation. |
$O(1)$ space but high repetitive modification cycles. |
$O(1)$ variable (for suffix sum): Draw one "Current Shift" box that overwrites itself N times. |
| 849 |
Maximize Distance to Closest Person |
For every empty seat '0', loop left to find the nearest '1' and loop right to find the nearest '1'. Take the min, then find the global max of these mins. |
Radial Search from Every Zero. $O(N^2)$. |
Draw a row of seats. At every '0', draw two arrows stretching out until they hit a '1'. Notice how many times the same '1's are hit by arrows. |
Two-Pass Distance Arrays OR Two Pointers (Gap Tracking). |
Longest Zero-Gap Measurement. |
Find the lengths of all "0" gaps. The max distance in a middle gap is `(length + 1) / 2`. Edge gaps (start or end) have a max distance equal to the total length of the gap. |
Draw the seats. Highlight the continuous blocks of zeros. Measure the width of each block. Write the "Max Distance" result for each block using the gap rules. |
Single Linear Scan. $O(N)$. |
Draw a single horizontal timeline. Mark '1's as milestones and measure the distance between them once. |
Multiple temporary distance lists: Draw overlapping arrays for each scan. |
Two Pointer Variables: Draw 'last_person' and 'current_seat' arrows. $O(1)$ space. |
| 850 |
Rectangle Area II |
Discretize all x and y coordinates into a grid of very small units. For every rectangle, mark all the grid units it covers. Sum the area of marked units. |
Unit Grid Summation. $O(N^3)$. |
Draw a coordinate plane. Draw overlapping boxes. Divide the whole area into tiny graph-paper squares and count every single square one by one. |
Line Sweep + Segment Tree (or Coordinate Compression). |
Scanning Laser Beam. |
Imagine a vertical line (the laser) moving from left to right. At every "event" (left or right edge of a rectangle), update the set of active vertical intervals and calculate the area of the vertical strip. |
Draw rectangles. Draw a vertical dashed line sliding across. At each stop, highlight the parts of the dashed line that are "inside" any rectangle. Multiply that length by the distance to the next stop. |
Event-Driven Sweep. $O(N \log N)$. |
Draw a timeline with 2N ticks. Each tick represents a "Pause" where $O(\log N)$ work is done to update a Segment Tree. |
2D Boolean Matrix: Draw a massive grid where thousands of cells are marked True/False. |
Segment Tree Nodes: Draw a balanced binary tree where each node tracks "Active Length" and "Cover Count." |
| 851 |
Loud and Rich |
For every person i, run a full DFS to find every person richer than them. Among all those found, look up their quietness and pick the minimum. |
Independent Redundant DFS. $O(N^2)$. |
Draw a graph of people. For Person A, trace all paths "upwards." For Person B, trace all paths "upwards." Notice how you traverse the same "Rich" nodes repeatedly. |
Topological Sort (Kahn’s) or Memoized DFS. |
Waterfall Inheritance. |
Start with the richest people (those with no one richer). Their "quietest richer person" is themselves. Pass this information down to everyone they are directly richer than. Keep the min of all incoming "quietest" values. |
Draw the graph with arrows from rich to poor. Color nodes from top to bottom. As color flows down, it carries the "minimum quietness" value like a liquid filling containers. |
Directed Acyclic Graph (DAG) Traversal. $O(V + E)$. |
Draw the graph and put a single checkmark on every edge. Every edge is processed exactly once. |
Multiple separate recursion stacks: Draw N vertical towers side-by-side. |
Answer Array (Memo): Draw a single strip of N boxes that store the final quietest ID once computed. |
| 852 |
Peak Index in a Mountain Array |
Linear scan the array from index 0 until you find an element that is larger than the next one (A[i] > A[i+1]). |
Linear Search. $O(N)$. |
Draw a line graph. Draw an arrow sliding from left to right, stopping only when the line starts to dip. |
Binary Search on Slope Direction. |
High-Low Hot/Cold game. |
Pick the middle element. Is the slope going up (mid < mid+1)? Then the peak is to the right. Is the slope going down? Then the peak is to the left or is the current index. |
Draw a mountain. Draw two pointers (L, R) at the bases. Draw a mid point. Draw a small tangent line at mid to see if it points up or down, then move L or R. |
Logarithmic Reduction. $O(\log N)$. |
Draw the array length. Cut it in half, then half again, showing only 3-4 steps for a huge array. |
$O(1)$ pointer: Draw one arrow index. |
$O(1)$ pointers: Draw L, R, mid arrow indices. |
| 853 |
Car Fleet |
Simulate the race second-by-second. In each second, move every car, check for collisions (fleets), and update speeds. Stop when all cars reach the target. |
Time-Step Simulation. $O(\\text{text}{\text{Time}} \\text{times} N)$. |
Draw a track. Draw dots for cars. Draw the track again for T=1, T=2... showing cars bunching up over time. |
Sorting + Monotonic Arrival Times. |
"Shadow" Arrival Times. |
Calculate the time each car *would* take to reach the target if alone (Time = (Target - Pos) / Speed). Sort cars by position (closest to target first). If a car behind takes LESS time than the car in front, they merge into one fleet. |
Draw cars on a line. Above each, write their "Independent Arrival Time." Look at them from right to left. If you see a "slow" time, any "faster" times to its left get absorbed into it. |
Sorting Bottleneck. $O(N \log N)$. |
Draw a Sorting Funnel, then one single right-to-left scan of the calculated times. |
Track State History: Draw many arrays representing snapshots of car positions at every second. |
Time Array: Draw an array of floats representing arrival times. $O(N)$ space. |
| 854 |
K-Similar Strings |
Generate every possible permutation of the first string and check which one matches the second string with the minimum number of swaps. |
Permutation Tree. $O(N!)$. |
Draw String A. Draw every possible single swap. From those, draw every possible second swap. The tree grows factorially. |
BFS with State Pruning (Shortest Path in String Graph). |
Breadth-First String Morphing. |
Treat each string as a node in a graph. A swap is an edge. Find the first index i where A[i]
eq B[i]. Find all j > i where A[j] == B[i] and swap them to create next states. BFS ensures the first time you hit String B, it's the min swaps. |
Draw String A at the top. Draw arrows to strings that are 1 swap away (only swapping at the first mismatch). Use a "Visited" set to avoid loops. |
Capped BFS. $O(\\text{text}{\text{States}} \\text{times} N)$. |
Draw a circle of "Visited Strings." Draw ripples moving outward from the start string until the target string is "touched." |
Exhaustive List: Draw every permutation of the string in memory. |
Queue + Visited Set: Draw a queue of string states and a hash set storing seen strings to prevent cycles. |
| 855 |
Exam Room |
Maintain a sorted list of seated students. For every seat() call, iterate through all gaps between students to find the largest distance. |
Linear Gap Scan. $O(N)$ per seat. |
Draw a row of seats. For every student added, draw arrows measuring every single empty space between students 'X'. |
Max-Heap (Priority Queue) of Intervals. |
The "Largest Void" Picker. |
Store every empty gap as an interval [start, end] in a Heap. The Heap is ordered by the distance to the closest student. seat() pops the best interval, splits it, and pushes two new ones back. |
Draw a number line. Draw arcs representing empty gaps. The Heap always points to the "fattest" arc. When someone sits, split the fat arc into two thinner arcs. |
Logarithmic Seat/Leave. $O(\log N)$. |
Draw a Tree structure. Each operation involves traveling from the root to a leaf (height of tree). |
Sorted List: Draw a 1D array that requires element shifting on every insertion. |
Priority Queue + Map: Draw a Binary Heap (Tree) and a Map to track student-to-interval links. |
| 856 |
Score of Parentheses |
Find matching pairs recursively. Split the string into (A) and AB components and calculate score for each sub-problem independently. |
Deep Recursive Tree. $O(N^2)$. |
Draw the string. Circle a group. Draw a branch to a new line for that group. Redundantly re-calculate scores for identical inner nested structures. |
Stack or "Core Value" Summation. |
Depth-Based Multiplier. |
The only parentheses that actually add value are the "cores" like (). Every ( you enter doubles the power of future cores. Every ) halves it. Total score = Sum of 2^{\text{depth}} for every () found. |
Draw the string. Below it, draw a "Power" variable. When you see (, Power \times 2. When you see ), Power / 2. When you see (), add the current Power to Total. |
Single Pass Scan. $O(N)$. |
Draw a straight timeline. Mark points where () occurs and note the multiplier at that specific timestamp. |
Recursion Stack: Draw a stack N/2 frames deep storing partial strings. |
$O(1)$ Variable: Draw two small boxes: "Current Power" and "Total Score." |
| 857 |
Minimum Cost to Hire K Workers |
For every worker i, assume they are the "wage captain" (the one whose ratio is used). Calculate wages for everyone else and pick the K cheapest. |
Nested Comparative Wage Scan. $O(N^2)$. |
Draw a list of workers. Pick the first. Draw lines to all others to calculate their price based on worker 1. Repeat for every worker. |
Sorting (by Ratio) + Max-Heap (for Quality). |
The "Value-to-Bulk" Sieve. |
Sort workers by "Expectation Ratio" (Wage / Quality). Slide a window of K workers. Use a Max-Heap to keep the K workers with the *lowest* total quality. As Ratio increases, total cost = CurrentRatio \times Sum(K\_Lowest\_Qualities). |
Draw workers sorted by their "Greediness" (Ratio). As you move right, you must pay everyone more. To keep cost low, use a "Quality Bucket" (Heap) to kick out the "bulkiest" (highest quality) worker. |
Sorting + Heap Traversal. $O(N \log N)$. |
Draw a Sorting Funnel followed by a window sliding over a list, with a Heap "pop/push" happening at each step. |
Repeated Sorting: Draw multiple temporary sorted arrays being generated. |
Max-Heap of Size K: Draw a small tree structure that only ever holds K elements. |
| 858 |
Mirror Reflection |
Simulate the laser beam physics. Calculate the y-coordinate at every wall hit (x=0, x=p) until y is exactly 0 or p. |
Point-by-Point Physics Simulation. $O(\\text{text}{\text{Intersections}})$. |
Draw a square. Draw a zig-zag line bouncing off walls. Track the coordinates manually until you hit a corner. |
Mathematical Least Common Multiple (LCM). |
The "Infinite Mirror Stack." |
Instead of bouncing the beam, imagine the room reflects upward infinitely. The beam is a straight line. It hits a corner when the total vertical distance (m \times q) equals the total horizontal distance (n \times p). Use GCD to simplify p and q. |
Draw a square. Above it, stack identical squares like a skyscraper. Draw one straight diagonal line from the bottom-left. See which floor and side it hits. |
Logarithmic GCD. $O(\log(\\text{min}(P, Q)$)). |
Draw the Euclidean Algorithm steps (repeated subtraction or modulo). Very few steps needed. |
Simulation Variables: Draw several float boxes (x, y, dx, dy) that update millions of times. |
$O(1)$ Space: Draw two integer variables P and Q. |
| 859 |
Buddy Strings |
Generate every possible single-swap permutation of String A and check if any of them equal String B. |
Permutation Matching. $O(N^2)$. |
Draw String A. Pick two letters, swap them, draw the result. Compare to B. Repeat for all \frac{N(N-1)}{2} pairs. |
Case-Based Comparison (Counter + Mismatch Pointer). |
The "Spot the Difference" Check. |
1. If lengths differ, False. 2. If A == B, check if A has any duplicate letter (swap them). 3. If A
eq B, find all indices where A[i]
eq B[i]. There MUST be exactly 2 differences, and A[i], A[j] must match B[j], B[i] cross-wise. |
Draw two strings. Trace your finger across both. When they differ, draw a circle. If you have 3 circles, stop (False). If 2 circles, check if they can "swap" to match. |
Single Pass Scan. $O(N)$. |
Draw a single straight line through both strings. No backtracking. |
Heap Copying: Draw N^2 different string objects being created in memory. |
List of Indices: Draw a small array that holds only 2 integers (mismatch positions). |
| 860 |
Lemonade Change |
Maintain an array of every bill received. For change, use a nested loop to search the array for combinations that sum to 5 or 15. |
Exhaustive Combination Search. $O(N^2)$. |
Draw a wallet getting stuffed with 5, 10, 20. For every new customer, draw arrows scanning through every single bill in the wallet to find change. |
Greedy Billing (Counter-based). |
Cashier's Till Logic. |
Only track the COUNT of 5 and 10 bills. When you need to give 15 change, ALWAYS try to give one 10 and one 5 first. Saving 5 bills is greedy because they are more "flexible" than 10s. |
Draw two bins: "5s" and "10s". When a 20 bill arrives, take one from the 10-bin and one from the 5-bin. If the 10-bin is empty, take three from the 5-bin. |
Single Linear Scan. $O(N)$. |
Draw a single straight line. Each customer is a $O(1)$ update to the counters. |
Dynamic List: Draw an array that grows to size N as the day progresses. |
$O(1)$ Space: Draw two integer variables 'five' and 'ten'. |
| 861 |
Score After Flipping Matrix |
Try every combination of flipping rows and columns (2^(R+C)) and calculate the matrix score for each to find the maximum. |
Exponential Transformation Tree. $O(2^(R+C)$ x RC). |
Draw a matrix. Branch out to "Flip Row 1" vs "Don't Flip." Repeat for every row and col. The tree becomes massive. |
Greedy Property (Row Head + Column Max). |
Binary Magnitude Prioritization. |
1. Ensure the first column is all '1's by flipping any row that starts with '0'. 2. For every other column, count 0s and 1s. If 0s > 1s, flip the column. Calculating the score is just powers of 2. |
Draw a matrix. Draw a vertical line through column 0; all cells must be 1. For other columns, draw a "Weight" icon at the bottom. Flip if it increases the 1-count. |
Double Pass Grid Scan. $O(R x C)$. |
Draw the grid being scanned once horizontally (rows) and then once vertically (columns). |
Full Grid Copies: Draw multiple R x C matrices for every recursive state. |
In-Place Modification: Draw one grid with small toggle switches on the side. |
| 862 |
Shortest Subarray with Sum at Least K |
Generate every possible subarray (N^2) and sum them to check if they are >= K. Keep the minimum length. |
All-Subarrays Scan. $O(N^2)$. |
Draw an array. Draw brackets of all sizes. For each bracket, draw a running sum calculation. |
Monotonic Deque + Prefix Sums. |
The "Sliding Window with a Memory." |
Use Prefix Sums. Maintain a Deque of indices where Prefix Sums are strictly increasing. If the current sum - sum at Deque head >= K, pop the head and update length. Pop the tail if the current sum is smaller than the tail's sum (since current is a "better" start). |
Draw a line of Prefix Sums. Use a "Snake" (Deque) that eats indices from the back if they are bigger than the current value, and sheds its tail from the front if the K condition is met. |
Amortized Linear Scan. $O(N)$. |
Draw a timeline where each index enters and exits the Deque exactly once. Total work is 2N. |
$O(1)$ excluding input, but visualized as redundant CPU loops. |
Deque + Prefix Sum Array: Draw a horizontal strip (Sums) and a double-ended queue box. |
| 863 |
All Nodes Distance K in Binary Tree |
For every node in the tree, run a full DFS/BFS to find nodes at distance K. Check if the target node is among them. |
Multiple Global Traversals. $O(N^2)$. |
Draw a tree. For every node, draw a "ripple" that spreads out. Note how often the same edges are traversed. |
Graph Conversion (Parent Pointers) + BFS. |
Tree-to-Network Morph. |
First, do a DFS to map every node to its parent. Now the tree is a generic graph. Start a BFS from the 'Target' node, moving to Left, Right, and Parent. Stop when the BFS level reaches K. |
Draw a tree. Draw extra arrows pointing UP from children to parents. Highlight the target node and draw a circle (BFS wave) that expands outward 1 level at a time. |
Two-Pass Traversal. $O(N)$. |
Draw the tree. Trace one pass for parents (green), and one pass for BFS (blue). Every edge is visited a constant number of times. |
Recursion Stack: Draw a stack H levels deep for every node. |
Hash Map (Parents) + Queue (BFS): Draw a mapping table and a 1D queue. |
| 864 |
Shortest Path to Get All Keys |
Try every possible permutation of the order in which you pick up keys. For each order, find the shortest path using BFS. |
Factorial Path Exploration. $O(K! x \text{NM})$. |
Draw a grid with keys A, B, C. Trace Path A->B->C, then A->C->B, etc. The number of paths grows to 720 for 6 keys. |
BFS on State (x, y, bitmask_of_keys). |
Multi-Floor Labyrinth. |
A "state" is your coordinates PLUS which keys you have. Use a bitmask (e.g., `001` means key 'a'). You can only cross a lock door 'A' if your mask has the 'a' bit. Use BFS to find the shortest path to a state where the mask is all 1s. |
Draw the grid. Imagine it has layers (like a 3D building). Every time you pick a key, you "teleport" to a new floor where doors are unlocked. |
BFS on 3D State Space. $O(\text{NM} x 2^K)$. |
Draw a 3D block of size N x M x 2^K. BFS visits each cell in this 3D space once. |
Permutation List: Draw a list of K! potential paths. |
Visited 3D Array / Set: Draw a 3D matrix (e.g., 30 x 30 x 64 for 6 keys). |
| 865 |
Smallest Subtree with all the Deepest Nodes |
1. Find the max depth. 2. For every node, check if its subtree contains all nodes at that max depth. 3. Return the lowest such node. |
Two-Pass Redundant DFS. $O(N^2)$. |
Draw a tree. Highlight nodes at max depth. For every node in the tree, draw a circle encompassing its children to see if all highlighted nodes are inside. |
Post-Order DFS (Depth-Pair Return). |
The "Highest Common Parent" Beacon. |
Each node returns a pair: {MaxDepthFound, SubtreeRoot}. If LeftChild.depth == RightChild.depth, this node is the new SubtreeRoot. If one is deeper, pass that child's result up. |
Draw a tree. At the bottom, nodes report their depth (e.g., 3). As info moves up, if a node sees 3 from both sides, it circles itself. If only from one side, it points an arrow to that child. |
Single Pass DFS. $O(N)$. |
Draw a single continuous line that traces the perimeter of the tree, visiting each node exactly once. |
$O(H)$ recursion stack but with redundant global set storage for deepest nodes. |
$O(H)$ Recursion Stack: Draw a vertical stack of boxes representing the call depth. |
| 866 |
Prime Palindrome |
Iterate numbers starting from N, one by one. For each, check if it's a palindrome, then check if it's prime. |
Linear Scan with Heavy Checks. $O(N √N)$. |
Draw a number line starting at N. For every single tick, draw two "validation boxes" (Prime? Palindrome?). Note how many numbers fail early. |
Palindrome Generation + Primality Test. |
Constructing from the "Mirror Center." |
Instead of checking all numbers, generate palindromes directly (1, 2, 3... mirror them). For each generated palindrome >= N, check if it's prime. Also, even-length palindromes (except 11) are divisible by 11, so skip them! |
Draw a small set of root numbers (e.g., 12). Draw a mirror line to create 121. Only run the "Prime Sieve" on these specific mirrored outputs. |
Square Root Palindrome Scan. $O(√10^8)$. |
Draw a timeline that skips huge chunks of numbers, only "pausing" at sparse points where palindromes exist. |
$O(1)$ excluding string conversions. |
$O(1)$ Space: Draw a few integer variables for the generator and the prime tester. |
| 867 |
Transpose Matrix |
Iterate through the matrix and for every element at (r, c), find the new position and swap. (Difficult if R
eq C). |
In-place Swap Logic. $O(R x C)$. |
Draw a non-square grid. Try to move a corner element to its new spot. Notice the grid shape must change, making in-place swaps almost impossible. |
New Grid Mapping. |
The "Row-to-Column" Pour. |
Create a new matrix with dimensions C x R. For every (r, c) in the original, set `newMatrix[c][r] = oldMatrix[r][c]`. |
Draw Matrix A (3 x 2). Draw Matrix B (2 x 3). Draw an arrow taking the first row of A and standing it up as the first column of B. |
Single Pass Grid Scan. $O(R x C)$. |
Draw the grid being scanned once, cell by cell, without any re-visits. |
$O(1)$ space attempt: Draw a messy diagram of index-shifting math. |
Full Matrix Allocation: Draw the C x R memory block as the destination. |
| 868 |
Binary Gap |
Convert the number to a binary string. Use nested loops to find every '1' and then find the next '1', calculating distance. |
String-Based Nested Scan. $O(\log N)$. |
Draw a binary string. Pick the first '1'. Scan all subsequent bits until you find another '1'. Repeat for every '1'. |
Bit Manipulation (Right Shift) + Distance Tracker. |
The "Conveyor Belt" Bit Check. |
Don't use strings. Use `n & 1` to check the last bit. Shift right (`n >>= 1`). Keep a counter of steps since the last '1' was seen. Update max distance whenever a new '1' appears. |
Draw the number in binary. Draw a "Window" at the far right. Slide the number through the window. Every time a '1' passes, reset a "Steps" counter and update "Record Max." |
Single Pass Bits. $O(\text{bits})$. |
Draw a straight horizontal line representing 32 bits. Each bit is visited exactly once. |
String Object: Draw a memory block for the binary string representation. |
$O(1)$ Space: Draw two integer boxes: 'lastPos' and 'maxGap.' |
| 869 |
Reordered Power of 2 |
Generate every permutation of the digits of N. For each permutation, check if it's a power of 2. |
Permutation Explosion. $O((\text{digits})$!). |
Draw the digits of N. Branch out to every possible ordering. For each leaf, check if it's in the list of powers of 2. |
Digit Frequency Counting (Anagram Check). |
The "Key-Value" Signature. |
A number is a reordered power of 2 if its digit counts match the digit counts of ANY power of 2. Pre-calculate the digit counts for all 31 powers of 2. Compare N's digit count to those 31 "signatures." |
Draw N. Count how many 1s, 2s, 3s... it has. This is its "Fingerprint." Compare this fingerprint to the 31 "Master Fingerprints" of all Powers of 2. |
Constant-time Comparative Scan. $O(\text{digits})$. |
Draw a tiny list of 31 items. For each, do a 10-step comparison (0-9). |
Permutation List: Draw a list of thousands of digit combinations. |
1D Array (Size 10): Draw a frequency array [count0, count1, ... count9]. |
| 870 |
Advantage Shuffle |
Generate every permutation of array A and count how many elements are greater than B at the same index. Return the best one. |
Permutation Matrix. $O(N!)$. |
Draw array A. Branch out to all possible orderings. For each ordering, draw a comparison line to array B. The tree is impossibly large. |
Greedy Strategy (Tian Ji's Horse Racing). |
The "Best Fit or Sacrifice" Tactic. |
Sort A and B (keep B's indices). For each element in B (from largest to smallest): If A's largest can beat it, use it. Otherwise, "sacrifice" A's smallest element against this powerhouse B element. |
Draw sorted A and sorted B. Draw a bridge between the top of A and top of B if A wins. If A loses, draw a bridge from the very bottom of A (smallest) to that top B. |
Sorting + Two Pointers. $O(N \log N)$. |
Draw two parallel timelines with pointers at both ends (Left/Right) moving toward the center. |
Exhaustive Memory: Draw N! rows of permutations. |
TreeMap or Sorted List: Draw two sorted arrays and an index-tracking Map. |
| 871 |
Minimum Number of Refueling Stops |
Recursive backtracking: At every gas station, either stop to refuel or skip it. Track fuel and distance. |
Decision Binary Tree. $O(2^N)$. |
Draw a car on a road. At each station icon, branch to "Fill" or "Pass". The depth is N stations. |
Greedy with Max-Heap (Priority Queue). |
"Retroactive Refueling." |
Drive as far as your current fuel allows. Every time you pass a station, put its fuel into a "Spare Tank" (Max-Heap). If you run out of gas before the destination, "teleport" a refuel from the biggest station you already passed. |
Draw a road. Draw a bucket (Heap) above the car. As the car passes a station, the gas "flies" into the bucket. When the car stops, pull the biggest gas can out of the bucket to keep moving. |
Linear Scan + Heap Ops. $O(N \log N)$. |
Draw a single horizontal road. Above each station, draw a small $O(\log N)$ tree icon for the Heap operation. |
Recursion Stack: Draw a stack N frames deep. |
Max-Heap: Draw a binary tree that stores gas amounts. $O(N)$ space. |
| 872 |
Leaf-Similar Trees |
Do a full traversal of Tree 1 and Tree 2. Store all nodes in two arrays. Compare the arrays. |
Full Node Comparison. $O(N_1 + N_2)$. |
Draw two trees. Circle every single node. Write them all down in two long lists and check every element. |
DFS (Leaf-only Extraction). |
The "Terminal Node" Filter. |
Perform a DFS on both trees. Only when a node has no children (leaf), add it to a list. Compare the two leaf-lists at the end. |
Draw two trees. Trace a path only to the tips of the branches. Write down the sequence of tips from left to right for both and see if they match. |
Single Pass Traversal. $O(N)$. |
Draw two trees with one continuous "string" connecting all their leaves. |
Full Tree Storage: Draw memory for every single node's value. |
Leaf List: Draw a small array that only holds the bottom-most values. $O(L)$ where L is # of leaves. |
| 873 |
Length of Longest Fibonacci Subsequence |
Try every possible starting pair (i, j). Use a loop to see how many subsequent Fibonacci numbers exist in the array. |
Triple Nested Search. $O(N^3)$. |
Draw an array. Pick two numbers. Search the whole array for their sum. If found, search again for the next sum. Repeat for every pair. |
2D Dynamic Programming + Hash Set. |
"Sum-to-Index" Mapping. |
Store val to index in a Map. Use DP state `dp[i][j]` representing the length of the sequence ending at indices i and j. To find the previous element: target = A[j] - A[i]. If target exists at index k, `dp[i][j] = dp[k][i] + 1`. |
Draw a 2D grid. The cell (i, j) looks back at a previous cell (k, i) based on a math calculation. Draw arrows connecting these grid cells. |
Squared Iteration. $O(N^2)$. |
Draw a half-matrix (triangle) representing all pairs (i, j). Each cell is processed in $O(1)$. |
$O(1)$ excluding input, but massive repetitive re-scanning of the array. |
2D DP Table: Draw an N x N matrix storing integers. |
| 874 |
Walking Robot Simulation |
For every command, move the robot step-by-step. For every step, check the entire list of obstacles to see if the robot is blocked. |
Step-by-Obstacle Scan. $O(\text{Commands} x \text{Steps} x \text{Obstacles})$. |
Draw a grid. Move a dot. For every tiny move, draw a line to every "X" (obstacle) on the map to see if you hit it. |
Hash Set (Coordinate Encoding). |
The "Obstacle Radar" (Pre-filtered). |
Convert all obstacle (x, y) coordinates into a string or long integer and store them in a Set. When moving, just check if the "Next Step" coordinate exists in the Set (O(1)). |
Draw a grid. Mark obstacles. When the robot moves, it "pings" the spot in front of it. If the ping hits the Set, it stops moving. |
Linear Path Simulation. $O(\text{Commands} x \text{Steps} + \text{Obstacles})$. |
Draw a timeline for obstacles, then a timeline for movement. No nested scans. |
$O(1)$ space but high CPU latency from redundant searches. |
Hash Set: Draw a bucket containing the "Blacklisted" coordinates. $O(\text{Obstacles})$ space. |
| 875 |
Koko Eating Bananas |
Try every possible eating speed K starting from 1. For each K, calculate the total hours needed. Stop at the first K that is <= H. |
Linear Search on Speed. $O(N x \text{max}(\text{piles})$). |
Draw a line of piles. For K=1, draw many tick marks for each pile. For K=2, redraw. Repeat thousands of times until K works. |
Binary Search on Answer (Range [1, max(piles)]). |
The "Speed Dial" Adjustment. |
Instead of 1 by 1, try the middle speed. If she finishes too fast, turn the dial down (Left). If she finishes too late, turn it up (Right). Each check takes $O(N)$ to sum up the hours. |
Draw a number line for Speed K. Mark L and R. Pick mid. Draw a clock icon showing if the total hours for mid is > H (Fail) or <= H (Possible). |
Binary Search Efficiency. $O(N \log(\text{max}(\text{piles})$)). |
Draw a timeline of length M (max piles). Cut it in half roughly 30 times (for 10^9) to show how fast it hits the answer. |
$O(1)$ extra space but visualized as massive repetitive CPU loops. |
$O(1)$ Space: Draw three integer variables: low, high, and totalHours. |
| 876 |
Middle of the Linked List |
Traverse the entire list once to count the total number of nodes N. Then traverse again and stop at N/2. |
Two-Pass Count and Scan. $O(N)$. |
Draw a linked list. Trace your finger to the end, counting. Go back to the start and trace exactly halfway. |
Tortoise and Hare (Slow & Fast Pointers). |
The "Double-Speed Lead." |
Start two pointers at the head. 'Slow' moves 1 step. 'Fast' moves 2 steps. When 'Fast' hits the end, 'Slow' is guaranteed to be exactly at the middle. |
Draw a linked list. Place 'S' and 'F' at the start. Draw arrows: S jumps 1 node, F jumps 2. When F hits the wall, circle the node where S is standing. |
Single Pass Scan. $O(N)$. |
Draw a single straight timeline. 'F' reaches the end at time N/2. |
$O(1)$ space, but with two full linear pass overheads. |
$O(1)$ Pointers: Draw two small arrow icons labeled 'Slow' and 'Fast' hovering over the list. |
| 877 |
Stone Game |
Recursive Minimax: Simulate every possible move for Alice and Bob (taking from either end) to see who can get the max score. |
Binary Decision Tree. $O(2^N)$. |
Draw the pile array. Branch left (take A[0]) or right (take A[n-1]). Repeat for every turn. The tree is huge. |
Mathematical Observation (Parity) OR 2D DP. |
The "Fixed Advantage" Logic. |
Because the sum of stones is odd and the number of piles is even, Alice can ALWAYS choose to take either all even-indexed piles or all odd-indexed piles. One of those sums MUST be greater. Thus, Alice always wins. |
Draw the array. Color even indices Blue and odd indices Green. Alice just sums them up in her head and picks the bigger color before the game starts. |
Constant Time Logic. $O(1)$. |
Draw a giant "TRUE" stamp. No calculation needed. |
Recursion Stack: Draw a stack N levels deep. |
$O(1)$ Space: Simply return true. |
| 878 |
Nth Magical Number |
Iterate from 1 upwards. For every number, check if it's divisible by A or B. Count until you reach N. |
Linear Scanning. $O(N x \text{min}(A, B)$). |
Draw a number line. Put a mark on every multiple of A and every multiple of B. Count them 1, 2, 3... until you hit N. |
Binary Search on Answer + Inclusion-Exclusion Principle. |
The "Overlap Correction" Filter. |
Count of magical numbers <= X is (X/A + X/B - X/LCM(A, B)). Binary search for the smallest X where this count >= N. Use LCM = (A x B) / GCD(A, B). |
Draw two circles (Multiples of A, Multiples of B). Shaded area in the middle is Multiples of LCM. Count is AreaA + AreaB - Overlap. Binary search adjusts the size of the circles. |
Binary Search on 10^15. $O(\log(N x \text{min}(A, B)$)). |
Draw a logarithmic curve. Very few steps (~60) needed to find a massive number. |
$O(1)$ extra space but visualized as billions of CPU cycles. |
$O(1)$ Space: Draw four integer variables (A, B, LCM, target). |
| 879 |
Profitable Schemes |
Generate every possible subset of "crimes" (schemes). For each subset, check if the total people required <= G and total profit >= P. |
Subset Power Set. $O(2^\text{crimes})$. |
Draw a list of crimes. Branch "Commit" or "Skip" for each. The bottom level of the tree has 2^100 leaves (impossible). |
3D Dynamic Programming (Knapsack variant). |
The "Profit vs. Personnel" Grid. |
State `dp[i][j][k]` is the number of ways using first `i` crimes, with `j` people, and `k` profit. As you iterate crimes, update the grid: `dp[people + currentP][min(P, profit + currentProfit)] += old_dp`. |
Draw a 2D grid where X-axis is "Profit" (capped at P) and Y-axis is "Group Size." Each cell stores "Number of Schemes." As you add a crime, "shift" and "add" the grid values. |
Pseudo-Polynomial DP. $O(\text{Crimes} x G x P)$. |
Draw a 3D block representing the state space. Each cell is filled exactly once. |
Recursive Memory: Draw an exponentially large stack. |
2D DP Table (Space Optimized): Draw a G x P grid that is updated N times. |
| 880 |
Decoded String at Index |
Fully expand the string in memory. If you see "apple3", store "appleappleapple". Then simply return the character at index K-1. |
Exponential String Expansion. $O(\text{Length of decoded string})$. |
Draw a small box "a". Draw it 10 times. Now draw that block of 10, 5 times. The paper runs out of space instantly because the string can be 10^18 chars. |
Reverse Work-Backwards with Modulo. |
The "Virtual Length" Unrolling. |
1. Calculate the *total size* of the decoded string using a single pass (O(N)). 2. Walk backwards through the original string. If K is at the end of a repetition, K % size == 0. If you hit a digit d, the new size is size / d and K = K % size. |
Draw the encoded string. Below it, write the "Current Size" at each step. Draw a pointer starting at the end. Use a "Modulo" icon to show K shrinking as it "wraps around" the repeated sections. |
Two-Pass Linear Scan. $O(N)$. |
Draw two parallel horizontal lines. One pass forward to build length, one pass backward to find the char. |
Gigantic String Buffer: Draw a memory block that exceeds the size of the universe. |
$O(1)$ Space: Draw one "Total Length" long-integer variable and one "K" variable. |
| 881 |
Boats to Save People |
Try every combination of 2 people to see if they fit in a boat. This is like a variation of the knapsack problem. |
Subset Pairing Tree. $O(2^N)$. |
Draw people as weights. Branch out every possible grouping into boats. It becomes an exhaustive search of partitions. |
Sorting + Two Pointers (Greedy). |
The "Heaviest + Lightest" Pairing. |
Sort the people by weight. Try to put the heaviest person (R) and the lightest person (L) on the same boat. If they fit, move both pointers. If not, the heaviest person *must* go alone; move only the R pointer. |
Draw a sorted line of weights. Draw a "Boat" bracket. Attempt to grab the far-left and far-right elements. If they don't fit, the bracket only takes the right-most element. |
Sorting Bottleneck. $O(N \log N)$. |
Draw a Sorting Funnel followed by a single inward-moving two-pointer scan. |
Recursion Stack/Partitions: Draw many overlapping lists of boat assignments. |
$O(1)$ Pointers: Draw two small arrow icons (L, R) over the sorted array. |
| 882 |
Reachable Nodes In Subdivided Graph |
BFS through the graph. For every edge with M new nodes, treat them as M individual nodes and run a standard BFS. |
Full Graph Expansion. $O(M x E)$. |
Draw two nodes with 1000 dots between them. Draw a ripple BFS that touches every single one of those 1000 dots. Do this for every edge. |
Dijkstra’s Algorithm + Edge Coverage Math. |
Shortest Path with "Remaining Fuel." |
1. Run Dijkstra to find the min distance to all original nodes. 2. For each node, calculate "remaining moves" after reaching it. 3. For each edge (u, v), the number of sub-nodes reached is min(total sub-nodes, moves left at u + moves left at v). |
Draw the graph. Label nodes with their "Reach Time." For each edge, draw two shaded areas creeping toward each other from the ends. The total coverage is the sum of these shaded parts. |
Priority Queue Traversal. $O(E \log V)$. |
Draw the graph. Draw a Heap icon next to the traversal to show the $O(\log V)$ cost of picking the next node. |
Gigantic Adjacency List: Draw a list with millions of sub-node entries. |
Distance Array + Map: Draw an N-sized strip for distances and a map to store edge-usage counts. |
| 883 |
Projection Area of 3D Shapes |
Build a 3D coordinate model of all the cubes. Project points onto xy, yz, xz planes and count unique occupied coordinates. |
3D Voxel Scanning. $O(N^2 x \text{max}(\text{Height})$). |
Draw a 3D grid. Fill in blocks. For each side, look through the grid and count how many "filled" spots you see. |
Row Max, Column Max, and Non-Zero Count. |
Shadow Profiles (Top, Front, Side). |
1. Top view (xy): Total count of cells where grid[i][j] > 0. 2. Front view (yz): Sum of maximum heights of each row. 3. Side view (xz): Sum of maximum heights of each column. |
Draw a 2D grid of numbers. 1. Put a dot in every cell >0. 2. Circle the biggest number in each row. 3. Circle the biggest number in each column. Add it all up. |
Single Grid Pass. $O(N^2)$. |
Draw the grid being scanned once. No complex logic or 3D math required. |
3D Boolean Array: Draw a cubic memory block of size N x N x H. |
$O(1)$ Accumulators: Draw three integer variables: top, front, side. |
| 884 |
Uncommon Words from Two Sentences |
Split sentences into words. For every word in Sentence 1, check every word in Sentence 2 (and its own sentence) to see if it appears exactly once. |
Nested String Comparison. $O(N^2 x L)$. |
Draw two lists of words. Draw lines from every word in List A to every word in List B. Note the redundant comparisons. |
Unified Hash Map (Frequency Counting). |
The "One-and-Only" Filter. |
Combine both sentences into one stream of words. Count the frequency of every word in a single Hash Map. A word is "uncommon" if its total frequency across both sentences is exactly 1. |
Draw a funnel. Pour both sentences in. Below, draw a "Frequency Table." Cross out any word where the count > 1. The remaining words are the answer. |
Linear Scan. $O(N x L)$. |
Draw a single straight timeline. Each word is processed once to increment a map, then once to filter. |
$O(1)$ extra space but visualized as extremely slow, repetitive scanning. |
Hash Map: Draw a table with `Word -> Count`. $O(\text{Total Words})$ space. |
| 885 |
Spiral Matrix III |
Build a full coordinate grid that contains the spiral. Move step by step. After every single move, check if the current coordinate is within the boundaries of the input matrix. |
Expanding Circular Scan. $O(\text{max}(R, C)$^2). |
Draw a small grid. Draw a spiral starting from the center that gets larger and larger. For every single dot in the spiral, draw a question mark: "Is this dot inside the grid?" |
Simulation with Step Increment (Greedy Walking). |
The "Square-Spiral Length" Tracker. |
The spiral pattern is: East 1, South 1, West 2, North 2, East 3, South 3... Notice that the step length increases every two directions. Maintain (r, c) and only add to result if 0 <= r < R and 0 <= c < C. |
Draw a small matrix. Draw a spiral path. Every two turns, increase the number of steps by 1. Use a "Filter Gate" icon at each step to see if the coordinate enters the final list. |
Proportional to Spiral Area. $O(\text{max}(R, C)$^2). |
Draw an Archimedean spiral. Each segment of the spiral is visited exactly once. |
Full Coordinate Cache: Draw a list storing thousands of "Out of Bounds" points. |
Result List: Draw a single 1D array of size R x C. $O(R x C)$ space. |
| 886 |
Possible Bipartition |
Generate every possible division of people into two groups (2^N). For each division, check all "dislikes" to see if any pair is in the same group. |
Exponential Grouping. $O(2^N)$. |
Draw N people. Branch out to group everyone into "Team A" or "Team B". For every leaf, draw lines representing dislikes to check for conflicts. |
Graph Coloring (Bipartite Graph Check). |
The "Red vs. Blue" Conflict Sieve. |
Represent people as nodes and dislikes as edges. Color a person Red. All their "dislikes" must be Blue. All their dislikes must be Red. If you ever try to color a person Red who is already Blue, bipartition is impossible. |
Draw the graph. Pick a node, color it Red. Trace edges and color neighbors Blue. If you find an edge connecting two nodes of the same color, draw a big red 'X' over it. |
Graph Traversal (DFS/BFS). $O(V + E)$. |
Draw the graph and put a checkmark on every dislike edge. Every edge is checked exactly once. |
Subset List: Draw a list with 2^N potential group configurations. |
Color Array: Draw a 1D strip of size N storing 0 (none), 1 (Red), or -1 (Blue). |
| 887 |
Super Egg Drop |
Recursive trial-and-error: Try dropping an egg from every floor. If it breaks, you have K-1 eggs and floor-1 levels to check. If not, K eggs and total-floor levels. Find the min of maxes. |
Minimax Decision Tree. $O(2^\text{Floors})$. |
Draw a building. Branch at floor 10. Left branch (Break), Right branch (Safe). The tree explores every single possible strategy. |
2D DP with Binary Search OR "Moves to Floors" Inverse DP. |
The "Max Reach" Strategy. |
Instead of "What's the min drops for F floors?", ask "What's the max floors I can check with M moves and K eggs?". dp[m][k] = dp[m-1][k-1] + dp[m-1][k] + 1. Keep increasing moves until dp[m][k] >= N. |
Draw a table where Rows are "Drops" and Columns are "Eggs." Fill in how many floors you can cover. Each cell is the sum of the cells above it (the "above-and-left" logic). |
Optimized DP. $O(K \log N)$. |
Draw a small grid that only goes as high as the log N of the floors. |
Exponential Call Stack: Draw a tree N levels deep with overlapping calls. |
1D DP Array (Space Optimized): Draw a single strip of size K being updated. $O(K)$ space. |
| 888 |
Fair Candy Swap |
For every candy in Alice's box, try swapping it with every candy in Bob's box. After each swap, recalculate both totals and see if they are equal. |
Nested Comparative Sums. $O(A x B)$. |
Draw two boxes of candies. Draw a line from every candy in Box 1 to every candy in Box 2. Calculate the "New Total" for every line. |
Hash Set (Target Difference math). |
The "Specific Missing Piece" Search. |
Find the difference between Alice and Bob's totals. To be fair, Alice must give x and receive y such that y - x = (BobSum - AliceSum) / 2. Put Bob's candies in a Set. For every candy Alice has, check if `candy + target_diff` is in Bob's Set. |
Calculate the "Gap" between the two friends. Draw Alice's candies. Next to each, draw a "Puzzle Piece" shape of size `gap/2`. Search Bob's "Inventory Box" (Set) for that exact shape. |
Linear Scan with Set Lookups. $O(A + B)$. |
Draw two parallel timelines. One pass for Alice, one pass for Bob's Set construction. |
$O(1)$ extra space but visualized as extremely slow, redundant looping. |
Hash Set: Draw a bucket containing Bob's unique candy sizes. $O(B)$ space. |
| 889 |
Construct Binary Tree from Preorder and Postorder Traversal |
Generate every possible binary tree with N nodes and for each, generate its preorder and postorder traversals to see if they match the input. |
Permutation Tree Matching. $O(\text{Catalan Number})$. |
Draw all possible shapes of trees with N nodes. For each, write out the traversal strings. The number of trees grows exponentially. |
Recursive Range Splitting (Divide and Conquer). |
The "Sub-problem Scope" Zoom. |
In Preorder, the first element is the Root. The second element is the Root of the Left Subtree. Find that second element in the Postorder array—this tells you where the Left Subtree ends and the Right Subtree begins. |
Draw the Preorder and Postorder arrays. Draw a "Cut Line" in Postorder at the index of `pre[1]`. Color the elements to the left Blue (Left Subtree) and right Green (Right Subtree). |
Linear Construction. $O(N)$. |
Draw the tree being built node-by-node. Each element in the arrays is touched once to create a node. |
$O(N!)$ storage for all potential tree shapes. |
$O(H)$ Recursion Stack: Draw a vertical stack representing the tree's height. |
| 890 |
Find and Replace Pattern |
For every word, generate every possible character mapping to see if one matches the pattern. |
Permutation Mapping Scan. $O(N x L!)$. |
Draw a word. Draw branches for every letter in the alphabet mapping to 'a', then 'b', etc. The search space is massive. |
Dual-Map Bijection or Pattern Normalization. |
The "Fingerprint" Signature. |
Transform every word into a generic code (e.g., "paper" -> "0.1.0.2.3"). If the word's code matches the pattern's code, it's a match. Alternatively, use two maps to ensure word[i] <=ftrightarrow pattern[i] is a 1-to-1 link. |
Draw the word "abb". Map a -> 0, b -> 1. Signature is "011". Draw the pattern "dee". Map d -> 0, e -> 1. Signature is "011". They match! |
Linear Character Scan. $O(N x L)$. |
Draw one straight timeline for each word. Every letter is visited exactly once to check or build the map. |
$O(L!)$ mapping tables for every word. |
Two 256-size arrays/maps: Draw two small boxes for char-to-char translation. |
| 891 |
Sum of Subsequence Widths |
Generate all 2^N subsequences. For each, find the max and min, calculate the width, and sum them up. |
Power Set Expansion. $O(2^N)$. |
Draw an array. Branch "Include/Exclude" for every element. For every leaf node, scan the collected elements for min/max. |
Sorting + Contribution of Each Element. |
Weighted Power-of-2 Summation. |
Sort the array. For element at index i, it is the MAX in 2^i subsequences and the MIN in 2^(N-1-i) subsequences. Total sum = sum (A[i] x (2^i - 2^N-1-i)). |
Draw a sorted array. Under each element, draw a "Weight" multiplier (2^i from left, 2^j from right). Subtract the right-weight from the left-weight and multiply by the value. |
Sorting Bottleneck. $O(N \log N)$. |
Draw a Sorting Funnel followed by a single linear pass with precomputed powers of 2. |
List of Subsequences: Draw 2^N memory blocks. |
$O(1)$ extra space (excluding powers array): Draw a single accumulator variable. |
| 892 |
Surface Area of 3D Shapes |
Build a 3D grid and check every face of every 1 x 1 x 1 cube to see if it's exposed to air. |
Voxel Face Counting. $O(N^2 x \text{max}(H)$). |
Draw a stack of cubes. For every single cube, count Top, Bottom, and 4 sides. Subtract faces that touch other cubes. |
Geometry Math (Column-based Calculation). |
"Total Potential - Hidden Area". |
Each stack of v cubes has 4v + 2 surface area. Subtract the overlapping area with neighbors: 2 x min(currentHeight, neighborHeight). |
Draw a 2D grid of numbers. For each cell, add (4 x height + 2) if height > 0. Then subtract the "contact walls" with the neighbor to the right and neighbor below. |
Single Grid Pass. $O(N^2)$. |
Draw a grid being scanned once. Every cell is visited once to check its 4 neighbors. |
3D Grid model: Draw a cubic memory block. |
$O(1)$ Space: Draw a single "Total Area" integer variable. |
| 893 |
Groups of Special-Equivalent Strings |
For every pair of strings, try every possible swap of even-indexed and odd-indexed characters to see if they can become equal. |
Restricted Permutation Search. $O(N^2 x (L/2)$!). |
Draw a string. Branch out every possible swap for even indices, then every swap for odd indices. Compare all results to every other string. |
Character Frequency Signatures (Even/Odd split). |
The "Split Bucket" Fingerprint. |
Two strings are equivalent if their even-indexed characters are anagrams AND their odd-indexed characters are anagrams. Create a signature: `sorted(evenChars) + sorted(oddChars)`. Count unique signatures in a Set. |
Draw a string like "abcd". Split it into "ac" (even) and "bd" (odd). Sort both. The fingerprint is "ac|bd". Drop this string into a Hash Set. |
Linear String Scan. $O(N x L)$. |
Draw a timeline where each string is split, sorted (O(L log L)), and hashed. |
List of permutations for every string. |
Hash Set of Signatures: Draw a set containing N strings of length L. |
| 894 |
All Possible Full Binary Trees |
Recursively generate all binary trees and filter out those that aren't "Full" (nodes with 0 or 2 children). |
Exhaustive Tree Generation. $O(2^N)$. |
Draw all combinations of N nodes. For each, check the "Full" property. The number of trees is massive. |
Recursion with Memoization (Divide and Conquer). |
The "Split N" Combinations. |
To make a full tree of N nodes, the root uses 1. Left subtree uses i nodes and Right uses N-1-i nodes. i must be odd. Recursively get all trees for i and N-1-i, and combine every left tree with every right tree. |
Draw N=7. Root takes 1. Options: (Left 1, Right 5), (Left 3, Right 3), (Left 5, Right 1). For (3, 3), draw all possible 3-node trees and pair them up. |
Catalan Complexity. $O(2^N/N^1.5)$. |
Draw a recursive tree where each node represents a number of nodes, branching into sub-problems that are cached. |
Recursive stack with redundant tree creation. |
Memoization Map: Draw a table storing `nodeCount -> List of Trees`. |
| 895 |
Maximum Frequency Stack |
Store all elements in a single list. For every pop, scan the entire list to find the frequency of every unique element, identify the max frequency, find the most recent occurrence, and remove it. |
Full Linear Scan per Pop. $O(N^2)$ for N operations. |
Draw a growing horizontal list. For every 'pop' operation, draw a scanner arrow that travels through every single box from right to left, counting occurrences in its head. |
Frequency Map + Map of Stacks (Grouped by Freq). |
The "Frequency Skyscraper." |
1. Map freq stores val -> count. 2. Map group stores count -> stack of vals. When you push '5', and it's the 3rd time, push '5' onto group[3]. Pop always takes from the highest frequency stack. |
Draw a set of vertical stacks labeled Freq 1, Freq 2, Freq 3... When '5' is pushed for the 3rd time, drop a block labeled '5' into the 3rd stack. To pop, just take the top block from the tallest stack. |
$O(1)$ Push and Pop. |
Draw two parallel timelines. Every push or pop is a single, instant dot on the line with no scanning. |
Single 1D Array: Draw one long line of boxes. |
Double-Map Structure: Draw a val -> int table and a int -> list table. $O(N)$ space. |
| 896 |
Monotonic Array |
Generate all possible pairs (i, j) and check if A[i] <= A[j] for all i < j, then repeat to check if all A[i] >= A[j]. |
All-Pairs Inversion Check. $O(N^2)$. |
Draw an array. Draw a web of lines connecting every element to every other element to its right. Check the slope of every single line. |
Single Pass Boolean Flag Scan. |
The "Directional Toggle." |
Assume the array is BOTH increasing and decreasing. As you walk through, if you see an increase, flip the "decreasing" flag to false. If you see a decrease, flip the "increasing" flag to false. At the end, return `increasing OR decreasing`. |
Draw two switches labeled "INC" and "DEC", both ON. Walk the array. If the path goes up, hit the DEC switch. If it goes down, hit the INC switch. If both are OFF, you're not monotonic. |
Linear Scan. $O(N)$. |
Draw one straight horizontal line passing through the array once. |
$O(1)$ extra space, but visualized as redundant, slow nested loops. |
Two Boolean Variables: Draw two small lightbulb icons representing the flags. |
| 897 |
Increasing Order Search Tree |
Traverse the tree, collect all node values in a list, sort the list, then build a completely new right-leaning tree (a linked list shape). |
Collect-Sort-Build. $O(N \log N)$. |
Draw a messy tree. Extract all nodes into a chaotic pile. Draw a funnel (Sort). Draw a long straight vertical line and attach the nodes one by one. |
In-order Traversal with In-place Re-linking. |
The "Threaded Unrolling." |
Perform a standard in-order traversal (Left-Root-Right). Keep track of the "last processed node." For the current node, set its left child to NULL and make it the right child of the "last processed node." |
Draw a BST. Follow the standard path (Bottom-Left to Root). As you touch a node, draw a new red arrow pointing from the previous node's right-side to it, and erase its left-side connection. |
Single Pass DFS. $O(N)$. |
Draw the tree. Trace a single line that visits every node once in numerical order. |
Full List of Values: Draw an array of size N storing integers. |
$O(H)$ Call Stack: Draw a vertical stack representing the recursion depth. $O(H)$ space. |
| 898 |
Bitwise ORs of Subarrays |
Generate every possible subarray (N^2), calculate the bitwise OR for each, and store unique results in a Set. |
All-Subarrays Bitwise Scan. $O(N^3)$. |
Draw an array. Draw brackets of all sizes. For each bracket, run a loop to calculate the OR of every number inside. Store results in a growing list. |
DP with Pruning (Capped Set size). |
The "Rolling Bit-Accumulator." |
At each index i, the possible OR values of subarrays ending at i are `{A[i] OR x}` for all `x` in the set of OR values ending at i-1. Because bitwise OR only adds '1's, there are at most 32 unique values in each step. |
Draw a sequence. Above each number, draw a small bubble containing a few bit-results. To get the next bubble, OR the current number with every result in the previous bubble. Merge into a "Global Set." |
Linear-ish Scan. $O(32N)$. |
Draw a timeline. At each step, show a constant amount of work (max 32 operations) being performed. |
Full N^2 result list: Draw a massive memory block for all results. |
Three Sets (Current, Prev, Result): Draw three small buckets that cycle their contents. $O(32N)$ space. |
| 899 |
Orderly Queue |
Simulate the process using a BFS or DFS: try moving any of the first K characters to the end. Find the lexicographically smallest string reached. |
Permutation Graph Search. $O(N!)$. |
Draw a string. Branch out K times (move char 1, move char 2...). From each result, branch again. It becomes an unmanageable tree of string permutations. |
Math Observation (Bubblesort Property). |
The "Sorting Flip" Logic. |
Case 1 (K=1): You can only rotate the string. Try all N rotations and pick the best. Case 2 (K > 1): You can eventually swap any two adjacent characters (like bubblesort). This means you can reach ANY permutation. The best permutation is simply the sorted string. |
Check K. If K=1, draw a circle and rotate the string like a wheel. If K > 1, draw a "Sort Machine" icon—the string goes in messy and comes out alphabetically sorted. |
Sorting or Rotation Scan. $O(N \log N)$ or $O(N^2)$. |
Draw a simple Sorting Funnel for K>1, or a small loop for K=1. |
Visited Set of Strings: Draw an exponentially large storage block for all permutations. |
Temporary Rotation String: Draw one extra string copy for comparisons. $O(N)$ space. |
| 900 |
RLE Iterator |
Fully decompress the Run-Length Encoding into a massive array (e.g., [8, 8, 8, 5, 5]). Maintain a current index pointer. |
Full Array Expansion. $O(\text{Total Count})$. |
Draw an encoded list [3, 8, 2, 5]. Draw a huge line of boxes: [8, 8, 8, 5, 5]. If the counts are in the millions, your drawing must go off the page. |
Pointer Simulation on Compressed Pairs. |
The "Tank Depletion" Model. |
Keep the encoded array as is. Maintain an index i for the current pair. When next(n) is called, "consume" n from the current count A[i]. If n > A[i], subtract A[i] from n and move to A[i+2]. |
Draw the array [count1, val1, count2, val2]. Draw a "Bucket" above count1. When next(5) is called, pour 5 out of the bucket. If it empties, move to the next bucket. |
Amortized Constant Time. $O(N)$ total for all calls. |
Draw a timeline where the pointer only moves forward. Each element of the original array is visited once across all function calls. |
Decompressed Array: Draw a memory block of size 10^9 (potential sum of counts). |
$O(1)$ excluding input: Draw one integer pointer and one "current count" variable. |
| 901 |
Online Stock Spanner |
Store every price in a list. For every new price, scan backwards from the end of the list to count how many consecutive previous days had a lower or equal price. |
Backward Linear Scan. $O(N^2)$ for N days. |
Draw a line graph. On day 10, draw an arrow pointing left that stops when it hits a higher peak. On day 11, draw a whole new arrow. The arrows overlap heavily. |
Monotonic Stack (Pair of Price and Span). |
The "Dominating Peak" Absorption. |
Maintain a stack of (price, span). When a new price comes, if it's >= stack top, "absorb" the top's span into the current span and pop. The stack only keeps "visible" peaks. |
Draw a series of bars. If a new tall bar comes, it "shadows" all shorter bars to its left. Combine the shadowed bars' counts into the new tall bar's total. |
Amortized Constant Time. $O(1)$ average per call. |
Draw a timeline. Each price is pushed once and popped at most once. Total work is 2N. |
Full Price History: Draw a growing 1D array. |
Monotonic Stack: Draw a stack containing only the decreasing "staircase" of prices. |
| 902 |
Numbers At Most N Given Digit Set |
Generate every possible combination of digits from the set. For each combination, check if the resulting number is <= N. |
Permutation Search. $O(\text{Digits}^\text{length of} N)$. |
Draw a tree where each node has D branches (one for each digit). The tree grows to the depth of the number of digits in N. |
Digit DP (Combinatorial Counting). |
The "Slot-by-Slot" Multiplier. |
1. Count all numbers with fewer digits than N (D^1 + D^2...). 2. For numbers with the same digits as N, iterate from left to right. For each position, count digits in the set smaller than N[i]. If N[i] is in the set, move to the next position; otherwise, stop. |
Draw N = 564. Slots: [__] [__] [__]. 1. Fill 1 and 2 slot options. 2. For 3 slots, if digit set is {1, 3, 5}, the first slot can be 1 or 3 (2 choices x 3 x 3). If first is 5, look at the second slot. |
Logarithmic (Length of N). $O(\log N)$. |
Draw a small timeline with length equal to the number of digits in N (usually <= 10). |
List of all valid numbers: Draw a massive memory block. |
$O(1)$ Space: Draw a few integer variables for counts and math. |
| 903 |
Valid Permutations for DI Sequence |
Generate all N! permutations of numbers [0, N]. For each, check if it satisfies the Increase/Decrease (D/I) conditions. |
Permutation Factorial. $O(N! x N)$. |
Draw the sequence "ID". Branch out to [0,1,2], [0,2,1], [1,0,2]... For each branch, check if the numbers go Up then Down. |
2D Dynamic Programming. |
The "Relative Rank" Offset. |
dp[i][j] is the number of valid permutations of length i ending with relative rank j. If 'D', dp[i][j] is sum of dp[i-1][k] for k >= j. If 'I', sum of dp[i-1][k] for k < j. |
Draw a grid where rows are the length of the sequence and columns are the possible ending values. Use prefix sums to fill the next row in $O(1)$ per cell. |
Squared DP. $O(N^2)$. |
Draw an N x N matrix. Each cell is updated once using the row above it. |
List of Permutations: Draw N! memory blocks. |
2D (or 1D) DP Table: Draw a single strip of size N being updated N times. |
| 904 |
Fruit Into Baskets |
For every possible starting tree i, scan forward until you encounter a third type of fruit. Keep track of the maximum length found. |
All-Subarrays Scan. $O(N^2)$. |
Draw a row of fruits. Draw a bracket starting at index 0. Expand until 3 types are seen. Reset bracket to index 1 and repeat. The bracket scans the same trees over and over. |
Sliding Window (Two Pointers) with Hash Map. |
The "Flexible Caterpillar" Walk. |
Maintain a window [L, R] and a map of fruit counts. Expand R. If map size > 2, increment L and decrease counts until map size is 2 again. Max window size is the answer. |
Draw a row of fruits. Draw a window (bracket). As the right side moves, fruit goes into a "Basket" (Map). If you have 3 types, move the left side of the window until a fruit type is completely removed from the baskets. |
Single Pass Scan. $O(N)$. |
Draw a single horizontal timeline. L and R pointers only ever move to the right. |
$O(1)$ extra space but visualized as extremely slow redundant loops. |
Hash Map (Size 2): Draw two small boxes representing the two fruit baskets. |
| 905 |
Sort Array By Parity |
Iterate the array twice: first extract all even numbers into a new array, then extract all odd numbers, and concatenate them. |
$O(N)$ Time, $O(N)$ Space. A conveyor belt sorting items into two separate bins, then dumping the bins in sequence. |
Draw the main array splitting into two separate smaller arrays (evens, odds), which then funnel into a brand new full-sized array. |
Two Pointers (In-place Swap) |
Two inspectors at opposite ends of a hallway. The left looks for odds, the right looks for evens. When both find targets, they swap them. |
Left pointer starts at 0, Right at end. Left moves if even. Right moves if odd. If Left is odd AND Right is even, swap them. Repeat until pointers cross. |
Draw the array. Place 'L' below index 0, 'R' below the last index. Draw high sweeping arches connecting elements when a swap occurs. |
$O(N)$ linear time, $O(1)$ space. A classic inward-colliding pointer model. |
Draw a horizontal line representing the array. Draw two arrows starting at the ends, pointing inward until they meet in the exact middle. |
Three full-length array blocks drawn side-by-side (Original, Temporary Evens, Temporary Odds). |
Just the single original array block. No extra storage boxes drawn. |
| 906 |
Super Palindromes |
Iterate through every single number from L to R. Check if it's a palindrome, then calculate its square root and check if that's a whole number and a palindrome. |
$O(R-L)$. A massive, dense timeline checking mostly invalid, useless numbers. Time Limit Exceeded. |
Draw a massive straight line with dots for numbers. Mark almost every dot with a red 'X' to demonstrate the sheer volume of wasted checks. |
Palindrome Construction (Math/Generator) |
Building outward from a "seed". Instead of checking big numbers, generate small seeds, mirror them into palindromes, square them, and verify range. |
Iterate seeds from 1 to 10^5. For each seed '12', create odd ('121') and even ('1221') palindromes. Square them. If the square is a palindrome in [L, R], increment count. |
Draw a small "seed" box (e.g., '12'). Draw arrows outward mirroring it to make '121'. Draw a machine box that squares it -> '14641'. |
$O(W^(1/4)$) where W is the upper bound R. The search space shrinks from 10^18 to just 10^5 iterations. |
Draw a tiny box (the seed generation space) compared to a massive box (the brute force space) to show the mathematical shortcut. |
Negligible variables, but massive loop bound counters ticking away. |
A string builder for constructing the mirrored seed, and a 64-bit integer variable to safely hold the squared result up to 10^18. |
| 907 |
Sum of Subarray Minimums |
Nested loops to generate every possible contiguous subarray, find the minimum of each, and sum them up. |
$O(N^2)$ or $O(N^3)$. A massive triangle of overlapping subarray segments being re-evaluated repeatedly. |
Draw the array. Below it, draw a bracket for size 1 subarrays, then size 2, etc., forming a dense pyramid of overlapping brackets. |
Monotonic Stack (Increasing) |
A bar chart / histogram where each bar casts a "shadow" left and right until it hits a shorter bar, defining its territory as the minimum. |
Find Previous Smaller Element (PSE) and Next Smaller Element (NSE) using a stack. For each element, subarrays where it is min = (i - PSE) * (NSE - i). Add (arr[i] * count) to total. |
Draw a histogram. From the top of a specific bar, draw a horizontal line left and right. Stop the line exactly when it crashes into a shorter bar. |
$O(N)$ linear time. A two-pass left-to-right and right-to-left sweep. |
Draw an array with a `+` above an element when pushed to the stack, and a `-` when popped. Max 2 operations per element. |
Conceptual $O(1)$ space, but mentally visualizing $O(N^2)$ temporary sub-arrays stored in memory. |
A vertical cylinder (stack) storing only array indices. When a smaller number arrives, the stack pops higher indices out. |
| 908 |
Smallest Range I |
Simulate adding/subtracting every value from -k to k for every element to generate all possible arrays, then calculate max-min for each. |
$O(X^N)$ exponential explosion. A massive decision tree of every possible modified array. |
Draw a single array element branching out into 2K+1 paths. Repeat for every element, showing a chaotic web of possibilities. |
Math / Greedy / Min-Max |
Two endpoints on a 1D number line (the min and max of the array) stretching toward each other by exactly distance K. |
Find the absolute minimum and maximum values in the array. If (max - K) <= (min + K), the answer is 0. Otherwise, the gap is (max - K) - (min + K). |
Draw a number line. Plot `MIN` and `MAX`. Draw an arrow starting at `MIN` moving right by K. Draw an arrow from `MAX` moving left by K. Measure the remaining gap. |
$O(N)$ single pass. A straight line scanning the array exactly once. |
Draw a horizontal array. Draw a single arrow sweeping from left to right, updating two small boxes labeled 'Min' and 'Max'. |
Thousands of temporary arrays drawn taking up $O(N \cdot X^N)$ memory space. |
Just two small integer variables. Draw two tiny boxes for $O(1)$ space: `min_val` and `max_val`. |
| 909 |
Snakes and Ladders |
Recursive Depth-First Search (DFS) exploring all 6 dice rolls from every square without tracking visited states. |
$O(6^N)$ or infinite loops. A sprawling tree that loops back on itself when hitting snakes. |
Draw nodes with 6 branches each. Draw long "snake" arrows pointing from deep in the tree back up to the root, demonstrating endless cycles. |
Breadth-First Search (BFS) |
Concentric ripples expanding in a pond from square 1. Each ripple represents one dice roll. The first ripple to touch the final square wins. |
Queue pairs of [square, moves]. Pop front, roll 1-6. If snake/ladder, take it immediately. If unvisited, mark visited and push to back of queue. |
Flatten the 2D board into a 1D timeline (1 to N^2). Draw short forward arcs for dice rolls (+1 to +6) and long specific arcs for snakes/ladders. Color them by "depth". |
$O(N^2)$ where N^2 is total squares. A grid where each cell is shaded exactly once. |
Draw the N x N grid. Lightly cross out each cell the moment it is pushed to the queue to prove no cell is processed twice. |
A massively deep call stack (DFS) that crashes with a StackOverflow due to cycles. |
A horizontal pipe (Queue) and a 1D boolean array (Visited). Draw elements entering the back of the pipe and leaving the front. |
| 910 |
Smallest Range II |
Try adding and subtracting K for every single element, creating all 2^N possible arrays, then find the min/max difference of each. |
$O(2^N)$ Exponential explosion. A massive, binary decision tree of array states. |
Draw an array element as a root node splitting into two paths (+K and -K). Repeat this split for every element, forming a dense web. |
Sort + Greedy Linear Scan |
A staircase of blocks (sorted array). You make a single vertical slice: everything left of the slice gets boosted (+K), everything right drops (-K). |
Sort the array. Iterate a split point `i`. Calculate the potential new max (either end of array - K, or `i` + K) and new min. Track the smallest gap. |
Draw a sorted bar chart. Draw a vertical line cutting through it. Draw up-arrows on the left bars and down-arrows on the right bars. Measure the new highest/lowest peaks. |
$O(N \log N)$ for sort, $O(N)$ for scan. A sorting funnel followed by a straight, one-way path. |
Draw a sorting algorithm box. Below it, draw a horizontal sorted array with a single pointer sliding from left to right. |
Generates $O(2^N)$ distinct array copies taking up massive heap space. |
In-place sorting $O(1)$ or $O(\log N)$ stack, plus a few isolated $O(1)$ variables to hold the current min and max peaks. |
| 911 |
Online Election |
For every query `t`, iterate through the `persons` array from time 0 up to time `t`, counting votes manually every time. |
$O(Q \cdot N)$. A windshield wiper that repeatedly sweeps from the start of the array to a specific point and back. |
Draw a timeline. For each query point, draw an arrow originating from zero, sweeping forward to `t`, and calculating the sum over and over. |
Precomputation + Binary Search |
A dynamic leaderboard that only records a snapshot when a new vote is cast, ignoring the dead time in between. |
Pre-calculate the winner at every given time using a hashmap. For a query `t`, binary search the `times` array to find the closest recorded snapshot <= `t`. |
Draw a timeline with distinct "vote" markers. Write the current winner below each marker. When a query lands between markers, draw an arrow snapping back to the closest left marker. |
$O(N)$ precomputation, $O(\log N)$ per query. A tree dividing a pre-calculated timeline. |
Draw a balanced binary search tree dropping down onto the timeline, zeroing in on the correct timestamp in logarithmic steps. |
$O(1)$ space if recounting, but wastes massive time. |
Two parallel $O(N)$ arrays: `times` and `winners`. Draw them stacked on top of each other like a lookup table. |
| 912 |
Sort an Array |
Bubble, Selection, or Insertion sort. Repeatedly sweeping the array to swap adjacent or min/max elements. |
$O(N^2)$ Quadratic. A dense triangle of nested loop iterations comparing almost every pair. |
Draw an array. Draw looping arcs connecting index 0 to every other element, then index 1 to the rest, creating a chaotic scribble. |
Merge Sort / Quick Sort / Heap Sort (Divide & Conquer) |
Splitting a thick deck of cards in half repeatedly until you have single cards, then meticulously weaving them back together in order. |
(Merge Sort) Split array down to size 1. Compare elements of two sorted sub-arrays with two pointers, placing the smaller into a new merged array. |
Draw the array splitting into branches like an upside-down tree until individual elements remain. Then draw branches merging back up, sorting at each junction. |
$O(N \log N)$. A tree graph of depth log(N) where work N is done at each horizontal level. |
Draw a grid. Height is log(N) splits. Width is N elements. Every level requires one full pass of N elements. |
$O(1)$ in-place swapping space, but $O(N^2)$ Time Limit Exceeded. |
$O(N)$ auxiliary array for Merge Sort. Draw an empty array of equal length positioned directly below the main array to hold the merged results. |
| 913 |
Cat and Mouse |
Standard DFS or BFS simply moving the cat and mouse. Fails due to infinite loops when they chase each other. |
Infinite time. A circular graph where nodes point back to each other in a death spiral. |
Draw a circle of nodes. Draw arrows from Mouse -> Cat -> Mouse -> Cat going around endlessly. |
Minimax / Topological Sort on States |
A massive board game where you work backward from the "Game Over" squares to figure out if the starting square is a guaranteed win. |
Define state as `(mouse, cat, turn)`. Find all known Game Over states (mouse=0, cat=mouse). Put them in a queue. Propagate the win/loss backward to previous states. |
Draw a grid. Mark the edges green (Mouse wins) and red (Cat wins). Draw arrows flowing backward from the edges to color the inner, unknown squares. |
$O(V \cdot E)$ where states are 2 * N^2. A 3D grid where each cell is resolved exactly once. |
Draw a cube representing the 3D state space `(mouse, cat, turn)`. Shade blocks as they are popped from the queue. |
Stack overflow from deep recursive cycles. |
A 3D array `color[50][50][2]` and a queue. Draw a Rubik's cube-like structure holding state integers. |
| 914 |
X of a Kind in a Deck of Cards |
Try all possible group sizes X from 2 up to N. For each X, iterate through card frequencies to see if they are perfectly divisible. |
$O(N^2)$. Testing every possible group size against every unique card type. |
Draw bars representing card counts. Draw horizontal cut lines at height 2, then 3, then 4, checking if every bar can be cut perfectly without remainders. |
Greatest Common Divisor (GCD) |
Finding the largest "measuring stick" that can perfectly divide all the frequency bars without leaving any leftover pieces. |
Count the frequency of each card. Apply the GCD algorithm to the frequencies sequentially: `result = gcd(result, freq[i])`. If `result >= 2`, return true. |
Draw two unequal bars. Subtract the shorter from the longer until they match in size (Euclidean algorithm). That matching size is the GCD. |
$O(N \log(\text{min}(\text{frequencies})$)). A funnel rapidly shrinking the compared numbers. |
Draw a timeline of elements, with a single variable accumulating the GCD. The GCD "eats" each frequency in logarithmic time. |
Minimal space, but repetitive math operations. |
$O(N)$ HashMap. Draw a two-column table mapping [Card Number -> Frequency]. |
| 915 |
Partition Array into Disjoint Intervals |
Try every possible split point. For each split, scan the left side for the maximum and the right side for the minimum. |
$O(N^2)$. Two nested scans for every split point in the array. |
Draw an array. Draw a vertical line moving from left to right. At each stop, draw two sweeping arrows: one checking everything to the left, one to the right. |
One-Pass Running Maximum |
A "High-Water Mark" system. You track the highest peak seen so far in the left partition and compare it to new elements as you walk. |
Track `maxLeft` (max in current left) and `globalMax` (max seen so far). If `arr[i] < maxLeft`, the split MUST move further right to include `i`. Update `maxLeft = globalMax`. |
Draw a line chart. Draw a horizontal "ceiling" line. If the chart dips below the ceiling later, the ceiling must be raised to the new peak. |
$O(N)$. A single runner moving from start to finish without looking back. |
Draw a straight arrow from index 0 to N-1. Draw a small "backpack" icon labeled `maxLeft` that updates as the arrow moves. |
$O(N)$ if storing prefix/suffix arrays, or $O(1)$ with repetitive re-calculation. |
$O(1)$. Two simple integer variables: `maxLeft` and `globalMax`. Draw two small post-it notes. |
| 916 |
Word Subsets |
For every word in A, check if every word in B is a subset. This involves frequency counting for every pair. |
$O(A \cdot B \cdot L)$ where L is word length. A massive cross-product of comparisons. |
Draw two columns (A and B). Draw lines connecting every word in A to every word in B. It becomes a tangled, solid block of lines. |
Frequency Map Compression (Maximum Requirements) |
A "Recipe Book." Combine all words in B into a single "master recipe" that contains the maximum count of each letter required. |
Create a 26-slot array `maxB`. For each word in B, update `maxB[char] = max(maxB[char], current_word_freq[char])`. Then check each word in A against this single `maxB`. |
Draw a single "Master Filter" box with 26 slots. Pour all words from B into it. Then pass words from A through it; only those with enough "ink" pass through. |
$O(A\cdot L + B\cdot L)$. Two independent linear scans. |
Draw a timeline for B, then a separate timeline for A. No connections between them; they process sequentially. |
$O(A + B)$ frequency counts stored temporarily during thousands of comparisons. |
$O(1)$ extra space (fixed 26-size arrays). Draw one fixed-size grid of 26 boxes. |
| 917 |
Reverse Only Letters |
Extract all letters into a temporary list, reverse that list, then iterate through the original string and put letters back in order. |
$O(N)$ Time and $O(N)$ Space. A process of dismantling a machine and rebuilding it elsewhere. |
Draw the string. Draw a separate array below it containing only the letters. Draw arrows showing the letters moving out, flipping, and moving back. |
Two Pointers (In-place) |
Two bookends sliding inward. They skip non-letters and only swap when both pointers are resting on valid letters. |
Left at 0, Right at end. While L < R: if L is not letter, L++. If R is not letter, R--. If both are letters, swap and L++, R--. |
Draw the string. Place 'L' and 'R' at ends. Use arches to show swaps. Draw "skip" symbols (like a hurdle) over punctuation characters. |
$O(N)$. Two pointers meeting in the middle. |
Draw a horizontal line. Draw two arrows pointing inward, meeting at the center point. |
$O(N)$ to store the extracted letters. Draw a second string container. |
$O(1)$ (or $O(N)$ if string is immutable like in Java/Python). Draw the single original string being modified. |
| 918 |
Maximum Sum Circular Subarray |
For every possible starting position (0 to N-1), run Kadane's algorithm on the N-length sequence starting there. |
$O(N^2)$. Running a linear algorithm N times. |
Draw N versions of the same array, each rotated by one index. Draw a Kadane's "sweep" arrow across every single one. |
Kadane's (Min/Max Complement) |
A "donut" logic. The max circular sum is either a normal subarray (Kadane) or the (Total Sum - Minimum Subarray Sum). |
Run Kadane once for `max_sum` and once for `min_sum`. Result is `max(max_sum, total_sum - min_sum)`. (Handle all-negative edge case). |
Draw a circle. Shade the "Max Subarray." Then, shade the "Min Subarray" and show that the remaining part of the circle is the "Circular Max." |
$O(N)$. A single pass through the array. |
Draw a single horizontal array. Draw one arrow sweeping through it, updating four small boxes: `max_so_far`, `min_so_far`, `curr_max`, `curr_min`. |
Wasted space representing the N rotated array variants. |
$O(1)$. Only variables to track the four Kadane states. Draw 4 small integer boxes. |
| 919 |
Complete Binary Tree Inserter |
For every `insert(val)`, perform a full BFS search starting from the root to find the first node with an empty child. |
$O(N)$ per insertion. Re-scanning the entire tree for every new node. |
Draw a tree. For the 1st node, scan level 0, 1. For the 2nd node, scan 0, 1 again. The search area grows every time. |
Queue-based Level Order State |
A "waiting room" (Queue). Only nodes that are still looking for children (i.e., have < 2 children) stay in the queue. |
During init, BFS once and store all nodes with < 2 children in a queue. On `insert`, peek queue front, add child. If parent now has 2 children, pop it. Push new child to queue. |
Draw a tree. Draw a horizontal pipe (Queue) below it containing only the leaf nodes and nodes with one child. Use arrows to show the "active" insertion point. |
$O(N)$ init, $O(1)$ per insert. Instant access to the target parent. |
Draw a single "Jump" arrow from the new value directly to its parent, skipping the rest of the tree. |
$O(1)$ per insert but $O(N)$ total if you count the BFS call stack. |
$O(N)$ to store the queue of eligible parents. Draw a persistent list of node references. |
| 920 |
Number of Music Playlists |
Recursive backtracking to generate every possible permutation of length L using N songs, checking the 'K' constraint for each. |
$O(N^L)$ Exponential. A massive tree where each node has N children, branching L levels deep. |
Draw a root node. Branch out N times. From each child, branch N times again. Mark paths that violate the "K songs apart" rule with a red 'X'. |
Dynamic Programming (2D) |
Building a playlist "brick by brick." At each step, you either pick a brand new song or a song you've already used (if it's far enough back). |
`dp[i][j]` is playlists of length `i` with `j` unique songs. Two cases: 1. Last song is new: `dp[i-1][j-1] * (N - (j-1))`. 2. Last song is old: `dp[i-1][j] * max(0, j-K)`. |
Draw a grid where rows are Playlist Length and columns are Unique Songs. Draw arrows entering a cell from the "top-left" (new song) and "directly above" (old song). |
$O(L \cdot N)$. Filling a rectangular grid of size L x N. |
Draw a rectangle divided into L x N squares. Draw a single diagonal sweep line to show the order of computation. |
A massive call stack tree taking up $O(L)$ depth but with a memory-heavy breadth. |
$O(L \cdot N)$ for the DP table (can be optimized to $O(N)$ using two rows). Draw two horizontal strips representing the "Current" and "Previous" length states. |
| 921 |
Minimum Add to Make Parentheses Valid |
Try inserting '(' or ')' at every possible index and check for validity. Repeat until valid. |
$O(N^2)$ or higher. Multiple passes and string re-constructions. |
Draw a string. Draw multiple "ghost" characters being inserted and deleted in a chaotic loop. |
Balance Counter (Greedy) |
A "Tug-of-War" or "Bank Balance." '(' increases the balance, ')' decreases it. If balance goes negative, you've overdrawn and need a '(' fix. |
Iterate through the string. Track `balance`. If `char == '('`, `balance++`. If `char == ')'`, if `balance > 0`, `balance--`, else `additions++`. Total = `additions + balance`. |
Draw a line chart that goes up for '(' and down for ')'. Whenever the line tries to go below the 0-axis, mark a "fix." Any height remaining at the end is also a "fix." |
$O(N)$. A single linear sweep. |
Draw a straight horizontal line. Draw one arrow moving left-to-right with two counter boxes: `OpenNeeded` and `CloseNeeded`. |
$O(N)$ to store numerous modified string copies. |
$O(1)$. Only two integer variables. Draw two small square boxes. |
| 922 |
Sort Array By Parity II |
Create two separate lists: one for all even numbers and one for all odd numbers. Then, iterate and alternate picking from each list. |
$O(N)$ Time, $O(N)$ Space. Two distinct sorting bins being merged into a third container. |
Draw the original array. Below it, draw two "holding pens" (Even/Odd). Draw a third "Final" array and arrows showing the items moving into specific slots. |
Two Pointers (In-place) |
Two runners: one on "Even Street" (indices 0, 2, 4) and one on "Odd Street" (indices 1, 3, 5). They only swap when both are standing on the wrong type of number. |
`i = 0` (even), `j = 1` (odd). While `i < N` and `j < N`: find an `i` where `A[i]` is odd and a `j` where `A[j]` is even. Swap `A[i]` and `A[j]`. |
Draw the array with indices labeled. Draw a pointer 'E' jumping by 2 and 'O' jumping by 2. Draw a swap arc between the mismatched elements. |
$O(N)$. A single pass where each element is visited once by its respective pointer. |
Draw a horizontal array. Draw two arrows (Even/Odd) both moving left-to-right in leaps, meeting at the end. |
$O(N)$ auxiliary space. Three full-sized array blocks drawn on paper. |
$O(1)$. No extra arrays. Draw the single original array being shuffled internally. |
| 923 |
3Sum With Multiplicity |
Three nested loops checking every possible triplet `(i, j, k)` to see if `arr[i] + arr[j] + arr[k] == target`. |
$O(N^3)$. A massive cube of comparisons. |
Draw a 3D coordinate system where each axis is the array. The search space is a solid volume filling the corner. |
Counting + Combinatorics (Three Cases) |
A "Frequency Buffet." Instead of looking at individual numbers, look at counts of values (0-100) and use math to calculate combinations. |
Count occurrences of each number. Iterate `i` and `j` from 0 to 100. Calculate `k = target - i - j`. Use `nCr` math if `i==j==k`, `i==j`, or `i
| Draw a small frequency table (values 0-100). Draw three "pickers" pointing to values that sum to the target. Write the math formula (e.g., `count[i] * count[j] * count[k]`) next to them. |
$O(N + M^2)$ where M is the range of values (101). A small, fixed-size grid calculation. |
Draw a 100x100 grid (the value range). This is much smaller than the N x N array grid. |
$O(1)$ extra space, but $O(N^3)$ time is the bottleneck. |
$O(M)$ space for the frequency map. Draw a single row of 101 boxes. |
|
| 924 |
Minimize Malware Spread |
For each node in the `initial` malware list, "remove" it, run a full BFS/DFS to see how many nodes get infected, and track the minimum. |
$O(I \cdot (V + E)$) where I is initial malware count. Repeatedly traversing the whole graph. |
Draw the graph. Draw I separate "what-if" scenarios, where in each one, a different infected node is deleted and the infection spread is colored in. |
Union-Find (Connected Components) |
"Islands of Infection." A map of disjoint islands. If an island has exactly ONE infected person, saving them saves the whole island. If it has two, the island is doomed anyway. |
1. Group all nodes into components using Union-Find. 2. Count size of each component. 3. Count how many initial infected nodes are in each component. 4. Pick the single-infected component with the largest size. |
Draw circles around connected clusters of nodes. Inside each circle, draw "Skull" icons for infected nodes. Highlight the largest circle that has exactly one "Skull." |
$O(N^2)$ to process the adjacency matrix once. |
Draw the adjacency matrix. Draw one sweep through it to build the Union-Find structure, then a second sweep through the malware list. |
Massive recursion depth or large queue for repeated BFS runs. |
$O(N)$ for the `parent` and `size` arrays in Union-Find. Draw two parallel rows of boxes representing the component structure. |
| 925 |
Long Pressed Name |
Generate all possible "long-pressed" variations of the 'name' string by duplicating characters and check if 'typed' matches any of them. |
$O(2^N)$ Exponential. A branching tree where every character can be repeated many times. |
Draw the word 'ALEX'. From 'A', draw branches for 'A', 'AA', 'AAA'. From 'L', draw more branches. It becomes an unmanageable forest. |
Two Pointers (Sequential Match) |
Two fingers pointing at 'name' and 'typed'. If they match, both move. If they don't, the 'typed' finger only moves if it's pointing at a "stuck" (repeated) key. |
`i=0, j=0`. While `j < typed.length`: if `name[i] == typed[j]`, increment both. Else if `j > 0` and `typed[j] == typed[j-1]`, increment only `j`. Otherwise, return false. |
Draw 'A L E X' and 'A A L E E X X'. Draw arrows connecting the first A to the first A. Then show the 'typed' arrow skipping the second 'A' because it matches the previous. |
$O(T)$ where T is length of 'typed'. A single forward pass. |
Draw a single horizontal line. Draw two arrows moving left-to-right. The 'name' arrow never moves faster than the 'typed' arrow. |
$O(2^N)$ memory to store generated permutations. |
$O(1)$. Only two integer index variables. Draw two small boxes for `i` and `j`. |
| 926 |
Flip String to Monotone Increasing |
Try every possible split point `i` where everything before `i` is '0' and everything after is '1'. Count flips for each and find min. |
$O(N^2)$. Nested loops calculating flip counts for every possible pivot. |
Draw the string. Draw a vertical line moving from left to right. At each stop, manually count all '1's on the left and '0's on the right. |
Dynamic Programming / Prefix Sums |
A "Water Pressure" system. As you walk, track how many '1's are "pushing" to be flipped, vs how many '0's would be cheaper to flip instead. |
Track `onesCount` and `flipCount`. For each char: if '1', `onesCount++`. If '0', `flipCount = min(onesCount, flipCount + 1)`. |
Draw a line graph. '1' increases a "potential" bar. '0' either increments the actual flip bar or resets it to the current "potential" if that's lower. |
$O(N)$. A single sweep through the string. |
Draw a horizontal string. Draw one arrow moving left-to-right, updating two small boxes: `ones` and `fips`. |
$O(N)$ if you pre-calculate prefix sums of ones. |
$O(1)$. Only two integer variables. Draw two small square boxes. |
| 927 |
Three Equal Parts |
Try all possible ways to place two dividers in the array, then convert each of the three segments from binary to decimal and compare. |
$O(N^2)$. Checking every combination of two split points. |
Draw an array. Draw two vertical lines 'i' and 'j'. Show them sliding in nested loops, creating a quadratic number of segments. |
Counting 1s + Suffix Matching |
"Slicing a Pie." Since each part must have the same value, they must have the same number of '1's and identical trailing zeros. |
1. Count total '1's (must be div by 3). 2. Find indices of the 1st, (k+1)th, and (2k+1)th '1'. 3. Slide all three pointers together to check if the patterns match until the end. |
Draw the binary array. Circle three groups of '1's. Draw a "stencil" over the first group and slide it over the other two to see if it fits perfectly. |
$O(N)$. One pass to count, one pass to match. |
Draw three parallel arrows starting at different points in the array, moving at the exact same speed toward the end. |
$O(N)$ to store decimal values of huge binary segments (might overflow). |
$O(1)$. Only three pointer variables. Draw three small post-it notes with indices. |
| 928 |
Minimize Malware Spread II |
For each malware node, remove it AND all its edges, run BFS to count total infections, and pick the one that results in the lowest count. |
$O(M \cdot (V + E)$). Repeated graph traversals for every malware node. |
Draw the graph. Draw 'M' different versions of the graph, each with one malware node and its connections erased. Color the remaining infections. |
Graph Connectivity (Unique Source Tracking) |
"Safe Zones." Identify components that are connected to exactly ONE malware node. Removing that specific node saves the entire component. |
1. Ignore all malware and find "clean" components. 2. For each clean component, count which malware nodes can reach it. 3. If a component is reachable by ONLY one malware node, add its size to that node's "saved" score. |
Draw clean node clusters as bubbles. Draw malware nodes outside. Draw lines from malware into bubbles. Highlight bubbles that have only one line entering them. |
$O(N^2)$. Building the graph and analyzing components once. |
Draw a bipartite graph mapping Malware Nodes to Component IDs. Count the "degree" of each Component node. |
Deep recursion or large queues for multiple BFS runs. |
$O(N)$ for component mapping and malware source lists. Draw a table mapping `Component_ID -> List of Malware Sources`. |
| 929 |
Unique Email Addresses |
For every email, manually iterate through every character, build a new string by handling '.' and '+', then check if it's already in a list. |
$O(N \cdot L^2)$ if using a list for uniqueness (O(L) for string building). |
Draw a mailbox. For every email, draw a factory that rebuilds the string, then a searcher that looks through every previously received email. |
String Parsing + HashSet |
A "Filter Funnel." Each email passes through a standard local-part filter and then is dropped into a "Unique Bucket" (Set). |
Split by '@'. In the local part: remove all '.', truncate everything after '+'. Recombine with '@domain' and add to a HashSet. Return set size. |
Draw an email. Draw a "Scissor" icon cutting it at '@'. Draw a "Eraser" removing dots and a "Cutter" stopping at '+'. Point the result to a Set { }. |
$O(N \cdot L)$. Every character is seen exactly once. |
Draw a conveyor belt of emails. Each email passes through three small "cleaning stations" and lands in a bin. |
Multiple temporary string copies for every single email. |
$O(N \cdot L)$ for the HashSet. Draw a large circular bin labeled "Unique Emails" containing unique string entries. |
| 930 |
Binary Subarrays With Sum |
Nested loops checking every possible subarray (i, j) and calculating the sum of elements within that range. |
$O(N^2)$. A dense triangle of overlapping ranges being summed repeatedly. |
Draw the array. Below it, draw a "ruler" that starts at index 0 and expands, then starts at index 1 and expands, etc. |
Prefix Sum + Hashmap (or Sliding Window) |
A "Look-back" ledger. As you walk, you record your current total. You check the ledger to see how many times (CurrentSum - Goal) occurred in the past. |
Maintain `currSum`. For each element, `currSum += val`. The number of valid subarrays ending here is `countMap[currSum - goal]`. Update `countMap[currSum]++`. |
Draw a timeline of running totals. Below each total, draw an arrow pointing back to a previous total that, when subtracted, equals the goal. |
$O(N)$. A single linear sweep with constant time lookups. |
Draw a straight horizontal arrow. Above it, draw a small table (Map) that updates its tallies as the arrow moves. |
$O(1)$ extra space if recalculating, but $O(N^2)$ time. |
$O(N)$ for the frequency map. Draw a two-column vertical table: [Sum -> Frequency]. |
| 931 |
Minimum Falling Path Sum |
Recursive DFS exploring all three possible downward paths (diagonal left, down, diagonal right) from every cell in the top row. |
$O(3^N)$ Exponential. A tree that triples in size at every single row level. |
Draw the top cell. Draw 3 arrows down. From those 3, draw 9 more. Show the tree quickly becoming a solid black mass of paths. |
Dynamic Programming (In-place) |
"Rainwater" accumulating. Each cell "pulls" the minimum value from the three cells directly above it to determine its own best total. |
Iterate from row 1 to N. `matrix[r][c] += min(matrix[r-1][c-1], matrix[r-1][c], matrix[r-1][c+1])`. The answer is the min value in the last row. |
Draw a grid. For a cell in row 2, draw three arrows pointing to it from the row above. Write the 'min' of those three inside the current cell. |
$O(N^2)$ where N is the grid dimension. Each cell is visited exactly once. |
Draw the grid. Draw a horizontal "scanning" line moving from the top row to the bottom row, coloring cells as it goes. |
Massive call stack due to $O(N)$ recursion depth and $O(3^N)$ branches. |
$O(1)$ if modifying the input matrix, or $O(N)$ to store one previous row. Draw a single row-sized buffer. |
| 932 |
Beautiful Array |
Generate all N! permutations and for each, check the condition 2 * A[k]
eq A[i] + A[j] for all triplets. |
$O(N! \cdot N^2)$. Factorial explosion combined with a quadratic check. Impossible for N > 10. |
Draw a tree that branches N! times. It is so wide that it goes off the edges of the paper immediately. |
Divide and Conquer (Odd/Even Separation) |
"Genetic Splitting." A beautiful array of size N is built by transforming a beautiful array of size N/2 into Odds and Evens and joining them. |
`f(N)` = `f(odds)` + `f(evens)`. Mapping: `odd = 2*x - 1`, `even = 2*x`. This property preserves the "beautiful" condition across scales. |
Draw a box labeled `[1]`. Split it into `[1]` (odd) and `[]` (even). Then split `[1, 2]` into `[1]` (odd) and `[2]` (even). Show the pattern 1, 3, 2, 4 emerging. |
$O(N \log N)$. A recursive tree with depth log(N), doing $O(N)$ work to transform elements at each level. |
Draw a binary tree where each node is a list. Each level's lists are combined to form the level above. |
Storing factorial numbers of array permutations. |
$O(N \log N)$ for the recursion stack and intermediate lists. Draw a few nested array boxes. |
| 933 |
Number of Recent Calls |
Store every timestamp ever received in a list. For every `ping(t)`, iterate through the whole list and count values in range [t-3000, t]. |
$O(N^2)$. A growing history that is re-scanned from the beginning for every single new event. |
Draw a timeline. For the 100th ping, draw a long arrow scanning back through all 99 previous pings. |
Sliding Window (Queue) |
A "3000ms conveyor belt." New pings enter the front; any ping that has traveled more than 3000ms falls off the back. |
Push `t` to queue. While `queue.front() < t - 3000`, `queue.pop()`. The answer is `queue.size()`. |
Draw a horizontal pipe. New numbers enter on the right. If the number on the far left is too "old" (outside the 3000 gap), draw it being kicked out. |
Amortized $O(1)$. Each ping is pushed once and popped once. |
Draw a timeline. Put a `+` when a ping arrives and a `-` when it is popped. Total operations = 2N. |
$O(N)$. An ever-growing list that never shrinks. |
$O(W)$ where W is the max number of pings within a 3000ms window. Draw a small, fixed-capacity box. |
| 934 |
Shortest Bridge |
For every water cell (0), calculate the distance to the nearest land cell (1) of Island A and Island B. Find the min. |
$O(N^4)$. For every grid cell, you might scan the entire grid again. |
Draw a grid. Pick a '0'. Draw arrows to every '1' in the grid. Repeat for every '0'. The paper is covered in overlapping lines. |
Multi-Source BFS |
"Expanding Ripples." Color Island A. Then, Island A acts as a single heat source that starts "melting" the surrounding water layer by layer until it hits Island B. |
1. DFS to find and mark all cells of Island A. Push them into a Queue. 2. BFS from that Queue. Each "step" increments distance. 3. First '1' (Island B) encountered is the shortest bridge. |
Draw two blobs. Shade one blob completely. Draw a "halo" around it (Distance 1), then a second halo (Distance 2), until the halo touches the second blob. |
$O(N^2)$. Each cell is visited at most a few times (once for DFS, once for BFS). |
Draw the grid. Shade the first island, then use a marker to draw concentric rings around it until they collide with the second island. |
$O(1)$ extra space but $O(N^4)$ time makes it unusable. |
$O(N^2)$ for the queue and visited set. Draw a large circular buffer (Queue) and a shadow grid (Visited). |
| 935 |
Knight Dialer |
Recursive DFS starting from every digit (0-9). For each step up to N, explore all valid L-shaped knight moves. |
$O(8^N)$ Exponential. A tree where every node has up to 8 children, branching N levels deep. |
Draw a phone keypad. Start at '1'. Draw arrows to '6' and '8'. From '6', draw arrows to '1', '7', '0'. The path options explode instantly. |
Dynamic Programming (State Compression) |
"A Group Migration." Instead of tracking individual paths, you track how many knights are standing on each digit at timestamp `t` and "hop" them all to their next possible digits at `t+1`. |
Create a mapping of moves (e.g., 1 -> [6, 8]). Use a 1D array of size 10. In each step, `new_dp[target] += old_dp[source]` for all valid moves. |
Draw 10 circles (0-9). Draw lines between them based on knight moves. At each step, write a number in each circle representing the count of paths ending there. |
$O(N)$. A sequence of N transformations on a fixed-size (10) array. |
Draw a horizontal timeline with N points. At each point, draw a small 1x10 grid being filled. |
Massive call stack due to $O(N)$ depth and exponential branching. |
$O(1)$ extra space (only two arrays of size 10). Draw two small rows of 10 boxes each. |
| 936 |
Stamping The Sequence |
Try every possible position to place the stamp at every step of the process, searching for a path to the target string. |
$O(N!)$ or high exponential. An astronomical number of ways to layer stamps. |
Draw the target string. Draw a stamp being placed at index 0, then index 1, etc. Show a massive tree of "partially stamped" strings. |
Greedy Reverse Matching (Work Backwards) |
"Removing the Paint." Instead of stamping, look for any part of the target that matches the stamp. "Un-stamp" it by turning it into wildcards (*), which can match anything in the next step. |
While changes occur: scan target for any substring that matches `stamp` (treating * as a match). If found, record index, turn those chars to *, and repeat until all are *. Reverse the recorded indices. |
Draw the final string. Circle a segment that matches the stamp. Replace it with '????'. Now look for the next segment that matches the stamp using the '?' as jokers. |
$O(N \cdot (N - M)$). Multiple passes through the string, where N is target length and M is stamp length. |
Draw a vertical stack of strings, each with more '?' than the one above it, until the string is all '????'. |
Storing thousands of intermediate string states in a search tree. |
$O(N)$ to store the result indices and the modified target string. Draw a single character array and a list of integers. |
| 937 |
Reorder Data in Log Files |
Use a basic sorting algorithm and, for every comparison, re-parse the entire string to determine if it's a "Letter-log" or "Digit-log." |
$O(N^2 \cdot L)$ if using an inefficient sort. Repeatedly parsing the same strings. |
Draw two log strings. Draw a magnifying glass over both, highlighting the manual logic used to split 'identifier' from 'content' over and over. |
Custom Comparator / Partitioning |
"Two Separate Folders." First, separate the logs into a Letter-list and a Digit-list. Sort the Letter-list using a specific rule; leave the Digit-list in its original order. |
Split logs into two lists. For letter-logs, sort by (content, then identifier). Return `letter_logs + digit_logs`. |
Draw a conveyor belt. A "sorter" box sends letter-logs to an "Alphabetical" bin and digit-logs to a "FIFO" (First-In-First-Out) bin. |
$O(N \log N \cdot L)$. Sorting N logs where each comparison takes time proportional to string length L. |
Draw a standard sorting "funnel" that splits into two paths at the very beginning. |
$O(1)$ if sorting in place, but very slow due to re-parsing. |
$O(N \cdot L)$ to store the partitioned lists. Draw two separate array blocks side-by-side. |
| 938 |
Range Sum of BST |
Perform a full traversal (Pre-order or In-order) of the entire tree, checking every single node's value against the range [L, R]. |
$O(N)$. Visiting every node regardless of its value. |
Draw a tree. Draw a single line that touches every single node, summing them as it goes. |
Recursive Pruning (BST Property) |
"Closing the Gates." If a node's value is greater than R, you know the entire right subtree is also greater than R, so you ignore it completely. |
If `root.val < low`, only search `root.right`. If `root.val > high`, only search `root.left`. Otherwise, add `root.val` and search both sides. |
Draw a BST. Shade the nodes that fall within the range. Draw a red "X" over entire branches that are clearly outside the range based on the parent's value. |
$O(N)$ in worst case (skewed tree), but $O(\log N)$ on average. |
Draw a tree where only a small "slice" or "wedge" of nodes is visited, while others remain untouched. |
$O(H)$ recursion stack for a full traversal. |
$O(H)$ recursion stack, but with fewer calls overall. Draw a shorter, thinner call stack. |
| 939 |
Minimum Area Rectangle |
Try every combination of 4 points from the input. For each set of 4, check if they form a rectangle aligned with the axes and calculate area. |
$O(N^4)$. A massive combination problem. |
Draw a scattered plot of dots. Draw four lines connecting four dots. Repeat this for every possible quartet. The paper becomes a mess of squares. |
Diagonal Point Matching + Hashset |
"Connecting the Corners." Pick any two points that could be a diagonal (i.e., different x and different y). Instantly check if the other two required corners exist in your "point database." |
Store all points in a Set for $O(1)$ lookup. Iterate pairs `(x1, y1)` and `(x2, y2)`. If `x1 != x2` and `y1 != y2`: check if `(x1, y2)` and `(x2, y1)` are in the Set. If yes, update `minArea`. |
Draw two dots as a diagonal. Draw "ghost" dots at the other two corners. Draw a "Search" icon pointing to a database to see if those ghosts are actually there. |
$O(N^2)$. We check every pair of points once. |
Draw a grid. Draw one arrow connecting two points, then two smaller arrows "pinging" the set to verify the rectangle. |
$O(1)$ extra space but unusable time complexity. |
$O(N)$ to store the point coordinates in a hash-friendly format. Draw a table of `(x, y)` pairs. |
| 940 |
Distinct Subsequences II |
Generate every possible subsequence of the string, store them in a HashSet to handle duplicates, and return the set size. |
$O(2^N)$. For a string of length 30, this is over 1 billion operations. |
Draw a string. From each character, draw two branches: "Include" and "Exclude." Highlight the duplicate strings formed at the leaf nodes. |
Dynamic Programming (Ending-character Tally) |
"Occupying Letter Slots." Keep track of how many distinct subsequences end with each of the 26 letters. When you see a new letter, it can append to *all* existing subsequences. |
`dp[26]` stores counts for 'a'-'z'. For each char `c`: `newCount = sum(dp) + 1`. Update `dp[c] = newCount`. Final answer is `sum(dp)`. |
Draw 26 boxes labeled A-Z. As you read 'A-B-A', show the 'A' box getting a '1', the 'B' box getting '2', then the 'A' box being updated based on the total. |
$O(N)$. A single pass through the string with a constant-time sum of 26 integers. |
Draw a horizontal timeline. At each step, show a single update to a small 26-slot array. |
$O(2^N)$ to store all unique subsequences in memory. |
$O(1)$ extra space (fixed-size array of 26). Draw one small row of 26 boxes. |
| 941 |
Valid Mountain Array |
Check every possible peak index `i`. For each `i`, verify if all elements before it are strictly increasing and all elements after are strictly decreasing. |
$O(N^2)$. Checking the entire array properties for every index. |
Draw the array as a bar chart. Draw a "Peak" marker at index 1 and scan everything. Move marker to index 2 and scan everything again. |
Two-Pointer "Climb" |
"Two Hikers." One hiker starts at the left and climbs up as long as it's steep. Another hiker starts at the right and climbs up (backwards) as long as it's steep. |
`i = 0, j = N-1`. While `arr[i] < arr[i+1]`, `i++`. While `arr[j] < arr[j-1]`, `j--`. If `i == j` and `0 < i < N-1`, it's a valid mountain. |
Draw a mountain shape. Place an 'L' at the start and an 'R' at the end. Draw arrows showing them both climbing toward the summit. They must meet at the same point. |
$O(N)$. Each element is visited at most once as pointers move inward. |
Draw a horizontal line. Draw two pointers moving toward each other, stopping at the first "downhill" slope they encounter. |
$O(1)$ space, but redundant logic. |
$O(1)$. Two integer pointers. Draw two small boxes for `i` and `j`. |
| 942 |
DI String Match |
Generate all (N+1)! permutations of numbers [0...N]. For each, check if it satisfies the sequence of 'I' (increase) and 'D' (decrease). |
$O(N!)$. Factorial explosion. |
Draw a tree that branches N+1 times, then N times, etc. Mark the very few valid paths with a green checkmark. |
Greedy Two-Pointer Placement |
"Squeezing the Range." Use the smallest available number for 'I' and the largest available for 'D'. This ensures you never "run out" of room to increase or decrease. |
`low = 0, high = N`. For each char: if 'I', use `low++`. If 'D', use `high--`. Use the remaining number for the last slot. |
Draw a list [0, 1, 2, 3, 4]. For 'I', take from the left end. For 'D', take from the right end. Show the "available" range shrinking from both sides. |
$O(N)$. A single pass through the string of length N. |
Draw the string. Below it, draw a horizontal line representing the output array, filling it as the pointers move. |
Storing N! permutations in a search tree. |
$O(N)$ to store the result array. Draw a single row of N+1 empty boxes. |
| 943 |
Find the Shortest Superstring |
Generate all N! permutations of the given words. For each, merge them by removing overlapping prefixes/suffixes and find the shortest result. |
$O(N! \cdot N^2)$. Extremely slow for N > 10. |
Draw a tree where each node is a word. Every path from root to leaf is a full permutation. Highlight the total length of the merged string at each leaf. |
Traveling Salesperson (TSP) with Bitmask DP |
"Finding the Best Route." Treat each word as a city. The "distance" between cities is how many *new* characters are added when merging. Find the shortest path that visits every city. |
`dp[mask][i]` is the shortest length visiting words in `mask`, ending at word `i`. Pre-calculate overlaps between all pairs of words. |
Draw a graph where words are nodes. Label edges with the cost (added characters). Use a bitmask (e.g., `1011`) to show which nodes are "lit up" in the current path. |
$O(N^2 \cdot 2^N)$. Still exponential, but much faster than N! (e.g., 12! approx 479M vs 12^2 * 2^12 approx 589K). |
Draw a grid where rows are bitmasks and columns are word indices. Shade cells to show the order of completion. |
Storing all permutations. |
$O(N \cdot 2^N)$ to store the DP table and parent pointers for reconstruction. Draw a 2D table where one dimension is the power-set of words. |
| 944 |
Delete Columns to Make Sorted |
Generate all possible combinations of column deletions (2^C) and for each, check if the remaining columns are individually sorted. |
$O(2^C \cdot R)$. Exponential search for a simple property. |
Draw a grid of letters. Cross out one column, check the rest. Cross out two, check the rest. Show the massive number of "what-if" scenarios. |
Greedy Column-wise Scan |
"The Independent Inspector." Each column's sorted status is independent of others. Just check each column once; if it's not sorted, increment the delete count. |
Iterate through columns j. For each column, iterate through rows i. If `grid[i][j] > grid[i+1][j]`, this column must be deleted. Break and move to next column. |
Draw a 2D grid. Draw a vertical magnifying glass moving from the first column to the last. Inside the glass, draw a tiny arrow checking if the letter below is >= the letter above. |
$O(R \cdot C)$. You look at every character in the grid exactly once. |
Draw the grid. Draw a single horizontal arrow above the grid, with vertical "check-mark" or "X" arrows pointing down into each column. |
Storing 2^C modified grid versions. |
$O(1)$. Only one integer counter variable. Draw a small box labeled `deleteCount`. |
| 945 |
Minimum Increment to Make Array Unique |
Check every number; if it's a duplicate, increment it by 1 and re-check the entire array for uniqueness. Repeat until all unique. |
$O(N^2)$ or $O(N^3)$. Repeatedly re-scanning a growing set of numbers. |
Draw a list [1, 1, 1]. Change the second '1' to '2'. Scan. Change the third '1' to '2'. Scan. Realize it's still a duplicate. Change to '3'. Scan. |
Sort + Tracking Next Available |
"A Waiting Line." Sort the numbers. If a number is smaller than or equal to the previous number, it must "move up" to be exactly `prev + 1`. |
Sort `A`. Iterate from index 1: if `A[i] <= A[i-1]`, calculate `diff = A[i-1] + 1 - A[i]`, add `diff` to moves, and set `A[i] = A[i-1] + 1`. |
Draw a sorted bar chart. If two bars are equal height, draw an arrow pushing the second bar up so it's one unit higher than the first. Count the arrow's length. |
$O(N \log N)$ for sorting, $O(N)$ for the scan. |
Draw a sorting machine funnel, followed by a straight line with a single "push-up" counter. |
$O(1)$ extra space, but extremely high time complexity. |
$O(1)$ if sorting in-place (or $O(\log N)$ stack space). Draw a single modified array. |
| 946 |
Validate Stack Sequences |
Generate all possible valid stack permutation sequences from the `pushed` array and check if `popped` matches any of them. |
$O(2^N)$ or $O(N!)$. Exploring a massive tree of "Push vs Pop" decisions. |
Draw a root. Branch 1: Push. Branch 2: Pop. Follow every branch to the end. It creates a fractal-like pattern on the paper. |
Simulation with Real Stack |
"The Mirror Test." Actually perform the push operations. Every time the top of your stack matches the current element in the `popped` array, you MUST pop it. |
For each `x` in `pushed`: push `x` to a stack. While `stack` is not empty and `stack.top == popped[j]`, pop and `j++`. Return `stack.isEmpty()`. |
Draw a vertical bucket. Put numbers in. Draw a 'checker' finger pointing at the `popped` array. If bucket-top == finger-target, draw an 'X' over the number and move the finger. |
$O(N)$. Every element is pushed once and popped once. |
Draw a timeline. Below it, write '+' for every push and '-' for every pop. Total operations = 2N. |
Exponential memory to store all possible valid stack permutations. |
$O(N)$ for the simulation stack. Draw a single vertical column. |
| 947 |
Most Stones Removed with Same Row or Column |
Try every possible sequence of removing stones. For each stone removed, check if it shares a row/column with a remaining stone. |
$O(N!)$. Factorial search for the optimal removal order. |
Draw stones on a grid. Pick stone A, then B, then C. Start over. Pick stone B, then A, then C. Count how many removals were valid in each path. |
Union-Find (Connected Components) |
"Constellations." Stones sharing a row or column belong to the same constellation. In any constellation of size S, you can remove S-1 stones, leaving 1. |
For each stone `(r, c)`, union row `r` and column `c` (using an offset to distinguish them). Total stones - number of unique components = stones removed. |
Draw the grid. Draw lines connecting stones in the same row/col. You will see "islands" of stones. Circle each island. |
$O(N \cdot α(N)$) where α is the inverse Ackermann function. Nearly linear. |
Draw a small table of "Row/Column parents." Show how stones "hook" rows and columns together into groups. |
Stack overflow or massive memory from searching N! paths. |
$O(N)$ to store parent pointers in Union-Find. Draw a single row of boxes representing groups. |
| 948 |
Bag of Tokens |
Exhaustive recursion: at every step, try playing every available token either "face up" (gain score) or "face down" (gain power). |
$O(2^N)$. A binary choice for every single token at every step. |
Draw a tree. Each node splits into "Face Up" and "Face Down" branches for every token. Show the branches hitting "out of power" or "out of score" blocks. |
Sort + Two Pointers (Greedy) |
"Buy Low, Sell High." Use your power to buy the cheapest tokens (score up). Use your score to "sell" the most expensive tokens (power up). |
Sort tokens. While `low <= high`: if `power >= tokens[low]`, buy `tokens[low]`, `score++`, `low++`. Else if `score > 0`, "sell" `tokens[high]`, `score--`, `high--`. Track max score. |
Draw a sorted list of prices. Place 'L' at the cheap end and 'R' at the expensive end. Use L to gain points and R to recharge your wallet. |
$O(N \log N)$ for sort, $O(N)$ for the scan. |
Draw a horizontal array. Draw two arrows pointing inward, meeting in the middle. |
Exponential memory in the recursion tree. |
$O(1)$ extra space (excluding sort). Draw three small boxes: `power`, `score`, and `max_score`. |
| 949 |
Largest Time for Given Digits |
N/A - The input size is fixed at 4 digits. Brute force is the only way (check all 4! permutations). |
$O(4!)$ = $O(24)$. Constant time because the input size never changes. |
Draw 4 slots. List all 24 ways to arrange the digits (e.g., 1234, 1243, etc.). |
Permutation Validation (Fixed Size) |
"The Digital Clock Filter." Test all 24 arrangements. Filter out those where HH > 23 or MM > 59. Pick the maximum of the remaining. |
Use nested loops or recursion to generate permutations. Format as `HH:MM`. Check if `HH < 24` and `MM < 60`. Compare with the current maximum time. |
Draw a 4x4 grid of permutations. Draw a "strikethrough" over times like 25:00 or 12:61. Circle the one that looks the "latest" on a clock. |
$O(1)$. Since the input is always 4 digits, the work is always 24 steps. |
Draw 24 small boxes. Each box is a "check/fail" test. |
$O(1)$. Only enough memory to store 4 digits and the max string. |
$O(1)$. Same as brute force. Draw one "Result" string box. |
| 950 |
Reveal Cards In Increasing Order |
Try every possible starting permutation of the deck and run the "reveal/move to bottom" simulation to see if it results in [1, 2, 3...]. |
$O(N! \cdot N)$. Factorial search for the correct starting order. |
Draw a tree of deck permutations. For each, draw a series of "Revealed" vs "Moved to Bottom" arrows. Most end in a red 'X'. |
Simulation with Queue (Work Backwards/Index Mapping) |
"Filling the Empty Slots." Sort the cards. Use a queue of indices [0, 1, 2...]. For each card, pick the front index (reveal) and move the next front index to the back (skip). |
1. Sort cards. 2. Create queue of indices 0 to N-1. 3. While cards remain: `res[q.pop()] = cards[i]`. If queue not empty, `q.push(q.pop())`. |
Draw N empty boxes. Below them, a queue of indices. Draw an arrow from the smallest card to the box whose index is at the front of the queue. |
$O(N \log N)$ for sort, $O(N)$ for queue simulation. |
Draw a sorting machine followed by a circular pipe (queue) where indices are recycled until all boxes are filled. |
$O(N!)$ to store all permutations. |
$O(N)$ for the queue and the result array. Draw a horizontal pipe and a row of N result boxes. |
| 951 |
Flip Equivalent Binary Trees |
Generate all possible tree structures by flipping every possible node, then check each one for isomorphism with the target tree. |
$O(2^N)$. An exponential number of potential "flipped" versions of the tree. |
Draw a tree. For every node, draw two branches: "Flip Children" and "Keep Children." It becomes a fractal of tree variants. |
Recursive Canonical Comparison |
"The Mirror Sync." At each node, check if the children match as-is OR if they match when cross-paired (Left1 with Right2 and Right1 with Left2). |
`isFlip(r1, r2)`: if both null, true; if one null or vals differ, false. Return `(isFlip(L1, L2) && isFlip(R1, R2)) || (isFlip(L1, R2) && isFlip(R1, L2))`. |
Draw two trees. Place a "Comparison Lens" over the roots. If they match, split the lens into two: one pair checking normally, one pair checking cross-wise. |
$O(\text{min}(N1, N2)$). Each node pair is visited once in the recursion. |
Draw a tree structure where each node has a "double-ended" arrow connecting it to its counterpart in the other tree. |
Exponential memory to store all tree permutations. |
$O(H)$ recursion stack where H is tree height. Draw a vertical column of function calls. |
| 952 |
Largest Component Size by Common Factor |
For every pair of numbers (a, b), calculate GCD(a, b). If > 1, draw an edge between them. Finally, find the largest connected component. |
$O(N^2 \cdot \log(\text{maxVal})$). Quadratic pair-checks with logarithmic GCD math. |
Draw dots for numbers. Draw lines between every single pair that shares a factor. The paper becomes a dense, unreadable cobweb. |
Union-Find + Prime Factorization |
"The Prime Hub." Instead of connecting numbers directly, connect each number to its prime factors. Numbers sharing a prime "hub" are automatically joined. |
For each `num`, find its prime factors (up to √num). Union `num` with all its prime factors. Use a map to count which parent has the most children. |
Draw numbers on top and prime numbers (2, 3, 5...) in the middle. Draw lines from numbers to their factors. Numbers that "plug into" the same prime are one group. |
$O(N \cdot √\text{maxVal})$. Much faster than checking all pairs. |
Draw a bipartite graph mapping Numbers to Prime Factors. Use Union-Find to merge the "Prime" sets. |
$O(N^2)$ memory to store all edges in the graph. |
$O(\text{maxVal})$ for the Union-Find parent array. Draw a single long row of boxes. |
| 953 |
Verifying an Alien Dictionary |
For every pair of adjacent words, check every possible alphabetical permutation until you find one that makes the list sorted. |
$O(26!)$. Checking against all possible alien alphabets. |
Draw a list of 26! possible alphabets. For each, draw a "Sorted?" checkmark next to the word list. |
Direct Mapping + Pairwise Check |
"The Translation Sheet." Convert the alien alphabet into a 26-slot lookup table where each alien letter maps to its "rank" (0-25). Then check adjacent words once. |
Create `orderMap[char] = index`. Compare words `A` and `B`: find first differing char; if `orderMap[A[i]] > orderMap[B[i]]`, return false. If `A` is a prefix of `B` and longer, return false. |
Draw two words vertically. Draw a "Comparison Bridge" between the first two letters. Use the "Translation Table" to check which letter is "heavier." |
$O(\text{Total Characters})$. A single linear pass through all words. |
Draw a horizontal timeline through the words. For each pair, draw a single "Comparison" box that either passes or fails. |
$O(26!)$ to store or iterate alphabet permutations. |
$O(1)$ extra space (fixed 26-size array). Draw one small row of 26 boxes labeled 'Alien Rank'. |
| 954 |
Array of Doubled Pairs |
Pick a number, search the entire array for its double. If found, remove both and repeat. If not found, try a different number first (backtracking). |
$O(N!)$. Factorial search for the correct removal order. |
Draw a tree where each node is a "removal choice." Most branches end early when no double is found for a remaining number. |
Frequency Map + Sorted Greedy |
"Smallest First." Always try to pair the smallest absolute value first. Since it's the smallest, it *must* be the "half" of a (x, 2x) pair, never the "double." |
1. Count frequencies in a Map. 2. Sort unique keys by absolute value. 3. For each `x`, if `count[x] > count[2x]`, return false; else `count[2x] -= count[x]`. |
Draw a sorted frequency table. Pick the first (smallest) number. Draw an arrow to its double. "Consume" the counts of both. Move to the next non-zero count. |
$O(N \log N)$ for sorting unique values, $O(N)$ for the greedy match. |
Draw a horizontal array. Draw one arrow sweeping from left to right, with "tally" marks being erased in pairs. |
$O(N!)$ search space in memory. |
$O(N)$ for the frequency map. Draw a two-column vertical table: [Value -> Count]. |
| 955 |
Delete Columns to Make Sorted II |
Try deleting every possible subset of columns (2^C combinations) and check if the resulting strings are lexicographically sorted. |
$O(2^C \cdot R \cdot L)$. Exponential search across all column combinations. |
Draw a grid. Cross out column 1. Check rows. Undo. Cross out column 2. Check. Undo. Cross out 1 and 2... the paper fills with "X" marks. |
Greedy with Sortedness Tracking |
"Locking the Rows." Check columns one by one. If a column helps sort the rows, "lock" the rows that are now strictly ordered so they don't need to be checked in future columns. |
Maintain a boolean array `isSorted[R-1]`. For each column, check if it's "safe" (no row `i` has `char[i] > char[i+1]` unless `isSorted[i]` is true). If safe, update `isSorted` where `char[i] < char[i+1]`. If not, delete column. |
Draw a vertical grid of words. Draw a "Lock" icon next to row pairs once the upper word is strictly alphabetically smaller than the lower one. |
$O(R \cdot C)$. Each character in the grid is inspected exactly once. |
Draw a horizontal arrow scanning columns. Below it, draw a vertical column of "Lock" symbols that close as the arrow moves right. |
$O(2^C)$ space to store or track combinations. |
$O(R)$ to store the `isSorted` boolean array. Draw a single column of R-1 checkboxes. |
| 956 |
Tallest Billboard |
For every rod, try three choices: 1. Add to Left Pile, 2. Add to Right Pile, 3. Don't use. Check if Left == Right at the end. |
$O(3^N)$. A ternary tree branching N levels deep (3^20 approx 3.4 billion). |
Draw a rod. Draw 3 branches. For each child, draw 3 more. Label the total height of each pile at the leaf nodes. |
DP (Difference as State) |
"The Balancing Scale." Instead of tracking two separate heights, track the *difference* between them. The goal is to reach a difference of 0 with the maximum height. |
`dp[diff]` = max height of the shorter pile. For each rod: `dp[diff + rod]`, `dp[abs(diff - rod)]`, and `dp[diff]` are updated based on the rod's placement. |
Draw a 1D array where indices represent the "Weight Difference" between two scales. Store the "Total Steel Used" in each index. |
$O(N \\text{cdot Sum})$. A grid where Sum is the total length of all rods. |
Draw a grid where rows are rods and columns are "Possible Differences." Shade cells as you reach new possible balances. |
$O(N)$ recursion depth but $O(3^N)$ state space. |
$O(\text{Sum})$ space for the DP array. Draw one long horizontal row of boxes representing every possible weight difference. |
| 957 |
Prison Cells After N Days |
Simulate the state of the 8 cells day by day for all N days, manually updating based on neighbors. |
$O(N)$. If N is 10^9, this will take years to run. |
Draw 8 boxes. Draw an arrow to Day 1, then Day 2... draw a very, very long line of boxes that goes out the door. |
Cycle Detection (Hash Map) |
"The Loop-the-Loop." There are only 2^6 (64) possible states for the inner cells. The sequence *must* repeat. Find the cycle and skip the middle 10^9 days. |
Store each state in a Map: `Map[State -> Day]`. When you see a state twice, calculate `CycleLength = CurrentDay - FirstSeenDay`. Then `N = N % CycleLength`. |
Draw a circular track. Each point on the track is a cell configuration. Draw a "Jump" arrow that skips many laps around the track to land near the finish. |
$O(2^K)$ where K is number of cells (here 2^6 = 64). Constant time relative to N. |
Draw a few states in a line, then an arrow looping back to an earlier state, with a "Math Shortcut" box next to it. |
$O(1)$ if simulating, but time is the bottleneck. |
$O(2^K)$ to store the states in a map for cycle detection. Draw a small table mapping [Bitmask -> Day Number]. |
| 958 |
Check Completeness of a Binary Tree |
For every node, check if its depth matches the expected depth for its position and if all its left-neighbors exist. |
$O(N \log N)$ or $O(N^2)$. Redundant checks of structure for every node. |
Draw a tree. For every leaf, draw a path back to the root to count depth and another path leftward to check for "gaps." |
Level-Order BFS (Null Detection) |
"The Solid Wall." In a complete tree, once you encounter a "Null" (an empty spot) in a level-order scan, you should NEVER see a real node again. |
Perform BFS including nulls. Maintain a flag `foundNull = false`. If you pop a node and `foundNull` is true, return false. If node is null, `foundNull = true`. |
Draw a tree. Draw a horizontal "Scanner" line moving level by level. If the scanner sees an empty spot and then another node later, draw a red alert light. |
$O(N)$. Every node (and its null children) is put into the queue exactly once. |
Draw a horizontal queue. Write node values in it. If a `null` appears, all boxes to its right in the queue MUST also be `null`. |
$O(N)$ for various structural checks. |
$O(N)$ for the BFS queue. Draw a horizontal pipe containing node pointers and `None` markers. |
| 959 |
Regions Cut By Slashes |
Treat the slashes as lines in a geometry problem. Calculate intersections and find closed polygons using coordinate geometry. |
$O(N^4)$ or higher. Extremely complex math with floating point issues. |
Draw a grid with slashes. Try to shade in the areas manually and count them. The shapes are triangles and trapezoids. |
Grid Expansion + DFS/BFS (or Union-Find) |
"Zooming In." Treat each 1x1 cell as a 3x3 mini-grid. A '/' becomes a diagonal of three colored blocks. Then simply count the number of "white" islands. |
1. Create a 3Nx3N grid. 2. For '/', mark `(0,2), (1,1), (2,0)`. For '', mark `(0,0), (1,1), (2,2)`. 3. Run a standard "Number of Islands" algorithm. |
Draw a square with a slash. Blow it up 3x into a 3x3 grid of pixels. Show the diagonal pixels being "filled in" like a staircase. |
$O(N^2)$. The expanded grid is 9N^2, which is still proportional to the input size. |
Draw the 3x3 expanded grid. Shade one "island" with a highlighter, then another, until all white space is accounted for. |
N/A - Too complex to implement. |
$O(N^2)$ for the expanded 3Nx3N grid. Draw a large pixelated grid with some cells blackened out. |
| 960 |
Delete Columns to Make Sorted III |
Try every possible subset of columns (2^C combinations). For each subset, check if every row in the remaining grid is lexicographically sorted. |
$O(2^C \cdot R \cdot C)$. Exponential search across all column combinations. |
Draw a grid. Try removing columns {1}, then {2}, then {1,2}, then {1,3}... label each branch with a "Valid/Invalid" status. |
Dynamic Programming (Longest Common Subsequence Variation) |
"Finding the Longest Shared Backbone." Instead of counting deletions, find the maximum number of columns you can *keep*. A column `j` can follow column `i` only if `row[i] <= row[j]` for ALL rows. |
`dp[j]` is max columns kept ending at index `j`. For each `j` from 0 to C: check all `i < j`. If `all(rows[row][i] <= rows[row][j])`, then `dp[j] = max(dp[j], dp[i] + 1)`. Result = `C - max(dp)`. |
Draw a row of column indices. Draw arrows from index `i` to index `j` only if `j` is a valid "successor" for every single row simultaneously. Find the longest chain of arrows. |
$O(R \cdot C^2)$. A nested loop over columns (C^2) with an inner loop over rows (R). |
Draw a 1D DP array of size C. Draw "pull" arrows from all valid previous indices into the current cell to show the maximization step. |
$O(2^C)$ space to track column combinations. |
$O(C)$ for the DP array. Draw a single row of C boxes. |
| 961 |
N-Repeated Element in Size 2N Array |
Sort the array and then iterate through it to find the element that appears N times. |
$O(N \log N)$. Sorting the entire array just to find a highly frequent element. |
Draw a bar chart of the array. Show the sorting process rearranging all bars, then a scan finding the longest flat plateau. |
Sliding Window / Randomized Search |
"The Proximity Rule." Since one element takes up half the array, it MUST appear either adjacent to itself or with at most two other elements in between. |
Iterate through the array. Check if `A[i] == A[i-1]`, `A[i] == A[i-2]`, or `A[i] == A[i-3]`. The first match found is the answer. |
Draw the array. Move a small "Magnifying Glass" of size 4 across it. The moment the glass contains two identical numbers, they are highlighted. |
$O(N)$. A single pass through the array. |
Draw a horizontal line. Draw a small sliding box moving from left to right, stopping immediately when a duplicate is found. |
$O(1)$ or $O(\log N)$ for sorting space. |
$O(1)$. No extra structures needed beyond the index pointer. Draw one small index box. |
| 962 |
Maximum Width Ramp |
Nested loops checking every pair (i, j) where i < j. If A[i] <= A[j], calculate j - i and track the maximum. |
$O(N^2)$. Checking all possible pairs in the array. |
Draw a line graph. Pick a low point, then scan every single point to its right to find the furthest high point. Repeat for all low points. |
Monotonic Stack (Decreasing) |
"Potential Anchors." Only indices that are smaller than all indices to their left can be the start of the *maximum* ramp. Store these in a stack, then scan backwards. |
1. Build a stack of indices i such that A[i] is decreasing. 2. Iterate j from N-1 down to 0. 3. While `A[j] >= A[stack.top()]`, pop stack and update `maxWidth = max(maxWidth, j - popped_i)`. |
Draw a bar chart. Mark "Anchor" bars that are the lowest seen so far. From the rightmost end, draw a "ruler" stretching left to see which anchor it can reach. |
$O(N)$. One pass to build the stack, one pass to process the ramp widths. |
Draw a horizontal timeline. Below it, draw a stack of indices. Above it, draw a single pointer moving from right to left. |
$O(1)$ extra space but unusable time. |
$O(N)$ for the stack. Draw a vertical cylinder containing array indices. |
| 963 |
Minimum Area Rectangle II |
Try every combination of 4 points. For each set, check if they form a rectangle (even if rotated) using dot products and calculate area. |
$O(N^4)$. Checking all quartets of points. |
Draw a scatter plot. Draw four lines connecting four dots in various orientations. The paper becomes a chaotic mess of tilted squares. |
Center Point + Diagonal Property |
"Matching Diagonals." A rectangle's diagonals have the same length and the same midpoint. Group all pairs of points by their (midpoint, length). |
1. Map `(midpoint, length)` to a list of point-pairs. 2. For each list, any two pairs (P1, P2) and (P3, P4) form a rectangle. 3. Calculate areas and find the minimum. |
Draw two lines that cross exactly in the middle and are of equal length. Draw "Ghost" lines connecting the four endpoints to show the resulting rectangle. |
$O(N^2)$ to find all pairs, plus the complexity of checking pairs within the same group (usually small). |
Draw a coordinate plane. Use a "Search" icon pointing to a Hash Map where the keys are `(x_mid, y_mid, dist)`. |
$O(1)$ extra space. |
$O(N^2)$ to store all pair diagonals in the map. Draw a multi-column table: [(Midpoint, Length) -> List of Pairs]. |
| 964 |
Least Operators to Express Number |
BFS or DFS exploring all four operators (+, -, *, /) with the base `x` to reach the target `target`. |
$O(4^\text{depth})$ or higher. An infinite tree branching 4 ways at every step. |
Draw the number `x`. Branch to `x+x`, `x-x`, `x*x`, `x/x`. From those, branch again. The tree grows faster than the paper can hold. |
Dynamic Programming (Base-X Representation) |
"Working in Base X." Express the number in base `x`. At each power level `x^k`, you can either reach the remainder by adding `x^k` multiple times or by going "over" and subtracting from `x^{k+1}`. |
`dp(i, target)` where `i` is the current power of `x`. At each step, calculate `rem = target % x`. Compare cost of `rem * cost(x^i)` vs `(x - rem) * cost(x^i)` + recursion. |
Draw a number line. Mark the target. Mark the nearest powers of X (x^k and x^k+1). Draw two paths to the target: one from below and one from above. |
$O(\log_x(\text{target})$). The number of steps is proportional to the number of digits in the base-x representation. |
Draw a horizontal line with logarithmic markers (x^1, x^2, x^3). Draw a "Decision" box at each marker. |
$O(4^D)$ memory in the search queue. |
$O(\log_x(\text{target})$) for the memoization table. Draw a small table mapping [Power, Remainder] to [Cost]. |
| 965 |
Univalued Binary Tree |
Perform a full traversal of the tree, store every value in a HashSet, and at the end check if the set size is 1. |
$O(N)$ Time and $O(N)$ Space. Overkill for a simple boolean property. |
Draw a tree. Draw a "Bucket" (Set) next to it. As you visit each node, draw an arrow dropping its value into the bucket. Circle the bucket showing only one number inside. |
Recursive Logical AND |
"The Chain of Trust." A node is univalued only if its value matches its children AND both subtrees are also univalued. |
Compare `root.val` with `root.left.val` and `root.right.val`. Recurse. If any comparison fails, the "False" signal propagates immediately up the chain. |
Draw a tree. Draw a green wire connecting all nodes. If a node has a different value, draw a "Cut" in the wire, showing the signal failing to reach the root. |
$O(N)$. Every node is visited once. |
Draw a tree with a single "Checkmark" arrow moving through every node in a DFS path. |
$O(N)$ to store the HashSet of values. |
$O(H)$ recursion stack space. Draw a thin vertical column representing the depth of the tree. |
| 966 |
Vowel Spellchecker |
For every query, iterate through the entire wordlist and perform three manual checks: exact match, case-insensitive match, and vowel-blind match. |
$O(\text{Queries} \\text{cdot Wordlist} \cdot L)$. A massive search for every single input query. |
Draw a list of queries and a list of words. Draw lines from every query to every word in the list, representing the repeated checks. |
Precomputed HashMaps (Priority Tiering) |
"Three Filter Bins." Pre-process the wordlist into three separate dictionaries: 1. Exact, 2. Lowercase (keeping first occurrence), 3. Vowel-masked (e.g., "apple" -> "p-pl-"). |
1. Check `ExactMap`. 2. If not found, check `LowerMap`. 3. If not found, check `VowelMap`. 4. Else, return "". |
Draw a word "Apple". Show it being transformed into three different forms and dropped into three different labeled boxes. |
$O(\text{Wordlist} + \text{Queries})$. Linear time to build the maps and constant time to look up each query. |
Draw a timeline of queries. Above each, draw a "Lookup" arrow that jumps directly to the correct map result in one step. |
$O(1)$ extra space but unusable time. |
$O(\text{Wordlist} \cdot L)$ to store the dictionaries. Draw three large rectangular boxes labeled "Level 1", "Level 2", and "Level 3". |
| 967 |
Numbers With Same Consecutive Differences |
Generate every number between 10^N-1 and 10^N - 1 and for each, check if the absolute difference between every two consecutive digits is K. |
$O(10^N)$. Checking billions of numbers for a small N. |
Draw a number line from 0 to 1,000,000. Put a tiny dot on the few numbers that satisfy the condition. The rest is empty space. |
BFS / DFS Digit Construction |
"Growing a Number." Start with digits 1-9. At each step, only add a digit that is exactly `last_digit + K` or `last_digit - K`. |
Start a Queue with [1,2,3,4,5,6,7,8,9]. While `num` length < N: pop `num`, find `last = num % 10`. If `last + K < 10`, push `num * 10 + (last + K)`. Repeat for `- K`. |
Draw a tree where the root is "Start". Level 1 has 9 nodes (1-9). Level 2 shows each node branching only to its "K-different" neighbors. |
$O(2^N)$. Each digit can branch at most twice. |
Draw a tree structure that is very narrow (only 2 branches max per node) rather than the massive 10-branch brute force tree. |
$O(10^N)$ would be needed if you stored the whole range. |
$O(2^N)$ for the BFS queue or recursion stack. Draw a horizontal pipe containing partially built numbers. |
| 968 |
Binary Tree Cameras |
Try placing a camera at every possible subset of nodes (2^N combinations) and for each, check if the whole tree is covered. |
$O(2^N \cdot N)$. Exponential search for the minimum set. |
Draw a tree. Shade node A, see if it covers B and C. Undo. Shade B, see if it covers A. The paper is covered in "what-if" shading. |
Greedy / Post-Order DP (State Signaling) |
"Bottom-Up Responsibility." Leaves refuse to have cameras; they force their parents to take a camera instead. Parents then signal to grandparents that they are "covered." |
State: 0 (Leaf/Needs cover), 1 (Has camera), 2 (Covered). If a child is 0, parent must be 1 (camera++). If a child is 1, parent is 2. Else parent is 0. |
Draw a tree. Use colored stickers: Red (Needs help), Green (Has Camera), Blue (Safe). Start at the bottom and let the Red stickers "demand" a Green sticker above them. |
$O(N)$. A single post-order traversal (bottom-up). |
Draw a tree with arrows pointing UP from leaves to root. Write a state number (0, 1, or 2) next to each node as the arrows move. |
$O(2^N)$ memory for combinations. |
$O(H)$ recursion stack space. Draw a vertical call stack column. |
| 969 |
Pancake Sorting |
Generate all possible sequences of "pancake flips" and for each, check if the resulting array is sorted. |
$O(N!)$ or higher. Exploring an infinite number of flip combinations. |
Draw a stack of pancakes. Draw 5 different ways to flip it. For each, draw 5 more. Show a massive tree of "shuffled" pancake stacks. |
Greedy "Largest to Back" |
"The Spatula Slide." Find the largest unsorted pancake. Flip it to the top (index 1), then flip the whole stack to move it to its correct position at the bottom. |
For `curr_size` from N down to 1: find index of `curr_size`. Flip at `index + 1` (moves to front). Flip at `curr_size` (moves to back). Repeat. |
Draw a stack of pancakes of different widths. Show a spatula sliding under the widest one, flipping the top part, and then flipping the whole stack to put the wide one on the plate. |
$O(N^2)$. We perform two flips for each of the N pancakes. |
Draw the array. Below it, draw a "Flip" icon and the resulting array. Repeat this N times, with each array having one more "sorted" element at the end. |
$O(N!)$ to store permutations. |
$O(N)$ to store the list of flip indices. Draw a single row of "Flip" integers. |
| 970 |
Powerful Integers |
Iterate through every integer i from 0 to bound and check if it can be represented as x^a + y^b by trying all combinations of a and b. |
$O(\text{bound} \cdot \log(\text{bound})$). Checking every single number in the range manually. |
Draw a number line from 0 to Bound. For every single tick mark, run a "Search" box that tries to solve the equation x^a + y^b = i. |
Double Logarithmic Loop (Logarithmic Bounds) |
"The Cartesian Grid." Instead of checking every number, pre-calculate all powers of x and y up to the bound. Then, just sum every pair. |
Nested loops: `i` from 1 (x^0) to bound, `j` from 1 (y^0) to bound. If `i + j <= bound`, add to a Set. (Handle case where x=1 or y=1 to avoid infinite loops). |
Draw a 2D grid. The x-axis is powers of x (1, x, x², ...), the y-axis is powers of y. Circle the intersections where the sum is less than the bound. |
$O(\log_x(\text{bound})$ * log_y(bound)). The number of powers is very small (e.g., 2^20 approx 10^6). |
Draw a small grid (e.g., 20x20). This is much smaller than the 1,000,000 length timeline of the brute force. |
$O(1)$ extra space but very slow. |
$O(\text{ResultSize})$ for the HashSet. Draw a small circular bin containing the unique sums. |
| 971 |
Flip Binary Tree To Match Preorder Traversal |
Try flipping every possible subset of nodes (2^N combinations). For each flipped version, perform a preorder traversal and check if it matches the target array. |
$O(2^N \cdot N)$. Exponential search through all possible tree structures. |
Draw a tree. Draw a branch for "Flip Root," another for "Don't Flip." Repeat for every node. Show a massive forest of tree variants. |
Greedy Preorder Simulation |
"The Guided Path." Walk through the tree in preorder. If the next node in the array doesn't match the current left child, flip the children and see if it works then. |
Maintain a global index `i`. If `root.val != voyage[i]`, return [-1]. If `root.left` exists and `root.left.val != voyage[i+1]`, record flip, swap calls to left/right. |
Draw a tree and a target list. Use a finger to point at the current tree node and a finger to point at the list. If they don't match the "plan," draw a "Switch" arrow between left and right children. |
$O(N)$. Every node is visited exactly once in the guided traversal. |
Draw a single "Preorder" arrow winding through the tree, with an index counter increasing at each step. |
$O(2^N)$ space for permutations. |
$O(H)$ recursion stack + $O(N)$ for the flip list. Draw a vertical call stack and a small list of flipped node values. |
| 972 |
Equal Rational Numbers |
Convert the repeating decimals into high-precision floating point numbers and check if the difference is less than a tiny epsilon. |
$O(L)$ but numerically unstable. Fails due to precision limits and rounding errors with long repeating sequences. |
Draw two numbers with 100 decimal places. Draw a magnifying glass over the 101st digit showing a slight mismatch. |
Fractional Conversion (Math/String) |
"The Pizza Slice." Every rational number (including repeating ones) can be perfectly represented as a fraction A/B. Convert both strings to fractions and compare. |
Parse non-repeating and repeating parts. Use formula: repeating_part / (10^len - 1) scaled by the decimal position. Simplify both to lowest terms using GCD. |
Draw a repeating decimal string. Use arrows to split it into an "Integer Part," "Fraction Part," and "Repeating Part." Show them being plugged into a formula to create a single fraction box. |
$O(L)$ where L is string length. |
Draw a flowchart: String -> Components -> Formula -> Fraction -> Simplify -> Compare. |
Negligible, but functionally broken. |
$O(1)$ to store the Numerator and Denominator. Draw two integer boxes. |
| 973 |
K Closest Points to Origin |
Calculate the distance for all points, store them in a list of `(distance, point)` pairs, sort the entire list by distance, and take the first K. |
$O(N \log N)$. Sorting the whole list when we only need the top K. |
Draw a scatter plot. Draw a line from the origin to every point. Show a massive "Sorting Machine" rearranging all points into a long line. |
Max-Heap (Size K) or QuickSelect |
"The Top K Club." Maintain a heap of the K closest points. When a new point comes, if it's closer than the "furthest" point in your club, kick the furthest one out and let the new one in. |
Maintain a Max-Heap of size K. For each point: calculate distance. If heap size < K, push. Else if `dist < heap.max()`, pop max and push current. |
Draw a small bucket that can only hold 3 balls. If you find a smaller ball, throw out the largest ball in the bucket and put the small one in. |
$O(N \log K)$. If K is much smaller than N, this is significantly faster than sorting. |
Draw a horizontal timeline of points. Above it, draw a small "Heap" triangle that stays the same size while points flow through it. |
$O(N)$ to store the distances of all points. |
$O(K)$ to store the heap. Draw a small binary tree structure (the heap) with K nodes. |
| 974 |
Subarray Sums Divisible by K |
Nested loops checking every possible subarray (i, j) and calculating (sum(A[i...j]) mod K). Count how many are 0. |
$O(N^2)$. Summing and checking a quadratic number of subarrays. |
Draw an array. Draw overlapping brackets for every possible range. Write the "remainder" inside each bracket. |
Prefix Sums + Frequency Map (Remainder Counting) |
"The Remainder Matchmaker." If the remainder of the sum up to index i is the same as the remainder up to index j, then the sum of the subarray between i and j must be exactly divisible by K. |
Maintain `runningSum`. For each element: `rem = (runningSum + x) % K` (handle negatives). Total count += `map[rem]`. `map[rem]++`. |
Draw a timeline of cumulative sums. Below it, write the remainder when divided by K. Draw arrows connecting two points that have the same remainder value. |
$O(N)$. A single linear sweep with constant time map updates. |
Draw a straight arrow. Below it, draw a small fixed-size array of size K (the map) that increments its values as the arrow passes. |
$O(1)$ extra space but unusable time. |
$O(K)$ for the remainder frequency table. Draw a row of K boxes labeled 0 to K-1. |
| 975 |
Odd-Even Jump |
For every index, simulate the odd and even jumps manually until you either hit the end or get stuck. |
$O(N^2)$. Each starting point can trigger a full $O(N)$ traversal of the remaining array. |
Draw an array. From each element, draw a "Zig-Zag" path that jumps forward based on complex rules. Most paths end in a dead-end "X". |
Monotonic Stack + DP (Suffix Jump Mapping) |
"Pre-calculating the Rails." First, use a sorted list and a stack to find the "next jump target" for every index (odd and even). Then, use DP to propagate "reachability" backwards from the end. |
1. Sort indices by value. 2. Use a Monotonic Stack to find `nextHigher[i]` and `nextLower[i]`. 3. `odd[i] = even[nextHigher[i]]`, `even[i] = odd[nextLower[i]]`. Count `odd[i] == true`. |
Draw the array twice (one for Odd jumps, one for Even). Draw fixed arrows from each index to its target. Then, shade the "End" and trace the arrows backwards to see which starting points are colored. |
$O(N \log N)$ for sorting/finding targets, $O(N)$ for DP. |
Draw two parallel 1D DP arrays (Odd/Even). Draw a single sweep line from Right to Left, updating the booleans. |
$O(1)$ if simulating, but $O(N^2)$ time is the blocker. |
$O(N)$ for the jump maps and DP arrays. Draw four horizontal strips: `nextH`, `nextL`, `canReachOdd`, `canReachEven`. |
| 976 |
Largest Perimeter Triangle |
Try every combination of three lengths from the array (N choose 3). For each, check if they satisfy the Triangle Inequality (a+b > c). |
$O(N^3)$. A cubic search through all possible triplets. |
Draw a pile of sticks. Pick three, try to form a triangle. Repeat for every possible trio. The paper is littered with "failed" triangles. |
Sort + Greedy (Adjacent Triplet) |
"The Heavyweight Trio." Sort the sticks by length. The best chance of forming a triangle is with three sticks that are as close in length as possible. Check only adjacent triplets starting from the largest. |
Sort `A`. Iterate from `i = N-1` down to 2. If `A[i-2] + A[i-1] > A[i]`, return `A[i-2] + A[i-1] + A[i]`. Else, move to the next triplet. |
Draw a sorted bar chart. Draw a "Triplet Window" (3 bars) at the very right. Slide it one step to the left until the two shorter bars combined are taller than the longest bar. |
$O(N \log N)$ for sorting, $O(N)$ for the single-pass check. |
Draw a sorting machine followed by a horizontal array with a 3-slot window sliding from right to left. |
$O(1)$ extra space, but unusable time. |
$O(1)$ extra space (ignoring sort). Draw the sorted array with three pointers: `a`, `b`, and `c`. |
| 977 |
Squares of a Sorted Array |
Square every number in the array, then run a standard sorting algorithm on the resulting list. |
$O(N \log N)$. Squaring preserves some order, but sorting the whole thing from scratch ignores the original "sorted" property. |
Draw a U-shaped graph (parabola). Show the negative points moving up. Then show a sorting machine re-ordering everything. |
Two Pointers (Inward Meeting) |
"The Tug-of-War." Since the array is sorted, the largest squares MUST come from either the far left (most negative) or the far right (most positive). Compare the ends and fill a new array from back to front. |
`L = 0, R = N-1`. `pos = N-1`. While `L <= R`: if `abs(A[L]) > abs(A[R])`, `res[pos] = A[L]^2, L++`. Else `res[pos] = A[R]^2, R--`. `pos--`. |
Draw the array with negative and positive numbers. Place 'L' at the left and 'R' at the right. Draw a third array below it. Show the larger square "dropping" into the last empty slot of the bottom array. |
$O(N)$. A single linear pass through the input. |
Draw a horizontal line. Draw two arrows pointing inward from the ends, meeting in the middle. |
$O(1)$ extra space (if squaring in place) but $O(N \log N)$ time. |
$O(N)$ for the result array. Draw two parallel array blocks. |
| 978 |
Longest Turbulent Subarray |
Nested loops checking every possible subarray (i, j) and verifying if it follows the "Up-Down-Up" or "Down-Up-Down" pattern. |
$O(N^2)$. Checking all N^2 ranges for the turbulent property. |
Draw a line graph. Draw brackets around every possible "Zig-Zag" segment. The paper is covered in overlapping zig-zag lines. |
Sliding Window / DP |
"Riding the Wave." Keep track of how long the current zig-zag has been going. If the pattern breaks, "reset" the wave and start counting again from the last two elements. |
Iterate through array. Compare `A[i-1]` and `A[i]`. If they flip comparison (e.g., `<` followed by `>`), `curr++`. Else if they are equal, `curr = 1`. Else `curr = 2`. Track `max_curr`. |
Draw a zig-zag line. Below it, draw a counter that increments as long as the line zig-zags. If the line goes flat or moves in the same direction twice, draw a "Reset" button. |
$O(N)$. A single pass through the array. |
Draw a horizontal line with an arrow. Above it, draw a single counter box that updates at each step. |
$O(1)$ extra space but unusable time. |
$O(1)$. Only variables to store the current length and the previous comparison result. Draw two small boxes. |
| 979 |
Distribute Coins in Binary Tree |
Try every possible sequence of moving coins between adjacent nodes until every node has exactly one coin, and count the total steps. |
$O(N!)$. Factorial search for the optimal movement sequence. |
Draw a tree with coins. Draw an arrow moving a coin from A to B. Start over. Try moving from A to C. It’s a massive web of "what-if" moves. |
Post-Order Traversal (Excess/Deficit Flow) |
"Balancing the Books." Each node calculates its "balance": `Coins_it_has + Balances_from_children - 1`. The absolute value of this balance is the number of coins that MUST cross the edge to its parent. |
Recursive `dfs(node)`: returns `balance`. `ans += abs(left_bal) + abs(right_bal)`. Return `node.val + left_bal + right_bal - 1`. |
Draw a tree. At each node, write the number of coins it has. Use red arrows (deficit) and green arrows (excess) to show "flow" moving up to the parent. |
$O(N)$. A single bottom-up traversal of the tree. |
Draw a tree. Draw arrows pointing UP from leaves to root. Write a "Net Balance" number (+2, -1, 0) next to each arrow. |
Stack overflow or massive memory from factorial path search. |
$O(H)$ recursion stack space. Draw a vertical column of function calls. |
| 980 |
Unique Paths III |
Standard DFS/Backtracking that counts all paths from start to end without checking if all empty squares were visited. |
$O(4^(R\cdot C)$). A sprawling tree where paths loop and miss squares, leading to incorrect counts. |
Draw a grid. Draw a line from start to end that skips the middle. Draw a red 'X' over it because it didn't touch every cell. |
Backtracking with State (Hamiltonian Path) |
"The Greedy Roomba." You must "vacuum" every single empty square exactly once before reaching the finish line. |
1. Count total empty squares. 2. DFS from start. 3. Mark current cell as visited. 4. If current is end and `remain == 0`, `count++`. 5. Backtrack (unmark cell). |
Draw a maze. Use a highlighter to trace a path. The path is only valid if there is no white space left in the "empty" zones when you reach the end. |
$O(3^N)$ where N is the number of empty cells. At each step, you have at most 3 choices (can't go back). |
Draw a decision tree where each node represents a `(row, col, remaining_squares)` state. Show branches dying if they reach the end too early. |
Deep recursion stack, but functionally incorrect results. |
$O(R\cdot C)$ for the recursion stack. Draw a vertical column of grid coordinates. |
| 981 |
Time Based Key-Value Store |
Store every `(key, value, timestamp)` in a single large list. For every `get(key, time)`, iterate backward through the whole list to find the match. |
$O(N)$ per get. A "Windshield Wiper" that sweeps the entire history for every single query. |
Draw a vertical timeline of all inputs. For a query at Time=10, draw an arrow scanning from the bottom of the paper all the way to the top. |
HashMap + Sorted List (Binary Search) |
"The Filing Cabinet." Each key has its own drawer. Inside each drawer, files (values) are sorted perfectly by time. You use a "Time Index" to jump to the right file. |
`Map>`. For `get`, fetch the list for that key. Use binary search (`bisect_right` or `upper_bound`) to find the largest timestamp <= target. |
Draw a cabinet. Labels are 'foo', 'bar'. Inside 'foo', draw a sorted list of timestamps [10, 20, 30]. For query 25, draw an arrow pointing between 20 and 30. |
$O(1)$ set, $O(\log N)$ get. Logarithmic "narrowing" of the search space. |
Draw a Binary Search Tree structure for a single key's history to show how we skip half the data at each step. |
$O(N)$ to store everything in a flat list. |
$O(N)$ to store everything in the Map. Draw a dictionary structure where each value is a horizontal array. |
| 982 |
Triplets with Bitwise AND Equal To Zero |
Three nested loops checking every possible combination `(i, j, k)` to see if `(A[i] & A[j] & A[k]) == 0`. |
$O(N^3)$. For N=1000, this is 1 billion operations. |
Draw a 3D cube of points. Every point in the volume must be checked manually. |
Precomputed Pairwise Frequency (Hashmap) |
"The Two-Step Filter." First, calculate the AND result for every *pair* and store the frequency. Then, iterate the array one more time to see which pairs "cancel out" the third element. |
1. `count[A[i] & A[j]]++` for all pairs. 2. For each `x` in `A`: iterate through `count` map; if `(x & pair_and) == 0`, `total += count[pair_and]`. |
Draw two arrays A and A. Show them "merging" into a frequency table of AND results. Then show a third array A "pinging" that table. |
$O(N^2 + N \cdot 2^{16})$. The second step is bounded by the max possible bitwise value (65536), not N. |
Draw a 2D grid for the N^2 part, followed by a linear scan of a 65,536-entry array. |
$O(1)$ extra space, but unusable time. |
$O(2^{16})$ space for the frequency map. Draw a single row of 65,536 boxes. |
| 983 |
Minimum Cost For Tickets |
Recursive DFS trying all 3 ticket types at every single travel day without caching the results. |
$O(3^N)$. A tree that triples in size for every travel day in the year. |
Draw a calendar. From Day 1, draw 3 branches. From Day 2, 9 branches. The tree covers the entire calendar like an overgrown vine. |
DP (1D Calendar / Days-based) |
"The Daily Budget." For each day, your minimum cost is the best of three "What Ifs": 1. Bought a 1-day yesterday, 2. Bought a 7-day a week ago, 3. Bought a 30-day a month ago. |
`dp[i]` = min cost for day `i`. If not a travel day, `dp[i] = dp[i-1]`. Else, `dp[i] = min(dp[i-1]+c[0], dp[max(0,i-7)]+c[1], dp[max(0,i-30)]+c[2])`. |
Draw a row of 365 boxes. For box 30, draw three "look-back" arrows pointing to box 29, box 23, and box 0. |
$O(W)$ where W is the travel window (max 365). Linear time relative to the number of days. |
Draw a horizontal timeline. Shade each day as you calculate it, using previous shaded values as inputs. |
Massive recursion depth and exponential state space. |
$O(W)$ for the DP array. Draw a single row of 365 boxes labeled 'Cost'. |
| 984 |
String Without AAA or BBB |
Generate all permutations of strings containing A 'a's and B 'b's and check each one for the 'AAA/BBB' condition. |
$O((A+B)$! / (A!B!)). Combinatorial explosion. |
Draw all ways to arrange "AABB". Highlight the ones that don't have three-in-a-row. For A=10, B=10, there are too many to draw. |
Greedy (Heavy-Letter Priority) |
"The Depletion Strategy." Always try to use your most plentiful letter first, unless you've already used it twice in a row. This prevents getting "stuck" with 3+ of the same letter at the end. |
While A > 0 or B > 0: if `a_count > b_count`, if last two were "aa", add 'b', else add 'a'. Else (if `b_count >= a_count`), if last two were "bb", add 'a', else add 'b'. |
Draw two piles of tokens (A and B). Draw a hand reaching for the taller pile. If it already picked two from that pile, the hand is forced to reach for the shorter pile. |
$O(A + B)$. A single pass to build the string. |
Draw a string being built character by character. Below it, draw the sizes of the two "letter piles" decreasing. |
$O(\text{Total}!)$ space to store permutations. |
$O(A + B)$ to store the result string. Draw a single row of empty boxes. |
| 985 |
Sum of Even Numbers After Queries |
For every query, update the array element, then iterate through the entire array and sum all even numbers from scratch. |
$O(Q \cdot N)$. A "Full Scan" for every single change. |
Draw an array. For Query 1, circle every even number and add them. For Query 2, do it again. The circles overlap and repeat work. |
Global Sum Maintenance (Delta Tracking) |
"The Live Counter." Calculate the sum of all even numbers once. For each query, only check if the specific number being changed was even (remove it from sum) or became even (add it to sum). |
1. `S = sum(evens)`. 2. For `val, idx` in query: if `A[idx]` was even, `S -= A[idx]`. 3. `A[idx] += val`. 4. If `A[idx]` is now even, `S += A[idx]`. 5. Store `S`. |
Draw a large "Total" box. When a number changes, draw an arrow "subtracting" the old value out of the box and another arrow "adding" the new value in. |
$O(N + Q)$. One initial scan, then $O(1)$ per query. |
Draw a horizontal timeline. Below it, draw a single "Running Sum" box that flickers and updates its value at each step. |
$O(1)$ extra space but very slow. |
$O(1)$ extra space (excluding the result array). Draw one small box labeled `evenSum`. |
| 986 |
Interval List Intersections |
Nested loops: for every interval in list A, compare it against every interval in list B to find overlaps. |
$O(A \cdot B)$. Checking every pair across two timelines. |
Draw two timelines. Draw lines connecting every segment in A to every segment in B. It becomes a tangled web of comparisons. |
Two Pointers (Parallel Scan) |
"The Zipper." Since both lists are sorted, you can move two pointers forward simultaneously. Only compare the two intervals the pointers are currently touching. |
`i=0, j=0`. While `i < A.size` and `j < B.size`: find `start = max(A[i].start, B[j].start)`, `end = min(A[i].end, B[j].end)`. If `start <= end`, record intersection. Increment the pointer that has the smaller `end` value. |
Draw two parallel horizontal lines with segments. Draw a vertical "Comparison Frame" that moves across both lines, only looking at two segments at a time. |
$O(A + B)$. A single pass through both lists. |
Draw two horizontal lines. Draw two arrows (one for each line) pointing right, moving in a "staggered" fashion until both reach the end. |
$O(1)$ extra space but quadratic time. |
$O(\text{IntersectionCount})$ for the result. Draw a single row of result segments below the two original lines. |
| 987 |
Vertical Order Traversal of a Binary Tree |
Perform BFS/DFS to find all nodes, store them in a list with their coordinates (x, y), and then perform a global sort on all nodes based on x, then y, then value. |
$O(N \log N)$. Sorting the entire tree globally when it already has structural order. |
Draw a tree. For every node, write `(x, y)`. Draw a massive "Sorting Bin" and dump all node values into it. |
TreeMap of Sorted Lists (Coordinate Grouping) |
"The Vertical Slot Machine." Use a map where the key is the x-coordinate. For each x, keep a list of nodes that you sort by y and value. |
1. BFS/DFS to populate `Map>`. 2. Sort the keys of the Map. 3. For each key, sort its list. 4. Collect results. |
Draw a tree. Draw vertical "Silos" (columns) through the tree. As you visit a node, it "drops" into its corresponding silo based on its horizontal position. |
$O(N \log N)$ in the worst case, but better distributed because you only sort nodes within the same x-coordinate. |
Draw a tree with vertical dashed lines representing x = -1, 0, 1... Below each line, draw a small vertical list of values. |
$O(N)$ to store the flat list of nodes. |
$O(N)$ for the coordinate map. Draw a multi-column table where each column represents a vertical slice of the tree. |
| 988 |
Smallest String Starting From Leaf |
Generate every possible string from leaf to root, store them in a list, sort the list, and return the first one. |
$O(N \cdot H)$ or higher. Storing and sorting many full-length paths. |
Draw a tree. From every leaf, draw an arrow to the root, writing the resulting string next to the leaf. Highlight the alphabetically smallest. |
DFS with Path Tracking (Bottom-Up Logic) |
"The Lexicographical Filter." As you traverse, build the string. When you hit a leaf, compare the current path (reversed) with the global minimum. |
Recursive `dfs(node, path)`: add current char to `path`. If leaf, `res = min(res, reverse(path))`. Recurse left and right. |
Draw a tree. At each leaf, draw a speech bubble with its path string. Draw a "Champion" box that holds only the smallest string seen so far, updating as the DFS progresses. |
$O(N \cdot H)$ because string concatenation and comparison take time proportional to the height of the tree. |
Draw a tree with a single path highlighted, and a small box labeled `smallest` that changes as the traversal moves to different leaves. |
$O(N \cdot H)$ to store all leaf-to-root strings. |
$O(H)$ recursion stack. Draw a vertical column of function calls, each holding a partial string. |
| 989 |
Add to Array-Form of Integer |
Convert the array `[1, 2, 0]` into the number 120, add `K`, and then convert the result back into an array. |
$O(N)$ but fails for large numbers. Most programming languages cannot store an array-form number like 10^10000 as a standard integer. |
Draw a huge array. Draw a tiny "Integer" box. Show the array trying to squeeze into the box and the box exploding (overflow). |
Schoolbook Addition (Right-to-Left) |
"The Manual Carry." Start at the end of the array. Add `K` to the last element. The new digit is `sum % 10`, and the new "carry" is `sum // 10`. Move left and repeat. |
Iterate `i` from `N-1` to 0. `K += A[i]`. `res.append(K % 10)`. `K //= 10`. After loop, if `K > 0`, append remaining digits of `K`. Reverse `res`. |
Draw two numbers stacked vertically, like in 2nd-grade math. Draw small "1"s (carries) above the columns as you move from right to left. |
$O(\text{max}(N, \log K)$). A single linear pass through the digits. |
Draw a horizontal array. Draw an arrow moving from right to left, with a "Carry" box being updated and added at each step. |
Negligible, but functionally broken for large inputs. |
$O(\text{max}(N, \log K)$) for the result array. Draw a single row of result digits. |
| 990 |
Satisfiability of Equality Equations |
Generate all possible assignments of values (0-25) to the 26 variables (26! or 10^26 combinations) and check if the equations hold. |
$O(26^26)$. An astronomical search space that is impossible to compute. |
Draw 26 variables. Try setting a=1, b=1, c=2... then a=1, b=2, c=1... Show a tree of choices that fills the entire universe. |
Union-Find (Consistency Check) |
"Connecting the Dots." Process all "==" equations first to group variables into "equality islands." Then, check all "!=" equations; if two variables in a "!=" rule are on the same island, the logic is broken. |
1. Initialize Union-Find for 26 letters. 2. For each eq `a==b`, `union(a, b)`. 3. For each eq `a!=b`, if `find(a) == find(b)`, return `false`. 4. Return `true`. |
Draw letters as nodes. For `a==b`, draw a solid line. For `c!=d`, draw a dashed red line with an 'X'. Logic is valid if no dashed line connects nodes in the same solid cluster. |
$O(N)$. Processing N equations with near-constant time Union-Find operations. |
Draw a 26-slot array (Parent pointers). Show pointers moving to point to "Group Leaders" as equations are processed. |
$O(26^26)$ state space. |
$O(1)$ extra space (fixed array of 26 integers). Draw one small row of 26 boxes labeled 'Parent'. |
| 991 |
Broken Calculator |
BFS starting from `startValue`, exploring `x * 2` and `x - 1` at every step to find the shortest path to `target`. |
$O(2^\text{depth})$. The search tree grows exponentially, especially because the value can grow much larger than the target before coming back down. |
Draw `startValue`. Branch to `*2` and `-1`. From those, branch again. The tree is lopsided and deep, often looping back on itself. |
Greedy Reverse Engineering (Work Backwards) |
"The Path of Least Resistance." It's easier to reach `startValue` from `target`. If `target` is even, you *must* have come from a `*2` (so divide by 2). If odd, you *must* have come from a `-1` (so add 1). |
While `target > startValue`: if `target % 2 == 0`, `target /= 2`, else `target += 1`. Increment `steps`. Final result = `steps + (startValue - target)`. |
Draw a number line. Mark Start and Target. Draw a single path from Target moving left. If the number is even, take a "Giant Leap" (divide); if odd, take a "Tiny Step" (plus 1). |
$O(\log(\text{target}/\text{start})$). Each division operation cuts the number in half. |
Draw a single horizontal line with one arrow moving from right to left, shrinking the target value rapidly. |
$O(2^\text{depth})$ space to store the BFS queue of reached numbers. |
$O(1)$. Only two integer variables. Draw two small boxes: `currentValue` and `steps`. |
| 992 |
Subarrays with K Different Integers |
Nested loops checking every possible subarray (i, j) and counting the number of unique integers in each using a HashSet. |
$O(N^2)$. Checking a quadratic number of ranges. |
Draw an array. Draw overlapping brackets for every range. Inside each bracket, draw a tiny Set { } to count unique numbers. |
Sliding Window (Exact = AtMost(K) - AtMost(K-1)) |
"The Difference of Two Windows." Counting *exactly* K is hard. Instead, calculate how many subarrays have *at most* K, and subtract those with *at most* K-1. |
`atMost(K)`: Use a sliding window with two pointers and a frequency map. If `map.size() > K`, shrink left. Subarrays ending at `right` = `right - left + 1`. |
Draw a large "Window" frame (AtMost K) and a smaller "Window" frame (AtMost K-1). Show that the subarrays in the large one but NOT the small one are exactly what we need. |
$O(N)$. Two linear passes (one for K, one for K-1). |
Draw two horizontal lines. On each, show two arrows (Left and Right pointers) moving strictly forward. |
$O(N^2)$ time with $O(N)$ space for sets. |
$O(K)$ space for the frequency map. Draw a vertical two-column table: [Integer -> Count]. |
| 993 |
Cousins in Binary Tree |
For every node in the tree, find its depth and its parent. Then, specifically check the target nodes `x` and `y` to see if they meet the criteria. |
$O(N)$ but involves multiple full traversals or storing a lot of redundant parent/depth info. |
Draw a tree. For every node, draw two arrows: one pointing to the root (depth) and one pointing to its parent. It's a lot of extra lines. |
Level-Order BFS (Same Level, Different Parent) |
"The School Grade." Nodes in the same "grade" (level) are candidates. If `x` and `y` are in the same grade but have different "Parents" (teachers), they are cousins. |
Use a Queue for BFS. In each level-step, check if `x` and `y` both exist in the current level. Before pushing children, check if a parent has both `x` and `y` as children (not cousins). |
Draw a tree. Draw horizontal "Level" lines. Circle `x` and `y`. If they are on the same line, look up one level; if they don't share the same parent node, draw a "Cousins" link between them. |
$O(N)$. Each node is visited exactly once. |
Draw a tree with horizontal dashed lines. Below it, draw a queue containing pairs of `(node, parent_val)`. |
$O(N)$ to store parent/depth maps. |
$O(W)$ where W is the maximum width of the tree. Draw a horizontal pipe (Queue). |
| 994 |
Rotting Oranges |
Perform a full DFS from every single rotten orange. For each, keep track of when each fresh orange gets infected, taking the minimum of all times. |
$O((R\cdot C)$^2). Multiple redundant traversals across the same grid. |
Draw a grid with two rotten oranges. Draw "Infection Ripples" from the first, then from the second. The ripples overlap and conflict on the paper. |
Multi-Source BFS |
"The Contagion." All rotten oranges start "rotting" their neighbors at the exact same time. The infection spreads in concentric squares level-by-level. |
1. Count fresh oranges. 2. Push all initial rotten oranges into a Queue. 3. While queue: for each rotten orange, infect neighbors, push to queue, `fresh--`. 4. Result is `time_elapsed`. |
Draw a grid. Mark rotten oranges as time "0". Mark their neighbors as "1", their neighbors as "2". It looks like a topography map where the "high points" are the last fresh oranges to rot. |
$O(R \cdot C)$. Every grid cell is visited exactly once. |
Draw the grid. Use a highlighter to "shade" cells minute-by-minute, showing the rot spreading outward like a wave. |
Deep recursion stack with $O(R\cdot C)$ depth and many branches. |
$O(R \cdot C)$ for the queue. Draw a large circular buffer containing `(row, col)` coordinates. |
| 995 |
Minimum Number of K Consecutive Bit Flips |
Iterate through the array. If you find a 0, flip the next K elements manually. Repeat until the end. |
$O(N \cdot K)$. In the worst case (K = N/2), you perform N/2 flips on N/2 elements. |
Draw a binary array. Below it, draw a "Flip" bar of length K. Every time the bar lands on a 0, redraw the array with inverted numbers. |
Greedy with Difference Array / Sliding Window |
"The Flip History." Instead of actually flipping elements, keep track of how many active flips are currently affecting the current index. A number is flipped only if the current active count is odd. |
Maintain `activeFlips`. If `(A[i] + activeFlips) % 2 == 0`, we MUST flip at `i`. Increment `activeFlips` and mark that this flip ends at `i + K`. At `i + K`, decrement `activeFlips`. |
Draw a horizontal timeline. Below it, draw "Effect Bars" of length K. Instead of changing the numbers above, just count how many bars are "overlapping" the current point. |
$O(N)$. A single linear sweep where each element is processed once. |
Draw an array. Above it, draw a "Flip-Counter" line that goes up when a flip starts and down when it expires. |
$O(1)$ if flipping in-place, but $O(N \cdot K)$ time is the bottleneck. |
$O(N)$ or $O(K)$ depending on implementation (to track flip expiry). Draw a small "Expiry Queue" or a second bit-array. |
| 996 |
Number of Squareful Arrays |
Generate all N! permutations of the array. For each, check if the sum of every adjacent pair is a perfect square. |
$O(N! \cdot N)$. Factorial explosion. For N=12, this is 479 million checks. |
Draw a tree that branches N times at the root. Most paths will fail the square check immediately, but you still have to explore the "what-ifs." |
Hamiltonian Path (Backtracking + Pruning) |
"Selective Building." Only place a number next to another if their sum is squareful. This prunes the search tree significantly. Use a frequency map to handle duplicates. |
1. Build a graph where an edge exists between `u` and `v` if `sqrt(u+v)` is an integer. 2. Use DFS to find all paths of length N that visit each element's frequency count correctly. |
Draw numbers as nodes. Draw lines only between numbers that sum to a square. Your task is to find all ways to draw a single continuous line through every node. |
$O(N \cdot 2^N)$ or better depending on graph density. Much smaller than N!. |
Draw a graph with very few edges. Show a "Path-Finder" moving only along these specific lines. |
$O(N!)$ to store permutations. |
$O(N^2)$ for the adjacency list and $O(N)$ for recursion. Draw a small graph connectivity matrix. |
| 997 |
Find the Town Judge |
For every person, check if they are trusted by everyone else and if they trust nobody by scanning the whole `trust` list twice. |
$O(N^2)$ or $O(N \cdot T)$. Repeated scans of the trust relationships. |
Draw N people. For each, count incoming and outgoing arrows by looking through a giant pile of paper (the trust list). |
Trust Score Array (In-Degree vs Out-Degree) |
"The Popularity Balance." A person's score is (People who trust them) - (People they trust). The judge must have a score of exactly N-1. |
Create an array `scores` of size N+1. For each `a, b` in trust: `scores[a]--`, `scores[b]++`. Find the index where `scores[i] == N-1`. |
Draw a vertical leaderboard. When A trusts B, B's score goes up 1 point and A's goes down 1 point. The Judge will be at the very top with N-1 points. |
$O(T + N)$ where T is the number of trust relationships. One pass through the list, one pass through the scores. |
Draw a horizontal timeline of trust events. Below it, draw a single 1D array updating its tallies. |
$O(1)$ extra space but very slow. |
$O(N)$ for the scores array. Draw a single row of N boxes. |
| 998 |
Maximum Binary Tree II |
Convert the existing tree back into its original array, append the new value to the end, and rebuild the entire Maximum Binary Tree from scratch. |
$O(N^2)$ in the worst case (rebuilding can be quadratic). |
Draw a tree. Flatten it into a line. Add a new number. Build a brand new tree. It’s a lot of erasing and redrawing. |
Right-Spine Insertion |
"The Newest Arrival." Since the new value is appended to the *end* of the array, it must either become the new root (if it's the largest) or live somewhere on the right-hand side of the current tree. |
If `val > root.val`: new node becomes root, old tree becomes its left child. Else: recurse into `root.right`. |
Draw a tree. Draw a "New Node" hovering to the right. Show it sliding down the right edge of the tree until it finds a node smaller than itself, then "inserting" itself there. |
$O(H)$ where H is the height of the tree. In a balanced tree, this is $O(\log N)$. |
Draw a tree with a single path highlighted on the far right. Draw an arrow showing where the new node "plugs in." |
$O(N)$ to store the intermediate array. |
$O(H)$ recursion stack. Draw a thin vertical column for the depth of the right spine. |
| 999 |
Available Captures for Rook |
For every square on the board, if it's a Pawn, check if there is a Rook in the same row or column that can reach it without hitting a Bishop. |
$O(64 \cdot 64)$. Redundant checks from every pawn's perspective. |
Draw an 8x8 grid. For every 'p', draw four long lines looking for a 'R'. The board becomes a mess of criss-crossing lines. |
Rook-Centric Scan |
"The Four-Way Look." Find the Rook first. Then, simply "look" in four directions (Up, Down, Left, Right) until you either hit a Pawn (capture!), a Bishop (blocked!), or the edge. |
1. Find Rook `(r, c)`. 2. For each direction `(dr, dc)`: move in that direction until you hit 'p' (count and break), 'B' (break), or edge. |
Draw an 8x8 grid. Shade the Rook. Draw four straight arrows extending from it. The moment an arrow hits a 'p', circle it. If it hits a 'B', draw a "Wall" icon. |
$O(1)$. The board is always 8x8, so you check at most 32 squares. |
Draw a central point (Rook) with four "Laser Beams" shooting out toward the boundaries. |
$O(1)$ space but inefficient logic. |
$O(1)$. No extra structures needed beyond a few coordinate variables. Draw four small integer boxes. |
| 1000 |
Minimum Cost to Merge Stones |
Try every possible combination of merging `K` adjacent piles. Use recursion to explore all paths to a single pile and find the minimum cost. |
$O(\text{Exponential})$. Similar to Matrix Chain Multiplication but with a K-pile constraint. |
Draw a row of stones. Draw brackets around any K stones. From that new state, draw more brackets. It becomes a massive tree of "what-if" merges. |
DP (Interval 3D) |
"The Sub-problem Pyramid." To merge a large range [i, j], you must first have merged it into some number of smaller piles. The state tracks the range and the number of piles it currently represents. |
`dp[i][j][k]` is the min cost to merge range `[i, j]` into `k` piles. Transition: `dp[i][j][k] = min(dp[i][mid][1] + dp[mid+1][j][k-1])`. If `k == 1`, add the total sum of the range. |
Draw a triangle (pyramid) over the array. Each block in the pyramid represents a range. Color a block when it successfully merges into 1 pile. |
$O(N^3 / K)$. While it's 3D, the range constraints and K-step jumps reduce the actual work. |
Draw a 2D grid of ranges [i, j]. For each cell, show a "Splitter" moving through all possible `mid` points to find the best merge. |
Massive recursion stack and repeated calculations of the same intervals. |
$O(N^3)$ for the 3D DP table. Draw a "Cube" of memory cells where the axes are Left, Right, and PileCount. |
| 1001 |
Grid Illumination |
For every query, iterate through every single lamp in the list. Check if its row, col, or diagonals hit the target square. |
$O(\text{Queries} \\text{cdot Lamps})$. Quadratic search for every light check. |
Draw a grid. For one query square, draw four long lines looking for any 'L' (Lamp) in the entire list of lamps. Repeat for all queries. |
HashMaps for Line Counting |
"The Four-Way Tally." Instead of checking lamps, track how many lamps are active on each row, column, and the two types of diagonals (r+c and r-c). A square is lit if any of its 4 lines have a count > 0. |
1. Four maps: `row`, `col`, `diag1`, `diag2`. 2. For each query, check maps. 3. Check 9 neighbors; if a lamp exists, decrement map counts and delete the lamp. |
Draw a grid. Above it, draw a row-counter; next to it, a col-counter. Draw two diagonal "rails" with counters. When a lamp is placed, it "increments" one slot on each of the 4 counters. |
$O(\text{Lamps} + \text{Queries})$. Building the counters is linear, and each query check is $O(1)$. |
Draw a 1D timeline of queries. Above it, draw four tiny hash tables being updated and queried. |
$O(1)$ extra space but unusable time. |
$O(\text{Lamps})$ to store the maps and the lamp coordinates. Draw four vertical tables: [LineID -> Count]. |
| 1002 |
Find Common Characters |
Pick the first word. For each of its characters, check if it exists in every other word. If yes, remove it from all words and add to the result. |
$O(N \cdot L^2)$. Repeatedly searching and modifying strings (which is expensive). |
Draw three words. Pick 'a' from word 1. Hunt for 'a' in word 2 and 3. Erase them with a pencil. Repeat. The paper is messy with erasures. |
Frequency Intersection (Min-Tally) |
"The Lowest Common Denominator." Count the characters in the first word. For every subsequent word, update your count to be the *minimum* of what you currently have and what the new word has. |
1. `minFreq` = 26-slot array for word[0]. 2. For word in words[1:]: get `currFreq`. For `i` in 0..25: `minFreq[i] = min(minFreq[i], currFreq[i])`. |
Draw a 26-slot "Master Frequency" bar chart. For each new word, "squash" the bars down so they never exceed the height of the current word's bars. |
$O(N \cdot L)$. You look at every character in every word exactly once. |
Draw a vertical stack of 26-slot arrays. Draw an arrow pointing down through each slot, taking the `min` value to the next row. |
$O(N \cdot L)$ for storing modified versions of the words. |
$O(1)$ extra space (fixed 26-size arrays). Draw two rows of 26 boxes: `Master` and `Current`. |
| 1003 |
Check If Word Is Valid After Substitutions |
Repeatedly search the string for "abc" and replace it with an empty string until no more "abc" instances remain. Check if string is empty. |
$O(N^2)$. String slicing and searching can be very slow if many small deletions happen. |
Draw a long string. Circle "abc" and cross it out. Re-write the remaining string. Repeat. Show a long stack of increasingly shorter strings. |
Stack Simulation |
"The Tetris Clear." Push characters onto a stack. Every time the top three characters form "abc", pop them all immediately. The string is valid if the stack is empty at the end. |
For char in S: push to stack. If `stack.suffix == "abc"`, pop 3 times. Return `stack.isEmpty()`. |
Draw a vertical bucket. Drop an 'a', then 'b', then 'c'. The moment 'c' hits, draw a "Clear!" flash and show the bucket becoming empty again. |
$O(N)$. Every character is pushed and popped at most once. |
Draw a horizontal timeline. Below it, draw a stack growing and shrinking like a wave. |
$O(N^2)$ memory if creating new string copies for every deletion. |
$O(N)$ for the stack. Draw a single vertical column of characters. |
| 1004 |
Max Consecutive Ones III |
Try every possible subarray (i, j). For each, count the number of zeros. If zeros <= K, calculate the length and track the max. |
$O(N^2)$. Checking a quadratic number of ranges. |
Draw an array. Draw overlapping brackets for every range. Inside each bracket, manually count the '0's. |
Sliding Window (Expand/Contract) |
"The Rubber Band." Stretch the right side of the window to include more numbers. If the count of '0's inside the window exceeds K, shrink the left side until the count is back to K. |
`i = 0`. For `j` in 0..N-1: if `A[j] == 0`, `K--`. If `K < 0`: if `A[i] == 0`, `K++`, then `i++`. Max length is `j - i + 1`. |
Draw an array. Draw a sliding frame `[ ... ]`. Show the frame expanding right. When it hits a 0 and has no "budget" left, show the left side of the frame snapping forward. |
$O(N)$. Two pointers moving strictly from left to right. |
Draw a horizontal line. Draw two arrows (Left and Right) moving right. The gap between them is the "Window." |
$O(1)$ extra space but unusable time. |
$O(1)$. Only variables for the pointers and the current zero-count. Draw three small boxes. |
| 1005 |
Maximize Sum Of Array After K Negations |
Scan the whole array to find the absolute minimum element. Flip its sign. Repeat this full scan K times. |
A loop running K times, where each iteration forces a full linear sweep of the array. |
Draw the array. Cross out the smallest number, write its opposite. Do this K times. Write $O(K \cdot N)$. |
Greedy (Sorting). |
A conveyor belt sorting elements from negative to positive, followed by a toggling machine. |
Sort the numbers. March left to right, flipping negatives to positives. If you run out of negatives but still have odd K left, flip the smallest positive number back and forth. |
Draw the sorted array. Put an arrow moving left-to-right. Strike through '-' signs while counting down K. If K remains, point at the smallest number and toggle it. |
A sorting funnel followed by a single straight line. |
Draw a box labeled "Sort" and write $O(N \log N)$ inside it. Follow it with a straight arrow labeled $O(N)$. |
In-place modification, so just one array. |
The same single array in-place, but visually ordered. Sorting overhead may take $O(\log N)$ stack space depending on the language. |
| 1006 |
Clumsy Factorial |
Build the entire math expression as a giant string ("10 * 9 / 8 + 7 - 6..."), then parse and evaluate it observing standard order of operations. |
A massive string builder followed by an expression tree parser (two heavy phases). |
Write out the full string equation. Draw parenthesis around all the * and / groups, then evaluate them one by one. Write Time: $O(N)$. |
Stack (Simulation of BODMAS/PEMDAS). |
A vertical processing tube with a 4-step cyclical engine (*, /, +, -). |
Push numbers into a tube. For * or /, immediately pop the top number, calculate, and push the result back. For + or -, just push the number (use negatives for -). Sum the tube at the end. |
Draw a tall U-shape (stack). Push N. For *, pop N, write (N * N-1) and push it. For +, push (N-3). Finally, add all numbers inside the U-shape. |
Single pass inserting and collapsing elements in a cylinder. |
Draw a straight line from N down to 1. Write $O(N)$. The operations inside are $O(1)$ constant time. |
A massive string allocation holding N characters/numbers before it even gets calculated. $O(N)$ space. |
A Stack structure. Show how the stack never grows past N/4 items because * and / immediately collapse elements. $O(N)$ space. |
| 1007 |
Min Domino Rotations For Equal Row |
Check numbers 1 through 6. For each number, scan the entire array of dominoes to see if a full row can be formed. Count swaps for both top and bottom. |
6 separate horizontal timelines, one for each face value on a die. |
Draw the dominoes as a 2xN grid. Write numbers 1-6. Pick '1', scan the whole grid to count tops and bottoms. Repeat for 2, 3, etc. Write $O(6 \cdot N)$. |
Greedy (Target Candidates). |
Two master keyholes (Target A and Target B) checking all subsequent locks. |
The only possible valid numbers MUST be either tops[0] or bottoms[0]. Check if target A exists in every domino. If yes, count swaps. Do the same for target B. |
Draw the 2xN grid. Circle the first top and first bottom. Draw two parallel arrows moving right, tallying missing tops/bottoms for Candidate 1 and Candidate 2. |
A single dual-track timeline. |
Draw the arrays with one straight arrow sweeping left to right. Write $O(N)$ above it. |
Just tracking counters, so conceptually a few boxes for $O(1)$ space. |
Only 4 small boxes (counters for top/bottom swaps for two candidates). Rigid $O(1)$ space. |
| 1008 |
Construct BST from Preorder Traversal |
Take the first element as root. For every following element, start from the root and traverse down to find its correct empty spot (standard BST insertion). |
Repeated falling balls. Every new number drops from the very top of the tree, bouncing left or right until it hits the floor. |
Draw a root node. Take the next number, draw a line from root to left/right. Take the third, trace from root again. Write $O(N^2)$ for a worst-case skewed tree. |
Recursion with Valid Range (Upper/Lower Bounds). |
A funnel dynamically narrowing its walls as you move deeper into the tree. |
Keep a "maximum allowed value". If the next number in the array is smaller than the current node, make it the left child. If it's bigger but within the max allowed, attach it to the right. |
Draw a node. Write `(-∞, ∞)` next to it. Draw a left child, update the text to `(-∞, ParentValue)`. Draw a right child, update to `(ParentValue, GrandparentValue)`. |
Single pass consumption of an array. |
Draw the input array with a single pointer moving strictly left to right. Write $O(N)$ time. |
$O(N)$ recursion stack memory. Visualized as a tall, leaning tower of function calls. |
$O(N)$ recursion stack memory (or explicit stack). Visualized as an expanding and contracting vertical column representing tree depth. |
| 1009 |
Complement of Base 10 Integer |
Convert the integer into a binary string ("101"), loop through the characters to flip '0' to '1' and '1' to '0', then parse the string back to an integer. |
A three-stage factory: Integer -> String Array -> Flipped String Array -> Integer. |
Write "5". Draw an arrow to "101". Cross out bits to write "010". Draw an arrow to "2". Write $O(\log N)$ operations with heavy string overhead. |
Bit Manipulation (XOR Masking). |
A precise stamped overlay (a mask of all 1s) pressing down onto the original bits to invert them simultaneously. |
Find out how many bits the number uses (e.g., 5 uses 3 bits: 101). Create a mask of the same length filled with 1s (111). XOR the mask with the number. |
Write the binary of N. Directly underneath it, write a row of 1s of the exact same length. Draw a line and perform XOR (if same write 0, if different write 1). |
Instantaneous bitwise logic gate. |
Draw a single bitwise operation block `N ^ Mask`. Write $O(1)$ or $O(\log N)$ depending on how the bit length is calculated. |
A string or char array allocation taking up $O(\log N)$ memory boxes. |
A single integer box for the bitmask. $O(1)$ pure space. |
| 1010 |
Pairs of Songs With Total Durations Divisible by 60 |
Compare every single song with every other song in a nested loop. Check if `(song1 + song2) % 60 == 0`. |
A complete web of lines connecting every item in an array to every other item (N^2 connections). |
Draw an N x N matrix grid. Cross out the diagonal. Shade the top right triangle to show unique pairs evaluated. Write $O(N^2)$. |
Hash Map / Frequency Array (Modulo Arithmetic). |
60 distinct buckets (numbered 0 to 59). Items drop in, and specific buckets are "paired" via an invisible wire. |
Take a song length, modulo 60. Drop it in that bucket. Immediately look at the complementary bucket `(60 - modulo) % 60` and add its count to your total. |
Draw a row of 60 boxes. Write tally marks in them. Draw connecting arches between box 1 and 59, 2 and 58, etc. Special circles on box 0 and 30. |
A single pass linear scan dropping items into fixed-size bins. |
Draw an array, with one straight arrow sweeping left to right. Write $O(N)$ Time. |
Conceptually carrying no extra space, just $O(1)$ pointers. |
A rigidly sized 60-element integer array. Visually represents true $O(1)$ space constraint regardless of N. |
| 1011 |
Capacity To Ship Packages Within D Days |
Start with ship capacity = max weight in array. Simulate loading. If it takes > D days, increment capacity by 1 and try again. |
A ship expanding its hull pixel by pixel, attempting the same full journey repeatedly. |
Draw a number line starting at Max_Weight. For every tick mark, draw a sub-loop simulating the array iteration. Write $O(N \\text{cdot SumOfWeights})$. |
Binary Search on Answer Range. |
A number line from `Max(weights)` to `Sum(weights)` where you chop the line in half based on a simulation test. |
Pick the middle capacity. Run through the conveyor belt of packages. If days > D, chop off the left half. If days <= D, chop off the right half to find a tighter fit. |
Draw a number line. Mark L = Max(arr) and R = Sum(arr). Put 'Mid' in the middle. Do a quick tally of days needed for 'Mid'. Cross out one half. |
A logarithmic zoom-in layered over a linear scan. |
Draw a logarithmic tree shrinking a range, where each node contains an $O(N)$ array scan. Write $O(N \log(\text{Sum})$). |
$O(1)$ space variables. |
$O(1)$ space variables: just L, R, Mid, and a day counter box. |
| 1012 |
Numbers With Repeated Digits |
Loop from 1 to N. Convert every integer to a string, toss characters into a Set, and check if Set size < string length. |
A massive factory line converting numbers to strings and tossing them into a shredder to check uniqueness. |
Draw numbers 1 to N. Under each, draw a miniature Set bucket catching its digits. Write $O(N \log N)$ (due to string conversion). |
Digit DP / Combinatorics. |
A branching decision tree placing digits into slots `_ _ _ _`, pruning branches where a digit is already used. |
Calculate Total Numbers (N). Calculate numbers WITHOUT repeated digits using Permutations (P(9, k)). Subtract the two. Total - Unique = Repeated. |
Draw blanks for digits `_ _ _`. Write available choices under the first blank (e.g., 9). Under the next, write 9, then 8. Multiply them. |
A shallow tree matching the number of digits in N. |
Draw a tree with depth equal to the number of digits of N (which is log10(N)). Write Time: $O(\log N)$. |
High memory churn from millions of string allocations. $O(\log N)$ space per number, GC overload. |
An array of digits or a small Memoization table of size ~10x1024. Represents $O(\log N)$ space. |
| 1013 |
Partition Array Into Three Parts With Equal Sum |
Place two dividers (i and j) to split the array into 3 parts. Check all possible combinations of i and j to see if sums match. |
Two sliding walls moving through the array in a nested fashion. |
Draw the array. Put a vertical line after index 0. Put a second vertical line moving from index 1 to end. Then move the first line to index 1... Write $O(N^2)$. |
Greedy Accumulation (Target Sum Matching). |
Three identical measuring cups. Pour elements in linearly until cup 1 is full, then cup 2, etc. |
Sum the whole array. Divide by 3 to find Target. March left to right, adding to a running total. When total == Target, "seal" the first part and reset to 0. Repeat for part 2. |
Draw array. Calculate `Target = Total/3`. Write running sum below elements. When sum hits Target, draw a vertical slash `|`. Do it again. Ensure elements remain for part 3. |
A single continuous sweep with conditional checkpoints. |
Draw an array with an arrow moving left to right. Mark two 'flags' on the arrow's path. Write $O(N)$. |
No extra space conceptually, just two pointers. |
Three variables: TotalSum, CurrentSum, and PartsFound. $O(1)$ space visualised as three small boxes. |
| 1014 |
Best Sightseeing Pair |
Compare every pair (i, j) where i < j. Calculate `values[i] + values[j] + i - j` and track the maximum. |
A measuring tape dragging from every starting point to every subsequent point. |
Draw array. From index 0, draw arcs to 1, 2, 3... Calculate formula for each arc. Repeat from index 1. Write $O(N^2)$. |
Dynamic Programming / 1D State Tracking. |
A decaying battery (max previous score) moving forward and comparing itself to the current spot. |
Split the formula: `(values[i] + i)` + `(values[j] - j)`. Track the maximum `(values[i] + i)` seen so far. At each step `j`, add it to `(values[j] - j)`, then update the max for the next step. |
Draw array. Keep a side-box called `Max_I`. At index `j`, write down `Max_I + values[j] - j`. Then update `Max_I` if `values[j] + j` is bigger. Move right. |
A single forward pass with a memory variable. |
Draw the array. Draw one arrow sweeping right, dragging a "highest value" block behind it that updates dynamically. Write $O(N)$. |
Strictly $O(1)$ conceptually. |
Two small boxes tracking `max_score` and `max_i`. Perfect $O(1)$ representation. |
| 1015 |
Smallest Integer Divisible by K |
Build the actual numbers 1, 11, 111, 1111... using BigInt logic and check if `number % K == 0`. |
A rapidly expanding string of '1's overflowing standard integer memory limits. |
Write 1 % K, 11 % K, 111 % K. Draw the numbers getting absurdly large. Write Time: $O(K)$, Space: $O(K)$ BigInts. |
Math (Modulo Arithmetic / Pigeonhole Principle). |
A clock face of size K. Stepping around the clock. If you hit a spot you've seen before without hitting 0, it's an infinite loop. |
Start at remainder R = 1 % K. Next R = (R * 10 + 1) % K. If R == 0, return length. If R repeats a past value, return -1. |
Draw a circle with K notches. Mark current remainder. Draw an arrow to the next remainder. Write the sequence 1, (R*10+1)%K... |
A loop running strictly at most K times before either hitting 0 or entering a cycle. |
Draw a line capping at length K. Write $O(K)$ Time. |
Massive BigInt text blocks filling up heap memory. |
A single integer tracking the remainder, and maybe a boolean array of size K (or just relying on loop count <= K). $O(1)$ space optimally. |
| 1016 |
Binary String With Substrings Representing 1 To N |
Loop i from 1 to N. Convert i to a binary string. Run standard substring search `S.contains(binary)` for every single number. |
N separate search parties sequentially scanning the entirety of string S. |
Write S. Under it, write binary of 1, 2, 3... and draw full-length search lines for each. Write $O(N \cdot S.\text{length})$. |
Sliding Window / Hash Set. |
A small, fixed-size window sliding over S once, capturing integer values into a bucket. |
Slide windows of lengths 1 up to log2(N)+1 across S. Convert those binary substrings to int. Add to a Set. If Set has N valid numbers <= N, return true. |
Draw string S. Draw a box of size 1 sliding across. Then box of size 2. Write numbers found into a circle (Set). Check if circle size == N. |
Sliding windows of max size ~30 over S, regardless of how huge N is. |
Draw S with a sliding frame. Write Time: $O(|S| \cdot \log N)$. |
N separate binary string allocations in memory. |
A Set holding at most N integers. $O(N)$ space constraint. |
| 1017 |
Convert to Base -2 |
Try to formulate it by regular base 2 conversion and fixing signs later, resulting in messy branching, patches, and infinite loops on negatives. |
A tangled decision tree of positive and negative remainders branching out of control. |
Write N / -2. Get stuck on negative remainders. Cross out and rewrite. Write $O(\text{Unknown})$. |
Math (Modulo with Negative Base). |
A continuous division machine where remainders are forced to be positive by artificially adjusting the quotient. |
Divide N by -2. If remainder is -1, mathematically change it to +1 and add 1 to the quotient. Prepend remainder to result string. |
Draw a vertical division table. N on left, quotient below, remainder on right. If remainder is < 0, add 2 to it, add 1 to quotient. |
A straight vertical mathematical descent to 0. |
Draw a cascading division block downwards. Write Time: $O(\log N)$. |
Heavy call stack or string builder exploding from infinite loops if negative remainders aren't handled. |
A simple String/StringBuilder growing to $O(\log N)$ size. |
| 1018 |
Binary Prefix Divisible By 5 |
Build the actual integer by appending bits one by one. Check if `num % 5 == 0`. |
An integer growing exponentially until it overflows 64-bit limits and crashes. |
Write 1. Next 10 (2). Next 101 (5). Write numbers getting massive. Write $O(N^2)$ due to BigInt string parsing. |
Math (Running Modulo). |
A dial with 5 positions (0-4). Appending a bit means doubling the dial position and adding the bit, wrapping around 5. |
Keep a running variable R = 0. For each bit, R = (R * 2 + bit) % 5. If R == 0, record true; else false. |
Draw the array. Below each bit, write the running R. E.g., bit 1 -> R=1. bit 0 -> R=(1*2+0)%5 = 2. |
A single stream processing bits and maintaining a tiny state machine. |
Draw the array with an arrow moving left to right. Write $O(N)$ Time. |
$O(N)$ large objects (BigInts) or huge strings allocated at each step. |
A single integer variable R. Perfect $O(1)$ space constraint. |
| 1019 |
Next Greater Node In Linked List |
For each node, traverse the rest of the linked list forward to find the first larger value. |
Nested loops; for every step forward, a "scout" runs all the way to the end of the line. |
Draw linked list. From node 1, draw an arrow checking node 2, 3, 4. From node 2, draw arrow to 3, 4. Write $O(N^2)$. |
Monotonic Stack. |
A waiting room (stack) of unresolved nodes. When a tall person (larger value) walks in, everyone shorter than them gets their answer and leaves. |
Push pairs of (index, value) onto a stack. If current value > stack top, pop stack top and set its result array index to current value. Push current. |
Draw list. Draw a U-shape (stack). Put index 0 in. If node 1 > node 0, cross out 0, write node 1's value in result array at index 0. |
A single linear sweep with a stack growing and shrinking. |
Draw an array creation, then a single pass line through the list. Write Time: $O(N)$. |
$O(1)$ pointers for the linked list search, plus $O(N)$ for the output array. |
A stack structure peaking at $O(N)$ size for strictly descending lists. |
| 1020 |
Number of Enclaves |
For every single land cell (1) in the grid, run a fresh DFS/BFS. If the path ever touches the grid boundary, mark it as invalid. Count the ones that never reach the edge. |
Hundreds of independent squiggly lines starting from the center and trying to worm their way to the map's edge. |
Draw a matrix. Pick a '1'. Draw arrows to its neighbors until you hit an edge or run out of 1s. Repeat this for the next '1'. Write $O(V \cdot (V+E)$). |
Multi-source DFS/BFS from Boundaries. |
A flood washing in from the outer edges of the map, eroding away all connected landmasses, leaving only the safe islands untouched in the center. |
Scan the 4 borders of the grid. If you see a '1', start a DFS that changes it and all connected '1's to '0's (or 'visited'). After the borders are processed, just count the '1's left in the grid. |
Draw the grid. Trace a highlighter around the border. For any '1' touching the border, scribble it out, then scribble out its '1' neighbors. Count the clean '1's left. |
A single inward-collapsing graph traversal. |
Draw the grid. Draw inward-pointing arrows from the four edges. Write Time: $O(M \cdot N)$ since each cell is visited at most once. |
Heavy recursion stack memory overlapping for multiple island checks. Space: $O(M \cdot N)$. |
Recursion stack (DFS) or Queue (BFS) sized to the maximum connected landmass. Space: $O(M \cdot N)$ worst case. |
| 1021 |
Remove Outermost Parentheses |
Find matching pairs by keeping a counter. Slice the string into valid primitive substrings. Then loop through each substring, remove the first and last character, and concatenate them. |
Slicing a string into physical blocks, surgically removing the ends of each block, and gluing them back together. |
Write the string. Draw vertical lines separating valid blocks `()()`. Cross out the first and last char of each block. Rewrite the remaining chars. Write $O(N^2)$ for string slicing. |
State Tracking (Depth Counter). |
An elevation map. We only keep parentheses that are strictly "above sea level" (depth > 0). The ones at sea level (depth 0) are stripped away. |
Keep a depth counter. If you see '(', check if depth > 0. If yes, it's inner, so keep it. Then increase depth. If you see ')', decrease depth first. If depth > 0, keep it. |
Write the string. Under each bracket, write the 'depth' count before processing for '(', and after processing for ')'. Circle any number > 0. These are the characters you keep. |
A single left-to-right pass building a new string. |
Draw a string with a single arrow sweeping right. Write Time: $O(N)$. |
Multiple substring arrays being created and destroyed. $O(N)$ temporary space footprint. |
A single array/StringBuilder growing exactly to the final size. $O(N)$ space. |
| 1022 |
Sum of Root To Leaf Binary Numbers |
Traverse the tree, passing down a string to build the binary number ("1" -> "10" -> "101"). At each leaf, parse the binary string to an integer and add to a global sum. |
A tree where each node holds a dynamically growing string, resulting in heavy string parsing bottlenecks at the leaves. |
Draw a binary tree. Next to each node, write the string "101". At the bottom, write `parseInt("101", 2) -> 5`. Write $O(N \cdot H)$ for string operations. |
Pre-order Traversal (Bitwise Accumulation). |
A falling snowball that doubles in size (shifts left by 1) and absorbs the current node's value as it rolls down each branch. |
Start at root with `val = 0`. As you go down, calculate `val = (val << 1) | node.val` (or `val * 2 + node.val`). When you hit a leaf, return `val`. For non-leaves, return `left_sum + right_sum`. |
Draw a tree. Pass a number down. Parent passes `2 * P + node.val` to children. At the leaves, circle the final numbers and sum them all up. |
Standard tree traversal visiting each node exactly once. |
Draw a binary tree with arrows tracing a DFS path. Write Time: $O(N)$. |
$O(N)$ unique string objects allocated, one for each path down the tree. |
$O(H)$ implicit call stack memory (Height of the tree), passing primitive integers. Perfectly bounded. |
| 1023 |
Camelcase Matching |
Generate a regular expression from the pattern (e.g., `F[a-z]*B[a-z]*`) and test every query string against it using a heavy Regex engine. |
A massive, opaque regex state machine compiling and evaluating strings over multiple passes. |
Write the pattern. Write the query. Draw complex regex matching paths for lowercase letters. Write $O(Q \cdot L^2)$ depending on the regex engine. |
Two Pointers (Subsequence Match with Constraints). |
A strict VIP checkpoint. The pattern is the VIP list. Lowercase letters in the query can wander past, but uppercase letters MUST match the next VIP in line. |
Pointer `i` on Query, `j` on Pattern. If `Q[i] == P[j]`, advance both. If `Q[i]` is lowercase, just advance `i`. If `Q[i]` is uppercase and DOESN'T match `P[j]`, the query fails. If `j` finishes, remaining `Q` must be lowercase. |
Write Query and Pattern. Put a dot under the start of each. Move Query dot right. If it matches Pattern dot, move Pattern dot. If Query hits an uppercase letter that doesn't match Pattern, draw a big red X. |
Parallel linear scans per query string. |
Draw two parallel arrays (Query and Pattern) with an arrow stepping through them. Write Time: $O(Q \cdot L)$ where L is max string length. |
Heavy Regex compilation objects and matcher states. |
Strictly $O(1)$ space per query (just two integer pointers `i` and `j`). |
| 1024 |
Video Stitching |
Generate all possible subsets of the clips. For each subset, check if it perfectly covers the interval [0, T] without gaps. Return the minimum size subset that works. |
An exploding decision tree of include/exclude operations, checking for continuous coverage only at the very bottom. |
Write all clips. Draw branching paths including or excluding clip 1, clip 2, etc. Write Time: $O(2^N)$. |
Greedy (Interval Scheduling / Jump Game logic). |
A series of overlapping searchlights. From your current position, look at all available searchlights and always pick the one that casts light the furthest to the right. |
Sort clips by start time. Track `current_end` and `farthest_reach`. Iterate clips that start before or at `current_end`, constantly updating `farthest_reach`. When you run out of clips in that range, increment your clip count and set `current_end = farthest_reach`. |
Draw a number line 0 to T. Draw clips as horizontal lines above it. Put a marker at 0. Find all clips starting <= 0. Pick the one that goes furthest right. Move marker to its end. Repeat. |
Sort block followed by a single sweep. |
Draw a sorting box `O(N log N)`. Then draw the array of intervals with one sweep arrow `O(N)`. Total Time: $O(N \log N)$. |
Massive exponential memory for tracking subsets or deep recursion stacks. |
$O(1)$ space for tracking variables (`end`, `farthest`, `count`), plus $O(N)$ or $O(\log N)$ implicit space for the sorting algorithm. |
| 1025 |
Divisor Game |
Recursively try every possible divisor 'x' for the current N, and for each, check if the other player can win from (N - x). |
A massive, bushy game tree where each node branches into multiple 'x' options. |
Draw N at top. Draw arrows to N-x1, N-x2... Repeat for each level. Label levels 'Alice' and 'Bob'. Write $O(2^N)$. |
Brain Teaser / Math (Parity). |
A seesaw. If Alice starts with an even number, she can always keep Bob on odd numbers until he hits 1 and loses. |
If N is even, Alice chooses x=1, giving Bob an odd N. Any divisor of an odd N is odd, so Bob must give Alice (Odd-Odd) = Even N back. |
Write "Even = Win", "Odd = Lose". Check `N % 2 == 0`. One simple comparison line. |
A single comparison gate. |
Draw a single bit check `(N & 1) == 0`. Write $O(1)$. |
A deep recursion stack frame for every possible move path. |
Zero extra space. Just the CPU register evaluating a parity bit. $O(1)$. |
| 1026 |
Max Difference Between Node and Ancestor |
For every node, start a new DFS to visit all its descendants and calculate the absolute difference between the node and each descendant. |
Exploding search circles. Every node acts as a new epicenter for a complete sub-tree scan. |
Draw a tree. For root, draw arrows to all nodes. For child, draw arrows to its nodes. Write $O(N^2)$ for skewed trees. |
DFS with Range Tracking (Top-Down). |
A descending elevator carrying two suitcases: the "Min-so-far" and "Max-so-far" encountered on the path from root. |
Pass current min/max down to children. At each node, calculate `max(node - min, max - node)`. Update global result and keep going down. |
Draw a tree. At each node, write a pair `[min, max]`. When moving to a child, update the pair: `[min(P_min, val), max(P_max, val)]`. |
A single fluid traversal of the tree. |
Draw a single DFS path (snake) through the tree. Write Time: $O(N)$. |
Repeatedly traversing subtrees, redundant visits visualized as darker, thick edges. |
A single recursion stack depth of $O(H)$, where H is tree height. Visualized as one vertical column. |
| 1027 |
Longest Arithmetic Subsequence |
Generate all possible subsequences (2^N), check if each is arithmetic, and track the maximum length. |
A dense forest of subsequences where most are invalid, checked only at the end. |
Draw dots for array elements. Draw branching lines for include/exclude. Write $O(2^N)$. |
2D Dynamic Programming (HashMap/Array). |
A 2D spreadsheet where Rows = Index in array and Columns = Common Difference. |
For each index `i`, look at all previous indices `j`. Calculate `diff = A[i] - A[j]`. The length at `(i, diff)` is `length at (j, diff) + 1`. |
Draw a grid. Rows 0 to N. Columns -500 to 500 (diffs). At `dp[i][diff]`, look at the value in row `j`, column `diff` and add 1. |
A double nested loop over the array. |
Draw a triangle of arrows: 0->1, 0->2, 1->2... Write $O(N^2)$ Time. |
Exponential memory for storing 2^N subsequences. |
A 2D table or an array of HashMaps. Space: $O(N \\text{cdot Range}_\text{of}_\text{Diffs})$. |
| 1028 |
Recover a Tree From Preorder Traversal |
Parse the string into nodes and their depths. Use a complex recursive function to find the "left" and "right" parts of the string by counting dashes. |
Heavy string slicing and substring creation at every recursive step. |
Draw the string. Circle "1-2--3--4-5--6--7". Draw lines splitting it into children blocks. Write $O(N^2)$ due to substring search. |
Iterative Stack (Depth Tracking). |
A stack representing the current "active" path from the root. |
Scan string. Count dashes for depth `D`. Parse node value. If `stack.size > D`, pop nodes until stack size equals `D`. Attach new node to `stack.top`. Push new node. |
Write string. Draw a stack (U-shape). "1" (depth 0) goes in. "-2" (depth 1) is child of 1, goes in. "--3" (depth 2) is child of 2, goes in. |
A single pass through the string with stack adjustments. |
Draw a straight line through the string. Write $O(S)$ where S is string length. |
Massive string duplication from repeated slicing. |
A stack with maximum size $O(H)$, the height of the tree. $O(N)$ worst case. |
| 1029 |
Two City Scheduling |
Try all combinations of sending N people to City A and N people to City B (NCr) and find the minimum total cost. |
A massive combination tree (2N choose N). |
Draw 2N slots. Branch into 'City A' or 'City B'. Stop when one city has N people. Write $O(2^2N)$. |
Greedy (Sorting by Opportunity Cost). |
A ranking list based on "How much will I regret NOT sending this person to City A?" |
Assume everyone goes to City A initially. Calculate the "refund" or "penalty" for switching to City B: `costB - costA`. Sort by this difference. Send the N people with the lowest difference to City B. |
Draw a table: [CostA, CostB, Diff (B-A)]. Sort rows by Diff. Circle the first N rows for City B, the rest for City A. Sum costs. |
A sort followed by a single split pass. |
Draw a sort box $O(N \log N)$ followed by a line $O(N)$. Total Time: $O(N \log N)$. |
Large memory to store all possible combinations. |
$O(N)$ space for the sorted array or the difference list. |
| 1030 |
All Cells in Distance Order in a Grid |
Put every cell coordinate (r, c) into a list. Sort the entire list using a custom comparator that calculates Manhattan distance from (rCenter, cCenter). |
A big pile of coordinates tossed into a sorting machine that reorders them one by one. |
Draw a grid. List all (r, c). For each, write |r-r0| + |c-c0|. Draw arrows rearranging them. Write $O(R\cdot C \log(R\cdot C)$). |
BFS (Level-Order Expansion) or Bucket Sort. |
A ripple in a pond. The center cell is the pebble, and waves move outward cell by cell. |
Start BFS at (rCenter, cCenter). Add neighbors to a Queue. Since each step moves exactly 1 distance unit, the Queue naturally stays sorted by distance. |
Draw a grid. Mark center '0'. Mark its 4 neighbors '1'. Mark their neighbors '2'. Follow the numbers to write your answer list. |
An expanding diamond shape covering every cell once. |
Draw a grid with concentric diamond outlines centered on (r0, c0). Write Time: $O(R \cdot C)$. |
$O(R\cdot C)$ space to store the list of all coordinates. |
A Queue structure peaking at $O(R+C)$ size, plus the result list. $O(R\cdot C)$ space. |
| 1031 |
Maximum Sum of Two Non-Overlapping Subarrays |
Use 4 nested loops to pick start/end of the first subarray and start/end of the second. Check if they overlap. If not, sum them. |
Two separate spotlights scanning the array independently, constantly colliding and resetting. |
Draw an array. Draw a bracket for Sub1. Under it, draw a bracket for Sub2 and move it across. Then move Sub1. Write $O(N^4)$. |
Dynamic Programming / Prefix Sums. |
A "high-water mark" tracking the best left-side window while a right-side window scans ahead. |
Fix the right window of length `M`. As you slide it, keep track of the maximum sum of a window of length `L` seen so far to its left. Max sum = MaxL + CurrentM. Reverse L and M and repeat. |
Draw a Prefix Sum array. Slide two windows `[L]` and `[M]`. Mark `MaxL` as you go. Total = `MaxL + current M`. Keep a running `globalMax`. |
Two linear passes across the array. |
Draw an array with two windows sliding from left to right. Write Time: $O(N)$. |
No extra memory besides the array itself. |
$O(N)$ for a Prefix Sum array, or $O(1)$ if you calculate window sums on the fly. |
| 1032 |
Stream of Characters |
For every new character, append it to a string. Then for every word in the dictionary, check if the string `endsWith(word)`. |
A growing scroll of paper. Every time a new letter is added, you search through a massive pile of dictionary books from scratch. |
Write "a", "b", "c". Check if "abc" ends with "apple", "cat", etc. Write $O(\text{Queries} \\text{cdot NumWords} \\text{cdot MaxWordLen})$. |
Trie (Prefix Tree) with Reversed Search. |
A tree where you start at the leaves and climb toward the root. |
Store dictionary words in a Trie *backwards*. Keep a stream of letters. When a new letter arrives, walk into the Trie starting from the most recent letter and go backwards. If you hit a "word-end" node, return true. |
Draw a Trie of reversed words. As letters 'a', 'b', 'c' arrive, look at 'c', then 'b', then 'a' in the tree. If you find a path to a leaf, mark 'Found'. |
A single path walk in a tree per query. |
Draw a Trie. Draw a pointer moving up one branch. Write Time: $O(\text{MaxWordLen})$ per query. |
A massive list of word strings stored multiple times during searches. |
A Trie structure storing each character exactly once per branch. Space: $O(\text{Total characters in dictionary})$. |
| 1033 |
Moving Stones Until Consecutive |
Try all possible move combinations recursively or using BFS to find min/max steps. |
An exploding state space tree of every possible stone jump. |
Draw 3 stones on a line. Draw all places stone A could jump. Repeat for B and C. Write $O(\text{Exponential})$. |
Greedy / Case Analysis. |
A gap-closing logic. You either jump into a hole (min) or slowly crawl toward the center (max). |
Sort positions a, b, c. **Max moves**: Just the total empty spaces between them `(c - a - 2)`. **Min moves**: If already consecutive, 0. If a gap is ≤ 2, 1 jump. Else, 2 jumps. |
Draw a number line with 3 dots. Count the 'empty' slots between them. Write Max = gap1 + gap2. For Min, check if stones are touching or nearly touching. |
A set of constant-time logic gates. |
Draw a flowchart with 3-4 decision boxes. Write Time: $O(1)$. |
Massive state-tracking sets for BFS. |
Just 3 integer variables for the stone positions. $O(1)$ space. |
| 1034 |
Coloring A Border |
Iterate every cell. If it matches the color, check neighbors. If any neighbor is different or it's an edge, add it to a list. Finally, color everything in the list. |
Two separate passes: one to find the border and another to paint it. |
Draw a grid. Circle the target color. For each, look at its 4 neighbors. If one neighbor is different, draw a thick border. Write $O(M\cdot N)$. |
DFS / BFS with Connectivity Logic. |
A "Coastline Finder". You travel only on land (original color) and mark only the spots that touch the ocean (different color) or the world's edge. |
Start DFS at (row, col). Visit neighbors of the same color. If a neighbor is out of bounds or a different color, the current cell is a "border" cell. Save border cells in a list, then paint them at the end. |
Draw a grid. Shade the connected component. Use a different color to trace ONLY the outer edge of that shape and internal boundaries. |
A single graph traversal through one connected component. |
Draw a blob in a grid. Draw a single path tracing its perimeter. Write Time: $O(M \cdot N)$. |
A copy of the entire grid to track changes. |
A "visited" boolean array and a recursion stack. Space: $O(M \cdot N)$. |
| 1035 |
Uncrossed Lines |
Generate all possible combinations of lines between matching numbers and check if any two lines `(i1, j1)` and `(i2, j2)` intersect. |
A tangled mess of "yarn" connecting two parallel boards, where you try to untangle them by hand. |
Draw two rows of numbers. Draw every possible line. Cross out intersections. Write $O(2^\text{min}(M,N)$). |
Dynamic Programming (Longest Common Subsequence). |
A grid-based strategy game where you move from Top-Left to Bottom-Right. |
If `A[i] == B[j]`, you take a diagonal step and add 1. If not, you take the maximum of moving either Right or Down. |
Draw an (M+1) x (N+1) grid. At each cell `(i, j)`, if numbers match, `dp[i][j] = dp[i-1][j-1] + 1`. Else, `max(dp[i-1][j], dp[i][j-1])`. |
A wave of calculation filling a 2D matrix. |
Draw a matrix with a single arrow sweeping from top-left to bottom-right. Write $O(M \cdot N)$ Time. |
Exponential stack space or massive list of line objects. |
A 2D array of integers, or a 1D array if space-optimized. $O(M \cdot N)$ or $O(N)$ space. |
| 1036 |
Escape a Large Maze |
Run a standard BFS or DFS in a 1,000,000 x 1,000,000 grid to find a path from source to target. |
A tiny ant trying to explore an entire continent's worth of grid cells. |
Draw a massive square. Mark 'S' and 'T'. Draw a path that hits a wall and resets. Write $O(10^12)$ - impossible. |
Bounded BFS / Geometric Limitation. |
A "Bubble Test". If you can move far enough away from the starting point without being blocked, you aren't trapped. |
Since there are only ~200 blocked cells, they can only enclose a limited area. Run BFS. If you visit > (B*(B-1))/2 cells, you've "escaped" the enclosure. Do this for both Source and Target. |
Draw a cluster of 5 blocks. Draw a circle around 'S' that expands until it either touches 'T' or grows larger than the enclosure capacity. |
Two small, localized "localized explosions" of search. |
Draw two small circles in a huge empty space. Write $O(B^2)$ where B is number of blocks. |
A Hashset or Boolean grid with 10^12 entries (OOM error). |
A Hashset storing only the visited blocked cells and a few thousand visited coordinates. $O(B^2)$ space. |
| 1037 |
Valid Boomerang |
Calculate the distances between all 3 points. Use the Triangle Inequality: if `a + b == c`, they are collinear (not a boomerang). |
Three measuring tapes forming a flat line. |
Draw 3 dots. Draw lines between them. Measure. Check if they form a flat line. Write $O(1)$ but involves floating point precision issues. |
Math (Cross Product / Slope Comparison). |
A "Leaning Test". If the slope from A to B is the same as the slope from B to C, they are a straight line. |
Instead of division `(y2-y1)/(x2-x1)`, use multiplication to avoid `div by zero`: `(y2 - y1) * (x3 - x2) == (y3 - y2) * (x2 - x1)`. If unequal, it's a boomerang. |
Write the coordinates. Calculate `dy1 * dx2` and `dy2 * dx1`. If the results are different, it's a boomerang. |
A single arithmetic comparison. |
Draw one box with the formula `Δy1*Δx2 != Δy2*Δx1`. Write $O(1)$ Time. |
Standard floating point variables. |
Three integer product variables. $O(1)$ space. |
| 1038 |
Binary Search Tree to Greater Sum Tree |
For every node, traverse the entire tree to find all nodes with values greater than itself and sum them up. |
N separate tree scans; every node triggers its own global search. |
Draw a BST. Pick '5'. Scan every other node and add those > 5. Repeat for every node. Write $O(N^2)$. |
Reverse In-order Traversal (Right -> Root -> Left). |
A "Greedy Accumulator" walking backward through the sorted sequence. |
Keep a global `running_sum`. Visit the furthest Right node (largest), add its value to `running_sum`, update node, then move to Root, then Left. |
Draw a BST. Write a number `0` on the side. Go to the max node, add its value to your side number, update the node with that sum. Follow the path Right-Root-Left. |
A single snaking path through the tree. |
Draw a tree with a single arrow going Right-Root-Left. Write $O(N)$ Time. |
$O(N^2)$ total nodes visited conceptually. |
$O(H)$ recursion stack where H is the height of the tree. |
| 1039 |
Minimum Score Triangulation of Polygon |
Try every possible way to pick 3 vertices and divide the polygon into smaller pieces. Recurse until only triangles remain. |
An exploding decision tree of "cuts" across a polygon. |
Draw a hexagon. Draw one triangle inside. Recurse on the remaining shapes. Write $O(\text{Exponential})$. |
Dynamic Programming (Matrix Chain Multiplication style). |
A "Slicing Table". You solve for small gaps between vertices and combine them to solve the whole polygon. |
`dp[i][j]` is the min score to triangulate vertices from `i` to `j`. To solve `dp[i][j]`, pick an intermediate vertex `k` and calculate `dp[i][k] + score(i,k,j) + dp[k][j]`. |
Draw a polygon. Label vertices 0 to N. Create a 2D table. Fill it diagonally, starting with gaps of size 2, then 3, until you reach the gap size of N. |
Filling a 2D triangle-shaped matrix. |
Draw an N x N matrix. Shade the upper triangle. Write $O(N^3)$ Time. |
Massive recursion depth without memoization. |
An N x N 2D array for memoization. $O(N^2)$ space. |
| 1040 |
Moving Stones Until Consecutive II |
Generate all possible positions for stones and use BFS to find the shortest/longest path to a state where stones are consecutive. |
A massive state-space graph where nodes are stone coordinates and edges are legal moves. |
Draw 3 dots on a line. Draw all possible jumps for the end stones. Note the branching factor. Write $O(\text{Exponential})$. |
Sliding Window + Mathematical Logic. |
A "Fixed-Size Template". You try to find where the existing stones fit best into a window of size N. |
**Max moves**: Total gaps minus the smaller of the two end-gaps. **Min moves**: Slide a window of size N; stones inside are "kept", stones outside need a jump. Handle the n-1 stone edge case separately. |
Draw a number line. Mark stones. Use a bracket of width N. Slide it left to right. Count "empty spots" in the bracket at each step. Record the minimum. |
Two separate linear logic checks. |
Draw a single arrow across the sorted stone array. Write $O(N \log N)$ for sorting, $O(N)$ for sliding window. |
Massive Hashset to track visited stone configurations in BFS. |
$O(1)$ space for variables (if ignoring sorting stack space). $O(N)$ to store stones. |
| 1041 |
Robot Bounded In Circle |
Simulate the robot's movement for thousands of iterations (e.g., 10,000) and check if it ever returns to (0,0). |
A long, meandering path that may or may not eventually loop back. |
Draw (0,0). Trace "GLGLG...". Keep tracing until you run out of paper or see a loop. Write $O(\text{Infinity}/\text{Heuristic})$. |
Vector Math / State Check. |
A "Compass Reset". If the robot isn't facing North after one cycle, it's guaranteed to loop eventually. |
Execute the instructions once. If the robot is back at (0,0) OR it is facing South, East, or West, return true. If it moved away and still faces North, it's gone forever. |
Draw a small coordinate plane. Mark (0,0). Trace one cycle. Draw an arrow for the final position and a small compass for the final direction. |
A single pass through the instruction string. |
Draw the instruction string with one arrow. Write $O(N)$ Time. |
Infinite storage of path coordinates to detect cycles. |
Four integer variables: x, y, dx, dy. $O(1)$ space. |
| 1042 |
Flower Planting With No Adjacent |
Try all 4^N combinations of flower types for the N gardens. For each combination, check all paths to ensure no two connected gardens have the same flower. |
A massive 4-ary tree of choices where most branches are pruned. |
Draw 3 gardens. Branch into [1,2,3,4] for garden 1. Then [1,2,3,4] for garden 2... Check constraints. Write $O(4^N)$. |
Greedy Coloring. |
A "Neighborhood Exclusion" map. You look at your neighbors, see what they picked, and take the first thing left. |
Initialize a result array of 0s. For each garden, check its adjacent neighbors. Mark their flower types as "used" in a boolean array of size 5. Pick the first unused color for the current garden. |
Draw the graph (dots and lines). At each dot, write "Available: 1, 2, 3, 4". Cross out colors used by connected neighbors. Write the first remaining number. |
A single pass through the vertices and their limited edges. |
Draw the adjacency list and one arrow through the gardens. Write $O(V + E)$. Since max 3 edges per garden, it's effectively $O(V)$. |
Exponential recursion stack for backtracking. |
An adjacency list $O(V+E)$ and a small boolean array per vertex. $O(V)$ space. |
| 1043 |
Partition Array for Maximum Sum |
Generate all possible ways to partition the array into subarrays of length up to K. Calculate the sum for each and find the max. |
An exploding decision tree where at each element you choose to end the partition at length 1, 2... or K. |
Draw the array. Branch: [elem1], [elem1, 2], [elem1, 2, 3]. Recurse on what's left. Write $O(K^N)$. |
Dynamic Programming (Linear). |
A "Best-Score History" bar. To find the best score for the current element, look back at the best scores of the last K steps. |
`dp[i]` is the max sum for the first `i` elements. For the current index, look back up to `K` steps. Calculate `(MaxVal in window) * (WindowLength) + dp[i - WindowLength]`. Pick the maximum. |
Draw the array. Below it, draw a `dp` array. For `dp[i]`, draw K small brackets looking backwards. Pick the best one and fill the `dp` cell. |
A nested loop where the inner loop is limited to K. |
Draw an array with an arrow sweeping right, and a smaller "backwards" window arrow. Write $O(N \cdot K)$ Time. |
Massive recursion stack for all partition combinations. |
A 1D array of size N. $O(N)$ space. |
| 1044 |
Longest Duplicate Substring |
Generate all possible substrings of all lengths. Store them in a frequency map. Return the longest one with a count > 1. |
A massive pile of string "shards" (O(N²) substrings) causing memory overflow. |
Write "banana". List: "b", "ba", "ban"... "a", "an", "ana". Sort and count. Write $O(N^3)$ due to string comparisons. |
Binary Search on Length + Rolling Hash (Rabin-Karp). |
A "Fingerprint Scanner". We search for the length of the substring by halving the search space, then use hashes to find duplicates quickly. |
Binary search for the length `L`. For a fixed `L`, slide a window over the string and calculate a rolling hash. Use a Set to store hashes. If a hash collision occurs, check if it's a real duplicate. |
Draw a number line for length 0 to N. Mark `mid`. For length `mid`, draw the sliding window. Write the hash formula `(h * base + char) % mod`. |
A logarithmic search wrapper around a linear scan. |
Draw a Binary Search tree of length. Inside each node, draw a linear arrow. Write $O(N \log N)$ Time. |
$O(N²)$ space to store all possible substrings. |
$O(N)$ space for the Hash Set and rolling hash variables. |
| 1045 |
Customers Who Bought All Products |
(SQL) Use a cross-join or subqueries to check every customer against every product in the product table. |
A Cartesian product grid where you manually check off every customer-product pair. |
Draw a table of Customers and a table of Products. Draw lines from every customer to every product. Highlight customers where all lines exist. |
Group By + Having Count (Distinct). |
A "Filtering Funnel". Aggregate the purchases and compare the size of the customer's shopping bag to the total product list. |
Group the `Customer` table by ID. Count the unique `product_key`s for each. Compare this count to the `SELECT COUNT(*)` from the `Product` table. |
Draw the Customer table. Circle unique product keys per ID. Write the count. Separately, count the Product table. Draw an equal sign between the counts. |
Single pass aggregation with a hash-map check. |
Draw the table with a grouping arrow. Write $O(N)$ where N is number of rows in Customer table. |
Temporary tables for every subquery comparison. |
A small hash map storing counts per Customer ID. $O(C)$ where C is number of customers. |
| 1046 |
Last Stone Weight |
Find the two heaviest stones by scanning the entire list. Smash them. Add the remainder back to the list. Repeat until one or no stones remain. |
A repetitive "search-and-destroy" loop where the list is scanned twice every single iteration. |
Draw the array. Circle the 2 largest. Cross them out. Write the difference. Re-write the whole array. Write $O(N^2)$. |
Max-Heap (Priority Queue). |
A "Weight-Sorted Volcano". The heaviest stones always float to the top automatically. |
Push all weights into a Max-Heap. Extract the top two (largest). If different, push the result back. Repeat until the heap size is 1 or 0. |
Draw a Max-Heap (Binary Tree). Show the two heaviest stones at the top being removed. Show the remainder bubbling down or up. |
Logarithmic extraction repeated N times. |
Draw a heap tree with N removals. Write $O(N \log N)$ Time. |
Constant array resizing and allocation for the modified list. |
A single heap structure storing N elements. $O(N)$ space. |
| 1047 |
Remove All Adjacent Duplicates In String |
Keep scanning the string from left to right. If you find "aa", remove it, and restart the scan from the beginning of the modified string. |
A "Shrinking Snake" that resets its head every time it bites a duplicate pair. |
Write "abbaca". Find "bb", remove it. Rewrite "aaca". Find "aa", remove it. Rewrite "ca". Write $O(N^2)$. |
Stack (LIFO processing). |
A "Vaporizing Bucket". Characters fall in. If the falling character matches the one on top, they both explode and disappear. |
Loop through the string. If the stack is not empty and the current character matches `stack.top()`, pop the stack. Else, push the character. |
Draw a U-shape (stack). Put 'a' in. 'b' enters. Another 'b' enters? Pop 'b'. 'a' enters? Pop 'a'. Final 'c', 'a' stay. |
Single pass linear scan. |
Draw a string with one arrow sweeping left to right. Write $O(N)$ Time. |
Massive string allocations for every deletion phase. |
A single stack (or StringBuilder used as a stack). $O(N)$ space. |
| 1048 |
Longest String Chain |
Generate every possible sequence of strings from the list and check if they form a valid chain (word B is word A + one letter). |
A massive "forest" of all possible word combinations, checking validity at every branch. |
Write words. Draw lines between all pairs. Check if `word2` can be formed by adding 1 char to `word1`. Write $O(2^N)$. |
Dynamic Programming + Hashing (Sorting by Length). |
A "Building Block" approach. Solve for short words first and use those results for longer words. |
Sort words by length. Use a HashMap `dp` where `dp[word]` is the longest chain ending at `word`. For each word, try removing one letter at a time to find its potential "parent" in the map. |
Draw words sorted by length. For "abcd", check "bcd", "acd", "abd", "abc" in your DP map. Chain length = `max(parents) + 1`. |
Linear scan with a small inner loop (word length). |
Draw a sorting box $O(N \log N)$ followed by an $O(N \cdot L^2)$ loop. Write Time: $O(N \log N + N \cdot L^2)$. |
$O(2^N)$ memory for tracking all possible path combinations. |
A HashMap storing N entries. $O(N \cdot L)$ space. |
| 1049 |
Last Stone Weight II |
Try every possible combination of stone smashing (brute force recursion) to find the minimum possible final weight. |
An exponential decision tree of "this stone minus that stone". |
Draw 3 stones. Branch: (A-B), (B-C), (A-C). For each result, smash with the remaining stone. Write $O(2^N)$. |
Dynamic Programming (0/1 Knapsack variation). |
A "Tug-of-War" Balancing. We want to divide the stones into two piles with the most similar total weights. |
The problem is equivalent to finding the maximum weight we can put in a bag of capacity `TotalSum / 2`. Min Weight = `TotalSum - 2 * (Max sum possible in bag)`. |
Draw a 1D DP array of size `Sum/2`. For each stone, update the array from right to left (Knapsack style). |
Nested loop over stones and half the sum. |
Draw a matrix (or 1D array) with a double-arrow loop. Write Time: $O(N \\text{cdot Sum})$. |
Deep recursion stack for all combinations. |
A boolean array of size `Sum/2`. $O(\text{Sum})$ space. |
| 1050 |
Actors and Directors Who Cooperated At Least Three Times |
(SQL) Self-join the table on actor_id and director_id multiple times to find rows where they appear together thrice. |
A massive Cartesian product where you look for triplets of the same pair. |
Draw the table. For each row, scan all other rows looking for the same actor-director pair. Count them. Write $O(N^2)$. |
Group By + Having. |
A "Pairing Bin". All matching (Actor, Director) pairs are tossed into the same bucket; we only keep buckets with 3+ items. |
Group the rows by `actor_id` and `director_id`. Use `COUNT(*)` to tally the occurrences in each group. Filter the groups where count >= 3. |
Draw a table with 3 columns: Actor, Director, Count. Every time you see a pair, increment its Count. Circle rows where Count >= 3. |
Single pass hashing/sorting aggregation. |
Draw the table with a grouping bracket. Write $O(N)$ where N is number of rows. |
Temporary tables for every self-join. |
A small internal hash table for group counts. $O(U)$ where U is number of unique pairs. |
| 1051 |
Height Checker |
Generate all possible permutations of the heights and see which one is perfectly non-decreasing. Compare it to the original. |
An N! (factorial) explosion of reordering possibilities. |
Draw [1, 1, 4, 2, 1]. Draw all 120 ways to reorder it. Pick the sorted one. Compare element by element. Write $O(N!)$. |
Sorting Comparison or Counting Sort. |
A "Shadow Array". You create the "perfect" version of the line and see who is standing in the wrong spot. |
Copy the array and sort it. Iterate through both arrays simultaneously. If `original[i] != sorted[i]`, increment the count. |
Draw the Input Array. Directly below it, draw the Sorted Array. Circle the indices where the numbers don't match. Count the circles. |
A sort followed by a single linear scan. |
Draw a sort box $O(N \log N)$ followed by a single arrow $O(N)$. Total Time: $O(N \log N)$. |
$O(N!)$ storage for permutations. |
$O(N)$ space for the sorted copy of the array. |
| 1052 |
Grumpy Bookstore Owner |
For every possible starting minute i of the "secret technique," calculate the total satisfied customers. Pick the i that maximizes the sum. |
A spotlight of size `minutes` sliding across the array, but recalculating the whole array sum from scratch at every step. |
Draw the customers and grumpy arrays. Draw a bracket of size K. Sum everything inside it + all non-grumpy outside. Move bracket. Repeat. Write $O(N^2)$. |
Sliding Window (Fixed Size). |
A "Conversion Window". The window turns "grumpy" 0s into "satisfied" 1s. We move it to find where it captures the most "lost" customers. |
Sum all customers where owner is NOT grumpy. Then, use a sliding window of size `minutes` to find the maximum "extra" customers that can be gained by ignoring grumpiness. Total = Initial + MaxExtra. |
Draw the array. Below it, write the number of "unhappy" customers (where grumpy=1). Slide a window of size K over these numbers and find the max sum. |
Two linear passes (one for base sum, one for window). |
Draw the array with one arrow for the base sum and a sliding box for the window. Write $O(N)$ Time. |
Redundant calculations stored for every window position. |
Three variables: `total_satisfied`, `current_window_extra`, `max_extra`. $O(1)$ space. |
| 1053 |
Previous Permutation With One Swap |
Generate all possible single-swap permutations. Find those smaller than the original, then pick the largest among them. |
An N^2 set of arrays, each being compared against the original and each other. |
Draw [3, 2, 1]. Swap (3,2)->[2,3,1], (3,1)->[1,2,3], (2,1)->[3,1,2]. Pick largest < 3,2,1. Write $O(N^2)$. |
Greedy (Right-to-Left Scan). |
A "Last-Minute Dip" search. We look for the first place the sequence stops increasing from right to left, then find its best smaller partner. |
Find the first index i (from right) where `arr[i] > arr[i+1]`. Then, find the largest `arr[j]` to the right of i such that `arr[j] < arr[i]`. Swap `arr[i]` and `arr[j]`. |
Draw the array. Move an arrow from right to left. Stop when numbers stop decreasing. Then look right for the biggest number smaller than the current. Swap them. |
Two partial linear scans. |
Draw the array with two arrows moving right-to-left. Write $O(N)$ Time. |
$O(N^2)$ space for storing all swapped array variations. |
In-place modification of the original array. $O(1)$ extra space. |
| 1054 |
Distant Barcodes |
Generate all permutations and check each one to see if adjacent barcodes are identical. Return the first valid one. |
An N! explosion of sequences, most failing the "no-neighbor" rule. |
Draw [1, 1, 1, 2, 2, 2]. List permutations until you find [1, 2, 1, 2, 1, 2]. Write $O(N!)$. |
Greedy + Frequency Fill (Even/Odd Interleaving). |
A "Zebra Stripe" filling pattern. We place the most frequent items in the "even" slots first to ensure they are separated. |
Count frequencies. Sort by frequency descending. Fill all even indices (0, 2, 4...) with the sorted barcodes. When even indices are full, fill all odd indices (1, 3, 5...). |
Draw N empty boxes. Sort numbers by count. Fill boxes 0, 2, 4... then 1, 3, 5... with the sorted numbers. |
Frequency count (O(N)) + Sorting (O(1) since barcode range is fixed) + Filling (O(N)). |
Draw a frequency map and an array with a "jumping" pointer (i += 2). Write $O(N)$ Time. |
$O(N!)$ space for permutations. |
A frequency map and the result array. $O(N)$ space. |
| 1055 |
Shortest Way to Form String |
Generate all possible subsequences of `source` and try to concatenate them in all possible ways to match `target`. |
A massive branching tree where each node is a subsequence choice. |
Write target "abcabc". List all source subsequences. Try matching "a", "ab", "abc"... then recurse. Write $O(2^S \cdot T)$. |
Greedy (Two Pointers / Multi-Pass). |
A "Looping Scanner". You scan the source repeatedly; each pass consumes as many characters of the target as possible. |
Point at target[0]. Scan source from left to right. If characters match, move target pointer. If you hit end of source, increment "count" and reset source pointer. |
Draw target on top, source below. Draw an arrow moving through target. Each time source finishes, draw a vertical line in target to show one "pass". |
A target-driven linear scan with repeated source passes. |
Draw target length T with segments of source length S. Write Time: $O(S \cdot T)$. |
Exponential storage for all source subsequences. |
Two integer pointers (i, j) and a counter. $O(1)$ space. |
| 1056 |
Confusing Number |
Convert number to string. Check if it contains invalid digits (2, 3, 4, 5, 7). If valid, generate all rotations and compare to original. |
String manipulation and character-by-character flipping. |
Write "89". Flip '8' to '8', '9' to '6'. Reverse order to get "68". Compare 68 != 89. Write $O(L)$ where L is digits. |
Math (Digit Extraction and Remainder). |
A "Rotating Dial". You extract digits from the end, map them to their rotated counterparts, and build a new number. |
Use `n % 10` to get digits. If digit is in {2,3,4,5,7}, return false. Else, use a map {0:0, 1:1, 6:9, 8:8, 9:6} to build `rotated = rotated * 10 + map[digit]`. |
Write original N. Below it, write the rotated digits as you extract them. If you see a 2, 3, 4, 5, or 7, draw a big X. Check if `rotated != original`. |
Single pass through the digits. |
Draw a number being dismantled and reassembled bit by bit. Write Time: $O(\log N)$. |
$O(L)$ space for string conversion. |
$O(1)$ space using integer math and a fixed-size mapping. |
| 1057 |
Campus Bikes |
Calculate all possible worker-bike pairings. Use backtracking to try every combination of assignments and find the one that meets the "closest" rule. |
A factorial permutation tree of worker-bike assignments. |
3 workers, 3 bikes. List all 3! = 6 assignment sets. Check distances for each. Write $O(N!)$. |
Bucket Sort / Greedy with Priority. |
A "Distance Sorter". We group all possible pairs by their distance and process the smallest distances first. |
Calculate distance for every pair (worker, bike). Put pairs into "buckets" indexed by distance. Iterate buckets 0 to 2000. Assign if worker and bike are both free. |
Draw a table with distance as rows. In each row, list (w, b) pairs. Scan from top row down. Mark 'w' and 'b' as used once assigned. |
Pair calculation (N*M) + Bucket iteration (Dist). |
Draw an N x M matrix mapped into a vertical bucket list. Write Time: $O(N \cdot M)$. |
$O(N!)$ space for permutations. |
$O(N \cdot M)$ space to store all pairs in buckets. |
| 1058 |
Minimize Rounding Error to Meet Target |
For each number, try both floor and ceil. Check all 2^N combinations of rounding to see which sum equals target. Return min error. |
A binary tree of "floor vs ceil" decisions at every index. |
[0.7, 2.3]. Try (0+2), (0+3), (1+2), (1+3). Check sums. Pick min error for target. Write $O(2^N)$. |
Greedy (Sorting by Fractional Part). |
A "Rounding Budget". Everyone floors first, then we "spend" our remaining target points on numbers that have the lowest cost to ceil. |
Floor all numbers and find the `lowerSum`. The number of ceils needed is `Target - lowerSum`. Sort numbers by their fractional parts `(val - floor(val))` in descending order. Ceil the top `k` numbers. |
Draw a table: [Original, Floor, Ceil, Diff]. Sort by Diff. Fill 'Floor' for everyone. Change 'Floor' to 'Ceil' for the top `k` rows. Sum the differences. |
A sort followed by a single pass. |
Draw a sort box $O(N \log N)$ and a linear sum $O(N)$. Write Time: $O(N \log N)$. |
Deep recursion stack for all rounding combinations. |
$O(N)$ space to store the fractional differences for sorting. |
| 1059 |
All Paths from Source Lead to Destination |
Generate every possible path starting from source using DFS. If any path ends at a node that isn't `destination` or contains a cycle, return false. |
Infinite exploration if a cycle exists, or checking an exponential number of paths. |
Draw a graph with a loop. Trace path. If you hit the loop, you never stop. Write $O(\text{Exponential}/\text{Infinite})$. |
DFS with State Marking (3-Coloring). |
A "Dead-End Check". Every path must eventually hit the specific destination node and nowhere else. |
Use DFS with states: 0=Unvisited, 1=Visiting, 2=Processed. If you hit a node in state 1, there's a cycle. If a node has no out-edges, it MUST be the destination. |
Draw the graph. Start DFS. Color node gray while searching. If you hit a gray node, draw a cycle symbol. If you hit a node with no arrows out, check if it's the target. |
Single pass graph traversal. |
Draw the graph with a single DFS path. Write Time: $O(V + E)$. |
Stack overflow or infinite loops. |
$O(V)$ for the state array and $O(H)$ for the recursion stack. |
| 1060 |
Missing Element in Sorted Array |
Start from the first element and iterate one by one, checking the gap between neighbors. Count how many numbers are missing until you hit K. |
A slow-moving walker checking every single floor tile for cracks. |
Draw [4, 7, 9, 10]. Count gaps: 4-7 has 2 missing (5,6), 7-9 has 1 missing (8). Total 3. If K=3, answer is 8. Write $O(N)$. |
Binary Search (Range-based). |
A "Gap Measurement". We check how many numbers are missing in the left half vs. the right half and jump accordingly. |
Calculate `missing(i) = nums[i] - nums[0] - i`. If `missing(mid) < k`, the answer is in the right half. Adjust K and move. |
Draw the array. Write `missing` counts below each index. Use Binary Search pointers L and R to narrow down the segment where the Kth missing number lies. |
Logarithmic search over the array indices. |
Draw a Binary Search tree narrowing down to a single index. Write Time: $O(\log N)$. |
No extra memory needed for the linear scan. |
Strictly $O(1)$ space with 3 integer pointers (L, R, Mid). |
| 1061 |
Lexicographically Smallest Equivalent String |
For every character equivalence, build a full adjacency list graph. For each character in the target string, run BFS/DFS to find the smallest char in its component. |
A sprawling social network where you visit every friend of a friend to find the one with the "smallest name." |
"parker"=="morris". Draw nodes P-M, A-O, R-R, etc. For 'p', follow all lines to find the smallest reachable letter. Write $O(T \cdot (S+E)$). |
Union-Find (DSU) with Path Compression. |
A "Family Tree" where the "Head" of the family is always the lexicographically smallest character. |
For each pair (s1[i], s2[i]), union their sets. When unioning, always make the smaller character the parent. To translate the target string, just call `find(char)`. |
Draw 26 dots. Draw lines between equivalent letters. For each group, circle the smallest letter and point all other letters in that group to it. |
Near-constant time set operations. |
Draw 26 nodes with flat parent pointers. Write Time: $O((S + T)$α(26)), where α is Inverse Ackermann (basically $O(1)$). |
Storing full adjacency lists for 26 characters. |
A single integer array of size 26 (parent pointers). $O(1)$ space. |
| 1062 |
Longest Repeating Substring |
Generate every possible substring and count their frequencies using a HashMap. Return the length of the longest one with frequency > 1. |
A massive "shredder" turning the string into $O(N²)$ pieces and piling them into buckets. |
"aaaaa". Substrings: "a", "aa", "aaa"... Count occurrences. Write $O(N^3)$ due to string extraction/hashing. |
Binary Search on Length + Rolling Hash (Rabin-Karp). |
A "Length Filter". We guess a length, scan for duplicates using hashes, and adjust our guess based on the result. |
Binary search the length `L` from 1 to N. For length `L`, use a rolling hash to check for duplicates in $O(N)$. If duplicate found, try a longer `L`. |
Draw the string. Pick a middle length. Use a sliding window to generate hashes. Write hashes into a Set. If a duplicate exists, mark "True". |
Logarithmic search over a linear scan. |
Draw a Binary Search tree of length values. Write Time: $O(N \log N)$. |
$O(N³)$ space for all substring objects. |
$O(N)$ space for storing hashes in a Set. |
| 1063 |
Number of Valid Subarrays |
Check every possible subarray [i, j]. If for all elements in the subarray, the first element is the smallest, increment the count. |
A nested loop scanning every possible sub-segment of the array. |
Draw [1, 4, 2, 5]. Subarrays: [1], [1,4], [1,4,2]... [4], [4,2] (invalid). Write $O(N^2)$. |
Monotonic Stack. |
A "Wall Finder". For each number, we find the first number to its right that is smaller (the "wall"). Every element before that wall forms a valid subarray. |
Iterate through the array. Keep a stack of indices in increasing order. When you see a number smaller than `stack.top()`, it means the current number is a "wall" for the numbers in the stack. Calculate `current_idx - stack.pop()` and add to total. |
Draw the array. Put indices on a stack. When a "smaller" number appears, pop the stack and draw an arrow from the popped index to the current. Add the distance. |
Single pass through the array. |
Draw an array with one arrow and a vertical stack growing/shrinking. Write Time: $O(N)$. |
No extra memory besides loops. |
A stack storing up to N indices. $O(N)$ space. |
| 1064 |
Fixed Point |
Iterate through the array from index 0 to N-1. Check if `arr[i] == i`. Return the first such index found. |
A linear scan of the array. |
Draw [-10, -5, 2, 3, 7]. Check index 0: -10 != 0. Index 2: 2 == 2. Answer is 2. Write $O(N)$. |
Binary Search. |
A "Balance Check". Since the array is sorted, we can determine which side a fixed point might be on by comparing `arr[mid]` to `mid`. |
Standard Binary Search. If `arr[mid] >= mid`, a fixed point could be at `mid` or to its left, so `R = mid`. Otherwise, `L = mid + 1`. |
Draw the array. Compare `mid` to its index. If `arr[mid] < mid`, the "fix" must be to the right. Use arrows to narrow the search. |
Logarithmic search. |
Draw a standard Binary Search tree. Write Time: $O(\log N)$. |
$O(1)$ space with a simple loop. |
$O(1)$ space with Binary Search pointers. |
| 1065 |
Index Pairs of a String |
For every word in the dictionary, search the entire text string for its occurrences using `indexOf` or a nested loop. |
Multiple search parties scanning the same terrain repeatedly. |
Text: "ababa", Words: ["aba", "ba"]. Search "aba" -> [0,2], [2,4]. Search "ba" -> [1,2], [3,4]. Write $O(\text{Words} \\text{cdot TextLen} \\text{cdot WordLen})$. |
Trie (Prefix Tree). |
A "Dictionary Overlay". We slide through the text and see which paths in our tree we can follow at each starting character. |
Build a Trie of all words. For each index i in the text, start a pointer at the Trie root and see how deep you can go starting from text[i]. Every "end of word" node reached is a valid pair. |
Draw the Trie. Under the text "ababa", draw arrows starting at 'a', 'b', etc., tracing paths in the Trie. Mark indices whenever a Trie "leaf" or "word-end" is hit. |
A single pass through the text with localized Trie depth walks. |
Draw the text string with small depth-limited trees branching off each character. Write $O(\text{TextLen} \\text{cdot MaxWordLen})$. |
$O(\text{Words} \\text{cdot MaxWordLen})$ for storing words in a list/set. |
$O(\text{TotalChars in Dictionary})$ for the Trie structure. |
| 1066 |
Campus Bikes II |
Generate every possible assignment of bikes to workers (Permutations) and calculate the Manhattan distance sum for each. Return the minimum. |
A factorial tree of all worker-bike pairings. |
W1: B1, B2. W2: B1, B2. List: (W1B1, W2B2), (W1B2, W2B1). Write $O(\text{Bikes}! / (\text{Bikes}-\text{Workers})$!). |
DP with Bitmasking. |
A "Reservation Ledger". A bitmask represents which bikes are already taken, and we solve for the best way to assign the remaining workers. |
`dp(worker_idx, bike_mask)` returns the min distance for remaining workers. For each bike j not in the mask, calculate `dist(worker, bike_j) + dp(worker+1, mask | (1 << j))`. Use memoization. |
Draw a table where rows are workers and columns are bitmasks (e.g., 0110). Fill the table by trying each available bike for the current worker. |
A state-space traversal where each state is (worker, mask). |
Draw a grid of size Workers x 2^Bikes. Write Time: $O(\text{Workers} \cdot 2^\text{Bikes})$. |
Large recursion depth and factorial storage. |
A memoization table or array of size 2^Bikes. $O(2^\text{Bikes})$ space. |
| 1067 |
Digit Count in Range |
Iterate through every number from `low` to `high`. For each number, convert it to a string and count the occurrences of digit `d`. |
A manual census, checking every single page of a giant book for a specific letter. |
Range 10-20, d=1. Check 10(1), 11(2), 12(1)... Total = 11. Write $O(N \log N)$ where N is high-low. |
Math / Digit DP. |
A "Slot-by-Slot" Calculation. We calculate how many times the digit `d` appears in the "ones" place, "tens" place, etc., across the whole range. |
Calculate `countDigit(N, d)` which returns the count of digit `d` from 1 to N. The answer is `countDigit(high, d) - countDigit(low-1, d)`. Use the math formula for each power of 10. |
Write the number N. For each position i (units, tens...), look at the prefix and suffix around it to determine how many times `d` rotates into that position. |
Constant time relative to the value of N (logarithmic to digits). |
Draw a number being analyzed digit-by-digit. Write Time: $O(\log N)$. |
$O(1)$ space for counts, but huge time consumption. |
$O(1)$ space for storing temporary math variables. |
| 1068 |
Product Sales Analysis I |
(SQL) For every row in the `Sales` table, perform a subquery to look up the `product_name` and `year` in the `Product` table. |
A repetitive lookup process for every sale record. |
Sales Table: [pid=1, year=2019]. Look up pid=1 in Product Table -> "Nokia". Write $O(S \cdot P)$. |
Inner Join. |
A "Table Stitch". We align the two tables by their shared `product_id` column to create a wider, combined view. |
`SELECT p.product_name, s.year, s.price FROM Sales s JOIN Product p ON s.product_id = p.product_id`. |
Draw the Sales table and the Product table side-by-side. Draw lines connecting matching `product_id`s. Show the columns from both merging into a new result row. |
Single pass join (usually using a hash join or merge join internally). |
Draw two tables merging into one. Write Time: $O(\text{Sales} + \text{Product})$. |
Multiple temporary sub-results stored in memory. |
A hash table created by the DB engine for the join. $O(\text{Product})$ space. |
| 1069 |
Product Sales Analysis II |
(SQL) Select all unique product IDs. For each ID, scan the entire Sales table to sum up the quantities. |
A "Filter and Sum" loop repeated for every unique product. |
Product 1: Find all Sales with pid=1, sum quantities. Product 2: Repeat. Write $O(\text{UniqueProducts} \\text{cdot Sales})$. |
Group By. |
A "Sorting Bin". Toss every sale into a bin based on its `product_id`, then count the total in each bin. |
`SELECT product_id, SUM(quantity) AS total_quantity FROM Sales GROUP BY product_id`. |
Draw the Sales table. Circle all rows with `product_id` 1. Sum their quantities. Do the same for `product_id` 2. |
Single pass aggregation. |
Draw a table being collapsed into a smaller summary table. Write Time: $O(\text{Sales})$. |
$O(\text{Sales})$ space for repeated sub-selections. |
An internal hash map for grouping. $O(\text{UniqueProducts})$ space. |
| 1070 |
Product Sales Analysis III |
(SQL) For every product, find the minimum year in the Sales table, then join that back to the original table to get the full record. |
A nested lookup: for every product row, a secondary search for its "earliest self." |
Sales: [P1, 2010], [P1, 2011]. Search P1's min year (2010). Select all rows matching (P1, 2010). Write $O(\text{Sales} \\text{cdot Products})$. |
Subquery with In-Clause or Window Functions. |
A "First-Strike Filter". We find the chronological start point for each product and discard everything else in one go. |
`SELECT ... FROM Sales WHERE (product_id, year) IN (SELECT product_id, MIN(year) FROM Sales GROUP BY product_id)`. |
Draw the Sales table. Group by PID. For each group, underline the row with the smallest Year. Draw a new table containing only underlined rows. |
Two-pass scan (one to group, one to filter). |
Draw an aggregation box leading into a filter gate. Write Time: $O(\text{Sales})$. |
Redundant scans for every row in the Sales table. |
An internal hash table for the grouped minimums. $O(\text{UniqueProducts})$ space. |
| 1071 |
Greatest Common Divisor of Strings |
Generate every possible substring of the shorter string. For each, check if it can divide (perfectly repeat to form) both strings. |
A "Tile Tester". Trying every possible tile size to see if it covers the whole floor. |
S1="ABABAB", S2="ABAB". Try "A", "AB", "ABAB". "ABAB" doesn't fit S1. "AB" fits both. Write $O(\text{min}(L1, L2)$^2). |
Math (Euclidean GCD Logic). |
A "String Congruence" check. If two strings have a GCD, their concatenation must be commutative. |
Check if `str1 + str2 == str2 + str1`. If false, return "". If true, find the GCD of their lengths L = gcd(len1, len2). The answer is `str1.substring(0, L)`. |
Write S1+S2. Below it, write S2+S1. If they look identical, calculate the GCD of their lengths on the side. Slice the first string at that GCD length. |
GCD calculation and string concatenation. |
Draw two strings joining, then a single math block `gcd(a, b)`. Write Time: $O(L1 + L2)$. |
Many temporary substring objects allocated during checks. |
One concatenated string for the check. $O(L1 + L2)$ space. |
| 1072 |
Flip Columns For Maximum Number of Equal Rows |
Try every possible subset of columns to flip (2^C combinations). For each subset, count how many rows become all 0s or all 1s. |
A massive explosion of 2^100 possibilities. Impossible to finish. |
Draw a 3x3 grid. Try flipping col 1. Then col 2. Then col 1&2. For each, check if rows are uniform. Write $O(2^C \cdot R \cdot C)$. |
Pattern Canonicalization / Hashing. |
A "Mirror Image" sorter. Two rows can become equal if they are identical OR perfect opposites. |
For each row, if it starts with 1, flip all its bits (canonical form). Use a HashMap to count occurrences of these canonical patterns. The answer is the highest frequency. |
Draw the grid. For each row, if it starts with '1', write its flipped version next to it. If it starts with '0', write it as is. Group the identical strings and count. |
Single pass through the matrix. |
Draw the matrix being converted into a frequency map of strings. Write Time: $O(R \cdot C)$. |
2^C search space storage. |
A HashMap storing R strings of length C. $O(R \cdot C)$ space. |
| 1073 |
Adding Two Negabinary Numbers |
Convert both arrays to base-10 integers, add them, and convert the result back to base -2. |
Arithmetic overflow! Base-10 cannot handle the large numbers represented by long negabinary arrays. |
[1,1] -> -2+1 = -1. [1] -> 1. Sum = 0. Convert 0 to negabinary -> [0]. Write $O(N)$ but fails on large N. |
Bitwise Simulation (Carry Manipulation). |
A "Custom Carry" logic. In base -2, a carry of `1+1` becomes `-1` because 2 = (-2) x (-1). |
Add digits from right to left with a `carry`. `sum = arr1[i] + arr2[j] + carry`. Digit = `sum & 1`. New carry = `-(sum >> 1)`. |
Write the two arrays one above the other. Add column by column. Write the result and the "negative carry" above the next column. Handle the -1 carry case carefully. |
Single pass from right to left. |
Draw two parallel arrays with a carry arrow moving left. Write Time: $O(\text{max}(N1, N2)$). |
Massive BigInteger allocations to avoid overflow. |
A single result array. $O(N)$ space. |
| 1074 |
Number of Submatrices That Sum to Target |
Check every possible submatrix (defined by top-left and bottom-right corners). Calculate the sum of each and compare to target. |
Four nested loops to define boundaries (N^4) plus two loops to sum (N^6). Even with 2D prefix sums, it is $O(N^4)$. |
Draw a grid. Pick any box inside it. Sum the numbers. Is it Target? Repeat for all boxes. Write $O(N^4)$. |
2D-to-1D Reduction + Subarray Sum Logic. |
A "Scanning Bar". We fix the top and bottom rows, compress the values between them into a 1D array, and solve the "Subarray Sum Equals K" problem. |
For every pair of rows (i, j), calculate the 1D prefix sums of the columns. Use a HashMap to find how many horizontal segments in this "compressed row" sum to target in $O(\text{Cols})$. |
Draw the grid. Pick row 1 and 2. Sum them vertically into a single row. On that single row, run the "Subarray Sum" algorithm using a HashMap. Repeat for all row pairs. |
Three nested loops (Row1, Row2, Cols). |
Draw a 2D grid being squashed into a 1D line, followed by a HashMap lookup. Write Time: $O(\text{Rows}^2 \\text{cdot Cols})$. |
$O(N^4)$ or $O(N^2)$ space for storing all possible submatrix sums. |
A 2D prefix sum array or just the current compressed row. $O(\text{Rows} \\text{cdot Cols})$ space. |
| 1075 |
Project Employees I |
(SQL) For every project row, run a subquery to look up the experience years for all its employees and calculate the average. |
A "Lookup and Scan" repeated for every project. |
Project 1: Find emp A, B, C. Scan Employee table for years. Sum and divide. Write $O(\text{Projects} \\text{cdot Employees})$. |
Join + Group By + AVG. |
A "Table Merge and Collapse". Align the project and employee data, then squish each project group into a single average value. |
`SELECT p.project_id, ROUND(AVG(e.experience_years), 2) FROM Project p JOIN Employee e ON p.employee_id = e.employee_id GROUP BY p.project_id`. |
Draw the Project table and Employee table. Connect IDs with lines. Group the resulting rows by project_id and write the calculated average next to each group. |
Single pass join and aggregation. |
Draw two tables merging, then a single aggregation box. Write Time: $O(\text{Projects} + \text{Employees})$. |
Many temporary sub-queries residing in memory. |
An internal hash map for grouping and summing. $O(\text{UniqueProjects})$ space. |
| 1076 |
Project Employees II |
(SQL) Group by project, count employees, sort descending, and take the top. Use another query to check if others have the same count. |
Multiple independent sorting and filtering passes. |
P1: 3, P2: 3, P3: 2. Sort: 3, 3, 2. Max is 3. Find all projects with 3. Write $O(\text{Projects} \\text{log Projects})$. |
Group By + Having (Subquery Max). |
A "High-Water Mark". Count everyone, find the highest count, and keep everyone who reached that peak. |
`SELECT project_id FROM Project GROUP BY project_id HAVING COUNT(employee_id) = (SELECT COUNT(employee_id) FROM Project GROUP BY project_id ORDER BY COUNT(employee_id) DESC LIMIT 1)`. |
Draw a bar chart of employee counts per project. Draw a horizontal line at the level of the tallest bar. List all bars touching the line. |
One pass for counts, one pass for the max, one pass for filter. |
Draw the table collapsing into counts, then a filter gate. Write Time: $O(\text{Projects})$. |
Multiple temporary result sets for sorting. |
A small internal hash table for counts. $O(\text{UniqueProjects})$ space. |
| 1077 |
Project Employees III |
(SQL) For every project, find all employees, then find the one with max experience within that subset. |
Nested correlated subqueries for every row in the Project table. |
Row 1: Project 1, Emp 1. Find max experience in Project 1. Compare Emp 1 to max. Write $O(\text{Projects} \\text{cdot Employees})$. |
Window Function (RANK/DENSE_RANK) or Join with Max-Group. |
A "League Leaderboard". Within each project "league," we rank employees by experience and pick only those in rank #1. |
`SELECT project_id, employee_id FROM (SELECT p.project_id, p.employee_id, RANK() OVER(PARTITION BY p.project_id ORDER BY e.experience_years DESC) as rnk FROM Project p JOIN Employee e ON ...) WHERE rnk = 1`. |
Draw the joined table. Group by project_id. Within each group, highlight the employee(s) with the highest years. Output those rows. |
Single pass sort-merge join and window calculation. |
Draw the table partitioned into colored blocks (projects), with a star next to the top value in each. Write Time: $O(N \log N)$. |
Exponentially growing complexity with nested subqueries. |
$O(N)$ space for the intermediate result set of the window function. |
| 1078 |
Occurrences After Bigram |
Use a sliding window of size 3. For every window, check if word 1 and word 2 match the bigram. If yes, take word 3. |
A three-word "frame" sliding across the text. |
"alice is a good girl". Bigram: "a good". Window 1: [alice, is, a]. Window 2: [is, a, good]. Window 3: [a, good, girl] -> Match! Output "girl". Write $O(N)$. |
Linear Scan / String Splitting. |
A "Pattern Sniffer". We scan the list of words and every time we see the first two pieces of the puzzle, we grab the piece that comes next. |
Split the text into an array of words. Loop from index 0 to length - 3. If `words[i] == first` and `words[i+1] == second`, add `words[i+2]` to the result list. |
Write the words in a horizontal line. Draw a rectangle covering the first two words. If they match the targets, circle the third word. Slide the rectangle one word at a time. |
Single pass through the word array. |
Draw a word array with a single arrow and a "check" bracket. Write Time: $O(N)$. |
Multiple substring allocations during window sliding. |
An array of words. $O(N)$ space where N is text length. |
| 1079 |
Letter Tile Possibilities |
Generate every possible permutation of every possible length. Store them in a Set to handle duplicates and return the size of the set. |
A massive, branching "Tree of Babble" where most branches are redundant. |
Tiles: "AAB". Length 1: A, B. Length 2: AA, AB, BA. Length 3: AAB, ABA, BAA. Write $O(P!)$ where P is number of tiles. |
Backtracking + Frequency Array. |
A "Tile Inventory". We don't care about the tiles' original order; we just care about how many 'A's and 'B's we have in our bag at any moment. |
Count character frequencies. Use DFS. In each step, pick an available character from the frequency array, decrement its count, increment the total count, and recurse. Increment the count back (backtrack) for the next branch. |
Draw the frequency map {A:2, B:1}. Start DFS. Pick A -> {A:1, B:1}. From there, pick A -> {A:0, B:1} or pick B -> {A:1, B:0}. Count every valid state reached. |
Exploration of unique character combinations. |
Draw a decision tree where each node is a frequency state. Write Time: $O(\text{Exponential but bounded by unique permutations})$. |
$O(P!)$ space to store all possible strings in a Set. |
$O(K)$ space for the frequency array (K=26) and $O(P)$ for the recursion stack. |
| 1080 |
Insufficient Nodes in Root to Leaf Paths |
Generate every possible path from root to leaf. For each path, check if the sum is < limit. If all paths passing through a node are "insufficient," delete the node. |
A tree where every node is covered in countless redundant path-strings. |
Draw a tree. List every path sum. If a node belongs only to sums < limit, erase it. Write $O(N \cdot H)$ or $O(N^2)$. |
Post-order Traversal (Bottom-Up Pruning). |
A "Path Validator". Nodes only stay if they can report at least one successful leaf-connection back to their parent. |
DFS down the tree. Subtract node value from the limit as you go. At leaf, if `limit > 0`, it's insufficient (return null). Going up, if both children of a node are null, this node becomes null too. |
Draw the tree. Write the current 'remaining limit' next to nodes. Start from bottom: if a leaf sum is bad, cross it out. If a parent has no children left, cross it out too. |
Single pass through the tree. |
Draw a tree with a single DFS "snake" path. Write Time: $O(N)$. |
Huge list of path-to-sum mappings stored in memory. |
$O(H)$ recursion stack space. |
| 1081 |
Smallest Subsequence of Distinct Characters |
Generate every possible subsequence that contains all distinct characters exactly once. Sort them lexicographically and pick the smallest. |
An exponential explosion of string permutations. |
"cbacdcbc". Distinct: a, b, c, d. Generate "abcd", "adbc"... compare. Write $O(2^N)$. |
Monotonic Stack + Greedy (Frequency Map). |
A "Strict Concierge". Characters enter a stack only if they are smaller than the top and the top character appears again later in the string. |
Track counts of each char. Use a stack and a `visited` set. If `char < stack.top` AND `count[stack.top] > 0`, pop the stack. Push char. Decrement counts. |
Draw a U-shaped stack. List the string. As you process a char, check if it's already in the stack. If not, pop larger tops that appear later. Put char in. |
Single pass through the string. |
Draw the string with one arrow and a stack filling/emptying. Write Time: $O(N)$. |
$O(2^N)$ space for all subsequences. |
$O(1)$ space (stack and map size capped at 26). |
| 1082 |
Sales Analysis I |
(SQL) Group by seller, sum prices, sort descending, and take the top. Use another query to find all sellers matching that max sum. |
Multiple independent sorting and aggregation passes. |
Seller 1: 100, Seller 2: 100, Seller 3: 50. Max is 100. Find all with 100. Write $O(N \log N)$. |
Group By + Having (Subquery Max). |
A "Leaderboard Sweep". Sum everyone's sales and keep only those who tied for first place. |
`SELECT seller_id FROM Sales GROUP BY seller_id HAVING SUM(price) = (SELECT SUM(price) FROM Sales GROUP BY seller_id ORDER BY SUM(price) DESC LIMIT 1)`. |
Draw the Sales table. Group by Seller. Write total next to each. Find the highest , then list all Sellers with that . |
Two-pass aggregation. |
Draw a table collapsing into sums, then a filter gate. Write Time: $O(N)$. |
Redundant temporary result sets. |
An internal hash map for grouping. $O(\text{UniqueSellers})$ space. |
| 1083 |
Sales Analysis II |
(SQL) Select all buyers of S8. Select all buyers of iPhone. Subtract the iPhone set from the S8 set. |
Set-based subtraction operations. |
S8 Buyers: {A, B, C}. iPhone Buyers: {B, D}. Result: {A, C}. Write $O(N)$. |
Group By + Having (Conditional Sums). |
A "Checklist Filter". Each buyer has a bucket; we only keep buckets that contain an S8 but do NOT contain an iPhone. |
`SELECT buyer_id FROM Sales JOIN Product USING(product_id) GROUP BY buyer_id HAVING SUM(product_name = 'S8') > 0 AND SUM(product_name = 'iPhone') = 0`. |
Draw the table. Group by Buyer. For each buyer, check: "Do they have an S8?" AND "Do they have 0 iPhones?". |
Single pass join and aggregation. |
Draw two tables merging, then a grouping filter. Write Time: $O(\text{Sales} + \text{Products})$. |
Multiple subqueries stored in temp memory. |
A hash map for grouping. $O(\text{UniqueBuyers})$ space. |
| 1084 |
Sales Analysis III |
(SQL) For every product, find all its sales dates. If every date is within Q1 2019, include the product. |
Correlated subqueries checking dates for every product row. |
Product 1: Sale 2019-01, Sale 2019-02. OK. Product 2: Sale 2019-01, Sale 2019-05. Fail. Write $O(\text{Products} \\text{cdot Sales})$. |
Group By + Having (Min/Max Dates). |
A "Date Boundary Check". For each product, we only care about its earliest and latest sale. If both fall in the window, all sales fall in the window. |
`SELECT product_id, product_name FROM Sales JOIN Product USING(product_id) GROUP BY product_id HAVING MIN(sale_date) >= '2019-01-01' AND MAX(sale_date) <= '2019-03-31'`. |
Draw the table. Group by Product. For each group, find the earliest and latest date. If both are in Q1, circle the product name. |
Single pass join and group. |
Draw a table collapsing into min/max dates. Write Time: $O(\text{Sales})$. |
Expensive subqueries for every row. |
A hash map for grouping. $O(\text{UniqueProducts})$ space. |
| 1085 |
Sum of Digits in the Minimum Number |
Sort the entire array to find the minimum element. Convert that number to a string and iterate through its characters to sum the digits. |
A heavy sorting funnel followed by a string-conversion factory. |
Draw [34, 23, 12, 45]. Sort it. Pick 12. Convert to "1", "2". Sum = 3. Check 3 % 2. Write $O(N \log N)$. |
Linear Scan + Digit Math. |
A "Lowest-Bar Search". Scan once for the min value, then use math to peel off its digits. |
Initialize `minVal = infinity`. Loop through array: `minVal = min(minVal, current)`. Then, use `while(minVal > 0) { sum += minVal % 10; minVal /= 10; }`. Return `sum % 2 == 0 ? 1 : 0`. |
Draw array. Point at each number. Circle the smallest. Draw a box for that number and use arrows to "extract" the last digit one by one. |
Single pass through the array. |
Draw an array with one arrow sweeping right. Write $O(N)$ Time. |
Full sorted copy of the array stored in memory. |
Two variables: `minVal` and `digitSum`. $O(1)$ space. |
| 1086 |
High Five |
Store all scores for each student in a list. Sort the list of scores for every single student and take the top five to average them. |
Multiple independent sorting bins for every student ID found. |
ID 1: [90, 80, 70, 100, 95, 60]. Sort: [100, 95, 90, 80, 70, 60]. Take first 5. Avg. Write $O(N \log N)$. |
TreeMap + Max-Heap (or Sorting). |
A "Top-Tier Filter". Each student has a small 5-slot priority queue that only keeps the best performances. |
Use a `Map>`. For each score, push to student's min-heap. If heap size > 5, pop the smallest. Finally, calculate averages from the remaining heaps. |
Draw a Map with IDs. Next to each ID, draw a small box (Heap) with 5 slots. Every time a score comes in, if it's bigger than the smallest in the box, swap it. |
Single pass through scores + constant time heap operations. |
Draw the score list being streamed into student-specific buckets. Write $O(N \log K)$ where K=5. |
Huge lists of all scores for every student. |
A map of fixed-size heaps. $O(\text{Students})$ space. |
| 1087 |
Brace Expansion |
Generate every possible combination of strings by expanding the braces. Store them in a list and sort them at the end. |
A massive branching tree of string permutations. |
"{a,b}c{d,e}". Branches: acd, ace, bcd, bce. List and sort. Write $O(K^N)$ where K is choices per brace. |
Backtracking + Sorting Groups. |
A "Pathfinder" through multiple layers of choices. |
Parse the string into groups (e.g., ["a","b"], ["c"], ["d","e"]). Sort characters within each group. Use DFS to traverse and build strings. |
Draw layers of dots. First layer: a, b. Second layer: c. Third layer: d, e. Draw every possible path from top to bottom. Each path is a result. |
Ordered exploration of the state-space. |
Draw a decision tree where characters are already alphabetically ordered at each branch. Write $O(\text{ResultCount})$. |
Exponential space to store all result strings before sorting. |
$O(N)$ recursion stack, where N is the number of groups. |
| 1088 |
Confusing Number II |
Iterate from 1 up to N. For each number, check if it's "confusing" (valid rotated digits and rotated value != original). |
A linear scan checking billions of numbers, most of which have invalid digits. |
N=100. Check 1, 2 (invalid), 3 (invalid)... Check 6. Check 9. Check 10. Write $O(N \log N)$. |
Digit-based DFS / Backtracking. |
A "Valid-Digit Only" Tree. We only ever look at numbers made of [0, 1, 6, 8, 9]. |
Start DFS from [1, 6, 8, 9]. For each valid number, append another digit from [0, 1, 6, 8, 9] as long as `newNumber <= N`. For each number generated, check if `rotate(num) != num`. |
Draw a tree starting at root. Branches: 1, 6, 8, 9. From '1', branches: 10, 11, 16, 18, 19. If a node > N, stop that branch. |
Exploring only 5^digits states instead of N states. |
Draw a 5-ary tree with a depth of log10(N). Write Time: $O(5^\log10(N)$). |
No extra memory besides the loop. |
$O(\log N)$ recursion stack. |
| 1089 |
Duplicate Zeros |
Create a new array. Iterate through the original; if you see a non-zero, copy it. If you see a zero, copy it twice. Stop when the new array is full. |
A "Double-Stamp" copier using a second sheet of paper. |
[1, 0, 2, 3]. New: [1]. Zero -> [1, 0, 0]. Next: [1, 0, 0, 2]. Result: [1, 0, 0, 2]. Write $O(N)$ but $O(N)$ space. |
Two-Pointer (In-Place). |
A "Reverse-Fill" strategy. Calculate how far the elements will shift, then move them from the back to the front. |
Count the zeros that will fit in the final array. Then, use two pointers: `i` (end of the source elements) and `j` (the true end of the array). Move backwards, copying `arr[i]` to `arr[j]` and duplicating if `arr[i]` is zero. |
Draw the array. Count zeros. Mark where the "last" element will end up. Use two arrows pointing at the end, moving left. Copy numbers; when you hit a 0, write it twice. |
Two linear passes through the array. |
Draw the array with two arrows moving right-to-left. Write $O(N)$ Time. |
$O(N)$ space for the auxiliary array. |
$O(1)$ extra space. |
| 1090 |
Largest Values From Labels |
Generate every possible subset of items. For each subset, check if size <= numWanted and if the label frequency <= useLimit. Return the max sum. |
An exponential subset tree (2^N) with massive branches being pruned by constraints. |
Draw 3 items [val, label]. List subsets: {1}, {2}, {3}, {1,2}... Check label counts for each. Write $O(2^N)$. |
Greedy (Sorting). |
A "High-to-Low" Filter. We take the most valuable items first and discard any that exceed our label quota. |
Combine values and labels into pairs. Sort by value descending. Iterate through pairs, keeping a frequency map of labels. If `map[label] < useLimit`, add value to total. Stop when `count == numWanted`. |
Draw a table [Value, Label]. Sort rows by Value. Have a side-table for "Label Usage". Mark checks next to rows you pick. Update label counts as you go. |
A sort followed by a single linear scan. |
Draw a sort box $O(N \log N)$ followed by a single arrow $O(N)$. Total Time: $O(N \log N)$. |
$O(2^N)$ space for all subsets. |
$O(N)$ space for sorted pairs and label frequency map. |
| 1091 |
Shortest Path in Binary Matrix |
Use DFS to find all possible paths from (0,0) to (n-1, n-1). Keep track of the minimum length among valid paths. |
A "Labyrinth" where a single runner tries every possible turn, often hitting dead ends or loops. |
Draw a grid. Mark '0's. Draw a path from start. When you hit a wall, backtrack. Write $O(8^(N^2)$). |
BFS (Level-Order Traversal). |
An "Expanding Ripple". Every valid step outward covers all cells reachable in k moves before checking k+1. |
Start at (0,0) and put in Queue. While Queue is not empty, pop current, check all 8 neighbors. If neighbor is 0 and not visited, mark visited and push to Queue with `dist + 1`. |
Draw the grid. Write '1' in (0,0). Write '2' in all its neighbors. Write '3' in all their neighbors. The number at target is your shortest path. |
A single outward-expanding wave covering the grid. |
Draw a grid with concentric squares expanding from top-left. Write Time: $O(N^2)$. |
Exponential recursion stack. |
A Queue and a visited matrix. $O(N^2)$ space. |
| 1092 |
Shortest Common Supersequence |
Generate every possible string that contains both str1 and str2 as subsequences. Find the shortest one among them. |
An infinite search space of string combinations. |
"ab", "ac". Try "abc", "acb", "abac"... Write $O(\text{Exponential})$. |
Dynamic Programming (LCS Variation). |
A "Master Blueprint". Find the Longest Common Subsequence (LCS) first, then fill in the unique characters around it. |
Compute the 2D DP table for LCS. Backtrack from `dp[n][m]`. If characters match, add once. If not, add the character that was dropped to reach the current DP state. Reverse result. |
Draw the DP matrix for LCS. Trace the diagonal path from bottom-right to top-left. For horizontal/vertical moves, write down the corresponding character. For diagonals, write the shared character. |
Two-pass process (compute matrix, then backtrack). |
Draw a grid with a single snaking path from end to start. Write Time: $O(N \cdot M)$. |
Massive string allocations. |
$O(N \cdot M)$ space for the DP table. |
| 1093 |
Statistics from a Large Sample |
Reconstruct the original sample array by duplicating the numbers based on their frequencies. Run standard statistical functions on the full array. |
Memory explosion! A frequency array of size 256 can represent a sample of millions of numbers. |
count[5]=1000. Write "5" one thousand times. Write $O(\text{TotalSamples})$. |
Frequency-Based Math. |
A "Virtual Array". We don't need the numbers physically; we just need to know their "positions" in an imaginary sorted list. |
Min/Max: find first/last non-zero index. Mean: `Sum(val * freq) / TotalSamples`. Mode: index with max frequency. Median: Track running count of samples until you hit `TotalSamples/2`. |
Draw the frequency array. Mark "Total Samples". Draw an arrow moving through the buckets, accumulating the count until it hits the middle point. |
Single pass through the 256-sized frequency array. |
Draw a small fixed-size bar chart. Write Time: $O(256)$ which is $O(1)$. |
$O(\text{TotalSamples})$ space. |
$O(1)$ space (fixed 256 array). |
| 1094 |
Car Pooling |
For every location from 0 to 1000, iterate through all trips and check how many people are in the car at that specific point. |
A "Snapshot Scan". At every mile marker, we re-verify the entire list of passengers. |
Trips: [[2,1,5], [3,3,7]]. Mile 1: 2. Mile 2: 2. Mile 3: 2+3=5. Mile 4: 5. Mile 5: 3. Write $O(\text{Locations} \\text{cdot Trips})$. |
Difference Array / Prefix Sums. |
A "Passenger Logbook". We only record when people get in (+) and when they get out (-). |
Create an array of size 1001. For each trip [num, start, end], do `arr[start] += num` and `arr[end] -= num`. Finally, compute the prefix sum; if any point exceeds capacity, return false. |
Draw a timeline 0-1000. At the 'start' mark, write '+ passengers'. At the 'end' mark, write '- passengers'. Sweep across the timeline, keeping a running sum. |
Two linear passes (one to log, one to sum). |
Draw a timeline with arrows going up and down. Write Time: $O(\text{Trips} + 1001)$. |
Storing lists of people for every single coordinate. |
$O(1)$ space (fixed-size array of 1001). |
| 1095 |
Find in Mountain Array |
Scan the entire array from left to right using `get(index)` until you find the target. |
A linear probe checking every single index in the mountain. |
Draw a peak. Start an arrow at index 0 and move one step at a time up and down the mountain. Write $O(N)$. |
Binary Search (Triple Pass). |
A "Three-Step Expedition". First find the peak, then search the ascending slope, then the descending slope. |
1. Binary search to find `peak` (where `arr[i] < arr[i+1]`). 2. Binary search for `target` in `[0, peak]`. 3. If not found, binary search `target` in `[peak+1, n-1]` with reversed comparison logic. |
Draw a mountain shape. Divide into two zones at the peak. Draw two Binary Search trees (one for each side). Use `target` to narrow the range. |
Logarithmic search with limited API calls. |
Draw three Binary Search trees. Write Time: $O(\log N)$. |
No extra memory. |
$O(1)$ space for pointers (left, right, mid). |
| 1096 |
Brace Expansion II |
Recursive expansion of every comma and brace. Store all generated strings in a Set and sort at the end. |
An exponential tree of string concatenations and unions. |
"{a,b}{c,{d,e}}". Expanding all possible paths. Write $O(\text{Exponential})$. |
Recursive Descent Parsing / Stack. |
A "Nested Layer" processing. We evaluate the innermost expressions and bubble their results up to combine with outer layers. |
Use a stack to store "current groups". When you see '{', push a new context. When you see ',', start a new term in the current context. When you see '}', pop and multiply (Cartesian product) with the previous context. |
Draw the string. Use vertical bars to represent stack levels. When a brace closes, draw lines showing how strings from the current level multiply into the previous level. |
Orderly expansion of the grammar. |
Draw a parse tree for the expression. Write Time: $O(N \log N)$ or $O(N^2)$ depending on result size. |
Massive duplication of intermediate strings. |
$O(\text{Depth of Braces})$ stack space + Result Set. |
| 1097 |
Game Play Analysis V |
(SQL) For every user, find their install date. For each date, find users who installed on that date and check if they logged in the next day. |
Nested self-joins and subqueries for every unique date. |
Date 1: Find installs. Check retention. Date 2: Repeat. Write $O(\text{Dates} \\text{cdot Users})$. |
Join + Group By (Install Date Logic). |
A "Cohorts Table". Group users by their first seen date and check the "Day 1" retention rate for each cohort. |
`SELECT install_dt, COUNT(*) AS installs, ROUND(COUNT(next_day)/COUNT(*), 2) AS Day1_retention FROM (SELECT player_id, MIN(event_date) AS install_dt FROM Activity GROUP BY player_id) ... LEFT JOIN Activity ON ...` |
Draw the Activity table. Create a side table for "First Login". Join them. Count how many users have a login exactly 1 day after their first. Group by first date. |
Two-pass aggregation. |
Draw a table collapsing into cohorts, then a join. Write Time: $O(\text{ActivityRows})$. |
Expensive temporary tables for every install date check. |
Hash map for the first-login lookup. $O(\text{UniquePlayers})$ space. |
| 1098 |
Unpopular Books |
(SQL) Select all books. For each book, filter orders in the last year, sum them, and check if < 10. Filter books available < 1 month. |
Filtered lookups for every book in the library. |
Book A: Check orders in 2026. Sum. Book B: Repeat. Write $O(\text{Books} \\text{cdot Orders})$. |
Left Join + Filtering + Having. |
A "Sales Ledger Filter". Combine the book list with recent orders, sum them, and keep only the "cold" inventory. |
`SELECT b.book_id, b.name FROM Books b LEFT JOIN Orders o ON b.book_id = o.book_id AND o.dispatch_date >= '2025-05-23' WHERE b.available_from < '2026-04-23' GROUP BY b.book_id HAVING SUM(o.quantity) < 10 OR SUM(o.quantity) IS NULL`. |
Draw the Books table. Cross out books released in the last month. Join remaining with the Orders table (filtered by date). Sum quantities. Highlight books with total < 10. |
Single pass join and filter. |
Draw a filtered table merging into an aggregation. Write Time: $O(\text{Books} + \text{Orders})$. |
Multiple sub-selections stored in memory. |
Hash map for grouping. $O(\text{Books})$ space. |
| 1099 |
Two Sum Less Than K |
Use nested loops to check every possible pair (i, j) and calculate their sum. If sum < K, update the maximum. |
A complete web of all possible pairs in the array. |
Draw the array. From index 0, draw lines to 1, 2, 3... Calculate sums. Write $O(N^2)$. |
Two Pointers (Sort + Shrink). |
A "Closing Door". We sort the numbers and use two pointers to find the best pair that doesn't "break" the limit K. |
Sort the array. Set `i=0`, `j=n-1`. If `nums[i] + nums[j] < K`, update max and move `i++`. Else, move `j--`. |
Draw a sorted line of numbers. Put an arrow at start and end. If the sum is too high, move the right arrow left. If sum is safe, record it and move the left arrow right. |
Sort followed by a single linear pass. |
Draw a sort box $O(N \log N)$ followed by a single arrow $O(N)$. Total Time: $O(N \log N)$. |
No extra memory besides loops. |
$O(1)$ extra space (ignoring sort space). |
| 1100 |
Find K-Length Substrings With No Repeated Characters |
Extract every substring of length K. For each substring, use a Set to check if all characters are unique. |
A sliding "Snapshot" taking N-K pictures and running a lab test on each. |
String: "havefunonleetcode", K=5. Draw brackets for "havef", then "avefu"... For each, check if count of unique == K. Write $O(N \cdot K)$. |
Sliding Window + Frequency Array/Set. |
A "Conveyor Belt with a Counter". As characters enter/exit the window, update a single tally. |
Maintain a window of size K. Use a frequency array of size 26. Count how many characters have frequency > 1. If that count is 0, the window is valid. |
Draw the string. Put 'L' and 'R' pointers at distance K. Slide them together. Write the 26-box frequency array below. Cross out/increment numbers as letters pass. |
Single pass through the string. |
Draw the string with one arrow and a fixed window box. Write Time: $O(N)$. |
Creating N-K unique substring objects in memory. |
A single fixed-size array of 26 integers. $O(1)$ space. |
| 1101 |
The Earliest Moment When Everyone Become Friends |
For every log entry (timestamp, X, Y), rebuild the entire friendship graph and check if it's connected (all nodes reachable from one). |
A massive graph being redrawn from scratch for every single second in the logs. |
Logs: [T1, 0, 1], [T2, 2, 3]... After T1, is everyone connected? No. After T2? No. Write $O(L \cdot (N + L)$) where L is logs. |
Union-Find (DSU) with Component Counting. |
A "Merger Map". We start with N isolated islands. Every log entry is a bridge. We stop when only 1 island remains. |
Sort logs by timestamp. Use DSU. Initialize `count = N`. For each log (X, Y), if `find(X) != find(Y)`, union them and `count--`. When `count == 1`, return the timestamp. |
Draw N dots. Sort the logs. Draw lines between dots as you read logs. Next to the graph, write "Islands: N". Decrement it every time a line connects two separate groups. |
Logarithmic sorting followed by near-linear union operations. |
Draw a sort box $O(L \log L)$ followed by a DSU line $O(L α(N)$). Write Time: $O(L \log L)$. |
Re-allocating the adjacency list multiple times. |
A single parent array of size N. $O(N)$ space. |
| 1102 |
Path With Maximum Minimum Value |
Use DFS to find all possible paths from (0,0) to (R-1, C-1). For each path, find the minimum value. Return the maximum of these minimums. |
A blind explorer trying every path, recording the "scariest" point of each. |
Grid: [[5,4,5], [1,2,6]]. Paths: (5-4-5-6, min=4), (5-1-2-6, min=1). Max min is 4. Write $O(4^(R\cdot C)$). |
Greedy (Priority Queue / BFS) or Binary Search + DFS. |
A "Dijkstra-style" Flood. We always expand the neighbor with the highest value to keep our minimum as high as possible. |
Use a Max-Heap. Push (value, r, c). Pop the largest value. Its value is the "bottleneck" so far. Update global min. Add unvisited neighbors to heap. Stop when target is reached. |
Draw the grid. Use a side-list called "Options (Heap)". Pick the largest number from the list, mark it on the grid, add its neighbors to the list. Keep track of the lowest number you've picked. |
Best-first search covering each cell once. |
Draw a grid with a path being built by picking the "best" available cell. Write Time: $O(R\cdot C \log(R\cdot C)$). |
Exponential recursion stack. |
A Max-Heap and a visited matrix. $O(R\cdot C)$ space. |
| 1103 |
Distribute Candies to People |
Simulate the distribution process step by step, one person at a time, until the candy bag is empty. |
A "Round Robin" loop running until exhaustion. |
N=7, C=4. P1: 1. P2: 2. P3: 3. P4: 1 (left). Result: [1, 2, 3, 1]. Write $O(\text{sqrt}(C)$). |
Simulation or Mathematical Arithmetic Progression. |
A "Growing Pour". Each step adds exactly one more candy than the previous step. |
Keep a pointer `i = 0` and `candies_to_give = 1`. While `total_candies > 0`, give `min(candies_to_give, total_candies)` to `person[i % n]`. Increment `i` and `candies_to_give`. |
Draw N empty buckets. Write the numbers 1, 2, 3... and "pour" them into the buckets sequentially. If the last number is bigger than what's left, pour the remainder. |
Linear simulation proportional to the number of distribution steps. |
Draw N buckets with a spiraling arrow filling them. Write Time: $O(\text{max}(N, \text{sqrt}(C)$)). |
$O(1)$ if just tracking, but $O(N)$ for the result. |
A single array of size N. $O(N)$ space. |
| 1104 |
Path In Zigzag Labelled Binary Tree |
Build the entire tree up to the level containing `label`, accounting for the zigzag pattern, then traverse up to the root. |
A "Tower Construction" requiring memory for every single node in the tree. |
Label 14. Level 1: 1. Level 2: 3, 2. Level 3: 4, 5, 6, 7. Level 4: 15...8. Construct and find 14. Write $O(\text{label})$. |
Math (Symmetry / Bit Manipulation). |
A "Mirror-Reflection" climb. In a normal tree, parent is `child/2`. In a zigzag tree, the parent is the mirror of `child/2` in the previous level. |
Find current level. Calculate the range of the current level `[min, max]`. The parent in a non-zigzag tree would be `label / 2`. The true parent is `(min_of_prev_level + max_of_prev_level) - (label / 2)`. |
Draw the levels. Write the labels in zigzag. For 14, look at the level above. Find its reflection point. Write the sequence: 14 -> 7 -> ... until 1. |
Logarithmic climb to the root. |
Draw a single straight line up from the leaf to the root. Write Time: $O(\\text{log label})$. |
$O(\text{label})$ space for the full tree structure. |
$O(\\text{log label})$ space to store the path nodes. |
| 1105 |
Filling Bookcase Shelves |
Recursion (Include/Exclude). For each book: 1. Place on current shelf (if fits). 2. Start a new shelf. |
Binary Decision Tree |
Draw a book. Branch left: "Same Shelf" (update remaining width, track max height). Branch right: "New Shelf" (reset width, add previous max height). |
1D Dynamic Programming |
Sliding Window DP Array |
Iterate books. For `dp[i]`, look back at previous books `j` to form a valid shelf. `dp[i] = min(dp[i], dp[j-1] + max_height)`. |
Draw the `dp` array. At index `i`, draw arrows pointing back to `j` (where width constraint holds). Write the `max_height` found in that window. |
Nested Loop Bracket Diagram |
Draw an outer loop N. Inner loop goes back up to N steps. Draw an area representing $O(N^2)$ combinations checked. |
Deep Recursion Stack + State variables |
Single 1D Array of size N+1. Draw boxes. Fill boxes left to right, representing optimal minimal height at each book count. |
| 1106 |
Parsing A Boolean Expression |
Recursive Descent Parser. Find matching parentheses, slice substrings, and recursively evaluate inner expressions. |
Deep Recursion Tree |
Draw the full string. Branch out for every '('. Draw substring slices being passed down. Write $O(N^2)$ next to it due to string copying. |
Stack (Iterative Evaluation) |
Stack Push/Pop Diagram |
Read left to right. Push operators (!, &, |) and characters (t, f, '(') to the stack. When hitting ')', pop 't' and 'f' until '(', evaluate against the operator, and push result back. |
Draw an open bucket (stack). Write chars going in. Cross them out as they pop, write 't' or 'f' result back in. |
Linear Timeline |
Draw a timeline of length N. Draw a single arrow sweeping left to right, representing $O(N)$ time. |
Massive Call Stack Frames |
Single 1D Array/Stack expanding and shrinking in place. |
| 1107 |
New Users Daily Count (SQL) |
Correlated subqueries. For every row, run another query to find the MIN(activity_date) for that specific user. |
Nested Table Scans |
Draw a table. For each row, draw an arrow looping back over the entire table to find the earliest date. |
Common Table Expression (CTE) / GROUP BY |
Hash Aggregation Pipeline |
Group all rows by user_id to find the minimum activity_date per user. Filter where the date is within 90 days. Group again by the resulting date and count users. |
Draw Input Table -> Funnel (Group by User) -> Filter Block (Date > 90 days) -> Funnel (Group by Date) -> Output Table. |
Map-Reduce Flowchart |
Draw two distinct mapping blocks (the two GROUP BY clauses) executing sequentially, not nested. |
Row-by-row memory cache |
Hash Tables holding User IDs and their first login dates. |
| 1108 |
Defanging an IP Address |
String concatenation in a loop. Because strings are immutable, this creates a new string copy every time a '.' is found. |
String Copy Waterfall |
Draw the original string. Draw a new, slightly longer string every time a '.' is encountered. |
String Builder / Pre-allocated Array |
Two-Pointer Array Fill |
Allocate a new array of size N + 6. Pointer 'i' reads original, pointer 'j' writes to new. If reading '.', write '[.]' to the new array and advance 'j' by 3. |
Draw original array top, new array bottom. Draw straight down arrows for numbers, and diagonal branching arrows mapping '.' to '[', '.', ']'. |
Flat Line $O(N)$ |
Sweep from left to right exactly once. Draw a straight line showing $O(N)$ time. |
Pyramid of garbage collected strings |
Two fixed-size character arrays (Input and Output). |
| 1109 |
Corporate Flight Bookings |
Nested loops. For each booking [i, j, k], loop from index i to j in the result array and add k to each seat. |
Overlapping Bar Charts |
Draw an array 1 to N. Draw a horizontal bar for each booking stretching from i to j. Sum the overlapping heights. $O(N \cdot M)$ time. |
Difference Array / Prefix Sum |
Delta Boundary Markers |
At index i, add k. At index j+1, subtract k. After processing all bookings, sweep left to right once, accumulating the running sum. |
Draw an array of zeros. Write +k at start index, -k after end index. Draw a second array below it sweeping right, adding the previous value. |
Two Disjoint Flat Lines |
Draw one line processing bookings $O(M)$, and a second separate line sweeping the final array $O(N)$. Total $O(M + N)$. |
Simple 1D array continuously mutating |
Two 1D arrays (Difference array acting as instructions -> Prefix sum array). |
| 1110 |
Delete Nodes And Return Forest |
Find node, delete it, re-root children, repeat. Requires multiple passes over the tree to find new targets. |
Disconnecting/Reconnecting Graph |
Draw a tree. Erase a node. Draw new roots for orphaned children. Re-traverse the newly severed branches to find next targets. |
Post-order DFS Traversal + Hash Set |
Bottom-Up Tree Pruning |
Convert 'to_delete' to a HashSet. DFS down to leaves. Process a node: if it needs deletion, add its non-null children to the result list, then return null to its parent. |
Draw tree. Circle nodes to delete. Draw arrows coming *up* from leaves. When hitting a circled node, cross it out, draw a box around its children, pass 'NULL' up. |
Single Tree Traversal Path |
Trace the outline of the tree exactly once. $O(N)$ time complexity. |
Multiple disconnected tree fragments |
Hash Set (for $O(1)$ lookups) + List of Root Pointers. |
| 1111 |
Maximum Nesting Depth of Two Valid Parentheses Strings |
Backtracking. Try assigning every bracket to either string A or string B and check which combination minimizes the maximum depth. |
Binary Decision Tree |
Draw the string. For every bracket, draw two branching paths (Group 0 or Group 1). $O(2^N)$ explosion. |
Greedy / Parity based on Depth |
Alternating Color Wave |
Keep a running `depth` counter. When seeing '(', increment depth. Assign to group `depth % 2`. When seeing ')', assign to `depth % 2`, then decrement depth. |
Write the string horizontally. Below each character, write the current depth number. Below that, write the modulo (0 or 1). Circle the 0s and 1s. |
Flat Line $O(N)$ |
Draw a single straight arrow sweeping from left to right under the string. |
Massive Call Stack Tower |
Single Output Array of size N filled with 0s and 1s. |
| 1112 |
Highest Grade For Each Student (SQL) |
Correlated Subquery. For each row, run a separate query to find the `MAX(grade)` for that specific `student_id`. |
Nested Loop Scanning |
Draw a table. For every single row, draw an arrow that loops back and scans the entire table from top to bottom. |
Window Function (ROW_NUMBER) |
Partitioning and Sorting Blocks |
Partition the data by `student_id`. Within each partition, sort by `grade` DESC, then `course_id` ASC. Assign a row number. Filter where `row_num = 1`. |
Draw boxes around groups of the same `student_id`. Inside each box, draw a sorted list. Highlight the top row of each box. |
$O(N \log N)$ Sorting Diagram |
Draw a funnel (Partitioning), leading into several mini sorting-tree graphs (processing in parallel). |
Full Cartesian Product in Memory |
Segmented Data Arrays (Partitions). |
| 1113 |
Reported Posts (SQL) |
Fetch all rows to the application layer, loop through them, filter by date/action, and manually count unique posts. |
Linear Scan and Map |
Check each row manually. Keep a running tally on a separate piece of paper, crossing out duplicates. |
COUNT(DISTINCT) with GROUP BY |
Hash Aggregation Pipeline |
Filter out irrelevant dates and non-report actions first. Push remaining rows into buckets based on `extra` (reason). Count unique `post_id`s in each bucket. |
Draw a "Filter Gate". Draw buckets for 'spam', 'racism', etc. Drop post IDs into buckets. Cross out duplicate IDs within each bucket. |
Linear Hash Grouping |
Draw a single-pass flowchart mapping inputs directly to their respective buckets. $O(N)$ time. |
Unbounded List of Objects |
Hash Sets (for uniqueness) inside a Hash Map (for categories). |
| 1114 |
Print in Order |
Busy Waiting. Use infinite `while` loops checking a shared boolean flag to see if it's a thread's turn. |
Spinning Gears (CPU Waste) |
Draw thread blocks continuously looping, reading a variable, doing nothing. Draw lightning bolts to show wasted CPU cycles. |
Concurrency: Mutexes / Semaphores / Promises |
Gated Checkpoints |
Thread 1 runs, unlocks Gate A. Thread 2 waits at Gate A, then runs, unlocks Gate B. Thread 3 waits at Gate B, then runs. |
Draw three parallel tracks. Draw a locked gate on Track 2 and 3. Draw a "key" passing from Track 1 to 2, then 2 to 3. |
Sequential Dependency Graph |
Draw 3 blocks connected by directed arrows (1 rightarrow 2 rightarrow 3). $O(1)$ time per thread. |
Shared global boolean variables |
OS-level Wait Queues (Threads are put to sleep, using 0 CPU). |
| 1115 |
Print FooBar Alternately |
`Thread.sleep()` guesswork or busy waiting with a single `isFooTurn` variable. Leads to race conditions or CPU burning. |
Ping-Pong with Dropped Balls |
Draw two loops constantly checking `if (turn == 1)`. Show execution overlapping chaotically. |
Concurrency: Two Alternating Semaphores |
Alternating Traffic Lights |
Initialize `fooSem = 1`, `barSem = 0`. Foo thread acquires `fooSem`, prints, releases `barSem`. Bar thread acquires `barSem`, prints, releases `fooSem`. |
Draw two columns (Foo and Bar). Draw an arrow zigzagging between them, passing a single "token" back and forth N times. |
Cyclic Graph |
Draw a circle with two states (Foo State rightarrow Bar State rightarrow Foo State). $O(N)$ total time. |
Memory Contention / Cache Bouncing |
Two Semaphore objects with distinct signal wait lists. |
| 1116 |
Print Zero Even Odd |
Busy waiting (Spinlocks). Use a single shared state variable (0, 1, 2) and have three threads stuck in infinite `while` loops checking the state. |
Overlapping Spin Cycles |
Draw three circular arrows spinning rapidly. Draw lightning bolts between them to represent wasted CPU cycles and high contention. |
Concurrency: 3 Semaphores |
Token Passing Triangle |
Initialize semaphores: Zero(1), Even(0), Odd(0). 'Zero' thread runs, prints 0, and signals either Even or Odd. They run, print, and signal Zero back. |
Draw 3 nodes (Z, E, O). Draw directed arrows: Z to O, O to Z, Z to E, E to Z. Trace a single "token" moving back and forth along these paths. |
Sequential Cyclic Execution Graph |
Draw a timeline. Plot alternating blocks: [Z][O][Z][E][Z][O]... showing $O(N)$ linear time with zero CPU waste. |
Shared volatile integer continuously polled |
3 OS-level Semaphore queues (Threads sleep efficiently). |
| 1117 |
Building H2O |
Unsynchronized counters. Threads check `h_count == 2` and `o_count == 1`. Highly prone to race conditions, deadlocks, and corrupted states. |
Traffic Gridlock |
Draw a bottleneck where 'H' and 'O' molecules are crashing into each other, trying to pass through a gate without a traffic light. |
Semaphores + CyclicBarrier / Phasers |
Molecular Funneling |
H-semaphore allows 2 permits, O-semaphore allows 1. A CyclicBarrier waits for exactly 3 threads. When 3 arrive, they bond and release simultaneously. |
Draw a funnel with 3 slots (2 for H, 1 for O). Drop "tokens" in. Once all 3 slots are full, draw a water droplet falling out the bottom, and reset the slots. |
Batch Processing Timeline |
Draw groups of 3 blocks aligning perfectly on a timeline before proceeding. $O(N)$ time scaling linearly with molecules. |
Unbounded thread wait-queues causing memory leaks |
Semaphore permits (Int counters) and a Barrier Lock Object. |
| 1118 |
Number of Days in a Month |
Massive `switch-case` statement with 12 branches, including custom nested `if` logic for leap years inside February. |
Branching Flowchart |
Draw a starting point splitting into 12 different paths. Draw the February path splitting again. Shows $O(1)$ but high code complexity. |
Pre-computed Array + Leap Year Math |
Indexed Array Lookup |
Create array `days = [31, 28, 31, ...]`. Check if month is 2. If so, apply leap year logic: `(Y % 4 == 0 && Y % 100 != 0) || Y % 400 == 0`. Add 1 if true. |
Draw a 12-slot array. Draw a pointer pointing directly to index `M-1`. Draw a side box that adds +1 conditionally. |
Direct Mapping Arrow |
Draw a single straight line from the Input (Year, Month) directly to the Output (Days). $O(1)$ Time. |
Switch statement bytecode / instruction overhead |
Constant size 12-element static integer array $O(1)$. |
| 1119 |
Remove Vowels from a String |
String Concatenation in a loop. Because strings are immutable in many languages, appending creates a full copy of the string every time. |
String Copy Waterfall |
Draw the original string. Draw a new, slightly longer string below it for every consonant added. Write $O(N^2)$ to highlight the hidden waste. |
Two Pointers / StringBuilder / RegEx |
Filter Pipeline |
Iterate characters. If character is NOT in the vowel set `[a, e, i, o, u]`, append it to a mutable array or StringBuilder. |
Draw the original string on top. Draw an empty array on the bottom. Draw straight down-arrows for consonants, and an 'X' over vowels. |
Flat Line $O(N)$ |
Draw a single arrow sweeping from left to right exactly once. |
Pyramid of garbage-collected intermediate strings |
Pre-allocated Character Array / StringBuilder $O(N)$. |
| 1120 |
Maximum Average Subtree |
Pre-order Traversal. For *every* node, launch a brand new DFS to sum its subtree and count nodes. Calculates average, tracks max. |
Nested Subtree Bubbles |
Draw a tree. For every node, draw a bubble wrapping its entire subtree. The massive overlap visually shows the $O(N^2)$ redundant work. |
Post-order DFS (Bottom-Up) |
Bubbling Up State Tuples |
DFS down to leaves. A node waits for Left and Right children to return an array: `[sum, count]`. Node calculates `[L_sum + R_sum + val, L_count + R_count + 1]`. |
Draw a tree. Start at leaves. Write `[val, 1]` next to them. Draw arrows moving UP to parents. Combine the arrays at the parent, cross out the old ones. |
Single Traversal Path $O(N)$ |
Trace the edges of the tree exactly once, following the perimeter from bottom to top. |
Massive Call Stack $O(N)$ for every $O(N)$ traversal |
Max Depth Call Stack $O(H)$ passing 2-element arrays. |
| 1121 |
Divide Array Into Increasing Sequences |
Backtracking/Recursion. Try every possible way to group the numbers into K-length sequences and check validity. |
Exponential Branching Tree |
Draw the input array. For each number, draw K paths representing different sequences it could join. $O(N^K)$ mess. |
Greedy / Frequency Counting |
Frequency Histogram Bar Limit |
Count the most frequent number (max_freq). Check if the total elements N can support max_freq groups of size K. Formula: N >= max_freq x K. |
Draw a frequency table. Circle the largest frequency. Draw a box representing N slots. Check if max_freq x K fits inside that box. |
Single Linear Pass $O(N)$ |
Draw a single straight line scanning the sorted array to find the max consecutive identical elements. |
Massive recursion stack |
$O(1)$ extra space (if array is sorted) or a Hash Map for frequencies. |
| 1122 |
Relative Sort Array |
Custom Comparator. For every pair of elements, check their indices in `arr2` using `.indexOf()`. |
Nested Search Comparison |
Draw two elements being compared. For each, draw an arrow scanning through `arr2` to find their priority. $O(N^2 \log N)$. |
Counting Sort (Frequency Map) |
Bucket Transfer Visualization |
Count frequencies of all numbers in `arr1`. Iterate through `arr2`, appending the number to the result count times and zeroing it in the map. Append remaining keys in sorted order. |
Draw a frequency map (buckets). Draw `arr2` below it. Cross out buckets as you move values from Map to Result. Finally, sort the remaining buckets. |
Linear + Sorting Remainder |
Draw a line for frequency counting, a line for `arr2` processing, and a small log-curve for sorting the leftover items. |
Temporary Index Lists |
Frequency Array (size 1001) or Hash Map. Draw a fixed-size 1D array. |
| 1123 |
Lowest Common Ancestor of Deepest Leaves |
Two-pass DFS. Pass 1: Find the depth of all leaves. Pass 2: Find the LCA of all leaves that hit the maximum depth. |
Double-Scan Perimeter Trace |
Draw a tree. Mark depths on all nodes. Then draw a second path searching for the intersection of the deepest paths. |
Post-order DFS (Depth-Pair Return) |
Recursive Depth-Balanced Scale |
Each node returns `(LCA_Candidate, Max_Depth)`. If `left_depth == right_depth`, the current node is the LCA candidate for that subtree. |
Draw tree. Start at bottom. Pass up `depth` and `node_pointer`. At each parent, if depths from left/right match, update the pointer to 'self'. |
Single Traversal $O(N)$ |
Draw a single continuous line tracing the tree once. $O(H)$ stack depth. |
Multiple lists of leaf paths |
Standard Call Stack. Draw the stack depth proportional to tree height. |
| 1124 |
Longest Well-Performing Interval |
Nested Loops. Check every possible subarray [i, j] and count if tiring days (>8) are more than non-tiring days. |
Subarray Matrix Grid |
Draw a grid of all i, j pairs. Show the $O(N^2)$ checks by shading every cell. |
Prefix Sum + Hash Map / Monotonic Stack |
Balance Beam / Coordinate Plot |
Transform array to +1 (tiring) and -1 (not tiring). Calculate prefix sums. If sum > 0, whole interval is valid. Else, look for the earliest occurrence of sum - 1. |
Draw a line graph of the prefix sum. Whenever the line goes above 0, mark the interval. If it dips, find the first time it was one step lower. |
Single Pass with Lookup $O(N)$ |
Draw a horizontal timeline with a single scan and a side-table for "First Seen" indices. |
Storing every subarray sum |
Hash Map or Monotonic Stack of indices. Draw a 1D Map for `sum -> index`. |
| 1125 |
Smallest Sufficient Team |
Brute Force / Backtracking. Try every combination of people (2^N combinations) and see which one covers all skills with the fewest people. |
Exponential Subset Tree |
Draw a list of people. Branch out: "Include Person" or "Exclude Person". Show 2^60 possible teams. |
Bitmask DP |
State-Space Compression Table |
Represent required skills as bits in an integer. `dp[mask]` stores the smallest list of people to achieve that skill combination. Update: `dp[mask | person_skills] = min(current, dp[mask] + person)`. |
Draw a table where the index is a binary bitmask (e.g., `1011`). Show the bitwise OR operation merging a person's skills into the current mask. |
$O(\text{People} x 2^\text{Skills})$ Map |
Draw a grid with 2^S rows. Each person updates the grid. Shows high complexity but significantly less than 2^P. |
Storing all possible team combinations |
1D DP array of size 2^S. Each cell holds a list/vector of indices. |
| 1126 |
Active Businesses |
Fetch all events, calculate the average for every event type in code, then iterate businesses to count events exceeding the average. |
Multiple Application Loops |
Draw Table -> App -> Avg Calc -> Table Rescan -> App -> Filter. |
Window Functions / CTEs |
The Threshold Filter |
Use a CTE to calculate `AVG(occurences) OVER (PARTITION BY event_type)`. Then SELECT businesses where occurrences > avg, and COUNT > 1. |
Draw events grouped by type. Draw a horizontal "Average Line" for each group. Cross out events under the line. Group remaining by business ID. |
Hash Aggregate $O(N \log N)$ |
Draw data flowing through a partition node, then a filter node. |
Massive in-memory sets. |
SQL execution buffer. $O(N)$ space. |
| 1127 |
User Purchase Platform (SQL) |
Multiple UNIONs or CASE statements attempting to calculate "Both" (Mobile + Web) by iterating through users one by one. |
Multi-Pass Fragmentation |
Draw three separate diagrams for Mobile, Web, and Both. Show the difficulty in aligning users who exist in two diagrams simultaneously. |
CROSS JOIN (Template) + LEFT JOIN |
Full Grid Skeleton Filling |
Create a "Template" of all possible Dates and Platforms (Mobile, Web, Both) using a CROSS JOIN. Left Join the actual purchase data into this skeleton and use `SUM(CASE...)` for the logic. |
Draw a 3x3 grid (Rows = Dates, Cols = Platforms). Even if a date has no purchases, the grid cell exists. Fill the grid cells with data from the real table. |
Cartesian Product x Linear Scan |
Draw a small fixed-size grid (Template) being joined with a large incoming stream of transaction data. |
Multiple temporary result sets |
Hash Aggregation for grouping by Date and Platform Type. |
| 1128 |
Number of Equivalent Domino Pairs |
Nested Loops (O(N^2)). For every domino `(a, b)`, scan the rest of the array to find `(a, b)` or `(b, a)`. |
Full Comparison Matrix |
Draw a square grid. Mark the diagonal. Show that every cell above the diagonal must be checked manually. |
Key Normalization + Frequency Map |
Canonical Form Bucketing |
For each domino, sort the pair so `(a, b)` becomes `(min(a,b), max(a,b))`. Use a hash map or 2D frequency array to store counts. Total pairs = sum fracn(n-1)2. |
Draw a set of buckets labeled by sorted pairs (e.g., "1-2", "2-3"). Drop dominoes into buckets. Write the count next to the bucket. |
Linear Scan $O(N)$ |
Draw a single straight arrow sweeping through the input array once. |
Brute force requires no extra storage besides input |
Fixed-size 2D array `int[10][10]` or Hash Map. |
| 1129 |
Shortest Path with Alternating Colors |
Modified BFS/DFS without state tracking. May result in infinite loops or missing the shortest "alternating" path. |
Cyclic Graph Maze |
Draw a graph with red and blue edges. Try to find a path by hand, getting stuck in a loop of the same color. |
BFS with Multi-State Tracking |
Layered Graph Expansion |
Queue stores `(node, color_of_last_edge)`. Distance is tracked separately for "Reaching Node via Red" and "Reaching Node via Blue". |
Draw the graph twice (Red layer and Blue layer). An edge in the Red layer takes you to the Blue layer of the destination node. Run standard BFS on this "Split-Node" graph. |
Graph Traversal $O(V+E)$ |
Draw two parallel lines (Red/Blue). Trace a zigzag line jumping between the two. Total steps = sum of edges. |
Exponential path storage if DFS |
Distance array `dist[N][2]` (size 2 x N). |
| 1130 |
Minimum Cost Tree From Leaf Values |
Recursion with Memoization. Try every possible split point to partition the array into left and right subtrees. |
Catalan Number Tree Explosion |
Draw an array. Draw splits at every possible index. For each split, draw further sub-splits. $O(N^3)$ or $O(N^4)$ complexity. |
Monotonic Stack / Greedy |
Neighbor Merging (Pop-and-Calculate) |
Maintain a monotonic decreasing stack. When a new value is larger than the top, the top is a local minimum. Multiply it by the smaller of its two neighbors (top-1 or current). |
Draw a stack vertically. Push numbers. When a "valley" forms (small number between two larger ones), "crush" the valley, multiply the values, and keep the larger one. |
Linear Pass $O(N)$ |
Draw a single arrow with numbers entering and leaving a stack. Each number enters and leaves exactly once. |
Massive DP table $O(N^2)$ |
Single 1D Stack $O(N)$. |
| 1131 |
Maximum of Absolute Value Expression |
Nested loops $O(N^2)$. Calculate the formula |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| for all pairs (i, j). |
Grid Comparison Matrix |
Draw an N x N grid. Show that every cell must be calculated. Highlight the diagonal to show redundant work. |
Math (Expression Expansion / 8 Scenarios) |
Coordinate Transform Plot |
Expand the absolute values into 4 (or 8) combinations of pm. For each scenario, find the max and min of the resulting expression. The answer is max(max_val - min_val). |
Draw 4 number lines. For each, plot the value of (arr1[i] pm arr2[i] pm i). Circle the furthest two points on each line. |
Multiple Linear Scans $O(N)$ |
Draw 4 parallel horizontal arrows. Each scans the array once. Total time is 4 x N. |
None (In-place loops) |
Constant variables (max1, min1... max4, min4). |
| 1132 |
Reported Posts II (SQL) |
Correlated subqueries or nested loops in Python to calculate percentages per day and then averaging them manually. |
Nested Calculation Waterfall |
Draw a table. For each date, draw a mini-table of unique posts, then another mini-table of removals, then a division. |
GROUP BY + COUNT(DISTINCT) + AVG |
Aggregation Pipe with Multi-Stage Filter |
Join `Actions` with `Removals`. Group by `action_date`. Calculate the ratio of `count(distinct removal_id)` to `count(distinct post_id)`. Wrap in an outer query for `AVG`. |
Draw a "Join" bridge. Then draw buckets by date. Show percentages being written on each bucket. Finally, draw one giant funnel averaging those percentages. |
Hash/Sort Aggregation $O(N \log N)$ |
Draw a flow from table to groups, then a single line for the final average. |
Massive temporary rowsets |
Hash Map for date-wise counts and distinct sets. |
| 1133 |
Largest Unique Number |
Sort the array and then iterate through it, checking if the current number is the same as the neighbors. |
Sorted Strip Search |
Draw a sorted list. Use three fingers (prev, curr, next) to find the largest value where prev != curr and curr != next. $O(N \log N)$. |
Frequency Map / Bucket Sort |
Histogram Frequency Buckets |
Create a frequency array (since numbers are 0-1000). Fill counts. Iterate from index 1000 down to 0. Return the first index with count == 1. |
Draw a row of 1001 boxes. Drop numbers into their boxes. Start at the rightmost box and move left until you find a box with exactly one item. |
Linear Scan $O(N)$ |
Draw a single pass for counting and a second pass for searching. Linear $O(N + K)$. |
Sorted In-place array |
Fixed-size array `int[1001]`. Draw a single static memory block. |
| 1134 |
Armstrong Number |
Convert the number to a string to find the length (k), then iterate through the string, converting back to int to power it. |
String-to-Int Conversion Chain |
Draw the number as a string. Draw arrows splitting characters. Show conversion blocks for each digit. |
Mathematical Digit Extraction |
Modulo-Divide Loop |
Find length using log_10(N) + 1. Use `n % 10` to get digits and `n /= 10` to strip them. Accumulate the sum of powers. |
Draw a number. Write "%10" to get the digit, and "/10" to shrink the number. Repeat until number is 0. Show the power sum increasing in a side box. |
Logarithmic $O(\log N)$ |
Draw a shrinking number line. Each step is 10x smaller. Time is proportional to the number of digits. |
String objects and character arrays |
Constant $O(1)$ space for integers. |
| 1135 |
Connecting Cities With Minimum Cost |
Backtracking. Try every combination of edges to see which forms a tree with the minimum sum. |
Edge Power Set Explosion |
Draw 3 cities. Draw all possible edges between them. Branch out for every "Edge Included" vs "Edge Excluded". $O(2^E)$ complexity. |
Kruskal's Algorithm (Greedy + DSU) |
Edge-Weight Ranking & Merging |
Sort all edges by cost. Use Union-Find to pick the cheapest edge that connects two different components. Stop when you have N-1 edges. |
Draw isolated city dots. List sorted edges. For the cheapest edge, draw a line. If the next edge connects two already connected cities, cross it out (cycle). |
$O(E \log E + E \text{alpha}(V)$) |
Draw a sorting timeline followed by a fast Union-Find pass. |
Adjacency Matrix $O(V^2)$ |
1D `parent` array for DSU and a list of edges. |
| 1136 |
Parallel Courses |
Try all permutations of courses and check if the prerequisite order is respected. |
Factorial Permutation Tree |
Draw 3 courses. Show 3! = 6 possible sequences. For N courses, show N! branches. |
Topological Sort (Kahn's Algorithm / BFS) |
Layered Dependency Slicing |
Count in-degrees for all nodes. Put nodes with 0 in-degree into a queue (Level 1). Process queue, decrement in-degree of neighbors. Nodes hitting 0 go to next level. |
Draw the graph. Next to each node, write its current "In-Degree". Cross out nodes as they reach 0 and move them to a "Current Semester" box. |
Linear Graph Scan $O(V + E)$ |
Draw a timeline where each course and each edge is touched exactly once. |
Adjacency Matrix $O(V^2)$ |
Adjacency List + In-degree Array + Queue. Draw a 1D array and a list of neighbors. |
| 1137 |
N-th Tribonacci Number |
Pure Recursion: T(n) = T(n-1) + T(n-2) + T(n-3). |
Exponential Triple-Branch Tree |
Draw T(n) at top. Split into 3 branches. Show how nodes like T(2) are recalculated hundreds of times. $O(3^N)$. |
Dynamic Programming (Iterative Space Optimized) |
Sliding Window of 3 Variables |
Start with a=0, b=1, c=1. In a loop, calculate next = a+b+c. Move a rightarrow b, b rightarrow c, c rightarrow next. Repeat N times. |
Draw three boxes labeled a, b, c. Write numbers in them. Draw an arrow shifting the numbers to the left and dropping the new sum into the c box. |
Linear Timeline $O(N)$ |
Draw a single straight line from 0 to N with a single loop operation. |
Massive Call Stack $O(N)$ |
Constant $O(1)$ space using 3 variables. |
| 1138 |
Alphabet Board Path |
BFS to find the shortest path between every consecutive letter in the target word. |
Grid Search Expansion (Multiple times) |
Draw the board. For each letter, draw a ripple effect (BFS) searching for the next letter. $O(\text{WordLength} x \text{BoardArea})$. |
Coordinate Math (Manhattan Distance Pathing) |
Direct Grid Vectoring |
Map each char to (row, col) where row = char / 5, col = char % 5. Calculate difference Delta R, Delta C. Move Up/Left first to handle 'z' safely. |
Draw the board grid. Write (R, C) coordinates next to each letter. For a target 'c' to 'o', draw the L-shape path and write the 'U/D/L/R' moves. |
Linear String Pass $O(N)$ |
Draw an arrow through the target word. Each letter transition is calculated in constant time $O(1)$. |
Queue and Visited Array for BFS |
None (In-place coordinate calculation). |
| 1139 |
Largest 1-Bordered Square |
Nested loops for every possible (i, j) top-left corner and every possible side length k. Manually check all 4 borders of each square. |
Quadratic Square Sampling $O(N^4)$ |
Draw a grid. Draw a square. For that square, draw 4 arrows tracing the perimeter. Repeat for every size. |
2D Prefix Sums (Left and Up counts) |
Horizontal/Vertical Continuity Map |
Pre-compute two 2D arrays: `left[i][j]` (consecutive 1s to the left) and `up[i][j]` (consecutive 1s above). For a square of size k, just check 4 pre-computed values. |
Draw the grid. In each cell, write two numbers (L, U). To verify a square, look at the bottom-right and check if L and U >= k, then check the top-right and bottom-left cells. |
Cubic Scan $O(N^3)$ |
Draw 3 nested loops: Row, Col, and then a shrinking Size check. Show the $O(1)$ lookup inside the third loop. |
None (Input grid only) |
Two N x N auxiliary matrices. |
| 1140 |
Stone Game II |
Brute force recursion. Try taking x stones where 1 <= x <= 2M, then let the opponent do the same for all possibilities. |
Min-Max Game Tree Explosion |
Draw the pile count. Branch out for X=1 to 2M. For each, branch again for the opponent. $O(2^N)$ complexity. |
DP with Memoization (Suffix Sums) |
Top-Down Decision State Cache |
State is `(index, M)`. Use a 2D DP table. At each state, calculate the max stones the current player can get using the remaining stones (suffix sum) minus the opponent's best outcome. |
Draw a table where Rows = Index, Cols = M. Fill the table using results from sub-problems. Show the "Max" calculation choosing the best path. |
$O(N^3)$ State Space |
Draw a grid N x N. Each cell takes $O(N)$ work to compute the max. |
Exponential Call Stack |
2D DP Array $O(N^2)$. |
| 1141 |
User Activity for the Past 30 Days I |
Fetch all rows, iterate through each, check if within date range, and manually add to a dictionary of sets per day. |
Nested Loop Data Scan |
Draw a massive table of logs. For each log, draw an arrow to a calendar. If it fits the 30-day window, write the User ID in that calendar square. |
GROUP BY + DATEDIFF / BETWEEN |
Time-Window Filtering Pipe |
Filter the dataset where `activity_date` is between '2019-06-28' and '2019-07-27'. Group by `activity_date` and `COUNT(DISTINCT user_id)`. |
Draw a funnel labeled "Date Filter". Draw buckets labeled by Date. Drop unique User IDs into buckets. Count the contents of each bucket. |
Linear Scan $O(N)$ |
Draw a single straight line scanning the table. Each row is either kept or discarded in one step. |
Unordered List of Log Objects |
Hash-based Grouping table. Draw a simple 2-column table: Date | Unique Count. |
| 1142 |
User Activity for the Past 30 Days II |
Loop through all users, count their unique sessions in the date range, then calculate the average in the application code. |
User-by-User Scan |
Draw a list of users. For each, draw a sub-list of their activities. Manually count unique sessions. Sum all and divide by total users. |
Aggregated Subquery / IFNULL |
Multi-Level Aggregation Waterfall |
Step 1: Get `COUNT(DISTINCT session_id)` grouped by `user_id` within the date range. Step 2: Calculate the `AVG` of those counts. Use `IFNULL` to handle zero cases. |
Draw a box for each User. Count their unique sessions. Then, draw a large plus sign connecting all boxes, leading into a division symbol. |
Two-Stage Linear Pass $O(N)$ |
Draw a flow from the Main Table to a "User-Session Summary" table, then to a single "Average" value. |
Application-level hash maps |
Database Hash Aggregator (Memory efficient). |
| 1143 |
Longest Common Subsequence |
Recursion with all possibilities. At each character, either include it (if they match) or skip one character from either string. |
Binary Decision Tree Explosion |
Draw two strings. Branch out: "Skip left char", "Skip right char". Show the 2^(N+M) combinations. |
2D Dynamic Programming (Bottom-Up) |
Grid-Based Dependency Map |
Build an (N+1) x (M+1) table. If `S1[i] == S2[j]`, `dp[i][j] = 1 + dp[i-1][j-1]`. Else, `dp[i][j] = max(dp[i-1][j], dp[i][j-1])`. |
Draw a grid. Label rows with String 1 and columns with String 2. Fill cells. Draw a diagonal arrow for matches and horizontal/vertical arrows for skips. |
Quadratic Grid Filling $O(N x M)$ |
Draw a rectangle of size N x M and shade it completely to show every cell is visited once. |
Exponential Recursion Stack |
2D Matrix (can be optimized to 1D Row). Draw a grid or a single line of boxes being updated. |
| 1144 |
Decrease Elements To Make Array Zigzag |
Try every possible reduction of every element and check if it satisfies the zigzag property. |
State-Space Search Tree |
Draw an array. Branch out into thousands of variations where elements are smaller. $O(2^N)$ logic. |
Greedy (Two Scenarios: Even vs Odd indices) |
Parity-Based Comparative Peaks |
Calculate cost for two cases: 1. Making even indices smaller than neighbors. 2. Making odd indices smaller than neighbors. Return the minimum cost. |
Draw the array twice. In row 1, circle even indices; in row 2, circle odd indices. For each circled item, calculate how much it must drop to be 1 less than its smallest neighbor. |
Linear Scan $O(N)$ |
Draw two separate lines under the array. Each represents one pass through the elements. |
Multiple array copies |
Constant $O(1)$ space using two accumulator variables (cost1, cost2). |
| 1145 |
Binary Tree Coloring Game |
Try picking every possible node as the second player and simulate the entire game to see who wins. |
Node-by-Node Game Simulation |
Draw a tree. For every node, draw a "Game Start" and color the nodes step-by-step. $O(N^2)$ complexity. |
Tree Partitioning / Subtree Counting |
Three-Way Connectivity Analysis |
Find the node 'X' picked by player 1. Calculate size of: 1. Left subtree of X. 2. Right subtree of X. 3. The rest of the tree (Total - Subtree_X). If any > Half, Player 2 wins. |
Draw the tree. Circle node X. Shade its left child's subtree, its right child's subtree, and everything above X in different colors. Compare the sizes of the three shaded regions. |
Single DFS Pass $O(N)$ |
Draw a single line tracing the tree to find node X and count its children. |
Full state-space simulation tree |
Standard DFS recursion stack $O(H)$. |
| 1146 |
Snapshot Array |
Every time `snap()` is called, copy the entire array into a new list. $O(N x \text{Snaps})$. |
Layered Memory Slices |
Draw a thick array. For every snap, draw an identical thick array below it. Show the massive space waste. |
History Tracking (Binary Search on Versions) |
Versioned Timeline Log |
Instead of copying the array, each index stores a list of `(snap_id, value)`. `set()` appends to the log. `get(index, snap_id)` uses binary search to find the latest value <= snap_id. |
Draw an array of buckets. Inside each bucket, draw a list of pairs like `[(0,5), (2,10)]`. For a query at snap 1, show a pointer moving to (0,5). |
Logarithmic Search $O(\log S)$ |
Draw a horizontal array of N size. Above each index, draw a vertical log curve representing the binary search depth. |
Exponential $O(N x S)$ |
Sparse Memory $O(\text{Sets} + \text{Snaps})$. Only store changes. |
| 1147 |
Longest Chunked Palindrome Decomposition |
Recursion with all possible prefix/suffix lengths. Try every possible split point and check if strings match. |
Symmetrical Branching Tree |
Draw a string. Branch out for every possible prefix length that matches a suffix length. $O(N^2)$ or $O(2^N)$ depending on implementation. |
Greedy + Two Pointers (Rolling Hash) |
Shrinking Window Matcher |
Use a pointer for the left prefix and right suffix. As soon as prefix == suffix, "cut" them, increment count by 2, and move inward. If you reach the middle, add 1. |
Draw a long rectangle. Shade a small piece at the left and right. If they match, cross them out and write "2". Move to the remaining inner part. |
Linear Scan $O(N)$ |
Draw a single line with two arrows moving from the ends toward the center meeting in the middle. |
Multiple String Subslices |
Constant $O(1)$ if using indices or $O(N)$ if storing the current chunk string. |
| 1148 |
Article Views I (SQL) |
Fetch all rows, loop through in Python, check `if author_id == viewer_id`, then put result in a set to handle duplicates and sort. |
Row-by-Row Comparison |
Draw the table. For each row, circle the two columns `author_id` and `viewer_id`. If they are the same, write the ID on a side list. |
SELECT DISTINCT + ORDER BY |
Filter and Deduplication Funnel |
Use `WHERE author_id = viewer_id`. Then use `DISTINCT` to remove users who viewed multiple of their own articles. Sort the final output by ID. |
Draw a "Filter Gate" where only rows with matching IDs pass through. Then draw a "Sieve" (Distinct) that only lets one instance of each ID through. |
Linear Scan + Sort $O(N \log N)$ |
Draw a single pass scan followed by a small sorting tree for the unique IDs. |
Unbounded Python Set |
Database-level Hash Set/Sorting buffer. |
| 1149 |
Article Views II (SQL) |
Group by User and Date, then count how many unique articles they viewed. Loop through these results in the app layer. |
Multi-Level Aggregation Scan |
Draw a table. Group it by User. Inside that group, group by Date. Manually count distinct articles. Repeat for all users. |
GROUP BY + HAVING COUNT(DISTINCT) |
Bucketing with Threshold Filter |
`GROUP BY viewer_id, view_date`. Use `HAVING COUNT(DISTINCT article_id) > 1`. Finally, select the distinct `viewer_id` and sort. |
Draw buckets for each `(User, Date)` pair. Count unique articles in each. Cross out buckets with count <= 1. Output the User IDs from remaining buckets. |
$O(N \log N)$ Hash Grouping |
Draw a flow from table into composite key buckets `(User+Date)`, then a filter step. |
Massive Map of Maps |
Optimized Hash Aggregator. |
| 1150 |
Check If a Number Is Majority Element in a Sorted Array |
Linear Scan $O(N)$. Count the frequency of the target number and check if it's > N/2. |
Linear Progress Bar |
Draw an array. Draw an arrow moving from index 0 to N-1, tallying the target number. |
Binary Search (Two Bounds) |
Target Range Squeeze |
Since it's sorted, find the first occurrence (`left`) and last occurrence (`right`) using `bisect_left` and `bisect_right`. If `right - left > N/2`, return true. |
Draw a sorted array. Use two pointers to "find" the start and end of the target number block. Measure the distance between them. |
Logarithmic $O(\log N)$ |
Draw two log curves on the array to locate the boundaries. |
None |
Constant $O(1)$ space. |
| 1151 |
Minimum Swaps to Group All 1's Together |
Check every possible window in the array. Count the number of zeros in each window and find the minimum. |
Sliding Window Matrix Scan |
Draw an array. Draw a box of size K (total 1s). Move the box one step at a time, counting 0s inside. $O(N^2)$ if re-counting. |
Fixed-Size Sliding Window |
Moving Viewport Frame |
Count total 1s (K). Initial window [0, K-1] count 0s. Slide window: add new element, remove old. Update min 0s count. |
Draw an array. Draw a bracket over the first K elements. Slide the bracket, writing the count of 0s below each position. |
Linear Scan $O(N)$ |
Draw a single straight line through the array. |
Multiple sub-array copies |
Constant $O(1)$ space using 3 variables. |
| 1152 |
Analyze User Website Visit Pattern |
Generate all possible 3-sequence combinations for all users, regardless of timestamp order. $O(U \cdot N^3)$. |
Combinatorial Explosion Grid |
Draw all visits. Draw messy overlapping lines forming random triangles of 3 websites. |
Sorting + Combinatorics + Hash Map |
The Ordered Triplet Generator |
Sort visits by time. For each user, use 3 nested loops to extract all valid chronologically ordered 3-sequences. Store in a Set to ensure unique counts per user, then aggregate globally. |
Draw a user's timeline. Drop 3 pointers (i, j, k) moving left-to-right. Every valid triplet drops a "coin" into a global bucket labeled with that triplet pattern. |
Polynomial Scan per User $O(N \log N + U \cdot V^3)$ |
Draw a timeline. For each user's segment, draw a small 3D cube representing the loop volume. |
Lists of all sequences. |
Hash Map for scores. $O(N^3)$ space in worst case. |
| 1153 |
String Transformation Into Another String |
Try every possible character replacement one by one and check if the target string can be reached. |
Recursive Permutation Search |
Draw the starting string. Draw branches for every possible char swap. $O(26^N)$. |
Graph Theory (Out-degree & Cycles) |
Character Mapping Forest |
Map `S1[i] \rightarrow S2[i]`. Each char can map to only one other. If any char maps to two different chars, impossible. If a cycle exists, you need one free character (temp) to break it. |
Draw letters a-z as nodes. Draw arrows from S1 to S2. Check if any node has two outgoing arrows. Check if the graph is a full "26-node cycle" with no spare letters. |
Linear Map Construction $O(N)$ |
Draw a single scan of both strings once, then a 26-node graph check. |
Multiple intermediate string copies |
Hash Map of size 26. Draw a small 2D table of char mappings. |
| 1154 |
Day of the Year |
Manual calculation using a complex series of `if-else` blocks for every month and year combination. |
Decision Tree Flowchart |
Draw a start node. Branch for month 1, 2, 3... Branch again for leap year in Feb. Show the logic nesting. |
Prefix Sum Array + Leap Year Logic |
Accumulative Bucket Fill |
Use a pre-computed array of days per month. Sum days for all months before the target month. Add the day of the current month. Add 1 if it's after Feb in a leap year. |
Draw 12 buckets with numbers (31, 28, 31...). Draw an arrow summing buckets up to the target month. Add a +1 box if leap year condition is met. |
Constant $O(1)$ |
Draw a direct path from input to sum. Total 12 lookups max. |
String parsing overhead |
Constant $O(1)$ integer space. |
| 1155 |
Number of Dice Rolls With Target Sum |
Brute Force Recursion. Try every face (1 to K) for every die (1 to N). |
K-ary Tree Explosion |
Draw a die. Branch into K paths. From each, branch into K more. For N dice, show K^N leaves. |
2D Dynamic Programming (Space Optimized) |
Rolling Sum Probability Grid |
`dp[i][j]` = number of ways to get sum `j` with `i` dice. `dp[i][j] = \sum_{face=1}^{K} dp[i-1][j-face]`. Optimize to 1D array to save space. |
Draw a grid: Rows = Dice, Cols = Sum. For a cell, sum the previous K values in the row above it. Draw a "sliding sum" window to illustrate. |
Quadratic $O(N \cdot K \\text{cdot Target})$ |
Draw a grid N x Target. Shading shows each cell is computed once. |
Exponential Call Stack |
1D DP Array of size Target. |
| 1156 |
Swap For Longest Repeated Character Substring |
Try every possible swap of any two characters in the string and calculate the length of the longest repeated character substring for each. |
Quadratic Swap Matrix $O(N^3)$ |
Draw a string. For index i, swap with every other index j. For each swap, scan the entire string to find the longest block. |
Grouping + Sliding Window/Case Analysis |
Block Compression Map |
Group consecutive characters (e.g., "aaabaaa" rightarrow `[[a,3], [b,1], [a,3]]`). Check if two blocks of the same char are separated by a single char, and if there's a third block to pull a swap from. |
Draw "Islands" of characters. Measure the gap between islands. If gap == 1, add island sizes. Draw a "Bridge" from another island if available. |
Linear Scan $O(N)$ |
Draw a single pass to compress blocks, then a single pass through the compressed list. |
Multiple full string copies |
Frequency Map + List of Groups. Draw a small table of character counts. |
| 1157 |
Online Majority Element In Subarray |
For every query (L, R, threshold), iterate from L to R, count all frequencies using a hash map, and check if any meet the threshold. |
Linear Scan per Query $O(Q x N)$ |
Draw an array. Shade the range [L, R]. Draw a tally chart on the side for that specific range. Repeat for every query. |
Boyer-Moore Voting + Random Sampling / Segment Tree |
Probabilistic Sampling Bucket |
Pick a few random indices in [L, R]. For those values, use a precomputed map of indices to binary search the exact frequency in $O(\log N)$. Threshold ensures high probability of success. |
Draw a "Spotlight" hitting 20 random spots in the range. For each hit, draw a binary search tree to find how many times that number appears in the total array. |
Logarithmic Queries $O(Q x \log N)$ |
Draw Q small log curves over the array length. |
None |
Map of lists (Value rightarrow Sorted Indices). Draw 26 buckets, each holding a sorted list of positions. |
| 1158 |
Market Analysis I (SQL) |
Iterate through Users. For each, run a subquery to count orders in 2019. JOIN with the orders table and group. |
Nested Select Waterfall |
Draw a table of Users. For each row, draw an arrow to the Orders table, filtering by Date manually. |
LEFT JOIN + Conditional Aggregate |
Skeleton-to-Data Mapping |
Start with the `Users` table (the skeleton). LEFT JOIN with `Orders` where year is 2019. Group by `user_id` and count. This ensures users with 0 orders remain in result. |
Draw a column of all User IDs. Draw a bridge to the Orders table. Only cross the bridge if the date is 2019. Count the crossings per user. |
Linear Hash Join $O(U + O)$ |
Draw a single pass through Users and a single pass through Orders to build the count. |
Rowset buffering |
Hash Aggregation for counts. |
| 1159 |
Market Analysis II (SQL) |
For every user, find all items sold, sort by date, find the 2nd one, then check if it matches the user's favorite brand. |
Procedural Sorting Scan |
Draw a user. Draw their sold items. Sort them. Point to item #2. Compare brand. Repeat for every single user. |
Window Function (ROW_NUMBER) + CTE |
Ranked Filtering Pipeline |
Use `ROW_NUMBER() OVER(PARTITION BY seller_id ORDER BY sale_date)` to rank sales. Filter where rank = 2. LEFT JOIN with Users to compare favorite_brand with item_brand. |
Draw the Sales table partitioned into "Seller Folders". Inside each folder, number the files 1, 2, 3... Pull out all files labeled "2" and compare with the User's "Favorite" note. |
$O(N \log N)$ Partition Sort |
Draw a sorting funnel for each partition, then a flat join. |
Complex nested loops in memory |
Partitioned sorting buffers. |
| 1160 |
Find Words That Can Be Formed by Characters |
For every word, sort the word and the `chars` string, then use two pointers to see if the word is a subset. |
Sorting Comparison Matrix $O(W \cdot N \log N)$ |
Draw a word. Sort it: "apple" rightarrow "aelpp". Sort chars: "aelppz". Compare. Repeat for 1000 words. |
Frequency Array (Hash Buckets) |
Inventory Check Visualization |
Count frequencies of `chars` in an array of size 26. For each word, count its frequencies. If word-count <= char-count for all 26 letters, add length to sum. |
Draw a "Pantry" with 26 jars labeled A-Z. Put the number of available letters in each jar. For a word, check if you have enough "ingredients" in each jar to cook it. |
Linear Scan $O(\text{Words} x \text{Length})$ |
Draw a single pass through `chars`, then a single pass through each word. No sorting needed. |
Multiple sorted string copies |
Two fixed-size arrays `int[26]`. Draw two small rows of 26 boxes. |
| 1161 |
Maximum Level Sum of a Binary Tree |
Recursive DFS. For every node, find its level, and then use another DFS or a global map to add its value to the sum of that level. |
Scattered Multi-Scan Diagram |
Draw a tree. For every single node, draw a pointer going back to the root to calculate depth, then update a global table. $O(N \cdot H)$. |
BFS (Queue-based Level Order) |
Level-by-Level Slicing |
Use a queue. While queue not empty, get the current size (number of nodes in this level). Sum them up. Track the max sum and its level index. |
Draw a tree. Draw horizontal dashed lines separating each level. Write the "Sum" at the end of each dashed line. Circle the maximum sum. |
Single Traversal $O(N)$ |
Draw a single continuous line passing through every node once in a horizontal wave pattern. |
Large hash map of level sums |
Queue holding max W (max width of tree) nodes. Draw a horizontal buffer. |
| 1162 |
As Far from Land as Possible |
For every water cell (i, j), run a BFS to find the nearest land cell (x, y). Calculate Manhattan distance. Return the maximum. |
Explosion from Every Pixel |
Draw a grid with land (1) and water (0). For every 0, draw concentric circles expanding until they hit a 1. $O((N^2)$^2) complexity. |
Multi-Source BFS |
Simultaneous Flood Fill |
Put all land cells (1s) into the queue at once. Start BFS from all of them. The "last" water cell reached by the expansion wave is the furthest. |
Draw the grid. Color all 1s red. Draw a single "wavefront" expanding from all red cells into the zeros at the same time. The last zero to be colored is the answer. |
Linear Grid Scan $O(N^2)$ |
Draw a single pass through the grid for the queue, and then each cell is visited once by the wave. |
N/A (Recomputing distance) |
Queue + In-place distance update in grid. Draw a grid where numbers represent "Steps from Land". |
| 1163 |
Last Substring in Lexicographical Order |
Generate all possible substrings, sort them, and return the last one. |
Massive Dictionary List |
Draw a string. List every possible starting point and every possible length. $O(N^2)$ substrings, sorting takes $O(N^2 \log N \cdot N)$. |
Two Pointers (Optimal Suffix Comparison) |
Pointer Competition / Race |
Set i=0, j=1. Compare chars at i+k and j+k. If S[i+k] < S[j+k], i is no longer a candidate for the start; move i past k and restart comparison. |
Draw a string. Place two arrows i and j. If i loses the comparison, jump it ahead. The arrow that survives the longest is the start of the lexicographical max. |
Linear Scan $O(N)$ |
Draw two arrows moving forward. They never look back, ensuring total time is $O(N)$. |
Storage of all substrings $O(N^3)$ |
Constant $O(1)$ extra space (just pointers). |
| 1164 |
Product Price at a Given Date (SQL) |
For every product, run a correlated subquery to find the maximum change date <= '2019-08-16'. If none, set price to 10. |
Nested Select Per Row |
Draw the Products table. For each unique ID, draw a loop back to the Prices table to find the latest valid date. |
UNION ALL + CTE / Subquery |
Filtered Grouping + Default Template |
Query 1: Find the latest price for each product before the date using `RANK()` or `MAX`. Query 2: Find all product IDs NOT in Query 1 and assign price 10. UNION them. |
Draw two boxes: "Updated Items" and "Default Items". Join them into one list. Show the date filter acting as a "Cutoff Wall". |
Linear Hash Aggregation $O(N)$ |
Draw a single pass through the price history and a single pass through the product list. |
Application layer filtering |
Database-level grouping and filtering. |
| 1165 |
Single-Row Keyboard |
For every character in the target word, use `.indexOf()` on the keyboard string to find its position. |
Repeated Linear Search |
Draw a keyboard string. For every letter in "apple", draw an arrow starting from the beginning of the keyboard to find the letter. $O(\text{Word} x \text{Keyboard})$. |
Frequency Map / Index Array |
Instant Location Lookup |
Create an array of size 26 where `index[char]` stores its position on the keyboard. Calculate `abs(current_pos - next_pos)` and update `current_pos`. |
Draw the keyboard. Above it, write the indices 0-25. Create a small table mapping 'a' rightarrow pos, 'b' rightarrow pos. Draw the distance calculation as a subtraction. |
Linear Word Scan $O(N)$ |
Draw a single pass to build the map, and a single pass through the word to sum distances. |
None |
Fixed-size array `int[26]`. |
| 1166 |
Design File System |
Store all paths in a simple Hash Map. To create `/a/b`, manually split the string and check if `/a` exists in the map. |
Flat Map Lookups |
Draw a list of paths. For every new path, draw an arrow scanning the entire list to find the parent string. $O(N)$ string operations. |
Trie (Prefix Tree) |
Hierarchical Directory Tree |
Each node in the Trie represents a folder level. `createPath` traverses the Trie; if the parent node doesn't exist, it fails. If the leaf already exists, it fails. |
Draw a root node `/`. Draw branches for each folder level. Circle nodes that have a "value" assigned. Tracing a path is moving down the branches. |
Path Length Linear $O(L)$ |
Draw a single vertical line from the root down to the depth of the file. L is the number of parts in the path. |
Massive Map of full strings |
Nested HashMaps (Trie nodes). Draw a tree where each node is a box containing a Map of its children. |
| 1167 |
Minimum Cost to Connect Sticks |
Sort the sticks. Pick the two smallest, combine them, add to total, re-sort the entire list. Repeat until one stick remains. |
Repeated Sort Waterfall |
Draw a list of sticks. Combine two. Redraw the whole list sorted. Repeat. Visually show $O(N^2 \log N)$ redundancy. |
Min-Heap (Priority Queue) |
Greedy Merging Funnel |
Add all sticks to a Min-Heap. Pop two smallest, add their sum to `total_cost`, and push the sum back into the heap. Repeat until heap size is 1. |
Draw a binary heap (tree). Circle the two bottom-most nodes. Remove them, draw a new node with their sum, and show it "bubbling up" to its correct spot. |
Heap Operations $O(N \log N)$ |
Draw a N log N curve. Each of the N-1 merges takes log N to re-balance the heap. |
Creating new arrays after each merge |
In-place Min-Heap. Draw a single array representing the heap structure. |
| 1168 |
Optimize Water Distribution in a Village |
Brute force recursion. Try every combination of building a well in a house vs. building a pipe between houses. |
Power Set Explosion |
Draw houses. Draw possible pipes. Branch out: "Well at H1", "Pipe H1-H2", etc. $O(2^N+E)$ complexity. |
Kruskal's / Prim's with Virtual Root |
Augmented Graph Merging |
Create a "Virtual Node" (Node 0) representing the water source. The cost to build a well at house i becomes an edge between Node 0 and Node i. Run MST on this graph. |
Draw houses as dots. Draw a "Star" (Node 0) in the middle. Connect it to all houses with well-costs. Draw pipe edges between houses. Use Kruskal's to pick the cheapest edges. |
$O(E \log E)$ for MST |
Draw a sorting line for edges, followed by a Union-Find $O(E \text{alpha} V)$ sweep. |
Adjacency Matrix $O(V^2)$ |
Union-Find `parent` array + Edge List. |
| 1169 |
Invalid Transactions |
Nested loops $O(N^2)$. For every transaction, check all other transactions for the same name to find time/city conflicts. |
Full Cartesian Comparison |
Draw a list. For each item, draw arrows to every other item in the list. Shade the ones that violate the rules. |
Hash Map Grouping + Sorting |
Grouped Conflict Scanning |
Map each transaction to a User. For each user, sort transactions by time. Use a sliding window or nested loop within the group to check 60-min city conflicts. |
Draw "User Folders". Put transactions inside. For each folder, check if amount > 1000. Then, check pairs of items to see if TimeDiff < 60 and City is different. |
Sorted Group Scan $O(N \log N)$ |
Draw a sorting curve followed by a linear pass within user groups. |
None (In-place loops) |
Hash Map `Name -> List[Transactions]`. Draw a table of folders. |
| 1170 |
Compare Strings by Frequency of the Smallest Character |
For every query, calculate f(s). Then for every word in the dictionary, calculate f(w) and compare. $O(Q x W x L)$. |
Nested String Scans |
Draw a query string. Count 'a's. Scan the whole dictionary. For each word, count its smallest char and compare. Massive redundant work. |
Pre-computation + Binary Search/Suffix Sum |
Frequency Distribution Map |
Step 1: Calculate f(w) for all dictionary words and store frequencies in an array of size 12. Step 2: Use a Suffix Sum on this array so `count[i]` = words with f(w) >= i. |
Draw a frequency array [0...11]. Put counts of words in each. Create a second array (Suffix Sum) where each cell is the sum of everything to its right. Instant lookup. |
Pre-compute $O(W + Q)$ |
Draw a single pass for words, a single pass for Suffix Sum, and a single pass for queries. $O(W + Q)$. |
Repeatedly calculating word frequencies |
Fixed-size array `int[12]` for frequencies. |
| 1171 |
Remove Zero Sum Consecutive Nodes from Linked List |
Nested loops $O(N^2)$. For every node, start a new sum and scan forward. If sum hits 0, delete all nodes between start and current. |
Sub-segment Scanning Waterfall |
Draw a linked list. From each node, draw arrows of increasing length checking for a sum of zero. $O(N^2)$ traversal. |
Prefix Sum + Hash Map (One/Two Pass) |
Pointer Redirection Map |
Store `prefix_sum -> node` in a map. If a sum repeats, it means the nodes in between summed to zero. Point the first occurrence's `next` to the second's `next`. |
Draw the list. Below each node, write the running sum. If you see a sum twice (e.g., '7'), draw a long "bridge" arrow skipping everything between the two '7's. |
Linear Scan $O(N)$ |
Draw a single pass through the list. Each node is visited twice (once to map, once to redirect). |
None (In-place pointer logic) |
Hash Map `int -> ListNode`. Draw a small 2-column table mapping sums to node references. |
| 1172 |
Dinner Plate Stacks |
Use a list of stacks. When pushing, iterate through all stacks from index 0 to find the first one with space. |
Linear Search through Buckets |
Draw a row of buckets. For every "push", draw an arrow starting from the first bucket checking "is full?". $O(N)$ per push. |
Min-Heap + List of Stacks |
Available-Slot Tracker |
Maintain a Min-Heap of indices of stacks that are not full. `push` always uses `heap.top()`. `popAtStack` adds that index back to the heap if it was full. |
Draw a row of stacks. Draw a small "Priority Queue" triangle on the side containing numbers (indices). Take the smallest number to know where to drop the plate. |
Logarithmic Operations $O(\log N)$ |
Draw a log curve for heap rebalancing after every push or pop. |
Unordered list of arrays |
Min-Heap (Tree) + List of Stacks. Draw a binary tree and a 2D grid of plates. |
| 1173 |
Immediate Food Delivery I (SQL) |
Fetch all rows, iterate and check `order_date == customer_pref_delivery_date`. Count them and divide by total. |
Row-by-Row Conditional Tally |
Draw the table. For each row, put a checkmark if the two dates match. Count checkmarks vs total rows. |
SUM(CASE) / AVG(IF) |
Boolean Projection Funnel |
Select `AVG(order_date = customer_pref_delivery_date) * 100`. The boolean comparison returns 1 for True and 0 for False. |
Draw a "Gate". If dates match, a '1' falls through. If not, a '0' falls through. Sum the results and divide by the gate's total throughput. |
Linear Scan $O(N)$ |
Draw a single straight arrow through the table. Total time is $O(N)$. |
Memory-intensive list processing |
Database-level aggregation. Zero extra memory in app layer. |
| 1174 |
Immediate Food Delivery II (SQL) |
For every customer, find all orders, sort by date, find the first one, then check if it was immediate. |
Partitioned Sort & Filter |
Draw a table. Group by Customer. Sort each group. Circle the first row. Check the "Immediate" status. $O(N \log N)$. |
IN Clause with Multi-Column Key |
Ranked Template Filtering |
Use a subquery to find `(customer_id, MIN(order_date))`. Filter the main table for these pairs. Then apply the logic from Q1173. |
Draw a list of (Customer, Earliest Date). Use this as a "Key Card" to unlock only the first-order rows from the massive main table. |
$O(N)$ with Hash Join |
Draw a single pass to find mins, then a single hash-join pass to filter. |
Complex nested maps in Python |
Hash Aggregation for Minimums. |
| 1175 |
Prime Arrangements |
Count primes up to n using a simple loop for each number. Then calculate permutations manually. |
Nested Primality Testing |
Draw numbers 1 to N. For each, draw a loop from 2 to √N checking for factors. $O(N √N)$. |
Sieve of Eratosthenes + Combinatorics |
Grid Pruning & Factorial Blocks |
Use a Sieve to find count of primes P in $O(N \log \log N)$. Primes must go in prime positions, non-primes in non-prime. Result = (P! x (N-P)!) mod 10^9+7. |
Draw a grid 1 to N. Cross out multiples of 2, 3, 5... Count remaining (Primes). Draw two "Factorial Machines" P! and (N-P)! and multiply their outputs. |
Linear-ish $O(N)$ |
Draw a Sieve pass followed by a single loop for factorials. |
List of boolean flags for primality |
Fixed-size boolean array `bool[N+1]`. Draw a row of T/F boxes. |
| 1176 |
Diet Plan Performance |
Nested loops $O(N \cdot K)$. For every day i, sum the calories for the next k days and compare with limits. |
Overlapping Segment Scan |
Draw an array. Draw a bracket of size k starting at every index. Show the redundant additions in the overlap. $O(N \cdot K)$. |
Sliding Window (Fixed Size) |
Rolling Sum Ribbon |
Calculate the sum of the first k days. For each subsequent day, subtract the calorie count of the day that just left the window and add the new day's count. |
Draw an array. Draw a box over the first k elements. Write the sum. Slide the box right: cross out the leftmost number, circle the new rightmost number, update the sum. |
Linear Scan $O(N)$ |
Draw a single straight arrow moving left to right. Each element is added once and subtracted once. |
Multiple sub-array slices |
Constant $O(1)$ space using a `current_sum` variable. |
| 1177 |
Can Make Palindrome from Substring |
For every query (L, R, k), extract the substring, count character frequencies, and check if half the odd-count characters <= k. |
Query-by-Query Extraction |
Draw the string. For each query, draw a box around the range. Draw a 26-row tally table for each box. $O(Q \cdot N)$. |
Prefix Sums + Bitmasking |
XOR Cumulative State |
Pre-compute a `prefix_xor` array where each bit i represents whether the i-th letter has appeared an odd number of times. The XOR of `pref[R]` and `pref[L-1]` gives the odd-count characters in $O(1)$. |
Draw a 1D array of binary numbers (bitmasks). To check a range, draw two masks being XORed. Count the "1" bits in the result (population count) and divide by 2. |
Linear Pre-compute + Constant Query $O(N + Q)$ |
Draw a single pass for the whole string, then a series of direct vertical arrows for each query. |
$O(Q \cdot N)$ for string slices |
$O(N)$ for the bitmask array. Draw a single row of integers. |
| 1178 |
Number of Valid Words for Each Puzzle |
For every puzzle, iterate through every word in the dictionary. Check if the word satisfies both constraints (contains first char, all word chars are in puzzle). |
Brute Force Cartesian Match |
Draw Puzzles on the left, Words on the right. Draw lines from every puzzle to every word. Check constraints for every line. $O(P \cdot W \cdot L)$. |
Bitmasking + Subset Enumeration |
Sub-mask Iteration Loop |
Represent words as bitmasks in a frequency map. For each puzzle, iterate only through its 2^6 possible sub-masks that include the first character's bit. Look up sub-masks in the map. |
Draw a puzzle mask. Draw a tree branching into its sub-masks. For each leaf, draw a pointer to a Hash Map to get the count. |
$O(W \cdot L + P \cdot 2^6)$ |
Draw a linear pass for words and a fixed-depth branching diagram for puzzles. |
None |
Hash Map `int -> frequency` for word masks. |
| 1179 |
Reformat Department Table |
Use 12 separate `SELECT` statements with `UNION` or manual loops in the application layer to pivot the data. |
Vertical-to-Horizontal Splice |
Draw a long vertical list of rows. Show the difficulty in manual reorganization into columns. |
Conditional Aggregation (SUM + CASE) |
Pivot Matrix Projection |
`GROUP BY id`. For each month column, use `SUM(CASE WHEN month = 'Jan' THEN revenue ELSE NULL END)`. The grouping collapses the rows into one. |
Draw a vertical table. Draw 12 funnels labeled by Month. Rows drop into the funnels. If a row is "Jan", it goes to the Jan column, otherwise it drops through as NULL. |
Linear Scan $O(N)$ |
Draw a single pass through the table. Each row is assigned to its horizontal slot instantly. |
Application list processing |
Database Hash Aggregation. |
| 1180 |
Count Substrings with Only One Distinct Character |
Generate all possible substrings $O(N^2)$ and for each, check if all characters are the same $O(N)$. Total $O(N^3)$. |
Substring Matrix Expansion |
Draw a string. Highlight every possible contiguous block. For each, draw an arrow checking for character equality. |
Two Pointers / Math (Sum of N) |
Consecutive Block Counting |
Iterate and find lengths of consecutive identical characters (e.g., "aaa" rightarrow length 3). The number of substrings is sum fracL(L+1)2. |
Draw a string. Draw brackets around blocks of same characters. For a block of size L, write the formula fracL(L+1)2 below it. Sum these values. |
Linear Scan $O(N)$ |
Draw a single arrow sweeping through the string. |
Massive substring storage |
Constant $O(1)$ space using a running counter and a length variable. |
| 1181 |
Before and After Puzzle |
Nested loops $O(N^2)$. For every pair of phrases, check if the last word of phrase A matches the first word of phrase B. |
Pairwise Match Grid |
Draw two lists of phrases. Draw lines from every phrase in list 1 to every phrase in list 2. Circle the lines where words overlap. |
Hash Map (First Word Mapping) |
Adjacency Grouping Table |
Store phrases in a map where the key is the *first word*. Iterate phrases; for each, look up its *last word* in the map to find all possible "After" candidates instantly. |
Draw a table: "First Word" rightarrow [List of Phrases]. Then take a phrase, look at its last word, and draw arrows only to the specific list in your table. |
Linear-ish $O(N \cdot L)$ |
Draw a single pass to build the map, followed by a single pass to join phrases. |
$O(N^2)$ joined strings |
Hash Map for grouping + TreeSet for sorted unique results. |
| 1182 |
Shortest Distance to Target Color |
For every query (index, color), scan left and right from that index until you hit the requested color. $O(Q \cdot N)$. |
Bidirectional Linear Search |
Draw the array. For each query, draw two arrows starting from the query index, expanding outward until they find the color. |
Dynamic Programming (Pre-computed Distances) |
3-Row Distance Matrix |
Pre-compute three arrays (one for each color). Perform one left-to-right pass and one right-to-left pass to find the nearest distance to each color for every index. |
Draw 3 rows below the array (Color 1, 2, 3). In each cell, write the distance to the nearest color of that type. Queries are now $O(1)$ lookups. |
Linear Pre-compute $O(N)$ |
Draw two horizontal passes (Left rightarrow Right and Right rightarrow Left). Total $O(N)$. |
None |
$O(3 \cdot N)$ distance matrix. Draw 3 rows of integers. |
| 1183 |
Maximum Number of Ones |
Try placing 1s in every possible coordinate and check the constraint for every possible subgrid. $O(2^\text{Area})$. |
Backtracking Bitmask Explosion |
Draw a grid. Branch out for every cell: "Place 1" or "Place 0". Show the massive tree for a large grid. |
Greedy + Coordinate Modulo Counting |
Modulo-Space Frequency Map |
Observe that the subgrid constraint repeats. Calculate the frequency of each (r % side, c % side) position in the full grid. Pick the top M positions with highest frequency. |
Draw a mini-grid (size S x S). For each cell in the mini-grid, count how many times it appears in the big grid. Circle the M cells with the biggest counts. |
Linear Grid Scan $O(N \cdot M)$ |
Draw a single pass to count frequencies, followed by a sort of the mini-grid $O(S^2 \log S)$. |
Massive search space |
Frequency array of size S^2. Draw a small square table. |
| 1184 |
Distance Between Bus Stops |
Use a general graph algorithm like BFS/Dijkstra to find the shortest path between two nodes. |
Graph Path Search |
Draw stops as nodes in a circle. Draw a wave expanding from the start stop until it hits the destination. |
Two-Way Summation (Circular Array) |
Clockwise vs Counter-Clockwise Comparison |
Sum the distances from `start` to `destination` (clockwise). The other path is just `Total_Sum - Clockwise_Sum`. Return the minimum. |
Draw a circle of numbers. Highlight the segment between start and end. Shade the remaining part of the circle in a different color. Compare the two. |
Linear Scan $O(N)$ |
Draw a single pass to calculate the total sum and one partial pass for the segment. |
Graph Adjacency List |
Constant $O(1)$ extra space using two sum variables. |
| 1185 |
Day of the Week |
Use built-in library functions like `datetime` or `Calendar` to extract the day. (Not useful for learning the algorithm). |
Opaque Library Black-box |
Draw an input going into a box and an output coming out. No internal visibility. |
Zeller’s Congruence / Sum of Days |
Accumulated Time Blocks |
Calculate total days passed since a known date (e.g., 1971-01-01 was a Friday). Sum days for years, then months (considering leaps), then days. Use `% 7`. |
Draw a timeline starting at 1971. Draw blocks for years passed, then smaller blocks for months. Sum them up and use a "Wheel of 7" to find the day name. |
Constant $O(1)$ |
Draw a direct path from input (D, M, Y) to the result. Total ~35 additions max. |
Library object overhead |
Constant $O(1)$ space. |
| 1186 |
Maximum Subarray Sum with One Deletion |
Iterate through all subarrays. For each, try deleting every single element one by one to find the max. |
Triple Nested Loop $O(N^3)$ |
Draw an array. Draw all possible brackets. Inside a bracket, draw an 'X' over each number sequentially. Massive redundancy. |
Dynamic Programming (Bi-directional Kadane's) |
Two-Way Maximum Gradient |
Compute `max_left[i]` (max subarray sum ending at i) and `max_right[i]` (max subarray sum starting at i). The max with one deletion at i is `max_left[i-1] + max_right[i+1]`. |
Draw the array. Below it, draw two rows. Row 1: Kadane from Left. Row 2: Kadane from Right. To "delete" an index, sum the values from the neighbors in both rows. |
Linear Scan $O(N)$ |
Draw two separate arrows: one moving L rightarrow R and one R rightarrow L. $O(N)$. |
Storage of every possible deletion variation |
Two 1D arrays of size N. Draw two parallel horizontal boxes. |
| 1187 |
Make Array Strictly Increasing |
Try every possible replacement from `arr2` for every element in `arr1` using recursion. |
Exponential Branching Tree $O(2^N \cdot M)$ |
Draw `arr1`. For each element, branch into "Keep" or "Replace with any valid from arr2". Show the tree depth N. |
Dynamic Programming (State: Index + Prev Value) |
Decision Matrix with Sorted Lookup |
`dp[i][prev]` stores min swaps to make `arr1[0...i]` increasing with `arr1[i]` ending at `prev`. Use binary search on `arr2` to pick the smallest valid replacement. |
Draw a table where Rows = Index in `arr1`, Columns = possible values from `arr2`. Mark paths that satisfy arr1[i] > prev. Shade the path with lowest cost. |
Quadratic $O(N \cdot M)$ |
Draw a grid of size N x M. Each cell represents a state transition calculated once. |
Massive recursion stack |
2D DP Table or a Map to handle sparse states. Draw a grid of integers. |
| 1188 |
Design Bounded Blocking Queue |
Use a simple list and check its size in a loop (`while size == capacity`). |
Busy-Waiting Spinlock |
Draw a thread spinning in a circle, hitting a "Full" wall repeatedly. Shows 100% CPU usage for nothing. |
Condition Variables / Semaphores |
Wait-Notify Traffic Signal |
Use two conditions: `notFull` and `notEmpty`. Threads call `wait()` when the queue is full/empty and are "woken up" by the OS when space or items are available. |
Draw a box (Queue) with a fixed size. Draw "Sleep" clouds above blocked threads. Draw a "Bell" (Notify) that wakes them up when an item is added/removed. |
Constant Time $O(1)$ |
Draw a direct flow: Push rightarrow Notify rightarrow Done. No redundant checks. |
Volatile variable polling |
Thread-safe memory buffer (Mutexes). Draw a locked container. |
| 1189 |
Maximum Number of Balloons |
For every "balloon" found, remove the characters from the input string until no more "balloons" can be formed. |
Destructive Subtraction Loop |
Draw the input string. Circle 'b', 'a', 'l', 'l', 'o', 'o', 'n'. Cross them out. Repeat. $O(N^2)$ in worst case string handling. |
Frequency Map / Bottleneck Analysis |
Ingredient Inventory Check |
Count frequencies of 'b', 'a', 'l', 'o', 'n' in the input. For 'l' and 'o', divide count by 2. The minimum value among all these counts is the answer. |
Draw a "Pantry" with jars for b, a, l, o, n. Write the required recipe amounts below (1, 1, 2, 2, 1). Divide your jars by the recipe and find the smallest result. |
Linear Scan $O(N)$ |
Draw a single pass through the string to fill the jars. $O(N)$. |
Multiple string copies |
Fixed-size array `int[26]`. Draw one row of 26 boxes. |
| 1190 |
Reverse Substrings Between Each Pair of Parentheses |
Find the innermost parentheses, reverse that substring, replace it in the original string, and repeat. |
Nested String Reconstruction $O(N^2)$ |
Draw a string. Highlight parentheses. Draw a whole new string with the middle reversed. Repeat for every pair. |
Wormhole Teleportation (O(N) Pre-matching) |
Two-Way Portal Jumping |
Pre-process parentheses to store pairs. Walk through the string; when you hit a bracket, "teleport" to its partner and reverse your walking direction. |
Draw the string. Draw "Portals" connecting '(' and ')'. Trace a line. When you hit a portal, jump to the other side and flip your arrow direction. |
Linear Scan $O(N)$ |
Draw a single continuous line that never visits a character more than twice. $O(N)$. |
Multiple temporary strings |
1D Array for portal indices + StringBuilder. Draw one index-map array. |
| 1191 |
K-Concatenation Maximum Sum |
Actually concatenate the array k times and run standard Kadane's algorithm. $O(N \cdot K)$. |
Giant Array Expansion |
Draw an array. Copy it K times to the right. Show the pointer moving through the entire massive length. $O(N \cdot K)$. |
Kadane's + Total Sum Logic |
Modular Segment Analysis |
If k=1, run Kadane. If k >= 2, run Kadane on the array concatenated twice. If the total array sum is positive, add (k-2) x TotalSum to the result. |
Draw two copies of the array. Run Kadane across the seam. Draw a "Multiplier" box for the remaining (k-2) middle copies if the array sum is > 0. |
Linear Scan $O(N)$ |
Draw an arrow through exactly two copies of the array. Total $O(2N)$ = $O(N)$. |
$O(N \cdot K)$ space for concatenated array |
Constant $O(1)$ extra space using a few sum variables. |
| 1192 |
Critical Connections in a Network |
Remove every edge one by one and run BFS/DFS to see if the graph remains connected. $O(E \cdot (V+E)$). |
Edge Deletion Trial Loop |
Draw a graph. Erase one edge. Check connectivity. Redraw edge. Repeat. Visually show massive redundant traversals. |
Tarjan's / Bridges (DFS Discovery Time) |
Discovery vs. Low-Link Depth |
Use DFS. For each node, track when it was first seen (`tin`) and the lowest-numbered node reachable from it (`low`). If a neighbor's `low` is greater than your `tin`, that edge is a bridge. |
Draw a graph. As you DFS, write two numbers inside each node (tin, low). If an edge leads to a neighbor whose low value is higher than your current tin, circle that edge as a bridge. |
Single Graph Scan $O(V + E)$ |
Draw a single DFS traversal path. Each node and edge is touched exactly once. |
Multiple full graph copies |
Two 1D arrays of size V (`tin` and `low`). Draw two rows of V boxes. |
| 1193 |
Monthly Transactions I (SQL) |
Fetch all rows, iterate in the app layer, group by month and country, and calculate counts/sums manually. |
Procedural Grouping List |
Draw the table. For each row, write its Month and Country on a sticky note. Put sticky notes in folders and count them. |
GROUP BY + DATE_FORMAT |
Bucket Aggregation Funnel |
Group by `DATE_FORMAT(trans_date, '%Y-%m')` and `country`. Use `SUM(IF(state = 'approved', amount, 0))` to get approved totals in one pass. |
Draw a "Folder Machine" where each folder is a `Month-Country` pair. Drop transaction rows into folders. Write the sums and counts on the folder labels. |
Linear Scan $O(N)$ |
Draw a single arrow through the table. Each row is assigned and summed instantly. |
Map of lists in memory |
Database Hash Aggregation. |
| 1194 |
Tournament Winners (SQL) |
Loop through every match, update player scores in a map, sort the map, and pick the top player per group. |
Step-by-Step Tally Scan |
Draw a match list. For each match, draw arrows to Player 1 and Player 2, adding points. Then manually sort every group. |
UNION ALL + Window Functions |
Consolidated Scoreboard Projection |
UNION the scores of first players and second players. Group by player, sum scores. Use `RANK() OVER(PARTITION BY group_id ORDER BY score DESC, player_id ASC)` to find winners. |
Draw two score sheets being merged into one master sheet. Draw buckets for Group IDs. Inside each bucket, draw a sorted list of players. Point to row #1. |
$O(N \log N)$ Sort/Group |
Draw a hash join (mapping match to players) followed by a sorting funnel. |
Unbounded scoreboard objects |
Partitioned sorting buffers. |
| 1195 |
Fizz Buzz Multithreaded |
Use 4 threads with busy-waiting loops checking `if (i % 3 == 0 && i % 5 == 0)`. |
Spinlock Congestion Diagram |
Draw 4 gears spinning independently. Only one gear can "catch" a number at a time, but all 4 are spinning 100% of the time. Wasted CPU. |
Synchronization (Semaphores / Mutex + Conditions) |
Gated Execution Relay |
Use a shared counter. Each thread (Fizz, Buzz, FizzBuzz, Number) waits on a condition that matches its math logic. When a thread finishes, it increments the counter and notifies others. |
Draw 4 parallel tracks. Draw a "Traffic Guard" in front of each. The guard only lets the thread through if the current number is theirs. Then the thread shouts "Next!" to everyone. |
Linear Output $O(N)$ |
Draw a single timeline with perfectly synchronized, non-overlapping blocks of execution. |
Global atomic integers |
Wait Queues (OS-managed). Draw threads "sleeping" until signaled. |
| 1196 |
How Many Apples Can You Put into the Basket |
Try all possible subsets of apples and check if their sum is <= 5000. Return the size of the largest valid subset. |
Exponential Subset Tree |
Draw 3 apples. Branch into 2^3 = 8 possible bags. For N apples, show 2^N branches. $O(2^N)$. |
Greedy (Sorting) |
Fill-to-Capacity Bar |
Sort apple weights. Add apples one by one starting from the lightest until the total weight exceeds 5000. |
Draw an empty box labeled "5000g". List sorted weights. Draw an arrow moving through the list, "dropping" apples into the box until it's full. |
Sorting $O(N \log N)$ |
Draw a sorting funnel followed by a single linear pass. |
None |
In-place sorting of input array. |
| 1197 |
Minimum Knight Moves |
BFS from (0,0) to all directions until target (x, y) is found. |
Radial Explosion (Infinite Grid) |
Draw a grid. From (0,0), draw 8 arrows. From each of those, draw 8 more. Show the massive number of cells visited far away from target. |
BFS with Symmetry + Pruning (or Math) |
Quadrant-Mapped Target Search |
Use the absolute value of x, y to focus on the first quadrant. Prune BFS to stay within a small buffer area around the target. Use a hash set for visited states. |
Draw only one quadrant of the grid. Mark the target. Use a "Compass" showing the 8 moves but cross out moves that go significantly away from (0,0) or target. |
Layered Search $O(|x| \cdot |y|)$ |
Draw a series of concentric "Knight-Move" shapes expanding toward the target. |
Massive state map |
Hash Set of visited (x, y) coordinates. Draw a small 2D table of seen points. |
| 1198 |
Find Smallest Common Element in All Rows |
For every element in the first row, scan every other row to see if it exists there. $O(M \cdot N \cdot N)$. |
Row-by-Row Linear Scan |
Draw 3 rows. Pick the first number. Draw arrows to every number in Row 2, then Row 3. Repeat for all numbers in Row 1. |
Frequency Array / Counting (Rows are Sorted) |
Bucket Frequency Waterfall |
Count the occurrences of every number across all rows using a frequency array. Since rows have unique elements, the first number with `count == total_rows` is the answer. |
Draw a 1D frequency array (indices 1-10000). For each number in the grid, increment its index. The first index to hit the "Total Rows" mark wins. |
Linear Matrix Pass $O(M \cdot N)$ |
Draw a single pass through the entire grid. Every element is touched exactly once. |
Matrix duplication |
Fixed-size array `int[10001]`. Draw one row of boxes. |
| 1199 |
Minimum Time to Build Blocks |
Recursion with memoization trying every possible split/work combination. |
Decision Tree Explosion |
Draw a block. Branch: "Worker splits" or "Worker builds". $O(2^N)$ tree. |
Greedy (Huffman Coding / Min-Heap) |
Bottom-Up Tree Merging |
Use a Min-Heap. Pop the two smallest times a, b. The time to build these is `max(a, b) + split_cost`. Push this back. Repeat until one value remains. |
Draw a forest of nodes (blocks). Pick the two smallest. Connect them to a parent node with value `max(small1, small2) + split`. Repeat until one root exists. |
Heap Operations $O(N \log N)$ |
Draw a sorting timeline followed by a log N rebalancing tree. |
Exponential recursion stack |
Min-Heap (Priority Queue). Draw a binary tree structure. |
| 1200 |
Minimum Absolute Difference |
Nested loops $O(N^2)$. Calculate difference for every possible pair and find the minimum. |
Full Comparison Matrix |
Draw the array. Draw lines connecting every number to every other number. Circle the ones with the smallest gaps. |
Sorting + Adjacent Comparison |
Sorted Gap Scan |
Sort the array. The minimum difference must exist between adjacent elements. Find the min diff in one pass, then collect all pairs with that diff in a second pass. |
Draw a sorted array. Draw brackets between adjacent numbers. Write the difference above each bracket. Circle the smallest difference and collect those pairs. |
Sorting $O(N \log N)$ |
Draw a sorting funnel followed by two linear passes. |
None |
List of pairs. Draw a table of two-element rows. |
| 1201 |
Ugly Number III |
Iterate incrementally from 1. Check every number modulo a, b, and c. Keep a counter and stop when the counter reaches n. |
1D Infinite Number Line Progression |
Draw a long straight horizontal line. Mark tick points 1, 2, 3... N. Draw a small circle over every number divisible by a, b, or c. Write $O(N \\text{cdot min}(a,b,c)$) indicating the length of the line drawn. |
Binary Search on Answer Range + Inclusion-Exclusion Principle |
Venn Diagram (Sets) combined with a Binary Search Decision Tree |
Visualize 3 overlapping circles (sets a, b, c). Pick a 'mid' number. Count how many numbers fall inside the circles up to 'mid' by adding the circles, subtracting the 2-way overlaps, and adding the 3-way overlap back. If count < n, shift your binary search window right. |
Draw a horizontal line with 'low' and 'high' pointers. Below it, draw a classic 3-circle Venn diagram. Label the 3 circles a, b, c. Label the overlaps LCM(a,b), LCM(b,c), LCM(a,c). Label the center LCM(a,b,c). Shift 'mid' on the line based on math formulas derived from the circles. |
Logarithmic Halving Block Diagram |
Draw a massive rectangular block representing 2 * 10^9. Divide it strictly in half. Cross out one half. Divide the remaining half again. Repeat this visually to represent $O(\log(\text{MAX}_\text{ANS})$). Next to it, draw a constant size $O(1)$ box for the LCM math. |
Draw a single, changing variable box labeled "Counter". Next to it, draw a "Current Number" box that increments endlessly. |
Draw exactly 4 static variable boxes representing $O(1)$ space: 'low', 'high', 'mid', and 'ans'. No arrays or dynamic structures needed. |
| 1202 |
Smallest String With Swaps |
Backtracking to generate all valid permutations of the string by performing every allowed swap recursively. Find the lexicographically smallest resulting string. |
Massive Exponential State-Space Tree |
Draw a root node with the initial string. Draw lines radiating downwards for every possible single swap. From those strings, branch out again. Write $O(V!)$ at the bottom to show the factorial branching explosion. |
Disjoint Set Union (DSU) / Connected Components + Sorting |
Graph Visualization (Forest of Trees) to Grouping Buckets |
Treat each string index as a node. Draw edges for allowed swaps. Notice they form connected "islands". Put all characters from one island into a bucket. Sort the bucket alphabetically. Place the sorted characters back into the original empty slots of that island. |
Draw circles representing the indices 0 to N-1. Draw lines connecting indices given in the 'pairs' array. Circle the connected groups. Next to each group, write down the characters at those indices, draw a down-arrow to a sorted list of those chars, and draw arrows mapping them back to the original index circles. |
Near-Linear Graph Traversal + Sorting Blocks |
Write $O(E \cdot α(V)$) for Union Find. Draw an array divided into chunks. Above each chunk, draw a sorting tree (Merge/Quick sort) labeled $O(K \log K)$ where K is the component size. |
Draw a deep, cascading Call Stack memory diagram representing recursive permutation generation, storing massive temporary string states. |
Draw two arrays for DSU: 'parent[]' and 'rank[]'. Below that, draw a Hash Map where keys are Root Nodes (integers) and values are Min-Heaps (Priority Queues) of characters. |
| 1203 |
Sort Items by Groups Respecting Dependencies |
Generate all N! possible orderings of the items. Check each ordering linearly to see if it satisfies both the group constraints and the item-dependency constraints. |
Factorial Explosion Diagram |
Draw slots 1 to N. Below slot 1, draw branches for N choices. Below slot 2, draw N-1 choices. End with a giant red X indicating the $O(N!)$ timeout failure. |
Double Topological Sort (Kahn's Algorithm) |
Two separate Directed Acyclic Graphs (DAGs): Macro (Groups) and Micro (Items) |
Build a graph of just the groups. Build a graph of just the items. Find groups with no incoming prerequisites (indegree 0). Process that group. Inside that group, process items with no prerequisites. Use queues to process level-by-level. |
Draw large circles representing "Groups" with directional arrows between them. Inside each large circle, draw smaller circles representing "Items" with arrows between them. Cross out nodes with 0 incoming arrows one by one, writing the crossed-out nodes into an output list. |
Graph Edge-Trimming Progression |
Draw a set of nodes V and edges E. Show a linear scan bar wiping across them to represent Kahn's algorithm visiting each node/edge exactly once: $O(V + E)$. |
Draw a single large array storing the current permutation, alongside a call stack of size N to track the backtracking state. |
Draw an Adjacency List (Array of Lists) for 'groupGraph' and 'itemGraph'. Next to them, draw two 1D integer arrays for 'groupIndegree' and 'itemIndegree'. Draw two separate Queue structures for Kahn's algorithm BFS state. |
| 1204 |
Last Person to Fit in the Bus (SQL) |
Use a Self-Join or Correlated Subquery. For every person entering the bus, calculate the sum of weights of everyone who entered before or with them. Filter where total <= 1000 and order descending to get the last one. |
Triangular Matrix/Nested Loop Expansion |
Draw a grid. For row 1, draw 1 block. For row 2, draw 2 blocks. For row N, draw N blocks. This triangle shape visually represents $O(N^2)$ query execution time. |
SQL Window Function (Cumulative Sum) |
Rolling Snowball / Single-Pass Accumulation |
Sort the people in order of their 'turn'. Next to each person, keep a running total. Add current person's weight to the previous running total. Stop exactly when the total exceeds 1000. The person right before the stop is your answer. |
Draw a vertical table with columns: 'Turn', 'Weight', and 'Running_Total'. Draw a downward arrow from row 1's Running_Total to row 2, writing "+ Weight" next to it. Put a red line under the row where Running_Total breaches 1000. |
Linear Scan Bar |
Draw a straight array of sorted items. Draw a single arrow scanning from left to right exactly once, representing $O(N \log N)$ (due to the ORDER BY) + $O(N)$ scan. |
Draw two identical instances of the table side-by-side with many criss-crossing arrows connecting row i to rows 1..i, representing a Cartesian explosion. |
Draw a single temporary working column appended to the original table, representing the $O(N)$ memory overhead of the Window Function state. |
| 1205 |
Monthly Transactions II (SQL) |
Perform multiple separate queries (one for approved, one for chargebacks) grouping by month/country, then join them using subqueries or FULL OUTER JOIN on a cross-product of dates. Handles nulls poorly. |
Tangled Web / Spaghetti Graph |
Draw two separate tables. Draw complex, tangled lines connecting rows between them, highlighting the expensive repeated scans of the Transactions table for different conditions. Write $O(N \cdot M)$. |
UNION ALL + Unified GROUP BY (CTEs) |
Data Funneling / Stacking Blocks |
Extract 'approved' transactions into a clean virtual pile. Extract 'chargebacks' (joining with transactions to get country/amount) into another virtual pile. Stack both piles on top of each other (UNION ALL). Push the stacked pile through a single "GroupBy" funnel. |
Draw a box labeled 'CTE_Approved'. Draw a box labeled 'CTE_Chargeback'. Draw arrows from both boxes feeding into a single large funnel labeled 'UNION ALL'. Below the funnel, draw a table with final aggregate columns (sums/counts). |
Parallel Processing Pipelines merging into Linear Aggregation |
Draw two separate linear scans $O(N)$ + $O(M)$ merging into a single hash-map bucket structure representing $O(N+M)$ grouping time. |
Draw multiple temporary database tables materializing in memory, taking up vast redundant disk space. |
Draw a single, unified intermediate table with a 'type' column (distinguishing 'approved' vs 'chargeback') feeding into a Hash-based Aggregation memory structure. |
| 1206 |
Design Skiplist |
Use a standard singly Linked List. To search, insert, or delete, traverse the list from the very head node one-by-one until you find the target or insertion point. |
Endless Train Cars |
Draw a long row of square boxes connected by single arrows pointing right. Trace a path from the first box all the way to the middle, writing $O(N)$ to show the linear distance traveled. |
Probabilistic Multi-Level Linked List |
Express Lanes on a Highway |
Imagine a highway. Level 0 is local traffic (all nodes). Level 1 is an express lane skipping some nodes. Level 2 skips even more. To find a number, start at the highest express lane. Drive until you overshoot, then drop down a level. Repeat until you reach Level 0. |
Draw 3-4 horizontal lines representing levels. Draw circles on the bottom line (Level 0). Flip a coin for each circle to see if it grows a circle directly above it on Level 1. Draw horizontal arrows between circles on the same level, and vertical drop-down arrows. Trace a "staircase" path down and right. |
Logarithmic Depth Grid |
Draw a pyramid of nodes where each layer has roughly half the nodes of the layer below it. Draw a path snaking down. Write $O(\log N)$ representing the height of the level-stack. |
Draw a single array of pointers: `Node next`. |
Draw a single Node object containing an array or vector of pointers: `Node* forward[]`. The length of this array varies randomly per node, representing $O(N)$ total space distributed log-normally. |
| 1207 |
Unique Number of Occurrences |
Use nested loops. For each number, scan the entire array to count its frequency. Store frequencies in a list. Then use another nested loop to check if any two frequencies in the list are identical. |
Cartesian Product Grid |
Draw an array. For every single element, draw a long arrow sweeping across the entire array again. Write $O(N^2)$ to represent the quadratic counting scans. |
Hash Map (Counting) + Hash Set (Uniqueness) |
Frequency Buckets feeding a Unique Filter |
Toss each number into a bucket labeled with its value. Once done, look at the size of each bucket (the frequency). Try to push each frequency size into a "Set" box. If it bounces back (already exists), return false. |
Draw an array mapping to a 2-column table (Key -> Count). Draw arrows from the 'Count' column pointing into a circle labeled 'Set'. If two arrows try to point to the same number in the Set, draw a red X. |
Two Sequential Linear Scans |
Draw an array block of size N. Draw an arrow to a Map block of size M (where M <= N). Draw an arrow to a Set block. Write $O(N)$ as it's a straight-through pipeline with no nesting. |
Draw a bare array and a single integer variable holding the current count state. |
Draw a HashMap (Table of Keys and Values) next to a HashSet (Circle containing only unique Values). Both take up $O(N)$ space. |
| 1208 |
Get Equal Substrings Within Budget |
Generate every possible substring (start index i, end index j). For each, calculate the total absolute difference cost. Find the maximum length substring where the total cost is <= maxCost. |
Triangle of Substrings |
Draw a string. Draw a bracket under index 0. Then brackets under 0-1, 0-2... then 1-2, 1-3. The expanding brackets form a pyramid representing $O(N^2)$ or $O(N^3)$ if re-summing every time. |
Sliding Window (Variable Size) |
Expanding and Contracting Caterpillar |
Imagine a caterpillar eating characters. As it eats the right character, it absorbs its "cost". If its belly gets too full (cost > maxCost), it must poop out the left character (subtract left cost). Keep track of its maximum physical length. |
Draw two parallel strings (s and t). Write the absolute differences between them in an array below. Draw 'L' and 'R' pointers starting at index 0. Move 'R' right, keeping a running sum. If sum > maxCost, move 'L' right. |
Two Independent Runners |
Draw an array. Draw an 'R' arrow moving continuously right. Draw an 'L' arrow occasionally moving right, but never passing 'R' and never moving left. Write $O(N)$ because both pointers only traverse the array once. |
Draw hundreds of short, temporary string snippets generated in memory for every substring check. |
Draw exactly 4 static integer boxes: 'left_pointer', 'right_pointer', 'current_cost', and 'max_length'. Representing $O(1)$ auxiliary space. |
| 1209 |
Remove All Adjacent Duplicates in String II |
Scan the string from left to right. If you find `k` identical adjacent characters, use string slicing to remove them. Restart the scan from the very beginning of the string. Repeat until no more removals can be made. |
Rewinding Tape |
Draw a string. Cross out a chunk of 'k' characters. Draw a massive curved arrow pointing all the way back to index 0. Write $O(N^2 / K)$ to represent the repeated forward scans. |
Stack with Frequency Pairs |
Tetris Blocks (Line Clear) |
Push characters into a vertical tube. If the character matches the one on top, don't add a new block, just increase the top block's "weight/count". If a block's count reaches 'k', it evaporates (POPs) like a cleared line in Tetris. |
Draw a vertical open-top box (a stack). Inside, draw small paired boxes like `['a', 1]`. When reading the next 'a', erase the `1` and write `2`. If it hits `k`, completely erase that pair from the box. |
Single Pass Linear Scan |
Draw a single string. Draw one straight arrow moving purely left-to-right exactly once. Write $O(N)$. |
Draw multiple completely new String arrays being created in memory every time a deletion occurs (due to string immutability in many languages). |
Draw a 2D Array or an Array of Objects representing the Stack, where each element explicitly holds `(character, integer_count)`. Space is $O(N)$. |
| 1210 |
Minimum Moves to Reach Target with Rotations |
Standard DFS without memoization. Recursively explore every possible move (right, down, rotate) from every position, resulting in exploring identical positions multiple times. |
Infinite Cyclic Tree |
Draw a root node. Draw branches for 'Right', 'Down', 'Rotate'. From those, draw branches again. Draw red arrows looping back to previous states, writing $O(4^N)$ to show exponential trap. |
Breadth-First Search (BFS) Shortest Path on a 3D State Graph |
Grid Snake & State-Space Layers |
Treat the 2-cell snake as a single object with a specific state: (tail_row, tail_col, orientation). Start at (0,0,Horizontal). Expand outwards layer by layer in a queue. If a state has been seen, ignore it. |
Draw a small N x N grid. Draw a 2-cell long block. Write down a queue: `[ (r, c, dir, dist) ]`. Pop the front, draw arrows in the grid for valid next positions, and add those new (r, c, dir, dist+1) tuples back to the queue. |
Bounded Grid Area Fill |
Draw a 2D N x N grid. Cut it in half diagonally or shade it. Write `N*N` cells * `2` orientations = $O(N^2)$ maximum possible unique states visited. |
Draw a massively deep, overflowing Recursive Call Stack memory block representing infinite loops. |
Draw a 3D boolean array `Visited[row][col][2]` (where 2 is H or V orientation) alongside a FIFO Queue structure. Space is $O(N^2)$. |
| 1211 |
Queries Quality and Percentage (SQL) |
Run three separate subqueries: one to count total queries, one to sum the ratings/positions, and one to count poor queries. Join all three together by query_name. |
Redundant Table Scans |
Draw the same table three times side-by-side. Draw an arrow scanning down the first table, then the second, then the third. Write $O(3N)$ representing wasted I/O reads. |
Single-Pass Aggregation with CASE/IF statements |
Multi-lane Data Funnel |
Group the rows by query_name. As you process each row in the group, simultaneously add its (rating/position) to a "Quality" bucket, and if rating < 3, add a 1 to a "Poor" bucket. Divide buckets by total rows at the end. |
Draw a table. Circle rows with the same query_name. Next to the circle, draw two buckets: 'Sum(rating/pos)' and 'Count(rating < 3)'. Draw arrows from each row dropping values directly into both buckets simultaneously. |
Single Linear Scan Bar |
Draw one table. Draw a single thick arrow scanning from top to bottom exactly once. Write $O(N)$. |
Draw three large temporary tables floating in memory. |
Draw a HashMap-style structure where Keys are `query_name` and Values are two small integer accumulators taking up minimal memory. |
| 1212 |
Team Scores in Football Tournament (SQL) |
Perform an exhaustive Cartesian product or nested loop joining Teams with Matches on both home_team and away_team conditions separately, then using complex subqueries to map points. |
Matrix Cross-Join |
Draw a Grid where rows are Teams and columns are Matches. Shade in every cell to show the database attempting to match every team against every single match record. Write $O(\text{Teams} \\text{cdot Matches})$. |
UNION ALL for Event Splitting + GROUP BY |
Event Duplication & Scoreboard Funneling |
Take every match and split it into two independent "point-awarding events": one for the home team, one for the away team. Stack all these events together (UNION ALL). Group by team and sum the points. |
Draw a 'Match' row: [Team A vs Team B, Score 2-1]. Draw two arrows splitting out of it: Arrow 1 says "Team A gets 3 points". Arrow 2 says "Team B gets 0 points". Route all these arrows into a final 'Scoreboard' table. |
Map-Reduce Pipeline |
Draw a linear list of matches mapped to exactly 2X events, funneling into a sorted hash-aggregation phase: $O(M + T \log T)$. |
Draw a massive intermediate Cartesian-joined table taking up excessive disk space. |
Draw a single, streamlined derived table (CTE) feeding directly into a memory-efficient grouping hash table. |
| 1213 |
Intersection of Three Sorted Arrays |
Take every element from array 1. For each element, use Binary Search to look for it in array 2. If found, use Binary Search to look for it in array 3. |
Nested Loop Pogo-Stick |
Draw Array 1. For index 0, draw an arrow jumping down to Array 2, bouncing logarithmically, then down to Array 3. Repeat for index 1, 2, etc. Write $O(N \log N)$. |
Three Pointers |
Three Runners on Parallel Tracks |
Place three runners at the start of three tracks (arrays). If they are all standing on the same number, record it and move all three forward. Otherwise, only the runner standing on the smallest number steps forward to catch up. |
Draw three horizontal arrays stacked on top of each other. Draw an upward pointing arrow (pointer) under the first element of each. Look at the three pointed values. Cross out the smallest one(s) and redraw its arrow one step right. |
Synchronized Linear Sweep |
Draw three horizontal lines. Draw three arrows moving rightwards steadily. They never go backward. Write $O(N)$. |
Draw a HashMap storing all 3N elements to count frequencies, wasting spatial efficiency. |
Draw exactly three static integer boxes (p1, p2, p3) taking up $O(1)$ auxiliary memory space. |
| 1214 |
Two Sum BSTs |
For every single node in Tree 1, perform a full recursive search (or binary search) across Tree 2 to look for the complement value (target - node.val). |
Tree-to-Tree Cartesian Search |
Draw Tree 1. Point to the root. Draw a long arrow to the root of Tree 2, showing a full traversal. Move to a leaf in Tree 1, draw another arrow to Tree 2 showing another full traversal. Write $O(N \cdot M)$. |
Inorder Traversal to Hash Set (or Two Pointers on Arrays) |
Tree Flattening / Bucket Filtering |
Traverse Tree 1 and dump all its values into a magic bucket (Hash Set). Then, traverse Tree 2. At each node, ask the bucket: "Do you contain (target - my_value)?". If yes, return true. |
Draw a Tree. Draw arrows pulling all its numbers out and dropping them into a circular 'Set'. Draw the second Tree. Draw arrows from its nodes pointing into the Set, carrying the math equation `(Target - Val)`. |
Sequential Tree Processing |
Draw Tree A being scanned once. Next to it, draw Tree B being scanned once. Write $O(N + M)$ indicating two independent linear time operations. |
Draw deep recursive call stacks running concurrently, potentially up to `O(Height1 + Height2)` space but highly inefficient in time. |
Draw a Hash Set (a circle containing numbers) taking up $O(N)$ space to store Tree 1's values, completely eliminating the need to re-traverse it. |
| 1215 |
Stepping Numbers |
Iterate through every single number from 'low' to 'high'. Convert each number to a string and check if the absolute difference between every adjacent digit is exactly 1. |
1D Number Line Check |
Draw a massive horizontal number line from 'low' to 'high'. For every tick mark, draw a downward arrow into a "checker" box. Write $O(N \cdot \log10(N)$) where N is the difference between high and low. |
BFS / DFS (State Space Generation) |
Directed N-ary Tree (Digit Appending) |
Start with seed digits 1-9. To generate the next valid number, look at the last digit 'd'. Append 'd-1' and 'd+1' (ignoring < 0 or > 9). If the generated number is within [low, high], add it. Stop branching if it exceeds 'high'. |
Draw root nodes 1 through 9. From 1, draw branches to 10 and 12. From 12, draw branches to 121 and 123. Circle the numbers that fall within your target range. Put a red 'X' on branches that go over 'high'. |
Pruned Tree Branching |
Draw a tree that starts wide but rapidly terminates branches with red Xs. Write $O(2^D)$ where D is the number of digits in 'high' (approx log10(high)). |
Draw basic static integer variables, but paired with millions of wasted CPU cycles. |
Draw a Queue (FIFO) array if using BFS, or a Call Stack block if using DFS, storing up to max $O(2^D)$ numbers at once. |
| 1216 |
Valid Palindrome III |
Try deleting 'k' characters in all possible combinations. For each resulting string, use a standard two-pointer approach to check if it forms a valid palindrome. |
Combinatorial Explosion Tree |
Draw the original string. Draw branches branching down for deleting index 0, then index 1, etc. Repeat this branching 'k' levels deep. Write $O(N^k)$ to show the explosive combinations. |
Dynamic Programming (Longest Palindromic Subsequence) |
2D DP Matrix Expansion (Subproblems) |
Find the Longest Palindromic Subsequence (LPS) of the string. If the characters match, inner LPS + 2. If not, max of (left LPS, right LPS). Finally, check if (String Length - LPS Length) <= k. |
Draw a grid with the string characters on both the X and Y axes. Shade the main diagonal with 1s. Draw arrows pointing from (i+1, j-1) to (i, j) for matches, and from left/bottom cells for mismatches. |
Half-Filled Grid Matrix |
Draw a square matrix. Shade only the top-right triangular half, leaving the bottom-left blank. Write $O(N^2)$ representing the number of unique subproblems solved. |
Draw a deep recursive call stack with massive, redundant string slice allocations in memory. |
Draw a 2D integer array `dp[N][N]` or, perfectly optimized, just two 1D integer arrays `curr[]` and `prev[]` representing $O(N)$ space. |
| 1217 |
Minimum Cost to Move Chips to The Same Position |
Pick every single position as a potential target. Loop through all chips, calculating the cost to move them to that target (cost 1 for odd distance, 0 for even). Find the minimum total cost. |
Many-to-One Arrow Fan |
Draw a number line with chips on it. Pick target '1', and draw sweeping arrows from all chips to 1. Then pick target '2' and redraw all arrows. Write $O(N^2)$. |
Parity Counting (Math/Greedy) |
Two Buckets Parity Sorting |
Recognize that moving a chip an even distance (cost 0) means all even positions are effectively the same spot, and all odd positions are the same spot. Just count how many chips are at even vs. odd positions. The answer is the smaller count. |
Draw two large circles labeled "Evens" and "Odds". Go through the array and draw tally marks inside the respective circles. Count the tallies. Circle the smaller number—that's your answer. |
Single Pass Splitter |
Draw an array. Draw one single straight arrow sweeping purely left-to-right. Write $O(N)$. |
Draw a basic array with an integer variable for 'min_cost'. |
Draw exactly two integer variables: `even_count` and `odd_count`. Representing absolute $O(1)$ auxiliary space. |
| 1218 |
Longest Arithmetic Subsequence of Given Difference |
Use a standard LIS (Longest Increasing Subsequence) $O(N^2)$ DP approach. For every element at index 'i', look back at all elements at index 'j' (where j < i) to see if arr[i] - arr[j] == difference. |
Backward-Looking Arcs |
Draw an array. Start at the last element. Draw curved arrows pointing backward to every single preceding element. Move one step left and repeat. Write $O(N^2)$. |
Dynamic Programming + Hash Map |
Hash Map Look-behind Chain |
As you read a number X, ask a Dictionary: "Do you have the length for (X - diff)?". If yes, take that length, add 1, and save it under X in the Dictionary. Keep track of the maximum length seen. |
Draw the array of numbers. Below it, draw a 2-column Hash Map table (Number -> Length). As you process 'arr[i]', draw an arrow pointing into the Hash Map to `arr[i] - diff`, pull its value out, add 1, and write the new row. |
Linear Array to HashMap Mapping |
Draw a straight horizontal arrow scanning the array. From the arrow head, draw a short line dropping directly down into a Map block. Write $O(N)$. |
Draw a 1D DP Array of size N. |
Draw a HashMap (Dictionary) where keys are the array integers and values are the current max subsequence lengths. Takes $O(N)$ space. |
| 1219 |
Path with Maximum Gold |
Run a pure BFS/DFS from every single cell without marking cells as visited properly, leading to infinite loops back and forth between two adjacent gold cells. |
Unconstrained Random Walk |
Draw a grid. Pick a cell. Draw squiggly lines crossing over themselves repeatedly back and forth between two adjacent cells. Write $O(∞)$ due to lack of constraints. |
DFS with Backtracking |
Backtracking Exploration Tree on a Grid |
Start DFS from every cell containing gold. "Mine" the gold (temporarily set to 0 to mark visited). Move to a valid neighbor. When stuck, "un-mine" (restore the value) and step back to try another path. Track the global maximum. |
Draw a grid with numbers. Trace a path with a solid line, crossing out numbers as you go. When you hit a dead end, draw a dotted line retracing your steps backward and un-cross the numbers to try a new route. |
Bounded Path Tree |
Write $O(K \cdot 4^K)$ where K is the number of cells with gold (max 25). Draw a grid highlighting only the K cells, showing limited, bounded branching. |
Draw a massive, overflowing stack memory block resulting from infinite recursion. |
Draw a Call Stack block of maximum depth 'K' (at most 25 frames). The grid itself is modified in-place, resulting in $O(K)$ auxiliary space. |
| 1220 |
Count Vowels Permutation |
Recursively generate all possible strings of length 'n'. For each character added, verify if it follows the vowel transition rules. |
Exponential Branching Tree |
Draw a root. Branch out to a, e, i, o, u. From 'a', branch only to 'e'. From 'e', branch to 'a' and 'i'. Continue for 'n' levels. Write $O(5^N)$ to show the massive explosion. |
Dynamic Programming (State Transitions) |
State Machine / Directed Graph Flow |
Imagine 5 buckets (a, e, i, o, u). In step 1, each has 1 token. In step 2, pour the 'a' tokens into the 'e' bucket, the 'e' tokens into 'a' and 'i', etc. Add up all tokens after 'n' steps. |
Draw 5 nodes labeled a, e, i, o, u. Draw directed arrows between them based on the rules (e.g., arrow from 'a' to 'e'). Next to each node, write the number of paths ending there. Update the numbers level by level using the arrows. |
Linear State Progression |
Draw a horizontal timeline of length 'N'. Above it, draw a constant height block representing 5 states. Write $O(N)$. |
Draw a deep recursive Call Stack of height 'N', holding millions of string prefixes. |
Draw exactly two 1D arrays of size 5: `prev_dp[]` and `curr_dp[]`. Space is strictly $O(1)$. |
| 1221 |
Split a String in Balanced Strings |
Iterate through all possible starting and ending indices (i, j) to form substrings. Count the 'L's and 'R's in each. If equal, increment a counter. |
Nested Triangle Grid |
Draw the string at the top. Below, draw lines for every substring length (size 1, size 2, size 3). For each line, scan and tally L vs R. Write $O(N^2)$. |
Greedy / Running Balance Counter |
Scale / Seesaw Balance |
Walk through the string character by character. If you see 'L', put a weight on the left side of a seesaw (+1). If 'R', put it on the right (-1). Every time the seesaw perfectly balances (counter hits 0), make a cut. |
Draw a horizontal line. Write the string above it. Below it, plot a line graph starting at 0. Go up 1 for 'L', down 1 for 'R'. Draw a thick vertical line every time your graph touches the 0 axis. Count the cuts. |
Single Linear Sweep |
Draw an array of characters. Draw one straight arrow scanning from left to right exactly once. Write $O(N)$. |
Draw an array storing every generated substring, wasting memory. |
Draw exactly two integer variables: `balance` and `split_count`. Takes $O(1)$ auxiliary space. |
| 1222 |
Queens That Can Attack the King |
For every single queen on the board, run an 8-directional search outward to see if it eventually hits the King's coordinate. |
Many-to-One Search Rays |
Draw an 8x8 grid. Mark the King and multiple Queens. From every Queen, draw 8 arrows shooting outward. Show them overlapping and repeating paths. Write $O(Q \cdot 64)$. |
Reverse Search (King outward to Queens) |
Radial Radar Sweep |
Stand on the King's square. Shoot 8 laser beams outward (N, S, E, W, NE, NW, SE, SW). As soon as a laser hits a Queen, record it and stop that specific beam. |
Draw an 8x8 grid. Mark the King. Draw 8 arrows extending outwards from the King. Put a dot on the first Queen each arrow hits, and draw a block immediately behind the Queen to show the arrow stops. |
Constant Time Bounded Rays |
Draw a small 8x8 box. Draw 8 short rays. Write $O(8 \cdot 8)$ = $O(1)$ maximum steps, regardless of the number of Queens. |
Draw an array storing the coordinates of all Queens, actively iterated repeatedly. |
Draw a 2D boolean grid `board[8][8]` to instantly check for Queen presence in $O(1)$ space. |
| 1223 |
Dice Roll Simulation |
Generate all possible dice roll sequences of length 'n' (6^n possibilities). Then loop through each sequence and discard it if it violates the `rollMax` constraints. |
6-ary Combinatorial Tree |
Draw a root node. Branch it out 6 ways (dice faces 1-6). From each, branch out 6 ways again. Mark entire subtrees with a red 'X' if they break the rules. Write $O(6^N)$. |
3D Dynamic Programming |
Constrained Stacking Blocks |
Track three things: `(current_roll_length, last_face_rolled, consecutive_count)`. To build the next roll, you can pick any face 1-6. If it's the same as `last_face`, increment `consecutive_count`. If `consecutive_count` exceeds `rollMax`, that move is blocked. |
Draw a 3D grid or a set of tables. Rows are 'n' (rolls), Columns are 'dice faces' (1-6). Inside each cell, write an array representing 'consecutive counts' (up to 15). Draw arrows from row i to row i+1 adding up the valid previous states. |
3D Bounded Matrix Fill |
Draw a 3D rectangular prism with dimensions N x 6 x 15. Shade it in progressively layer by layer. Write $O(N \cdot 6 \cdot 15)$ which simplifies to $O(N)$. |
Draw an enormous Call Stack block representing depth 'N' recursion with 6 branches each. |
Draw a 3D integer array `dp[N][6][15]` or optimize to just two 2D arrays `curr[6][15]` and `prev[6][15]` for $O(1)$ space. |
| 1224 |
Maximum Equal Frequency |
For every possible prefix of the array, calculate the frequencies of all elements from scratch. Then check if removing exactly one element makes all remaining non-zero frequencies identical. |
Repeated Prefix Scanning |
Draw the array. Bracket the first 2 elements, count frequencies. Bracket the first 3, count from scratch. Bracket first 4, count from scratch. Write $O(N^2)$. |
Double Hash Maps (Count of Counts) |
Frequency Grouping Bins |
Maintain one map of 'Number -> Frequency' and another of 'Frequency -> Count of Numbers with that Frequency'. Update both dynamically as you read each number. Check 3 simple mathematical conditions at each step to see if a valid removal exists. |
Draw two tables side-by-side. Table 1: [Num: Freq]. Table 2: [Freq: How Many]. Read a number. Add 1 to Table 1. In Table 2, subtract 1 from the old Freq and add 1 to the new Freq. Check if Table 2 has exactly 1 or 2 entries that fit the rules. |
Parallel Synchronized Hashing |
Draw an array. Draw a single horizontal arrow scanning right. Draw two boxes below it updating instantly on each step. Write $O(N)$. |
Draw a completely new Hash Map being created and destroyed for every single prefix check. |
Draw exactly two Hash Maps (or fixed-size Arrays if max value is known) taking up $O(N)$ space, updated in-place. |
| 1225 |
Report Contiguous Dates (SQL) |
Using a recursive CTE or a nested subquery to check the day before and day after for every single row to see if the status (failed/succeeded) changes. |
Double-Ended Date Scanning |
Draw a calendar. For every date, draw two magnifying glasses looking at the previous and next days. Write $O(N^2)$ due to row-by-row comparisons. |
Gaps and Islands (Row Number Difference) |
Floating Island Groups |
Assign a row number to all dates. Assign a second row number to dates within each category (succeeded/failed). Subtract the two row numbers. Dates in the same contiguous block will have the same "Difference Constant". Group by this constant. |
Draw a table with columns: Date, Status, RowNum_Total, RowNum_Group. Create a new column "Diff" (Total - Group). Circle all rows where the "Diff" value is identical—these are your islands. |
Linear Partitioning |
Draw a straight timeline. Draw vertical bars at every date change. Write $O(N \log N)$ (due to sorting by date). |
Draw a deep stack of recursive pointers checking neighboring rows. |
Draw a single temporary table with 3 additional integer columns used for the subtraction logic. |
| 1226 |
The Dining Philosophers |
Allow every philosopher to pick up their left fork whenever they want. This leads to a circular wait where everyone has one fork and no one can eat. |
Cyclic Lock Diagram |
Draw 5 circles (philosophers) and 5 lines (forks) between them. Draw an arrow from every philosopher to their left fork. Note the closed loop—this is Deadlock. |
Resource Hierarchy / Semaphores |
The "Odd-Man Out" Protocol |
Either limit the number of philosophers at the table to 4, or force one philosopher to pick up forks in the opposite order (Right then Left) while others do (Left then Right). This breaks the symmetry. |
Draw the 5 circles. Draw a "Permission Slip" (Semaphore) in the middle. Only 4 philosophers can hold the slip at once. Trace the fork-grabbing sequence and show how at least one person is always guaranteed both forks. |
State Transition Graph |
Draw a graph showing states (Thinking, Hungry, Eating). Show that no state leads to a sink-hole (deadlock). Write $O(1)$ per philosopher action. |
Draw 5 threads spinning in an infinite 'while(true)' loop, consuming CPU cycles. |
Draw a Mutex array of size 5 and a single "Chaperone" Semaphore with a counter of 4. |
| 1227 |
Airplane Seat Assignment Probability |
Simulate the entire process using recursion: f(n) = frac1n(1 + sum_i=2^n-1 f(i)). This computes the probability for every possible seat the first person might take. |
Recursive Branching Probability Tree |
Draw a root (Person 1). Draw N branches for seats 1 to N. For the "wrong" seats, branch again. The tree grows massively deep. Write $O(N!)$ or $O(N^2)$ with memoization. |
Mathematical Induction / Constant Observation |
The Coin Flip Simplification |
Realize that for any n > 1, the first person's choice eventually boils down to whether they (or someone they displaced) takes seat 1 or seat n. It is a symmetric 50/50 chance. |
Write n=1 rightarrow 1.0. Write n=2 rightarrow 0.5. Write n=3 rightarrow 0.5. Draw a big arrow pointing to 0.5 for all n > 1. |
Constant Time Result |
Draw a single dot. Write $O(1)$. The calculation doesn't depend on the size of n. |
Draw a huge memoization table or recursion stack of size N. |
Draw a single return statement. Space is $O(1)$. |
| 1228 |
Missing Number In Arithmetic Progression |
Scan the array and calculate the difference between every pair of adjacent numbers. The most frequent difference is the step. Scan again to find where the step is violated. |
Double Linear Pass |
Draw the array. Draw small "jump" arrows between every number. Write the difference above each arrow. Find the one that's double the others. Write $O(N)$. |
Binary Search (Range-based Gap Detection) |
Binary Search "Middle Check" |
Compare the value at `mid` with the expected value `first + mid * diff`. If they match, the gap is to the right. If they don't, the gap is to the left (or at mid). |
Draw a line with `L`, `M`, and `R` pointers. Calculate `expected_mid`. If `actual_mid == expected_mid`, move `L` to `M+1`. Repeat until `L == R`. |
Logarithmic Halving |
Draw a block of length N. Divide it in half, then half again. Write $O(\log N)$. |
Draw a standard array in memory. |
Draw 3 integer variables: `low`, `high`, `mid`. Space is $O(1)$. |
| 1229 |
Meeting Scheduler |
Compare every single time slot in Person 1's list with every single time slot in Person 2's list to check for an overlap of at least length `duration`. |
Cartesian Product Overlap Check |
Draw two rows of intervals. Draw a line from the first interval of Row 1 to every interval of Row 2. Repeat for all. Write $O(N \cdot M)$. |
Two Pointers on Sorted Intervals |
Parallel Scanning Sliders |
Sort both lists. Place a pointer at the start of both. Check the intersection: `max(start1, start2)` to `min(end1, end2)`. If the intersection >= duration, you're done. Otherwise, move the pointer that ends earlier. |
Draw two horizontal timelines with shaded intervals. Place an arrow under the first interval of each. If they don't overlap enough, move the arrow that points to the interval ending first. Trace the "overlap window". |
Linear Scan of Sorted Data |
Draw two timelines. Draw two arrows moving strictly left-to-right. Write $O(N \log N + M \log M)$ due to the initial sort. |
Draw a massive list of all possible overlapping pairs. |
Draw two sorted arrays and two integer pointers. Space is $O(1)$ (or $O(N+M)$ depending on sort implementation). |
| 1230 |
Toss Strange Coins |
Generate all 2^N possible outcomes (Heads/Tails) for N coins. For each outcome, calculate its probability and sum the probabilities where exactly 'target' coins are Heads. |
Binary Decision Tree Explosion |
Draw a root. Branch out H and T for coin 1. For each, branch out H and T for coin 2. Continue for N coins. Write $O(2^N)$ to show the geometric growth of leaves. |
Dynamic Programming (Linear State) |
Probability Distribution Layering |
Use a DP array where `dp[i]` is the probability of getting i heads. For each new coin with probability p, the new `dp[i]` is: (Prob it was already i and this coin is Tails) + (Prob it was i-1 and this coin is Heads). |
Draw a row of N coins. Below, draw an array of size `target + 1`. For each coin, draw arrows from `dp[i]` and `dp[i-1]` to a new row, representing the "contribution" of the current coin's P(H) and P(T). |
2D Grid Reduction |
Draw an N x Target grid. Show each cell being computed from two cells in the previous row. Write $O(N \\text{cdot Target})$. |
Draw a massive list of 2^N strings or sequences in memory. |
Draw a single 1D array of size `Target + 1`. Show values updating in-place. Space: $O(\text{Target})$. |
| 1231 |
Divide Chocolate |
Try every possible way to cut the chocolate into K+1 pieces using recursion/backtracking. Find the maximum of the minimum sweetness among all combinations. |
Combinatorial Partitioning Tree |
Draw a bar of chocolate. Draw lines representing cuts at every possible index. Show the recursive branching for K cuts. Write $O(N^K)$. |
Binary Search on Answer (Range) |
The "Greedy Satiety" Threshold |
Guess a sweetness value X. Walk through the chocolate and cut a piece as soon as its sweetness >= X. If you can make >= K+1 pieces, X might be too small. If not, X is too large. |
Draw a horizontal line for the range [min_sweetness, total_sweetness]. Pick a 'Mid'. Below it, draw the chocolate array and group elements into chunks that sum to 'Mid'. If chunks >= K+1, shift 'Low' to 'Mid'. |
Logarithmic Search + Linear Scan |
Draw a shrinking range [L, R] alongside a single horizontal scan arrow. Write $O(N \log(\text{Total}_\text{Sweetness})$). |
Draw a deep recursion stack representing the search for all cut combinations. |
Draw 4 integer variables: `low`, `high`, `mid`, `current_sum`, and `count`. Space: $O(1)$. |
| 1232 |
Check If It Is a Straight Line |
Calculate the slope between every possible pair of points. If all slopes are identical, they are on a straight line. |
All-Pairs Slope Comparison |
Draw 5 points. Draw lines connecting 1-2, 1-3, 1-4, 1-5, then 2-3, 2-4... Write $O(N^2)$ to represent the nested comparisons. |
Cross-Multiplication (Slope Equality) |
Reference Vector Alignment |
Take the first two points to define the "reference slope". For every subsequent point, check if the slope it forms with the first point matches the reference. Use dx_1 * dy_2 = dx_2 * dy_1 to avoid division by zero. |
Draw an (x, y) coordinate plane. Draw the first two points and a dashed line through them. For each new point, draw a small triangle to show its dx/dy relative to Point 0. Check the cross-product math. |
Single-Pass Validation |
Draw a sequence of points. Draw one continuous arrow connecting Point 0 to 1, then 0 to 2, then 0 to 3. Write $O(N)$. |
Draw a list of all calculated slope values (floats) in a temporary array. |
Draw four integer variables to store dx_1, dy_1, dx_i, dy_i. Space: $O(1)$. |
| 1233 |
Remove Sub-Folders from the Filesystem |
For every folder, compare it with every other folder in the list. If folder A starts with folder B followed by a '/', folder A is a sub-folder and should be removed. |
Nested String Prefix Matching |
Draw a list of strings. Draw an arrow from string 1 to every other string. Draw an arrow from string 2 to every other string. Write $O(N^2 \cdot L)$ where L is max path length. |
Sort + Prefix Check (or Trie) |
Alphabetical Path Pruning |
Sort the folders alphabetically. Sub-folders will now always appear immediately after their parent folder. Scan the sorted list; if the current folder starts with the "last saved parent" + '/', skip it. |
Draw a sorted list of paths. Draw a "Last_Parent" box. Move an arrow down the list. If the arrow points to a string containing "Last_Parent/", draw a red line through it. If not, update "Last_Parent". |
Sorted Linear Scan |
Draw a sorting block followed by a single linear scan arrow. Write $O(N \cdot L \log N)$. |
Draw multiple temporary sub-string copies being created for comparisons. |
Draw a single Result List and one string variable for the `last_parent`. Space: $O(N \cdot L)$ for output. |
| 1234 |
Replace the Substring for Balanced String |
Generate every possible substring. For each, check if removing it allows the remaining characters (Q, W, E, R) to be balanced (each occurring exactly N/4 times). |
Substring Exhaustion |
Draw a string of length N. Draw brackets for every possible start and end point. For each bracket, count the characters inside. Write $O(N^3)$. |
Sliding Window (Shrinkable) |
Two-Pointer Requirement Gap |
First, count the total frequency of Q, W, E, R. Identify which characters exceed N/4. Use a sliding window [L, R] to find the smallest substring that contains all those "excess" characters. |
Draw the string. Above it, write the "Excess" counts (e.g., Q: 2, W: 1). Draw L and R pointers. Move R until the window contains the excess. Then move L to shrink the window as much as possible while still holding the excess. |
Linear Window Crawl |
Draw a string with L and R arrows. Show R moving right, then L moving right. Each moves at most N times. Write $O(N)$. |
Draw thousands of substring objects being stored in memory. |
Draw a frequency array of size 4 (or a small Hash Map) and two integer pointers. Space: $O(1)$. |
| 1235 |
Maximum Profit in Job Scheduling |
Recursively explore two choices for every job: include it (and skip all overlapping future jobs) or exclude it. Without memoization, this explores every possible subset. |
Overlapping Job Subsets Tree |
Draw Job A, B, C. Branch from A: "Take A" (points to first non-overlapping job) and "Skip A" (points to Job B). Repeat for all. Write $O(2^N)$. |
DP + Sorting + Binary Search |
Weighted Timeline Chain |
Sort jobs by end time. `dp[i]` is max profit using jobs up to index `i`. For a new job, search (Binary Search) for the last job that ended before this one started. `dp[curr] = max(dp[prev_index] + profit, dp[curr-1])`. |
Draw a timeline. Plot jobs as horizontal bars. Below, draw an array `dp`. For a job ending at time T, draw a dashed arrow back to the nearest previous job end time, then a plus sign for profit. |
Log-Linear Growth Curve |
Draw an N log N curve representing the initial sort, followed by a staircase representing N steps of Binary Search. Write $O(N \log N)$. |
Draw an enormous call stack representing the 2^N recursive paths. |
Draw a sorted 2D array of jobs and a 1D DP array of size N. Space: $O(N)$. |
| 1236 |
Web Crawler |
A standard DFS/BFS that explores every single link it finds, regardless of the hostname, potentially trying to crawl the entire internet. |
Global Web Graph Expansion |
Draw a central node. Draw hundreds of lines out to "other" sites. Show no boundary. Write $O(V + E)$ where V is the entire web. |
BFS/DFS with Hostname Filtering |
Bounded Domain Bubble |
Start at the seed URL. Extract its hostname. Use a queue/stack to visit neighbors. Before adding a neighbor to the queue, check: "Is its hostname the same?". If no, discard immediately. Use a Set to avoid cycles. |
Draw a large circle labeled "Hostname". Place the start URL inside. Draw arrows to links. If an arrow points outside the circle, draw a red "X" through the link. Use a "Seen" checklist box. |
Subgraph Traversal |
Draw a small connected cluster of nodes. Highlight that only nodes inside this specific cluster are touched. Write $O(N)$ where N is links within the same domain. |
Draw a memory block that grows indefinitely as it discovers new domains. |
Draw a FIFO Queue and a HashSet of "Seen" strings. Memory is proportional only to valid URLs found. Space: $O(N)$. |
| 1237 |
Find Positive Integer Solution for a Given Equation |
Nested loops iterating x from 1 to 1000 and y from 1 to 1000. Calculate f(x, y) for every pair and check if it equals z. |
Full Grid Scan |
Draw a 1000x1000 grid. Color every single cell to show it was checked. Write $O(X \cdot Y)$. |
Two Pointers on Monotonic Surface |
Staircase Descent |
Start at (x=1, y=1000). If f(x, y) > z, y must decrease. If f(x, y) < z, x must increase. This traces a single path from top-left toward bottom-right. |
Draw a coordinate axis. Start a point at top-left. Draw a jagged line moving only Right or Down. If you hit a solution, mark with a star. Write $O(X + Y)$. |
Boundary Trace Line |
Draw a square. Draw a single diagonal-like line cutting through it. Write $O(1000 + 1000)$. |
Draw a basic list of solutions. |
Draw two integer variables (x and y). Space: $O(1)$ (excluding output). |
| 1238 |
Circular Permutation in Binary Representation |
Generate all 2^n binary numbers. Try every possible permutation of these numbers until you find one where adjacent values (and the ends) differ by exactly one bit, starting at `start`. |
Hamiltonian Path Search (Exponential) |
Draw nodes for 00, 01, 10, 11. Draw lines between all. Show a path-finding search attempting every backtrack. Write $O((2^n)$!). |
Gray Code Generation + Bitwise XOR |
The "Reflected Binary" Mirror |
Generate the standard Gray Code sequence of length 2^n (using i oplus (i gg 1)). To start at `start`, XOR every element in the sequence with `start`. This preserves the 1-bit difference property. |
Write 0, 1. Mirror them: 0, 1 | 1, 0. Add prefix: 00, 01, 11, 10. Then XOR each by `start`. Show how the 1-bit difference stays constant. |
Linear Bitwise Transformation |
Draw a list of 2^n slots. Draw an arrow pointing to a bit-shifter and an XOR gate. Write $O(2^n)$. |
Draw massive backtracking stacks and path-storage lists. |
Draw a single array of size 2^n. Space: $O(2^n)$. |
| 1239 |
Maximum Length of a Concatenated String with Unique Characters |
Try every possible subset of the given strings. For each subset, combine them and check if all characters are unique. |
Power Set Tree |
Draw strings ["un", "iq", "ue"]. Branch: "Take un" / "Skip un". From "Take un", branch "Take iq" / "Skip iq". Write $O(2^N)$. |
Bitmasking + Backtracking (Pruned) |
32-bit Integer Filters |
Convert each string into a bitmask (bit 0 for 'a', bit 1 for 'b'). If a string has internal duplicates, discard it. Recursively combine masks using `(mask & next_mask) == 0`. Keep track of max bits set. |
Draw an array of strings. Below, draw 26-bit binary numbers. Use an AND (&) gate symbol between two bitmasks. If output > 0, draw a red line. If 0, show them combining via OR (|). |
Pruned Recursive Forest |
Draw a tree where many branches are cut early due to bitmask collisions. Write $O(2^N)$ (worst case) but effectively much faster. |
Draw a call stack storing many temporary string concatenations. |
Draw a list of integers (bitmasks) and a single max_length integer. Space: $O(N)$. |
| 1240 |
Tiling a Rectangle with the Fewest Squares |
Recursively try to place every possible size of square (1x1 to min(N,M)x(N,M)) starting from the first empty cell. Explore all valid tilings and count the squares. |
Exponential State Space Tree |
Draw an N x M grid. Branch out for placing a 1x1, then a 2x2. Within those, branch again. Note the massive repetition of grid states. Write $O(\text{min}(N,M)$^(N*M)). |
Backtracking with Pruning & Skyline State |
Grid "Skyline" Contour Filling |
Find the first empty cell (lowest row, then lowest column). Try placing a square of size 'k'. Update the "skyline" (height array of the rectangle). If current count >= best found, stop this branch immediately. |
Draw an N x M grid. Shade the filled areas. Draw a bold line tracing the top "edge" of the filled area (the skyline). Write down a 1D array representing heights. Show squares being "dropped" into the lowest valleys of the skyline. |
Pruned Backtracking Tree |
Draw a tree where most branches are cut very high up by a horizontal "Best Count" line. Write Exponential (Heuristic). Small constraints (N,M < 14) allow this. |
Draw a massive stack of full 2D grid copies. |
Draw a single 1D "heights" array of size M and a recursive call stack of depth N*M. Space: $O(M)$. |
| 1241 |
Number of Comments per Post (SQL) |
Using correlated subqueries in the SELECT clause to count comments for every unique parent_id found in the submissions table. |
Repeated Table Scans (O(N*M)) |
Draw two copies of the Submissions table. For every row in Table A, draw an arrow scanning the entire Table B. Write $O(N^2)$. |
LEFT JOIN + GROUP BY + DISTINCT |
Relational Set Intersection |
Create a set of unique "Posts" (parent_id is null). Create a set of "Comments" (parent_id is not null). Left Join them on post_id = parent_id. Group by post_id and count unique comment_ids. |
Draw two circles (Sets). Circle 1: Unique Post IDs. Circle 2: Comment rows. Draw arrows from Circle 2 entries to Circle 1. Group the arrows by their target. Use a "Distinct" filter on the arrows. |
Sorted/Hash Join Projection |
Draw a sort-merge symbol (two sorted lists merging) or a hash-map scan. Write $O(N \log N)$. |
Draw multiple temporary result sets for each sub-query. |
Draw a single Hash Table in memory storing Post IDs as keys and counters as values. |
| 1242 |
Web Crawler Multithreaded |
A sequential BFS crawler that visits one URL at a time, waiting for each network request to complete before moving to the next. |
Single-File Queue Progression |
Draw a horizontal queue. Draw a single person picking one URL, walking to a "Server" box, and coming back. Write $O(N \\text{cdot Latency})$. |
Thread Pool + Thread-Safe Queue/Set |
Parallel Worker Pipelines |
Use a shared Thread-Safe Queue and a Concurrent Set (Seen URLs). Multiple "Workers" grab URLs from the queue, fetch links, and push them back if they match the hostname and haven't been seen. |
Draw a large "Work Queue" in the center. Draw 4-8 "Worker" circles around it. Draw arrows of workers taking tasks from the queue and pushing new tasks back. Use a central "Seen" checklist. |
Concurrent Overlapping Latency |
Draw several parallel bars representing time. Show the "Network Latency" blocks overlapping across different threads. Write $O(N \\text{cdot Latency} / \text{Threads})$. |
Draw a single queue and a single set. |
Draw a BlockingQueue, a ConcurrentSet, and a FixedThreadPool structure. Space: $O(N)$. |
| 1243 |
Array Transformation |
Create a new copy of the array for every single day. Iterate through the array and apply rules. If no changes occur, stop. |
Repeated Simulation Cycles |
Draw the array. Below it, draw a modified copy. Below that, another copy. Draw a big loop arrow until the "day before" matches the "current day". Write $O(\text{Days} \cdot N)$. |
In-Place Simulation (Two Pointers/Copying) |
Accordion Oscillation |
Use two arrays: `current` and `next`. In each step, check if an element is greater than its neighbors (shrink) or smaller (grow). Swap `current` and `next` until they are identical. |
Draw the array values as vertical bars (like a bar chart). Draw arrows showing bars getting shorter or taller based on neighbors. Stop when the "silhouette" of the bars stays the same. |
Linear Convergence Pass |
Draw a sequence of N operations. Write $O(N \cdot \\text{text}{\text{max}_\text{val}})$ because an element can only change at most `max_val` times. |
Draw many copies of the array being allocated in memory. |
Draw exactly two arrays: `arr` and `temp`. Space: $O(N)$. |
| 1244 |
Design A Leaderboard |
Store everything in a simple List. For `top(K)`, sort the entire list and sum the first K elements. For `addScore`, find the player in the list and update. |
Global Sorting Scan |
Draw a long list of players. For every `top(K)` call, draw a "Sorting Machine" processing the whole list. Write $O(N \log N)$ per query. |
Hash Map + Balanced BST (or TreeMap/SortedSet) |
Frequency-Ordered Tree |
Use a HashMap for `O(1)` access to player scores. Use a TreeMap (or similar) where the Key is the `Score` and the Value is the `Count` of players with that score. For `top(K)`, iterate backwards through the tree. |
Draw a HashMap: [ID -> Score]. Next to it, draw a Binary Search Tree where nodes are sorted by Score. For `addScore`, update the Map and move the node in the Tree. For `top(K)`, trace the right-most (largest) nodes. |
Logarithmic Updates + K-Step Fetch |
Draw a tree of height log N. Show an update path going down one branch. Write $O(\log N)$ for updates and $O(K)$ for top scores. |
Draw a simple array of objects. |
Draw a HashMap and a TreeMap (Red-Black Tree structure). Space: $O(N)$. |
| 1245 |
Tree Diameter |
For every single node in the tree, start a BFS/DFS to find the farthest node from it. The diameter is the maximum distance found across all starts. |
All-Pairs Shortest Path Scan |
Draw a tree. Pick Node 1, color all reachable paths. Pick Node 2, color all paths again. Repeat for N nodes. Write $O(N^2)$. |
Double BFS (or DFS with Height Tracking) |
The "Elastic String" Stretch |
1. Pick a random node. 2. Find the farthest node from it (let's call it 'A'). 3. Find the farthest node from 'A' (let's call it 'B'). The distance between A and B is the diameter. |
Draw a tree. Start at any node, draw an arrow to the leaf furthest away. From that leaf, draw a long bold arrow across the tree to the opposite leaf. Label the bold arrow "Diameter". |
Linear Edge Traversal |
Draw a tree. Show two distinct colored sweeps across all nodes. Write $O(N)$. |
Draw a massive matrix of distances for all node pairs. |
Draw an Adjacency List and a Queue for BFS or a recursion stack for DFS. Space: $O(N)$. |
| 1246 |
Palindrome Removal |
Try every possible subset of palindromes to remove recursively. Explore all permutations of removals to see which leads to the minimum steps. |
Exponential Recursive Explosion |
Draw a string. Branch out for every possible sub-palindrome removal. From the resulting fragmented strings, branch again. Write $O(2^N)$. |
Interval Dynamic Programming |
Sub-Interval Collapsing Matrix |
Define `dp[i][j]` as the min steps to remove substring `s[i...j]`. If `s[i] == s[j]`, they can potentially be removed along with the last palindrome in the inner interval. |
Draw an N x N grid with indices on both axes. Fill the diagonal (length 1) with 1s. Then fill length 2, then length 3. For each cell, show it combining results from smaller inner intervals. |
Half-Matrix Filling (Diagonal-wise) |
Draw a square grid. Shade only the upper triangle. Draw arrows showing the "bottom-up" filling from diagonal to corner. Write $O(N^3)$. |
Draw a recursive tree with millions of string copies. |
Draw a 2D integer array `dp[N][N]`. Space: $O(N^2)$. |
| 1247 |
Minimum Swaps to Make Strings Equal |
Use backtracking to try all possible swaps of characters between strings `s1` and `s2` at every index to find the minimum path to equality. |
Backtracking Decision Tree |
Draw two strings. Draw branches for every possible swap (s1[i] with s2[j]). Show the tree getting deeper until strings match. Write $O(2^N)$. |
Greedy / Parity Counting |
Mismatch Pair Bucketing |
Ignore matching characters. Count pairs of "x-y" (s1 has x, s2 has y) and "y-x". Two "x-y" pairs take 1 swap. Two "y-x" pairs take 1 swap. One of each takes 2 swaps. If total mismatches are odd, return -1. |
Draw two columns: "s1" and "s2". Circle indices where they differ. Tally these as "x-y" or "y-x". Group them into pairs. Write "+1" for same-type pairs and "+2" for mixed pairs. |
Single Linear Pass |
Draw two arrays. Draw a single arrow scanning both simultaneously. Write $O(N)$. |
Draw a deep recursion stack storing many string state variations. |
Draw exactly two integer counters: `xy_count` and `yx_count`. Space: $O(1)$. |
| 1248 |
Count Number of Nice Subarrays |
Generate every possible subarray. For each, count the number of odd integers. If it equals `k`, increment the total count. |
Nested Subarray Windowing |
Draw an array. Draw brackets for every possible start and end. For each bracket, scan the contents. Write $O(N^2)$. |
Sliding Window / Prefix Sum Hashing |
Odd-Number "Running Tally" |
Convert the problem: Treat odd as 1 and even as 0. Now find the number of subarrays that sum to exactly `k`. Use a Sliding Window to find (at most k) - (at most k-1). |
Draw an array. Mark odd numbers with a '1'. Draw a window [L, R]. Move R to include k ones. Count how many L positions keep exactly k ones. Total = `Count(atMost(k)) - Count(atMost(k-1))`. |
Linear Runner Sweep |
Draw an array. Draw two arrows (L, R) moving right. Write $O(N)$. |
Draw thousands of temporary subarray slices. |
Draw a frequency array for prefix sums or just 4-5 integer variables for the sliding window. Space: $O(N)$ or $O(1)$. |
| 1249 |
Minimum Remove to Make Valid Parentheses |
Generate all possible subsequences of the string. For each, check if it's a valid parenthetical string. Pick the longest one. |
Subsequence Power Set |
Draw a string. Branch for "Keep" or "Remove" for every character. Check the validity of every leaf. Write $O(2^N)$. |
Stack / Two-Pass Filtering |
Balance Counter / Redundant Marker |
Scan left-to-right: Keep a balance of open `(`. If `)` appears when balance is 0, mark it for removal. Scan right-to-left: Do the same for `(`. Combine markers to build the final string. |
Draw the string. Sweep an arrow rightarrow. If you hit a `)` and have no `(`, draw a red 'X' over it. Sweep <=ftarrow. If you have extra `(`, draw a red 'X' over them. Reconstruct from the remaining characters. |
Linear Scan & Reconstruction |
Draw two horizontal arrows (Forward and Backward). Show a third pass for the final build. Write $O(N)$. |
Draw a massive list of strings in memory. |
Draw a Stack (storing indices) or a Character Array (same size as input). Space: $O(N)$. |
| 1250 |
Check If It Is a Good Array |
Generate all possible linear combinations of the numbers in the array (Bézout's identity) and check if any combination can result in 1. |
Infinite Linear Combination Web |
Draw circles for numbers. Draw infinitely branching lines for (ax + by + cz...). Show the search space never ending. Write $O(2^N)$. |
Number Theory (Greatest Common Divisor) |
GCD Reduction Chain |
According to Bézout's Lemma, a "Good Array" exists if and only if the GCD of all numbers in the array is 1. Iterate through the array, updating the cumulative GCD. If it hits 1, stop. |
Draw the array. Draw a funnel below the first two numbers calculating their GCD. Feed that result and the next number into another GCD funnel. If the funnel output ever reaches 1, draw a big green checkmark. |
Linear Logarithmic Step-down |
Draw a sequence of N blocks. Above each transition, write "Euclidean Algorithm". Write $O(N + \log(\text{min}_\text{val})$). |
Draw a massive set storing every possible sum result generated. |
Draw a single integer variable `g` to store the current GCD. Space: $O(1)$. |
| 1251 |
Average Selling Price (SQL) |
For every transaction in the `UnitsSold` table, run a subquery against the `Prices` table to find the price valid for that specific date. Then calculate the average. |
Row-by-Row Correlated Lookup |
Draw the UnitsSold table. For every row, draw a search arrow that scans the entire Prices table. Write $O(U \cdot P)$. |
LEFT JOIN on Interval + GROUP BY |
Date-Range Overlap Join |
Join `Prices` and `UnitsSold` where `product_id` matches AND `purchase_date` falls between `start_date` and `end_date`. Sum up (price * units) and divide by total units for each product. |
Draw two tables side-by-side. Draw arrows connecting a purchase date to the specific price-row that "contains" that date. Group these connected rows by product ID and show a calculator summing them up. |
Hash/Sort-Merge Join on Ranges |
Draw a sorted timeline of prices. Show purchases being "dropped" into their respective price buckets. Write $O(U \log U + P \log P)$. |
Draw multiple temporary result tables for each correlated subquery. |
Draw a single intermediate table result from the join, processed in a single grouping pass. |
| 1252 |
Cells with Odd Values in a Matrix |
Initialize a full m x n matrix with zeros. For every query (r, c), iterate through the entire row r and increment values, then iterate through the entire column c and increment. Finally, count odd cells. |
Full Grid Simulation |
Draw a grid. For every query, draw a horizontal line and a vertical line, manually adding +1 to every box. Then count all boxes with odd numbers. Write $O(L \cdot (M+N)$ + M*N). |
Parity Counting (Row/Col Arrays) |
XOR-like Row/Column Toggles |
Instead of the whole grid, just maintain two arrays: `rows[m]` and `cols[n]`. For each query (r, c), increment `rows[r]` and `cols[c]`. A cell (i, j) is odd if `rows[i] + cols[j]` is odd. |
Draw a horizontal array (Rows) and a vertical array (Cols) next to a ghost grid. Mark which rows/cols were incremented an odd number of times. A cell is odd if exactly one of its row/column markers is "Odd". |
Linear Vector Scan |
Draw two separate lines (length M and length N). Write $O(L + M + N)$ where L is the number of indices. |
Draw a full M x N integer matrix in memory. |
Draw two 1D boolean/integer arrays of size M and N. Space: $O(M + N)$. |
| 1253 |
Reconstruct a 2-Row Binary Matrix |
Use backtracking to try all combinations of 0s and 1s in the two rows for every column, checking if the sums match `upper`, `lower`, and `colsum`. |
Exponential Choice Tree |
Draw columns. For column 0, branch [1,1], [1,0], [0,1], [0,0]. Repeat for N columns. Write $O(2^N)$. |
Greedy Strategy |
Priority Placement (2s then 1s) |
Columns with `colsum=2` must have 1 in both rows. Fill those first. Then for `colsum=1`, greedily place a 1 in the row (upper or lower) that still needs more 1s. If `colsum=0`, both are 0. |
Draw two empty rows. Look at the `colsum` array. For every '2', put '1' in both rows. For every '1', check if `upper > 0`; if yes, put '1' on top, else put it on bottom. If you run out of 1s to give, draw a red "Impossible". |
Single-Pass Deterministic Scan |
Draw an array. Draw a single arrow scanning left-to-right once. Write $O(N)$. |
Draw a massive recursion stack for the 2^N search. |
Draw two 1D arrays of size N. Space: $O(N)$. |
| 1254 |
Number of Closed Islands |
For every 0 (land), check every possible path to see if it reaches the boundary of the grid. If all paths are blocked by 1s (water), it's closed. |
Unbounded Path Exploration |
Draw a grid. Pick a 0. Draw lines radiating in every direction until they hit water or the edge. Repeat for every land cell. Write $O((M\cdot N)$^2). |
Flood Fill (DFS/BFS) + Edge Trimming |
Boundary Drainage Simulation |
First, run Flood Fill on all land (0) connected to the edges and turn them into water (1). These can never be closed. Then, count how many separate land "islands" are left in the middle. |
Draw a grid. Take a "bucket of water" and pour it on all four edges. Let it flow into any connected land (0s) and turn them blue (1s). Then, find the remaining dry land pockets and circle each island one by one. |
Linear Grid Traversal |
Draw a grid. Show a single sweep turning edge-islands into water, then a second sweep counting the rest. Write $O(M \cdot N)$. |
Draw a massive list of all possible paths from every cell. |
Draw a recursion stack for DFS of max depth M x N. Space: $O(M \cdot N)$. |
| 1255 |
Maximum Score Words Formed by Letters |
Try every possible subset of the given words (Power Set). For each subset, check if it can be formed using the provided letters and calculate the score. |
Exhaustive Decision Tree |
Draw a root node. For Word 1, branch "Include" or "Exclude". For each leaf, branch for Word 2. Repeat for all words. Write $O(2^N)$. |
Backtracking with Frequency State Management |
Resource Depletion Tracker |
Start with a pool of letters (frequency array). Recursively decide to pick a word. If you pick it, subtract its letters from the pool. If pool goes negative, backtrack (prune). Keep track of the highest score achieved. |
Draw a "Vault" containing letter counts. Draw a path representing a word choice. If the word takes more letters than the vault has, draw a red "STOP" sign. If it fits, update the vault and move to the next word. Undo (add letters back) when moving up. |
Pruned Recursive Forest |
Draw a tree where many branches end prematurely with "X" because the letter pool is empty. Write $O(2^N \cdot L)$ where L is word length. |
Draw a list of all 2^N word combinations stored in memory. |
Draw one 1D frequency array of size 26 and a recursive call stack of depth N. Space: $O(N)$. |
| 1256 |
Encode Number |
Convert numbers to binary strings manually, padding them and trying to map them one-by-one to the pattern: ""->0, "0"->1, "1"->2, "00"->3... |
Pattern Matching Table |
Draw a table with 0, 1, 2, 3 and try to manually find a formula by staring at the binary representations. Write $O(N)$ lookups. |
Binary Offset Mapping |
The "Binary Mirror" Increment |
Observation: The encoding of N is simply the binary representation of N+1 with the leading '1' removed. For example, N=3 rightarrow 3+1=4 rightarrow bin(4) = "100" rightarrow remove first '1' rightarrow "00". |
Write the number N. Add 1. Write the binary form of N+1. Draw a pair of scissors cutting off the very first bit. The remainder is your answer. |
Constant-Time Math / Bit-shifter |
Draw a single box taking input N and performing a single bitwise/string operation. Write $O(\log N)$ (the number of bits). |
Draw a hardcoded mapping table. |
Draw a single string variable for the result. Space: $O(\log N)$. |
| 1257 |
Smallest Common Region |
For two regions, find every "ancestor" region (parent, grandparent, etc.) by searching the hierarchy. Store all ancestors of Region 1 in a list, then scan Region 2's ancestors for the first match. |
Exhaustive Parent Search |
Draw a tree. Pick Region 1, draw arrows to root. Pick Region 2, draw arrows to root. Check every pair of arrows for equality. Write $O(N^2)$. |
Hash Map (Parent Pointer) + Set Intersection |
The "Ancestry Trace" Path |
Build a Map where Key = Child and Value = Parent. Trace the path from Region 1 to the root and put it in a Set. Then trace Region 2 up; the first node you find already in the Set is the answer. |
Draw a Map table: [Child | Parent]. Trace Region 1 up, circling nodes in blue. Trace Region 2 up, circling nodes in red. The first node with both colors is your Smallest Common Region. |
Two Linear Path Scans |
Draw a hierarchy tree. Draw two lines moving upward from different leaves to the root. Write $O(N)$. |
Draw multiple lists of all regions in the system. |
Draw a HashMap for child-parent relationships and a HashSet for the first path. Space: $O(N)$. |
| 1258 |
Synonymous Sentences |
Generate every possible combination of words by looking at every synonym for every word in the sentence. Check for cycles and indirect synonyms using nested loops. |
Exponential Sentence Generator |
Draw the sentence. For each word, branch out for every synonym. If a synonym has a synonym, branch more. Write $O(\text{Synonyms}^N)$. |
DSU (Disjoint Set Union) + Backtracking + Sorting |
Synonym "Island" Buckets |
Group all related synonyms into "islands" using Union-Find. For each word in the sentence, find its island, get all words in that island, sort them, and use backtracking to generate all sentences lexicographically. |
Draw words as nodes. Draw lines (edges) between pairs of synonyms. Circle the connected components (islands). For each word in the original sentence, replace it with its sorted "island" list and branch. |
Grouped Combinatorial Expansion |
Draw a Union-Find forest. Show a single backtracking tree branching only by the size of synonym groups. Write $O(\text{Combinations})$. |
Draw a deep recursion stack with many duplicate synonym lookups. |
Draw DSU `parent` map, a Map of `Root -> SortedList`, and the final output list. Space: $O(\text{Total Words})$. |
| 1259 |
Handshakes That Don't Cross |
Recursively try every possible person for the first person to shake hands with. For each choice, count how many ways the remaining people (divided into two separate groups) can shake hands. |
Recursive Catalan Branching |
Draw 6 people in a circle. Draw a line between 1-2, then recurse for 3-4-5-6. Then 1-4, recurse for (2-3) and (5-6). Write $O(N!)$. |
Dynamic Programming (Catalan Number Variation) |
Dividing the Circle |
If person 1 shakes hands with person i, the circle is split into two independent groups of size (i-2) and (N-i). Both must be even. DP[N] = sum (DP[i-2] x DP[N-i]). |
Draw a circle with N points. Draw a line connecting two points, effectively cutting the circle into two halves. Write the number of ways for the left half x number of ways for the right. Sum these for all valid cuts. |
1D State Accumulation |
Draw an array of size N/2. For each element, draw arrows showing it summing products of previous elements. Write $O(N^2)$. |
Draw an enormous recursive tree with repeated subproblems. |
Draw a single 1D DP array of size N/2 + 1. Space: $O(N)$. |
| 1260 |
Shift 2D Grid |
Perform the shift 'k' times. In each shift, move every element (i, j) to the right, and move the last element of a row to the first element of the next row. |
Nested Loop Cycle |
Draw a grid. Draw an arrow from every cell to its neighbor. Draw a big circular arrow from the bottom-right back to the top-left. Repeat this drawing 'k' times. Write $O(k \cdot m \cdot n)$. |
1D Index Mapping (Modulo Arithmetic) |
Flattened Array Ring |
Treat the 2D grid as a single long 1D array of length m x n. The new position of an element at 1D index i is (i + k) modm x n. Convert back to 2D indices. |
Draw a grid. Label cells 0, 1, 2... up to mn-1. Draw a straight line below it with the same numbers. Show a shift of k on the line. Map the new line numbers back into a fresh grid. |
Single Linear Transformation |
Draw a 1D block representing the grid. Draw a single set of arrows shifting all elements simultaneously. Write $O(m \cdot n)$. |
Draw multiple intermediate 2D grid copies for each shift. |
Draw a single new 2D grid of size m x n. Space: $O(m \cdot n)$ for the result. |
| 1261 |
Find Elements in a Contaminated Binary Tree |
Every time the `find(target)` function is called, perform a full DFS or BFS traversal of the tree to search for the value. |
Repeated Tree Scans |
Draw a tree. For every search query, draw a path that visits every node in the tree until found. Write $O(Q \cdot N)$ where Q is number of queries. |
Pre-computation with Hash Set |
Tree Recovery to Bucket Fill |
During the constructor call, traverse the tree once using the rule (2 * val + 1 or 2 * val + 2) to fix values. Store all recovered values in a Hash Set. `find(target)` becomes a simple $O(1)$ check. |
Draw the contaminated tree (all nodes are -1). Draw an arrow pointing to a recovered tree (0, 1, 2...). Next to it, draw a large circle (Set) containing all the recovered numbers. For queries, just point at the Set. |
Linear Scan + Constant Time Lookup |
Draw a single tree traversal arrow followed by multiple small dots representing $O(1)$ lookups. Write $O(N + Q)$. |
Draw no extra storage, but constant CPU spikes for every query. |
Draw a HashSet containing N integers. Space: $O(N)$. |
| 1262 |
Greatest Sum Divisible by Three |
Generate every possible subsequence of the array. For each subsequence, calculate the sum and check if it's divisible by 3. Keep the max. |
Power Set Subset Tree |
Draw an array. Branch out "Include" or "Exclude" for every element. Write the sum at each leaf. Circle sums divisible by 3. Write $O(2^N)$. |
Dynamic Programming (Remainder State) |
Modular Bucketing (3-State DP) |
Maintain 3 variables: `dp[0], dp[1], dp[2]` representing the max sum found so far that has a remainder of 0, 1, or 2 when divided by 3. For each number, update all three states based on the new remainder. |
Draw three boxes labeled 0, 1, 2. Process a number (e.g., 5, remainder 2). Show 5 being added to the value in box 1 and the result potentially updating box 0 (since 1+2=3 equiv 0). |
Fixed-State Linear Pass |
Draw a horizontal line for the array. Above it, draw three small constant tracks. Write $O(N \cdot 3)$ = $O(N)$. |
Draw a massive list of 2^N sums. |
Draw exactly three integer variables: `rem0`, `rem1`, `rem2`. Space: $O(1)$. |
| 1263 |
Minimum Moves to Move a Box to Their Target Location |
Standard BFS exploring only the box's position. This fails because the box's movement depends on where the person is standing relative to the box. |
Incomplete State Space |
Draw a grid. Show the box moving but ignore the person. Draw a red "X" because the pathing is blocked by the person's inability to reach the "push side". |
Nested BFS / State BFS (Box Pos + Person Pos) |
Dual-Object Coordination (4D State) |
The state is `(box_row, box_col, person_row, person_col)`. For every potential box move, run a sub-BFS to see if the person can reach the side of the box required to push it in that direction. |
Draw a grid. Use a solid circle for the box and a star for the person. Draw a path for the box. At each step, draw a "mini-grid" highlighting the area reachable by the star without crossing the box or walls. |
Bounded 4D State Exploration |
Draw a M x N grid. Multiply by the number of box positions (M x N). Write $O(M^2 \cdot N^2)$. |
Draw a simple queue that doesn't track the person's location, leading to incorrect results. |
Draw a 4D boolean array `visited[m][n][m][n]` or a Set of 4-tuples, plus a BFS Queue. Space: $O(M^2 \cdot N^2)$. |
| 1264 |
Page Recommendations (SQL) |
For user 1, find all friends. For each friend, find all their liked pages. Then check if user 1 already likes those pages. Filter and distinct. |
Nested Loop Friend Scan |
Draw User 1. Draw arrows to Friends A, B, C. From each, draw arrows to their liked pages. Then draw arrows back to User 1's likes to compare. Write $O(N^2)$. |
CTE / UNION for Bidirectional Friends + JOIN |
Three-Step Filtering Funnel |
1. Create a unified `Friends` list for User 1 (handling both `user1_id` and `user2_id` columns). 2. Join this list with `Likes` to get friends' pages. 3. Filter out pages User 1 already likes using `NOT IN` or `EXCEPT`. |
Draw a list of User 1's friends. Next to it, draw the `Likes` table. Draw arrows connecting friends to pages. Draw a "Blacklist" containing User 1's own liked pages. If a page is in the blacklist, erase the arrow. |
Relational Set Operations |
Draw a circle of "Friends' Pages" and subtract a circle of "My Pages". Write $O(N \log N)$. |
Draw multiple intermediate temporary tables for each friend's lookup. |
Draw a single Hash Set for User 1's pages to perform $O(1)$ exclusion checks. |
| 1265 |
Print Immutable Linked List in Reverse |
Iteratively find the last element, print it, then find the second to last, print it, and so on. Since you can't move backward, you must scan from the start N times. |
Descending Length Scans |
Draw a list of N nodes. Draw an arrow from 1 to N. Then an arrow from 1 to N-1. Then 1 to N-2. The triangle of arrows represents $O(N^2)$. |
Recursive Backtracking (Implicit Stack) |
Depth-First Echo |
Call a function on the current node that first calls itself on `node.getNext()`. Only *after* the recursive call returns do you call `node.printValue()`. This naturally uses the call stack to reverse. |
Draw a vertical "Stack" box. Draw an arrow entering for node 1, then node 2, then node 3. Once at the end, show the arrows "popping" out in reverse order (3, then 2, then 1) with a "Print" label on each exit. |
Linear Recursion Depth |
Draw a single straight line representing N steps. Write $O(N)$. |
Draw a constant memory footprint for the pointers but N repeated scans. |
Draw a "Stack Frame" tower of height N. Each frame holds a reference to a node. Space: $O(N)$. |
| 1266 |
Minimum Time Visiting All Points |
Calculate the Manhattan distance or try to simulate step-by-step movement (up, down, left, right) for every point in the sequence. |
Incremental Step Grid Walk |
Draw two points. Draw a path of many tiny arrows connecting them in an L-shape. Write $O(\text{Total Steps})$. |
Chebyshev Distance (Max of ΔX, ΔY) |
Diagonal Cutting |
Realize that you can move diagonally (1 step in both x and y simultaneously). The time taken between two points (x1, y1) and (x2, y2) is simply the maximum of |x2 - x1| and |y2 - y1|. |
Draw two points on a grid. Draw a diagonal line until you are aligned with one of the coordinates of the target, then a straight horizontal/vertical line. Label the total time as `max(dx, dy)`. |
Single Sequence Sweep |
Draw an array of N points. Draw one continuous line jumping from point 1 to 2, 2 to 3, etc. Write $O(N)$. |
Draw an array of all individual unit-steps taken. |
Draw exactly two integer variables for the current point and the total time. Space: $O(1)$. |
| 1267 |
Count Servers that Communicate |
For every cell (i, j) containing a server, scan the entire row i and the entire column j to see if another server exists. If so, increment the communicator count. |
Cell-by-Cell Cross Scans |
Draw a grid. For every server, draw a long horizontal line and a long vertical line. Write $O(M \cdot N \cdot (M+N)$). |
Row/Column Frequency Counting |
Projection Sums |
Pre-calculate the number of servers in each row and store in `rowCount[m]`. Do the same for `colCount[n]`. A server at (i, j) can communicate if `rowCount[i] > 1` OR `colCount[j] > 1`. |
Draw a grid with servers. At the end of each row, write the total count. At the bottom of each column, write the total count. Circle servers where either their row total or column total is > 1. |
Linear Grid Scan (Two Pass) |
Draw a grid. Show one horizontal pass for totals, one vertical pass for totals, and a final pass for counting. Write $O(M \cdot N)$. |
Draw no extra arrays, but massive repeated CPU loops over the same rows. |
Draw two 1D arrays of size M and N to store the counts. Space: $O(M + N)$. |
| 1268 |
Search Suggestions System |
For every character typed, scan the entire list of products. Filter those that match the current prefix, sort them alphabetically, and pick the top 3. |
Repeated Sorting & Filtering |
Draw the word "mouse". For "m", draw a sorting box for 1000 words. For "mo", draw another sorting box. For "mou", draw another. Write $O(L \cdot N \log N)$ where L is word length. |
Sort + Binary Search (Two Pointers) |
Alphabetical Range Narrowing |
Sort the products once. For each typed character, use two pointers (`left`, `right`) to shrink the range in the sorted list that matches the prefix. The first 3 elements from `left` are your suggestions. |
Draw a sorted list of words. Draw two pointers at the very top and bottom. As you type "m", move `left` down and `right` up. As you type "o", move them further inward. Circle the 3 items starting at `left`. |
Binary Search Halving |
Draw a sorting block followed by a sequence of L binary search operations. Write $O(N \log N + L \log N)$. |
Draw multiple temporary sorted lists being created in memory for every keystroke. |
Draw one sorted list and two integer pointers. Space: $O(N \cdot \\text{text}{\text{avg}_\text{len}})$. |
| 1269 |
Number of Ways to Stay in the Same Place After Some Steps |
Standard DFS exploring all 3 choices (Left, Right, Stay) for every step. Without memoization, this explores every possible path. |
3-way Branching Decision Tree |
Draw a root (Index 0). Branch out to -1 (red X), 0, and 1. From each, branch out 3 ways again. The tree depth is 'Steps'. Write $O(3^\\text{text}{\text{Steps}})$. |
Dynamic Programming (State Compression) |
Pascal-like Triangle Transition |
`dp[i][j]` is the number of ways to be at index j after i steps. `dp[i][j] = dp[i-1][j-1] + dp[i-1][j] + dp[i-1][j+1]`. Since you can't return to 0 if you go too far, j is limited to `min(steps, arrLen)`. |
Draw a grid where rows are "Steps" and columns are "Indices". For a cell at `step 2, index 1`, draw three arrows coming from `step 1, index 0`, `step 1, index 1`, and `step 1, index 2`. |
Linear Layer Processing |
Draw a rectangle of width `min(Steps, ArrLen)` and height `Steps`. Write $O(\text{Steps} \\text{cdot min}(\text{Steps}, \text{ArrLen})$). |
Draw a massive recursive call stack. |
Draw two 1D arrays of size `min(Steps, ArrLen)` to represent the "current" and "previous" step counts. Space: $O(\text{Steps})$. |
| 1270 |
All People Report to the Given Manager |
For every employee, trace their management chain manually using multiple nested subqueries (Level 1, then Level 2, then Level 3). |
Static Chain Hardcoding |
Draw a person. Draw 3 nested boxes around them. Label the outer box "Boss". Write $O(N)$ with 3 table scans. |
Recursive CTE (Common Table Expression) |
Hierarchical Tree Traversal |
Start with the "Big Boss" (ID 1). Find everyone who reports to them. Then find everyone who reports to those people. Stop exactly at depth 3. |
Draw ID 1 at the top. Draw arrows to their direct reports. From those, draw arrows to their reports. Stop after 3 levels of arrows. Circle everyone except ID 1. |
BFS-style Level Expansion |
Draw a tree growing downwards. Highlight only the first 3 levels. Write $O(N)$. |
Draw several temporary tables for each hardcoded level. |
Draw a single result set that expands iteratively in memory. |
| 1271 |
Hexspeak |
Convert the decimal string to a hex string. Then, manually iterate through every hex character and check if it's in the valid set {A, B, C, D, E, F, I, O}. |
Character-by-Character Mapping |
Draw the hex string. Above each character, draw a magnifying glass. If it's '1', write 'I'. If '0', write 'O'. If '2-9', draw a red "ERROR". Write $O(\log₁₆N)$. |
Direct String Transformation + Regex |
Lookup Table / Filter Funnel |
Convert the entire number to uppercase Hex. Replace '1' with 'I' and '0' with 'O'. Use a filter to see if any remaining characters are digits '2-9'. If yes, it's "ERROR". |
Draw a box labeled "Hex Converter". Feed the number in. Output a string. Draw a "Validator" box that checks for digits 2-9. If the validator is green, replace 1->I and 0->O. |
Constant-Time String Scan |
Draw a single arrow scanning the hex string once. Write $O(\log₁₆N)$. |
Draw a temporary list of individual characters. |
Draw a single string builder or modified string object. Space: $O(\log₁₆N)$. |
| 1272 |
Remove Interval |
Iterate through every interval in the list and check if it overlaps with the "To-be-removed" interval. If it overlaps, manually calculate the new fragmented pieces. |
Interval Collision Check |
Draw a timeline. Draw the removal interval as a red block. Draw the input intervals as blue blocks. For every collision, draw a "Splitting" symbol. Write $O(N)$. |
Linear Boundary Comparison |
The "Cookie Cutter" Slice |
For each interval `[start, end]`: 1. If it's entirely before the removal, keep it. 2. If it's entirely after, keep it. 3. If it overlaps, keep the part from `start` to `remove_start` (if valid) and `remove_end` to `end` (if valid). |
Draw a long horizontal line. Draw two markers for the removal range. For each input interval, drop it onto the line. If it hits the markers, show it being "cut" and only the outside pieces falling into the result bucket. |
Single-Pass Sweep-line |
Draw an array. Draw a single arrow scanning it. Write $O(N)$. |
Draw a list of all potential fragments, including duplicates. |
Draw a single result list to store the final intervals. Space: $O(N)$. |
| 1273 |
Delete Tree Nodes |
For every node, calculate the sum of its subtree. If the sum is 0, delete it. But since deleting a parent affects the structure, you'd have to re-scan the tree multiple times. |
Recursive Multi-Scan |
Draw a tree. Pick a node, scan its children. Go back to the root, scan again. Write $O(N^2)$. |
Post-Order Traversal (Bottom-Up) |
Subtree Information Bubbling |
Use a single DFS. Each node returns two things to its parent: the total sum of its subtree and the total number of non-deleted nodes. If the sum is 0, the node tells the parent "my count is 0". |
Draw a tree. Draw arrows moving from leaves up to the root. At each node, write "(Sum, Count)". If Sum=0, cross out the node and all its children and change Count to 0. |
Linear Single-DFS Sweep |
Draw a tree. Show a single path that visits every node and edge exactly twice (down and up). Write $O(N)$. |
Draw a massive table of all subtree sums stored separately. |
Draw a recursion stack and an Adjacency List. Space: $O(N)$. |
| 1274 |
Number of Ships in a Rectangle |
Scan every single integer coordinate (x, y) within the rectangle and call the `hasShips` API for each. |
Grid Coordinate Exhaustion |
Draw a grid. Draw a dot on every single intersection point. Write $O(\text{Width} \\text{cdot Height})$. |
Divide and Conquer (Quadtree Decomposition) |
Quadrant Partitioning |
Call `hasShips` for the whole rectangle. If true, divide the rectangle into 4 smaller quadrants. Repeat for each quadrant. If `hasShips` is false for a quadrant, prune it immediately. |
Draw a large rectangle. Divide it into 4. If a quadrant has a ship, divide it into 4 again. If it doesn't, put a big red "X" and stop. Trace the path to the individual ship coordinates. |
Logarithmic Spatial Search |
Draw a large box being split into smaller and smaller boxes. Write $O(S \cdot \log(\\text{text}{\text{max}_\text{dimension}})$) where S is number of ships. |
Draw a list of every single coordinate scanned. |
Draw a recursion stack with a depth proportional to the log of the area. Space: $O(\log(\\text{text}{\text{max}_\text{dimension}})$). |
| 1275 |
Find Winner on a Tic Tac Toe Game |
After every single move, scan all 3 rows, 3 columns, and 2 diagonals from scratch to check if there is a winner. |
Repeated Grid Scans |
Draw a 3x3 grid. For every move 'X' or 'O' placed, draw 8 lines through the grid to check for winners. Write $O(\text{Moves} \cdot 8)$. |
Row/Column/Diagonal Counters |
8-Directional Vector Tally |
Maintain two sets of 8 counters (one for Player A, one for Player B). Counters for: 3 rows, 3 columns, and 2 diagonals. When a player moves to (r, c), increment their `rows[r]` and `cols[c]`. If r==c, increment diagonal. If r+c==2, increment anti-diagonal. |
Draw a grid. Outside the grid, draw 3 boxes on the right (Rows) and 3 boxes at the bottom (Cols). Draw two extra boxes for Diagonals. For each move, put a tally in the corresponding side boxes. If any box hits "3", that player wins. |
Linear Move Processing |
Draw a list of moves. Draw a single arrow scanning the list once. Write $O(N)$ where N is number of moves. |
Draw a full 3x3 character matrix being stored and re-scanned. |
Draw two integer arrays of size 8 (or separate variables). Space: $O(1)$. |
| 1276 |
Number of Burgers with No Waste |
Use nested loops to try every possible combination of Jumbo Burgers (4 tomato, 1 cheese) and Small Burgers (2 tomato, 1 cheese) that could be made with the given total ingredients. |
Ingredient Search Grid |
Draw a coordinate plane where X is Jumbo and Y is Small. Shade every integer point (X, Y) and check the sum. Write $O(\text{Tomato} \\text{cdot Cheese})$. |
Linear Algebra (System of Equations) |
Mathematical Intersection |
Solve: 4x + 2y = tomato and x + y = cheese. Rearranging gives x = (tomato - 2 * cheese) / 2. Calculate x and y. If they are non-negative integers, you found the answer. |
Write the two equations. Show the algebra steps leading to the formulas for x and y. Draw a "Filter" box that checks if (tomato - 2cheese) is even and >= 0. |
Constant-Time Calculation |
Draw a single dot. Write $O(1)$. The time does not grow with the input size. |
Draw a list of all tried combinations. |
Draw two variables for X and Y. Space: $O(1)$. |
| 1277 |
Count Square Submatrices with All Ones |
For every cell (i, j) containing a '1', try to expand squares of size 2x2, 3x3, etc., checking if every cell in the expanded square is also a '1'. |
Expanding Perimeter Scan |
Draw a grid. For a '1' at the center, draw concentric squares growing outward. For each square, shade every inner cell. Write $O(M \cdot N \cdot \\text{min}(M,N)$). |
2D Dynamic Programming |
Corner-Based Dependency |
`dp[i][j]` represents the size of the largest square whose bottom-right corner is at (i, j). If `grid[i][j] == 1`, then `dp[i][j] = min(top, left, top-left) + 1`. The total count is the sum of all `dp[i][j]` values. |
Draw a 3x3 grid of 1s. For the bottom-right cell, draw 3 arrows pointing from its neighbors (up, left, up-left). Write the minimum of those neighbors + 1 in the cell. Show how this value represents exactly how many squares end there. |
Linear Grid Traversal |
Draw a grid. Show a single sweep from top-left to bottom-right. Write $O(M \cdot N)$. |
Draw no extra memory but massive re-scans of the input grid. |
Draw a 2D integer matrix `dp[M][N]` (can be done in-place to save space). Space: $O(1)$ or $O(M\cdot N)$. |
| 1278 |
Palindrome Partitioning III |
Recursively try every possible way to partition the string into K parts. For each partition, calculate the changes needed to make each part a palindrome. |
Recursive Partition Tree |
Draw a string. Branch out for every possible location of the first cut. For each, branch for the second cut. Continue until K cuts. Write $O(N^K)$. |
Interval DP + Partition DP |
Two-Stage Cost Matrix |
1. Pre-calculate `cost[i][j]`: min changes to make `s[i...j]` a palindrome. 2. Define `dp[i][k]` as min changes to partition `s[0...i]` into k palindromes. `dp[i][k] = min(dp[j][k-1] + cost[j+1][i])`. |
Draw a 2D matrix `cost`. Below it, draw a 2D matrix `dp`. Show an entry in `dp` being filled by looking at a whole row in the `cost` matrix. Trace the "optimal cut" back through the layers. |
Nested Interval Loops |
Draw a square grid for the cost pre-calculation (N^2). Below it, draw a grid for the DP (N * K). Write $O(N^2 \cdot K)$. |
Draw a massive recursion stack with redundant palindrome checks. |
Draw two 2D arrays: `cost[N][N]` and `dp[N][K]`. Space: $O(N^2)$. |
| 1279 |
Traffic Light Controlled Intersection |
Allow any car to cross whenever it arrives. If two cars from different roads (Road 1 and Road 2) cross at the same time, it results in a collision/concurrency error. |
Uncontrolled Race Condition |
Draw two intersecting lines. Draw two cars arriving at the center simultaneously. Draw a red explosion symbol. Write Safety Violation. |
Synchronization (Mutex/Locking) |
The "Green Light" Semaphore |
Use a single `Lock` or `synchronized` block for the entire intersection. When a car arrives, check if the current green light is for its road. If not, toggle the light (call `turnGreen`). Then let the car cross and release the lock. |
Draw a "Lock" icon over the intersection. Draw a "Light" variable (1 or 2). Show a car arriving: it grabs the lock, checks the light, flips it if needed, crosses, and then "drops" the lock for the next car. |
Serialized Event Processing |
Draw a timeline. Show car events being placed one after another, never overlapping. Write $O(N)$. |
Draw multiple threads crashing into each other. |
Draw a single `Mutex` object and one integer variable for `currentLight`. Space: $O(1)$. |
| 1280 |
Students and Examinations (SQL) |
Join the Students and Examinations table directly. This fails to account for students who attended zero exams for a specific subject, leaving gaps in the output. |
Fragmented Result Set |
Draw two lists: Students and Exams. Draw lines between them only where data exists. Point to the missing subjects and write "NULL/GAPS". Write $O(N)$. |
CROSS JOIN (Cartesian Base) + LEFT JOIN |
The "Grid Completion" Master Table |
First, force every student to be paired with every subject using a CROSS JOIN. Then, LEFT JOIN that "perfect grid" with the actual Examinations table to fill in the counts. Use `COALESCE` to turn NULLs into 0. |
Draw a Table A (Students) and Table B (Subjects). Draw arrows from every row in A to every row in B to create a full grid. Overlay a "Checked-in" list from the Exams table. Count occurrences within each grid cell. |
Cartesian Expansion + Hash Join |
Draw a rectangle representing S x Subj. Show a scan of the Exams table filling this rectangle. Write $O(S \\text{cdot Subj} + \text{Exams})$. |
Draw a list of only successful exam entries. |
Draw a 2D Matrix visualization where every cell is initialized to 0 before the count begins. |
| 1281 |
Subtract the Product and Sum of Digits of an Integer |
Convert the integer to a string. Iterate through the string, converting each character back to an integer, and maintain two running totals (product and sum). |
Character-by-Character Mapping |
Draw the number as a string of characters. Draw two boxes below. For each character, drop it into both boxes. Write $O(\log₁₀N)$. |
Iterative Modulo (%) and Division (/) |
Digit Extraction Loop |
While the number is greater than 0, use `n % 10` to peel off the last digit. Update the sum and product. Use `n / 10` to discard the last digit and repeat. |
Draw a number. Draw a "Peeler" (% 10) taking the last digit and a "Discarder" (/ 10) shortening the number. Show the peeled digit feeding into a "Sum" and a "Product" accumulator. |
Logarithmic Step-down |
Draw a number getting shorter by one digit in each step. Write $O(\log₁₀N)$. |
Draw a character array or string buffer. |
Draw exactly two integer variables for sum and product. Space: $O(1)$. |
| 1282 |
Group the People Given the Group Size They Belong To |
Iterate through all possible group sizes (1 to N). For each size, scan the entire array to find people who belong to that size and manually group them. |
Multi-Scan Filtering |
Draw an array. For size 1, scan the whole array. For size 2, scan again. Repeat for all sizes. Write $O(N^2)$. |
Hash Map of Lists (Greedy Accumulation) |
Wait-list Buckets |
Create a Map: `GroupSize -> List of IDs`. As you scan the array, add the person's ID to the list for their size. If the list size equals their `GroupSize`, move that list to the result and clear the map entry. |
Draw an array of sizes. Below, draw several buckets labeled by size. As you process an ID, drop it into its bucket. When a bucket is full, tip it over into a "Final Groups" box. |
Linear Pass with Map Updates |
Draw an array. Draw a single arrow scanning right. Draw a Map updating in real-time. Write $O(N)$. |
Draw multiple temporary arrays for each group size search. |
Draw a HashMap where the sum of all list lengths equals N. Space: $O(N)$. |
| 1283 |
Find the Smallest Divisor Given a Threshold |
Try every possible divisor starting from 1 up to the maximum number in the array. For each divisor, calculate the sum of divisions and check against the threshold. |
Brute Force Divisor Scan |
Draw a number line for divisors: 1, 2, 3... Max. For each divisor, draw a full scan of the array. Write $O(\text{Max} \cdot N)$. |
Binary Search on Answer Range |
The "Sum-Divisor" Seesaw |
Divisors have a monotonic property: a larger divisor results in a smaller sum. Binary Search between `low=1` and `high=max(nums)`. If `sum(mid) > threshold`, the divisor is too small; move `low` to `mid+1`. |
Draw a range [1, Max]. Pick a `mid`. Below it, show the array values being divided by `mid` and summed. If the sum is "too heavy" (over threshold), push the search range to the right. |
Logarithmic Search + Linear Summation |
Draw a range being halved repeatedly. Inside each half, draw a single linear scan. Write $O(N \log(\text{Max})$). |
Draw no extra memory but massive CPU cycles for the linear scan. |
Draw 3 integer variables: `low`, `high`, `mid`. Space: $O(1)$. |
| 1284 |
Minimum Number of Flips to Convert Binary Matrix to Zero Matrix |
Try every possible subset of cells to flip (2^M x N combinations). For each subset, perform the flips and check if the matrix becomes all zeros. |
Flip-Combination Power Set |
Draw a small 3x3 grid. Branch out "Flip cell 1" or "Don't flip". Continue for all 9 cells. Write $O(2^{M \cdot N})$. |
BFS on Matrix State (Bitmasking) |
State-Space Level Traversal |
Represent the matrix as an integer bitmask. Start with the initial state in a Queue. In each step, generate all possible "next states" by flipping one cell (and neighbors). Use a Set to avoid cycles. The first time you hit 0 is the min flips. |
Draw the initial grid. Draw arrows to all possible grids reachable in 1 flip. From those, draw arrows to grids reachable in 2 flips. Circle the first "All Zero" grid you find. |
Bounded State-Graph BFS |
Draw a graph where nodes are unique matrix configurations. Highlight the BFS layers. Write $O((M \cdot N)$ \cdot 2^{M \cdot N}). |
Draw a massive recursion stack for backtracking all combinations. |
Draw a Queue of integers and a "Visited" HashSet of integers. Space: $O(2^{M \cdot N})$. |
| 1285 |
Find the Start and End Number of Continuous Ranges (SQL) |
For every ID, search for the next ID in a loop. If `ID + 1` doesn't exist, mark it as an "End" and look for the next available ID as a "Start". |
Row-by-Row Search Jump |
Draw a list of IDs: 1, 2, 3, 7, 8, 10. For '1', look at '2'. For '2', look at '3'. For '3', scan the rest to see if '4' exists. Write $O(N^2)$. |
Gaps and Islands (Row Number Difference) |
Parallel Sequence Alignment |
Line up the IDs in order. Below them, write a sequence of row numbers (1, 2, 3...). Subtract the row number from the ID. Continuous ranges will produce the same constant difference. Group by this difference. |
Draw a table. Col 1: ID (1, 2, 3, 7, 8). Col 2: RowNum (1, 2, 3, 4, 5). Col 3: Diff (0, 0, 0, 3, 3). Circle the IDs with the same Diff. The min/max of these circles are your Start/End. |
Single Sort-and-Scan |
Draw a sorted list. Draw a single arrow scanning once, calculating a subtraction at each step. Write $O(N \log N)$. |
Draw multiple temporary subqueries checking for `id+1` and `id-1`. |
Draw a single temporary table with one extra integer column for the "Difference Constant." |
| 1286 |
Iterator for Combination |
Generate every possible combination of length `k` during initialization and store them in a massive list. The `next()` function just returns the next item from that list. |
Full Combinatorial Pre-generation |
Draw the string "abc". Draw branches for "ab", "ac", "bc". Show them being stored in a giant array. Write $O(N \text{choose} K)$. |
Bitmasking / Backtracking Iterator |
Current State Pointer / Binary Toggle |
Instead of pre-generating, store the current combination's indices. `next()` calculates the next lexicographical combination on the fly. You can use bitmasking to find the next set bit combination. |
Draw indices [0, 1]. For `next()`, increment the last index. If it hits the limit, increment the one before it and reset. Like a car odometer. |
On-demand State Shift |
Draw a single state object. Show an arrow shifting one index inside it for each `next()` call. Write $O(K)$ per `next()`. |
Draw a giant list holding all (n Choose k) strings in memory. |
Draw exactly one integer array (indices) of size `k` or one bitmask. Space: $O(K)$. |
| 1287 |
Element Appearing More Than 25% In Sorted Array |
Iterate through the array and use a HashMap to count the frequency of every element. Check if any count exceeds N/4. |
Frequency Counting Map |
Draw an array. Draw a Map next to it. For every element, draw an arrow to its key in the Map and increment the value. Write $O(N)$. |
Binary Search on Candidate Points |
The "25% Interval Jump" |
Because the array is sorted, an element appearing > 25% must appear at index N/4, 2N/4, or 3N/4. Check only these 3 candidates. Use `upper_bound - lower_bound` (via binary search) to get their exact count. |
Draw a long bar. Mark the 25%, 50%, and 75% markers. Pick the numbers at those spots. For each number, find its first and last occurrence. If the gap between first and last is > N/4, you're done. |
Constant-Search within Logarithmic Bounds |
Draw 3 dots on an array. For each dot, draw two binary search "V" shapes. Write $O(\log N)$. |
Draw a HashMap that could potentially store N keys. |
Draw 3 candidate variables and a few pointers for binary search. Space: $O(1)$. |
| 1288 |
Remove Covered Intervals |
Compare every interval with every other interval. If interval A is covered by B (i.e., B.start <= A.start and A.end <= B.end), mark A for removal. |
All-Pairs Overlap Scan |
Draw N intervals on a timeline. Draw arrows from interval 1 to 2, 1 to 3, etc. checking for containment. Write $O(N^2)$. |
Sort by Start (Asc) and End (Desc) + Greedy Scan |
The "Expanding Shadow" Sweep |
Sort intervals by start time. If starts are equal, sort by end time descending. Now, as you scan, you only need to track the `max_end` seen so far. If a current interval's end is <= max_end, it's covered. |
Draw sorted intervals stacked vertically. The first one is the "Shadow". For the next one, if its end is inside the shadow, cross it out. If it extends beyond, it becomes the new "Shadow." |
Sorted Linear Pass |
Draw a sorting block followed by a single arrow scanning once. Write $O(N \log N)$. |
Draw a boolean array of size N to track removals. |
Draw one integer variable `max_end` and a counter. Space: $O(1)$ (ignoring sort). |
| 1289 |
Minimum Falling Path Sum II |
Recursively explore every possible path from top to bottom. From cell (r, c), you can move to any cell in row r+1 except those in column c. |
N-way Branching Path Tree |
Draw a grid. From the first row, draw N-1 arrows to the next row for every cell. The branching is massive. Write $O(N^N)$. |
DP with Two Minimums (Optimization) |
Minimum-Only State Transfer |
Instead of checking all N-1 previous cells, just track the `First Min` and `Second Min` values from the previous row. If current column matches First Min's column, add Second Min. Otherwise, add First Min. |
Draw two rows of a grid. Above row 1, write "Min1: 5 (Col 2), Min2: 8 (Col 4)". For each cell in row 2, just look at these two values. If you are in Col 2, take 8. Otherwise, take 5. |
Linear Row Processing |
Draw a grid. Show each row being processed by looking only at two summary values from the row above. Write $O(N^2)$. |
Draw an enormous recursive tree with N^N nodes. |
Draw exactly two 1D arrays of size N (or just track 4 variables for the mins). Space: $O(N)$. |
| 1290 |
Convert Binary Number in a Linked List to Integer |
Traverse the list to store all values in an array. Reverse the array. Iterate through the array and for index i, add val * 2^i to the result. |
Two-Pass Array Conversion |
Draw a linked list. Draw an arrow to an array. Draw another arrow to a reversed array. Draw a final arrow to a summation box. Write $O(N)$ with two passes. |
Bit Manipulation (Left Shifting) |
The "Rolling Snowball" Left-Shift |
Initialize `res = 0`. As you move to each node, shift your current result left by 1 (`res << 1`) and add the current node's value (`res | node.val`). This builds the number bit-by-bit from the most significant to least significant. |
Draw a linked list: 1 -> 0 -> 1. Below it, draw a box `res`. Step 1: `res = 1`. Step 2: Shift `res` (becomes 10 in binary) and add 0. Step 3: Shift `res` (becomes 100 in binary) and add 1. Final: 101 (5). |
Single-Pass Linear Scan |
Draw a linked list. Draw one single arrow moving purely left-to-right once. Write $O(N)$. |
Draw an extra array of size N to store the bits. |
Draw exactly one integer variable `res`. Space: $O(1)$. |
| 1291 |
Sequential Digits |
Iterate from `low` to `high`. For every number, check if all adjacent digits have a difference of 1 and are strictly increasing. |
1D Linear Range Exhaustion |
Draw a massive number line from 10 to 10^9. Draw a tiny magnifying glass over every single number. Write $O(\text{High} - \text{Low})$. |
Sliding Window on Digit String "123456789" |
Substring Frame over "123456789" |
All sequential numbers are substrings of "123456789". Try all possible window lengths (from length of `low` to length of `high`) and slide them across the string. If the resulting number is in range, add to result. |
Write "123456789" on paper. Draw a bracket of length 2: [12], [23]... then length 3: [123], [234]... and so on. Check each against the `low`/`high` boundaries. |
Constant-Bounded Substring Scan |
Draw the string "123456789". Show about 36 possible windows. Write $O(1)$ because the max number of sequential digits is fixed (45 total). |
Draw nothing extra, but note the extreme time waste of millions of checks. |
Draw a small result list and one constant string "123456789". Space: $O(1)$. |
| 1292 |
Maximum Side Length of a Square with Sum Less than or Equal to Threshold |
For every cell (i, j), try squares of all possible side lengths k. For each square, sum all elements manually to check the threshold. |
Brute Force Volume Scan |
Draw a grid. For one cell, draw a 1x1, 2x2, 3x3 square. For each, shade every inner cell. Write $O(M \cdot N \cdot \\text{min}(M,N)$^3). |
2D Prefix Sum + Binary Search (or Greedy Side Length) |
Integral Image / Region Sum |
Pre-calculate a 2D prefix sum. Now, the sum of any square can be found in $O(1)$. Since side lengths are monotonic, for each cell, check if a square of `current_max_side + 1` is valid. If so, increment and repeat. |
Draw a grid. Draw the formula: `Sum = P[i][j] - P[i-k][j] - P[i][j-k] + P[i-k][j-k]`. Show how 4 points on the prefix sum grid replace thousands of additions. |
Linear Grid Traversal with $O(1)$ Checks |
Draw a grid. Show a single sweep. At each cell, show a single $O(1)$ lookup. Write $O(M \cdot N)$. |
Draw no extra memory but massive re-scans of the input grid. |
Draw a 2D Prefix Sum matrix of size (M+1) x (N+1). Space: $O(M \cdot N)$. |
| 1293 |
Shortest Path in a Grid with Obstacles Elimination |
Standard BFS exploring only `(row, col)`. This fails because you might need to take a longer path to save an "elimination" for later. |
Missing Path State |
Draw a grid with obstacles. Draw a BFS that stops at an obstacle. Draw a red "X" showing the path blocked despite having elimination power. |
BFS on 3D State (row, col, k) |
Layered Grid Exploration |
The state is `(row, col, remaining_k)`. You can visit the same `(row, col)` multiple times as long as you have a different number of `k`. A queue manages the shortest path (distance) layer by layer. |
Draw 3 identical grids stacked like floors in a building. Floor 0: k=0 left. Floor 1: k=1 left. If you hit an obstacle on Floor 1, draw an arrow moving to a regular cell on Floor 0. |
Bounded 3D State BFS |
Draw a cube representing M x N x K. Shade the BFS expansion inside it. Write $O(M \cdot N \cdot K)$. |
Draw a simple 2D visited array that leads to infinite loops or wrong answers. |
Draw a 3D boolean array `visited[m][n][k]` or a Set of 3-tuples, plus a BFS Queue. Space: $O(M \cdot N \cdot K)$. |
| 1294 |
Weather Type in Each Country (SQL) |
For every country, run a correlated subquery for the month of November 2019 to calculate the average weather state. |
Row-by-Row Country Scan |
Draw the Countries table. For every row, draw a search arrow that scans the entire Weather table. Write $O(\text{Countries} \\text{cdot Weather})$. |
JOIN + GROUP BY + CASE/IF logic |
Aggregate Filtering Funnel |
Join `Countries` and `Weather` on `country_id`. Filter specifically for `day` in November 2019. Group by `country_name` and calculate `AVG(weather_state)`. Use `CASE` to categorize the average into 'Cold', 'Warm', or 'Hot'. |
Draw two tables. Join them. Draw a filter box that only lets "2019-11" rows through. Group those by country. Show a calculator finding the average and a "Branching Logic" box deciding the category. |
Linear Scan & Sort |
Draw a filtered table. Draw a single arrow scanning to aggregate. Write $O(\text{Weather} \\text{log Weather})$ (due to sorting/grouping). |
Draw multiple temporary result tables for each country's sub-query. |
Draw a single intermediate joined table result, processed in one grouping pass. |
| 1295 |
Find Numbers with Even Number of Digits |
Convert every number to a string and check the length of that string. If `length % 2 == 0`, increment the count. |
String Conversion Scan |
Draw an array. For every number, draw an arrow to a "String Box". Count the characters in the box. Write $O(N \cdot D)$ where D is number of digits. |
Logarithmic Digit Counting / Range Check |
Mathematical Threshold Comparison |
Instead of strings, check if the number falls in specific ranges: [10, 99], [1000, 9999], [100000, 1000000]. Alternatively, use lfloor log_10(n) rfloor + 1 to get the digit count. |
Draw a number line. Mark "Even Digit Zones" with green shading and "Odd Digit Zones" with red. For each number in the array, simply check if it falls in a green zone. |
Linear Pass with Constant Operations |
Draw an array. Draw one single arrow scanning once. For each element, draw a simple "If/Else" gate. Write $O(N)$. |
Draw a temporary string buffer for every single element in the array. |
Draw zero extra data structures. Space: $O(1)$. |
| 1296 |
Divide Array in Sets of K Consecutive Numbers |
Sort the array. For the smallest available number X, search for X+1, X+2, dots, X+k-1. If all are found, remove them. Repeat until empty. |
Nested Search and Destroy |
Draw a sorted array. For the first element, draw arrows searching for consecutive partners. If found, cross them out. Repeat. Write $O(N^2)$. |
Frequency Map + Greedy Sorting |
Consecutive Block Clearing |
Use a TreeMap to store `value -> frequency`. Take the smallest key X. If it has frequency F, then X+1, dots, X+k-1 must each have at least frequency F. Subtract F from all. If any don't exist or have too low frequency, return False. |
Draw a table: [Num | Freq]. Pick the lowest Num. Draw a bracket of length K. Subtract the count from all numbers in that bracket. Show the bucket levels dropping simultaneously. |
Ordered Frequency Scanning |
Draw a sorted frequency list. Draw a window of size K sliding across it. Write $O(N \log N)$. |
Draw a sorted array being modified/shortened repeatedly. |
Draw a TreeMap or a sorted HashMap. Space: $O(N)$. |
| 1297 |
Maximum Number of Occurrences of a Substring |
Generate every possible substring of length between `minSize` and `maxSize`. For each, check if the number of unique characters <= `maxLetters` and count occurrences. |
All-Substring Exhaustion |
Draw a string. Draw brackets for every possible length between min/max. For each, scan for unique chars. Write $O(N^2)$. |
Sliding Window (Observation: minSize only) |
Fixed-Width Frequency Map |
Key Insight: If a string of length `maxSize` satisfies the condition, its prefix of length `minSize` *also* satisfies it. Thus, you only need to check substrings of length `minSize`. Use a sliding window to count occurrences in a Map. |
Draw a string. Draw a fixed-width window of `minSize`. Slide it one character at a time. For each position, check unique letters (using another tiny map) and store the substring in a "Global Frequency" Map. |
Linear Rolling Window |
Draw a string. Draw a sliding box of size `minSize`. Write $O(N)$. |
Draw a massive list of all possible substrings of various lengths. |
Draw a single HashMap: `Substring -> Frequency`. Space: $O(N \\text{cdot minSize})$. |
| 1298 |
Maximum Candies You Can Get from Boxes |
Recursively open boxes. If you find a box you can't open (no key), store it and check back every time you find a new key. |
Unstructured Recursive Search |
Draw a tree of boxes. Draw lines looping back from keys to previously locked boxes. Write $O(N^2)$ due to repeated re-scanning of "waiting" boxes. |
BFS with Two-Condition Entry (Keys + Possession) |
The "Ready-to-Open" Queue |
Maintain three states: `HasBox` (Boolean array), `HasKey` (Boolean array), and `Visited`. When you get a box, mark `HasBox`. When you get a key, mark `HasKey`. A box enters the BFS queue only if `HasBox AND HasKey AND !Visited`. |
Draw a "Holding Area" for locked boxes and a "Keychain". When a new key comes, check the Holding Area. If the box is there, move it to the "Open Queue". When a new box comes, check the Keychain. |
Single-Pass State Graph |
Draw a directed graph where nodes are boxes. Write $O(N + K)$ where N is boxes and K is total keys/contained boxes. |
Draw many nested lists representing recursive calls. |
Draw two boolean arrays of size N and a Queue. Space: $O(N)$. |
| 1299 |
Replace Elements with Greatest Element on Right Side |
For every element at index i, scan the entire sub-array from i+1 to N-1 to find the maximum value. Replace `arr[i]` with that max. |
Nested Max Scanning |
Draw an array. For index 0, draw an arrow scanning all remaining elements. For index 1, scan again. Write $O(N^2)$. |
Reverse Linear Scan (Right-to-Left) |
The "Backwards Max" Rolling Variable |
Start from the last element. The last element is replaced by -1. Keep a running variable `maxSoFar`. As you move left, the current element's replacement is the current `maxSoFar`. Update `maxSoFar` with the original value of the current element. |
Draw an array. Place an arrow at the very end. Move the arrow left. Write down `max_val` and update it as the arrow passes each number. Show the numbers being overwritten by the *previous* `max_val`. |
Single Linear Pass |
Draw an array. Draw one single arrow moving purely right-to-left once. Write $O(N)$. |
Draw nothing extra, but note the $O(N^2)$ time complexity. |
Draw exactly one integer variable `maxSoFar`. Space: $O(1)$. |
| 1300 |
Sum of Mutated Array Closest to Target |
Iterate through every possible integer value for 'value' from 0 to the maximum element in the array. For each, calculate the mutated sum and track the one closest to target. |
Linear Value Scan |
Draw a horizontal line from 0 to Max. For every integer point, draw a vertical line representing a full array scan. Write $O(\text{Max} \cdot N)$. |
Binary Search on Value Range |
Sum-Monotonicity Curve |
As 'value' increases, the mutated sum increases monotonically. Use binary search between 0 and Max. At each 'mid', calculate the mutated sum. Move left or right depending on whether you are over or under the target. |
Draw a range [0, Max]. Pick 'mid'. Show the array: elements > mid are capped at mid. Calculate sum. If sum < target, shift L to mid + 1. Note: Check both 'ans' and 'ans-1' at the end for "closest". |
Logarithmic Search with Linear Check |
Draw a block being halved repeatedly. Inside each, a single array scan arrow. Write $O(N \log(\text{Max})$). |
Draw no extra data structures but highlight the high CPU usage of the loop. |
Draw 3-4 integer variables (low, high, mid, best_val). Space: $O(1)$. |
| 1301 |
Number of Paths with Max Score |
Use simple recursion (DFS) to find every possible path from 'S' to 'E'. For each path, calculate the sum of digits and count paths that hit the maximum found. |
Exponential Path Tree |
Draw a grid. From 'S', draw arrows to Up, Left, and Diagonal. From those, branch again. The tree grows to size 3^N. Write $O(3^N)$. |
2D Dynamic Programming (Suffix-Sum style) |
Grid Propagation (Max & Count) |
Start from the target 'E'. Each cell (i, j) stores two values: [Max Score to reach E, Number of ways to get that Max]. Update each cell by looking at its neighbors (Down, Right, Bottom-Right). |
Draw the board. Start at bottom-right. Move towards top-left. In each cell, write two numbers. Use arrows to show the "best" score being pulled from neighbor cells into the current one. |
Linear Grid Scan |
Draw a grid. Show a single sweep from bottom-right to top-left. Write $O(N^2)$. |
Draw a massive recursion stack storing millions of path segments. |
Draw two 2D integer arrays (or one 2D array of pairs) of size N x N. Space: $O(N^2)$. |
| 1302 |
Deepest Leaves Sum |
Traverse the tree once to find the maximum depth. Traverse a second time to find all leaves at that depth and sum their values. |
Two-Pass DFS |
Draw a tree. Draw a full sweep coloring all nodes to find height. Draw another sweep coloring only the bottom-most nodes. Write $O(N)$. |
BFS (Level-Order Traversal) |
Level-by-Level Sum Reset |
Use a Queue for BFS. For each level, calculate the sum of its nodes. Every time you start a new level, reset the sum. The sum remaining after the last level is processed is the result. |
Draw a tree. Draw horizontal "clouds" circling each level. Next to each cloud, write the sum of the nodes inside it. Cross out the previous sum as the next cloud is calculated. |
Single-Pass Breadth Scan |
Draw a tree. Draw an arrow snaking through levels from top to bottom. Write $O(N)$. |
Draw a recursion stack of height H. |
Draw a Queue that stores at most one level of the tree (max width W). Space: $O(W)$. |
| 1303 |
Find the Team Size (SQL) |
For every employee, run a correlated subquery that counts the number of employees sharing the same team_id. |
Row-by-Row Correlation |
Draw the Employee table. For every row, draw an arrow that scans the entire table again looking for matching team_ids. Write $O(N^2)$. |
Window Function (COUNT OVER PARTITION) |
Data Partitioning Buckets |
Use `COUNT(employee_id) OVER(PARTITION BY team_id)`. This logic groups team_ids behind the scenes once and maps the count back to every row in that group. |
Draw a table. Draw boxes around rows with the same `team_id`. Count the rows in each box and write that number into a new column for every row inside that box. |
Linear Sort/Hash Aggregate |
Draw a single pass scanning a sorted or hashed table. Write $O(N \log N)$ or $O(N)$ depending on SQL engine. |
Draw multiple temporary result tables created for each subquery. |
Draw a single temporary Hash Map of Team IDs to Counts stored in memory. |
| 1304 |
Find N Unique Integers Sum up to Zero |
Use a randomized search or backtracking to pick N unique numbers and check if their sum is 0. If not, backtrack and try again. |
Randomized Search Space |
Draw a bag of numbers. Draw branches picking different sets. Write $O(\text{Explosive})$. |
Symmetric Construction (Pairing) |
Zero-Centered Balance |
Construct pairs of (i, -i) starting from 1. For n=5, use (1, -1, 2, -2) and then add a 0. For n=4, use (1, -1, 2, -2). This guaranteed uniqueness and a zero sum. |
Draw a number line with 0 in the center. Mark 1 and -1, then 2 and -2. Show how they "cancel out" back to zero. If N is odd, put a dot on 0. |
Single-Pass Array Fill |
Draw an array of size N. Draw a single arrow filling it from left to right. Write $O(N)$. |
Draw many discarded arrays during randomized trials. |
Draw one integer array of size N. Space: $O(N)$ for the result. |
| 1305 |
All Elements in Two Binary Search Trees |
DFS traverse both trees, append all nodes into a single unorganized array, and run QuickSort on the combined array. |
Array Concatenation + Sorting Funnel Graph |
Draw two trees pointing into two messy arrays. Join them into one large array, and draw a massive sorting algorithm funnel processing $O(K \log K)$ steps. |
In-order DFS + Two-Pointer Merge |
Two Parallel Sorted Streams |
Extract Tree 1 into Array A, Tree 2 into Array B. Place pointer `i` at start of A and `j` at start of B. Point to smaller item, copy to Result, advance that pointer. |
Draw two arrays, A and B. Draw two distinct arrows (i and j). Compare the values they point to. Write the smaller value into a new output array at the bottom. |
Dual Linear Progression Rails |
Draw two horizontal bars of length N and M. Draw an arrow sweeping smoothly from left to right across both, proving strictly $O(N+M)$ steps. |
Dynamic Expanding Array: Draw a single block expanding unpredictably as nodes are discovered, before a massive memory shuffle (sorting). |
Three Contiguous Blocks: Draw two size-bound arrays (N and M) and one final output array (N+M) with static memory boundaries. |
| 1306 |
Jump Game III |
Blindly branch into `i + arr[i]` and `i - arr[i]` recursively without marking indices as visited, resulting in infinite loops. |
Cyclic Infinite Binary Recursion Tree |
Draw root 'start' index. Branch left and right based on math. Draw red circular looping arrows pointing back to upper levels to show an infinite cycle trap. |
Graph BFS / DFS with Visited Array |
Directed Graph State Traversal |
Draw the array indices as circles. Draw an edge from index 'i' to 'i + arr[i]' and 'i - arr[i]'. Start at the given node. Paint circles grey once visited. Stop when hitting '0'. |
Draw array elements. Put your pen on the start index. Draw an arc to the next calculated index. Put an 'X' over the current index so you don't return. Continue to '0'. |
Graph Node-Edge Visitation Tracking |
Draw N unshaded nodes. Show exactly 2 outgoing edges per node. Shade nodes one-by-one. Prove that no node is shaded twice, yielding exactly $O(N)$ time complexity. |
Unbounded Call Stack: Draw stacked memory frames that pile up infinitely due to cycle repetition until a StackOverflow exception occurs. |
Array-based Hash Set & Queue: Draw a fixed size boolean array (Visited checks) sitting next to a dynamically sizing FIFO Queue. |
| 1307 |
Verbal Arithmetic Puzzle |
Generate all permutations of 0-9 for up to 10 unique characters, fully evaluating the entire equation string to test validity. |
10-ary Permutation Tree |
Draw a root node. Branch 10 times for the first letter, 9 for the next. Show a massive tree of 10! (3.6M) leaf nodes where full equations are calculated. |
Backtracking DFS with Column-by-Column Pruning |
Column-Addition Grid Space |
Write the words stacked vertically like primary school addition. Start right. Assign digits, calculate `sum % 10` and `carry`. Immediately reject paths if the column doesn't match the result string. |
Stack words. Draw a box around the rightmost column. Write assigned numbers above letters. Draw an arrow carrying the 10s place to the next column left. |
Severely Pruned DFS Tree |
Draw the permutation tree, but immediately place a red "X" right beneath the root on most branches, proving invalid sums cut off thousands of paths instantly. |
Deep Call Stack + Mutable Array: Deep recursive frames passing heavy string states. |
Static Map & Bitmask: Draw a 26-slot fixed array mapping characters to digits, paired with a 10-bit integer bitmask locking used numbers. |
| 1308 |
Running Total for Different Genders (SQL) |
Correlated Subquery: For every single row, run a separate query to sum all previous dates. $O(N^2)$. |
Nested Scanning Grid |
Draw a table. For row 10, draw an arrow scanning rows 1-9. For row 11, scan 1-10. The arrows form a dense triangle. |
Window Functions (SUM OVER) |
The Ordered Accumulator |
Partition the data by gender, sort by date. Maintain a running sum that updates as the "window" slides down. |
Draw two boxes (Male/Female). List dates vertically. Draw an arrow moving down once, updating a cumulative tally. |
Sort + Single Pass $O(N \log N)$ |
Draw a sorting tree followed by a single straight line representing the $O(N)$ accumulation pass. |
Multiple temporary result sets in memory. |
A single buffer holding current_sum. $O(1)$ space. |
| 1309 |
Decrypt String from Alphabet to Integer |
Scan left-to-right. On '1' or '2', branch into "single-digit" vs "double-digit" recursive paths, backtracking if a '#' is not found later. |
Lookahead Reversal Branching |
Draw string as a tape. Move pointer right. When hitting 1 or 2, split into two paths, crossing one out upon hitting/missing '#'. |
Single-Pass Reverse Scan (Right-to-Left Pointer) |
Reverse Tape Reading |
Place pointer at string's end. If char is '#', read the two chars to its left, decode, and jump left by 3. Otherwise, decode the single char and jump left by 1. |
Draw string. Place arrow at end pointing left. Draw a big leap arc (3 chars wide) when landing on '#', and a small step arc (1 char wide) otherwise. |
Single Continuous Backward Arrow |
Draw the string array with a single uninterrupted line starting at index N-1 and ending at 0, indicating strictly $O(N)$ ops. |
Recursive String Builder: Intermediate substring copies piling up in memory. |
Static Output Buffer: Draw an empty `std::string` buffer. Fill backward, then apply a final `std::reverse` to avoid costly prepends. |
| 1310 |
XOR Queries of a Subarray |
For each query [L, R], iterate through the array from L to R and compute the cumulative XOR sum manually. |
Overlapping Subarray Scans |
Draw array. For each query, draw horizontal brackets over [L, R]. Show brackets heavily overlapping, indicating redundant $O(Q \cdot N)$ operations. |
Prefix XOR Array (Cumulative State Cache) |
Cumulative State Blocks |
Calculate `prefix[i] = prefix[i-1] ^ arr[i]`. To solve query [L, R], look up `prefix[R]` and `prefix[L-1]`, then XOR them together. |
Draw `arr`. Below it, draw `prefix`. To solve [L, R], draw a circle around `prefix[R]` and `prefix[L-1]`, connecting them with an XOR gate symbol. |
Two-Step $O(1)$ Lookup |
Draw Q dots (queries). Draw exactly 2 straight lines from each dot down to the prefix array, proving $O(1)$ work per query. |
Accumulator Variable: No complex structure, just an integer resetting repeatedly. |
Parallel Cache Array: Draw `std::vector arr` next to a `std::vector prefix_xor` of size N+1 acting as a permanent lookup table. |
| 1311 |
Get Watched Videos by Your Friends |
Run DFS from the start, find all possible paths, filter nodes that are exactly distance K, then aggregate and sort their videos. |
Unbounded Graph Traversal |
Draw a graph. Trace multiple twisting, looping paths from start, crossing out paths exceeding distance K, highlighting redundant node visits. |
Level-Order BFS + Frequency Map Sort |
Concentric Ripples / Graph Layers |
Put start in Queue. Pop, push unvisited neighbors. Repeat exactly K times (like pond ripples). Dump Level-K node videos into a frequency map, then sort. |
Draw start node. Draw a circle around it (Level 1), then a wider circle (Level 2). Stop at K. Dump videos from circle K into a bucket and tally. |
Breadth-First Expansion Wave |
Draw an expanding funnel. The traversal hits a hard barrier (Level K). Draw an arrow pointing to a sorting funnel (O(V log V) for V videos). |
Massive Call Stack: Thousands of overlapping path histories and visited states. |
Queue, Visited Set, Map: Draw a `std::queue` for expansion, a `std::vector` visited array, and a `std::unordered_map` for frequency. |
| 1312 |
Min Insertions to Make String Palindrome |
Try inserting every possible character at every possible index and recursively check if the result is a palindrome. |
Exponential Insertion Tree |
Draw string. At every gap, draw arrows outward representing 26 possible letter insertions. The tree explodes with $O(2^N)$ branching. |
2D DP: Longest Common Subsequence (LCS) |
2D DP LCS Matrix |
Reverse string `s` to get `rev_s`. Find LCS between `s` and `rev_s`. The minimum insertions required is simply `length(s) - LCS`. |
Draw a grid with `s` on top and `rev_s` on the left. Fill cells diagonally if chars match (+1), or take max of top/left if not. Subtract bottom-right value from N. |
N x N Matrix Fill |
Draw a square box (N x N space). Draw a zigzag line sweeping top-left to bottom-right, showing strict $O(N²)$ calculation bounds. |
Heavy String Mutation Stack: Heavy recursive frames holding thousands of copied and modified string variations. |
Space-Optimized DP Arrays: Draw two 1D `std::vector` arrays (`prev` and `curr`). Show data cascading down, proving $O(N)$ memory replaces the $O(N²)$ matrix. |
| 1313 |
Decompress Run-Length Encoded List |
Iterate pairwise, repeatedly calling `push_back` on a dynamic array for every single frequency count, triggering multiple memory reallocations. |
Staircase Array Resizing |
Draw an array growing. Show it hitting capacity, creating a larger array, copying elements over, and deleting the old one. Repeat this $O(N)$ reallocation process. |
Pre-allocation + Linear Fill |
Contiguous Memory Block Reservation |
Pass 1: Sum all frequencies at even indices. Pass 2: Allocate an array of exactly that total size. Fill it using a direct index pointer. |
Draw the input array. Circle the even indices and write their sum. Draw a final, strictly bounded output array of that exact length. Fill it left-to-right. |
Single Static Bar Graph |
Draw a fixed-width bar representing $O(S)$ time, where S is the sum of all frequencies. No expanding bounds. |
Dynamic Vector: Draw a `std::vector` block that shatters and duplicates into larger sizes as capacity is breached. |
Pre-sized Vector: Draw a `std::vector` initialized with `.reserve(total_size)` or a direct size constructor. No resizing occurs. |
| 1314 |
Matrix Block Sum |
For every single cell (i, j), run a nested 2D loop iterating from `i-k` to `i+k` and `j-k` to `j+k` to sum the block. |
Overlapping Iteration Grids |
Draw a matrix. For cell A, draw a bounding box. For adjacent cell B, draw a nearly identical bounding box. Shade the heavily overlapping redundant cells darkly. |
2D Prefix Sum Array |
Area Subtraction Geometry |
Compute `prefix[i][j]` as the sum from (0,0) to (i,j). For any block, calculate: Total Area - Top Area - Left Area + Top-Left Overlap (Inclusion-Exclusion Principle). |
Draw the prefix matrix. To find a block sum, circle the bottom-right corner. Draw lines subtracting the top and left boundaries, then add back the doubly-subtracted top-left corner. |
Four-Point $O(1)$ Lookup |
Draw a matrix. Draw exactly 4 dots at the corners of a target block. Connect them with +/- operators, proving $O(1)$ time per query. |
Accumulator Variables: Transient integers recalculating overlapping data inside $O(M\cdot N\cdot K^2)$ loops. |
2D Matrix Cache: Draw a `std::vector>` padded with an extra top row and left column (1-indexed) to avoid out-of-bounds checks. |
| 1315 |
Sum of Nodes with Even-Valued Grandparent |
For every node, traverse upwards (if parent pointers exist) or do a localized search to confirm its grandparent's value, duplicating tree traversals. |
Redundant Up-Down Tree Traversal |
Draw a tree. From a leaf, draw an arrow up to the parent, then up to the grandparent. Repeat for every node, showing massive overlap in path tracing. |
Top-Down DFS with State Passing |
Generational State Cascade |
Start DFS at root. Pass `parent_val` and `grandparent_val` as function arguments to children. If `grandparent_val % 2 == 0`, add current node's value to a global sum. |
Draw a tree. Next to each node, draw a small tag: `[P: x, GP: y]`. As you draw arrows down to children, shift the values: current becomes P, P becomes GP. |
Single Pass $O(N)$ Tree Sweep |
Draw a single, uninterrupted line winding through every node in the tree exactly once. |
Heavy Call Stack + Lookups: Deep stack frames querying external maps or parent pointers repeatedly. |
$O(H)$ Call Stack Frame: Draw a stack of memory frames of height H (tree height). Each frame holds only exactly 3 integers: `node`, `parent`, `grandparent`. |
| 1316 |
Distinct Echo Substrings |
Generate all possible substrings $O(N^2)$, split each in half, compare them for equality $O(N)$, and store them in a Set. Overall $O(N^3)$. |
Massive String Slicing Tree |
Draw a word. Draw dozens of brackets extracting every possible substring. Draw a scissors icon cutting each in half, and a balance scale comparing them. |
Rolling Hash (Rabin-Karp) + Hash Set |
Sliding Window Hash Comparison |
Precompute prefix hashes. For any length L, compare the hash of `str[i...i+L-1]` against `str[i+L...i+2L-1]` in $O(1)$ time. If they match, add the hash to a set. |
Draw an array representing a string. Draw two contiguous boxes of length L. Write a numeric "Hash Code" inside each box. Compare the two numbers directly. |
Dual Sliding Windows |
Draw a string array. Show two adjacent, fixed-size windows sliding left-to-right together, demonstrating $O(N^2)$ total comparisons instead of $O(N^3)$. |
String Pool Explosion: Draw hundreds of distinct `std::string` objects filling up memory from `substr()` calls. |
Numeric Hash Set: Draw a `std::unordered_set` storing only 64-bit integer hashes, drastically reducing memory footprint compared to string storage. |
| 1317 |
Convert Integer to the Sum of Two No-Zero Integers |
Convert numbers A and B to strings and run string search algorithms to check for '0' inside a heavy iteration loop. |
String Conversion Overhead |
Draw an integer passing through a "toString()" factory, then a magnifying glass scanning the characters for '0'. Note the extreme $O(Log N)$ string allocation overhead per loop. |
Math/Modulo Zero-Check Loop |
Base-10 Digit Extraction |
Loop A from 1 to N. Set B = N - A. Check if A or B contains zero by repeatedly doing `val % 10 == 0` and `val /= 10`. Return the first valid pair. |
Draw integer N. Split into A and B. Draw a division bracket showing `modulo 10` popping off the last digit. If it's a zero, cross out the pair and try the next. |
Logarithmic Digit Peeling |
Draw a number. Draw arrows peeling off digits right-to-left. Show that checking a number takes strictly $O(\log10(N)$) integer math operations. |
String Allocation Trashing: Heap memory fragmentation from repeatedly allocating and destroying small string objects. |
$O(1)$ Register Variables: Draw a CPU register holding simple integer values `A`, `B`, and `temp`. No heap allocations required. |
| 1318 |
Minimum Flips to Make a OR b Equal to c |
Convert A, B, and C to full 32-bit binary strings, pad them with leading zeros, and manually compare string indices. |
Stringified Binary Alignment |
Draw three long 32-character arrays of '1's and '0's. Draw a pointer moving column by column, doing character comparisons. |
Bitwise Operations & Masking |
Vertical Bit-Column Alignment |
Iterate through all 32 bits. Extract the i-th bit of A, B, and C using `(val >> i) & 1`. If `bit_c == 1`, flip A or B if both are 0. If `bit_c == 0`, flip A and B if they are 1. |
Stack A, B, and C vertically as binary numbers. Draw a vertical box around a single column of bits. Apply the logic rules to count flips for that specific column. Move right-to-left. |
32-Step Bit Shift |
Draw a fixed 32-slot grid. Show an arrow sweeping across exactly 32 times, proving strict $O(1)$ total time regardless of integer size. |
Allocated String Buffers: Three 32-byte strings resting in dynamic memory. |
Bitwise Registers: Draw pure CPU-level bit manipulation. Memory is strictly $O(1)$ auxiliary space using basic integer variables. |
| 1319 |
Number of Operations to Make Network Connected |
Build a full adjacency list, run standard DFS multiple times to count components, and use a massive Set to track all redundant edges individually. |
Redundant Edge Spaghetti Graph |
Draw computers as nodes and cables as edges. Use a red marker to circle cables that form cycles. Erase them and manually draw them to isolated nodes. Shows chaotic $O(V + E)$ overhead. |
Union-Find (Disjoint Set) |
Forest Component Clustering |
Start with N isolated nodes. For each cable, union the two nodes. If they are already in the same set, increment `extra_cables`. At the end, count total root nodes. Result is `roots - 1` (if `extra >= roots - 1`). |
Draw N dots. As you read edges, draw lines grouping them into blobs. Count the disconnected blobs. Count edges that try to connect two dots inside the same blob. |
Flat Tree Array Collapses |
Draw an array mapping `i` to `parent[i]`. Show long chains of arrows collapsing into a single direct pointer to a root, visualizing $O(α(N)$) Inverse Ackermann time. |
Fat Adjacency List: Draw an array of `std::vector` that allocates heavily on the heap for every single edge. |
1D Parent Array: Draw a single flat contiguous `std::vector` array. Extremely cache-friendly and strictly $O(N)$ space. |
| 1320 |
Minimum Distance to Type a Word |
Pure recursion without memoization. At each letter, branch into two parallel universes: Finger 1 types it, OR Finger 2 types it. |
Exponential Binary Fork Tree |
Draw the root letter. Draw two branches (F1 moves, F2 moves). Repeat for every letter in the word. Tree explodes massively showing $O(2^N)$ paths. |
3D Dynamic Programming / Memoization |
Two-Finger State Matrix |
Track `dp(index, finger1_pos, finger2_pos)`. To type the next letter, calculate the minimum of `dp(next, next_char, f2)` + dist(f1, next) AND `dp(next, f1, next_char)` + dist(f2, next). |
Draw an alphabet grid. Place two coins on it representing fingers. Move one coin to the next letter, note the distance. Reset and move the other coin. Record the smaller sum. |
N x 26 x 26 State Cuboid |
Draw a 3D box (length N, width 26, height 26). Shade cells sequentially layer by layer, showing strict $O(N \cdot 26 \cdot 26)$ bounds. |
Unbounded Call Stack: Deep recursive frames blowing up memory with massive duplicate state evaluations. |
3D DP Array: Draw a static `int[][][]` table. Even better, draw two 2D layers swapping (Space Optimization to $O(1)$ auxiliary size). |
| 1321 |
Restaurant Growth (SQL) |
Use Correlated Subqueries. For every single date in the table, scan the entire table again to find rows within the last 6 days and sum them up. |
Overlapping Full Table Scans |
Draw a table. For row 10, draw an arrow scanning rows 4-10. For row 11, draw an arrow scanning rows 5-11. Highlight the heavily overlapping $O(N^2)$ disk reads. |
Window Functions (Sliding Window) |
Sliding Partition Frame |
First, aggregate sales by day. Then apply `SUM(amount) OVER (ORDER BY visited_on ROWS BETWEEN 6 PRECEDING AND CURRENT ROW)` to get the moving sum in $O(N)$. |
Draw the dates stacked vertically. Draw a rectangular box capturing 7 days. Slide the box down one row at a time, keeping a running total inside the box. |
Linear Single-Pass Tape |
Draw a dataset as a tape. Show one read head sliding down, maintaining a running total buffer of 7 items, proving $O(N)$ sequential reads. |
Massive Temp Tables: Database engines generating huge intermediate N x N row sets in memory. |
In-Memory Queue Buffer: The DB engine uses a fixed 7-row memory buffer sliding down the sorted cursor. |
| 1322 |
Ads Performance (SQL) |
Calculate clicks and views separately using two independent subqueries for every ad_id, then join them. |
$O(N²)$ Correlated Subquery Overhead |
Draw an Ad table. For each row, draw two arrows scanning the whole Click table and the whole View table. Shows redundant IO. |
Conditional Aggregation (SUM + CASE) |
Single-Pass Result Bucket |
Group by `ad_id`. Use `SUM(CASE WHEN action='Clicked' THEN 1 ELSE 0 END)` to count clicks and views in one scan. Use `NULLIF` to handle division by zero. |
Draw a table of actions. Draw a funnel with two counters: "Clicks" and "Views". Scan once. Calculate `Clicks/(Clicks+Views) * 100`. |
$O(N \log N)$ (Sort + Group) |
Draw a single line passing through the sorted table. Each ad's data is aggregated in one contiguous block. |
Temporary Join Tables: Database creating huge intermediate tables in memory. |
In-Memory Hash Map: Draw a small hash table keyed by `ad_id` storing click/view tallies. |
| 1323 |
Maximum 69 Number |
Convert the integer to a string, generate all N possible string variations by replacing one digit, parse all back to integer, and use `max()`. |
String Factory Overhead |
Draw an integer entering a factory, splitting into multiple `String` objects, undergoing character replacement, parsing back to integers, and fighting for the highest value. |
First-Occurrence String Search / Math |
Left-to-Right Greedy Scan |
Convert to string/char array. Scan strictly left-to-right. The absolute first time you see a '6', change it to '9' and instantly return. |
Write the number. Put your pen on the leftmost digit. Move right. If you see a '6', cross it out, write '9', and stop immediately. |
Single Short-Circuit Arrow |
Draw an array of digits. Draw a single arrow pointing left-to-right that abruptly stops in the middle, proving worst-case $O(L)$ where L is length. |
Garbage Collection Nightmare: Repeated heap allocations for temporary strings throwing off the garbage collector. |
In-place Char Array Mutation: Convert to `std::string` or `char[]`, mutate one byte in-place, and `stoi()` back. Negligible memory footprint. |
| 1324 |
Print Words Vertically |
Create a massive NxM 2D character matrix filled entirely with spaces. Loop through words, placing chars precisely, then scan column-by-column to build outputs. |
Sparse Matrix Wasted Space |
Draw a large grid. Write a small word. Leave dozens of empty cells (wasted space) before the next word. Highlight the padding overhead. |
Parallel StringBuilder Appending |
Vertical Typewriter Columns |
Find max word length `max_len`. Create an array of `max_len` StringBuilders. Iterate through the words array. Append the i-th character of the word to the i-th StringBuilder (or a space if out of bounds). |
Draw vertical columns. For each word in the string, read it top-to-bottom. Drop its letters down into the respective columns one by one like a Tetris piece. |
Dynamic String Expansion |
Draw distinct vertical bars of varying heights. Show them extending smoothly downward only when characters are actually added, proving optimal $O(N)$ time. |
Fixed 2D Char Array: Allocating `O(Words * MaxLength)` contiguous memory, heavily populated with useless space characters. |
Array of Dynamic Builders: Draw a `std::vector`. Each string dynamically sizes to its required length. A final `.trimRight()` drops trailing spaces efficiently. |
| 1325 |
Delete Leaves With a Given Value |
Repeated Pre-Order scans. Traverse the entire tree to find target leaves. Delete them. If the tree changed, start a completely new traversal from the root. |
$O(N²)$ Redundant Tree Sweeps |
Draw a tree. Sweep top-to-bottom and cross out leaves. Because a parent is now a leaf, you must draw a completely new top-to-bottom sweep again. |
Bottom-Up Post-Order DFS |
Recursive Pruning from Leaves |
Process children first. `node.left = dfs(node.left)`, `node.right = dfs(node.right)`. AFTER children are resolved, check if the current node is now a leaf with the target value. If so, return `null`. |
Draw a tree. Start strictly at the bottom leaves. If a leaf matches, erase it. Move up to the parent. The parent realizes it has no children left. If it matches, erase it too. |
Single-Pass Tree Rollup |
Draw a single line tracing the outside edge of the tree, starting at the root, going left, bottom, right, and returning up. It never retraces paths. |
Unpredictable Stack Depth + Tree Mutations: Memory states getting messy with repeated disconnected node handling. |
$O(H)$ Call Stack Frame: Standard recursion stack of maximum depth H (Height of Tree). Modifies pointers perfectly in-place as it unwinds. |
| 1326 |
Minimum Number of Taps to Open to Water a Garden |
Generate all 2^N possible subsets of taps. For each subset, combine their coverage intervals and check if they fully cover [0, n]. |
Combinatorial Subset Tree |
Draw a massive binary tree where each tap is either "ON" or "OFF". The leaves generate wildly overlapping coverage maps, illustrating $O(2^N)$ wasted effort. |
Greedy Array Processing (Jump Game II Pattern) |
Overlapping Interval Jumps |
Convert tap ranges to `[left, right]`. Create an array `max_reach` where index is `left` and value is `right`. Iterate through the garden, greedily jumping to the furthest reachable `right` bound. |
Draw a number line from 0 to N. Above it, draw horizontal lines representing tap ranges. Start at 0, trace a line to the tap that extends the furthest right. Repeat from that new endpoint. |
Single-Pass Max-Reach Sweep |
Draw an array of length N. Draw a single arrow making a few large, calculated leaps left-to-right, proving strictly $O(N)$ time. |
Unbounded Recursive Heap: Stack frames holding temporary arrays of combined intervals for subset validation. |
1D Max-Reach Array: Draw a fixed size `std::vector` mapping each starting integer to its maximum reachable endpoint. |
| 1327 |
List the Products Ordered in a Period (SQL) |
Run a correlated subquery fetching SUM of units for each product ID, row by row, while filtering dates. |
N x M Cross Join Iteration |
Draw the Products table. For every single row, draw an arrow to the Orders table that scans the entire orders list to match dates and IDs, demonstrating $O(N\cdot M)$ disk reads. |
INNER JOIN with GROUP BY and HAVING |
Filtered Set Aggregation |
Filter Orders table for dates in Feb 2020. INNER JOIN with Products table. GROUP BY `product_name`. HAVING `SUM(unit) >= 100`. |
Draw two tables side-by-side. Draw a funnel filtering out non-Feb orders. Draw matching lines linking the remaining rows by ID. Group identical names into a bucket and sum. Discard buckets < 100. |
Pipelined Relational Algebra |
Draw a flowchart: Filter Node -> Join Node -> Aggregate/Hash Node -> Output. Shows $O(N \log N)$ or $O(N)$ hash-based execution. |
Massive Temporary Tables: Database spinning up unindexed intermediate result sets in memory. |
Hash Map Aggregation: Draw an in-memory Hash Table using `product_id` as the key and a running integer sum as the value. |
| 1328 |
Break a Palindrome |
Iterate through every index. Replace the character with every letter 'a' through 'z'. Check if the result is still a palindrome. Keep the lexicographically smallest. |
$O(N²)$ String Mutation & Verification |
Draw a word. Draw 26 arrows pointing down from the first letter, 26 from the second. For every new word created, draw an arrow scanning the whole string to verify palindrome status. |
Greedy Half-Scan Mutation |
Midpoint Pointer Stop |
Scan only the first half of the string (`0` to `n/2 - 1`). Change the very first non-'a' character to 'a' and return. If all are 'a', change the very last character to 'b'. |
Draw a palindrome. Draw a vertical line exactly in the middle. Scan left to right until the line. Cross out the first non-'a', write 'a'. If you hit the line without changing anything, change the final character to 'b'. |
Early-Exit Single Arrow |
Draw a string array. Draw an arrow stopping before the halfway point, proving optimal $O(N)$ time with immediate short-circuiting. |
String Factory Heap Fragmentation: Generating thousands of candidate `std::string` objects and holding them for `min()` comparison. |
In-Place Character Array Mutation: Draw a single `std::string` or `char[]`. A single byte is overwritten in memory. Space complexity is exactly $O(1)$ auxiliary. |
| 1329 |
Sort the Matrix Diagonally |
Extract each diagonal into a dynamic list, use a standard $O(K \log K)$ sort, and write them back into the matrix using complex boundary math nested inside double loops. |
Matrix Teardown and Reassembly |
Draw a grid. Draw arrows pulling elements into separate arrays, sorting them individually, and pushing them back in. Highlights high overhead in index management. |
Map of Min-Heaps (Group by i - j) |
Diagonal Equivalence Classes |
Observation: Elements on the same diagonal share the exact same `i - j` value. Create a `unordered_map>`. Push all elements. Iterate matrix again, popping from the PQ for that `i - j`. |
Draw a matrix. Write `(row - col)` in every cell. You'll see identical numbers form diagonal stripes. Throw all elements of a stripe into a funnel (Heap), and let them drop back in sorted order. |
Hash Table of Sorting Funnels |
Draw a matrix pointing to a Hash Map. Show the map values are individual Heaps processing data in $O(M\cdot N \log(\text{min}(M,N)$)). |
Dynamic 2D Arrays: Massive allocations of varying length vectors extracted from the matrix. |
Hash Map of Priority Queues: Draw a `std::unordered_map` keyed by integer, holding `std::priority_queue` structures acting as memory-efficient sorting buffers. |
| 1330 |
Reverse Subarray To Maximize Array Value |
Generate all possible subarray combinations [L, R]. Physically reverse each subarray, calculate the absolute differences of the entire array, and track the maximum. |
$O(N³)$ Brute Force Array Reversals |
Draw an array. Underneath it, draw N² different variations of the array with different chunks reversed. Draw a magnifying glass iterating $O(N)$ times over every single variation to calculate sums. |
Math / Edge-Delta Optimization |
Boundary Severing and Reattachment |
Reversing [L, R] only changes the connections at `L-1` and `R+1`. The delta is `abs(A[L] - A[R+1]) + abs(A[R] - A[L-1]) - abs(A[L-1] - A[L]) - abs(A[R] - A[R+1])`. Maximize this in $O(N)$. |
Draw an array. Draw a box around a subarray. The internal links don't change absolute sum. Draw scissors cutting the left and right edges of the box, and draw them crossing over to attach to opposite ends. |
Single-Pass Min/Max Tracking |
Draw an array. Draw exactly one arrow moving left-to-right, keeping track of 4 mathematical variables in constant time, proving $O(N)$ logic. |
$O(N²)$ Array Copies: Allocating a brand new `std::vector` for every theoretical reversal check. |
Four Constant Registers: Draw a CPU. Only 4 integer registers are used to track `max_min_edge`, `min_max_edge`, and boundary deltas. $O(1)$ space. |
| 1331 |
Rank Transform of an Array |
For every single element, loop through the entire array to count exactly how many unique elements are strictly smaller than it to determine its rank. |
$O(N²)$ Nested Comparison Loops |
Draw an array. For element 0, draw an arrow pointing to every other element. For element 1, do the same. Darkly shade the massive web of redundant comparisons. |
Sort + De-duplicate + Hash Map |
Sorted Unique Mapping |
Copy array and sort it. Remove duplicates. The index + 1 in this unique sorted array is the rank. Map original values to their new ranks using a Hash Map, then overwrite original array. |
Draw original array. Below it, draw a sorted copy. Cross out duplicates. Number the remaining items 1, 2, 3... Draw arrows from the original array numbers down to their assigned rank. |
Sorting Funnel -> Dictionary Lookup |
Draw an array passing through a sorting funnel $O(N \log N)$. Draw a direct 1-to-1 lookup into a dictionary yielding strictly $O(N)$ mapping time. |
$O(N)$ Set Lookups inside Loops: Dynamically building Sets repeatedly to count unique smaller numbers. |
$O(N)$ Vector Copy + Hash Map: Draw a cloned `std::vector` that is sorted, and an `std::unordered_map` mapping values to ranks. |
| 1332 |
Remove Palindromic Subsequences |
Generate all possible subsequences $O(2^N)$, check each for being a palindrome $O(N)$, remove valid ones, and recurse on the remainder. |
Exponential Subsequence Tree |
Draw a string. Branch out with every possible character exclusion combination. The tree explodes exponentially, showing massive redundant palindrome checks. |
Brainteaser / Logical Deduction |
Binary State Check |
Notice the string ONLY contains 'a' and 'b'. If it's already a palindrome, it takes 1 step. If not, remove all 'a's (which is a palindrome), then all 'b's. Always takes 2 steps max. |
Draw the string. Check if it reads the same backwards. If yes, write '1'. If no, cross out every 'a' (step 1), then cross out every 'b' (step 2). Write '2'. |
$O(N)$ Two-Pointer Sweep |
Draw a string. Place an arrow at the start and end. Move them towards the center. If they mismatch even once, immediately stop and return 2. |
Unbounded Call Stack: Thousands of string permutations held in recursive memory frames. |
Two Integer Pointers: Draw two variables (`left` and `right`) traversing the single existing string in memory. $O(1)$ space. |
| 1333 |
Filter Restaurants |
Sort the entire raw dataset first $O(N \log N)$, then run multiple nested loops or unoptimized filters to remove invalid restaurants. |
Over-Sorting Redundant Data |
Draw a massive funnel sorting all restaurants. Below it, draw a filter that throws away 80% of the sorted data. Highlights wasted sorting computations. |
Linear Filter Pipeline + Custom Sort |
Multi-Stage Sieve |
Pass 1: Iterate strictly once. If `veganFriendly` matches AND `price <= maxPrice` AND `distance <= maxDistance`, keep it. Pass 2: Sort only the surviving restaurants by rating, then ID. |
Draw an array of restaurant objects. Pass a sliding "filter box" over them. Erase non-matching ones. Take the small remaining pile and arrange them highest-rating first. |
Data Reduction Funnel |
Draw a wide array entering a filter block. A much thinner array exits. Point the thin array into a small sorting box, proving $O(K \log K)$ where K << N. |
Full Cloned Array: Duplicating the entire N-sized 2D array before applying any logic. |
Filtered Dynamic Array: Draw a `std::vector` that only ever allocates space for valid entries before the sort operation. |
| 1334 |
Find the City With Smallest Neighbors |
Run a standard DFS from every single node, attempting every possible path without weight consideration, exploding with cycles. |
Infinite Cyclic Pathing |
Draw a graph. Start from Node 0. Trace every path, looping around cycles until the distance limit is hit. Repeat for all nodes, showing astronomical path explosion. |
Floyd-Warshall (All-Pairs Shortest Path) |
Adjacency Matrix Relaxation |
Initialize an N x N matrix with edge weights (infinity where no edge). Use 3 nested loops (k, i, j) to update `dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])`. Count valid cities per row. |
Draw a grid. Let K be an intermediate city. Pick cell (I, J). Look at (I, K) and (K, J). If their sum is smaller than (I, J), cross out (I, J) and write the new sum. Repeat. |
N x N Matrix Sweeping |
Draw an N x N grid. Show a sweeping animation processing the grid exactly N times (for each K), proving strict $O(N³)$ deterministic time. |
Massive Recursion Stack: Holding thousands of DFS path combinations and visited sets. |
Dense 2D Matrix: Draw a static `int[][]` array of size N x N. Extremely cache-friendly and strictly $O(N²)$ space. |
| 1335 |
Minimum Difficulty of a Job Schedule |
Generate all possible ways to partition an array into `d` contiguous subarrays, calculating the max of each subarray and summing them. |
Combinatorial Partitioning |
Draw an array. Draw `d-1` vertical slices. Show all possible places those slices could be inserted. Highlights $O(N^d)$ explosion of combinations. |
2D Dynamic Programming |
State Matrix Expansion |
`dp[i][k]` = min difficulty to schedule first `i` jobs in `k` days. Iterate `k` days, iterate `i` jobs, iterate `j` (last day's jobs). `dp[i][k] = min(dp[j][k-1] + max(jobs[j+1...i]))`. |
Draw a grid: Days (rows) vs Jobs (cols). Fill day 1 by tracking the running maximum. For day 2, look at previous day's cells and add the max of the remaining jobs chunk. |
3-Loop Matrix Fill |
Draw a 2D grid. Point to a cell. Draw a line looking back at the previous row, scanning a range of columns to find the optimal cut, proving $O(N² \cdot d)$ time. |
Deep Partition Stack: Recursive frames tracking array indices and running sums. |
2D DP Cache: Draw a `std::vector>` of size `N` x `d`. (Can also be space-optimized to 1D `vector` of size N, swapping daily). |
| 1336 |
Number of Transactions per Visit (SQL) |
Use a recursive CTE to join Visits and Transactions, attempting to count zero-transaction visits by scanning the entire transaction table for missing IDs. |
Logical Gaps in Left Joins |
Draw a list of visits. Draw empty spaces where no transactions occurred. Note the difficulty in "generating" rows for counts (0, 1, 2...) that don't exist in data. |
Recursive CTE (Range Generation) + Left Join |
Sequence-to-Data Alignment |
1. Count transactions per visit. 2. Use a Recursive CTE to generate a sequence of numbers from 0 to max_transactions. 3. Left Join the sequence to the counts to fill gaps. |
Draw a vertical ruler from 0 to Max. Next to it, draw buckets for transaction counts. Map the visits to the buckets. Empty buckets get a count of 0. |
$O(N + \text{MaxCount})$ |
Draw a data stream entering a tally array, followed by a join with a generated sequence. |
Full Cartesian Product: Trying to join every visit to every possible transaction count. |
$O(\text{MaxCount})$ Temporary View: Draw a small generated table of 0 to N used as a skeleton for the final result. |
| 1337 |
The K Weakest Rows in a Matrix |
Scan every entire row $O(N)$ to count '1's. Store (count, index) pairs, then sort the entire list $O(M \log M)$. |
Full Array Scan + Heavy Sort |
Draw a 2D matrix. Draw an arrow reading every single '0', wasting time. Point the results to a massive sorting funnel processing all M rows. |
Binary Search + Max-Heap (Priority Queue) |
Targeted Indexing + Bounded Sifting |
Since rows are sorted (1s then 0s), use Binary Search to find the last '1' in $O(\log N)$. Push the count and index into a Max-Heap of strictly size K. |
Draw a row. Jump to the middle. If '1', jump right. If '0', jump left. Find the boundary. Toss the result into a small bucket that only holds K items, throwing out the largest when full. |
Logarithmic Search Rails |
Draw M horizontal lines (rows). Draw a dot cutting each line in half recursively (Binary Search). Point them to a Heap container bounded by K, proving $O(M \log N + M \log K)$. |
$O(M)$ Pair Array: An unoptimized list of M tuples waiting to be sorted. |
Fixed Size Max-Heap: Draw a `std::priority_queue`. Cap its physical drawing size at K. When a new item enters, the heaviest item immediately falls out. |
| 1338 |
Reduce Array Size to The Half |
Generate subsets, physically remove them from the array, and recalculate frequencies manually inside a nested loop. |
Redundant Array Shifting |
Draw an array. Pick a number, erase all its occurrences, shift the remaining elements to fill gaps, and check the size. Highly inefficient $O(N²)$. |
Frequency Map + Greedy Sort |
Tally and Greedily Consume |
Count frequencies using a Hash Map. Extract just the frequency values into an array. Sort descending. Greedily subtract frequencies from `total_size` until `<= half`. |
Draw an array. Dump it into buckets based on value. Measure bucket weights. Sort buckets by weight. Pick the heaviest bucket, subtract its weight from N. Repeat until half. |
Map -> Value Sort -> Linear Scan |
Draw an array tunneling into a Hash Map $O(N)$. Draw the values flowing into a sorting funnel $O(U \log U)$. Draw a single arrow ticking down a counter until half. |
Mutated Cloned Arrays: Thousands of array copies with elements physically removed. |
Hash Map + Value Vector: Draw a `std::unordered_map` for counting, and a compact `std::vector` holding just the frequencies for sorting. |
| 1339 |
Maximum Product of Splitted Binary Tree |
For every edge, physically remove it, run two separate DFS traversals to sum both resulting subtrees, and calculate the product. |
Edge-by-Edge Tree Partitioning |
Draw a tree. Draw a "scissor" icon on one edge. Color the two resulting pieces. Repeat for every single edge in the tree, showing $O(N²)$ traversals. |
Post-Order DFS Sum Tracking |
Subtree Sum Collection |
Run Pass 1 (DFS) to find the `TotalSum` of the tree. Run Pass 2 (DFS): for each node, calculate its subtree sum and store it. The product is `SubtreeSum * (TotalSum - SubtreeSum)`. |
Draw a tree. In each node, write the sum of all nodes below it. Calculate the product at each node by multiplying its value with (Total - Value). Circle the maximum. |
Two-Pass Linear Sweep |
Draw a single line tracing the tree once for summation and once for product calculation, proving strict $O(N)$. |
$O(N)$ Re-traversal Overhead: Multiple recursive stacks rebuilding sums from scratch for every edge cut. |
Single List of Subtree Sums: Draw a `std::vector` that simply records the result of each `dfs(node)` call during one pass. |
| 1340 |
Jump Game V |
Recursively explore every jump from every index without memoization, leading to the same index being calculated thousands of times. |
$O(N \cdot d^N)$ Overlapping Search Tree |
Draw an array. From index i, draw arrows to all i pm d valid jumps. For each jump, repeat. The tree branches explode and overlap constantly. |
DP + Memoization or Monotonic Stack Sort |
Directed Acyclic Graph (DAG) Layers |
Sort indices by value. Start DP from the smallest value. For each index, `dp[i] = 1 + max(dp[j])` for all reachable `j`. Alternatively, use Top-Down DFS + Memo. |
Draw an array. For each index, draw arrows to reachable lower-valued neighbors. Fill the values from lowest to highest. Each arrow adds +1 to the source's max jump. |
$O(N \cdot d)$ |
Draw a grid: Index vs. MaxJumps. Show arrows only moving from lower heights to higher heights, proving it's a DAG. |
Exponential Call Stack: Thousands of identical recursive frames. |
$O(N)$ DP Array: Draw a single 1D array `memo[]` storing the results for each index. |
| 1341 |
Movie Rating (SQL) |
Run two entirely separate SQL queries, one for the user with most ratings and one for the movie with highest avg rating, then UNION them. |
Independent Full-Scan Queries |
Draw two separate workflows. Query A scans Users/Ratings. Query B scans Movies/Ratings. Both perform heavy sorting twice. |
Window Functions / Order By + Limit 1 |
Top-K Filtering |
Join Users and Ratings. Group by User, Sort by Count DESC, Name ASC. Limit 1. Repeat for Movies with Average Rating in Feb 2020. |
Draw two separate funnels. Funnel 1 filters users by count. Funnel 2 filters movies by avg rating. The "winners" from both are joined at the end. |
$O(N \log N)$ |
Draw two sorting processes. Show the top item from each being selected for the final output. |
Large Buffer Sorts: Database sorting thousands of strings for lexicographical ties. |
Hash Aggregate Buffers: Draw in-memory hashes for user-counts and movie-averages. |
| 1342 |
Number of Steps to Reduce to Zero |
Standard iterative simulation: check even/odd, divide or subtract until zero. |
Linear Step Log |
Draw a number. Subtract 1. Divide by 2. Repeat. Each operation is one step. Linear visualization of work. |
Bit Manipulation (Popcount + Bit Length) |
Binary Bit-Strip Transition |
Total steps = `(total_bits - 1) + (count_of_set_bits)`. Every '0' is 1 step (div), every '1' is 2 steps (sub then div), except the last '1'. |
Write the number in binary. Count the length. Count the '1's. Add them and subtract 1. That is your total steps. |
$O(\log N)$ or $O(1)$ |
Draw a 32-bit register. Show an arrow scanning the bits once. $O(\log_10 N)$ complexity since we process bits. |
Variable Stack: Simple loop variables. |
Register Operation: Draw a CPU performing `CLZ` (Count Leading Zeros) and `POPCNT`. |
| 1343 |
Number of Sub-arrays of Size K and Average >= Threshold |
For every starting index `i`, loop `k` times to calculate the sum of the subarray, calculate average, and compare. |
$O(N\cdot K)$ Sliding Brackets |
Draw an array. Draw a bracket of length K. Slide it right. At every stop, draw K small arrows inside the bracket summing elements. Show massive overlap. |
Sliding Window (Fixed Size) |
Rolling Sum Window |
Calculate sum of first `K` elements. Slide the window: `new_sum = old_sum - arr[left] + arr[right]`. Compare `sum` to `threshold * k` to avoid division. |
Draw an array. Draw a box around first K elements. Move the box one step right; draw an arrow removing the left element and another adding the new right element. |
Single-Pass Constant Update |
Draw one arrow moving left-to-right. At each step, show exactly one addition and one subtraction, proving $O(N)$. |
$O(1)$ Accumulator: Resetting sum for every bracket. |
$O(1)$ Rolling Sum: Draw a single integer variable that updates in-place as the window moves. |
| 1344 |
Angle Between Hands of a Clock |
Attempt to simulate the rotation of hands in minute-by-minute increments until they reach the target time. |
Simulation Progression |
Draw a clock. Move the hand 360 times for an hour. Very inefficient and prone to rounding errors. |
Mathematical Relative Position |
Degree Calculation Formula |
Minute hand: `6° * minutes`. Hour hand: `30° * (hour % 12) + (0.5° * minutes)`. Find the absolute difference and return `min(diff, 360 - diff)`. |
Draw a clock face. Mark the minute hand position. Mark the hour hand position. Calculate the angle from 12 o'clock for both. Subtract. |
$O(1)$ Constant Formula |
Draw a calculator icon showing one single mathematical expression, proving $O(1)$ time complexity. |
Simulation State: Variables tracking ticks and movements. |
Constant Math Registers: No extra memory. $O(1)$. |
| 1345 |
Jump Game IV |
DFS with recursion to find all paths to the last index, exploring all same-value jumps without a visited set. |
Exponential Cyclic Tree |
Draw a graph where nodes jump to `i+1`, `i-1`, or any index with the same value. Show paths looping back and forth infinitely. |
BFS with Multi-Value Jump Optimization |
Shortest Path Level-Expansion |
Use BFS to find the shortest path. Store indices of same values in a Map. **Crucial:** Once you jump to all indices of value `X`, clear the map entry for `X` so you don't re-process those jumps. |
Draw nodes. Draw edges for neighbors and same-value groups. Start a BFS "wave". Once a value-group is visited, "cut" those edges so the wave doesn't look back. |
Level-Order Search (Wavefront) |
Draw concentric circles from the start node. Show the wave hitting the end node, proving $O(N)$ because each node and edge is processed once. |
Unbounded Recursion: Stack overflow from massive cyclic paths. |
Queue + Visited Set + Value Map: Draw a `std::queue` and a `std::unordered_map>` for value-to-index lookups. |
| 1346 |
Check If N and Its Double Exist |
Nested loops comparing every element `i` with every element `j` to see if `arr[i] == 2 * arr[j]`. |
$O(N²)$ All-Pairs Comparison Web |
Draw an array. From each element, draw arrows to every other element in the array. Note the N^2 total connections. |
Hash Set (Single Pass) |
Dynamic Membership Testing |
Iterate through the array. For each `x`, check if `2*x` or `x/2` (if even) exists in the Set. If not, add `x` to the Set. |
Draw an array and an empty "Bucket" (Set). Move through the array; for each number, check the bucket for its double or half. If found, stop. If not, drop the number in. |
$O(N)$ Linear Scan |
Draw a single straight arrow passing through each element once, pointing to a Set lookup box (O(1)). |
$O(1)$ Accumulator: No extra memory beyond loop indices. |
Hash Set Storage: Draw a hash table structure where each element occupies a bucket based on its hash. $O(N)$. |
| 1347 |
Minimum Number of Steps to Make Two Strings Anagram |
For every character in string `s`, search for it in string `t`. If found, "delete" it from `t`. Count the remaining characters in `s`. |
$O(N²)$ Repeated String Searches |
Draw two strings. Draw an arrow from the first char of `s` scanning all of `t`. If matched, cross it out. Repeat for every char in `s`. |
Frequency Array (Character Tally) |
Character Balance Sheet |
Create a frequency array of size 26. Increment counts for chars in `s`, decrement for chars in `t`. The sum of all positive differences is the answer. |
Draw a table with 26 columns (A-Z). For string `s`, put a '+' mark in the corresponding letter box. For `t`, put a '-' mark. Count how many '+' remain unmatched. |
$O(N)$ Linear Tally |
Draw two horizontal bars (strings) feeding into a single 26-slot histogram, proving $O(N + M)$ time. |
Mutable String Copies: Storing modified versions of `t` to track "deleted" characters. |
Fixed Frequency Map: Draw a 26-slot integer array. This is $O(1)$ space relative to the alphabet size. |
| 1348 |
Tweet Counts Per Frequency |
Store every tweet in a simple list. For every query, filter the entire list by name and time, then sort the results to group them into intervals. |
$O(Q \cdot N \log N)$ Query Filtering |
Draw a long list of tweets. For one query, draw a filter that extracts a few items, then a sorting funnel. Repeat for every query. |
Hash Map of Sorted Sets (TreeMap) |
Binned Time Segments |
Map each `tweetName` to a `std::set` or `std::multiset` of timestamps. Use `lower_bound` to find the start time and iterate through the interval, incrementing counts for each "bin". |
Draw a Map where keys are names. Each key points to a sorted timeline. For a query, draw a "window" on the timeline and divide it into equal segments (bins). Count dots in each bin. |
$O(Q \cdot (\log N + K)$) Range Search |
Draw a balanced tree (Set). Show an arrow jumping directly to the start time (O(log N)) and then traversing only the relevant interval (O(K)). |
Unstructured List: A massive, unsorted array of all tweet objects ever recorded. |
Grouped Timelines: Draw a Map pointing to multiple sorted arrays or BSTs, optimizing for search over insertion. |
| 1349 |
Maximum Students Taking Exam |
Try every possible combination of seating (2^NM) and check if each seat is broken or has a student cheating diagonally/horizontally. |
2^NM Brute Force Subsets |
Draw a grid. Show a binary tree where each seat is a "Yes/No" branch. The leaves are astronomical (2^64 for an 8x8). |
Dynamic Programming with Bitmask |
Row-by-Row State Compression |
`dp[row][mask]` = max students for first `row` with current row's seating pattern `mask`. Check `mask` against the previous row's mask for cheating. |
Draw a grid row. Represent the row as a 0101 bitmask. Compare it with the row above. If a '1' is diagonally adjacent to a '1' above, cross out the pattern. |
$O(\text{Rows} \cdot 2^2 \\text{cdot Cols})$ Complexity |
Draw a matrix where rows are grid rows and columns are all possible 2^Cols bitmasks. Show data flowing only from the previous row to the current. |
Global State Stack: Recursive frames trying to track every individual seat's choice. |
2D Bitmask Table: Draw a table of size `M x (1 << N)`. Show it being filled row-by-row, usually only keeping two rows in memory. |
| 1350 |
Students with Invalid Departments (SQL) |
Use a nested `NOT IN (SELECT id FROM Departments)` which often forces the DB to scan the subquery for every row in the outer query. |
$O(S \cdot D)$ Nested Subquery Scan |
Draw a Student row. Draw an arrow checking the entire Department table to see if the ID *doesn't* exist. Repeat for every student. |
LEFT JOIN + NULL Filtering |
Set Difference Visualization |
`SELECT name FROM Students LEFT JOIN Departments ON d_id = id WHERE Departments.id IS NULL`. This allows the optimizer to use hash joins. |
Draw the Student table and Department table. Draw lines connecting matching IDs. Circle the students on the left who have no line connecting to the right. |
$O(S + D)$ Hash Join |
Draw a hash table of Departments. Scan Students once, checking if their ID is in the hash. Proves linear efficiency. |
$O(S\cdot D)$ Intermediate Sets: Wasted work comparing every ID to every other ID. |
Hash Set: Draw an in-memory Hash Set of department IDs for $O(1)$ lookups. |
| 1351 |
Count Negative Numbers in a Sorted Matrix |
Nested loops iterating through every single element of the M x N matrix to count how many are less than zero. |
Full M x N Scan |
Draw a grid. Draw a single long arrow snaking through every single cell in the matrix. $O(M x N)$. |
Staircase Search (Saddleback) |
Boundary Tracking Zig-Zag |
Start at the bottom-left corner. If current is negative, all elements above it in that column are negative; add `rows - r` and move right. If positive, move up. |
Draw a matrix. Start at the bottom-left. Draw a "staircase" line. If the number is negative, "step" right. If positive, "step" up. The area below the stairs is your count. |
$O(M + N)$ Linear Trace |
Draw a matrix. Draw one continuous "L" shaped or zig-zag line from one corner to another, touching at most M+N cells. |
$O(1)$ Accumulator: No extra memory beyond a single integer counter. |
$O(1)$ Pointers: Draw two variables, `row` and `col`, changing as the search moves. |
| 1352 |
Product of the Last K Numbers |
Store all numbers in a list. For every query, iterate back through the last K elements and multiply them. |
$O(K)$ Linear Query Scan |
Draw an array. For a query, draw a bracket covering the last K elements and an arrow hopping through each. Repeat for every query. |
Prefix Product Array with Zero-Reset |
Cumulative Multiplier Stream |
Maintain a running product list. `getProduct(k)` is `total_product / prefix[N-K-1]`. If a zero is added, clear the list because any product including it will be zero. |
Draw a stream of numbers. Below it, write the running product. When a '0' appears, draw a "Wall" and start the running product from '1' again. |
$O(1)$ Constant Lookup |
Draw an array index. Draw two dots and a single division operator, proving the result takes exactly one math operation regardless of K. |
Dynamic List: A simple growing list of integers. |
Prefix List: Draw a list where each element i is the product of all elements from the last '0' to i. |
| 1353 |
Maximum Number of Events That Can Be Attended |
Sort by start time. Try every possible day for every event using a recursive backtracking approach to see which combination yields the max. |
Exponential Choice Tree |
Draw an event. Branch out into every possible day it could be attended. The branches multiply for every overlapping event, leading to $O(2^N)$. |
Greedy + Min-Heap (Priority Queue) |
Timeline Priority Sorter |
Sort events by start time. Iterate through days. On each day, add all events starting today to a Min-Heap (ordered by end time). Attend the event that ends the earliest. |
Draw a timeline (days). Above it, draw events as horizontal bars. On Day 1, pick the bar that finishes first. On Day 2, pick the next. Throw away bars whose end date has passed. |
$O(N \log N + \text{TotalDays} \log N)$ |
Draw a sorting funnel followed by a moving day-pointer and a small Heap bucket that constantly pushes/pops. |
Global Combinatorial Stack: Massive memory usage tracking all valid/invalid day assignments. |
Min-Priority Queue: Draw a heap structure storing only the end-times of "active" events. Space is $O(N)$. |
| 1354 |
Construct Target Array with Multiple Sums |
Start with an array of 1s and try adding elements in all permutations to reach the target. |
Forward Search Explosion |
Draw [1, 1, 1]. Branch into [3, 1, 1], [1, 3, 1], etc. Show how the values grow, making it impossible to know which path leads to the target. |
Reverse Simulation with Max-Heap |
Backward Value Reduction |
Work backward from the target. Replace the largest element with `max_val % (sum - max_val)`. If the max becomes 1, return true. Use a Max-Heap to always find the largest. |
Draw the target array. Circle the biggest number. Subtract the sum of others from it. Write the new smaller number. Repeat until all numbers are 1. |
$O(N \log N \cdot \log(\text{max}_\text{val})$) |
Draw a Max-Heap. Show the largest element being popped, reduced by a modulo operation, and pushed back, proving logarithmic reduction. |
Search Tree Nodes: Billions of possible array states in memory. |
Max-Priority Queue: Draw a heap of target values. Memory is strictly $O(N)$. |
| 1355 |
Activity Participants (SQL) |
Calculate counts for all activities, then use nested subqueries to find the literal MIN and MAX values by scanning the count list twice. |
$O(N²)$ Redundant Aggregation Scans |
Draw an Activity table. For each row, run a scan to count, then run another scan to find the max, then another for the min. Very inefficient disk usage. |
Window Functions (RANK / DENSE_RANK) |
Rank-Based Exclusion |
Group by activity and count. Use `RANK() OVER (ORDER BY count DESC)` and `RANK() OVER (ORDER BY count ASC)`. Filter out rows where either rank is 1. |
Draw a list of activities with their participant counts. Sort them. Cross out the very top and the very bottom. The remaining list is your answer. |
$O(N \log N)$ Sorting |
Draw a single sorting funnel. Show the top and bottom of the sorted list being "snipped" off. |
Multiple Temp Tables: Storing intermediate counts in multiple scratchpads. |
Single Result Set: Draw one table with an added `rank_desc` and `rank_asc` column. |
| 1356 |
Sort Integers by The Number of 1 Bits |
For every comparison in a sort, convert both integers to binary strings, count the '1's, and then compare. |
$O(N \log N \cdot \log V)$ Redundant Computation |
Draw a sorting algorithm. Inside every "comparison" box, draw a sub-process that converts numbers to strings and scans them. |
Custom Comparator with __builtin_popcount |
Bit-Weighted Sorting |
Use a standard sort but define a custom rule: if `popcount(a) != popcount(b)`, sort by popcount. Otherwise, sort by value. |
Draw a list of numbers. Next to each, write its "Weight" (number of 1s). Group numbers by weight and then sort each group normally. |
$O(N \log N)$ with Constant Bit-Count |
Draw a sorting funnel. The "Decision" gate uses a single CPU instruction (popcount) to compare weights, proving efficient $O(1)$ comparison. |
String Buffers: Temporary binary strings generated during every comparison. |
In-place Sort: Draw the original array being re-ordered. No extra memory beyond the recursion stack for sorting. |
| 1357 |
Apply Discount Every n Orders |
Maintain a full transaction history in a list. Every time a bill is calculated, check the entire history to see if the current count is a multiple of n. |
$O(N)$ History Traversal |
Draw a ledger. For every new customer, scan all previous pages to count them. $O(N^2)$ over time. |
Stateful Counter + Hash Map |
Incremental Triggering |
Store a simple integer `counter`. Use a Map to store `productId -> price`. For each bill, increment counter. If `counter % n == 0`, apply discount. |
Draw a counter (like a car odometer). Draw a "Price Book" (Map). For each customer, look up prices in the book, sum them, and check if the odometer hit the discount mark. |
$O(M)$ per Bill |
Draw a single lookup into a Map for each item in the bill (O(1)) and a single modulo check (O(1)). |
List of All Transactions: A growing memory footprint storing every past order. |
Fixed Price Map: Draw a `std::unordered_map`. Memory is $O(\text{Products})$, staying constant regardless of the number of customers. |
| 1358 |
Number of Substrings Containing All Three Characters |
Generate every possible substring $O(N^2)$ and check if each contains 'a', 'b', and 'c' $O(N)$. |
$O(N³)$ Substring Sifting |
Draw a string. Draw every possible bracket. For each bracket, draw a magnifying glass looking for 'a', 'b', and 'c'. |
Sliding Window (Two-Pointer / At-Most) |
Shrinking Valid Window |
Move `right` pointer to include chars. Once you have all three, every substring starting at or before `left` and ending at `right` is valid. Add `left + 1` to total and move `left`. |
Draw a string. Slide `right` until you have 'a,b,c'. Note that everything to the left of the current `left` pointer *also* makes a valid string when combined with the current window. |
$O(N)$ Linear Slide |
Draw two pointers moving together from left to right. They never go backward, proving exactly 2N steps. |
$O(N²)$ Substring Pool: Storing or processing every variation of the string. |
Fixed Frequency Tracker: Draw a 3-slot array (or 3 integers) tracking counts of 'a', 'b', and 'c'. $O(1)$ space. |
| 1359 |
Count All Valid Pickup and Delivery Options |
Generate all (2N)! permutations and validate if every Pickup happens before its Delivery. $O((2N)$!). |
Factorial Validation Tree |
Draw an impossible tree. Branch out for every P and D. Cross out branches where D comes before P. |
Combinatorics / Math (DP) |
The Slot Insertion Visual |
For n pairs, we have 2n total slots. Assume n-1 pairs are placed (taking 2n-2 slots). The new pair (P, D) can be placed in the remaining slots. The number of ways is (2n-1) x n. |
Draw existing items as blocks with gaps. Draw P and D. If P is put in gap 1, D can go in any gap after it. The math formula perfectly calculates the sum of these choices. |
Linear Formula Iteration $O(N)$ |
Draw a straight line 1 dots N. Multiply an accumulator by a simple math function at each step. |
Generating permutations. |
One integer variable. $O(1)$ space. |
| 1360 |
Number of Days Between Two Dates |
Iterate day-by-day from the start date to the end date, manually checking for leap years and month boundaries. |
$O(\text{Days})$ Linear Simulation |
Draw a calendar. Draw an arrow for every single day passed. If dates are 100 years apart, that's 36,500 arrows. |
Days Since Epoch (1971) Calculation |
Coordinate Geometry Projection |
Calculate total days from 1971 for both dates independently. Subtract the two numbers. Leap year logic: `y/4 - y/100 + y/400`. |
Draw two points on a timeline relative to an 'Origin' (1971). Calculate the distance from Origin to A and Origin to B. Subtract the segments. |
$O(1)$ Constant Math |
Draw a calculator showing two fixed-length mathematical formulas being subtracted. |
Simulation State: Variables tracking current day/month/year. |
Constant Registers: Only a few integers needed for the formula. |
| 1361 |
Validate Binary Tree Nodes |
Perform a random walk from any node and check if you can reach all nodes without hitting a cycle. |
$O(N^2)$ Unstructured DFS |
Draw nodes. Draw an arrow from one. It might loop or miss nodes. Repeat from every node to "be sure." |
Graph In-Degree Count + BFS/DFS |
Directional Flow Validation |
1. Every node except root must have in-degree 1. 2. Root must have in-degree 0. 3. Exactly one root must exist. 4. BFS from root must visit exactly N nodes. |
Draw nodes with arrows. Write the 'In-Degree' count next to each. If any number > 1 or more than one node has 0, cross it out. Then trace from the '0' node to see if you hit everything. |
$O(N)$ Single Sweep |
Draw an array for in-degrees (Linear Scan) followed by a BFS wave (O(V+E)). |
Visited Set per Path: Keeping track of path history to detect cycles manually. |
$O(N)$ In-Degree Array: Draw a simple array of size N tracking counts. |
| 1362 |
Closest Divisors |
For both `num + 1` and `num + 2`, iterate from 1 to the number itself to find all divisor pairs and pick the one with the smallest difference. |
$O(N)$ Factor Search |
Draw a number line. Scan every single number from 1 to N looking for a factor. |
Square Root Search (Greedy) |
Centric Factor Scan |
Start searching for divisors from √num+2 downwards to 1. The first divisor found will automatically have the smallest difference. |
Draw a number. Mark its square root. Draw an arrow starting at the root and moving LEFT. The first number it hits that divides the target is the winner. |
$O(√N)$ Reduced Search |
Draw a line that only covers a tiny fraction of the number's total value (the root), proving efficiency. |
List of All Factors: Storing every pair found before comparing. |
$O(1)$ Two-Integer Result: Only store the "current best" pair. |
| 1363 |
Largest Multiple of Three |
Generate all possible subsequences of the digits (2^N), sort each to form the largest number, and check if the sum of digits is divisible by 3. |
$O(2^N)$ Subset Sorting |
Draw a digits array. Branch into every possible subset. For each subset, show a sorting process and a division check. |
Greedy Tally + Remainder Math |
Modulo-Based Sieve |
Count digits 0-9. Calculate total sum % 3. If remainder is 1, remove the smallest digit with %3==1 (or two with %3==2). If remainder is 2, remove smallest %3==2 (or two with %3==1). Sort descending. |
Draw buckets for remainders 0, 1, and 2. Put digits in buckets. Based on total sum, "discard" one or two digits from the 1 or 2 buckets. Concatenate the rest from 9 down to 0. |
$O(N)$ Counting Sort |
Draw a 10-slot frequency array. Show a single pass to fill it and a constant-time math check for deletions. |
Subsequence Pool: Millions of strings competing for the "max" title. |
10-Slot Tally Array: Draw an array of size 10 storing frequencies. $O(1)$ space relative to input size. |
| 1364 |
Number of Trusted Contacts of a Customer (SQL) |
Iterate through every invoice, then for each invoice, search the Contacts table, and for each contact, search the Customers table to see if they are "trusted." |
$O(I \cdot C \\text{cdot Cust})$ Triple Nested Scan |
Draw three tables. For one Invoice, draw arrows to Contacts, then nested arrows to Customers. The "web" of connections becomes unreadable. |
Multi-Level LEFT JOIN with Grouping |
Relational Join Pipeline |
`JOIN` Invoices with Customers. `LEFT JOIN` with Contacts. `LEFT JOIN` with Customers again (to verify if contact is a customer). Group by Invoice ID. |
Draw an Invoice. Draw lines to its contacts. If a contact has a matching ID in the "Main Customer" list, color it green (trusted). Count total lines and green lines. |
$O(N \log N)$ Hash Joins |
Draw a pipeline where Invoices flow through multiple "Checkpoints" (Join nodes), emerging as a single row with aggregated counts. |
Cartesian Bloat: Attempting to join all contacts to all invoices without specific ID mapping. |
Hash Join Index: Draw an in-memory Hash Table for the Customer list to make "Trust" checks $O(1)$. |
| 1365 |
How Many Numbers Are Smaller Than the Current Number |
Nested loops: for each element `i`, iterate through all other elements `j` and count how many are smaller. |
$O(N^2)$ Comparison Matrix |
Draw an array. For each item, draw an arrow to every other item. Shows a dense web of redundant checks. |
Bucket Sort / Prefix Sum |
Frequency Accumulation |
Count occurrences of each number (0-100) in a frequency array. Calculate prefix sums of the frequency array. `prefix[i-1]` gives the count of numbers smaller than `i`. |
Draw a frequency histogram. For any bar, the sum of all bars to its LEFT is the answer. Use a running total to pre-calculate these sums. |
$O(N + \text{MaxValue})$ |
Draw a linear scan to count, then a single 100-step pass to sum frequencies, proving linear performance. |
$O(1)$ Counter: A single variable reset for every outer loop. |
101-Slot Frequency Array: Draw a fixed-size array mapping values to counts. |
| 1366 |
Rank Teams by Votes |
For every team, calculate all possible permutations of rankings and use a nested loop to compare each team against every other team. |
$O(T! \cdot V)$ Combinatorial Comparison |
Draw 26 teams. Show a web of lines connecting every team to every other team. Inside each connection, draw a sub-graph of votes. |
Multi-Level Sorting (Frequency Matrix) |
2D Scoreboard Heatmap |
Create a 26x26 matrix. `matrix[team][rank]` stores the vote count. Sort teams based on the entire row of the matrix as a key. |
Draw a grid: Teams (rows) vs. Ranks (columns). Fill with vote counts. To compare Team A and B, scan columns left-to-right. The first column where counts differ decides the winner. |
$O(V \cdot T + T^2 \log T)$ |
Draw a sorting funnel where each "Comparison" involves a linear scan of a fixed-size row (size 26), proving stability. |
Permutation List: Storing massive strings of team orders to find the "best" one. |
Fixed 2D Matrix: Draw a 26x26 integer array. Space is $O(1)$ since the number of teams is capped at 26. |
| 1367 |
Linked List in Binary Tree |
For every single node in the binary tree, start a new DFS to see if the linked list matches a downward path from that node. |
$O(N \cdot M)$ Dual Traversal |
Draw a tree. At every node, draw a "mini-tree" representing a full path check for the list. Note the massive overlapping checks. |
KMP Pattern Matching on Tree |
String-Matching State Machine |
Treat the linked list as a pattern. Precompute KMP's prefix function. Use DFS to traverse the tree while maintaining the KMP state. |
Draw the linked list with "fallback" arrows (KMP). As you move down the tree, follow the list. If a mismatch occurs, use the fallback arrow to skip redundant comparisons. |
$O(N + M)$ Linear Tree Scan |
Draw a tree with a single arrow tracing it, while a small pointer moves along the linked list pattern, proving single-pass efficiency. |
Deep Recursive Stack: Many overlapping frames checking the same list segments repeatedly. |
KMP Prefix Array + Stack: Draw a small array for the list pattern and a standard DFS stack. |
| 1368 |
Minimum Cost to Make at Least One Valid Path in a Grid |
Use DFS to find all possible paths from (0,0) to (m,n), summing the costs of changing arrows on each path. |
$O(4^\text{NM})$ Path Explosion |
Draw a grid. Show arrows branching in 4 directions from every cell. The tree grows exponentially, revisiting cells and looping. |
0-1 BFS / Dijkstra's Algorithm |
Weight-Layered Expansion |
Follow the arrow's direction with weight 0 (Deque: push to front). Move in other directions with weight 1 (Deque: push to back). Always pop from the front. |
Draw the grid. Start at (0,0). "Free" moves (cost 0) expand like a liquid. "Paid" moves (cost 1) create a new outer layer. The first time you touch the exit, that's your min cost. |
$O(N \cdot M)$ Level Traversal |
Draw the grid. Show the BFS "front" moving across cells. Each cell is added/popped from the Deque at most twice, proving linear time. |
Unbounded Path History: Massive memory usage tracking every path's unique direction changes. |
Cost Grid + Deque: Draw a 2D array `dist[M][N]` and a Double-Ended Queue (Deque). |
| 1369 |
Get the Second Most Recent Activity (SQL) |
For every user, find the most recent activity, remove it, then find the most recent in the remaining set. If only one exists, return it. |
$O(N²)$ Correlated Delete-Search |
Draw a user's timeline. Erase the top dot. Find the new top dot. If there's no new dot, bring back the erased one. Repeat for every user. |
Window Function (ROW_NUMBER + COUNT) |
Ranked Timeline Indexing |
Use `ROW_NUMBER() OVER (PARTITION BY username ORDER BY startDate DESC)` and `COUNT(*) OVER (PARTITION BY username)`. Filter where `rank = 2` OR `(count = 1 AND rank = 1)`. |
Draw a timeline for a user. Label dots 1, 2, 3 starting from the latest. Pick dot #2. If only one dot exists, pick #1. |
$O(N \log N)$ Partitioned Sort |
Draw the table divided into user-colored blocks. Inside each block, show the rows being numbered from 1 to N based on date. |
Intermediate Result Sets: Cloning the table multiple times to perform "Not In" exclusions. |
Row-Indexed Cursor: Draw a single pass through the table that attaches an index to each row within its group. |
| 1370 |
Increasing Decreasing String |
Find the lexicographical smallest char, append it, then search the remaining string for the next smallest, and so on. |
$O(N^2)$ Repeated Searching |
Draw a string. Draw a magnifying glass scanning the whole string for 'a', then 'b', etc. Show the glass moving back and forth across the entire tape. |
Bucket Sort / Counting Tally |
Pendulum Scan |
Count all characters into a 26-slot frequency array. Loop 1: Scan 0 to 25, taking 1 of each char. Loop 2: Scan 25 down to 0, taking 1 of each char. Repeat. |
Draw 26 buckets labeled 'a' to 'z'. Fill them with letters. Draw a pointer moving left-to-right (up the alphabet), then right-to-left (down), picking one letter per bucket. |
$O(N)$ Bucket Pass |
Draw a 26-slot array. Show an arrow sweeping back and forth like a windshield wiper until all slots are empty. |
Temporary String Subsets: Creating new strings repeatedly after "deleting" used characters. |
26-Slot Integer Array: Draw a simple frequency array. $O(1)$ space relative to alphabet. |
| 1371 |
Find the Longest Substring Containing Vowels in Even Counts |
Check every possible substring (O(N^2)) and count the vowels in each to see if all counts are even (O(N)). |
$O(N^3)$ Substring Sifting |
Draw a string. Draw thousands of brackets. Inside each, draw 5 counters (a, e, i, o, u) ticking up. Total N^3 operations. |
Bitmask + Prefix XOR (First Occurrence) |
State-Space Hashing |
Represent the parity (odd/even) of the 5 vowels as a 5-bit mask (e.g., `00101`). Use XOR to update the mask. The longest substring is between two indices with the same mask. |
Draw a string. As you move, toggle bits in a 5-bit "switchboard." Record the first index each switchboard configuration appears in a Map. If you see the configuration again, calculate the distance. |
$O(N)$ Linear Pass |
Draw a single arrow moving left-to-right. Show a small "state" variable (the mask) updating in-place, and a single Map lookup per step. |
$O(N^2)$ Substring Storage: Massive memory consumption for intermediate string processing. |
32-Slot First-Occurrence Array: Draw a fixed-size array of 32 elements (2^5). Space is strictly $O(1)$. |
| 1372 |
Longest ZigZag Path in a Binary Tree |
For every node, start two separate DFS paths (one starting left, one starting right) and manually count the zig-zags. |
$O(N^2)$ Redundant Tree Paths |
Draw a tree. From every node, draw a jagged "Z" line downward. Note how many nodes are visited multiple times by different starting points. |
Top-Down DFS with State Passing |
Recursive State Carry-over |
DFS function takes `(node, direction, currentLength)`. If moving Left, next call is `(node.left, 'Right', currentLength + 1)` AND reset for the other side `(node.right, 'Left', 1)`. |
Draw a tree. At each node, write two numbers: `L` (length if we arrived from left) and `R` (length if we arrived from right). Carry the values down the tree. |
$O(N)$ Single Tree Traversal |
Draw a single line snaking through the tree in a standard DFS pattern, proving each node is touched exactly once. |
Duplicate Call Stack: Multiple DFS entries per node causing memory bloat and redundant work. |
$O(H)$ Recursion Stack: Draw a single stack trace where each frame holds only the current node and two integers. |
| 1373 |
Maximum Sum BST in Binary Tree |
For every node, run a full BST validation check $O(N)$ and calculate the sum of its subtree $O(N)$. Total $O(N^2)$. |
$O(N^2)$ Nested Tree Validation |
Draw a tree. For the root, draw a circle around the whole tree. For its child, draw another overlapping circle. Repeat for every node. |
Post-Order DFS (Bottom-Up State) |
Multi-Value Recursive Return |
Each node returns: `{isBST, minVal, maxVal, sum}`. A node is a BST only if its children are BSTs and `left.max < node.val < right.min`. |
Draw a tree. Start at leaves. Write `[Min, Max, Sum]` in a box. Move to parent; check the child boxes, calculate new sum, and update the global max. |
$O(N)$ Bottom-Up Pass |
Draw an arrow moving from leaves up to the root. Each node is processed exactly once after its children, proving linear time. |
Redundant Traversal Stacks: Re-visiting subtrees over and over to re-verify BST properties. |
$O(H)$ Stack + Struct: Draw a stack where each frame returns a custom object containing 4 integers. |
| 1374 |
Generate a String With Characters... |
Use a random generator to build strings and a complex frequency map to check if all counts are odd. |
$O(N!)$ Randomized Search |
Draw a cloud of random strings. Draw a filter checking each one. Wasted CPU cycles on a simple parity problem. |
Greedy Parity Construction |
Odd-Even Split Logic |
If N is odd, return "aaa..." (N times). If N is even, return "aaa..." (N-1 times) + "b". Both ensure all character counts are odd. |
Draw a line of 'a's. If the line is even, cross out the last 'a' and write 'b'. Count them: N-1 (odd) and 1 (odd). |
$O(N)$ Linear String Build |
Draw a single line of length N being filled character by character in one pass. |
Temporary String Buffer Pool: Storing many candidate strings in the heap. |
Single String Builder: Draw one contiguous memory block of size N. |
| 1375 |
Number of Times Binary String Is Prefix-Aligned |
For every step `i`, iterate from 1 to `i` to check if all bits are set to 1. |
$O(N^2)$ Repeated Prefix Checks |
Draw a binary string growing. At step 3, check bits 1, 2, 3. At step 4, check bits 1, 2, 3, 4. Note the overlap. |
Max-Value Tracking (Greedy) |
Running Peak Alignment |
Observe that the string is prefix-aligned if and only if the maximum index seen so far equals the number of bits flipped so far (`max_pos == current_step`). |
Draw a sequence: `[3, 1, 2, 5, 4]`. Track `max` at each step. Step 1: max=3. Step 2: max=3. Step 3: max=3 (Step matches Max! Count++). |
$O(N)$ Single Scan |
Draw a single arrow moving through the input array, comparing two integers at each step. |
Full Bitset: Maintaining a physical bit array and scanning it repeatedly. |
$O(1)$ Two-Integer State: Only store `max_seen` and `count`. |
| 1376 |
Time Needed to Inform All Employees |
For every employee, trace the path back to the head of the company and sum the time, then find the global maximum. |
$O(N \cdot H)$ Path Tracing |
Draw an organizational chart. For every leaf, draw a line up to the CEO. Note the overlapping paths near the top of the tree. |
Top-Down DFS (Tree Path Sum) |
Weighted Depth Traversal |
Standard DFS starting from the CEO. Each call passes the `currentTime` accumulated from the parent. Global max of `currentTime` is the answer. |
Draw the hierarchy. On each edge, write the "inform time." Trace down every path, adding the weights. Write the total time next to each leaf. |
$O(N)$ Graph Traversal |
Draw a single wave of information flowing from the top to the bottom of the tree. Each employee is reached once. |
Parent Pointers Map: Storing every relationship in a way that requires constant back-tracing. |
Adjacency List + Recursion: Draw a CEO node pointing to subordinates. Memory is $O(N)$. |
| 1377 |
Frog Position After T Seconds |
Use BFS to explore all possible positions at every second, but without handling the "frog stays put" rule correctly, leading to wrong probabilities. |
$O(\text{Branches}^T)$ State Explosion |
Draw a frog on a tree. At each second, draw a new frog for every possible jump. The number of frogs grows exponentially. |
DFS with Probability Propagation |
Path Weight Product |
Trace a single path to the target. If target is reached at `t` (or reached early and has nowhere to jump), probability is `1 / product(number of children at each step)`. |
Draw the tree. At the root, prob = 1. Jump to a node with 3 children; each gets 1/3. If a node has 2 children, they each get (1/3 * 1/2) = 1/6. Stop at time T. |
$O(N)$ Target Path Search |
Draw a single line from the root to the target node. Once found, calculate the probability along that specific path. |
Massive BFS Queue: Storing thousands of `(node, prob, time)` tuples for every possible location. |
$O(H)$ Path State: Draw a single recursion stack that only keeps the probability and current time for one branch. |
| 1378 |
Replace Employee ID With The Unique Identifier (SQL) |
Nested Loop Join: For every employee, full scan the UniqueID table. $O(N \cdot M)$. |
Full Cartesian Product Grid |
Draw Table A and Table B. Draw a line from every row of A to every row of B. |
LEFT JOIN (Hash Join) |
The Index Matcher |
The engine builds a hash table of UniqueID and probes it using Employee IDs in a single pass. |
Draw the Employees table. Next to it, draw a "Lookup Map". Draw straight arrows directly to the map. |
Hash/Merge Join $O(N + M)$ |
Draw two parallel lines flowing into a single merge node. |
Massive disk I/O for repeated scans. |
Hash Table for the smaller table. $O(M)$ space. |
| 1379 |
Find a Corresponding Node of a Binary Tree in a Clone of That Tree |
Traverse the original tree to find the target, record its "path" (e.g., Left-Right-Left), then replay that path on the cloned tree. |
Double Tree Traversal |
Draw two identical trees. Trace a path in the first, then draw a second identical path in the clone. Note the redundant work of two separate traversals. |
Synchronized DFS / BFS |
Dual-Pointer Tree Sweep |
Traverse both trees simultaneously. If `original_node == target`, return the current `cloned_node`. This avoids needing to store path history. |
Draw Tree A and Tree B side-by-side. Draw two fingers pointing to the root of both. Move both fingers to the left child, then right, etc., until Finger A hits the target. Finger B is your answer. |
$O(N)$ Single Pass |
Draw a single line snaking through both trees in parallel, proving you visit each node position exactly once. |
Path String/List: Storing a sequence of "L" and "R" directions in memory. |
$O(H)$ Call Stack: Draw a single recursion stack where each frame holds two node pointers (Original and Cloned). |
| 1380 |
Lucky Numbers in a Matrix |
For every cell (i, j), check if it's the minimum in its row $O(C)$ and then check if it's the maximum in its column $O(R)$. |
$O(R\cdot C \cdot (R+C)$) Nested Checks |
Draw a matrix. Pick a cell. Draw a horizontal line across its row and a vertical line through its column. Repeat for every single cell in the grid. |
Precomputed Row-Mins and Col-Maxes |
Intersection of Two Sets |
Calculate an array `min_rows` (size R) and `max_cols` (size C). A number is "lucky" if `matrix[i][j] == min_rows[i]` AND `matrix[i][j] == max_cols[j]`. |
Draw the matrix. Write the minimum of each row to the right. Write the maximum of each column at the bottom. Circle any number that matches both its row-minimum and column-maximum. |
$O(R \cdot C)$ Linear Grid Scan |
Draw two passes: one sweeping horizontally to find row mins, one sweeping vertically to find col maxes. |
Redundant Scan Buffers: Thousands of temporary lists created for min/max checks. |
Two 1D Arrays: Draw a vertical array (Row Mins) and a horizontal array (Col Maxes). Memory is $O(R + C)$. |
| 1381 |
Design a Stack With Increment Operation |
When `increment(k, val)` is called, iterate through the first k elements of the stack and physically add `val` to each. |
$O(K)$ Linear Increment |
Draw a stack of boxes. For every increment, draw an arrow pointing to each of the bottom k boxes, adding the value. Note the performance hit for large stacks. |
Lazy Propagation (Difference Array Logic) |
Bottom-Up Value Cascading |
Store increments in an auxiliary array `inc`. When `pop()` happens, return `stack[top] + inc[top]`, and pass the increment down: `inc[top-1] += inc[top]`. |
Draw a stack. Next to it, draw an "Increment Buffer." When you increment the bottom 3 by 10, just write '10' next to the 3rd element. Only add it when that element is popped. |
$O(1)$ Constant Time per Op |
Draw a stack with a single pointer. Show that `push`, `pop`, and `increment` each touch only a single memory address, proving $O(1)$. |
$O(N)$ Repeated Iteration: CPU cycles wasted looping through stack contents. |
Auxiliary Increment Array: Draw two parallel 1D arrays of size `maxSize`. One for data, one for "lazy" updates. |
| 1382 |
Balance a Binary Search Tree |
Repeatedly perform tree rotations or attempts to "re-hang" nodes until the height difference between children is minimized. |
$O(N \log N)$ Chaotic Rebalancing |
Draw a skewed tree. Draw arrows showing nodes shifting left and right. The logic is hard to visualize and prone to infinite loops. |
In-Order Flattening + Midpoint Reconstruction |
Array-to-Balanced-Tree Fold |
1. Perform in-order traversal to get a sorted array of nodes. 2. Use a recursive function to pick the middle element as the root, then repeat for left and right halves. |
Draw a sorted list of numbers. Circle the middle one—that's the root. Draw two lines to the middle of the left and right halves—those are the children. It creates a perfect pyramid. |
$O(N)$ Linear Reconstruction |
Draw a single tree traversal (O(N)) followed by a recursive build process that visits each element once (O(N)). |
In-place Rotation Stack: Complex pointers and temporary node variables during rotation. |
$O(N)$ Sorted List: Draw a simple flat array of node pointers used to store the tree's values temporarily. |
| 1383 |
Maximum Performance of a Team |
Generate all possible subsets of engineers (up to 2^N), calculate performance for each, and find the maximum. |
2^N Subset Combination |
Draw an engineer. Branch out: "Include" or "Exclude." The tree reaches 2^N leaves, which is impossible for N=100,000. |
Greedy + Min-Heap (Bounded Priority Queue) |
Efficiency-Ordered Sliding Window |
Sort engineers by efficiency descending. Iterate through, adding speed to a Min-Heap. If heap size > K, remove the smallest speed. Performance = `sum_of_speeds * current_efficiency`. |
Sort engineers by efficiency. Move a "window" down the list. Keep the fastest K engineers in a "Fastest Bucket" (Heap). Every time efficiency drops, update the performance score. |
$O(N \log N + N \log K)$ |
Draw a sorting funnel followed by a linear scan where a small Heap bucket (size K) is updated at each step. |
$O(2^N)$ Subset States: Storing thousands of combinations in the recursion stack. |
Min-Priority Queue: Draw a heap that only grows to size K. Space is $O(N + K)$. |
| 1384 |
Total Sales Amount by Year (SQL) |
For every sale, calculate the duration, then check every day in the calendar to see which year it belongs to, summing manually. |
$O(\text{Sales} \\text{cdot Days})$ Nested Logic |
Draw a sale spanning 3 years. Draw an arrow for every single day in that range, checking the year. Massive CPU overhead for date ranges. |
Recursive CTE (Year-Level Pivot) |
Yearly Segment Slicing |
Use a Recursive CTE to generate the years 2018, 2019, 2020. Join with Sales where the year is between `start_date` and `end_date`. Calculate overlap days per year. |
Draw a sale bar. Place three boxes representing 2018, 2019, and 2020. Cut the sale bar into parts that fit into each box. Multiply each part by the daily price. |
$O(\text{Sales} \cdot 3)$ Linearized Split |
Draw a sale record entering a machine that splits it into at most 3 rows (one for each valid year). |
Massive Daily Logs: Creating a row for every single day in a 3-year period in memory. |
3-Row Splitter: Draw a structure where one input row transforms into a maximum of 3 output rows. |
| 1385 |
Find the Distance Value Between Two Arrays |
For every element in `arr1`, loop through every element in `arr2` to check if the absolute difference is less than or equal to `d`. |
$O(N \cdot M)$ Quadratic Search |
Draw two arrays. From the first element of `arr1`, draw arrows to every element of `arr2`. Repeat for all elements. Total N x M checks. |
Sorting + Binary Search (Range Check) |
Targeted Gap Detection |
Sort `arr2`. For each `x` in `arr1`, binary search for any value in `arr2` within the range `[x - d, x + d]`. If none exist, increment count. |
Draw a sorted number line for `arr2`. For an element from `arr1`, draw a "danger zone" of size d around it. If no dots from `arr2` fall in the danger zone, the element is "safe." |
$O(N \log M + M \log M)$ |
Draw a sorting funnel for one array, then a series of $O(\log M)$ jumps for each element in the other array. |
Nested Loop Accumulators: Constant re-scans of the second array. |
$O(M)$ Sorted Array: Draw a single sorted `std::vector` for the second array. Memory is $O(M)$. |
| 1386 |
Cinema Seat Allocation |
Create a full 2D Boolean matrix of size N x 10 to represent the entire cinema and iterate through every row to check for valid 4-person groups. |
$O(N x 10)$ Sparse Matrix Scan |
Draw a massive grid with 10 columns and N rows. Shade only a few cells (reserved seats). Show an arrow scanning every empty cell, highlighting the waste for N=10^9. |
Hash Map + Bitmask (Sparse Row Processing) |
Compressed Row Bit-States |
Only process rows that have reserved seats. Represent each row as a 10-bit integer. Use bitwise AND to check if blocks [2,5], [6,9], or [4,7] are free. |
Draw a row of 10 boxes. For a reserved seat at 3, put a '1' in the 3rd box. Use three "transparent templates" (the bitmasks for valid blocks) to see which fits over the 0s. |
$O(\text{ReservedSeats})$ Complexity |
Draw a small Map. Show that the total operations depend only on the number of reservations, not the total number of rows N. |
Massive 2D Array: A 10^9 x 10 grid in memory, causing a Memory Limit Exceeded (MLE) error. |
$O(K)$ Hash Map: Draw a `std::unordered_map` where K is the number of rows with at least one reservation. |
| 1387 |
Sort Integers by The Power Value |
For every integer in the range [lo, hi], calculate its power value from scratch by simulating the Collatz sequence repeatedly. |
Redundant Collatz Trajectories |
Draw a number line. For each number, draw a path of arrows showing its transformations. Note how paths for different numbers eventually merge and repeat the same steps. |
Recursion with Memoization (Top-Down DP) |
Global Result Cache |
Store the power value of every number calculated in a Hash Map. If you reach a number you've seen before (like 4, 2, 1), instantly return its cached value. |
Draw a "Memory Bank" (Map). As you calculate a path, check the bank. If you find a match, stop the path and just add the bank's value to your current step count. |
$O(N \\text{cdot avg}_\text{path})$ with Cache |
Draw a network of nodes where many paths converge into single cached nodes, proving that each unique number is calculated only once. |
Simulation State: Re-calculating the same values for 3, 5, 6, etc., over and over. |
$O(\text{UniqueStates})$ Cache: Draw a Hash Map storing results of the function `f(n)`. |
| 1388 |
Pizza With 3n Slices |
Generate every possible combination of picking N non-adjacent slices from a circular array and calculate the max sum. |
$O(2^N)$ Combinatorial Explosion |
Draw a pizza circle. Pick a slice, cross out neighbors. Pick next. Show the tree of choices branching out for every possible starting slice. |
Dynamic Programming (Linear House Robber Variant) |
State Matrix Optimization |
The problem reduces to: Pick N non-adjacent items from 3N items. Since it's circular, run DP twice: once for slices [0...3N-2] and once for [1...3N-1]. |
Draw the slices in a line. Create a grid: Slices (rows) vs. Items Picked (cols). For each cell, the max value is either "Don't pick this slice" (cell above) or "Pick this slice" (cell 2-above + current value). |
$O(N²)$ Matrix Fill |
Draw a 2D grid of size 3N x N. Show arrows looking back 1 and 2 steps, filling the matrix sequentially. |
Recursion Tree Memory: Storing millions of partial sum states in a deep call stack. |
2D DP Table: Draw a `dp[3n][n]` array. (Can be space-optimized to two rows). |
| 1389 |
Create Target Array in the Given Order |
Use a standard dynamic array and perform the `insert(index, value)` operation for every element, causing massive element shifting. |
$O(N^2)$ Array Shifting |
Draw an array. To insert a '5' at index 1, draw arrows moving every element from index 1 to the end one slot to the right. Repeat N times. |
Self-Balancing BST or Linked List (Ideal) |
Node Insertion without Shift |
In high-level languages like Python, `list.insert` is $O(N)$. For true optimization, use a Linked List (though index access is $O(N)$) or a Balanced BST where each node tracks subtree size for $O(\log N)$ inserts. |
Draw a sequence of nodes with pointers. To insert, simply "cut" two pointers and draw two new ones connecting the new node. No elements are "moved." |
$O(N)$ (Language dependent) / $O(N \log N)$ |
Draw a tree being built. Each insertion involves walking down the tree height and adding a node, proving logarithmic or linear performance per step. |
$O(N)$ contiguous block: One array being repeatedly resized and copied. |
Pointer-based Memory: Draw individual nodes scattered in memory, connected by arrows. |
| 1390 |
Four Divisors |
For every number, iterate from 1 to the number itself and count how many divisors it has. |
$O(N x \text{num})$ Linear Divisor Scan |
Draw a number. Scan every integer up to it. If N = 10^5, you are doing billions of checks. |
Square Root Divisor Hunt |
Mirrored Divisor Pairs |
Iterate from 1 to √num. If d divides num, then num/d also divides it. If you find more than 4 distinct divisors during the scan, short-circuit and stop. |
Draw a number. Mark its square root. Scan from 1 to the root. For every hit, write down its "partner" on the other side of the root. If you have exactly 2 hits (4 divisors), sum them. |
$O(N √\text{max}_\text{val})$ |
Draw a line covering only the root of the number. Show the scan stopping early as soon as a 5th divisor is found. |
$O(\text{num})$ List of Divisors: Storing all numbers in an array before counting. |
$O(1)$ Counter: Only track `count` and `sum` during the √N loop. |
| 1391 |
Check if There is a Valid Path in a Grid |
Try moving in all 4 directions from every cell without checking if the street pipes actually connect, leading to invalid jumps. |
Blind BFS/DFS Exploration |
Draw a grid with pipes. Show an arrow jumping through a wall where pipes don't align. The path logic is broken. |
Disjoint Set Union (DSU) or Validated BFS |
Pipe-to-Pipe Connection Validation |
For each cell, check its 4 neighbors. Only union/jump if the current pipe's opening matches the neighbor's opening (e.g., a "Left" opening must meet a "Right" opening). |
Draw two adjacent cells with their pipe shapes. Circle the "mouths" of the pipes. If the mouths touch, draw a "link." Check if (0,0) and (M,N) are in the same link-set. |
$O(M x N x \text{alpha}(N)$) |
Draw the grid as a graph. Show a single BFS wave that only passes through valid connections, visiting each cell once. |
Unchecked Recursion Stack: Exploring paths that don't exist, leading to deep wasted recursion. |
$O(\text{MN})$ DSU Array or Visited Set: Draw a parent array representing connected pipe components. |
| 1392 |
Longest Happy Prefix |
For every possible prefix length L, extract the prefix and the suffix of length L, and compare them as strings $O(N)$. |
$O(N^2)$ String Slicing |
Draw a string. Highlight a prefix and suffix of length 1, then length 2... For each, draw a comparison process scanning both. |
KMP Algorithm (Prefix Function) |
Self-Matching Array (LPS) |
Compute the "Longest Prefix Suffix" (LPS) array used in KMP. The value at the very last index of the LPS array tells you the longest prefix that is also a suffix. |
Draw the string. Below it, draw an empty array. Fill the array by matching the string against itself with a shift. The value at the end is your answer. |
$O(N)$ Linear Scan |
Draw a single arrow moving across the string, maintaining a "match" length that updates in-place without ever backtracking. |
$O(N^2)$ String Fragments: Storing or comparing hundreds of temporary substring objects in memory. |
$O(N)$ LPS Array: Draw a single integer array of size N that tracks the state of the pattern match. |
| 1393 |
Capital Gain/Loss (SQL) |
Using correlated subqueries to find the 'Buy' price for every 'Sell' row individually and subtracting them. |
$O(N²)$ Row-by-Row Search |
Draw a table. For every "Sell" row, draw an arrow searching through all previous rows to find a matching "Buy". Massive overlapping reads. |
Conditional Aggregation (SUM + IF/CASE) |
Value Polarized Tallying |
Treat 'Buy' as negative and 'Sell' as positive. Group by `stock_name` and simply sum the prices: `SUM(IF(action='Buy', -price, price))`. |
Draw two columns: Buy and Sell. Put a minus sign next to Buy prices and a plus next to Sell. Group by stock name and add all numbers in the group. |
$O(N)$ Single Table Scan |
Draw a single arrow moving down the table once. Each row is processed and added to a running group total, proving linear time. |
Massive Temp Tables: Database engines generating huge intermediate sets for subquery matching. |
Hash Map Aggregator: Draw an in-memory Hash Map keyed by stock name, holding a single running integer sum. |
| 1394 |
Find Lucky Integer in an Array |
For every number in the array, loop through the whole array to count its frequency. If `count == value`, it's a candidate. |
$O(N²)$ Nested Frequency Counts |
Draw an array. For each element, draw arrows to every other element to count matches. A dense web of redundant checks. |
Frequency Map (Counting Sort Style) |
Histogram Density Check |
Use a Hash Map or a fixed-size array (if values are bounded) to count all frequencies in one pass. Then iterate the Map to find the max key where `key == value`. |
Draw 10 buckets. As you read the array, toss a pebble into the bucket matching the number. At the end, check if any bucket has exactly as many pebbles as its label. |
$O(N)$ Linear Scan |
Draw two separate arrows: one to build the tally and one to check the counts, proving 2N steps total. |
$O(1)$ Accumulator: Resetting a single counter variable N times. |
$O(N)$ Hash Table: Draw a key-value store mapping numbers to their frequencies. |
| 1395 |
Count Number of Teams |
Generate all possible triplets (i, j, k) with i < j < k and check if they are strictly increasing or decreasing. |
$O(N³)$ Triplet Enumeration |
Draw an array. Draw every possible triangle connecting three indices. The number of triangles grows cubically. |
DP / Middle-Element Counting |
Pivot-Based Combinatorics |
For each element j, count how many elements to its left are smaller/larger and how many to its right are smaller/larger. Teams = `left_smaller * right_larger + left_larger * right_smaller`. |
Draw an array. Circle a middle element. Draw arrows to the left for smaller numbers and to the right for larger ones. Multiply the counts to get the number of teams through that pivot. |
$O(N²)$ Linear Pivot Search |
Draw an arrow moving through the array. For each stop, draw two smaller arrows scanning left and right, proving quadratic time. |
$O(1)$ Memory: Just three nested loops using index variables. |
$O(1)$ Memory: Four integer counters for each pivot element. |
| 1396 |
Design Underground System |
Maintain a massive list of every completed trip. For `getAverageTime`, filter the entire list for matching start/end stations and sum their durations. |
$O(N)$ Query Filtering |
Draw a logbook with thousands of entries. For every query, draw a hand scanning every single page to find specific station pairs. |
Dual Hash Maps (In-Transit & Completed) |
Aggregated Buffer Lookup |
Map 1: `id -> {station, time}` for active trips. Map 2: `(start, end) -> {totalTime, count}`. Update Map 2 immediately upon checkout. |
Draw two boxes. Box A stores people currently on trains. When they step off, move their time to Box B, which already has the "Running Total" and "Count" for that specific route. |
$O(1)$ Constant Lookup |
Draw a direct arrow to a specific slot in a Hash Map, proving that average time is just one division away. |
Unstructured History: A single list that grows infinitely, consuming more memory and time. |
$O(S²)$ Station Map: Draw a Map of pairs where the memory depends on the number of unique routes, not the number of passengers. |
| 1397 |
Find All Good Strings |
Generate all possible strings lexicographically between s1 and s2 and use `string.find()` to check if the 'evil' pattern exists. |
$O(26^N \cdot M)$ Exponential Search |
Draw a massive tree where each level has 26 branches. Mark paths that fall outside [s1, s2] as dead, but note the billions of valid paths still requiring pattern checks. |
Digit DP + KMP (Automata State) |
State-Transition Matrix |
Use DP to count strings. State: `(index, evil_match_len, is_less, is_greater)`. Use KMP's failure function to jump to the next matching state for the 'evil' string. |
Draw a grid: String index vs. KMP state. Draw arrows showing how adding a character 'c' moves you to a new KMP state. If you hit the end of 'evil', that state is a "Dead Zone." |
$O(N \cdot M \cdot 26)$ |
Draw a 4D box (N x M x 2 x 2). Show data flowing layer by layer from index i to i+1, proving linear time relative to length N. |
$O(26^N)$ String Pool: Millions of strings stored or checked in a massive recursion stack. |
4D DP Table: Draw a compact multidimensional array `dp[501][51][2][2]` storing long integers. |
| 1398 |
Customers Who Bought A and B but Not C (SQL) |
Use `WHERE product='A' AND product='B' AND product!='C'`, which fails because SQL filters row-by-row, not across the customer's entire history. |
Logical Record Mismatch |
Draw a table. Check row 1: "Is it A and B and not C?" No, it's just A. Row 2 is just B. Result is empty. Visually shows why row-level logic fails for set-level problems. |
Group By + Having (Set Membership) |
Venn Diagram Filtering |
`GROUP BY customer_id` and use `HAVING SUM(product='A') > 0 AND SUM(product='B') > 0 AND SUM(product='C') = 0`. |
Draw a circle for Customer 1. Put all their purchases inside. If 'A' and 'B' are inside, but 'C' is not, color the circle green. If 'C' enters, color it red immediately. |
$O(N \log N)$ or $O(N)$ |
Draw a Hash Map where keys are Customer IDs and values are a bitmask or set of products, proving a single pass over the orders table. |
Subquery Temp Tables: Database creating multiple intermediate clones of the table to perform `EXCEPT` or `INTERSECT`. |
In-Memory Hash Aggregator: Draw a simple Hash Table tallying product counts per ID. |
| 1399 |
Count Largest Group |
For every number, convert it to a string, split the characters, parse back to integers, sum them, and store in a list of lists. |
$O(N \log N)$ String Manipulation |
Draw an integer entering a "String Factory." It comes out as characters, goes through a "Summer," and then gets sorted. High overhead for simple math. |
Integer Modulo Sum + Frequency Bucket |
Digit Peeling Tally |
Sum digits using `n % 10` and `n / 10`. Use an array to count how many numbers share the same digit sum. Find the max frequency and count how many sums hit that max. |
Draw a line of numbers. Peel off their digits using modulo 10. Write the sum. Drop a pebble into a bucket labeled with that sum. Find the fullest bucket. |
$O(N \log₁₀ N)$ |
Draw a single loop from 1 to N. Each step involves a small nested loop that runs exactly as many times as there are digits (very small constant). |
Nested List Buffers: Storing every number categorized by its sum in dynamic lists. |
Fixed Size Array: Draw an array of size 37 (max digit sum for 10000). Space is strictly $O(1)$ relative to input size. |
| 1400 |
Construct K Palindrome Strings |
Generate all permutations of the string and try to split them into k parts, checking each part for the palindrome property. |
$O(N! \cdot N)$ Combinatorial Hell |
Draw the string. Branch out into every possible reordering. For each reorder, draw k-1 "cutting" lines in every possible gap. Exponentially impossible. |
Odd Frequency Character Counting |
Parity Constraint Logic |
A palindrome can have at most one character with an odd frequency. If the number of characters with odd frequencies is > k, or if k > length of string, it's impossible. |
Draw characters as dots. Group them in pairs. Any dot without a pair is "lonely" (odd). Each lonely dot *must* be the center of its own palindrome. If you have more lonely dots than k slots, you fail. |
$O(N)$ Frequency Scan |
Draw a single pass through the string to count letters, followed by a comparison of two integers (k and odd_count). |
Permutation Buffer: Storing billions of string variations in memory. |
26-Slot Tally Array: Draw a simple frequency array. Space is $O(1)$ relative to the input size. |
| 1401 |
Circle and Rectangle Overlapping |
Check every coordinate point (x,y) inside the rectangle bounds to see if it satisfies the circle's equation: (x-center_x)² + (y-center_y)² <= radius². |
2D Grid Traversal / Nested Loops Space |
Draw a Cartesian plane. Draw a box representing bounds (x1 to x2, y1 to y2). Draw arrows iterating through every single integer point inside the box. Label area as $O(W \cdot H)$. |
Math / Geometry (Closest Point) |
Bounding Box Projection |
Clamp the circle's center coordinates to the rectangle's edges. Calculate the distance from this new "closest point" to the circle's center. If distance <= radius, they overlap. |
Draw the rectangle. Draw the circle center outside it. Draw dashed orthogonal lines projecting the center onto the closest edge/corner of the rectangle. Draw a solid line showing the distance. |
$O(1)$ Constant Time Node |
Draw a single box labeled "Clamp X, Clamp Y -> Math Formula". Write $O(1)$ inside it with no loops attached. |
Single Frame / Scalar Variables |
Two small boxes labeled "closestX" and "closestY" floating independently. No arrays. |
| 1402 |
Reducing Dishes |
Generate all possible subsequences (combinations of taking/leaving dishes) while maintaining relative order. Calculate the "like-time coefficient" for each and find the max. |
Binary Recursion Tree |
Draw a root node splitting into two branches: "Cook Dish[i]" and "Skip Dish[i]". Branch down to depth N. Write $O(2^N)$ at the bottom. |
Sorting + Greedy (or 1D DP) |
Accumulator Array / Sliding Prefix Sum |
Sort dishes descending. Keep a running sum of dishes taken. If the running sum > 0, add it to the total satisfaction. Stop when adding the next dish makes the running sum negative. |
Draw an array of numbers sorted highest to lowest. Draw a pointer moving right. Below it, draw two boxes: "Running Sum" and "Total Sum", updating their values as the pointer moves. |
Linear Scan Pipeline |
Draw a box "Sort: $O(N \log N)$" -> an arrow -> a box "Linear Scan: $O(N)$". Circle the sort box as the bottleneck. |
Call Stack Tower |
Draw two variables (RunningSum, Total) updating sequentially. No extra arrays needed, just $O(1)$ auxiliary space. |
| 1403 |
Minimum Subsequence in Non-Increasing Order |
Generate all subsets. Check if subset sum > remaining sum. Filter valid subsets, sort by length, then by sum, and pick the optimal one. |
Subset Generation Tree |
Draw a tree expanding into 2^N subsets. At each leaf node, draw a scale weighing "Subset Sum" vs "Total - Subset Sum". |
Sorting + Greedy Accumulation |
Two-Pan Balance Scale Visualization |
Calculate total array sum. Sort descending. Iterate, adding to `current_sum` and pushing to result array. Stop when `current_sum` > `total_sum - current_sum`. |
Draw the sorted array. Shade elements from the left one by one. Draw a scale below where the left side gets heavier (current sum) while the right side gets lighter (remaining sum). |
Sorting Bottleneck Graph |
Draw $O(N)$ for Total Sum -> $O(N \log N)$ for Sort -> $O(N)$ for Greedy selection. |
Massive Array Heap |
Draw one output array growing dynamically (List/Vector) and a single integer variable tracking 'current_sum'. |
| 1404 |
Number of Steps to Reduce a Number in Binary Representation to One |
Parse string to BigInt. While > 1: check if even (divide by 2) or odd (add 1). Convert back to string if simulating manually. |
String Reallocation Cycle |
Draw a long binary string. Draw an arrow pointing to a newly allocated string for the next step, repeating until "1". Label as $O(N^2)$ due to string shifting. |
Right-to-Left Carry Simulation (Greedy) |
Bitwise Carry Propagation |
Traverse string right to left. If bit + carry == 1 (odd), step=step+2, carry=1. If bit + carry == 0 (even), step=step+1. Special case for the MSB. |
Draw the binary string in individual cells. Place a pointer at the far right. Draw a small "Carry" flag floating above the current cell. Move pointer left, updating steps and carry. |
Single Pass Array Traversal |
Draw a 1D array with an arrow moving strictly right-to-left. Label with $O(N)$ time. |
Multiple String Allocations in Heap |
Draw a single integer "Carry" (0 or 1) and a "Steps" counter. Point to the original immutable string. Space is $O(1)$. |
| 1405 |
Longest Happy String |
Backtracking algorithm. Try adding 'a', 'b', or 'c'. If valid (no 3 consecutive), recurse. Find the longest valid path. |
Trinary Backtracking Tree |
Draw a root splitting into 3 branches (a, b, c). Prune branches where 3 identical letters align. Extremely wide tree, $O(3^(A+B+C)$). |
Max Heap / Priority Queue (Greedy) |
Resource Pool Extraction |
Put counts of a, b, c in a Max Heap. Pop the most frequent character. If appending it breaks the rule, pop the second most frequent. Append, decrement, and push back if > 0. |
Draw 3 buckets for a, b, c. Continually take a block from the fullest bucket. If you take 2 from the same bucket in a row, temporarily block it and take from the next fullest. |
Logarithmic Heap Operations |
Draw a loop iterating (A+B+C) times. Inside the loop, draw a heap push/pop box labeled $O(\log 3)$ -> effectively $O(1)$. |
Deep Recursion Call Stack |
Draw a small 3-element tree/array representing the Max Heap. Below it, draw a dynamically growing string buffer for the result. |
| 1406 |
Stone Game III |
Minimax Recursion. Try taking 1, 2, or 3 stones. Alice maximizes her score minus Bob's; Bob minimizes the difference. Try all paths. |
Minimax Decision Tree |
Draw a root node branching into 3 paths (take 1, 2, 3). Alternate row labels: "Alice (Max)" and "Bob (Min)". $O(3^N)$ due to 3 branches at every step. |
1D Dynamic Programming (Bottom-Up) |
Backward Induction Array |
Start from the end of the array. At index `i`, calculate the max of `sum(stones[i..i+k-1]) - dp[i+k]` for k in (1,2,3). Store in `dp[i]`. |
Draw an array of size N. Start a pointer at the rightmost index. Draw 3 arrows jumping left (sizes 1, 2, 3). Write the max difference formula above the jumps. |
Single Reverse Traversal |
Draw a straight arrow moving right-to-left across an array. Label it $O(N)$ time. |
Deep Recursion Call Stack |
Draw a 1D DP array of size N+1. (Or optionally, just 3 standalone variables for $O(1)$ space optimization). |
| 1407 |
Top Travellers (SQL) |
Correlated Subquery. For every single user in the Users table, run a separate SELECT sum(distance) query on the Rides table. |
Nested Loop Join Plan |
Draw a 'Users' table. From every single row, draw an arrow pointing to a full scan of the 'Rides' table. Label $O(N \cdot M)$. |
LEFT JOIN + GROUP BY + COALESCE |
Hash Join & Aggregation Pipeline |
Group the Rides table by user_id to sum distances. LEFT JOIN Users to this aggregated data. Use COALESCE to turn NULLs into 0. Sort by distance DESC, name ASC. |
Draw two tables. Draw a funnel extracting and summing 'Rides' by user_id. Draw lines matching 'Users.id' to the funnel output. Show NULLs converting to 0. |
Pipeline Bottleneck Graph |
Draw Hash Map symbol $O(N+M)$ -> Sort symbol $O(N \log N)$. |
Cartesian Product / Repeated Scans |
Draw an intermediate Hash Table storing `user_id -> total_distance` in memory. |
| 1408 |
String Matching in an Array |
Compare every string with every other string using standard string search `str1.indexOf(str2)`. Requires nested loops over the array. |
All-Pairs Directed Graph |
Draw N nodes. Draw directed edges from every node to every other node (N^2 edges). Label edge cost as $O(L^2)$ for basic string matching. |
Length Sort + KMP (or Suffix Tree) |
Substring Sliding Window |
Sort array by string length. For each string, use KMP to search for it in all longer strings. KMP uses an LPS (Longest Prefix Suffix) array to skip redundant checks. |
Draw a short string underneath a long string. Draw a sliding window box. When a character mismatches, draw an arrow sliding the window right by multiple spaces using LPS. |
Linear String Matching |
Draw string traversal $O(L1 + L2)$. Total time $O(N^2 \cdot (L1+L2)$). |
N^2 Function Call Frames |
Draw a small integer array (LPS array) floating next to the string variables, size equal to the shortest string. |
| 1409 |
Queries on a Permutation With Key |
Array shifting. For each query, do a linear search to find the element, then shift all elements before it one position right, placing it at index 0. |
Array Shifting Avalanche |
Draw an array. Circle the target element. Draw arrows shifting every element to its left one step right. Move the target to index 0. $O(M \cdot N)$. |
Fenwick Tree (Binary Indexed Tree) |
Prefix Sum Coordinate Compression |
Create an array of size `2M + N`. Place permutation at the end. Use a BIT to track active positions (1=present). To move an item, query prefix sum for its index, set old position to 0, place at new front, set to 1. |
Draw a wide array with empty slots on the left. Draw a binary tree above it tracking the sum of 1s. Show an element moving from the right side to an empty left slot, updating the tree path. |
Logarithmic Tree Traversal |
Draw a tree path update. Label depth as $O(\log(N+M)$). Total time $O(M \log(N+M)$). |
Single Contiguous Array |
Draw an oversized Array and a Fenwick Tree array, both of size `2M + N`. |
| 1410 |
HTML Entity Parser |
Multi-pass replace. Use `string.replace()` 6 separate times for the 6 different HTML entities, scanning the string from start to finish each time. |
Multi-Pass String Reallocation |
Draw the input string. Draw 6 separate horizontal arrows over it (one for each entity type), each generating a brand new string below it. Label $O(K \cdot N)$. |
Single-Pass Two-Pointer / StringBuilder |
Finite State Machine / Buffer Append |
Read characters into a StringBuilder. If '&' is seen, buffer chars until ';'. If the buffered string matches a Hash Map key, append decoded char. Else, append literal buffer. |
Draw an input tape and an output tape. A read head moves right. When it hits '&', characters divert into a small "entity buffer" box. If valid, drop 1 char to output; if invalid, drop whole buffer to output. |
Single Linear Scan |
Draw a single straight arrow moving left to right across the string. Label $O(N)$ time. |
Multiple Large Strings in Heap |
Draw a single dynamically growing StringBuilder (char array) and a small, static HashMap of size 6. |
| 1411 |
Number of Ways to Paint N × 3 Grid |
Backtracking to color each cell row by row. Try all 3 colors for each cell, recursively validating against the left and top adjacent cells. |
Exponential Branching Tree |
Draw an N-depth tree where each row attempts up to 27 combinations. Cross out invalid adjacent colors with red Xs. Label $O(27^N)$. |
State Machine DP / Math |
2-State Transition Graph |
A row has 2 valid patterns: 3-colors (Type 1) or 2-colors (Type 2). T1 generates 2 new T1s and 2 T2s. T2 generates 2 T1s and 3 T2s. Iterate N times updating counts. |
Draw two nodes labeled "Type 1" and "Type 2". Draw directed arrows looping back to themselves and to each other, labeled with multipliers (2 and 3). |
Constant Time Loop |
Draw a circular loop running N times. Inside the loop, write $O(1)$ basic arithmetic operations. Total $O(N)$. |
Deep Recursion Call Stack |
Draw just two floating integer variables `T1` and `T2` updating their values simultaneously. Space is $O(1)$. |
| 1412 |
Find the Quiet Students in All Exams (SQL) |
Correlated Subqueries. For every student, run a subquery to find their exams, and for each exam, run another subquery to find the absolute max and min scores of that specific exam. |
Triple Nested Loop Join |
Draw the Student table pointing to the Exam table, which then points to two separate full-table scans of the Exam table for MAX() and MIN(). Label $O(S \cdot E^2)$. |
Window Functions (RANK / MAX OVER) |
Partitioned Data Frame |
Use `MAX(score) OVER(PARTITION BY exam_id)` to tag the top/bottom scores inline. Flag students who hit these extremes. Group by student and filter out flagged ones. |
Draw the Exam table chopped into blocks by `exam_id`. Add a virtual column beside it instantly showing the max/min for that block. Cross out students matching those virtual numbers. |
Partition & Filter Pipeline |
Draw a Database symbol -> Partition/Sort $O(E \log E)$ -> Filter $O(E)$ -> Join $O(S)$. |
Massive Temp Tables |
Draw a single, partitioned dataset held in memory during the Window Function execution. |
| 1413 |
Min Value to Get Positive Step by Step Sum |
Simulation. Start by guessing `startValue = 1`. Run through the array calculating the sum. If it ever hits 0 or less, stop, increment `startValue` to 2, and try again. |
Iterative Simulation Timeline |
Draw a timeline for start=1. If it hits <=0, draw a red X and draw a whole new timeline below it for start=2. Repeat until a timeline survives to the end. $O(N \\text{cdot min}_\text{val})$. |
Prefix Sum / Minimum Running Sum |
Line Chart Trough Finding |
Calculate the running sum of the array. Track the absolute minimum value reached at any point. The required start value is simply `1 - minimum_running_sum` (if min < 0), else 1. |
Draw a line graph dipping below the x-axis. Circle the lowest point (the trough). Draw an arrow from the trough up to the +1 line. The length of that arrow is the answer. |
Single Pass Array Traversal |
Draw an array with a single pointer sliding left to right. Label $O(N)$ time. |
$O(1)$ Auxiliary Space |
Draw two integer variables: `running_sum` and `min_sum` updating as the array is read. Space $O(1)$. |
| 1414 |
Find Min Fibonacci Numbers Whose Sum Is K |
Subset Sum Backtracking. Generate all Fibonacci numbers up to K. Try all possible combinations of them to find which subset sums exactly to K with the fewest elements. |
Exponential Subset Tree |
Draw a binary tree deciding "Include Fib[i]" or "Exclude Fib[i]" for all ~45 Fibonacci numbers up to K. Massive $O(2^45)$ search space. |
Greedy Algorithm (Coin Change variation) |
Largest Denomination Subtraction |
Generate Fibonacci numbers up to K. Greedily subtract the largest possible Fibonacci number from K. Repeat with the remainder until K equals 0. Count the subtractions. |
Draw a number line ending at K. Draw the largest possible backward jump using a Fibonacci number. From that landing spot, draw the next largest valid backward jump, until hitting 0. |
Logarithmic Generation + Scan |
Draw a loop generating Fibs $O(\log K)$ -> an arrow -> a backwards loop $O(\log K)$. Total $O(\log K)$ time. |
Massive Recursion Stack |
Draw a simple dynamic array (List/Vector) holding about 45 integers (since Fib(45) > 10^9). |
| 1415 |
The k-th Lexicographical String of All Happy Strings |
Generate All & Sort. Use backtracking to build every single valid happy string of length n. Store them all in an array, sort alphabetically, and return the k-th index. |
Full Generation & Sort Pipeline |
Draw a tree generating 3 * 2^(n-1) strings. Dump them into a large bucket, draw a sorting machine, and pull out the k-th item. $O(2^N \cdot N \log(2^N)$). |
Math / Permutation Pruning (Binary Search style) |
Directed Path Traversal |
Total possible strings = `3 * 2^(n-1)`. If k is larger, return "". Otherwise, calculate which main branch (a, b, c) k falls into. For subsequent characters, halve the search space to pick the next valid char. |
Draw 3 large buckets (a, b, c). If k belongs in 'b', cross out 'a' and 'c'. Zoom into 'b' and split it into its 2 sub-buckets. Repeat this zooming process down to depth n. |
Single Path Tree Descent |
Draw a tree, but highlight only ONE single path going straight down from the root to the leaf. Label $O(N)$. |
Massive Array $O(2^N)$ |
Draw a single dynamically growing StringBuilder/String variable. Space is $O(N)$. |
| 1416 |
Restore The Array |
Pure Recursion. At each character, try placing a split. Convert the resulting substring to an integer. If it's valid (1 to k) and no leading zeros, recursively process the rest of the string. |
Exponential Branching Tree |
Draw a string. Below it, draw a massive tree where each node splits into up to N branches (for every possible substring length). Label $O(2^N)$. |
1D Dynamic Programming (Suffix/Prefix Array) |
Sliding Window Bounded Checks |
Work backwards. `dp[i]` = ways to restore suffix starting at `i`. Check substrings `s[i...j]`. Stop if number > k or length exceeds `len(str(k))`. Add `dp[j+1]` to `dp[i]`. |
Draw the string with a pointer moving right-to-left. From the pointer, draw a small sliding window expanding rightwards, hitting a wall when length > len(str(k)). Write sum updates above it. |
Bounded Linear Scan |
Draw an array of length N. Inside, draw a nested loop of max size `log10(k)`. Total time $O(N \cdot \log10(k)$). |
Deep Recursion Call Stack |
Draw a single 1D DP array of size N+1. Space $O(N)$. |
| 1417 |
Reformat The String |
Generate all possible permutations of the string. For each permutation, check if it alternates between letters and digits. Return the first valid one. |
Permutation Generation Graph |
Draw a root node branching into N factorial paths. Add a filter machine at the bottom that drops all invalid strings. Label $O(N!)$. |
Two-Pointer / Bucket Splitting |
Zipping Two Arrays |
Separate characters into a `letters` list and a `digits` list. If their lengths differ by more than 1, return "". Otherwise, alternate popping from the larger list, then the smaller list. |
Draw two separate buckets: "Letters" and "Digits". Draw a zipper pulling one item from the heavier bucket, then one from the lighter bucket, linking them into a single chain. |
Two-Pass Linear Traversal |
Draw one arrow splitting a string into two arrays $O(N)$ -> an arrow merging them back $O(N)$. Total $O(N)$. |
N! Permutation Strings in Memory |
Draw two dynamic arrays (List/Vector) representing the separated buckets, and one StringBuilder for the output. |
| 1418 |
Display Table of Food Orders in a Restaurant |
Multiple full scans. Find all unique tables. Find all unique foods. For every (table, food) combination, scan the entire orders list to count occurrences. |
Nested Loop Scanning Grid |
Draw a grid of Tables (rows) and Foods (cols). In every single cell, draw an arrow pointing to a full top-to-bottom scan of the original Orders list. Label $O(T \cdot F \cdot N)$. |
Hash Map of Hash Maps & Tree Sets |
2D Matrix Aggregation |
Track unique foods in a TreeSet (auto-sorts). Use a Map `>`. Iterate orders once, populating counts. Sort Table IDs, then format into a 2D string array. |
Draw a large map symbol. Inside it, draw smaller maps keyed by Table ID. Beside it, draw a sorted vertical list of unique food names. Draw arrows mapping data into a clean 2D table. |
Map Insertion & Sort Pipeline |
Draw Hashing $O(N)$ -> Sorting Foods $O(F \log F)$ -> Sorting Tables $O(T \log T)$ -> Formatting $O(T \cdot F)$. |
Cartesian Product Temp Tables |
Draw a nested Map structure and a Set structure in memory, finally converting into a 2D String Array. |
| 1419 |
Minimum Number of Frogs Croaking |
String Mutation / Subsequence Extraction. Search for "c", then "r", etc., deleting them or replacing them with spaces. Repeat until the string is empty or invalid. |
Multi-Pass String Reallocation |
Draw the string. Draw a highlighter finding "c-r-o-a-k" and erasing it. Draw a second highlighter doing it again. Label $O(N^2)$ due to repeated scans and string shifts. |
State Machine / Concurrent Counters |
Waterfall Pipeline / Watermark Tracking |
Keep 5 counters for c,r,o,a,k. Increment current char, decrement previous char (e.g., 'r' increments r, decrements c). If any counter goes negative, invalid. Max concurrent 'c's is the answer. |
Draw 5 buckets (c,r,o,a,k). Water flows sequentially from c -> r -> o -> a -> k. Track the maximum water level ever recorded in bucket 'c' before it flows out to 'k' (which acts as a drain). |
Single Pass State Machine |
Draw an array with a single pointer sliding left to right. Label $O(N)$ time. |
Multiple Large Strings in Heap |
Draw an array of 5 integers representing the state machine counters, plus a `max_frogs` integer. Space $O(1)$. |
| 1420 |
Build Array Where You Can Find The Maximum Exactly K Comparisons |
Backtracking / Brute Force Generation. Generate all possible arrays of length N where elements are 1 to M. Run the search cost algorithm on each. If cost == K, increment answer. |
Exponential Array Generation |
Draw a tree generating an array element by element. Each node has M branches. At the leaves (depth N), draw a calculator checking the cost. Label $O(M^N)$. |
3D Dynamic Programming |
State Transition Cube |
`dp[i][j][c]` = ways to build array of length `i`, max value `j`, cost `c`. If we append `x <= j`, cost stays `c` (j choices). If we append `x > j`, cost becomes `c+1` (transition to new max). |
Draw a 3D grid. The x-axis is array length (N), y-axis is max value (M), z-axis is cost (K). Draw an arrow staying on the same z-plane (x <= j), and an arrow jumping up a z-plane (x > j). |
3D Nested Loop Execution |
Draw 3 nested `for` loops. Add an inner loop for transitions (summing previous maxes). Time $O(N \cdot M^2 \cdot K)$. |
Massive Recursion Stack |
Draw a 3D Array `dp[N+1][M+1][K+1]`. Space $O(N \cdot M \cdot K)$. |
| 1421 |
NPV Queries (SQL) |
Correlated Subqueries / Unfiltered Cross Joins. For every row in the Queries table, run an independent SELECT on the NPV table to find the matching id and year, returning null if missing, then wrap in an ISNULL check. |
Nested Query Pipeline |
Draw the Queries table. From each row, draw an arrow triggering a full scan of the NPV table. Label $O(Q \cdot N)$. |
LEFT JOIN + COALESCE / IFNULL |
Hash Join & Default Fallback |
Perform a standard LEFT JOIN from Queries to NPV on id and year. Wrap the joined NPV value in `COALESCE(npv, 0)` so that unmatched queries safely resolve to 0. |
Draw two tables side-by-side. Draw straight lines connecting matching IDs. For unconnected Queries rows, draw a dotted line dropping into a "Default 0" bucket. |
Hash Match Node Graph |
Draw a Join node: Queries -> Hash Map (NPV). Label $O(Q + N)$. |
Cartesian Product Temp Tables |
Draw a small Hash Map in memory holding the NPV data. $O(N)$ space. |
| 1422 |
Maximum Score After Splitting a String |
Nested Loops. Iterate the split point `i` from 1 to N-1. For each split, run a loop over the left side to count '0's and a loop over the right side to count '1's. Sum them and track max. |
Redundant Substring Scanning |
Draw the string. Draw a vertical line cutting it. Draw arrows scanning left from scratch, and right from scratch. Move the cut line, redraw the scanning arrows. Label $O(N^2)$. |
Two-Pass / Prefix Tracking |
Sliding Partition Counter |
Pass 1: Count total '1's in the string. Pass 2: Move split point left to right. If char is '0', increment left_zeros. If char is '1', decrement right_ones. Score = left_zeros + right_ones. |
Draw the string. Write "Total 1s: X" above it. Draw a sliding vertical partition. Keep two small chalkboards next to it ("Left 0s" and "Right 1s") that increment/decrement instantly as the partition shifts one space. |
Two-Pass Array Traversal |
Draw an arrow completely across the array (Pass 1), and a second arrow (Pass 2). Label $O(N)$. |
Multiple String Allocations |
Draw two simple integer variables: `left_zeros` and `right_ones`. $O(1)$ space. |
| 1423 |
Maximum Points You Can Obtain from Cards |
Recursion Tree. At each step, branch into two decisions: take the leftmost card or take the rightmost card. Recurse K times to find the max sum. |
Binary Decision Tree |
Draw a root node branching into "Pick Left" and "Pick Right". Continue branching K times. Label $O(2^K)$. |
Sliding Window (Inverse approach) |
Fixed-Length Min Window |
Taking K cards from the edges is mathematically identical to leaving a contiguous subarray of size `N-K` in the middle. Find the minimum sum subarray of size `N-K`. Max Score = Total Sum - Min Subarray Sum. |
Draw a long array. Draw a box of length `N-K` over the array. Slide the box from left to right. Whatever sum is left OUTSIDE the box is your score. Find the box placement that minimizes the inside sum. |
Single Window Slide |
Draw an array with a fixed-size bracket sliding from left to right. Label $O(N)$ time. |
Call Stack Tower |
Draw a single `current_window_sum` integer updating as the window shifts. $O(1)$ space. |
| 1424 |
Diagonal Traverse II |
Matrix Padding & Simulation. Find the max width. Pad all rows with nulls to make a perfect rectangle. Run standard top-right to bottom-left matrix diagonal traversal, skipping nulls. |
Sparse Matrix Over-Iteration |
Draw a jagged grid of numbers. Fill all the empty jagged space with huge 'X's to make a square. Draw diagonal lines through everything, crossing out X's. Very wasteful, $O(R \\text{cdot max}_C)$. |
Hash Map Grouping by `Row + Col` |
Coordinate Sum Bucketing |
Elements on the same bottom-left to top-right diagonal share the same `row + col` sum. Iterate through the jagged array. Place `nums[r][c]` into `map[r+c]`. Flatten the map into a 1D array. |
Draw the jagged grid. Draw diagonal stripes across it, labeling them "Sum=0", "Sum=1", "Sum=2". Draw buckets below matching these sums. Drop numbers into their respective sum bucket. |
Linear Matrix Traversal |
Draw a nested loop visiting only the actual elements. Label $O(N)$ where N is total elements. |
Gigantic Padded 2D Array |
Draw an Array of dynamic Lists (or Map of Lists) to hold grouped elements. Space $O(N)$. |
| 1425 |
Constrained Subsequence Sum |
1D DP with Inner Loop. `dp[i]` = max sum ending at `i`. To calculate `dp[i]`, loop backwards `k` steps to find `max(dp[i-k] ... dp[i-1])`. Add `nums[i]`. |
Overlapping Lookback Scans |
Draw an array. For every element, draw an arrow pointing back exactly K steps. As you move right, these lookback arrows heavily overlap, representing redundant checks. $O(N \cdot K)$. |
DP + Monotonic Deque (Sliding Window Maximum) |
Decreasing Deque Tube |
Maintain a deque storing indices of the DP array in monotonically decreasing order of their DP values. To calculate `dp[i]`, simply look at `deque.front()`. Remove indices from front if they are `< i - k`. |
Draw the array. Beside it, draw a horizontal pipe (the deque). As you calculate values, drop them in the right side. If a new value is bigger than older ones in the pipe, push the older ones out the back. Only the strongest/freshest survive. |
Amortized Constant Time Operations |
Draw an array with an arrow moving right $O(N)$. Draw the Deque with a small $O(1)$ label for push/pop. Total $O(N)$. |
Full DP Array $O(N)$ |
Draw a Double-Ended Queue (Deque) containing at most K integers. Space $O(N)$ for DP + $O(K)$ for deque. |
| 1426 |
Counting Elements |
Nested Loops. For every element `x` in the array, run a second loop to search for `x + 1` in the entire array. Increment count if found. |
Quadratic Search Scan |
Draw an array. For each index, draw a long arrow that sweeps across the entire array again. Label $O(N²)$. |
Hash Set / Boolean Array |
Presence Lookup Table |
Put all elements into a Hash Set. Iterate through the array once: if `set.contains(x + 1)`, increment result. |
Draw a list of numbers. Draw a circle representing a "Knowledge Bucket" (Set). Pour all numbers into the bucket. Then point to each number in the list and ask the bucket "Do you have my+1?". |
Linear Two-Phase Scan |
Draw two parallel arrows: one for "Insert" $O(N)$, one for "Search" $O(N)$. Label total $O(N)$. |
N/A (In-place search) |
Draw a Set structure (Unique values) separate from the original array. Space $O(N)$. |
| 1427 |
Perform String Shifts |
Literal Simulation. For every shift operation, physically cut the string and re-attach it. Repeat for all elements in the `shift` array. |
Repeated String Reallocation |
Draw a string. Show it being cut and the end being moved to the front. Repeat this for every command in the shift array. Label $O(S \cdot N)$ where S is number of shifts. |
Net Shift Calculation + Slicing |
Vector Resultant Sum |
Calculate the "Net Shift" by summing all left shifts (negative) and right shifts (positive). Apply `net_shift % length` exactly once at the end using a single slice. |
Draw a dial with numbers 0 to Length-1. Draw arrows jumping forward and backward on the dial. Mark the final resting position. Perform one single string cut at that mark. |
Linear Command Processing |
Draw a list of shift commands. Draw a single summation box $O(S)$ -> one string slice $O(N)$. Label $O(S + N)$. |
Multiple String Objects |
Draw a single integer variable "TotalShift". $O(1)$ extra space (excluding result string). |
| 1428 |
Leftmost Column with at Least a One |
Exhaustive Grid Search. Scan every single cell row by row, column by column using `BinaryMatrix.get(r, c)`. Keep track of the first column index where you see a 1. |
Full Matrix Scan Graph |
Draw a grid. Draw an arrow snaking through every single cell from top-left to bottom-right. Label $O(R \cdot C)$. |
Staircase Search (Top-Right Start) |
Path of Least Resistance |
Start at the top-right corner. If current is 0, move DOWN (this row is useless). If current is 1, move LEFT (searching for a better leftmost 1). Stop when out of bounds. |
Draw the grid. Start at [0][Cols-1]. Draw a "staircase" line: left, left, down, left, down, down. The path only moves left or down, never back. |
Linear Perimeter Scan |
Draw a line tracing the top and side edge of the matrix. Label $O(R + C)$. |
Heavy API Call Stack |
Draw two variables: `curr_row` and `curr_col`. $O(1)$ space. |
| 1429 |
First Unique Number |
List Scanning. Store numbers in a list. For `showFirstUnique()`, iterate the list and check the count of each number in a frequency map until you find one with count 1. |
Linear Search on Request |
Draw a list of numbers. When "Who is first unique?" is asked, draw an arrow starting from index 0 and moving right until it hits a unique one. Label $O(N)$ per call. |
Linked Hash Map / Queue + Hash Map |
Ordered Frequency Stream |
Use a Queue for order and a Map for counts. `add(x)`: update Map and push to Queue. `showFirstUnique()`: peek queue; if `map[peek] > 1`, pop it. Stop when front is unique or empty. |
Draw a Queue and a Map. When a duplicate enters, mark it in the Map. When "First Unique" is called, pop the "garbage" (duplicates) off the front of the queue until a "clean" unique number is visible. |
Amortized Constant Time |
Draw a "Pop" operation that happens only once per element. Label $O(1)$ average. |
List and Map Growth |
Draw a Hash Map (Frequency) and a Doubly Linked List/Queue (Order). Space $O(N)$. |
| 1430 |
Check If a String Is a Valid Sequence from Root to Leaves in a Binary Tree |
All Path Generation. Find all root-to-leaf paths in the tree. Convert them to arrays/strings and compare each with the target array. |
Full Tree DFS Traversal |
Draw a tree. Draw arrows tracing every single path to every single leaf. Label $O(2^N)$ in worst case (though technically limited by nodes). |
Pruned DFS (Early Exit) |
Targeted Path Tracing |
Run DFS. If current node value != `arr[index]`, return false (Prune). If at a leaf and `index == arr.length - 1`, return true. Else, recurse left/right for `index + 1`. |
Draw the tree and the target array. Place a finger on the tree root and a finger on the array's first index. Move both. If the node doesn't match the finger on the array, stop immediately. |
Bounded Node Visit |
Draw a tree where only one path is highlighted. Label $O(N)$ where N is nodes in tree. |
List of Lists (All paths) |
Draw the recursion stack. Depth is H (height of tree). Space $O(H)$. |
| 1431 |
Kids With the Greatest Number of Candies |
Nested Loops. For each kid, add extraCandies. Then, loop through all other kids to see if anyone has more than the current kid's new total. |
Quadratic Comparison Grid |
Draw an array of kids. For Kid A, draw arrows to Kids B, C, D... checking candy counts. Repeat for Kid B. Label $O(N²)$. |
Two-Pass Greedy (Max Tracking) |
High-Water Mark Strategy |
Pass 1: Find the absolute maximum candy count in the array. Pass 2: For each kid, check if (candies[i] + extraCandies) >= max_candy. |
Draw a horizontal line representing the 'Max Candy' level. For each kid, draw a dashed line extending their candy bar by the 'extra' amount. If it touches or crosses the Max line, mark True. |
Two Linear Scans |
Draw two parallel arrows across the array. Label $O(N)$ + $O(N)$ = $O(N)$. |
N/A (In-place check) |
A single integer `max_val` and a boolean result array of size N. Space $O(1)$ auxiliary. |
| 1432 |
Max Difference You Can Get From Changing an Integer |
Try every possible digit (0-9) to replace every other digit (0-9) in the number. Generate all possible numbers, store them, and find (max - min). |
Exhaustive Permutation Search |
Draw the number. Branch into 10 options for replacing '1', 10 for '2', etc. Draw a massive list of results and a sorting machine. Label $O(100 \\text{cdot Digits})$. |
Greedy Digit Substitution |
Priority Placement (Most Significant Digit) |
To Maximize: Replace the first digit that isn't '9' with '9'. To Minimize: If first digit > 1, replace it with '1'. Else, replace the first digit (after first) that isn't '0' or '1' with '0'. |
Draw the digits as slots. For MAX, look left-to-right for the first "weak" slot (not 9) and fill it/all its twins with 9s. For MIN, look for the first slot to force toward 0 or 1. |
Constant-Time String Scan |
Draw a single arrow over the digits. Label $O(\log N)$ where N is the number (digits count). |
List of all possible transformed numbers |
Two string copies of the original number. Space $O(\log N)$. |
| 1433 |
Check If a String Can Break Another String |
Generate all permutations of both strings. For every pair of permutations, check if one "breaks" the other (all chars >=). |
Factorial Permutation Explosion |
Draw two nodes. Each explodes into N! paths. Draw a matching engine trying to find one valid pair. Label $O(N! \cdot N!)$. |
Sorting + Frequency Counting |
Sorted Alignment Check |
Sort both strings. Check if `s1[i] >= s2[i]` for all `i`. Then check if `s2[i] >= s1[i]` for all `i`. If either is true, return true. |
Draw two arrays of sorted characters, one above the other. Draw vertical lines connecting `s1[i]` to `s2[i]`. If all arrows point "up" or all arrows point "down", it's a break. |
Sorting Bottleneck |
Draw $O(N \log N)$ Sort -> $O(N)$ Scan. Total $O(N \log N)$. |
Massive Permutation Set |
Two sorted character arrays or two frequency arrays (size 26). Space $O(N)$ or $O(1)$. |
| 1434 |
Number of Ways to Wear Different Hats to Each Other |
Backtracking. For each person, try assigning every hat they like. Keep track of used hats in a set. If all people get a unique hat, increment count. |
Exponential Assignment Tree |
Draw 10 people. Branch each into their liked hats (up to 40). Prune if a hat is already taken. Label $O(H^P)$ where H=hats, P=people. |
Bitmask Dynamic Programming (Inverted) |
State Compression (Person Mask) |
Instead of "People pick hats," do "Hats pick people." `dp[hat_id][mask]` is the number of ways to assign hats up to `hat_id` to people represented by the bitmask. |
Draw a grid: Rows = Hats (1-40), Cols = Bitmask (0-1023). For Hat 1, decide which person in the mask gets it. Move to Hat 2. Use bitwise OR to update masks. |
Grid Traversal (Hats * 2^People) |
Draw a loop for 40 hats and a nested loop for 1024 states. Label $O(H \cdot 2^P)$. |
Deep Recursion Call Stack |
A 2D DP table (or two 1D rows for space optimization) of size 2^P. Space $O(2^P)$. |
| 1435 |
Create a Session Bar Chart (SQL) |
Filtered Counts. Run 5 separate SELECT statements with hardcoded WHERE clauses for each duration range and UNION them together. |
Multi-Scan Union Pipeline |
Draw the Sessions table. Draw 5 separate arrows, each scanning the table once for a specific range. Label $O(5 \cdot N)$. |
CASE WHEN + CROSS JOIN (Static Ranges) |
Categorical Bucket Aggregation |
Create a CTE with all 4 bin names. LEFT JOIN it with a subquery that groups the Sessions table into bins using `CASE WHEN`. Use `COUNT(session_id)` to ensure 0s show up. |
Draw a static "Bin Template" table. Draw the Sessions table passing through a "Categorizer" funnel. Match the categorized results to the template and fill in the counts. |
Single Scan + Join Pipeline |
Draw one scan $O(N)$ -> Grouping $O(N)$ -> Join $O(\text{Bins})$. Total $O(N)$. |
N/A (Database Level) |
Small Hash Map for grouping categories in memory. Space $O(\text{Bins})$. |
| 1436 |
Destination City |
Nested Search. For every "Destination" city in the list, check if it appears as a "Source" city anywhere else in the list. If it doesn't, that's the final destination. |
Quadratic Lookup Scan |
Draw a list of paths [A->B, B->C]. Take 'B', scan all sources (A, B). Found B. Take 'C', scan all sources. Not found. Label $O(N²)$. |
Set Difference / Hash Map |
Source City Exclusion |
Add all "Source" cities to a Hash Set. Iterate through all "Destination" cities. The city that is NOT in the set is the answer. |
Draw two buckets: "Outgoing" and "Incoming". Throw the first city of every pair into Outgoing. Then look at the second city of every pair—if it can't find itself in the Outgoing bucket, it's the end. |
Linear Two-Phase Scan |
Draw one arrow for "Set Build" $O(N)$ -> one arrow for "Set Check" $O(N)$. Total $O(N)$. |
N/A (In-place search) |
A Hash Set containing all source cities. Space $O(N)$. |
| 1437 |
Check If All 1's Are at Least Length K Places Away |
Nested Loops. For every '1' found at index `i`, run a loop from `i+1` up to `i+k` to ensure no other '1's exist in that range. |
Sliding Fixed-Range Scan |
Draw an array. At every '1', draw a bracket of size K. If another '1' falls inside the bracket, mark invalid. Label $O(N \cdot K)$. |
Single-Pass Pointer Distance |
Previous Index Tracking |
Iterate once. Keep a variable `last_pos`. When you hit a '1', check if `current_index - last_pos - 1 < k`. Update `last_pos` to `current_index`. |
Draw the array. Place a marker at the first '1'. As you move to the next '1', draw a bridge between them and count the empty slots. If bridge < K, fail. |
Single Linear Scan |
Draw a single arrow left-to-right. Label $O(N)$. |
N/A |
A single integer variable `last_pos`. Space $O(1)$. |
| 1438 |
Longest Continuous Subarray With Absolute Diff <= Limit |
All Subarrays. Generate every possible subarray (O(N²)). For each, find max and min (O(N)). Check if `max - min <= limit`. |
Cubic Subarray Inspection |
Draw an array. Draw a sliding window that grows from every starting point. Inside each window, draw arrows finding high/low values. Label $O(N³)$. |
Sliding Window + Monotonic Deques |
Dual Monotonic Queue Pipeline |
Maintain two deques: one `max_deque` (decreasing) and one `min_deque` (increasing). As you expand the window, update deques. If `max - min > limit`, shrink window from left. |
Draw a window over an array. Below it, draw two "tubes" (deques). One holds the "kings" (descending maxes), one holds the "peasants" (ascending mins). When they clash (diff > limit), push the window left. |
Amortized Linear Scan |
Draw an arrow moving right (Expand) and a trailing arrow moving right (Shrink). Total $O(N)$. |
$O(N²)$ result list |
Two Deques storing indices. Space $O(N)$. |
| 1439 |
Find the Kth Smallest Sum of a Matrix With Sorted Rows |
Generate all possible row combinations and their sums. Sort the massive list of sums and pick the Kth one. |
Exponential Sum Combinations |
Draw a matrix. Branch out every choice: Row1[0]+Row2[0]..., Row1[0]+Row2[1]... Massive tree. Label $O(M^N)$. |
Max Heap / Binary Search on Sums |
Bounded Row-by-Row Merging |
Merge rows one by one. After merging Row A and Row B, keep only the smallest K sums. Use these K sums to merge with Row C, and repeat. |
Draw Row 1. Add Row 2 to it to get all sums. Draw a "K-Filter" box that only lets the smallest K sums through. Feed those into Row 3. |
K-Bounded Merge Sort |
Draw a loop for M rows. Inside, a merge operation of size (K*N). Label $O(M \cdot K \cdot \log K)$. |
Recursive Call Stack (M^N) |
A Min-Heap or sorted list of size K. Space $O(K)$. |
| 1440 |
Evaluate Boolean Expression (SQL) |
Correlated Subqueries. For every row in Expressions, run two separate SELECTs on the Variables table to find the value of left_operand and right_operand. |
Multi-Join Scan |
Draw the Expressions table. Draw two lines from each row to the Variables table for lookups. Label $O(E \cdot V)$. |
Double JOIN + CASE Statement |
Relational Mapping & Logic Switch |
JOIN the Expressions table twice to the Variables table (once for left, once for right). Use a `CASE` statement to evaluate the `operator` string (>, <, =). |
Draw three tables. Expressions in the middle, Variables on both sides. Link them by name. Draw a logic gate (CASE) that takes the numbers and the symbol to output 'true' or 'false'. |
Hash Join Execution |
Draw Join $O(E + V)$ -> Logic Evaluation $O(E)$. Total $O(E + V)$. |
N/A (DB Engine) |
Temporary Join Hash Tables in memory. Space $O(V)$. |
| 1441 |
Build an Array With Stack Operations |
Generate every possible combination of "Push" and "Pop" sequences. Check each sequence against the target array to see which one builds it exactly. |
Backtracking Decision Tree |
Draw a root node branching into "Push" or "Push then Pop". Continue for all numbers up to N. Label $O(2^N)$. |
Simulation (Two-Pointer Logic) |
Stream Synchronization |
Iterate from 1 to N. Use a pointer `p` for the target array. If `i == target[p]`, Push and move `p`. Else, Push and immediately Pop. Stop when `p` reaches end. |
Draw a stream of numbers 1, 2, 3... and the Target list. For each number, if it matches Target, draw a "Push" arrow to a bucket. If it doesn't match, draw "Push" then a "Pop" arrow out of the bucket. |
Single Pass Iteration |
Draw an arrow from 1 to N. Label $O(N)$ or $O(\text{target}.\text{length})$ depending on exit condition. |
List of all operation strings |
A single result list of strings. Space $O(N)$ for output. |
| 1442 |
Count Triplets That Can Form Two Arrays of Equal XOR |
Triple Nested Loops. Pick `i`, `j`, and `k`. Calculate XOR sum of `arr[i...j-1]` and `arr[j...k]`. If they are equal, increment count. |
Cubic Subarray XOR Scans |
Draw an array. Draw three pointers i, j, k. Draw two boxes representing the XOR segments. Slide them through all combinations. Label $O(N⁴)$ or $O(N³)$ with prefix XOR. |
Prefix XOR + Property of XOR |
Zero-Sum Interval Matching |
If `XOR(i...k) == 0`, then any `j` between `i` and `k` works. Count is `(k - i)`. Use a Map to store prefix XOR frequencies and indices to find matches in $O(1)$. |
Draw a line of Prefix XOR values. If two points have the same Prefix XOR value, draw a bridge between them. Every integer point inside that bridge is a valid 'j'. |
One-Pass Hash Map Scan |
Draw an arrow moving left-to-right once. Label $O(N)$. |
N/A |
A Hash Map storing `XOR_value -> [list of indices]`. Space $O(N)$. |
| 1443 |
Minimum Time to Collect All Apples in a Tree |
Generate all possible paths from root to every apple. Calculate the union of all these edges and count them twice (down and up). |
Full Path Enumeration |
Draw a tree with apples on leaves. Highlight every path from root to an apple separately. Label $O(\text{Apples} \\text{cdot Depth})$. |
Post-Order DFS (Bottom-Up) |
Pruned Recursive Bubbling |
Recursively check children. A node "needs" to be visited if it has an apple OR any of its children returned "true" (contains apples). Only add +2 to time if a child branch is fruitful. |
Draw a tree. Starting at the leaves, if an apple exists, "light up" the edge to the parent. Parent lights up its own parent. Finally, count all "lit" edges and multiply by 2. |
Single DFS Traversal |
Draw a tree with a single DFS path visiting each node once. Label $O(N)$. |
Adjacency List $O(N)$ |
Recursion stack (Height of tree) + Adjacency List. Space $O(N)$. |
| 1444 |
Number of Ways of Cutting a Pizza |
Backtracking with slicing simulation. Try every possible horizontal and vertical cut. Check if the remaining piece has at least one apple. Repeat K-1 times. |
Exponential Slice Tree |
Draw a grid. Branch into all possible horizontal cuts, then all vertical cuts. Label $O((R+C)$^K). |
2D DP + 2D Prefix Sum (Suffix Sum) |
Sub-Grid State Memoization |
`dp[k][r][c]` is ways to cut a pizza starting at `(r,c)` with `k` cuts left. Use a 2D Suffix Sum to instantly check if a piece contains apples. |
Draw a pizza. Represent a cut as a state transition from a large rectangle `(r,c,R,C)` to a smaller one. Use the DP table to store the results of these smaller rectangles. |
Tabulated State Space |
Draw 3 nested loops: K, Rows, Cols, plus an inner loop for the cut position. Label $O(K \cdot R \cdot C \cdot (R+C)$). |
Recursion stack |
A 3D DP table of size K * R * C. Space $O(K \cdot R \cdot C)$. |
| 1445 |
Apples & Oranges (SQL) |
Two separate SELECTs and a JOIN. Get total apples per day in one table, total oranges per day in another, then join on the date and subtract. |
Multi-Scan Joined Result |
Draw two filtered versions of the Sales table (one for Apples, one for Oranges). Draw lines matching the dates. Label $O(N)$. |
GROUP BY + SUM(CASE WHEN) |
Pivoted Aggregation |
Group by sale_date. Use `SUM(CASE WHEN fruit='apples' THEN sold_num ELSE -sold_num END)` to calculate the net difference in a single pass. |
Draw the Sales table. Group rows by date. Inside each group, flip the sign of "Oranges". Sum the numbers. One table out. |
Single Pass Aggregation |
Draw one scan $O(N)$ -> Grouping/Sort $O(N \log N)$. Total $O(N \log N)$. |
N/A |
Small hash table for grouping categories in memory. Space $O(\text{Unique Dates})$. |
| 1446 |
Consecutive Characters |
Generate all possible substrings of the input string. For each substring, check if it consists of only one unique character. Return the length of the longest such substring. |
Quadratic Substring Scan |
Draw a string. Draw brackets for every possible start and end index. For each bracket, draw a loop checking for character equality. Label $O(N³)$. |
Single-Pass Greedy Counter |
Running Streak Tracker |
Iterate through the string. If the current character is the same as the previous one, increment a `count`. Otherwise, reset `count` to 1. Track the `max_count` seen so far. |
Draw the string. Place a pointer that moves index by index. Above it, draw a "Streak" box that ticks up as you hit same letters and resets to 1 when a new letter appears. |
Linear String Traversal |
Draw a single arrow moving left to right. Label $O(N)$. |
List of all substrings |
Two integer variables: `current_streak` and `max_streak`. Space $O(1)$. |
| 1447 |
Simplified Fractions |
Generate all possible fractions `i/j` where `1 <= i < j <= n`. Convert each fraction to a decimal (floating point) and store in a Set to ensure uniqueness. Return simplified forms. |
Floating Point Set Filter |
Draw nested loops generating i and j. Draw a "Black Box" (Set) that filters out fractions that result in the same decimal. Label $O(N²)$. |
Greatest Common Divisor (GCD) Filter |
Co-prime Mathematical Filtering |
Iterate `j` from 2 to `n` and `i` from 1 to `j-1`. A fraction `i/j` is in its simplest form if and only if `gcd(i, j) == 1`. |
Draw a grid of `i` vs `j`. In each cell, write the GCD. Circle only the cells where GCD = 1. These circled cells form your output list. |
Nested GCD Computation |
Draw nested loops. Inside, draw a Euclidean Algorithm flowchart. Label $O(N² \log N)$. |
N/A |
A list of strings to store the result. Space $O(N²)$ in terms of output size. |
| 1448 |
Count Good Nodes in Binary Tree |
Generate all paths from the root to every node. For each node, check all ancestors in its path to see if any are greater than the current node. |
Path Ancestor Validation |
Draw a tree. For a node at depth 4, draw arrows pointing to its 3 ancestors. Check each. Repeat for all nodes. Label $O(N \cdot H)$ where H is height. |
DFS with Max-So-Far Parameter |
Top-Down Threshold Propagation |
Perform a DFS. Pass a `max_val` parameter to child calls. A node is "good" if its value >= `max_val`. Update `max_val` for children: `max(max_val, current_node.val)`. |
Draw a tree. At the root, write "Max=RootVal". As you move down a branch, draw an "Envelope" being passed to the child containing the updated Max. If node >= Envelope, it's a "Good Node". |
Single DFS Traversal |
Draw a tree with a single DFS path visiting each node once. Label $O(N)$. |
List of all path nodes |
Recursion stack (height of the tree). Space $O(H)$. |
| 1449 |
Form Largest Integer With Digits That Add up to Target |
Backtracking / Exhaustive Search. Try adding every possible digit (1-9) repeatedly until the cost equals the target. Store all valid strings and sort them to find the "largest". |
Exponential String Generation |
Draw a tree where each node has 9 branches (digits 1-9). Depth is `target / min_cost`. Label $O(9^(\text{Target}/\text{MinCost})$). |
1D Dynamic Programming (Knapsack Variation) |
Value-Length Optimization |
`dp[t]` stores the maximum string (or max length) achievable with cost `t`. Since we want the largest number, prioritize longer strings, then lexicographical order. |
Draw an array of size `Target + 1`. Fill it from left to right. For each cell `i`, look back at `i - cost[digit]` and append the digit to that previous string if it makes the result "larger". |
Linear DP with Digit Scans |
Draw a loop from 1 to Target. Inside, a loop for 9 digits. Label $O(9 \\text{cdot Target})$. |
Deep Recursion Call Stack |
A 1D DP array of strings (or lengths + backtracking info). Space $O(\text{Target})$. |
| 1450 |
Number of Students Doing Homework at a Given Time |
Nested Loops. For every integer time point from 1 to max(endTime), check which students were active. If the query time matches, return the count. |
Time-Point Scanning |
Draw a timeline. For every tick on the timeline, scan the student arrays. Label $O(\text{MaxTime} \cdot N)$. |
Single-Pass Range Intersection |
Direct Interval Validation |
Iterate through the students once. For each student `i`, check if `startTime[i] <= queryTime` AND `endTime[i] >= queryTime`. |
Draw the queryTime as a vertical line. Draw each student's homework as a horizontal bar from startTime to endTime. Count how many horizontal bars the vertical line passes through. |
Single Linear Scan |
Draw a single arrow left-to-right through the input arrays. Label $O(N)$. |
N/A |
A single integer `count`. Space $O(1)$. |
| 1451 |
Rearrange Words in a Sentence |
Split string into a list. Run a standard unstable sort (like quicksort) based on length. Re-capitalize the first word and join. |
Unstable Sorting Scatter |
Draw a list of words. Draw arrows swapping words of the same length, showing they lose their original relative order. Label $O(N \log N)$. |
Stable Sort / Map of Lists |
Preservation Sorting (Stable) |
Split string. Use a stable sort algorithm (like MergeSort or built-in `stable_sort`) to sort words by length. This ensures words of the same length maintain their input order. |
Draw a set of colored blocks of varying lengths. Sort them by length, but ensure blocks of the same length keep their left-to-right sequence. Re-case the new head block. |
Stable Sorting Pipeline |
Draw $O(N)$ Split -> $O(N \log N)$ Stable Sort -> $O(N)$ Join. Total $O(N \log N)$. |
In-place swapping (risky) |
A list of word objects/strings. Space $O(N)$ for the split components. |
| 1452 |
People Whose List of Favorite Companies Is Not a Subset of Another List |
For every person `i`, compare their list with every other person `j`. Check if `list[i]` is a subset of `list[j]` by nested looping through elements. |
Quadratic Subset Intersection |
Draw N nodes. For each pair, draw an intersection diagram. Label $O(N² \cdot M)$ where M is avg list size. |
Bitmasking / Set Hashing |
ID-Based Set Containment |
Map every unique company name to an ID. Convert each person's list into a Set of IDs. For person `i`, only compare with people who have a larger list. Use `set.containsAll()`. |
Draw a Master Index of company names. For each person, draw a "Punch Card" with holes at the company IDs. Stack one card over another; if all holes are covered, it's a subset. |
Pruned Comparisons |
Draw a loop of N. Inside, a comparison of Sets. Total $O(N² \cdot M)$ but with high constant-factor improvement. |
Repeated String Re-parsing |
A List of HashSets (Integer IDs). Space $O(\text{Unique Companies} + N\cdot M)$. |
| 1453 |
Maximum Number of Darts Inside of a Circular Dartboard |
Randomly sample millions of points in the plane and count how many darts are within `radius` of each point. |
Monte Carlo Scatter Plot |
Draw a cloud of random dots over a 2D plane. Draw a circle at each dot. Label $O(\text{Samples} \cdot N)$. |
Angular Sweep / Fixed Circle Centers |
Circumference Intersection Points |
For any optimal circle, at least two points will lie on its boundary. For every pair of points, calculate the two possible centers of a circle with `radius` passing through them. Count points in these circles. |
Draw two points. Draw two overlapping circles of given radius that both hit those points. The centers are the candidates. Sweep an imaginary circle around each candidate. |
Geometry All-Pairs Processing |
Draw nested loops for point pairs $O(N²)$ -> inner count loop $O(N)$. Total $O(N³)$. |
Coordinate Arrays |
Small floating point variables for circle centers. Space $O(N)$ to store input. |
| 1454 |
Active Users (SQL) |
Self-Join on dates. Join the table with itself 4 times to check for `date + 1`, `date + 2`, etc., for every user. |
Multi-Way Cross Join |
Draw a table. Draw 5 lines from one row to 5 different other rows to find a sequence. Label $O(N^5)$. |
Window Functions (LEAD / DENSE_RANK) |
Gaps and Islands (Grouping) |
Use `DENSE_RANK()` over (User ID, Date). Subtract the rank from the date. Consecutive dates will result in the same "Difference Date" (the Island). Count these groups. |
Draw a calendar. Circle active days for a user. Assign each day a rank (1, 2, 3). Subtract: (Jan 5 - 1 = Jan 4), (Jan 6 - 2 = Jan 4). Same result = Consecutive! |
Single-Pass Ranking |
Draw a Sort/Partition $O(N \log N)$ -> Ranking $O(N)$ -> Grouping $O(N)$. Total $O(N \log N)$. |
N/A |
A temporary sorted partition in memory. Space $O(N)$. |
| 1455 |
Check If a Word Occurs As a Prefix of Any Word in a Sentence |
Standard String Search. Use `sentence.indexOf(prefix)`. If result > -1, check if the character before the match is a space. |
Substring Scanning with Post-Filter |
Draw a long sentence. Highlight all occurrences of the prefix. Check the "boundary" of each highlight. Label $O(N \cdot M)$. |
Tokenization + `startsWith` |
Word-by-Word Matching |
Split the sentence by spaces. For each word, check if it starts with the `searchWord` using `word.startsWith(prefix)`. Return the 1-based index of the first match. |
Draw a sentence broken into separate boxes (words). Place the prefix under each box. Compare character by character from the start of the box only. |
Linear Word Scan |
Draw an arrow skipping word by word. Label $O(N)$. |
Full Sentence Copy |
A list of strings after splitting. Space $O(N)$. |
| 1456 |
Max Number of Vowels in a Substring of Given Length |
Iterate through all possible substrings of length `k`. For each substring, loop through every character to count vowels. |
Fixed-Width Sliding Scan (Redundant) |
Draw an array. Draw a box of size K. For every step the box moves, draw arrows re-counting every single item inside. Label $O(N \cdot K)$. |
Sliding Window (Fixed) |
Rolling Counter Update |
Initialize a window of size `k` and count its vowels. Slide the window right: if the character leaving is a vowel, decrement `count`; if the character entering is a vowel, increment `count`. |
Draw the string. Place a window over the first K chars. Draw a "-" sign at the left edge and a "+" sign at the right edge. Move the window, updating the total count instantly. |
Single Linear Scan |
Draw a single arrow left-to-right. Label $O(N)$. |
$O(N)$ substring storage |
A single integer `max_vowels` and `current_vowels`. Space $O(1)$. |
| 1457 |
Pseudo-Palindromic Paths in a Binary Tree |
Find all root-to-leaf paths. For each path, store it as a list, sort it, and check if it can form a palindrome (at most one odd-frequency element). |
Full Path Construction & Sorting |
Draw a tree. At each leaf, draw a full array of the path. Draw a sorting machine for each array. Label $O(N \cdot H \log H)$. |
DFS + Bit Manipulation |
Parity Bitmask Toggling |
Run DFS. Use an integer as a bitmask where the `i-th` bit represents the parity of digit `i`. XOR the bitmask with `(1 << node.val)`. At a leaf, path is valid if `(mask & (mask - 1)) == 0`. |
Draw a tree. Each node has a 10-bit light switch panel. As you go down, flip the switch for that digit. At the leaf, if only 0 or 1 lights are on, it's a "pseudo-palindrome". |
Single DFS Traversal |
Draw a tree with a single DFS path. Label $O(N)$. |
Path Lists $O(N\cdot H)$ |
Recursion stack (Height) + single integer bitmask per level. Space $O(H)$. |
| 1458 |
Max Dot Product of Two Subsequences |
Generate all subsequences of `nums1` and all subsequences of `nums2`. Calculate the dot product of all pairs of equal-length subsequences. |
Double Exponential Search |
Draw two nodes. Each explodes into 2^N paths. Draw a matching engine to pair every path of length L with every other path of length L. Label $O(2^N \cdot 2^M)$. |
2D Dynamic Programming (LCS Variant) |
Choice-Matrix Accumulation |
`dp[i][j]` = max dot product using prefixes `nums1[0...i]` and `nums2[0...j]`. Options: `nums1[i]*nums2[j] + max(0, dp[i-1][j-1])`, `dp[i-1][j]`, or `dp[i][j-1]`. |
Draw a grid with `nums1` on top and `nums2` on the left. In each cell, decide: "Do I multiply these two and add previous best, or just take the best from my neighbor?". |
2D Grid Traversal |
Draw a nested loop through the DP grid. Label $O(N \cdot M)$. |
Recursive Path Storage |
A 2D DP table (or two 1D rows for space optimization). Space $O(N \cdot M)$. |
| 1459 |
Rectangles Area (SQL) |
Join Points table with itself twice. For every pair, manually calculate `abs(x1-x2) * abs(y1-y2)`. Filter out results where the area is 0. |
Self-Cross Join Grid |
Draw the Points table. Draw lines connecting every point to every other point. Label $O(N²)$. |
Self-Join with Inequality Constraints |
Coordinate Geometry Filtering |
`JOIN Points p1, Points p2 ON p1.id < p2.id`. Calculate `Area = ABS(p1.x_value - p2.x_value) * ABS(p1.y_value - p2.y_value)`. Use `WHERE p1.x_value != p2.x_value AND p1.y_value != p2.y_value`. |
Draw two identical point sets. Link Point A to Point B ONLY if A's ID is smaller. Filter out any horizontal or vertical links. The remaining links are diagonals of valid rectangles. |
Nested Loop Join Plan |
Draw a Join $O(N²)$ -> Math/Filter $O(1)$. Label $O(N²)$. |
N/A (DB Level) |
A result set containing pairs and their areas. Space $O(N²)$. |
| 1460 |
Make Two Arrays Equal by Reversing Sub-arrays |
Simulate reversals. Find the first mismatch, then search for the correct element in the rest of the array and reverse the segment to bring it forward. |
Selection Sort Simulation |
Draw an array. Find the wrong number. Draw a reversal bracket. Repeat until sorted. Label $O(N²)$. |
Frequency Counting (Hash Map) |
Multiset Equality Check |
If two arrays have the same elements with the same frequencies, they can always be made equal by reversing sub-arrays (property of bubble sort/reversals). |
Draw two grocery bags. Take an item from Bag A and put it in a "Counter" box. Take an item from Bag B and remove it from the "Counter". If the box is empty at the end, they match. |
Linear Pass or Sorting |
Draw $O(N \log N)$ Sort or $O(N)$ Hash Map count. Label $O(N)$. |
N/A (In-place reversal) |
A Hash Map (Frequency) of size 1000. Space $O(1)$ or $O(N)$. |
| 1461 |
Check If a String Contains All Binary Codes of Size K |
Generate all 2^K possible binary strings. For each one, use a string search function to see if it exists in the input string S. |
Exhaustive Search / Pattern Matching |
Draw a list of 2^K codes. For each code, draw an arrow scanning the entire string S. Label $O(2^K \cdot N)$. |
Sliding Window + Hash Set (or Rolling Hash) |
Bitmask Presence Tracking |
Slide a window of size K over S. Convert each substring to its integer value and add it to a Hash Set. Finally, check if `set.size() == 1 << K`. |
Draw the binary string. Slide a window of size K. As the window moves, draw the bits being "shifted in" and "shifted out". Drop the resulting value into a "Unique Values" bucket. |
Single-Pass Constant Lookup |
Draw one arrow left-to-right. Label $O(N)$ assuming K is small. |
Full list of 2^K strings |
A Hash Set of integers (or a boolean array) of size 2^K. Space $O(2^K)$. |
| 1462 |
Course Schedule IV |
For every query (u, v), run a separate BFS or DFS starting from u to see if v is reachable. |
Repeated Graph Traversal |
Draw a graph. For every query, draw an expanding "ripple" starting from the first course. Label $O(Q \cdot (V + E)$). |
Floyd-Warshall (Transitive Closure) |
All-Pairs Reachability Matrix |
Create a 2D boolean matrix `isPrereq[V][V]`. For every intermediate course `k`, if `i` is a prereq of `k` and `k` is a prereq of `j`, then `i` is a prereq of `j`. |
Draw a square grid. Pick a "bridge" course K. Update all cells (i, j) if there's a path through K. Show the matrix filling up with "True" values. |
Triple Nested Loop |
Draw three nested `for` loops. Label $O(V^3)$. Queries then become $O(1)$. |
Recursive Call Stack per Query |
A 2D boolean adjacency matrix of size V x V. Space $O(V^2)$. |
| 1463 |
Cherry Pickup II |
Backtracking / Recursion. Simulate all possible moves for Robot 1 and Robot 2 starting from (0, 0) and (0, C-1) down to the last row. |
Dual Exponential Branching |
Draw two starting points. Each splits into 3 choices per step. Since they move together, it's 3 x 3 = 9 branches at every level. Label $O(9^R)$. |
3D Dynamic Programming (Top-Down) |
Synchronized Multi-Agent State |
`dp[row][col1][col2]` = max cherries collected when Robot 1 is at `col1` and Robot 2 is at `col2` on the current `row`. Move both to the next row in 9 possible combined directions. |
Draw a grid. Place two markers on the same row. Draw arrows showing them jumping to the next row simultaneously. Highlight that if they land on the same cell, cherries are only counted once. |
3D State Space Traversal |
Draw a 3D cube. Label the axes Row, Col1, Col2. Label $O(R \cdot C^2)$. |
Massive Recursion Tree |
A 3D DP table of size R x C x C. Space $O(R \cdot C^2)$. |
| 1464 |
Maximum Product of Two Elements in an Array |
Nested Loops. Calculate (nums[i]-1) * (nums[j]-1) for every pair (i, j) and track the maximum value found. |
All-Pairs Product Grid |
Draw a matrix where row i and col j intersect at the product. Highlight the max cell. Label $O(N^2)$. |
Two-Pointer / Max Tracking |
"Top Two" Leaderboard |
Iterate through the array once. Keep track of the two largest numbers seen so far (`max1` and `max2`). Result is `(max1-1) * (max2-1)`. |
Draw an array. Draw two podiums: "1st Place" and "2nd Place". As you scan numbers, draw them challenging the current podium holders and potentially bumping them down. |
Single-Pass Scan |
Draw one arrow from start to end. Label $O(N)$. |
N/A |
Two integer variables. Space $O(1)$. |
| 1465 |
Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts |
Calculate the area of every single piece of cake created by the intersections of all horizontal and vertical cuts. Find the max. |
Grid Exhaustion |
Draw a rectangle with all cuts. Draw a loop that calculates the area of every little square inside the grid. Label $O(H_\text{cuts} \cdot V_\text{cuts})$. |
Greedy (Independent Max Gaps) |
Orthogonal Max-Gap Projection |
The maximum area is simply (Maximum horizontal gap) x (Maximum vertical gap). Sort the cut arrays, find the max difference between adjacent cuts, and multiply. |
Draw the cake. Highlight the largest gap between horizontal lines. Highlight the largest gap between vertical lines. The intersection of these two specific gaps is the largest piece. |
Sort-Centric Bottleneck |
Draw Sort(H) rightarrow Scan(H) rightarrow Sort(V) rightarrow Scan(V). Label $O(H \log H + V \log V)$. |
N/A |
Two sorted arrays of cuts. Space $O(H + V)$. |
| 1466 |
Reorder Routes to Make All Paths Lead to the City Zero |
Backtracking. For every city, check if there is a path to city 0. If not, try reversing one edge and check again. Repeat until all cities can reach 0. |
Exponential Reconfiguration Tree |
Draw a directed graph. For every edge, branch into "Keep" or "Reverse". Label $O(2^E)$. |
BFS / DFS with Edge Direction Tracking |
Outward Flow Detection |
Start a traversal from city 0. Treat the graph as undirected but keep track of the original directions. If you traverse an edge in its *original* direction (away from 0), you must flip it. |
Draw city 0 in the center. Draw neighbors. If an original arrow points AWAY from city 0, circle it in red (requires flip). If it points TOWARD 0, it's safe. |
Single Traversal (Undirected) |
Draw a standard BFS/DFS visiting each node and edge once. Label $O(V + E)$. |
List of all paths $O(E!)$ |
Adjacency list storing pairs: {neighbor, is_original_direction}. Space $O(V + E)$. |
| 1467 |
Probability of a Two Boxes Having The Same Number of Distinct Balls |
Generate all possible ways to distribute the balls into two boxes. Count how many ways result in equal ball counts and equal distinct color counts. |
Full Permutation Search |
Draw balls of different colors. Branch into every possible box assignment. Label $O(N!)$ where N is total balls. |
Dynamic Programming / Backtracking with Memoization |
Multi-State Combinatorial Counting |
`dfs(color_index, balls1, balls2, distinct1, distinct2)`: At each color, decide how many balls of this color go to box 1 and box 2 using combinations (nCr). |
Draw a row for each color. Use boxes for the two containers. For each color, write down the combinations formula for splitting the count. Show the "distinct color" counter ticking up. |
Memoized State Space |
Draw a state tree where nodes are (color, count1, count2, diff_distinct). Label $O(\text{Colors} \cdot N^2 \\text{cdot Colors})$. |
N/A |
A Map or 4D array for memoization. Space $O(\text{Colors} \cdot N^2)$. |
| 1468 |
Calculate Salaries (SQL) |
Correlated Subqueries. For every employee, run a SELECT to find the MAX(salary) of their company, then apply a CASE statement to determine the tax. |
Row-by-Row Max Calculation |
Draw the Salaries table. For each row, draw an arrow scanning all other rows in the same company to find the max. Label $O(N^2)$. |
Window Function (MAX OVER) |
Partitioned Maximum Scaling |
Use `MAX(salary) OVER(PARTITION BY company_id)` to get the threshold for the entire company. Use a `CASE` statement to apply 0%, 24%, or 49% tax based on that max. |
Draw the table grouped by company. Add a temporary column "CompanyMax". Calculate the tax based on "CompanyMax" and subtract from original salary. |
Single Scan Partitioning |
Draw a Database symbol -> Sort/Partition $O(N \log N)$ -> Filter/Math $O(N)$. Total $O(N \log N)$. |
N/A |
A temporary sorted partition in memory. Space $O(N)$. |
| 1469 |
Find All The Lonely Nodes |
Find all root-to-node paths. For each node, check if its parent has only one child. |
Path Ancestor Scan |
Draw a tree. For every node, look at its parent and then look at the parent's other child pointer. Label $O(N)$. |
DFS / BFS (Parental Context) |
Single-Child Branch Detection |
Traverse the tree. At each node, if it has exactly one child, add that child's value to the result list. |
Draw a tree. Use a magnifying glass to look at each node. If the node has only one leg (left or right), circle the foot of that leg (the child). |
Linear Tree Traversal |
Draw a single DFS traversal arrow visiting each node once. Label $O(N)$. |
List of all nodes |
A result list and the recursion stack. Space $O(H)$ where H is tree height. |
| 1470 |
Shuffle the Array |
Create two temporary arrays (first half and second half). Iterate through both and alternate adding elements to a new result array. |
Array Split & Merge |
Draw an array. Cut it in half. Draw two buckets. Pull from Bucket 1, then Bucket 2. Label $O(N)$. |
Single-Pass Two-Pointer (In-place if bits allow) |
Interleaved Index Mapping |
Use one pointer `i` starting at 0 and another `j` starting at `n`. Increment both by 1 while alternating their placement in the result. |
Draw the array with two pointers, `p1` at 0 and `p2` at N. Draw an output array. Draw an arrow from `p1` to index 0, then `p2` to index 1, then move both pointers. |
Single Linear Pass |
Draw a single arrow from start to mid. Label $O(N)$. |
Two temporary arrays $O(N)$ |
A result array of size 2N. Space $O(N)$ (or $O(1)$ extra if modifying original using bit manipulation). |
| 1471 |
The k Strongest Values in an Array |
Sort the array to find the median. Calculate the "strength" of every element (|arr[i] - median|). Sort the entire array again based on these custom strength values and pick the top K. |
Double Sorting Pipeline |
Draw an array. Sort it. Find the middle element. Draw a second array of the same size with subtracted values. Sort that second array. Label $O(N \log N)$. |
Sorting + Two-Pointer |
Outward Distance Convergence |
Sort to find median. Since the strongest values are those furthest from the median, they must be at the very ends of the sorted array. Use two pointers (left and right) to pick the stronger of the two until K elements are found. |
Draw a sorted array. Place pointers at the leftmost and rightmost elements. Compare their distances to the median (middle). Pick the winner, move that pointer inward, and repeat K times. |
Sorting Bottleneck + Linear Selection |
Draw $O(N \log N)$ Sort rightarrow $O(K)$ Two-Pointer selection. Total $O(N \log N)$. |
Duplicate Strength Array |
A single sorted version of the input array. Space $O(\log N)$ or $O(N)$ depending on sort implementation. |
| 1472 |
Design Browser History |
Use a List to store history. For `visit`, append the URL and delete all subsequent URLs. For `back`/`forward`, move an index pointer across the list. |
Array Reallocation / Truncation |
Draw a list of URLs. When visiting a new page from the middle, draw a giant "X" over the right side of the list and draw new boxes. Label $O(N)$ per visit. |
Two Stacks or Doubly Linked List |
Dual-Container Navigation |
Use two stacks: `history` and `future`. `visit`: clear `future`, push to `history`. `back`: pop from `history` and push to `future`. `forward`: vice versa. (Or use a fixed array with a boundary pointer for $O(1)$). |
Draw two vertical tubes. One is "Past", one is "Future". As you move back, a ball drops from Past into Future. As you visit, the Future tube is emptied into a trash can. |
Constant Time Operations |
Draw a single box for each method. Label each $O(1)$. |
Repeated List Slicing |
A single contiguous array with a current pointer and a "max-reachable" pointer. Space $O(N)$. |
| 1473 |
Paint House III |
Backtracking. For every unpainted house, try all N colors. For each configuration, calculate the number of neighborhoods and the total cost. Keep the minimum cost. |
Exponential Color Assignment |
Draw M houses. Each splits into N branches. At the bottom, draw a neighborhood counter. Label $O(N^M)$. |
3D Dynamic Programming |
State Compression (House, Neighborhood, PrevColor) |
`dp[i][j][k]` = min cost to paint up to house `i` with `j` neighborhoods and the i-th house painted color `k`. Transition by checking if current color matches previous to increment neighborhood count. |
Draw a 3D grid. X-axis: Houses, Y-axis: Target Neighborhoods, Z-axis: Colors. For each cell, look at the previous house's Z-plane and pick the cheapest compatible color. |
Triple Nested Loop with Color Scans |
Draw three nested loops (M, Target, N) plus an inner loop for prev color. Label $O(M \\text{cdot Target} \cdot N^2)$. |
Massive Recursion Tree |
A 3D DP table of size M x Target x N. Space $O(M \\text{cdot Target} \cdot N)$. |
| 1474 |
Delete N Nodes After M Nodes of a Linked List |
Convert the linked list to an array. Create a new linked list by picking M elements, skipping N, and repeating until the end. |
List-to-Array Transformation |
Draw a chain of nodes. Draw an array. Copy nodes into array. Draw a second array with skips. Build a new chain. Label $O(N)$. |
In-Place Link Manipulation |
Jump-and-Stitch Traversal |
Traverse M nodes using a pointer `curr`. From `curr`, find the next node after skipping N steps. Set `curr.next` to that node. Repeat until the end of the list. |
Draw a linked list. Draw a solid line over M nodes, then a dashed "jumping" line over the next N nodes. Show the "stitch" where the last solid node points to the end of the dashed jump. |
Single-Pass Linear Traversal |
Draw a single arrow jumping across the list. Label $O(N)$ where N is total nodes. |
New Linked List Copy |
No extra space except for temporary pointers. Space $O(1)$. |
| 1475 |
Final Prices With a Special Discount in a Shop |
Nested Loops. For every item at index i, scan all items to its right (j > i) until you find the first one where prices[j] <= prices[i]. Apply the discount. |
Quadratic Right-Scan |
Draw an array. For each element, draw a search arrow that moves right until it finds a smaller/equal value. Label $O(N^2)$. |
Monotonic Stack (Increasing) |
Next Smaller Element Pattern |
Iterate through prices. Maintain a stack of indices whose prices are in increasing order. When you see a price smaller than the stack top, the stack top has found its discount. Pop and update. |
Draw the array. Below it, draw a "Waiting Room" (Stack). If a new shopper is "cheaper" than the person in the waiting room, the person in the room gets their discount and leaves. |
Linear Pass with Stack Pops |
Draw an arrow moving once across the array. Each element enters and leaves the stack exactly once. Label $O(N)$. |
N/A (Modify in place) |
A stack storing at most N indices. Space $O(N)$. |
| 1476 |
Subrectangle Queries |
Literal Matrix Update. For every `updateSubrectangle` call, use a nested loop to iterate through every cell in the defined range and update its value in the original 2D array. |
2D Grid Re-writing |
Draw a grid. Draw a rectangle inside it. Draw arrows filling every single box in that rectangle with a new number. Label $O(R \cdot C)$ per update. |
Update-History Log (Inverse Search) |
Reverse-Chronological Log Scan |
Store updates in a list of `[r1, c1, r2, c2, newValue]`. For `getValue(r, c)`, scan the list from the end (most recent). If the coordinate falls within an update range, return that value. |
Draw a timeline of update stickers. Instead of applying stickers to the board, just look at the stack of stickers. Pick the one on top that covers your target (r, c). |
Linear History Scan |
Draw a vertical list of update commands. Draw an arrow starting from the bottom moving up. Label $O(\text{updates})$ per query, $O(1)$ per update. |
Full Matrix Copy |
A dynamic list (vector) of 5-element arrays. Space $O(\text{updates})$. |
| 1477 |
Find Two Non-overlapping Sub-arrays Each with Target Sum |
Generate all subarrays that sum to target. Check every possible pair of these subarrays to see if they overlap. If not, calculate their combined length and track the minimum. |
All-Pairs Subarray Conflict Check |
Draw an array. Highlight all segments that sum to target. For every segment, compare it to all others. Label $O(N²)$ segments, $O(S²)$ comparisons. |
Sliding Window + 1D DP (Prefix Min) |
Left-to-Right Min-Length Propagation |
Use a sliding window/Hash Map to find subarrays summing to target. `leftMin[i]` stores the shortest subarray ending at or before `i`. For a new subarray `[i, j]`, the result is `length(i, j) + leftMin[i-1]`. |
Draw an array. Slide a window. As you find a match, record its length in a "Best-So-Far" array. Then, as you find the *next* match, look at the Best-So-Far array to its left to see the shortest partner. |
Two-Pass Linear Scanning |
Draw two parallel arrows. One finds matches $O(N)$, one updates prefix minimums $O(N)$. Total $O(N)$. |
Large List of Subarrays |
Two 1D arrays: one for Prefix Min Lengths and one for Suffix Min Lengths. Space $O(N)$. |
| 1478 |
Allocate Mailboxes |
Backtracking / Exhaustive Search. Try placing K mailboxes in every possible combination of integer coordinates between houses. For each, calculate total distance. |
Combinatorial Coordinate Search |
Draw a number line. Try placing 3 dots (mailboxes) in every possible set of gaps between houses. Label $O(N \text{choose} K)$. |
DP + Median Distance Pre-computation |
Clustered Median Minimization |
Cost of 1 mailbox for houses `[i...j]` is minimized at their median. Pre-compute a 2D `cost[i][j]`. Then use DP: `dp[k][i]` is min cost for `i` houses with `k` mailboxes. |
Draw houses as dots on a line. Group them into K circles. Inside each circle, the mailbox is at the middle dot. DP decides where the circle boundaries go to minimize total distance. |
Nested Interval Partitioning |
Draw 3 nested loops: K (mailboxes), N (houses), and a split point. Label $O(K \cdot N²)$. |
Deep Recursion Tree |
A 2D `cost` matrix $O(N²)$ and a 2D `dp` table $O(K \cdot N)$. Space $O(N²)$. |
| 1479 |
Sales by Day of the Week (SQL) |
Multiple Joins and Filters. Run 7 separate queries (one for each day) and UNION them together, or JOIN the Items table with 7 filtered versions of the Orders table. |
Multi-Scan Union Pipeline |
Draw an Items table. Draw 7 arrows pointing to the Orders table, each filtering for a specific `DAYOFWEEK`. Label $O(7 \cdot N)$. |
CASE WHEN + SUM (Pivoting) |
Categorical Pivot Table |
Select `item_category`. Use `SUM(CASE WHEN day='Monday' THEN quantity ELSE 0 END)` for each day of the week. Left Join Items with Orders to ensure categories with no sales show 0. |
Draw a table with 8 columns (Category + 7 Days). As you scan the orders, drop the quantity into the specific day-column that matches the date. |
Single-Scan Aggregation |
Draw one scan $O(N)$ -> Grouping $O(\text{Categories})$. Total $O(N)$. |
N/A |
Temporary Hash Table for grouping category names. Space $O(\text{Categories})$. |
| 1480 |
Running Sum of 1d Array |
Nested Loops. For every index i, run a second loop from 0 to i to sum up all elements and store in the result array. |
Redundant Summation Scan |
Draw an array. For index 3, draw arrows to indices 0, 1, 2, 3. For index 4, redraw all those arrows plus one more. Label $O(N²)$. |
Prefix Sum (In-place) |
Cumulative Accumulator |
Iterate from index 1 to N-1. Add the value of the previous element to the current element: `nums[i] = nums[i] + nums[i-1]`. |
Draw a row of numbers. As you move right, draw an arrow pulling the "Total-So-Far" from the left and merging it into the current box. |
Single-Pass Linear Scan |
Draw one arrow moving left-to-right once. Label $O(N)$. |
Result Array $O(N)$ |
No extra space if modifying the input array in place. Space $O(1)$ auxiliary. |
| 1481 |
Least Number of Unique Integers after K Removals |
Generate all subsets of the array of size `N-K`. For each subset, count unique elements. Return the minimum count found. |
Exponential Subset Selection |
Draw a tree branching into every way to pick N-K elements. Count unique items at each leaf. Label $O(N \text{choose} K)$. |
Greedy Frequency Sorting |
Elimination of Smallest Buckets |
Count frequencies of all numbers. Sort the frequencies in ascending order. Remove frequencies one by one using `K` until `K` is exhausted. Remaining unique counts is the answer. |
Draw buckets for each unique number. Sort them from shortest to tallest. Start "deleting" buckets from the left (shortest) using your total K budget until you can't afford the next one. |
Sorting Frequency Bottleneck |
Draw $O(N)$ Frequency Map -> $O(U \log U)$ Sort (where U is unique count) -> $O(U)$ Scan. Total $O(N \log N)$. |
All possible subsets list |
A Hash Map for counts and a sorted list of frequencies. Space $O(N)$. |
| 1482 |
Minimum Number of Days to Make m Bouquets |
Simulation. For every day D from 1 to `max(bloomDay)`, check the entire array to see which flowers have bloomed. See if you can form M bouquets of size K. |
Linear Day-by-Day Search |
Draw a calendar. For every single day, redraw the flower array and check for contiguous segments of size K. Label $O(\text{maxDay} \cdot N)$. |
Binary Search on Answer Range |
Feasibility Threshold Testing |
Binary search for the day D between `min(bloomDay)` and `max(bloomDay)`. For a given D, use a greedy linear scan to count how many K-sized bouquets can be formed. |
Draw a slider labeled "Days". Pick the middle day. Check the array: "Can I make M bouquets?". If Yes, move slider Left; if No, move slider Right. Repeat. |
Logarithmic Range Search |
Draw a binary tree search path of depth log(maxDay). At each node, a linear scan $O(N)$. Total $O(N \log(\text{maxDay})$). |
Full simulation state storage |
N/A. Just a few integer variables (low, high, mid, current_count). Space $O(1)$. |
| 1483 |
Kth Ancestor of a Tree Node |
For every `getKthAncestor(node, k)` call, jump to the parent `k` times using a simple `parent[node]` pointer. |
Linear Jump Traversal |
Draw a tree. For a query (node, k=5), draw 5 arrows jumping up node-by-node. Label $O(K)$ per query. |
Binary Lifting (Sparse Table) |
Power-of-Two Precomputed Leaps |
Precompute `up[node][i]`, which is the 2^i-th ancestor of `node`. To find the K-th ancestor, decompose K into powers of 2 (binary representation) and jump accordingly. |
Draw a tree. Give each node a "Jetpack" with buttons: "Jump 1", "Jump 2", "Jump 4", "Jump 8". To jump 13, press 8, then 4, then 1. Total 3 jumps instead of 13. |
Logarithmic Jump Traversal |
Draw binary representation of K. Label $O(\log N)$ per query, $O(N \log N)$ preprocessing. |
Standard Parent Array $O(N)$ |
A 2D array `up[N][log N]`. Space $O(N \log N)$. |
| 1484 |
Group Sold Products By The Date (SQL) |
Multiple Selects and Joins. For every unique date, run a subquery to find all distinct products and another to count them, then concatenate them manually. |
Correlated Subquery Aggregation |
Draw the Activities table. For each date, draw an arrow to a filtered list of unique products. Label $O(\text{Dates} \cdot N)$. |
GROUP BY + GROUP_CONCAT / STRING_AGG |
Pivoted String Accumulation |
Group the table by `sell_date`. Use `COUNT(DISTINCT product)` for the count and `GROUP_CONCAT(DISTINCT product ORDER BY product)` for the comma-separated list. |
Draw a funnel. Dump rows into buckets by date. Inside the bucket, remove duplicate names, sort them alphabetically, and join them with a comma. |
Sort-Centric Aggregation |
Draw a Sort $O(N \log N)$ -> Single Pass Grouping $O(N)$. Total $O(N \log N)$. |
N/A |
A temporary buffer/map to handle string concatenation per group. Space $O(N)$. |
| 1485 |
Clone Binary Tree With Random Pointer |
Two-Pass Recursion. Pass 1: Clone the tree structure (left/right) and store the mapping of `OldNode -> NewNode` in a Hash Map. Pass 2: Iterate through both trees and set the `random` pointers using the map. |
Structure-First Mirroring |
Draw the original tree. Draw a second blank tree. Copy nodes one by one. Then draw a mapping table. Finally, draw the random arrows on the second tree. Label $O(N)$. |
DFS / BFS with Node Mapping (Memoization) |
Identity-Preserving Deep Copy |
Use a Hash Map to store `OldNode -> NewNode`. Run a single DFS. For each node, if it's already in the map, return it. Else, create it, add to map, and recursively clone left, right, and random. |
Draw the tree. When you visit a node, "stamp" a copy and record it in a ledger. If you see a random pointer to a node you've already stamped, just check the ledger and point to that copy. |
Single Linear Traversal |
Draw a DFS arrow visiting each node exactly once. Label $O(N)$. |
Deep Recursion + Mapping Table |
A Hash Map storing N entries and the recursion stack. Space $O(N)$. |
| 1486 |
XOR Operation in an Array |
Literal Array Construction. Create an array of size n, fill each index i with `start + 2*i`, then iterate through the array to XOR all elements. |
Linear Iteration Scan |
Draw an array of n slots. Write numbers in each. Draw an XOR accumulator box and move through the array. Label $O(n)$. |
Direct Accumulation (Math optional) |
Running Bitwise Accumulator |
Initialize `res = 0`. Loop from 0 to n-1, calculating `start + 2*i` on the fly and XORing it into `res`. (Note: $O(1)$ math pattern exists based on 4k XOR cycle). |
Draw a single variable "Result". Draw a loop that calculates a value and immediately merges it into "Result" using an XOR gate. No array needed. |
Single-Pass Loop |
Draw an arrow moving from 0 to n. Label $O(n)$ time. |
Full Array Storage $O(n)$ |
Single integer variable. Space $O(1)$. |
| 1487 |
Making File Names Unique |
Nested Search. For every new name, check if it exists in a list. If it does, try appending (1), (2), (3)... and re-scan the entire list for each attempt. |
Quadratic Collision Search |
Draw a list of names. For a new "doc", check list. Found. Try "doc(1)", check list. Found. Try "doc(2)". Label $O(n^2)$. |
Hash Map with Suffix Tracking |
Historical Collision Memory |
Use a Hash Map to store `name -> next_available_suffix`. When a name is seen, check the map. If it exists, start searching from the stored suffix number until a unique name is found. Update map for both old and new names. |
Draw a Map. Key: "file", Value: 3. When a new "file" comes in, instantly jump to checking "file(3)". No need to check (1) or (2) again. |
Amortized Linear Insertion |
Draw an arrow through the names. Each name lookup/insertion is $O(L)$ where L is string length. Label $O(n \cdot L)$. |
List of all generated names |
A Hash Map storing all used names and their next suffix counter. Space $O(n \cdot L)$. |
| 1488 |
Avoid Flood in The City |
Backtracking. For every dry day (0), try drying every possible full lake. If a flood occurs later, go back and change which lake was dried. |
Decision Tree Explosion |
Draw a tree where each '0' day is a branch for every lake. Label $O(L^\text{dry}_\text{days})$. |
Greedy + Greedy with Binary Search (TreeSet) |
Just-In-Time Disaster Prevention |
Store indices of dry days in a sorted set. Use a map to track `lake -> last_rained_day`. If it rains on a full lake, find the first dry day available *after* the last rain on that lake using `set.higher()`. |
Draw a timeline. Mark "Rain" days and "Sun" days. When a lake rains twice, look at the "Sun" days between the two rains. Pick the earliest one to "use up" and dry that lake. |
Logarithmic Set Lookups |
Draw an arrow through the days $O(n)$. Inside, a binary search in the dry-day set $O(\log n)$. Label $O(n \log n)$. |
Full path history stack |
A Hash Map (lake history) and a TreeSet (available dry days). Space $O(n)$. |
| 1489 |
Find Critical and Pseudo-Critical Edges in MST |
Generate all possible Minimum Spanning Trees (MSTs) and see which edges appear in all of them (critical) or only some of them (pseudo-critical). |
Combinatorial Tree Search |
Draw a graph. List every single spanning tree. Compare all edge sets. Label $O(2^E \cdot V)$. |
Kruskal’s + Edge Exclusion/Inclusion |
Weight-Consistent Connectivity Test |
1. Find MST weight W. 2. For each edge: exclude it and find MST; if weight > W or disconnected, it's **Critical**. 3. If not critical, force-include it and find MST; if weight == W, it's **Pseudo-Critical**. |
Draw the graph. Run Kruskal's. Now, "delete" one edge and re-run. If the bridge collapses (weight goes up), that edge was Critical. If you can force it in without breaking the bank, it's Pseudo. |
Multi-Pass MST Execution |
Draw a loop over E edges. Inside, run Kruskal's $O(E \log E)$. Label $O(E^2 \log E)$. |
Recursive tree lists |
Union-Find structure and sorted edge list. Space $O(V + E)$. |
| 1490 |
Clone N-ary Tree |
Manual Copy. Traverse the tree. For each node, manually create a new node and append all its children by looking them up. |
Structure-First Mirroring |
Draw the original tree. Create a new root. For each child in the old root, create a new child in the new root. Label $O(n)$. |
DFS Recursion (Post-Order) |
Recursive Component Assembly |
Create a `new_node` using `old_node.val`. For every `child` in `old_node.children`, recursively call `clone(child)` and add the result to `new_node.children`. |
Draw a node. It "shouts" to its children to clone themselves. The children send back their clones, and the parent "glues" them into its own list of children. |
Single Pass Traversal |
Draw a DFS arrow visiting every node once. Label $O(n)$. |
N/A |
Recursion stack (height of tree). Space $O(h)$. |
| 1491 |
Average Salary Excluding the Minimum and Maximum Salary |
Sort the array. Iterate from index 1 to n-2, summing the values. Divide the sum by n-2. |
Sorting Bottleneck Scan |
Draw an array. Sort it. Cross out the first and last boxes. Draw an arrow through the middle boxes into a sum box. Label $O(n \log n)$. |
One-Pass Min-Max Tracking |
Extreme Value Filtering |
Iterate once. Keep track of the `total_sum`, `min_val`, and `max_val`. Result is `(total_sum - min_val - max_val) / (n - 2)`. |
Draw an array. As you scan, update three small chalkboards: "Running Total", "Current Min", "Current Max". At the end, perform one subtraction and division. |
Single-Pass Linear Scan |
Draw one arrow from start to end. Label $O(n)$. |
N/A |
Three integer/float variables. Space $O(1)$. |
| 1492 |
The kth Factor of n |
Loop from 1 to n. Check if n % i == 0. Store all factors in a list and return the k-th element. |
Linear Exhaustive Scan |
Draw a line from 1 to N. Check every single number. If it's a factor, drop it into a bucket. Pull the k-th item from the bucket. Label $O(n)$. |
Square Root Factor Pairing |
Symmetric Divisor Property |
Loop from 1 to √n. If i is a factor, it's the "small" factor. The "large" factor is n/i. Count the small ones; if you exceed k, the answer is i. Otherwise, calculate the k-th from the large ones. |
Draw a line at √n. For every factor found on the left, draw a "buddy" factor on the right side. Count up the left side, then count down the right side. |
Sub-linear Search |
Draw an arrow that stops at √n. Label $O(√n)$. |
Full list of factors $O(n)$ |
A small list to store factors for the second-half calculation. Space $O(√n)$. |
| 1493 |
Longest Subarray of 1's After Deleting One Element |
Generate all possible subarrays after deleting exactly one element at each possible index i. Find the longest one consisting only of 1s. |
Quadratic Subarray Generation |
Draw an array. "Hide" index 0, find longest 1s. "Hide" index 1, find longest 1s. Repeat. Label $O(n^2)$. |
Sliding Window (Flexible) |
Zero-Budget Constraint Window |
Maintain a window with at most one '0'. If the number of '0's exceeds 1, shrink the window from the left. The answer is `max(right - left)`. (Subtract 1 because one element must be deleted). |
Draw a sliding box. If a 0 enters the box, it's okay. If a second 0 enters, slide the left side until the first 0 is pushed out. The window "breathes" as it encounters 0s. |
Two-Pointer Linear Scan |
Draw an arrow for 'Right' and a trailing arrow for 'Left'. Label $O(n)$. |
All subarray strings |
A few integer pointers. Space $O(1)$. |
| 1494 |
Parallel Courses II |
Greedy: Always take the K courses with the most dependents. (Note: This is a known hard problem where Greedy fails; it requires checking all subsets). |
Greedy Heuristic Failure |
Draw a dependency graph. Pick the "most important" nodes first. Show a counter-example where this leads to more semesters. |
Dynamic Programming with Bitmasking |
State Compression (Course Completion Mask) |
`dp[mask]` = min semesters to complete courses in mask. For each state, identify all "available" courses (prereqs met). Try all combinations of taking K or fewer available courses. |
Draw a bitmask of 1010... representing finished courses. Identify nodes with no incoming edges from 0s. Branch into all ways to pick K of those nodes to turn them into 1s. |
Exponential Mask Transition |
Draw a transition from one bitmask to another. Label $O(3^n)$ or $O(2^n \cdot n^k)$. |
N/A |
A DP array of size 2^n. Space $O(2^n)$. |
| 1495 |
Friendly Movies Streamed Last Month (SQL) |
Multiple Joins with String Filtering. Join TVProgram, Content, and filter by `program_date` (June 2020) and `Kids_Friendly = 'Y'` and `content_type = 'Movies'`. |
Multi-Join Row-by-Row Scan |
Draw three tables. Draw lines connecting Program to Content. Filter by Date. Filter by "Kids". Filter by "Movies". Label $O(n)$. |
JOIN + Distinct Filtering |
Relational Intersection |
`JOIN TVProgram p ON c.content_id = p.content_id`. Use `WHERE` clause for the date range (June 2020) and flags. Use `DISTINCT` to avoid duplicate movie titles. |
Draw two tables side-by-side. Connect matching IDs. Shade only the rows that satisfy the June date, Movie type, and Kids-Friendly flag. Extract the Titles. |
Index-Optimized Join |
Draw a Join $O(n)$ -> Filter $O(n)$ -> Distinct $O(n \log n)$. Total $O(n \log n)$. |
N/A |
Temporary hash table for distinct values. Space $O(n)$. |
| 1496 |
Path Crossing |
Iterate through the string. For every step, store the full coordinate history in a List. For each new step, iterate through the entire list to see if the current (x,y) has appeared before. |
Quadratic History Scan |
Draw a 2D grid. Trace a path. At every point, draw arrows pointing back to every single previous dot on the path to check for a match. Label $O(N^2)$. |
Hash Set of Visited Points |
Coordinate Fingerprinting |
Use a Hash Set to store strings of coordinates like `"x,y"`. For each move (N, S, E, W), update current (x, y), check if it exists in the set. If it does, return true; else, add it. |
Draw a "Memory Bucket" (Set). As you walk on the grid, drop your coordinate into the bucket. If you try to drop a coordinate that's already in the bucket, a buzzer sounds (Path Crossed). |
Single Pass Constant Lookup |
Draw one arrow through the input string. Label $O(N)$. |
List of coordinates $O(N^2)$ |
A Hash Set of point strings. Space $O(N)$. |
| 1497 |
Check If Array Pairs Are Divisible by k |
Backtracking. Try all possible pairings of the numbers in the array. For each pairing, check if the sum of every pair is divisible by k. |
Exponential Pairing Tree |
Draw N numbers. Branch into every possible way to pair them up. Check validity at the leaves. Label $O(N!!)$ (Double Factorial). |
Remainder Frequency Counting |
Complementary Remainder Matching |
Calculate `(num % k + k) % k` for all numbers. Store frequencies in a map. A remainder `r` must be paired with `k - r`. If `count[r] == count[k-r]` (and special rules for `r=0` or `r=k/2`), return true. |
Draw k buckets labeled 0 to k-1. Toss numbers into buckets based on their remainder. Check if bucket r and bucket k-r have the same number of items. They "cancel" each other out. |
Linear Remainder Pass |
Draw one arrow across the array $O(N)$ -> then a loop through k buckets $O(k)$. Total $O(N + k)$. |
Full recursion stack |
An array of size k for frequencies. Space $O(k)$. |
| 1498 |
Number of Subsequences That Satisfy the Given Sum Condition |
Generate all 2^N subsequences. For each, find the min and max. If `min + max <= target`, increment the answer. |
Exponential Power Set Scan |
Draw a tree branching into every possible subsequence. At each leaf, find Min/Max. Label $O(2^N \cdot N)$. |
Sorting + Two Pointers |
Binary Subsequence Counting |
Sort the array. Use two pointers L and R. If `arr[L] + arr[R] <= target`, then all subsequences starting with `arr[L]` and ending with any element up to `arr[R]` are valid. Add 2^(R-L) to result. |
Draw a sorted array. Place pointers at ends. If sum is okay, you can keep the left element and pick any combination of the (R-L) elements in between. Use a precomputed "Powers of 2" array. |
Sorting Bottleneck |
Draw $O(N \log N)$ Sort -> $O(N)$ Two-pointer scan. Total $O(N \log N)$. |
List of all subsequences |
Sorted array and Powers of 2 array. Space $O(N)$. |
| 1499 |
MaxValue of Equation |
Nested Loops. For every pair (i, j) where j > i and |x_i - x_j| <= k, calculate y_i + y_j + |x_i - x_j| and track the maximum. |
Quadratic Window Search |
Draw a set of points. For point i, draw a window of width k. Scan all points inside and compute the formula. Label $O(N^2)$. |
Monotonic Deque (Sliding Window Max) |
Variable Decomposition Optimization |
Maximize (y_j + x_j) + (y_i - x_i). As you iterate j, you need the max (y_i - x_i) for previous points within x-distance k. Use a deque to store indices i in decreasing order of (y_i - x_i). |
Draw a sliding window. Inside, keep a "Leaderboard" (Deque). When a new point arrives, it calculates its (y-x) and replaces anyone on the board who is "weaker" and "older". |
Amortized Linear Scan |
Draw an arrow moving right. Each element enters and leaves the deque once. Label $O(N)$. |
N/A |
A Deque of point indices. Space $O(N)$. |
| 1500 |
Design a File Sharing System |
Use a Map to track `userID -> Set of chunks`. For `request`, search every user's set for the required chunk. For `join`, find the first available integer for userID by scanning from 1 up to infinity. |
Linear User ID Search |
Draw a list of active Users. When a new user joins, scan from ID 1, 2, 3... until you find a gap. When a chunk is requested, scan everyone. Label $O(N)$ per operation. |
Min-Heap + Map of Sets |
Efficient Resource Reclaiming |
Use a Min-Heap (or TreeSet) to store recycled User IDs. If heap is empty, next ID is `max_id++`. Use a `HashMap>` for user data. Use an inverted `HashMap>` for chunk locations to speed up requests. |
Draw a "ID Recycle Bin" (Heap). If someone leaves, their ID goes in. If someone joins, pull from the bin first. Draw a "Chunk Directory" (Map) that points directly to owners of a chunk. |
Logarithmic Management |
Draw Heap pop/push $O(\log N)$ -> Map/Set operations $O(\log C)$. Label $O(\log N + \log C)$. |
Repeated Linear Scans |
A Min-Heap for IDs and two HashMaps for tracking. Space $O(N \cdot C)$ where C is chunks. |
| 1501 |
Countries You Can Safely Invest In (SQL) |
Calculate global avg. Then for each country, scan calls table to find specific avg. $O(N \\text{cdot Calls})$. |
Repetitive Aggregation Loops |
Draw a globe. For each country, draw a calculator rescanning the entire Calls table. |
JOIN + GROUP BY + HAVING |
The Global Filter Funnel |
Join all tables once. Group by country. Calculate avg per group and use HAVING to compare to the global mean. |
Draw data pouring into Country Buckets. Calculate bucket avg. Draw a horizontal "Global Avg Line"; keep buckets above it. |
Linear Aggregation $O(\text{Calls})$ |
Draw a single pipeline flow processing all calls in one pass. |
App-side memory for multiple lists. |
Database internal aggregation buffer. $O(\text{Countries})$ space. |
| 1502 |
Can Make Arithmetic Progression From Sequence |
Sort the array, then iterate to check if the difference between adjacent elements is constant. |
Sorting Tree Visualization (O(N log N)) |
Draw a wide triangle narrowing down to a single line representing the merge/quicksort depth, followed by a straight linear line (N) for the difference check. |
Math / Hash Set (Min/Max finding) |
Number Line Boundary Check |
Find global min/max. Calculate expected step `(max-min)/(n-1)`. Jump along the number line by `step`, checking if each expected value exists in a Set. |
Draw a straight horizontal line (number line). Mark the min and max dots. Draw evenly spaced arcs between them representing the calculated 'step'. Tick off nodes as you find them. |
Linear Scan Visualization $O(N)$ |
Draw three parallel horizontal lines of length N representing the 3 passes: 1 to find min/max, 1 to populate Set, 1 to verify expected steps. |
Array blocks shifting/rearranging in place. |
A Hash Set bucket grid. Draw items being dropped into distinct buckets in $O(1)$ space (if tracking seen) or purely variables (O(1)). |
| 1503 |
Last Moment Before All Ants Fall Out of a Plank |
Simulate every single step (t=1, t=2...) for every ant. When ants collide, swap their directions. |
2D Grid Simulation (Time x Space) |
Draw a matrix where rows are time (t) and columns are positions. Draw arrows moving. Highly dense, showing $O(T \cdot N)$ explosion. |
Brainteaser / Array Math (Ghost Ants) |
Pass-Through Illusion Viz |
Realize that two ants bouncing off each other is mathematically identical to two ants passing *through* each other. Ignore collisions completely. |
Draw the plank as a straight line. Draw a left-facing arrow from the rightmost 'left' ant to index 0. Draw a right-facing arrow from the leftmost 'right' ant to index n. The answer is simply the longest arrow. |
Max Search $O(N)$ |
Draw a single straight line. Highlight finding the max value in the `left` array and max value of `n - val` in the `right` array. |
Multiple array snapshots for every time step `t`. |
Two single variable boxes: `max_left` and `max_right`. Erase and rewrite the number inside as you iterate linearly. $O(1)$ space. |
| 1504 |
Count Submatrices With All Ones |
4 nested loops to select top-left and bottom-right corners, then 2 nested loops to check if all cells inside are '1'. $O(N^6)$. |
6-Dimensional Loop Hierarchy |
Draw 6 nested concentric squares. The innermost square represents the area check, highlighting the massive redundant work done for overlapping submatrices. |
Monotonic Stack / Histogram |
Dynamic Histogram Shrinking |
Treat each row as a base. Build a histogram of contiguous 1s going upwards. Use a monotonic stack to calculate combinations of rectangles formed by the current histogram bars. |
Draw a 2D grid. For row `i`, draw vertical bars going up representing the number of 1s above it. Then sweep left-to-right, drawing expanding horizontal rectangles clamped by the shortest vertical bar. |
2D Sweep Line $O(R \cdot C)$ |
Draw a 2D matrix. Draw a single arrow sweeping down row by row, and another sweeping left to right. Mark a constant amount of work per cell. |
No extra memory, but massive redundant pointer variables. |
A 1D array representing the 'height' of the histogram for the current row, and a Stack box beside it pushing/popping indices. $O(C)$ space. |
| 1505 |
Minimum Possible Integer After at Most K Adjacent Swaps |
Recursively try all combinations of adjacent swaps up to K depth, tracking the lexicographically smallest string. |
K-ary Expansion Tree $O(N^K)$ |
Draw a giant, rapidly expanding tree. The root is the starting string, branching out N times for each possible swap, extending K levels deep. |
Greedy + Fenwick Tree / Segment Tree |
Dynamic Sliding Window |
Scan for the smallest digit (0-9) within a window of size K. Bring it to the front. Use a Fenwick tree to track how indices shift dynamically so you don't actually modify the array $O(N)$ times. |
Write the string. Draw a bracket of size K. Find the min digit inside. Draw a curved arrow pulling it to the front. Mark a '+1 shift' counter on the elements it jumped over. |
Logarithmic Updates $O(N \log N)$ |
Draw a straight line of length N. Above each node, draw a tiny binary tree of height logN representing the cost to query/update the shift offset. |
Huge recursive call stack boxes stacking infinitely. $O(K)$ deep. |
A 1D array representing the Fenwick Tree. Draw it as an array where certain indices hold sum brackets covering multiple preceding elements. $O(N)$. |
| 1506 |
Find Root of N-Ary Tree |
Store all children in a Hash Set. Iterate through all nodes; the node not in the children set is the root. |
Two Buckets (Difference) $O(N)$ |
Draw a large circle containing all Node IDs. Cross out any ID that appears as a child. The final uncrossed ID is the root. |
Math (Summation / XOR) |
The Balancing Scale |
Keep a running total. Add the value of every node you visit, and subtract the value of every child you see. The remaining value is the root node. |
Draw an accumulator variable `val = 0`. As you touch a parent, write `+parent`. For its children, write `-child`. Watch all pairs cancel out until only the root is left. |
Pure Linear Scan $O(N)$ |
Draw a single straight line weaving through all nodes exactly once. Constant work at each stop. |
A grid-like Hash Set taking up $O(N)$ memory blocks. |
A single box labeled `val`. Cross out the number and rewrite it as it updates. $O(1)$ space. |
| 1507 |
Reformat Date |
Complex string parsing with massive nested if/else logic or switch statements to map strings to numerical values. |
Messy Flowchart $O(1)$ |
Draw a string and a spiderweb of erratic arrows pointing from "Oct" to 10, "20th" dropping the "th", etc. |
String Splitting + Hash Map |
Dictionary Lookup |
Split the string by spaces into `[Day, Month, Year]`. Look up the month in a pre-defined Map. Pad the day with a zero if length < 2. Concatenate Year-Month-Day. |
Draw the split array `["20th", "Oct", "2052"]`. Draw an arrow from "Oct" to a mini 2-column lookup table yielding "10". Reassemble the pieces. |
Constant Time Block $O(1)$ |
Draw a single, solid dot. Since date strings have a fixed max length, the time taken does not scale with any input N. |
Multiple allocated string copies in memory. |
Draw a fixed 12-row table representing the Hash Map of months. $O(1)$ space. |
| 1508 |
Range Sum of Sorted Subarray Sums |
Generate all N^2 subarray sums with nested loops, store them, sort the giant array, then sum indices left to right. $O(N^2 \log N^2)$. |
Giant Funnel Sorting |
Draw an array expanding into a massive N^2 grid, followed by a chaotic sorting bracket encompassing the whole grid. |
Min-Heap / Priority Queue (Multi-way Merge) |
Multi-way Expansion |
Push the start of every subarray into a Min-Heap. Pop the smallest sum, add to result if in range, then expand that specific subarray (current sum + next element) and push it back. |
Draw a triangle (Heap). Pop the top node, draw an arrow adding it to the result. Draw another arrow fetching the next element from the array, adding it to the popped sum, and pushing it back into the triangle. |
Heap Operations $O(N^2 \log N)$ |
Draw a long line of N^2 steps. At each step, draw a small tree of height logN representing the heap push/pop cost. |
A massive, continuous array block of size $O(N^2)$. |
A small bounded triangle (Heap) that never exceeds width N. $O(N)$ space. |
| 1509 |
Minimum Difference Between Largest and Smallest Value in Three Moves |
Recursively try changing 3 elements to literally any other number. Infinite search space. |
Infinite Explosion Tree |
Draw an array. Pick one element, draw an infinite number of arrows replacing it with every other possible integer. |
Sorting + Greedy (Sliding Window) |
The 4-Scenario Window |
Recognize that changing an element to match another means "removing" it from the difference calculation. Sort the array. We just need to drop 3 items from the edges. Try 4 scenarios: Drop 3 left, 2 left 1 right, 1 left 2 right, 3 right. |
Draw the sorted array. Draw a bracket covering `N-3` elements. Slide this bracket exactly 4 times (touching left edge, moving right by 1, 2, and 3 steps). Note the difference between the ends of the bracket each time. |
Sorting Bottleneck $O(N \log N)$ |
Draw a classic merge-sort tree structure, followed by 4 short horizontal lines representing the constant $O(1)$ window checks at the end. |
Stack Overflow / Giant Recursion Tree $O(N)$. |
Array rearranging itself in place. $O(1)$ extra space or $O(\log N)$ for sorting overhead. |
| 1510 |
Stone Game IV |
Pure Minimax recursion. Try subtracting every perfect square from the current stone count. If any move forces the opponent into a losing state, return true. |
Exploding Game Tree $O(N^\text{sqrt}(N)$) |
Draw a root node N. Branch out with √N edges (one for each perfect square <= N). Repeat this recursively. Watch the tree width explode. |
Dynamic Programming (Bottom-Up 1D) |
State Dependency Array |
Build a boolean array up to N. For each state `i`, check if there's any perfect square `k*k` where `dp[i - k*k]` is False (meaning the next player loses). If so, `dp[i]` is True. |
Draw a 1D array of boxes. To fill box 10, draw backward arrows jumping to box 9 (-1), box 6 (-4), and box 1 (-9). If any target box has 'F', write 'T' in box 10. |
Sub-linear Lookbacks $O(N \\text{cdot sqrt}(N)$) |
Draw a straight line N. From each point, draw backward arcs. The number of arcs grows very slowly (as the square root), so the line looks like it has a light "fringe" of arcs. |
Massive call stack depth $O(N)$. Draw recursive boxes stacked vertically. |
A single 1D boolean array. Draw T/F flags sequentially filling up boxes. $O(N)$ space. |
| 1511 |
Customer Order Frequency (Premium SQL) |
Using multiple subqueries or a Cartesian Product (Cross Join) without proper index filtering, scanning tables repeatedly for June and July. |
Nested Loop Join Grid (O(N*M)) |
Draw a massive grid multiplying every row in the `Customers` table by every row in `Orders` and `Product`. Shade in the massive amount of wasted space where IDs don't match. |
JOIN + Conditional Aggregation |
The Filtering Funnel |
Join the 3 tables. Funnel the data by dropping any rows not in June or July. Use a `GROUP BY` customer, and run two separate `SUM(CASE WHEN...)` checks to see if both months > 100. |
Draw 3 separate boxes (Tables). Draw connecting lines (JOINs) between matching IDs. Draw a funnel shape. Push rows through it. At the bottom, draw a scale checking if the June pile and July pile both weigh > 100. |
Hash Join & Pipeline (O(N+M)) |
Draw parallel lines representing the tables flowing into a single merge node (Hash Join), then immediately passing through a filter node, ending in a tiny output box. |
Massive temporary tables written to disk to hold un-indexed Cross Joins. |
A small Hash Map in memory. Keys are `customer_id`, and values are just two running integer sums (June Total, July Total). |
| 1512 |
Number of Good Pairs |
Nested loops comparing every single element with every other element appearing after it to check if they match. |
Handshake Network $O(N^2)$ |
Draw N dots in a line. Draw an arc from the 1st dot to all others. Then from the 2nd to all others. The arcs form a dense, messy web. |
Hash Map / Combinatorics |
Frequency Buckets |
Count the occurrences of each number. If a number appears `C` times, the number of valid pairs is `C * (C - 1) / 2`. Add this formula's result for all unique numbers. |
Draw labelled buckets. As you read the array, drop tally marks into the matching bucket. Once finished, write the `n(n-1)/2` formula under each bucket and sum them up. |
Two Parallel Lines $O(N)$ |
Draw one line for iterating the array to build the map, and a second shorter line representing iterating through the map's keys to apply the formula. |
$O(1)$ space. Draw two pointer fingers `i` and `j` moving along a single array block. |
A Hash Map. Draw a 2-column table mapping the integer key to an integer tally count. $O(N)$ space. |
| 1513 |
Number of Substrings With Only 1s |
Generate all possible substrings with nested loops, then verify if each substring only contains '1's. |
Expanding Triangle Grid $O(N^2)$ |
Draw the array as the top row. Below it, draw all substrings of length 2, then length 3, forming a large downward-pointing triangle of redundant checks. |
Math / Contiguous Counting |
Length to Combination Mapping |
Iterate the string counting consecutive 1s. When you hit a 0, take the length `L` of the previous 1s block and add `L * (L + 1) / 2` to the total answer. Reset count. |
Write the binary string. Draw brackets around groups of contiguous 1s. Write the length of each bracket. Plug each length into the formula and sum the results. |
Linear Scan Segmenting $O(N)$ |
Draw a single straight line. Color the segments of '1's blue and '0's red. The work done is strictly proportional to the length of the line. |
A memory block for every substring generated. $O(N^2)$ space. |
A single variable box `count`. Erase and rewrite the number inside as it increments, resetting to 0. $O(1)$ space. |
| 1514 |
Path with Maximum Probability |
DFS to find every possible path from start to end, multiplying probabilities along the way, and returning the maximum. |
Exponential Path Branching $O(V!)$ |
Draw a spiderweb graph. Trace a colored line for every unique path from A to B. The lines will heavily overlap and explode in quantity. |
Graph / Dijkstra's (Max-Heap) |
Expanding Wavefront of Certainty |
Use a Max-Heap initialized with start node (prob 1.0). Pop the node with the highest probability. Multiply its probability with its neighbors' edge weights. If higher than the neighbor's current known probability, update and push to heap. |
Draw a graph with edge decimals. Draw a starting circle. Draw expanding concentric ripples. When a ripple hits a node, update a small "score box" next to the node if the multiplied path score is higher. |
Heap-Managed Graph Traversal $O((V+E)$ log V) |
Draw a V+E length line representing edge relaxations. Above it, draw a logV height tree representing the heap rebalancing on every push/pop. |
Massive recursive call stack and `visited` sets for path tracking. $O(V)$. |
A Graph Adjacency List (an array of lists) and a Triangle representing the Max-Heap. $O(V+E)$ space. |
| 1515 |
Best Position for a Service Centre |
Iterate over every coordinate on a dense 2D grid within the bounds using tiny increments (e.g., 0.00001) to find the minimum distance sum. |
Dense Pixel Grid Search $O(\text{Grid Area})$ |
Draw a large square grid completely filled with dots. Shade in the entire area, representing the brute-force checking of every possible sub-coordinate. |
Geometry / Gradient Descent (or Weiszfeld's) |
Simulated Annealing / Converging Steps |
Start at the centroid (average x, average y). Check neighbors at a step distance `d`. Move to the neighbor if it lowers the total distance. If no neighbor is better, shrink `d` (e.g., `d *= 0.9`). Stop when `d` is incredibly small. |
Draw scattered points on a 2D plane. Drop a pin in the middle. Draw arrows stepping outward in 4 directions. Move the pin to the best option. Draw progressively shorter arrows as the pin hones in on the center of mass. |
Shrinking Radii Loops $O(N \\text{cdot iterations})$ |
Draw a line of length N representing the distance calculation for one step. Encircle it with a loop representing the number of gradient steps before the delta hits the precision limit. |
$O(1)$ space, purely looping over variables. |
Variables for `x`, `y`, `step`, and an array holding the input coordinates. $O(1)$ extra space. |
| 1516 |
Move Sub-Tree of N-Ary Tree |
Physically tear the tree apart without tracking parents, potentially creating infinite cycles if moving a node into its own subtree. |
Cycle-Creation Web |
Draw a tree. Rip node A, attach to node B (which is under A). Draw an infinite loop arrow. |
DFS (Parent Tracking) + Pointer Manipulation |
The Safe Relocation Map |
1. DFS to find Node P, Node Q, and their parents. 2. Check if P is an ancestor of Q. If yes, you must carefully detach Q and attach it to P's old parent before moving P under Q. |
Draw the tree. Highlight P and Q. Draw a dotted line "up" from Q to see if it hits P. If it does, draw the complex "swap" arrows. Otherwise, simply cut P's top string and tie it under Q. |
Single Tree Trace $O(N)$ |
Draw a single line down the tree to locate targets and check ancestry. |
Massive deep copies. |
Recursion stack. $O(H)$ space. |
| 1517 |
Find Users With Valid E-Mails (Database / String) |
Massive nested if/else statements. Loop through the string checking if character 1 is a letter, if characters 2-N are valid symbols, manually checking for '@leetcode.com', etc. |
Spaghetti Code Flowchart $O(N \cdot L)$ |
Draw a word, and from every single letter draw 4-5 erratic arrows pointing to different decision boxes ("Is it a letter?", "Is it a dash?", "Is it an underscore?"). |
Regular Expressions (Regex) |
Finite State Automaton (FSM) |
Define a strict pattern: `^[a-zA-Z][a-zA-Z0-9_.-]*@leetcode\.com`. The engine processes the string character by character, moving through states. If it hits an invalid transition, it immediately rejects. |
Draw 3 large circles (States): "Start", "Prefix", and "Domain". Draw arrows between them. Start -> Prefix (requires letter). Prefix -> Prefix (allows letters/numbers/dash). Prefix -> Domain (requires @leetcode.com). |
Regex Engine Scanning $O(L)$ |
Draw a straight timeline representing the length of the string. Draw a scanner moving left to right. Constant time $O(1)$ decision per character. |
Multiple boolean variables and temporary string builders taking up memory. |
The Regex engine's compiled state table (O(Pattern Length) space), requiring essentially $O(1)$ auxiliary space for the actual string validation. |
| 1518 |
Water Bottles |
Simulate exactly what a human would do in a `while` loop: drink bottles, add to empty count, divide empty by exchange rate to get new full bottles, remainder carries over. |
Cyclic Loop Drain $O(\log N)$ |
Draw a large block representing N bottles. Draw an arrow looping back, slicing off a fraction of the block and converting it back into a smaller block of "new" bottles. Repeat until the block vanishes. |
Math Formula |
Geometric Convergence |
Realize this is a math puzzle. Every time you exchange `E` bottles for 1, you effectively "spend" `E - 1` bottles to get a refill. Formula: `N + (N - 1) / (E - 1)`. |
Draw N bottles. Group them visually into blocks of `(E - 1)`. The number of these blocks immediately tells you how many free refills you get. |
Constant Time Block $O(1)$ |
Draw a single dot. No matter if you start with 10 bottles or 10 billion bottles, the mathematical formula calculates the answer instantly in one step. |
A few tracking integer variables: `full`, `empty`, `total`. $O(1)$ space. |
Pure variables evaluated instantly. $O(1)$ space. |
| 1519 |
Number of Nodes in the Sub-Tree With the Same Label |
For every single node in the tree, launch a completely new DFS to explore its subtree and count matching labels. $O(N^2)$ time. |
Overlapping Triangles $O(N^2)$ |
Draw a large triangle (the tree). Draw a smaller triangle inside it for a child's DFS. Then another inside that. The overlapping shading represents massive redundant work. |
Post-Order DFS (Bottom-Up) |
Buckets Merging Upwards |
Go to the leaf nodes first. Each node returns an array of size 26 (frequencies of a-z). A parent node receives these arrays from its children, adds them together, adds its own label, and passes the merged array up. |
Draw a tree. At the bottom leaves, draw small boxes like `[a:1]`. Draw arrows pushing these boxes UP to the parent. The parent combines them into a bigger box `[a:2, b:1]`, answers its own question, and pushes it up again. |
Linear Scan x 26 $O(N)$ |
Draw a single line hitting every node exactly once. At each node, draw a small, fixed-size block of 26 operations. Since 26 is constant, it's $O(N)$. |
Recursive call stack $O(H)$, plus N separate tally arrays allocated and destroyed. |
A single call stack of depth $O(H)$. The memory visualization is an array of size 26 being passed and returned at every level. Space is $O(H + 26)$ -> $O(H)$. |
| 1520 |
Maximum Number of Non-Overlapping Substrings |
Generate every single valid substring that meets the condition (all occurrences of its characters are inside it). Then use recursive backtracking to find the maximum non-overlapping combination. |
Exploding Interval Tree $O(2^N)$ |
Draw a timeline with overlapping horizontal lines (intervals). Branch into a massive decision tree: "Include Interval A" (branch left) vs "Exclude Interval A" (branch right). |
Interval Expansion + Greedy Search |
Bounding Box Consolidation |
1. Find first and last occurrence of every letter. 2. Expand these bounds (if interval 'a' contains 'b', expand 'a' to include all of 'b'). 3. Sort valid intervals by their END point and pick greedily. |
Draw a string. Draw a bracket under all the 'a's, and a bracket under all the 'b's. If the brackets overlap, draw a giant bracket merging them. Finally, sort the brackets by their right edge and circle them left-to-right. |
3-Phase Linear Pipeline $O(N)$ |
Draw 3 horizontal lines. Phase 1: Scan string to find start/ends. Phase 2: Expand bounds (26 characters max, so constant work). Phase 3: Greedy select. Overall time is strictly linear. |
Massive subsets of arrays stored in memory during backtracking. |
Two arrays of size 26 storing the `left` and `right` indices of each character. $O(1)$ auxiliary space (since 26 is constant). |
| 1521 |
Find a Value of a Mysterious Function Closest to Target |
Generate all possible subarrays using nested loops, calculate the bitwise AND for each, and track the minimum difference to the target. $O(N^2)$. |
Overlapping Subarray Grid $O(N^2)$ |
Draw an array. Underneath it, draw N decreasing blocks of subarrays, doing redundant bitwise AND operations for every single combination. |
Bitwise AND Properties / Hash Set |
Shrinking Bit Set |
Recognize that bitwise AND only *decreases* or stays the same. At any index `i`, the number of unique AND results ending at `i` is at most 32. Use a Set to track valid AND results ending at the previous step, update them with the current number, and check the difference. |
Draw an array. Below the current element, draw a small box (the Set) containing a few numbers. Draw an arrow pulling the *next* array element into the box, applying the `&` operator to everything inside, dropping duplicates, and updating the global minimum difference. |
Bounded Set Updates $O(N \log(\text{Max}_\text{Val})$) |
Draw a linear timeline of length N. At each tick, draw a small, fixed-size cluster of max 32 operations representing the set updates. |
$O(1)$ memory for tracking the current global minimum, but massive redundant variables. |
Two small Hash Sets (or arrays of max size 32) representing `prev_results` and `curr_results` swapping back and forth. $O(\log(\text{Max}_\text{Val})$) space. |
| 1522 |
Diameter of N-Ary Tree (Premium) |
For every single node, run a full DFS to find the maximum depth of all its children subtrees, summing the top two. $O(N^2)$ for skewed trees. |
Cascading Triangles $O(N^2)$ |
Draw a large tree. Pick a node, draw a shaded triangle under it for its DFS. Pick its child, draw another shaded triangle overlapping the first. Huge redundant work. |
Post-Order DFS (Tree DP) |
Top-2 Bubble Up |
Traverse to the leaves. As you return back up to a parent, each child reports its max depth. The parent tracks its *top 2* deepest children. The diameter through that parent is `top1 + top2`. Pass `top1 + 1` up to the grandparent. |
Draw a node with 4 children. The children pass up the numbers `[1, 4, 2, 3]`. The parent circles `4` and `3`, adds them to check the global max (7), and then passes `4 + 1 = 5` up the chain. |
Single-Pass Tree Trace $O(N)$ |
Draw a single line snaking down to the leaves and back up to the root, touching every edge exactly twice (down and up). |
Massive recursive call stacks stacked inside loops. $O(N)$. |
Two local variables per stack frame (`max1` and `max2`). $O(H)$ space for the recursive call stack height. |
| 1523 |
Count Odd Numbers in an Interval Range |
A `for` loop iterating from `low` to `high`, doing an `if (i % 2 != 0)` check and incrementing a counter. $O(N)$ where N is the range size. |
Linear Hash Marks $O(N)$ |
Draw a number line. Draw a tally mark on every single odd number between the start and end bounds, counting them manually one by one. |
Math |
Bounding Box Formula |
The number of odds between any two numbers is roughly half the distance. Formula: `(high - low) / 2`. If either `low` or `high` is odd, add 1. |
Draw a block representing the range. Split the block perfectly in half visually. Check the edges of the block; if an edge lands on an odd number, add a single dot to the final sum. |
Instant Calculation $O(1)$ |
Draw a single dot. The math formula executes instantly regardless of whether the range spans 10 numbers or 10 billion numbers. |
A single counter variable. $O(1)$. |
A single equation evaluated in CPU registers. $O(1)$ space. |
| 1524 |
Number of Sub-arrays With Odd Sum |
Nested loops to generate every subarray, computing the sum for each and checking if it's odd. $O(N^2)$ or $O(N^3)$. |
Redundant Summation Brackets |
Draw an array. Draw overlapping brackets. Inside each bracket, draw a mini-calculator constantly re-adding the same numbers together. |
Prefix Sum + Math (Parity) |
Even/Odd State Toggling |
Keep a running total (Prefix Sum). If the current sum is Even, you can form an odd subarray by subtracting a previous Odd prefix. If the current sum is Odd, subtract a previous Even prefix. Track the counts of Even and Odd prefixes seen so far. |
Draw an array. Below it, draw two buckets labeled "Even Prefixes" and "Odd Prefixes" (Even starts at 1). As you scan the array, add the current number to your total. If the total is odd, pour the "Even" bucket into your answer, then add a tally to the "Odd" bucket. |
Linear Parity Scan $O(N)$ |
Draw a single straight line crossing the array. Above the line, draw a toggle switch flipping between "E" and "O" as the sum grows. |
Allocated arrays to hold every subarray sum. $O(N^2)$. |
Two integer variables: `even_count` and `odd_count`. $O(1)$ space. |
| 1525 |
Number of Good Ways to Split a String |
Loop to place a split at every index `i`. For each split, slice the string into two, dump both into separate Hash Sets, and compare sizes. $O(N^2)$. |
Two Sliding Windows $O(N^2)$ |
Draw a string. Draw a vertical slice. Draw two circles (Sets) processing the left and right halves. Erase everything, move the slice over by 1, and redraw everything from scratch. |
Prefix & Suffix Arrays (State Tracking) |
The Meeting Point |
Precompute how many unique characters exist from right-to-left and store it in an array `suffix_unique`. Then iterate left-to-right, keeping a running set of unique chars, and compare it to the `suffix_unique[i+1]` array. |
Draw a string. Draw a row of boxes below it (the Suffix array) filled back-to-front with unique counts. Draw a scanner moving left-to-right, tallying unique letters. At each step, compare the scanner's tally with the box immediately to its right. |
Two-Pass Linear $O(N)$ |
Draw two parallel horizontal lines. One arrows points right-to-left (precomputation). The second arrow points left-to-right (the checking phase). Both are $O(N)$. |
Multiple substring allocations and Set rebuilds taking massive garbage collection space. $O(N^2)$. |
One integer array of size N (the suffix tracker) and one integer array of size 26 (the left character tracker). $O(N)$ space. |
| 1526 |
Minimum Number of Increments on Subarrays to Form a Target Array |
Find the minimum value in the array, add it to the total operations, subtract it from all elements, and recursively process the left and right split arrays. Worst case $O(N^2)$. |
Cascading Valleys $O(N^2)$ |
Draw a mountain range (the array). Draw a horizontal line cutting off the lowest peak, splitting the mountain in two. Recursively draw lines cutting the sub-mountains. High redundant scanning. |
Greedy / Array Math |
The Staircase Difference |
Only count the *upward* steps. Iterate through the array. If `target[i] > target[i-1]`, it means we need `target[i] - target[i-1]` new overlapping operations that the previous number couldn't cover. Add this difference to the total. |
Draw a bar chart of the array. Start from the left. Draw a horizontal line extending rightwards from the top of the first bar. When a taller bar pierces the line, color the exposed top part. The sum of these colored top parts is the answer. |
Single Linear Pass $O(N)$ |
Draw a single straight line. At each step, do a constant $O(1)$ subtraction check between the current node and the immediate previous node. |
Deep recursive call stacks holding start/end indices of subarrays. $O(N)$. |
A single variable `operations`. $O(1)$ space. |
| 1527 |
Patients With a Condition (SQL) |
Scanning the entire table, loading the string column into memory, and using expensive regex or split operations per row in the application layer. |
Full Table String Parsing $O(N \cdot L)$ |
Draw a massive database block. Draw an arrow pulling every single row into a magnifying glass, where a complex engine slices the string by spaces to check every word. |
SQL LIKE Operator / String Matching |
The Dual-Condition Filter |
Use the SQL `LIKE` operator to check two specific patterns: `conditions LIKE 'DIAB1%'` (starts with it) OR `conditions LIKE '% DIAB1%'` (contains it with a leading space). This ensures we catch the exact condition prefix without false positives. |
Draw a database table pouring rows into a Y-shaped funnel. One branch checks if the string explicitly starts with 'DIAB1'. The other checks if ' DIAB1' is buried inside. If either is true, the row drops into the result bucket. |
Indexed / Scanned Filter $O(N)$ |
Draw a linear pipeline. The database engine does a single pass over the rows, applying a highly optimized C-level string match. |
Application memory overhead for loading unneeded rows. |
Zero application memory. The filtering happens in the database engine memory buffer. $O(1)$ auxiliary space. |
| 1528 |
Shuffle String |
Search the `indices` array for 0, append the matching char. Search for 1, append matching char. Nested loops resulting in $O(N^2)$. |
Redundant Searching Lines $O(N^2)$ |
Draw the character array. Draw a massive tangle of lines repeatedly scanning left-to-right looking for the number 0, then again for 1, then again for 2. |
Direct Array Placement / Cyclic Sort |
The Mailbox Sorter |
Create a new character array of the same length. Iterate the original string. Place the character `s[i]` directly into the new array at index `indices[i]`. |
Draw the original string and the `indices` array on top of each other. Below them, draw a blank array of boxes. Draw a straight, single-shot arrow from `s[i]` directly into the blank box labeled `indices[i]`. |
Parallel Assignment $O(N)$ |
Draw a single horizontal line representing the `for` loop. At each tick, draw an arrow pointing to a random bucket. Exact linear time. |
Immutable string concatenations causing massive garbage collection $O(N^2)$. |
A single character array of length N to hold the result before converting to a string. $O(N)$ space. |
| 1529 |
Minimum Suffix Flips (Bulb Switcher IV) |
When encountering a mismatch between current state and target, actually iterate through the rest of the string (the suffix) and flip all the bits physically. $O(N^2)$. |
Massive Bit-Flipping Waves $O(N^2)$ |
Draw a row of 0s. When a 1 is needed, draw an arrow physically flipping all remaining numbers to 1. Then when a 0 is needed later, draw an arrow flipping them all back. Huge redundant writes. |
State Tracking / Greedy |
The Virtual Toggle Switch |
Realize you don't need to physically flip anything. Just track the *current state* of the bulbs (starts at '0'). Iterate through the target string. If `target[i]` differs from `state`, increment a flip counter and toggle `state`. |
Draw the target string. Hold a token labeled '0'. Slide along the string. When the token doesn't match the current character, add a tally mark, flip the token over to '1', and keep sliding. |
Single State Scan $O(N)$ |
Draw a single timeline. Above the line, draw a toggle switch that flips its state whenever a mismatch is detected. No nested loops. |
An array of length N constantly being mutated. $O(N)$ space. |
Two single variables: `flips` and `current_state`. $O(1)$ space. |
| 1530 |
Number of Good Leaf Nodes Pairs |
Find all leaf nodes. For every pair of leaves, find their Lowest Common Ancestor (LCA) and calculate the path distance. Check if it's <= limit. $O(L^2 \cdot N)$. |
Exploding Path Tracer $O(L^2)$ |
Draw a tree. Highlight the leaves. Draw a massive, chaotic spiderweb of lines connecting every single leaf to every other leaf, tracing up and down the tree branches. |
Post-Order DFS (Tree DP) |
Distance Buckets Bubbling Up |
From each node, return an array (or list) of distances to all leaves in its subtree. The parent receives left and right distance lists. It compares every left leaf with every right leaf. If `left_dist + right_dist <= limit`, count it. Then, increment all distances by 1 and return to the grandparent. |
Draw a small subtree. The left child passes up `[1]`. The right passes up `[1, 2]`. The parent draws connecting lines between the left list and right list, checking sums. Then it adds 1 to all numbers, creating `[2, 2, 3]`, and pushes that box up. |
Bounded Double Loop per Node $O(N \\text{cdot Limit}^2)$ |
Draw a tree traversal line. At each node, draw a small, bounded grid representing the cross-comparison of left and right distances (capped by the small limit size). |
Storing full paths or massive distance matrices for all leaves. $O(N^2)$. |
Each recursive call returns a small array/list bounded by the `limit` size (max 10). Space is $O(H \\text{cdot limit})$ -> effectively $O(H)$. |
| 1531 |
String Compression II |
Try every possible combination of deleting K characters using backtracking. $O(2^N)$. |
Exponential Subsequence Tree $O(2^N)$ |
Draw the string. Branch out twice for every character: "Keep" or "Delete". The tree depth is N, and the width doubles at every level. |
Dynamic Programming (Top-Down with Memo) |
The 4-Variable State Cube |
Define a state `dp(idx, last_char, last_count, k)`. At each step, either delete the char (if `k > 0`) or keep it. If keeping, check if it matches `last_char` to update the compressed length (watching for 1->2, 9->10, 99->100 transitions). |
Draw a 3D grid where axes are `Index`, `K`, and `LastChar`. As you move through the string, draw an arrow jumping between cells in the grid, only computing a cell if it's empty (memoization). |
State-Space Product $O(N^2 \cdot K \cdot 26)$ |
Draw a dense 2D table representing `Index x K`. Inside each cell, imagine a small 26-slot drawer. The total "work" is filling every drawer exactly once. |
An enormous recursion tree with redundant string slices. |
A 4D Memoization table/array. Draw a block of memory divided into `N * K * 26 * 100` small compartments. $O(N^2 \cdot K)$ space. |
| 1532 |
The Most Recent Three Orders (SQL) |
For every user, select all orders, sort them by date descending in the application, and slice the first 3. $O(U \cdot O \log O)$. |
User-by-User Sorting $O(U \cdot O \log O)$ |
Draw a list of users. For each user, draw a separate sorting funnel that takes all their orders and outputs just three. Highly inefficient for large databases. |
Window Function (ROW_NUMBER) |
The Partitioned Ranker |
Use `ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY order_date DESC)`. This assigns a 1, 2, 3... to each customer's orders internally. Then just filter for `rank <= 3`. |
Draw a table of orders. Draw horizontal dividers grouping orders by `customer_id`. Inside each group, draw an arrow sorting the dates and writing "1", "2", "3" next to them. Circle the rows with numbers 1-3. |
Partitioned Scan $O(N \log N)$ |
Draw a single line of data being sorted once globally within its partitions, then a quick linear filter pass. |
Loading tens of thousands of rows into server memory for manual sorting. |
The database's internal sort buffer. $O(N)$ space to hold the ranking metadata. |
| 1533 |
Find the Index of the Large Integer (Interactive) |
Compare every single index or pair using the API until the "heavier" one is found. $O(N)$. |
Linear Balance Scale $O(N)$ |
Draw a line of weights. Put weight 1 on the left scale and weight 2 on the right. If equal, repeat for weight 3 and 4. Slow, incremental progress. |
Binary Search (Ternary Splitting) |
The Halving Scale |
Split the range into two equal halves (if odd, keep the middle element out). Compare the two halves using the API. Move to the half that is "heavier". If they are equal, the middle element you kept out is the answer. |
Draw a large block. Split it in half. Draw two hands lifting each half. An arrow points to the heavier side, and the other half is crossed out. Repeat until one small block remains. |
Logarithmic Queries $O(\log N)$ |
Draw a line that shrinks by half at every step. Even for a billion elements, you only need ~30 steps. |
Zero memory; purely sequential logic. |
Two pointer variables `low` and `high`. $O(1)$ space. |
| 1534 |
Count Good Triplets |
The only way: Three nested loops `i, j, k` checking all 3 absolute difference conditions. $O(N^3)$. |
Triple Nested Loop Cube $O(N^3)$ |
Draw a 3D cube made of tiny dots. Each dot represents one `(i, j, k)` combination. You must touch every single dot in the cube to finish. |
Brute Force / Constraint Optimization |
Early Exit Pruning |
While still $O(N^3)$, you can stop the `k` loop from even starting if the `abs(arr[i] - arr[j])` condition isn't met first. |
Draw the three loops. Draw a "Gate" between the 2nd and 3rd loop. If the first condition fails, the gate slams shut, preventing the inner-most loop from running. |
Pruned Cubic $O(N^3)$ |
Draw a cubic volume, but shade parts of it red to show they are "skipped" by the early exit conditions. |
Three pointer variables in registers. $O(1)$. |
No extra data structures. $O(1)$ space. |
| 1535 |
Find the Winner of an Array Game |
Physically simulate the game by moving the loser to the end of the array (using `list.pop(0)` and `list.append()`) until someone wins K times. $O(N \cdot K)$. |
Queue Rotation $O(N \cdot K)$ |
Draw a circle of numbers. Two numbers fight, the loser moves to the back of the line. The numbers keep spinning in a circle until a winner is found. |
One-Pass Greedy / Simulation |
The King of the Hill |
Don't actually move any elements. Just keep track of the `current_winner`. Iterate through the array once. If the next element is bigger, it becomes the `new_winner` and the win-streak resets to 1. If you finish the array without a K-streak, the max element is the winner. |
Draw a line of people. The first person stands on a pedestal. They fight the next person in line. If they win, draw a tally mark on their chest. If they lose, they step down and the winner takes the pedestal. |
Linear Scan $O(N)$ |
Draw a single straight line. Each element is compared exactly once. The game ends either when someone hits K wins or we reach the end of the line. |
Constant array re-allocations or shifts. $O(N^2)$ in some languages. |
Two variables: `curr_winner` and `streak`. $O(1)$ space. |
| 1536 |
Minimum Swaps to Arrange a Binary Grid |
Exhaustively try every possible row swap combination to see which leads to the target "upper triangular" form. $O(N!)$. |
Factorial Permutation Tree |
Draw a grid. Branch out N times for every possible first row swap, then (N-1) for the second. The tree width is astronomical. |
Greedy / Bubble Sort Logic |
Trailing Zero Tally |
1. Convert each row into a single number: the count of trailing zeros. 2. For each position `i`, find the first row (from `i` downwards) that has at least `n-1-i` trailing zeros. 3. "Bubble" that row up to position `i` and count the swaps. |
Draw the grid. To the right of each row, write the count of its trailing zeros (e.g., [2, 0, 1]). For row 0, you need 2 zeros. Locate the row with '2', draw a curved arrow hopping it over the other rows to the top. Count the hops. |
Nested Linear Scan $O(N^2)$ |
Draw a square. An arrow sweeps from top to bottom (outer loop), and for each step, a second arrow sweeps from the current point to the bottom (inner search). |
Storing full grid states in a queue for BFS. $O(N^2 \cdot N!)$. |
A 1D array of size N to store the trailing zero counts. $O(N)$ space. |
| 1537 |
Get the Maximum Score |
Use DFS to explore every single path starting from the beginning of both arrays, following "teleport" junctions (equal values) whenever they appear. $O(2^N)$. |
Junction Branching Tree |
Draw two parallel lines with occasional bridges connecting them. At every bridge, the path splits into two. The number of paths doubles at every junction. |
Two Pointers / Greedy Prefix Sum |
Parallel Track Accumulation |
Iterate through both sorted arrays simultaneously. Accumulate sums for both independently. When you hit a "junction" (common element), take the `max(sum1, sum2)` plus the junction value, reset sums, and continue. |
Draw two parallel horizontal paths. Draw "sum buckets" for each path. When the paths meet at a common number, compare the buckets, empty the lighter one into the trash, and put the heavier one's total into a "Global Max" box. |
Synchronized Linear Scan $O(N + M)$ |
Draw two parallel lines. Draw a single vertical "scanning bar" that moves across both simultaneously, pausing only to sync up at junctions. |
Recursive stack for all path combinations. $O(N+M)$. |
Two sum variables (`s1`, `s2`) and two pointers (`i`, `j`). $O(1)$ space. |
| 1538 |
Guess the Majority Element in a Hidden Array (Interactive) |
Query every possible subset of 4 elements to determine parities. $O(N^4)$. |
Complete Subgraph Querying |
Draw N dots. Draw a circle around every possible group of 4. The lines overlap until the page is completely black. |
Relative Parity / Math |
The Pivot Reference |
Use two constant pivots. Compare `query(0,1,2,3)` with `query(1,2,3,4)` to see if element 0 and 4 are the same. By shifting the "window" of the query, you can determine if every element `i` is the same as element 0 or not. |
Draw a line of mystery boxes. Query the first 4. Then drop the first and add the 5th. If the result is the same, box 1 and box 5 are identical. Use this to mark boxes with 'A' or 'B'. Count which letter appears more. |
Linear Query Limit $O(N)$ |
Draw a line of length N. At each step, draw a single query box. The number of queries is exactly N+1. |
Storing every query result in a map. $O(N)$. |
Two counters (`countA`, `countB`) and one index `lastIndex`. $O(1)$ space. |
| 1539 |
Kth Missing Positive Number |
Iterate from 1 upwards, checking if each number exists in the array. Stop when the "missing" counter hits K. $O(N + K)$. |
Linear Number Line Check |
Draw a number line. Cross out numbers present in the array. Count the gaps until you reach the Kth gap. |
Binary Search (Range-Based) |
Missing Count Predicate |
At any index `i`, the number of missing elements before it is `arr[i] - (i + 1)`. Binary search for the largest index where missing elements are less than K. |
Draw the array. Below each element, write the result of `arr[i] - (i + 1)`. Use binary search pointers (`L` and `R`) to find the "jump" point where the missing count exceeds K. |
Logarithmic Search $O(\log N)$ |
Draw a line that is cut in half repeatedly. Even if the array has a million elements, you find the spot in 20 steps. |
Converting the array to a Hash Set for $O(1)$ lookups. $O(N)$ space. |
Two pointers `low` and `high`. $O(1)$ space. |
| 1540 |
Can Convert String in K Moves |
For each character difference, try to find a unique "move number" by iterating from 1 to K for every single character. $O(N \cdot K)$. |
Move-exhaustion Loop |
Draw two strings. For each character, draw a loop that spins from 1 to K looking for an available shift value. |
Hash Map / Frequency Counting |
Shift Cycle Multiplier |
Calculate the required shift `d` for each character `(t[i] - s[i] + 26) % 26`. If `d > 0`, the moves needed are `d, d+26, d+52...`. Just track how many times each shift `d` has occurred and check if the *last* required move `d + (count[d]-1)*26` is within K. |
Draw a table with 26 slots (0-25). As you calculate a shift, put a tally mark in the slot. If slot 5 has 3 tallies, the moves used are 5, 31, and 57. Check if 57 <= K. |
Single Pass $O(N)$ |
Draw a single line for the string. For each character, draw one arrow to a fixed-size table of 26 buckets. |
Allocating a new string or list of all possible moves. $O(K)$. |
A fixed-size integer array of size 26. $O(1)$ space (since 26 is constant). |
| 1541 |
Minimum Insertions to Balance a Parentheses String |
Generate all possible valid parentheses combinations and check the edit distance to the target string. $O(2^N)$. |
Backtracking Growth Tree |
Draw a root. Branch out 3 ways: "Add (", "Add )", "Leave as is". The tree explodes to depth N. |
Greedy / Stack Logic (Counter) |
Dual-Requirement Counter |
Treat '(' as a requirement for TWO ')'. Iterate through the string. If you see '(', you need two closers. If you see ')', check if the next char is also ')'. If not, "insert" one. Use a `need` and `res` variable to track. |
Draw the string. Below it, draw a "Debt Box" labeled `needed_closers`. When you see `(`, put two +1 tokens in the box. When you see `))`, take two tokens out. If the box is empty and you see `)`, add a +1 to your "Fine" (result) and take a token anyway. |
One-Pass Linear $O(N)$ |
Draw a single straight line. Above the line, show a running total incrementing and decrementing. Constant work at each index. |
A stack of character objects. $O(N)$. |
Two integer variables: `res` (total insertions) and `need` (current balance). $O(1)$ space. |
| 1542 |
Find Longest Awesome Substring |
Generate all N^2 substrings. For each, count the frequency of digits 0-9. If at most one digit has an odd frequency, it's "awesome". $O(N^3)$. |
N-Cubed Frequency Grid |
Draw the array. Draw N^2 brackets. For every bracket, draw 10 tally boxes and fill them. This is an massive waste of time. |
Bitmask + Prefix XOR |
The 10-Bit Toggle |
Represent the parity of digits 0-9 as a 10-bit integer (mask). A substring is awesome if the XOR sum of its prefix masks results in a mask with at most one bit set. Use a Hash Map to store the first time each mask was seen. |
Draw a 10-slot light switch board. As you read a digit '3', flip switch #3. Check a table to see if this exact switch configuration was seen before. Then flip each switch one by one to see if *that* configuration was seen (this handles the "one odd digit" case). |
Linear Scan with Constant Multiplier $O(10 \cdot N)$ |
Draw a line of length N. At each step, draw 11 arrows (1 for the current mask, 10 for the bit-flips) pointing to a Map of size 2^{10}. |
Full frequency maps for every substring. $O(N^2)$. |
A Map or Array of size 1024 (representing all 2^{10} possible bitmasks). $O(1)$ space since 1024 is constant. |
| 1543 |
Fix Product Name Format (SQL) |
Pull all data into Python/Java, use `.trim()` and `.toLowerCase()` on every string, then group and count in code. $O(N)$. |
Application-Side Processing |
Draw a database. Draw an arrow pulling every row into a separate "Cleaning Station" outside the DB before sending it back. |
String Functions + Aggregation |
The Clean-Pipe Grouping |
Use `TRIM(LOWER(product_name))` and `DATE_FORMAT(sale_date, '%Y-%m')` directly in the `SELECT` and `GROUP BY` clauses. The database engine cleans and aggregates in a single internal pass. |
Draw a table with messy data (" AppLe ", "2026-03-15"). Draw it passing through a "Squeegee" (TRIM) and a "Filter" (LOWER). The output is a clean "apple". Group these clean outputs. |
Internal Sort/Hash Grouping $O(N \log N)$ |
Draw a single flow line. The work happens inside the DB engine's memory buffer as a single scan and group operation. |
Storing thousands of unrefined string objects in application RAM. |
Zero extra application memory. The DB uses its internal temporary buffer. $O(N)$ space for grouping. |
| 1544 |
Make The String Great |
Repeatedly scan the string from the beginning. If you find a pair like 'aA', remove it and start the scan again from index 0. $O(N^2)$. |
Recursive String Shrinking $O(N^2)$ |
Draw a string. Circle a pair, erase it, and draw a long arrow pointing back to the start of the string to begin again. |
Stack (Greedy Elimination) |
The Collision Buffer |
Iterate through the string once. For each character, check the top of the stack. If they are the same letter but different case (absolute difference of 32 in ASCII), pop the stack. Otherwise, push the char. |
Draw a vertical tube (the stack). Drop 'a' in. Next is 'A'. Since they "react," they both vanish. Drop 'b' in. Next is 'c'. They stay. The contents of the tube at the end is the "Great" string. |
One-Pass Linear $O(N)$ |
Draw a single horizontal line. Each character is looked at exactly once and either added to or removed from the stack. |
New string allocations for every single deletion. $O(N^2)$. |
A stack or character array. $O(N)$ space. |
| 1545 |
Find Kth Bit in Nth Binary String |
Physically generate the string S_n using the formula S_n = S_{n-1} + "1" + reverse(invert(S_{n-1})). Then return the Kth character. $O(2^N)$. |
Exponential String Builder |
Draw S_1. Then draw S_2 which is twice as long. By S_{20}, the string is over 1 million characters. This will crash your memory. |
Recursive Symmetry / Divide & Conquer |
The Mirror Logic |
Notice the string's length is 2^n - 1. If K is the middle bit, it's '1'. If K is in the first half, it's the same as S_{n-1}[k]. If K is in the second half, it's the *inverted* bit of S_{n-1} at the mirrored position. |
Draw a long bar. Mark the center point. If K is on the right side, "fold" the bar in half. Note that you now need to "invert" the answer. Keep folding until the bar is length 1. |
Logarithmic Depth $O(N)$ |
Draw a line of length N. Each step represents one recursive call where we decide which "half" to zoom into. |
Storing the full 2^N length string in memory. $O(2^N)$. |
Recursive call stack depth. $O(N)$ space. |
| 1546 |
Maximum Number of Non-Overlapping Subarrays With Sum Equals Target |
Generate every single subarray, find all that sum to target, and use backtracking to find the maximum non-overlapping set. $O(2^N)$. |
Recursive Interval Forest |
Draw an array. Underneath, draw dozens of overlapping horizontal brackets representing valid subarrays. Branch out into a tree where you choose to "pick" or "skip" each bracket. |
Prefix Sum + Hash Set + Greedy |
The Resetting Prefix Map |
Keep a running prefix sum. If `(prefix_sum - target)` exists in your Set, you've found a valid subarray. To ensure they are non-overlapping, count it and **clear the Set** immediately to start fresh from the current index. |
Draw an array. Draw a scanner moving right. Below it, draw a "Memory Bin" (Set). When the scanner finds a match, draw a vertical "Wall" (reset). The number of walls you draw is the answer. |
Linear Greedy Scan $O(N)$ |
Draw a single straight line. Each element is visited once, and Set operations (add/check/clear) are $O(1)$ on average. |
Storing all possible subarray indices in a 2D list. $O(N^2)$. |
A Hash Set of prefix sums. $O(N)$ space. |
| 1547 |
Minimum Cost to Cut a Stick |
Try every permutation of cut orders. For 100 cuts, this is 100!, which is more than the atoms in the universe. |
Permutation Explosion |
Draw a stick. Draw 3 cut points. Branch into 3! = 6 paths. Now imagine 100 cut points. The tree cannot be drawn; it is a black hole of complexity. |
Dynamic Programming (MCM Variant) |
The Recursive Stick Splitter |
Sort the cut positions and add the stick ends (0 and L). Define `dp(i, j)` as the min cost to cut a stick between `cuts[i]` and `cuts[j]`. To solve `dp(i, j)`, try every cut `k` between them: `cost = (cuts[j] - cuts[i]) + dp(i, k) + dp(k, j)`. |
Draw a stick. Pick a cut point in the middle. The stick "snaps" into two smaller sub-problems. Draw arrows pointing to these two new sticks. Use a 2D table to store the cost of every possible `(left_cut, right_cut)` pair. |
Cubic DP $O(M^3)$ (M = # of cuts) |
Draw a 2D matrix of size M x M. To fill one cell, draw a horizontal line representing the loop through all possible "middle" cuts `k`. |
Zero-memoization recursion with repeated subproblems. |
A 2D DP table of size M x M. $O(M^2)$ space. |
| 1548 |
The Most Similar Path in a Graph (Premium) |
Explore every possible path of length L in the graph using DFS. $O(V^L)$. |
Exponential Path Web |
Draw a graph. From a starting node, draw every possible path of length 1, 2, 3... The number of paths grows exponentially with the length of the target string. |
Dynamic Programming (Viterbi-like) |
The Multi-Stage State Grid |
Define `dp[i][v]` as the minimum edit distance for a path of length `i` ending at node `v`. To calculate `dp[i][v]`, look at all neighbors `u` of `v` from the previous step `dp[i-1][u]`. |
Draw the target path as a sequence of stages. For each stage, draw all graph nodes. Draw arrows from nodes in stage 1 to their neighbors in stage 2. Each arrow carries a "cost" (0 if name matches, 1 if not). |
Graph-Breadth DP $O(L \cdot E)$ |
Draw a 2D grid (Nodes x Path Length). For each column, you only look at the edges (E) of the graph. |
Storing every path in a list of lists. |
A 2D DP table (L x V) and a "parent" table to reconstruct the path. $O(L \cdot V)$ space. |
| 1549 |
The Most Recent Orders for Each Product (SQL) |
Join Products and Orders, then use a `WHERE order_date = (SELECT MAX...)` subquery that runs for every single row. $O(N^2)$. |
Correlated Subquery Loop |
Draw a table. For every row, draw a separate "Searcher" that scans the entire table again to find the max date for that product. |
Window Function (RANK) |
The Product-Date Ranker |
Use `RANK() OVER (PARTITION BY product_id ORDER BY order_date DESC)`. This labels the most recent orders as "1". Filter for `rank = 1`. This is faster than `MAX()` because it handles ties automatically. |
Draw a table sorted by Product and Date. Draw brackets around each product. Within each bracket, write "1" next to the latest date(s), "2" next to the second latest, etc. |
Sorted Partition Scan $O(N \log N)$ |
Draw a single sorting flow into a partitioner. The database handles the ranking in one efficient pass. |
Application-side memory for manual filtering. |
Database internal sort buffer. $O(N)$ space. |
| 1550 |
Three Consecutive Odds |
Generate all subarrays of length 3 and check if each element is odd. $O(N)$. |
Sliding Window Triplets |
Draw the array. Draw a box covering 3 elements. Slide it one by one, checking if the numbers inside are all odd. |
Linear Scan / Counter |
The Odd-Streak Counter |
Iterate once. If the number is odd, increment a `count`. If even, reset `count` to 0. If `count == 3`, return true. |
Draw the array. Below it, write a 0. Every time you see an odd number, erase and write a +1. If you see an even number, slam it back to 0. If it hits 3, you win. |
Pure Linear Scan $O(N)$ |
Draw a single straight line. Each element is checked exactly once. |
Creating a list of booleans for every number. $O(N)$. |
A single integer variable `count`. $O(1)$ space. |
| 1551 |
Minimum Operations to Make Array Equal |
Generate the array of size N where `arr[i] = (2 * i) + 1`. Calculate the target value (average). Then, loop through the first half of the array and sum the differences. $O(N)$. |
Arithmetic Series Summation $O(N)$ |
Draw an array of odd numbers. Draw a horizontal line through the middle (average). Draw vertical arrows showing how much each number must "move" to hit the line. |
Math (Arithmetic Progression) |
The Symmetrical Balance |
Recognize that for an array of size N, the operations needed are the sum of an arithmetic progression. For even N, it's 1+3+5...+(N-1). For odd N, it's 2+4+6...+(N-1). Formula: n^2 / 4. |
Draw a staircase of blocks. Draw a horizontal line cutting through the middle of the staircase. The "extra" blocks above the line perfectly fill the "gaps" below the line. |
Constant Time Calculation $O(1)$ |
Draw a single point. The solution is a single mathematical expression evaluated instantly. |
A physical array of size N in memory. $O(N)$. |
Pure variables. $O(1)$ space. |
| 1552 |
Magnetic Force Between Two Balls |
Generate all combinations of placing M balls in N positions and calculate the minimum distance for each. $O(N \text{Choose} M)$. |
Combinatorial Explosion $O(C(N, M)$) |
Draw N dots. Try to pick M dots. Draw all possible ways to pick those M dots. The number of paths is massive. |
Binary Search on Answer |
The "Can-Place" Feasibility Bar |
Binary search for the *distance* (result). For a given distance `d`, greedily place balls to see if you can fit M of them. If yes, try a larger `d`; if no, try a smaller `d`. |
Draw a sorted number line of positions. Draw a ruler of length `d`. Place the first ball at index 0. Slide the ruler: place the next ball only where the ruler ends or further. Count balls. |
Search-Space Reduction $O(N \log(\text{Max}_\text{Dist})$) |
Draw a range [1, 10^9]. Draw a line being chopped in half at each step. At each chop, draw a linear scan across the array (N). |
Storing every possible combination. |
A sorted array of positions. $O(1)$ extra space beyond sorting. |
| 1553 |
Minimum Number of Days to Eat N Oranges |
Simple recursion: `1 + min(eat(n-1), eat(n/2), eat(n/3))`. This explores many redundant paths. $O(3^N)$. |
Expanding 3-way Decision Tree |
Draw a root N. Draw three branches (-1, /2, /3). Repeat. The tree becomes incredibly wide almost immediately. |
DP + BFS / Optimized Recursion |
The Greedy Jump BFS |
Instead of subtracting 1 orange at a time, calculate the days to reach the next multiple of 2 or 3: `1 + (n % 2) + eat(n / 2)` and `1 + (n % 3) + eat(n / 3)`. Use a map for memoization. |
Draw a node N. Draw only TWO branches that "jump" to `n/2` and `n/3`. Write the cost of the "jump" (1 + remainder) on the edge. This forces the tree to shrink logarithmically. |
Logarithmic State Space $O(\log^2 N)$ |
Draw a tree where each node has only two children and the value of the children is half or a third of the parent. The tree is very deep but very thin. |
A recursion stack that goes N levels deep. |
A Hash Map (Memo table). Draw a table with key-value pairs where keys are only the specific values of N reached by division. $O(\log^2 N)$ space. |
| 1554 |
Strings Differ by One Character |
Compare every pair of strings. For each pair, iterate through all characters to count differences. $O(N^2 \cdot L)$. |
Nested Loop Matrix $O(N^2 \cdot L)$ |
Draw a grid of strings. Draw arrows connecting every string to every other string. For each arrow, draw a sub-scanner checking characters. |
Hashing / Rolling Hash |
The Masked Hash Set |
For each string, calculate its hash. Then, for each character position `j`, calculate what the hash would be if char `j` were removed (the "masked hash"). Store these in a Set. If a collision occurs, a match exists. |
Draw a string "abc". Draw three "ghost" versions: "*bc", "a*c", "ab*". Calculate a numeric ID for each ghost and drop it into a bucket. If a bucket already has an ID, you found the pair. |
Linear Scan with Character Masking $O(N \cdot L)$ |
Draw a 2D grid (Strings x Length). Draw an arrow sweeping every cell exactly once to generate and check hashes. |
Storing all string pairs. |
A Hash Set of masked hashes. $O(N \cdot L)$ space. |
| 1555 |
Bank Account Summary II (SQL) |
Select all users, and for each user, run a subquery that sums their transactions and then filters. $O(U \cdot T)$. |
Correlated Subquery Scan |
Draw a user list. For every user, draw a magnifying glass that scans the entire transaction table. Redundant and slow. |
JOIN + GROUP BY + HAVING |
The Aggregate Funnel |
Join the `Users` and `Transactions` tables on `account`. Group by the user's name. Use `SUM(amount)` and filter using `HAVING sum > 10000`. |
Draw two tables. Draw lines connecting account IDs. Group the connected rows into "buckets" by name. Draw a scale under each bucket; only keep those weighing over 10,000. |
Hash Aggregate Scan $O(N)$ |
Draw a pipeline where data flows through a join and into a hash table for grouping, finishing with a single filter pass. |
Application-side memory for calculating sums manually. |
Database internal buffer for grouping. $O(U)$ space for the result set. |
| 1556 |
Thousand Separator |
Convert number to string, then use a loop to insert '.' every 3 characters from the left. $O(N^2)$ due to frequent string re-allocations/shifts. |
Shifting Block Visualization |
Draw a string of numbers. Every 3 steps, draw an arrow pushing the entire remaining string to the right to make room for a dot. High friction, high cost. |
Reverse Traversal / String Builder |
The Backwards Ticker |
Iterate from the end of the string. Maintain a `count`. Every 3 characters, append a dot *unless* you're at the very beginning. Reverse the result at the end. |
Write the number: "1234567". Start at '7'. Draw a tally: 1, 2, 3... Dot! 1, 2, 3... Dot! Draw the result building up from right to left in a single pass. |
Linear Pass $O(N)$ |
Draw a single straight horizontal line. Each digit is visited exactly once. |
Multiple intermediate string copies. $O(N^2)$ space in some languages. |
A single StringBuilder or character array. $O(N)$ space. |
| 1557 |
Minimum Number of Vertices to Reach All Nodes |
Run a full DFS/BFS starting from every single node to see which ones can cover the entire graph. $O(V \cdot (V + E)$). |
Massive Overlapping Search Trees |
Draw a graph. From node A, draw a shaded area for its reach. From node B, draw another. Many areas will overlap, showing redundant computation. |
Graph Theory (In-Degree Zero) |
The Source Identification |
In a Directed Acyclic Graph (DAG), any node with an in-degree of 0 *must* be part of the result, as no other node can reach it. Any node with in-degree > 0 can be reached by a source. |
Draw the nodes. For every edge `u -> v`, draw a red "X" on node `v` (the target). After processing all edges, circle the nodes that don't have an "X". These are your sources. |
Edge List Scan $O(E)$ |
Draw a line representing the edge list. Each edge is processed once to update a boolean array. |
Storing full adjacency lists and multiple "visited" sets. $O(V + E)$. |
A single boolean array of size V. $O(V)$ space. |
| 1558 |
Minimum Numbers of Function Calls to Make Target Array |
Reverse simulation: repeatedly subtract 1 from elements until they are even, then divide everything by 2. $O(N \\text{cdot Max}_\text{Val})$. |
Iterative Step-by-Step Drain |
Draw the target array. Draw arrows showing every single decrement operation until you can finally draw one "divide by 2" arrow for the whole group. Slow and tedious. |
Greedy / Bit Manipulation |
Bit-Level Deconstruction |
Every "1" in the binary representation of a number represents an "add 1" operation. The number of "multiply by 2" operations is determined by the most significant bit (MSB) of the largest number in the array. |
Draw the largest number in binary. Count the '1's (increments). Count the total number of bits minus 1 (doubles). Do this for all numbers, but only count the "doubles" once for the whole array. |
Linear Bit-Check $O(N \cdot \log(\text{Max}_\text{Val})$) |
Draw a line of length N. For each number, draw a small tree of height 32 (bits). |
Multiple copies of the array during simulation. |
Standard integer variables for `max_doubles` and `total_increments`. $O(1)$ space. |
| 1559 |
Detect Cycles in 2D Grid |
Run BFS/DFS from every cell. If you ever hit a "visited" cell that isn't your direct parent, a cycle exists. $O(R \cdot C)$ with potential high constant factor. |
Grid-based Ripple Expansion |
Draw a 2D grid. Color a path of same characters. If the path "bites its own tail" (connects to a non-parent visited cell), highlight the cycle. |
DFS + Backtracking (Parent Tracking) |
The Breadcrumb Trail |
Standard DFS but pass the `(prev_r, prev_c)` coordinates to the next call. This prevents you from immediately moving back to where you just came from and incorrectly calling it a "cycle." |
Draw the grid. Draw a line moving through cells of 'A'. Mark each cell with a 'V'. If your next step hits a 'V' that isn't the cell you just left, draw a circle around the connection. |
Single Grid Pass $O(R \cdot C)$ |
Draw a rectangle. A single snake-like arrow moves through it, visiting each cell at most once. |
Massive `visited` matrix and deep recursion stack. |
A 2D boolean `visited` array. $O(R \cdot C)$ space. |
| 1560 |
Most Visited Sector in a Circular Track |
Simulate every single lap and every single sector visit, incrementing a frequency array. $O(\text{Laps} \cdot N)$. |
Circular Lap Counter |
Draw a circle. Draw an arrow spinning around the circle multiple times, leaving a tally mark on every sector it passes. |
Math (Observation) |
Start-End Range Selection |
Because it's a circular track, only the path from the *first* sector to the *last* sector matters. Intermediate full laps visit every sector equally. If `start <= end`, the answer is `[start...end]`. If `start > end`, the answer is `[1...end] + [start...n]`. |
Draw a circle with 1 at the top. Mark the 'Start' and 'End' points. Color the path from Start to End clockwise. Those colored numbers are the sectors that were visited one extra time. |
Constant/Linear Range Logic $O(N)$ |
Draw a single straight line from 1 to N. Highlight one or two segments of that line based on the start/end values. |
A frequency array of size N and full simulation variables. |
A single list to hold the result range. $O(N)$ space. |
| 1561 |
Maximum Number of Coins You Can Get |
Try every possible triplet combination (A, B, C) to find the grouping that maximizes your total (the second largest in each triplet). $O(N!)$. |
Factorial Permutation Web |
Draw a set of piles. Draw arrows branching out showing every possible way to pick 3 piles at a time. The tree width explodes instantly. |
Greedy / Sorting |
The Sandwich Selection |
Sort the piles. Alice takes the largest, you take the second largest, and Bob takes the absolute smallest. This ensures you always get the best "middle" value while Bob gets the "trash." |
Draw a sorted line of numbers. Mark 'A' at the rightmost, 'Me' next to it, and 'B' at the leftmost. Move the 'A/Me' pair inward and the 'B' pointer rightward. Circle the 'Me' values. |
Sorting Bottleneck $O(N \log N)$ |
Draw a standard Merge Sort tree height \log N followed by a single linear line representing the N/3 iterations. |
Massive recursive stack for triplet combinations. |
Array blocks shifting in-place. $O(1)$ extra space if using in-place sort. |
| 1562 |
Find Latest Group of Size M |
For every step i, update the grid, then scan the entire grid to count contiguous groups of 1s of size M. $O(N^2)$. |
Redundant Scanning Timeline |
Draw a binary string that changes at each step. Below each state, draw a full scan arrow from left-to-right counting clusters. N rows of length N. |
Union-Find or Boundary Mapping |
Boundary Length Propagation |
Maintain an array `count` where `count[i]` is the length of the 1-group containing index i. When a 1 is added at x, only update the *outermost boundaries* of the new merged group. |
Draw an array of 0s. When you put a '1' at index i, look at i-1 and i+1. If they are part of groups of size L and R, draw a single bridge connecting them. Update only the leftmost and rightmost index with L+R+1. |
Direct Map Update $O(N)$ |
Draw a single straight line. For each element, draw two small "look-aside" arrows to neighbors and one tally update. No nested loops. |
A new copy of the array for every single bit flip. |
An integer array `length` of size N and a `frequency` map. $O(N)$ space. |
| 1563 |
Stone Game V |
Recursive minimax. Try splitting the array at every possible index i, following the rule that the smaller sum is kept. $O(2^N)$. |
Exponential Splitting Tree |
Draw a block. Split it at pos 1, 2, 3... For each split, draw a new tree. The branching factor is N and the depth is N. |
Dynamic Programming + Prefix Sums |
The Range-Interval Matrix |
Use dp[i][j] to store the max score for stones from index i to j. Use prefix sums to calculate the sum of any range in $O(1)$. Optimize the split search by observing sum properties. |
Draw a 2D N \times N grid. To fill a cell (i, j), draw a vertical line representing a scan through all possible split points k. Use a prefix sum array on the side to quickly "weigh" the left and right halves. |
Cubic DP $O(N^3)$ |
Draw a triangular matrix. Each cell's complexity is $O(\\text{text}{\text{length of interval}})$. The volume of the total "work" is a pyramid. |
Massive recursive call stack with redundant string/array slices. |
A 2D N \times N integer table. $O(N^2)$ space. |
| 1564 |
Put Boxes Into the Warehouse I |
For every box, try to push it as far as possible, checking every warehouse room it passes through. $O(B \cdot W)$. |
Nested Scanning Grid |
Draw boxes on the left and a warehouse on the right. For each box, trace a line through the warehouse until it hits a "low ceiling" or another box. |
Greedy / Preprocessing |
Ceiling Normalization |
A box can only be as tall as the *minimum* height it passed through. Pre-process the warehouse so each room's height is `min(current, previous)`. Sort boxes and fit them greedily from right to left. |
Draw the warehouse as a jagged ceiling. Draw a "steamroller" smoothing it out from left to right (non-increasing). Then, match the smallest boxes into the furthest available normalized slots. |
Sorting + Linear Scan $O(B \log B + W)$ |
Draw a sorting tree for boxes, followed by two parallel lines (Boxes and Warehouse) with a single pointer on each. |
Redundant simulation variables. |
The original warehouse array (modified in-place) and the sorted box array. $O(1)$ extra space beyond sorting. |
| 1565 |
Unique Orders and Customers Per Month (SQL) |
Fetch all orders, parse the month in your code, use a Set to find unique customers per month, and count orders manually. $O(N)$. |
Manual Tally Sheet |
Draw a database. Draw an arrow pulling every row out into a "Sorting Room" where you manually write things on sticky notes. |
SQL GROUP BY + COUNT(DISTINCT) |
The Multi-Pivot Table |
Group by the month (extracted using `DATE_FORMAT`). For each group, count total `order_id` and use `COUNT(DISTINCT customer_id)` to handle the unique requirement. Filter by `invoice > 20`. |
Draw a table. Circle the rows where price > 20. Group the circled rows into boxes by month. Inside each box, count the items and count the *unique* names. |
Index-Optimized Aggregation $O(N \log N)$ |
Draw a single flow line into a hash-aggregation node. The database performs the grouping and distinct-counting in a highly optimized internal pass. |
Application-side memory for storing large sets of customer IDs. |
Database internal hash buffer. $O(M)$ where M is the number of months. |
| 1566 |
Detect Pattern of Length M Repeated K or More Times |
Check every possible starting index i. For each i, slice the pattern of length m and check if the next k-1 blocks are identical. $O(N \cdot M \cdot K)$. |
Redundant String Comparison Grid |
Draw a string. For index 0, draw k identical brackets. Shift to index 1, draw another k brackets. The overlapping brackets create a massive mess. |
Single Pass / Offset Comparison |
The Parallel Offset Scanner |
If a pattern of length m repeats, then arr[i] must equal arr[i+m]. Keep a counter of how many consecutive indices satisfy this. If the counter reaches (k-1) \cdot m, a pattern is found. |
Draw an array. Draw two pointers: i and i+m. Slide them together. Every time they match, draw a tick mark. If you get enough ticks in a row, you've found the repeat. |
Linear Scan $O(N)$ |
Draw one straight line across the array. Each element is looked at once relative to its offset. No nested loops. |
Storing multiple string slices in a list. $O(N \cdot M)$. |
Two pointer variables and one integer counter. $O(1)$ space. |
| 1567 |
Maximum Length of Subarray With Positive Product |
Generate all N^2 subarrays. For each, multiply all elements and check if the product is positive. $O(N^3)$ or $O(N^2)$ with prefix products. |
Nested Triangle Expansion |
Draw a 2D matrix where (i, j) is the product of arr[i \dots j]. You must fill the whole upper triangle of the matrix. |
Dynamic Programming / Greedy State |
Dual Tracking (Positive/Negative Lengths) |
At each index, track two values: `pos_len` (max length ending here with positive product) and `neg_len` (max length ending here with negative product). Switch them when you hit a negative number. Reset on zero. |
Draw the array. Below it, draw two rows labeled '+' and '-'. When you hit a positive, increment the '+' row. When you hit a negative, cross-swap the values from the previous step and add 1. |
Linear State Transition $O(N)$ |
Draw a single straight line. At each step, show two small boxes updating based on the previous two boxes. |
A 2D matrix of products. $O(N^2)$. |
Two integer variables: `pos` and `neg`. $O(1)$ space. |
| 1568 |
Minimum Number of Days to Disconnect Island |
Try removing every combination of 1, 2, 3... pixels and run BFS/DFS each time to check if the island is disconnected. $O(2^N)$. |
Exponential Removal Tree |
Draw the grid. Branch out for every single pixel: "Remove" or "Keep." The tree depth is the number of '1's in the grid. |
Graph Theory (Articulation Points / 2-Day Rule) |
The Critical Bridge Identifier |
Fact: You never need more than 2 days (isolate a corner). 1. Check if already disconnected (0 days). 2. Use Tarjan’s or check every single '1' removal (1 day). 3. Otherwise, 2 days. |
Draw the grid. Run a BFS to count islands. Then, circle every '1' and pretend it's a '0' one by one, re-running BFS. If any single "circle" splits the island, answer is 1. |
Grid-Iterative DFS $O((R \cdot C)$^2) |
Draw a square. For every pixel in the square, draw a full "scan" arrow representing the connectivity check. |
Queue/Stack for all combinations. |
Standard DFS recursion stack and a visited matrix. $O(R \cdot C)$ space. |
| 1569 |
Number of Ways to Reorder Array to Get Same BST |
Generate all N! permutations, build a BST for each, and compare the structures. $O(N! \cdot N)$. |
Permutation Tree Explosion |
Draw N dots. Branch out N! ways. For each leaf, draw a full tree structure. Impossible to fit on paper. |
Divide & Conquer + Combinatorics (Pascal's Triangle) |
The Subtree Interleaving Viz |
The first element is the root. All smaller elements go to the left subtree, larger to the right. The number of ways is `(WaysLeft * WaysRight * combinations(total-1, left_size))`. Recurse. |
Draw the root. Draw two arrows to "Left" and "Right" buckets. Write the size of each bucket. Use the formula: \binom{L+R}{L} to show how many ways the two sequences can interleave. |
Recursive Partitioning $O(N^2)$ |
Draw a tree where each node shows the "nCr" calculation. Pascal's triangle lookup is $O(1)$ after $O(N^2)$ precomputation. |
Storing every permutation. |
Recursion stack and a precomputed Pascal's Triangle (2D array). $O(N^2)$ space. |
| 1570 |
Dot Product of Two Sparse Vectors |
Multiply the two full vectors index by index. $O(N)$. Even if most are zeros, you still waste time on 0 \cdot 0. |
Linear Redundant Multiplication |
Draw two long lines of length 10^6. Most are zeros. Draw arrows connecting every pair, even if they result in zero. |
Two Pointers on Compressed Pairs |
The Parallel Index Matcher |
Store only `(index, value)` pairs in a list. Use two pointers to iterate through both lists. Only multiply when the indices match. If idx1 < idx2, increment pointer 1. |
Draw two short lists: `[(2, 5), (10, 8)]` and `[(2, 3), (12, 1)]`. Align them vertically. Only draw a circle around the matching index 2. Ignore the rest. |
Intersection Linear Scan $O(L_1 + L_2)$ |
Draw two short lines representing the non-zero elements. The pointers move linearly through these condensed lists. |
Two full arrays of size N. $O(N)$. |
Two compressed lists of size L (non-zero count). $O(L)$ space. |
| 1571 |
Warehouse Manager (SQL) |
Join `Warehouse` and `Products`. For every row, calculate `Width * Length * Height` in the application layer and then group by warehouse. $O(N \cdot M)$. |
Row-by-Row Multiplication Grid |
Draw two tables. For every row in Table A, draw an arrow to Table B. Inside the arrow, draw a tiny 3D box being calculated before it lands in a "Warehouse Bin." |
SQL Aggregation / JOIN |
The Volumetric Funnel |
Perform a `JOIN` on `product_id`. Multiply the three dimensions to get the unit volume, multiply by `units`, and use `SUM()` with `GROUP BY` warehouse name. |
Draw the tables joined. For each warehouse, draw a single "Volume Bucket." Pour all the calculated product volumes into it. The final level in the bucket is the result. |
Hash/Merge Join Aggregation $O(N)$ |
Draw a pipeline. One pass through the data performs the join and the sum simultaneously. |
Application-side cache for all product dimensions. $O(P)$. |
Zero application memory. DB uses internal aggregate buffer. $O(W)$ space. |
| 1572 |
Matrix Diagonal Sum |
Nested loops iterating over the entire N \times N matrix. Check if `i == j` or `i + j == n - 1` and add to sum. $O(N^2)$. |
Full Grid Scan $O(N^2)$ |
Draw a square grid. Draw a horizontal arrow for every row. Highlight only the diagonal elements inside each scan. |
Single Pass / Linear Indexing |
The X-Symmetry Trace |
Iterate once from `i = 0` to `n-1`. Add `mat[i][i]` and `mat[i][n-1-i]`. If `n` is odd, subtract the middle element once (as it's added twice). |
Draw the square. Draw a giant "X" across it. Number the "X" nodes from 1 to N. Note how each "i" maps to exactly two spots on the "X". |
Linear Diagonal Scan $O(N)$ |
Draw a single straight line of length N. Each step represents one jump directly to the diagonal indices. |
Storing a copy of the diagonals in a list. $O(N)$. |
A single `total_sum` integer variable. $O(1)$ space. |
| 1573 |
Number of Ways to Split a String |
Try every possible pair of split points (i, j) and check if the count of '1's in the three resulting substrings is equal. $O(N^3)$ or $O(N^2)$. |
Split-Point Combination Grid |
Draw a string. Draw two vertical lines at every possible pair of gaps. The number of combinations is \binom{N-1}{2}. |
Combinatorics / Gap Counting |
The "Gap Multiplication" Viz |
Count total '1's. If not divisible by 3, return 0. If total is 0, use \binom{N-1}{2}. Otherwise, find the size of the gaps of '0's between the 1st/2nd third and the 2nd/3rd third. Result is `(gap1 + 1) * (gap2 + 1)`. |
Draw 3 groups of '1's. Circle the clusters of '0's between group 1 and 2, and between 2 and 3. Write "Choices" under each circle. Multiply the choice counts. |
Three-Pass Linear Scan $O(N)$ |
Draw a single straight line. Mark the locations of the "Split-Ready" zones. No nested operations. |
Generating all split substrings. $O(N^2)$. |
A list of indices for '1's or just a few pointer variables. $O(1)$ extra space if not storing indices. |
| 1574 |
Shortest Subarray to be Removed to Make Array Sorted |
Try removing every possible subarray [i, j] and check if the remaining array is non-decreasing. $O(N^3)$. |
Subarray Deletion Tree |
Draw an array. Cross out a section. Scan the rest. Repeat for every possible "cross-out" section. Massive redundant work. |
Two Pointers (Prefix/Suffix) |
The Bridge Connection Viz |
1. Find the longest sorted prefix and longest sorted suffix. 2. You must remove everything in between. 3. Try to "bridge" them by moving a pointer at the end of the prefix and a pointer at the start of the suffix to see if they can connect. |
Draw two sorted segments at the edges. Draw a "gap" in the middle. Move a left finger across the prefix and a right finger across the suffix. Draw a dotted line when `left_val <= right_val`. Record the minimum gap length. |
Two-Pointer Convergence $O(N)$ |
Draw two parallel lines (Prefix/Suffix). Draw a single arrow connecting them that "slides" forward. Total work is just 2N. |
Storing all valid remaining arrays. $O(N^2)$. |
Two pointer variables: `left` and `right`. $O(1)$ space. |
| 1575 |
Count All Possible Routes |
DFS starting from `start` to all other locations, subtracting fuel based on distance. If you reach `finish`, count it and *keep going* if fuel remains. $O(N^{\text{Fuel}})$. |
Exploding Fuel-Decision Tree |
Draw a location. Branch out N-1 times (one for each other city). The fuel decreases. Each node repeats this. The tree depth is huge. |
Dynamic Programming (State: City x Fuel) |
The Fuel-Depletion Matrix |
Define `dp[city][fuel]` as the number of ways to reach `finish` from `city` with `fuel` remaining. Since fuel only decreases, this is a Directed Acyclic Graph (DAG) state space. |
Draw a grid where rows are Cities and columns are Fuel levels. To fill a cell (C, F), draw arrows from all other cities C' where F + dist(C, C') was the previous state. |
State-Space Product $O(N^2 \cdot \\text{text}{\text{Fuel}})$ |
Draw a 2D table of size N \times \text{Fuel}. For each of the N \cdot \text{Fuel} cells, you perform N additions. |
Massive recursive call stack with redundant state paths. |
A 2D DP table/Memoization map. $O(N \cdot \\text{text}{\text{Fuel}})$ space. |
| 1576 |
Replace All ?'s to Avoid Consecutive Repeating Characters |
Try all 26^Q combinations for Q question marks and check each full string for validity. $O(26^Q)$. |
Exponential Substitution Tree |
Draw a string with '?' at index 1 and 3. Branch out 26 times for the first '?', then 26 for the second. The tree width is huge. |
Greedy / Linear Scan |
The Neighbor-Exclusion Check |
Iterate through the string. When you hit '?', check the characters at i-1 and i+1. Pick the first letter ('a', 'b', or 'c') that doesn't match either neighbor. |
Draw the string. When you reach '?', draw two small arrows to the left and right characters. Cross out the letters those neighbors use. Write the first available letter in the box. |
Linear Scan $O(N)$ |
Draw a single straight line. At each index, show a maximum of 3 character checks. Constant work per index. |
Storing every possible generated string. $O(N \cdot 26^Q)$. |
Converting the string to a character array. $O(N)$ space. |
| 1577 |
Number of Ways Where Square of One Number Equals Product of Two Numbers |
For every number in array 1, calculate its square. Then, use nested loops to find every pair in array 2 and check the product. Repeat for the other direction. $O(N \cdot M^2 + M \cdot N^2)$. |
Cubic Nested Grid Scan |
Draw array 1. For each element, draw a 2D matrix representing all pairs in array 2. Highlight the matching products. Massive redundancy. |
Hash Map / Frequency Counting |
The Square-to-Pair Map Matcher |
1. Count frequencies of all numbers in both arrays. 2. For each array, calculate squares. 3. For the other array, iterate through pairs in the frequency map to find products that match the square. |
Draw two frequency tables. Draw a square (e.g., 10^2 = 100). Now look at the other table. Find pairs like (2, 50) or (4, 25). Multiply their frequencies and add to total. |
Frequency Pair Scan $O(N^2 + M^2)$ |
Draw two separate grids for calculating all possible products in each array. The work is proportional to the number of *unique* product combinations. |
Storing every pair explicitly. $O(N^2)$. |
Two frequency Hash Maps. $O(N + M)$ space. |
| 1578 |
Minimum Time to Make Rope Colorful |
Backtracking: for every consecutive pair of same-colored balloons, try deleting either the left or the right and recurse to find the minimum total cost. $O(2^N)$. |
Decision-Binary Tree |
Draw a rope. For every pair of same colors, branch out: "Delete 1st" or "Delete 2nd". Tree depth is N. |
Greedy / Two Pointers |
The "Keep the Maximum" Rule |
Whenever you encounter a group of consecutive balloons with the same color, you must remove all but one. To minimize cost, you keep the one with the *highest* cost and remove the rest. |
Draw a row of same-colored balloons. Write their costs underneath. Circle the highest cost. Cross out all other costs in that group and add them to a "Total Cost" box. |
One-Pass Linear $O(N)$ |
Draw a single horizontal line. When you hit a sequence, you only do one scan to find the max and the sum. |
Massive recursive stack for every pair deletion. $O(N)$. |
A few pointer variables and a `total_cost` integer. $O(1)$ space. |
| 1579 |
Remove Max Number of Edges to Keep Graph Fully Traversable |
Try removing every possible subset of edges and run BFS/DFS for both Alice and Bob to check connectivity. $O(2^E \cdot (V+E)$). |
Exponential Edge-Subset Tree |
Draw a graph. Branch out for every edge: "Keep" or "Discard". For each leaf, run two separate connectivity checks. |
Union Find (DSU) / Greedy |
The Common-Edge Priority Viz |
1. Process Type 3 edges (Alice & Bob) first. Use DSU to connect nodes. 2. Then, independently process Type 1 (Alice) and Type 2 (Bob) using separate DSU states. 3. If an edge connects two already-connected nodes, discard it. |
Draw two blank graphs (Alice's and Bob's). Pick Type 3 edges first. Draw them on both graphs. If they merge components, count as "Used". Then draw Alice's specific edges only on her graph and Bob's only on his. |
Union-Find with Path Compression $O(E \cdot \\text{alpha}(V)$) |
Draw a single scan of the edge list. Above each edge, draw a tiny "Find/Union" tree operation (\alpha(V) is nearly constant). |
Storing every subset of edges in memory. |
Two DSU integer arrays (parent/rank) of size V. $O(V)$ space. |
| 1580 |
Put Boxes Into the Warehouse II (Premium) |
Try every permutation of boxes and try to fit them from either the left or the right side of the warehouse. $O(B! \cdot 2^B)$. |
Factorial Simulation Tree |
Draw boxes. Branch out for every possible sequence. For each box in the sequence, branch again for "Enter from Left" or "Enter from Right". |
Greedy / Two Pointers / Preprocessing |
The Bi-Directional Ceiling Normalization |
A box can enter from either side. Preprocess the warehouse so each room's height is the *maximum* of its "left-limited" height and "right-limited" height. Then sort boxes and use two pointers to fit them from the edges. |
Draw the warehouse. From the left, draw a "Low-Ceiling" line. From the right, draw another. The effective height of a room is the *better* of the two. Match the smallest boxes to the tightest effective spots. |
Sorting + Linear Scan $O(B \log B + W)$ |
Draw a sorting tree for boxes and a single linear pass for the warehouse preprocessing, followed by two pointers meeting in the middle. |
Storing all fitment combinations. |
Modified warehouse array and sorted box list. $O(1)$ extra space beyond sorting. |
| 1581 |
Customer Who Visited but Did Not Make Any Transactions (SQL) |
For every visit record, scan the entire transactions table to see if a matching `visit_id` exists. $O(V \cdot T)$. |
Nested Loop Scanning Grid |
Draw a list of visits. For each visit, draw a search arrow that scans every single row of the transaction table. A massive amount of redundant effort. |
LEFT JOIN / WHERE IS NULL |
The Exclusion Funnel |
Perform a `LEFT JOIN` on `visit_id`. Any visit that doesn't have a transaction will result in a `NULL` for the transaction columns. Filter for these `NULL`s and group by customer. |
Draw two overlapping circles (Visits and Transactions). Shade the area in the Visit circle that *doesn't* overlap with Transactions. Group the customer IDs in that shaded area and count them. |
Hash/Merge Join Aggregation $O(V + T)$ |
Draw a single flow line where both tables are hashed and compared in a single internal pass. |
Application-side tracking of all IDs in memory. |
Zero application memory; DB handles grouping in its internal buffer. $O(V)$ space. |
| 1582 |
Special Positions in a Binary Matrix |
For every cell `(r, c)` that contains a 1, scan the entire row `r` and entire column `c` to count 1s. $O(R \cdot C \cdot (R+C)$). |
Cubic Intersection Scan |
Draw a 2D grid. For every '1', draw a horizontal and a vertical laser line. If a laser hits another '1', the cell isn't "special." Redundant laser fires. |
Preprocessing (Row/Col Sums) |
The Coordinate Projection Viz |
Pre-calculate the sum of 1s in every row and every column. A cell `(r, c)` is special if `mat[r][c] == 1`, `row_sum[r] == 1`, and `col_sum[c] == 1`. |
Draw the grid. To the right of each row, write the row sum. Below each column, write the column sum. Circle the '1's where the corresponding row and column sums are both exactly 1. |
Single Grid Pass $O(R \cdot C)$ |
Draw a rectangle. One pass to fill sum arrays, one pass to check cells. Strictly linear to grid size. |
Storing full lists of 1-coordinates. $O(R \cdot C)$. |
Two integer arrays: `rowCount` of size R and `colCount` of size C. $O(R + C)$ space. |
| 1583 |
Count Unhappy Friends |
For every pair (x, y), iterate through all other pairs (u, v) and check the preference list conditions for both x and y. $O(N^2)$. |
Quadratic Comparison Matrix |
Draw N dots. For every connected pair, draw arrows to every other dot to check for "jealousy" based on preference indices. A tangled web. |
Rank Mapping (Hash Map / 2D Array) |
The Preference Ranker |
Pre-calculate the rank (index) of each friend in everyone's preference list: `rank[i][j]` is how much friend i likes friend j. Then, for any pair (x, y), iterate through friends u that x likes *more* than y and check if u also likes x more than their current partner. |
Draw the pairs. For person x, list everyone they like more than their current partner. For each person u in that list, look up their partner v. Check if rank[u][x] < rank[u][v]. If so, x is unhappy. |
Linear Partner Check $O(N^2)$ |
Draw a single pass through the N/2 pairs. For each person, we check at most N people. Overall time is proportional to the size of the preference grid. |
Nested simulation loops. |
A 2D `rank` array of size N \times N. $O(N^2)$ space. |
| 1584 |
Min Cost to Connect All Points |
Generate all possible spanning trees and calculate the total weight of each. $O(\\text{text}{\text{Exponential}})$. |
Factorial Tree Growth |
Draw all points. Draw every possible line between them. Try to find every possible set of lines that connects all points without cycles. The number of trees is massive. |
Graph (Prim's or Kruskal's MST) |
The Greedy Bridge Expansion |
Use Prim’s: Start with one point. Always pick the closest point that isn't connected yet and add it to the set. Use a Min-Heap to quickly find the next closest edge. |
Draw the points. Circle the first point. Find the shortest line from that circle to any outside point. Draw the line and extend the circle. Repeat until all points are inside one giant circle. |
Heap-Optimized Prim's $O(E \log V)$ or $O(V^2)$ |
Draw a line of length V. Above each step, draw a tiny tree height \log V (heap operations). Since the graph is dense (E = V^2), $O(V^2)$ Prim's is actually faster. |
Full edge list or adjacency matrix. $O(V^2)$. |
Min-Heap and `dist` array. $O(V)$ or $O(E)$ space. |
| 1585 |
Check If String Is Transformable With Substring Sort Operations |
Try all possible substring sort operations at every step to see if you can reach the target string. $O(\\text{text}{\text{Exponential}})$. |
Exponential State-Space BFS |
Draw a string. Branch out for every possible substring you could sort. The tree width is N^2 at every level. |
Greedy / Relative Order Tracking |
The "Barrier" Check Viz |
A digit d can move left only if no digit *smaller* than d is in its way. For each occurrence of digit d in the target, check if any digit 0 \dots d-1 appears earlier in the original string's relative queue. |
Write both strings. Use 10 queues to store the indices of each digit 0-9 in the original. For each character in the target, say '3', check the queues of '0', '1', and '2'. If any of their indices are smaller than the current '3' index, '3' is blocked and cannot move left. |
Linear Scan with Constant Multiplier $O(10 \cdot N)$ |
Draw a single straight line for the target string. For each character, draw 10 small "lookups" into the index queues. |
All possible string permutations. |
10 Queues (Lists) to store indices. $O(N)$ space. |
| 1586 |
Binary Search Tree Iterator II (Premium) |
Upon initialization, perform a full In-order traversal and store all nodes in a list. Moving next/prev is just moving a pointer in that list. $O(N)$ init. |
Full Tree Flattening |
Draw a BST. Draw a single long horizontal line below it. Draw arrows from every node dropping down into the line in sorted order. |
Lazy Iteration + Stack/List Cache |
The Controlled Stack Surge |
Only traverse when `next()` is called beyond the cached list. Use a stack to store the "left-most" path. Keep an index to allow `prev()` to move back through the list without re-traversing. |
Draw a BST. Draw a vertical Stack box on the side. Draw a horizontal "Cache List" below. When `next()` is called, show nodes moving from Tree \rightarrow Stack \rightarrow List. For `prev()`, just move a pointer i back on the List. |
Amortized Linear $O(1)$ per call |
Draw a timeline of N calls. Highlight that the total "push/pop" work over all N calls equals the number of nodes. |
A static list of N nodes. $O(N)$. |
A dynamic list plus a stack of height H. $O(N)$ total, but lazy. |
| 1587 |
Bank Account Summary II (SQL) |
Fetch all users. For each user, run a nested scan of the transactions table to calculate their sum. $O(U \cdot T)$. |
Nested Multi-Scanner |
Draw a User list. For every single entry, draw a loop that iterates through the entire Transactions table. Redundancy is highlighted by the repeated scans. |
Hash Aggregation / Index Join |
The Partitioned Accumulator |
Join the tables on Account ID. Use a Hash Map to accumulate sums for each unique account in one pass. Filter results where Sum > 10,000. |
Draw two tables. Draw a "Join Pipe" that merges them. At the end of the pipe, draw several "Buckets" (Accounts). As data flows, it drops into the matching bucket and increments the total. |
Linear Scan $O(U + T)$ |
Draw two parallel lines representing the tables. Show them feeding into a single processing node that outputs the final filtered list. |
Application-side memory for storing all intermediate join results. |
Database internal aggregation buffer. $O(U)$ space. |
| 1588 |
Sum of All Odd Length Subarrays |
Generate every possible odd-length subarray [i, j] using three nested loops and sum the elements. $O(N^3)$. |
Subarray Pyramid Expansion |
Draw the array. Below it, draw all subarrays of length 1, then length 3, then length 5. The overlapping brackets cover the page. |
Combinatorics (Contribution of Each Element) |
The Element Frequency Heatmap |
Calculate how many times arr[i] appears in any odd-length subarray. An element at index i is in ((i+1) \cdot (n-i) + 1) / 2 subarrays. Multiply value by count. |
Draw the array. Below each index, write a multiplier (e.g., i=0 is in 3 subarrays). Draw arrows from the element to all the hypothetical brackets it belongs to. |
Pure Linear Scan $O(N)$ |
Draw a single straight line. Above each node, draw a single math operation box. Total time is N \times $O(1)$. |
Creating N^2 lists of subarrays. $O(N^3)$. |
A single `total_sum` variable. $O(1)$ space. |
| 1589 |
Maximum Sum Obtained of Any Permutation |
For every permutation of the array, calculate the sum of all provided ranges. Find the max. $O(N! \cdot Q \cdot N)$. |
Factorial Range-Sum Web |
Draw the array. Branch out N! ways. For each leaf, draw all Q range brackets and sum them. This is an algorithmic nightmare. |
Difference Array + Greedy (Sweep Line) |
The Overlap Frequency Bar-Graph |
1. Use a difference array to count how many ranges cover each index in $O(Q+N)$. 2. Sort the frequencies. 3. Sort the input array. 4. Assign the largest numbers to the most frequent indices. |
Draw a line of indices. For each range [start, end], write +1 at start and -1 at end+1. Sweep across to get frequencies. Draw a bar chart of frequencies and a bar chart of sorted array values. Match the tallest bars. |
Sorting Bottleneck $O(N \log N + Q)$ |
Draw a linear scan for ranges, followed by a Merge Sort tree height \log N. Total time is dominated by the sort. |
Storing all subarray sums for N! cases. |
An integer array of size N for frequencies. $O(N)$ space. |
| 1590 |
Make Sum Divisible by P |
Try removing every possible subarray [i, j] and check if the sum of the remaining elements is divisible by P. $O(N^2)$. |
Quadratic Subarray Deletion |
Draw an array. Cross out one index, check sum. Cross out two indices, check sum. You will draw N(N+1)/2 cross-out scenarios. |
Prefix Sum + Hash Map (Modular Arithmetic) |
The Target Remainder Tracker |
Calculate total sum mod P (let it be T). We need to find the shortest subarray with sum mod P = T. Iterate with prefix sums S, storing the latest index of each S \pmod P in a Map. Look for (S - T) \pmod P. |
Draw the array and a Hash Map on the side. As you scan, write the current Sum \pmod P in the Map. Draw an arrow from the current index i to a previous index j stored in the Map that satisfies the modular condition. |
Linear Scan with Map Lookups $O(N)$ |
Draw a single straight line. Above each node, draw an arrow pointing to a Map box. $O(1)$ work per node. |
Storing the results of all N^2 sum checks. |
A Hash Map of size P (or N). $O(N)$ space. |
| 1591 |
Strange Printer II |
Try every permutation of colors as the "printing order." For each order, check if the grid can be formed. $O(\\text{text}{\text{Colors}}! \cdot R \cdot C)$. |
Factorial Color Permutation Tree |
Draw all colors present. Branch out for every possible printing sequence. For each sequence, simulate the layers. The tree is impossibly wide. |
Graph Theory (Topological Sort) |
The Color Dependency DAG |
For each color, find its bounding box. If another color exists inside that box, the first color must have been printed before the second. Build a directed graph where an edge A \rightarrow B means A is under B. Check for cycles using Kahn's or DFS. |
Draw a node for each color. Find the min/max rows and columns for Color 1. Scan that rectangle. If you see Color 2, draw an arrow 1 \rightarrow 2. Once all arrows are drawn, try to find a "Sink" node (no outgoing arrows). |
Directed Graph Scan $O(\\text{text}{\text{Colors}}^2 + R \cdot C)$ |
Draw a single pass through the grid (R \cdot C) to find boundaries, followed by a cycle detection scan on max 60 nodes. |
Storing every intermediate grid state. |
An adjacency list for up to 60 colors and boundary arrays. $O(\\text{text}{\text{Colors}}^2)$ space. |
| 1592 |
Rearrange Spaces Between Words |
Extract words and count spaces. Iterate through all possible spacing combinations until the total space count matches the original. $O(\\text{text}{\text{Exponential}})$. |
Space-Partitioning Brute Force |
Draw the words. Try placing 1 space, then 2, then 3 between each until you find a balance. |
String Manipulation / Math |
The Even Distribution Buckets |
Count total spaces and total words. Divide spaces by (words - 1) to get the gap size. Use the remainder for the trailing spaces. Concatenate with a join operation. |
Write words as blocks. Count total empty spaces. Draw "bins" between words. Distribute spaces like cards: 1 for you, 1 for you... The "leftovers" go to a separate bin at the end. |
Two-Pass Linear Scan $O(N)$ |
Draw a single straight line. Pass 1: count spaces/words. Pass 2: Reconstruct string. Total work is 2N. |
Multiple substring allocations and intermediate strings. |
A StringBuilder or character list of length N. $O(N)$ space. |
| 1593 |
Split a String Into the Max Number of Unique Substrings |
Generate every possible way to partition the string and check if all resulting substrings in each partition are unique. $O(2^N)$. |
Partitioning Subset Tree |
Draw the string. At every gap between letters, draw two branches: "Split" or "Don't Split". For each leaf, check uniqueness using a Set. |
Backtracking / Set |
The Greedy Partition with Pruning |
Try splitting at every index from the current start. If the current substring is not in the Set, add it and recurse. If the remaining characters are fewer than the current max count improvement needed, prune the branch. |
Draw the string. Use a vertical bar to represent a split. Move the bar one letter at a time. If the left side is "New", add to a "Seen" list and move to the right side. If you hit a duplicate, backtrack the bar. |
Pruned Backtracking $O(2^N)$ |
Draw a decision tree. Shade the branches that are "pruned" to show reduced work compared to brute force. |
A list of lists storing all valid partitions. |
A Hash Set and recursion stack of depth N. $O(N)$ space. |
| 1594 |
Maximum Non Negative Product in a Matrix |
Explore every path from (0,0) to (R-1, C-1) using DFS and calculate the product for each. $O(2^{R+C})$. |
Path-Explosion Binary Tree |
Draw a grid. From (0,0), draw two arrows (Right/Down). Each node branches again. Highlight the massive overlapping paths. |
Dynamic Programming (Min/Max Tracking) |
The Sign-Aware Value Grid |
Because negative numbers can flip a product, each cell (r, c) must store two values: the `min_product` and `max_product` possible to reach it. |
Draw the grid. In each cell, draw two boxes (Min/Max). Calculate the Max by looking at (Previous\_Max \cdot current) and (Previous\_Min \cdot current) from the top and left. The negative numbers act as "switches." |
Iterative Matrix DP $O(R \cdot C)$ |
Draw a 2D rectangle. A single diagonal-like arrow sweeps from top-left to bottom-right. Each cell is filled once. |
Full recursion stack for every possible path. |
A 2D DP table (or two 1D rows) storing two long integers per cell. $O(R \cdot C)$ space. |
| 1595 |
Minimum Cost to Connect Two Groups of Points |
Try every possible subset of edges that connects both groups and find the minimum cost. $O(2^{N \cdot M})$. |
Edge-Subset Power Set |
Draw two groups of points. Draw all lines between them. Branch out for every line: "Include" or "Exclude". The complexity is astronomical. |
DP + Bitmask |
The Connectivity Mask Matrix |
Define `dp[i][mask]` as the min cost to connect the first i items of Group 1, where `mask` represents the set of Group 2 items already connected. Use bitwise OR to update the mask. |
Draw Group 1 on the left and Group 2 on the right. Group 2 nodes are "lights" that can be ON or OFF. For the 1st node of Group 1, try connecting it to every light. Write down the cost and the configuration of ON lights. Move to node 2. |
State-Space Product $O(N \cdot 2^M \cdot M)$ |
Draw a 2D table where rows are Group 1 (N) and columns are 2^M possible binary states. Each cell's update involves a loop of size M. |
Massive recursive tree with redundant state paths. |
A 2D DP table of size N \times 2^M. $O(N \cdot 2^M)$ space. |
| 1596 |
Most Frequently Ordered Products for Each Customer (SQL) |
For every customer, calculate order counts for every product they bought, then scan that list to find the maximum count. $O(C \cdot P)$. |
Nested Aggregation Grid |
Draw a list of Customers. For each, draw a sub-table of Products with tally marks. Find the max tally in each sub-table. Highly redundant. |
Window Functions (RANK / CTE) |
The Frequency-Ranked Partition |
Use a Common Table Expression (CTE) to count `customer_id` and `product_id`. Then apply `RANK() OVER (PARTITION BY customer_id ORDER BY cnt DESC)` to pick the top-ordered items. |
Draw a table with columns: Customer, Product, Count. Draw horizontal dividers between customers. In each section, write "Rank 1" next to the highest count(s). Circle the Rank 1 rows. |
Partitioned Hash-Agg $O(N \log N)$ |
Draw a single pipeline. Data flows into a "Grouping Node," then a "Sorting Node," and finally a "Filter Node." |
Application-side memory to store product-customer counts. |
Database internal sort/hash buffer. $O(N)$ space. |
| 1597 |
Build Binary Expression Tree From Infix Expression |
Full recursive parsing: find the operator with the lowest precedence that is not in parentheses, make it the root, and recurse on left/right. $O(N^2)$. |
Recursive Substring Slicing |
Draw the expression. Search for '+' or '-'. Split the string. Search again. Draw a tree where each node requires a full string scan. |
Shunting-yard Algorithm / Stack |
The Operator-Operand Two-Stack Viz |
Use two stacks: one for operands (nodes) and one for operators. When an operator is popped, it becomes the parent of the top two nodes in the operand stack. |
Draw two vertical boxes: "Values" and "Ops". Walk through the string. Push numbers. When an op has lower precedence than the stack top, pop Op, pop two Values, draw a mini-tree, and push the root back to Values. |
One-Pass Linear $O(N)$ |
Draw a single straight line. Above each character, show a $O(1)$ stack push/pop operation. |
Massive recursive call stack and string allocations. |
Two stacks storing pointers to node objects. $O(N)$ space. |
| 1598 |
Crawler Log Folder |
Split the full path string by '/' and simulate the navigation using a list, adding or removing elements. $O(N \cdot L)$. |
String-Splitting Navigation |
Draw a list of folder names. For "../", cross out the last name. For "./", do nothing. For "dir/", add a name. |
Stack / Integer Counter |
The Depth Gauge |
Treat the folder structure as a depth level. Start at 0. "../" means `depth = max(0, depth - 1)`. "x/" means `depth++`. "./" means do nothing. |
Draw a vertical line (y-axis). A pointer starts at 0. For each log, move the pointer up or down. The final y-value is the answer. |
Single-Pass Linear $O(N)$ |
Draw a single horizontal line. Each log entry is checked once with a constant $O(1)$ arithmetic update. |
Storing the full path as an array of strings. $O(N)$. |
A single integer variable `ans`. $O(1)$ space. |
| 1599 |
Maximum Profit of Operating a Centennial Wheel |
Simulate the wheel movement person-by-person until the waitlist is empty. $O(\\text{text}{\text{Total People}})$. |
Continuous Simulation Ticker |
Draw a wheel with 4 gondolas. Draw a "Waiting" bin. Every rotation, move 4 people from Bin to Wheel. Count profit at each step. |
Simulation / Greedy |
The Queue-to-Gondola Flow |
Maintain `waiting_customers` and `total_profit`. Each rotation, take `min(4, waiting_customers)`, add to `on_board`, subtract costs, and update the `max_profit` index. |
Draw a 4-slot Gondola. Draw an "Incoming" arrow from the customers array and a "Profit" counter. Fill the gondola, update profit, and repeat until both the array and the waitlist are empty. |
Linear Simulation $O(N)$ |
Draw a single straight line. Each step represents one rotation of the wheel. The line length is proportional to total customers. |
Recording every single profit state in a list. |
Variables for `max_profit`, `waiting`, and `current_profit`. $O(1)$ space. |
| 1600 |
Throne Inheritance |
On every `getInheritanceOrder()` call, rebuild the entire tree and filter out dead members. $O(N^2)$. |
Tree Re-Construction Matrix |
Draw a family tree. On every request, redraw the entire tree, but erase the nodes of people who have died. High overhead. |
DFS / Preorder Traversal + Hash Set |
The "Dead-Flag" Tree Traversal |
Store the family as an Adjacency List (Parent \rightarrow Children). Use a Hash Set to track the "Dead." The inheritance order is simply a Preorder Traversal, skipping nodes in the "Dead" set. |
Draw a standard tree. Put a red "X" over nodes of people who died. Trace a line starting from the Root, following the left-most branch first. Only write down names that don't have an "X". |
Preorder Traversal $O(N)$ |
Draw a single snaking line through the family tree. Each person (node) is visited exactly once. |
Copying and sorting name lists on every call. |
A Hash Map for the tree and a Hash Set for the dead. $O(N)$ space. |
| 1601 |
Maximum Number of Achievable Transfer Requests |
Backtracking (Try taking/ignoring every request) |
Recursion Tree Growth |
Draw a binary tree. Each level (M) splits into 2 branches (Take/Skip). Total leaves = 2^M. |
Bitmasking / State Space Search |
Binary State Enumeration |
List bitmasks 0 to (2^M)-1. For each 1-bit, trace +1/-1 on building capacities. |
Draw an array of N buildings. Underneath, write a bitmask (e.g., 101). Draw arrows between array indices based on 1s. |
Iteration Space Grid |
Draw a massive grid of 2^M rows. Next to it, draw a small inner loop column of size M to show the $O(M \cdot 2^M)$ steps. |
Call Stack: Stack overlapping boxes vertically representing recursive calls. |
1D Array: Draw a single horizontal array of size N (indegrees) that resets to 0s each loop. |
| 1602 |
Find Nearest Right Node in Binary Tree |
DFS storing node depths in a Map, then search |
Graph Traversal Map |
Draw a tree. Next to it, draw a two-column hash map mapping node IDs to integer depths. |
BFS (Level Order Traversal) |
Queue Sliding Window |
Draw a queue. Push root. Pop, check if target, return next in queue. Push children. |
Draw an open-ended tube (queue). Write node values passing through left-to-right, marking the target node with a star. |
Linear Node Processing |
Draw N nodes as a straight line showing each visited exactly once for $O(N)$ time. |
Hash Map & Call Stack: Draw a growing stack and a growing key-value table. |
Queue: Draw a segmented tube holding max W elements (W = max width of tree). |
| 1603 |
Design Parking System |
If-else chains checking type and decrementing 3 separate variables |
Decision Flowchart |
Draw a diamond shape with 3 outgoing arrows leading to decrement operations. Constant time $O(1)$. |
Array Indexing (Direct Access) |
Index-Mapped State Array |
Map carType (1,2,3) to index (0,1,2). Decrement value at index. If > 0, return true. |
Draw an array of 3 boxes labeled [Big, Med, Small]. Cross out a number and write the lower number inside. |
Constant Time Lookup |
Draw a single dot or a direct arrow to a box, highlighting $O(1)$ instant access. |
Variables: Draw three isolated named buckets. |
Array: Draw a single contiguous block divided into 3 segments. |
| 1604 |
Alert Using Same Key-Card Three or More Times... |
For every swipe, check all other swipes for the same user within 60 mins. |
N-to-N Connection Graph |
Draw N dots. Draw lines connecting every dot to every other dot. $O(N^2)$ complexity. |
Hash Map of Lists + Sorting + Sliding Window (Size 3) |
Timeline Sliding Window |
Group times by user. Sort lists. Frame a 3-element box and slide it across the timeline. |
Draw a horizontal number line of minutes. Draw a bracket spanning exactly 3 points. If distance <= 60, alert. |
Sorting Bottleneck |
Draw a funnel (sorting $O(N \log N)$) leading to a straight pipe (linear scan $O(N)$). |
Nested Loops: Draw a 2D grid matrix of size N x N. |
Map of Arrays: Draw a 2-column table where column 2 contains sorted horizontal arrays. |
| 1605 |
Find Valid Matrix Given Row and Column Sums |
Backtracking every possible integer combination in a 2D grid until sums match. |
Combinatorial Explosion |
Draw a massive branching tree where each node has branches equal to the row/col sum limit. |
Greedy Matrix Allocation |
Water Flow/Drainage Simulation |
Cell (i,j) = min(rowSum[i], colSum[j]). Subtract this from both. Move to next cell. |
Draw a grid. Put remaining row sums on the right, col sums on the bottom. Fill cell, cross out sums, write new remaining sums. |
Linear Matrix Traversal |
Draw a grid and a single snake-like line visiting each cell exactly once for $O(R \cdot C)$. |
Recursive Stack + 2D Matrix: Deep stack of matrices. |
2D Array + 2 1D Arrays: Draw a grid flanked by one vertical array (rows) and one horizontal array (cols). |
| 1606 |
Find Servers That Handled Most Number of Requests |
Linear scan of k servers for every incoming request to find the first free one. |
2D Grid Traversal |
Draw a grid: N rows (requests) and K columns (servers). Draw a horizontal line scanning across columns for every row. $O(N \cdot K)$. |
Two Heaps (Priority Queues) / TreeSet |
Dual Funnel System |
Incoming request pops busy servers whose time expired, pushes them to free heap. Assign request to smallest free server ID. |
Draw two pyramids (heaps): "Free" and "Busy". Draw arrows moving numbers between them as time progresses. |
Logarithmic Rebalancing |
Draw a funnel where data passes through quickly. Write $O(N \log K)$ next to it. |
1D Array: Draw an array of size K storing end-times for each server. |
Two Min-Heaps: Draw two tree-like structures mapping available IDs and busy end-times. |
| 1607 |
Sellers With No Sales (SQL/DB) |
Nested loop evaluating every seller against every single order (Cartesian check). |
N-to-M Connections |
Draw S dots (sellers) and O dots (orders). Draw lines connecting every S to every O. $O(S \cdot O)$ execution. |
Hash Anti-Join (LEFT JOIN + IS NULL) |
Venn Diagram Exclusion |
Hash all sellers who made sales in 2020. Scan seller list; if not in hash, add to result. |
Draw two overlapping circles (Sellers, 2020 Sales). Shade ONLY the crescent moon on the Sellers side. |
Linear Table Scan |
Draw two distinct columns. Draw a single straight line down each column. $O(S + O)$. |
Nested Loops (Memory Buffer): Draw a massive temporary grid holding all combinations. |
Hash Set: Draw a bucket of 2020 seller IDs, and an array of all sellers passing through a filter. |
| 1608 |
Special Array With X Elements... |
For every integer x from 0 to N, iterate through the whole array to count elements >= x. |
Double Iteration Matrix |
Draw an N x N matrix representing an outer loop (x) and an inner loop checking all array values. $O(N^2)$. |
Counting Sort / Frequency Array |
Reverse Histogram Cumulative Sum |
Count frequencies. Iterate from N down to 0, keeping a running sum of counts. If sum == x, return x. |
Draw a bar chart of frequencies. Draw a cumulative wave moving from right to left, stopping when wave height equals the index. |
Linear Scan |
Draw a single straight arrow pointing across a frequency array. $O(N)$. |
Two Variables: Simple outer and inner loop counters. |
Frequency Array: Draw an array of size N+1 with tallies (hash marks) inside the boxes. |
| 1609 |
Even Odd Tree |
DFS traversal, throwing all nodes and their levels into an unstructured list, then sorting and verifying later. |
Tangled Graph |
Draw a tree with messy lines jumping from random leaf nodes to a separate table, symbolizing $O(N \log N)$ sorting step. |
BFS (Level Order Traversal) |
Horizontal Slicing |
Use a queue. For each level, keep track of the 'previous' node value. Check parity (even/odd) and strict increasing/decreasing rules. |
Draw a tree and slice it with horizontal dashed lines. Draw a left-to-right arrow on each level validating the > or < signs. |
Level-by-Level Linear Process |
Draw N nodes in a straight horizontal line to represent $O(N)$ time complexity. |
List + Call Stack: Draw a deep recursive stack and a chaotic 1D array. |
Queue: Draw an open-ended pipe containing exactly one level of the tree at a time (Max size = W). |
| 1610 |
Maximum Number of Visible Points |
Calculate the angle between every possible pair of points to find the densest cluster. |
Complete Graph (N^2 Angle Checks) |
Draw N points in a circle. Draw a line from every point to every other point. $O(N^2)$. |
Polar Angle Sorting + Sliding Window |
Radar Sweep |
Calculate polar angles (atan2) of all points from your location. Sort them. Append points + 360 to handle wraparound. Slide a window of size 'angle'. |
Draw a circle with dots. Draw a pizza slice (wedge) representing the viewing angle. Rotate the slice around the circle, counting dots inside. |
Sorting Bottleneck |
Draw a funnel (O(N log N) sorting) leading into a straight pipe (O(N) sliding window). Overall $O(N \log N)$. |
2D Matrix: Array of N arrays holding angle differences. |
Extended 1D Array + Two Pointers: Draw an array of sorted angles, doubled in length, with a bracket [L, R] sliding across. |
| 1611 |
Minimum One Bit Operations to Make Integers Zero |
BFS/Recursion trying all valid bit flips at every step to reach 0. |
Infinite State Maze |
Draw a massive branching tree of binary states going in circles. $O(2^N)$ steps. |
Gray Code Reversal / Bit Manipulation |
Recursive Bit Flipping |
Apply Gray Code math: XOR current with (current-1), apply alternating signs, and accumulate the result. |
Write the binary number. Cross out the leftmost 1, write its Gray Code integer equivalent underneath, and subtract the next 1's value. |
Logarithmic Ladder |
Draw a ladder with 32 rungs (for 32 bits), showing the calculation drops instantly to $O(\log N)$. |
Graph Queue: Draw a massive tube overflowing with visited binary strings. |
$O(1)$ Variables: Draw three small, distinct boxes for tracking `n`, `sign`, and `res`. |
| 1612 |
Check If Two Expression Trees are Equivalent |
Traverse both trees, build two large strings, sort both, and compare. |
Tangled String Sorting |
Draw two messy piles of letters passing through an $O(N \log N)$ sorting funnel. |
DFS + Frequency Array (Counting) |
Bucket Tallying / Neutralization |
DFS Tree 1: Add +1 to letter bucket. DFS Tree 2: Add -1 to bucket. Return true if all buckets are exactly 0. |
Draw an array of 26 slots. Draw +1s dropping in from one tree, and -1s dropping in from the second tree to cancel them out. |
Linear Tree Paths |
Draw two tree structures with a single continuous arrow tracing through every node for $O(N)$ time. |
Large Strings: Draw two massive horizontal, contiguous text blocks. |
Size-26 Array: Draw a fixed, small 26-slot grid holding integers. |
| 1613 |
Find the Missing IDs (SQL) |
Load all DB records into application memory, loop 1 to Max, check if missing. |
Memory Overload |
Draw a database cylinder dumping millions of records into a cramped RAM box. $O(N)$ space. |
SQL Recursive CTE + Anti-Join |
Number Line Generator Belt |
Recursively generate sequence 1 to Max(ID). Filter out (NOT IN) IDs that exist in the original table. |
Draw a factory belt generating numbers 1, 2, 3... and a trapdoor that drops numbers if they match the Customer table. |
Indexed Lookup |
Draw a straight arrow from the generated sequence bypassing an index filter $O(N)$. |
App Memory Hash Set: Draw a chaotic blob holding disorganized IDs. |
DB Engine Buffer: Draw a clean, tabular temporary memory space managed natively by the DB. |
| 1614 |
Maximum Nesting Depth of the Parentheses |
Use an explicit Stack. Push '(', pop ')'. Track max stack height. |
Physical Tower Building |
Draw physical blocks being stacked up and then removed. Memory grows to $O(N)$. |
Single Counter Tracking |
Elevation Profile / Line Graph |
Loop string. '(' adds 1 to depth. ')' subtracts 1. Record the peak "altitude". |
Draw a 2D graph. X-axis is the string index. Y-axis is depth. Draw a line going up on '(' and down on ')'. Peak is the answer. |
Single Flat Scan |
Draw a straight horizontal arrow scanning the text string exactly once. $O(N)$ time. |
Stack: Draw a deep vertical tube holding bracket symbols. |
Single Variable: Draw a single box holding an integer that constantly overwrites itself. |
| 1615 |
Maximal Network Rank |
Loop every pair (A,B). For every road, check if it touches A or B. $O(V^2 \cdot E)$. |
Exhaustive Edge Checking |
Draw V dots. For every pair, draw a magnifying glass inspecting every single edge E in the whole graph. |
Degree Array + Edge Adjacency Matrix |
Heavy Node Pairing |
Precompute road counts. For pair A,B: Rank = count[A] + count[B] - (1 if connected else 0). Find max. |
Draw nodes sized by their degree (number of roads). Pick the two fattest nodes, sum their sizes, cross out the line between them if it exists. |
Adjacency Lookup Grid |
Draw a V x V grid. Highlight a quick coordinate lookup $O(1)$ inside an outer pair loop $O(V^2 + E)$. |
Edge List: Draw a massive, unstructured bag of lines. |
1D Array + 2D Matrix: Draw one horizontal array for degrees, and a checkerboard grid for connections. |
| 1616 |
Split Two Strings to Make Palindrome |
Split at every index i, concatenate A_prefix+B_suffix and B_prefix+A_suffix, then check both for palindromes. |
Nested Iteration Loop |
Draw a string sliced at every single letter. At each slice, draw a magnifying glass iterating over the entire new string. $O(N^2)$. |
Two Pointers (Outside-In) + Middle Checking |
Symmetric Pincer Movement |
Pointer `left` at start of A, `right` at end of B. Move inwards while characters match. If they mismatch, check if the remaining middle of A or middle of B is a palindrome. |
Write string A on top of B. Draw an arrow pointing right from A[0] and left from B[N-1]. Connect matching outer letters with lines, leaving an isolated box in the center. |
Single Linear Scan |
Draw two arrows converging precisely at the center of a string without ever backtracking. $O(N)$. |
Multiple String Allocations: Draw numerous floating blocks representing newly created concatenated strings. |
Two Index Variables: Draw two tiny boxes holding integers (the left and right pointers) with no extra memory allocated. $O(1)$. |
| 1617 |
Count Subtrees With Max Distance Between Cities |
Run BFS/DFS from every node in every possible subset to find the maximum tree diameter. |
Double Exponential Explosion |
Draw a massive branching tree of subsets (2^N), and inside every leaf, draw a tangled graph search. |
Bitmasking Subset Enumeration + DFS / Floyd-Warshall |
State Traversal Filtering |
Precompute all-pairs shortest paths. Use a bitmask (1 to 2^N) to represent a subset. Check if subset is connected (Edges == Nodes - 1). If valid, find max distance in subset. |
Draw a binary number representing included cities. Beside it, draw a distance matrix grid. Circle the matrix intersections that correspond to the 1s in the binary number. |
Matrix + Exponential Check |
Draw a 2^N tall column. For each row, draw an arrow pointing to a fixed, pre-calculated square grid (Matrix). |
Call Stacks + Dynamic Sets: Chaotic clusters of hash sets created and destroyed for every subset. |
2D Array + Integer Bitmask: Draw a static NxN grid for distances, and a single 32-bit register mapping the current subset. |
| 1618 |
Maximum Font to Fit a Sentence in a Screen |
Linear search from the smallest font up to the largest, checking width and height formulas every time until it fails. |
Linear Stepping |
Draw a staircase. Draw a character climbing one step at a time until they hit a ceiling (the screen height/width). $O(N)$. |
Binary Search on Monotonic Property |
Search Space Halving |
Set Low=0, High=len(fonts)-1. Check Mid. Does height and width fit? If yes, Low=Mid+1 (try bigger). If no, High=Mid-1. |
Draw an array of fonts. Put brackets at the ends. Point an arrow at the middle. Cross out the left half if it fits, cross out the right half if it doesn't. |
Logarithmic Search Tree |
Draw an array sliced in half, then that half sliced in half, reaching a single box in $O(\log N)$ steps. |
$O(1)$ Variables: An index pointer stepping through. |
Three Pointers (Low, Mid, High): Draw three small indicator arrows sliding across a static array. $O(1)$. |
| 1619 |
Mean of Array After Removing Some Elements |
Sort the entire array from scratch, manually slice off the top and bottom 5%, and sum the rest. |
Heavy Sorting Funnel |
Draw a massive funnel rearranging every single item in the array to achieve $O(N \log N)$ time. |
QuickSelect Partitioning (nth_element) |
Pivot Boundary Shifting |
Calculate K = 5%. Use QuickSelect to place the Kth smallest element at index K. Then place the Kth largest at index N-K. Sum the middle. |
Draw an unsorted array. Draw two bold vertical lines at the 5% and 95% marks. Write arbitrary small numbers left of the first line, big numbers right of the second. Sum the middle. |
Linear Partitioning Time |
Draw an array being split into buckets roughly in half a few times, culminating in an $O(N)$ straight line. |
Copied Array Slice: Draw a brand new, slightly smaller array allocated in memory. |
In-Place Array Pointers: Draw the original array with elements swapped internally, avoiding extra memory overhead. $O(1)$ auxiliary space. |
| 1620 |
Coordinate With Maximum Network Quality |
N/A - The constraints are so small (50x50) that an exhaustive calculation is the intended brute force and optimized solution. |
Radar Map Iteration |
Draw a 50x50 grid. For every single cell, draw a line to every single tower (T) in the list. $O(\text{Grid} \cdot T)$. |
Exhaustive Heatmap Search (Brute Force) |
Signal Overlay Processing |
Loop X (0-50), Loop Y (0-50). Measure Euclidean distance to all towers. If <= radius, add `floor(quality / (1 + distance))` to cell score. Track max score. |
Draw a 2D coordinate plane. Place 3 dots (towers). Pick a random coordinate square. Draw expanding rings from the towers to see if they reach that square. Tally the score. |
Fixed Boundary Iteration |
Draw a static square (51x51) with a straight arrow looping through it representing a strict bounded $O(1)$ mathematical constraint. |
Variables: Accumulators tracking distance and signal strength. |
$O(1)$ Memory Trackers: Draw three distinct boxes: `max_quality`, `best_X`, `best_Y`. Overwrite them continuously as you scan the grid. |
| 1621 |
Number of Sets of K Non-Overlapping Line Segments |
Backtracking to check every possible combination of starting and ending points for K segments. |
Combinatorial Explosion |
Draw a massive, dense tree where every node branches into multiple segment choices. $O(N^K)$. |
Dynamic Programming / Combinatorics Math |
3D DP State Transition Grid |
dp[i][j][is_started] tracks index `i`, segments `j`, and if a segment is open. Or use the pure math formula: (N+K-1) Choose (2K). |
Draw a 2D grid for N and K. Divide each cell into two triangles (segment started vs. not started). Fill cells sequentially. |
Matrix Fill (DP) or $O(1)$ Math |
Draw a single arrow filling a grid row-by-row (O(N*K)), or a single formula evaluation box $O(1)$ if using pure math. |
Deep Recursion Call Stack: Tall, unstable stack of overlapping segment states. |
2D/1D DP Array: Draw a static grid or just two 1D arrays swapping states to save space. |
| 1622 |
Fancy Sequence |
Loop through the entire sequence and apply the add or multiply operation to every element, one by one. |
Sweeping Array Updates |
Draw an array. For every operation Q, draw an arrow hitting every single cell in the array. $O(N \cdot Q)$. |
Math (Modular Inverse) + Global Modifiers |
Global Lens Filter |
Keep global `add` and `mul` variables. When appending `x`, reverse-engineer its value before adding it: `(x - add) * modInverse(mul)`. |
Draw an array of raw values. Draw a "lens" or "filter" box above it containing the global multiplier and adder. |
$O(1)$ Direct Access |
Draw a single direct arrow through the "lens" straight to a specific array index. $O(1)$ per query. |
Standard Array: Modifying the actual values constantly in memory. |
Array + Global Variables: Draw a static array with two standalone, highly active variables floating above it. |
| 1623 |
All Valid Triplets That Can Represent a Country (SQL) |
Cross-joining all three tables blindly (Cartesian product) and filtering at the very end. |
3D Cartesian Block |
Draw three axes (A, B, C) creating a massive 3D cube of millions of invalid row combinations. $O(A \cdot B \cdot C)$. |
INNER JOIN with Inequality Filtering |
Sequential Funneling |
Join A to B filtering out matching names/IDs. Take that small result and Join to C filtering out names/IDs from both A and B. |
Draw a large funnel. Pour Table A and B in, filter out duplicates. Pour the trickle into a second funnel with Table C. |
Progressive Row Reduction |
Draw thick lines (data) progressively getting thinner after passing through two distinct filter checkpoints. |
Massive Temp Table: Draw an overflowing memory buffer holding a 3D join result. |
Streaming Pipeline: Draw small, temporary row buffers processing data step-by-step. |
| 1624 |
Largest Substring Between Two Equal Characters |
Nested loops checking every character against every other character ahead of it to find matching pairs. |
N^2 Pairwise Matrix |
Draw a string. Draw a line from the 1st letter to all other letters. Then from the 2nd letter to all others. $O(N^2)$. |
Hash Map / Fixed Array (First Occurrence) |
Anchor and Measure |
Use an array of size 26. Store the index of the *first* time a char appears. When seen again, calculate `currentIndex - firstIndex - 1`. |
Draw an array of 26 empty slots. Point an anchor line from a slot to a letter. Later in the string, draw a measuring tape back to that anchor. |
Single Linear Scan |
Draw a single straight arrow scanning across the string from left to right. $O(N)$. |
Two Loop Counters: Simple floating variables `i` and `j`. |
Size-26 Integer Array: Draw a small, fixed-size 26-box grid storing integer indices. Space is $O(1)$. |
| 1625 |
Lexicographically Smallest String After Applying Operations |
Apply the "add" and "rotate" operations randomly without keeping track of what strings have already been checked. |
Infinite Loop Graph |
Draw a circle of nodes where operations just loop back onto themselves forever, crashing the program. |
BFS / DFS with Visited State Set |
Exhaustive State Space Search |
Push original string to queue. Pop string, apply both operations. If the resulting strings are not in the "Visited" set, push them to the queue. Track the minimum string seen. |
Draw a starting node (string). Draw two branching arrows ("Add" and "Rotate"). If a branch leads to a string already drawn, draw a big red X. |
Bounded Graph Traversal |
Draw a tree that gets wider but eventually stops growing because all finite possible combinations have been visited. |
Infinite Call Stack: Stack overflowing with repetitive data. |
Queue + Hash Set: Draw a horizontal pipe (Queue) feeding into a bag (Hash Set) that filters out duplicates. |
| 1626 |
Best Team With No Conflicts |
Generate every possible subset of players, check each for age/score conflicts, and keep the max sum. |
Exponential Tree Branches |
Draw a massive binary tree (include/exclude) for N players. $O(2^N)$ time. |
Sorting + DP (Longest Increasing Subsequence Variant) |
Sorted Cascading Array |
Sort players by age (then score). Run a nested loop: for each player `i`, look back at all `j < i`. If score[i] >= score[j], dp[i] = max(dp[i], dp[j] + score[i]). |
Draw an array of players sorted by age. Draw curved arrows pointing from left-side players to right-side players, carrying a cumulative score sum. |
Double Iteration Overlap |
Draw an N x N triangular grid representing the `i` outer loop and `j` inner loop. $O(N^2)$ time. |
Deep Recursion Call Stack: Overflowing stack tracking massive combinations. |
1D DP Array: Draw a single horizontal array holding the max score achievable up to that index. |
| 1627 |
Graph Connectivity With Threshold |
For every query, calculate GCD for all pairs to build a graph, then run BFS/DFS to see if a path exists. |
Dense Graph Traversal |
Draw N dots. Draw lines between almost every dot (calculating GCD). Send a magnifying glass to trace paths for every query. $O(Q \cdot N^2)$. |
Union-Find (Disjoint Set) with Math Multiples |
Grouping Multiples (Forest) |
Loop `i` from `threshold + 1` to `n`. Loop its multiples `j = 2i, 3i...` and Union(`i`, `j`). For queries, just check if `Find(u) == Find(v)`. |
Draw numbers 1 to N. Circle a number (e.g., 3). Draw lines grouping 3, 6, 9 together. When queried, just check if two numbers are in the same drawn blob. |
Near-Constant Lookup |
Draw a funnel (Union-Find setup) leading to a direct $O(1)$ straight line mapping queries to answers. $O(N \log(\log N)$ + Q). |
Adjacency List + Visited Array: Large web of connected edges stored in memory. |
Union-Find Array: Draw a single array where indices point to their "parent" index, forming flat trees. |
| 1628 |
Design an Expression Tree With Evaluate Function |
Repetitive string parsing and recalculation every time the evaluate function is triggered. |
String Parsing Loop |
Draw a long string equation being sliced and re-read from left to right constantly. |
Object-Oriented Design (Polymorphism) + Postfix Stack Tree |
Abstract Syntax Tree (AST) |
Read postfix array. Push numbers as NumberNodes to stack. For operators, pop right and left nodes, create OperatorNode, push back. Call `evaluate()` recursively. |
Draw a tree where leaves are numbers and internal nodes are operators (+, -, *, /). Draw arrows bubbling values from the bottom up to the root. |
Single DFS Traversal |
Draw a tree and a single continuous line weaving through every node exactly once to get the final answer. $O(N)$. |
Raw Strings / Arrays: Raw data buffers constantly being copied. |
Node Objects + Stack: Draw a stack used temporarily to assemble an interconnected web of smart Node objects. |
| 1629 |
Slowest Key |
Create a separate array of all durations, sort it to find the max, resolve ties using a secondary sort. |
Sorting Bottleneck |
Draw a list of numbers passing through a sorting funnel $O(N \log N)$ just to find the biggest one. |
Single Pass Linear Scan |
Max Tracking Sweep |
Loop once. Current duration = releaseTimes[i] - releaseTimes[i-1]. Update `maxDuration` and `bestKey` if current is greater (or equal but lexically larger). |
Draw an array of times. Slide a 2-element window across it. Subtract the left from the right. If it beats the current record holder, overwrite the record box. |
Linear Arrow |
Draw a single straight arrow pointing left to right across the data array. $O(N)$. |
Secondary Duration Array: Draw a newly allocated array of size N holding the differences. |
Two Trackers: Draw two isolated boxes labeled `max_time` and `best_char` being continuously overwritten. $O(1)$. |
| 1630 |
Arithmetic Subarrays |
For each query, copy the subarray, run a full sorting algorithm, and check if the differences are uniform. |
Multiple Sorting Funnels |
Draw Q different funnels. Slices of an array are thrown into each funnel to be sorted. $O(Q \cdot M \log M)$. |
Hash Set + Min/Max Math (No Sorting) |
Set Boundary Validation |
Find min/max of subarray. Diff = (max - min) / (len - 1). If not an integer, return false. Put subarray in HashSet. Loop from min to max by Diff, check if present. |
Draw a sliced array. Pluck out the smallest and largest numbers. Calculate the required "step". Toss all sliced numbers into a bucket (Set). Check if the bucket has every required "step" number. |
Linear Scan per Query |
Draw Q straight arrows tracing over slices of the array. No funnels. $O(Q \cdot M)$. |
Copied Arrays: Draw M new arrays allocated in memory to be sorted. |
Temporary Hash Set: Draw a single bucket created and emptied for each query to check for element existence. $O(M)$ space per query. |
| 1631 |
Path With Minimum Effort |
DFS/Backtracking to find every possible path from top-left to bottom-right and recording the max effort of each. |
3-Way Branching Recursion Tree |
Draw a massive tree where each node splits into 3 (up, down, left, right excluding the parent). $O(3^(M\cdot N)$). |
Dijkstra / Binary Search + BFS |
Weighted Expansion Ripple |
Use a Min-Heap. Always expand to the neighbor that requires the minimum "maximum effort". Mark cells as visited to prevent re-entry. |
Draw a grid. Mark each cell with its "current min-effort". Use a circle to represent the expanding frontier of the Min-Heap. |
Frontier Log-Linear Growth |
Draw an expanding circle across a grid. Write E log(V) where E is edges (cell adjacencies) and V is vertices (cells). |
Infinite Recursion Stack: Draw a stack of grids being passed down through recursive calls. |
Priority Queue + 2D Effort Matrix: Draw a min-heap (pyramid) and one static 2D grid storing best effort values. |
| 1632 |
Rank Transform of a Matrix |
Find global minimum, rank it, then find next min, check all row/col constraints manually. |
Search and Replace Loop |
Draw a matrix. Draw a hand searching through all cells over and over again. $O((M\cdot N)$^2). |
Union-Find + Topological Sort (Indegree) |
Dependency Graph Chain |
Group cells by value. Use Union-Find to link cells in same row/col. Build a DAG of ranks. Use BFS (Topological Sort) to assign final ranks. |
Draw groups of cells as blobs. Draw arrows from "lower value" blobs to "higher value" blobs. Label blobs with an indegree count. |
Grouped Processing Pipe |
Draw cells moving through a funnel (sorting) and then through a pipeline (linear graph scan). $O(\text{MN} \\text{log MN})$. |
Massive Constraint Lists: Draw lists of pairs for every single cell interaction. |
Union-Find + Adjacency Map: Draw a Forest of Trees (UF) and a Map linking groups to their neighbors. |
| 1633 |
Percentage of Users Attended a Contest (SQL) |
For every contest ID, run a subquery to count all users in the Users table. |
Nested Loop Subquery |
Draw a Contest table row. Inside, draw a separate magnifying glass scanning the entire User table. $O(C \cdot U)$. |
Group By + Scalar Subquery / Cross Join |
Bucket aggregation with Shared Total |
Group the Register table by contest_id. Divide the count(user_id) by a single pre-calculated (select count(*) from Users). |
Draw a table split into contest-ID buckets. Draw one big box representing the Total User Count. Draw arrows from buckets to the big box. |
Single Linear Table Scan |
Draw a straight arrow through the Register table once. $O(R + U)$. |
Temporary Results Matrix: Draw multiple temporary tables for each subquery execution. |
Hash Aggregate Buffer: Draw a small table in RAM where contest counts are incremented as the table is read. |
| 1634 |
Add Two Polynomials Represented as Linked Lists |
Merge both lists into one, then sort by exponent and combine terms with the same power. |
Unstructured Merge + Sort |
Draw two chains merging into a messy pile, then passing through an $O(N \log N)$ sorting funnel. |
Two Pointers (Merge Sort Style) |
Synchronized Zipper Traversal |
Place a pointer on both heads. If exp1 > exp2, add term1 and move p1. If exp2 > exp1, add term2 and move p2. If equal, add coefficients. |
Draw two parallel chains. Move two arrows left-to-right. Draw a new chain forming underneath as the arrows move. |
Linear Simultaneous Scan |
Draw two parallel horizontal arrows moving at the same speed. $O(N+M)$. |
Temporary Array/Map: Draw a separate data structure storing all nodes for sorting. |
In-place / Single Chain: Draw a single new chain being linked node-by-node using existing values. $O(1)$ auxiliary space (excluding result). |
| 1635 |
Hopper Company Queries I (SQL) |
Complex nested joins between Months, Drivers, and Rides for every month individually. |
Correlated Monthly Subqueries |
Draw 12 separate SQL query boxes, each scanning the entire Rides and Drivers tables for that specific month. |
Recursive CTE (Month Generator) + LEFT JOIN + Window Functions |
Timeline Stencil Overlay |
Generate 12 months using a CTE. Left join Drivers (on join month <= current month) and Rides (on join month = current month). Count and SUM. |
Draw a vertical timeline 1-12. Layer Driver data over it (cumulative) and Ride data (individual month snapshots). |
Full Table Scan with Aggregation |
Draw a single pass through the Driver and Ride tables to populate the monthly buckets. $O(D + R)$. |
Subquery Cache: Draw multiple redundant copies of table segments in memory. |
Virtual Timeline CTE: Draw a small, temporary 12-row table that acts as the "skeleton" for the join. |
| 1636 |
Sort Array by Increasing Frequency |
Nested loops to count every element's frequency, then use a standard sort on the count results. |
Multi-Pass Funnel |
Draw an array. Draw N arrows pointing to a frequency table. Then draw a sorting funnel. $O(N^2)$ or $O(N \log N)$ depending on count logic. |
Hash Map + Custom Comparator Sorting |
Frequency Bucket Mapping |
Store counts in a Map. Sort the original array using a comparator that checks Map.get(a) vs Map.get(b), then (b-a) for ties. |
Draw a 2-column table (Val | Freq). Below it, draw the array and use "Weight" lines (thicker lines for higher freq) to visualize the new order. |
Sorting Bottleneck |
Draw a funnel with N log N capacity. Input is N, output is sorted N. |
Intermediate Count Array: Draw a separate, potentially large array of counts. |
Hash Map: Draw a small "cloud" or "bucket" holding unique keys and their integer counts. $O(N)$ space. |
| 1637 |
Widest Vertical Area Between Two Points... |
Compare every point (x,y) with every other point to find the gap between their x-coordinates. |
Complete Connection Graph |
Draw N dots. Draw lines connecting every single pair to measure the horizontal distance. $O(N^2)$. |
X-Coordinate Sorting |
Vertical Slat/Fence Scan |
Ignore y-coordinates. Sort all x-coordinates. Loop once to find the maximum `x[i] - x[i-1]`. |
Draw points on a graph. Draw vertical dashed lines through each point. The widest "hallway" between any two adjacent lines is the answer. |
Log-Linear Funnel |
Draw a funnel (O(N log N)) leading to a straight linear pipe (O(N)). |
Point Matrix: Draw a 2D grid storing both X and Y for all points. |
1D X-Array: Draw a single horizontal array holding only the sorted x-values. $O(N)$ space. |
| 1638 |
Count Substrings That Differ by One Character |
Generate every possible substring pair from S and T, and check each pair for exactly one mismatch. |
Combinatorial Matrix Check |
Draw a 2D matrix of substrings of S vs substrings of T. Magnifying glass checks every cell. $O(N^4)$ or $O(N^3)$. |
DP / Central Expansion (Mismatch Count) |
Diagonal Expansion Tally |
Pick starting points (i, j). Expand while characters match. When a mismatch occurs, continue expanding until a second mismatch hits. |
Draw S horizontally and T vertically. Draw diagonal arrows. Mark a '1' when you hit a mismatch and keep counting until you hit a '2'. |
Triangular DP Grid |
Draw an N x M grid. Draw single arrows sliding down the diagonals. $O(N \cdot M)$. |
Substring List: Draw two massive buckets of all possible string slices. |
3D/2D DP Matrix: Draw a static grid where each cell holds two integers: prefix_match and suffix_match. |
| 1639 |
Number of Ways to Form a Target String... |
Backtracking to try every character at every column index in the dictionary to build the target. |
Recursive Decision Tree |
Draw a massive tree where each level branches out for every word in the dictionary. $O(\text{Words}^\text{TargetLength})$. |
DP + Character Frequency Pre-computation |
Columnar Selection Grid |
Precompute counts of each char 'a'-'z' per column. DP[i][j] = ways to form target[0...i] using dictionary columns [0...j]. |
Draw a grid of target characters (rows) and dictionary columns (cols). Fill cells using: (Ways using current col * freq) + (Ways using previous col). |
2D Matrix Fill |
Draw an N (Target) x M (Columns) grid filled row-by-row. $O(N \cdot M + \text{Words} \cdot M)$. |
Recursive Call Stack: Stack of states representing column/target indices. |
2D Freq Array + 1D DP: Draw a 26 x M frequency table and a single rotating DP row. |
| 1640 |
Check Array Formation Through Concatenation |
Try every permutation of 'pieces' to see if any sequence matches the original 'arr'. |
Permutation Tree |
Draw a tree starting with pieces. Branch out into every possible order. $O(P!)$. |
Hash Map (Piece-Start Mapping) |
Index-Linked Jump Scan |
Store the first element of each piece in a Map. Iterate through `arr`. If current `arr[i]` is a key in the Map, check the whole piece; else return false. |
Draw `arr` as a long line. Draw pieces as small segments. Use arrows to "snap" piece segments onto the main line based on the starting number. |
Linear Snap-Fit |
Draw a single straight arrow through `arr`. Pieces are matched instantly via Map lookups. $O(N)$. |
Permutation List: All possible re-orderings of pieces. |
Hash Map: Draw a 2-column table (StartVal | PieceIndex). $O(N)$ space. |
| 1641 |
Count Sorted Vowel Strings |
Recursive backtracking: generating all combinations of length N using vowels [a, e, i, o, u] in non-decreasing order. |
Standard Decision Tree |
Draw a tree starting with 5 branches. Each branch splits into 5 more, but pruned to stay sorted. $O(N^5)$. |
Math (Stars and Bars) / DP |
Combinatorial Grid / Formula |
The problem is equivalent to choosing n items from 5 types with repetition: \binom{n + 5 - 1}{5 - 1}. Or a 1D DP array update. |
Draw 5 buckets (a, e, i, o, u). Draw n stars being distributed into these buckets. Use the formula \binom{n+4}{4}. |
Constant or Linear Time |
Draw a single calculation box for $O(1)$ math, or a 5-element array being updated n times for $O(n)$. |
Recursive Stack: Draw a stack of depth n. |
1D Array / Math: Draw a small 5-slot array or a single line of algebra. |
| 1642 |
Furthest Building You Can Reach |
Try every combination of using bricks or ladders at every height jump using recursion/backtracking. |
Exponential Choice Tree |
Draw a tree where each node has two branches: "Use Bricks" or "Use Ladder". $O(2^N)$. |
Greedy + Min-Heap (Priority Queue) |
Ladder Allocation Strategy |
Use ladders for the largest jumps seen so far. If you run out of ladders, replace the smallest ladder jump with bricks from your stash. |
Draw building heights as bars. Mark jumps with arrows. Use a "Top-K" box (Min-Heap) to store the L largest jumps where you used ladders. |
Heap-Sorted Stream |
Draw a line of n elements passing through a funnel of size L (ladders). $O(N \log L)$. |
Call Stack: Deep stack for every height choice. |
Min-Heap: Draw a small binary tree (heap) that stores up to L integers. |
| 1643 |
Kth Smallest Instructions |
Generate all permutations of "H" and "V" instructions, sort them lexicographically, and pick the Kth one. |
Permutation Explosion |
Draw a massive sorted list of all combinations. $O(\\text{binom}{R+C}{R} \log \\text{text}{\text{total}})$. |
Combinatorial Counting (Pascal's Triangle logic) |
Recursive Range Partitioning |
At each step, decide whether to place 'H'. Calculate how many instructions start with 'H'. If K \leq that count, place 'H'; else place 'V' and subtract count from K. |
Draw a path grid. At each junction, write the number of ways to reach the destination using combinations formula nCr. Compare K to this number. |
Linear Step-down |
Draw a straight path of length R+C where each step is a single decision. $O(R + C)$. |
List of Strings: A massive storage of all possible strings. |
$O(1)$ Variables: Draw a few boxes for n, r, k and the result string. |
| 1644 |
Lowest Common Ancestor of a Binary Tree II |
Standard LCA but without checking if nodes exist; then doing a second pass to verify both nodes are in the tree. |
Two-Pass Traversal |
Draw a tree. Draw one arrow traversing for LCA, then two more arrows searching for existence. $O(N)$. |
DFS (Post-order Traversal) with Existence Flags |
Bubble-up Search |
Traverse the whole tree. A node returns itself if it matches p or q. Parent nodes return p/q if found in subtrees. Use a global counter to ensure both are found. |
Draw a tree. Color nodes p and q red. Draw arrows "reporting" the find upwards. LCA is where the two red reports first meet. |
Single Linear Depth-First Scan |
Draw one continuous line weaving through every node exactly once. $O(N)$. |
Call Stack + Full Tree Copy: Redundant memory for tracking presence. |
Recursive Call Stack: Draw a vertical stack representing the current path depth. $O(H)$. |
| 1645 |
Hopper Company Queries II (SQL) |
Join Drivers and Rides for every month separately using subqueries to calculate active drivers and ride counts. |
Nested Loop Aggregates |
Draw 12 monthly boxes, each triggering a full scan of the Drivers and Rides tables. |
Recursive CTE + LEFT JOIN + SUM/COUNT Window Functions |
Ratio Overlay Timeline |
Generate 12 months. Join Drivers (cumulative active) and Rides (unique monthly drivers with rides). Calculate (Drivers with Rides / Total Active) * 100. |
Draw a 12-row table. Column 1: Months. Column 2: Total Drivers (running sum). Column 3: Drivers with Rides. Column 4: Percentage calculation. |
Sequential Table Scan |
Draw a single pass through the database tables to populate the monthly buckets. $O(D + R)$. |
Temp Table Sprawl: Multiple redundant data slices for monthly averages. |
Hash Aggregate Buffer: Draw a single clean table in RAM being filled as data streams from disk. |
| 1646 |
Get Maximum in Generated Array |
Recursive calculation of each element `nums[i]` on-demand, leading to massive redundant calculations. |
Redundant Recursion Tree |
Draw a tree where calculating `nums[10]` branches into `nums[5]`, which branches into `nums[2]`, etc., with many repeating nodes. |
Iterative DP / Simulation |
Linear Fill Sweep |
Loop from 1 up to `n/2`. Fill `nums[2i]` and `nums[2i+1]` using existing values. Track a `max_val` variable simultaneously. |
Draw an array of size n+1. Write the indices above the boxes. Fill them one by one from left to right, circling the largest number found. |
Single Linear Pass |
Draw a straight arrow pointing across the array from index 0 to n. $O(n)$ time. |
Call Stack: A deep, heavy stack of pending recursive calls. |
1D Array: A single static horizontal array holding n+1 integers. |
| 1647 |
Minimum Deletions to Make Character Frequencies Unique |
Generate every possible combination of deletions and check if character frequencies are unique for each. |
Subsets of Frequencies |
Draw 26 bars. For each bar, branch out into all possible shorter heights. $O(2^{26})$ or $O(\\text{text}{\text{TotalChars}}^2)$. |
Greedy + Frequency Sorting / Hash Set |
Frequency Staircase Smoothing |
Count frequencies. Sort them descending. If a frequency is already in the "Used" set, decrement it until it's unique or zero. |
Draw a bar chart of frequencies. If two bars are the same height, "shave" the second bar down until it is shorter than any existing unique height. |
Log-Linear Funnel |
Draw a funnel (sorting 26 chars) leading to a short linear pipe. $O(n + 26 \log 26)$. |
Recursion Tree: A chaotic web of deletion states. |
Frequency Array + Set: A fixed-size array of 26 and a small bucket (set) for unique counts. |
| 1648 |
Sell Diminishing-Valued Colored Balls |
Simulate selling one ball at a time: find the max value ball, sell it, decrement its count, and repeat k times. |
Repetitive Max Selection |
Draw a list of numbers. Draw k arrows pointing to the maximum number each time. $O(k \cdot n)$ or $O(k \log n)$. |
Binary Search on Value Threshold / Greedy Math |
Horizontal Cut-off Line |
Binary search for a price P such that we can sell all balls with value > P. Use Arithmetic Progression (AP) to calculate total profit. |
Draw inventory as a histogram (columns of balls). Draw a horizontal line at height P. Calculate the area of the bars above the line using the sum of AP formula. |
Logarithmic Search Range |
Draw a number line from 0 to \max(\text{inventory}). Draw brackets halving the range until P is found. $O(n \log(\\text{max})$). |
Priority Queue: A tree-like structure being modified k times. |
Variables + Sorting: A sorted array and a few integer variables for the math formulas. |
| 1649 |
Create Sorted Array through Instructions |
For each new number, iterate through the existing "sorted" part of the array to find the insertion point and shift elements. |
Linear Shift / Search |
Draw an array. For every new insertion, draw arrows showing every element to the right moving one step over. $O(n^2)$. |
Fenwick Tree (BIT) / Segment Tree |
Prefix Sum Accumulator |
Use a Fenwick Tree to store frequency of numbers. For each instruction x, `cost += min(query(x-1), total_so_far - query(x))`. Update BIT with x. |
Draw a Binary Indexed Tree (a tree where each node covers a range of frequencies). Mark nodes that update when a new number "drops" into the tree. |
Logarithmic Tree Update |
Draw a tree of height \log(\max). Show the update path from a leaf to the root for each of the n instructions. $O(n \log(\\text{max})$). |
Dynamic Array: A constantly resizing and shifting block of memory. |
BIT Array: A static array where each index stores a cumulative frequency sum. |
| 1650 |
Lowest Common Ancestor of a Binary Tree III |
Start from node p, traverse all the way to the root and store the path in a Set. Then traverse from q until a node is found in the Set. |
Path Hash Mapping |
Draw two paths from p and q to the root. Circle the path from p and drop it into a "Used" bucket. $O(h)$ space. |
Two Pointers (Linked List Intersection Style) |
Cycle Synchronization |
Pointer `a` starts at p, `b` at q. When `a` hits the root, jump to q. When `b` hits the root, jump to p. They will meet at the LCA. |
Draw two paths of different lengths. Show the pointers "switching" tracks to equalize the travel distance, meeting exactly at the junction. |
Linear Simultaneous Scan |
Draw two parallel arrows moving up the parent pointers. No extra structures. $O(h)$. |
Hash Set: A bucket storing node references from the first path. |
Two Pointers: Two small boxes holding the current node reference. $O(1)$ auxiliary space. |
| 1651 |
Hopper Company Queries III (SQL) |
Run 10 separate queries for each 3-month rolling window (Jan-Mar, Feb-Apr, etc.). |
Sequential Window Scan |
Draw 10 distinct SQL result sets being calculated one-by-one. $O(10 \cdot N)$. |
Recursive CTE + Window Function (ROWS BETWEEN) |
Sliding Window Overlay |
Generate 12 months. Join with monthly sums. Apply `AVG(...) OVER(ORDER BY month ROWS BETWEEN CURRENT ROW AND 2 FOLLOWING)`. |
Draw a table with 12 rows. Draw a physical bracket covering rows 1, 2, and 3. Slide it down row by row to show the average calculation. |
Single Linear Aggregation |
Draw a single pass through the month-summary table. $O(N)$. |
Temp Table Buffer: Draw multiple redundant copies of table segments. |
Aggregate Cache: Draw a single clean output table with a "lookahead" pointer. |
| 1652 |
Defuse the Bomb |
For every index i, run a loop to sum the next (or previous) k elements. |
Nested Loop Grid |
Draw an array. For every element, draw k arrows pointing to its neighbors. $O(N \cdot K)$. |
Fixed Size Sliding Window |
Rotating Circular Tape |
Calculate the initial sum of the first window. For the next element, add the "new" neighbor and subtract the "old" neighbor. Handle circularity with modulo. |
Draw the array as a circle. Draw a highlighter "window" of size k. Rotate the highlighter while updating the running sum. |
Linear Sweep |
Draw a single straight arrow circling the array exactly once. $O(N)$. |
Two Loop Counters: Simple floating pointers i and j. |
Sliding Window Sum: Draw a single box holding the current sum that updates N times. $O(1)$ aux space. |
| 1653 |
Minimum Deletions to Make String Balanced |
Try every possible split point i. For each i, count 'b's on the left and 'a's on the right to delete. |
N^2 Partition Search |
Draw a string. Draw a vertical line moving across it. At each position, draw two arrows scanning the whole string. $O(N^2)$. |
Dynamic Programming / Greedy Tally |
Balancing Scales |
Maintain a count of 'b's seen. If you encounter an 'a', you can either delete the current 'a' (cost +1) or delete all previous 'b's. Take the minimum. |
Draw a string. As you move right, keep a tally of 'b's. When an 'a' appears, decide: "Keep a and pay in B's" or "Drop a". Write the cost underneath each char. |
Single Linear Pass |
Draw a single horizontal arrow moving left to right. $O(N)$. |
Prefix/Suffix Arrays: Draw two full arrays of size N storing counts. |
Two Variables: Draw two boxes: `b_count` and `deletions`. $O(1)$ aux space. |
| 1654 |
Minimum Jumps to Reach Home |
Recursive DFS trying all forward and backward jumps without tracking visited states properly. |
Infinite Loop Graph |
Draw a character jumping back and forth on a number line forever. |
BFS (Breadth-First Search) |
Level-by-Level Ripple |
Use a Queue and a Visited Set that stores (position, direction). Direction matters because you can't jump back twice in a row. Stop at forbidden points or beyond the upper bound. |
Draw a number line. Mark forbidden spots with 'X'. Draw circles around reachable points, expanding outwards like a ripple until you hit 'home'. |
Bounded State Traversal |
Draw a graph where each node is a (position, flag). Total states are roughly 2 \times (\max\_pos + a + b). $O(N)$. |
Infinite Call Stack: Stack crashing due to cycles. |
Queue + HashSet: Draw a pipe (Queue) and a bucket (Set) holding coordinate-direction pairs. |
| 1655 |
Distribute Repeating Integers |
Backtracking to assign every single integer to a customer, checking if their requirements are met. |
Factorial Complexity Tree |
Draw a tree where each node branches for every possible customer. $O(N^M)$. |
Bitmask DP (Submask Iteration) |
Tetris Block Matching |
Calculate frequency of numbers. DP[i][mask] = can first i frequencies satisfy customer subset 'mask'. For each frequency, iterate through submasks. |
Draw a binary bitmask (e.g., 1011). Underneath, draw frequency "buckets". Try to fit the requirements of the 1-bits into the buckets. |
Submask Iteration Sum |
Draw a tree where each level has 3^M states (due to submask iteration math). $O(N \cdot 3^M)$. |
Deep Backtracking: Massive stack of partial assignments. |
2D/1D DP Array: Draw a grid of size [FreqCount][2^M]. |
| 1656 |
Design an Ordered Stream |
Every time an ID is inserted, sort the whole collection of IDs to find the next contiguous sequence. |
Sorting Funnel Bottleneck |
Draw a funnel where every single insertion forces N \log N work. Total $O(N^2 \log N)$ over N calls. |
Pointer-based Simulation |
Conveyor Belt with Stopper |
Keep an array of size N+1. When an ID is inserted, check if the current pointer `ptr` is at that ID. If yes, move `ptr` forward until you hit an empty slot. |
Draw an array. Place a marker (ptr) at index 1. When a value arrives at 1, move ptr right until it hits a blank. Those skipped indices are your output. |
Amortized Linear Scan |
Draw a single arrow that moves across the array exactly once over the lifetime of the object. $O(N)$ total. |
Dynamic List/Tree: Redundant memory overhead from complex data structures. |
Fixed-size Array: Draw a simple static horizontal array of size N+1. $O(N)$ space. |
| 1657 |
Determine if Two Strings Are Close |
Generate every possible string transformation using the two allowed operations (swap, transform) and check for equality. |
Exponential State Space |
Draw a starting string. Branch into thousands of possible transformed strings. $O(2^N)$ or worse. |
Frequency Maps + Character Set Comparison |
Histogram Signature Matching |
Two strings are "close" if: 1. They have the same unique characters. 2. The *sorted* frequency counts of those characters are identical. |
Draw two bar charts (histograms) of character frequencies. Sort the bars by height. If the shapes of the two bar charts are identical, they are close. |
Linear Scan + Fixed Sort |
Draw a straight arrow through the strings, then a small funnel for 26 characters. $O(N + 26 \log 26)$. |
Recursion State Set: Draw a massive bucket storing all generated string permutations. |
Two Arrays of size 26: Draw two fixed 26-slot grids. $O(1)$ auxiliary space. |
| 1658 |
Minimum Operations to Reduce X to Zero |
Try every combination of picking from the left and right ends using recursion/backtracking. |
Binary Choice Tree |
Draw a tree where each node branches to "Pick Left" or "Pick Right". $O(2^N)$. |
Sliding Window (Target = TotalSum - x) |
Inverse Sliding Frame |
Finding the min elements to remove from ends is the same as finding the *max length* contiguous subarray that sums to `Total - x`. |
Draw an array. Draw a rectangular "frame" (window) sliding across it. Keep track of the frame's sum and its max width. |
Linear Simultaneous Scan |
Draw two pointers moving from left to right across the array. $O(N)$. |
Recursive Call Stack: Draw a stack of depth N storing remaining sums. |
Two Pointers: Draw two boxes (`left`, `right`) and a `currentSum` variable. $O(1)$ space. |
| 1659 |
Maximize Grid Happiness |
Exhaustive search placing introverts and extroverts in every cell and calculating the resulting score. |
Grid Permutation Map |
Draw a grid and branch for every possible assignment (Empty, Intro, Extro) per cell. $O(3^{M \\text{times} N})$. |
DP + Ternary Bitmask (State Compression) |
Layered Row Slices |
DP state: `(index, intro_count, extro_count, prev_row_mask)`. Use a base-3 mask to represent the configuration of the previous row. |
Draw a grid. Shade the current cell and the N cells preceding it (the "frontier"). Write the state as a base-3 number (e.g., 012). |
Memoized Grid Fill |
Draw a massive table of states. $O(M \\text{times} N \\text{times} I \\text{times} E \\text{times} 3^N)$. |
Infinite Recursion: A stack of grids representing every partial assignment. |
4D/5D DP Table: Draw a high-dimensional matrix block in memory. |
| 1660 |
Correct a Binary Tree |
Traverse the tree and for every node, manually check all other nodes to see if any have a faulty right pointer. |
N-to-N Node Check |
Draw a tree where every node "looks" at every other node in the tree. $O(N^2)$. |
BFS (Reverse Level Order) + Hash Set |
Level-by-Level Boundary Check |
Traverse the tree from right to left using BFS. Store visited nodes in a Set. If a node's right child is already in the Set, it's a "back-edge". Delete it. |
Draw the tree levels. Draw an arrow on each level going Right-to-Left. If an arrow "jumps" to a node you've already seen on that same level, cut that branch. |
Single BFS Sweep |
Draw a line weaving through levels exactly once. $O(N)$. |
Full Tree Copy: Redundant storage for nodes during re-evaluation. |
Queue + Hash Set: Draw a horizontal pipe (Queue) and a bucket (Set) holding node references. $O(W)$ where W is width. |
| 1661 |
Average Time of Process per Machine (SQL) |
For every 'start' row, run a correlated subquery to find its matching 'end' row and subtract times. |
Row-by-Row Search Grid |
Draw a table. For every row, draw an arrow scanning the entire table again looking for a match. $O(N^2)$. |
Self-Join / Aggregate CASE WHEN |
Pivoted Timeline Alignment |
Group by machine_id. Use `AVG(CASE WHEN type='end' THEN timestamp ELSE -timestamp END * 2)`. |
Draw a table where each machine has two values: a negative 'start' and a positive 'end'. Sum them and divide by count. |
Single Table Scan |
Draw a straight arrow moving top-to-bottom through the table once. $O(N)$. |
Subquery Cache: Draw multiple redundant data buffers in RAM. |
Hash Aggregate Table: Draw a small summary table (MachineID | RunningSum) that fills in one pass. |
| 1662 |
Check If Two String Arrays are Equivalent |
Concatenate all strings in Array1 into String A, do the same for Array2 into String B, then compare A == B. |
Memory-Heavy Construction |
Draw multiple small boxes (strings) being glued into one giant, long box. $O(N + M)$ space. |
Two Pointers (Nested Indexing) |
Dual-Cursor Tape Read |
Pointer `p1` for array index, `i1` for char index. Pointer `p2` and `i2` for the second array. Compare char-by-char without joining. |
Draw two rows of boxes. Place two "needles" (pointers) at the start. Move the needles char-by-char. If a needle reaches the end of a box, jump it to the next box. |
In-Place Linear Scan |
Draw two parallel arrows moving across the original data structure without creating new ones. $O(N+M)$. |
Giant Strings: Draw two massive horizontal bars in memory. |
Four Integer Variables: Draw four small boxes: `arrIdx1, charIdx1, arrIdx2, charIdx2`. $O(1)$ space. |
| 1663 |
Smallest String With A Given Numeric Value |
Backtracking/DFS to generate every possible string of length N and calculating its value until you find the lexicographical minimum. |
26-Way Decision Tree |
Draw a tree where every node has 26 branches ('a' to 'z'). $O(26^N)$. |
Greedy (Fill from Back) |
Right-to-Left "Z" Saturation |
Start with a string of N 'a's. Subtract their value (N) from K. Iterate from the back: add \min(25, \text{remaining } K) to each 'a'. |
Draw N empty slots. Fill them all with 'a'. Go to the last slot and turn it into 'z'. If you still have value, move left. |
Single Linear Pass |
Draw a straight arrow moving from the right end to the left. $O(N)$. |
Recursive Stack: Draw a vertical stack of depth N holding partial strings. |
Char Array: Draw a single horizontal array of size N being modified in place. |
| 1664 |
Ways to Make a Fair Array |
For every index i, remove the element, then run a loop to sum all new even indices and all new odd indices. |
N^2 Re-Summing |
Draw an array. Draw N different "views" where one element is missing, each with its own full-scan summation. $O(N^2)$. |
Prefix Sums (Even/Odd Tracking) |
Running Balance Sheet |
Precompute total even/odd sums. As you iterate i, "even" indices after i become "odd", and vice versa. Use totals to calculate new sums in $O(1)$. |
Draw two rows: "Prefix Evens" and "Prefix Odds". When you "remove" a node, swap the "suffixes" of the two rows to see if they balance. |
Linear Scan with Constant Lookups |
Draw a single horizontal arrow with two summary boxes (LeftSum, RightSum). $O(N)$. |
Variable Counters: Simple loop indices. |
Four Variables / Two Arrays: Draw two prefix arrays or just four variables tracking running sums. $O(1)$ or $O(N)$ space. |
| 1665 |
Minimum Initial Energy to Finish Tasks |
Try every permutation of task orders (N!) to find the one that requires the least starting energy. |
Factorial Order Tree |
Draw a tree that branches N times, then N-1, etc. Total N! leaves. |
Greedy (Sort by Difference) |
Critical Margin Sorting |
Sort tasks by the difference between `minimum` and `actual` energy (descending). Process tasks that "save" the most margin first. |
Draw tasks as boxes with two numbers. Subtract the small number from the big one. Sort the tasks so the biggest gap comes first. |
Sorting Bottleneck |
Draw a funnel (O(N log N)) leading to a straight linear execution pipe. |
Permutation List: Draw a massive storage of all possible task sequences. |
Sorted Array: Draw the original array rearranged into a specific order. $O(1)$ or $O(N)$. |
| 1666 |
Change the Root of a Binary Tree |
Copy the entire tree into an adjacency list (Graph), then run BFS/DFS from the new root to rebuild the tree. |
Full Graph Conversion |
Draw a tree. Draw arrows going in both directions for every edge to show it's now a graph. $O(N)$. |
Recursive In-place Pointer Reversal |
Path Reversal / Link Flipping |
Traverse from `leaf` up to the original `root`. For each node, make its parent its child and adjust left/right pointers. |
Draw a tree. Pick a leaf. Draw a thick "path" to the root. Erase the parent-child arrows on that path and draw them in reverse. |
Linear Path Traversal |
Draw a single straight arrow from the leaf to the root. $O(H)$ where H is height. |
Adjacency List: Draw a table mapping every node to a list of neighbors. $O(N)$ space. |
Recursive Call Stack: Draw a narrow stack representing the depth of the path being reversed. $O(H)$. |
| 1667 |
Fix Names in a Table (SQL) |
Fetch all names into Python/Java, use string slicing to fix casing, and update the DB row by row. |
Network I/O Bottleneck |
Draw a database cylinder sending thousands of individual rows to a small computer icon. $O(N)$ network calls. |
String Concatenation + Substring functions |
Character-Level Masking |
Use `CONCAT(UPPER(LEFT(name, 1)), LOWER(SUBSTRING(name, 2)))`. This happens entirely within the DB engine. |
Draw a single name string. Place a "Magnifier" over the first letter (UPPER) and a "Filter" over the rest (LOWER). |
Single Table Scan |
Draw a straight arrow through the table. $O(N)$. |
Application Heap: Draw a massive bubble in RAM holding all table rows. |
Database Page Buffer: Draw a clean, localized memory block where the DB processes data in chunks. |
| 1668 |
Maximum Repeating Substring |
Check every possible count k by building a string of `word` repeated k times and checking if it exists in `sequence`. |
String Concatenation Loop |
Draw a string growing longer and longer (k, 2k, 3k...) and sliding across the sequence each time. $O(N^2)$. |
Dynamic Programming (Suffix-based) |
Match Accumulator Scan |
If `sequence[i:i+len(word)] == word`, then `dp[i] = 1 + dp[i+len(word)]`. Track the max value in the DP array. |
Draw the sequence. Below it, draw an array. When a word matches, draw a "link" to the next possible match point and add 1. |
Linear Scan |
Draw a single horizontal arrow moving right-to-left (or left-to-right) across the sequence. $O(N)$. |
Multiple Temp Strings: Draw numerous floating horizontal bars in memory. |
1D DP Array: Draw a single horizontal array of integers of size N. |
| 1669 |
Merge In Between Linked Lists |
Traverse list1 to find node a, store its reference. Traverse to find node b. Traverse list2 to find its tail, then link them all. |
Disconnected Segment Scan |
Draw three separate arrows scanning different parts of the two lists at different times. $O(N + M)$. |
Two Pointers (Marker Placement) |
Bridge Connection |
Pointer `prevA` stops at a-1. Pointer `afterB` stops at b+1. Link `prevA.next` to `list2.head` and `list2.tail.next` to `afterB`. |
Draw list1. Draw a "cut" before a and after b. Draw list2 dropping into the gap. Draw two "welding" lines (links) connecting the pieces. |
Linear Simultaneous Scan |
Draw two parallel arrows moving through list1 and one through list2. $O(N + M)$. |
Dummy Nodes / Lists: Draw extra nodes being created for temporary storage. |
Pointer Variables: Draw four small boxes: `curr`, `prevA`, `afterB`, and `tail2`. $O(1)$ space. |
| 1670 |
Design Front Middle Back Queue |
Use a single Array/List. For every "Middle" operation, use `list.add(index, val)` which shifts all subsequent elements. |
Array Shifting Cascade |
Draw an array. For an insertion, draw 50 arrows showing every element moving one slot to the right. $O(N)$. |
Two Deques (Balanced Halves) |
Balanced Scales |
Maintain two Deques: `left` and `right`. Keep their sizes equal (or `right` having one extra). Insert/Pop from either end or the "middle" (junction of the two). |
Draw two horizontal tubes meeting in the center. Mark the center point as the "Middle". Elements flow in/out of the ends or the center junction. |
Constant Time Operations |
Draw a dot (O(1)) for every operation, regardless of where the insertion happens. |
Continuous Memory Block: Draw one giant box that must resize and shift. |
Two Segmented Blocks: Draw two separate tubes. Rebalancing just moves one element between them. $O(N)$ total space. |
| 1671 |
Minimum Number of Removals to Make Mountain Array |
Check every possible peak index i, then for each peak, try every subset of elements to form a mountain. |
Power Set Explosion |
Draw a massive branching tree for every element (include/exclude). $O(2^N)$. |
LIS (Longest Increasing Subsequence) + LDS (Decreasing) |
Bidirectional Wavefront |
Calculate LIS from left-to-right and LDS from right-to-left. A "mountain" at i is `LIS[i] + LDS[i] - 1`. Find the max such value. |
Draw the array. Below it, draw two rows of numbers. One shows "longest climb" to that point, the other "longest descent" from that point. Look for the highest sum. |
Dual-Pass Linear / Log-Linear |
Draw two arrows: one moving L-to-R, one R-to-L. $O(N \log N)$ if using binary search for LIS. |
Recursive Call Stack: Stack of depth N storing all subsets. |
Two 1D Arrays: Draw two horizontal arrays of size N storing subsequence lengths. |
| 1672 |
Richest Customer Wealth |
Standard nested loops: sum each row, compare with global max. |
Linear Row Sweep |
Draw a grid. Draw an arrow scanning each row horizontally. $O(M \\text{times} N)$. |
Row-wise Iteration (Simple Scan) |
Horizontal Accumulator |
Iterate through customers. For each, sum their accounts. If current sum > max, update max. |
Draw a table. Add a "Total" column on the right. Write the sum for each row and circle the biggest one. |
Constant Flow Grid Scan |
Draw a single straight arrow weaving through every cell in the matrix once. $O(M \\text{times} N)$. |
Temporary Variable: Single sum variable. |
Single Integer: Draw one small box labeled `maxWealth`. $O(1)$ space. |
| 1673 |
Find the Most Competitive Subsequence |
Generate all subsequences of length K, sort them lexicographically, and pick the smallest. |
Combinatorial Sorted List |
Draw a massive sorted list of all \binom{N}{K} possible combinations. $O(\\text{binom}{N}{K} \cdot K)$. |
Monotonic Stack (Greedy) |
Stack-based "Kick-out" Logic |
Iterate through array. While current element is smaller than stack top AND we have enough elements left to fill K, pop from stack. Push current. |
Draw a vertical bucket (Stack). As you process numbers, if a "smaller" number arrives, erase the "bigger" ones above it to make room, but only if the remaining numbers in the array are enough to reach K. |
Single Linear Pass |
Draw one horizontal arrow scanning the array. $O(N)$. |
Large Subsequence Buffer: Massive memory to store all combinations. |
Stack / 1D Array: Draw a single horizontal array/stack of size K. $O(K)$ space. |
| 1674 |
Minimum Moves to Make Array Complementary |
Try every possible target sum S from 2 to 2 \times \text{limit}, and for each, count moves needed for all pairs. |
Target-Sum Sweep Grid |
Draw a range 2 to 2 \times \text{limit}. For each number, draw N/2 arrows checking pairs. $O(\\text{text}{\text{limit}} \\text{times} N)$. |
Difference Array (Line Sweep) |
Range Impact Overlay |
For each pair (a, b), identify move boundaries: [2 moves], [1 move], [0 moves]. Use a Difference Array to add +1 or +2 to these ranges in $O(1)$. |
Draw a long number line (2 to 2 \times \text{limit}). For each pair, draw "brackets" showing where moves increase or decrease. Sum the overlaps. |
Linear Range Scan |
Draw two arrows: one to build the difference array $O(N)$, one to prefix-sum it $O(\\text{text}{\text{limit}})$. Total $O(N + \\text{text}{\text{limit}})$. |
Nested Loop Counts: Constant recalculation without storage. |
1D Difference Array: Draw an array of size 2 \times \text{limit} where only the "boundary" changes are stored. |
| 1675 |
Minimize Deviation in Array |
Generate every possible version of every number (by multiplying/dividing by 2) and check every subset for the smallest range. |
Exhaustive Range Search |
Draw a tree where each leaf is a unique combination of transformed numbers. $O(\\text{text}{\text{Too much to calculate}})$. |
Priority Queue (Max-Heap) + Greedy Shrinking |
Squeezing the Range |
Convert all odds to evens (multiply by 2). Put all in a Max-Heap. Keep track of the minimum. Pop the max, calculate deviation, divide it by 2, push back, and update min. Stop when max is odd. |
Draw a Max-Heap (Pyramid). Draw a "Min" box on the side. Pop the top of the pyramid, half it, and put it back in. Watch the "Max" and "Min" values get closer together. |
Heap-Logarithmic Convergence |
Draw a funnel (Heap) processing N \log(\max) operations. $O(N \log N \cdot \log(\\text{max})$). |
Transformation Matrix: Storing all possible states of all numbers. |
Max-Heap + Variable: Draw a binary tree (heap) and one integer box (`currentMin`). $O(N)$ space. |
| 1676 |
Lowest Common Ancestor of a Binary Tree IV |
For every pair of nodes in the input array, find their LCA individually, then find the LCA of those results. |
Recursive Pairwise Tree |
Draw a tree. Draw multiple colored paths meeting at different junctions over and over. $O(\text{Nodes} \\text{times} K)$. |
DFS (Post-order) + Target Set |
Simultaneous Node Reporting |
Throw all target nodes into a Hash Set. Run DFS. A node returns itself if it is in the Set. If a node receives "found" reports from both subtrees, it is an LCA candidate. |
Draw a tree. Mark target nodes with stars. Draw arrows moving up from stars. The highest node where the number of "star-reports" equals the target list size is the answer. |
Single Depth-First Scan |
Draw one continuous line weaving through every node exactly once. $O(N)$. |
Multiple Path Sets: Draw several separate buckets for each individual LCA search. |
Hash Set + Call Stack: Draw one small bucket (Set) and a vertical stack for recursion. $O(H + K)$. |
| 1677 |
Product's Worth Over Invoices (SQL) |
Use correlated subqueries in the SELECT clause to sum Rest, Paid, Canceled, and Refunded amounts for each product. |
Nested Loop Subquery Grid |
Draw a Product table. For each row, draw 4 separate magnifying glasses scanning the entire Invoice table. $O(P \\text{times} I)$. |
LEFT JOIN + GROUP BY + IFNULL/COALESCE |
Product-Invoice Pivot Table |
Join Product to Invoice. Group by Product Name. Sum all invoice columns. Use `IFNULL(..., 0)` to handle products without invoices. |
Draw a table on the left (Products) and right (Invoices). Draw lines connecting them. Collapse all invoices for one product into a single "Summary Row". |
Single Simultaneous Scan |
Draw a straight arrow through both tables once to build a hash-aggregate. $O(P + I)$. |
Temp Multi-Table Memory: Draw redundant memory buffers for each subquery. |
Hash Aggregate Buffer: Draw a small table in RAM being updated as invoices are read. |
| 1678 |
Goal Parser Interpretation |
Use a series of global "Replace All" string functions for every pattern ("G", "()", "(al)"). |
Multi-Pass String Splicing |
Draw a string. Draw an arrow scanning it for "G". Then draw a whole new arrow scanning the new string for "()", etc. $O(N^2)$. |
Single-Pass Pointer Scan |
Text Stream Decoding |
Iterate through the string. If current is 'G', append 'G'. If '(', check next: if ')', append 'o'; if 'a', append 'al'. |
Draw a string of characters. Place a finger (pointer) on a letter. Look at the next 1-2 letters. Write the decoded result in a box underneath. |
Linear Stream Arrow |
Draw a single straight arrow moving left to right once. $O(N)$. |
Intermediate Strings: Draw numerous floating blocks for each replaced version of the string. |
StringBuilder / Result Array: Draw a single growing horizontal box. $O(N)$ space. |
| 1679 |
Max Number of K-Sum Pairs |
Nested loops to find every pair (i, j) that sums to k. When a pair is found, "remove" both and restart search. |
Quadratic Pair Search |
Draw an array. Draw a line from the first number checking every other number. Repeat. $O(N^2)$. |
Two Pointers (Sorted) or Hash Map (Frequency) |
Symmetric Squeeze / Bucket Matching |
Sort array. Pointer `left` at start, `right` at end. If sum > k, move `right` in. If sum < k, move `left` in. If equal, count and move both. |
Draw a sorted line of numbers. Draw two arrows at the ends pointing inward. When they point to a pair that sums to k, circle them and move the arrows. |
Sorting Bottleneck |
Draw a funnel (O(N log N)) leading to a linear scan (O(N)). Total $O(N \log N)$. |
Nested Loop Markers: Simple loop indices. |
Frequency Map: Draw a 2-column table (Num | Count) or a single sorted array. $O(N)$ space. |
| 1680 |
Concatenation of Consecutive Binary Numbers |
For each number i from 1 to n, convert i to a binary string, concatenate all strings, then convert the massive string back to decimal. |
Heavy String Conversion |
Draw numbers turning into binary text ribbons, being taped together, then re-parsed. $O(N \\text{times} \\text{text}{\text{Length}})$. |
Bit Manipulation (Shift and Add) |
Binary Sliding Accumulator |
Maintain a `result`. For each i, determine its bit-length. Shift `result` left by that length and add i. Take modulo at each step. |
Write current total in binary. To add the next number, "push" the total to the left to make empty spaces, then write the next number in those spaces. |
Direct Mathematical Loop |
Draw a single loop from 1 to n where each step is a bit-shift. $O(N)$. |
Massive String Buffer: Draw a giant ribbon of text. $O(N \log N)$ space. |
Single 64-bit Variable: Draw one small box holding the running total. $O(1)$ auxiliary space. |
| 1681 |
Minimum Incompatibility |
Backtracking to try every possible way of partitioning n numbers into k groups of size n/k. |
Factorial Branching Tree |
Draw a root node splitting into every possible subset of size n/k. Repeat for remaining. $O(N! / (n/k)$!^k). |
Bitmask DP + Submask Iteration |
State-Space Matrix |
dp[\text{mask}] represents the min incompatibility for a used subset of numbers. Iterate through submasks of size n/k that are valid (unique numbers). |
Draw a bitmask (e.g., 1011). Show it splitting into a valid submask (1001) and a remaining mask (0010). Write incompatibility sums in the nodes. |
Exponential Grid Fill |
Draw a row of 2^N states. For each, show a loop of size \binom{n}{n/k}. $O(3^N)$ or $O(2^N \cdot \\text{binom}{n}{n/k})$. |
Recursive Call Stack: Massive stack of partial group assignments. |
1D DP Array: Draw a horizontal array of size 2^N storing integers. |
| 1682 |
Longest Palindromic Subsequence II |
Exhaustive recursion to find all subsequences, checking if each is an even-length palindrome with no two adjacent identical chars. |
Binary Choice Tree |
Draw a tree branching for every character (Include/Exclude). $O(2^N)$. |
3D Dynamic Programming |
Multi-Layered Grid |
dp[i][j][\text{last\_char}]: Max length for s[i \dots j] where the outer char is `last_char`. Base case: i, j match and
eq \text{prev}. |
Draw an N \times N grid. For each cell, draw a 26-slot vertical "depth" bar representing the possible last characters used. |
3D Cube Fill |
Draw a cube N \times N \times 26 being filled from small ranges to large ranges. $O(26 \cdot N^2)$. |
Recursive Call Stack: Deep stack of string slices. |
3D Array: Draw a block representing the N \times N \times 26 structure. |
| 1683 |
Invalid Tweets (SQL) |
Fetch all tweets into a script, loop through, and count characters in the content string one by one. |
Network Data Stream |
Draw a DB cylinder sending full text blobs to a CPU icon. $O(N \\text{times} \\text{text}{\text{AvgLength}})$. |
SQL Length Function (LENGTH/CHAR_LENGTH) |
Filtered Column Scan |
Use `WHERE LENGTH(content) > 15`. This runs natively in the database engine. |
Draw a single column (Content). Draw a "Ruler" next to it. If the ruler marks > 15, highlight the row in green. |
Single Linear Table Scan |
Draw a straight arrow through the table. $O(N)$. |
App Heap RAM: Draw a large box holding all tweet text. |
Buffer Cache: Draw a small page-sized block where strings are measured and discarded. |
| 1684 |
Count the Number of Consistent Strings |
For each string in the array, loop through every character and check if it exists in the 'allowed' string using `allowed.contains()`. |
Nested Character Scan |
Draw N strings. For each, draw an arrow scanning every character and checking a separate "allowed" list. $O(N \\text{times} \\text{text}{\text{WordsLength}} \\text{times} \\text{text}{\text{AllowedLength}})$. |
Boolean Frequency Array / Hash Set |
Stencil Filter Overlay |
Convert 'allowed' into a boolean array of size 26. For each word, check if every char maps to `true` in the array. |
Draw a 26-slot checklist. Check the "allowed" letters. Slide each word through a "stencil" with holes for those letters. If it fits, count it. |
Linear Aggregate Scan |
Draw a straight arrow through all words. $O(\text{Total Characters})$. |
Variable Counters: Simple loop indices. |
Size-26 Boolean Array: Draw a small 26-box grid. $O(1)$ space. |
| 1685 |
Sum of Absolute Differences in a Sorted Array |
For every index i, run a second loop to calculate |nums[i] - nums[j]| for all j. |
Quadratic Difference Matrix |
Draw an N \times N grid of all possible subtraction results. $O(N^2)$. |
Prefix Sums (Mathematical Simplification) |
Sectional Area Calculation |
Total Diff = (Nums to left \times val - LeftSum) + (RightSum - Nums to right \times val). Use precomputed prefix sums to get Left/Right sum in $O(1)$. |
Draw a bar chart of the array. For any bar, the sum of differences is the area of the "empty space" to its left plus the area above it to its right. |
Single Linear Pass |
Draw a straight arrow through the array. $O(N)$. |
Nested Loop Markers: Simple loop indices. |
Prefix Sum Array: Draw a single horizontal array of size N storing cumulative totals. |
| 1686 |
Stone Game VI |
Backtracking to simulate every possible sequence of moves by Alice and Bob to find the optimal scores. |
Game Decision Tree |
Draw a tree where each level represents a turn. Each node branches into N remaining stones. $O(N!)$. |
Greedy (Sorting by Combined Value) |
Value Sum Comparison |
Alice and Bob don't just pick their best; they pick the stone that denies the most to the opponent. Sort by `aliceValues[i] + bobValues[i]`. |
Draw a 3-column table: Alice's Value | Bob's Value | Sum. Sort the rows by Sum (desc). Mark 'A' for the first row, 'B' for second, and so on. |
Sorting Bottleneck |
Draw a funnel (O(N log N)) leading to a simple linear sum $O(N)$. |
Recursive Stack: Deep stack of stone states. |
2D Array / Pair List: Draw a table of N rows and 3 columns for sorting. $O(N)$ space. |
| 1687 |
Delivering Boxes from Storage to Ports |
Backtracking to try every possible split point for the truck's trips. |
Partition Tree |
Draw a string of boxes. Branch for every possible number of boxes the truck can take in trip 1. $O(2^N)$. |
DP + Monotonic Queue (Sliding Window) |
Sliding Trip Window |
Use DP[i] to store min trips for i boxes. Optimize the range [j, i] using a queue to keep track of the best j that fits truck limits. |
Draw a line of boxes. Draw a "Truck Window" sliding over them. Maintain a "Trip Counter" that increments when consecutive boxes go to different ports. |
Linear Optimized Scan |
Draw a single horizontal arrow through the boxes with a "look-back" window. $O(N)$. |
Call Stack: Stack of partial trip counts. |
1D DP Array + Deque: Draw a horizontal array and a small "Tube" (Queue) with elements sorted by value. |
| 1688 |
Count of Matches in Tournament |
Recursive simulation: if N is even, N/2 matches; if odd, (N-1)/2 matches. Update N until N=1. |
Tournament Bracket Tree |
Draw a standard tournament bracket (pyramid). Count the horizontal lines (matches). $O(\log N)$. |
Mathematical Insight (Elimination) |
Single Match Winner Logic |
Every match eliminates exactly one team. To get 1 winner from N teams, you must eliminate N-1 teams. Result is always N-1. |
Draw N dots. Circle two dots and draw an 'X' over one. Continue until only one dot is left without an 'X'. |
Constant Time |
Draw a single calculation box. $O(1)$. |
Recursive Stack: Stack of depth \log N. |
Variables: One box holding the result. $O(1)$ space. |
| 1689 |
Partitioning Into Minimum Deci-Binary Numbers |
Backtracking or greedy subtraction: find the largest deci-binary possible and subtract until zero. |
Successive Subtraction Flow |
Draw the number. Subtract 111... repeatedly. Draw an arrow for every subtraction. $O(N \\text{times} \\text{text}{\text{Value}})$. |
Greedy (Maximum Digit) |
Peak Digit Identification |
A deci-binary number uses only 0s and 1s. To satisfy a digit '9', you need at least nine 1s in that position. Thus, the answer is just the max digit in the string. |
Write the string (e.g., "3271"). Scan every character. Circle the largest digit. |
Single Linear Scan |
Draw a straight arrow through the string. $O(N)$ where N is string length. |
Recursive State: Deep stack of subtraction results. |
Variable: One small box labeled `maxDigit`. $O(1)$ space. |
| 1690 |
Stone Game VII |
Recursion with all possible choices (remove left or remove right) for each turn to find max score difference. |
Minimax Recursion Tree |
Draw a tree where each node splits into "Left" and "Right". Height of tree is N. $O(2^N)$. |
2D Interval Dynamic Programming |
Triangular DP Matrix |
DP[i][j] stores the max score difference for the range [i, j]. Use prefix sums to calculate range sums in $O(1)$. |
Draw an N \times N matrix. Fill the diagonals first (length 1), then length 2, then 3, until you reach the top-right corner. |
Matrix Fill Area |
Draw a 2D square. Shade the upper-right triangle representing the states being calculated. $O(N^2)$. |
Deep Recursion Stack: Stack of depth N storing range indices. |
2D DP Array: Draw a square grid of size N \times N. $O(N^2)$ space. |
| 1691 |
Maximum Height by Stacking Cuboids |
Try every permutation of cuboid orientations and every possible stacking order. |
Factorial Permutation Tree |
Draw a node branching into N! paths, with each node having 3^N orientation sub-branches. $O(N! \cdot 3^N)$. |
Dimension Sorting + LIS (Dynamic Programming) |
DAG of Valid Stacks |
Sort dimensions within each cuboid (w \leq l \leq h). Sort cuboids by total dimensions. Apply LIS logic: dp[i] = h[i] + \max(dp[j]) where cuboid j fits under i. |
Draw cuboids as sorted triplets. Draw arrows from smaller cuboids to larger ones they can support. Label each cuboid with its "max cumulative height". |
Nested Loop Triangle |
Draw an N \times N triangular grid representing the i and j loops. $O(N^2)$. |
Recursive Stack: Draw a stack of depth N storing all partial stack states. |
1D DP Array: Draw a horizontal array of size N storing max heights. $O(N)$ space. |
| 1692 |
Count Ways to Distribute Candies |
Backtracking to assign every candy to every possible bag, checking for empty bags at the end. |
Assignment Decision Tree |
Draw a tree where each level (candy) branches into K paths (bags). $O(K^N)$. |
DP (Stirling Numbers of Second Kind) |
State Transition Table |
dp[n][k] = k \cdot dp[n-1][k] + dp[n-1][k-1]. Logic: Candy n either joins an existing bag (k choices) or starts a new bag. |
Draw a grid (Candies vs. Bags). For each cell (n, k), show it pulling values from the cell above and the cell top-left. |
2D Matrix Fill |
Draw a square grid of size N \times K being filled row-by-row. $O(N \cdot K)$. |
Recursive Call Stack: Stack of depth N tracking candy assignments. |
2D DP Table: Draw a grid of size N \times K. $O(N \cdot K)$ space (or $O(K)$ if optimized). |
| 1693 |
Daily Leads and Partners (SQL) |
Fetch all records to application memory, iterate through, and use nested sets to count unique pairs per day. |
Row-by-Row Comparison |
Draw a table. Draw a loop scanning the entire table for every unique date/brand. $O(N^2)$. |
Group By + Aggregate COUNT(DISTINCT) |
Bucket Partitioning |
Partition the table by `date_id` and `make_name`. Inside each bucket, count unique `lead_id` and `partner_id`. |
Draw a table split into distinct color-coded boxes. In each box, list the IDs and circle only the unique ones. |
Single Table Pass |
Draw a straight arrow moving top-to-bottom through the table once. $O(N)$. |
Application Map: Draw a massive nested Hash Map structure in RAM. |
Hash Aggregate Buffer: Draw small buckets in memory that increment as the DB scans. |
| 1694 |
Reformat Phone Number |
Manual string concatenation with complex if-else logic for every possible remainder (2, 3, 4). |
Conditional Splicing |
Draw a string. Draw multiple branching arrows for each "if" condition during parsing. $O(N)$. |
Iterative Cleanup + Block Processing |
Pointer-based Grouping |
Remove spaces/dashes. While length > 4, take 3 digits. Handle the last 2, 3, or 4 digits specifically (2-2 or 3). |
Draw a digit string. Draw vertical "cut" lines every 3 digits. If the tail has 4 digits, erase the last cut and draw one in the middle (2-2). |
Linear Stream Arrow |
Draw a single straight arrow moving left to right once. $O(N)$. |
Temp String Fragments: Draw multiple floating small text blocks. |
StringBuilder / Result Array: Draw a single growing horizontal box. $O(N)$ space. |
| 1695 |
Maximum Erasure Value |
Check every possible subarray, use a Set to verify uniqueness, and calculate the sum for each. |
Quadratic Subarray Scan |
Draw an array. Draw N start pointers, each with N end pointers scanning. $O(N^3)$ or $O(N^2)$. |
Sliding Window + Hash Set |
Elastic Frame with Duplicate Alert |
Expand `right` and add to sum. If `nums[right]` is in Set, shrink `left` and subtract from sum until the duplicate is gone. Track max sum. |
Draw an array. Draw a rectangular "frame". If a number enters the frame that's already there, move the left side of the frame forward like a rubber band snapping. |
Two-Pointer Linear Scan |
Draw two arrows (`left`, `right`) moving left to right across the array. $O(N)$. |
Nested Loop Sums: Redundant variable calculations. |
Hash Set + Variables: Draw a bucket (Set) and two boxes (`currSum`, `maxSum`). $O(\text{min}(N, K)$) space. |
| 1696 |
Jump Game VI |
Dynamic Programming: for each index i, look back at all indices from i-1 to i-k to find the max score. |
Scanning Window Overlap |
Draw an array. For each cell, draw k arrows pointing backwards to previous cells. $O(N \\text{times} K)$. |
DP + Monotonic Queue (Deque) |
Sliding Max-Window Deque |
Use a Deque to store indices of potential max scores. Ensure the Deque is always decreasing. Pop indices out of the k-range. DP[i] = nums[i] + DP[deque.front()]. |
Draw an array and a small "Tube" (Deque) above it. Write indices in the tube. When a new number comes, "kick out" smaller numbers from the back of the tube. |
Linear Amortized Scan |
Draw a single horizontal arrow moving through the array. $O(N)$. |
DP Array: A static array of size N. |
Deque + DP Array: Draw a horizontal array and a small segmented tube for the Deque. $O(N + K)$. |
| 1697 |
Checking Existence of Edge Length Limited Paths |
For every query (u, v, limit), run a BFS/DFS only using edges with weight < limit. |
Repetitive Graph Traversal |
Draw a graph. For each of the Q queries, draw a magnifying glass scanning the whole edge list. $O(Q \\text{times} E)$. |
Offline Queries + Union-Find (DSU) |
Sorted Edge Injection |
Sort both edges and queries by weight. Iterate through sorted queries; for each, add all edges with weight < query limit into the DSU. Check `find(u) == find(v)`. |
Draw a set of disconnected dots. Draw edges sorted by thickness. "Inject" thin edges first, then query connections, then inject medium edges. |
Sorting + DSU Path Compression |
Draw two funnels (Sort E, Sort Q) leading into a single DSU "Tree of Trees". $O(E \log E + Q \log Q)$. |
Adjacency List: A standard web of linked nodes. |
DSU Parent Array: Draw an array where indices point to their root "Parent". $O(V + Q)$. |
| 1698 |
Number of Distinct Substrings in a String |
Generate every possible substring and insert them into a Hash Set. Count the size of the set. |
N^2 Substring Grid |
Draw a grid of all start and end points. Each cell contains a text string. $O(N^3)$ (including hashing). |
Suffix Automaton (SAM) or Rolling Hash |
State Machine Transitions |
Build a Suffix Automaton. Each node represents a set of substrings. Total distinct substrings = \sum (len(node) - len(link(node))). |
Draw a directed graph where nodes are "states" and arrows are characters. Count the total number of unique paths from the start node. |
Linear State Building |
Draw a single arrow building the automaton state-by-state. $O(N)$. |
HashSet of Strings: Draw a massive bucket overflowing with redundant text blocks. $O(N^3)$ space. |
SAM Graph: Draw a clean web of nodes and transition edges. $O(N)$ space. |
| 1699 |
Number of Calls Between Two Persons (SQL) |
Self-join the table to find (A, B) and (B, A) pairs, then use UNION to combine and group them. |
Redundant Cartesian Join |
Draw a table joined to itself, creating a massive matrix of duplicate calls. $O(N^2)$. |
SQL LEAST() and GREATEST() Functions |
Sorted Key Normalization |
Transform every row so `person1` is always the smaller ID and `person2` is the larger. `GROUP BY LEAST(p1, p2), GREATEST(p1, p2)`. |
Draw a table with two columns. For each row, write the smaller ID on the left and larger on the right. Group the identical rows. |
Single Table Pass |
Draw a straight arrow through the table once. $O(N)$. |
Temp Union Tables: Multiple redundant copies of the dataset in memory. |
Hash Grouping Buffer: Draw a single aggregate table in RAM. $O(N)$. |
| 1700 |
Number of Students Unable to Eat Lunch |
Simulate the queue: if the front student doesn't want the top sandwich, move them to the back. Repeat until no one takes the top sandwich. |
Cyclic Queue Rotation |
Draw a circle of students and a stack of sandwiches. Draw an arrow circling the students repeatedly. $O(N^2)$. |
Frequency Counting (Greedy) |
Student Type Bucketing |
Count students who want type 0 and type 1. Iterate through sandwiches. If a sandwich of type X is on top and `count[X] == 0`, no more sandwiches can be eaten. |
Draw two buckets: "Wants 0" and "Wants 1". As you go down the sandwich stack, decrement the corresponding bucket. Stop when a bucket hits zero. |
Linear Sandwich Scan |
Draw a single horizontal arrow through the sandwich array. $O(N)$. |
Queue + Stack: Two full data structures tracking order. |
Two Integer Variables: Draw two small boxes: `count0` and `count1`. $O(1)$ space. |
| 1701 |
Average Waiting Time |
Simulate timeline minute-by-minute, checking if a chef is busy or free for every single minute. |
Timeline Expansion (1D Number Line with unit steps). |
Draw a long horizontal line. Make a tick for *every* minute. Shade segments where the chef works. |
Greedy / Event Simulation (State tracking). |
State Jump Timeline (jumping from event to event instead of minute to minute). |
Track one variable: `next_free_time`. Jump it to `max(arrival, next_free_time) + prep_time`. |
Draw a timeline. Only draw dots for arrival times. Draw a jumping arrow updating the `free_time` pointer. |
Linear Flowchart (Single Pass over input array). |
Draw the array `N`. Draw an arrow passing through it exactly once. Label it $O(N)$. |
Array of size T (max time) to represent chef's schedule. Box grid. |
Two solitary boxes: `current_time` and `total_wait`. Eraser marks updating them. $O(1)$ space. |
| 1702 |
Maximum Binary String After Change |
BFS/Backtracking. Try applying rules (00->10, 10->01) on every possible index, generating a tree of strings. |
State-Space Search Tree. |
Draw a root circle with the starting string. Draw branches for every valid rule application. Grows exponentially. |
Greedy / Math (Zero Counting). |
Block Shifting / Swapping visual. |
Push all '1's after the first '0' to the right. Convert all '0's to '1's except one '0'. |
Draw string. Circle the first '0'. Cross out remaining '0's, write '1'. Move the circled '0' right by (zero_count - 1). |
Two-Pass Array Scan. |
Draw array. Arrow 1: Find first zero. Arrow 2: Count zeroes. Write $O(N)$. |
Call Stack / Queue representation holding multiple string permutations (huge memory). |
Three integer boxes: `first_zero_idx`, `zero_count`. $O(1)$ space visual. |
| 1703 |
Minimum Adjacent Swaps for K Consecutive Ones |
Find all combinations of K ones, calculate swap distance for each to group them together. |
Combination Matrix / Nested Loops. |
Draw array. Pick K items. Draw curved lines to pull them together. Repeat for next combination. |
Sliding Window over an array of indices + Median greediness. |
Window frame sliding over the 'Indices Array'. Target converging on the median. |
Extract indices of all '1's. Slide a window of size K. The optimal meeting point is the median index of this window. |
List indices of '1's. Draw a bracket of size K. Circle the middle element. Draw arrows from others to the middle. |
Sliding Window Cost Update. |
Draw array of size N (for extraction) + Window sliding over size M (M<=N). $O(N)$. |
Temporary arrays for every combination tested. |
One array `P` (storing indices), and a prefix sum array `Pref` for $O(1)$ cost calculation. $O(N)$ space. |
| 1704 |
Determine if String Halves Are Alike |
Split string. Loop over half 1, check if char in 'aeiouAEIOU' string. Loop over half 2. Compare. |
Split Array & Linear Scan. |
Draw string cut in half. Draw tick marks under vowels in left, then right. |
Two Pointers (Left & Right) converging to center, using a Hash Set for vowels. |
Two Pointers converging. |
Pointer L starts 0, Pointer R starts end. Move inwards. If L sees vowel, `count++`. If R sees vowel, `count--`. |
Draw string. `L ->` at start, `<- R` at end. Tally marks in the center (+1 for L, -1 for R). Target is 0. |
Converging Arrows. |
Draw array. Arrow from left, Arrow from right meeting in the middle. $O(N)$. |
Two new string allocations for `half1` and `half2` (O(N) space). |
A small HashSet box containing 10 vowels. $O(1)$ space. |
| 1705 |
Maximum Number of Eaten Apples |
Nested loop: For every day, scan all remaining apples to find the one that rots earliest. |
2D Grid Check (Days vs Apples array). |
Draw days on X axis. Draw apples on Y axis. Cross-reference every day with every remaining apple pile. $O(N^2)$. |
Min-Heap (Priority Queue) tracking `[rot_day, count]`. |
Funnel / Sorting Machine. |
Every day, toss `[rot_day, apples]` into funnel. Shake funnel (heapify). Drop rotten ones. Eat 1 from the top. |
Draw a tree (Min-Heap). Root is always smallest `rot_day`. Cross out root if expired. Decrement count if eaten. |
Tree Insertion/Extraction (Logarithmic scaling). |
Draw N elements flowing into a triangle (Heap). Label height as Log(N). Total: $O(N \log N)$. |
Massive daily snapshot arrays. |
A Binary Tree structure (Heap array) storing at most N tuples. $O(N)$ space. |
| 1706 |
Where Will the Ball Fall |
Deep recursion tree trying every path, checking boundaries repeatedly without caching. |
Branching Maze Search. |
Draw a grid. Draw squiggly lines bouncing off walls blindly. |
Iterative Grid Simulation. |
Pinball Plinko Drop. |
Drop ball at col `c`. Look at `grid[r][c]`. If 1, check right for V-shape. If -1, check left. If clear, drop to `r+1`. |
Draw grid cells. Draw a diagonal arrow `` for 1, `/` for -1. Trace a solid line mapping the drop path. Stop if it hits a `V`. |
Independent Parallel Lines. |
Draw N starting nodes. Draw straight lines down M levels. Label $O(M \cdot N)$. |
Deep Call Stack frames (O(M) memory for recursion). |
One single integer `current_col` per ball. $O(1)$ space visual. |
| 1707 |
Maximum XOR With an Element From Array |
For every query, loop over all numbers. Filter numbers <= `m`. Calculate XOR for all, track max. |
Nested Loop Multiplication. |
Draw Q query boxes. From each, draw N arrows pointing to the nums array. Write $O(Q \cdot N)$. |
Offline Queries + Bitwise Trie. |
Water Valve into a Filtering Tree. |
Sort queries by `m`. Sort `nums`. Slide pointer in `nums` up to `m`, adding to Trie. Traverse Trie picking opposite bits for max XOR. |
Draw sorted nums. Draw an expanding bracket up to `m`. Draw a binary tree (0s left, 1s right). Trace path taking opposite branches. |
Sort + Constant Depth Tree Traversal. |
Draw sort arrays $O(N \log N + Q \log Q)$. Draw Trie traversal straight down 32 levels: $O(32 \cdot Q)$. |
Array of results created piecemeal. |
A Binary Tree where each node has 2 children (0 and 1) max depth 32. $O(N)$ space. |
| 1708 |
Largest Subarray Length K |
Generate all possible subarrays of length K. Compare them element by element to find the lexicographically largest. |
Overlapping Window Matrix. |
Draw long array. Draw many brackets of size K. Draw comparison arrows between every single bracket. |
Greedy Peak Finding (Single Element Identifier). |
Sniper Scope on Valid Range. |
Because elements are unique, the largest subarray of length K MUST start with the maximum number available in indices `0` to `N-K`. |
Draw array. Bracket indices `0` to `N-K`. Circle the largest number in that bracket. Take K items from there. |
Single Partial Pass. |
Draw array. Arrow scanning only the first N-K elements. Label $O(N-K)$. |
Storing multiple sub-arrays in memory for comparison: $O(N \cdot K)$. |
Two solitary boxes: `max_val` and `max_idx`. $O(1)$ space visual. |
| 1709 |
Biggest Window Between Visits (SQL) |
Self-join the table to find the immediate next visit for every user, filtering by date > current date. |
Cartesian Product Cross-Hatch. |
Draw table A and table B. Draw lines connecting every row in A to every row in B. Cross out invalid dates. |
SQL Window Function: `LEAD()` over Partition. |
Row-by-Row Peeking (Rolodex). |
Sort by user, then date. Use `LEAD(date)` to peek at the next row's date. If null, use '2021-01-01'. Subtract current from next. |
List dates in a column. Draw an arrow from Row 1 curving directly to Row 2 to pull its value up. Calculate diff. |
Sequential Sort and Scan. |
Draw unsorted table -> sort funnel $O(N \log N)$ -> straight line scan $O(N)$. |
Massive intermediate joined tables (N^2 row explosions). |
One extra temporary column appended next to the original column in memory. $O(N)$ space. |
| 1710 |
Maximum Units on a Truck |
0/1 Knapsack Dynamic Programming or generating all combinations of boxes to fit the truck size. |
2D DP Grid / Exponential Tree. |
Draw a grid of Items vs Capacity. Fill out every cell calculating max value for every weight step. |
Greedy + Sorting. |
Filling a bucket with the heaviest gold first. |
Sort boxes by units per box (descending). Throw boxes onto truck until truck size is full. If a whole box batch doesn't fit, take a fraction. |
Draw boxes of different sizes. Write 'Value' on them. Sort them. Draw a truck box. Move highest value boxes in until full. |
Sort + Linear Accumulation. |
Draw blocks rearranging (O(N log N)). Draw an arrow moving left to right summing values $O(N)$. |
A 2D matrix of size `N * TruckCapacity`. |
In-place sorting on the input array. $O(1)$ extra space. |
| 1711 |
Count Good Meals |
Nested loop over all pairs. Check if `sum(arr[i], arr[j])` is a power of 2 using bitwise AND. |
Complete Graph Connections. |
Draw array elements in a circle. Draw lines connecting every single node to every other node. $O(N^2)$. |
Hash Map (Frequency Map) + Two Sum variant for 22 static targets. |
Vending Machine / Target Lock. |
Iterate array. For each num, calculate `target - num` for all powers of 2 (up to 2^21). Look up targets in Hash Map. Add to answer, then add `num` to Map. |
Draw array and a box for Hash Map. Point to current element. Draw 22 branching arrows to potential "partners" in the Map. |
Linear Scan with Constant Magnifying Glass. |
Draw array of size N. Draw a magnifying glass over one item split into 22 small rays. Label $O(22 \cdot N)$ -> $O(N)$. |
Two integer pointers. $O(1)$ space. |
Hash Map box scaling with unique array elements. $O(N)$ space. |
| 1712 |
Ways to Split Array Into Three Subarrays |
Two nested loops placing two dividers `i` and `j` to generate all valid `left`, `mid`, `right` subarrays. Sum and compare. |
Double Guillotine Search. |
Draw array. Draw two slicing lines shifting right iteratively. $O(N^2)$ checks. |
Prefix Sums + Binary Search (or Two Pointers). |
Sliding Valid Zone on a Number Line. |
Compute prefix sums. Iterate first divider `i`. The second divider `j` must fall within a specific range to satisfy the inequalities. Find `j_min` and `j_max` via Binary Search. |
Draw Prefix array. Pin index `i`. Draw a bracket representing the valid window `[j_min, j_max]` further down the array. |
Loop Wrapping a Tree Search. |
Draw N iterations. Inside each, draw a Binary Search tree of depth Log N. Total $O(N \log N)$. |
Multiple temporary subarray accumulations. |
One continuous Prefix Sum array parallel to the input. $O(N)$ space. |
| 1713 |
Minimum Operations to Make a Subsequence |
Standard Longest Common Subsequence (LCS) 2D Dynamic Programming. |
2D Grid DP. |
Draw an N x M grid mapping `target` vs `arr`. Fill out every cell. $O(N \cdot M)$. |
Target Index Mapping + Longest Increasing Subsequence (LIS) via Patience Sorting. |
Patience Sorting (Deck of Cards). |
Map `target` elements to their indices. Replace `arr` elements with these indices. Run $O(N \log K)$ LIS algorithm on the index array. Answer is `len(target) - LIS`. |
Write target map. Rewrite `arr`. Draw "piles" of numbers. Place new numbers on leftmost valid pile (Binary Search). Count piles. |
Linear Sweep with Binary Placement. |
Draw arrow sweeping array, dropping items down into Log K height piles. Label $O(N \log K)$. |
Massive 2D Matrix of size N * M. |
Hash Map for indices + 1D `tails` array for piles. $O(N)$ space. |
| 1714 |
Sum Of Special Evenly-Spaced Elements In Array |
For every query, jump through the array step by step (by size `y`), summing the values on the fly. |
Frog Jumping Loop. |
Draw array. For a query, draw a frog doing jumps of size `y` repeatedly until the end. $O(Q \cdot N)$. |
Square Root Decomposition (Block separation). |
Two-Lane Highway Routing. |
Threshold = `sqrt(N)`. If step size `y <= sqrt(N)`, do an $O(1)$ lookup in a precomputed suffix array. If `y > sqrt(N)`, do the manual frog jump (takes at most `sqrt(N)` jumps). |
Draw queries hitting a toll booth. "Small" queries route to a precomputed lookup table. "Large" queries route to a manual loop. |
Capped Funnel Limit. |
Draw queries passing through a funnel constrained to a max width of `sqrt(N)`. Label $O(Q \\text{cdot sqrt}(N)$). |
Variables for summing on the fly. $O(1)$ extra space. |
Wide but shallow 2D array: `suf[sqrt(N)][N]`. $O(N \\text{cdot sqrt}(N)$) space. |
| 1715 |
Count Apples and Oranges (SQL) |
Write two separate queries (one for boxes only, one for boxes joined with chests), then UNION ALL and group by. |
Venn Diagram Duplicate Aggregation. |
Draw Table A, Table B. Draw overlapping circles, pulling data twice and adding complexity to aggregation. |
LEFT JOIN with COALESCE / IFNULL. |
Lego Blocks with Optional Snap-ons. |
Select `sum(box.apple + COALESCE(chest.apple, 0))`. Every box is evaluated. If chest exists, grab those apples too. If null, grab 0. |
Draw two tables side-by-side. Draw linking arrows. For missing links, draw a ghost box containing '0' snapping into place. |
Parallel Stream Merge. |
Draw two conveyor belts merging into one sum bucket in a single pass. |
Multiple heavy intermediate temporary tables holding UNION data. |
Appending columns conceptually in-place via the SQL JOIN engine. $O(1)$ row expansion. |
| 1716 |
Calculate Money in Leetcode Bank |
Loop from day 1 to n. Keep track of the current day of the week and the current Monday's base value. Sum day by day. |
Calendar Tallying. |
Draw a calendar grid. Point to each day, write the incrementing amount, and keep a running sum next to it. $O(N)$. |
Math (Arithmetic Progression Series). |
Stacking Blocks (Staircase). |
Calculate full weeks: `w = n / 7`. The sum of these weeks forms an arithmetic series. Calculate leftover days: `d = n % 7`. Sum the remainder directly. |
Draw large rectangular blocks for full weeks (AP formula). Draw a small staircase block for the remainder days. Add them. |
Formula Substitution. |
Write `O(1)` next to the math equation. No loops required. |
$O(1)$ loop variables. |
$O(1)$ math formula variables. Constant space. |
| 1717 |
Maximum Score From Removing Substrings |
Recursively search the string for "ab" or "ba", remove them, branch out, and backtrack to find the absolute maximum possible score. |
String Permutation Tree. |
Write string. Draw branches for every single "ab" or "ba" found. Tree grows exponentially. |
Greedy + Stack (Two Passes). |
Spring-Loaded Stack Drops. |
Identify higher-scoring pair (e.g., "ab"). Push chars to stack. If top of stack + current char == "ab", pop and add score. Do a second pass on remaining stack for the lesser pair ("ba"). |
Draw a vertical bucket (stack). Drop letters in. When "a" lands directly on "b", circle them, POOF them out, and write `+score`. |
Two Sequential Linear Sweeps. |
Draw array. Arrow sweeping left-to-right, then a second arrow sweeping remaining elements. $O(N)$. |
Deep call stack and multiple modified string copies. $O(N^2)$. |
A Stack array holding up to N characters. $O(N)$ space. |
| 1718 |
Construct the Lexicographically Largest Valid Sequence |
Generate all possible permutations of the required numbers. Filter them against the distance rules. Pick the lexicographically largest valid one. |
Factorial Permutation Generator. |
Draw a massive list of arrays. Cross out 99% of them that break the distance rule. $O(N!)$. |
Backtracking + Greedy (Place largest available number first). |
Puzzle Board with Fixed Constraints. |
Create empty array size `2n-1`. Try placing numbers `n` down to `1` in the first empty spot. If `k>1`, check if `index + k` is empty. Place both, recurse. If dead end, backtrack (undo). |
Draw blank slots. Hold the number 5. Drop it in slot 0. Count 5 steps right, drop the second 5. If blocked later, erase them and try 4. |
Pruned Decision Tree. |
Draw a tree, but heavily cross out branches very early. Worst case $O(N!)$, but practically much faster due to tight pruning. |
Holding thousands of permutations in memory. |
Array of size `2n-1` + boolean `used` array. $O(N)$ space. |
| 1719 |
Number Of Ways To Reconstruct A Tree |
Generate all possible rooted trees from the nodes. For each tree, find all ancestor-descendant pairs and compare with the given pairs array. |
Forest of All Possible Trees. |
Draw 5 different tree structures. For each, list all vertical paths. Compare lists. $O(V^V)$. |
Graph Theory / Degree Sorting (Constructive). |
Hierarchy by Popularity (Degree). |
Count degree (pairs) per node. Root MUST have degree `V-1`. Sort nodes by degree descending. Attach each node to the ancestor with the smallest degree >= its own degree. |
Draw nodes as circles sized by their degree. Largest circle goes at the top. Smaller circles hang off circles just slightly larger than them. |
Adjacency Matrix Validation. |
Draw nodes, sorting them $O(V \log V)$. Draw edge validation loop taking $O(V^2)$ or $O(E)$. |
Storing multiple tree structures. |
Adjacency list/set for fast lookup. $O(E)$ space. |
| 1720 |
Decode XORed Array |
Guess the next number from 0 to max_val, check if `guess XOR prev_val == encoded_val`. Repeat for every element. |
Guess-and-Check Lock. |
Write encoded array. Guess numbers iteratively until the XOR matches. $O(N \\text{cdot MaxVal})$. |
Bitwise XOR Properties (`A ^ B = C` implies `A ^ C = B`). |
Domino Effect / Chain Reaction. |
Initialize `ans` array with `first`. Loop through `encoded`. The next number is simply `ans[i] ^ encoded[i]`. Push to `ans`. |
Draw `ans[0]`. Draw an arrow from `ans[0]` and `encoded[0]` into an XOR gate (⊕), outputting `ans[1]`. Chain this forward continuously. |
Single Linear Pass. |
Draw array. Single arrow moving left to right. $O(N)$. |
Same as optimal (O(N) result array). |
Result array of size N+1. $O(N)$ space. |
| 1721 |
Swapping Nodes in a Linked List |
Traverse list to count length N. Traverse again to find node at K. Traverse again to find node at N-K. Swap their values. |
Multi-Pass Array Extraction. |
Draw Linked List. Draw three separate full-length arrows passing over it one after another. $O(N)$. |
Two Pointers (Fast & Slow Ruler Slide). |
Sliding a Rigid Measuring Stick. |
Pointer 1 moves K steps. Mark this as Node A. Pointer 2 starts at head, Pointer 3 starts at Node A. Move 2 and 3 together. When 3 hits the end, 2 is at N-K. Swap values. |
Draw nodes. Drop an anchor at K. Connect a stick between head and K. Slide the stick right until the right end falls off. The left end is your target. Swap. |
Overlapping Single Sweep. |
Draw nodes. Arrow A goes partway. Parallel Arrows B and C slide to the end. Total nodes touched = N. $O(N)$. |
Creating a temporary array of size N to access indices directly. |
Three floating pointer tags attached to existing nodes. $O(1)$ space. |
| 1722 |
Minimize Hamming Distance After Swap |
Generate all possible permutations of the source array using the allowed swaps. Compare each to target to find minimum distance. |
Exponential Permutation Tree. |
Draw source array. Draw branching paths for every single valid swap combo. Tree explodes in size. $O(N!)$. |
Disjoint Set Union (DSU) / Connected Components + Hash Maps. |
Islands of Paint Buckets. |
Treat allowed swaps as edges. Group connected indices into 'islands'. For each island, dump source numbers into a frequency map. Check if target numbers at those indices exist in the map. |
Draw indices as dots. Draw lines connecting allowed swaps. Circle the connected blobs. Next to each blob, tally available numbers. Cross them off as target uses them. |
Graph Grouping & Hash Lookup. |
Draw V nodes, E edges merging (O(N+E)). Draw linear scan checking Maps $O(N)$. Total $O(N + E)$. |
Holding factorial string/array permutations in memory. |
Parent array for DSU + Array of Hash Maps for frequencies. $O(N)$ space. |
| 1723 |
Find Minimum Time to Finish All Jobs |
Assign every job to every possible worker combinations. For each, calculate the max workload. Find the minimum of these maximums. |
K-ary Backtracking Tree. |
Draw Job 1. Draw K lines to K workers. From each worker, draw K lines for Job 2. $O(K^N)$. |
Binary Search on Answer + Pruned Backtracking. |
Adjustable Limbo Bar + Bucket Filling. |
Guess a max time 'T'. Try assigning jobs (largest first) to workers. If a worker exceeds T, backtrack. If assignment succeeds, lower T. If impossible, raise T. |
Draw a line at height T. Drop job blocks into K buckets. If a bucket overflows T, stop, undo, try next bucket. Prune heavily if dropping a block into an empty bucket fails. |
Binary Search wrapping a Decision Tree. |
Draw Answer Number Line (Log(Sum) steps). Inside each step, draw a heavily crossed-out decision tree. |
K-sized array duplicated K^N times in call stack. |
One K-sized array modified in-place + Recursion stack. $O(K + N)$ space. |
| 1724 |
Checking Existence of Edge Length Limited Paths II |
For every query (p, q, limit), run a fresh BFS/DFS from `p` to `q` ignoring edges >= limit. |
Repeated Graph Traversal. |
Draw graph. For Query 1, cross out heavy edges, run BFS. Redraw graph. Query 2, cross out edges, run BFS. $O(Q \cdot (V+E)$). |
Kruskal's MST + LCA (Lowest Common Ancestor) with Binary Lifting. |
Bottleneck Hierarchy Tree (Kruskal Reconstruction). |
Build MST but track merge weights. Treat merges as new parent nodes with the edge weight. Find LCA of `p` and `q` in this tree. If LCA weight < limit, path exists. |
Draw original graph. Re-draw it bottom-up: nodes merge into a parent circle labeled with the bottleneck edge weight. Trace paths up to common ancestor. |
Graph-to-Tree + $O(Log V)$ Jumps. |
Draw sorting (E log E) + DSU build. Draw Q arrows jumping up the tree via powers of 2 (Q log V). |
Standard Queue/Visited sets per query. $O(V)$. |
Binary lifting jump table `up[V][logV]`. $O(V \log V)$ space. |
| 1725 |
Number Of Rectangles That Can Form The Largest Square |
Calculate max square `min(L, W)` for all rectangles and store in a new array. Sort or scan the array to find max, then scan again to count. |
Multi-Pass Array Processing. |
Draw rectangles. Write square sizes in a list. Scan list for the max number. Scan list again tallying occurrences. $O(N)$. |
Single Pass Streaming Maximum (King of the Hill). |
Throne and Tally Board. |
Iterate once. `side = min(l, w)`. If `side > max_len`, new king: `max_len = side`, reset `count = 1`. If `side == max_len`, increment tally: `count++`. |
Draw a throne (`max`) and a tally board. If bigger square arrives, kick out king, erase tally, sit down. If equal square arrives, add a tick mark. |
Single Left-to-Right Sweep. |
Draw array. One arrow passes over from start to finish. $O(N)$. |
$O(N)$ new array to store square dimensions. |
Two integer variables: `max_len`, `count`. $O(1)$ space. |
| 1726 |
Tuple with Same Product |
Four nested loops picking every possible combination of 4 distinct numbers (a,b,c,d) and checking if a*b == c*d. |
4-Dial Combination Lock. |
Draw array. Draw 4 nested brackets mapping every 4-element subset. Calculate and compare. $O(N^4)$. |
Hash Map (Frequency Counting) + Math Combinatorics. |
Product Sorting Buckets. |
Two nested loops to calculate products of all pairs. Drop pair into a Hash Map keyed by the product. If a bucket has `k` pairs, they can form `(k * (k-1) / 2) * 8` valid tuples. |
Draw pairs `(a,b)` mapping to a bucket labeled `Product X`. If two pairs land in the same bucket, draw arrows linking them into 8 different tuple arrangements. |
Double For-Loop Pair Generation. |
Draw an N x N matrix grid, filling only the upper triangle. Label $O(N^2)$. |
None, just loop pointers. $O(1)$ space. |
Hash Map dynamically scaling with the number of unique pair products. $O(N^2)$ space. |
| 1727 |
Largest Submatrix With Rearrangements |
Generate every possible subset of columns, rearrange them, and check all resulting submatrices for all 1s. |
Column Permutation Explosion. |
Draw a matrix. Slice out columns. Shuffle them in every possible order. Check for rectangles. $O(N! \cdot N^2)$. |
Dynamic Programming (Histogram Heights) + Greedy Sorting. |
Falling Tetris Blocks / Pillar Sorting. |
Going row by row, count consecutive 1s looking upwards (like pillars). For the current row, sort the pillar heights descending. The max rectangle area ending here is `height[i] * (index + 1)`. |
Draw matrix of 1s and 0s. Transform columns into vertical stacks of blocks (tallest where 1s are continuous). On each row, sort the stacks tallest to shortest. Draw the largest bounding box. |
Row-by-Row Array Sorting. |
Draw Matrix R x C. For each row, draw the sorting block `C log C`. Label $O(R \cdot C \log C)$. |
Massive copies of rearranged matrices. |
A single 1D array updating the heights of the pillars row-by-row. $O(C)$ space. |
| 1728 |
Cat and Mouse II |
Standard DFS/BFS simulating every move for Mouse, then Cat. Extremely deep recursion leading to TLE due to cycles. |
Infinite Ping-Pong Recursion. |
Draw Cat and Mouse nodes. Draw lines branching to valid moves. Lines loop back on themselves creating an infinite graph. |
Game Theory (Minimax) + 3D Memoization (Topological Sort from End States). |
Backwards Win-State Propagation. |
Identify absolute win/loss states (Cat catches Mouse, Mouse gets Food, Cat gets Food, Turn limit reached). Propagate these results backwards to the start state using Minimax logic. |
Draw Food, Cat, Mouse on a grid. Circle the food (Mouse Win). Draw arrows *backwards* from the food to spaces the mouse could have come from. Color code winning/losing nodes. |
3D State Space Graph Completion. |
Draw a cube representing `[MousePos][CatPos][Turn]`. Fill it block by block. Label $O(\text{Rows}^2 \\text{cdot Cols}^2 \\text{cdot MaxTurns})$. |
Stack overflow / unbounded queue. |
A 3D Memoization table of size `[R*C][R*C][Limit]`. $O(\text{Rows}^2 \\text{cdot Cols}^2 \\text{cdot MaxTurns})$ space. |
| 1729 |
Find Followers Count (SQL) |
Use a correlated subquery for every distinct user_id to count their followers independently. |
Ping-Pong Querying. |
Draw User list. For each user, draw an arrow to the Followers table, run a count, and bring the number back. Inefficient N queries. |
SQL Aggregation: `GROUP BY` + `COUNT()`. |
Sorting Bins by User. |
Scan the table, grouping rows by `user_id`. Apply `COUNT(follower_id)` to each group. Output the results ordered by `user_id`. |
Draw rows of data. Draw buckets labeled with `user_id`. Toss rows into their respective buckets. Tally the items in each bucket. Order buckets ascending. |
Single Pass Grouping Funnel. |
Draw unsorted rows flowing into grouping funnels, exiting as aggregated rows, then sorted. $O(N \log N)$ for the final sort. |
Multiple database cursor memory states. |
SQL Engine grouping hash tables. $O(\text{Unique Users})$ space. |
| 1730 |
Shortest Path to Get Food |
DFS (Depth First Search) exploring every possible path to find food, keeping track of the minimum path length. Re-evaluating cells. |
Blind Snake Winding. |
Draw grid. Draw a line wandering randomly into dead ends, backtracking, and trying again until it finds food. Extremely slow. |
BFS (Breadth First Search) for Unweighted Shortest Path. |
Water Ripple Expansion. |
Push starting position to Queue. Expand out 1 step in all 4 valid directions. Mark visited. Repeat level by level. The first time you hit 'Food', that's guaranteed the shortest path. |
Draw grid. Place a dot at start. Draw concentric rings expanding outwards by 1 cell per step, ignoring walls. Stop when a ring touches food. |
Level-Order Grid Traversal. |
Draw grid mapping M x N. Highlight cells progressively. Worst case touches all cells once. $O(M \cdot N)$. |
Deep recursion stack. $O(M \cdot N)$. |
Queue storing the "frontier" of the current ripple. Max size is the grid diagonal. $O(M \cdot N)$ space. |
| 1731 |
The Number of Employees Which Report to Each Employee (SQL) |
Nested subqueries to count reports for every employee ID, then another subquery to calculate the average age. |
Recursive Loopback Search. |
Draw a list of names. For each name, scan the entire list again to find anyone listing them as 'manager'. Very slow. |
Self-Join on ID = Reports_To + Group By. |
Organization Chart Linkage. |
Join Table A (Managers) with Table B (Reports) where `A.employee_id = B.reports_to`. Group by Manager ID and calculate `count(B.id)` and `avg(B.age)`. |
Draw two identical tables. Draw a line from the 'reports_to' column in table 1 to the 'employee_id' in table 2. Circle the resulting pairs. |
Hash Join Aggregation. |
Draw a funnel where rows are sorted by manager ID. Tally reports as they pass through. $O(N \log N)$. |
Multiple memory scans for subqueries. |
A single temporary hash table for grouping manager IDs. $O(N)$ space. |
| 1732 |
Find the Highest Altitude |
For every index `i`, calculate the altitude by summing all elements from `0` to `i`. Track the max sum. |
Nested Accumulation (Quadratic). |
Draw a list. For element 1, sum 1 item. For element 2, sum 2 items. For element 3, sum 3 items. $O(N^2)$. |
Prefix Sum (Running Total). |
Hiking Elevation Map. |
Start at 0. Add current `gain[i]` to `current_altitude`. Update `max_altitude = max(max_altitude, current_altitude)`. |
Draw a mountain profile. Write the 'gain' on the slopes (+5, -3). Label each peak with the current sum. Highlight the highest point. |
Single Linear Path. |
Draw a straight line arrow over the array. Label $O(N)$. |
None, just sum variables. $O(1)$ space. |
Two integer variables: `current` and `max`. $O(1)$ space. |
| 1733 |
Minimum Number of People to Teach |
Try teaching every possible language to every person. For each language, check if it allows everyone in every friendship to communicate. |
Language Matrix Intersection. |
Draw Languages vs Friendships. Try Language 1, count learners. Try Language 2, count learners. $O(L \cdot (P + F)$). |
Greedy + Set Intersection (Filtering Friendships). |
Venn Diagram Filters. |
Identify friendships that *cannot* communicate. For these broken friendships, find the language most common among them. Teach that language to those who don't know it. |
Draw two circles per friendship representing languages. If circles don't overlap, mark as 'Broken'. In a side tally, count how many broken-friendship-people know Language X. |
Set Membership Scan. |
Draw F friendships (linear) + L languages (linear). $O(F + P \cdot L)$. |
None, just tally variables. |
A set of sets (languages per person) for $O(1)$ communication checks. $O(P \cdot L)$ space. |
| 1734 |
Decode XORed Permutation |
Backtracking or Guessing the first element `perm[0]` and decoding the whole array to see if it's a valid permutation of 1..N. |
Guessing/Backtracking Tree. |
Draw branches for every possible starting number. Verify permutation at each leaf. $O(N!)$. |
Bitwise Logic (Total XOR Property). |
Mathematical Balance Scale. |
Total XOR of 1..N is `A`. The XOR of encoded elements at odd positions is `B`. Therefore, `perm[0] = A ^ B`. Once you have `perm[0]`, decode the rest using Q1720 logic. |
Write 1 to N. XOR them into a result box (Total). Write encoded items. Circle every other item. XOR them. Subtract (XOR) the two boxes to find the missing first element. |
Two Linear Passes. |
Draw two arrows over the input/output arrays. Label $O(N)$. |
Stack frames for backtracking. |
Output array of size N. $O(N)$ space. |
| 1735 |
Count Ways to Make Array With Product |
Recursive partitioning: find all ways to split factor `k` into `n` parts, accounting for order and empty slots. |
Product Partition Tree. |
Draw `k`. Draw branches for every possible factor split. For k=6, branches for (1,6), (2,3), (3,2)... Grows exponentially. |
Prime Factorization + Stars and Bars (Combinatorics). |
Dividers and Marbles. |
Find prime factors of `k` (e.g., 12 = 2^2 * 3^1). For each prime factor power `p`, count ways to put `p` items in `n` bins using `comb(n+p-1, p)`. Multiply results. |
Draw a Factor Tree for `k`. For each factor power, draw `p` stars and `n-1` bars. Draw the combinatorial formula next to it. |
Precomputed Sieve + Combinations. |
Draw a Sieve $O(\text{MaxK} \log \\text{log MaxK})$ + Q queries of $O(\log K)$ factorizing. Label $O(K + Q \log K)$. |
Deep recursion stack. |
Factor list + Precomputed Pascal's Triangle (Combinations table). $O(N + \text{MaxK})$ space. |
| 1736 |
Latest Time by Replacing Hidden Digits |
Check all 1440 possible minutes in a day (00:00 to 23:59) and see which one fits the pattern. |
Clock Face Tally. |
Draw a clock. Rotate through every minute. Check if the string matches. $O(1440)$ -> $O(1)$. |
Greedy Positional Logic. |
Slot-by-Slot Maximization. |
Evaluate each '?' independently from left to right. If `time[0] == '?'`, check `time[1]` to decide between 1 or 2. |
Draw 4 boxes. For each '?', write the highest possible digit allowed by time rules (23:59). |
Constant Step Checklist. |
Draw 4 checkmarks. Label $O(1)$. |
Variable for max time. |
Single string of length 5. $O(1)$. |
| 1737 |
Change Minimum Characters to Satisfy Condition |
Try changing both strings to every possible character 'a'-'z' and check all three conditions for each. |
Character Permutation Grid. |
Draw a 26x3 matrix. For each cell, simulate the entire string change. $O(26 \cdot (N+M)$). |
Prefix Sums + Frequency Maps. |
Histogram Sliding Barrier. |
Count char frequencies for A and B. Use prefix sums to find how many chars are ≤ 'c'. The cost to make A < B at pivot 'c' is `(A > c) + (B ≤ c)`. |
Draw two bar charts (A and B). Draw a vertical line between 'c' and 'c+1'. Shifting the line calculates cost in $O(1)$. |
Fixed-Width Alphabet Scan. |
Draw an arrow over a 26-slot array. Label $O(26 + N + M)$. |
None, just sum variables. |
Two arrays of size 26. $O(1)$ space. |
| 1738 |
Find Kth Largest XOR Coordinate Value |
For every (i, j), re-loop from (0,0) to (i,j) to calculate the XOR sum. Store all in a list and sort. |
Nested Area Recalculation. |
Draw a grid. For each cell, draw a rectangle back to the origin and re-sum. $O(M^2 \cdot N^2)$. |
2D Prefix Sum (DP) + Quickselect/Min-Heap. |
Overlapping Transparency Sheets. |
`dp[i][j] = matrix[i][j] ^ dp[i-1][j] ^ dp[i][j-1] ^ dp[i-1][j-1]`. Maintain a Min-Heap of size K to find the Kth largest. |
Draw a cell. Color its top neighbor, its left neighbor, and the diagonal. Use the 2D XOR formula to fill the grid. |
Grid Pass + Heap Maintenance. |
Draw a grid traversal $O(\text{MN})$ and a small heap $O(\log K)$. Total $O(\text{MN} \log K)$. |
A huge list of MN elements. |
A 2D DP table + Heap of size K. $O(\text{MN})$ space. |
| 1739 |
Building Boxes |
Add boxes one by one, ensuring each is supported. Count total until it exceeds `n`. |
Layer-by-Layer Physical Simulation. |
Draw a pyramid base. Add one box at a time to the edge. $O(\text{sqrt}(N)$). |
Mathematical Series (Tetrahedral Numbers) + Greedy. |
Staircase Growth Pattern. |
Use `i*(i+1)*(i+2)/6` to find the largest complete tetrahedral pyramid. Then add leftover boxes in a triangular sequence. |
Draw a 3D pyramid. Calculate its base. For leftovers, draw a new 2D triangle attached to the base. |
Mathematical Convergence. |
Draw a number line. Jump to the nearest pyramid size, then step to the answer. $O(N^(1/3)$). |
None, just counters. |
$O(1)$ variables for current height and base. |
| 1740 |
Find Distance in a Binary Tree |
Convert the tree into an undirected graph (Adjacency List). Use BFS starting from `p` to find `q`. |
Spiderweb Graph Traversal. |
Draw the tree. Draw double arrows between all nodes. Trace a path from `p` to `q`. $O(N)$. |
Lowest Common Ancestor (LCA) + Node Depth. |
Tree "V" Shape Path. |
`Dist(p, q) = Depth(p) + Depth(q) - 2 * Depth(LCA(p, q))`. Find LCA in one pass, then find depths. |
Draw the tree. Highlight `p` and `q`. Trace up to the first shared node (LCA). Count steps from `p` to LCA and `q` to LCA. |
Single Pass DFS Traversal. |
Draw one DFS arrow visiting every node once. Label $O(N)$. |
Adjacency List + Visited Set + Queue. $O(N)$. |
Recursion stack (height of tree). $O(H)$. |
| 1741 |
Find Total Time Spent by Each Employee (SQL) |
Select all records. In your application code, loop through every row and maintain a manual dictionary to sum the time per employee per day. |
Data Row Accumulation. |
Draw a raw data table. Draw arrows from rows to a blank "result table" where you manually add values for matching IDs. $O(N)$. |
SQL Aggregation: `GROUP BY` on multiple columns. |
Bucket Sort with Summing. |
Calculate `(out_time - in_time)` for each row. Group rows by `event_day` AND `emp_id`. Use `SUM()` on the calculated time. |
Draw table. Draw bins labeled by both `Day` and `ID`. Toss calculated time into bins. Tally the final amounts in each bin. |
Hash-based Multi-Key Grouping. |
Draw data flowing into a 2D grid of buckets. One pass: $O(N)$. Final sort: $O(N \log N)$. |
Huge dictionary in app memory. |
SQL temporary result set. $O(\text{Unique Groups})$ space. |
| 1742 |
Maximum Number of Balls in a Box |
For every number in range, convert to string, split into chars, parse back to int, sum them, and update a frequency map. |
String Conversion Overhead. |
Draw a ball. Draw a text bubble converting `123` to `"123"`. Draw arrows splitting it to `"1", "2", "3"`. $O(N \\text{cdot NumDigits})$. |
Mathematical Digit Summing + Array Frequency Map. |
Rolling Modulo Tally. |
Loop from `low` to `high`. For each `i`, use `while i > 0: sum += i % 10; i //= 10`. Increment `boxes[sum]`. Keep track of the max frequency. |
Draw a sequence of numbers. Below each, draw a small machine that spits out a single sum (e.g., 15). Point an arrow to Box 15 and add a tick mark. |
Direct Integer Arithmetic Sweep. |
Draw an arrow over the number line. Label $O(N \cdot \log(\text{maxVal})$). |
String buffer overhead for every number. |
A fixed-size array of 46 (max sum for 99999 is 45). $O(1)$ space. |
| 1743 |
Restore the Array From Adjacent Pairs |
Generate all possible permutations of the numbers. Check each one to see if every adjacent pair in the permutation exists in the input pairs. |
Factorial Permutation Search. |
Draw all numbers. Draw every possible path connecting them. Cross out 99.9% of the paths. $O(N!)$. |
Graph Adjacency List + Degree Finding + DFS/Linear Traversal. |
Connecting the Dots (Unrolling a Chain). |
Build an adjacency map from the pairs. Find the two nodes with degree 1 (the endpoints). Start at one endpoint and follow the unique path to the other. |
Draw nodes. Draw edges as lines. Circle the two nodes that only have one line. Follow the line from one circle to the next node until you hit the other circle. |
Adjacency Map Build + Single Path Trace. |
Draw a hash map $O(N)$. Draw a single line of nodes $O(N)$. Total $O(N)$. |
None (if just checking permutations). |
Adjacency List (Map of Lists). $O(N)$ space. |
| 1744 |
Can You Eat Your Favorite Candy on Your Favorite Day? |
For every query, simulate eating candies day-by-day until the favorite day. Check if the candy eaten is of the target type. |
Daily Consumption Simulation. |
Draw days. Draw eating 1 candy, then 2, etc. Repeat for every query. $O(Q \\text{cdot TotalCandies})$. |
Prefix Sums + Range Intersection (Inequality Check). |
Overlapping Temporal Windows. |
Precompute Prefix Sums of candy counts. For each query, calculate the min candies needed (day + 1) and max candies possible ((day + 1) * cap). Check if this range overlaps with the range of the target candy type. |
Draw a long bar of candies colored by type. Below it, draw a "Day Range" bracket. If the bracket touches the target color, it's true. |
Preprocessing + $O(1)$ Query. |
Draw a prefix sum array $O(N)$. Draw Q checkmarks $O(Q)$. Total $O(N + Q)$. |
Variables for current candy type and day. |
Prefix sum array of size N. $O(N)$ space. |
| 1745 |
Palindrome Partitioning IV |
Try all possible ways to split the string into 3 parts (two nested loops for split points). For each part, check if it's a palindrome. |
Triple-Split Naive Check. |
Draw string. Draw two slicing lines. For each segment, check palindromes. $O(N^3)$ or $O(N^4)$. |
2D Dynamic Programming (Palindrome Table). |
Symmetry Grid (Boolean Matrix). |
Build a boolean `isPal[i][j]` table where `isPal[i][j]` is true if `s[i...j]` is a palindrome. Then loop over all `i, j` such that `0 < i < j < n-1` and check if `isPal[0][i-1]`, `isPal[i][j]`, and `isPal[j+1][n-1]` are all true. |
Draw an N x N grid. Fill it diagonally. Once filled, pick two split points `i` and `j`. Check three coordinates in your grid. If all are 'T', result is 'T'. |
Matrix Precomputation + Double Loop. |
Draw an N x N grid $O(N^2)$. Draw a double loop over the string $O(N^2)$. Total $O(N^2)$. |
None, just split pointers. |
2D boolean array `isPal[N][N]`. $O(N^2)$ space. |
| 1746 |
Maximum Subarray Sum After One Operation |
Generate all subarrays. For each, try squaring every element one by one and find the max sum. |
Triple-Nested Loop (Subarray Start, End, and Square index). |
Draw array. Draw two brackets for subarray. Inside, highlight one element to square. Repeat for all. $O(N^3)$. |
Dynamic Programming (State Machine Kadane's). |
Switching Tracks (Train Track). |
Maintain two states: `s0` (max sum ending at `i` without any squares) and `s1` (max sum ending at `i` with exactly one square already used). |
Draw two parallel horizontal lines (tracks). If you stay on Track 0, add `num`. If you jump to Track 1, you can either square `num` or add `num` to a previous square. |
Parallel State Progression. |
Draw two arrows moving together over the array. Label $O(N)$. |
None, just sum variables. |
Two variables per iteration (or two 1D DP arrays). $O(N)$ or $O(1)$ space. |
| 1747 |
Leetflex Banned Accounts (SQL) |
Self-join the table on `account_id` and check every possible pair of login sessions for overlap using multiple nested loops in code. |
Pairwise Time Overlap Matrix. |
Draw a list of login sessions. Draw lines connecting every session of the same account. Check if time ranges intersect. $O(N^2)$. |
SQL Self-Join with Inequality Constraints. |
Gantt Chart Conflict Detector. |
Join Table T1 and T2 where `T1.account_id = T2.account_id` and `T1.ip_address != T2.ip_address`. Check overlap using: `T1.login < T2.logout` and `T2.login < T1.logout`. |
Draw two horizontal bars for the same user but different IPs. If they overlap vertically at any point, circle the conflict. |
Sorted Interval Intersection. |
Draw sorted login events. One pass to find overlaps. $O(N \log N)$ for the join/sort. |
N^2 joined rows in memory. |
In-memory hash join/sort. $O(N)$ space. |
| 1748 |
Sum of Unique Elements |
For each element, loop through the rest of the array to see if it appears again. If not, add it to the sum. |
Nested Scanning (Quadratic). |
Draw array. For element 1, scan everything else. For element 2, scan everything else. $O(N^2)$. |
Hash Map / Frequency Array. |
Sorting into Tally Buckets. |
Traverse array once to count frequencies in a map/array. Traverse the map and add keys where value == 1. |
Draw bins labeled with numbers found. Toss items into bins. Only count the sum of bins that contain exactly one item. |
Two-Pass Linear Scan. |
Draw two sequential arrows over the array/map. Label $O(N)$. |
None, just loop pointers. |
A frequency array of size 101. $O(1)$ space relative to problem constraints. |
| 1749 |
Maximum Absolute Sum of Any Subarray |
Generate all subarrays, calculate their sums, take absolute values, and find the maximum. |
Nested Subarray Matrix. |
Draw array. Draw brackets for every possible start and end. Calculate sums. $O(N^2)$. |
Prefix Sum Range (Max - Min). |
Vertical Oscillation (Altitude Swing). |
The max absolute subarray sum is simply the difference between the maximum prefix sum and the minimum prefix sum (including 0). |
Draw a line graph of prefix sums. Find the highest peak and the lowest valley. The vertical distance between them is your answer. |
Single Pass Min-Max Tracking. |
Draw one arrow sweeping the array, updating `max_pre` and `min_pre`. Label $O(N)$. |
None, just sum variables. |
Two integer variables: `min_sum` and `max_sum`. $O(1)$ space. |
| 1750 |
Minimum Length of String After Deleting Similar Ends |
Recursively or iteratively check the first and last char. If equal, create a new string by trimming all matching prefix/suffix chars and repeat. |
String Slicing / Substring Creation. |
Draw string. Cut off ends. Write a NEW string. Cut off ends. Write a NEW string. $O(N^2)$ due to allocations. |
Two Pointers (Inward Convergence). |
Candle Burning from Both Ends. |
`left = 0`, `right = n-1`. While `left < right` and `s[left] == s[right]`, store the char and move `left` forward and `right` backward as long as they match that char. |
Draw string. Place `L` at start, `R` at end. If they match 'a', move `L` past all 'a's and `R` past all 'a's. Stop when they don't match or they cross. |
Converging Linear Scan. |
Draw two arrows meeting in the middle. Label $O(N)$. |
Multiple string copies in memory. $O(N^2)$. |
Two integer pointers. $O(1)$ space. |
| 1751 |
Maximum Number of Events That Can Be Attended II |
Recursive backtracking: For each event, either attend it (and skip all overlapping ones) or skip it. Try all combinations. |
Binary Decision Tree. |
Draw a root. Branch "Attend" or "Skip". If attend, cross out all siblings that overlap. $O(2^N)$. |
DP + Binary Search (Weighted Interval Scheduling). |
Layered Suffix Maximization. |
Sort events by start time. Use DP `memo[idx][k]`. For `attend`, use binary search (`bisect_left`) to find the next event that starts after current event's end time. |
Draw timeline. Use a bracket for current event. Draw a dashed arrow skipping ahead to the first available event after the bracket ends. |
Grid Search with Logarithmic Jumps. |
Draw an N x K grid. For each cell, draw a Log(N) search arrow. Label $O(N \cdot K \cdot \log N)$. |
Deep recursion stack. $O(N)$. |
2D Memoization Table of size N * K. $O(N \cdot K)$ space. |
| 1752 |
Check if Array Is Sorted and Rotated |
Try all N possible rotations of the array. For each rotation, check if it is sorted in non-decreasing order. |
Rotating Ring Inspection. |
Draw the array on a circular wheel. Rotate the wheel N times. For each stop, check if it's a straight line. $O(N^2)$. |
Single Pass Contraction Check. |
The "Drop" Counter. |
Count how many times `arr[i] > arr[i+1]`. In a sorted/rotated array, this "drop" can happen at most once (including the wrap-around from last to first). |
Draw the array as a line graph. It should go up, drop once, and go up again. If it drops twice, it's invalid. |
Linear Scan. |
Draw a single arrow passing through the array once. Label $O(N)$. |
$O(N)$ to store each rotation. |
One integer variable: `count`. $O(1)$ space. |
| 1753 |
Maximum Score From Removing Stones |
Simulate the process: in each step, try all 3 pairs of piles. Recursively find the one that leads to the maximum score. |
3-Way Game Tree. |
Draw 3 branches from every state. Calculate score at each leaf. $O(3^\text{Sum})$. |
Greedy (Always pick two largest) or Math. |
Pile Leveling. |
Sort piles `a, b, c`. If `a + b <= c`, the max score is just `a + b`. Otherwise, the piles are "balanced" enough to use almost all stones: `(a + b + c) // 2`. |
Draw three vertical bar charts. Take one block from each of the two tallest. Repeat until only one (or zero) pile remains. |
Constant Time Formula. |
Write the `min` formula. Label $O(1)$ if math, or $O(\\text{log MaxValue})$ if simulating with a Max-Heap. |
Recursion stack. |
Three integer variables. $O(1)$ space. |
| 1754 |
Largest Merge Of Two Strings |
Generate all possible merges (similar to interleave strings) and find the lexicographically largest one. |
Interleaving Permutation Tree. |
Draw two strings. Branch left or branch right for every character choice. $O(2^(N+M)$). |
Greedy with Suffix Comparison. |
Pointer "Look-Ahead". |
At each step, compare `s1` and `s2`. Pick the character from the string that is lexicographically larger *as a whole*. |
Draw two pointers. If `s1[i] > s2[j]`, pick `s1[i]`. If equal, look ahead until they differ to decide which "path" is better. |
String Slicing Comparison. |
Draw two arrows. For each step, draw a "sub-scan" comparison. Label $O((N+M)$^2). |
List of all merged strings. |
One result string. $O(N+M)$ space. |
| 1755 |
Closest Subsequence Sum |
Generate every possible subset sum of the array (2^N combinations) and find the one closest to the target. |
Full Power Set Expansion. |
Draw N nodes. Each node splits into "Include" or "Exclude". Total 2^N leaves. For N=40, this is 1 trillion. |
Meet-in-the-Middle + Two Pointers. |
Half-Divide & Conquer. |
Split array into two halves (20 elements each). Generate all sums for both (2^{20} \approx 10^6 each). Sort one. Use Two Pointers/Binary Search to find pairs `(sum1 + sum2)` closest to target. |
Draw two smaller trees (2^20 each). List their results. Draw two sorted lists side-by-side with pointers at opposite ends moving toward the target sum. |
Exponential Reduction. |
Draw $O(2^{N/2} \cdot N)$. Label it as the "Bridge" between brute force and impossible. |
Variable for min difference. |
Two arrays of size 2^{N/2}. $O(2^N/2)$ space. |
| 1756 |
Design Most Recently Used Queue |
Use a standard list. For `fetch(k)`, remove element at `k-1` and `append` to the end. |
Array Shift Animation. |
Draw a line of boxes. Cross out box K. Draw arrows shifting every box to the right of K one spot left. $O(N)$. |
Square Root Decomposition or Fenwick Tree. |
Block-Level Jumping. |
Divide N elements into \sqrt{N} blocks. Fetching involves finding the right block, removing from it, and appending to the last block. Rebalance if a block gets too large. |
Draw \sqrt{N} large buckets. To move an item, draw it jumping from Bucket A to the very last Bucket Z. |
Segmented Linear Scan. |
Draw \sqrt{N} steps to find the block + \sqrt{N} steps to shift within the block. Label $O(\\text{sqrt}{N})$. |
Single contiguous array. |
A list of lists (the blocks). $O(N)$ total space. |
| 1757 |
Recyclable and Low Fat Products (SQL) |
Select all rows from the table, then use a `for` loop in a programming language to filter for 'Y' in both columns. |
Unfiltered Data Stream. |
Draw a massive table. Draw a funnel that checks every single row one by one. $O(N)$. |
SQL Logical Indexing (`AND` condition). |
Boolean Masking. |
Database engine uses a B-Tree or Hash Index to immediately isolate rows where `low_fats = 'Y'` and `recyclable = 'Y'`. |
Draw two overlapping circles (Low Fat and Recyclable). Shade the intersection. |
Index Seek vs Scan. |
Draw a B-Tree traversal path. Label $O(\log N)$ if indexed, or $O(N)$ if not. |
Whole table loaded into application memory. |
Database-level filtering, only result rows returned. $O(1)$ extra space. |
| 1758 |
Minimum Changes To Make Alternating Binary String |
Generate all 2^N possible binary strings, check which ones are alternating, and find the minimum distance. |
Exponential Search Tree. |
Draw a root. Branch 0 or 1 for every index. Huge tree. $O(2^N)$. |
Greedy Comparison (2 Target States). |
Target Pattern Overlay. |
There are only 2 possible alternating strings: "0101..." or "1010...". Count differences with "0101...". The other count is just N - \text{first\_count}. |
Draw the input string. Below it, write "010101...". Circle every mismatch. Count circles. |
Single Pass Comparison. |
Draw one arrow passing over the string. Label $O(N)$. |
Stack frames for recursion or list of all strings. |
One or two counter variables. $O(1)$ space. |
| 1759 |
Count Number of Homogenous Substrings |
Generate every possible substring (O(N^2)). For each, check if all characters are identical (O(N)). |
Triple-Nested Loop Matrix. |
Draw array. Draw brackets for every possible start and end. For each bracket, scan all inside. $O(N^3)$. |
Two Pointers (Sliding Window) + Arithmetic Progression. |
Chunking / Grouping by Color. |
Find consecutive identical characters of length k. A group of length k contributes k \times (k+1) / 2 substrings. |
Draw a string like "aaabb". Group them: [aaa], [bb]. Write 3(4)/2 = 6 for first, 2(3)/2 = 3 for second. Total 9. |
Linear Chunk Scan. |
Draw an arrow jumping from the start of a char-group to the start of the next. Label $O(N)$. |
Storing all substrings in a list. |
One variable for current group length. $O(1)$ space. |
| 1760 |
Minimum Limit of Balls in a Bag |
Try every possible "max balls" value from 1 to 10^9. For each, simulate the splits. |
Linear Search on Answer Space. |
Draw a number line from 1 to 1,000,000,000. Start at 1 and check every single dot. $O(\text{MaxVal} \cdot N)$. |
Binary Search on the Answer. |
The "Can-I-Do-It?" Guessing Game. |
If we allow at most M balls per bag, the number of operations needed is \sum (\text{bag} - 1) // M. If \text{ops} \leq \text{maxOps}, M is possible; try smaller. Otherwise, try larger. |
Draw a "Target Size" slider. If slider is at 3, show how a bag of 9 splits into [3, 3, 3] (2 operations). |
Logarithmic Guessing Funnel. |
Draw a range [Low, High]. Draw a split in the middle. Show the search space shrinking by half. $O(N \log (\\text{text}{\text{maxVal}})$). |
None, just variables. |
Standard integer variables for Low, High, Mid. $O(1)$ space. |
| 1761 |
Minimum Degree of a Connected Trio in a Graph |
Iterate through every combination of three nodes (u, v, w). Check if all three pairs (u,v), (v,w), and (u,w) exist in the edge list. |
Combination Exhaustion. |
Draw a set of N dots. Circle every possible group of 3. For each group, check for a triangle. $O(N^3)$. |
Adjacency Matrix + Degree Precomputation. |
The "Triangle Filter". |
Use an N \times N adjacency matrix for $O(1)$ edge lookups. Precompute the degree of each node. Only check trios (u, v, w) where u < v < w. Result is deg(u) + deg(v) + deg(w) - 6. |
Draw an adjacency matrix grid. Highlight cells (u,v), (v,w), (u,w). Write down node degrees and subtract 6 (the 3 internal edges). |
Cubic Pruning. |
Draw a cube and slice it into N \times N \times N blocks. Label it $O(N^3)$. Note: Pruned loops don't change complexity but reduce constant factors. |
Edge list or adjacency list. $O(E)$. |
N \times N Boolean Matrix. $O(N^2)$ space visual. |
| 1762 |
Buildings With an Ocean View |
For each building, check every building to its right. If any building is taller or equal, it has no ocean view. |
Nested Right-Scan. |
Draw buildings as bars. For each bar, draw arrows to every bar to the right. $O(N^2)$. |
Right-to-Left Monotonic Scan. |
The "Horizon Sweep". |
Start from the rightmost building (always has a view). Move left, keeping track of the `max_height_seen`. If current building > `max`, it has a view. Update `max`. |
Draw buildings. Place a "sun" on the right. Draw a horizontal line moving left that only rises when it hits a taller building. |
Single Reverse Pass. |
Draw one arrow moving from right to left over the array. Label $O(N)$. |
None, just loop pointers. $O(1)$. |
One integer variable: `max_height`. $O(1)$ extra space visual. |
| 1763 |
Longest Nice Substring |
Generate all substrings. For each, check if it's "nice" (contains both uppercase and lowercase for every character present). |
Substring Matrix Check. |
Draw the string. Draw brackets for all (i, j) pairs. Inside each bracket, check all chars. $O(N^3)$. |
Divide and Conquer (Recursive Splitting). |
Shattering a Glass String. |
Scan string for characters that don't have their "pair" (e.g., 'a' exists but not 'A'). If found, the longest nice substring cannot contain this char. Split the string at this char and recurse. |
Draw the string. Circle the "lonely" character. Draw a vertical line through it, splitting the string into two smaller pieces. Repeat for each piece. |
Recursive Tree Depth. |
Draw a tree where each node is a string segment. Label $O(N^2)$ worst-case or $O(26 \cdot N)$ with sliding window. |
List of all substrings. $O(N^3)$. |
Recursion call stack. $O(N)$ space visual. |
| 1764 |
Form Array by Concatenating Subarrays of Another Array |
Try every possible starting position in the main array for each group in the input. |
Pattern Matching Backtracking. |
Draw main array. For Group 1, try all start points. If it fits, try all start points for Group 2. $O(\\text{text}{\text{Exponential}})$. |
Greedy Pointer Matching. |
Linear Progress Bar. |
Iterate through the main array with a pointer `idx`. For each group, search for its first occurrence starting from `idx`. If found, update `idx` to the end of that occurrence. |
Draw the array. Shade the area where Group 1 is found. Move the "search start" pointer just past that shaded area. Repeat for Group 2. |
Single Sequence Pass. |
Draw one arrow passing over the array. Each group is searched linearly. Label $O(N \cdot M)$. |
Stack frames for backtracking. |
Pointer variables. $O(1)$ space. |
| 1765 |
Map of Highest Peak |
For every land cell, calculate the Manhattan distance to every single water cell. Pick the minimum distance. |
Point-to-Point Manhattan Grid. |
Draw a grid. Pick a land cell. Draw arrows to all water cells. Repeat for every land cell. $O((R \cdot C)$^2). |
Multi-Source BFS. |
Water Ripple Expansion. |
Initialize a height grid. Put all water cells (height 0) into a queue. Expand outward layer-by-layer. For each neighbor, height = current\_height + 1. |
Draw a grid. Mark all water sources with '0'. Draw concentric squares (ripples) moving outward. Each new square increases the number by 1. |
Level-Order Grid Traversal. |
Draw an R \times C grid. Color cells as they are visited. Label $O(R \cdot C)$. |
None, just distance calculations. |
Queue for BFS + Height Matrix. $O(R \cdot C)$ space. |
| 1766 |
Tree of Coprimes |
For every node, traverse upwards towards the root. Calculate GCD of current node and every ancestor until you find a coprime or hit the root. |
Recursive Ancestor Crawl. |
Draw a tree. From a leaf, draw a line all the way to the root. Repeat for every leaf. $O(N \cdot H)$ where H is tree height. |
DFS + Ancestor Value Tracking (Value-based Map). |
The "Last Seen" Value Tally. |
Since node values are small (1-50), keep a dictionary `ancestors[val] = (depth, node_id)`. During DFS, check all 50 values; if `gcd(current_val, v) == 1`, pick the one with max depth. |
Draw a tree. Next to it, draw a table with 50 rows. As you go down a path, update row `X` with the current node's depth. When backtracking, erase it. |
DFS with Constant-Width Lookups. |
Draw one DFS traversal arrow. At each node, draw a small box representing 50 parallel checks. Label $O(N \cdot 50)$. |
None, just recursion stack. |
A dictionary of size 50 + Recursion stack. $O(N + 50)$ space. |
| 1767 |
Find the Subtasks That Did Not Execute (SQL) |
Write a script to generate every possible task-subtask pair in memory, then compare with the executed table using double loops. |
Full Permutation Scanning. |
Draw Table A (Tasks). For each, draw all subtasks. Then scan Table B (Executed) to cross out matches. $O(N^2)$. |
Recursive CTE + LEFT JOIN. |
The "Template and Punch-out" Method. |
Use a Recursive CTE to generate all subtasks from 1 to `subtasks_count` for each task. LEFT JOIN this with the `Executed` table where executed is NULL. |
Draw a "Shadow Table" (Template) with every expected subtask. Place the "Executed Table" over it. Whatever shadow remains visible is your result. |
Sequential Generation and Filtering. |
Draw a generation funnel $O(N)$ followed by a filter $O(N)$. Label $O(N)$. |
Massive arrays in application memory. |
SQL Engine temporary result set. $O(N)$ rows. |
| 1768 |
Merge Strings Alternately |
Convert both strings to arrays. Use a loop to pick one from A, one from B, and repeat. Use string concatenation inside the loop. |
Iterative String Stitching. |
Draw string A and B. Draw lines pulling letters one-by-one into a new string. $O(N + M)$. |
Two Pointers (Parallel Pointers). |
Zipper Merging. |
Maintain `i` for `word1` and `j` for `word2`. While either is valid, append `word1[i]` then `word2[j]`. If one finishes, append the remainder of the other. |
Draw two horizontal strings. Place two fingers at the start. Move them together to the right, picking letters like a zipper closing. |
Single Concurrent Sweep. |
Draw two parallel arrows moving together. Label $O(N + M)$. |
$O((N+M)$^2) due to repeated string immutability re-allocations in some languages. |
String builder or character array. $O(N + M)$ space. |
| 1769 |
Minimum Number of Operations to Move All Balls to Each Box |
For every box i, loop through all other boxes j. If box j has a ball, add `abs(i - j)` to the total for box i. |
All-Pairs Manhattan Distance. |
Draw boxes. Pick box 0, draw arrows from all other balls. Pick box 1, repeat. $O(N^2)$. |
Two-Pass Prefix and Suffix Sum. |
Cumulative Momentum. |
Pass left-to-right: keep track of `balls` seen and current `operations`. At each box, `ops = ops + balls`. Repeat right-to-left. The result for each box is `left_ops + right_ops`. |
Draw boxes. Draw a rolling snowball from the left. As it hits a ball, it gets heavier (ball count) and takes more effort (ops) to push. Do the same from the right. |
Two Sequential Linear Sweeps. |
Draw one arrow moving right, then one arrow moving left. Label $O(N)$. |
None, just loop variables. |
One result array of size N. $O(N)$ space. |
| 1770 |
Maximum Score from Performing Multiplication Operations |
Recursion without memoization: For each multiplier, pick from either the left or right of the nums array. Try all 2^M combinations. |
Binary Choice Tree. |
Draw root. Branch "Left" or "Right" for each multiplier. $O(2^M)$. With M=1000, this is astronomical. |
2D Dynamic Programming (Memoization). |
Shrinking Range Matrix. |
State: `dp[i][left]` is the max score after `i` operations with `left` elements taken from the start. (Note: `right` can be calculated as `n - 1 - (i - left)`). |
Draw a grid where rows are "Operations Done" and columns are "Left Side Taken". Each cell depends on the cell above it (left or right choice). |
Iterative State Fill. |
Draw an M \times M matrix. Highlight the dependency triangle. Label $O(M^2)$. |
Massive recursion stack. |
2D array of size M \times M. $O(M^2)$ space. |
| 1771 |
Maximize Palindrome Length From Subsequences |
Generate all subsequences of word1 and word2. Concatenate them and check if the result is a palindrome. Track the max length. |
Power Set Generation & Symmetry Check. |
Draw two sets of branching paths (2^N and 2^M). For every leaf in A, combine with every leaf in B. $O(2^{N+M})$. |
2D Dynamic Programming (LPS on word1 + word2). |
The "Bridged" DP Grid. |
Concatenate S = word1 + word2. Run Longest Palindromic Subsequence (LPS). Only update max length if the palindrome characters chosen span across the boundary of word1 and word2. |
Draw an (N+M) \times (N+M) grid. Mark the boundary line. Only "count" cells where the indices i and j are on opposite sides of the line and S[i] == S[j]. |
Diagonal Matrix Fill. |
Draw the square matrix and draw diagonal arrows representing the state transitions. Label $O((N+M)$^2). |
Huge list of subsequence strings. |
2D array of size (N+M) \times (N+M). $O((N+M)$^2) space. |
| 1772 |
Sort Features by Popularity |
For each feature, loop through all responses. Count occurrences using nested loops, then use a standard sort. |
Nested Search and Reorder. |
Draw Features list. For each item, draw arrows to all responses. $O(F \\text{times} R \\text{times} \\text{text}{\text{WordsPerResponse}})$. |
Hash Map (Counter) + Custom Stable Sort. |
The "Tally and Index" Rank. |
Put unique words of each response into a set to count popularity. Store counts in a Map. Sort features by (count DESC, original_index ASC). |
Draw a frequency table. Next to it, draw the original list with index numbers. Use a "Stable Sorting" funnel to keep order in case of ties. |
Linear Count & Logarithmic Sort. |
Draw the tallying pass $O(R \cdot W)$ and the sorting pass $O(F \log F)$. Total $O(R \cdot W + F \log F)$. |
Repeatedly scanning text in-place. |
Hash Map for counts + Set for response unique words. $O(F + \\text{text}{\text{TotalWords}})$ space. |
| 1773 |
Count Items Matching a Rule |
Loop through every item. Check if any property matches the rule using multiple IF-ELSE conditions or nested loops. |
Item-by-Item Verification. |
Draw a spreadsheet. For each row, check the specific column requested. $O(N)$. |
Index Mapping + Linear Scan. |
The "Column Filter". |
Map `ruleKey` to index (0 for type, 1 for color, 2 for name). Iterate through items and check if `item[index] == ruleValue`. |
Draw a table. Highlight only the column mentioned in the `ruleKey`. Scan only that column. |
Single Pass Filtering. |
Draw one vertical arrow down the target column. Label $O(N)$. |
None, just variables. |
A single counter variable. $O(1)$ extra space. |
| 1774 |
Closest Dessert Cost |
Try all combinations of base ice creams and all combinations of toppings (0, 1, or 2 of each). Calculate sums. |
Recursive Branching (Ternary). |
Draw a root (base). From it, draw 3 branches for Topping 1 (none, one, two). From each, 3 for Topping 2. $O(B \cdot 3^T)$. |
Backtracking with Pruning. |
The "Price Ceiling" Tree. |
Start recursion for each base. If current cost exceeds `target + (target - min_found)`, stop branching (pruning). Track the cost with the smallest absolute difference. |
Draw a search tree. Draw a "red line" at a certain cost. Cross out all branches that go past that line. |
Bounded Exponential Search. |
Draw a tree with 3^T nodes but highlight how pruning cuts off half the width. Label $O(B \cdot 3^T)$. |
None, just sum tracking. |
Recursion stack (Topping count). $O(T)$ space. |
| 1775 |
Equal Sum Arrays With Minimum Number of Operations |
Try every possible way to change numbers in both arrays until sums are equal, perhaps using BFS or DFS. |
State-Space Pathfinding. |
Draw two sums. Branch into every possible modification (1-6) for every index. $O(6^{N+M})$. |
Greedy + Frequency Counting (Bucket Sort). |
The "Gap Shrinker". |
Calculate `diff = abs(sum1 - sum2)`. Put potential gains (6 - val) or (val - 1) into a frequency array (buckets 0-5). Pick from the largest gain bucket (5) first. |
Draw two bar charts (sums). Draw the "gap" between them. Draw 5 buckets of potential "bricks" to fill the gap. Take bricks from the largest bucket until the gap is \le 0. |
Frequency-Based Greedy Scan. |
Draw a fixed-size loop (6 iterations). Label $O(N + M)$. |
Deep recursion stack. |
Frequency array of size 6. $O(1)$ extra space. |
| 1776 |
Car Fleet II |
For every car, check all cars in front. Calculate collision times for every pair and simulate fleets merging step-by-step. |
Nested Right-Side Simulation. |
Draw cars as dots. Draw lines for every potential future collision point. $O(N^2)$. |
Monotonic Stack (Right-to-Left) + Collision Time Comparison. |
The "Vanishing Horizon" Stack. |
Traverse from right to left. Maintain a stack of cars. If a car is faster than the one in front, it will collide. If its collision time is later than the car in front's own collision, pop the front car (it's part of a different fleet already). |
Draw a vertical stack. Push a car. If the next car "catches" it too late (past its own collision), pop. Use the formula: time = (pos2 - pos1) / (speed1 - speed2). |
Single Pass Stack Maintenance. |
Draw one arrow moving right-to-left. For each car, show 0-2 pops. Label $O(N)$. |
Multiple copies of fleet state arrays. |
A Stack of indices/floats. $O(N)$ space. |
| 1777 |
Product's Price for Each Store (SQL) |
Use 3 separate SELECT queries (one for each store) and UNION them together using multiple joins or subqueries. |
Vertical-to-Horizontal Join. |
Draw Table A, Table B, Table C. Use arrows to link Product IDs across all three. $O(N)$. |
Pivot Table (CASE WHEN + GROUP BY). |
Sorting into Vertical Columns. |
Group by `product_id`. For each group, use `SUM(CASE WHEN store = 'store1' THEN price ELSE NULL END)` to "lift" the price into the correct column. |
Draw a narrow, tall table. Draw 3 buckets labeled Store1, Store2, Store3. Tally prices into the buckets for each ID. |
Single Pass Aggregation. |
Draw one sweep through the table rows. Label $O(N)$. |
3 temporary tables in memory. |
In-memory grouping hash table. $O(\text{Unique}\_\text{Products})$ space. |
| 1778 |
Shortest Path in a Hidden Grid |
Blindly move in random directions using the Master object until you happen to find the target, without mapping visited cells. |
Random Walk / Infinite Graph Search. |
Draw a line wandering randomly. It might loop or visit the same cell 1000 times. No bound. |
DFS (to Map) + BFS (to Find Shortest Path). |
The "Cartographer" Search. |
1. Use DFS to explore the entire hidden grid and build an internal map (`visited` set). 2. Use BFS on your internal map to find the shortest path from (0,0) to target. |
Draw a dark grid. Draw a pencil tracing all reachable cells (DFS). Then, draw a water ripple (BFS) on the paper you just drew to find the path. |
Grid-Size Traversal. |
Draw an R \times C grid. Show one DFS pass and one BFS pass. Label $O(R \cdot C)$. |
None, just current state. |
A Hash Map/Set of coordinates + BFS queue. $O(R \cdot C)$ space. |
| 1779 |
Find Nearest Point That Has the Same X or Y Coordinate |
Loop through all points. Check if it's valid (same X or Y), calculate Manhattan distance for all valid points, sort them by distance and index. |
List-then-Sort Filter. |
Draw all points. Draw lines to target. Filter lines. Sort. $O(N \log N)$. |
Single Pass Minimum Tracking. |
The "Streaming Winner". |
Iterate through points once. If x == x1 or y == y1, calculate dist. If dist < min\_dist, update min\_dist and min\_idx. |
Draw a list. Hold a "Winner" card. As you scan, if a point is closer, swap the card. |
Linear Sweep. |
Draw one arrow passing over the points. Label $O(N)$. |
$O(N)$ list to store distances. |
Three integer variables. $O(1)$ space. |
| 1780 |
Check if Number is a Sum of Powers of Three |
Recursive backtracking: try including every power of 3 (3^0, 3^1, 3^2...) up to n to see if any subset sums to n. |
Binary Decision Tree. |
Draw a root. Branch "Include" or "Exclude" for each power of 3. $O(2^{\log_3 n})$. |
Base 3 Representation (Ternary Logic). |
The "Digit Filter". |
Convert n to base 3. If any digit in the base-3 representation is '2', it means you need to use a power of 3 twice, which is not allowed. If only '0's and '1's, return True. |
Perform repeated division by 3. If `n % 3 == 2`, write "FAIL". Otherwise, keep dividing. |
Logarithmic Reduction. |
Draw a number shrinking by 1/3 each time. Label $O(\log_3 n)$. |
Recursion stack. |
A single integer variable. $O(1)$ space. |
| 1781 |
Sum of Beauty of All Substrings |
Three nested loops: two for (i, j) boundaries and a third to count char frequencies in each substring. |
Triple-Nested Sliding Window. |
Draw a string. Draw brackets for every substring. For each bracket, draw a frequency table and scan all letters. $O(N^3)$. |
Nested Loop with Running Frequency Array. |
The "Expanding Balloon" Tally. |
Fix the start point i. Move j from i to n-1. In each step, just increment the frequency of S[j] in a 26-size array and find the max/min of that array. |
Draw i as an anchor. Draw j sliding right. Below, draw a 26-slot array updating in real-time. Sum (max - min) at each j. |
2D Parameter Scan. |
Draw an N \times N grid. Each cell is $O(26)$. Label $O(26 \cdot N^2)$. |
$O(N)$ for each substring's copy. |
A fixed-size array of 26. $O(1)$ extra space visual. |
| 1782 |
Count Pairs Of Nodes |
Iterate through every possible pair of nodes (u, v). Calculate their combined incident edges (subtracting the shared edge) and compare to queries. |
All-Pairs Edge Inspection. |
Draw N nodes. Draw lines connecting every node to every other node. Count incident edges for each pair. $O(N^2 + Q \cdot N^2)$. |
Two Pointers on Sorted Degrees + Shared Edge Subtraction. |
The "Sort and Correct" Pivot. |
1. Get degrees of all nodes and sort them. 2. Use two pointers to count pairs where deg(u) + deg(v) > query. 3. Iterate through actual edges and subtract those where deg(u) + deg(v) - shared\_edge drops below the query threshold. |
Draw a list of sorted degrees. Use two pointers moving inward. Then, draw a hash map of edge counts and cross out pairs that fall below the limit after subtraction. |
Sorting + Pointer Convergence. |
Draw sorting $O(N \log N)$ + Two pointers $O(N)$ + Edge Correction $O(E)$. Label $O(Q \cdot (N+E)$). |
Adjacency matrix. $O(N^2)$. |
Hash map for edges + Sorted degree array. $O(N + E)$ space. |
| 1783 |
Grand Slam Titles (SQL) |
Use 4 separate SELECT statements for each Grand Slam (Wimbledon, US_Open, etc.), count titles per player, and then JOIN them manually. |
Multi-Source Vertical Join. |
Draw 4 separate winner tables. Manually tally Player ID occurrences across all four. $O(N)$. |
UNION ALL + GROUP BY. |
The "Funnel Merge". |
`SELECT Wimbledon AS id FROM Championships UNION ALL SELECT Fr_Open...` Group the result of the UNION by `id` and count. Join with the `Players` table. |
Draw 4 streams flowing into one vertical pipe. At the bottom of the pipe, a machine groups identical IDs and prints a tally. |
Single Pass Aggregation. |
Draw one sweep through the aggregated ID list. Label $O(N)$. |
Multiple temp tables for each slam. |
One temporary hash table for grouping. $O(\text{Unique}\_\text{Winners})$ space. |
| 1784 |
Check if Binary String Has at Most One Segment of Ones |
Count all segments of "1"s in the string. If count > 1, return false. |
Segment Counting Sweep. |
Draw a string. Circle every cluster of 1s. Count circles. $O(N)$. |
Pattern Searching (Presence of "01"). |
The "Gap Detector". |
Since the string always starts with '1', a second segment can only exist if there is a '0' followed by a '1'. Simply return `'01' not in s`. |
Draw a string starting with 1. If you ever see a "0" then a "1", draw a red 'X'. |
Single Scan Pattern Match. |
Draw one arrow passing over the string. Label $O(N)$. |
List of segments. |
No extra space. $O(1)$ space. |
| 1785 |
Minimum Elements to Add to Form a Given Sum |
While the current sum != goal, add `limit` or a fraction of it to the sum and increment a counter. |
Linear Simulation. |
Draw a number line. Start at `sum`. Draw jumps of size `limit` until you hit `goal`. $O(\\text{text}{\text{Diff}/\text{Limit}})$. |
Mathematical Ceiling Division. |
The "Greedy Bridge". |
Calculate `diff = abs(goal - current_sum)`. The answer is `(diff + limit - 1) // limit`. |
Calculate the gap. Divide the gap by the maximum possible step size. Round up. |
Constant Time Calculation. |
Write the math formula. Label $O(1)$ for query, $O(N)$ for the initial sum. |
None. |
Single float/int variables. $O(1)$ space. |
| 1786 |
Number of Restricted Paths From First to Last Node |
DFS to find all paths from 1 to n. For each edge (u, v) in a path, check if distance(u, n) > distance(v, n) by recalculating Dijkstra for every step. |
Exponential Path Tree with Redundant Dijkstra. |
Draw node 1. Branch into all neighbors. For every branch, draw a full Dijkstra table. $O(2^N \cdot E \log V)$. |
Dijkstra (from Node N) + DAG DP (Topological Sort/Memoization). |
Gradient Descent on a Graph. |
1. Run Dijkstra starting from node N to get distances to all nodes. 2. Treat the graph as a Directed Acyclic Graph (DAG) where edges only go from high distance to low distance. 3. Count paths using DP. |
Draw nodes. Next to each, write its distance to N. Draw arrows only from large numbers to small numbers. Use a DP tally at each node starting from N=1. |
Single Source Shortest Path + Linear DAG Scan. |
Draw Dijkstra $O(E \log V)$ + DFS with memoization $O(E)$. Total $O(E \log V)$. |
Massive recursion stack without memoization. |
Distance array + Memoization array + Priority Queue. $O(V + E)$ space visual. |
| 1787 |
Make the XOR of All Segments Equal to Zero |
For every segment of size K, try changing every number to all possible values in range (0-1023) to see if XOR of every segment is 0. |
State-Space Combinatorial Explosion. |
Draw K slots. For each slot, draw 1024 branches. $O(1024^K)$. |
DP with Frequency Partitioning (i \pmod K). |
XOR Cumulative Balance Sheet. |
Numbers nums[i] and nums[i+K] must be the same for all segments to have XOR 0. Group indices by i \pmod K. Use DP to find the min changes for each group to reach a target XOR. |
Draw K columns. Put numbers into columns based on `index % K`. For each column, track how many elements exist. Use a DP table `dp[position][current_xor]`. |
Iterative Matrix Transformation. |
Draw a K \times 1024 grid. Each cell is a XOR state. Label $O(K \cdot 1024)$. |
Recursive stacks for combinations. |
2D DP table + Frequency Maps for each column. $O(K \cdot 1024)$ space. |
| 1788 |
Maximize the Beauty of the Garden |
Find all pairs of identical flowers. For each pair, sum all positive beauties between them. Find the max. |
All-Pairs Range Sum (Quadratic). |
Draw array. Find identical numbers. Draw a bracket between them and sum the items inside. $O(N^2)$. |
Prefix Sums + First Occurrence Hash Map. |
The "Bookend" Summation. |
Precompute prefix sums of *only* positive beauty values. Store the first occurrence index of each value. When you see the value again at index j, the beauty is 2 \cdot val + (pref[j-1] - pref[first\_idx]). |
Draw a prefix sum line (only going up for positives). Mark the "First Sight" of each number. When you see it again, subtract the "First Sight" value from the current "Total". |
Single Pass Lookup. |
Draw one arrow passing over the array. Label $O(N)$. |
None, just sum variables. |
Hash map of size N + Prefix sum array. $O(N)$ space. |
| 1789 |
Primary Department for Each Employee (SQL) |
For each employee, check if they have a 'Y' in primary. If not, re-scan the table to see if they only have one department total. |
Nested Subquery Scan. |
Draw Employee list. For each, draw a line to the table to find 'Y'. If empty, draw another line to count total rows. $O(N^2)$. |
UNION of two filtered sets. |
The "Binary Filter" Set. |
Filter 1: All rows where `primary_flag = 'Y'`. Filter 2: All rows for employees where `COUNT(dept) = 1`. UNION these results. |
Draw two funnels. Funnel A catches all 'Y's. Funnel B catches "Only Children". Combine the output. |
Sequential Filtering. |
Draw one sweep through the table rows. Label $O(N)$. |
Multiple memory scans for subqueries. |
SQL temporary result set. $O(N)$ space. |
| 1790 |
Check if One String Swap Can Make Strings Equal |
Try swapping every possible pair (i, j) in string 1. After each swap, check if s1 == s2. |
All-Pairs Swapping. |
Draw string 1. Draw arrows swapping index 0 with 1, 0 with 2... after each, compare with s2. $O(N^3)$. |
Mismatch Index Comparison. |
The "Error Spotlight". |
Find all indices i where s1[i] != s2[i]. If count is 0, true. If count is not 2, false. If count is 2, check if s1[i] == s2[j] and s1[j] == s2[i]. |
Draw two strings. Circle the indices where letters don't match. If you have exactly two circles, draw an "X" between them to see if the letters flip correctly. |
Single Linear Scan. |
Draw one arrow passing over the strings. Label $O(N)$. |
None, just loop pointers. |
A list of at most 2 indices. $O(1)$ extra space. |
| 1791 |
Find Center of Star Graph |
Iterate through all nodes. For each node, count how many edges it is connected to. The center node will have n-1 connections. |
Degree Tally Map. |
Draw N nodes. Draw lines for every edge. Build a table and tally connections for every node. $O(N)$. |
Logical Comparison of First Two Edges. |
The "Common Link" Snapshot. |
In a star graph, the center MUST appear in every edge. Just look at the first two edges [u1, v1] and [u2, v2]. The center is the node that appears in both. |
Draw two pairs of numbers. Circle the number that appears in both pairs. That's the center. |
Constant Time Check. |
Write down two edges. Label $O(1)$. |
Adjacency list or degree array of size N. $O(N)$. |
Two edge variables. $O(1)$ space. |
| 1792 |
Maximum Average Pass Ratio |
Try adding each extra student to every possible class and see which one increases the total average the most. Repeat for every extra student. |
Nested Greedy Simulation. |
Draw extra students as blocks. For each block, calculate the new average for every class. $O(\\text{text}{\text{extraStudents}} \\text{times} \\text{text}{\text{classes}})$. |
Max-Heap (Priority Queue) of "Potential Gain". |
The "Marginal Benefit" Funnel. |
Calculate the gain if one student is added: gain = \frac{pass+1}{total+1} - \frac{pass}{total}. Store classes in a Max-Heap based on this gain. Always pick the top class, update its pass/total, recalculate gain, and push back. |
Draw a heap (tree). Root is the class that benefits MOST from one student. Take the root, add a student, re-insert. Repeat for all extra students. |
Logarithmic Selection. |
Draw a heap update cycle. Label $O(\\text{text}{\text{extraStudents}} \cdot \log(\\text{text}{\text{classes}})$). |
None, just sum variables. |
A Max-Heap storing N classes. $O(N)$ space. |
| 1793 |
Maximum Score of a Good Subarray |
Generate all subarrays that include index k. For each, find the minimum value and multiply by the subarray length. |
Nested Range Search (Quadratic). |
Draw the array with k highlighted. Draw all possible brackets (i, j) such that i \le k \le j. Calculate score for each. $O(N^2)$. |
Two Pointers (Expanding from k). |
The "Expanding Walls" Search. |
Start at i = j = k. While you can expand left or right, always move the pointer that points to a larger value to keep the "minimum" as high as possible. Track max score. |
Draw array. Place i and j at k. Compare arr[i-1] and arr[j+1]. Move to the larger one. Update the "global minimum" as you go. |
Linear Treadmill. |
Draw one set of pointers converging (or expanding) across the entire array once. Label $O(N)$. |
None, just variables. |
Three integer variables (i, j, \text{min\_val}). $O(1)$ space. |
| 1794 |
Count Pairs of Equal Substrings With Minimum Difference |
Find all pairs of equal characters in s1 and s2. For each pair at indices (i, j), calculate i - j. Find the minimum difference and count occurrences. |
All-Pairs Character Intersection. |
Draw s1 and s2. Draw lines connecting every 'a' in s1 to every 'a' in s2. Repeat for all letters. $O(N \cdot M)$. |
First/Last Occurrence Hash Map. |
The "Global Extremes" Comparison. |
To minimize i - j, we need the *smallest* i (first occurrence in s1) and the *largest* j (last occurrence in s2). Store these in two maps of size 26. Calculate i - j for each character. |
Draw two alphabet lists (A-Z). Mark the first index for s1 and last for s2. Subtract them. Find the smallest result. |
Alphabet-Constrained Scan. |
Draw one sweep through s1 and s2, then a 26-step loop. Label $O(N + M)$. |
List of all index pairs. |
Two arrays of size 26. $O(1)$ space. |
| 1795 |
Rearrange Products Table (SQL) |
Select all rows. In the application layer, loop through each row and if store1, store2, or store3 prices exist, create a new record for each. |
Application-Level Row Multiplying. |
Draw one wide row. Draw three arrows pointing to three narrow rows. $O(N)$. |
SQL UNION ALL (Unpivoting). |
The "Stacking Transformation". |
Use `SELECT id, 'store1' AS store, store1 AS price FROM Table WHERE store1 IS NOT NULL` and `UNION ALL` for each store column. |
Draw a table with 3 price columns. Draw a vertical funnel for each column. The funnels stack the results on top of each other. |
Multi-Pass Filter & Merge. |
Draw three parallel arrows filtering the same data source. Label $O(N)$. |
$O(N)$ data loaded into memory. |
SQL engine streaming. $O(N)$ output rows. |
| 1796 |
Second Largest Digit in a String |
Extract all digits into a list, remove duplicates by converting to a set, sort the list in descending order, and pick the second element. |
Multi-Stage Data Filtering. |
Draw a string. Draw a sieve that only lets digits through. Draw a sorting funnel. Pick the 2nd item. $O(N \log N)$. |
Single-Pass Scalar Tracking. |
The "Runner-Up" Podium. |
Iterate through characters. Maintain two variables: `first` and `second`. If digit > `first`, `second = first`, `first = digit`. If digit < `first` but > `second`, update `second`. |
Draw two podium steps labeled 1st and 2nd. When a new number arrives, show it bumping the 1st place holder down to 2nd. |
Linear Scan. |
Draw one straight arrow over the string. Label $O(N)$. |
A list/set storing all digits in the string. $O(N)$. |
Two integer variables. $O(1)$ space. |
| 1797 |
Design Authentication Manager |
Use a list of pairs `(tokenId, expiryTime)`. For every `generate` and `renew`, scan the entire list to find the ID. |
Iterative Record Searching. |
Draw a vertical log. For every request, draw an arrow searching from the top to find a specific ID. $O(N)$ per op. |
Hash Map (Dictionary) for $O(1)$ Access. |
Token Vault. |
Store tokens in a Map: `tokenId: expiryTime`. `generate` is a simple put. `renew` checks if `current < map[id]`; if yes, update. `countUnexpired` iterates over values. |
Draw a box divided into slots (HashMap). Show an ID pointing directly to its expiry time slot. No searching required. |
Constant Time Operations (mostly). |
Write $O(1)$ for generate/renew and $O(T)$ for counting. Label $O(N)$ for space. |
List of pairs. $O(N)$. |
HashMap entries. $O(N)$ space. |
| 1798 |
Maximum Number of Consecutive Values You Can Make |
Generate all 2^N possible subset sums. Sort the resulting sums and find the length of the longest consecutive sequence starting from 0. |
Exponential Sum Tree. |
Draw N nodes. Each branches into "include" or "exclude". Total 2^N leaves. For N=20, $O(1,048,576)$. |
Greedy (Sort and Gap-Check). |
The "Expanding Reach" Number Line. |
Sort coins. Maintain `res = 1` (we can make 0 initially). For each coin `c`, if `c <= res`, we can now make everything up to `res + c`. If `c > res`, there is a gap. |
Draw a number line shaded from 0 to `res`. If the new coin `c` is smaller than the shaded length, extend the shade by `c`. |
Sorting + Linear Sweep. |
Draw the sorting $O(N \log N)$ funnel followed by a single arrow $O(N)$. Label $O(N \log N)$. |
List of 2^N sums. $O(2^N)$. |
None, just a `res` variable. $O(1)$ extra space. |
| 1799 |
Maximize Score After N Operations |
Recursive backtracking: Pick any 2 numbers, calculate score, and repeat for the remaining numbers. Try all possible pairings. |
Recursive Pairwise Combinations. |
Draw numbers. Branch for every possible first pair. Branch for second pair. $O((2N)$! / (2^N * N!)). |
Bitmask Dynamic Programming + GCD Precomputation. |
Binary Toggle Switches. |
Use an integer `mask` where the i-th bit is 1 if nums[i] is used. `dp[mask]` stores the max score for that state. Transition by picking two unset bits i, j and recurse. |
Draw 14 light switches. Show a "State" where switches 1 and 4 are ON. Show arrows leading to new states where 2 more switches are flipped ON. |
State-Space Exploration with Pruning. |
Draw a graph of bitmasks. Label $O(2^{2N} \cdot (2N)$^2). For N=7, 2^{14} = 16,384 states. |
Deep recursion stack with duplicated arrays. |
1D DP array of size 2^{2N} + 2D GCD table. $O(2^2N)$ space. |
| 1800 |
Maximum Ascending Subarray Sum |
Generate all subarrays (O(N^2)). For each, check if it's strictly ascending (O(N)) and find the sum. |
Triple-Nested Loop Matrix. |
Draw array. Draw brackets for every possible start and end. Inside, draw a checkmark if ascending. $O(N^3)$. |
Single-Pass Greedy Accumulation (Kadane's Variant). |
The "Growing Wave" Reset. |
Iterate once. If `arr[i] > arr[i-1]`, add to `current_sum`. Else, `current_sum = arr[i]`. Track `max_sum = max(max_sum, current_sum)`. |
Draw a line graph. As long as it goes up, keep a running total. If it drops, "break" the line and start a new total from the bottom. |
Single Linear Sweep. |
Draw one arrow passing over the array. Label $O(N)$. |
List of all ascending subarray sums. |
Two integer variables: `current` and `max`. $O(1)$ space. |
| 1801 |
Number of Orders in the Backlog |
Array insertion and linear scan for matching best prices. |
Linear timeline graph. |
Draw an array, use arrows to simulate a full scan for each new order, noting $O(N)$ per step. |
Two Priority Queues (Min-Heap for Sell, Max-Heap for Buy). |
Dual Pyramids (Heaps). |
Place buys in max-heap, sells in min-heap. If max top >= min top, cross out quantities and update. |
Draw two triangles (heaps). Write values at the top. Draw arrows matching top nodes, cross out matched amounts. |
Logarithmic tree traversal paths. |
Draw a binary tree path, highlight $O(\log N)$ swaps down the tree per insertion/deletion. |
Contiguous array blocks shifting elements. |
Array-backed binary tree blocks (heap array mapping). |
| 1802 |
Maximum Value at a Given Index in a Bounded Array |
Linear search from maxSum down to 1, validating each by simulating the array. |
Step-by-step array generation grid. |
Draw a grid. Row by row, generate the array for a candidate value. Count the sum. |
Binary Search on Answer + Greedy Math (Arithmetic Progression sum). |
Search space division line & mountain array shape. |
Pick mid. Calculate arithmetic sum on left and right. Compare to maxSum to adjust L/R pointers. |
Draw a horizontal line 1 to maxSum. Mark mid. Draw a triangle (peak at index) and calculate area (sum). |
Binary search halving line + $O(1)$ math evaluation. |
Draw a line cut in half repeatedly, marking $O(1)$ next to each cut. |
Full array allocation blocks (O(N) space). |
Three variables (L, R, Mid) as isolated memory registers (O(1) space). |
| 1803 |
Count Pairs With XOR in a Range |
Nested loops $O(N^2)$ calculating XOR for every pair. |
N x N grid matrix. |
Draw an N x N matrix. Cross out the lower triangle. Mark cells where XOR is within [low, high]. |
0-1 Trie (Binary Trie). |
Binary Decision Tree. |
Insert numbers bit by bit. For counting, traverse based on XOR logic comparing with high+1 and low. |
Draw a binary tree with 0 and 1 edges. Track count at each node. Traverse down matching bits. |
Constant depth tree paths (Depth 15). |
Draw a single downward path of length 15. Annotate with $O(1)$ constant time max-depth per number. |
$O(1)$ loop variables in stack. |
Nodes with 2 children mapped as a DAG/Tree in heap memory. |
| 1804 |
Implement Trie II (Prefix Tree) |
Array of Strings. Insert = append. Count = linear scan with string matching. |
Parallel string comparison bars. |
List strings. Draw an arrow sliding down each string sequentially to check prefixes. |
Standard Trie with wordCount and prefixCount variables at each node. |
Multi-way Tree (26-ary). |
Add word: travel nodes, increment prefixCount. At end, increment wordCount. Erase: decrement both. |
Draw circles containing letters. Write [wc: 0, pc: 1] next to them. Update numbers as you trace paths. |
String length path traversal. |
Draw a sequence of nodes equal to string length L. Annotate with $O(L)$ time. |
Dynamic array of full strings. |
Nodes with arrays of size 26 containing pointers + 2 integer counters. |
| 1805 |
Number of Different Integers in a String |
Replace non-digits with space, split string, parse to integer, add to Set. |
Multi-pass string transformation pipeline. |
Draw the string. Cross out letters. Write new string. Circle segments. Map to integers. |
Two Pointers + Hash Set (skip leading zeros directly). |
Sliding window pointers moving on a tape. |
Move i to digit. Move j to end of digits. Strip leading '0's. Add to Hash Set. Update i = j. |
Draw string as a tape. Draw arrow i scanning. When digit found, draw j jumping ahead. |
Single pass linear tape. |
Draw an arrow traversing a line from 0 to N. Mark $O(N)$. |
Intermediate string arrays + Hash Set buckets. |
Hash Set containing substring pointers/references. |
| 1806 |
Minimum Number of Operations to Reinitialize a Permutation |
Simulate the permutation process using two arrays until the array matches the original. |
Array state transition matrix. |
Draw the array at step 0. Draw arrows moving elements to new indices. Count steps until sorted. Mark $O(N^2)$ worst case. |
Math/Graph (Cycle Detection). Track only the movement of index 1. |
Directed graph cycle tracking a single node. |
Start at index 1. Apply the formula to find its next position. Increment a counter until it returns to 1. |
Draw a circle. Write '1' at the top. Calculate the next index, draw an arrow to it. Continue until the arrow points back to '1'. |
Single integer loop timeline. |
Draw a single loop with a counter 'k'. Annotate with $O(N)$ time and $O(1)$ space. |
Multiple arrays created and cloned in memory (O(N) space). |
Two integer variables (current_pos, steps) mapped as $O(1)$ registers. |
| 1807 |
Evaluate the Bracket Pairs of a String |
Extract each key, linearly search the knowledge array for a match, and use string concatenation. |
String builder with nested linear scan arrows. |
Draw the string. Circle a bracketed word. Draw an arrow to the list of pairs, scanning down to find a match. $O(N \cdot M)$. |
Hash Map for lookups + Single Pass StringBuilder. |
Hash table lookup pipeline. |
Store knowledge in map. Read string. If '(', collect key. Lookup key in map, append value (or '?') to result string. |
Draw a map with keys/values. Draw the string as a tape. Below it, draw the output tape filling up via $O(1)$ map lookups. |
Parallel tracks (Map creation + String traversal). |
Draw one track for $O(E)$ hash map creation, and a second track for $O(N)$ string traversal. |
Immutable string objects causing memory fragmentation. |
Hash Map buckets and a contiguous mutable StringBuilder array. |
| 1808 |
Maximize Number of Nice Divisors |
Backtracking to find all prime factorizations and calculating divisors. |
Exponential tree of prime factor splits. |
Draw a root node, branch out all possible integer partitions, calculate product for each. Mark $O(2^N)$. |
Greedy Math (Integer Break logic) + Fast Modular Exponentiation. |
Number line divided into blocks of 3. |
Check base cases. Maximize 3s. If remainder is 1, swap a 3 for two 2s. Use fast power for 3^k mod M. |
Draw a block of length N. Chop it into 3s. If a 1 is left, group it with the last 3 to make two 2s. |
Logarithmic halving steps. |
Draw $O(\log N)$ exponentiation by squaring steps as a collapsing binary tree for the math calculation. |
Massive call stack for exponential recursion. |
$O(1)$ space with simple modulo variables and bitwise shift registers. |
| 1809 |
Ad-Free Sessions (SQL) |
Cross join Playback and Ads, filter where ad timestamp is between playback times. Exclude matches. |
Cartesian product grid. |
Draw a table mapping every session to every ad. Cross out rows without time overlaps. |
LEFT JOIN with time range condition + IS NULL check. |
Venn diagram with exclusion (Anti-Join). |
Join Playback to Ads only where ad times overlap. Select Playback IDs where the joined Ad ID is missing. |
Draw two tables. Draw lines connecting overlapping times. Circle the Playback rows that have NO lines connected. |
Relational Algebra Hash/Merge Join flow. |
Draw a hash table for intervals to visualize how the DB engine optimizes the join in $O(N \log N)$ or $O(N)$. |
N x M massive temporary table in disk/memory. |
Hash join partitions and filtered result set in memory. |
| 1810 |
Minimum Path Cost in a Hidden Grid (Premium) |
Random walk or unoptimized backtracking to find the target, then simple BFS. |
Blindfolded maze traversal graph. |
Draw a grid with hidden cells. Draw a chaotic squiggly line showing inefficient exploration. |
DFS mapping (to reveal grid) + Dijkstra's Algorithm (Shortest Path). |
Wavefront expansion on a newly revealed map. |
Use DFS to move the robot, recording costs. Backtrack to explore all reachable cells. Run Dijkstra from start on the known map. |
1. Draw a tree for DFS backtracking. 2. Draw concentric rings from the start node showing Dijkstra expanding. |
Graph traversal V+E bounds combined. |
Draw a grid bounding box, noting $O(V+E)$ exploration and $O(E \log V)$ for Dijkstra's heap operations. |
Unbounded recursive call stack or infinite loops without visited sets. |
2D Visited/Cost Matrix + Priority Queue (Min-Heap array) for routing. |
| 1811 |
Find Interview Candidates (SQL) |
Multiple heavy subqueries: Self-joins to find 3 consecutive wins, UNION with group by for 3+ total medals. |
Nested query execution trees. |
Draw tables joined multiple times with thick lines, highlighting the massive row combinations (N x N) for consecutive checks. |
Window Functions (ROW_NUMBER) to group consecutive sequences + CTEs. |
Partitioned data blocks sliding over time. |
Subtract row_number from contest_id. If a user wins consecutive contests, this difference remains constant. Group by this difference. |
List rows. Next to them, write RowNum and (ContestID - RowNum). Circle the blocks where the result is identical. |
Linear table scan pipeline. |
Draw a single arrow scanning down the table, calculating $O(1)$ row_number operations per row. |
Large intermediate temporary tables generated in memory/disk. |
In-memory partitioned window frames. |
| 1812 |
Determine Color of a Chessboard Square |
Initialize an 8x8 matrix simulating the board with true/false, then parse the string to look up the matrix. |
2D Matrix Allocation block. |
Draw an 8x8 grid. Shade alternating squares. Map coordinates to a specific cell. |
Math (Parity check): Sum of ASCII value of letter and integer value of number. |
Modular arithmetic scale. |
Convert 'a' to 1. Add it to the row number. If the sum is even, it's black (false). If odd, it's white (true). |
Write (col_value + row_value). Write "% 2". Draw a decision split: 0 -> Black, 1 -> White. |
Single CPU cycle operation block. |
Draw a simple mathematical formula box. Mark as $O(1)$ time complexity. |
8x8 Array/Matrix taking up memory space. |
No data structures. Just $O(1)$ stack variables. |
| 1813 |
Sentence Similarity III |
Try inserting all possible substrings into the shorter sentence to see if it matches the longer one. |
Combinatorial string matching tree. |
Draw the short sentence. Branch out all possible insertions. Compare each with the target. Very high complexity. |
Two Pointers / Deque (Match from front, match from back). |
Two shrinking arrays from opposite ends. |
Split both into word arrays. While front words match, move left pointer. While back words match, move right pointer. Valid if short array is fully crossed out. |
Draw two arrays of words. Draw L pointer moving right, R pointer moving left. Cross out matched words. Check if L > R on short array. |
Two pointers converging linearly. |
Draw a line of length N. Draw arrows from both ends meeting in the middle. Annotate $O(N)$. |
Many intermediate substring allocations. |
Two Arrays of string references + 4 integer pointers. |
| 1814 |
Count Nice Pairs in an Array |
Nested loops checking every pair (i, j) if nums[i] + rev(nums[j]) == nums[j] + rev(nums[i]). |
N x N interaction grid. |
Draw an array. Draw lines connecting every element to every other element. Mark $O(N^2)$ checks. |
Math Rearrangement + Hash Map: Check nums[i] - rev(nums[i]) == nums[j] - rev(nums[j]). |
Frequency Buckets. |
For each num, calculate difference = num - rev(num). Look up difference in hash map. Add current count to total pairs, then increment map. |
Draw an array. Under each, write `x - rev(x)`. Draw buckets for each unique difference. Add combinations `n*(n-1)/2` for each bucket. |
Single pass + constant time lookups. |
Draw a single pass arrow over the array, pointing to a hash map. Mark $O(N)$ time. |
No extra memory besides loop variables, but $O(N^2)$ time limit exceeded. |
Hash Map mapping integer differences to frequency counts. |
| 1815 |
Maximum Number of Groups Getting Fresh Donuts |
Generate all permutations of the groups to find the exact ordering that maximizes happy groups. |
Factorial explosion tree (O(N!)). |
Draw a tree branching into N paths, then N-1, etc. Note that it's physically impossible to draw completely. |
Greedy (modulo matches) + DP with Bitmask / Memoization for remainders. |
State space reduction + Memoization DAG. |
1. Take groups where size % batch == 0. 2. Pair up groups where a + b == batch. 3. Use DP/DFS with a tuple of remainder frequencies to find the rest. |
Draw buckets 0 to batch_size-1. Match bucket 1 with bucket k-1. For leftovers, draw a small state transition tree showing memoized branches. |
Bounded state combinations grid. |
Draw a multidimensional grid representing states of remainder counts. Max states are heavily constrained, making it $O(\text{States})$. |
Massive recursion stack for permutations. |
Hash Map / Multi-dimensional Array mapping tuple states to max happy groups. |
| 1816 |
Truncate Sentence |
Split the entire string by spaces into an array, slice the first k elements, then join them back into a string. |
Array fragmentation and reassembly block. |
Draw a long string. Draw vertical lines slicing it at every space. Box the first k words, draw an arrow joining them back. Mark $O(N)$ space. |
Single Pointer Iteration (count spaces and substring once). |
Pointer sliding on a continuous tape. |
Move a pointer i from 0. If s[i] == ' ', increment a space counter. When counter == k, return s[0...i]. |
Draw the string as a single strip. Move an arrow (pointer i) left to right. Tick off a tally mark at each space. Cut the strip at k. |
Partial linear scan line. |
Draw an arrow starting at index 0 and stopping before the end of the line at index M (where M <= N). Mark $O(M)$ time. |
Full array of string tokens allocated in heap memory. |
Single contiguous memory block for the final substring. |
| 1817 |
Finding the Users Active Minutes |
Nested loops comparing every log entry to filter out duplicate minutes for each user manually. |
N x N interaction grid of log comparisons. |
Draw a list of logs. For every log, draw lines connecting to every other log checking for matching user IDs and times. |
Hash Map mapping User ID to a Hash Set of minutes. |
Buckets (Users) containing unique marbles (minutes). |
Iterate logs. Map[user_id].add(time). Then, create an answer array. Iterate Map values, increment answer[set.size() - 1]. |
Draw buckets labeled with User IDs. Toss "minute" numbers into them. Cross out duplicates. Count marbles in each bucket, tally in an array. |
Two-phase linear traversal (Logs -> Map -> Array). |
Draw a flow chart: $O(N)$ log traversal -> $O(U)$ map traversal -> $O(K)$ array update. |
Large unsorted nested lists or multi-dimensional arrays. |
Hash Map chaining to Hash Sets in memory. |
| 1818 |
Minimum Absolute Sum Difference |
Try replacing every nums1[i] with every nums1[j], recalculate the entire sum difference, and track the minimum. |
Combinatorial replacement matrix. |
Draw the array. Pick one element, draw N arrows replacing it with every other element. Repeat for all N elements. $O(N^2)$. |
Binary Search (bisect) on a sorted copy of nums1 to find the closest value to nums2[i]. |
Number line with jump distances. |
Calculate base diff sum. Sort a copy of nums1. For each i, binary search nums2[i] in sorted_nums1. Find closest value. Maximize (old_diff - new_diff). |
Draw original arrays and their vertical differences. Draw a sorted nums1. Pick a nums2 target, binary search the sorted array, draw a new shorter difference line. |
$O(N \log N)$ sorting + N * $O(\log N)$ search operations. |
Draw N distinct binary search trees branching off a main iteration line. |
$O(1)$ memory if mutating original array to check differences, but computationally heavy. |
One duplicated sorted array $O(N)$ for binary search reference. |
| 1819 |
Number of Different Subsequences GCDs |
Generate all 2^N possible subsequences, calculate the GCD for each, and store in a Set. |
Exponential binary inclusion/exclusion tree. |
Draw a massive tree branching left (include) and right (exclude) for every element. $O(2^N)$ paths. |
Math (Sieve-like approach). Check if a target GCD 'x' can be formed by iterating its multiples. |
Multiplication grid overlay on a number line. |
Track present numbers in a boolean array. For every potential GCD x (1 to MaxNum), find all its multiples in the array. If the GCD of these multiples == x, increment answer. |
Draw a number line. Pick a candidate x (e.g., 3). Hop by 3s (3, 6, 9). Circle the ones present in the input. Calculate the running GCD of circled numbers. |
Harmonic series summation graph. |
Draw bars representing N/1 + N/2 + N/3... showing the sum bounded by $O(\text{MaxNum} \cdot \log(\text{MaxNum})$). |
Massive call stack or arrays generating 2^N subsequences. |
Single boolean array of size MaxNum (O(W) space). |
| 1820 |
Maximum Number of Accepted Invitations (Premium) |
Generate all permutations of boy-girl pairings and count valid invitations. $O(N!)$. |
Factorial explosion of pairing combinations. |
Draw a set of Boys and Girls. Draw every possible tangled web of matching lines, generating millions of invalid graphs. |
Bipartite Graph Maximum Matching (Kuhn's Algorithm / DFS with Backtracking). |
[Image of Bipartite Graph Matching]
Bipartite Graph with Augmenting Paths. |
For each boy, run DFS to find a willing girl. If she is unmatched, pair them. If matched, ask her current partner to recursively find someone else. |
Draw two columns (Boys, Girls). Draw valid invite lines. Trace a path: B1->G1. Then B2->G1 (conflict!). B2 asks B1 to move. B1 moves to G2. Both matched! |
Graph traversal with V * E paths. |
Draw a bipartite graph bounding box, noting $O(V \cdot E)$ where V is vertices and E is edges. |
Memory limits exceeded tracking all permutation states. |
Adjacency list/matrix + a `match` array mapping Girls to Boys. |
| 1821 |
Find Customers With Positive Revenue this Year (SQL) |
Pull all records into application memory, iterate through them, and filter in code. |
Full table scan highlighting. |
Draw a table. Draw an arrow reading every single row. Cross out rows where year != 2021 or revenue <= 0. |
WHERE clause filtering directly in SQL engine. |
Data filtering funnel. |
Database engine evaluates `year = 2021 AND revenue > 0`. Only matching `customer_id`s are passed to the result set. |
Draw a funnel. Top: "All Rows". Middle: "Filter: 2021 & >0". Bottom: "Result IDs". |
$O(N)$ linear scan or $O(\log N)$ index seek. |
Draw an arrow jumping directly to the relevant block via a B-Tree index visualization. |
Pulling all rows into an application-side array (O(N) RAM). |
Streamed result set in Database memory (O(1) extra space). |
| 1822 |
Sign of the Product of an Array |
Multiply all numbers together to get the final product, then check if it's positive, negative, or zero. (Causes integer overflow). |
Accumulator variable exploding in size. |
Write the numbers out. Draw multiplication signs. Draw a giant resulting number that exceeds the 32-bit limit. |
Math (Parity tracking). Count negative numbers and check for zeros. |
Toggle switch (positive/negative). |
Start sign = 1. Read num. If num == 0, return 0. If num < 0, flip sign to -sign. Return sign. |
Draw the array. Write `sign = 1`. Hop to each number. If negative, cross out 1, write -1, and vice versa. |
Single linear pass. |
Draw an arrow traversing the array from index 0 to N-1. Mark $O(N)$. |
Large Number object / BigInt in heap memory. |
Single 32-bit integer register. |
| 1823 |
Find the Winner of the Circular Game |
Simulate with an Array or List. Physically remove the element at `(current + k - 1) % len` repeatedly. |
Circle shrinking with $O(N)$ shifts per deletion. |
Draw a circle of numbers. Count k steps, cross out the number. Redraw the entire circle smaller. Repeat. $O(N^2)$. |
Math (The Josephus Problem) / Bottom-Up DP. |
Recursive mapping of zero-indexed positions. |
Base case: 1 person, winner is index 0. For `i` from 2 to N, new winner = `(old_winner + k) % i`. Return ans + 1 (to 1-index it). |
Write DP states: i=1 -> win=0. i=2 -> win=(0+k)%2. Compute iteratively bottom-up without tracking the actual array. |
Simple $O(N)$ loop iteration. |
Draw a loop going from 1 to N, updating a single variable. Mark $O(N)$ time. |
Dynamic array resizing (shifting elements takes $O(N)$ memory/time). |
$O(1)$ space holding the current winner index variable. |
| 1824 |
Minimum Sideway Jumps |
Recursive DFS/BFS exploring every possible forward move and sideways jump. |
Huge exponential decision tree. |
Draw a frog at pos 0. Branch paths for jumping left, right, or forward. Mark redundant overlapping paths. $O(3^N)$. |
Dynamic Programming (State Machine) / Greedy. |
3xN Grid tracking minimum jumps. |
Keep an array of 3 lanes. For each position, if there's a rock, that lane = infinity. Update other lanes: `dp[lane] = min(dp[lane], min_of_other_lanes + 1)`. |
Draw a 3-row grid. Move column by column. Write min jumps in each cell. If rock, write X. If hopping lanes, add 1 to the minimum of that column. |
$O(N)$ matrix column traversal. |
Draw a box around a single column, showing it shifts right exactly N times. |
$O(N)$ call stack for recursion depth. |
$O(1)$ space: just an array of size 3 for the current column's states. |
| 1825 |
Finding MK Average |
Keep a queue of the last M elements. On calculate, copy to an array, sort it, slice bottom/top K, and average the rest. |
Queue flushing to an $O(M \log M)$ sort operation. |
Draw a queue. Copy it to a list. Sort the list. Cross out first K and last K elements. Average the middle ones. |
Queue + 3 TreeMaps (Multisets for Bottom K, Middle M-2K, Top K) + Running Sum. |
Three balancing BSTs transferring elements. |
Add num: Insert into a TreeMap, rebalance sizes to exactly K, M-2K, K. Update Middle sum. Remove old num (from queue): Delete from TreeMap, rebalance. Calculate: MiddleSum / (M-2K). |
Draw 3 buckets (Bottom, Mid, Top). Put new number in. If Mid gets too big, push max to Top or min to Bottom. Read pre-calculated Mid sum in $O(1)$. |
Logarithmic tree balancing paths. |
Draw insertion/deletion paths of depth log M in the trees. Mark query as $O(1)$. |
$O(M)$ intermediate arrays created and garbage collected on every query. |
Queue of size M + 3 TreeMaps holding exactly M nodes in heap memory. |
| 1826 |
Faulty Sensor (Premium) |
Nested loops to compare all possible sub-arrays of both sensors to find which one dropped a value. |
Sliding window comparison grid. |
Draw two rows. Try sliding the second row right by 1 and check if the remaining elements match the first row. Repeat for the other row. |
Two Pointers / Linear Comparison (Shift checking). |
Pointer alignment tape. |
Find first index i where s1[i]
eq s2[i]. Check if s1[i...n-2] matches s2[i+1...n-1] and vice versa. |
Draw two arrays. Mark the first mismatch. Draw arrows from s1[i] to s2[i+1] to check for a shift. If only one matches, that sensor is faulty. |
Single-pass comparison segments. |
Draw a line of length N. Mark the mismatch point. Show two short $O(N)$ scans from that point forward. |
Multiple sub-array copies (O(N) space). |
Two static arrays (Input) + 2 integer pointers (O(1) extra space). |
| 1827 |
Minimum Operations to Make the Array Increasing |
For each element i, if a[i] \le a[i-1], use a while loop to increment a[i] one by one until a[i] > a[i-1]. |
Stepping-stone bar chart. |
Draw a bar chart. For a low bar following a high bar, draw tiny blocks being added one by one until it's taller. $O(N \\text{times} \\text{text}{\text{max}\_\text{diff}})$. |
Greedy Math (Single Pass). |
Fill-to-level line. |
If current \le prev, calculate needed = prev + 1 - current. Add needed to total and update current = prev + 1. |
Draw the array. For each mismatch, write the math: diff = (prev + 1) - curr. Cross out curr, write the new value, and tally the diff. |
Linear traversal timeline. |
Draw an arrow from left to right. Label it $O(N)$ with a single constant time operation at each step. |
No extra data structures, but highly inefficient time usage. |
Two variables: `total_ops` and `prev_val` (O(1) space). |
| 1828 |
Queries on Number of Points Inside a Circle |
Nested loops: For every circle, iterate through every point and check the distance formula. |
Full cartesian product grid. |
Draw circles and points. Draw a line from every circle center to every single point. Mark $O(Q \cdot P)$ checks. |
Math (Distance Squared Comparison). |
Radial expansion zones. |
For each query (x, y, r), check if (px-x)^2 + (py-y)^2 \le r^2. Avoid `sqrt` to save precision and time. |
Draw a point and a circle. Write the formula d^2 \le r^2. Use a coordinate grid to show which points fall inside the boundary. |
Linear Query \times Linear Points. |
Draw Q boxes, each containing a scan of P points. Annotate as $O(Q \\text{times} P)$. |
Large list of calculated floating-point distances. |
Input points/queries + a simple output integer array. |
| 1829 |
Maximum XOR for Each Query |
For each query, calculate the XOR of the entire current array, then iterate through all k < 2^{maximumBit} to find the max. |
Nested bitwise scan matrix. |
Draw the array. At each step, XOR all elements. Then test every possible k. $O(N^2 + N \\text{times} 2^M)$. |
Prefix XOR + Bitwise Complement. |
Bitwise puzzle pieces (XOR cancellation). |
Maintain a running `totalXor`. The k that maximizes the result is `totalXor` XORed with a bitmask of all 1s (2^m - 1). Remove last element from `totalXor` for next query. |
Write `mask` (e.g., 111). Write `currentXor`. Subtract/XOR them to find k. Move to next number and repeat. |
Single pass cumulative XOR. |
Draw an arrow traversing the array once. Mark each step as $O(1)$ bitwise math. |
Repeatedly creating new arrays for each query. |
Single output array + one `currentXor` integer variable. |
| 1830 |
Minimum Number of Operations to Make String Sorted |
Physically perform the operation (find i, find j, swap, reverse) until the string is sorted. |
Permutation state graph. |
Write the string. Manually find indices, swap, and reverse. Redraw the string. Repeat until sorted. $O(N!)$. |
Combinatorics (Cantor Expansion) + Modular Multiplicative Inverse + Precomputed Factorials. |
Permutation rank tree. |
For each position, count how many characters smaller than s[i] are available. Multiply by (n-1-i)! and divide by duplicates factorials. Sum these up modulo 10^9+7. |
Write the string. Under each char, write "Count of smaller chars on right". Write factorials. Multiply and sum. |
Linear pass with frequency array updates. |
Draw a line of length N. At each point, show an $O(26)$ scan of the frequency array. Total $O(26N)$. |
Massive recursion stack or thousands of string objects. |
Frequency array (size 26) + Precomputed factorial array (size N). |
| 1831 |
Maximum Transaction Each Day (SQL) |
Correlated subquery: For each row, calculate the max amount for its day and check if it matches. |
Nested loop execution tree. |
Draw a table. For every row, draw a loop that scans the entire table again to find the max of that date. Mark $O(N²)$. |
Window Function: RANK() or ALL operator. |
Grouped partitions with rank labels. |
Partition table by Date. Sort by Amount descending. Label rows with rank. Select only those where rank = 1. |
Draw boxes around rows with the same date. Circle the row with the largest number in each box. |
Linear partition scan. |
Draw a table divided into sections. Draw one arrow passing through each section once. Mark $O(N)$. |
Full table copies in nested recursion. |
In-memory partitioned frames for the window function. |
| 1832 |
Check if the Sentence Is Pangram |
Iterate through the alphabet (a-z). For each letter, scan the entire string to see if it exists. |
26-row linear scan matrix. |
Write a-z on the left. For 'a', draw an arrow through the sentence. For 'b', draw another arrow, etc. $O(26 \cdot N)$. |
Hash Set or Boolean Frequency Array. |
Checklist / Bucket filling. |
Traverse the string once. Mark the corresponding index in a boolean array of size 26. Check if the final set size is 26. |
Draw 26 empty squares. Read the sentence. Tick the square for each letter found. See if all squares are ticked. |
Single pass linear timeline. |
Draw an arrow from 0 to N. Mark each step as $O(1)$ array access. Total $O(N)$. |
No extra memory if using alphabet scan (but slow). |
Fixed-size bitset or array of 26 booleans (O(1) space). |
| 1833 |
Maximum Ice Cream Bars |
Backtracking: Try every possible combination of ice cream bars to see which one fits the budget with the most items. |
Exponential combination tree. |
Draw a root. Branch out for every bar (take/not take). Note the $O(2^N)$ complexity. |
Greedy Algorithm + Sorting. |
Ascending staircase fill. |
Sort costs. Buy cheapest first. Subtract from coins until budget is depleted or no more bars left. |
Sort the numbers. Draw a line (coins). Subtract the smallest number. Subtract next smallest. Stop when line is empty. |
$O(N \log N)$ sorting slope. |
Draw a sorting merge-tree (log N levels). Below it, draw a single $O(N)$ pass. |
Call stack depth for recursion (O(N)). |
Sorting overhead (O(log N) or $O(N)$ space depending on sort type). |
| 1834 |
Single-Threaded CPU |
At every time step, scan all available tasks and pick the one with the shortest processing time manually. |
Timeline with nested $O(N)$ search per event. |
Draw a timeline. At t=1, scan all tasks. At t=5, scan again. Mark $O(N²)$ worst case. |
Min-Priority Queue (Min-Heap) sorted by processing time and original index. |
Waiting Room (Heap) and Processing Table. |
Sort tasks by arrival. Add arrived tasks to heap. CPU pops from heap, advances time by processing duration. Repeat. |
Draw a queue for incoming tasks and a Triangle (Heap). Move tasks from queue to heap as time passes. Pop the top task. |
$O(N \log N)$ event-based jumps. |
Draw $O(\log N)$ paths for each heap insertion/deletion along a line of N tasks. |
Unordered list of tasks. |
Heap structure (Array-based binary tree) in memory. |
| 1835 |
Find XOR Sum of All Pairs Bitwise AND |
Nested loops: For every element in arr1 and every element in arr2, calculate (a AND b) and XOR them into a result. |
N x M cross-product grid. |
Draw a grid. Fill every cell with (row AND col). XOR all cells. Mark $O(N \cdot M)$. |
Math (Distributive Law): (a^b) AND (c^d). |
Logic Gate Distributivity. |
XOR all elements in arr1 to get X. XOR all elements in arr2 to get Y. Final answer is X AND Y. |
Write arr1. XOR them to one number. Write arr2. XOR them to one number. Draw an AND gate connecting the two results. |
Parallel linear scans. |
Draw two independent horizontal lines (arr1 and arr2). Mark each as $O(N)$ and $O(M)$. Total $O(N+M)$. |
Large intermediate result matrix. |
Two integer registers for cumulative XORs. |
| 1836 |
Remove Duplicates From an Unsorted Linked List (Premium) |
Nested loops: For each node, scan the rest of the list to see if its value appears again. Delete duplicates. |
Nodes with N \times N link-traversal arrows. |
Draw a linked list. From each node, draw long loops checking every subsequent node. Mark $O(N^2)$. |
Hash Map Count + Sentinel Node. |
Two-pass nodal filtering. |
Pass 1: Count frequencies in a Map. Pass 2: Use a `dummy` node. If `curr.next.val` count > 1, skip it; else move `curr`. |
Draw a list. Above it, draw a Map with counts. Draw a 'Skip' arrow jumping over nodes with count > 1. |
Two separate linear scans. |
Draw two parallel horizontal arrows representing $O(N)$ + $O(N)$. |
Constant space but extreme time overhead (recursive deletion). |
Hash Map buckets storing integer counts (O(N) space). |
| 1837 |
Sum of Digits in Base K |
Convert number to a base-K string, split into characters, and sum them up. |
String conversion pipeline. |
Draw the number. Draw a box converting it to a long string. Sum the digits. Mark space overhead for the string. |
Iterative Modulo and Division. |
Successive stripping scale. |
While n > 0, add n \% k to sum, then n = n / k. |
Write n. Draw a vertical line. Repeatedly divide by k. Circle the remainders and sum them. |
Logarithmic reduction steps. |
Draw a value N shrinking by k each time until it hits 0. Mark $O(\log_k N)$. |
Temporary string buffer in memory. |
Single integer 'sum' register (O(1) space). |
| 1838 |
Frequency of the Most Frequent Element |
For every element i, try using k operations to make other elements equal to nums[i]. Check max count. |
N x N growth matrix. |
Draw an array. Pick one element. Draw arrows showing other elements "growing" to its height. $O(N^2)$. |
Sorting + Sliding Window. |
Growing window on a sorted bar chart. |
Sort. Use window (L, R). Total operations needed = nums[R] \times (R - L + 1) - \text{current\_sum}. If > k, move L. |
Draw bars in increasing order. Draw a rectangle (L, R) with height nums[R]. Empty space in rectangle must be \le k. |
$O(N \log N)$ Sort + Linear Scan. |
Draw a merge-sort tree followed by a single line with two pointers (L, R). |
No extra structure, but repeated sum calculations. |
Sorting overhead + sliding window variables (O(1) or $O(N)$ space). |
| 1839 |
Longest Substring Of All Vowels in Order |
Check every substring to see if it contains all 5 vowels in non-decreasing order. |
Subsegment search matrix (O(N^3)). |
Draw a string. Highlight every possible start and end point. For each, check conditions. Mark as inefficient. |
One-pass Sliding Window / Greedy. |
Staircase vowel tracker. |
Iterate. If s[i] \ge s[i-1], increment length. Count unique vowels. If s[i] < s[i-1], reset. Record length if unique vowels == 5. |
Draw the string. Draw an arrow i moving right. If next char is "equal or greater" in 'aeiou' order, keep going. Mark reset points. |
Single linear pass. |
Draw an arrow from 0 \to N. Mark $O(N)$. |
Storing all substrings in a list. |
Integer variables for `current_len`, `max_len`, and `vowel_count`. |
| 1840 |
Maximum Building Height |
Brute force simulation of every building height while satisfying constraints for all neighbors. |
$O(N \\text{cdot MaxHeight})$ grid filling. |
Draw a grid. Try to fill each building height by checking every restriction. Note $O(N^2)$ or worse. |
Sorting + Two-pass scan (Left-to-Right & Right-to-Left). |
Squeeze-bound visualization. |
Sort restrictions. Pass 1: Bound h[i] by h[i-1] + dist. Pass 2: Bound h[i] by h[i+1] + dist. Max height between two is calculated via (h1 + h2 + dist) / 2. |
Draw points (restrictions). Draw a line from left, then a line from right, "pinching" the heights. Find the highest peak in the gaps. |
$O(M \log M)$ where M is number of restrictions. |
Draw the sort tree, followed by two linear passes over M points. Mark $O(M \log M)$. |
Large DP table for all buildings. |
List of restriction tuples (O(M) space). |
| 1841 |
League Statistics (SQL) |
Multiple nested subqueries and repeated self-joins to calculate home and away stats separately. |
Nested join execution tree. |
Draw a table. Draw two separate loops scanning the matches table (one for home, one for away). Mark $O(N²)$. |
UNION ALL within a CTE + Group By. |
Data merging stream (Vertical Concatenation). |
Treat every match as two separate entries (Home Team entry, Away Team entry). Stack them, then run a single Group By on team_id. |
Draw two tables (Home results, Away results). Draw an arrow merging them into one long list. Circle teams and sum their points. |
Linear set union and scan. |
Draw a single arrow passing through the combined list once. Mark $O(N)$. |
Large temporary tables for separate joins. |
Hashed aggregation buckets in DB memory. |
| 1842 |
Next Palindrome Using Same Digits (Premium) |
Generate all permutations of the digits, check if each is a palindrome, sort them, and pick the next one. |
Factorial permutation tree (O(N!)). |
Draw a tree branching into every possible digit arrangement. Mark it as "Impractical to finish." |
Next Permutation Algorithm on the first half. |
Peak and Valley pointer swap. |
Take the first n/2 digits. Find the rightmost dip i. Find smallest digit larger than s[i] to its right. Swap and reverse suffix. Mirror back. |
Draw the first half of the string. Draw a "dip" in the numbers. Swap two numbers. Draw a "Reverse" arrow for the tail. Mirror it for the second half. |
Single pass index jumps. |
Draw an arrow scanning the half-string twice. Mark $O(N)$. |
Massive list of all string permutations. |
Fixed-size character array (O(N) space). |
| 1843 |
Suspicious Bank Accounts (SQL) |
Self-join the transactions table on account_id and check for matches where month = current_month + 1. |
Cross-product grid of transactions. |
Draw a list of transactions. For every row, draw a line to every other row to find consecutive months. $O(N²)$. |
Window Function (LEAD/LAG) or PERIOD_DIFF. |
Row-shifting frames. |
Group by account and month. Use `LEAD` to compare the current month's total income with the next month's total income. Filter where both exceed limit. |
Draw a table. Draw an arrow from one row to the next. Write "Suspicious" if both rows have income > limit and are 1 month apart. |
Single pass partition scan. |
Draw a single arrow sliding down the rows within each account partition. Mark $O(N)$. |
N x N result set in disk/memory. |
In-memory partitioned window frames. |
| 1844 |
Replace All Digits with Characters |
Create a new string. For every character, if it's a digit, calculate the shift and append to the new string. |
String builder accumulation. |
Draw the original string. Draw an arrow pointing to a new empty string filling up step-by-step. |
In-place modification of Character Array. |
Tape mutation. |
Iterate through odd indices. Replace `s[i]` with `(char)(s[i-1] + s[i] - '0')`. |
Draw the string as a tape. At index 1, 3, 5... draw an "X" and write the new calculated character directly over it. |
Linear one-pass traversal. |
Draw an arrow moving from left to right across the string. Mark $O(N)$. |
Two string copies in memory (input and output). |
$O(1)$ extra space (if modified in-place) or $O(N)$ for the character array. |
| 1845 |
Seat Reservation Manager |
Use a boolean array. `reserve()` scans for the first `false`. `unreserve()` sets the index to `false`. |
Linear scan timeline per request. |
Draw an array of boxes. For every reservation, draw an arrow starting from index 0 until it finds a blank box. $O(N² \text{total})$. |
Min-Priority Queue (Min-Heap). |
Triangle/Pyramid of available seats. |
`reserve()`: Pop the min from the heap. `unreserve()`: Push the seat back into the heap. |
Draw a Triangle (Heap) with small numbers at the top. Pop the top number for a reservation. Write a seat number and "toss" it back into the triangle for unreservation. |
Logarithmic tree path height. |
Draw a binary tree. Mark a path from root to leaf as $O(\log N)$. |
Boolean array of size N. |
Heap structure (Array-based binary tree) in memory holding up to N integers. |
| 1846 |
Maximum Element After Decreasing and Rearranging |
Generate all permutations of the array and for each, try to satisfy the condition by decrementing. |
Factorial Permutation Tree. |
Draw a root node branching into N! paths. Note that it's impossible to compute for large N. |
Sorting + Greedy Pass (or Counting Sort for $O(N)$). |
Staircase alignment. |
Sort the array. Set arr[0] = 1. For i=1 \dots n-1, set arr[i] = \min(arr[i], arr[i-1] + 1). Return arr[n-1]. |
Draw a set of bars of different heights. Sort them. Draw a diagonal line starting at height 1. Cap each bar to be at most 1 unit taller than the previous. |
$O(N \log N)$ Sort or $O(N)$ Count line. |
Draw a merge-sort tree or a single $O(N)$ pass line. |
Massive recursion stack for permutations. |
$O(1)$ extra space if sorting in-place; $O(N)$ for Counting Sort frequency array. |
| 1847 |
Closest Room (Premium) |
For every query, iterate through all rooms, filter by size, and find the one with the minimum |preferred - roomID|. |
Query \times Room search matrix. |
Draw Q rows and R columns. For each row, scan every column. Mark $O(Q \\text{times} R)$. |
Offline Queries + Sorting + Balanced BST (TreeSet). |
Sweep-line with a dynamic search set. |
Sort queries and rooms by size (descending). Iterate queries; add rooms that meet size requirement to a TreeSet. Use `ceiling` and `floor` to find closest ID. |
Draw a "Size" timeline. Move from right (large) to left (small). As you pass a room, put its ID in a "Search Box" (BST). Use the box to find the closest number. |
$O(R \log R + Q \log Q)$. |
Draw two sorting trees and a loop with $O(\log R)$ tree operations. |
$O(1)$ extra besides input/output. |
TreeSet (Red-Black Tree) nodes in heap memory. |
| 1848 |
Minimum Distance to the Target Element |
Linear scan through the entire array to find all indices where nums[i] == target, then calculate min distance. |
Full array linear scan. |
Draw an array. Draw an arrow from 0 \dots N-1. Mark $O(N)$. |
Two-way expansion from 'start' index. |
Concentric search rings. |
Check `start`, then `start-1` and `start+1`, then `start-2` and `start+2`. Stop as soon as target is found. |
Draw an array with a pointer at `start`. Draw arrows pointing outwards in both directions simultaneously. Stop at the first target. |
Linear bounded scan. |
Draw an arrow starting at `start` and ending at index i. Mark $O(N)$ worst case, but $O(1)$ best case. |
List to store all matching indices. |
$O(1)$ stack variables. |
| 1849 |
Splitting a String Into Descending Consecutive Values |
Generate all possible splits of the string and check if they form a descending sequence. |
Exponential partition tree. |
Draw a string "123". Branch into ["1","23"], ["12","3"], ["1","2","3"]. Note $O(2^N)$ splits. |
Backtracking with Value Pruning. |
Decision Tree with early exit. |
Try first substring as `prev`. Recursively find `next` such that `next == prev - 1`. If we reach the end of the string, return true. |
Draw a tree. At each node, write the current number. Only draw branches where the next number is exactly 1 less than the current. |
Depth-limited search. |
Draw a tree where each branch is strictly constrained. Note that the number of valid paths is very small. |
Massive list of all split combinations. |
Recursive call stack of depth $O(N)$. |
| 1850 |
Minimum Adjacent Swaps to Reach the Kth Smallest Number |
Find the k-th permutation, then use a standard swap-counting algorithm (like inversion count). |
Permutation generation + swap tracking. |
Draw the string. Show k steps of finding the next permutation. Then show a bubble-sort style swap count. $O(k \cdot N + N^2)$. |
Next Permutation (K times) + Greedy Swap Alignment. |
Index mapping and element displacement. |
Run `next_permutation` k times to get target string. Then, for each character in original, find its position in target and "bubble" it to its correct index, counting swaps. |
Draw the original string and the target string. Pick the first char of original. Find where it is in target. Draw "hops" (swaps) to move it there. Tally hops. |
$O(k \cdot N + N^2)$. |
Draw k horizontal lines (permutations) and then an $O(N^2)$ swap grid. |
Staging all k permutations in memory. |
Two character arrays (Original and Target). |
| 1851 |
Minimum Interval to Include Each Query |
For each query q, iterate through all intervals [l, r], check if l \le q \le r, and track the minimum (r - l + 1). |
Query \times Interval matrix. |
Draw Q vertical query lines and I horizontal interval bars. For each vertical line, check every horizontal bar it intersects. Mark $O(Q \\text{times} I)$. |
Offline Queries + Sorting + Min-Priority Queue (Heap). |
Sweep-line with a size-ordered Heap. |
Sort queries and intervals. Move a sweep-line across. Add intervals starting before query to a Min-Heap (ordered by size). Pop intervals ending before query. Top of heap is the answer. |
Draw a timeline. Plot queries as dots and intervals as segments. As you move left-to-right, "pick up" intervals into a triangle (Heap) and "drop" them when they expire. |
$O(I \log I + Q \log Q)$. |
Draw two sorting trees and a series of $O(\log I)$ heap operations along a single timeline. |
$O(1)$ extra besides input/output. |
Min-Heap array structure and a sorted query-index mapping array. |
| 1852 |
Distinct Numbers in Each Subarray (Premium) |
For every possible window of size k, create a new Hash Set and count its elements. |
Sliding window "Flashlight" view. |
Draw an array. Draw a box of size k. Move it one by one. For each position, list all unique numbers inside. Mark $O(N \\text{times} k)$. |
Sliding Window + Frequency Array/Map. |
Sliding frame with a tally board. |
Initialize window of size k. Move window: add `new_item` to map (increment count), remove `old_item` (decrement count). If count becomes 0, remove key. Map size is the answer. |
Draw the array and a tally table below. As the window moves, update tally marks. Count the number of rows in the table with non-zero marks. |
Single linear pass. |
Draw an arrow from 0 \dots N. Mark each step as $O(1)$ hash map update. Total $O(N)$. |
Multiple Hash Sets (one per window) causing GC pressure. |
A single Frequency Array (size MaxVal) or a Hash Map in heap memory. |
| 1853 |
Convert Date Format (SQL) |
Fetch all dates into a programming language (like Python), parse them, and reformat manually. |
Table-to-Script data flow. |
Draw a database table. Draw an arrow to a code block. Inside the block, show string manipulation logic for every row. |
SQL DATE_FORMAT() function. |
Transformation pipe. |
The database engine applies a mask (e.g., `%W, %M %e, %Y`) to each date field internally. |
Draw a raw date '2021-07-01'. Draw it passing through a "Lens" labeled `%W`. The output is 'Thursday'. |
Linear table scan. |
Draw an arrow passing through the column. Mark as $O(N)$. |
Large array of date strings in application RAM. |
Zero extra application memory; processed in DB stream. |
| 1854 |
Maximum Population Year |
For each person, iterate through every year from `birth` to `death - 1` and increment a counter in a year-indexed array. |
N \times Year increment grid. |
Draw a grid where rows are people and columns are years. For each person, shade their living years. Sum the shaded cells in each column. $O(N \\text{times} 100)$. |
Difference Array / Prefix Sum (Line Sweep). |
Step-function accumulation. |
At `birth`, add +1. At `death`, add -1. Then, calculate prefix sum of years. The year with the maximum sum is the result. |
Draw a number line for years. For each person, draw a '+' at birth and a '-' at death. Walk the line, keeping a running total. |
Two linear passes (Logs then Years). |
Draw two arrows: one for $O(N)$ log updates, one for $O(100)$ year scan. Total $O(N)$. |
$O(1)$ extra if years are fixed range, but inefficient updates. |
A single array of size 101 (years 1950 to 2050). |
| 1855 |
Maximum Distance Between a Pair of Values |
Nested loops: For every i in `nums1`, check every j \ge i in `nums2` and find max j-i where `nums1[i] <= nums2[j]`. |
Upper-triangular comparison matrix. |
Draw two arrays. Draw lines from every i to every valid j. Note the $O(N \\text{times} M)$ density. |
Two Pointers (Greedy). |
Two-lane parallel pointers. |
Initialize i=0, j=0. While i < n and j < m: if `nums1[i] <= nums2[j]`, update max distance and move j; else move i. |
Draw two tapes. Place finger i on top and finger j on bottom. If bottom is \ge top, slide j right. Else, slide i right. Track the max gap. |
Single linear pass over both arrays. |
Draw two arrows moving only forward. Mark as $O(N + M)$. |
$O(1)$ extra space. |
$O(1)$ stack variables (pointers i, j, res). |
| 1856 |
Maximum Subarray Min-Product |
Iterate through every possible subarray (i, j), find the minimum element in that range, and multiply it by the subarray sum. |
N x N Subarray search matrix. |
Draw an array. Draw nested loops covering all segments. For each segment, draw a scan to find the min. Mark $O(N^3)$. |
Prefix Sum + Monotonic Stack (Next Smaller Element). |
Building boundaries with a Stack. |
For each element, find the nearest smaller element to the left and right using a stack. These form the boundaries. Use prefix sums to get the sum in $O(1)$. |
Draw a bar chart. For each bar, draw horizontal dashed lines until you hit a shorter bar. Calculate area = (bar height) * (sum of bars between dashed lines). |
Three independent linear scans. |
Draw three parallel arrows representing $O(N)$ for prefix sums, $O(N)$ for left bounds, and $O(N)$ for right bounds. |
$O(1)$ extra space (ignoring recursive calls). |
Prefix Sum array and an Array-based Stack (LIFO) in heap memory. |
| 1857 |
Largest Color Value in a Directed Graph |
Use DFS to find every possible path in the graph. For each path, count the occurrences of each color. |
Exponential Path Tree. |
Draw a graph with many cycles or paths. Show how DFS explores all permutations. Note $O(V \cdot 2^E)$ potential paths. |
Topological Sort (Kahn's) + Dynamic Programming. |
Node processing queue with color propagation. |
Calculate in-degrees. Use a Queue for 0 in-degree nodes. For each node, update its neighbors' color counts: dp[neighbor][color] = \max(dp[neighbor][color], dp[node][color]). |
Draw nodes with colors. Next to each node, draw a 26-slot table. As you process a node, pass its table values to neighbors, adding 1 for the neighbor's color. |
Linear Graph Traversal (V+E) with constant color factor. |
Draw an arrow passing through each edge once. Mark $O(26 \\text{times} (V+E)$). |
Recursion stack leading to TLE or StackOverflow. |
2D DP Array (V \times 26) in heap memory + Adjacency List. |
| 1858 |
Longest Word With All Prefixes (Premium) |
Sort words by length. For each word, manually check if every prefix exists in the original list using a Set. |
Nested loop string comparison. |
List words. For each, draw arrows checking every prefix length against the whole list. Mark $O(N \cdot L^2)$. |
Trie (Prefix Tree) + DFS. |
Path validation in a tree. |
Insert all words into a Trie. DFS through the Trie, only descending into nodes that are marked as "end of word". Track the deepest node. |
Draw a tree where each node is a letter. Circle nodes that finish a word. Trace only paths where every circle is solid from the root. |
Linear Trie traversal. |
Draw an arrow following the paths of the Trie. Mark $O(\\text{text}{\text{Total characters in input}})$. |
Hash Set containing N large strings. |
Recursive tree nodes with 26-sized pointer arrays. |
| 1859 |
Sorting the Sentence |
Split the sentence. Use a standard sorting algorithm with a custom comparator that extracts the trailing digit. |
Sorting algorithm comparison tree. |
Draw words. Use arrows to show a sort (like Bubble or Merge sort) based on the number at the end. $O(N \log N)$. |
String Split + Bucket Array mapping. |
Direct Index Placement. |
Split sentence by spaces. For each word, use the last char as an index. Place the word (minus the digit) into `result[index-1]`. Join result. |
Draw the sentence and an empty array with slots 1-9. Pick a word, look at its number, and "drop" it into the corresponding slot. |
Single linear pass over the words. |
Draw an arrow from left to right. Mark $O(N)$ where N is length of sentence. |
Temporary arrays for the sort. |
Fixed-size array (size 9) containing string references. |
| 1860 |
Incremental Memory Leak |
Simulate second-by-second memory allocation until both memory sticks cannot satisfy the current requirement. |
Linear timeline simulation. |
Draw two bars (Memory1, Memory2). Every second, subtract i. Show the subtraction until numbers go negative. |
Standard Simulation (Loop) or Math (Square root approach). |
Draining buckets. |
Use a while loop. At time t, if `m1 >= m2`, subtract t from `m1`; else subtract t from `m2`. Stop when t > \max(m1, m2). |
Write M1 and M2. For t=1, 2, 3 \dots, perform subtraction on the larger number. Stop when current t is bigger than both remaining values. |
Square root time complexity. |
Note that the sum 1+2+ \dots + t \approx t^2/2. Thus t \approx \sqrt{2M}. Mark $O(\\text{sqrt}{M1+M2})$. |
$O(1)$ stack variables. |
$O(1)$ stack variables (three integers: t, m1, m2). |
| 1861 |
Rotating the Box |
Rotate the matrix first, then for each column, repeatedly swap stones down until they hit an obstacle or the bottom. |
Step-by-step frame animation of falling stones. |
Draw the rotated grid. For every stone '#', draw an arrow moving it down one cell at a time. $O(R \cdot C \cdot R)$. |
Two Pointers (Gravity logic) + Standard Matrix Rotation. |
Sliding "Empty Slot" pointer. |
In each row (pre-rotation), iterate from right to left. Keep a pointer `empty` at the rightmost free space. If stone found, move it to `empty` and decrement `empty`. If obstacle found, reset `empty` to obstacle-1. |
Draw a row. Place a finger at the end (empty slot). Move another finger left. When it hits a '#', move the '#' to your first finger's spot. Rotate the paper 90°. |
Two independent linear passes (Gravity then Rotate). |
Draw one arrow for the row scan and one arrow for the index mapping. Mark $O(R \\text{times} C)$. |
Intermediate matrix copies for each "step" of gravity. |
In-place modification of the original row (O(1) extra) + final rotated matrix (O(R*C)). |
| 1862 |
Sum of Floored Pairs |
Nested loops: For every pair (i, j), calculate floor(nums[i] / nums[j]) and sum them up. |
N \times N division matrix. |
Draw an array. Draw lines connecting every element to every other element. Note the $O(N^2)$ density. |
Frequency Array + Prefix Sums + Math (Harmonic Series block processing). |
Range-sum frequency blocks. |
Count frequencies. Calculate prefix sums. For each unique number x, find how many numbers fall in ranges [x, 2x-1], [2x, 3x-1], etc., using prefix sums. Add (range\_count \times floor\_val) to total. |
Draw a frequency number line. Pick a number x=3. Draw brackets around [3-5], [6-8], [9-11]. Use prefix sums to quickly count dots in each bracket. |
Harmonic Series Summation $O(M \log M)$ where M is MaxValue. |
Draw the summation N/1 + N/2 + N/3... and mark the area under the 1/x curve as $O(\log N)$. |
$O(1)$ stack space, but massive time overhead. |
Frequency array and Prefix Sum array of size MaxValue. |
| 1863 |
Sum of All Subset XOR Totals |
Generate all 2^N subsets, calculate the XOR of each, and sum the results. |
Exponential Binary Tree. |
Draw a root. Branch left (include) and right (exclude) for every element. Mark all 2^N leaves. |
Backtracking/Recursion or Bit Manipulation (Math: result is OR(all\_elements) \times 2^{n-1}). |
Decision Tree of XOR states. |
Recursive function: `dfs(index, currentXor)`. Add `currentXor` to total. Recurse with `index+1` for both including and excluding `nums[index]`. |
Draw a tree. At each node, write the running XOR. Branch into "With element" and "Without element". Sum the leaf values. |
$O(2^N)$ for recursion or $O(N)$ for the bitwise math trick. |
Draw a single arrow for the $O(N)$ math approach. Mark it as significantly faster than the $O(2^N)$ tree. |
Storing all subsets in a list of lists (O(N \cdot 2^N)). |
$O(1)$ extra space for math; $O(N)$ depth for recursion stack. |
| 1864 |
Minimum Number of Swaps to Make the Binary String Alternate |
Generate all permutations of the binary string, check which are "alternating", and find the minimum swaps using inversion count. |
Permutation forest. |
Draw a string. List all possible ways to rearrange 0s and 1s. Mark $O(N!)$. |
Greedy Counting (Compare with two possible targets: "0101..." and "1010..."). |
Pattern matching masks. |
Count total 0s and 1s. If diff > 1, impossible. Else, count mismatches against "0101..." and "1010...". The min swaps is `mismatches / 2` for a valid target. |
Write the input string. Below it, write "0101...". Circle the spots where they don't match. Repeat for "1010...". Count circles. |
Single linear pass. |
Draw an arrow from 0 \dots N. Mark as $O(N)$. |
Massive list of permutations. |
$O(1)$ stack variables (counts for 0s, 1s, and mismatches). |
| 1865 |
Finding Pairs With a Certain Sum |
In `count()`, use nested loops to check every pair from `nums1` and `nums2` that sums to `tot`. |
N x M cross-product query matrix. |
Draw two arrays. Draw lines from every element in A to every element in B. Mark $O(N \\text{times} M)$ per query. |
Hash Map Frequency Tracking. |
Value-to-Frequency Lookup. |
Store `nums2` frequencies in a Map. `add(index, val)`: Update `nums2` and the Map. `count(tot)`: Iterate `nums1`, for each x, add `Map.getOrDefault(tot - x, 0)` to the result. |
Draw `nums1`. Next to it, draw a Map (frequency table) for `nums2`. For each number in `nums1`, calculate `tot - num`, and look it up in the table. |
$O(N)$ for `count` and $O(1)$ for `add`. |
Draw an arrow through `nums1` (O(N)) pointing to a single Map access (O(1)). |
No extra memory besides original arrays. |
Hash Map containing up to M unique values from `nums2`. |
| 1866 |
Number of Ways to Rearrange Sticks With K Sticks Visible |
Generate all n! permutations. For each, count visible sticks by scanning from left to right. |
Factorial Permutation Tree. |
Draw a root node branching into N children, then N-1, etc. Label the leaves with "Count Visible". Mark $O(N \cdot N!)$. |
Dynamic Programming (Stirling Numbers of the First Kind). |
State Transition Grid (N \times K). |
dp[i][j] is ways to arrange i sticks with j visible. If tallest is last, dp[i-1][j-1]. If tallest is not last, (i-1) \times dp[i-1][j]. |
Draw an N \times K table. Fill cells using the formula. Draw two arrows pointing to dp[i][j] from its two dependency states in the previous row. |
Rectangle Area calculation. |
Draw an N \times K rectangle. Shade the whole area to show all N \cdot K states are visited. Mark $O(\text{NK})$. |
Recursion stack of depth N plus N! result storage. |
2D array of size N \times K (or 1D array for space-optimized DP). |
| 1867 |
Orders With Maximum Quantity Above Average (SQL) |
Use subqueries to calculate the average of max quantities for all orders, then filter original table. |
Multi-stage data scan. |
Draw a table. Draw an arrow scanning for averages, then another arrow scanning to filter based on that global value. $O(N^2)$. |
Window Functions or Common Table Expressions (CTEs) with MAX() and AVG(). |
Data Filtering Pipeline. |
Group by `order_id`. Calculate `MAX(quantity)` for each. Find the `MAX` of those `AVG(quantity)` across the whole result set and filter. |
Draw a table grouped by ID. Draw a funnel that calculates a single global threshold, then discards rows below it. |
Linear record processing. |
Draw a single vertical arrow through the data. Mark $O(N)$. |
Large temporary tables on disk. |
Hash-based aggregation in RAM. |
| 1868 |
Product of Two Run-Length Encoded Arrays (Premium) |
Expand both RLE arrays into full arrays, multiply index by index, then compress the result back to RLE. |
Expanded Tape Expansion. |
Draw two short compressed arrays. Draw long "unrolled" versions below them. Draw multiplication lines between every index. $O(\text{Expanded Length})$. |
Two Pointers on compressed segments. |
Sliding segment overlaps. |
Move p1 and p2 on encoded arrays. Multiply values. Take the min frequency f = \min(f1, f2). Append [val1 \cdot val2, f] to result. Subtract f from both pointers. |
Draw two bars of different lengths. Align them. Draw a vertical line at the shorter bar's end. Multiply the overlapping part. Slide to the next boundary. |
Linear walk of segment boundaries. |
Draw two parallel lines with arrows jumping from one segment boundary to the next. Mark $O(N+M)$. |
Massive uncompressed arrays (potential Memory Limit Exceeded). |
A single list of compressed [val, freq] pairs (O(N+M) space). |
| 1869 |
Longer Contiguous Segments of Ones than Zeros |
Generate all possible substrings, check if they are contiguous, and track the max length for '1's and '0's. |
Substring Matrix (O(N^2)). |
Draw a grid representing start and end indices of substrings. Mark valid contiguous ones. Note $O(N^2)$. |
Single Pass Counter (Greedy). |
Running tally line. |
Iterate through string. If s[i] == s[i-1], increment current count. Else, update max for that character and reset current count to 1. |
Draw the string. Write `ones=0, zeros=0` below. As you move right, increment the tally for the current char. When the char changes, "box" the max and reset. |
Linear timeline. |
Draw an arrow from left to right. Mark $O(N)$. |
List of all substring strings. |
Four integer variables (curr0, max0, curr1, max1). |
| 1870 |
Minimum Speed to Arrive on Time |
Linear Search: Try speed = 1, then 2, then 3... up to 10^7 until the total time is \le hour. |
Linear Search brute force line. |
Draw a line from 1 to 10^7. Draw an arrow stepping through every single integer. Mark $O(N \cdot 10^7)$. |
Binary Search on Answer. |
Range Halving search. |
Set `low=1, high=1e7`. Calculate `time(mid)`. If `time <= hour`, `high=mid` (possible answer); else `low=mid+1`. |
Draw a line 1 to 10^7. Mark `mid`. Calculate time. Draw a big "X" through the half that is now impossible. Repeat. |
Logarithmic search depth. |
Draw a binary tree of height \log_2(10^7) \approx 24. Each node takes $O(N)$ time. Mark $O(N \log M)$. |
$O(1)$ stack space. |
$O(1)$ stack space for search boundaries. |
| 1871 |
Jump Game VII |
Recursive DFS: From index i, check every j \in [i + minJump, i + maxJump]. If s[j] == '0', recurse. |
Exponential Branching Tree. |
Draw a root node. Branch into multiple paths for every possible jump. Note overlapping subproblems and $O(2^N)$ depth. |
Dynamic Programming + Sliding Window (Prefix Sum of Reachable Nodes). |
Sliding "Jump Zone" window. |
Maintain `reachable_count`. For current i, if s[i] == '0' and `reachable_count > 0` in its valid jump source range, mark i as reachable. |
Draw the string. Below it, draw a window that slides. If the window contains at least one 'True', and the current character is '0', mark current as 'True'. |
Single Pass Linear Scan. |
Draw an arrow from 0 \to N. Mark $O(N)$ with a sliding window moving in parallel. |
Deep Recursion Stack (O(N) depth). |
Boolean DP array of size N (can be optimized with a queue). |
| 1872 |
Stone Game VIII |
Standard Minimax recursion: Alice tries to maximize score, Bob tries to minimize, exploring all possible stone pick counts. |
Game State Decision Tree. |
Draw a tree with Alice/Bob levels. Each node has N-1 branches. Mark $O(N!)$ or $O(2^N)$. |
Prefix Sum + Dynamic Programming (Suffix Max). |
Backward accumulation tape. |
Calculate prefix sums. Alice's best score at index i is \max(dp[i+1], prefixSum[i] - dp[i+1]). Work backward from N-1 to 1. |
Write prefix sums. Start from the right. At each step, compare current sum minus previous best. Keep the maximum as you move left. |
Single Reverse Linear Pass. |
Draw an arrow from N-1 back to 1. Mark as $O(N)$. |
Massive recursion stack and state-memoization map. |
$O(1)$ extra space (if using a single variable to track the running suffix max). |
| 1873 |
Calculate Special Bonus (SQL) |
Pull all records into Python/Java. Iterate rows, use `if/else` for naming/ID conditions, and sort the list. |
Application-side data processing flow. |
Draw a database table and an arrow to a code loop. Inside the loop, draw branches for `id % 2 != 0` and `name not like 'M%'`. |
`CASE` statement or `IF` function + `MOD()` + `LIKE`. |
Conditional Field Mapping. |
The SQL engine evaluates `id % 2 != 0 AND name NOT LIKE 'M%'` for each row. If true, `bonus = salary`; else `0`. Sort by `employee_id`. |
Draw the input table. For each row, check the two conditions. Write the bonus in a new column. Cross-reference with the original salary. |
$O(N \log N)$ for Sorting (or $O(N)$ scan). |
Draw a vertical arrow through the table. Mark as $O(N)$. |
Full result set storage in application RAM. |
Negligible (processed in SQL engine stream). |
| 1874 |
Minimize Product Sum of Two Arrays (Premium) |
Generate all N! permutations of one array and multiply by the other array index-by-index. |
Factorial Combination Grid. |
Draw a root node branching into N! leaves. Calculate sum for each leaf. Mark $O(N!)$. |
Greedy Algorithm (Rearrangement Inequality): Sort one ascending, one descending. |
Opposing Sorting Scales. |
Sort `nums1` [1, 2, 3]. Sort `nums2` [5, 4, 1]. Multiply smallest by largest: (1 \cdot 5) + (2 \cdot 4) + (3 \cdot 1). |
Draw two arrays. Sort them. Draw arrows connecting the smallest of A to largest of B, second smallest to second largest, etc. |
$O(N \log N)$ Sorting. |
Draw two Merge Sort trees. Mark $O(N \log N)$. |
Large list of all possible sums. |
$O(1)$ extra space (if sorted in-place) or $O(N)$ for copies. |
| 1875 |
Group Employees of the Same Salary (Premium) |
Self-join the table on `salary` and filter rows where `count(salary) > 1`, then manually assign IDs. |
N \times N Join Interaction. |
Draw a table. Draw lines connecting every employee to every other employee with the same salary. Mark $O(N^2)$. |
CTE with `COUNT(*) OVER(PARTITION BY salary)` + `DENSE_RANK()`. |
Ranked frequency buckets. |
1. Partition by salary and count. 2. Filter where count > 1. 3. Use `DENSE_RANK()` on the salary to create the `team_id`. |
Group employees by salary. Cross out lone employees. Give the first group "Team 1", second group "Team 2", etc. |
$O(N \log N)$ for Partitioning/Ranking. |
Draw a table divided into blocks. Draw an arrow sorting/ranking the blocks. Mark $O(N \log N)$. |
Massive N^2 temporary join tables. |
Hashed partitioning in database memory. |
| 1876 |
Substrings of Size Three with Distinct Characters |
Iterate through every substring of length 3 and use a Set to check if size is 3. |
Nested loop scan blocks. |
Draw a string. Draw brackets for [0,2], [1,3], [2,4]... list characters in each and circle the ones with no repeats. $O(3N)$. |
Fixed Sliding Window (No Set). |
3-digit sliding frame. |
Check s[i] != s[i+1] and s[i] != s[i+2] and s[i+1] != s[i+2]. Return count of true. |
Draw the string. Place a 3-slot window. Move it right one char at a time, checking the internal 3-way inequality. |
Single linear pass. |
Draw an arrow from 0 \to N. Mark $O(N)$. |
Multiple temporary Sets/Hash structures in heap memory. |
$O(1)$ stack memory (just the input string and a counter). |
| 1877 |
Minimize Maximum Pair Sum in Array |
Generate all possible ways to pair up N elements and find the maximum sum for each set. |
Factorial Pairing Tree. |
Draw 4 nodes. Draw all pairing combinations. Show how complexity explodes for N=100,000. $O(N!)$. |
Greedy Strategy + Sorting. |
Opposing Sorting Pointers. |
Sort the array. Pair smallest with largest, second smallest with second largest. The max of these sums is the answer. |
Draw two parallel sorted lists (or one sorted array). Draw arrows connecting the head to the tail, moving inwards. Write sums next to arrows. |
$O(N \log N)$ Sorting. |
Draw a Merge Sort tree diagram. Mark as $O(N \log N)$. |
Massive list of all possible set combinations. |
$O(1)$ extra space if sorted in-place. |
| 1878 |
Get Biggest Three Rhombus Sums in a Grid |
For every cell (i, j) and every possible side length, calculate the sum of the four boundaries manually. |
Triple nested loop (Row x Col x SideLength). |
Draw a grid. Pick a center. Draw a diamond. Show the addition of every cell on the diamond edge. $O(R\cdot C\\text{cdot min}(R,C)$). |
2D Diagonal Prefix Sums (Prefix Sum on two diagonal directions). |
Diagonal accumulation matrix. |
Precompute `diag1[i][j]` and `diag2[i][j]`. The sum of a diamond side is now $O(1)$ using subtraction. Check only unique sums for the top 3. |
Draw the grid. Draw two extra grids for "Top-Left to Bottom-Right" and "Top-Right to Bottom-Left" running sums. Outline a diamond and calculate its sum using the four corner points. |
$O(R \cdot C)$ Precomputation + $O(R \cdot C \\text{cdot min}(R,C)$) checking (but with $O(1)$ interior). |
Draw a rectangle area (R*C) and label the constant-time diamond lookup inside. |
None (besides input). |
Two auxiliary 2D arrays of size R x C to store prefix sums. |
| 1879 |
Minimum XOR Sum of Two Arrays |
Generate all permutations of `nums2` and calculate XOR sum with `nums1`. |
Factorial Permutation Forest. |
Draw a root node branching into N paths. Note $O(N!)$. |
Dynamic Programming + Bitmasking. |
State Transition DAG (Directed Acyclic Graph). |
`dp[mask]` represents the min XOR sum using elements of `nums1` indicated by bits in `mask`. For the next number, try XORing with all available elements in `nums2`. |
Draw a vertical column for "Index in nums1". Draw a set of bits (0110). Show arrows representing choosing the next element and updating the mask. |
$O(N \cdot 2^N)$. |
Draw a grid where one axis is N and the other is 2^N. Mark the total cells as the complexity. |
Storage of all permutations. |
DP array of size 2^N (Max 2^{14} = 16384 entries). |
| 1880 |
Check if Word Equals Summation of Two Words |
Convert each word to a string of digits, parse to a Long, and then check the sum. |
String concatenation pipeline. |
Draw words 'abc'. Convert to '012'. Then to number 12. Repeat for all words. Mark space for strings. |
Direct Math (Positional Notation). |
Polynomial expansion sum. |
Iterate through characters. num = num \cdot 10 + (char - 'a'). Compare (word1Num + word2Num) == targetNum. |
Draw each word as a sequence. Under it, draw the running calculation: 0 \cdot 10 + 0 \dots 0 \cdot 10 + 1 \dots 1 \cdot 10 + 2. |
Three linear passes (one per word). |
Draw three separate arrows for $O(L1)$, $O(L2)$, $O(L3)$. Mark total as $O(N)$. |
Intermediate string objects for digit conversion. |
$O(1)$ extra space using three integer variables. |
| 1881 |
Maximum Value after Insertion |
Try inserting the digit x at every possible index (0 \dots N) and store all resulting strings in a list. Find the maximum. |
Permutation generation tree. |
Draw the number. Draw arrows to N+1 different circles, each representing a new string. Mark as $O(N^2)$ due to string copying. |
Greedy (First Mismatch). |
Pointer comparison tape. |
If positive, find first digit < x. If negative, find first digit > x. Insert x at that position. |
Draw the digits on a line. Move an arrow. At the first digit that fails the "greater/smaller" check, draw a caret (^) and write x. |
Single linear pass. |
Draw a single arrow moving from 0 \to N. Mark $O(N)$. |
$O(N^2)$ space to store all temporary string results. |
Single StringBuilder or character array (O(N) space). |
| 1882 |
Process Tasks Using Servers |
For every second, iterate through all servers to find the best available one and update busy servers' timers. |
Timeline with nested $O(S)$ server scan. |
Draw a timeline. At each t, draw a loop scanning a box of S servers. Mark $O(T \\text{times} S)$. |
Two Priority Queues (Available Heap, Busy Heap). |
Dual-Heap state transfer. |
1. Move servers from Busy to Available if `time >= finishTime`. 2. Pick top of Available. 3. Push to Busy with updated `finishTime`. |
Draw two triangles. Label one "Free" (sorted by weight/ID) and one "Busy" (sorted by time). Draw arrows showing servers "jumping" between triangles as time moves. |
$O((T + S)$ \log S). |
Draw $O(\log S)$ paths for heap operations along a timeline of T tasks. |
List/Array of all server states refreshed every second. |
Two array-backed binary heaps in memory. |
| 1883 |
Minimum Skips to Arrive at Meeting on Time |
Recursion with backtracking: At each road, decide to skip the rest period or not. Check all 2^N paths. |
Exponential Decision Tree. |
Draw a root. Branch "Skip" and "No Skip" for every road. Note the $O(2^N)$ leaf nodes. |
Dynamic Programming (State: [roads][skips]). |
DP Grid with ceiling math. |
dp[i][j] is min time for first i roads with j skips. Use long/epsilon to handle floating-point precision when calculating `ceil(time/speed)`. |
Draw a grid. Rows = roads, Cols = skips. In each cell, write the min time. Draw arrows from dp[i-1][j] (no skip) and dp[i-1][j-1] (skip). |
$O(N^2)$ state traversal. |
Draw a square grid of size N \times N. Shade it to show all states are calculated. Mark $O(N^2)$. |
Deep recursion stack. |
2D DP table (can be 1D space optimized). |
| 1884 |
Egg Drop With 2 Eggs and N Floors |
Try dropping an egg from every floor i. If it breaks, linearly test 1 \dots i-1. If not, recurse on i+1 \dots N. |
Minimax recursion tree. |
Draw a root floor. Branch into "Breaks" and "Safe". For each, list the next floors to test. |
Math (Triangular Numbers) or DP. |
Staircase reduction. |
With x moves, you can cover x + (x-1) + \dots + 1 = \frac{x(x+1)}{2} floors. Find smallest x such that \text{sum} \ge N. |
Draw a staircase. The first step is x floors high, next is x-1, etc. Total height is N. Find how many steps are in the staircase. |
$O(\\text{sqrt}{N})$ for math or $O(N)$ for DP. |
Draw a single line showing the jump sizes decreasing. Mark $O(\\text{sqrt}{N})$. |
Exponential call stack. |
$O(1)$ if using the quadratic formula; $O(N)$ for DP array. |
| 1885 |
Count Pairs in Two Arrays |
Nested loops: For every pair (i, j), check if nums1[i] + nums1[j] > nums2[i] + nums2[j]. |
N \times N comparison grid. |
Draw two arrays. Draw lines connecting every index pair. Mark $O(N^2)$. |
Two Pointers on Difference Array. |
Opposing sorting pointers. |
Rearrange: (nums1[i] - nums2[i]) + (nums1[j] - nums2[j]) > 0. Let diff[i] = nums1[i] - nums2[i]. Sort diff. Use L and R pointers to count valid pairs where diff[L] + diff[R] > 0. |
Draw the diff array. Sort it. Place L at start, R at end. If L+R > 0, then R can pair with all elements between L and R-1. Add (R-L) to count. |
$O(N \log N)$ Sorting + $O(N)$ Two Pointers. |
Draw a sorting tree followed by a single linear pass with two arrows meeting. Mark $O(N \log N)$. |
$O(1)$ besides input. |
One auxiliary diff array of size N in memory. |
| 1886 |
Determine Whether Matrix Can Be Obtained By Rotation |
Manually simulate 90°, 180°, and 270° rotations by creating new matrices and comparing them to the target. |
Matrix state-machine flowchart. |
Draw a square grid. Draw four arrows pointing to 4 separate grids, each showing the indices shifted. Mark $O(N^2)$ per rotation. |
In-place Matrix Rotation (Transpose + Reverse) or Index Mapping. |
Coordinate Transformation Map. |
Map (i, j) to (j, n-1-i). Check if this mapping holds for all 4 possible rotations without allocating new memory. |
Draw a 2x2 grid. Label corners (0,0), (0,1), (1,0), (1,1). Show where (0,0) moves in each rotation. Verify target cell matches. |
Single pass comparison over 4 states. |
Draw an arrow passing through the N \times N matrix once. Mark as $O(N^2)$. |
Temporary 2D arrays for each rotation stage (O(N^2) space). |
$O(1)$ extra space using four boolean flags (rot0, rot90, rot180, rot270). |
| 1887 |
Reduction Operations to Make the Array Elements Equal |
Find the largest element, find the next largest, and reduce the largest to that value repeatedly. |
Staircase descending simulation. |
Draw a bar chart with different heights. Pick the tallest bar and "cut" it to match the height of the second tallest. Count cuts. $O(N^2)$. |
Sorting + Greedy Counting. |
Frequency-weighted step chart. |
Sort the array. Iterate from right to left. When nums[i]
eq nums[i-1], all elements from i to end must be reduced. Add (n-i) to total. |
Draw a sorted bar chart. Draw a vertical line where heights change. Every element to the right of a "step" represents one extra operation. |
$O(N \log N)$ sorting + $O(N)$ scan. |
Draw a merge-sort tree and a single horizontal scan line. Mark $O(N \log N)$. |
$O(1)$ if modifying input, but high computational time. |
$O(1)$ or $O(N)$ for the sorted copy. |
| 1888 |
Minimum Number of Flips to Make the Binary String Alternating |
For every possible cyclic shift of the string, check how many flips are needed to match patterns "0101..." or "1010...". |
Circular permutation search matrix. |
Draw a circle of bits. For every starting point, draw the string and count mismatches against a target. Mark $O(N^2)$. |
Sliding Window on concatenated string (s + s). |
Fixed-size window on a double-length tape. |
Create patterns "0101..." of length 2N. Slide a window of size N over (s+s). Maintain counts of mismatches. Min mismatches is the result. |
Draw s+s on a tape. Below it, draw a "0101..." template. Slide a box of length N. Update mismatch count as bits enter/leave the box. |
Single pass linear window movement. |
Draw an arrow from 0 \to 2N. Mark as $O(N)$. |
Storing N separate strings (O(N^2) space). |
$O(N)$ for the doubled string or $O(1)$ if simulated via modulo. |
| 1889 |
Minimum Space Wasted From Packaging |
For every supplier, check every box and see which packages fit. Sum the waste. |
Supplier \times Box \times Package triple-interaction. |
Draw boxes and items. For each supplier, draw arrows matching every item to its box. $O(S \cdot B \cdot P)$. |
Sorting + Binary Search (Prefix Sums). |
Cumulative Distribution Step Function. |
Sort packages. For each supplier, sort boxes. Use binary search to find how many packages fit in `box[i]`. Use prefix sums to calculate total package weight in that range in $O(1)$. |
Draw a sorted package line. Mark "Box 1 capacity", "Box 2 capacity". Use pointers to find segments. Area above packages but below box line is the waste. |
$O(P \log P + \\text{sum} (B \log B + B \log P)$). |
Draw a sorting tree for packages. For each supplier, draw a sequence of binary search jumps. Mark $O(P \log P + B \log P)$. |
None (O(1) besides input). |
Prefix Sum array of size P in memory. |
| 1890 |
The Latest Login in 2020 (SQL) |
Pull all records into application logic, filter by year, and find the max date for each user. |
Full table-to-app data stream. |
Draw a table. Draw an arrow to a code block. Show a dictionary mapping `user_id` to `max_date`. |
GROUP BY + MAX() + EXTRACT/LIKE/YEAR(). |
Hashed Aggregation. |
Filter rows where `time_stamp` is in 2020. Group by `user_id`. Select `MAX(time_stamp)`. |
Draw a table. Highlight rows from 2020. Group those with same ID. Circle the row with the latest time. |
Linear table scan (or index seek). |
Draw an arrow passing through the column once. Mark $O(N)$. |
Massive array of login objects in app RAM. |
Zero extra application memory; handled by DB engine. |
| 1891 |
Cutting Ribbons (Premium) |
Linear search: Try ribbon length L from max(ribbons) down to 1. Check if total ribbons \ge k. |
Linear Search decrement line. |
Draw a line from Max to 1. Draw an arrow stepping through every single integer. Mark $O(N \\text{times} \\text{text}{\text{MaxLen}})$. |
Binary Search on Answer. |
Monotonic Range Halving. |
Define L=0, R=10^5. Test mid. If \sum (\text{ribbon} / mid) \ge k, search higher (L=mid); else search lower (R=mid-1). |
Draw a horizontal line for the length range. Mark the middle. Cross out the half that cannot satisfy the ribbon count k. |
Logarithmic search height. |
Draw a binary tree of height \log(\text{MaxLen}). Each node takes $O(N)$. Mark $O(N \log \\text{text}{\text{MaxLen}})$. |
$O(1)$ extra space. |
$O(1)$ stack variables (L, R, mid, sum). |
| 1892 |
Page Recommendations II (SQL Premium) |
Self-join the Friendship and Likes tables multiple times to find friends' liked pages that the user hasn't liked. |
Nested join interaction tree. |
Draw two tables (Users, Pages). Draw lines for friends, then more lines for their likes. Mark $O(N^3)$ complexity. |
Common Table Expression (CTE) + LEFT JOIN filtering. |
Venn Diagram exclusion. |
1. Create symmetric friendship table. 2. Join with Likes on friend_id. 3. Join with original Likes on user_id to exclude existing likes. |
Draw two circles: "Pages Friends Liked" and "Pages I Liked". The answer is the crescent moon shape (Left Only). |
Linear table scan and set subtraction. |
Draw a flow chart: Join \to GroupBy \to Filter. Mark as $O(N \log N)$ or $O(N)$. |
Large N^2 temporary join results in disk/memory. |
In-memory hash-joins and indexed lookups. |
| 1893 |
Check if All the Integers in a Range Are Covered |
For every integer x in [left, right], iterate through every range in `ranges` to see if x is contained. |
N \times R scan matrix. |
Draw a number line. For each point, draw arrows checking every given range. Mark $O(N \\text{times} \\text{text}{\text{length}})$. |
Difference Array / Prefix Sum (Line Sweep). |
Cumulative coverage tracker. |
Create array of 52 zeros. For each [start, end], add 1 at `start`, subtract 1 at `end + 1`. Calculate prefix sums to see coverage \ge 1. |
Draw a number line 1-50. Mark '+' at start and '-' after end. Walk the line, if count stays above 0 for the whole target range, return true. |
Linear passes (Fixed range 50). |
Draw an arrow passing through the 50-slot array once. Mark $O(N + 50)$. |
List of boolean flags for every point. |
Difference array of size 52 in memory. |
| 1894 |
Find the Student that Will Replace the Chalk |
Simulate the process: repeatedly subtract chalk[i] from k in a loop until k < chalk[i]. |
Spiral decrement timeline. |
Draw students in a circle. Draw an arrow circling them, subtracting values from k until k hits 0. Mark $O(k/N)$ passes. |
Prefix Sum + Modulo Arithmetic + Binary Search. |
One-pass modulo reduction. |
1. Calculate `totalSum`. 2. Set k = k \pmod{totalSum}. 3. Use binary search on the prefix sum array to find the first index i where prefix[i] > k. |
Draw the students' chalk on a tape. Calculate the total. "Cut" the k tape into pieces of `totalSum` length. Look at the leftover piece and find where it stops on the student tape. |
$O(N)$ for prefix sums + $O(\log N)$ search. |
Draw an arrow for prefix sum, then a binary search tree of height \log N. Mark $O(N)$. |
$O(1)$ extra space. |
One prefix sum array of size N in memory. |
| 1895 |
Largest Magic Square |
Iterate through every possible square in the grid (Row x Col x SideLength) and check if all row/col/diag sums are equal. |
N \times M \times S \times S quadruple scan. |
Draw a grid. Outline a square. Draw arrows for every row, column, and two diagonals. Mark $O(\text{min}(R,C)$^4). |
2D Prefix Sums (Rows, Cols, and Diagonals). |
Sub-grid sum lookup table. |
Precompute prefix sums for rows, columns, and two diagonal directions. Check if a square of side k is magic in $O(k)$ time by comparing these sums. |
Draw four grids representing the running sums in four directions. For a candidate square, pick the boundaries and subtract endpoint values to get the sums instantly. |
$O(R \cdot C \cdot \\text{min}(R,C)$). |
Draw a rectangle R \times C. At each cell, mark a loop of size \min(R,C). Mark $O(R \cdot C \cdot \\text{min}(R,C)$). |
None (besides input). |
Four auxiliary 2D arrays of size R \times C in heap memory. |
| 1896 |
Minimum Cost to Change the Final Value of Expression |
Recursively try flipping every character (0 to 1, AND to OR) and re-evaluate the entire string. |
Exponential decision tree. |
Draw a root node. Branch out for every possible character flip. Mark as $O(2^N)$ combinations. |
Stack-based Expression Parsing + Dynamic Programming (bottom-up costs). |
Nodal evaluation pairs (value, cost). |
Parse into a tree or stack. Each node returns a pair: its result and the cost to change it. Combine costs using boolean logic rules. |
Draw an expression tree. At each leaf, write (val, 1). For parent nodes, use min() logic to determine cost based on AND/OR rules. |
Linear tree traversal. |
Draw an arrow traversing the tree from leaves to root. Mark $O(N)$. |
None (computational explosion). |
Stack of integer pairs `[value, cost_to_flip]` in memory. |
| 1897 |
Redistribute Characters to Make All Strings Equal |
Generate all possible ways to move letters between words and check if all words become identical. |
Combinatorial arrangement grid. |
Draw strings as buckets of letters. Try moving letters one by one into new arrangements. Mark $O(N!)$. |
Hash Map / Frequency Count (Modulo Arithmetic). |
Tally board + Total strings count. |
Count total occurrences of every character. For each char, if `total_count % number_of_words != 0`, return false. |
Draw a 26-slot table. Scan all strings and fill with tallies. Divide each tally by the number of words. Look for remainders. |
Single linear pass over all characters. |
Draw an arrow passing through all strings. Mark $O(\\text{text}{\text{Total Length}})$. |
Storing all possible word permutations in a list. |
Fixed-size integer array of size 26 (O(1) extra space). |
| 1898 |
Maximum Number of Removable Characters |
Linear Search: Remove 1 char, check subsequence. Remove 2, check... continue until p is no longer a subsequence of s. |
K \times (N+M) search timeline. |
Draw a line 1 to K. For each step, redraw the string and run two-pointer subsequence check. Mark $O(K \cdot N)$. |
Binary Search on Answer (k) + Two Pointers. |
Success/Failure range halving. |
Pick mid. Mark first mid indices in `removable` as "deleted". Run two pointers on s and p. If p is a subsequence, search higher. |
Draw a line 0 to K. Mark `mid`. Cross out characters in s. Draw two arrows (pointers) scanning s and p. If they finish, search the right half. |
Logarithmic search height. |
Draw a binary tree of height \log K. Each node takes $O(N)$. Mark $O(N \log K)$. |
Multiple copies of strings for each k. |
A single boolean array or bitset of size N to track "removed" indices. |
| 1899 |
Merge Triplets to Form Target Triplet |
Try all possible combinations of triplets (subsets) and calculate the component-wise maximum for each. |
2^N subset combination tree. |
Draw a root. Branch "Include/Exclude" for every triplet. Check final max for all 2^N leaves. |
Greedy Filtering (One Pass). |
Requirement checklist. |
Iterate through triplets. If a triplet has any element greater than the target's corresponding element, discard it. For the rest, check if you hit each target value. |
Draw the target [a, b, c]. List triplets. Cross out any triplet where t[0]>a or t[1]>b or t[2]>c. Of the remaining, check if the max of all indices equals the target. |
Single linear pass. |
Draw an arrow from 0 \to N. Mark $O(N)$. |
List to store all possible merged results. |
Three boolean flags or a single 3-element integer array. |
| 1900 |
The Earliest and Latest Rounds Where Players Compete |
Simulate all possible tournament brackets and track the round where player 1 and player 2 meet. |
Combinatorial bracket explosion. |
Draw a tournament tree. Branch out for every possible winner of every game. Mark $O(2^N)$ brackets. |
Memoized Recursion / Dynamic Programming on (n, firstPlayer, secondPlayer). |
State space reduction grid. |
Recursive function `solve(n, p1, p2)`. Try all possible counts of winners between p1 and p2. Use memoization to avoid re-calculating identical game states. |
Draw a table representing `solve(n, p1, p2)`. For each cell, show a loop trying different winner counts. Mark states that merge to the same result. |
$O(N^4)$ State Space. |
Draw a 4D cube (or N^4 grid) representing all state variables. Mark as $O(N^4)$. |
$O(1)$ extra space (ignoring recursive calls). |
3D/4D memoization table (e.g., `int[n][n][n]`) in heap memory. |
| 1901 |
Find a Peak Element II |
Traverse every single element in the m x n matrix to find the global maximum. |
2D Grid Scanning / Area Shading |
Draw an m x n grid. Cross out cells sequentially row by row, showing $O(m\cdot n)$ coverage. |
Binary Search on Columns/Rows |
Search Space Reduction (Matrix Bisection) |
Highlight middle column. Find max. Check left/right neighbors. Grey out half of the matrix based on the greater neighbor. |
Draw a bounding box. Draw a vertical line down the middle. Draw an arrow pointing to the side with the larger neighbor. Redraw a smaller bounding box. |
Area Halving Tree |
Draw a rectangle of size m*n. Draw an arrow to a rectangle of m*(n/2), then m*(n/4), demonstrating $O(m \log n)$ shrinkage. |
Single pointer `(i, j)` moving sequentially through a 2D array grid layout. |
`start`, `end`, and `mid` column pointers on a 1D axis, with an auxiliary variable mapping to the row index of the column's max element. |
| 1902 |
Depth of BST Given Insertion Order |
Insert nodes one by one into a standard Binary Search Tree, traversing from the root every time. |
Unbalanced Tree Expansion |
Draw a root. Draw paths getting longer and longer for worst-case (e.g., sorted array), counting edge traversals up to $O(N^2)$. |
TreeMap / Ordered Map (Next/Prev Greater Element) |
Number Line Boundary Mapping |
Place node on a 1D number line. Find nearest left and right neighbors. Depth is max(depth[left], depth[right]) + 1. |
Draw a horizontal line. Plot existing nodes. Drop a new node between two existing ones. Draw vertical arrows mapping its depth to the max of its neighbors. |
Logarithmic Map Insertion Timeline |
Draw N dots. For each, draw an $O(\log N)$ lookup arrow to a balanced Binary Search Tree representing the TreeMap. Total $O(N \log N)$. |
Standard Pointer-based Tree nodes dynamically allocating memory on the heap (many isolated boxes with L/R arrows). |
A contiguous Array/Hash Map storing `node_val -> depth`, representing flattened memory lookup. |
| 1903 |
Largest Odd Number in String |
Generate all possible substrings, check if they are odd, keep track of the maximum length. |
Permutation/Substring Tree |
Draw a string. Draw overlapping brackets representing every possible substring combination, highlighting $O(N^2)$ possibilities. |
Greedy (Right-to-Left Traversal) |
Reverse Linear Scanning |
Start pointer at the very end of the string. Move left until the first odd digit is found. Slice string from index 0 to that point. |
Write the string as an array of boxes. Draw an arrow starting at the last box, skipping leftwards. Circle the first odd number, box everything to its left. |
Early Termination Bar Graph |
Draw a single straight line representing $O(N)$. Put a stop sign at the first odd occurrence to show worst-case linear, best-case $O(1)$ time. |
A giant memory block holding an array of all generated substring strings (High memory overhead). |
Two index integer variables (0 and right_pointer) referencing the original string in place. $O(1)$ space. |
| 1904 |
The Number of Full Rounds You Have Played |
Step minute by minute from start time to end time, checking if a 15-minute interval is completed. |
Minute-by-Minute Tick Line |
Draw a clock face or timeline. Put tick marks for every single minute passed, accumulating $O(\text{Total Minutes})$ steps. |
Math / Modular Arithmetic |
Interval Snapping / Step Functions |
Convert times to minutes. Snap start time to the next 15-min mark (ceil). Snap end time to the previous 15-min mark (floor). Subtract. |
Draw a timeline. Plot start and end. Draw curved arrows pushing "start" forward to a 15-min notch and "end" backward to a 15-min notch. Count blocks. |
$O(1)$ Constant Calculation Box |
Draw a single input box mapping to an equation `(end - start) / 15`, resulting in a single output box. $O(1)$ time. |
A `while` loop accumulating a counter integer in the stack. |
Just 4 simple integer variables in the call stack (`start_mins`, `end_mins`, `rounded_start`, `rounded_end`). |
| 1905 |
Count Sub Islands |
DFS to find all islands in Grid 2. For each island, iterate through its cells again and check if Grid 1 has a 1. |
Dual Grid Overlay (Redundant checks) |
Draw Grid 2, circle an island. Draw an arrow to Grid 1, circle the same cells. Show two separate loops running sequentially. |
Graph / DFS with Simultaneous Verification |
Simultaneous Mask Overlay |
Run DFS on Grid 2. As you visit a cell, immediately verify if Grid 1 has a 1 at the same coordinate. If not, mark a boolean flag false. |
Draw Grid 1 on top of Grid 2. As the DFS snake moves through Grid 2, draw an immediate "X" or "Check" based on the layer above it. |
Recursive Call Tree Size |
Draw an m*n grid. Shade visited cells, proving each cell is visited only once. $O(m\cdot n)$ time. |
Call stack mapping separate arrays storing coordinates of islands before validation. |
Recursive DFS call stack frames storing just `(r, c)` and a passed boolean reference, no extra array memory required. |
| 1906 |
Minimum Absolute Difference Queries |
For each query, slice the sub-array, sort it, and compare adjacent elements to find the minimum difference. |
Array Slicing & Sorting Timeline |
Draw an array. Draw a bracket for the query range, extract it into a new box, sort it, and draw loops connecting adjacent elements. $O(Q \cdot N \log N)$. |
Prefix Sums over Frequency Array |
Frequency Prefix Matrix Subtraction |
Subtract prefix frequencies at `L-1` from `R` to get counts of numbers in the range. Iterate 1 to 100 to find the minimum difference between present numbers. |
Draw a 100-column matrix. Highlight row R and row L-1. Draw an arrow subtracting them to create a single 1D array of active frequencies. Find gaps. |
Constant Operations per Query Graph |
Draw N blocks representing prefix building. Then draw Q blocks, each containing exactly 100 constant steps. $O(N\cdot 100 + Q\cdot 100)$. |
Dynamically allocated sub-arrays constructed and discarded on the heap for every single query. |
A contiguous 2D array `prefix[N][100]` storing integer counts. |
| 1907 |
Count Salary Categories |
Iterate through all accounts three separate times to count "Low", "Average", and "High" tiers independently. |
Triple Pass Linear Scan |
Draw three separate horizontal arrows scanning across the full length of an array representation of the data. |
Single Pass Bucketing (or SQL UNION/GROUP BY) |
Multi-bin Dropping |
Iterate through accounts exactly once. Use if/else logic to increment one of three specific category counters. |
Draw a conveyor belt (the array). At the end, draw 3 buckets. For each item on the belt, draw an arrow dropping it into the corresponding bucket. |
Single Scan Bar |
Draw a single straight arrow from start to finish representing strictly $O(N)$ operations. |
Loading the entire dataset into memory multiple times (High I/O overhead). |
Three isolated integer variables (`low`, `avg`, `high`) existing in a constant $O(1)$ memory space. |
| 1908 |
Game of Nim |
Backtracking / Minimax to simulate every single possible move from every pile to find a winning branch. |
Massive Game State Tree |
Draw a root node branching out into dozens of child states, exploding exponentially downward $O(2^N)$. |
Sprague-Grundy Theorem (Bitwise XOR / Nim-Sum) |
Bitwise XOR Stacking |
Write all pile sizes in binary. Compute the XOR sum. If the final sum is not 0, the first player wins. |
Write the binary numbers stacked vertically. Draw a line underneath. Do column-wise XOR (if count of 1s is odd, write 1; if even, write 0). |
$O(N)$ Funnel Gate |
Draw N input numbers funneling into a single XOR logic gate to produce one boolean output. |
A massive call stack for DFS with a large Hash Map to memoize visited states. |
A single integer `xor_sum` accumulator variable acting in-place. $O(1)$ space. |
| 1909 |
Remove One Element to Make the Array Strictly Increasing |
Create N different versions of the array, each missing one element. Scan each version to see if it is strictly increasing. |
N-Array Rebuilding |
Draw the original array N times, each with a different element shaded out. Draw scan arrows over all N arrays. $O(N^2)$. |
Single Pass Greedy Violation Detection |
Dip Detection & Patching |
Traverse left to right. At the first violation (`nums[i-1] >= nums[i]`), verify if removing either `nums[i-1]` or `nums[i]` fixes the slope based on `nums[i-2]`. |
Draw the array values as points on a line graph. Identify the "dip". Draw dotted lines showing the two possible deletions to see which bridges the gap cleanly. |
Violation Stop-Gate |
Draw a single line forward. Add a small "bump" icon. Allow exactly one bump before returning false. $O(N)$ time. |
N separate arrays of size N-1 actively sitting in system memory. |
A few pointer and counter variables (`count`, `prev_val`) traversing the original array. $O(1)$ space. |
| 1910 |
Remove All Occurrences of a Substring |
Repeatedly call built-in string replacement, scanning the whole string from scratch every time a match is removed. |
Repeated String Shifting |
Draw a string. Cross out a substring. Redraw the collapsed, shorter string below it. Repeat until clean. $O(N^2)$. |
Stack-based Pattern Matching |
Stack Push-and-Pop Deletion |
Push characters onto a stack one by one. Check the top elements. If they form the target substring, pop them off. |
Draw a vertical bucket. Drop letters in. When the top letters spell the target, draw an eraser wiping them out, then continue dropping. |
Linear Stack Traversal |
Draw an arrow moving forward (push), with occasional short backwards hops (pop). Bound by $O(N)$. |
High garbage collection overhead from creating completely new intermediate strings on the heap. |
A contiguous character array or string builder pre-allocated to size N acting as a stack. $O(N)$ space. |
| 1911 |
Maximum Alternating Subsequence Sum |
Use recursion to generate every possible subsequence (pick or skip), calculating the alternating sum for each. |
Exponential Decision Tree |
Draw a root node. Branch left for "pick", right for "skip". Keep branching until you have a massive tree of $O(2^N)$ leaves. |
Dynamic Programming / State Machine |
2-State Transition Diagram |
Maintain two running totals: max sum ending on an 'even' index (adding) and an 'odd' index (subtracting). Update both sequentially. |
Draw two boxes labeled "Even (Add)" and "Odd (Subtract)". Draw arrows crisscrossing between them as a pointer moves across the array values. |
Parallel Linear Tracks |
Draw two parallel horizontal lines representing $O(N)$ time. Draw vertical ticks connecting them at each step. |
Deep recursive call stack frames piling up in memory. $O(N)$ depth. |
Exactly two integer variables (`even_sum`, `odd_sum`) in local scope. $O(1)$ space. |
| 1912 |
Design Movie Rental System |
Store all movie copies in a standard list. Scan the entire list linearly to find unrented movies, cheapest movies, or to drop off. |
Unsorted Array Scanning |
Draw a massive array. Draw a magnifying glass starting at index 0 and sliding all the way to N for every single query. $O(N)$ per operation. |
Multiple TreeSets / Priority Queues + HashMaps |
Connected Multi-Index Routing |
Keep an `unrented` sorted set and a `rented` sorted set. Use HashMaps to instantly find a movie's node, then move it between the sets. |
Draw two large bins (TreeSets). Draw a movie item. Draw an arrow moving the item instantly from 'unrented' to 'rented', preserving its sorted rank. |
Logarithmic Branch Lookup |
Draw a balanced tree. Highlight a single path from root to leaf to represent the $O(\log N)$ lookup and insertion time. |
A massive flat array or list taking up continuous heap memory. |
Complex web of balanced Binary Search Trees nodes and Hash Map buckets linking to the same memory addresses. |
| 1913 |
Maximum Product Difference Between Two Pairs |
Sort the entire array first, then multiply the two largest numbers and subtract the product of the two smallest numbers. |
Sorting Funnel Timeline |
Draw a jumbled array falling through a funnel labeled "Sort", emerging as an ordered array. Highlight the first two and last two boxes. $O(N \log N)$. |
Single Pass Greedy Tracking |
Four-Variable Pipeline |
Iterate the array exactly once. Compare each number against your running `max1`, `max2`, `min1`, and `min2` variables, updating them on the fly. |
Draw an array. Draw 4 distinct boxes below it (M1, M2, m1, m2). Slide a single pointer across the array, drawing update arrows to the boxes. |
Single Continuous Arrow |
Draw one straight arrow moving from left to right over an array block, representing strictly $O(N)$ time. |
Heap memory allocated for sorting algorithms (like TimSort's auxiliary arrays). |
Just 4 primitive integer variables stored on the stack. $O(1)$ space. |
| 1914 |
Cyclically Rotating a Grid |
Shift every single cell in the grid one position clockwise, and repeat this entire process K times. |
Concentric Rings Shifting |
Draw a grid. Draw tiny arrows moving every cell one spot. Write "Repeat K times" next to it. $O(M\cdot N\cdot K)$. |
1D Array Extraction & Modular Rotation |
Peel, Slice, and Wrap |
Extract each layer of the grid into a flat 1D array. Rotate the 1D array by `K % length`. Wrap the array back into the grid layer. |
Draw a 2D grid. Draw an arrow pulling the outer border out into a flat 1D strip. Cut the strip, swap the halves, and push it back into the grid. |
Fixed Operations Pipeline |
Draw three boxes: "Extract $O(M\cdot N)$", "Shift $O(M\cdot N)$", "Insert $O(M\cdot N)$". $O(M\cdot N)$ total time regardless of K. |
A temporary 2D grid re-created K times in memory. |
A temporary 1D array buffer sized exactly to the perimeter of the current layer being rotated. |
| 1915 |
Number of Wonderful Substrings |
Generate all possible substrings. For each one, count the character frequencies to check if at most one character is odd. |
Nested Substring Bracketing |
Draw a string. Draw overlapping brackets underneath for every possible start and end index. Tally characters inside every bracket. $O(N^2)$ or $O(N^3)$. |
Bitmasking + Prefix XOR + Frequency Hash Map |
Bitmask State Toggling |
Represent the 10 letters (a-j) as a 10-bit binary number. Toggle bits via XOR as you iterate. Count how many times you've seen the current mask (or masks 1 flip away). |
Draw the string. Below each char, write a 10-bit number. Draw a running "XOR Mask" box that flips bits. Draw arrows from it to a Hash Map keeping count. |
Linear Scan with $O(1)$ Checks |
Draw a timeline arrow. At each step, draw exactly 10 tiny checkmarks, showing the constant-time bit-flip checks. $O(N \cdot 10)$. |
Generating thousands of temporary string objects or frequency integer arrays. |
A fixed-size integer array of length 1024 (representing 2^10 possible bitmasks), operating in $O(1)$ space. |
| 1916 |
Count Ways to Build Rooms in an Ant Colony |
Generate all possible topological permutations of the dependency tree and validate them one by one. |
Brute Force Permutation Tree |
Draw a massive branching tree generating N! permutations. Cross out paths that violate the tree's parent-child ordering constraints. |
Tree DP with Combinatorics |
Subtree Merging (Multinomial Coefficients) |
Run a bottom-up DFS. At each node, merge its children's valid permutations using combinations (size A + size B choose size A), multiplying the ways. |
Draw a tree. Start at the leaves, passing up their "sizes" and "ways". At each parent, draw a merging funnel labeled "Combinatorics Math" producing a new "ways" count. |
Bottom-Up Tree Reduction |
Draw a tree collapsing layer by layer upwards into the root, showing an $O(N)$ single-pass consolidation. |
Huge sets holding N! array permutations on the heap. |
Precomputed 1D Arrays for Factorials/Inverses, plus the recursive DFS Call Stack frames tracking subtree sizes and ways. |
| 1917 |
Leetcodify Friends Recommendations (SQL) |
Cross-join all users with all users for all days, then filter for ≥ 3 common songs and no existing friendship. |
Multi-dimensional Cartesian Cube |
Draw a cube representing Users x Users x Songs x Days. Cross out invalid combinations. Massive $O(U^2 \cdot S \cdot D)$ scale. |
Self-Join with Anti-Join (NOT IN) |
Relational Venn Diagram Filtering |
Self-join the Listens table on day and song_id. Group by user pairs. Count distinct songs ≥ 3. Exclude existing friends via LEFT JOIN or NOT IN. |
Draw the Listens table joining itself. Draw an arrow to an aggregate funnel (Count ≥ 3). Draw a filter blocking pairs that already appear in the Friends table. |
Hash Join & Aggregate Pipeline |
Draw two cylinders (tables) feeding into a "Hash Join" gear, then a "Group By" gear, ending in a filtered result set. |
Giant intermediate spool space / temp tables created on the database disk to hold Cartesian products. |
In-memory Hash Tables built internally by the SQL engine for efficient group-by aggregations. |
| 1918 |
Kth Smallest Subarray Sum |
Generate all possible subarrays, calculate their sums, store them in a list, sort the list, and pick the Kth element. |
Array Slicing & Giant Sorting Funnel |
Draw overlapping brackets generating $O(N^2)$ subarrays. List all their sums, funnel them into a sorting box, and point to the K-th item. $O(N^2 \log(N^2)$). |
Binary Search on Answer + Sliding Window |
Threshold Counting Number Line |
Pick a target sum 'mid'. Use a sliding window to count how many subarrays have a sum ≤ 'mid'. If count ≥ K, shrink right; else, shrink left. |
Draw a number line for the sum. Pick 'mid'. Below it, draw the array with an expanding/contracting sliding window (caterpillar) counting valid subarrays. |
Logarithmic Number Line Search |
Draw a number line shrinking by half log(Sum) times. At each step, draw a linear $O(N)$ caterpillar scan. Total $O(N \log M)$. |
A massive dynamic array holding $O(N^2)$ integer sums before sorting. |
A few simple integer pointers (`left`, `right`, `count`, `current_sum`) for the sliding window taking strictly $O(1)$ space. |
| 1919 |
Leetcodify Similar Friends (SQL) |
Cross-join the entire Friends table with the Listens table multiple times to find overlapping daily songs naively. |
Redundant Table Scans |
Draw the Friends table pointing to the entire Listens table for user1, then pointing again for user2, with heavy loops iterating row by row. |
Filtered Inner Join Pipeline |
Intersection Pipelining |
Inner join Friends with Listens for user1, then inner join again with Listens for user2 on the same day and song_id. Group and filter for count ≥ 3. |
Draw the Friends table acting as a strict bridge. Only rows matching the bridge pass into the Listens self-join. Draw the overlapping songs dropping into a counter bucket. |
Indexed Hash Join Filter |
Draw the Friends table as a primary filter gate, massively reducing the data volume before it hits the heavier Group-By operations. |
Massive temporary Cartesian tables spilling over into database disk storage. |
Efficient Hash Tables mapping User-Day-Song triplets, staying well within the SQL engine's RAM limits. |
| 1920 |
Build Array from Permutation |
Create a brand new array of size N. Iterate through nums and directly assign `ans[i] = nums[nums[i]]`. |
Parallel Array Mapping |
Draw `nums` array on top, `ans` array on bottom. Draw crossed arrows mapping values from `nums` as indices back to `nums` and down to `ans`. |
In-Place Encoding (Math / Modulo) |
Dual-State Storage (2 values in 1 slot) |
Traverse the array. Encode the new value alongside the old using `nums[i] = nums[i] + N * (nums[nums[i]] % N)`. Traverse again to extract new values by dividing by N. |
Draw a single array block. Draw it splitting into two layers conceptually (Remainder for Old, Quotient for New). Run through twice: first packing the box, second unpacking it. |
Two-Pass Linear Scan |
Draw one straight arrow left to right (Encoding pass). Draw a second straight arrow left to right (Decoding pass). Strictly $O(N)$ time. |
A newly allocated `ans` array of size N taking up $O(N)$ heap memory. |
The input array mutated in place. Zero extra allocations, operating in strictly $O(1)$ extra space. |
| 1921 |
Eliminate Maximum Number of Monsters |
At each minute, simulate all monster movements and pick a monster to shoot based on current distance naively. |
Real-time Simulation Timeline |
Draw a timeline from t=0 onwards. For each tick, redraw all monster positions closer to the origin. $O(\text{Time} \cdot N)$. |
Greedy Sorting by "Time-to-Arrival" |
Timeline Slot Booking |
Calculate `arrival_time = dist / speed` for each monster. Sort these times. Check if the i-th monster arrives before minute i. |
Draw a list of arrival times. Draw a minute-clock next to it. Compare the sorted list against the clock. If `Time[i] <= i`, game over. |
Sorted Departure Queue |
Draw a funnel (Sort) leading to a linear conveyor belt (Check). $O(N \log N)$ for sorting, $O(N)$ for scan. |
Large list of dynamic objects or coordinate pairs updated repeatedly in memory. |
A simple 1D array of floats representing `time_to_impact` for each monster. |
| 1922 |
Count Good Numbers |
Iterate from index 0 to n-1, checking for each index whether the digit fits the "good" criteria and multiplying results. |
Iterative Multiplication Chain |
Draw a long chain of N nodes. Label even nodes with "5 options" and odd nodes with "4 options". $O(N)$. |
Binary Exponentiation (Fast Power) |
Divide and Conquer Multiplication Tree |
Use the property `(a^n = (a^(n/2))^2)`. Calculate 5^{\lceil n/2 \rceil} and 4^{\lfloor n/2 \rfloor} using modular exponentiation. |
Draw a tree starting at power N, branching into N/2, then N/4. Highlight only one side of the branch being computed. |
Logarithmic Depth Tree |
Draw a tree of height log(N). Each level represents one multiplication. $O(\log N)$ time. |
$O(1)$ iterative variables, but slow $O(N)$ execution time. |
Recursive function stack with depth $O(\log N)$. |
| 1923 |
Longest Common Subpath |
Generate every possible subpath of every path and find the longest one that appears in all lists using a Hash Set. |
Subsequence Intersection Overlap |
Draw multiple circles representing all subpaths of each path. Find the central intersection of all circles. $O(N^2)$ paths. |
Binary Search on Length + Rolling Hash (Rolling Hash) |
Sliding Window Hash Validation |
Binary search for the length 'L'. For a fixed L, use Rabin-Karp (rolling hash) to find common subpaths across all users. |
Draw a number line for length. Pick 'L'. For each path, slide a window of size L. Generate a hash value. Compare hashes across paths. |
Logarithmic Search with Linear Check |
Draw a binary search tree for length (log N) and for each node, draw a linear scan across all paths (sum of lengths). $O(\text{Sum}(L)$ * log N). |
Massive Hash Set storing every single possible string/subpath from every path. |
A set of long integers (hashes) for each path at a specific length L, clearing memory after each binary search step. |
| 1924 |
Erect a Fence II |
Exhaustively check all possible circles formed by 2 or 3 points to see which one contains all other points. |
Exhaustive Geometric Search |
Draw every triplet of points. Draw the circumcircle. Check if all other N-3 points are inside. $O(N^4)$. |
Welzl's Algorithm (Recursive Smallest Enclosing Circle) |
Incremental Boundary Expansion |
Start with an empty circle. Randomly add points. If a point is outside, the new circle must have this point on its boundary. |
Draw a set of points. Circle the first two. Add a third; if outside, redraw circle using the new point and previous ones. Repeat. |
Linear Randomized Expected Time |
Draw a single line. Indicate that while it looks complex, the "expected" visits per point is constant. $O(N)$ average case. |
$O(1)$ if iterative, but $O(N^4)$ state checks in the naive version. |
Recursive call stack for Welzl's, with depth proportional to the number of points on the boundary (usually small). |
| 1925 |
Count Square Sum Triples |
Use three nested loops for a, b, and c (from 1 to n) and check if a^2 + b^2 = c^2. |
Triple-Nested Loop Cube |
Draw a 3D cube of size n x n x n. Every cell in the cube is a check operation. $O(n^3)$. |
Double Loop with Square Root Check |
2D Grid with Perfect Square Probe |
Loop a and b from 1 to n. Calculate val = a^2 + b^2. Check if val \le n^2 and if \sqrt{val} is an integer. |
Draw a 2D grid (a vs b). For each cell, calculate the hypotenuse and check if it’s a "clean" integer within bounds. |
Quadratic Area Scan |
Draw a 2D square of size n \times n. Every cell is one operation. $O(n^2)$ total time. |
$O(1)$ - Three integer counters in a loop. |
$O(1)$ - Two integer counters and one math check variable. |
| 1926 |
Nearest Exit from Entrance in Maze |
DFS to explore every path from entrance to every boundary, tracking the shortest. |
Exhaustive Path Branching Tree |
Draw a maze. From entrance, draw multiple winding lines that hit dead ends or circle back. $O(4^(M\cdot N)$) exponential exploration. |
Breadth-First Search (BFS) |
Expanding Concentric Ripples |
Add entrance to a Queue. Expand 1 step in all directions simultaneously. The first "exit" reached is the shortest. |
Draw the grid. Color the entrance. Draw Layer 1 (adjacent cells), then Layer 2, like a growing wave until a border cell is hit. |
Grid Visitation Map |
Draw an M x N grid. Cross out each cell once as it enters the queue. $O(M\cdot N)$ time. |
Deep recursive stack frames for every possible path branch, leading to StackOverflow on large mazes. |
A First-In-First-Out (FIFO) Queue box and a 2D boolean 'visited' array (or in-place grid modification). |
| 1927 |
Sum Game |
Simulate every possible digit (0-9) Alice and Bob can pick for every '?' and check sums. |
Recursive Minimax Tree (10-way branching) |
Draw a root. Branch 10 times (for 0-9). For each, branch another 10 times. Tree depth = total '?'. $O(10^?)$. |
Greedy Mathematical Balancing |
Scale Balance / Seesaw |
Calculate initial sums of Left/Right. Count '?' on each side. Every pair of '?' Bob can "cancel" Alice's move if they sum to 9. |
Draw a seesaw. One side has current sum + X questions marks. Draw Alice trying to tip it, and Bob trying to level it using the 9-sum rule. |
Static Expression Evaluation |
Draw a single equation box: `Diff == (Right? - Left?) * 4.5`. If true, Bob wins. $O(N)$ scan. |
Massive game-state memoization table to store win/loss for every possible sum and '?' count. |
Five integer variables: `sumL`, `sumR`, `qL`, `qR`, and `netDiff`. $O(1)$ extra space. |
| 1928 |
Minimum Cost to Reach Destination in Time |
Find all possible paths from source to destination using DFS, then filter by those within `maxTime`. |
Path Enumeration Tree |
Draw nodes. Draw every single possible sequence of edges. Highlight many paths that exceed time and are discarded. $O(V!)$. |
Modified Dijkstra (or 2D DP) |
Time-Layered Graph State |
Run Dijkstra where the state is `(cost, node, time)`. Prune nodes if a cheaper cost is found for the SAME or LESS time. |
Draw a table where Rows = Nodes and Columns = Time (0 to maxTime). Fill cells with the minimum fee to reach that node at that time. |
Layered Node Processing |
Draw E edges being relaxed for each of the T time units. Total $O(E \\text{cdot maxTime})$. |
A list of all possible path strings or node sequences stored in memory. |
A 2D array `min_cost[maxTime + 1][n]` or a Priority Queue storing `[fee, node, time]`. |
| 1929 |
Concatenation of Array |
Loop once to copy elements to a new array, then loop a second time to append them again. |
Two-Stage Serial Copy |
Draw an array. Draw a new empty array double its size. Draw arrows for the first half, then a separate set for the second half. |
Single-Pass Index Mapping |
Array Duplication Mirror |
Loop from `i = 0` to `n-1`. In one step, set `ans[i] = nums[i]` and `ans[i + n] = nums[i]`. |
Draw `nums` on top. Draw `ans` (double length) below. Draw one arrow splitting into two "y-shape" paths to fill both halves simultaneously. |
Linear Block Allocation |
Draw one straight line across the output array. $O(N)$ time. |
Two temporary intermediate arrays before merging into the final result. |
A single pre-allocated array of size 2N. $O(1)$ extra space (excluding result). |
| 1930 |
Unique Length-3 Palindromic Subsequences |
Check every combination of 3 indices `(i, j, k)` to see if `s[i] == s[k]` and the subsequence is unique. |
Triple Nested Index Scan |
Draw three pointers `i`, `j`, `k`. Show them sliding in nested loops. $O(N^3)$. |
First/Last Index Pre-computation |
Character "Range Sandwiches" |
For each char (a-z), find its first and last occurrence. Count how many unique characters exist between these two indices. |
Draw the string. For 'a', circle the first 'a' and last 'a'. Highlight the middle section and count unique letters inside it using a Set. |
Constant-Factor Linear Scan |
Draw 26 horizontal lines (one per letter). For each line, draw one scan between the first/last markers. $O(26 \cdot N)$. |
A Hash Set of all possible 3-character strings generated during the N^3 scan. |
26-size arrays for `first_occurrence` and `last_occurrence`, and a temporary Set for middle-character counting. |
| 1931 |
Painting a Grid With Three Different Colors |
Backtracking to try every possible color (3 colors) for every cell in the m x n grid, checking adjacent constraints. |
Exponential Decision Tree (m*n depth) |
Draw a root node. Branch it 3 times (colors). For each branch, another 3. Total 3^{m \times n} leaf nodes. $O(3^{\text{MN}})$. |
Bitmask / Profile DP |
State Transition Adjacency Matrix |
Generate all valid vertical column profiles first. Then, use DP to count how many ways a column of type A can be placed next to type B. |
Draw a list of all 3-color permutations for one column. Draw arrows between "compatible" permutations (no same color in the same row). |
Iterative Matrix Layering |
Draw N columns. For each column, draw a box representing the 3^M states. Total $O(N \cdot 3^{M} \cdot 3^{M})$. |
Deep recursion stack for every single cell in the grid. |
A 1D array of size 3^M (storing counts for current column profiles). $O(3^M)$ space. |
| 1932 |
Merge BSTs to Create Single BST |
Try every possible way to pick a root and attach other trees into its leaves, then check if it's a valid BST. |
Factorial Permutation Search |
Draw N small trees. Show all N! ways to order them for merging. Cross out invalid BSTs. $O(N! \cdot N)$. |
Hash Map Root Lookup + DFS Validation |
Tree Piece Stitching (Puzzle) |
Map each root's value to its tree object. Identify the global root (appears as root but never as leaf). DFS from global root, "stitching" trees by replacing leaf values with root matches. |
Draw separate small trees. Draw "bridge" arrows from a leaf in Tree A to the root of Tree B if values match. Finally, perform one in-order traversal. |
Linear Graph Traversal |
Draw N nodes being visited exactly once in a connected component. $O(N)$ time. |
Multiple copies of tree structures being built and discarded during search. |
A Hash Map of `value -> TreeNode*` and a frequency map for leaf values to find the global root. |
| 1933 |
Check if String Is Decomposable Into Value-Equal Substrings |
Generate all possible partitions of the string and check if exactly one has length 2 and the rest have length 3. |
Backtracking Partition Tree |
Draw a string. Branch out every possible cut (length 2 or 3). Check if any path consumes the whole string correctly. |
Greedy Block Counting (Run-Length) |
Frequency Block Segmentation |
Iterate through the string, grouping identical consecutive characters. Count the remainder of each group length when divided by 3. |
Draw the string. Draw brackets over identical character runs. Below each bracket, write `length % 3`. Sum the remainders to see if they fit the "one 2, zero 1" rule. |
Single-Pass Scan Line |
Draw a single straight arrow over the string. $O(N)$ time. |
A list of strings or substrings created for every possible partition combination. |
Two simple integer counters: `countOfLength2` and a `boolean` flag for validity. $O(1)$ space. |
| 1934 |
Confirmation Rate (SQL) |
Correlated subqueries for every user: one to count 'confirmed' and another to count total, then divide. |
Row-by-Row Nested Scans |
Draw the `Signups` table. For every row, draw two separate magnifying glasses scanning the entire `Confirmations` table. $O(S \cdot C)$. |
LEFT JOIN with Conditional Aggregation |
Join-Aggregate Funnel |
Left Join `Signups` with `Confirmations`. Use `AVG(IF(action='confirmed', 1, 0))` grouped by `user_id`. `COALESCE` nulls to 0. |
Draw two tables side-by-side. Draw horizontal join lines. Group the results into boxes. Inside each box, calculate confirmed/total. |
Hash Join + Hash Aggregate Pipeline |
Draw the two tables feeding into a Join gear, then a Group-By gear. $O(S + C)$ time. |
Temporary tables generated for every single user in the system. |
In-memory hash buckets created by the SQL optimizer for the Group-By operation. |
| 1935 |
Maximum Number of Words You Can Type |
For every word in the sentence, iterate through every character in `brokenLetters` to check for any intersection. |
Nested Loop Intersection |
Draw a sentence. Circle each word. For each word, draw arrows comparing its letters to a list of broken letters. $O(\text{WordCount} \\text{cdot WordLen} \\text{cdot BrokenLen})$. |
Hash Set / Boolean Array Lookup |
Set-Filtering Pipeline |
Store `brokenLetters` in a boolean array of size 26. Split the sentence into words. Check if any char in a word exists in the boolean array. |
Draw the sentence. Draw a "Forbidden Gate" (Set). Words try to pass through. If a word contains a forbidden letter, it's blocked. Count those that pass. |
Linear Stream Processing |
Draw a single line moving through the sentence once, doing $O(1)$ checks per character. $O(N)$ time. |
Multiple string comparisons happening in-place without auxiliary structures. |
A fixed-size array/set of 26 booleans. $O(1)$ auxiliary space. |
| 1936 |
Add Minimum Number of Rungs |
Simulate climbing the ladder, adding one rung at a time whenever the next gap exceeds the max distance. |
Incremental Stepping Simulation |
Draw a ladder with a huge gap. Draw many small rungs being added one by one inside that gap. $O(\text{Total Height} / \text{Dist})$. |
Greedy with Modular Arithmetic |
Gap Quantization (Chunking) |
For each pair of rungs, calculate the gap. If `gap > dist`, use ans += (gap - 1) / dist to jump the logic. |
Draw two rungs. Draw a bracket for the gap. Write the division formula inside the bracket to show instant calculation. |
Single-Pass Scan Line |
Draw one straight arrow through all rungs. $O(N)$ time. |
A `while` loop counter incrementing many times in the stack. |
A single integer `count` variable. $O(1)$ space. |
| 1937 |
Maximum Number of Points with Cost |
For every cell in the current row, iterate through every cell in the previous row to find the max points after penalty. |
All-to-All Row Connections |
Draw two rows of C cells. Draw lines from every cell in Row 1 to every cell in Row 2. Total $O(R \cdot C^2)$. |
DP with Left/Right Prefix Max |
Penalty-Decay Waves |
Run two passes per row: one left-to-right (carrying over values with a -1 penalty) and one right-to-left. Take the max of both. |
Draw a row. Draw an arrow moving right, decreasing values by 1 each step. Draw another arrow moving left. Pick the peak at each cell. |
Linear Multi-Pass Scan |
Draw R rows. For each, draw two horizontal arrows (left and right). $O(R \cdot C)$ time. |
A 2D DP table of size R x C on the heap. |
Two 1D arrays (previous row and current row) swapped iteratively. $O(C)$ space. |
| 1938 |
Maximum Genetic Difference Query |
For each query, traverse from the node up to the root, calculating the XOR with `val` for every ancestor. |
Vertical Path Scanning |
Draw a tree. For each query, draw a line from the target node back to the root. Total $O(Q \\text{cdot Depth})$. |
Offline Queries + DFS + Binary Trie |
Trie-Based Bitwise Path Tracking |
Store queries in an adjacency list. DFS through the tree; as you enter a node, add its value to a Binary Trie. Answer queries at that node using Trie's max-XOR logic. Remove value on exit. |
Draw a tree and a separate Binary Trie. As the DFS "pointer" moves down, bits are added to the Trie. At the query node, show a "search path" through the Trie bits. |
Trie-Augmented DFS |
Draw N nodes (DFS) and Q queries (Trie search). $O((N + Q)$ * log(MaxVal)). |
Storing lists of paths or large query results naively. |
A Binary Trie (Tree of bit-nodes) and an offline query mapping. $O(N + Q)$ space. |
| 1939 |
Users That Actively Request Confirmation Messages |
Self-join the table on user_id, calculate the time difference for every single pair of requests per user. $O(N^2)$. |
Quadratic Time-Delta Grid |
Draw a timeline of requests. Draw an arrow from request 1 to 2, 1 to 3, 2 to 3, checking if they fall within 24 hours. |
Window Function (LAG/LEAD) |
The 24-Hour Sliding Window |
Use `LEAD(time_stamp)` to peek at the user's *next* request. Use `TIMESTAMPDIFF` to check if the gap is <= 24 hours. |
Draw a timeline. Move a 2-item viewing window left-to-right. Check the gap between the two items in the window. |
Partitioned Scan $O(N \log N)$ |
Draw a sorting pipeline partitioning by user, followed by a single read-head scanning adjacent pairs. |
Massive intermediate join tables. |
Internal DB window buffer. $O(N)$ space. |
| 1940 |
Longest Common Subsequence Between Sorted Arrays |
Use standard LCS DP for multiple arrays, or find common elements between the first two, then that result with the third, etc. |
Multi-Way DP Intersection |
Draw three 2D grids (LCS tables). Each table is $O(N^2)$. Very slow for many arrays. |
Frequency Counting (Since arrays are sorted & distinct) |
Histogram Frequency Filtering |
Count the occurrence of every number across all arrays. If a number's count equals the total number of arrays, it is in the LCS. |
Draw all arrays stacked. Draw a vertical line. If the line hits a number in every single row, circle it. |
Linear Multi-Scan |
Draw M arrays of size N. Draw one scan line through each. $O(M \cdot N)$ time. |
Large 2D DP matrices on the heap. |
A single integer Hash Map or array of size 100 (range of values) to store counts. $O(1)$ or $O(\text{Range})$. |
| 1941 |
Check if All Characters Have Equal Number of Occurrences |
For each character in the string, scan the entire string again to count its occurrences. |
Nested Scanning Grid |
Draw a string. For each character, draw a full scan line below it. $O(N^2)$. |
Hash Map / Frequency Array |
Histogram Leveling |
Iterate once to build a frequency map. Check if all values in the map are equal. |
Draw 26 buckets. Drop letters into buckets. Check if all non-empty buckets are filled to the same height. |
Linear Scan Bar |
Draw one straight line across the string. $O(N)$ time. |
Constant repeated scans without extra storage (except the loop index). |
A fixed-size integer array of length 26. $O(1)$ extra space. |
| 1942 |
The Number of the Smallest Unoccupied Chair |
For each arriving friend, scan through all chairs to find the first one that is unoccupied based on previous departure times. |
Linear Chair Search |
Draw a row of chairs. For every arrival, draw an arrow checking chair 0, then 1, then 2, until an empty one is found. $O(N^2)$. |
Two Min-Heaps (Priority Queues) |
Available vs. Occupied Pools |
Use one heap to store `(departureTime, chairNumber)` and another for `availableChairNumbers`. As people leave, move chairs back to the available heap. |
Draw two circles (pools). One pool has "Free Chairs" sorted. The other has "Busy People" sorted by time. Draw arrows transferring chairs between pools. |
Logarithmic Heap Processing |
Draw N arrivals. For each, draw an $O(\log N)$ heap extraction/insertion. Total $O(N \log N)$. |
A list of current chair statuses updated row-by-row. |
Two balanced Binary Heaps (represented as arrays) and a sorted event list. |
| 1943 |
Describe the Painting |
Initialize a massive array for the entire range. For each segment, loop through its range and add its color value to every index. |
Brute Force Range Filling |
Draw a long number line. For every segment, draw a horizontal bar covering the range, adding numbers to every point. $O(N \\text{cdot Range})$. |
Sweep Line / Difference Array |
Point-of-Change (Delta) Tracking |
Store changes at `start` (+val) and `end` (-val). Sort the points. Traverse the sorted points to calculate prefix sums for each interval. |
Draw a number line. Mark only the start and end points of segments with their + and - values. Sum them up as you move left to right. |
Sorted Point Traversal |
Draw N points. Sort them (log N). Scan them (linear). Total $O(N \log N)$. |
A dense array of size 10^5, even if segments are sparse. |
A TreeMap or a sorted list of "Change" objects. Space proportional to N, not the range. |
| 1944 |
Number of Visible People in a Queue |
For each person, look at every subsequent person to count how many are visible until a taller person blocks the view. |
Forward Raycasting |
Draw a series of sticks of varying heights. For each stick, draw arrows to every stick it can "see." $O(N^2)$. |
Monotonic Stack (Decreasing) |
Horizon Line Pruning |
Iterate from right to left. Use a stack to keep track of people who could be seen. Pop people who are shorter than the current person (they are visible). |
Draw a stack bucket. As you move left, "drop" people into the bucket. If the new person is taller than the top, "eject" the top and count the visibility. |
Linear Amortized Scan |
Draw a line across the queue. Note that each person is pushed and popped exactly once. $O(N)$ time. |
Nested loops scanning forward with no auxiliary storage. |
A Stack (Array or Linked List) storing heights of potential visible people. $O(N)$ space. |
| 1945 |
Sum of Digits of String After Convert |
Convert the string to a giant number string. Repeatedly convert that string back to a number to sum its digits K times. |
Repeated String-Number Conversion |
Draw a string. Draw a long digit sequence. Draw a new shorter string below it for each K iteration. $O(K \cdot N)$. |
Direct Integer Accumulation |
In-Place Digit Summing |
Perform the first conversion (char to int) and sum digits immediately. For the remaining K-1 steps, sum the digits of the previous integer. |
Draw the string. Below each letter, write its 1-2 digit value. Draw a circle around all digits and a single sum arrow. Repeat sum for K. |
Iterative Reduction Funnel |
Draw a wide block (string), funneling down to a smaller block (sum) K times. $O(N + K)$. |
Intermediate creation of multiple long string objects in memory. |
A single integer accumulator variable updated through basic modulo/division. $O(1)$ space. |
| 1946 |
Largest Number After Mutating Substring |
Generate all possible substrings, apply the mutation map to each, and compare results to find the lexicographically largest. |
$O(N^2)$ Substring Grid |
Draw a matrix where row is start index and col is end index. Color every cell to represent a string mutation check. |
Greedy One-Pass |
First-Improvement Window |
Scan left to right. Start mutating at the first digit where change > original. Stop mutating the moment change < original. |
Draw the string. Draw a "Mutation Brush". Show the brush painting over a segment of digits until it hits a "stop" condition. |
$O(N)$ Linear Scan |
Draw a single arrow from start to finish with a "Mutation Active" toggle. |
A collection of N strings stored in a list during comparison. |
In-place character array modification or single string builder. $O(N)$ space. |
| 1947 |
Max Compatibility Score Sum |
Generate all M! permutations of students and match them with mentors to calculate all possible total scores. |
Factorial Decision Tree |
Draw a root. Branch out M times, then M-1, then M-2. Total leaf nodes = M!. |
DP with Bitmask |
Bitmask State Grid |
Maintain a DP table where `dp[mask]` is the max score for students represented by the "on" bits in the mask matched with the first `count_bits(mask)` mentors. |
Draw a 1D array of size 2^M. Shade bits in the mask (e.g., 1011) to show which students are "assigned." |
$O(M \cdot 2^M)$ State Transition Graph |
Draw 2^M nodes. For each node, draw M outgoing arrows to the next state. |
A massive list of all permutation arrays. |
A memoization table/array of size 2^M. $O(2^M)$ space. |
| 1948 |
Delete Duplicate Folders in System |
For every folder, recursively build its full string representation (content + children) and compare with every other folder's string. |
$O(N^2)$ String Matching Matrix |
Draw folder icons. Draw lines connecting every folder to every other folder with a "String Compare" label. |
Trie + Merkle Hashing (Post-order) |
Subtree Fingerprinting |
Build a Trie. Use post-order traversal to generate a unique hash/string for each subtree. Store counts in a map. Delete subtrees with count > 1. |
Draw a Tree. At each node, write its "Fingerprint" (e.g., "a(b)(c)"). Color duplicate fingerprints with the same color. |
$O(N \\text{cdot Depth})$ Tree Traversal |
Draw the tree once. Show a single bottom-up "bubbling" of hash strings. |
Heavy overhead of redundant string objects for every path. |
A Trie (Tree structure) and a Hash Map for fingerprint deduplication. |
| 1949 |
Strong Friendship (SQL) |
For every friend pair, perform a subquery to count the intersection of their friend lists one by one. |
Row-by-Row Correlation Scan |
Draw the Friend table. For each row, draw two magnifying glasses scanning the entire table again. $O(N^2)$. |
Self-Join on Common Friends |
Triadic Closure Filter |
Join the table with itself on `user1_id` to find common friends. Group by the original friend pair and filter for `COUNT >= 3`. |
Draw three dots (A, B, C). Draw lines forming a triangle. The SQL finds how many "C"s exist for a fixed "A-B" line. |
Hash Join Aggregate |
Draw two tables feeding into a Join Gear, then a Group-By funnel. $O(N \log N)$ or $O(N)$. |
Massive intermediate result sets in temp storage. |
Database Hash Index buckets for fast friend-pair lookups. |
| 1950 |
Max of Min Values in All Subarrays |
For every possible subarray length L (1 to N), find every subarray of that length, find their minimums, and then find the max of those minimums. |
$O(N^3)$ Nested Loop Cube |
Draw a 3D space: [Start Index] x [Length] x [Min Scan]. Total volume N^3. |
Monotonic Stack + Range Extension |
Expansion Boundary Mapping |
For each element, find the nearest smaller element to the left and right. This defines the largest range where this element is the minimum. Update `ans[range_len]`. |
Draw the array. For each number, draw "arms" reaching left and right until they hit a smaller number. The distance between arms is the "Range Length". |
$O(N)$ Amortized Pass |
Draw one scan for "Left Smaller" and one for "Right Smaller". Then a final fill-in scan. |
Generating and storing all N^2 subarray minimums. |
A Monotonic Stack (Array) and three 1D arrays (`left`, `right`, `ans`). $O(N)$ space. |
| 1951 |
All the Pairs With the Maximum Number of Common Followers (SQL) |
Generate all possible user pairs (A, B) and for each pair, query the intersection of their follower lists. |
$O(U^2 \cdot F)$ Intersection Matrix |
Draw a grid of User pairs. In each cell, draw two lists and circle matching IDs. Highlight the cell with the most circles. |
Self-Join on Follower Column |
Relational Intersection Tally |
Join the table with itself on `follower_id` where `user1 < user2`. Group by `user1, user2` and use `RANK()` or `ALL` to find the maximum count. |
Draw the table with User and Follower columns. Draw arrows connecting different users sharing the same Follower ID. Count these connections per pair. |
Index-Based Hash Join |
Draw two copies of the Follower table. Connect them via a central "Follower ID" pivot. $O(N \log N)$ or $O(N)$ with indexing. |
Massive temporary intersection sets stored in database memory for every pair. |
Internal Hash Map/B-Tree index traversal on the `follower_id` column. |
| 1952 |
Three Divisors |
Loop from 1 to n and count how many numbers divide n without a remainder. |
Linear Scan Number Line |
Draw a line from 1 to n. Put a tick mark on every number that is a factor. Count the ticks. $O(N)$. |
Square of Prime Property |
Prime-Factor Geometric Mapping |
Check if n > 1, if \sqrt{n} is an integer, and if that square root is a prime number. Only such numbers have exactly 3 divisors. |
Draw the number n as a square area. Label the side length p. Show that the only factors are 1, p, and p^2. |
Constant Time Math Check |
Draw a single decision box: "Is \sqrt{n} prime?". $O(\text{sqrt}(N)$) or $O(1)$ if using a precomputed sieve. |
A simple integer counter incrementing in a loop. |
A single boolean or integer check after a square root operation. $O(1)$ space. |
| 1953 |
Maximum Number of Weeks for Which You Can Work |
Use backtracking to simulate every possible sequence of projects, ensuring no two consecutive weeks are the same project. |
Recursive Permutation Tree |
Draw a tree where each level is a week. Branches represent choosing a project. Prune if project[i] == project[i-1]. $O(2^N)$. |
Greedy Gap Filling / Pigeonhole Principle |
Seesaw / Balance Scale |
Find the max project count M and the sum of all other projects S. If M > S + 1, result is 2S + 1. Else, result is M + S. |
Draw one giant block (Max Project). Draw many small blocks (Others). Show the small blocks acting as "buffers" between segments of the giant block. |
Single-Pass Accumulator |
Draw a single arrow across the input array to find Sum and Max. $O(N)$ time. |
Call stack for recursion and lists to track remaining project counts. |
Two long integer variables: `max_val` and `total_sum`. $O(1)$ space. |
| 1954 |
Minimum Garden Perimeter to Collect Enough Apples |
Start with a side length of 2 and iteratively expand the square perimeter, calculating the total apples in the grid until the limit is reached. |
Concentric Expansion Layers |
Draw a small square. Draw a larger square around it. Calculate apple sum for the new border. Repeat until sum ≥ target. $O(N)$. |
Binary Search on Cubic Formula |
Monotonic Function Search |
The total apples in a square of half-side n is 2n(n+1)(2n+1). Binary search for the smallest n that satisfies the condition. |
Draw a graph of f(n) = \text{Apples}. Draw a horizontal line for the target. Use binary search (left, right, mid) to find the intersection. |
Logarithmic Range Halving |
Draw a number line. Repeatedly cut it in half log(Max) times. $O(\log N)$ time. |
Variables to store running totals of apples per layer. |
Three integer pointers for Binary Search: `low`, `high`, `mid`. $O(1)$ space. |
| 1955 |
Count Number of Special Subsequences |
Generate every possible subsequence (2^N) and check if it follows the pattern 0...01...12...2. |
Exponential Subsequence Tree |
Draw an array. Branch out "Pick/Don't Pick" for every element. Filter the 2^N results. $O(2^N)$. |
Dynamic Programming (3-State Machine) |
State Transition Flowchart |
Maintain three counts: `dp[0]` (subsequences ending in 0), `dp[1]` (ending in 1), `dp[2]` (ending in 2). Update based on the current number. |
Draw three boxes: [0], [1], [2]. If current is '1', draw arrows showing it can append to a [0] or another [1], doubling the ways. |
Linear Scan DP |
Draw an arrow moving across the array. Below each step, update the 3 DP variables. $O(N)$ time. |
Storing every subsequence string to validate the pattern. |
An array of 3 integers (or 3 variables) to store the counts. $O(1)$ extra space. |
| 1956 |
Minimum Time For K Virus Variants to Spread |
Run BFS from every single point on the massive 2D grid continuously. Time Limit Exceeded instantly. |
Infinite Ripple Expansion |
Draw a massive grid. Draw thousands of expanding circles from every single node until they overlap. |
Binary Search on Answer + Intersection Checks |
The Bounding Box Overlap |
Binary search the "Days" (D). For a given D, each virus spreads in a diamond shape (Manhattan distance). Check if there is any point in the grid covered by at least K diamonds. |
Draw the virus starting points. For a guess D, draw a diamond of radius D around each. If K diamonds overlap at any single pixel, the guess is valid. |
Logarithmic Search $O(\log(\\text{text}{\text{Max}})$ \cdot \text{Points}^3) |
Draw a timeline cut in half. At each step, draw a check matrix for the virus coordinates. |
Massive 2D grids. |
Variables for boundaries. $O(1)$ extra space. |
| 1957 |
Delete Characters to Make Fancy String |
Check every possible substring and remove characters if they violate the "no 3-consecutive" rule, repeatedly scanning. |
Repeated String Re-scans |
Draw the string. Circle 3 identical chars. Redraw the string without one. Repeat until clean. $O(N^2)$. |
Single-Pass Greedy Scan |
Sliding Window Filter |
Iterate once. Keep a character only if it is not the same as the previous two characters in the result string. |
Draw the string. Below it, draw a "Result Bucket". Drop characters in unless the last two in the bucket match the current one. |
$O(N)$ Linear Flow |
Draw a single straight arrow from start to end of the input string. |
Multiple intermediate string objects created during deletions (Garbage Collection heavy). |
A single StringBuilder or character array of size N. $O(N)$ space. |
| 1958 |
Check if Move is Legal |
For every cell on the board, check if placing a piece there completes a valid line in any direction. |
Full Grid Multi-directional Scan |
Draw an 8x8 grid. For every single cell, draw 8 arrows stretching out to the edges. $O(64 \cdot 8 \cdot 8)$. |
8-Directional Raycasting from Move |
Compass Point Expansion |
From the specific `(r, c)` coordinate, fire "rays" in 8 directions. Check if a ray hits an opposite color and ends with the same color. |
Draw a central dot (the move). Draw 8 arrows (Compass). Along each arrow, check for the pattern: `Opposite...Opposite Same`. |
$O(1)$ Constant Bound Scan |
Draw 8 lines. Each line is max 8 units long. Indicate 8 * 8 = 64 operations (Constant for an 8x8 board). |
No extra structures, but high repeated logic if scanning every cell. |
A simple 2D direction array `[[-1,0], [1,0]...]` and integer coordinate variables. $O(1)$ space. |
| 1959 |
Minimum Total Space Wasted With K Resizing Operations |
Try resizing at every possible index and for every possible count up to K using recursion. |
Recursive Branching (Partitioning) |
Draw an array. Branch into "Resize here" or "Don't resize". Tree depth = N, K limits branches. $O(N^K)$. |
DP with Interval Precomputation |
Partitioning State Matrix |
`dp[i][k]` is min waste for first `i` elements with `k` resizes. Precompute max element in any range `[j, i]` to find waste. |
Draw a 2D table (Index i vs. Resizes k). For a cell, look at all previous indices `j` and calculate waste based on the max value in range `[j, i]`. |
$O(N^2 \cdot K)$ DP Table |
Draw a 2D grid of size N x K. Indicate each cell takes $O(N)$ time to compute by scanning previous row. |
Exponential recursion stack tracking every partition combination. |
A 2D array `dp[N][K]` and potentially a precomputed 2D `max_range[N][N]` table. $O(N^2)$ space. |
| 1960 |
Maximum Product of the Length of Two Palindromic Substrings |
Find every palindrome. For every pair, check if they overlap. Multiply lengths. $O(N^3)$. |
Quadratic Pair Checking |
Draw the string. Bracket every palindrome. Draw lines connecting every bracket to every other bracket. |
Manacher's Algorithm + Prefix/Suffix Max |
The Dual Max-Span Tracker |
1. Use Manacher's to find max palindrome radius at every center in $O(N)$. 2. Build `left_max` array (max palindrome ending before i) and `right_max`. 3. Iterate i to maximize `left_max[i] * right_max[i+1]`. |
Draw the string. Draw an array above it tracking the biggest palindrome seen so far from the left. Draw one below for the right. Pick the index i where Top \times Bottom is largest. |
Three Linear Passes $O(N)$ |
Draw 3 parallel lines. Pass 1: Manacher's. Pass 2/3: Prefix/Suffix filling. |
Storing all palindromes. |
Arrays for radii, left, and right. $O(N)$ space. |
| 1961 |
Check If String Is a Prefix of Array |
Concatenate the entire array into one long string first, then check if it starts with the target string. |
Full String Expansion |
Draw all array elements being merged into one giant box. Then draw a comparison pointer. $O(\text{Total Chars in Array})$. |
Early Exit Iterator |
Pointer-to-String Segment Matching |
Iterate through `words`. Match each word against the target `s` using a pointer. If they mismatch or `s` ends mid-word, return false. |
Draw the target string `s` as a long bar. Below it, draw array words as small blocks. Check if blocks align perfectly with the bar. |
Linear Scan with Short-Circuiting |
Draw a single line moving across `s`. Note that we stop as soon as `s` is covered or a mismatch occurs. $O(\text{min}(\text{len}(s)$, len(total_words))). |
A newly created, massive string object in the heap. |
$O(1)$ auxiliary space (just a few integer pointers/indices). |
| 1962 |
Remove Stones to Minimize the Total |
In each of the K operations, sort the entire array to find the largest pile, then halve it. |
Repeated Sorting Funnel |
Draw K funnels labeled "Sort". After each funnel, draw the first element being updated. $O(K \cdot N \log N)$. |
Max-Priority Queue (Heap) |
Heap Bubble-Down Mechanics |
Insert all piles into a Max-Heap. Extract the top, halve it, and push it back K times. Finally, sum the heap. |
Draw a Binary Tree (Heap). Highlight the root being popped and a smaller value being "bubbled down" to its correct spot. |
Logarithmic Re-balancing Graph |
Draw N nodes. Then draw K paths of length log N. Total $O(N + K \log N)$. |
Multiple temporary copies of sorted arrays during the K loops. |
A standard Max-Heap structure (contiguous array representation). $O(N)$ space. |
| 1963 |
Minimum Number of Swaps to Make the String Balanced |
Generate all permutations of swaps and use recursion to find the shortest path to a balanced state. |
State-Space BFS Tree |
Draw a tree where each node is a string version and edges are swaps. Tree grows exponentially. $O(N!)$. |
Greedy "Unbalanced" Counter |
Stack-Based Cancellation (Logical) |
Traverse the string. Track "open" brackets. If you see a "close" and `open > 0`, decrement `open`. Otherwise, it's an "imbalance". Result is `(imbalance + 1) / 2`. |
Draw a "Balance" scale. Add 1 for `[` and subtract 1 for `]`. If scale goes negative, note the "max dip". |
Single-Pass Linear Scan |
Draw one straight line across the bracket sequence. $O(N)$ time. |
A massive queue/set for BFS to track visited string states. |
Two integer variables: `open_count` and `swaps`. $O(1)$ extra space. |
| 1964 |
Find the Longest Valid Obstacle Course at Each Position |
For each position `i`, check all previous positions `j < i` and find the max valid sequence length. |
$O(N^2)$ Backwards Lookback |
Draw an array. For each element, draw arrows pointing to all preceding elements. $O(N^2)$. |
Patience Sorting (LIS Variation) |
Binary Search in Active Tails |
Maintain a `tails` array where `tails[i]` is the smallest tail of all increasing subsequences of length `i+1`. Use binary search to find insertion point. |
Draw a row of "piles" (like cards). Each new obstacle either starts a new pile or updates an existing one using binary search logic. |
Logarithmic Insertion Timeline |
Draw N elements. For each, draw a binary search tree lookup/update. $O(N \log N)$. |
A 1D DP table of size N. |
A `tails` array that grows up to size N. $O(N)$ space. |
| 1965 |
Employees With Missing Information (SQL) |
Use correlated subqueries in the SELECT clause to check for the existence of information in the other table. |
Row-by-Row Membership Testing |
Draw Table A. For every row, draw a loop that scans every row of Table B. $O(A \cdot B)$. |
FULL OUTER JOIN (or UNION of LEFT JOINs) |
Venn Diagram Symmetric Difference |
Select IDs where information is missing in either the Employees table OR the Salaries table, then sort. |
Draw two overlapping circles. Shade the parts that do NOT overlap. Label the shaded regions as the result set. |
Hash Join / Index Merge Pipeline |
Draw two sorted IDs lists being merged. Indicate that non-matches are immediately identified. $O(N \log N)$ or $O(N)$. |
Temp tables created for every row check if indexes aren't present. |
In-memory Hash Table for the join operation. |
| 1966 |
Binary Searchable Numbers in an Unsorted Array |
For every element in the array, simulate a binary search and see if it successfully finds that specific element. |
N-Tree Simulation Grid |
Draw the array. Below each index, draw the specific path a binary search would take to find that index. $O(N \log N)$. |
Prefix Max & Suffix Min Pass |
Squeeze-Bound Validation |
An element is searchable if it is greater than all elements to its left and smaller than all elements to its right. |
Draw two arrows above the array: one scanning Max from Left, one scanning Min from Right. Circle indices where both conditions meet. |
Linear Multi-Pass Scan |
Draw two horizontal parallel arrows (Prefix/Suffix) over the array box. $O(N)$. |
A collection of log N search paths for every element. |
Two 1D arrays `preMax[N]` and `sufMin[N]`. $O(N)$ space. |
| 1967 |
Number of Strings That Appear as Substrings in Word |
For each string in the pattern list, perform a standard string search (like `indexOf`) against the target word. |
Independent String Comparison Bars |
Draw the patterns list. For each pattern, draw a sliding window across the word. $O(\text{Patterns} \\text{cdot PatternLen} \\text{cdot WordLen})$. |
KMP or Optimized Built-in Search |
Pattern Matching Pipeline |
Iterate through patterns and use the most efficient string matching available to count hits. |
Draw patterns as small blocks. Draw the word as a long conveyor. Check if each block "fits" into any part of the conveyor. |
Summed Linear Search |
Draw a timeline where each pattern is checked in a single linear pass. $O(\text{Total Length of Patterns})$. |
Multiple temporary string slices generated during the search. |
Pointer-based indexing into existing pattern strings. $O(1)$ extra space. |
| 1968 |
Array With Elements Not Equal to Average of Neighbors |
Generate all permutations of the array and check the "not equal to average" condition for each. |
Factorial Search Space Tree |
Draw a tree of permutations. Highlight paths that fail the average condition until a valid one is found. $O(N!)$. |
Sort & Interleave (Wiggle Sort) |
Peak-Valley Waveform |
Sort the array. Interleave the first half with the second half so that every element is surrounded by much larger or smaller ones. |
Draw a "mountain range" graph. Place the smallest numbers in valleys and largest on peaks to ensure no element is the average of neighbors. |
Single Sorting Funnel |
Draw the array falling into a "Sort" box, then splitting into two "Shuffler" streams. $O(N \log N)$. |
A massive set of all possible array permutations. |
A single output array of size N. $O(N)$ space. |
| 1969 |
Minimum Non-Zero Product of the Array Elements |
Calculate all numbers in the range [1, 2^p - 1], then try swapping bits between all pairs to find the min product. |
Exponential Bit-Swap Matrix |
Draw all numbers. Show arrows for every possible bit exchange between every pair. $O(2^p!)$. |
Greedy Pairing + Modular Exponentiation |
Extremes Coupling (1 and 2^p-2) |
Observe that pairing x and y to make them 1 and x+y-1 minimizes their product. We can form 2^{p-1}-1 such pairs of (2^p-2). |
Draw a line of numbers. Connect the 1st with the 2nd-to-last, 2nd with 3rd-to-last, etc. Result is (2^p-2)^{(2^{p-1}-1)} \times (2^p-1) \pmod{10^9+7}. |
Logarithmic Math Calculation |
Draw a single calculation box representing the modular exponentiation formula. $O(p)$. |
An exhaustive list of all 2^p integers. |
$O(1)$ extra space; just a few long integer variables for the formula. |
| 1970 |
Last Day Where You Can Still Cross |
For every single day, rebuild the grid and run a BFS from top to bottom to check if a path exists. |
$O(\text{Days} \\text{cdot Row} \\text{cdot Col})$ Grid Scanning |
Draw a sequence of grids for Day 1, Day 2, etc. For each, draw a BFS wave. $O(D \cdot R \cdot C)$. |
Binary Search on Days + BFS/DFS |
Search Space Halving (Connectivity) |
Binary search for the latest day D. For a mid-day, check if the grid is crossable. If yes, search later; if no, search earlier. |
Draw a timeline of days. Pick the middle day. Draw the grid with "water" cells filled. Use a "pathfinding snake" to check crossing. |
Logarithmic BFS Chain |
Draw a binary search tree (log D). Inside each node, draw an $O(R\cdot C)$ grid scan. $O(R\cdot C \cdot \log(R\cdot C)$). |
Re-allocating the entire grid for every daily connectivity check. |
A single reusable visited array/grid for the BFS/DFS checks. $O(R\cdot C)$ space. |
| 1971 |
Find if Path Exists in Graph |
Try every possible path from source to destination using simple recursion without tracking visited nodes (leads to infinite cycles). |
Infinite Cyclic Graph Walk |
Draw a source node. Draw arrows moving back and forth between two nodes indefinitely, showing a path that never ends. $O(\text{Infinite})$. |
Union-Find (Disjoint Set Union) |
Disjoint Set Forest |
For each edge, connect the two nodes in the DSU structure. Finally, check if find(source) == find(destination). |
Draw dots for nodes. For each edge, draw a line. Use "clouds" to circle connected components. Check if source/dest are in the same cloud. |
Path Compression Tree Flatting |
Draw a deep tree. Draw an arrow bypassing intermediate nodes to point directly to the root. $O(E α(V)$). |
Deep recursive stack that crashes on large graphs. |
A 1D array `parent[N]` representing the forest structure. $O(V)$ space. |
| 1972 |
First and Last Call On the Same Day (SQL) |
For every user and every day, use separate subqueries to find the MIN(time) and MAX(time) and join them back. |
Multi-Scan Row Correlation |
Draw a row. Draw two magnifying glasses: one scanning the table for the earliest call, one for the latest. $O(N^2)$. |
Window Functions (ROW_NUMBER/RANK) |
Temporal Partitioning Buckets |
Partition data by user and day. Sort by time. Pick rows where rank=1 (first) and rank=N (last). Compare caller/receiver IDs. |
Draw columns of rows. Group them into boxes by "User-Day". Circle the very top and very bottom row in each box. |
Sorted Stream Processing |
Draw a sorted table. Show a single pass that identifies the boundaries of each user-day group. $O(N \log N)$. |
Temporary tables generated for every individual row comparison. |
Internal Hash partitions used by the SQL engine for partitioning. |
| 1973 |
Count Nodes Equal to Sum of Descendants |
For every node, launch a full recursive search on its children to sum all descendants. |
Recursive Redundancy Tree |
Draw a tree. For each node, draw overlapping "summation waves" that visit lower nodes multiple times. $O(N^2)$. |
Post-order Traversal (Bottom-Up) |
Value Bubbling (Accumulation) |
Recursive DFS where each node returns the sum of its subtree to its parent. The parent then checks the condition and returns. |
Draw a tree. At the leaves, write their values. Draw arrows up. Each parent writes "My Val + Child Sums". Circle matches. |
Single-Pass Tree Depth |
Draw a tree with a single snake-like line visiting every node exactly once. $O(N)$. |
Large call stack with repeated visits to the same memory addresses. |
DFS recursion stack proportional to the height of the tree. $O(H)$ space. |
| 1974 |
Minimum Time to Type Word Using Special Typewriter |
Simulate the typewriter moving character by character, always moving clockwise. |
Linear Circular Sweep |
Draw a clock. To go from 'a' to 'z', draw an arrow all the way around the long way. $O(N \cdot 26)$. |
Greedy Modular Distance |
Clockwise vs Counter-Clockwise Comparison |
Calculate the distance between current and target characters. Min(dist, 26-dist) is the movement time. Add 1 for typing. |
Draw a circular alphabet 'a' through 'z'. Draw two arrows from 'a' to 'c'—one short (right), one long (left). Pick the short one. |
Linear Scan $O(N)$ |
Draw a straight line through the target word. Each step takes constant time. $O(\text{WordLength})$. |
Looping through 26 characters for every movement step. |
Zero extra data structures; just an integer variable for current position. $O(1)$ space. |
| 1975 |
Maximum Matrix Sum |
Try all possible adjacent swaps to see which configuration maximizes the sum. |
Combinatorial Grid Toggling |
Draw a 2x2 matrix. Show every possible way to flip pairs of signs (+ to -). $O(2^(N\cdot N)$). |
Greedy Parity Property |
Negative Sign Migration |
Notice that you can "move" a negative sign anywhere. If the count of negatives is even, they all cancel. If odd, one remains at the smallest absolute value. |
Draw a grid. Draw arrows "pushing" negative signs toward each other until they vanish or only one tiny negative is left. |
Single Pass Grid Reduction |
Draw an M x N grid. Draw a single scan arrow that tallies the sum, negative count, and min absolute value. $O(N^2)$. |
Recursive state-space tree of grid states. |
Three integer variables: `total_sum`, `min_abs`, and `neg_count`. $O(1)$ space. |
| 1976 |
Number of Ways to Arrive at Destination |
DFS to find every possible path from 0 to n-1, filtering by the shortest total weight found. |
Path Explosion Tree |
Draw node 0 branching into all neighbors, branching further. Show the number of paths growing exponentially. $O(V!)$. |
Dijkstra + DP (Counting) |
Weighted Shortest-Path Relaxation |
Use a Min-Heap for Dijkstra. When relaxing an edge, if a new shortest distance is found, reset path count; if equal, add to path count. |
Draw nodes with labels: `(minDist, ways)`. As you "relax" an edge, update the label. Use different colors for updated paths. |
Priority-Queue Driven Scan |
Draw E edges being processed. For each, show a log(V) heap operation. $O(E \log V)$. |
A list of all path sequences (high memory cost). |
A Min-Heap and two 1D arrays: `dist[N]` and `ways[N]`. $O(V)$ space. |
| 1977 |
Number of Ways to Separate Numbers |
Backtracking to try every possible split of the string into numbers, checking if the sequence is non-decreasing. |
Recursive Partition Tree |
Draw a string. Branch at every character. Label branches with the number formed. Cross out invalid paths. $O(2^N)$. |
DP + LCP (Suffix) + Prefix Sums |
Windowed State Transition Matrix |
`dp[i][len]` is the number of ways to form a valid sequence ending at index `i` with the last number having length `len`. Use LCP to compare strings in $O(1)$. |
Draw a 2D grid where X-axis is string index and Y-axis is length. Draw arrows summing the previous row's valid lengths to fill the current cell. |
Quadratic Dynamic Programming |
Draw an N x N grid. Explain that each cell is computed in $O(1)$ via prefix sums. $O(N^2)$. |
Massive recursive tree with string slicing for comparisons. |
A 2D DP array `dp[N][N]` and an $O(N^2)$ LCP matrix. $O(N^2)$ space. |
| 1978 |
Employees Whose Manager Left the Company (SQL) |
Use a dependent subquery for every row to check if the `manager_id` exists in the `employee_id` column. |
Row-by-Row Membership Scan |
Draw the table. For one row, draw a loop that scans the entire `employee_id` column of the same table. $O(N^2)$. |
Self-Anti-Join / WHERE NOT IN |
Venn Diagram Exclusion |
Filter rows where salary < 30,000. Use `WHERE manager_id NOT IN (SELECT employee_id FROM Employees)`. |
Draw two circles. Circle 1: Employees with salary < 30k. Circle 2: All Employee IDs. Highlight parts of Circle 1 not in Circle 2. |
Hash Join / Index Seek |
Draw a sorted index. Show the engine quickly skipping rows that have a manager match. $O(N \log N)$ or $O(N)$. |
Repeated full-table scans in database cache. |
In-memory Hash Table built from the `employee_id` column for fast lookups. |
| 1979 |
Find Greatest Common Divisor of Array |
Sort the array, take the first and last elements, and then loop from 1 to the smaller number to find the max divisor. |
Linear Factor Scan |
Draw the small number X. Draw a line from 1 to X. Check every tick mark. $O(N \log N + X)$. |
Euclidean Algorithm (Recursive/Iterative) |
Subtraction/Modulo Reduction |
Find min/max in one pass. Apply `gcd(a, b) = gcd(b, a % b)` until `b == 0`. |
Draw two bars of lengths A and B. "Cut" the longer bar by the length of the shorter one repeatedly until only the GCD length remains. |
Logarithmic Descent |
Draw a pair of numbers shrinking rapidly. Show that they reach zero in log(min(A,B)) steps. $O(N + \log(\text{min}(A,B)$)). |
A full copy of the sorted array in memory. |
Two primitive integer variables for min/max and the recursion stack (depth $O(\log N)$). |
| 1980 |
Find Unique Binary String |
Generate all 2^n binary strings of length n and check which one is not present in the input list. |
Exhaustive Permutation Grid |
Draw a table with 2^n rows. Cross out the n rows provided. Show the massive number of remaining candidates. $O(2^N)$. |
Cantor's Diagonalization |
Diagonal Bit Toggling |
For the i-th binary string in the input, pick its i-th character and flip it (0 to 1, or 1 to 0). The resulting string is guaranteed to be unique. |
Draw an n \times n matrix of the input strings. Circle the diagonal from top-left to bottom-right. Write the flipped bits below. |
Single-Pass Diagonal Scan |
Draw a line slicing through the input matrix diagonally. One operation per string. $O(N)$. |
A Hash Set containing up to 2^n binary strings. |
A single StringBuilder or character array of length N. $O(N)$ space. |
| 1981 |
Minimize the Difference Between Target and Chosen Elements |
Recursive backtracking: pick one element from each row and compute every possible sum. |
Exponential Decision Tree |
Draw a row. Branch C times (columns). From each branch, branch another C times. Total C^R leaf nodes. |
DP with Bitset Optimization |
Bitset Left-Shift Propagation |
Represent reachable sums in a bitset. For each row, create a new bitset by OR-ing current reachable sums shifted by each value in the row. |
Draw a long horizontal ribbon of 1s and 0s. For each element x in a row, shift the entire ribbon left by x and overlay (OR) it. |
Row-Linear State Pass |
Draw R rows. For each, show a bitwise shift/OR operation. $O(R \cdot \\text{text}{\text{max}\_\text{sum}} / 64)$. |
Deep recursion stack storing R choices per path. |
A single Bitset/Boolean array of length 4901. $O(\\text{text}{\text{target}\_\text{sum}})$ space. |
| 1982 |
Find Array Given Subset Sums |
Try every possible subset sum combination to match the given list of 2^n sums. |
Subset Sum Permutation Matrix |
Draw a list of 2^n sums. Show arrows attempting to "group" them into original elements. $O(2^n \cdot n)$. |
Recursive Divide and Conquer (Sign Partitioning) |
Recursive Binary Split Tree |
Find the smallest absolute difference d (potential array element). Split the 2^n sums into two halves (one with d, one without). Repeat. |
Draw a list of numbers. Draw two arrows splitting it into two smaller lists. Color code which list contains the '0' sum. |
Logarithmic Depth Halving |
Draw a tree of height n. Each level involves a linear scan of current sums. $O(n \cdot 2^n)$. |
Massive nested loops and hash maps to track subset combinations. |
Recursion stack of depth n, with sorted lists at each level. |
| 1983 |
Widest Pair of Indices With Equal Range Sum |
Check every pair (i, j) and calculate sums for both arrays to see if they match. |
$O(N^2)$ Nested Loop Grid |
Draw two arrays side by side. Draw brackets of varying widths (i, j) over both. $O(N^2)$. |
Prefix Sum + Hash Map (Diff Tracking) |
Difference Trendline Convergence |
Track `diff = sum1[i] - sum2[i]`. If `diff` at index j equals `diff` at index i, the sum of ranges between i and j is equal. |
Draw a table: `Index | Sum1 | Sum2 | Diff`. Circle the first and last occurrence of the same `Diff`. |
Single Linear Pass |
Draw a single arrow scanning from left to right. $O(N)$. |
Generating all possible range sums and storing them for comparison. |
A Hash Map storing `diff -> first_index_seen`. $O(N)$ space. |
| 1984 |
Min Diff Between Highest and Lowest of K Scores |
Generate all possible subsets of size K, find max/min for each, and track the global minimum. |
Combinatorial Subset Search |
Draw combinations nCr(n, k). For each group, calculate difference. $O(2^n)$. |
Sorting + Fixed-Size Sliding Window |
Sorted Proximity Window |
Sort the scores. The minimum difference for K scores must occur in a contiguous window of length K. Check `nums[i+k-1] - nums[i]`. |
Draw sorted dots on a line. Draw a bracket of width K. Slide the bracket across the dots and measure its "span." |
Sorting-Dominated Timeline |
Draw an $O(N \log N)$ sorting funnel followed by an $O(N)$ sliding scan. |
Auxiliary lists to store every generated subset. |
In-place sort and two integer pointers for the window. $O(1)$ extra space. |
| 1985 |
Find the Kth Largest Integer in the Array |
Convert all strings to huge integers (or doubles), sort them, and pick the k-th. |
Type-Conversion Sorting Funnel |
Draw strings turning into giant number blocks. Funnel them into a sort engine. $O(N \log N \cdot \\text{text}{\text{MaxLen}})$. |
Custom Sort (Length then Lexicographical) |
String-Length Bucket Sorting |
Sort the array of strings using a custom comparator: if lengths differ, longer is larger; if equal, use `string::compare`. |
Draw strings of different lengths. Group by length. Inside groups, sort alphabetically. Find the k-th from the end. |
String-Aware Sort Complexity |
Draw N elements being compared. Each comparison takes $O(L)$ where L is length. $O(N \log N \cdot L)$. |
Memory overhead from creating many large BigInteger objects. |
A Min-Heap (size K) or in-place sorting of original string array. $O(K \cdot L)$ or $O(1)$ extra space. |
| 1986 |
Minimum Number of Work Sessions to Finish the Tasks |
Recursively try all possible permutations of tasks and greedily assign them to sessions until all are done. |
Decision Tree Permutation |
Draw a root. Branch for every possible first task. At level 2, branch for every remaining task. Total leaf nodes: N!. |
DP with Bitmask (State: Mask of completed tasks) |
State-Space Lattice |
Use a bitmask to represent completed tasks. For each state, iterate through all submasks to find the optimal last session. |
Draw a column of 16-bit binary numbers. Draw arrows from "simpler" masks (few bits set) to "complex" masks. |
$O(3^N)$ Submask Enumeration Graph |
Draw a pyramid. Each level k represents masks with k bits. Total transitions follow the \sum \binom{n}{k} 2^k = 3^n logic. |
Massive recursion stack with N levels of task lists. |
A 1D array of size 2^N (storing min sessions). $O(2^N)$ space. |
| 1987 |
Number of Unique Good Subsequences |
Generate every possible subsequence, store in a Hash Set to ensure uniqueness, then filter for those starting with '1' (plus '0'). |
Exponential Power Set |
Draw the string. Branch out 2^N times for every "pick or skip" decision. Circle unique results. |
Dynamic Programming (Two-State: Ends in 0, Ends in 1) |
Linear State Transition Flow |
Maintain `ends_with_zero` and `ends_with_one`. When encountering '1', it can be appended to all existing subsequences to form new ones ending in 1. |
Draw two boxes labeled '0' and '1'. Use a single scan arrow. Update the boxes based on the current digit, subtracting overlaps. |
Single-Pass Linear Scan |
Draw one straight line across the string. Each step is $O(1)$. Total $O(N)$. |
A Hash Set containing up to 2^N string objects. |
Two long integer variables and a boolean for the existence of '0'. $O(1)$ space. |
| 1988 |
Find Cut-Off Score for Each School (SQL) |
For each school, perform a subquery that scans the entire Exam table to find all scores that meet capacity, then take the minimum. |
Row-by-Row Correlation Scan |
Draw the Schools table. For each row, draw a loop that scans the Exam table. $O(S \\text{times} E)$. |
LEFT JOIN + Aggregation |
Relational Bucket Filtering |
Join Schools and Exams on `capacity >= student_count`. Group by school and select the minimum score. Use `COALESCE` for non-matches. |
Draw two tables. Draw lines connecting schools to all valid exam scores. Group by school and pick the lowest value in each group. |
Index-Optimized Hash Join |
Draw a B-tree index on the Score column. Show the engine skipping scores that don't meet student requirements. $O(S \log E)$. |
Repeated full-table scans slowing down the database cache. |
In-memory result sets generated during the Group By aggregation. |
| 1989 |
Maximum Number of People That Can Be Caught in Tag |
For every 'catcher', search the surrounding indices (within distance k) for an 'uncaught' player. |
Nested Range Scanning |
Draw the array. For every '1' (catcher), draw a bracket of width 2k. Check every cell inside. $O(N \\text{times} k)$. |
Two Pointers (Greedy) |
Linear Synchronized Pointers |
Move one pointer for catchers and another for players. If a player is too far left, move them. If within range, catch and move both. Else move catcher. |
Draw the array. Place pointer i on the first catcher and pointer j on the first player. Draw "catch" arrows and slide pointers right. |
Double Linear Scan |
Draw two parallel arrows moving across the array at different speeds. Both finish in $O(N)$. |
A list of indices for players and catchers if separated first. |
Exactly two integer variables used as indices on the original array. $O(1)$ space. |
| 1990 |
Count the Number of Experiments (SQL) |
Group the table by platform and experiment name to count successes, but missing combinations won't appear. |
Group-By with Missing Keys |
Draw the original table. Circle blocks of data. Notice that "Web - Experiment 3" might be totally missing from the circles. |
Cross Join (Master Template) + Left Join |
Cartesian Template Overlay |
Create a "Master Table" by Cross Joining all Platforms and all Experiments. Left Join the real data to this template to get counts. |
Draw a grid of all possible (Platform, Exp) pairs. Draw the actual data as "stamps" on this grid. Count the stamps per cell. |
Fixed-Size Grid Mapping |
Draw a small 3 \times 3 grid. Show that the template creation is constant $O(1)$ and the data join is $O(N)$. |
Missing data rows lead to incomplete reports. |
A small in-memory constant table created by the Cross Join. |
| 1991 |
Find the Middle Index in Array |
For every index i, iterate left to sum 0 \dots i-1 and iterate right to sum i+1 \dots n-1. |
Nested Scanning (O(N^2)) |
Draw an array. For each cell, draw two arrows: one moving left to the start and one moving right to the end. |
Prefix Sum (Total Sum Balance) |
Running Total Scale |
Calculate total sum. Iterate once, maintaining a `leftSum`. The `rightSum` is simply `totalSum - leftSum - currentElement`. |
Draw a "Total Sum" bar. Draw a slider moving across it. The part to the left of the slider is `leftSum`, the part to the right is `rightSum`. |
Single-Pass Linear Timeline |
Draw one straight line across the array box. Mark two constant-time operations per cell. $O(N)$. |
No extra storage besides simple sum variables. |
A single `totalSum` integer and a `leftSum` integer. $O(1)$ space. |
| 1992 |
Find All Groups of Farmland |
For every '1' encountered, launch a full BFS/DFS to find its boundaries, even if previously visited. |
Redundant Area Coverage |
Draw a grid with overlapping shaded regions. Show the scanner revisiting the same cells multiple times. |
Greedy Boundary Detection (Top-Left to Bottom-Right) |
Rectangle Corner "Snap" |
Scan the grid linearly. When you find a '1' that hasn't been visited (or is a top-left corner), expand right and down to find the far corner. Mark the area as visited. |
Draw a grid. Circle the top-left '1'. Draw two perpendicular arrows (Right and Down) to define the rectangle boundary. Shade it and move the scanner past it. |
Total Cell Visitation Map |
Draw the grid. Show that each cell is visited/marked exactly once. $O(M \\text{times} N)$. |
Massive recursive stack frames for every cell in an island. |
In-place grid modification or a 2D boolean `visited` array. $O(M \\text{times} N)$ space. |
| 1993 |
Operations on Tree |
For every `lock`, `unlock`, or `upgrade`, traverse up to the root to check ancestors and down to all leaves for descendants. |
Tree Path Exhaustion |
Draw a tree. For one node, draw lines to every ancestor and every single descendant. $O(N)$ per operation. |
Hash Map State Tracking + DFS Pruning |
State-Annotated Tree Nodes |
Store `lock` status in an array. For `upgrade`, check ancestors using the `parent` array and count locked descendants using a quick DFS. |
Draw a tree. Label nodes with 'L' (Locked) or 'U' (Unlocked). Use a recursive "Search" arrow for the upgrade operation. |
Operation-Specific Complexity Bars |
Draw $O(H)$ for ancestors and $O(N)$ for descendants. Total time depends on tree depth. |
Lists of paths or repeated tree copies. |
`parent` array, `locked` state array, and an adjacency list for children. $O(N)$ space. |
| 1994 |
The Number of Good Subsets |
Generate every possible subset of the input array and check if the product of its elements is a "good" number (distinct primes). |
Exponential Power Set (O(2^N)) |
Draw a tree branching 2^N times. Most branches lead to "invalid" products with square factors. |
DP with Bitmask (Prime Representation) |
Prime Bitmask Transition Lattice |
Map numbers 1-30 to a 10-bit mask (one bit per prime < 30). Use DP where `dp[mask]` is the count of subsets with that prime signature. |
Draw a table where columns are numbers 1-30 and rows are bitmask states (0-1023). Show current mask XOR-ing with new number masks. |
Fixed-State Iterative Grid |
Draw 30 steps. In each step, iterate through 1024 states. $O(30 \\text{times} 2^{10})$. |
Storing billions of subset combinations in memory. |
A frequency array for numbers 1-30 and a DP array of size 1024. $O(1)$ effective space. |
| 1995 |
Count Special Quadruplets |
Four nested loops a < b < c < d to check if nums[a] + nums[b] + nums[c] == nums[d]. |
4D Index Hypercube (O(N^4)) |
Draw four pointers (i, j, k, l) slowly incrementing through a list. |
Hash Map (Meet-in-the-Middle logic) |
Sum Pair Balancing |
Rearrange to nums[a] + nums[b] = nums[d] - nums[c]. Fix b and c, and use a Hash Map to store counts of valid a or d values. |
Draw two arrows. One finds nums[a]+nums[b] and stores it in a box (Map). The second finds nums[d]-nums[c] and looks it up in the box. |
Quadratic Scan Line |
Draw an $O(N^2)$ nested loop structure. Indicate the $O(1)$ Hash Map lookup inside. $O(N^2)$. |
Only index variables in the stack. |
A Hash Map or Frequency Array for sum occurrences. $O(N)$ or $O(\\text{text}{\text{MaxSum}})$. |
| 1996 |
The Number of Weak Characters in the Game |
For every character, compare it against all other characters to see if both attack and defense are strictly lower. |
$O(N^2)$ Pairwise Comparison Matrix |
Draw an N x N grid where each cell (i, j) represents a comparison. Shade every cell. $O(N^2)$. |
Sorting (Attack Desc, Defense Asc) + 1-Pass Greedy |
Sorted Defense Trendline |
Sort by Attack descending. If Attack is equal, sort Defense ascending. Maintain `maxDefense` seen so far. If current Defense < `maxDefense`, it's weak. |
Draw dots on a 2D plane. Sort by X-axis. Draw a horizontal "Max-Line" that moves with the scan. Any point below the line is "weak". |
$O(N \log N)$ Sorting Funnel |
Draw the array falling into a "Sort" box. Show a single linear scan arrow emerging. $O(N \log N + N)$. |
Zero extra structures; just indices in the stack. |
Sorted array of objects on the heap. $O(N)$ space. |
| 1997 |
First Day Where You Have Been in All the Rooms |
Simulate the movement day-by-day based on the rules, manually counting visits per room. |
Time-Series Simulation Line |
Draw a timeline from Day 0, Day 1... and mark the room position. Show the exponential length for large N. $O(2^N)$. |
Dynamic Programming (Prefix Sum Transition) |
Recursive State Revisit Map |
`dp[i]` is the days to reach room `i`. To reach `i+1`, you must reach `i`, go back to `nextVisit[i]`, return to `i`, and move forward. |
Draw rooms 1 to N. Draw a curved "revisit" arrow from `i` back to `nextVisit[i]`. Label the segments with DP transition times. |
Linear DP Dependency Graph |
Draw N nodes. For each node, draw an arrow to the next, showing a single pass through the states. $O(N)$. |
A frequency map of all room visits during simulation. |
A 1D DP array of size N storing long integers (modulo 10^9+7). $O(N)$ space. |
| 1998 |
GCD Sort of an Array |
Try every possible swap of pairs (i, j) if `gcd(nums[i], nums[j]) > 1`, and check if you can eventually sort the array. |
$O(N!)$ Permutation Search |
Draw a state graph where each node is an array configuration and edges are valid GCD swaps. $O(N!)$. |
Union-Find + Sieve of Eratosthenes |
Component Connectivity Clusters |
Connect numbers to their prime factors using DSU. If `nums[i]` and `sortedNums[i]` belong to the same component, they can be swapped. |
Draw a list of numbers. Below them, draw their prime factors. Draw circles (DSU) grouping all numbers sharing at least one prime factor. |
$O(N \log(\log N)$) Sieve + DSU Pass |
Draw a Sieve timeline (primes) and then a linear scan through the array with DSU lookups. $O(N \\text{sqrt}{M})$. |
A massive adjacency list for all reachable array states. |
DSU `parent` array and a prime-factor mapping array up to 10^5. $O(\\text{text}{\text{MaxNum}})$. |
| 1999 |
Smallest Greater Multiple Made of Two Digits |
Start from k+1 and check every single integer to see if it only contains digits d1, d2 and is a multiple of k. |
Infinite Linear Search |
Draw a number line starting at k. Mark every multiple. Check digits for each. Worst-case: no upper bound. |
BFS (Digit Permutation Generation) |
Queue-Based Level Traversal |
Use a Queue to generate numbers using only d1 and d2 in increasing order. For each, check if it's > k and a multiple of k. Stop at 32-bit integer limit. |
Draw a tree: Root (empty) branches into d1 and d2. Each child branches into d1 and d2. Traverse level by level. |
BFS Tree Depth Analysis |
Draw a tree with 2^L nodes where L is the number of digits in 2^{31}-1. $O(2^{10})$. |
A list of every valid number checked on the number line. |
A Queue storing generated candidate numbers. $O(2^L)$ space. |
| 2000 |
Reverse Prefix of Word |
Iterate through the string, find the character, slice the prefix, reverse it, and concatenate it back. |
String Slicing/Re-allocation |
Draw a string. Box the prefix. Draw it reversed in a separate box. Draw the remainder. Glue them. $O(N)$. |
Two-Pointer In-Place Swap |
Dual-Pointer Mirroring |
Find the first occurrence of `ch`. Use two pointers (start, end) to swap characters in place within that prefix. |
Draw the string. Point `L` at index 0 and `R` at the index of `ch`. Draw arrows swapping the letters until they meet. |
Linear Single-Pass $O(N)$ |
Draw a line to the first occurrence, then a backward sweep for the swap. Total $O(N)$. |
Creating multiple new string objects on the heap. |
A single character array modified in-place. $O(1)$ extra space (excluding result). |
| 2001 |
Number of Pairs of Interchangeable Rectangles |
Nested loops comparing width/height ratio of every single pair `i` and `j`. |
N x N Adjacency/Comparison Matrix |
Draw an N x N grid. Cross out the diagonal and bottom half. The remaining upper triangle represents the $O(N^2)$ comparisons. |
Hash Map (Frequency Counter) with GCD reduction for fractions |
State Tracking Array to Map Transition |
Map each rectangle to a simplified ratio string/tuple, tally it in the hash map, and add current tally to total pairs. |
Draw two columns: Left is the incoming array. Right is a dynamic Hash Table updating the frequency of ratio keys. |
Linear Timeline Arrow |
Draw a single straight line spanning 0 to N-1, showing $O(1)$ hash map operations at each step. Total time $O(N)$. |
Call stack boxes containing variables for nested loop pointers `i` and `j`. |
Key-Value Block Diagram showing ratio strings as keys and integer frequencies as values. |
| 2002 |
Maximum Product of the Length of Two Palindromic Subsequences |
Recursively generate all disjoint subsequence pairs, check if palindrome, multiply lengths. |
Binary Recursion Tree (Exponential Expansion) |
Draw a tree where each node branches into 3 choices for each character: skip, add to sub1, add to sub2. Notice the massive $O(3^N)$ fan-out. |
Bitmask Enumeration + Precomputed Palindromes |
Bitwise Mask Overlays |
Write the string out. Use binary numbers (0s and 1s) directly underneath to visualize which characters are "turned on" for a subsequence. |
Draw the string horizontally. Below it, list bitmasks. Use bitwise AND `(&)` logic gates on paper to show disjoint sets (mask1 & mask2 == 0). |
Set Space Partitioning Venn Diagram |
Draw a universal set of 2^N masks. Show the iteration filtering down to valid palindromes, bounded by $O(3^N)$ subset traversal. |
Deep recursive stack frames showing passing of strings and current index. |
1D Array of size 2^N representing bitmasks, storing boolean `true/false` for palindromes. |
| 2003 |
Smallest Missing Genetic Value in Each Subtree |
For each node, traverse its entire subtree, collect all values into a set, and find MEX (Minimum Excluded) starting from 1. |
Overlapping Subtree Blob Diagrams |
Draw a tree. For each node, circle its subtree. Show how subtrees at the top redundantly encompass already-processed subtrees. $O(N^2)$. |
DFS Post-order Traversal + Tracking Node with Value 1 |
Path Upward Highlighting |
Find the node with value `1`. The MEX can only be >1 for nodes on the path from `1` to the root. Track visited nodes using a global set. |
Draw the tree. Highlight the path from node `1` up to the root. Maintain a global "visited" bucket on the side, adding nodes as you walk up. |
Single-Pass Tree Edges |
Trace every edge exactly twice (down and up). Show the global `mex` variable incrementing linearly. Total $O(N)$. |
N separate sets re-allocated for every single node in the tree. |
One single global Set (hash set) that persists and grows as pointers move up the tree. |
| 2004 |
The Number of Seniors and Juniors to Join the Company (SQL) |
Cross-join tables and use correlated subqueries to calculate running totals for each row individually. |
Cartesian Product Grid |
Draw Table A and Table B intersecting. Shade every cell to represent the $O(N^2)$ row-by-row correlation checks. |
SQL Window Functions (Cumulative Sum/Running Total) + CTEs |
Waterfall Budget Pipeline |
List seniors ordered by salary. Keep a running total column. Draw a line where total > 70000. Use remainder for juniors. |
Draw two sequential spreadsheets. Sheet 1: Seniors with a `SUM() OVER()` column. Sheet 2: Juniors using the leftover budget calculated from Sheet 1. |
Two Sequential Linear Scans |
Draw two separate arrays. Scan the first for $O(S)$, calculate remainder, then scan the second for $O(J)$. Time $O(S \log S + J \log J)$ due to sorting. |
Redundant intermediate temporary tables created for every subquery. |
Two distinct CTE (Common Table Expression) blocks sitting in memory before final projection. |
| 2005 |
Subtree Removal Game with Fibonacci Tree |
Minimax algorithm generating all possible game states for Alice and Bob. |
Game State Decision Tree |
Draw a root state. Branch out for every possible subtree removal. Notice the tree expands factorially based on remaining nodes. |
Game Theory (Sprague-Grundy/Nim) & Modulo Math Pattern |
Modulo Cycle Wheel |
Compute `N % 6`. If it's `1`, Bob wins. Otherwise, Alice wins. No tree traversal needed. |
Draw a circle with numbers 0 through 5. Map `N` onto the circle. If it lands on 1, write "False", else write "True". |
Constant Time Block (O(1)) |
Write down the formula `N % 6 != 1`. Draw a box around it. It executes in exactly one operation. |
Massive recursive tree with memoization dictionary mapping tree structures to boolean states. |
A single integer register in the CPU holding `N`, performing one modulo operation. (O(1) Space). |
| 2006 |
Count Number of Pairs With Absolute Difference K |
Nested loops iterating `i` and `j` checking `|nums[i] - nums[j]| == k` for every possible pair. |
Complete Graph / N x N Grid |
Draw the array on both the X and Y axis of a grid. Cross out the diagonal. The remaining checks represent $O(N^2)$ time. |
Hash Map (Frequency Count) / Single Pass |
Array to Hash Map Lookup Arrow |
Iterate the array once. For element `x`, look up `x-k` and `x+k` in the Hash Map. Add their frequencies to total. Add `x` to map. |
Draw the array on the left and a Hash Map on the right. Draw a forward arrow from the array to the map asking "Do I have my pair?". |
Single Timeline Arrow |
Draw a straight horizontal line. Mark points on it representing $O(1)$ hash map lookups. Total time $O(N)$. |
Call stack boxes with just two integer pointers `i` and `j` constantly resetting. Space $O(1)$. |
Key-Value Block Diagram showing integers as keys and their occurrence frequencies as values. Space $O(N)$. |
| 2007 |
Find Original Array From Doubled Array |
For every element, search the entire remaining array for its double. Use backtracking if a dead end is reached. |
Multi-branch Backtracking Tree |
Draw a tree where each node is the array state. Branch out for every valid pair removal. Notice the massive branching factor. |
Sorting + Frequency Map (or Queue) |
Sliding Window / Matching Arcs |
Sort the array. Sweep left to right. If the current number's count is > 0, find its double. Decrement both counts. |
Write out the sorted array. Circle the smallest number, draw an arc to its double, and cross them both out. Move right. |
Sorting Funnel to Linear Pipe |
Draw a funnel representing $O(N \log N)$ sorting, connecting to a straight pipe representing the $O(N)$ sweep. |
Deep recursive call stack frames holding copied array states. |
A Hash Map (or fixed-size array if values are small) holding leftover counts, decrementing in real-time. |
| 2008 |
Maximum Earnings From Taxi |
Pick or skip each passenger trip. Recursively check all valid combinations avoiding overlapping times. |
Binary Choice Tree (Knapsack Style) |
Draw a root. Branch left ("Take passenger, skip to end time") and right ("Skip passenger, check next"). Tree grows $O(2^N)$. |
Sorting + Dynamic Programming + Binary Search |
Timeline Intervals with DP Snapshots |
Sort trips by end time. At each trip, use binary search to find the latest previous trip that doesn't overlap. DP[i] = max(skip, take + profit). |
Draw a horizontal timeline. Draw trip intervals as floating blocks above it. Below, write a DP array updating max profit at each end time. |
Array Scan with Backward Search Beams |
Draw an array representing the DP loop. From each cell, draw a dashed arrow pointing backward representing the $O(\log N)$ binary search. Time: $O(N \log N)$. |
Recursion stack $O(N)$ deep holding state parameters. |
1D Array of size N tracking max profit up to the `i-th` sorted interval. |
| 2009 |
Minimum Number of Operations to Make Array Continuous |
Try making every possible continuous range of length N. Iterate the array to see how many elements already fit in that range. |
Sliding Window over Infinite Number Line |
Draw a huge number line. Draw a bracket of size N sliding by 1 unit infinitely. Highly inefficient $O(N^2)$ or worse. |
Sort + Deduplicate + Sliding Window (Two Pointers) |
Caterpillar Window on Unique Blocks |
Sort and remove duplicates. For each `nums[i]`, valid range is `[nums[i], nums[i] + N - 1]`. Slide a right pointer to count valid elements. Operations = N - valid. |
Draw the unique sorted array as blocks. Draw a fixed-width bracket `[ ... ]` starting at each block. Count blocks inside the bracket. |
Funnel + Inchworm Line |
Draw a funnel (O(N log N) sorting). Below it, draw a line with a sliding segment moving rightwards in $O(N)$ time. Total $O(N \log N)$. |
Temporary arrays constantly created to hold checked ranges. |
A compacted, deduplicated version of the original array (Space $O(N)$) with two integer pointers `L` and `R`. |
| 2010 |
The Number of Seniors and Juniors to Join the Company II (SQL) |
Cross joins with multiple correlated subqueries to track remaining budget dynamically per row. |
Nested Cartesian Grid |
Draw multiple tables crossing over each other, heavily shading cells to show iterative, row-by-row budget subtractions $O(N^2)$. |
SQL Window Functions + Common Table Expressions (CTEs) |
Data Pipeline / Flowchart |
CTE1 ranks/sums Seniors. CTE2 finds leftover budget. CTE3 ranks/sums Juniors based on CTE2's leftover budget. Filter final results. |
Draw 3 distinct boxes (CTEs). Box 1 outputs leftover budget to Box 2. Box 2 passes limits to Box 3. Connect with thick, one-way arrows. |
Sequential Table Scans |
Draw three straight, parallel lines showing data passing through phases sequentially without looping back. $O(N \log N)$ due to ORDER BY. |
Huge temporary tables in database memory holding Cartesian products. |
Streamlined intermediate tables (CTEs) bounded by N rows, quickly dropped from memory after the final projection. |
| 2011 |
Final Value of Variable After Performing Operations |
Compare the full string against "++X", "X++", "--X", "X--" using multiple if/else branches. |
String Matching Pipeline |
Draw out each full string. Draw a magnifying glass looking at all 3 characters one by one. $O(N \cdot 3)$ operations. |
Middle Character Extraction |
Targeted Index Lookup |
Look only at the 1st index (middle char) of each string. If it's '+', add 1. If it's '-', subtract 1. |
List the array of strings. Circle only the middle character of each. Draw an arrow from the circled char to a running total integer. |
Single Linear Sweep Arrow |
Draw one straight line across N items. Time complexity $O(N)$. |
String variables allocating memory to hold copied strings for comparison. |
A single $O(1)$ integer register holding the value `X`. |
| 2012 |
Sum of Beauty in the Array |
For every index i, loop all the way to 0 to check the left, and all the way to N to check the right. $O(N^2)$. |
Double-Sided Radar Sweeps |
Draw the array. For every element, draw two long scanning arrows going left and right. |
Prefix Max and Suffix Min Arrays |
The Pre-calculated Boundary Walls |
Pre-calculate the max value seen from the left (`prefix_max`) and min value seen from the right (`suffix_min`). At index i, a beauty of 2 exists if `prefix_max[i-1] < nums[i] < suffix_min[i+1]`. |
Draw the array. Above it, draw the "Max Wall" growing left-to-right. Below, draw the "Min Wall" growing right-to-left. To check i, just look at the two walls directly above and below it. |
Three Linear Passes $O(N)$ |
Draw 3 parallel lines. Two for building the walls, one for the final check. |
N/A |
Two arrays of size N. $O(N)$ space. |
| 2013 |
Detect Squares |
For every query point, pair it with EVERY other existing point in the system, then search for the remaining two points. |
Scatter Plot Complete Graph |
Draw points on a 2D plane. Draw lines connecting EVERY point to EVERY other point. $O(N^2)$ or worse per query. |
Hash Map Point Frequencies + Diagonal Anchoring |
Corner Completion Box |
Given query `(x,y)`, iterate only over points that form a diagonal `(px, py)`. The missing corners MUST be `(x, py)` and `(px, y)`. Multiply their frequencies. |
Draw a query point and one diagonal point. Draw a bounding box around them. The other two corners are instantly known. Read their counts from a Hash Map. |
$O(N)$ Linear Scan |
Draw a line representing the list of unique points. For each valid diagonal, draw 3 quick $O(1)$ lookups to the Hash Map. Time $O(N)$ per query. |
A dynamic array continuously growing, requiring full linear scans. |
A nested Hash Map `Map>` or 1D array if coordinates are small. Space $O(N)$. |
| 2014 |
Longest Subsequence Repeated k Times |
Generate all possible string combinations, check if each is a valid subsequence that appears `k` times. |
Massive Exponential Tree |
Draw a tree generating every combination of letters. $O(2^N)$. It becomes impossible to draw past level 3. |
Breadth-First Search (BFS) String Building + Frequency Pruning |
Pruned BFS Queue |
Filter chars appearing >= k times. Put them in a queue. Pop string, append valid chars, check if valid subsequence `k` times. Keep track of longest. |
Draw a queue. Start with single valid letters. Branch out to 2-letter combos. Cross out branches that fail the subsequence check immediately. |
Bounded BFS Tree |
Draw a tree, but severely limit the branches to only characters that passed the `count >= k` threshold. Max depth is 7. |
Massive arrays storing all generated combinations before validation. |
A Queue holding valid prefixes, and a 26-slot integer array for initial frequency filtering. |
| 2015 |
Average Height of Buildings in Each Segment |
Create an array representing every coordinate point. Loop over buildings and add height to every point in range. |
Dense 1D Array Painting |
Draw a massive number line. For a building spanning [1, 1000], physically draw 1000 "+H" marks. $O(N \\text{cdot Range})$. |
Line Sweep Algorithm + TreeMap (Event Sorting) |
Timeline Event Flags |
Record events: `start_point` (+height, +1 building), `end_point` (-height, -1 building). Sort events. Sweep left to right keeping a running average. |
Draw a number line. Drop a green flag at a building's start, a red flag at its end. Walk the line, updating your "current total height" only at the flags. |
Sorting Funnel to $O(N)$ Sweep |
Draw a funnel (O(N log N) sorting events) flowing into a straight timeline (O(N) processing). |
A huge integer array spanning the maximum coordinate `10^8`. Space Limit Exceeded. |
A balanced Binary Search Tree (TreeMap) or Sorted Array storing exactly 2N event objects. |
| 2016 |
Maximum Difference Between Increasing Elements |
Nested loops comparing every single element `i` against every subsequent element `j` where `i < j`. |
N x N Upper Triangle Matrix |
Draw an array as both rows and columns. Cross out the bottom-left half. Every remaining cell is a calculation you have to do. $O(N^2)$. |
Single Pass with Running Minimum (Prefix Min) |
Dynamic Anchor Point Line |
Sweep right. Constantly update `min_value` seen so far. At each step, subtract `min_value` from the current number to see if it's the max difference. |
Draw the array. Keep your left finger anchored on the smallest number seen so far. Move your right finger one by one, writing the difference below. |
Single Arrow Sweep |
Draw one continuous horizontal arrow. Time is strictly $O(N)$ as each element is visited exactly once. |
Call stack storing two nested loop pointers over and over. Space $O(1)$. |
Two simple integer registers: one for `min_val` and one for `max_diff`. Space $O(1)$. |
| 2017 |
Grid Game |
Simulate every single path for Robot 1 (DFS), then for *each* path, simulate every possible path for Robot 2. |
Exponential Branching Trees (Nested) |
Draw a massive binary tree of all paths. For *every single leaf node*, draw another entire binary tree representing Robot 2's choices. $O(2^N \cdot 2^N)$. |
Prefix Sum & Suffix Sum Arrays (Minimax pattern) |
Pivoting Seesaw Balance |
Robot 1 goes down at column `i`. Robot 2 is forced to take either the top-right remainder or bottom-left remainder. Calculate both via prefix/suffix sums and minimize the max. |
Draw a 2xN grid. Draw a solid line going right, then dropping at column `i`. Shade the remaining top-right and bottom-left cells. Compare their sums. |
Three Parallel Array Scans |
Draw two arrays representing $O(N)$ prefix/suffix buildup, followed by one more $O(N)$ scan to find the optimal pivot `i`. Total $O(N)$. |
Gigantic recursion stack frames copying the grid state at every single node. |
Two 1D arrays of size N holding cumulative sums. Space $O(N)$ (can be optimized to $O(1)$ keeping running sums). |
| 2018 |
Check if Word Can Be Placed In Crossword |
For every single cell, try fitting the word in all 4 directions, backing out (backtracking) if a block or mismatch is hit. |
4-Way Spiderweb Search |
Draw a grid. From every single empty cell, draw 4 arrows expanding outward. Highly redundant checks. |
String Splitting (by '#') + Segment Matching |
Window Overlay Template Matching |
Extract every valid vertical/horizontal segment (bounded by '#' or edges). Reverse it to check both directions. Overlay the target word to see if characters match perfectly. |
Draw the grid. Highlight a gap between two '#' blocks. Below it, write the target word forwards, then backwards. Connect matching letters with straight lines. |
Linear Scan of Segments |
Draw the grid as flattened 1D strips. Slide the target word over the strips. Time $O(M\cdot N)$ to scan the matrix. |
Deep recursive stack maintaining current cell `(r, c)` and current character index. |
A temporary string buffer to hold the current row/column segment being checked. |
| 2019 |
The Score of Students Solving Math Expression |
Try every single permutation of parentheses for the string, calculating the result recursively without memoization. |
Catalan Number Explosion Tree |
Draw a tree splitting the string at every operator. It grows exponentially based on Catalan numbers. Completely intractable for longer strings. |
Interval DP (Matrix Chain Multiplication) + HashSet |
Expanding Triangle Bottom-Up DP Table |
Find correct answer using stack. Then use DP: `dp[i][j]` stores all possible results for substring `i` to `j`. Combine subproblems strictly bounding answers to <= 1000. |
Draw a pyramid. Bottom layer is single digits. Above layers combine digits using operators, storing sets of possible results, capping out at 1000. |
N x N Grid with $O(N)$ cell combinations |
Draw an N x N matrix. For each cell `(i, j)`, draw arrows pointing to all `k` split points between `i` and `j`. Time $O(N^3)$. |
Massive recursion stack repeatedly calculating the exact same substrings. |
An N x N DP table where each cell contains a Hash Set of integers (max size 1000). Space $O(N^2 \cdot 1000)$. |
| 2020 |
Number of Accounts That Did Not Stream (SQL) |
Correlated subqueries for every single subscription record checking against the stream table row by row. |
Nested Loop Join Grid |
Draw the Subscriptions table. For each row, draw a loop scanning the *entire* Streams table. Very slow. |
LEFT JOIN with NULL check / EXCEPT operator |
Venn Diagram (Set Difference) |
Filter Subscriptions to 2021. Filter Streams to 2021. Do a LEFT JOIN from Sub to Streams. Count where the Stream ID is NULL. |
Draw two overlapping circles. Left is "2021 Subscriptions", Right is "2021 Streams". Shade ONLY the left crescent moon part. |
Two Parallel Filtered Streams merging |
Draw two tables filtering down rows in $O(N)$, then feeding into a Hash Join box $O(N)$. Total Time $O(N)$. |
Temporary tables created repeatedly for each correlated subquery execution. |
Two highly filtered intermediate subsets residing in RAM before a single efficient Hash Join. |
| 2021 |
Brightest Position on Street |
Iterate through every single integer coordinate on the number line covered by the lights and calculate overlaps. |
Dense Number Line Shading |
Draw a massive number line. Physically draw overlapping lines for every light's radius. Count the stacked lines at every point. Time limit exceeded for large radii. |
Line Sweep Algorithm + TreeMap (Difference Array) |
Event Flags (+1 / -1) |
Record `start = position - radius` (+1) and `end = position + radius + 1` (-1). Sort events. Sweep left to right, maintaining a running sum of brightness. |
Draw a number line. Mark start points with a green '+1' arrow pointing up, and end points with a red '-1' arrow pointing down. Tally the running total as you walk the line. |
Sorting Funnel to Timeline |
Draw a funnel representing $O(N \log N)$ sorting of event points, flowing into a straight horizontal line for the $O(N)$ sweep. |
A colossal array attempting to map coordinates from -10^8 to 10^8. (Memory Limit Exceeded). |
A balanced Binary Search Tree (TreeMap in Java/C++) storing at most 2N unique event coordinates. Space $O(N)$. |
| 2022 |
Convert 1D Array Into 2D Array |
Manually copy elements using nested `for` loops for rows and columns, manually tracking the 1D index with a separate variable. |
Manual Copy Grid |
Draw the 1D array on top. Draw an empty 2D grid below. Draw an arrow moving one item at a time, crossing out the top and filling the bottom. |
Math/Index Mapping (i / n, i % n) |
Division/Modulo Coordinates |
Iterate through the 1D array with index `i`. Place `original[i]` at `2D_array[i / cols][i % cols]`. |
Write the 1D indices 0,1,2,3. If cols=2, write the division (row) and modulo (col) results underneath each index to see the exact 2D coordinates instantly. |
1-to-1 Mapping Arrows |
Draw N straight, parallel arrows from the 1D array to the 2D grid. Strict $O(M\cdot N)$ time where M*N is the array length. |
Intermediate variables managing row and column states continuously. |
A pre-allocated contiguous block of memory for the resulting 2D array (Space $O(M\cdot N)$). |
| 2023 |
Number of Pairs of Strings With Concatenation Equal to Target |
Nested loops comparing every string `i` with every other string `j`, checking if `nums[i] + nums[j] == target`. $O(N^2 \cdot L)$. |
N x N String Concat Grid |
Draw an N x N grid. Inside every cell, write out the concatenated string and a comparison check to the target. Highly repetitive. |
Hash Map (Frequency) + String Prefix/Suffix Splitting |
Target Splitting Scissor Cut |
Count frequencies of all strings. Slice the `target` string at every possible index. If both the left slice (prefix) and right slice (suffix) exist in the map, multiply their frequencies. |
Write the target string. Draw a vertical dashed line separating it into two parts. Look up both parts in a frequency table drawn to the side. |
L Slices x Hash Lookups |
Draw the target string of length L. Show L split points. For each point, draw two quick $O(1)$ arrows to a Hash Map. Time $O(N + L^2)$. |
Countless temporary strings created in memory during the $O(N^2)$ concatenation step. |
A single Hash Map storing the original strings as keys and their integer frequencies as values. Space $O(N)$. |
| 2024 |
Maximize the Confusion of an Exam |
Generate every possible substring. Count the 'T's and 'F's in each. Check if the minority character count is <= k. $O(N^3)$. |
Nested Triangle Grid |
Draw a triangle of all substrings. In each box, draw a mini tally chart for 'T' and 'F'. |
Sliding Window (Two Pointers) Run Twice |
Expanding/Contracting Window Frame |
Run a sliding window to find the longest substring with at most `k` 'F's. Then run it again for at most `k` 'T's. Take the max length. |
Write the string. Use two fingers (L and R). Move R forward. Keep a tally of the "wrong" answer. If the tally exceeds `k`, drag L forward until it drops back to `k`. |
Two Parallel Sweeps |
Draw two horizontal lines spanning the string. One represents the 'T' sweep, one represents the 'F' sweep. Both are $O(N)$. Total Time $O(N)$. |
Heavy recursive frames or redundant substring arrays pushing space to $O(N^2)$. |
Two integer pointers (`left`, `right`) and a single integer counter for the target character. Space $O(1)$. |
| 2025 |
Maximum Number of Ways to Partition an Array |
For every element, change it to `k`. Then, recalculate prefix/suffix sums to count valid partitions. $O(N^2)$. |
N Arrays x N Partitions |
Draw N different copies of the array (each with one element changed). For each copy, draw a sliding partition line to check sums. Massive duplicate work. |
Prefix Sums + Hash Maps for Difference Tracking |
Balance Scale with Shifting Weights |
Calculate prefix sums and the `diff` (Left Sum - Right Sum) at every partition. When you change `nums[i]` to `k`, the difference changes by `d = k - nums[i]`. Use Hash Maps to find how many partitions now have a diff of 0. |
Draw a balance scale. The left side is Prefix, right is Suffix. When you change a number, write `+d` on the left side and `-d` on the right side. Check Hash Maps to re-balance. |
Three Linear Sweeps |
Draw three parallel lines: one for initial prefix sums, one for populating the right-side Hash Map, and one moving the pivot left-to-right updating maps. Time $O(N)$. |
A new cloned array and new prefix sum array created for every single element change. |
Two Hash Maps (Left Map and Right Map) tracking the frequencies of sum differences dynamically. Space $O(N)$. |
| 2026 |
Low-Quality Problems (SQL) |
Read the entire table into application memory, loop through each row, calculate the percentage, and filter. |
Full Table Extraction Pipeline |
Draw a massive database cylinder dumping all its contents into a tiny funnel (application memory). Extremely slow I/O. |
Direct SQL Filtering (Math inside WHERE clause) |
In-Database Sieve |
Calculate `likes / (likes + dislikes)` directly in the query. Return only the IDs that evaluate to strictly less than 0.6. |
Draw a table. Add a temporary column mentally for the calculation. Cross out rows >= 0.6. Read the remaining IDs top to bottom. |
Single Filtered Table Scan |
Draw one thick arrow passing through a filter block (the WHERE condition) and out comes a smaller subset of IDs. Time $O(N)$. |
Massive arrays in application memory holding the entire unoptimized dataset. |
Zero application memory. The database engine streams the filtered IDs directly. |
| 2027 |
Minimum Moves to Convert String |
Try converting every combination of 'X' substrings using backtracking to find the absolute minimum steps. |
Explosive Decision Tree |
Draw a string. From the first 'X', draw branches for "flip 1 char", "flip 2 chars", "flip 3 chars". Tree explodes to $O(3^N)$. |
Greedy Algorithm (Pointer Jumping) |
Jumping Frog on Lilypads |
Scan left to right. When you hit an 'X', increment your move count and jump your pointer forward by 3 indices. |
Write out the string. Put your finger at index 0. If it's 'O', move 1 step. If it's 'X', draw an arc jumping over the next 3 letters, and add a tally mark. |
Segmented Line Hops |
Draw a horizontal line. Draw arrows jumping rightwards. Some are size 1, some are size 3. It reaches the end in one pass. Time $O(N)$. |
Recursion stack holding string states. Space $O(N)$. |
A single integer pointer `i` and an integer `moves`. Space $O(1)$. |
| 2028 |
Find Missing Observations |
Use a recursive backtracking function to try all combinations of 1-6 for the `n` missing dice until the target sum is hit. |
Deep 6-ary Search Tree |
Draw a root node. Branch out 6 ways for dice rolls 1 through 6. For each, branch 6 ways again. $O(6^N)$ time. Impossible to draw fully. |
Math / Greedy Distribution (Base + Remainder) |
Water Pitcher Equalization |
Find required missing sum. Check bounds (`n` to `6n`). Base value = `sum // n`. Remainder = `sum % n`. Give every die the base value. Distribute remainder +1 to the first few dice. |
Draw `n` empty boxes. Calculate the base integer and write it in every box. Take the remainder and distribute it as "+1"s starting from the first box. |
$O(1)$ Math to $O(N)$ Fill |
Draw a calculator symbol (O(1) math) pointing to an array of size `N`. Draw a straight line filling the array. Total Time $O(N + M)$. |
Massive recursive stack frames generating failed dice combinations. |
A simple 1D array of size `n` allocated once and filled instantly. Space $O(N)$. |
| 2029 |
Stone Game IX |
Minimax tree simulating every possible sequence of valid stone removals for Alice and Bob. $O(N!)$. |
Factorial Game State Tree |
Draw a starting state. Branch out for every single valid stone you can pick. Tree fan-out decreases by 1 each step but remains massive. |
Math (Modulo 3 Categorization) & Case Analysis |
Three Buckets (0, 1, 2) Strategy |
The absolute values don't matter, only `val % 3`. Count stones that leave remainder 0, 1, and 2. Alice wins based on whether counts of 1s and 2s are balanced, altered by parity of 0s. |
Draw 3 buckets labeled 0, 1, and 2. Tally the stones into them. Follow a simple 3-branch flowchart rule based on the tally counts to declare Alice or Bob the winner. |
Constant Time Decision Matrix |
Draw a linear scan (O(N) to populate the 3 buckets), followed by a simple $O(1)$ mathematical check. Total Time $O(N)$. |
Huge memoization hash map storing exact array states to avoid duplicate game branches. |
A 3-element integer array tracking the counts of modulo 0, 1, and 2. Space $O(1)$. |
| 2030 |
Smallest K-Length Subsequence With Occurrences of a Letter |
Generate all subsequences of length `k`. Filter for the target letter count. Sort them lexicographically and pick the first. |
Combinatorial Explosion Grid |
Draw an array of all combinations "N choose K". Beside it, draw a filter, then a massive sorting funnel. $O(2^N)$ space and time. |
Monotonic Stack with Budget Constraints |
Greedy Stack with Lifelines |
Iterate string. Pop from stack if current char is smaller, but ONLY if we have enough total chars left to reach `k`, and enough target letters left to hit `repetition`. |
Draw a string. Maintain two counters: total chars left, target chars left. Draw a stack (array). When a smaller char comes, erase the top of the stack if counters allow it. |
Single Pass with Stack Adjustments |
Draw a straight line. Underneath, draw a stack growing and occasionally shrinking. Every element is pushed/popped at most once. Time $O(N)$. |
Gigantic lists holding all valid string subsequences in memory. |
A Char Array (Stack) of max size `k`, plus a few integer counters. Space $O(N)$ or $O(K)$. |
| 2031 |
Count Subarrays With More Ones Than Zeros |
Nested loops generating every possible subarray, counting 1s and 0s from scratch every time. $O(N^3)$ or $O(N^2)$. |
Overlapping Subarray Pyramids |
Draw the array. Draw brackets for size 1, then size 2 overlapping, etc. Shade the repetitive counting logic happening inside every bracket. |
Prefix Sum + Binary Indexed Tree (Fenwick) / Merge Sort |
Prefix Sum Step Chart |
Convert 0s to -1s. Keep a running sum. The problem becomes finding how many previous prefix sums are strictly less than the current prefix sum. Use a BIT to query this in $O(\log N)$. |
Draw a line chart of the prefix sum going up and down. For every point, cast a horizontal ray to the left. Count how many points lie strictly below this ray. |
Logarithmic Accumulation Sweep |
Draw an array sweep (O(N)). At each step, draw a small binary tree traversal upwards to represent the $O(\log N)$ Fenwick Tree update/query. Total $O(N \log N)$. |
Countless temporary subarray arrays or nested variable states constantly overwriting. |
A single Fenwick Tree (1D array of size 2N+1 shifted to handle negative indices). Space $O(N)$. |
| 2032 |
Two Out of Three |
Use nested loops to check every element of nums1 against nums2 and nums3, then repeat for the others. |
Three-Way Cartesian Web |
Draw 3 separate lists. Draw lines connecting every item in list 1 to every item in lists 2 and 3. Extremely messy $O(N^2)$ visual. |
Frequency Hash Map or Bitmasking on an Array |
Bitwise Venn Diagram |
Use an array of size 101. For a number in nums1, OR its index with 1. For nums2, OR with 2. For nums3, OR with 4. Check which numbers have a value of 3, 5, 6, or 7. |
Draw a table from 1 to 100. Make three columns (A, B, C) with checkboxes. Tick the boxes as you iterate. Pick rows with at least 2 ticks. |
Three Sequential Fast-Forwards |
Draw 3 separate straight lines representing the $O(N)$ iteration of the three arrays, dumping data into a central bucket. Total time $O(N)$. |
Three distinct dynamic lists repeatedly checked via linear scans. |
A fixed-size integer array `int[101]` storing bitmasks. Space $O(1)$ relative to input size constraints. |
| 2033 |
Minimum Operations to Make a Uni-Value Grid |
Try setting the target uni-value to every single element in the grid, calculate operations for all other elements, take the minimum. $O((M\cdot N)$^2). |
Grid-to-Grid Delta Matrices |
Draw the grid. Then draw another full grid next to it representing the "cost" to turn everything into the top-left element. Repeat for every element. |
Math (Median Finding) + Divisibility Check |
Flattening & Center of Mass |
Flatten grid to 1D, sort it. The optimal target is always the median element. Also check if `abs(num - median) % x == 0` for all elements; if not, return -1. |
Draw the 2D grid melting into a sorted 1D line. Put a star on the exact middle element (median). Draw arcs from all other numbers to the median, verifying step sizes. |
Funnel to Linear Median Sweep |
Draw the grid funneling into a sorted array (O(MN log MN)). Then draw a single pass over the array calculating distance to the center (O(MN)). |
Variables storing running minimums inside deeply nested 4-level loops. |
A single 1D array of size M*N to facilitate fast sorting. Space $O(M\cdot N)$. |
| 2034 |
Stock Price Fluctuation |
Keep an unsorted list of records. Scan the entire list every time you need the max, min, or current price. $O(N)$ per query. |
Unordered Ledger Search |
Draw a long receipt. When asked for "max", draw a magnifying glass starting from the top and looking at every single line down to the bottom. |
Hash Map (Timestamp -> Price) + Two Heaps (or TreeMap) |
Synchronized Double-Ended Queue/Tree |
Map tracks exact price at exact time. A Max-Heap and Min-Heap track all prices. When popping from a heap, check the map. If `heap_price != map[heap_timestamp]`, it's stale—discard it. |
Draw a Hash Map on the left for direct time lookups. On the right, draw a Min-Heap and a Max-Heap. Draw "trash cans" next to the heaps for lazy-deleting outdated prices. |
$O(1)$ Map Lookups + $O(\log N)$ Heap Bubbles |
Draw a timeline. `current()` is a straight arrow (O(1)). `max()`/`min()` point to the top of a triangle (Heap), pulling values and occasionally sinking them (O(log N)). |
A dynamically resizing array taking full $O(N)$ sweeps per API call. |
A Hash Map and two Priority Queues (Heaps) containing custom timestamp-price objects. Space $O(N)$. |
| 2035 |
Partition Array Into Two Arrays to Minimize Sum Difference |
Generate every single possible combination of picking exactly N elements out of 2N elements. $O(2^(2N)$). |
Exploding N-Choose-K Tree |
Draw a root. Branch out 2N ways. Then 2N-1 ways. The tree becomes completely unmanageable to draw after 3 levels. Time Limit Exceeded. |
Meet in the Middle + Binary Search |
Bridge Connecting Two Islands |
Split array into Left and Right halves. Calculate all subset sums for both (categorized by how many elements were picked). To find best match for Left subset of size `k`, binary search the Right subsets of size `N-k`. |
Draw two islands (Left and Right). On each island, sort subsets into buckets labeled by size (0 to N). Draw a bridge connecting a bucket of size `k` on the left to `N-k` on the right. |
Two Small Trees + Sorting/Binary Search |
Draw two separate $O(2^N)$ trees (much smaller than $O(2^(2N)$)). Followed by sorting arrays and drawing $O(\log 2^N)$ binary search arcs between them. |
A massive recursive call stack holding every possible N-length combination before validation. |
Arrays of Lists (`List[]`) storing all possible subset sums for the Left and Right halves. Space $O(2^N)$. |
| 2036 |
Maximum Alternating Subarray Sum |
Generate every single subarray. For each, loop through its elements applying the alternating +/- sign and keep track of the max sum. $O(N^3)$. |
Overlapping Triangle Grids |
Draw the array. Draw brackets for every possible start and end point. Inside every bracket, draw alternating + and - signs. Highly redundant recalculations. |
Dynamic Programming (Kadane's Algorithm Variant) |
Two Parallel State Tracks |
Maintain two running maximums: one ending on a positive addition, one ending on a negative subtraction. Update both at each step using the previous step's states. |
Draw two horizontal timelines: "Max Even Length" and "Max Odd Length". Walk through the array, drawing crossing arrows between the two lines to show state transitions. |
Double Linear Sweep |
Draw a single straight line sweeping across the array, updating two variables (O(1) work) at each step. Total time $O(N)$. |
Variables inside deeply nested loops constantly resetting and accumulating sums from scratch. |
Two simple integer registers tracking `odd_sum` and `even_sum` states. Space $O(1)$. |
| 2037 |
Minimum Number of Moves to Seat Everyone |
Try every possible permutation matching students to seats and calculate the total difference for each arrangement to find the minimum. $O(N!)$. |
Factorial Bipartite Graph Matching |
Draw seats on the left, students on the right. Draw chaotic, crossing lines connecting every student to every seat in all combinations. Explodes instantly. |
Sorting + Greedy Matching |
Parallel Ordered Lines |
Sort both the seats array and the students array. The optimal matching is simply pairing the i-th student with the i-th seat. Sum the absolute differences. |
Draw the unsorted arrays. Then draw them sorted directly beneath. Draw perfectly vertical, parallel lines connecting index 0 to 0, 1 to 1, etc., writing the difference on the line. |
Sorting Funnels to Parallel Sweep |
Draw two funnels representing the $O(N \log N)$ sorts. Below them, draw a single straight downward sweep adding the differences $O(N)$. |
Massive recursion tree generating permutations. |
Two in-place sorted integer arrays. Space $O(1)$ or $O(N)$ depending on sorting algorithm. |
| 2038 |
Remove Colored Pieces if Both Neighbors are the Same Color |
Simulate the game exactly. Find a valid piece, remove it, create a new shortened string, and rescan from the beginning for the next player. $O(N^2)$. |
Shrinking String Tape |
Draw the string. Erase one character, rewrite the whole shorter string. Repeat until no moves are left. Massive string copying overhead. |
Single Pass Counting (Independent Moves) |
Consecutive Block Highlighting |
Alice and Bob's moves are completely independent (removing 'A' doesn't create new 'B's). Just count consecutive 'A's >= 3 and consecutive 'B's >= 3. Compare totals. |
Write the string. Circle blocks of 'A's. If a block has length L > 2, write L-2 below it for Alice. Do the same for Bob's 'B' blocks. See who has a higher total score. |
Linear Scan Checkpoint Line |
Draw one continuous line across the string. Time is strictly $O(N)$ as it requires only a single forward pass. |
Multiple newly allocated string copies representing the board state after every single move. |
Two simple integer counters: `alice_moves` and `bob_moves`. Space $O(1)$. |
| 2039 |
The Time When the Network Becomes Idle |
Simulate every single second of the network. Track every individual message traveling back and forth along the edges. |
Chaotic Particle Simulation |
Draw a graph. For every tick of a clock, draw little dots (messages) moving along edges. The number of dots grows massively due to retries. Time Limit Exceeded. |
Breadth-First Search (BFS) + Mathematical Formula |
Concentric Ripple Expansion |
Use BFS from the master node (0) to find the shortest path (distance * 2 = round trip time) for each node. Use math `(round_trip - 1) / patience * patience + round_trip` to find when the last message arrives. Find max. |
Draw the graph with node 0 at the top. Draw downward layers (Level 1, Level 2). Write the round-trip time next to each node, then apply the math formula to find its specific "idle time". |
BFS Tree to Array Max |
Draw a BFS traversal touching all V vertices and E edges $O(V+E)$. Then draw an $O(V)$ scan across an array of calculated idle times. |
Heavy object-oriented queues tracking the exact location and timer of thousands of simulated packets. |
A standard BFS Queue, a `visited` array, and a `distances` array. Space $O(V)$. |
| 2040 |
Kth Smallest Product of Two Sorted Arrays |
Multiply every element in nums1 by every element in nums2, store all results in an array, sort the array, and pick the Kth element. |
Massive Cartesian Matrix |
Draw an N x M grid. Fill every single cell with the product. Then draw a massive sorting funnel. $O(N\cdot M \log(N\cdot M)$). Memory limit exceeded for size 10^5. |
Binary Search on Answer Range + Two Pointers/Binary Search for Counting |
Searching the Value Axis |
The answer lies between -10^10 and 10^10. Binary search this range. For a `mid` value, count how many products are <= `mid` using two pointers (or binary search) on the arrays. Adjust range based on `k`. |
Draw a massive number line from -10^10 to 10^10. Place a pin at `mid`. Below it, draw the two sorted arrays and show pointers sliding to count valid pairs without generating them. |
Logarithmic Zoom with Linear Counting |
Draw an overarching $O(\log(\text{Range})$) binary search loop. Inside it, draw two arrays sweeping in $O(N+M)$ or $O(N \log M)$ to count pairs. Total Time $O((N+M)$ * log(10^10)). |
A colossal array of size N*M (e.g., 10^10 elements) trying to hold all possible products in memory. |
Zero extra space. Only pointers and the two original input arrays are used. Space $O(1)$. |
| 2041 |
Accepted Candidates From the Interviews (SQL) |
Extract both tables entirely into memory, loop over all candidates, find their interviews, manually sum the scores, and check conditions. |
Full Cartesian Cross-Reference |
Draw two separate tables. Draw a line from every candidate to every interview to check if IDs match. Highly inefficient. |
SQL JOIN + GROUP BY + HAVING |
Data Pipeline Funnel |
Inner Join Candidates and Rounds. Group by candidate ID. Sum the scores. Filter with HAVING `years_of_exp >= 2` AND `SUM(score) > 15`. |
Draw two tables merging into a smaller third table (JOIN). Draw a funnel at the bottom catching only candidates passing the `>15` and `>=2` filters. |
Sequential Filtering Blocks |
Draw horizontal blocks: JOIN -> GROUP -> HAVING. Show rows decreasing as they pass through each block. Time $O(N \log N)$ or $O(N)$ depending on DB index. |
Massive array of Candidate and Interview objects stored in application RAM. |
Streamed directly by the DB engine; minimal application memory needed. |
| 2042 |
Check if Numbers Are Ascending in a Sentence |
Split the sentence into an array of words. Loop through, try to parse every word as an integer. Store integers in a new array. Loop again to check if sorted. |
Multi-Pass Array Transformation |
Write the sentence. Draw an array below it containing extracted numbers. Draw a loop iterating over that new array checking `arr[i] < arr[i+1]`. |
Single Pass Tokenization / On-the-fly Parsing |
Scanning Playhead |
Read string left to right. When a digit is found, parse the full number. Compare it immediately to a `prev_num` variable. If valid, update `prev_num`. |
Write the sentence. Use your finger as a playhead. Stop at a number. Compare it to a single sticky note labeled `prev`. Overwrite the sticky note and keep moving. |
Single Horizontal Timeline |
Draw one continuous line from index 0 to N. Mark $O(1)$ integer comparisons at specific points. Total Time $O(N)$. |
An array of strings (for words) and another array of integers (for numbers). Space $O(N)$. |
A single integer variable `prev_num` (initialized to -1) and a current parsing variable. Space $O(1)$. |
| 2043 |
Simple Bank System |
Store accounts in a complex list of objects. For every transaction, iterate through the list to find matching account IDs and validate balances. |
Unordered Ledger Search |
Draw a list of bank accounts. For every transfer, draw a magnifying glass starting at the top and scanning down to find Account A, then scanning again for Account B. |
1D Array Direct Indexing (1-based to 0-based mapping) |
Direct Memory Addressing |
Store balances in a standard array. `account 1` is `balance[0]`. To transfer, instantly check `if (acc1 <= n && acc2 <= n)` and `if (balance[acc1-1] >= money)`. Apply math. |
Draw an array of boxes. Label boxes 0 to N-1. When given Account 5, draw a lightning bolt directly to box 4. Instantly perform the +/- math. |
$O(1)$ Direct Access Points |
Draw a timeline of transactions. Above each transaction, draw a quick, direct downward arrow hitting an array. Strict $O(1)$ time per operation. |
Complex objects or dynamically resizing Hash Maps adding overhead to simple queries. |
A single fixed-size 1D `long[]` array allocated exactly once during instantiation. Space $O(N)$. |
| 2044 |
Count Number of Maximum Bitwise-OR Subsets |
Generate every single subset explicitly, store them in a massive list, loop through the list to calculate the OR of each, find the max, recount. $O(N \cdot 2^N)$. |
Massive Power Set Array |
Draw an array containing all 2^N subsets. Draw a separate loop calculating the OR for every single array. Space and time explosion. |
Backtracking (DFS) / Pick & Skip State Tracking |
Binary Decision Tree with Carried State |
First, find the `max_or` by ORing all elements. Then, DFS: at each element, branch left (include: `curr_or | nums[i]`) and branch right (exclude: `curr_or`). If leaf equals `max_or`, add 1. |
Draw a binary tree. Each node is a decision (Take/Skip). Carry the accumulated OR value down the branches. At the bottom leaves, check if the value matches `max_or`. |
Bounded DFS Traversal Paths |
Draw a tree expanding to depth N. Trace paths from root to leaf. Time complexity is strictly $O(2^N)$ but with $O(1)$ internal work. |
Gigantic 2D arrays storing all 2^N possible array combinations in memory. Space $O(2^N)$. |
Only the recursion call stack proportional to the array length. Space $O(N)$. |
| 2045 |
Second Minimum Time to Reach Destination |
Standard DFS tracking every single possible path from node 1 to N, allowing cycles, and trying to sort the resulting path times. $O(N!)$. |
Infinite Cyclic Graph Web |
Draw a graph. Trace a path going forward, then looping back and forth between two nodes forever to generate different times. Infinite loop. |
Modified BFS (Dijkstra-like) with Top-2 Tracking + Traffic Light Math |
Two-Lane BFS Expansion |
Standard BFS finds shortest path. We need the *second* shortest. Keep an array storing `dist1` (shortest) and `dist2` (second shortest) for every node. Allow a node to be added to the queue twice. Calculate wait times dynamically using `time % (2 * change)`. |
Draw the graph. Next to each node, draw two empty slots: `[ t1, t2 ]`. As BFS waves hit the node, fill t1. The next wave (or cyclic wave) fills t2. Stop when destination's t2 is filled. |
BFS Level Waves with Wait Buffers |
Draw a queue processing nodes $O(V+E)$. Show mathematical delays (red lights) calculated in $O(1)$ time before pushing to the queue. Total time $O(V+E)$. |
Deep recursive stack holding cyclic graph paths, causing stack overflow. |
A BFS Queue and two arrays (`dist1`, `dist2`) of size V initialized to infinity. Space $O(V+E)$. |
| 2046 |
Sort Linked List Already Sorted Using Absolute Values |
Copy all node values into a standard array, perform a built-in sort (e.g., Timsort), and reconstruct the linked list nodes from scratch. |
List-to-Array Funnel |
Draw a linked list. Draw an array. Draw arrows from every node into the array. Then draw a sorting funnel. $O(N \log N)$ time and $O(N)$ space. |
Head Re-linking (Two-Pointer Shift) |
Needle and Thread Weaving |
Iterate through the list. If a node is negative, pluck it from its current position and sew it to the very front of the list (before the current head). |
Draw the list. When you hit a negative node, draw a dashed arrow showing it moving to the front. Draw a solid arrow updating the `previous.next` pointer. |
Single-Pass Threading |
Draw a single horizontal line through the list. Every node is visited once and re-linked in $O(1)$. Total time $O(N)$. |
An auxiliary array of size N holding all node values. |
Zero extra space. Only local pointers (`curr`, `prev`, `head`) are manipulated. Space $O(1)$. |
| 2047 |
Number of Valid Words in a Sentence |
Split sentence by spaces. For each word, use nested loops to check if every character is a digit, if multiple hyphens exist, or if punctuation is in the wrong place. |
Word-by-Word Character Scan Grid |
Draw the sentence. For every word, draw a checklist: No digits? One hyphen max? Punctuation at end? $O(\text{Words} \\text{cdot AvgChars})$. |
Regex Matching or Structured Single-Pass Scan |
Pattern Filter Sieve |
Iterate each character once. Track hyphen count and punctuation position. Validate: digits = invalid, hyphen must be surrounded by letters, punctuation must be at end. |
Draw a word. Draw three boxes below: `hyphens`, `punctuation`, `valid?`. Fill boxes as you scan character by character. If a digit appears, immediately cross out the word. |
Linear String Scan Line |
Draw one continuous line from 0 to string length N. Total time $O(N)$. |
A list of strings created by the `split()` function. Space $O(N)$. |
A few boolean flags and integer counters. Space $O(1)$. |
| 2048 |
Next Greater Numerically Balanced Number |
Increment N by 1 repeatedly. For each number, count the frequency of its digits and check if each digit `d` appears exactly `d` times. |
Brute Force Trial-and-Error Loop |
Draw N. Draw an arrow to N+1. Below N+1, draw a frequency tally. If it fails, draw an arrow to N+2. $O(K \\text{cdot digits})$, where K is the distance to the next valid number. |
Precomputation / Backtracking with Pruning |
Digit Permutation Tree |
Generate all numerically balanced numbers up to 7 digits (since N <= 10^6). Sort them. Use binary search to find the first one strictly greater than N. |
Draw a tree where each branch is a valid digit count (e.g., three 3s). At the bottom, list the generated numbers like 122, 333, etc. Find where N fits in the list. |
Static List Binary Search |
Draw a sorted list. Draw a binary search "zoom" arrow (O(log M) where M is the count of balanced numbers). Total Time $O(\log M)$. |
Calculated on-the-fly, high frequency of garbage collection for short-lived tally arrays. |
A constant-size sorted list of all valid numerically balanced numbers. Space $O(1)$ relative to input limits. |
| 2049 |
Count Nodes With the Highest Score |
For every node, physically remove its edges to split the tree into components. Use BFS/DFS to count the nodes in each resulting component and multiply the sizes. |
Edge Deletion Ripple Effect |
Draw a tree. Pick a node and erase its connections. Count the remaining pieces. Repeat this entire process N times. $O(N^2)$. |
DFS with Subtree Size Precomputation |
Bottom-Up Subtree Accumulation |
Perform one DFS to find the size of every subtree. At each node `i`, the scores are: `size(left_child)`, `size(right_child)`, and `(TotalNodes - size(i))`. Multiply these. |
Draw the tree. Write the size of the subtree inside each node starting from the leaves up. At each node, multiply its children's sizes and the remaining outer nodes. |
Post-Order Traversal (One Pass) |
Draw a tree with a single arrow path going down and back up once. Total Time $O(N)$. |
Multiple temporary adjacency lists or component sets created for every node removal. |
A single `sizes` array of length N and the recursion stack. Space $O(N)$. |
| 2050 |
Parallel Courses III |
Simulate month by month. Check which courses have all prerequisites finished, start them, and track their remaining time until 0. |
Chronological Step-by-Step Simulation |
Draw a calendar. For month 1, list available courses. For month 2, update their timers. Very slow if course durations are large. |
Topological Sort (Kahn's) + Dynamic Programming |
Gantt Chart with Critical Path Analysis |
Use Kahn's Algorithm. Maintain a `max_time[i]` representing the earliest possible start time for course `i`. `max_time[next] = max(max_time[next], completion_time_of_current)`. |
Draw nodes with their individual times. Draw arrows (prereqs). For each node, calculate: `StartTime = Max(Prereq Finish Times)`. The answer is `Max(StartTime + Duration)`. |
In-Degree Reduction + Linear Array Update |
Draw the graph once (O(V+E)). Draw a single sweep through the queue. Total Time $O(V+E)$. |
Heavy state-tracking objects for every ongoing "simulated" course. |
An `in-degree` array and a `max_time` array of size V. Space $O(V+E)$. |
| 2051 |
The Category of Each Member in the Store (SQL) |
Join all tables (Members, Visits, Purchases). For each member, manually count visits and purchases using nested correlated subqueries. |
Nested Loop Join Grid |
Draw three tables. For every row in 'Members', draw a loop scanning 'Visits', then another scanning 'Purchases'. Extremely redundant I/O. |
Left Join + CASE Statement + Aggregate Functions |
Multi-Level Data Sieve |
Left Join Members with Visits, then Purchases. Group by Member ID. Calculate `100 * count(purchase_id) / count(visit_id)`. Categorize using a CASE statement. |
Draw three circles (Venn Diagram). Use a Left Join to keep all Members. Group items into buckets. Apply a formula label to each bucket based on the percentage result. |
Linear Scan with Aggregation |
Draw three parallel data streams merging into one. The combined stream is grouped once. Total Time $O(N \log N)$ for the join and sort. |
Multiple intermediate temporary tables created for each subquery. |
A single execution plan with memory-efficient Hash Joins or Merge Joins. |
| 2052 |
Minimum Cost to Separate Sentence Into Rows |
Try every possible way to insert line breaks between words using a simple recursion (backtracking). |
Exponential Branching Tree |
Draw a sentence. After the first word, branch: "Break here" or "Continue". After second word, branch again. Grows to $O(2^N)$. |
Dynamic Programming (1D) |
Optimal Path on 1D Array |
`dp[i]` is the min cost to format the sentence starting from word `i`. For each `i`, look ahead to all possible `j` that fit on one line. `dp[i] = min(cost(i, j) + dp[j+1])`. |
Draw the words in a line. Underneath, draw an array `dp`. From each cell `i`, draw arcs to future cells `j` that stay within the `k` limit. Choose the cheapest arc. |
Linear Scan with Lookahead Window |
Draw an array of length N. For each cell, show a small sliding window of lookahead work. Total Time $O(N \cdot K/\text{avg}_\text{word}_\text{len})$. |
Deep recursion stack storing current string formatting state. |
A 1D array of size N to store computed subproblem results (Memoization). Space $O(N)$. |
| 2053 |
Kth Distinct String in an Array |
Nested loops: for each string, iterate through the entire array again to count its occurrences. Store distinct ones in a list and return the Kth. |
N x N Comparison Matrix |
Draw the array. For the first item, draw a line to every other item to check for equality. Repeat for all N. $O(N^2)$. |
Hash Map (Frequency Counter) + Second Pass |
Two-Pass Frequency Sieve |
Pass 1: Tally all string frequencies in a Hash Map. Pass 2: Iterate the array again; if a string's frequency in the map is 1, decrement K. When K reaches 0, that's the answer. |
Draw the array on the left and a Hash Map on the right. Tally everything. Then, walk the array again, pointing to the Map. If the tally is '1', tick a "K counter". |
Two Parallel Sequential Lines |
Draw two straight lines, one for the tally pass and one for the search pass. Total Time $O(N)$. |
A new list created to hold distinct strings, potentially $O(N)$. |
A Hash Map storing strings as keys and integers as values. Space $O(N)$. |
| 2054 |
Two Best Non-Overlapping Events |
Nested loops comparing every event `i` with every event `j`. If they don't overlap, sum their values and track the max. |
N x N Compatibility Matrix |
Draw the events as intervals on a timeline. For event 1, check every other interval for overlap. $O(N^2)$. |
Sorting + Binary Search + Suffix Max |
Sorted Timeline with Future-Peak Lookup |
Sort events by start time. Create a `suffix_max` array to store the highest value from index `i` to the end. For each event, binary search for the first event that starts after it ends, and add its `suffix_max`. |
Draw a timeline. Above it, sorted intervals. Below it, a `suffix_max` line. For an interval, draw an arrow to the right, jumping over its end time to find the highest value waiting there. |
Sorting Funnel to Binary Search Arcs |
Draw a funnel (O(N log N) sort). Then draw N arcs, each representing an $O(\log N)$ binary search. Total Time $O(N \log N)$. |
$O(1)$ space if just using nested loops, but $O(N^2)$ time. |
Two arrays of size N: one for sorted events and one for suffix maximums. Space $O(N)$. |
| 2055 |
Plates Between Candles |
For each query `[L, R]`, iterate through the substring, find the first and last candle, and manually count the stars '*' between them. |
Nested Query Scan |
Draw the string. For every query bracket, draw a loop scanning the characters inside. $O(\text{Queries} \cdot N)$. |
Prefix Sums + Nearest Candle Precomputation |
Instant Anchor Lookups |
Precompute: 1) Prefix sum of plates. 2) Nearest candle to the left of index `i`. 3) Nearest candle to the right. For any query, jump to the nearest candles within `[L, R]` and use prefix sums for the count. |
Draw the string. Below it, draw three helper rows: `LeftCandleIdx`, `RightCandleIdx`, and `PlateCount`. For a query, draw two lightning bolts to the helper rows to get the bounds and subtract the counts. |
Triple Precompute + $O(1)$ Query |
Draw three parallel horizontal lines (O(N) total) for precomputation. Then draw $O(1)$ query points. Total Time $O(N + Q)$. |
$O(1)$ extra space but slow time. |
Three integer arrays of size N. Space $O(N)$. |
| 2056 |
Number of Valid Move Combinations On Chessboard |
Simulate every possible end-position combination for all pieces, and for each, simulate the full paths to check for collisions at every second. |
Multi-Dimensional Path Collision Grid |
Draw 8x8 boards for every second (T=1, T=2...). Draw arrows for all pieces. Check if any two pieces occupy the same square at the same T. Exponential. |
Backtracking + Recursive State Validation |
Decision Tree with Temporal Pruning |
Generate all valid moves for piece 1. For each, recursively move piece 2. Check collision *only* against pieces already placed. If collision, prune that branch. |
Draw a tree. Level 1 = Piece 1 moves. Level 2 = Piece 2 moves. At each node, draw a mini-board and mark "X" if paths intersect in time. |
Bounded Exponential Search |
Draw a tree with a branching factor of max 15 (moves per piece). Depth is number of pieces (max 4). Total $O(15^4)$, which is manageable. |
Deep nested arrays storing all path coordinate strings for comparison. |
A 1D array/stack storing current piece move objects; space $O(\text{Pieces})$. |
| 2057 |
Smallest Index With Equal Value |
Iterate the array and for each element, calculate the index modulo 10 and compare it to the value. |
Sequential Scan |
Draw the array. Below each index, write its value and its modulo 10 result. Draw a loop checking each one-by-one. |
Single-Pass Early Exit |
Linear Playhead |
Start index `i` at 0. Check `i % 10 == nums[i]`. If true, return `i` immediately. Else, move to 1. If loop ends, return -1. |
Write indices 0 to N. Below index 0, write "0 % 10 = 0?". If it matches `nums[0]`, stop. Draw a single forward arrow. |
Single Horizontal Line |
Draw a straight line. Total time $O(N)$. |
Standard variable overhead. |
Single integer `i` in a register. Space $O(1)$. |
| 2058 |
Find the Minimum and Maximum Number of Nodes Between Critical Points |
Traverse the list, find all critical points, store their indices in an array, then use nested loops to find min/max distances between all pairs. |
Two-Pass List-to-Array Transformation |
Draw a linked list. Circle the critical points. Draw an array and copy indices. Then draw arcs between all elements in the array to find min/max. |
Single Pass with Three-Node Window + Edge Point Tracking |
Sliding Triple-Node Frame |
Maintain `first_cp`, `prev_cp`, and `curr_cp`. As you find a new critical point, update `max_dist = current - first_cp` and `min_dist = min(min_dist, current - prev_cp)`. |
Draw the list. Use a 3-node bracket `[prev, curr, next]`. When a CP is found, draw a pin on the timeline. Update `min` using the last pin and `max` using the very first pin. |
Single Linear Sweep |
Draw a horizontal line. Total time $O(N)$. |
An auxiliary array storing all CP indices, potentially size $O(N)$. |
Four integer variables: `first`, `prev`, `count`, and `min_dist`. Space $O(1)$. |
| 2059 |
Minimum Operations to Convert Number |
Recursive DFS exploring every possible addition, subtraction, and XOR until the target is reached. |
Infinite Unbounded Tree |
Draw a root node. Branch 3*N ways. For each child, branch again. Without state tracking, this loops forever and grows infinitely. |
BFS (Breadth-First Search) + Visited Array (0-1000) |
Expanding Wavefront on Fixed Range |
Use a Queue for BFS. Only push numbers between 0 and 1000 into the Queue and mark them in a `visited` boolean array. If the result equals `goal`, return current steps. |
Draw a number line 0 to 1000. Start a ripple at `start`. Show the ripple expanding to new numbers each step. If a ripple hits `goal`, stop. |
State-Space BFS |
Draw a graph where nodes are 0-1000. Time $O(1000 \cdot N)$ because each number in the 0-1000 range is processed at most once. |
Recursion stack with massive redundant state storage. |
A Queue and a boolean array of size 1001. Space $O(1000)$. |
| 2060 |
Check if an Original String Exists Given Two Encoded Strings |
Expand both encoded strings into every possible combination of letters (for numbers) and compare them all. $O(\\text{text}{\text{Exponential}})$. |
Exponential Expansion Tree |
Draw "a3b". Branch it into "a---b". Do the same for the second string. Cross-compare billions of literal strings. |
Dynamic Programming (State: i, j, diff) |
The Length-Delta Synchronizer |
Track indices `i` (string 1) and `j` (string 2) and the `diff` in their currently expanded lengths. If `diff == 0` and chars match, advance both. If numbers, add to `diff`. |
Draw two strings. Draw a "Delta Gauge" (a scale). Read a number? Add weight to the scale. Read a letter? Subtract weight. If the scale stays near 0 and letters match, you are valid. |
3D DP Matrix $O(N \cdot M \cdot 2000)$ |
Draw a 3D grid: index1 x index2 x length_difference. Each cell takes constant time transitions. |
Massive arrays of expanded strings. |
A 3D DP memoization table or Hash Set of states. $O(N \cdot M \cdot \\text{text}{\text{Diff}})$ space. |
| 2061 |
Number of Spaces Cleaned by Robot |
Simulate the robot's movement step by step. If it hits a wall or obstacle, turn 90 degrees. Keep going until an arbitrary time limit. |
Infinite Simulation Path |
Draw a grid. Draw a line for the robot's path. Without a cycle-detection rule, the line could loop forever in your drawing. $O(\text{Infinity})$. |
Simulation + 3D State Tracking (r, c, direction) |
State-Space Grid Overlay |
Move the robot according to rules. Use a boolean 3D array `visited[rows][cols][4]` to track if the robot has been at `(r, c)` facing the same direction. Stop if a state repeats. |
Draw the grid. As the robot cleans a cell, shade it. On the side, maintain a "State Log": `(0,0,East) -> (0,1,East)`. If you see a log entry repeat, stop. |
Bounded Grid Scan |
Draw the grid. Since there are only `R*C*4` possible states, the robot eventually stops. Time $O(R \cdot C)$. |
Storing every coordinate in a massive list for comparison. |
A 3D boolean array `visited[R][C][4]` and a 2D array for cleaned cells. Space $O(R \cdot C)$. |
| 2062 |
Count Vowel Substrings of a String |
Generate all possible substrings using nested loops. For each substring, check if it contains *only* vowels and includes all five ('a', 'e', 'i', 'o', 'u'). |
Nested Triangle Grid |
Draw the string. Draw brackets for every possible start and end. Inside each, draw 5 checkboxes for the vowels. $O(N^3)$. |
Sliding Window (Two Pointers) with Sub-problem Logic |
Caterpillar Window with Constraints |
A substring is "vowel-only" if it ends at `j` and starts after the nearest consonant. The number of such substrings containing all 5 vowels is `atMost(5) - atMost(4)`. |
Write the string. Mark consonant positions as "walls". Between walls, slide a window. Tally vowel counts in a 5-slot box below the window. |
Linear Scan with Two Passes |
Draw a horizontal line. Show the window expanding and contracting. Total time $O(N)$. |
Creating new string objects for every substring check. Space $O(N^2)$. |
A Hash Map or `int[26]` array for the 5 vowel frequencies. Space $O(1)$. |
| 2063 |
Vowels of All Substrings |
Generate every substring, count the vowels in each, and sum the counts. |
Substring Summation Matrix |
Draw an N x N grid where each cell `(i, j)` contains the number of vowels in `s[i...j]`. Sum every cell. $O(N^2)$. |
Math / Contribution Technique |
Contribution Bar Chart |
For each character at index `i`, if it's a vowel, how many substrings contain it? It must start in `[0...i]` and end in `[i...n-1]`. Count = `(i + 1) * (n - i)`. |
Write the string. For each vowel, draw an arrow pointing left (start options) and right (end options). Write the math `(i+1)*(n-i)` underneath it. Sum the results. |
Single-Pass Accumulator |
Draw a single straight line through the string. Each character is visited once. Total time $O(N)$. |
Storing all counts in a large matrix. |
A single `long` variable for the total sum. Space $O(1)$. |
| 2064 |
Minimized Maximum of Products Distributed to Any Store |
Try every possible value for `x` (max products per store) starting from 1. For each `x`, calculate how many stores are needed. Stop when stores <= `n`. |
Linear Guess-and-Check |
Draw a line of possible answers 1 to MaxValue. For each number, draw a mini-loop dividing all product quantities. $O(\text{Max} \\text{cdot Products})$. |
Binary Search on Answer Range |
Logarithmic Zoom into Range |
Binary search the answer between `1` and `100,000`. For `mid`, calculate required stores: `sum(ceil(quantity / mid))`. If result <= `n`, `mid` is possible; try smaller. |
Draw a number line `[1 ... 100,000]`. Mark `mid`. Below it, write the product array and divide each by `mid`. If the total "buckets" fit in `n`, shade the left half. |
Log-Linear Search |
Draw an $O(\\text{log Max})$ binary search loop. Inside it, draw an $O(M)$ sweep over the products. Total Time $O(M \log(\text{MaxVal})$). |
Storing multiple distribution trial results in a list. |
No extra data structures beyond the input. Space $O(1)$. |
| 2065 |
Maximum Path Quality of a Graph |
Explore every possible path starting from node 0 using a standard DFS without any time constraints. |
Infinite Graph Traversal |
Draw a graph. Trace paths. Without the "maxTime" limit, your drawing would loop infinitely because nodes can be revisited. $O(\text{Infinity})$. |
Backtracking (DFS) with Time Pruning |
Pruned Exploration Tree |
Perform DFS starting at node 0. Keep track of current path time. If `currentTime > maxTime`, return. If at node 0, update max quality (use a frequency array to only count a node's quality once). |
Draw a tree where each node is a graph node. Beside each node, write `remTime`. If `remTime < 0`, cross out the branch. Keep a "Visited Set" for quality tally. |
Exponentially Bounded Search |
Draw a tree with a branching factor of max 4 (edges per node). Depth is limited by time. Though exponential, the small constraints make $O(4^10)$ feasible. |
Large path lists stored for every recursive call. |
An adjacency list and the recursion stack. Space $O(N + E)$. |
| 2066 |
Account Balance After Transactions (SQL) |
Iterate through every row in the Transactions table, update the corresponding account in the Accounts table one by one. |
Row-by-Row Update Loop |
Draw an Accounts table and a Transactions table. For every row in Transactions, draw an arrow to Accounts, erase the old value, and write a new one. $O(T \cdot A)$. |
SQL Common Table Expressions (CTE) + SUM() Aggregate |
Ledger Balance Sheet |
Sum all `amount` values (deposits as +, withdrawals as -) grouped by `account_id` in a temporary table. JOIN this with the original balances. |
Draw a table of transactions. Group them by ID. Calculate a "Net Change" column. Draw an arrow merging this with the original "Starting Balance". |
Single Grouped Scan + Hash Join |
Draw two parallel lines (Transactions scan $O(T)$, Accounts scan $O(A)$). Merge them at a single Join point. Total Time $O(T + A)$. |
Hundreds of individual update queries hitting the database disk. |
A single set-based calculation performed in the database's memory/buffer. |
| 2067 |
Number of Equal Count Substrings |
Generate all possible substrings. For each substring, count character frequencies and check if every present character appears exactly `count` times. |
N x N Substring Grid |
Draw an N x N triangle for all substrings. Inside each cell, draw a 26-slot frequency map. Very slow $O(26 \cdot N^2)$. |
Fixed-Window Sliding (Multiple Passes) |
Multi-Level Sliding Brackets |
The window size must be `v * count`, where `v` is the number of unique characters (1 to 26). Iterate `v` from 1 to 26, sliding a window of that fixed size. |
Write the string. For `v=1`, slide a bracket of size `count`. For `v=2`, slide a bracket of size `2*count`. Check counts in the bracket. |
26 x $O(N)$ Linear Passes |
Draw 26 horizontal lines, each with a sliding bracket moving from left to right. Total Time $O(26 \cdot N)$. |
Newly created substring copies in the heap for every combination. |
A single `int[26]` array used to keep track of characters within the current window. Space $O(1)$. |
| 2068 |
Check Whether Two Strings are Almost Equivalent |
Nested loops: for every character 'a'-'z', scan through string1 to count it, then scan through string2 to count it, then compare. |
26 x (2 x N) Scan Matrix |
Draw a table with letters 'a' through 'z'. For 'a', draw a line scanning string1, then string2. Repeat for all 26. $O(26 \cdot N)$. |
Dual Frequency Array Comparison |
Letter Balance Scales |
Create two arrays of size 26. In one pass, populate frequencies for both strings. Iterate 0 to 25 and check if `abs(freq1[i] - freq2[i]) > 3`. |
Draw two 26-slot boxes labeled A-Z. As you read string1, tally marks in box 1. For string2, tally in box 2. Finally, subtract the tallies for each slot. |
Single Pass + Constant Loop |
Draw one straight line (O(N)) followed by a tiny 26-step dot (O(1)). Total Time $O(N)$. |
Temporary objects or sorting the strings (O(N log N)) to compare. |
Two fixed-size `int[26]` arrays. Space $O(1)$. |
| 2069 |
Walking Robot Simulation II |
Actually move the robot one grid cell at a time for every `num` steps requested. Handle direction turns at corners. |
Step-by-Step Crawl |
Draw the grid. For a command "Move 1,000,000", physically draw one million tiny arrows around the perimeter. Time Limit Exceeded. |
Perimeter Modulo Math |
Track on a Flattened Perimeter Line |
The robot only moves along the perimeter of size `P = 2*(W+H) - 4`. Use `num % P` to find the actual displacement. Map the resulting number back to (x, y) coordinates. |
Draw the grid. Calculate the perimeter length. If the robot moves past the total length, use the remainder. Mark the remainder's position on the "border" only. |
Constant Time Calculation (O(1)) |
Draw a single mathematical formula box. It takes 1 step regardless of how large the input `num` is. Total Time $O(1)$ per move. |
Variables tracking every single coordinate the robot touches during the crawl. |
Four integer variables: `x`, `y`, `width`, `height`, and one direction string. Space $O(1)$. |
| 2070 |
Most Beautiful Item for Each Query |
For each query `q`, iterate through all items, find those with `price <= q`, and keep track of the maximum beauty seen. |
Nested Query Scan |
Draw Items on left, Queries on right. Draw lines from every query to every single item to check the price. $O(Q \cdot N)$. |
Sorting + Prefix Maximum + Binary Search |
Ascending Beauty Staircase |
Sort items by price. Replace each beauty value with the max beauty seen up to that point (`items[i].beauty = max(items[i].beauty, items[i-1].beauty)`). Binary search for each query price. |
Draw items as dots on a graph (Price vs Beauty). Connect dots with a "staircase" line that never goes down. For a query, draw a vertical line and find where it hits the staircase. |
Sorting Funnel to Binary Search Arcs |
Draw a funnel (O(N log N) sort). Then draw Q arcs representing the $O(\log N)$ binary searches. Total Time $O((N+Q)$ log N). |
Storing lists of filtered items for every single query. |
One sorted array of items and one result array of size Q. Space $O(N + Q)$. |
| 2071 |
Maximum Number of Tasks You Can Assign |
Try every possible subset of tasks and workers. For each subset, check if workers can complete tasks using a pills. $O(2^N \cdot 2^M)$. |
Exponential Subset Power Set |
Draw two circles (Tasks, Workers). Draw lines for every possible combination of task-worker pairs. The search space is massive. |
Binary Search on Answer + Greedy with Monotonic Queue (Deque) |
Sorted Matchmaker with a Booster |
Binary search the number of tasks k. For a given k, pick the k easiest tasks and k strongest workers. Use a Deque to greedily assign the hardest task to the weakest worker (with a pill if needed). |
Draw two sorted arrays. Pick the k smallest tasks and k largest workers. Draw arrows from workers to tasks. If a worker needs a pill, draw a '+' sign and jump to the hardest possible task they can now handle. |
Log-Linear Sorting & Matching |
Draw a funnel (O(N log N) sort). Then draw $O(\log N)$ binary search iterations, each doing an $O(N)$ sweep. Total Time $O(N \log^2 N)$. |
Recursive stack frames storing thousands of subset combinations. |
A Deque or Balanced BST to store worker strengths during the greedy check. Space $O(N)$. |
| 2072 |
The Winner University (SQL) |
Join both tables, loop through all students, count those with scores >= 90 for each university separately, and then compare. |
Cross-Join and Multi-Scan |
Draw NewYorkUniv table and CaliforniaUniv table. Draw a loop scanning the first, then a second loop scanning the second. $O(N + M)$. |
Independent Subqueries / Common Table Expressions (CTE) |
Score Board Comparison |
Create two CTEs. CTE1 counts "excellent" students in NY. CTE2 counts "excellent" students in CA. Use a CASE statement in the final query to compare the two counts. |
Draw two tally boxes labeled NY and CA. Put a checkmark in NY for every score >= 90. Do the same for CA. Compare the final numbers on a podium. |
Two Parallel Filtered Scans |
Draw two straight parallel lines. Each line filters rows in $O(N)$. Final comparison is $O(1)$. Total Time $O(N + M)$. |
Temporary tables containing the full data of both universities before filtering. |
Two single integer variables storing the counts in memory. Space $O(1)$. |
| 2073 |
Time Needed to Buy Tickets |
Simulate the queue. Decrement the first person's ticket count, move them to the back if tickets > 0. Repeat until person k has 0 tickets. |
Queue Rotation Spiral |
Draw a circle of people. Draw an arrow moving around the circle, erasing a "ticket" from each person. Count the total rotations. $O(N \\text{cdot MaxTickets})$. |
One-Pass Mathematical Summation |
Linear Contribution Baseline |
Everyone before k will buy at most `tickets[k]` tickets. Everyone after k will buy at most `tickets[k] - 1` tickets. Sum these limited values. |
Write the array. Circle the value at index k. For every element to the left, write `min(val, tickets[k])`. For elements to the right, write `min(val, tickets[k]-1)`. Sum the new numbers. |
Single Horizontal Sweep |
Draw one continuous line from 0 to N-1. Each element is touched once. Total Time $O(N)$. |
A Queue data structure repeatedly re-allocating memory for moved elements. |
A single integer `totalTime` and a loop counter. Space $O(1)$. |
| 2074 |
Reverse Nodes in Even Length Groups |
Convert the entire linked list to an array, group elements, reverse the even groups in the array, then reconstruct the list. |
List-to-Array Transformation Funnel |
Draw a linked list. Draw an array below it. Draw arrows copying every node. Perform the group reversals in the array, then draw arrows back. $O(N)$. |
In-Place Group Iteration & Re-linking |
Segmented Weaving |
Iterate with a counter for group size (1, 2, 3...). Count how many nodes are actually available. If the actual count is even, reverse that segment in-place. Link it back to the previous and next parts. |
Draw the list. Use a bracket to mark groups of increasing size. If a bracket has an even number of nodes, draw a "U-turn" arrow inside it and update the `.next` pointers on both ends. |
Two-Pointer Linear Segmenting |
Draw a horizontal line representing the list. Draw vertical bars separating groups. Each node is visited/reversed a constant number of times. Total Time $O(N)$. |
An array of size N storing all node references. Space $O(N)$. |
Local pointers like `prevGroupEnd`, `curr`, and `next`. Space $O(1)$. |
| 2075 |
Decode the Slanted Ciphertext |
Construct the full 2D grid from the string using `rows` and `cols`. Then, manually traverse the diagonals to collect characters. |
Grid Reconstruction and Diagonal Scan |
Draw an empty grid of size `rows x cols`. Fill it row by row with the input string. Then draw slanted arrows starting from each top-row cell. $O(N)$. |
Direct Index Mapping (One-Pass) |
Diagonal Jump Calculation |
The character at `(r, c)` in the grid is at `index = r * cols + c` in the string. For a diagonal starting at `c0`, the next character is at `(r+1, c0+r+1)`. Just calculate these indices directly. |
Write the string. Calculate the `cols` value. For the first diagonal, circle index 0, then `cols + 1`, then `2*(cols + 1)`. For the second diagonal, start at 1, then `cols + 2`. |
Single-Pass Jump String |
Draw a horizontal line of the input. Draw "hopping" arrows jumping over `cols` characters at a time to pick the message. Total Time $O(N)$. |
A full 2D character array (matrix) representing the grid. Space $O(N)$. |
A single StringBuilder to collect the decoded characters. Space $O(N)$. |
| 2076 |
Process Restricted Friend Requests |
For each request, check if adding the edge creates a path between any restricted pair using BFS or DFS from scratch. |
Repetitive Connectivity Matrix |
Draw a graph. For every new edge, draw a full BFS search to see if "Restricted Person A" can now reach "Restricted Person B". $O(\text{Requests} \\text{cdot Restrictions} \cdot (V+E)$). |
Disjoint Set Union (DSU) with Restrictions Check |
Dynamic Bubble Merging with Forbidden Lists |
For request (u, v), find their root parents P_u, P_v. Check if merging P_u and P_v violates any of the given restrictions (x, y). If safe, merge the components. |
Draw circles (components). For each request, draw a "tentative bridge". Check the "Forbidden List". If no forbidden pair exists across the bridge, solidify the line. |
Log-Linear Union-Find |
Draw the DSU tree structure. Each operation is near-constant due to path compression. Total Time $O(\text{Requests} \\text{cdot Restrictions} \cdot α(N)$). |
Multiple temporary adjacency lists or full connectivity matrices for every query. |
A `parent` array of size N and a `rank` array. Space $O(N + \text{Restrictions})$. |
| 2077 |
Paths in Maze That Lead to Same Room |
Generate all possible paths of length 3 starting from every room and check if the start room equals the end room. |
Exponential Path Tree (Depth 3) |
Draw a root room. Draw all neighbors. For each neighbor, draw all its neighbors. Check if any hit the root room. $O(V \\text{cdot Degree}^3)$. |
Adjacency Set Intersection (Triangle Counting) |
Neighbor Intersection Venn Diagram |
For every edge (u, v), count how many neighbors they have in common. Each common neighbor w forms a triangle (u, v, w). Total count divided by 3 (or only iterate u < v < w). |
Draw an adjacency list as sets. For edge (u, v), highlight the overlap between `Set(u)` and `Set(v)`. Every highlighted number is a valid 3-cycle. |
$O(E \\text{cdot AverageDegree})$ Search |
Draw the edges. For each edge, show a set intersection operation. Total time $O(E \\text{cdot min}(V^1/2, \text{max}_\text{degree})$). |
Storing full path histories for every search branch. |
A List of Sets (Adjacency List). Space $O(V + E)$. |
| 2078 |
Two Furthest Houses With Different Colors |
Nested loops comparing every house `i` with every house `j`. If `colors[i] != colors[j]`, update the max distance. |
N x N Comparison Grid |
Draw the array on X and Y axes. Shade all cells where colors are different. The max distance is the cell furthest from the diagonal. $O(N^2)$. |
Greedy Extremes Check |
Two-Way Anchor Pull |
The max distance must involve either the first house or the last house. Check the distance from the first house to the furthest different color from the right, and vice versa. |
Write the array. Place your left finger on index 0. Slide your right finger from the end until it hits a different color. Repeat with right finger on N-1 and slide left. |
Single Linear Sweep |
Draw two horizontal lines. One starts at left, one at right. Each is $O(N)$. Total Time $O(N)$. |
Call stack for nested loop pointers. Space $O(1)$. |
Two integer variables for distances. Space $O(1)$. |
| 2079 |
Watering Plants |
Actually simulate every step: move to plant, water, if empty move back to river, refill, move back to plant. |
Physical Step Simulation |
Draw a river at -1. Draw plants at 0, 1, 2... Draw a line representing the feet moving back and forth. Count every single mark. $O(N + \text{Refills} \\text{cdot AverageDistance})$. |
Math-Based Accumulator |
Linear Path with Penalty Gaps |
Iterate through plants. Keep track of current water. If `water < needed`, total steps += `2 * current_index` (back and forth) plus the normal step forward. |
Draw the plant line. Draw a tally marks for each forward step. At a refill, draw a long U-turn arrow back to the start and back to the current plant. Write the math below. |
Single Pass Counter |
Draw one straight line (O(N)). Mathematical jumps are $O(1)$ inside the loop. Total time $O(N)$. |
Storing full coordinate histories of the robot's steps. |
Three integer variables: `currentWater`, `totalSteps`, and `index`. Space $O(1)$. |
| 2080 |
Range Frequency Queries |
For every query `(left, right, value)`, iterate through the array from `left` to `right` and count the occurrences of `value`. |
Nested Query Scan |
Draw the array. For every query bracket, draw a loop counting only the specific value. $O(\text{Queries} \cdot N)$. |
Hash Map of Sorted Indices + Binary Search |
Value-Indexed Frequency Map |
In constructor, store indices of each value in a sorted list: `Map>`. For a query, binary search for the first index >= `left` and the last index <= `right` in the list for that specific value. |
Draw a Hash Map where keys are values. Next to each key, draw a sorted row of indices. For a query, use two "binary search" arrows to find the range within that row. Result is `end_idx - start_idx + 1`. |
$O(N)$ Precompute + $O(\log N)$ Query |
Draw a funnel (O(N) building the map). Then draw Q arcs representing the $O(\log N)$ binary searches. Total Time $O(N + Q \log N)$. |
$O(1)$ space but slow query time. |
A Hash Map of Lists storing all N indices once. Space $O(N)$. |
| 2081 |
Sum of k-Mirror Numbers |
Iterate through all integers starting from 1. For each, check if it is a palindrome in base-10, then convert to base-k and check again. |
Infinite Linear Trial-and-Error |
Draw a number line. At every integer, draw two check-boxes (Base-10? Base-K?). Shade the thousands of failed checks before hitting one "true". $O(\text{NumberValue})$. |
Palindrome Generation (Length-based) |
Mirror Reflection Growth |
Instead of checking all numbers, generate base-10 palindromes of increasing length (1, 2, 3...). For each generated palindrome, convert to base-k and check mirror property. |
Draw a "root" half-number (e.g., '12'). Fold it over a dashed line to get '1221'. Immediately convert '1221' to base-k and verify the string. |
Bounded Search Space Sweep |
Draw a small tree generating palindromes. The search space is logarithmic relative to the brute force. Time $O(\text{Total Palindromes Checked})$. |
String conversions for every single integer in memory. |
Only the current candidate string and the total sum accumulator. Space $O(Log N)$. |
| 2082 |
The Number of Rich Customers (SQL) |
Select all rows where amount > 500, then read into a set in Python/Java to count unique customer IDs. |
Full Row Retrieval Funnel |
Draw a massive database table. Draw an arrow pulling every single "rich" transaction into an application-side bucket. |
COUNT(DISTINCT customer_id) |
Unique Filter Sieve |
Perform a single SQL query: `SELECT COUNT(DISTINCT customer_id) FROM Store WHERE amount > 500`. The DB engine does the deduplication. |
Draw the table. Cross out rows <= 500. Highlight the IDs in the remaining rows, but only circle each unique ID once. Write the total count at the bottom. |
Single Filtered Scan |
Draw one straight line (O(N) scan). Data passes through a "Distinct" filter. Total Time $O(N)$. |
A huge list or set in application memory holding duplicate IDs. |
In-memory Hash Set handled by the database engine. Space $O(\text{Unique Customers})$. |
| 2083 |
Substrings That Begin and End With the Same Letter |
Generate all N^2 substrings, check the first and last character of each. $O(N^2)$. |
Nested Scanning Grid |
Draw the string. Draw overlapping brackets for every substring length. Check edges of every bracket. |
Combinatorics / Hash Map |
The Frequency Multiplier |
Iterate once. Keep a running count of each character's frequency. Every time you see a character 'a', it can form a valid substring with *every* previous 'a', plus itself. Add its current frequency to the total. |
Draw the string. Draw buckets for A-Z. Read 'a'. Add 1 to 'a' bucket. Add bucket's value to Total. Read 'b'. Add 1 to 'b' bucket. Add to Total. |
Single Linear Pass $O(N)$ |
Draw a single straight line. $O(1)$ map lookup and addition at each step. |
Lists of all generated substrings. |
An integer array of size 26. $O(1)$ space. |
| 2084 |
Drop Type 1 Orders for Customers With Type 0 Orders (SQL) |
For every customer, check if they have a type 0. If they do, delete all their type 1 orders row by row. |
Correlated Row-by-Row Deletion |
Draw the table. For each row, look up the customer's other orders. If you find a '0', mark the current '1' for deletion. $O(N^2)$. |
Window Function (MIN) or Grouped Filtering |
Customer Priority Filter |
For each customer, find the minimum `order_type`. If min is 0, filter for `order_type = 0`. If min is 1, keep `order_type = 1`. |
Draw groups of orders. For a group containing both 0 and 1, draw a cross over the 1s. For a group with only 1s, keep them. |
Grouped Parallel Scan |
Draw data streams entering a "Group By Customer" block. Out of the block comes the filtered rows. Time $O(N \log N)$ for grouping/sorting. |
Huge overhead for individual row existence checks. |
Efficient set-based processing in the DB buffer. |
| 2085 |
Count Common Words With One Occurrence |
For every word in `words1`, search for it in `words1` to ensure it's unique, then search for it in `words2` to ensure it's unique there too. |
Nested Triple-Scan |
Draw two lists. For one word in List A, scan A, then scan B. Total $O(N\cdot M)$. |
Two Hash Maps (Double Tally) |
Dual Frequency Intersection |
Create `Map1` and `Map2` for frequencies of `words1` and `words2`. Iterate through keys of `Map1`. If `Map1[word] == 1` and `Map2[word] == 1`, increment result. |
Draw two Hash Maps. Fill them with tallies. Highlight keys where both maps show a count of exactly "1". |
Two Parallel Linear Scans |
Draw two horizontal lines (O(N) and $O(M)$) followed by an $O(N)$ map key comparison. Total Time $O(N + M)$. |
Nested loop pointers in the call stack. |
Two Hash Maps storing strings and integers. Space $O(N + M)$. |
| 2086 |
Minimum Number of Food Buckets to Feed the Hamsters |
Try placing a bucket in every possible empty space and backtrack to find the valid configuration with the fewest buckets. $O(2^N)$. |
Bucket Placement Decision Tree |
Draw a street. At every empty lot, branch: "Place Bucket" or "Don't Place". Tree width explodes. |
Greedy / Linear Scan |
The "Right-First" Coverage |
Iterate left to right. If a hamster needs food, try to place a bucket to its RIGHT first (index i+1), because that bucket might also feed the *next* hamster. If the right is blocked, place it on the LEFT. |
Draw the string. When you hit a Hamster ('H'), look right. If it's a '.', draw a Bucket ('B') there. This bucket projects a feeding aura to i and i+2. |
Single Linear Pass $O(N)$ |
Draw a single straight line. Make $O(1)$ neighbor checks at each step. |
Recursion state tracking. |
Modified string/array. $O(N)$ space. |
| 2087 |
Minimum Cost Homecoming of a Robot in a Grid |
Standard BFS or Dijkstra to find the shortest path from start to home in an M x N grid. |
Grid Wavefront Expansion |
Draw a grid. Start a ripple. At each cell, branch in 4 directions. $O(M \cdot N \log(\text{MN})$) for Dijkstra. |
Greedy Coordinate Accumulation (Math) |
X-Y Axis Projection |
The robot only needs to move towards the target row and target column. The cost is simply the sum of row costs and column costs along the path, regardless of the sequence. |
Draw the X-axis and Y-axis costs as bars. Shade all bars between startRow and homeRow, and startCol and homeCol. Sum the shaded areas. |
Two Independent Linear Scans |
Draw two separate lines (O(M) and $O(N)$). Total Time $O(M + N)$. |
A massive priority queue and a distance matrix for Dijkstra. |
Two cost arrays. Space $O(1)$ if indexing directly. |
| 2088 |
Count Fertile Pyramids in a Land |
For every cell, try to build the largest possible pyramid and inverse pyramid, counting levels one by one. |
Nested Geometric Growth |
Draw a grid. For each '1', draw larger and larger triangles until you hit a '0'. $O(R \cdot C \\text{cdot min}(R, C)$). |
2D Dynamic Programming (Bottom-Up) |
Heatmap Leveling |
Let `dp[i][j]` be the max height of a pyramid with apex at `(i, j)`. It depends on the `dp` values of the three cells in the row below it. `dp[i][j] = min(dp[i+1][j-1], dp[i+1][j], dp[i+1][j+1]) + 1`. |
Draw a grid. Fill it with numbers. Each number is the min of its three "supports" below plus 1. Do it twice: once for up, once for down. |
Two Parallel Matrix Scans |
Draw two grid sweeps. Total Time $O(R \cdot C)$. |
Redundant coordinate checks for every pyramid level. |
Two 2D DP matrices of size R x C. Space $O(R \cdot C)$. |
| 2089 |
Find Target Indices After Sorting Array |
Sort the array using a standard library sort, then iterate through the sorted array to find and collect target indices. |
Sorting Funnel to Linear Search |
Draw the array. Funnel it through a sort (O(N log N)). Then draw a single scan searching for the target. |
Counting / Frequency (Linear Scan) |
Rank Calculation |
Count how many numbers are strictly smaller than `target` (this gives the starting index) and how many numbers are equal to `target`. |
Draw the array. Draw two boxes: `countSmaller` and `countEqual`. Every number increments one of them. The result is `[smaller, smaller + 1, ... , smaller + equal - 1]`. |
Single Horizontal Sweep |
Draw one straight line (O(N)). Total Time $O(N)$. |
Memory for the sorted copy of the array. |
Two integer counters. Space $O(1)$ (excluding output). |
| 2090 |
K Radius Subarray Averages |
For every index `i`, manually sum all elements from `i-k` to `i+k` and divide by `2k+1`. |
Sliding Sum Overlap |
Draw the array. For each element, draw a window of size 2k+1. Recalculate the sum from scratch for every window. $O(N \cdot K)$. |
Sliding Window (Fixed Size) / Prefix Sums |
Moving Average Window |
Calculate the initial sum of the first `2k+1` elements. As the window moves right, subtract the element leaving the left and add the one entering the right. |
Draw the array. Place a bracket of size 2k+1. As you move the bracket, draw a minus sign on the left edge and a plus sign on the right edge. |
Single Pass with Two Pointers |
Draw one straight line (O(N)). Each element is added/subtracted once. Total Time $O(N)$. |
Nested variables for repeated summation. |
A single `long` variable for the running sum. Space $O(N)$ for result array. |
| 2091 |
Removing Minimum and Maximum From Array |
Generate every possible combination of deletions from both ends that would include the min and max, then pick the smallest. |
Combination Search Tree |
Draw the array. Branch out into every "Delete from Left" and "Delete from Right" sequence until both Min and Max are gone. $O(2^N)$. |
Three-Case Greedy Analysis |
Triple Path Selection |
Find indices of min and max (i, j). Calculate 3 costs: 1) Both from front, 2) Both from back, 3) One from front and one from back. Take `min`. |
Draw the array. Mark indices i and j. Draw three arrows: one from left to the furthest index, one from right to the furthest, and two shorter arrows from both ends. |
Constant Time Decision (O(1)) |
Draw a single pass (O(N)) to find indices, followed by three $O(1)$ math boxes. Total Time $O(N)$. |
Recursion stack holding various array states. |
Four integer variables: `minIdx`, `maxIdx`, `n`, and `result`. Space $O(1)$. |
| 2092 |
Find All People With Secret |
For every new meeting, check if any participant knows the secret. If they do, spread it. Repeat until no new people learn the secret. |
Iterative Propagation Matrix |
Draw people as nodes. For every time T, draw edges and ripple the "Secret" color. Re-scan every time T repeatedly. $O(T \\text{cdot Meetings})$. |
Sorted Time Processing + DSU with Reset |
Time-Chunked Graph Island Merging |
Sort meetings by time. Process meetings of the same time as a group using DSU. If a person is connected to `Person 0`, they keep the secret. Otherwise, `reset` their parent. |
Draw groups of meetings by time. Inside each group, draw DSU "bubbles". If a bubble doesn't touch the "Secret Person", pop the bubble (reset parents) before moving to the next time. |
Sorting Funnel to Time-Grouped DSU |
Draw a funnel (O(M log M) sort). Below, draw small clusters of $O(M)$ DSU operations. Total Time $O(M \log M)$. |
A massive graph being re-traversed for every single time step. |
A `parent` array for DSU and a `secret_holders` set. Space $O(N + M)$. |
| 2093 |
Minimum Cost to Reach City With Discounts |
Standard BFS exploring all paths, but branching for "use discount" and "don't use discount" at every single edge. |
Exponential Branching Graph |
Draw a node. Branch to all neighbors. For each edge, draw two versions: "Full Price" and "Discounted". Tree explodes $O(2^\text{Edges})$. |
Dijkstra with State (City, DiscountsUsed) |
Multi-Layered Graph Plane |
Treat each (City, k) as a unique node in a 2D state space. Run Dijkstra. If a city has d discounts left, you can move to (neighbor, d) or (neighbor, d-1). |
Draw the cities. Above each city, draw "Discount Levels" 0 to K. Draw arrows between cities that either stay on the same level or drop down one level. |
Priority Queue Wavefront (O(E * K log(V * K))) |
Draw a Priority Queue popping (Cost, City, d). Show it exploring $O(E\cdot K)$ states. Total Time $O(\text{EK} \log(\text{VK})$). |
Heavy recursive stack frames storing all path possibilities. |
A 2D `dist[V][K+1]` array to store minimum costs per state. Space $O(\text{VK})$. |
| 2094 |
Finding 3-Digit Even Numbers |
Generate every possible combination of 3 indices from the array, form a number, check if even, and add to a Set. |
N-choose-3 Combinatorial Grid |
Draw an N x N x N grid. Every cell is a 3-digit number. Highlight the ones that are even and have no leading zeros. $O(N^3)$. |
Frequency Counting + Iterative Value Check |
Reverse Lookup Sieve |
Instead of the array, iterate through all even 3-digit numbers (100 to 998). For each number, check if the original array has enough counts of each digit. |
Draw a list: 100, 102, 104... 998. Draw a single digit frequency tally of the input array. For '102', ask: "Do I have one 1, one 0, and one 2?". |
Constant-Time Range Scan |
Draw a straight line from 100 to 999. Total iterations are fixed at 450. Total Time $O(N + 450)$. |
A huge Hash Set storing thousands of generated numbers before deduplication. |
A fixed-size `int[10]` frequency array. Space $O(1)$. |
| 2095 |
Delete the Middle Node of a Linked List |
Count all nodes in the list, calculate the middle index N/2, then iterate again to find the (N/2 - 1)-th node and delete its next. |
Two-Pass Linear Scan |
Draw the list. Draw one arrow counting 1, 2, 3... until the end. Then draw a second arrow stopping at the midpoint. $O(2N)$. |
Fast and Slow Pointers |
The Hare and the Tortoise |
Initialize `slow` and `fast` pointers at head. Move `fast` two steps and `slow` one step. When `fast` hits the end, `slow` will be at the middle. |
Draw the list. Use two markers. Move one twice as fast as the other. When the fast one hits the finish line, the slow one is exactly at the node before the middle. |
Single-Pass Threading |
Draw one straight line (O(N)) with two pointers moving in parallel. Total Time $O(N)$. |
Variables for the two passes and the count integer. |
Only two node pointers (`slow`, `fast`). Space $O(1)$. |
| 2096 |
Step-By-Step Directions From a Binary Tree Node to Another |
Build a full adjacency list of the tree (convert to a graph), then run BFS to find the shortest path between start and end. |
Graph Search Wavefront |
Draw the tree as a bidirectional graph. Start a ripple from the start node until it hits the destination. $O(N)$ space and time. |
LCA (Lowest Common Ancestor) + Path Comparison |
Common Path Trimming |
Find the path from root to Start and root to Dest as strings (L, R). Find the first point where paths diverge (LCA). Convert start path to 'U's and append the remaining dest path. |
Draw paths from root to S and D. Circle the fork in the road (LCA). Replace every edge in the S-branch with 'U' (Up) and keep the D-branch edges as is. |
Two Parallel DFS Traversals |
Draw two separate arrows from root to nodes. Total time $O(N)$. |
A full Map/Graph structure storing all parent pointers. Space $O(N)$. |
Two string/StringBuilder objects for path strings. Space $O(\text{Height})$. |
| 2097 |
Valid Arrangement of Pairs |
Backtracking to try every possible permutation of the given pairs to form a continuous chain. |
Factorial Permutation Tree |
Draw pairs as dominoes. Try every combination to see which ones "snap" together. $O(N!)$. |
Hierholzer’s Algorithm (Eulerian Path) |
Non-Reversible Threading |
Treat pairs as directed edges in a graph. Find the start node (OutDegree = InDegree + 1). Use DFS to find the Eulerian path, pushing nodes to a stack as you backtrack. |
Draw the graph nodes. Start at the "Source". Follow edges, erasing them as you go. If you get stuck, move the node to a "Finished" list and step back. |
Linear Edge Traversal |
Draw a single pass through all edges. Total time $O(V + E)$. |
Massive recursion stack for all permutation attempts. |
Adjacency List (Map) + Frequency Map for In/Out Degrees. Space $O(N)$. |
| 2098 |
Subsequence of Size K With the Largest Even Sum |
Generate every possible subsequence of size K, sum them up, and check if the sum is even. |
Combination Choice Grid |
Draw N items. Choose K. Use $O(N-\text{choose}-K)$ to visualize the massive search space. |
Greedy Selection + Smallest-Odd/Even Swap |
Heuristic Swap Logic |
Sort numbers descending. Pick top K. If sum is even, you're done. If odd, try two swaps: 1) Replace smallest even in K with largest odd outside K, 2) Replace smallest odd in K with largest even outside. Take max. |
Draw a sorted list. Draw a vertical line after K items. If sum is odd, draw arrows showing potential "trades" across the line to flip parity. |
Sorting Funnel to $O(K)$ Sum |
Draw a funnel (O(N log N) sort) followed by a single $O(K)$ addition and $O(1)$ swap checks. Total Time $O(N \log N)$. |
Memory for every possible subsequence combination. |
Two separate lists for even and odd numbers. Space $O(N)$. |
| 2099 |
Find Subsequence of Length K With the Largest Sum |
Generate all subsequences of length K, calculate sums, find the max, and return it. |
Combinatorial Power Set |
Draw a tree generating subsets. For each leaf, sum K elements. $O(N^K)$. |
Sorting by Value + Sorting by Index |
Double-Sort Pipeline |
Store indices with values. Sort by value descending and take top K. Then sort those K elements by their original indices to maintain "subsequence" order. |
Draw the array. Circle the K largest numbers regardless of position. Then, rewrite those circled numbers in the order they appeared in the original string. |
Dual Funnel Sort |
Draw a funnel (O(N log N)). Below it, draw a smaller funnel (O(K log K)). Total time $O(N \log N)$. |
Storing lists of all possible sums in memory. |
An array of pairs (value, index). Space $O(N)$. |
| 2100 |
Find Good Days to Rob the Bank |
For every day `i`, check if the previous `time` days are non-increasing and the next `time` days are non-decreasing by scanning. |
Nested Sliding Windows |
Draw the array. At each index, draw two arrows (left and right) of length `time`. Perform $O(\text{time})$ checks per index. $O(N \\text{cdot time})$. |
Precomputed Prefix/Suffix Counts (DP) |
Dual Flow Chart |
Precompute `left[i]` (count of non-increasing days ending at `i`) and `right[i]` (count of non-decreasing days starting at `i`). Valid if `min(left[i], right[i]) >= time`. |
Draw two helper rows. `Row 1`: count how long the price has been falling. `Row 2`: count how long the price will stay rising. Highlight indices where both rows have values >= `time`. |
Three Linear Sweeps |
Draw three parallel horizontal lines (left pass, right pass, final check). Total time $O(N)$. |
Redundant loops and local counters inside the main loop. |
Two integer arrays of size N. Space $O(N)$. |
| 2101 |
Detonate the Maximum Bombs |
DFS from every single bomb after checking all $O(N^2)$ pairs. |
Forest of N separate n-ary recursive trees. |
Draw N distinct root nodes, branching out into worst-case N-1 children each. Write $O(N^3)$ total. |
Graph Traversal (Directed Graph) + BFS/DFS. |
Directed Graph Adjacency List. |
Color source node red, expand wave (BFS) or deep path (DFS) coloring visited nodes orange. |
Draw circles for bombs, draw one-way arrows if bomb A radius covers center of bomb B. |
Graph Edge + Node summation formula. $O(N^2)$ edges + $O(N \cdot (V+E)$). |
Draw N^2 grid for edge building, then V+E linear flow chart for traversal phase. |
N^2 Adjacency Matrix + Deep Call Stack. |
Array of Lists mapping [Bomb Index] -> [List of reachable indices]. |
| 2102 |
Sequentially Ordinal Rank Tracker |
Insert item into a List, sort the List, index the i-th element. |
Array shifting and block sorting visualization. |
Draw an unsorted array, draw an arrow pointing to a newly sorted array, circle the target index. |
Two Heaps (Min-Heap / Max-Heap) or Balanced BST. |
Two balanced scales or two triangles facing each other. |
Push string to Max-Heap, pop top of Max-Heap and push to Min-Heap. |
Draw 2 triangles (trees). Draw arrows moving root of one triangle over to the bottom of the other. |
$O(\log N)$ tree traversal paths. |
Draw a binary tree. Highlight a single path from root to leaf to represent log(N) time. |
Continuous contiguous array blocks. |
Two distinct tree structures containing object references. |
| 2103 |
Rings and Rods |
Array of 10 Sets. Iterate string, add char to Set at index. |
Linear scan with hashing overhead. |
Draw string of chars, draw arrows pointing to 10 buckets containing unique letters. |
Bitmasking + Array. |
10-element array of 3-bit binary numbers. |
Iterate string, use bitwise OR to flip 1st, 2nd, or 3rd bit of the rod's index integer. |
Draw 10 slots. In each slot write 000. Cross out 0s and write 1s based on RGB colors seen. |
$O(N)$ linear time with $O(1)$ bitwise operations. |
Straight horizontal line (string length N) passing through a bitwise OR gate. |
Array of pointers to heap-allocated Set objects. |
Contiguous integer array of size 10 (Fits in CPU Cache). |
| 2104 |
Sum of Subarray Ranges |
$O(N^2)$ nested loops, tracking running max/min for each subarray. |
Upper-triangular matrix traversal. |
Draw an N x N grid, shade the top right half to show $O(N^2)$ combinations. |
Monotonic Stack (O(N)). |
Stack of blocks maintaining strictly increasing/decreasing sizes. |
Push elements. If new element breaks monotonicity, pop and calculate contribution. |
Draw a U-shape (stack). Draw numbers dropping in. If a smaller number drops in, draw the larger ones getting kicked out. |
Amortized $O(N)$ step function. |
Draw an array. Draw exactly one "push" arrow and one "pop" arrow for every element. |
Two variables (min/max) overwritten in a loop. |
Two Stack arrays storing indices, growing/shrinking dynamically. |
| 2105 |
Watering Plants II |
Simulate exactly as described using a loop and conditions. |
Two pointers moving inward. |
Draw array of plants. Draw 'A' at start, 'B' at end. Draw arrows moving inward one step at a time. $O(N)$. |
Two Pointers (Greedy Simulation). |
Pincers closing in on an array. |
Track remaining water for A and B. Deduct plant requirement. Refill (increment counter) if negative. |
Draw water bucket icons above A and B. Cross out bucket capacity and write new capacity after each plant. |
$O(N/2)$ linear scan. |
Draw N boxes. Shade boxes from left and right simultaneously until meeting in the middle. |
Single flat array. |
Single flat array with two integer variables (pointers) referencing indices. |
| 2106 |
Maximum Fruits Harvested After at Most K Steps |
Simulate walking left/right for every possible combination of K steps. |
Massive branching decision tree (Left/Right at each step). |
Draw a binary tree of depth K, branching left and right. Write $O(2^K)$. |
Prefix Sum + Binary Search (or Sliding Window). |
1D Number line with shaded intervals. |
Fix a turnaround point, calculate remaining steps to walk in the opposite direction, query prefix sum for that range. |
Draw a number line. Mark starting point. Draw an arched arrow going left, then turning back right, highlighting the covered segment. |
$O(N \log N)$ prefix sum queries or $O(N)$ sliding window. |
Line representing N iterations, each branching to a shrinking log(N) search space. |
Deep recursion stack frames. |
Flat continuous Prefix Sum array. |
| 2107 |
Number of Unique Flavors After Sharing K Candies |
Try removing every contiguous subsegment of size K, put rest in a hash set, count unique. |
Rebuilding a Hash Set N-K times. |
Draw N overlapping rectangles of size N-K, each pointing to a separate bucket (Set). |
Sliding Window + Frequency HashMap. |
A fixed-width frame sliding over an array. |
Add elements outside window to map. Slide window: subtract outgoing element's count, add incoming element's count. |
Draw array. Draw bracket [ ... ] of size K. Erase old boundary, draw new boundary shifted by 1. Update tally marks in a box. |
Single linear pass $O(N)$. |
Single straight horizontal arrow sliding across an array block. |
$O(N)$ distinct Hash Sets instantiated repeatedly. |
Single Frequency Map tracking integer counts. |
| 2108 |
Find First Palindromic String in the Array |
Iterate array, for each string reverse it using library functions and compare to original. |
Reversing full string blocks in a loop. |
Draw string blocks being flipped over entirely one by one. |
Two Pointers (String validation). |
Pointers at start and end of string, moving inwards. |
For each string, check s[i] == s[j]. If true, i++, j--. If false, instantly move to next string. |
Word written out. Draw arrows pointing to first and last letter. Move them towards the center step-by-step. |
$O(N \cdot M)$ where M is max string length. |
Grid of strings, early exit arrows stopping midway through words. |
Creating new reversed string objects $O(M)$ repeatedly. |
Two integer variables $O(1)$ tracking indices. |
| 2109 |
Adding Spaces to a String |
String concatenation in a loop (immutable strings result in copying). |
Repeatedly allocating larger and larger string buffers. |
Draw a small box, a bigger box, and an even bigger box being created sequentially. $O(N^2)$. |
Two Pointers + Pre-allocated Array/StringBuilder. |
Reading from original string and writing to a new larger array simultaneously. |
Pointer `i` on string, `j` on space indices. If `i == spaces[j]`, append space, `j++`. Else append `s[i]`, `i++`. |
Old string at top, new longer blank array at bottom. Draw lines mapping old letters to new slots, inserting ' ' where indices match. |
$O(N + M)$ single linear sweep. |
Two parallel linear tracks being consumed at constant speed from left to right. |
$O(N^2)$ garbage collection of intermediate strings. |
Exact sized char array or StringBuilder $O(N + M)$. |
| 2110 |
Number of Smooth Descent Periods of a Stock |
Find all $O(N^2)$ subarrays, check if each is a valid smooth descent. |
Upper-triangular matrix of subarrays, validating each one element by element. |
Nested loops spanning N elements, drawing lines checking i to j. |
Dynamic Programming / Math (Running Count). |
Accumulating a running tally that resets on condition failure. |
dp = 1. If arr[i] == arr[i-1] - 1, dp += 1. Total += dp. Else dp = 1. |
Line graph of stock prices. Draw triangles under the descending slopes. The area is the total periods. |
$O(N)$ single linear pass. |
Single horizontal arrow with a running sum counter that drops to 1 occasionally. |
$O(N)$ memory if subarray slicing is used. |
Single integer keeping track of the current descent length $O(1)$. |
| 2111 |
Minimum Operations to Make the Array K-Increasing |
Try all possible replacements for each k-spaced subsequence to make it non-decreasing. |
Exponential decision tree per subsequence. |
Draw an array, branch into N^2 choices per element (keeping vs. replacing). |
Longest Non-Decreasing Subsequence (Patience Sorting / Binary Search). |
Multiple parallel arrays mapping out LIS sequences. |
Group elements by spacing `k`. Find length of LIS for each group. Operations = (Group Size) - (LIS Length). |
Circle elements spaced by `k`. Draw a separate line for them. Cross out elements that break the increasing order. |
$O(N \log(N/K)$) binary search trees over a linear scan. |
Draw K separate arrays, each with a log(M) binary search curve underneath. |
Deep recursive call stack frames. |
A `tails` array for the LIS binary search, dynamically resizing up to N/K. |
| 2112 |
The Airport With the Most Traffic |
Iterate all flights, maintain a hash map of arrivals and departures per airport, scan map for max. |
Linear scan adding to a disorganized map. |
Draw flights as arrows. Draw a massive tally board where you add marks one by one. $O(E)$. |
Graph Degree Counting (Array-based Frequency Map). |
Nodes with incoming and outgoing edges summing up. |
Read `[src, dst]`. Increment `count[src]`, increment `count[dst]`. Track `max_traffic` on the fly. |
Draw airports as nodes. Every flight is an edge. Write a number inside the node that goes up by 1 for every touching edge. |
$O(V + E)$ single linear pass. |
Straight arrow through the edge list, then a straight arrow through the vertex array. |
Dynamically resizing Hash Map causing memory overhead. |
Fixed-size integer array indexed by airport ID (O(V)). |
| 2113 |
Elements in Array After Removing and Replacing Elements |
Simulate the exact removal and replacement minute by minute, physically copying arrays. |
A series of shrinking and growing arrays over time. |
Draw array at t=0, below it t=1 with one less item, down to t=n, then growing again. $O(Q \cdot N)$. |
Math / Modulo Arithmetic. |
A cyclical timeline (sine wave or clock face). |
Cycle is `2 * N`. For query `(time, index)`, find `time % (2*N)`. Math checks if it's in the shrink or grow phase. |
Draw a V-shape. Top-left is full array, bottom is empty, top-right is full again. Map the `time` to a point on this V to find array size. |
$O(1)$ per query. |
A single dot representing a constant time math formula. |
Multiple $O(N)$ array copies generated sequentially. |
$O(1)$ extra space, purely mathematical index mapping. |
| 2114 |
Maximum Number of Words Found in Sentences |
Split each string by space into a new array of words, count the length of the array, find max. |
Chopping blocks of text into smaller blocks. |
Draw a sentence, draw scissors cutting at every space, count the resulting pieces. |
String Iteration / Character Counting. |
Highlighting only the spaces in a continuous string. |
For each sentence, count ' ' (spaces). Words = spaces + 1. Update global max. |
Write the sentences. Put a dot under every space. Tally the dots + 1. |
$O(N \cdot M)$ single pass per character. |
A single continuous line scanning through all characters of all sentences. |
Array of Strings (Allocating new memory for every word $O(N\cdot M)$). |
$O(1)$ running counter variable. |
| 2115 |
Find All Possible Recipes from Given Supplies |
DFS for every recipe. Recursively check if missing ingredients can be made. May infinite loop. |
Messy recursive trees with potential cycles. |
Draw recipe as root, ingredients as branches. If an ingredient is a recipe, branch again. |
Topological Sort (Kahn's Algorithm) / BFS. |
Directed Acyclic Graph (DAG) with Dependency Resolution. |
Supplies have in-degree 0 (queue them). Process queue: "create" ingredient, reduce in-degree of recipes depending on it. If recipe in-degree == 0, queue it. |
Draw circles for supplies (green) and recipes (white). Draw arrows from ingredients to recipes. Erase arrow when ingredient is available. Color recipe green when 0 arrows remain. |
$O(V + E)$ graph traversal. |
Draw a queue processing nodes, one edge removal at a time. |
Deep recursion stack, vulnerable to StackOverflow. |
`inDegree` Map + Adjacency List `graph` + BFS Queue. |
| 2116 |
Check if a Parentheses String Can Be Valid |
Recursively branch on every 'unlocked' character, trying both '(' and ')', and check validity. |
Massive binary decision tree exploring every wildcard. |
Draw a root node branching into 2 choices for every '0' in the lock string. Write $O(2^N)$. |
Greedy (Two-Pass Scanning). |
A sliding balance scale that allows a range of values. |
Pass 1 (Left to Right): Treat unlocked as '('. If balance < 0, fail. Pass 2 (Right to Left): Treat unlocked as ')'. If balance < 0, fail. |
Write the string. Below it, write a running sum tracking `minOpen` and `maxOpen`. Cross out invalid paths if `maxOpen` drops below 0. |
$O(N)$ linear time, two distinct sweeps. |
Two long horizontal arrows passing over an array, one facing right, one facing left. |
Deep recursion stack frames (O(N)). |
Two simple $O(1)$ integer counters. |
| 2117 |
Abbreviating the Product of a Range |
Multiply all numbers in the range into a BigInteger, then stringify and extract characters. |
A number expanding massively in size, causing overflow or heavy arbitrary-precision math. |
Draw a tiny box multiplying by another box, ballooning into an enormous screen-filling box. |
Math (Trailing Zeros + Modulo/Logarithms). |
Isolating the front and back of a massive number while throwing away the middle. |
Factor out 2s and 5s for trailing zeros. Maintain the last 5 digits using modulo 10^5. Maintain the first 5 digits using floating-point logarithms. |
Draw a long rectangle. Shade the left 5 blocks (Prefix) and right 5 blocks (Suffix). Cross out the middle and draw an ellipsis (...). Add a bucket for trailing zeros. |
$O(N)$ arithmetic operations. |
Straight line through the numbers `left` to `right`, feeding into a modulo gear and a log gear. |
Massive BigInteger string allocation (O(N log(Max))). |
A few $O(1)$ primitive types (long/double) to hold prefix/suffix/zero counts. |
| 2118 |
Build the Equation (SQL) |
Fetch all rows into application memory, sort them, and use string concatenation loops. |
Data moving from database server to application server in raw, unformatted chunks. |
Draw a messy pile of database rows being dragged into a RAM stick, then sorted by hand. |
SQL String Aggregation (`GROUP_CONCAT` / `STRING_AGG`). |
A funnel taking multiple rows and squeezing them into one single text line. |
Format each term based on sign (e.g., `+5X^2` or `-3X`). `ORDER BY` power descending. Aggregate into one string, append `=0`. |
Draw a 2-column table (Power, Factor). Draw an arrow pulling the highest power row first, writing it on a line, then the next, forming an equation. |
$O(N \log N)$ database-side sorting. |
A funnel icon with an inner sorting filter, outputting a single straight string line. |
High application memory overhead storing intermediate Row objects. |
Database engine memory (optimized, often streamed directly to result set). |
| 2119 |
A Number After a Double Reversal |
Convert integer to string, reverse it, parse to int. Repeat the process. Compare results. |
String allocation, character shifting, and type-casting loops. |
Draw a number, convert to a text box, flip the text box backwards, convert back to number. |
Math / Observation (O(1)). |
A simple logic gate. |
Check if the number is exactly 0. If yes, True. Otherwise, check if `num % 10 == 0`. If yes, False. Else, True. |
Draw a number. Look at the last digit. If it's a '0' (and the number isn't just '0'), draw a red 'X' because the zero will vanish when reversed. |
$O(1)$ constant time modulo operation. |
A single dot representing instant evaluation. |
Multiple intermediate String and StringBuilder allocations. |
No extra memory. Pure $O(1)$ integer evaluation. |
| 2120 |
Execution of All Suffix Instructions Staying in a Grid |
(This *is* the standard optimal approach) For every suffix start position, simulate movement. |
Nested loops iterating over the instruction string. |
Draw an N x N grid. For each character in the string, draw a tiny robot attempting to follow the path from the start point. |
$O(M^2)$ Simulation (M = instruction length). |
A timeline dropping the first event repeatedly to simulate "suffixes". |
Loop `i` from 0 to M. Set `curr_pos = start_pos`, `count = 0`. Loop `j` from `i` to M. Move `curr_pos`. If out of bounds, break. Else `count++`. |
Draw a 3x3 grid. Draw an 'X' at start. Trace the path `R, R, L, U`. Count steps. Erase the path. Start again from the second instruction `R, L, U`. |
$O(M^2)$ quadratic simulation. |
Draw an M x M triangle shape (like an upper-triangular matrix) showing the shrinking suffix lengths being processed. |
Creating substrings for every suffix (O(M^2) space). |
Two pointers on the original string, tracking row/col integers (O(1) auxiliary space). |
| 2121 |
Intervals Between Identical Elements |
Nested loops. For each item, scan the whole array to find matches and sum the index differences. |
Spaghetti web of lines connecting matching numbers. |
Draw an array. For every '2', draw a separate arched line connecting it to every other '2', summing lengths. $O(N^2)$. |
Prefix and Suffix Sums / Hash Map of Lists. |
Two sweeping accumulators (left-to-right, right-to-left). |
Group indices by value. For each group, calculate prefix sum of indices. Current element's total diff relies on count of items before it and their sum, plus items after it. |
Draw out a sub-array of indices for a specific number. Draw a left-facing arrow calculating left-side pull, and a right-facing arrow for right-side pull. Add them. |
$O(N)$ linear sweep across grouped indices. |
Two parallel straight horizontal arrows scanning an array. |
No extra memory, just $O(1)$ variables holding sums. |
Hash Map mapping Integer -> List of Integers (indices). Memory is $O(N)$. |
| 2122 |
Recover the Original Array |
Try every possible subset to form 'lower' and 'higher' arrays, validating if they have a constant difference 2k. |
Massive decision tree of choosing whether each element is in 'lower' or 'higher'. |
Draw a binary tree branching into 2^N combinations, crossing out invalid leaves. |
Sorting + Greedy Candidate Validation. |
A sorted number line sliding a fixed measuring stick `2k`. |
Sort array. The smallest element *must* be `lower[0]`. Iterate through rest to guess `higher[0]`, yielding candidate `2k`. Greedily try to pair up all remaining elements using a frequency map. |
Draw sorted array. Draw an arrow from index 0 to index `i`. Calculate `diff`. Go through the rest of the array crossing off numbers that are exactly `diff` apart. |
$O(N^2)$ worst case, nested looping over candidates. |
An N x N grid where you pick a candidate from the top row and scan the array below it. |
Creating thousands of intermediate subset arrays (O(2^N)). |
A Frequency Array or Hash Map of size N, dynamically tracking unused numbers. |
| 2123 |
Minimum Operations to Remove Adjacent Ones in Matrix |
Try flipping every combination of 1s to 0s to see if no adjacent 1s remain. |
Grid states exploding exponentially. |
Draw a grid, branch out 2 choices (flip or don't flip) for every single '1'. $O(2^K)$. |
Bipartite Graph Matching / Min Vertex Cover. |
A chessboard pattern separating nodes into black and white sets. |
Color the grid like a chessboard. Edges only exist between adjacent 1s (which are different colors). Run Max Bipartite Matching to find the Min Vertex Cover. |
Draw the grid. Circle the 1s. Color them alternating shades. Draw lines between adjacent 1s. Circle the minimum number of nodes needed to break all those lines. |
Polynomial time graph matching (e.g., Hopcroft-Karp or DFS matching). |
Draw two columns of nodes (bipartite). Draw a network flow arrow pushing through them. |
Recursive state matrices. |
Adjacency List for the bipartite graph + boolean visited arrays. |
| 2124 |
Check if All A's Appears Before All B's |
Nested loops comparing every 'a' to ensure no 'b' came before it. |
Backwards pointing arrows checking past characters. |
Draw a string. For every 'a', draw lines checking every single letter before it to make sure it's not a 'b'. |
Linear Scan / Substring Search. |
A single trap-detector sliding over a string. |
Iterate string. If you see 'b', set a flag `seen_b = true`. If you see 'a' AND `seen_b` is true, return false. Or simply check if string contains "ba". |
Write the string. Slide a box of size 2 across it. If the box ever contains "ba", draw a red X and stop. |
$O(N)$ single pass. |
A single straight line scanning left to right. |
$O(1)$ extra space. |
$O(1)$ extra space, single boolean variable `seen_b`. |
| 2125 |
Number of Laser Beams in a Bank |
For every single device, scan the entire grid below it to find the next devices without blocked paths. |
Rays drawn point-to-point, checking empty rows continuously. |
Draw an R x C grid. Draw lines from one '1' to another '1' in a lower row, manually verifying no 1s exist in rows between them. $O((R\cdot C)$^2). |
Math (Combinatorics) + Filtering. |
Collapsing empty space and multiplying adjacent layers. |
Count '1's in each row. Discard rows with 0 devices. For remaining rows, multiply count of row `i` with row `i+1` and add to total. |
Draw the grid. Write the total count of '1's next to each row. Cross out any '0' totals. Multiply the remaining adjacent numbers: `R1 * R2 + R2 * R3`. |
$O(R \cdot C)$ single pass through grid. |
Draw a scanner moving down the rows one by one, outputting a single integer list, then a math symbol multiplying them. |
Coordinate arrays storing locations of every single device. |
Two integer variables: `prev_row_count` and `curr_row_count`. $O(1)$ space. |
| 2126 |
Destroying Asteroids |
Scan the entire unsorted array repeatedly to find any asteroid smaller than current mass, destroy it, and repeat. |
An unordered pool of rocks, with a line frantically jumping back and forth searching for targets. |
Draw a circle of rocks. Draw a line from the planet to a small rock, absorb it, then redraw lines checking all remaining rocks again. $O(N^2)$. |
Greedy + Sorting. |
A snowball rolling down a hill, accumulating increasingly larger rocks. |
Sort the array. Iterate left to right. If `current_mass >= asteroid[i]`, `current_mass += asteroid[i]`. Else, return false. |
Draw sorted rocks in a line left to right. Draw a Pac-Man eating them one by one, writing its new size above each eaten rock. If it hits a wall (bigger rock), draw an X. |
$O(N \log N)$ sorting + $O(N)$ linear scan. |
A sorting funnel that drops elements onto a single straight conveyor belt moving left to right. |
$O(N)$ boolean visited array to track which asteroids were destroyed in the chaotic loops. |
$O(1)$ auxiliary space (or $O(\log N)$ for in-place sorting stack). |
| 2127 |
Maximum Employees to Be Invited to a Meeting |
Generate all N! permutations of employees, seating them at a table and validating the "favorite" rules. |
A massive factorial decision tree mapping out every possible seating arrangement. |
Draw a circular table. Try placing Person 1, then Person 2. Backtrack and erase if the rule breaks. Write $O(N!)$. |
Graph (Functional Graph / Cycle Detection + Topological Sort). |
Isolated circular islands (cycles) with rivers (chains) flowing into them. |
Identify cycles. Case 1: Max cycle length > 2 (can only invite this one cycle). Case 2: Sum of all (cycles of length 2 + longest chain flowing into node A + longest chain flowing into node B). Return max of Case 1 and 2. |
Draw nodes as circles, with single arrows pointing to their favorite. Find closed loops. For 2-node loops, draw the longest "tail" of nodes pointing into each half of the pair. |
$O(N)$ graph traversal. |
A single sweep highlighting edges, grouping them into distinct components. |
$O(N!)$ space holding recursive permutations. |
$O(N)$ arrays for `in_degree`, `depth`, and `visited` status. |
| 2128 |
Remove All Ones With Row and Column Flips |
BFS/DFS exploring the state space of flipping every possible row or column until the matrix is all zeros. |
Exponential explosion of matrix states. |
Draw a grid. Branch it out into R matrices (flipping each row), and C matrices (flipping each col). $O(2^(M+N)$). |
Math / Binary Pattern Recognition. |
Comparing visual stencils to a master template. |
For the grid to be solvable, every row must either be *exactly identical* to the first row, or the *exact bitwise inverse* of the first row. |
Write out Row 0. Write Row 1 below it. Check if R1 == R0 or R1 == ~R0. If not, draw a giant red X. It's impossible. Repeat for all rows. |
$O(M \cdot N)$ single pass matrix check. |
A scanner locking onto Row 0, then sweeping down the remaining rows comparing them to the locked template. |
A massive Queue storing full 2D array states for BFS. |
$O(1)$ extra space. Just comparing elements in-place. |
| 2129 |
Capitalize the Title |
Split string by spaces, loop over each word, lowercase/uppercase characters, and concatenate strings in a loop. |
Chopping a block into pieces, altering them, and gluing them back together, leaving debris. |
Sentence -> Array of Words -> Array of Modified Words -> New Sentence. |
String Builder / Two Pointers (In-place if allowed). |
A sliding window moving across a string, highlighting word boundaries. |
Convert whole string to lowercase. Iterate with pointers to find words. If word length > 2, uppercase the first character. Append to result. |
Write the string. Box each word. If the box length is 1 or 2, do nothing. If > 2, circle the first letter and write its capital above it. |
$O(N)$ single linear scan. |
Straight horizontal line scanning left to right, occasionally pinging the first character of a sequence. |
$O(N)$ memory wasted generating intermediate String arrays from `split()`. |
A single StringBuilder or Character Array of size $O(N)$. |
| 2130 |
Maximum Twin Sum of a Linked List |
Convert the entire linked list into an Array/List, then use two pointers at the start and end to find the max sum. |
Extracting nodes into a contiguous block before processing. |
Draw the Linked List. Draw arrows extracting the values into an array. Draw rainbow arches connecting the array ends. $O(N)$ time and space. |
Fast/Slow Pointers + Reverse Linked List. |
Folding a physical chain in half directly over itself. |
Use fast/slow pointers to find the middle. Reverse the second half of the list. Put one pointer at the head, one at the new middle. Sum pairs, update max, move both 1 step. |
Draw the list. Find the middle line. Erase the arrows in the second half and draw them pointing backward. Draw a curved line bringing the old tail directly under the head. |
$O(N)$ traversal. |
Three straight linear passes: Find mid (fast/slow), Reverse half, Parallel sum check. |
$O(N)$ Array or List allocation to hold node values. |
$O(1)$ auxiliary space, purely manipulating existing node pointers. |
| 2131 |
Longest Palindrome by Concatenating Two Letter Words |
Generate all possible permutations of the words, check each string to see if it is a palindrome. |
Massive branching factorial tree mapping out word combinations. |
Draw word blocks. Draw lines linking every block to every other block in a massive web. Write $O(N!)$. |
Frequency Hash Map + Greedy Matching. |
Matching puzzle pieces. |
Count frequencies of all words. If you see "ab", look for "ba". If found, add 4 to length, decrement both counts. Track double-letter words (e.g., "cc") separately for a possible center piece. |
Draw 2-letter blocks. Find a block's reverse, draw a line connecting them, and cross both out. If a block has identical letters (e.g., "zz"), leave one uncrossed for the absolute middle. |
$O(N)$ linear time frequency counting. |
Single pass through the array, funneling into a tally board, then a single pass through the tally board. |
$O(N!)$ recursive stack frames and massive string allocations. |
Hash Map mapping String (length 2) to Integer count. Max 26x26 entries (O(1) space technically). |
| 2132 |
Stamping the Grid |
For every empty cell, try placing a stamp. Loop over the stamp's area to verify no blocked cells, mark cells as stamped. |
Nested loops inside nested loops scanning patches of a grid. |
Draw a large grid. Draw a small stamp box. Move the stamp one cell right, color underneath it, repeat. Write $O(R \cdot C \\text{cdot stampR} \\text{cdot stampC})$. |
2D Prefix Sum + 2D Difference Array. |
Two separate translucent overlays on top of the original grid. |
Pass 1: Prefix sum of blocked cells to $O(1)$ verify if a stamp fits. Pass 2: If it fits, use Difference Array to mark stamp boundaries. Pass 3: Prefix sum of Difference Array to check if all empty cells are covered. |
Draw the grid. Draw an overlay calculating blocked sums. If sum == 0 for a stamp area, draw +1 at top-left and -1 just outside bottom-right. Resolve the +1s and -1s to shade covered areas. |
$O(R \cdot C)$ multi-pass scanning. |
Three distinct, flat grid layers being processed one after another in straight horizontal sweeps. |
Deep iteration counters, possible boolean matrix replication. |
Two extra 2D integer arrays of size (R+1) x (C+1). |
| 2133 |
Check if Every Row and Column Contains All Numbers |
Extract every row and every column into a 1D array, sort it, and check if it equals [1, 2, ... n]. |
Extracting, sorting, and throwing away data repeatedly. |
Draw the grid. Yank out Row 1, sort it, verify. Yank out Col 1, sort it, verify. Write $O(N^2 \log N)$. |
Hash Set Validation (or Boolean Array Tracking). |
A bingo card tracking seen numbers per row and column. |
Iterate through every cell `grid[r][c]`. Attempt to add the value to `rowSet[r]` and `colSet[c]`. If it's already there, return false immediately. |
Draw the grid. Next to Row 1, draw a box checking off numbers 1-N. Above Col 1, draw another box. If you write the same number twice in a box, draw a red X. |
$O(N^2)$ single matrix traversal. |
A single scanner scanning the matrix row by row, updating side and top tally boards simultaneously. |
$O(N^2)$ memory allocating temporary arrays for sorting. |
Two arrays of HashSets or N x N boolean matrix tracker (O(N^2)). |
| 2134 |
Minimum Swaps to Group All 1's Together II |
For every possible starting position in the circular array, count how many 0s exist in a block of size K. |
A loop resetting and recalculating the same block over and over. |
Draw a circle. Draw a curved bracket. Move the bracket one step, manually count all 0s inside. Repeat. $O(N^2)$. |
Fixed Sliding Window on a Concatenated Array. |
A rigid frame sliding over a doubled array. |
Count total 1s -> `k`. Append array to itself to simulate circularity. Slide a window of size `k`. `Swaps` = `k` minus `max 1s found in any window`. |
Draw the array twice side-by-side. Draw a rectangle of size `k`. Slide it to the right one step at a time. Keep track of the highest number of 1s you see inside it. |
$O(N)$ linear scan. |
A single horizontal arrow sliding a fixed-width box across a line. |
$O(N^2)$ loop counters. |
$O(N)$ new duplicated array, OR $O(1)$ if using modulo `% N` math for indices. |
| 2135 |
Count Words Obtained After Adding a Letter |
For each target word, remove one letter, then loop through the entire `startWords` array comparing characters. |
Massive string comparison loops. |
Draw target word. Erase one letter. Draw lines checking every start word. Erase a different letter. Repeat. $O(N \cdot M \cdot K)$. |
Bitmasking / Sorting + Hash Set. |
Translating words into unique barcodes, then matching them. |
Convert all `startWords` to sorted strings or integer bitmasks. Add to Set. For each target word, convert to bitmask, iteratively drop exactly 1 set bit, and check if it exists in the Set. |
Write target word. Sort its letters. Draw lines branching down where one letter is omitted. If the resulting word is in the "Start Words Box", circle it in green. |
$O(N \log K + M \cdot K)$ string processing. |
A funnel converting strings into pure numbers, dropping into an $O(1)$ lookup bucket. |
Massive nested loop string allocations. |
A Hash Set containing integers (bitmasks) or strings (sorted). $O(M)$ space. |
| 2136 |
Earliest Possible Day of Full Bloom |
Try every single permutation of planting orders and calculate the max bloom day for each. |
Factorial explosion of timelines. |
Draw 3 flowers. Map out 3! (6) different timelines of planting them, picking the one that ends soonest. $O(N!)$. |
Greedy + Sorting. |
A Gantt chart with overlapping task bars. |
Sort by `growTime` descending. Keep a running sum of `plantTime`. For each flower, `bloomDay = currentPlantTime + growTime`. Track the absolute maximum `bloomDay`. |
Draw horizontal bars. Red for planting (must be sequential), Green for growing (can overlap). Place the longest green bars first to let them grow while you plant the rest. |
$O(N \log N)$ sorting + $O(N)$ scan. |
A funnel sorting the items, then a single straight horizontal line adding up the days. |
$O(N!)$ recursive stack frames. |
$O(N)$ array of objects/indices to facilitate sorting. |
| 2137 |
Pour Water Between Buckets to Make Water Levels Equal |
Simulate pouring water drop by drop from the fullest bucket to the emptiest until they balance. |
An infinite loop of tiny subtractions and additions. |
Draw buckets. Erase one drop from a full bucket, draw it in an empty bucket, subtract the spill percentage. Repeat forever. $O(\text{WaterAmount})$. |
Binary Search on Answer. |
A horizontal laser sweeping up and down to find the perfect equilibrium line. |
Guess a target water level `mid`. Calculate total water spilled to bring high buckets down to `mid`. Check if remaining water is enough to bring low buckets up to `mid`. Adjust `low` and `high` bounds. |
Draw an uneven bar chart. Draw a horizontal line across the middle. Shade the tops of bars above the line (water to pour) and the empty space below the line (water needed). Balance the shaded areas. |
$O(N \log(\text{Max} - \text{Min})$) search space. |
A binary search tree curve shrinking down to a single horizontal float value. |
Deep iteration counters. |
$O(1)$ extra space. Just a few float variables. |
| 2138 |
Divide a String Into Groups of Size k |
Use a loop to build strings character by character, then manually add the `fill` character at the end. |
Gluing individual letters together one by one. |
Draw characters dropping into a bucket. When bucket has `k` items, move to next bucket. If out of characters, drop `fill` characters. $O(N)$. |
String Chunking / Substring Math. |
A cookie cutter chopping a long dough roll into equal pieces. |
Loop `i` from 0 to N with step `k`. Take substring `s[i:i+k]`. If the last chunk is too short, pad it with the `fill` character using a string multiplier/builder. |
Write the string. Draw vertical lines every `k` characters. For the very last box, if there are empty slots, draw the `fill` character to pad it out. |
$O(N)$ linear string slicing. |
A single horizontal arrow jumping forward `k` steps at a time. |
$O(N)$ intermediate string builder allocations. |
$O(N)$ Array of Strings to hold the final result. |
| 2139 |
Minimum Moves to Reach Target Score |
Start at 1, BFS/DFS branching into (+1) and (*2) at every step until hitting the target. |
A massive, exponentially expanding binary tree originating from 1. |
Draw root node '1'. Branch to '2' and '2'. Branch those to '3','4' and '3','4'. Stop at target. $O(2^\text{Target})$. |
Greedy (Work Backwards from Target). |
Starting at the top of a mountain and taking the biggest possible jumps down. |
Start at `target`. If `target` is even and `maxDoubles > 0`, divide by 2, decrement `maxDoubles`. If odd, subtract 1. If `maxDoubles == 0`, just add `target - 1` to moves and finish. |
Write the target number. If it's even, draw a long arrow dividing it by 2. If it's odd, draw a tiny arrow subtracting 1. Stop when you hit 1. |
$O(\\text{log Target})$ max divisions. |
A steep curve dropping rapidly down to 1, followed by a straight line if doubles run out. |
Huge BFS Queue holding $O(2^\text{Target})$ nodes (will Time Out/Memory Out). |
$O(1)$ auxiliary space. Just modifying the integer directly. |
| 2140 |
Solving Questions With Brainpower |
Pure recursion. For each question, branch into two paths: "Solve it" or "Skip it". |
Exponential branching decision tree without memory. |
Draw Question 0. Branch left (Solve -> skip to Q3). Branch right (Skip -> go to Q1). Continue branching until end of array. $O(2^N)$. |
1D Dynamic Programming (Right to Left). |
An array where each cell looks forward to find the optimal path. |
Start from the end of the array. `dp[i] = max(dp[i+1] (skip), points[i] + dp[i + brainpower + 1] (solve))`. |
Draw an array. Start at the last box. Write its points. Move left. For each box, draw an arrow to the very next box, and another arched arrow skipping `brainpower` boxes. Take the max sum. |
$O(N)$ single linear pass. |
A single horizontal arrow scanning from right to left, doing an $O(1)$ comparison at each step. |
$O(2^N)$ recursive call stack. |
$O(N)$ 1D array to store the maximum points achievable from index `i` to the end. |
| 2141 |
Maximum Running Time of N Computers |
Try every possible time `T` and attempt to distribute battery power using a greedy recursive simulation. |
A massive branching search over the time range [1, TotalPower]. |
Draw a timeline. For every possible second, try to fit batteries like a Tetris game. Write $O(\text{Sum}(\text{Power})$). |
Binary Search on Answer + Greedy. |
A water tank being filled to a specific height limit. |
Pick a time `mid`. Each battery can contribute at most `mid` minutes. If total battery capacity >= `n * mid`, then `mid` is possible. Adjust binary search bounds. |
Draw `n` vertical columns (computers). Draw batteries as blocks. Any battery taller than the `mid` line is "chopped off" at the line. Sum the areas of all blocks and see if it covers the rectangle `n * mid`. |
$O(M \log(\text{MaxPower})$) where M is number of batteries. |
A binary search tree narrowing down on a single horizontal "capacity line." |
Recursive state matrices tracking battery usage per computer. |
$O(1)$ extra space (after sorting). |
| 2142 |
The Number of Passengers in Each Bus (SQL) |
For each bus, scan the entire passenger table to see who arrived before the bus but after the previous bus. |
Nested loops scanning a table for every row of another table. |
Draw Bus A. Draw lines to all passengers. Draw Bus B. Draw lines to all passengers. Write $O(B \cdot P)$. |
Sorting + Window Functions (Lead/Lag) or Inequality Joins. |
A timeline with intervals where people "fall" into the next available slot. |
Order buses by time. For each bus, find the range `[prev_bus_time, current_bus_time]`. Count passengers in that range. |
Draw a horizontal time axis. Mark buses as vertical walls. Mark passengers as dots. Count how many dots are trapped between two walls. |
$O(B \log B + P \log P)$ due to sorting and efficient indexing. |
Two sorted streams being merged/zipped together once. |
$O(B \cdot P)$ intermediate join result sets in memory. |
$O(B + P)$ streaming execution. |
| 2143 |
Choose Numbers From Two Arrays in Range |
Generate every possible combination (2^N) of choosing from array A or B and check if the sums are equal. |
A binary decision tree of depth N. |
Draw index 0. Branch to A[0] or B[0]. At index 1, branch again. Count paths that sum to 0 at the end. $O(2^N)$. |
Dynamic Programming (Space Optimized HashMap). |
A balance scale shifting left or right with each choice. |
`dp[sum]` stores the number of ways to reach a specific difference. For each pair `(a, b)`, update `new_dp[sum + a]` and `new_dp[sum - b]`. |
Draw a number line with 0 in the center. At each step, move all existing "counts" to the left by `b` and to the right by `a`. Sum overlapping counts. |
$O(N \\text{cdot Sum})$ where Sum is the range of possible differences. |
A grid where each row updates based on the previous row's shifted values. |
$O(2^N)$ recursion stack. |
Two HashMaps (Current and Next) or a fixed-size array $O(\text{Sum})$. |
| 2144 |
Minimum Cost of Buying Candies With Discount |
Generate all possible purchase and "free" combinations to find the absolute minimum cost. |
Factorial search space of groups of three. |
Draw 6 candies. Try every way to pick 2 and take 1 for free. Write $O(N!)$. |
Greedy (Sorting). |
Grouping the most expensive items together to maximize the "free" value. |
Sort costs descending. Iterate through the array: buy the two most expensive, skip the third (it's free). Repeat. |
Draw candies in a row from largest to smallest. Circle 2, cross out 1. Circle 2, cross out 1. Sum the circled ones. |
$O(N \log N)$ sorting. |
A sorting funnel followed by a single linear pass skipping every 3rd element. |
Recursive permutation arrays. |
$O(1)$ extra space beyond the input array sorting. |
| 2145 |
Count the Hidden Sequences |
Try every possible starting value within `[lower, upper]` and simulate the sequence to see if it stays in bounds. |
Multiple linear simulations starting from different points. |
Draw a range [1..100]. Start a sequence at 1, see if it breaks. Start at 2, see if it breaks. $O(\text{Range} \cdot N)$. |
Prefix Sum + Range Math. |
A rigid "shape" (the relative sequence) being slid up and down within a fixed window. |
Calculate the relative prefix sums. Find the `max_diff` and `min_diff` relative to the start. The "height" of the sequence is `max_diff - min_diff`. If this height fits in `upper - lower`, count the valid starting positions. |
Draw a mountain range (relative sequence). Measure the distance from the highest peak to the lowest valley. See how many ways this "mountain" can slide up and down between the `upper` and `lower` lines. |
$O(N)$ single pass to find min/max prefix sum. |
A single straight horizontal line calculating two global variables (min/max). |
$O(\text{Range} \cdot N)$ simulation states. |
$O(1)$ extra space (tracking only current_sum, min_sum, and max_sum). |
| 2146 |
K Highest Ranked Items Within a Price Range |
Perform a BFS to find all reachable items, store them in a list, and sort the entire list by the 4-tier ranking criteria. |
A wave expanding from a point, followed by a massive, disorganized sorting block. |
Draw a grid with a ripple. Then draw a huge list of items with arrows pointing to a sorted list. $O(R\cdot C + N \log N)$. |
BFS + Priority Queue (Min-Heap / Max-Heap). |
A radar sweeping the grid and dropping items into a small, sorted "top-K" bucket. |
Use BFS to explore by distance. For each item in price range, add to a Priority Queue of size K. Stop BFS early if current distance > distance of last item in K. |
Draw a grid. Mark 'Start'. Draw concentric squares (distance 1, 2, 3). For items found, write their (dist, price, r, c) in a "Top K" table, replacing entries as higher ranks appear. |
$O(R\cdot C)$ traversal + $O(\log K)$ heap ops. |
A grid ripple feeding into a small fixed-size vertical stack (the heap). |
Massive List storing every single grid cell as an object. |
BFS Queue (frontier) + Priority Queue of size K. $O(R\cdot C)$. |
| 2147 |
Number of Ways to Divide a Long Corridor |
Backtracking: Try placing a divider after every possible seat pair and recursively count valid configurations. |
Exponentially branching tree based on possible divider positions. |
Draw seats (S) and plants (P). Branch into 1, 2, or 3 divider spots between two S groups. $O(2^N)$. |
Combinatorics / Greedy Math. |
Counting the number of "options" (plants) between clusters of seats. |
Count total seats. If < 2 or odd, return 0. Iterate and group seats in pairs. Count the number of plants between each pair-cluster. Multiply (plants + 1) for each gap. |
Draw 'S' and 'P' on a line. Circle groups of two 'S'. Look at the empty space between circles. Count the 'P's in that gap. `Ways = (P1+1) * (P2+1)...` |
$O(N)$ single linear scan. |
A single straight line scanning left to right, updating a product variable at specific gap intervals. |
Deep recursion stack frames. |
$O(1)$ extra space (or $O(N)$ if storing seat indices in a list). |
| 2148 |
Count Elements With Strictly Smaller and Greater Elements |
Nested loops: For each element, scan the entire array twice to see if a smaller and a larger value exist. |
Every element shooting two rays (left/right) to scan the whole array. |
Draw an array. Circle an element. Draw arrows to every other element to check size. Repeat N times. $O(N^2)$. |
Min/Max Tracking. |
Isolating the two "boundary walls" of the dataset. |
Find the global `min` and global `max` of the array in one pass. Count how many elements `x` satisfy `min < x < max`. |
Draw a number line. Mark the absolute leftmost (Min) and rightmost (Max) points. Count all dots that fall strictly between these two lines. |
$O(N)$ single pass. |
Two scanners finding the edges, then one scanner counting the middle. |
No extra memory. |
$O(1)$ auxiliary space (storing `min`, `max`, and `count`). |
| 2149 |
Rearrange Array Elements by Sign |
Extract all positives into one list, all negatives into another, then merge them alternatingly into a new array. |
Diverting a stream into two separate buckets, then pouring them back into a third bucket. |
Draw input array. Draw two separate side-arrays (Pos/Neg). Draw arrows from side-arrays into a final interleaved array. $O(N)$. |
Two Pointers (One-Pass). |
A single stream being split by a switch into two target slots. |
Initialize a result array of size N. Use `posIdx = 0` and `negIdx = 1`. Iterate input: if positive, place at `posIdx` and `posIdx += 2`. If negative, place at `negIdx` and `negIdx += 2`. |
Draw the empty result array with indices 0, 1, 2, 3... Point a finger at 0 (for Pos) and 1 (for Neg). Move through input; fill the slot your finger is on, then hop that finger two spaces right. |
$O(N)$ single pass. |
A single horizontal arrow reading the input, with two jumping "write" pointers on the output array. |
$O(N)$ for two intermediate lists + $O(N)$ for result. |
$O(N)$ for the result array only (O(1) auxiliary if you don't count the output). |
| 2150 |
Find All Lonely Numbers in the Array |
Nested loops: For each number, check the rest of the array to see if it appears again or if `x+1` or `x-1` exists. |
N searches over N elements. |
Draw an array. For each item, draw arrows checking every other item for three conditions. $O(N^2)$. |
Frequency Hash Map. |
A census where each number reports its presence and checks its immediate neighbors. |
Build a Frequency Map of all numbers. Iterate through the keys: if `map[num] == 1` AND `num-1` is not in map AND `num+1` is not in map, it's lonely. |
Draw a tally board. Count occurrences of each number. Then, for each number on the board with exactly 1 tally, check if the numbers immediately above/below it have any tallies. |
$O(N)$ linear time. |
A pass to fill the bucket (map), then a pass to check the bucket. |
Nested loops and $O(1)$ space (at the cost of $O(N^2)$ time). |
$O(N)$ to store the Frequency Map. |
| 2151 |
Maximum Good People Based on Statements |
Generate all 2^N combinations of people being "good" or "bad". For each combo, check if all statements are consistent. |
Massive binary tree with 2^N leaves. |
Draw a root branching into 'Good' and 'Bad' for Person 0, then 2 branches for Person 1, etc. Circle valid leaf nodes. $O(2^N \cdot N^2)$. |
Bitmasking (Brute Force is the only way, but Bitmasking is the production-ready implementation). |
Iterating through an integer from 0 to (2^N - 1) as a binary representation. |
For mask `i`, if `(i >> j) & 1`, assume person `j` is good. Check their statements in the grid against the mask bits. If contradiction, discard mask. |
Write numbers 0-7 (if N=3). Convert to binary (000, 001...). For each binary string, map 1 to Good and 0 to Bad. Check if '1' people's statements match the binary pattern. |
$O(2^N \cdot N^2)$ search space. |
A vertical list of 2^N binary strings being fed through a "Consistency Filter" one by one. |
Deep recursion stack for backtracking. |
$O(1)$ extra space (using bitwise integers). |
| 2152 |
Minimum Number of Lines to Cover Points |
Generate all possible lines between all pairs of points, then try every combination of lines to see which set covers all points. |
Power set of all possible lines. |
Draw points. Draw every possible connecting line. Try picking subsets of lines. $O(2^(N^2)$). |
Bitmask DP / State Compression. |
A grid where rows are "points covered" (bitmasks) and values are "min lines". |
`dp[mask]` = min lines to cover points in mask. For each mask, pick 2 uncovered points, form a line, find all points on that line, and update `new_mask`. |
Draw a bitmask (e.g., 1011). Shade the 1st, 3rd, and 4th points. Try adding a line that hits the 2nd point. Update the mask to 1111. Write the +1 line cost. |
$O(N^2 \cdot 2^N)$. |
A 1D array of size 2^N being filled from left to right, where each cell looks back at previous states. |
Massive list of line objects and subsets. |
$O(2^N)$ 1D array to store DP states. |
| 2153 |
The Number of Passengers in Each Bus II (SQL) |
Recursive CTE or nested subqueries to simulate bus arrivals and passenger boarding one by one. |
A sequential dependency chain where Bus N depends on Bus N-1's remaining capacity. |
Draw Bus 1. Calculate boarders. Draw Bus 2. Subtract Bus 1's boarders from total passengers, then calculate. $O(B \cdot P)$. |
Iterative Simulation with Window Functions. |
A conveyor belt with fixed-size buckets and a spillover mechanic. |
Join passengers to buses by time. Use a recursive variable to track: `Boarded = min(Capacity, WaitingAtStation + NewArrivals - PrevBoarded)`. |
Draw a table with columns: Bus Time, Capacity, New Arrivals, Waiting, Boarded. Fill row-by-row, carrying the "Waiting" value down to the next row. |
$O(B + P)$ linear processing. |
A single pass through the sorted bus and passenger events. |
Large intermediate join tables in the DB buffer. |
Temp tables or variables to hold the "waiting" state across rows. |
| 2154 |
Keep Multiplying Found Values by Two |
For each multiplication, scan the entire array to see if the new value exists. Repeat until not found. |
Repeated linear searches over the same data. |
Draw the `original` value. Draw an arrow scanning every element. If found, double it. Draw another arrow scanning the whole array again. $O(N \cdot \log(\text{Max}/\text{Original})$). |
Hash Set / Sorting + Binary Search. |
A direct-lookup bucket. |
Put all numbers into a Hash Set. While `original` exists in set, `original *= 2`. Return `original`. |
Draw a box labeled "Set" containing all array numbers. Write the `original`. Check the box. If inside, erase `original`, write `original * 2`, and check the box again. |
$O(N)$ to build set + $O(\log N)$ lookups. |
A single pass to fill the set, then a vertical drop through a "doubling loop." |
$O(1)$ extra space but $O(N^2)$ time with nested loops. |
$O(N)$ space for the Hash Set. |
| 2155 |
All Divisions With the Highest Score of a Binary Array |
For every possible division point `i`, iterate through the left side to count 0s and the right side to count 1s. |
Nested loops scanning left and right for every index. |
Draw an array. Draw a divider at index 1. Count 0s on left, 1s on right. Move divider to index 2. Recount everything. $O(N^2)$. |
Prefix Sum / Running Count. |
A slider that updates two counters as it moves. |
Calculate total 1s initially. Iterate through array: if current is 0, `leftZeros++`. If current is 1, `rightOnes--`. `Score = leftZeros + rightOnes`. Track max score. |
Write the array. Above it, write the total count of 1s. Slide a pencil along the array; if you pass a '0', add 1 to your "Left" tally. If you pass a '1', subtract 1 from your "Right" tally. Sum them. |
$O(N)$ single pass. |
A single horizontal arrow scanning left to right, updating two integer variables in $O(1)$. |
No extra memory. |
$O(1)$ auxiliary space (excluding the result list). |
| 2156 |
Find Substring With Given Hash Value |
Iterate through every possible substring of length k, calculate the rolling hash from scratch for each. |
A sliding window where the entire window contents are re-processed at every step. |
Draw a string. Draw a bracket of size k. Draw arrows calculating hash. Move bracket 1 step. Redraw all arrows. $O(N \cdot k)$. |
Rolling Hash (Rabin-Karp) - Reversed. |
A "Sliding Window" that updates only the edges. |
Process the string from right to left. Subtract the contribution of the character leaving the window and add the new character. Using `(hash * power + val) % modulo`. |
Draw a string. Draw a bracket at the very end. Move it one character left. Write the math: `NewHash = (OldHash * power + NewChar - OldChar * power^k)`. |
$O(N)$ single linear pass. |
A single horizontal arrow moving right-to-left across the string. |
Multiple $O(k)$ substring objects created and discarded. |
$O(1)$ auxiliary space (storing current hash and power variables). |
| 2157 |
Groups of Strings |
Compare every pair of strings. Check if they are connected by 1 addition, 1 deletion, or 1 replacement. |
An $O(N^2)$ fully connected graph comparison. |
Draw N dots. Draw lines between every single dot and check the rules for each line. Write $O(N^2 \\text{cdot length})$. |
Bitmasking + Disjoint Set Union (DSU). |
Merging bubbles together based on shared attributes. |
Represent each string as a 26-bit integer. For each bitmask, check its variations (flip one bit for add/delete, flip two for replace). Use a Map to see if those variations exist and `union()` them. |
Draw bitmasks as binary strings. Draw a "Variation Factory" that flips 1 bit at a time. If the factory output matches another string, draw a circle around both to group them. |
$O(N \cdot 26)$ or $O(N \cdot 26^2)$ depending on replacement logic. |
A vertical list of N strings, each branching into 26 constant-time lookups. |
$O(N^2)$ graph adjacency list. |
DSU `parent` and `size` arrays (O(N)) + Hash Map of bitmasks. |
| 2158 |
Amount of New Area Painted Each Day |
For each day, iterate through the given interval `[start, end]`. Use a boolean array to mark cells as painted. Only count if not marked. |
Painting over a wall where some spots are already wet. |
Draw a 50,000-cell line. For day 1, shade cells 1-5. For day 2, try shading 3-7, but only count 6-7. Write $O(N \\text{cdot Range})$. |
Merge Intervals / Segment Tree / Jump Pointers (DSU). |
A "Skip List" where you leap over already painted segments. |
Use DSU to point each index to its next unpainted neighbor. When painting index `i`, count it, then `parent[i] = find(i + 1)`. |
Draw a number line. If you paint a segment, draw an arched "jump" arrow from the start to the end of that segment. Next time you land in it, follow the jump immediately. |
Amortized $O(N + \text{Range})$. |
A horizontal line with "teleportation" paths that shorten the distance of the scan. |
$O(N \\text{cdot Range})$ nested loops. |
$O(\text{Range})$ array for DSU or Segment Tree nodes. |
| 2159 |
Order Two Columns Independently (SQL) |
Complexity is in the logic. Brute force would be a cross join and filtering, which is highly inefficient. |
A Cartesian product shrinking down. |
Draw Table A. Draw Table B. Connect every row of A to every row of B. Filter out 99% of it. |
Window Functions (`ROW_NUMBER`). |
Two separate parallel sorted lists. |
Rank Column 1 by value. Rank Column 2 by value. Join the two lists where `Rank1 == Rank2`. |
Draw two separate vertical lists. Sort the first list. Sort the second list. Draw straight horizontal lines connecting the 1st items, 2nd items, etc. |
$O(N \log N)$ database sorting. |
Two funnels (sorting) feeding into a single zipper (join). |
Massive temporary tables for intermediate joins. |
In-memory sorting buffers (O(N)). |
| 2160 |
Minimum Sum of Four Digit Number After Splitting Digits |
Generate all possible permutations of the 4 digits and all possible ways to split them into two numbers. |
A small exhaustive search tree. |
Draw 4 digits. Branch into all 24 permutations. For each, try split (1,3) and (2,2). $O(4!)$. |
Greedy (Sorting). |
Pairing the smallest available values with the highest available decimal places. |
Sort the 4 digits: `d1, d2, d3, d4`. The minimum sum is always `(d1 * 10 + d3) + (d2 * 10 + d4)`. |
Write the 4 digits. Sort them. Take the two smallest and put them in the "Tens" column. Take the two largest and put them in the "Ones" column. Add. |
$O(1)$ (since N is always 4). |
A single dot representing a constant time operation. |
Array of 24 permutation strings. |
$O(1)$ array of size 4. |
| 2161 |
Partition Array According to Given Pivot |
Scan array multiple times: once for elements < pivot, once for = pivot, once for > pivot. Concatenate results. |
Multiple linear sweeps across the same track. |
Draw an array. Draw three separate lines underneath it, each picking only specific elements to form new arrays. $O(N)$. |
Three-Pointer Simulation (Single-Pass Result Array). |
Three distinct funnels feeding into a single sorted conveyor belt. |
Initialize result array. Use `low` pointer at start, `mid` count for pivots, and `high` for greater elements. Or simply iterate and fill in order. |
Draw the original array. Draw an empty target array. Draw arrows for all elements < pivot first, then all pivots, then all elements > pivot. |
$O(N)$ single linear pass. |
A single horizontal line moving left to right once. |
Temporary sub-lists for each partition $O(N)$. |
Single pre-allocated result array $O(N)$. |
| 2162 |
Minimum Cost to Set Cooking Time |
Try every single possible combination of buttons (00:00 to 99:99) and check if they sum to the target seconds. |
Exhaustive list of timestamp strings. |
Draw a clock. Write out "99 seconds" as "01:39" and "00:99". Calculate costs for both. Write $O(1)$ (Fixed Search). |
Greedy (Two-Candidate Check). |
Comparing two specific "paths" on a numeric keypad. |
Convert target seconds to `mins:secs`. Candidate 1: `mins` and `secs` (if `secs < 100`). Candidate 2: `mins-1` and `secs+60` (if `mins > 0`). Calculate push/move cost for both. |
Draw a 3x3 phone keypad. Trace the finger movement for "1-3-9" vs "9-9". Mark each button press and finger slide with a cost. |
$O(1)$ (Only 2 cases to check). |
Two dots representing the only two logical possibilities. |
No significant memory used. |
$O(1)$ primitive variables for costs. |
| 2163 |
Minimum Difference in Sums After Removal of Elements |
For every possible split point, calculate the min-sum of the left N elements and max-sum of the right N elements. |
$O(N^2)$ total work: sorting subsets at every split point. |
Draw an array of size 3N. Place a divider. Sort left and right parts. Move divider. Repeat. $O(N^2 \log N)$. |
Two Heaps (Priority Queues) + Prefix/Suffix Sums. |
A balance scale being adjusted by swapping the "heaviest" and "lightest" weights. |
Build `leftMin[i]` using a Max-Heap to keep the N smallest elements. Build `rightMax[i]` using a Min-Heap for N largest. `Result = min(leftMin[i] - rightMax[i+1])`. |
Draw two arrays for sums. Use a small triangle (Heap) to track elements. When a new small number arrives, pop the largest from the Max-Heap. Record the sum. |
$O(N \log N)$ heap operations. |
A linear scan with a "bubble" (Heap) floating above it, processing each element in log(N). |
Creating sub-arrays for every split $O(N^2)$. |
$O(N)$ for two sum arrays and a Priority Queue. |
| 2164 |
Sort Even and Odd Indices Independently |
Extract even indices into one list and odd into another. Sort each. Interleave them back into the original array. |
Splitting a braid into two strands, smoothing them, and braiding them back. |
Draw an array. Pull out elements at 0, 2, 4... into a box. Pull out 1, 3, 5... into another. Sort. Re-plug them. $O(N \log N)$. |
In-Place Extraction + Sorting. |
Two separate parallel sorted lists. |
Sort even-index elements in non-decreasing order. Sort odd-index elements in non-increasing order. Use custom comparators. |
Draw the array. Put a square around even indices and a circle around odd. List the squares and sort them. List the circles and sort them (reversed). Map them back. |
$O(N \log N)$ due to sorting. |
Two funnels (sorting) feeding back into a single array structure. |
$O(N)$ to store extracted lists. |
$O(N)$ for intermediate storage (standard sorting memory). |
| 2165 |
Smallest Value of the Rearranged Number |
Generate all permutations of digits, convert to long, check for leading zeros, find minimum. |
Factorial explosion of digit combinations. |
Draw "310". List: 013, 031, 103, 130, 301, 310. Pick 103. $O(D!)$. |
Greedy Sorting. |
A numeric keypad sorting logic. |
If positive: Sort digits ascending. If smallest is '0', swap it with the first non-zero digit. If negative: Sort digits descending and keep the '-' sign. |
Write the digits. If positive, sort them: 0, 1, 3. Find the first non-zero (1), move it to the front: 1, 0, 3. If negative, sort 3, 1, 0: -310. |
$O(D \log D)$ where D is number of digits (Max 15). |
A single sorting funnel followed by a constant-time swap. |
$O(D!)$ list of strings. |
$O(D)$ char array/frequency array. |
| 2166 |
Design Bitset |
Actually flip every bit in an array when `flip()` is called. |
$O(N)$ for every single flip operation. |
Draw a row of 100 boxes. For every 'flip' command, draw a hand manually changing every 0 to 1. $O(F \cdot N)$. |
Lazy Flipping (Flag + Two Arrays). |
A mirror that you can choose to look through or not. |
Maintain a `flipped` boolean. If true, interpret 0 as 1 and 1 as 0. Maintain two strings (one normal, one flipped) for `toString()`. |
Draw two bit-rows (Original vs. Inverted). Draw a toggle switch labeled "View". If switched to Inverted, read the second row. `flip()` just flips the switch. |
$O(1)$ for all operations (except toString). |
A single dot representing instant toggle, with a one-time linear line for string conversion. |
A single integer array or boolean array. |
Two separate BitSet arrays or strings + 1 boolean flag (O(N)). |
| 2167 |
Minimum Time to Remove All Cars Containing Illegal Goods |
Try every possible combination of removing from the left, removing from the right, and removing from the middle. |
Exponential branching of removal choices. |
Draw a train. Branch into: "Remove head", "Remove tail", or "Remove inner car at cost 2". $O(3^N)$. |
Dynamic Programming / Prefix-Suffix Min. |
A water level rising from both ends. |
`left[i]` = min cost to clear illegal cars from start to `i`. `right[i]` = min cost from end back to `i`. Answer is `min(left[i] + right[i+1])`. |
Draw the train. Underneath, write the cost of deleting everything from the left. Do the same from the right. At each car, sum the two costs and find the lowest. |
$O(N)$ single linear pass. |
Two straight horizontal arrows (Left-to-Right and Right-to-Left) followed by a final comparison sweep. |
Deep recursive stack frames (O(N)). |
Two 1D arrays of size N for prefix and suffix costs. |
| 2168 |
Unique Substrings With Equal Digit Frequency |
Generate all substrings, count frequencies for each, check equality, and add to a Set. |
Redundant frequency counting and string hashing. |
Draw a string. For every substring, draw a separate frequency table. $O(N^3)$. |
Rolling Hash (Rolling Frequencies) + Trie. |
A tree where each path is a unique substring being counted on the fly. |
Iterate from each starting index. As you extend the substring, update the digit frequency map and verify the "Equal Frequency" condition in $O(1)$. |
Draw a "Root" node. For "1212", draw a path 1 -> 2 -> 1 -> 2. At each node, check if all digits seen so far have the same count. Circle valid nodes. |
$O(N^2)$ double-loop with $O(1)$ checks. |
An upper-triangular matrix of checks performed in a single sweep. |
$O(N^3)$ memory for millions of stored substring strings in a Set. |
A Trie structure or a Set of Longs (Hashes) to store uniqueness (O(N^2)). |
| 2169 |
Count Operations to Obtain Zero |
Simulation: Use a `while` loop to subtract the smaller from the larger until one is zero. |
A staircase of subtractions. |
Draw two bars (Num1, Num2). Chop the shorter bar off the taller one. Repeat until a bar disappears. $O(\text{Num}1 + \text{Num}2)$. |
Math (Euclidean-like division). |
A fast-forward button on the subtraction process. |
`count += num1 / num2`. `num1 %= num2`. This jumps multiple subtractions in one step. |
Draw 100 and 7. Instead of 7+7+7..., draw a box labeled "14" and write "14 times". Use the remainder for the next step. |
$O(\log(\text{min}(\text{num}1, \text{num}2)$)) - logarithmic time. |
A steep curve dropping rapidly toward zero. |
No significant memory. |
$O(1)$ space, single counter variable. |
| 2170 |
Minimum Operations to Make the Array Alternating |
Try every possible combination of two numbers for even and odd positions. |
$O(U^2)$ where U is the number of unique elements. |
Draw two lists: "Possible Evens" and "Possible Odds". Draw lines connecting every item in List A to List B. $O(N^2)$. |
Frequency Counting + Top 2 Candidates. |
A podium for the two most popular numbers. |
Find the two most frequent numbers for even indices and the two most frequent for odd indices. If the top ones differ, use them. If they match, pick the next best pairing. |
Draw two tally boards (Even indices vs Odd indices). Pick the winner and runner-up for both. Write them in a 2x2 grid to find the best pair that isn't the same number. |
$O(N)$ frequency count + $O(1)$ top-2 comparison. |
A single pass to fill the buckets, then a constant-time 4-way comparison. |
$O(N)$ for intermediate pair arrays. |
Two Frequency Maps (size $O(N)$). |
| 2171 |
Removing Minimum Number of Magic Beans |
Try making every possible number of beans (from 0 to max) the "target level" for all bags. |
A scanning horizontal line moving up through a bar chart, recalculating all areas. |
Draw a bar chart. Draw a horizontal line. Shade everything above it and cross out everything below it. Repeat for every height. $O(N \\text{cdot MaxValue})$. |
Sorting + Math (Prefix Sum Logic). |
A single horizontal "cut" that maximizes the remaining rectangle. |
Sort bags. If we pick bag `i` as the minimum level, the total remaining beans will be `beans[i] * (n - i)`. Cost = `Total - Remaining`. |
Draw bars in increasing order. For each bar, draw the largest rectangle that fits under it and to the right. The "beans to remove" is the white space outside that rectangle. |
$O(N \log N)$ sorting. |
A sorting funnel followed by a single straight line scanning for the maximum product. |
Deep iteration through value ranges. |
$O(1)$ auxiliary space (if sorted in place). |
| 2172 |
Maximum AND Sum of Array |
Try every permutation of putting N numbers into M slots (max 2 per slot) and calculate total AND sum. |
Massive factorial/exponential tree of assignments. |
Draw N numbers and M slots. Draw lines connecting numbers to slots. Branch into every valid mapping. $O(M^N)$. |
Bitmask DP (Ternary/Base-3 or Base-2 with double slots). |
A puzzle board where each cell represents a state of "slots filled". |
`dp[mask]` = max sum for assigned numbers. Mask tracks how many items are in each slot (0, 1, or 2). Use memoization. |
Draw a grid. Let each column represent a slot. Use a 2-bit counter for each column. Iterate through numbers and "fill" the counters, updating a max_sum table. |
$O(N \cdot 3^M)$. |
A lattice of states where each layer represents the number of elements processed. |
$O(M^N)$ recursive state storage. |
$O(3^M)$ DP array/memoization table. |
| 2173 |
Longest Winning Streak (SQL) |
For each player, fetch all matches, find all contiguous subsegments of 'Win', and find max length. |
Row-by-row nested scanning for every player. |
Draw player names. For each, scan their match list. Find 'W, W, L'. Reset counter. Find 'W, W, W'. $O(\text{Players} \\text{cdot Matches})$. |
Window Functions (Gaps and Islands). |
Grouping "islands" of wins by subtracting row numbers. |
Assign `ROW_NUMBER()` to all matches. Assign `ROW_NUMBER()` only to wins. `Island_ID = All_RN - Win_RN`. Wins with the same ID belong to the same streak. |
Draw two columns of numbers. Col A: 1,2,3,4,5. Col B (only for wins): 1,2,4,5. Subtract B from A: 0,0,1,0. Identical 0s form a streak. |
$O(N \log N)$ database sorting. |
Parallel tracks being compared to find where the "synchronization" breaks. |
Application-side processing of large result sets. |
$O(N)$ database memory for window sorting. |
| 2174 |
Remove All Ones With Row and Column Flips II |
BFS/DFS to try flipping every possible row and column containing a '1' in every possible order. |
State space tree of grid transformations. |
Draw a 2D grid. Branch into R+C new grids for every '1' you encounter. $O(2^(R\cdot C)$). |
Bitmask DP / Backtracking with State Compression. |
An "On/Off" switchboard for the whole grid. |
Represent grid as a bitmask. For each '1' at (r, c), generate a new mask where row `r` and col `c` are all 0. Find min steps to reach mask 0. |
Draw the grid. For a '1' at (0,0), draw a horizontal and vertical "eraser" line. Repeat until the page is blank. Count the number of eraser lines used. |
$O(2^(R\cdot C)$ * R * C). |
A directed graph of grid states moving toward the "all-zero" sink node. |
Huge queue of matrix objects. |
$O(2^15)$ (max grid size 15) memoization table. |
| 2175 |
The Change in Global Rankings (SQL) |
Calculate rank for every player. Update points. Re-calculate rank for every player. Compare. |
Two full table scans and two full sorting passes. |
Draw a leaderboard. Sort. Change one value. Sort again. Compare old index to new index. $O(N \log N)$. |
Window Functions (`RANK()` or `ROW_NUMBER()`). |
Two static snapshots of a leaderboard joined by Player ID. |
`RANK() OVER(ORDER BY points)` for initial. `RANK() OVER(ORDER BY (points + change))` for final. Join on `player_id` and subtract. |
Draw two parallel lists. Draw lines from "Player A" in List 1 to "Player A" in List 2. Calculate the vertical distance moved. |
$O(N \log N)$ due to sorting requirements for Ranking. |
Two sorting funnels feeding into a single hash join. |
Temporary tables for snapshot storage. |
$O(N)$ sort buffers. |
| 2176 |
Count Equal and Divisible Pairs in an Array |
Nested loops checking every pair (i, j) where i < j. Check if nums[i] == nums[j] and (i * j) % k == 0. |
An upper-triangular matrix of pair comparisons. |
Draw an N x N grid. Shade the top-right triangle. Each cell check is one $O(1)$ condition. Write $O(N^2)$. |
Frequency Hash Map (Value -> List of Indices). |
Grouping same-colored balls into buckets before checking internal connections. |
Group indices by value. For each group, perform a nested loop over the indices list. If index_i * index_j % k == 0, increment count. |
Draw buckets for each unique number. Put indices 0, 2, 5 into Bucket "3". Draw lines between 0, 2, and 5. Check the math (0*2%k, 0*5%k, etc.) only for these connected lines. |
$O(N^2)$ worst case (if all numbers same), but $O(N)$ average case with distinct values. |
A collection of small, isolated star-graphs (cliques) within the array. |
No extra memory (in-place nested loops). |
Hash Map mapping Integer -> List of Integers (O(N) space). |
| 2177 |
Find Three Consecutive Integers That Sum to a Number |
Iterate from 1 to N/3, checking every triplet (x, x+1, x+2) to see if they sum to N. |
A sliding window of size 3 scanning a massive range. |
Draw a long number line. Slide a small 3-cell box and check the sum in each position. Write $O(N)$. |
Math (Algebraic Equation). |
A balance scale with three equal parts and a remainder. |
Equation: x + (x+1) + (x+2) = N -> 3x + 3 = N -> 3x = N - 3. If (N-3) % 3 == 0, result is [x, x+1, x+2]. |
Write the number N. Subtract 3. Check if the remaining number can be divided into 3 equal blocks. If yes, those blocks are your answer. |
$O(1)$ constant time. |
A single dot representing an instant mathematical formula. |
Looping through potentially billions of integers. |
$O(1)$ auxiliary space (just 3 long variables). |
| 2178 |
Maximum Split of Positive Even Integers |
Recursively try every combination of even integers to see which set sums to N. |
A subset-sum style decision tree. |
Draw N. Branch into 2, 4, 6, 8... For each, branch again. $O(2^N)$. |
Greedy (Smallest Even Strategy). |
Filling a container with the smallest possible even blocks first. |
If N is odd, return empty. Otherwise, take 2, 4, 6... until the remaining sum is less than the next even number. Add that remainder to the last number in the list. |
Draw a bar of length N. Cut a piece of length 2. Cut a piece of length 4. Keep cutting until you can't cut a piece larger than the previous. Take the "scrap" and weld it onto the last piece. |
$O(\text{sqrt}(N)$) because the sum of 2+4+...+2k grows quadratically. |
A staircase that grows until its height matches the target. |
Massive recursion stack for backtracking. |
$O(\text{sqrt}(N)$) to store the resulting list. |
| 2179 |
Count Good Triplets in an Array |
Three nested loops to check indices i < j < k in array A and their relative positions in array B. $O(N^3)$. |
Cubic Position Matching |
Draw Array A and B. Pick 3 elements in A. Draw lines trying to find them in the exact same order in B. |
Fenwick Tree (BIT) / Index Mapping |
The Pivot-Counting Scales |
Map elements of A to their indices in B. For each element acting as the middle of the triplet, use a Fenwick tree to count how many valid elements are to its *left*, and math to find how many are to its *right*. Multiply them. |
Draw the mapped array. Pick a pivot. Look left: "How many smaller numbers?" (Use BIT). Look right: "How many larger?" (Total larger - already seen larger). Multiply Left \times Right. |
Logarithmic Updates $O(N \log N)$ |
Draw a linear scan. Above each step, draw a log-height traversal up a Binary Indexed Tree. |
None, purely CPU bound. |
Two arrays of size N (mapping and BIT). $O(N)$ space. |
| 2180 |
Count Integers With Even Digit Sum |
Loop from 1 to N. For each number, convert to string or use modulo to sum digits. Increment count if sum is even. |
Linear scan with digit decomposition. |
Draw a line of numbers. Under each, write its digit sum. Circle the even ones. Write $O(N \cdot \log N)$. |
Math / Parity Analysis. |
A pattern that repeats every 10 or 20 numbers. |
If the digit sum of N is even, the answer is floor(N/2). If N is even but the sum is odd, it's (N/2)-1. Generally, if digit_sum(N) is even, floor(N/2) otherwise floor((N-1)/2). |
Write numbers 1-20. Sum their digits. Notice the alternating pattern: Even, Odd, Even, Odd... If N is even, the sum of its digits tells you if the "even count" ends on a high or low note. |
$O(\log N)$ to sum the digits of the upper bound N once. |
A single vertical drop (digit sum) followed by an $O(1)$ subtraction. |
No significant memory used. |
$O(1)$ extra space. |
| 2181 |
Merge Nodes in Between Zeros |
Extract all non-zero node values into a list, iterate the list to sum segments between imaginary zeros, and create a new Linked List. |
Dumping a chain into a bucket, then building a new chain. |
Draw a linked list. Draw arrows moving values to a temporary array. Draw a second set of arrows building new nodes. $O(N)$. |
In-Place Two Pointers / Link Manipulation. |
A single pointer moving forward and "consuming" the nodes behind it. |
Use two pointers: `curr` to read and `res` to write. Sum nodes until `curr.val == 0`. Assign sum to `res.next`, move `res`. |
Draw the list. Circle nodes between two zeros. Draw a heavy arrow from the first zero to a new node containing the sum of the circle. Delete the old nodes. |
$O(N)$ single linear pass. |
A single horizontal arrow moving through the nodes, stopping at each zero to perform a sum. |
$O(N)$ extra space for the temporary list and new nodes. |
$O(1)$ auxiliary space (modifying the existing list nodes). |
| 2182 |
Construct String With Repeat Limit |
Generate all possible permutations of characters, check repeat limits, and find the lexicographically largest. |
Factorial explosion of character strings. |
Draw 'a, a, b'. List: 'aba', 'baa', 'aab'. Pick 'baa'. Write $O(N!)$. |
Greedy + Frequency Array (Counting Sort). |
A tall chimney where you always pull from the highest level (largest char). |
Count frequencies of 'z' down to 'a'. Take as many of the largest char as `repeatLimit` allows. If more remain, take exactly one of the next available smaller char to "break" the streak. |
Draw a frequency bar chart for each letter. Take 3 blocks from 'z'. If more 'z's are left, take 1 block from 'y'. Go back to 'z' and take another 3. |
$O(N)$ linear time (Max 26 iterations per append). |
A descending scanner that jumps between the two highest non-empty buckets. |
Storing N! strings in a list. |
$O(1)$ extra space (Frequency array of size 26). |
| 2183 |
Count Array Pairs Divisible by K |
Nested loops checking every pair (i, j) where (nums[i] * nums[j]) % k == 0. |
Full quadratic matrix of pair multiplications. |
Draw an N x N grid. Shade the top triangle. Each cell performs a multiplication and modulo. $O(N^2)$. |
Number Theory (GCD + Frequency Map). |
Grouping numbers by their "Shared DNA" with K. |
For each number, find its `gcd(num, k)`. Store frequencies in a map. For any two GCDs `g1` and `g2`, if `(g1 * g2) % k == 0`, pairs = `freq[g1] * freq[g2]`. |
Draw a table of all divisors of K. For each number in the array, put it into a divisor bucket based on its GCD with K. Cross-multiply buckets that satisfy the condition. |
$O(N + \text{Divisors}^2)$. |
A pass to fill buckets, then a small nested loop over the limited number of divisors. |
No extra memory (in-place checks). |
Frequency Map of divisors (O(sqrt(k)) space). |
| 2184 |
Number of Ways to Build Sturdy Brick Wall |
Recursively try every combination of bricks for every row, checking every joint against the row below. |
Exponential branching of row configurations. |
Draw row 1. Branch into all 20 possible brick patterns. For each, branch into row 2 patterns. $O(\text{Patterns}^\text{Height})$. |
Bitmask DP + State Compression. |
A graph where nodes are "Row Patterns" and edges are "Compatibility". |
1. Find all possible row patterns as bitmasks (bits = joint positions). 2. Pre-calculate which masks don't have overlapping bits. 3. `dp[row][mask]` = ways to end current row with this mask. |
Draw a single row. Mark the cracks between bricks. Represent as 10100. Draw a second row. If its cracks are 01010, they don't line up—"Sturdy!" Write a transition between these two states. |
$O(\text{Height} \\text{cdot Patterns}^2)$. |
A layered graph where each layer represents a row in the wall. |
Deep recursion stack. |
$O(\text{Height} \\text{cdot Patterns})$ for the DP table. |
| 2185 |
Counting Words With a Given Prefix |
Loop through the array. For each word, use `word.substring(0, pref.length())` and compare it to the prefix. |
Linear scan with substring allocations. |
Draw words. Draw a "lens" of length K. Look through the lens at the start of each word. Circle if match. $O(N \cdot M)$. |
String Comparison (In-place `startsWith`). |
A sliding filter that only looks at the first few characters. |
For each word, check if `word[i] == pref[i]` for all `i` up to `pref.length`. If any character mismatches or word is too short, skip. |
Write words in a list. Write prefix on a separate card. Slide the card over the start of each word. Tally the perfect overlaps. |
$O(N \cdot L)$ where L is prefix length. |
A single horizontal arrow scanning the words, with a small vertical comparison at the start of each. |
$O(N \cdot L)$ space due to many temporary substring objects. |
$O(1)$ auxiliary space (using direct character comparison). |
| 2186 |
Minimum Number of Steps to Make Two Strings Anagrams II |
Generate all character counts, then iterate and check differences by repeatedly scanning both counts. |
Two separate buckets, measuring the weight of each item one by one. |
Draw two lists of characters. For every 'a' in S, look for 'a' in T. If missing, count it. $O(N + M)$. |
Frequency Array (Counting Sort). |
A balance scale comparing two sets of weights. |
Count frequencies of 'a'-'z' for both strings in two arrays of size 26. Sum the absolute difference: `abs(countS[i] - countT[i])`. |
Draw two 26-slot tables. Tally the characters of S in Table 1 and T in Table 2. Subtract the counts and sum the absolute results. |
$O(N + M)$ single pass per string. |
Two straight horizontal lines scanning the strings, followed by a constant-time 26-step loop. |
$O(N + M)$ space if using frequency maps with objects. |
$O(1)$ extra space (Two fixed-size arrays of 26 integers). |
| 2187 |
Minimum Time to Complete Trips |
Iterate through every possible second (1, 2, 3...) and calculate the total trips done by all buses. |
A clock ticking upwards until the trip goal is met. |
Draw a timeline. At t=1, check trips. At t=2, check trips. Repeat until total >= totalTrips. $O(\text{totalTrips} \\text{cdot maxTime})$. |
Binary Search on Answer. |
A horizontal laser scanning up and down to find the minimum threshold. |
Choose `mid` time. Calculate `TotalTrips = sum(mid / time[i])`. If >= target, search left; else search right. |
Draw a number line for time. Pick the middle. For each bus, calculate how many times it "fits" into that middle. Sum them up and compare to the goal. |
$O(N \log(\text{MaxTime})$). |
A binary search tree narrowing down on a single horizontal time value. |
Massive loop variables and deep stacks if recursive. |
$O(1)$ auxiliary space (just bounds and sum variables). |
| 2188 |
Minimum Time to Finish the Race |
Recursively calculate the cost of doing every possible number of laps with every possible tire. |
Exponential branching race track. |
Draw 10 laps. Branch into 10 choices (tires) for Lap 1, then another 10 for Lap 2. $O(T^L)$. |
Dynamic Programming + Precomputed Best Times. |
A staircase where each step looks at the best "leap" possible from previous steps. |
1. Precompute `best[i]`: min time to finish `i` laps with a *single* tire. 2. `dp[i] = min(dp[i-k] + best[k] + changeTime)`. |
Draw a line of laps 1 to N. For each lap, draw multiple "arches" representing finishing `k` laps with one tire and then switching. Pick the path with the smallest total length. |
$O(\text{Laps} \\text{cdot MaxLapsSingleTire})$. |
A directed graph where nodes are laps and edges are the min time for a set of laps with one tire. |
Deep recursive call stack. |
$O(N)$ for the DP table and precomputed array. |
| 2189 |
Number of Ways to Build House of Cards |
Recursively try building the house level by level, ensuring the current level has fewer triangles than the one below. |
A pyramid-building decision tree. |
Draw 3 cards for a triangle. Branch into how many triangles can be on the next level. $O(2^N)$. |
2D Dynamic Programming / Memoization. |
A grid where each cell stores the ways to use `n` cards with `k` triangles on the base. |
`dp(cardsLeft, prevBase)`: Iterate through possible `currBase` (must be < `prevBase`). Subtract `3 * currBase - 1` from `cardsLeft`. |
Draw a house of cards. Write the number of cards used. Move up a level and draw a smaller base. Track the remaining cards in a tally box. |
$O(N^2)$ state space. |
A 2D matrix being filled row by row. |
Exponential recursive state space. |
$O(N^2)$ memoization table. |
| 2190 |
Most Frequent Number Following Key In an Array |
For every occurrence of `key`, iterate through the rest of the array to find what follows and count them. |
A searchlight finding the `key` and then scanning everything else repeatedly. |
Draw an array. Highlight the `key`. Look at the next number. Scan and tally that number in a list. Repeat. $O(N^2)$. |
Single-Pass Frequency Map. |
A tally board updated by a single pointer. |
Iterate from 0 to N-2. If `nums[i] == key`, increment the count of `nums[i+1]` in a frequency map. Track the max frequency on the fly. |
Draw the array. Every time you see the `key`, draw an arrow to its neighbor. Circle that neighbor and add a tally mark to its name in a side-box. |
$O(N)$ single pass. |
A single horizontal line scanning left to right, updating an $O(1)$ lookup table. |
$O(N^2)$ space for redundant lists. |
$O(N)$ for the frequency map (worst case: all unique followers). |
| 2191 |
Sort the Jumbled Numbers |
For every comparison in a sort, re-calculate the mapped value of both numbers by iterating through their digits. |
A sorting algorithm where the "Comparison" step is an expensive $O(\text{Digits})$ function. |
Draw a sorting network. At every cross-over, draw a converter box that turns 345 -> 891. $O(N \log N \cdot D)$. |
Pre-calculation + Stable Sorting. |
A two-column lookup table (Original Value | Mapped Value). |
Iterate through `nums` once. Convert each to its jumbled form and store as a pair `(mappedValue, originalIndex)`. Sort the list of pairs. |
Draw a T-chart. On the left, write the input number. On the right, replace each digit using the mapping array. Sort the T-chart based on the right column. |
$O(N \log N)$ sorting + $O(N \cdot D)$ pre-calc. |
A single pass through a "Translator" funnel, followed by a standard sorting track. |
Repeated string/digit conversions in the middle of sorting. |
$O(N)$ to store the pre-calculated mapped values and original indices. |
| 2192 |
All Ancestors of a Node in a DAG |
For each node, perform a full DFS/BFS to find all nodes that can reach it. |
N separate traversals of the entire graph. |
Draw a graph. For Node 1, color all reachable nodes. Clear. For Node 2, repeat. $O(N \cdot (V + E)$). |
Reverse Graph Traversal or Topological Sort. |
"Spreading a signal" backwards through a network. |
Reverse all edges. For each node `i`, perform one DFS to find all reachable nodes—these are ancestors. Use a boolean array to avoid cycles/duplicates. |
Draw the graph with arrows flipped. Start at Node 0. Follow all paths out. Any node you touch, write "0" in its ancestor list. Move to Node 1. Repeat. |
$O(N \cdot (V + E)$). (The complexity remains same but constant factor/efficiency improves with sorted set merging). |
A series of N wave-expansions from each source node. |
Massive redundant path storage. |
$O(N^2)$ for the result adjacency list (ancestors). |
| 2193 |
Minimum Number of Moves to Make Palindrome |
Generate all permutations of the string and find the one that is a palindrome with the minimum swap distance. |
Factorial search space of character arrangements. |
Draw 'aabb'. List all 24 permutations. Calculate swap distance to 'abba', 'baab'. $O(N!)$. |
Greedy (Two Pointers). |
A pair of bookends moving toward the center, fixing one letter at a time. |
Place pointer `L` at start, `R` at end. For `s[L]`, find the rightmost match `s[k]`. Swap `s[k]` to position `R`. Move `L++`, `R--`. Handle middle char specifically. |
Write the string. Point to the first letter. Find its twin near the end. Draw an arrow "hopping" the twin to the very last position. Count the hops. Shrink the window. |
$O(N^2)$ due to searching and swapping. |
A shrinking box where each step involves a linear scan inside the box. |
$O(N!)$ storage for permutations. |
$O(N)$ for string manipulation/character array. |
| 2194 |
Cells in a Range on an Excel Sheet |
Parse the string, then use nested loops with string conversions and character math to build every coordinate. |
A grid-filling simulation. |
Draw 'A1:B2'. Draw a 2x2 grid. Manually write A1, A2, B1, B2. $O(\text{Rows} \\text{cdot Cols})$. |
Nested Char Loops. |
A nested scanner moving through a spreadsheet. |
Extract startCol, endCol, startRow, endRow. Outer loop `c` from startCol to endCol. Inner loop `r` from startRow to endRow. Append `c + r`. |
Write the start 'K' and end 'L'. Write the numbers 1 to 3. Draw a table. Fill 'K' column first (K1, K2, K3), then move to 'L' column. |
$O(\text{Total Cells})$ linear to output size. |
A single horizontal line that "steps" into a vertical loop at each increment. |
Intermediate string parsing and type casting. |
$O(N)$ to store the list of resulting coordinate strings. |
| 2195 |
Append K Integers With Minimal Sum |
Iterate from 1 upwards. If a number is not in `nums`, add it to the sum and decrement K. Repeat until K=0. |
A linear search starting from 1 that could go up to 10^9. |
Draw a number line. If a number is in the array, skip it. If not, circle it. Keep circling until you have K circles. $O(K \cdot N)$. |
Sorting + Arithmetic Progression. |
A mathematical formula that "fills the gaps" between sorted numbers. |
Sort and de-duplicate `nums`. Calculate sum of first K integers `K*(K+1)/2`. For each `x` in `nums`, if `x <= K`, subtract `x`, increment `K`, and add the new `K` to the sum. |
Draw a number line with gaps. Calculate the sum of 1 to K. If you find a number `x` in your array that is \le K, it "steals" a spot. Cross it out and take the next available number (K+1). |
$O(N \log N)$ for sorting. |
A sorting track followed by a single linear "Gap filler" pass. |
$O(N)$ for a HashSet to check existence in the brute force. |
$O(1)$ auxiliary space (after sorting). |
| 2196 |
Create Binary Tree From Descriptions |
For every description, scan all previously created nodes to find the parent and child. If not found, create them. |
$O(N^2)$ search through a growing list of orphan nodes. |
Draw a list of nodes. For a new description, draw arrows checking every node in the list. Write $O(N^2)$. |
Hash Map (Val -> Node) + Set (Child Tracking). |
A central warehouse (Map) that instantly retrieves any part needed for the machine. |
Iterate descriptions. Store nodes in a Map. Map `[parentVal] -> Node(parentVal)`. Link child to parent based on `isLeft`. Add child values to a 'Children' Set. The Root is the only parent not in the Children Set. |
Draw a Map box. For `[20, 15, 1]`, write 20 and 15 in the box. Draw an arrow from 20 to 15. Write "15" in a "Not Root" bucket. After the loop, pick the only number not in the bucket. |
$O(N)$ single pass. |
A straight horizontal line scanning descriptions, feeding into a single Map lookup. |
$O(N)$ search logic variables. |
$O(N)$ for the Hash Map and Child Set. |
| 2197 |
Replace Non-Coprime Numbers in Array |
Keep scanning the array from left to right. If two neighbors are non-coprime, replace them with their LCM. Repeat the entire scan until no more changes occur. |
A bubbling effect where a single change can trigger a chain reaction, requiring a full re-scan. |
Draw an array. Circle two items. Replace them. Go back to the very start of the array and check again. Write $O(N^2)$. |
Stack (Greedy Simplification). |
A chemical reaction where adding a drop triggers an immediate merge with the surface. |
Iterate through `nums`. Push `num` to a stack. While `stack.top()` and the new `num` are non-coprime, pop, compute `lcm`, and repeat the check with the new `top`. |
Draw a vertical stack. Drop a number in. If it reacts (GCD > 1) with the number below it, erase both and write their LCM. Repeat until no reaction occurs. |
Amortized $O(N \log(\text{MaxVal})$). |
A horizontal line with a vertical "pop-off" valve that runs in log time. |
Repeated array copies and multiple $O(N)$ passes. |
$O(N)$ for the result stack. |
| 2198 |
Number of Single Divisor Triplets |
Triple nested loops checking every combination (i, j, k) to see if their sum is divisible by exactly one of the numbers. |
Full cubic search space. |
Draw three pointers i, j, k. Move k across N, then j, then i. Write $O(N^3)$. |
Frequency Array + Triple Loop (Values 1-100). |
A small, dense grid representing the limited range of values. |
Count frequencies of values 1-100. Loop `a` from 1 to 100, `b` from `a`, `c` from `b`. Check the "single divisor" rule. If true, count = `freq[a] * freq[b] * freq[c]` (adjust for duplicates). |
Draw a frequency table (1: 5 times, 2: 10 times...). Pick three numbers from the table. If they pass the rule, multiply their frequencies. Sum the results. |
$O(V^3)$ where V=100 (Constant time effectively). |
A 100x100x100 tiny cube compared to an N^3 massive block. |
No extra memory. |
$O(1)$ extra space (Frequency array of size 101). |
| 2199 |
Finding the Topic of Each Post (SQL) |
For each post, scan the entire keywords table. Use `LIKE` or `REGEXP` for every keyword to see if it exists in the post. |
A Cartesian product of posts and keywords. |
Draw a Post. Draw lines to every single keyword in the Topic table. Repeat for every Post. Write $O(P \cdot K)$. |
SQL Join + String Aggregation. |
A filter that catches specific words and labels them. |
Join `Posts` and `Topics` where `post_content` contains the `word`. Group by `post_id`. Use `GROUP_CONCAT` or `STRING_AGG` on `topic_id` sorted alphabetically. |
Draw a table of posts. Draw a table of keywords. Draw lines only where a keyword exists in a post. Group the lines by post and list the topic IDs found. |
$O(P \cdot K)$ - SQL engines optimize this with indexing, but complexity remains bound to string searching. |
A funnel taking post/keyword pairs and outputting a single string per post. |
Large intermediate join tables. |
$O(P + K)$ database memory buffers. |
| 2200 |
Find All K-Distant Indices in an Array |
For every index `i`, scan the entire array to find if there exists an index `j` such that `nums[j] == key` and `abs(i - j) <= k`. |
A double loop checking the distance condition for every pair. |
Draw an array. For every index, draw arrows checking every other index for the 'key'. Write $O(N^2)$. |
Two Pointers / Single-Pass Sliding Window. |
A spotlight that illuminates a range around a target. |
Find all indices `j` where `nums[j] == key`. For each `j`, the range `[max(0, j-k), min(n-1, j+k)]` is valid. Use a pointer to keep track of the "last added index" to avoid duplicates. |
Draw an array. Circle all 'keys'. Draw a bracket of size 2k around each circle. Shade everything inside the brackets. The shaded indices are your answer. |
$O(N)$ linear time. |
A single horizontal pass marking intervals. |
N iterations of scanning. |
$O(N)$ for the result list. |
| 2201 |
Count Artifacts That Can Be Extracted |
Nested Loops
Iterate over every cell of each artifact, and linearly search the `dig` array every time to see if the cell is excavated. |
Cartesian Plane / Nested Loop Graph |
Draw a 2D matrix. For every cell inside an artifact, draw a line pointing to a linear scan of the entire `dig` array to highlight the $O(A \\text{cdot cells} \cdot D)$ multiplier. |
Hash Set / Direct Indexing |
Set Membership Diagram |
Create a "Dig Set" bucket. Point each cell of an artifact to the bucket. If all cells yield a "hit", tick the artifact as extracted. |
Draw the `dig` array being pushed into a circular "Hash Set". Draw artifacts as 2x2 blocks. Shade block cells green if they match a coordinate in the Set. |
Linear Timeline Partition |
Draw two distinct, non-overlapping timelines: $O(D)$ to build the Set, followed by a separate $O(A \\text{cdot cells})$ timeline to query. |
Array Memory Map (showing repeated scans of standard linear arrays). |
Hash Table Bucket Array (showing hashed coordinate tuples pointing to $O(1)$ boolean values). |
| 2202 |
Maximize the Topmost Element After K Moves |
Simulation / Backtracking
Recursively simulate every possible valid combination of popping and pushing elements up to K moves to find the max top. |
Decision Tree (N-ary) |
Draw a tree where each node branches into two choices: "Pop" or "Push". Count the depth up to K to show the exponential $O(2^K)$ explosion. |
Greedy / Math Analysis |
Array Indexing & Boundary Pointers |
Place a pointer over the array. Check the max of elements from index 0 to K-2. Then check the element at index K. Pick the maximum. |
Draw the array. Put a bracket over elements `[0` to `k-2]`. Circle the element at `[k]`. Cross out element `[k-1]`. Pick the largest circled/bracketed number. |
Single Pass Window Line |
Draw a single straight line spanning from index 0 to min(K, N). Write $O(K)$ above the line to show the time bounded strictly by K or N. |
Deep Call Stack Diagram (showing multiple recursive states pushing to stack memory). |
Single State Variables (showing a single `max_val` register updating in memory; $O(1)$ space). |
| 2203 |
Minimum Weighted Subgraph With the Required Paths |
DFS all paths
Find all paths from src1 to dest and src2 to dest. Combine every possible pair of paths to find the minimum subgraph. |
Combinatorial Graph Paths |
Draw a graph with paths branching everywhere. Highlight path 1 in red, path 2 in blue, and show the overlap. Write out permutations to show $O(V!)$ or $O(2^E)$ explosion. |
3-Way Dijkstra's Algorithm |
Intersection Point / Convergence Map |
Run Dijkstra from src1, src2, and dest (on reversed graph). For every node, calculate distance from src1 + src2 + dest. The node with the minimum sum is the intersection. |
Draw the graph. Shade `src1`, `src2`, and `dest`. Draw radiating "distance waves" from all 3 points. Where the three waves intersect with the lowest sum, draw a star. |
Priority Queue Timeline |
Draw 3 separate Priority Queues being processed. Write $O(E \log V)$ above each, showing they are sequential additions, not multiplicative. |
Adjacency List with massive path-history arrays carrying over per recursive step. |
Min-Heap Structure (showing node objects with current min-distance) alongside 3 static distance arrays. |
| 2204 |
Distance to a Cycle in Undirected Graph |
DFS per Node
For every single node in the graph, run a full DFS/BFS to find the shortest path to any node that belongs to a cycle. |
Repeated Graph Traversal Grids |
Draw the graph N times. For each drawing, start at a different node and trace the path to a cycle. Sum the operations to show $O(N \cdot (V+E)$). |
Kahn's Algorithm (Topological Sort) + Multi-source BFS |
Degree Trimming & Expanding Waves |
Peel away nodes with degree 1 until only the cycle remains. Then push all cycle nodes into a queue and run BFS outward to calculate distances. |
Draw a graph with "leaves". Erase leaves one by one until a loop remains (Kahn's). Mark loop nodes as "0". Draw concentric circles outward marking distances 1, 2, 3... |
Two-Phase Pipeline Graph |
Draw Phase 1: Degree Array elimination -> $O(V+E)$. Draw Phase 2: Multi-source BFS -> $O(V+E)$. Total time is linear. |
N separate Queue states initialized inside an outer loop. |
Degree Array (Integers) and a single global Queue pushing outward from cycle nodes. |
| 2205 |
The Number of Users That Are Eligible for Discount |
Nested Window Iteration
For each user, iterate through every possible sliding window of their purchases and check if it meets the requirements. |
Sliding Window Combinatorics |
Draw a timeline of purchases. Draw boxes of varying sizes over the timeline. Draw inner loops counting frequencies for each box. |
Fixed Sliding Window + Frequency Map |
Rolling Hash / Frequency Counters |
Maintain a dictionary of required items. Slide a fixed window across the user's purchases. When an item enters, +1; when it leaves, -1. Check against requirements. |
Draw an array of purchases. Draw a transparent "window" box covering N items. Slide the box right: cross out the item falling off the left side, add the new item on the right. |
Window Shift Arrow Diagram |
Draw a line representing $O(N)$ traversal. Show operations at each step as strictly $O(1)$ hash map updates, verifying linear time. |
Multiple sub-array copies allocated per window slice. |
Two Frequency Hash Maps: One static (requirements), one rolling (current window state). |
| 2206 |
Divide Array Into Equal Pairs |
Nested Loops / Sorting
Sort the array, then iterate through checking if `nums[i] == nums[i+1]`. If not, return false. |
Linear Scan Ribbon |
Draw the unsorted array, draw a downward arrow to a sorted array, then draw brackets grouping every 2 adjacent elements to check for equality. |
Frequency Map / Hash Table |
Bucket / Frequency Chart |
Create a tally chart. For each number, add a tally mark. At the end, scan the buckets to check if every single one has an even number of tallies. |
Draw empty buckets labeled with unique numbers. Drop array elements into their matching buckets. Visually cross out pairs within each bucket. |
Single Pass Line with Lookups |
Draw a single timeline for the array traversal representing $O(N)$. Below it, draw a secondary, shorter timeline for verifying the hash map values $O(U)$, where U is unique elements. |
Sorting space (usually $O(\log N)$ or $O(N)$ depending on language implementation) with mutated array blocks. |
Hash Map showing Key-Value pairs (where the Value is the frequency integer). |
| 2207 |
Maximize Number of Subsequences in a String |
Insertion Simulation
Try inserting `pattern[0]` and `pattern[1]` at every possible index in the string, then run a full subsequence count for every variation. |
Branching Combinations |
Draw the string multiple times, inserting the character at a new spot each time. Below each, draw lines connecting matching character pairs. |
Greedy / Prefix Counters |
Accumulator Flow |
Traverse string once. Maintain counts of `pattern[0]` and `pattern[1]`. If you see `pattern[1]`, add the current count of `pattern[0]` to your total. Add the max of the two counts at the end. |
Draw the string. Write `count0` and `count1` below it. As you move left to right, update the counts and draw an arrow to a "Total Subsequences" bucket whenever a valid pairing occurs. |
Linear Single-Pass Timeline |
Draw one straight arrow from start to end of the string, labeling it $O(N)$. Show variables updating in strictly $O(1)$ time at each step. |
Multiple string copies held in memory for each insertion state. |
Three scalar integer variables (`ans`, `count0`, `count1`) representing $O(1)$ space. |
| 2208 |
Minimum Operations to Halve Array Sum |
Repeated Linear Scan
Linearly search the array for the maximum element, halve it, subtract from sum. Repeat this entire process until the sum is halved. |
Repeated Array Scans |
Draw the array. Draw a magnifying glass finding the biggest number. Erase it, write the half-value. Redraw the magnifying glass scanning the whole array from scratch. |
Max Heap (Priority Queue) |
Binary Tree (Heap Structure) |
Push all elements into a Max Heap. Pop the root (the max), halve it, subtract from target sum, push it back. Repeat until target sum is reached. |
Draw a tree where the parent is always larger than its children. Circle the root, draw an arrow pulling it out, halve it, and draw it trickling back down the tree structure. |
Heap Operation Cycles |
Draw an $O(N)$ box for the initial heapify. Then draw a circular arrow labeled `K` times. Inside the loop, write `O(log N)` for extraction/insertion, showing $O(N + K \log N)$ total. |
Mutating the original flat array in place (O(1) extra space). |
A balanced binary tree structure in memory representing the Priority Queue array (O(N) space). |
| 2209 |
Minimum White Tiles After Covering With Carpets |
Backtracking / Combinations
At every white tile, recursively branch into two choices: place a carpet here or skip it and leave it visible. |
Exponential Decision Tree |
Draw a node representing the current tile. Draw two branching arrows: "Cover (skip L tiles)" and "Skip (add 1 visible)". Show the tree exploding in width. |
2D Dynamic Programming |
2D DP Grid / Matrix |
State is `(tile_index, carpets_left)`. Fill a table where each cell takes the minimum of skipping the tile `(val + DP[i-1][c])` or covering it `(DP[i-L][c-1])`. |
Draw a grid with `tiles` on the X-axis and `carpets` on the Y-axis. Fill cells left-to-right, drawing arrows to show a cell pulling data from the left (skip) or jumping left by `L` (cover). |
Matrix Fill Process |
Draw the DP grid and shade it in row by row. Label the dimensions `N` and `C`. Write $O(N \cdot C)$ to show every state is computed exactly once. |
Massive deep call stack with repeated identical states (overlapping subproblems). |
2D Array / Matrix of size `N x C` storing integer minimums. |
| 2210 |
Count Hills and Valleys in an Array |
Nested Expansion
For every element, use an inner loop to scan left and right until you find a non-equal neighbor to determine if it's a peak or valley. |
Left/Right Radiating Arrows |
Draw the array. For element `i`, draw arrows pointing left and right, stepping one by one until a different number is found. Repeat this for every element. |
Single Pass + Prev Pointer |
Pointer Tracking & Flatline Compression |
Traverse the array once. Keep a pointer to the `last_different_value`. If the current value differs from the next, compare it against `last_different_value` and `next_value`. |
Draw the array as a line graph (mountains and valleys). If there's a flat plateau (e.g., 5, 5, 5), draw a circle around the whole flat part and treat it as a single compressed point. |
Two-Pointer Traversal Line |
Draw an $O(N)$ line representing the main loop. Show the `prev` pointer trailing behind and updating instantly, proving $O(1)$ operations per element without inner loops. |
Static array with multiple temporary pointer variables instantiated repeatedly inside loops. |
Two single integer registers (`prev_val` and `count`) updating continuously (O(1) space). |
| 2211 |
Count Collisions on a Road |
Step-by-step Simulation
Simulate each unit of time. Move every 'L' left and 'R' right, checking adjacent indices for collisions, and updating states to 'S'. |
Multi-Step State Grid |
Draw the string of cars. Below it, draw the string again for time t=1, shifting characters. Draw explosion markers where 'L' and 'R' swap indices or hit 'S'. |
Two Pointers / String Trimming |
Boundary Trimming & Inclusion Zone |
Ignore cars on the far left moving left (they escape). Ignore cars on the far right moving right. Every other moving car in the middle will eventually collide. |
Draw the string. Cross out all consecutive 'L's from the left end. Cross out all consecutive 'R's from the right end. Draw a box around the remaining characters and count all non-'S' cars inside. |
Two-Pointer Inward Shift |
Draw an array. Draw a left pointer skipping 'L's and a right pointer skipping 'R's. Write $O(N)$ showing a single pass to count the bounded region. |
Multiple string/array copies representing the road at different time steps. |
Two integer pointers (`left` and `right`) and a single `count` variable (O(1) space). |
| 2212 |
Maximum Points in an Archery Competition |
Permutations of Arrows
Try distributing `numArrows` across 12 sections in every possible combination (e.g., 0 for section 1, 3 for section 2...) and check valid sums. |
N-ary Recursion Tree |
Draw a root node. Branch it out into `numArrows` + 1 children. Repeat this 12 levels deep to show a massive combinatorial explosion. |
Bitmask / Binary Enumeration |
12-Bit Binary Mask Table |
Bob either strictly wins a section (shooting Alice's arrows + 1) or shoots 0. Since there are exactly 12 sections, iterate through all 2^12 (4096) win/loss combinations using a bitmask. |
Draw 12 slots. Write a binary number like `1010001...` below it. For every `1`, write `alice[i]+1` arrows and add `i` points. If the arrow sum <= `numArrows`, keep the max score. |
Fixed-Size Bitmask Grid |
Draw a box representing 4096 rows. Next to it, draw 12 columns. Write `O(2^12 * 12)` and circle it, writing "O(1) Constant Time" since the constraint is strictly fixed to 12. |
A deep recursion call stack with an array passed down each level to track arrow distributions. |
A single integer `mask` iterating up to 4096, and a few temporary sum variables (O(1) space). |
| 2213 |
Longest Substring of One Repeating Character |
Update & Linear Scan
For every query, update the character in the string, then run a full $O(N)$ loop over the string to count the longest repeating substring. |
Repeated Linear Scanning |
Draw the string. Erase one character and write the new one. Draw a loop scanning the entire string left-to-right counting consecutive characters. Repeat for every query. |
Segment Tree |
Segment Tree Merging Diagram |
Build a Segment Tree where each node stores 3 things: longest prefix, longest suffix, and longest overall substring. When combining nodes, if the boundary characters match, merge the left suffix and right prefix. |
Draw a binary tree over the string. At each node write `[pre, suf, max]`. When a leaf changes, draw arrows moving straight UP the tree, recalculating the 3 numbers at each parent node. |
Tree Path Update |
Draw the Segment Tree. Highlight a single path from the root down to a leaf and back up. Label the height of the tree as $O(\log N)$ per query. |
Allocating a new full string or array copy after every query update. |
An array of size `4*N` representing the Segment Tree, where each element is an object holding 3 integers. |
| 2214 |
Minimum Health to Beat Game |
Simulation with Binary Search
Binary search the starting health. For each midpoint, simulate the whole game and greedily use armor on the first fatal hit. |
Binary Search Space + Inner Loops |
Draw a number line of possible health values. Pick a middle number. Draw a simulation scanning the damage array to see if you survive. Show $O(N \log(\text{Sum})$). |
Greedy Math / Total Sum |
Bar Chart with Armor "Cutoff" |
Find the level with the highest damage. Your armor is best used here. Total health needed is the sum of all damage, minus the damage your armor actually absorbed, plus 1 (to stay alive). |
Draw the damage array as vertical bars. Find the tallest bar. Draw a dashed horizontal line showing the armor "shaving off" the top of that bar. Sum the remaining areas and add 1. |
Two-Pass Line Diagram |
Draw an array. Draw one arrow sweeping left-to-right to find the max value. Draw another sweeping to sum the values. Label the total time as exactly $O(N)$. |
Excessive recursive states or tracking arrays if simulated dynamically. |
Two scalar integer variables (`total_sum` and `max_damage`) calculated in place (O(1) space). |
| 2215 |
Find the Difference of Two Arrays |
Nested Loops
For every element in `nums1`, iterate through the entirety of `nums2` to see if it exists. Repeat the reverse process for `nums2`. |
Bipartite Crossing Lines |
Draw `nums1` on the left, `nums2` on the right. Draw a line from the first element of `nums1` pointing to every single element in `nums2` one by one. |
Hash Sets / Set Difference |
Venn Diagram |
Convert both arrays to Sets. `answer[0]` is all elements in Set 1 that aren't in Set 2. `answer[1]` is all elements in Set 2 that aren't in Set 1. |
Draw two overlapping circles. Put unique `nums1` elements in the left crescent, unique `nums2` elements in the right crescent, and common elements in the intersection. |
Set Membership Lookups |
Draw array elements dropping into Hash Sets (O(N)). Then draw elements passing through a filter representing $O(1)$ Set lookups, avoiding nested iteration. |
No extra space technically required, but execution call stack suffers from $O(N\cdot M)$ time. |
Two Hash Sets in memory storing only the unique integer values from both arrays. |
| 2216 |
Minimum Deletions to Make Array Beautiful |
Recursive Deletion
Scan the array. If `nums[i] == nums[i+1]` on an even index, delete it, shift all remaining elements left, and restart the scan from the beginning. |
Shifting Array Simulation |
Draw the array. Cross out the violating element. Redraw the *entire* array shifted one space to the left to show the $O(N)$ penalty of deletion. |
Greedy / Virtual Deletion |
Parity Offset Pointer |
Traverse left-to-right. Keep a `deleted` count. The *virtual* index of any element is `actual_index - deleted`. If virtual index is even and matches the next element, increment `deleted`. |
Draw the array. Keep a tally of `deleted` on the side. Point at an element. Subtract the tally from its index. If even and it matches the neighbor, cross it out and add 1 to the tally. |
Single Linear Pass |
Draw one straight arrow across the array. Above it, write $O(N)$. Show the `deleted` variable updating in strictly $O(1)$ time without any array shifting. |
Multiple array copies allocated in memory for every shift/deletion (O(N^2) time, $O(N)$ space). |
A single integer variable `deleted` acting as a virtual offset (O(1) space). |
| 2217 |
Find Palindrome With Fixed Length |
Iterative Counting
Start from the lowest number of length L (e.g., 100 for L=3). Increment by 1, check if it's a palindrome, and stop when you reach the K-th one. |
Endless Number Line |
Write out numbers sequentially (100, 101, 102...). Cross out the non-palindromes. Circle the valid ones and count them until you hit K. |
Math / Half-String Mirroring |
Mirror Reflection |
A palindrome is determined entirely by its first half. The lowest half for length L is `10^(half_length - 1)`. Add `(K - 1)` to this base. Mirror this half to form the answer. |
Draw a dashed vertical "mirror" line. Calculate the left half (Base + K - 1). Write it on the left of the line. Draw arrows physically reflecting the digits to the right side of the line. |
Direct Formula Mapping |
Draw an input K. Draw a single arrow through a "Math Formula" box mapping directly to the output. Label it $O(L)$ time per query (for string creation). |
Massive loop counters and string allocations for checking every single number. |
A small string builder holding only the left half of the characters before appending the reverse. |
| 2218 |
Maximum Value of K Coins From Piles |
Backtracking Combinations
At every pile, try picking 0 coins, 1 coin, 2 coins, etc., recursively moving to the next pile. Keep track of coins left until K is reached. |
Massive N-ary Tree |
Draw a root node. Branch it out based on how many coins you pick from Pile 1. From *each* branch, branch out again for Pile 2. Show the tree width exploding. |
2D DP (Knapsack Variant) |
Prefix Sum + 2D DP Table |
`dp[i][j]` is max value from first `i` piles using exactly `j` coins. Precalculate prefix sums for each pile. Try taking `x` coins from the current pile and `j-x` coins from the previous DP state. |
Draw a grid: Piles (Y-axis) by Coins (X-axis). To fill a cell, draw arrows pointing to `dp[prev_pile][j-x]` and add the prefix sum of `x` coins from the current pile. Pick the max. |
Nested Loop Matrix |
Draw a 3-layered nested loop box: Loop Piles (N) -> Loop Capacity (K) -> Loop Current Pile Coins (min(K, size)). Label total $O(N \cdot K^2)$. |
A massive call stack depth of $O(N)$ with exponential branching states. |
A 2D DP matrix of size `N x K` and a secondary array for prefix sums. |
| 2219 |
Maximum Sum Score of Array |
Repeated Subarray Sums
For every single index `i`, run an inner loop to sum elements from 0 to `i`, and another inner loop to sum elements from `i` to N-1. |
Overlapping Subarray Sweeps |
Draw the array. Point to index `i`. Draw a sweeping arrow left to 0, and a sweeping arrow right to N-1. Move the pointer and redraw both sweeps again. |
Prefix Sums / Running Totals |
Running Total Accumulator |
Calculate the total sum of the array first. Traverse left-to-right maintaining a `running_left_sum`. The `right_sum` is instantly `total_sum - running_left_sum + current_val`. |
Draw the array. Write the Total Sum at the top. Below the array, keep a running sum as you move right. Calculate the right sum by doing basic subtraction on paper. |
Two Parallel Timelines |
Draw a timeline for the initial Total Sum pass $O(N)$. Draw a second parallel timeline for the Left/Right evaluation pass $O(N)$. Total = $O(N)$. |
Re-evaluating dynamic sums in temporary variables inside an $O(N^2)$ loop. |
Two massive integers (64-bit to prevent overflow): `total_sum` and `running_left_sum` (O(1) space). |
| 2220 |
Minimum Bit Flips to Convert Number |
String Conversion & Padding
Convert `start` and `goal` to binary strings. Pad the shorter one with leading zeroes. Iterate through and count mismatching characters. |
String Alignment & Comparison |
Write out the binary string for `start`. Right below it, write the string for `goal`. Draw vertical lines connecting them. Circle the pairs that do not match. |
Bitwise XOR + Brian Kernighan's Alg |
Bitwise XOR Gate Filter |
`xor_result = start ^ goal`. An XOR outputs a `1` only where the bits differ. The answer is simply the number of set bits (1s) in `xor_result`. |
Write the two binary numbers. Draw a line underneath. Do the XOR: 1^0=1, 0^1=1, 1^1=0, 0^0=0. Finally, draw circles around all the 1s in the result to count them. |
Bit Shifting Timeline |
Draw the XOR result. Draw an arrow looping while `n > 0`, showing `n = n & (n-1)` to clear the lowest set bit. Label time as $O(\text{Set Bits})$. |
Allocating strings or character arrays to hold the binary representations (O(log(max_val)) space). |
A single integer holding the XOR result, manipulated in place (O(1) space). |
| 2221 |
Find Triangular Sum of an Array |
Iterative Array Reduction
Create a new array of size N-1, sum adjacent elements modulo 10, and repeat this process N-1 times until one number remains. |
Inverted Number Pyramid |
Draw the initial array at the top. Draw lines connecting pairs of adjacent numbers down to a single number below them, forming a triangle that points downward. |
Math / Binomial Coefficients |
Combinatorial Weight Mapping |
Each number at index `i` contributes to the final sum exactly `nCr(N-1, i)` times. Calculate the combinations, multiply by `nums[i]`, and sum them all modulo 10. |
Draw the array. Below each element `i`, write `C(N-1, i)`. Draw an arrow multiplying the array element by its combinatorial weight, pointing to a final sum bucket. |
Linear Pass with Math Lookups |
Draw a single pass timeline representing $O(N)$. Inside, show $O(1)$ mathematical updates using a precomputed factorials array or Lucas Theorem, completely avoiding the $O(N^2)$ triangle generation. |
Allocating N separate shrinking arrays, resulting in $O(N^2)$ memory overhead. |
A single accumulation integer variable and possibly a small fixed array for factorial caching (O(1) auxiliary space). |
| 2222 |
Number of Ways to Select Buildings |
Nested Triple Loops
Use three nested loops to select indices `i < j < k`. Check if the characters form either "010" or "101" and increment a counter. |
3-Pointer Combinatorial Sweep |
Draw the string. Place pointer `i`. Run pointer `j` from `i+1` to end. Run pointer `k` from `j+1` to end. Draw curved lines connecting valid triplets. |
Prefix/Suffix Counts |
Pivot & Multiply |
Count total '0's and '1's. Iterate through the string treating each char as the middle building. If '1', add `(left '0's) * (right '0's)` to total. If '0', do the same for '1's. |
Draw the string. Circle a '1' in the middle as the pivot. Count '0's to the left, count '0's to the right. Multiply those two numbers and draw an arrow to the `total_ways` bucket. |
Parallel Aggregate Timeline |
Draw an $O(N)$ line for the initial total count pass. Draw a second $O(N)$ line for the pivot pass. Show that left/right counts update in $O(1)$ time at each step. Total time $O(N)$. |
Call stack holding states for recursive subset generation or deep nested loops. |
Four running counters (`left_0`, `left_1`, `right_0`, `right_1`) taking strictly $O(1)$ space. |
| 2223 |
Sum of Scores of Built Strings |
Suffix String Matching
For every suffix of the string, iterate character by character comparing it to the prefix of the original string until a mismatch occurs. |
Overlapping Prefix/Suffix Alignment |
Write the string. Write the suffix below it aligned to the left. Draw vertical lines comparing characters until you hit a mismatch. Repeat for every suffix. |
Z-Algorithm |
Z-Box Sliding Window |
Use the Z-algorithm to construct a Z-array in linear time, where `Z[i]` stores the length of the longest substring starting at `i` that matches the prefix. Sum the Z-array. |
Draw the string. Draw a "Z-box" bracket over the known matching prefix. When evaluating a new index `i` inside the box, draw an arrow pulling the previously calculated `Z` value to instantly skip redundant checks. |
Z-Array Linear Construction |
Draw the string array and the Z-array side-by-side. Trace pointers `L` and `R` moving strictly to the right, proving that character comparisons never go backward. $O(N)$ time. |
Creating new string copies for every suffix substring check (O(N^2) space). |
A single integer `Z-array` of length N tracking prefix matches (O(N) space). |
| 2224 |
Minimum Number of Operations to Convert Time |
BFS Shortest Path
Treat the start time as a node. Generate neighbors by adding 1, 5, 15, and 60 minutes. Run a Breadth-First Search to find the shortest path to the goal time. |
Exploding Time Graph |
Draw a starting clock. Branch into 4 new clocks (+1, +5, +15, +60). Branch those again. Highlight the shortest path to the target time. |
Greedy Subtraction |
Coin Change / Cascade Subtraction |
Convert both times to total minutes. Find the difference. Greedily divide by 60, take the remainder. Divide by 15, take remainder, then 5, then 1. Add the quotients together. |
Draw a bucket of "Total Difference" minutes. Draw 4 sieves of sizes 60, 15, 5, 1. Pour the minutes through the 60 sieve, count what falls through. Pass the remainder to 15, and so on. |
Constant Step Cascade |
Draw a flow chart with exactly 4 steps: `diff / 60`, `diff / 15`, `diff / 5`, `diff / 1`. Write $O(1)$ overall since the operations are fixed regardless of the input size. |
A massive BFS Queue storing hundreds of minute states and a visited set. |
A single integer representing the `minute_difference`, updated sequentially (O(1) space). |
| 2225 |
Find Players With Zero or One Losses |
Nested Array Scans
For every player ID from 1 to 10^5, scan the entire `matches` array to count their wins and losses. |
Exhaustive ID Lookup |
Draw a number line from 1 to 10^5. For number 1, draw a magnifying glass scanning the whole match list. Repeat for 2, 3, etc. Show $O(\text{Max}_\text{ID} \\text{cdot Matches})$ explosion. |
Hash Map / Frequency Array |
Filter Buckets |
Iterate through matches once. Record losses in a Hash Map or Array. Iterate through the unique players and filter them into an "answer[0]" bucket (0 losses) and "answer[1]" bucket (1 loss). |
Draw a hash table tallying losses. Draw an arrow from players with 0 tallies to a green bucket, and players with 1 tally to a yellow bucket. Discard the rest. Sort the buckets. |
Map Population & Sorting Timeline |
Draw an $O(N)$ line for scanning matches and updating the map. Draw a second line $O(K \log K)$ representing the sorting of the K unique valid players at the end. |
Multiple full passes over a large 2D matrix, often loading redundant data. |
A single Hash Map or an integer array of size 10^5 (O(N) space where N is unique players). |
| 2226 |
Maximum Candies Allocated to K Children |
Linear Increment Simulation
Start by trying to give every child 1 candy. Then try 2, then 3, iterating linearly and recounting the piles every time until it fails to satisfy K children. |
Endless Trial-and-Error Loop |
Draw the candy piles. Write "Target: 1". Cross out piles and divide them manually. Erase, write "Target: 2", and redraw the division. Show $O(N \\text{cdot Max}_\text{Candy})$ explosion. |
Binary Search on Answer |
Search Space Halving Line |
The minimum possible answer is 0, the max is the largest pile. Pick the middle value. See if you can form K piles of that size. If yes, search the right half; if no, search the left half. |
Draw a number line from 0 to Max Candy. Put a dot in the middle. Do a quick division check `sum(pile // mid)`. Draw an arrow discarding half the number line instantly based on the result. |
Logarithmic Search Timeline |
Draw a loop iterating `log(Max_Candy)` times. Inside the loop, draw an $O(N)$ line representing the array scan. Total complexity is strictly $O(N \log M)$. |
Repeated array allocations to simulate the breaking down of piles step-by-step. |
Two pointers (`left`, `right`) representing the binary search bounds (O(1) space). |
| 2227 |
Encrypt and Decrypt Strings |
Combinatorial Decryption
For decryption, generate every possible string combination using the character mapping, then check if each combination exists in the allowed dictionary. |
Exploding Tree Graph |
Draw a starting encoded pair. Branch out into every valid decrypted character. Repeat for every pair in the string, resulting in an $O(2^N)$ or worse branching tree. |
Reverse Encryption Mapping (Trie/Hash) |
Precomputed Frequency Map |
Instead of decrypting the ciphertext, *encrypt* every word in the dictionary once during initialization. Store the encrypted strings and their frequencies in a Hash Map. Decrypt is then an $O(1)$ lookup. |
Draw the dictionary words passing through an "Encryption Funnel" into a bucket (Hash Map) with tally marks. For a decrypt query, draw an arrow pointing straight to the tally mark in the bucket. |
Precomputation vs Query Chart |
Draw a large block labeled "Init: $O(\text{Dict}_\text{Size} \\text{cdot Word}_\text{Len})$". Then, draw a tiny block for "Decrypt: $O(1)$". Show how shifting the heavy lifting to initialization optimizes the query phase. |
A massive call stack and an array of temporary strings holding all possible permutations. |
A Hash Map mapping encrypted dictionary strings to their integer frequencies (O(N) space). |
| 2228 |
Users With Two Purchases Within Seven Days |
Nested Cross-Join (SQL)
Join the purchases table to itself. For every single transaction a user made, compare it against every other transaction they ever made to check the 7-day window. |
N x N Cartesian Grid |
Draw a grid with User 1's dates on the X and Y axes. Draw an intersection point for every comparison, showing $O(N^2)$ checks per user. |
Window Function / LAG (SQL) |
Sliding Window Timeline |
Sort purchases by user and date. Use a `LAG` window function to look at the exact previous purchase row for that user. Check if the difference is <= 7 days. |
Draw a timeline of dates. Draw a small window grouping exactly two adjacent dates. Slide the window right by one step, calculating the difference instantly. |
Sorting and Single Pass Arrow |
Draw an $O(N \log N)$ step for the required chronological sorting. Then draw a single arrow representing the $O(N)$ linear scan using the Window function. |
Massive intermediate join tables held in memory during query execution. |
In-place pointer tracking for the previous row during the DB engine's sequential scan. |
| 2229 |
Check if an Array Is Consecutive |
Sort and Scan
Sort the array. Iterate from index 0 to N-1, checking if `nums[i] + 1 == nums[i+1]`. If it fails anywhere, return false. |
Sorting Bottleneck Pipeline |
Draw a messy array. Draw a funnel pushing it into a sorted array. Draw loops connecting adjacent numbers verifying the +1 difference. Note the $O(N \log N)$ sort time. |
Math Bounds + Hash Set |
Bounding Box & Unique Check |
Find the Min and Max in $O(N)$. If `Max - Min + 1 != length`, it's not consecutive. If true, put everything in a Hash Set to verify there are exactly `length` unique numbers (no duplicates). |
Draw a box representing the expected range `[Min, Max]`. Drop array elements into the box. If an element tries to drop into an occupied spot, circle it as a failure (duplicate). |
Three Parallel Timelines |
Draw three $O(N)$ actions happening independently: Find Max, Find Min, Fill Hash Set. Show that $O(N)$ + $O(N)$ + $O(N)$ is strictly linear time $O(N)$. |
Space for the sorting algorithm's implementation (often $O(\log N)$ or $O(N)$). |
A Hash Set containing N elements to check for uniqueness in $O(N)$ space. |
| 2230 |
The Users That Are Eligible for Discount |
Full Table Scan & Grouping
Scan every single transaction in the database. Group them all by user. For each group, loop through to see if any transaction fits the date and amount criteria. |
Funnel with Heavy Processing |
Draw a massive pile of transactions. Draw them all funneling into "User Buckets". Draw a magnifying glass painstakingly checking every item inside every bucket. |
Targeted Filter + Distinct (SQL) |
Multi-Stage Sieve |
Filter rows immediately where `amount >= minAmount` AND `date BETWEEN start AND end`. Take the `DISTINCT user_id` from whatever makes it through the filter. |
Draw two sieves. Pour transactions through the "Date Sieve". Pour the survivors through the "Amount Sieve". Whatever user IDs remain, drop them into a set to remove duplicates. |
Pipeline Elimination Chart |
Draw a wide block of data narrowing instantly based on the `WHERE` clause (using database indexes if available), followed by a simple $O(N)$ distinct hash pass. |
Large hash tables storing lists of all transactions per user in memory. |
A single Hash Set filtering out duplicate valid user IDs as they stream through. |
| 2231 |
Largest Number After Digit Swaps by Parity |
Permutation Generation
Generate every possible permutation of the digits, filter out the ones that swap odd with even, and then find the maximum value among the valid permutations. |
Exploding Decision Tree |
Write the starting number. Draw branches for every possible valid swap. Continue branching until all valid arrangements are found, demonstrating $O(N!)$ factorial explosion. |
Sorting by Parity / Max Heap |
Two-Lane Sorting Funnel |
Separate the digits into an 'Odd' bucket and an 'Even' bucket. Sort both buckets in descending order. Reconstruct the number by pulling from the respective bucket based on the original digit's parity. |
Draw the number. Draw arrows dropping odd digits into a red bin and evens into a blue bin. Sort both bins. Point back to the original number spots, pulling the highest available digit from the matching color bin. |
Parallel Sorting Timeline |
Draw an $O(N)$ string traversal. Then draw two independent $O(K \log K)$ sort operations for the two buckets. End with a final $O(N)$ reconstruction pass, proving efficiency over $O(N!)$. |
Massive array allocations holding every generated permutation string. |
Two small arrays or priority queues holding at most 10 digits each (O(N) space). |
| 2232 |
Minimize Result by Adding Parentheses to Expression |
String Manipulation Simulation
Since constraints are tiny (string length <= 10), the brute force *is* the optimal. Generate all valid splits `num1 * (num2 + num3) * num4`, evaluate using a math parser, and track the minimum. |
Combinatorial Splitting Grid |
Draw the expression `12+34`. Draw a matrix of choices for the left parenthesis `(` (index 0, 1) and right parenthesis `)` (index 3, 4). Calculate the math for each cell. |
Sliding Boundary Pointers |
4-Part Substring Slicing |
Find the '+' index. Use an outer loop `i` for the left parenthesis (from 0 to '+') and an inner loop `j` for the right parenthesis (from '+' to end). Slice the string into 4 numeric parts and evaluate `p1 * (p2 + p3) * p4`. |
Write the string. Highlight the `+` sign as an anchor. Put a left bracket `[` before the `+` and slide it left. Put a right bracket `]` after the `+` and slide it right. Write the multiplication output below each step. |
Nested Loop Bounding Box |
Draw a small $O(L^2)$ box, where L is the length of the string. Inside the box, draw constant $O(1)$ string-to-integer conversions, showing that small constraints make $O(N^2)$ perfectly optimal. |
Repeated creation of new substring memory allocations per loop iteration. |
Four scalar integer variables holding the parsed substring values for calculation (O(1) space). |
| 2233 |
Maximum Product After K Increments |
Repeated Linear Scan
Linearly scan the entire array to find the absolute minimum value. Increment it by 1. Repeat this entire linear search K times, then multiply everything. |
Endless Array Scans |
Draw the array. Draw a magnifying glass finding the smallest number. Erase the number, write the +1 value. Redraw the magnifying glass scanning the whole array from scratch. Show $O(K \cdot N)$. |
Min Heap (Priority Queue) |
Self-Balancing Tree Sink |
Heapify the array into a Min-Heap. Pop the root (minimum element), increment it by 1, and push it back. The heap self-balances. Repeat K times. Multiply all elements modulo 10^9 + 7. |
Draw a binary tree with the smallest number at the top. Circle the top node, extract it, add 1, and drop it back at the top. Draw arrows showing it "sinking" down to its correct sorted level. |
Heap Cycle Timeline |
Draw an initial $O(N)$ box for building the heap. Draw a circular loop for K iterations. Inside the loop, write $O(\log N)$ for the pop/push operations. Show $O(N + K \log N)$ total time. |
Mutating the original flat array in place, suffering from slow $O(N)$ searches. |
A balanced binary tree array structure holding the Min Heap elements (O(N) space). |
| 2234 |
Maximum Total Beauty of the Gardens |
Backtracking / Combinations
Recursively try every combination of forcing a garden to be "complete" and distributing remaining flowers to incomplete gardens. |
Exponential Branching |
Draw the array of gardens. Branch into two paths: "Make Complete" or "Leave Incomplete". For "Leave Incomplete", branch again on how many flowers to add. Show infinite combinatorial spread. |
Sorting + Prefix Sum + Two Pointers/Binary Search |
Suffix Anchoring & Prefix Flooding |
Sort gardens. Precompute prefix sums to quickly calculate how many flowers are needed to raise the minimum level of the first `i` gardens. Loop backwards making `N` to `0` gardens complete, and use binary search on the prefix to maximize the minimum of the rest. |
Draw the sorted array as a rising staircase. Pin the top steps (suffix) and color them "Complete". For the bottom steps (prefix), draw "water" (flowers) flooding them until you run out of remaining flowers. Calculate the score. |
Two-Phase Array Sweep |
Draw an $O(N \log N)$ sorting step. Draw a timeline representing the suffix loop $O(N)$. Inside it, draw an $O(\log N)$ binary search step to find the water level. Total: $O(N \log N)$. |
Massive call stack depth passing remaining flower counts and garden states. |
A prefix sum array of size N to allow $O(1)$ range sum queries (O(N) space). |
| 2235 |
Add Two Integers |
Simulation by Looping
Start with `num1`. Use a `while` loop to increment `num1` by 1 and decrement `num2` by 1 until `num2` hits 0. |
Tally Mark Transfer |
Draw two buckets. Move one tally mark from bucket 2 to bucket 1. Repeat until bucket 2 is empty. Show how this takes $O(\text{num}2)$ steps. |
Direct Math Operations / ALU |
ALU Hardware Addition |
Return `num1 + num2`. The underlying hardware/ALU performs this in a single clock cycle using bitwise adders natively. |
Draw two integer boxes feeding into an "ALU Addition" funnel, which immediately spits out a single combined number box. |
$O(1)$ Instant Box |
Draw a single box labeled $O(1)$. No loops, no iterations. It is a fundamental hardware-level instruction. |
Iterative counter variables looping repeatedly in the call stack. |
Two register loads into the CPU resulting in a single integer return (O(1) space). |
| 2236 |
Root Equals Sum of Children |
Recursive Tree Traversal
Perform a full Depth First Search (DFS) to collect all node values, then check if the root matches the sum of its left and right children. |
Full Tree Scan Visualization |
Draw a small 3-node tree. Draw an arrow starting at the root, visiting left, then right, then back to root. Note that you visited 3 nodes for a 3-node problem. |
Direct Comparison / $O(1)$ Access |
Constant Node Check |
Since the problem strictly specifies a root and two children, simply perform: `root.val == root.left.val + root.right.val`. |
Draw a box around the root and its two direct children. Draw two "+" arrows from the children to a sum bubble, then a "==" line to the root. |
$O(1)$ Single Step Box |
Draw a single box labeled $O(1)$. No recursion or loops are needed as the tree size is fixed at 3 nodes by the problem constraints. |
Recursive call stack nodes for each tree level (O(H) space). |
Direct memory reference to three existing objects; no extra structure (O(1) space). |
| 2237 |
Count Positions on Street With Required Brightness |
For every lamp, iterate through its entire range [pos - range, pos + range] and add +1 to an array. $O(N \cdot R)$. |
Overlapping Paint Strokes |
Draw a street. For each lamp, physically color in the blocks it lights. Overlap colors. Slow for huge ranges. |
Difference Array (Sweep Line) |
The Entry/Exit Tally |
Instead of painting the whole range, mark +1 at the start of the light and -1 just after the light ends. Do a single prefix sum sweep to calculate actual brightness at each spot. |
Draw the street. Place a '+1' token where a lamp's light starts. Place a '-1' token where it ends. Sweep left-to-right, keeping a running total of tokens to reveal the true brightness. |
Two-Pass Linear $O(N + L)$ |
Draw one pass to place boundary tokens, and one sweep pass to accumulate. |
Massive array re-allocations. |
A difference array of size N+1. $O(N)$ space. |
| 2238 |
Number of Times a Driver Was a Passenger |
Nested SQL Subqueries
For every unique driver ID in the table, run a separate subquery to count how many times that ID appears in the 'passenger_id' column. |
Row-by-Row Lookup |
Draw two copies of the table. For the first row in Table A, scan all rows in Table B. Repeat for every row. Show the quadratic $O(N^2)$ search pattern. |
Left Join + Group By (SQL) |
Relational Mapping / Hash Join |
Create a frequency table of passenger counts. Join this to the unique list of driver IDs using a LEFT JOIN to ensure drivers with 0 passenger trips are included. |
Draw two lists: "Drivers" and "Passenger Counts". Draw lines connecting IDs. If a Driver has no match in the count list, draw a line to a "0" bucket. |
Hash Table Build/Probe Pipeline |
Draw an $O(N)$ step to build a hash map of passenger frequencies. Draw an $O(M)$ step to probe that map for each driver. Total complexity $O(N+M)$. |
Heavy temporary result sets stored in memory for each nested subquery call. |
A single Hash Map (Frequency Table) storing ID-Count pairs (O(Unique_IDs) space). |
| 2239 |
Find Closest Number to Zero |
Sort by Absolute Value
Sort the entire array using a custom comparator that looks at `abs(x)`. If absolute values are equal, sort by the actual value in descending order. Return the first element. |
Sorting Re-ordering Pipeline |
Draw the number line. Draw arrows moving every number to its absolute distance from 0. Show the sorting process $O(N \log N)$ rearranging the whole array. |
Linear One-Pass Update |
Closest-So-Far Register |
Traverse the array once. Maintain a variable `closest`. If `abs(current) < abs(closest)`, update. If `abs(current) == abs(closest)`, pick the larger of the two. |
Draw a number line with a "Zero" marker. As you scan the array, draw a "target" that jumps to the number nearest to zero. If two numbers are equidistant, the target moves to the positive one. |
Single Linear Timeline |
Draw one straight arrow representing the array scan. Label it $O(N)$. Show the `closest` variable updating instantly in $O(1)$ at each step. |
A new sorted copy of the array (O(N) space) or sorting stack space (O(log N)). |
A single integer variable `closest` updating in-place (O(1) space). |
| 2240 |
Number of Ways to Buy Pens and Pencils |
Double Nested Loops
Iterate `i` from 0 to total for pens, and an inner loop `j` from 0 to total for pencils. If `(i*cost1 + j*cost2) <= total`, increment count. |
2D Coordinate Grid Search |
Draw a grid where X is "Number of Pens" and Y is "Number of Pencils". Shade every cell (i, j) that fits the budget. Show the $O(\text{Total}^2)$ area being checked. |
Single Loop Math |
Linear Budget Depletion |
Iterate through the number of pens you can buy (0 to `total/cost1`). For each quantity of pens, the remaining money is `rem`. The number of ways to buy pencils is simply `(rem / cost2) + 1`. |
Draw a vertical bar representing the "Total Budget". Chop off a piece for "Pens". Take the remaining "Pencil" piece and draw marks showing how many times the `cost2` fits into it. |
Linear Arithmetic Pass |
Draw a single timeline representing the pen loop $O(\text{Total} / \text{Cost}1)$. Inside, show an $O(1)$ division operation. Total time $O(N)$, where N is the max number of pens. |
Deep nested loop counters and potentially a coordinate list of valid pairs. |
A single 64-bit integer `total_ways` and one loop index `i` (O(1) space). |
| 2241 |
Design an ATM Machine |
Full Array Sorting/Re-ordering
Every time a withdrawal is requested, create a copy of the banknote counts, sort them by value, and run a simulation to see if the amount can be reached. |
Repeated Snapshot Simulation |
Draw the ATM state as a set of cash drawers. For every withdrawal, draw a new set of drawers and cross out bills one by one. Highlight the $O(N)$ cost per withdrawal query. |
Greedy Hash Map / Frequency Array |
Static Indexed Buckets |
Store banknote counts in a fixed-size array of length 5. For withdrawals, iterate from the largest index (500) to the smallest. Use `min(needed, available)` to greedily take bills. |
Draw 5 labeled boxes: [20, 50, 100, 200, 500]. For a withdrawal of 600, draw an arrow pulling one "500" and then one "100". Update the numbers inside the boxes instantly. |
$O(1)$ Fixed Loop Chart |
Draw a flow chart with 5 sequential steps (one for each bill type). Label it $O(1)$ because the number of bill types is constant (5), regardless of the withdrawal amount. |
Creating copies of the entire banknote inventory for every single transaction attempt. |
A fixed-size array of 5 long integers representing the count of each banknote (O(1) space). |
| 2242 |
Maximum Score of a Node Sequence |
DFS for Path Length 4
Run a Depth First Search from every node to find all possible simple paths of length 4, calculating the score for each and keeping the maximum. |
Exponential Path Exploration |
Draw a graph. From a starting node, draw 3 branches, then 3 more from each. Show how the search space explodes to $O(V \cdot E^3)$ or worse. |
Edge-Centric + Top 3 Neighbors |
Middle-Edge Pivot Map |
Iterate through every edge `(u, v)` as the middle of the 4-node sequence. To complete the sequence `(a-u-v-b)`, pick the best neighbor `a` of `u` and `b` of `v` that are not `u`, `v`, or each other. Store only the top 3 neighbors per node. |
Draw an edge between `U` and `V`. Next to `U`, list its 3 highest-value friends. Next to `V`, list its 3 highest-value friends. Draw lines connecting a friend from `U` and a friend from `V` to form a chain of 4. |
Linear Edge Sweep |
Draw an $O(E)$ timeline representing the edge loop. Inside, show a small constant number of checks (3x3 = 9 combinations). Total complexity: $O(E + V \log 3)$. |
Massive recursion stack and path-history sets to prevent cycles during DFS. |
An adjacency list where each node only stores a list of its top 3 weighted neighbors (O(V) space). |
| 2243 |
Calculate Digit Sum of a String |
Recursive String Rebuilding
While string length > k, slice the string into groups, convert each to an integer, sum digits, and concatenate back. Repeat recursively. |
Layered String Transformation |
Draw the string. Draw vertical lines every K characters. Below each group, write the sum. Draw arrows merging those sums into a new, slightly shorter string. Repeat the drawing. |
Iterative StringBuilder / Two-Pointer |
Chunk-Based Accumulator |
Use a `while` loop and an internal `for` loop to jump by `k`. Use a `StringBuilder` to collect sums. This minimizes the overhead of creating many intermediate string objects in memory. |
Draw the string with a sliding window of size K. As the window slides, calculate the digit sum and drop it into a "Result String" bucket. When the pass is over, the bucket becomes the new string. |
Shrinking Timeline Cascade |
Draw a wide bar (length N), then a smaller bar (N/K), then smaller. Label the summation of the series. Even though it looks complex, it converges to $O(N)$ or $O(N \log N)$. |
Creating thousands of immutable string slices and sub-string objects in the heap. |
A single reusable `StringBuilder` or `char array` to construct the next iteration (O(N) space). |
| 2244 |
Minimum Rounds to Complete All Tasks |
Backtracking / Change Making
For each task frequency, use recursion to try every combination of subtracting 2 or 3 until the count reaches zero. |
Decision Tree (2 vs 3) |
Draw a number (e.g., 7). Branch into -2 (5) and -3 (4). Continue branching until you find the shortest path to 0. Show the $O(2^N)$ depth. |
Greedy Math / Frequency Map |
Remainder Pattern Logic |
Group tasks by difficulty. For a frequency `f`: if `f == 1`, impossible. Otherwise, the minimum rounds is `ceil(f / 3.0)`. This covers all cases: `3k`, `3k+1`, and `3k+2`. |
Draw a frequency bar. If it's 7, group them: [3, 2, 2]. If it's 9, group them: [3, 3, 3]. Note that any number > 1 can be broken into 2s and 3s with a simple formula. |
Map Scan Timeline |
Draw an $O(N)$ line for the initial frequency count. Draw an $O(U)$ line (unique tasks) for the math calculation. Total time: $O(N)$. |
Deep recursion stacks for every unique task difficulty. |
A Hash Map storing `Difficulty -> Frequency` (O(N) space). |
| 2245 |
Maximum Trailing Zeros in a Cornered Path |
DFS Path Traversal
For every cell, explore all possible "cornered" paths (horizontal then vertical) and count the factors of 2 and 5 in the product of all numbers. |
Exhaustive Path Counting |
Draw a 2D grid. From one cell, draw a line right, then several lines branching down from every point on that line. Show the $O(R\cdot C \cdot (R+C)$) explosion. |
2D Prefix Sums (Factors of 2 and 5) |
Factor Grid Overlay |
Trailing zeros are `min(count_of_2, count_of_5)`. Create four 2D prefix sum arrays: prefix_2_row, prefix_5_row, prefix_2_col, prefix_5_col. For any corner, calculate factors in $O(1)$. |
Draw the grid. Overlay it with "Factor 2" and "Factor 5" counts instead of the original numbers. Show a horizontal prefix sum bar and a vertical one meeting at a "Corner Cell". |
Precomputation + Scan Matrix |
Draw the precomputation block $O(R\cdot C)$. Then draw the evaluation block where each cell is checked in $O(1)$. Total time: $O(R\cdot C)$. |
Calculating the actual product of numbers (which would cause massive overflow) and counting zeros. |
Four 2D arrays of integers (O(R*C) space) to store the prefix sums of prime factors. |
| 2246 |
Longest Path With Different Adjacent Characters |
All-Pairs DFS
For every single node in the tree, run a DFS to find the longest valid path starting at that node where no two adjacent nodes have the same character. |
Overlapping Tree Traversals |
Draw the tree. Highlight node A and trace all paths from it. Then highlight node B and trace all paths from it. Show how many edges are re-traversed, leading to $O(N^2)$. |
Tree DP (Post-order Traversal) |
Two-Max Child Branching |
Each node returns the longest valid path from its subtree to itself. The longest path *through* the current node is the sum of the two longest valid paths from its children (plus 1). |
Draw a node with several children. Only keep paths from children whose characters differ from the parent. Pick the top 2 longest paths, draw a "V" shape connecting them through the parent. |
Bottom-Up Single Pass |
Draw the tree. Draw arrows starting from the leaves moving upward to the root. Label it $O(N)$ because each node and edge is visited exactly once. |
Recursive call stack storage of all paths found during the $O(N^2)$ search. |
A single recursion stack of height H and one integer return value per node (O(N) space). |
| 2247 |
Maximum Cost of Trip With K Highways |
Backtracking with Depth K
From every city, use recursion to explore all possible paths of length K. Use a 'visited' set to ensure the path is simple (no cycles). |
Exponential Path Tree |
Draw a city node. Branch out to all neighbors. For each neighbor, branch to *their* neighbors. Show the tree depth reaching K, resulting in $O(N \\text{cdot Degree}^K)$. |
Dynamic Programming with Bitmask |
State Compression Grid |
`dp[mask][u]` represents the max cost to reach city `u` having visited the cities represented by the bitmask. Transition by moving to a neighbor `v` not in the current mask. |
Draw a table where the Y-axis is cities and the X-axis is a bitmask (e.g., 10110). Show a cell `(mask, u)` pulling the max value from `(mask ^ (1<
| State-Space Matrix Fill |
Draw a box representing all possible states. Label the width 2^N and the height N. Write $O(2^N \cdot N \\text{cdot Degree})$ to show that every state is computed exactly once. |
Massive recursion stack and thousands of temporary sets to track visited cities. |
A 2D DP array of size `2^N x N` storing the maximum costs (O(N * 2^N) space). |
| 2248 |
Intersection of Multiple Arrays |
Nested Contains Checks
Take the first array. For every element in it, check if it exists in the second array, then the third, and so on using linear scans. |
Linear Scan Pipeline |
Draw Array 1. Point to the first element. Draw an arrow checking every element in Array 2, then Array 3. Repeat for every element in Array 1. |
Frequency Map / Counting Sort |
Tally Marks Filter |
Iterate through all elements in all arrays and count their occurrences in a frequency map. Only the elements whose count equals the number of arrays are in the intersection. |
Draw a set of empty buckets numbered 1 to 1000. For every number seen in any array, drop a coin in its bucket. At the end, only keep buckets containing exactly N coins (where N is total arrays). |
Total Elements Timeline |
Draw a single line representing the total number of elements across all arrays. Label it $O(\text{Sum of all lengths})$. Show a final $O(1000)$ scan of the buckets. |
Allocating new intermediate result arrays after every intersection check. |
A single frequency array of size 1001 (O(1) auxiliary space beyond the output). |
| 2249 |
Count Lattice Points Inside Circles |
Circle-to-Circle Search
For every circle, iterate through every point in its bounding box and add it to a Set if it satisfies the circle equation `(x-x1)^2 + (y-y1)^2 <= r^2`. |
Overlapping Grid Checks |
Draw three overlapping circles. For each, draw a square around it and check every dot inside. Show the same points being checked multiple times. |
Global Bounding Box Scan |
Universal Grid Sweep |
Find the global min/max X and Y across all circles. Iterate through every `(x, y)` in this single large grid once. For each point, check if it lies inside *any* circle and break early if it does. |
Draw one large rectangle that contains all the circles. Draw a grid of dots inside. Move a pointer dot-by-dot. At each dot, ask: "Am I inside Circle 1? No. Circle 2? Yes!" and move to the next dot immediately. |
2D Grid Area Pass |
Draw a grid of size `W x H`. Label the total complexity $O(W \cdot H \cdot N)$ where N is the number of circles. Show that N is reduced by the "early break" logic. |
Large Hash Set storing thousands of coordinate tuples to handle duplicates. |
A simple nested loop with a few integer variables; no extra data structures needed beyond the input (O(1) extra space). |
| 2250 |
Count Number of Rectangles Containing Each Point |
Nested Point-in-Rect Loop
For every point query, iterate through the entire list of rectangles to check if `x_rect >= x_point` and `y_rect >= y_point`. |
Point-to-All-Rects Mapping |
Draw a query point. Draw 100 rectangles. One-by-one, check if the point is inside. Repeat for every query point. Show the $O(Q \cdot R)$ complexity. |
Sorting + Binary Search (By Height) |
Y-Grouped Sorted X-Lists |
Since heights are small (1-100), group rectangle widths by their heights. Sort each group. For a query `(x, y)`, iterate through heights `h` from `y` to 100 and binary search for `x` in those sorted lists. |
Draw 100 horizontal shelves (one for each height). Put rectangle widths on their respective shelves in sorted order. For a query, look only at shelves above the point's Y and count widths >= X using binary search. |
Multi-List Binary Search |
Draw 100 $O(\log N)$ operations for each query. Total time: $O(Q \cdot 100 \cdot \log N)$. Contrast this against the brute force $O(Q \cdot N)$. |
Storing all rectangles in a single flat list requiring full scans. |
An array of 101 lists, each containing sorted integers (O(N) space). |
| 2251 |
Number of Flowers in Full Bloom |
Full Calendar Simulation
For every person's arrival time, iterate through the entire list of flowers and check if the arrival time falls within the start and end bloom times. |
Point-to-Interval Intersection |
Draw a timeline. For each person (point), draw a vertical line that crosses through all horizontal bars (flower bloom intervals). Show $O(P \cdot F)$ complexity. |
Coordinate Compression / Line Sweep |
Difference Array on Sorted Events |
Convert each flower into two events: `(start, +1)` and `(end+1, -1)`. Sort events by time. Use a prefix sum to find the bloom count at any specific time point using binary search. |
Draw a timeline with points labeled "+1" (bloom start) and "-1" (bloom end). Draw a person's arrival time as a magnifying glass and calculate the sum of all +1s and -1s to its left. |
Dual-Point Binary Search |
Draw two sorted arrays: `starts` and `ends`. For a time `T`, find `count(starts <= T) - count(ends < T)`. Label each search $O(\log F)$. Total time: $O((F+P)$ log F). |
Allocating a massive array for every single possible day (millions of entries) if done via simulation. |
Two sorted integer arrays of size F (O(F) space). |
| 2252 |
Dynamic Pivoting of a Table |
Manually write `CASE WHEN` statements for every known column. Fails when new dynamic categories are added. |
Hardcoded Query Walls |
Draw a massive SQL query with hardcoded `CASE WHEN` lines for every possible value. |
Prepared Statements / Dynamic SQL |
The Code-Generating Query |
Use `GROUP_CONCAT` to dynamically build a string of `SUM(CASE WHEN...)` statements based on distinct values. Then `PREPARE` and `EXECUTE` that dynamically generated string. |
Draw a machine building a blueprint. The DB scans for unique names, writes the SQL code as a string, feeds that string back into its own compiler, and runs it. |
Two-Phase Execution |
Draw a preliminary scan for distinct values, followed by the execution of the generated pivoted query. |
N/A |
Internal string buffers for query generation. |
| 2253 |
Dynamic Unpivoting of a Table |
Manually write `SELECT id, 'col1', col1 UNION ALL SELECT id, 'col2', col2`. Hardcoded and inflexible. |
Hardcoded Union Stacks |
Draw multiple separate `SELECT` blocks glued together manually. |
Dynamic SQL / Information Schema |
The Column Exploder |
Query the `information_schema` to dynamically find all columns for the table, construct a massive `UNION ALL` string dynamically, and execute it. |
Draw a wide row. Drop it into an "Exploder" that shatters it into vertical rows of keys and values based on the schema blueprint. |
Dynamic Execution Overhead |
Draw a linear scan where each row undergoes a dictionary-to-row transformation. |
N/A |
Temporary memory for string concatenation. |
| 2254 |
Design Video Sharing Platform |
Linear List Storage
Store all videos in a simple list. For every `search` or `delete` operation, iterate through the list until the specific video ID is found. |
Sequential Array Scan |
Draw a long list of video boxes. To delete ID 500, check box 1, then 2, then 3... all the way to 500. Show how the platform slows down as more videos are added. |
Hash Map + Min-Heap (for ID reuse) |
Indexed Registry + ID Generator |
Use a Hash Map `ID -> VideoObject` for $O(1)$ access. Use a Min-Heap to track deleted IDs so they can be reused in $O(\log N)$ for the next upload. |
Draw a central "Registry" (HashMap). When a video is deleted, drop its ID into a "Recycle Bin" (Min-Heap). When a new video arrives, check the Bin first. |
Logarithmic/Constant Pipeline |
Draw the Upload $O(\log N)$, Delete $O(1)$, and Search $O(1)$ blocks. Show how this maintains performance at scale. |
Searching and shifting elements in an array for every deletion (O(N) time). |
A Hash Map of video objects and a Min-Heap of available integer IDs (O(N) space). |
| 2255 |
Count Prefixes of a Given String |
Nested String Comparison
For every word in the array, check if it matches the prefix of the target string using a built-in `startsWith()` function or a loop. |
Multi-String Matching |
Draw the target "apple". Draw the list ["a", "app", "cat"]. Check "a" against "apple", then "app", then "cat". Highlight the repeated comparisons. |
Trie (Prefix Tree) / Hash Map |
Prefix Path Traversal |
Insert the target string's prefixes into a Hash Set, or build a Trie of the word list. For the target string, simply walk the Trie once to count how many words end on its path. |
Draw a tree where each node is a character. "apple" is a single branch. For each word in the list, see if it fits entirely on that branch. Every time you hit a "Word End" marker, count it. |
Linear Path Count |
Draw a single pass through the word list. Label it $O(\text{Sum of all word lengths})$. Show that each check is proportional to the word's length, not the total number of words. |
Multiple substring allocations `s.substring(0, i)` for every comparison. |
A Trie structure or a Hash Set containing the unique words/prefixes (O(Total Characters) space). |
| 2256 |
Minimum Average Difference |
Nested Subarray Sums
For every index `i`, run an inner loop from 0 to `i` to calculate the left average, and another inner loop from `i+1` to N-1 for the right average. |
Repeated Window Summation |
Draw an array. At each index, draw two large brackets: one covering the left side and one covering the right. Show the $O(N^2)$ total additions. |
Prefix Sum / Running Total |
Total Sum Balancing Act |
Calculate the total sum of the array first. Traverse once. Maintain a `left_sum`. The `right_sum` is simply `total_sum - left_sum`. Calculate averages in $O(1)$ at each step. |
Draw a horizontal bar representing the `total_sum`. Draw a divider sliding from left to right. As it slides, show the `left_sum` growing and the `right_sum` shrinking instantly. |
Single Linear Timeline |
Draw one $O(N)$ pass to get the total sum, followed by one $O(N)$ pass to calculate the differences. Total time: $O(N)$. |
Re-calculating sums in temporary variables inside an $O(N^2)$ loop. |
Two 64-bit integer variables (`total_sum`, `left_sum`) taking $O(1)$ auxiliary space. |
| 2257 |
Count Unguarded Cells in the Grid |
Full Grid Simulation per Guard
For every guard, initiate a 4-direction scan. For every step in a direction, check the entire list of walls and other guards to see if the vision is blocked. |
Guard-to-Obstacle Cross-check |
Draw a grid. For one guard, draw vision lines. At every cell, draw a magnifying glass checking the "Wall List". Show the $O(G \cdot (R+C)$ * W) complexity. |
Matrix Marking / State Grid |
Vision Obstacle Overwrite |
Create a 2D grid where walls and guards are marked as 'blocking'. For each guard, radiate vision in 4 directions, stopping immediately when hitting a 'blocking' cell. Count remaining '0' cells. |
Draw a grid with 'W' for walls. For a guard 'G', draw arrows that stop physically when they hit 'W' or another 'G'. Mark all cells the arrows pass through as 'Watched'. |
Multi-Directional Grid Sweep |
Draw a grid and show 4 passes (or 1 pass per guard with early exit). Label it $O(R\cdot C + G\cdot (R+C)$). Total time is bounded by the grid area. |
Large lists of coordinates being re-scanned and filtered constantly. |
A 2D integer/char array of size R x C representing the grid states (O(R*C) space). |
| 2258 |
Escape the Spreading Fire |
BFS with Time Simulation
For every possible starting delay `t`, simulate the fire spreading and the person moving simultaneously to see if they can reach the safehouse. |
Binary Search over Simulation |
Draw a timeline of delays: 1 min, 2 mins, 3 mins... For each, draw a sequence of grid states showing the fire and person moving. Show $O(\log(R\cdot C)$ * (R*C)) complexity. |
Multi-Source BFS + Arrival Time Comparison |
Time-to-Burn Heatmap |
Run one Multi-Source BFS to find the `fire_arrival_time` for every cell. Run a second BFS for the person's `earliest_arrival_time`. Use the difference to find the max delay. |
Draw two grids side-by-side. Grid A: Fire's arrival time at each cell. Grid B: Person's arrival time. Subtract A - B for each cell to find the "Safety Margin" at the exit. |
Parallel BFS Timelines |
Draw two sequential $O(R\cdot C)$ blocks. The first populates the fire heatmap; the second finds the path. This avoids the overhead of repeated simulations. |
Storing thousands of grid states for every different time-delay simulation attempt. |
Two 2D integer arrays (O(R*C) space) for storing the fire and person arrival times. |
| 2259 |
Remove Digit From Number to Maximize Result |
String Reconstruction
Find every occurrence of the digit. For each, create a new string with that instance removed, convert to a BigInt, and compare to find the max. |
Branching String Copies |
Draw the number "1231". Draw two branches: "231" and "123". Compare them as strings. Note the cost of $O(N^2)$ for many large string allocations. |
Greedy One-Pass Comparison |
Peak-Drop Scanning |
Traverse the string. If `current_digit == target` and the `next_digit > current_digit`, remove it immediately (greedy). If no such case exists, remove the *last* occurrence. |
Draw the string. Point to the target digit. Look at its right neighbor. If the neighbor is "higher", draw a "Delete" X over the current digit and stop. Otherwise, keep moving. |
Linear Scan with Early Exit |
Draw a single $O(N)$ line. Inside, show a simple $O(1)$ comparison `s[i] < s[i+1]`. This avoids building multiple temporary strings until the very end. |
Multiple large string objects (N strings of length N-1) held in the heap. |
A single pass with two pointers and one final substring operation (O(N) space). |
| 2260 |
Minimum Consecutive Cards to Pick Up |
Nested Loop Comparison
For every card at index `i`, run an inner loop `j` to find the next occurrence of the same card and calculate the distance `j - i + 1`. |
Quadratic Pair Search |
Draw the cards. Pick card 1. Scan the rest of the array for a match. Pick card 2. Scan the rest of the array. Highlight the $O(N^2)$ search lines. |
Sliding Window / Hash Map |
Last-Seen Index Tracking |
Iterate through the array once. Use a Hash Map to store the `card_value -> last_seen_index`. If a card is seen again, calculate the distance from its `last_seen_index`. |
Draw the array. Keep a "History Book" (HashMap) on the side. When you see a card, look it up in the book. If it's there, draw a bracket between the current and old position. Update the book with the new index. |
Single Pass Registry |
Draw an $O(N)$ timeline. Show the Hash Map being updated in $O(1)$ at each step. Total time is strictly linear. |
No extra space, but $O(N^2)$ time creates a massive execution bottleneck. |
A Hash Map storing unique card values and their most recent integer index (O(N) space). |
| 2261 |
K Divisible Elements Subarrays |
All Subarrays + Divisibility Check
Generate every possible subarray (O(N^2)). For each, iterate through its elements to count how many are divisible by `p`. If count <= k, add the subarray to a Set to ensure uniqueness. |
Triple Nested Iteration |
Draw an array. Draw all possible brackets (subarrays). For each bracket, draw a smaller loop inside checking every number. Note the $O(N^3)$ time and $O(N^3)$ space for the Set. |
Sliding Window + Rabin-Karp / Trie |
Rolling Hash Subarray Fingerprinting |
Use two pointers to find valid windows. To handle "uniqueness" without storing full strings, use a Trie to insert each valid subarray. Each path in the Trie represents a unique subarray. |
Draw a Trie (Prefix Tree). As you find a valid subarray, trace its numbers as a path down the tree. If you reach a new node, increment the `unique_count`. This avoids storing massive strings in a Set. |
Amortized Trie Insertion |
Draw an $O(N^2)$ loop for all starting positions. For each, draw an $O(N)$ extension that inserts into the Trie. Total time: $O(N^2)$. Space is optimized because overlapping prefixes share nodes. |
A massive Hash Set storing full copies of every valid subarray as strings or lists. |
A Trie where each node stores a single integer and a map of children (O(Total_Unique_Elements) space). |
| 2262 |
Total Appeal of A String |
Exhaustive Substring Scoring
Generate all $O(N^2)$ substrings. For each substring, use a Hash Set to count the number of distinct characters (appeal). Sum all these counts. |
Quadratic Set Accumulation |
Draw the string "abbca". List every substring. Next to each, draw a small set showing distinct letters. Sum the sizes. Highlight the $O(N^3)$ or $O(N^2)$ bottleneck. |
DP / Contribution of Each Character |
Last-Occurrence Influence Map |
The "appeal" of a string can be calculated by summing the contribution of each character. A character at index `i` contributes to all substrings starting at `0 to last_seen[char]` and ending at `i`. |
Draw the string. For the current char, find its previous identical twin. Every substring ending *after* the twin and including the current char gets +1 appeal. Write a simple formula: `total += (i - prev[char]) * (n - i)`. |
Linear Aggregate Sweep |
Draw a single $O(N)$ pass. At each step, show a single integer addition to the `total_appeal` using the distance to the last-seen index. Total time: $O(N)$. |
Creating and storing N^2 substrings or using sets repeatedly in a nested loop. |
An integer array of size 26 to store the `last_seen_index` of each character (O(1) space). |
| 2263 |
Make Array Non-decreasing or Non-increasing |
Recursive Cost Minimization
At each index, try changing the number to every possible value within the range [min, max] of the array and recurse to see if the rest can be made non-decreasing. |
Branching Value Assignments |
Draw an array element. Branch out into 100 different possible values it could become. Repeat for every element. Show the exponential $O(\text{Range}^N)$ explosion. |
Priority Queue (Slope Trick) |
Max-Heap Gradient Balancing |
To make an array non-decreasing, maintain a Max-Heap. For each element `x`, push it to the heap. If `x < heap.top()`, the cost is `heap.top() - x`. Pop the top and push `x` twice to maintain the optimal "slope." |
Draw a Max-Heap. Push numbers in. When a smaller number arrives, "squash" the difference by popping the largest and adding the difference to a `total_cost` bucket. Repeat for the reversed array. |
Linear Heap Processing |
Draw an $O(N)$ timeline for the array pass. Inside, draw an $O(\log N)$ heap operation. Total complexity: $O(N \log N)$. |
A massive 2D DP table `dp[index][value]` if using standard DP (O(N * Range)). |
A Priority Queue (Max-Heap) containing at most N elements (O(N) space). |
| 2264 |
Largest 3-Same-Digit Number in String |
Substring Slicing & Sort
Extract every 3-character substring. Check if all 3 characters are the same. Store valid ones in a list, sort them, and return the largest. |
Window Extraction & Filtering |
Draw the string. Draw a 3-wide box. Slide it. If the box has "777", copy it to a side list. If "333", copy it. Sort the list at the end. |
Iterative Comparison |
Peak Triple Search |
Traverse the string from index 0 to N-3. If `s[i] == s[i+1] == s[i+2]`, compare this digit to the `max_digit` found so far. Return the digit repeated thrice as a string. |
Draw the string. Point to `s[i]`. Check the next two neighbors. If they match, update a "Best Digit" register. Do this in one pass without extra string allocations. |
Single Linear Scan |
Draw one $O(N)$ line. Show three simple equality checks at each step. Total time is $O(N)$ with $O(1)$ extra work per step. |
A list of strings containing all valid 3-digit triplets (O(N) space). |
A single character or integer variable `max_digit` (O(1) space). |
| 2265 |
Count Nodes Equal to Average of Subtree |
Recursive Re-calculation
For every node in the tree, initiate a separate DFS to calculate the sum and count of all nodes in its subtree. Then check if `node.val == sum/count`. |
Redundant Tree Traversals |
Draw a tree. For the root, highlight the whole tree. For the left child, highlight its subtree. Note that nodes at the bottom are counted many times (O(N^2)). |
Post-order Traversal (Bottom-Up DP) |
State-Passing Recursion |
Perform a single DFS where each node returns a pair: `{sum_of_subtree, count_of_nodes}`. Use these values at the parent to check the condition in $O(1)$ and return the updated pair. |
Draw a node. It receives `(sum: 10, count: 2)` from left and `(sum: 5, count: 1)` from right. It adds its own value (e.g., 5). New state: `(sum: 20, count: 4)`. Average is 5. Matches! Increment global counter. |
Single-Pass Tree Sweep |
Draw the tree with arrows starting from leaves and moving upward. Label it $O(N)$. Each node is visited exactly once, and its subtree stats are built incrementally. |
No extra data structures, but $O(N^2)$ time causes performance lag on deep trees. |
A recursion stack of height H and a pair of integers per recursive call (O(H) space). |
| 2266 |
Count Number of Texts |
Recursive Permutations
For a string like "222", recursively branch into: "2", "22", or "222" (representing 'a', 'b', 'c'). Count all leaf nodes in the recursion tree. |
Exploding Decision Tree |
Draw a root node. Branch into 3 choices for digit '2'. From each choice, branch again. Show the $O(3^N)$ or $O(4^N)$ depth for keys like '7' or '9'. |
Linear DP (Climbing Stairs Variant) |
Sliding Window Accumulator |
`dp[i]` is the number of ways to decode the prefix of length `i`. If `s[i] == s[i-1]`, then `dp[i]` can include `dp[i-2]`, and so on, up to the max letters per key (3 or 4). |
Draw a 1D array. For each index, draw curved arrows reaching back to the previous 3 (or 4) indices. Sum those values and write the result in the current cell. |
1D State-Space Timeline |
Draw an $O(N)$ line representing the DP array fill. Above it, show a constant-time "Lookback" window of size 4. Total complexity: $O(N)$. |
Massive call stack depth with thousands of redundant calculations for the same substrings. |
A 1D DP array of size N (or even $O(1)$ space if using only the last 4 variables). |
| 2267 |
Check if There Is a Valid Parentheses String Path |
Exhaustive DFS
Explore every possible path from (0,0) to (m,n). For each path, maintain a string of '(' and ')' and check if it is a valid parenthesis sequence at the end. |
Path Permutation Grid |
Draw a 3x3 grid. Draw every possible "Right-Down" snake path. For each path, write out the string and check balance. Show the $O(2^(M+N)$) explosion. |
3D Dynamic Programming |
Visited State Pruning |
Use a 3D state `dp[r][c][balance]`, where `balance` is the count of open '(' minus closed ')'. If `balance < 0`, the path is invalid. Store booleans to mark reachable states. |
Draw the grid. In each cell, list the possible "balance" values (e.g., {1, 3}). When moving to the next cell, increment or decrement those values based on the new character. |
Matrix-State Filling |
Draw an `M x N x (M+N)` box. Label it $O(M \cdot N \cdot (M+N)$). Show that even though it’s 3D, it’s far smaller than the exponential brute force. |
Storing every full path string in a list (massive memory overhead). |
A 3D boolean array or a 2D array of Hash Sets (O(M * N * (M+N)) space). |
| 2268 |
Minimum Number of Keypresses |
Permutation of Keymaps
Try mapping every character (a-z) to every possible position on a 9-key keypad. Calculate total presses for each map and pick the minimum. |
Brute Force Mapping Search |
Draw a 9-key keypad. Assign 'a' to key 1, 'b' to key 1, 'c' to key 1, etc. Then swap. Note the $O(26!)$ factorial possibilities. |
Greedy + Sorting |
Frequency-First Distribution |
Count the frequency of each letter. Sort letters by frequency (highest first). Assign the top 9 letters to the 1st position (1 press), next 9 to 2nd (2), and the rest to 3rd (3). |
Draw a frequency bar chart. Take the 9 tallest bars and put them in a "1-Press" bucket. Take the next 9 and put them in a "2-Press" bucket. Multiply frequency by bucket weight. |
Frequency Sort Timeline |
Draw an $O(N)$ pass for counting, an $O(26 \log 26)$ step for sorting, and an $O(26)$ pass for calculation. Total time: $O(N)$. |
Generating and storing millions of keypad configuration strings. |
An integer array of size 26 for frequency counts (O(1) auxiliary space). |
| 2269 |
Find the K-Beauty of a Number |
Integer-to-String Slicing
Convert the number to a string. Use a nested loop to extract every substring of length K, convert it back to an integer, and check the divisibility. |
Sub-segment Division Check |
Write "240" with k=2. Highlight "24" and "40". Draw a division sign `/` for 240/24 and 240/40. Circle the ones that leave 0 remainder. |
Sliding Window (String or Math) |
Fixed-Width Window Scan |
Use a single pass over the string version of the number. Extract a window from index `i` to `i+k`. Check divisibility immediately. Use `BigInteger` if the constraints exceed 64 bits. |
Draw the number as a tape. Draw a fixed-size frame of width K. Slide the frame one digit at a time. At each step, write the frame's number and the result of the `%` operation. |
Linear String Sweep |
Draw an $O(N)$ timeline where N is the number of digits. Label each step as $O(K)$ for substring and parsing. Total: $O(N\cdot K)$. |
Creating and storing an array of all possible substring integers before checking. |
A few integer/string variables for the current window (O(K) or $O(1)$ space). |
| 2270 |
Number of Ways to Split Array |
Nested Summation
For every possible split point `i`, run an inner loop from 0 to `i` for the left sum and `i+1` to N-1 for the right sum. |
Pivot-Point Overlap |
Draw an array. Point to index 0. Draw a sum-bracket for the left and a long sum-bracket for the right. Move to index 1 and redraw everything. Show $O(N^2)$. |
Prefix Sum / Running Total |
Balance Beam Pivot |
Calculate the total sum first. Traverse once. Maintain a `left_sum`. The `right_sum` is simply `total_sum - left_sum`. Compare `left_sum >= right_sum`. |
Draw the total sum as a weight. Draw a sliding divider. As the divider moves right, the "Left Weight" increases and "Right Weight" decreases instantly. Count the moments of balance. |
Two-Pass Linear Scan |
Draw an $O(N)$ line for the total sum, then a second $O(N)$ line for the splitting checks. Total time: $O(N)$. |
Re-calculating the sum of N elements for N split points (O(N^2) work). |
Two 64-bit integer variables (`total_sum`, `left_sum`) taking $O(1)$ space. |
| 2271 |
Maximum White Tiles Covered by a Carpet |
Nested Coverage Check
For every single starting coordinate of every white tile range, place the carpet and iterate through all ranges to count how many tiles are covered. |
Carpet-to-Range Overlap |
Draw a number line with white tile segments. For every integer point, draw a "carpet" bar. Manually count the overlap with the tile segments. Show $O(N^2)$ or worse depending on tile density. |
Two Pointers + Prefix Sum |
Sliding Window over Intervals |
Sort the tile ranges. Use a sliding window where the `left` pointer is the start of a range and the `right` pointer is the furthest range the carpet can reach. Use prefix sums to count full ranges in $O(1)$ and handle the partial end-range. |
Draw sorted segments. Draw a "carpet" bracket covering multiple segments. Slide the bracket to the next segment's start. Show the "Full Segments" being added via prefix sum and the "Partial Segment" calculated via subtraction. |
Linear Window Sweep |
Draw an $O(N \log N)$ sorting step, followed by an $O(N)$ sliding window pass. Label it $O(N \log N)$ total. Show each pointer moving strictly forward. |
Iterating through every individual coordinate unit (can be billions) instead of interval ranges. |
A prefix sum array of the tile counts per range and the sorted range list (O(N) space). |
| 2272 |
Substring With Largest Variance |
All Substrings + Freq Map
Generate every possible substring (O(N^2)). For each, count the frequency of all characters and find `max_freq - min_freq`. |
Nested Window Variance |
Draw the string. Draw every possible window. For each window, draw a tally chart of all 26 letters. Calculate variance. Show the $O(N^2 \cdot 26)$ complexity. |
Kadane’s Algorithm Variation |
Binary Character-Pair Filter |
Variance only depends on two characters (a, b). For every pair of characters in the alphabet (26x25), treat 'a' as +1 and 'b' as -1. Run a modified Kadane’s to find the max subarray sum that includes at least one -1. |
Pick 'a' and 'b'. Draw the string as a sequence of +1, -1, and 0s. Run the "Max Subarray Sum" logic, but keep a flag that you've seen at least one 'b'. Repeat for all 650 possible pairs. |
Fixed-Pair Linear Pass |
Draw a block labeled "26 x 25 pairs". Inside, draw an $O(N)$ Kadane's pass. Total: $O(26^2 \cdot N)$. Show why this is faster than $O(N^2)$ when N is large. |
Storing frequency maps or sets for every single substring in memory. |
A few integer variables (`current_sum`, `max_variance`) per character pair pass (O(1) auxiliary space). |
| 2273 |
Find Resultant Array After Removing Anagrams |
Recursive Deletion
Scan the array. If `words[i]` and `words[i-1]` are anagrams, delete `words[i]`, shift the array, and restart the scan from index 1. |
Array Mutation Simulation |
Draw the list of words. Circle two anagrams. Cross one out. Redraw the *entire* list shifted. Repeat. Show the $O(N^2)$ work for removals. |
Stack / Previous-Word Pointer |
Immediate Neighbor Comparison |
Iterate through the array once. Compare the current word's sorted version (or frequency map) with the *last added* word in your result list. If they differ, add the current word. |
Draw a "Result" conveyor belt. Look at the word in the input. Compare its "sorted" tag to the last word on the belt. If they don't match, drop it on the belt. If they do, skip it. |
Single Pass Filter |
Draw a single $O(N)$ timeline. Label each step as $O(\text{Length of Word})$ for the anagram check. Total time: $O(N \cdot L)$. |
Repeatedly creating new shifted copies of the original array. |
A new result list and a temporary frequency array of size 26 (O(N * L) space). |
| 2274 |
Maximum Consecutive Floors Without Special Floors |
Boolean Array / Bitset
Create a boolean array from `bottom` to `top`. Mark special floors as `true`. Scan the array for the longest sequence of `false` values. |
Full Range Grid Scan |
Draw a line of numbers from 1 to 1,000,000,000. Mark the "Special" spots. Count the white space. Show why this fails for large ranges (O(Range)). |
Sorting + Gap Calculation |
Sorted Milestone Gaps |
Sort the `special` floors array. The gaps are: (1) `special[0] - bottom`, (2) `special[i] - special[i-1] - 1`, and (3) `top - special[last]`. Find the maximum of these gaps. |
Draw a number line. Mark the `bottom` and `top`. Plot the sorted `special` points. Draw "jump" arrows between the points and write the distance above each jump. Pick the longest jump. |
Sort and Linear Difference |
Draw an $O(S \log S)$ sorting pass for the special floors. Draw an $O(S)$ pass to check the gaps. Label it $O(S \log S)$ where S is the number of special floors, regardless of the building height. |
A massive boolean array or hash set containing every single floor number in the building. |
A single sorted integer array of the special floors (O(S) space). |
| 2275 |
Largest Combination With Bitwise AND Greater Than Zero |
Power Set Combinations
Generate every possible subset of the numbers. For each subset, calculate the bitwise AND. Find the largest subset where the result > 0. |
Exponential Subset Tree |
Draw 3 numbers. Draw a tree branching into every combination: {1}, {1,2}, {1,3}, {1,2,3}... Show the $O(2^N)$ explosion. |
Bit-Position Counting |
Vertical Bit-Column Sum |
A bitwise AND is > 0 if there is at least one bit position where *all* numbers in the combination have a '1'. Check each of the 32 bit positions and count how many numbers have a '1' there. The max count is the answer. |
Draw the numbers in binary, stacked vertically. Draw a vertical box around "Column 0", "Column 1", etc. Count the 1s in each column. The tallest column is your largest combination. |
Constant Bit-Width Scan |
Draw a loop from 0 to 31. Inside, draw an $O(N)$ pass over the array. Total complexity: $O(32 \cdot N)$, which is effectively linear $O(N)$. |
Massive recursion stack and memory for storing all subset results. |
A single integer `max_count` and a loop index (O(1) auxiliary space). |
| 2276 |
Count Integers in Covered Intervals |
Boolean Array / Set
Maintain a massive boolean array or a Hash Set. For every `add(left, right)`, loop from `left` to `right` and set the values to true. Count the true values for the query. |
Unit-by-Unit Marking |
Draw a number line from 1 to 10^9. For an interval [5, 1000], draw 995 individual dots. Show why this crashes memory/time for large ranges. |
Segment Tree (Dynamic) / Churning Map |
Interval Merging / Overlap Collapse |
Use a `TreeMap` (in Java) or `SortedDict` to store non-overlapping intervals. When adding `[L, R]`, find all existing intervals that overlap, merge them into one large interval, and update the global count. |
Draw two existing bars: [10, 20] and [30, 40]. Draw a new bar [15, 35] above them. Show the three bars "melting" together into one single bar [10, 40]. Subtract the old counts and add the new merged length. |
Logarithmic Search & Merge |
Draw an $O(\log N)$ step to find the overlap start. Draw an $O(K)$ step to delete K overlapping intervals. Show that each interval is added/deleted once, making it amortized $O(\log N)$. |
Allocating a bit-set of size 10^9 (requires ~125MB) and iterating through it linearly. |
A balanced BST or TreeMap storing only the endpoints of disjoint intervals (O(N) where N is number of intervals). |
| 2277 |
Closest Node to Path in Tree |
Full Path Search + BFS
For each query `(start, end, node)`, find the unique path between `start` and `end` using DFS. Then, for every node on that path, run a BFS to find the distance to the target `node`. |
Multi-Search Tree Traversal |
Draw a tree. Highlight the path from A to B. For every node on that path, draw a "Search Wave" looking for node C. Repeat for every query. Show $O(Q \cdot N)$. |
LCA + Distance Formula |
Triple LCA Intersection |
The closest node on the path `(u, v)` to node `p` is one of the three LCAs: `LCA(u, v)`, `LCA(u, p)`, or `LCA(v, p)`. Specifically, it's the one with the maximum depth. |
Draw nodes U, V, and P. Draw the path U-V. Draw the LCA of (U,V), (U,P), and (V,P). Notice that one of these three points *must* be the entry point to the path from P. |
Precomputed Binary Lifting |
Draw an $O(N \log N)$ precomputation block for LCA. Draw an $O(1)$ or $O(\log N)$ block for each query. Total time: $O(N \log N + Q \log N)$. |
Storing all nodes of every path found in memory for every query. |
A 2D `parent[N][log N]` table for binary lifting (O(N log N) space). |
| 2278 |
Percentage of Letter in String |
Character Conversion & List Filter
Convert the string to a list of characters. Filter the list to keep only the target letter. Divide the length of the filtered list by the original length. |
List Filtering Simulation |
Draw the string "apple". Copy only the 'p's into a new box. Count both boxes. Show the overhead of creating a new list. |
Linear Counter + Math |
Single-Pass Incrementer |
Iterate through the string once with a simple counter. At the end, perform: `(count * 100) / length` using integer division as per the problem. |
Draw the string as a sequence of characters. Point a finger at each. If it matches, click a handheld "tally counter". At the end, write the fraction and multiply by 100. |
Linear Timeline Pass |
Draw one straight $O(N)$ arrow. No extra allocations, no sub-loops. Total time is strictly $O(N)$. |
Creating a new filtered string or list of characters in the heap (O(N) space). |
A single integer `count` and an index variable (O(1) space). |
| 2279 |
Maximum Bags With Full Capacity of Rocks |
Backtracking / Combinations
Try distributing the `additionalRocks` in every possible way among the bags to see which combination results in the most full bags. |
Recursive Distribution Tree |
Draw 3 bags. Branch into: "Put 1 rock in bag A", "Put 2 rocks in bag A", etc. Show the branching factor exploding based on the number of rocks. |
Greedy + Sorting |
Shortest-Gap-First Filling |
Calculate the `remaining_capacity` for each bag (`capacity[i] - rocks[i]`). Sort these gaps from smallest to largest. Fill the bags with the smallest gaps first until you run out of rocks. |
Draw a series of "partially full" glasses. Sort them by how much empty space is at the top. Pour water into the one that needs the least first. Count how many you filled completely. |
Sort and Linear Fill |
Draw an $O(N)$ pass to find gaps, an $O(N \log N)$ sort, and an $O(N)$ fill pass. Total: $O(N \log N)$. |
Storing recursion states and partial distributions of rocks across N bags. |
A single integer array of size N to store the gaps (O(N) space). |
| 2280 |
Minimum Lines to Represent a Line Chart |
All-Pairs Slope Comparison
For every set of 3 consecutive points, calculate the slope between Point 1 & 2 and Point 2 & 3 using floating-point division. Compare them. |
Consecutive Slope Check |
Draw three points. Draw a line through P1-P2 and P2-P3. If they look "different", increment the line count. Show why floating-point precision issues lead to wrong answers. |
Sorting + Cross-Multiplication |
Precision-Safe Collinearity |
Sort points by X-coordinate. For three points `(x1,y1), (x2,y2), (x3,y3)`, they are on the same line if `(y2-y1)*(x3-x2) == (y3-y2)*(x2-x1)`. This avoids precision errors. |
Draw points on a graph. Sort them. Draw a line segment. For the next point, check the "cross-product" equality. If it fails, start a new line. Show the calculation using integers only. |
Sort and Single Pass |
Draw an $O(N \log N)$ sorting step. Draw an $O(N)$ pass to check slopes. Label it $O(N \log N)$ total. |
No extra space, but incorrect results due to `double` or `float` precision loss. |
Sorting the input array in place (O(log N) or $O(1)$ extra space). |
| 2281 |
Sum of Total Strength of Wizards |
All Subarrays Min * Sum
Generate every possible subarray (O(N^2)). For each, find the minimum element and the sum of elements, then multiply and add to total. |
Nested Subarray Evaluation |
Draw an array. For every possible bracket, manually find the smallest number and add up all numbers. Note the $O(N^3)$ or $O(N^2)$ complexity. |
Monotonic Stack + Prefix Sum of Prefix Sums |
Contribution of Min Element |
For each element `arr[i]`, find the range `(L, R)` where it is the minimum using a monotonic stack. Calculate the sum of all subarrays in that range containing `i` using a "Prefix Sum of Prefix Sums" to achieve $O(1)$ range summation. |
Draw an element `X`. Draw a boundary to its left and right where it remains the "boss" (the minimum). Use a math formula to "teleport" the sums of all subarrays passing through `X` using precomputed sum-arrays. |
Three-Pass Linear Scan |
Draw an $O(N)$ pass for the stack (left bounds), an $O(N)$ pass for right bounds, and an $O(N)$ pass for the final math. Total time: $O(N)$. |
Calculating sums repeatedly in $O(N^2)$ loops. |
Two monotonic stack arrays and two prefix-sum-based arrays (O(N) space). |
| 2282 |
Number of People That Can Be Seen in a Grid |
4-Directional Linear Scan
For every cell `(r, c)`, look in all 4 directions and count how many people can be seen before someone taller blocks the view. |
Exhaustive Vision Check |
Draw a grid. From one cell, draw an arrow. Stop the arrow only when it hits a taller person. Repeat for every cell in all directions. Show $O(R \cdot C \cdot (R+C)$). |
Monotonic Stack (Row/Col wise) |
Descending Height Vista |
Process each row and each column independently using a monotonic decreasing stack. When a new person is added to the stack, they can "see" the person currently at the top of the stack. |
Draw a row of people. Use a stack to keep track of the "tallest seen so far." When a person is popped, increment their "seen" count. Show how each person enters and leaves the stack exactly once. |
Linear Row/Col Processing |
Draw an $O(R\cdot C)$ line representing the scan of all rows, followed by another $O(R\cdot C)$ for all columns. Total time: $O(R\cdot C)$. |
Multiple lists to store the "visible" people per cell before counting. |
A single monotonic stack used repeatedly across rows and columns (O(max(R,C)) auxiliary space). |
| 2283 |
Check if Number Has Equal Digit Count and Digit Value |
Nested Counting
For every index `i`, run an inner loop over the string to count how many times the digit `i` appears. Compare that count to the value at `num[i]`. |
Digit-by-Digit Verification |
Write "1210". For index 0, count how many '0's are in the string. For index 1, count how many '1's. Note the $O(N^2)$ redundancy. |
Frequency Array / Hash Map |
Single-Pass Tally |
Traverse the string once and store the count of each digit in a frequency array of size 10. Then, traverse the string again to compare `freq[i]` with the value at `num[i]`. |
Draw 10 buckets (0-9). Drop each digit of the string into its bucket. Then, walk through the buckets and check if the number of items in bucket `i` matches the character at `num[i]`. |
Two Sequential Linear Passes |
Draw one $O(N)$ arrow to fill the buckets and a second $O(N)$ arrow to verify the counts. Total time: $O(N)$. |
No extra space, but $O(N^2)$ time creates a bottleneck for very long strings. |
A fixed-size integer array of size 10 (O(1) auxiliary space). |
| 2284 |
Sender With Largest Word Count |
Sort by Message Length
Combine all messages for each sender into one giant string, split by spaces, count the words, and then sort the senders by count. |
Full String Concatenation |
Draw a box for Sender A. Append all their messages. Split the massive string into a list. Count. Repeat for all senders. Note the $O(\text{Total}_\text{Chars})$ space. |
Hash Map + Word Split |
Accumulative Word Tally |
Iterate through the messages. For each message, count the spaces to get the word count. Add this to the sender's total in a Hash Map. Keep track of the sender with the max count (and lexicographical tie-breaker). |
Draw a Hash Map. For each message, count the words (don't concatenate!) and add to the sender's score. Use a "Leaderboard" variable to track the winner in real-time. |
Linear Message Scan |
Draw a single $O(\text{Total}_\text{Words})$ timeline. Show the Hash Map updating in $O(1)$ for each message. Total time: $O(N)$. |
Storing massive concatenated strings in memory for every sender. |
A Hash Map storing `SenderName -> IntegerCount` (O(Unique_Senders) space). |
| 2285 |
Maximum Total Importance of Roads |
Permutation of Importance
Try assigning every permutation of importance values (1 to N) to the cities. For each permutation, calculate the total road importance and find the max. |
Factorial Assignment Tree |
Draw 5 cities. Assign [1,2,3,4,5] in all possible ways. Calculate sum of road values for each. Show the $O(N!)$ explosion. |
Greedy Degree-Based Assignment |
High-Degree Priority Sorting |
Count the "degree" (number of roads) for each city. Assign the highest importance values (N, N-1, etc.) to the cities with the highest degrees. |
Draw a graph. Write the degree next to each city (e.g., City A has 4 roads). Sort cities by these numbers. Assign '5' to the city with 4 roads, '4' to the next, etc. |
Degree Count + Sort |
Draw an $O(E)$ pass to count degrees, an $O(V \log V)$ sorting pass, and an $O(V)$ calculation. Total time: $O(E + V \log V)$. |
A list of every possible assignment of importance values. |
A single integer array of size V to store the degrees (O(V) space). |
| 2286 |
Booking Concert Tickets in Groups |
For every booking, linearly scan rows from 0 to N, summing available seats. $O(N)$ per query rightarrow $O(Q \cdot N)$. |
Row-by-Row Search Grid |
Draw a theater. For every group, draw an arrow scanning row 1, then row 2, etc., until enough seats are found. |
Segment Tree (Range Sum & Max) |
The Hierarchical Theater Sections |
Use a Segment Tree to track both the `max_available` seats in any row of a range, and the `sum_available` seats in a range. This allows finding a row for `gather` in $O(\log N)$ and allocating `scatter` in $O(\log N)$. |
Draw the rows at the bottom. Draw a binary tree above them. Each node stores the max and sum of its children. To find 5 seats together, walk down the tree guided by the `max` value. |
Logarithmic Query/Update $O(Q \log N)$ |
Draw a timeline of Q queries. Above each, draw a tree traversal of height log N. |
Storing full row states with no metadata. |
A Segment Tree array of size 4N. $O(N)$ space. |
| 2287 |
Rearrange Characters to Make Target String |
Target Simulation
Physically remove characters from the source string to build one copy of the target. Repeat until you can no longer complete the target string. |
Physical Character Depletion |
Draw the source "abbacc" and target "abc". Cross out one 'a', one 'b', one 'c'. That's 1 copy. Try to cross out more. Count the total successful rounds. |
Frequency Map Ratio |
Limiting Reagent Calculation |
Count the frequency of each character in the source and the target. For each character in the target, calculate `source_freq / target_freq`. The minimum of these ratios is the maximum number of copies. |
Draw two frequency tables. Table A: Source counts. Table B: Target counts. For each letter in Table B, divide A/B. Circle the smallest resulting number (the "bottleneck"). |
Parallel Map Scan |
Draw an $O(N)$ line for the source scan and an $O(M)$ line for the target. Label it $O(N + M)$. Show the $O(26)$ calculation at the end. |
Creating multiple new strings as you "delete" characters from the source. |
Two integer arrays of size 26 (O(1) auxiliary space). |
| 2288 |
Apply Discount to Prices |
Regex Splitting + Global Search
Use a complex regular expression to find all price patterns. For each match, parse the number, calculate the discount, and replace the text. |
Pattern Matching & Replacement |
Draw the sentence. Highlight "100". Draw an arrow to a calculator. Write "90.00" in its place. Show how edge cases like "10a" can break complex regex logic. |
Word-by-Word Parsing |
Token Validation & Transform |
Split the sentence into words by spaces. For each word, check if it starts with '', followed only by digits. If valid, convert to double, apply discount, and format to 2 decimal places. Join words back. |
Draw the string split into boxes. Look at box 1. Does it start with ''? Yes. Are the rest digits? Yes. Apply math. Look at box 2. Repeat. Assemble the boxes back into a line. |
Single Pass Tokenizer |
Draw an $O(N)$ timeline where N is the length of the string. Show each word being processed exactly once in linear time. |
Multiple large strings created during repeated regex `replaceAll` calls. |
A list of word strings and a `StringBuilder` to reconstruct the sentence (O(N) space). |
| 2289 |
Steps to Make Array Non-decreasing |
Iterative Simulation
Scan the array and delete every element `nums[i]` where `nums[i] < nums[i-1]`. Repeat the entire scan until no more deletions occur. |
Repeated Deletion Rounds |
Draw the array. Cross out elements in the first pass. Redraw the shortened array. Cross out elements in the second pass. Repeat. Show the $O(N^2)$ complexity. |
Monotonic Stack (Time-to-Die) |
Eat-Left Influence Chain |
Use a monotonic stack to store elements and the "time" (number of steps) they will survive. An element dies if there is a larger element to its left. Its "time to die" is the max of the die-times of the elements it "eats" + 1. |
Draw the array. Use a stack to track how long each element survives. When an element is blocked by a larger one to its left, calculate its "survival duration" based on the neighbors it outlasted. |
Linear Stack Sweep |
Draw an $O(N)$ timeline. Show each element being pushed/popped from the stack exactly once. The answer is the maximum "survival time" found. |
Storing multiple full copies of the array for each step of the simulation. |
An integer array to store survival times and a monotonic stack (O(N) space). |
| 2290 |
Minimum Obstacle Removal to Reach Corner |
Standard BFS (All Paths)
Run a BFS where each state is `(row, col, obstacles_removed)`. Explore all paths and find the one with the minimum obstacles. |
Layered Wavefront BFS |
Draw a grid. Draw a wave starting at (0,0). For each obstacle, the "cost" increases. Show how the queue grows exponentially as it tracks different removal counts. |
0-1 BFS (Deque) |
Weighted Shortest Path |
Treat empty cells as weight 0 and obstacles as weight 1. Use a `Deque`. If moving to an empty cell, `push_front` (higher priority). If moving to an obstacle, `push_back`. This finds the shortest path in $O(V+E)$. |
Draw the grid. Use a Deque to manage the "frontier." When you hit an empty cell, jump it to the front of the line. When you hit a wall, send it to the back. This ensures you always explore the "cheapest" paths first. |
Graph Traversal Flow |
Draw a grid and show the "search wave" prioritizing empty paths. Label it $O(R\cdot C)$ since each cell is visited optimally once. |
A massive priority queue or multiple state arrays for every possible obstacle count. |
A 2D `dist` array and a Deque of coordinates (O(R*C) space). |
| 2291 |
Maximum Profit From Trading Stocks |
Backtracking / Subsets
For every stock, try either buying it or skipping it. Check all combinations that fit within the `budget` and calculate the total profit. |
Exponential Decision Tree |
Draw a root node. For Stock 1, branch into "Buy" and "Skip". Repeat for Stock 2. Note the $O(2^N)$ paths. Show how many branches are pruned when the budget is exceeded. |
1D Dynamic Programming (Knapsack) |
Budget-Space Optimization |
This is a 0/1 Knapsack problem. Create a `dp` array where `dp[i]` is the max profit for budget `i`. For each stock, iterate the budget *backwards* from `maxBudget` to `cost` to update the profit. |
Draw a 1D array representing budget levels. For a stock with cost 5 and profit 10, show the values in the array from index 5 to Max shifting upwards as the new profit is added. |
DP Matrix Fill Pass |
Draw an $O(N)$ loop for stocks and an $O(B)$ loop for budget. Label it $O(N \cdot B)$. Show how the 1D array allows us to save space compared to a 2D table. |
Massive recursion stack and memory for every valid purchase combination. |
A 1D integer array of size `budget + 1` (O(B) space). |
| 2292 |
Products With Three or More Orders in Two Consecutive Years |
Massive self-joins checking Year 1 against Year 2, filtering counts in both simultaneously. |
Tangled Self-Join Web |
Draw Year 2020 pointing to 2021, and 2021 pointing to 2022, doing separate aggregations for each link. |
CTE Aggregation + Window Function (LEAD) |
The Year-Over-Year Filter |
1. CTE to group by Product and Year, keeping only rows where `COUNT >= 3`. 2. Use `LEAD(year)` on this filtered list to check if the next valid year is exactly `current_year + 1`. |
Draw a timeline. Put gold stars on years with 3+ orders. Erase other years. Look at the gold stars. If two stars are right next to each other (Year gap = 1), keep the product. |
Hash Aggregation + Sort $O(N \log N)$ |
Draw the aggregation pipeline, a filter, and a final sort/window scan. |
Massive intermediate join tables. |
Internal DB window buffer. $O(P)$ space. |
| 2293 |
Min Max Game |
Recursive Array Slicing
While the array length > 1, create a brand new array half the size. Manually populate it by alternating between `min()` and `max()` of pairs. |
Shrinking Layer Simulation |
Draw an array of 8 numbers. Below it, draw 4 numbers (the results of pairs). Below that, 2, then 1. Show the repeated memory allocation for each new array. |
In-Place Iterative Reduction |
Half-Length Compression |
Use a single array. In each round, update the first `n/2` elements using the values from the current array. Reduce the "active" size of the array by half until only index 0 remains. |
Draw one array. Draw arrows from `nums[0], nums[1]` to `nums[0]`. Then from `nums[2], nums[3]` to `nums[1]`. Show the data "collapsing" toward the left side of the same array. |
Logarithmic Reduction Timeline |
Draw a loop that runs log(N) times. Inside, show an $O(N)$ pass. The total work is N + N/2 + N/4... which converges to $O(N)$. |
Allocating log(N) different arrays, totaling $O(N)$ extra space. |
Mutating the original array in place (O(1) extra space). |
| 2294 |
Partition Array Such That Maximum Difference Is K |
Power Set Partitioning
Try every possible way to group the numbers into subsets. For each subset, check if `max - min <= k`. Find the minimum number of subsets needed. |
Exponential Grouping Tree |
Draw a set 1, 2, 10. Branch into groups: [1,2, 10] or [1, 2, 10]. Note the massive number of partitions to check. |
Sorting + Greedy Subsequences |
Sorted Interval Anchoring |
Sort the array. Start a new subsequence with the first element as the `min`. Iterate through the array; if the current element is > `min + k`, start a *new* subsequence and update the `min`. |
Draw a sorted number line. Mark the first point. Draw a bracket of width K. All points inside the bracket are in Group 1. The first point *outside* starts Group 2. Count the brackets. |
Sort and Linear Sweep |
Draw an $O(N \log N)$ sort. Draw an $O(N)$ single pass to count the brackets. Total time: $O(N \log N)$. |
Storing multiple lists of subsets in memory. |
A single variable to track the current `min` of the active group (O(1) auxiliary space). |
| 2295 |
Replace Elements in an Array |
Nested Search and Replace
For every operation `[old, new]`, iterate through the entire array to find the `old` value and replace it with the `new` one. |
Repeated Linear Scanning |
Draw an array. For Operation 1, draw a magnifying glass scanning the whole array to find "3". Replace it. For Operation 2, scan again. Show $O(\text{Ops} \cdot N)$. |
Inverted Index (Hash Map) |
Value-to-Index Map |
Create a Hash Map where `Value -> Index`. For each operation `[old, new]`, look up the index of `old` in $O(1)$, update the array at that index, and update the Map to point `new` to that index. |
Draw the Array and a Map side-by-side. For an operation, point to the Map. It gives you the index immediately. Jump to that index in the Array, swap the value, and update the Map entry. |
Linear Operation Stream |
Draw an $O(N)$ pass to build the map, followed by an $O(M)$ pass for M operations. Total time: $O(N + M)$. |
No extra space, but $O(N\cdot M)$ time is too slow for large inputs. |
A Hash Map containing N entries for mapping values to indices (O(N) space). |
| 2296 |
Design a Text Editor |
String Concatenation
Represent the text as a single large string. For every `addText` or `deleteText`, create new substrings and concatenate them. Use `substring()` for cursor movement. |
String Slicing & Rebuilding |
Draw a long string. To insert "hello", draw a line splitting the string, then redraw the whole string with "hello" in the middle. Show the $O(N)$ cost per edit. |
Two Stacks / Gap Buffer |
Cursor-Centric Movement |
Use two stacks (or strings): `left` (text before cursor) and `right` (text after cursor). `addText` pushes to `left`. `cursorLeft` pops from `left` and pushes to `right`. `deleteText` just pops from `left`. |
Draw two vertical stacks facing each other. The gap between them is the cursor. To move left, pop a letter from the left stack and drop it into the right. To type, just drop a letter onto the left stack. |
$O(1)$ Amortized Editing |
Draw two blocks representing the stacks. Show that moving the cursor or adding text only affects the "tops" of the stacks. Label it $O(K)$ where K is characters moved/added. |
Large immutable string objects created in the heap for every single cursor move. |
Two `StringBuilder` objects or character stacks representing the text (O(N) space). |
| 2297 |
Jump Game VIII |
Recursive DFS with Memo
From each index, check all possible jump conditions (min/max of range). Recursively find the path with minimum cost to reach the end. |
Decision Tree Branching |
Draw an index. Branch to every index it *could* jump to. Repeat. Even with memoization, show the number of edges being checked repeatedly. |
Monotonic Stack + 1D DP |
Next Greater/Smaller Anchoring |
An index `i` can jump to the "next greater or equal" element and the "next smaller" element. Use two monotonic stacks to precompute these "next" indices for everyone. Then run a simple DP to find the min cost. |
Draw the array. Use a stack to find the "Next Big" and "Next Small" neighbors for each point. Draw arrows connecting them. Fill a 1D DP array by taking `min(cost[current] + jump_price)`. |
Linear Precomputation + DP |
Draw $O(N)$ for precomputing jump targets using stacks. Draw $O(N)$ for the DP pass. Total complexity: $O(N)$. |
Massive recursion stack and potentially checking $O(N^2)$ jump edges. |
Two integer arrays for jump targets and one for DP costs (O(N) space). |
| 2298 |
Tasks Count in the Weekend |
Iterative Date Parsing
Iterate through every task in the database. Use a programming language function or SQL logic to determine the "Day of Week" for each date. Count if it's Saturday or Sunday. |
Row-by-Row Calendar Check |
Draw a table of dates. For each row, pull out a calendar and check if that date falls on a weekend. Tally it. Show $O(N)$ full table scan. |
Weekday Function (SQL CASE/WEEKDAY) |
Logical Boolean Summation |
Use `WEEKDAY(date)` or `TO_CHAR(date, 'D')`. If the result is 5/6 (or 1/7 depending on DB), treat it as a weekend. Use a `SUM(CASE ...)` or `COUNTIF` for efficiency. |
Draw a flow chart. Data enters, passes through a "Weekend Filter" (Saturday/Sunday), and increments a counter. Everything else passes into a "Weekday Counter." |
Indexed Date Filter |
Draw an $O(N)$ scan. Note that if the `date` column is indexed, the database can optimize the retrieval and counting process significantly. |
Creating temporary lists of all weekend dates before counting them. |
A few integer registers in the DB engine to store the counts (O(1) auxiliary space). |
| 2299 |
Strong Password Checker II |
Multiple Regex Passes
Run 6-7 different regular expressions against the password to check for length, lowercase, uppercase, digits, special chars, and duplicates. |
Sequential Pattern Matching |
Draw a password string. Pass it through Filter 1 (Length), then Filter 2 (Lower), etc. Show how the engine restarts the scan from the beginning for every regex. |
Single-Pass Flagging |
Multi-State Boolean Registry |
Iterate through the string exactly once. Use 4-5 boolean flags. At each character, update the flags and check `char[i] == char[i-1]` for the duplicate rule. |
Draw the string. Write 5 checkboxes below it. As you scan, check the boxes. At the end, if all boxes are checked and you never saw two same neighbors, the password is "Strong." |
Linear Single-Pass Timeline |
Draw one straight $O(N)$ arrow. Show all conditions being evaluated simultaneously at each character step. |
Allocating multiple match objects and temporary string copies for each regex. |
A set of boolean variables and one "last_char" variable (O(1) space). |
| 2300 |
Successful Pairs of Spells and Potions |
Nested Loop Multiplier
For every spell, iterate through every potion and multiply them. If the product >= `success`, increment the count. |
Quadratic Intersection Grid |
Draw Spells on the Y-axis and Potions on the X-axis. For every intersection, draw a multiplication sign. Note the $O(N \cdot M)$ total calculations. |
Sorting + Binary Search |
Threshold Search Space |
Sort the `potions` array. For each spell, calculate the `required_potion = ceil(success / spell)`. Use binary search (`lower_bound`) to find the first potion that meets this requirement. |
Draw a sorted line of Potions. For one Spell, calculate the "entry requirement." Draw an arrow jumping straight to the middle of the Potions line to find the cutoff point. |
Logarithmic Multi-Search |
Draw an $O(M \log M)$ sort for potions. Draw an $O(N \log M)$ block for searching. Total complexity: $O((N+M)$ log M). |
No extra space, but $O(N\cdot M)$ time is too slow for 10^5 elements. |
The sorted version of the potions array (O(M) space). |
| 2301 |
Match Substring After Replacement |
Nested loops: For every index in `s`, check if `sub` matches using an exhaustive check against the `mappings` array. |
Nested Loop Tree (O(N * M * K)) |
Draw a timeline for `s`. From each node (character), draw branches representing the length of `sub`, then branch again for every possible character mapping. |
Sliding Window + Hash Map of Sets |
Sliding Window Frame over `s` mapped to a Dictionary Lookup. |
Slide a fixed-width rectangular box (size of `sub`) across `s`. For each alignment, point arrows from `sub` chars to `s` chars, checking the Hash Map. |
Draw string `s` as an array. Draw string `sub` below it. Draw a box around `sub`. Cross out mismatched pairs, or draw a checkmark if valid via mapping. |
Linear Scan Line + Constant Lookups (O(N * M)) |
Draw a straight timeline of N steps. At each step, draw a smaller secondary line of M steps. No deep branching. |
Draw a 2D matrix representing the raw `mappings` array. |
Draw a Hash Map where keys are chars and values are circled Sets of allowed replacement chars. |
| 2302 |
Count Subarrays With Score Less Than K |
Generate every possible subarray, compute the sum, multiply by length, and check if < k. |
N-Squared Triangle Grid |
Draw a staircase or a 2D grid where rows are start indices and columns are end indices. Fill cells with computed scores. |
Sliding Window (Two Pointers) |
Expanding and Shrinking Caterpillar |
Place `left` and `right` markers. Move `right` to expand (add to sum). If score >= k, move `left` to shrink (subtract from sum). Add `(right - left + 1)` to total. |
Draw an array. Draw `L` and `R` arrows pointing to indices. Draw a box showing `Current Sum` and `Current Score` updating as arrows move right. |
Parallel Pointers (O(N)) |
Draw two parallel timelines. The `R` timeline moves forward steadily. The `L` timeline occasionally catches up, but neither moves backward. |
Draw an empty space (O(1) memory), but sketch a stack of overlapping subarray segments to represent the nested iterations. |
Draw two variables (`sum`, `score`) as small boxes whose values get crossed out and updated continuously. |
| 2303 |
Calculate Amount Paid in Taxes |
Iterate linearly through the tax brackets, computing tax for the overlapping portion of income. |
Linear Step Ladder (O(N)) |
Draw a number line. Slice it into segments based on bracket upper bounds. |
Linear Iteration (Math/Simulation) |
Filling Stepped Buckets |
Track `prev_bound`. For each bracket, tax the amount `min(income, upper) - prev_bound`. Subtract from total income. |
Draw buckets of varying widths (bracket limits). Shade the buckets up to the `income` level, multiplying shaded areas by the percentage. |
Single Straight Line (O(N)) |
Draw a straight line connecting N nodes (brackets). |
Draw the 2D array of `brackets` as a simple list of pairs. |
Draw the same list of pairs, plus one accumulator variable box for `Total Tax`. |
| 2304 |
Minimum Path Cost in a Grid |
DFS / Backtracking: Explore every possible path from the first row to the last row, summing costs. |
Exponential Recursion Tree |
Draw a root node branching out `cols` times. Each of those branches out `cols` times, repeating for `rows` levels. |
Dynamic Programming (Bottom-Up) |
Directed Acyclic Graph (DAG) Shortest Path |
Initialize a DP array with the first row. For the next row, calculate the min cost to reach each cell by looking at all cells in the previous row + transition cost. |
Draw a 2D grid. In each cell, write the minimum cost to get there. Draw multiple arrows from the row above to the current cell, circling the one with the lowest total. |
3D Nested Loop Block (O(M * N^2)) |
Draw a 3D rectangular prism where dimensions are M (rows), N (cols), and N (prev cols). |
Draw a deep vertical Call Stack representing the recursion depth (O(M)). |
Draw two 1D arrays representing `prev_row_dp` and `curr_row_dp`, showing how one overwrites the other. |
| 2305 |
Fair Distribution of Cookies |
Generate all possible permutations of assigning N bags of cookies to K children. |
K-ary Tree (O(K^N)) |
Draw a massive tree where each node has K branches, going N levels deep. |
Backtracking with Pruning |
Trimmed Recursion Tree |
Assign a bag to a child. If a child's current total exceeds the best minimum maximum found so far, immediately stop exploring that path (prune). |
Draw a tree, but place a large red "X" on branches that get cut off early to visualize the saved computation. |
Asymmetric Pruned Tree |
Draw an unbalanced tree that starts wide at the top but abruptly narrows down on the right side where pruning occurs. |
Draw a deep Call Stack + a size K array representing the kids' current cookie counts. |
Draw the identical Call Stack + size K array, but with a global `best_ans` variable box that dictates the pruning. |
| 2306 |
Naming a Company |
Double loop over the array, swapping first letters of every possible pair and checking if both new words exist in the array. |
N-Squared Grid (O(N^2)) |
Draw an N by N matrix. Each cell represents a pair comparison with two string creations and two array lookups. |
Group by First Letter + Venn Diagram Intersection |
Intersecting Sets (Venn Diagrams) |
Group suffixes into 26 sets by their first letter. Pick two sets (e.g., 'c' and 't'). Find mutual suffixes. Valid names = (Set1_Size - Mutual) * (Set2_Size - Mutual) * 2. |
Draw 26 buckets. Pick two. Draw overlapping circles for their contents. Count the items exclusively in the left circle and exclusively in the right circle, then multiply. |
26x26 Grid Comparison (O(26^2 * N)) |
Draw a constant 26x26 grid. Inside each cell, draw a linear scan representing the $O(N)$ time to find the intersection of two sets. |
Draw one massive Hash Set containing all original strings. |
Draw an Array of 26 Hash Sets, where each set holds string suffixes. |
| 2307 |
Check for Contradictions in Equations |
Assign a random value to the first variable, then recursively substitute values into all other equations to see if a mathematical contradiction occurs. |
Exponential Substitution Tree |
Draw a branching tree where every equation substitution creates a new path of dependent variable resolutions. |
Union-Find with Weights / Directed Graph DFS |
Directed Weighted Graph |
For `A / B = V`, map a directed edge `A -> B` with weight `V`. If `A` and `B` already share a root (or path), traverse the path and multiply weights. If the product != `V`, it's a contradiction. |
Draw nodes (variables) and directed arrows (equations). Write the multiplier on the arrow. Draw a dashed arrow for the new equation to see if it closes the loop cleanly. |
Forest of Trees (O(N * α(N))) |
Draw separate clusters of connected nodes. Each cluster flattens out into a shallow star shape due to path compression. |
Draw a 2D adjacency matrix storing direct equation values. |
Draw two parallel 1D Arrays: `parent[]` and `weight[]`. |
| 2308 |
Arrange Table by Gender |
Scan the input array multiple times, picking out one gender sequentially (e.g., female, then male, then other) and appending to a new array. |
Multi-pass Scanning Lines (O(N^2)) |
Draw a horizontal array. Draw three separate scan lines passing over it from left to right, repeatedly starting over. |
Multi-Queue Interleaving |
Three Funnels into One Stream |
Make 3 Queues (F, M, O). Iterate input once, pushing elements to their respective queue. Then Pop from F, Pop from M, Pop from O repeatedly until empty. |
Draw three vertical tubes representing queues. Draw arrows pulling the bottom item from each tube sequentially into a single horizontal output row. |
Single Pass + Merge (O(N)) |
Draw one timeline splitting into three, which immediately zip back together into a single timeline. |
Draw multiple intermediary arrays being created and destroyed. |
Draw 3 separate Linked Lists (Queues) and 1 output Array. |
| 2309 |
Greatest English Letter in Upper and Lower Case |
Iterate from 'Z' down to 'A'. For each letter, scan the entire string to check if its uppercase exists, then scan again for its lowercase. |
26 Linear Scans (O(26 * N)) |
Draw a timeline. Draw 26 separate loops looping over the timeline one after another. |
Hash Set / Bitmasking |
52-Slot Toggle Switchboard |
Do one pass over the string. Flip the switch (boolean) for the character seen. Then loop from 'Z' to 'A' checking if both the upper and lower switches for that letter are ON. |
Draw a row of 52 checkboxes. Tick them as you read the string. Then look at pairs of (Upper, Lower) checkboxes starting from the end of the alphabet. |
Two Independent Lines (O(N) + $O(26)$) |
Draw one long horizontal line (string length N), followed by a very short fixed line (length 26). |
Draw memory as empty, heavily utilizing the CPU stack for repeated loops. |
Draw a 52-element Boolean Array (or a single 64-bit integer Bitmask with 1s and 0s). |
| 2310 |
Sum of Numbers With Units Digit K |
Backtracking: generate all possible combinations of numbers ending in K, sum them, and check if they equal `num`. |
Exponential Recursion Tree |
Draw a root node branching out for every number ending in K (k, k+10, k+20...). |
Greedy Math / Modulo Arithmetic |
Modulo 10 Wheel |
Since we only care about the last digit, loop `n` from 1 to 10. Check if `(n * k) % 10 == num % 10`. If it matches, verify that `n * k <= num`. If so, `n` is the answer. |
Draw a 1-to-10 table. Write the result of `n * k`. Circle the last digit. Draw a line connecting it to the last digit of `num`. |
Constant Time Block (O(1)) |
Draw a tiny, fixed loop of exactly 10 iterations. It never grows regardless of the input size. |
Draw a deep Call Stack for the recursive backtracking state. |
Draw three small integer variable boxes (`n`, `k`, `num`). |
| 2311 |
Longest Binary Subsequence Less Than or Equal to K |
Generate all possible subsequences (2^N), convert each to decimal, check if <= K, and track the maximum length. |
Exponential Subset Tree (O(2^N)) |
Draw a massive binary tree branching out at every character: left branch means "include char", right branch means "skip char". |
Greedy (Right-to-Left) |
Reverse Accumulator Timeline |
Scan the string backwards. Always pick '0's (they add length but no value). Pick '1's only if adding their decimal value (2^position) keeps the total sum <= K. |
Draw the string as an array. Draw an arrow starting from the far right moving left. Underneath, draw two boxes: `current_val` and `length`. Update them as the arrow moves. |
Single Reverse Line (O(N)) |
Draw a straight, unbranching timeline moving from right to left. |
Draw a deep Call Stack for the recursive state to track combinations. |
Draw three simple integer variables (`val`, `len`, `power_of_two`) that just overwrite themselves. |
| 2312 |
Selling Pieces of Wood |
Recursively try every possible horizontal and vertical cut on the current piece of wood, calculating the max price for all combinations. |
Dense Branching Recursion |
Draw a rectangle. Draw lines showing it splitting into two smaller rectangles in every possible position, then repeat for the smaller ones. |
2D Dynamic Programming |
Bottom-Up Grid Merging |
Initialize a DP grid with base prices. For cell (i, j), the max money is the best of its base price, or splitting it horizontally `dp[k][j] + dp[i-k][j]`, or vertically `dp[i][k] + dp[i][j-k]`. |
Draw a grid. Pick a cell. Draw horizontal and vertical arrows pointing to pairs of previous cells in the same row/column that sum up to the current dimensions. |
3D Nested Loop Block (O(M*N*(M+N))) |
Draw an M x N grid on the floor, and from each cell, draw a vertical bar representing the (M+N) iterations to find the max cut. |
Draw an immense, repetitive Call Stack representing overlapping subproblems. |
Draw a single 2D Matrix (the DP table) getting filled systematically from top-left to bottom-right. |
| 2313 |
Minimum Flips in Binary Tree to Get Result (Premium) |
Generate all combinations of flipping flippable nodes and evaluate the boolean tree from scratch each time. |
Combinatorial Exhaustion |
Draw a tree where every "NOT", "AND", or "OR" node branches out into a parallel universe of "Flipped" and "Not Flipped". |
Tree DP (Bottom-Up State) |
Bubbling Up Pairs [True_Cost, False_Cost] |
Start at leaves. Pass up an array `[cost_to_make_true, cost_to_make_false]`. At each parent, calculate its own costs based on the operation (AND/OR) and children's costs. |
Draw a binary tree. Next to each leaf, draw a small box with two numbers `[T: x, F: y]`. Draw arrows pushing these boxes up to the parent, merging them via math. |
Single Tree Traversal (O(N)) |
Draw the outline of the tree exactly once, tracing a line around the perimeter from bottom to top. |
Draw a Call Stack paired with a massive array tracking flip states. |
Draw the Tree nodes, each containing a tiny size-2 Array `[T, F]`. |
| 2314 |
The First Day of the Maximum Recorded Degree in Each City |
Find max degree per city. Join back to the main table. If there are ties, group again and find the minimum date. |
Multi-Join Tie-Breaker |
Draw the table. Extract maxes. Glue them back. Find dates. Extract min date. Glue back again. |
Window Function (ROW_NUMBER) |
The Ultimate Tie-Breaking Ranker |
Use `ROW_NUMBER() OVER (PARTITION BY city_id ORDER BY degree DESC, day ASC)`. Filter for `row_num = 1`. This handles the max degree AND the earliest date tie-breaker simultaneously. |
Draw buckets for cities. Inside, sort temperatures high-to-low. If tied, sort by date old-to-new. Hand a "#1" trophy to the top row in each bucket. |
Partitioned Sort $O(N \log N)$ |
Draw a single pass that partitions, sorts by two keys, and filters the top rank. |
Temporary tables for tie-breaking joins. |
DB internal sort buffer. $O(N)$ space. |
| 2315 |
Count Asterisks |
Split the entire string by the '|' character into a new array. Iterate over the even-indexed chunks and count the '*' characters. |
Array Allocation & Scanning (O(N)) |
Draw a string being chopped into distinct blocks, copied into a list, and then scanned. |
Single Pass State Toggle |
On/Off Switchboard |
Read char by char. Keep a boolean `inside_bar`. If you see '|', flip the boolean. If you see '*' AND you are `!inside_bar`, increment count. |
Draw a timeline of characters. Draw a line above it: when you hit '|', the line jumps UP (inside). Hit '|' again, it jumps DOWN (outside). Only circle '*' when the line is DOWN. |
Flat Straight Line (O(N)) |
Draw a constant linear arrow left to right. No branching, no extra steps. |
Draw a new Array in memory holding the split substring chunks. |
Draw just two variables: a Boolean (`inside`) and an Integer (`count`). |
| 2316 |
Count Unreachable Pairs of Nodes in an Undirected Graph |
Iterate through all possible pairs of nodes (i, j) and run BFS/DFS for each pair to see if a path exists. |
N-Squared Graph Search (O(N^2 * (V+E))) |
Draw an N x N matrix. Inside every cell, sketch a tiny tree representing a full graph search to connect two nodes. |
Connected Components (DFS/BFS) + Combinatorics |
Grouped Islands Cross-Multiplication |
Find the size of each isolated island of nodes. For an island of `size`, the number of unreachable nodes from it is `Total_Nodes - size`. Add `size * (Total - size)` to total pairs, then divide by 2 to remove duplicates. |
Draw circles representing disconnected islands. Write the number of nodes inside each circle. Draw lines connecting the islands, representing the multiplication of their sizes. |
Linear Component Sum (O(V + E)) |
Draw a few separate clusters of dots. Draw one line scanning through all clusters exactly once. |
Draw an enormous Call Stack for repeated DFS calls + a 2D matrix of pairs. |
Draw an Adjacency List (Array of Lists) + a boolean `visited` Array. |
| 2317 |
Maximum XOR After Operations |
Attempt to simulate the bitwise operation with all possible values of 'x' for every element to find the max combination. |
Infinite State Tree |
Draw an array branching out infinitely, as 'x' can theoretically be any number, creating endless array states. |
Bitwise OR (Math / Bit Manipulation Insight) |
Vertical Bit Stacking Funnel |
Realize the operation `nums[i] AND (nums[i] XOR x)` just allows you to arbitrarily turn any '1' bit into a '0'. To maximize XOR, we just need one '1' in each bit position across the whole array. So, just Bitwise OR all numbers. |
Write all numbers in binary, stacked vertically. Draw a vertical box around each column. If a column has at least one '1', write '1' at the bottom. Otherwise, write '0'. |
Single Line Pass (O(N)) |
Draw a straight, horizontal timeline passing through the array exactly once. |
Draw an exponentially growing list of intermediate Array states. |
Draw a single Integer variable (`res`) acting as a bitmask accumulator. |
| 2318 |
Number of Distinct Roll Sequences |
Backtracking: build every sequence of length N by trying digits 1-6, verifying GCD, adjacent equality, and the 2-gap rule at every step. |
Base-6 Exponential Tree (O(6^N)) |
Draw a root node branching into 6 paths. Each of those branches into 6 paths, going N levels deep (crossing out invalid branches). |
3D Dynamic Programming (State Machine) |
Sliding 6x6 Matrix Grid |
The state only depends on `length`, `last_roll`, and `second_to_last_roll`. For length `i`, look at valid `(prev1, prev2)` pairs from `i-1`, check constraints, and sum paths to the new `(curr, prev1)` state. |
Draw N vertical slices. Inside each slice, draw a 6x6 grid representing `(prev1, prev2)`. Draw arrows carrying the sum of ways from valid cells in slice `i-1` to cells in slice `i`. |
Constant Grid Layers (O(N * 6^3)) |
Draw a straight timeline. At each step, draw a small, fixed-size 3D cube (6x6x6 transitions). |
Draw an extremely deep Call Stack representing the sequence building. |
Draw a 3D Matrix/Array of size `N x 6 x 6` (or just two `6 x 6` matrices swapped for space optimization). |
| 2319 |
Check if Matrix Is X-Matrix |
Iterate through all cells. If a cell is on a diagonal, verify it's not zero. If it's not on a diagonal, verify it is zero. |
2D Grid Scan (O(N^2)) |
Draw an N x N grid. Trace a line going row by row, checking every single square. |
Single Pass Matrix Traversal |
'X' Pattern Masking |
Iterate `i` (rows) and `j` (cols). A cell is on a diagonal if `i == j` (main) or `i + j == N - 1` (anti). Apply the condition based on the coordinates instantly. |
Draw a square grid. Highlight the main and anti-diagonals in yellow to form an 'X'. Put checkmarks inside the 'X' (must be >0) and crosses outside (must be 0). |
Flat Grid Scan (O(N^2)) |
Draw a standard 2D grid filled linearly. The visual complexity matches the brute force because we must read every element once. |
Draw the 2D matrix structure. |
Draw the same 2D matrix structure. Only $O(1)$ auxiliary space (just `i` and `j` variables) is used. |
| 2320 |
Count Number of Ways to Place Houses |
Backtracking: Generate every possible combination of house placements on both sides of the street simultaneously, checking adjacent rules. |
2^(2N) Branching Tree |
Draw a timeline of length 2N, branching into two parallel universes ("House" or "No House") at every single step. |
1D DP (Fibonacci) + Math Independence |
Two Parallel Fibonacci Timelines |
Because the two sides of the street don't interact, solve for one side using DP: `ways[i] = ways[i-1] + ways[i-2]` (Fibonacci). The total answer is `ways[N] * ways[N]`. |
Draw a single 1D array. Fill it out using Fibonacci addition (like jumping 1 step or 2 steps). Take the final number in the array, multiply it by itself, and box the result. |
Single Straight Line (O(N)) |
Draw one timeline of length N. The math multiplication at the end takes zero visual space. |
Draw a massive Call Stack representing the simultaneous street state. |
Draw two simple Integer variables (`prev1`, `prev2`) carrying the Fibonacci state forward (O(1) memory). |
| 2321 |
Maximum Score Of Spliced Array |
Try swapping every possible subarray `(left, right)` between `nums1` and `nums2`, then calculate the sum of both arrays to find the maximum. |
Cubic Loop Blocks (O(N^3)) |
Draw two parallel arrays. Draw a box selecting a segment in array 1, draw a box in array 2, swap them, and then draw a line scanning the whole array to sum it. |
Kadane's Algorithm on Difference Array |
Max Contiguous Delta Peak |
Create a difference array `diff[i] = nums2[i] - nums1[i]`. Run Kadane's to find the max subarray sum of `diff`. Add this to the total sum of `nums1`. Repeat for `nums1 - nums2`. |
Draw three arrays: `nums1`, `nums2`, and `diff`. In `diff`, draw a sliding bracket that expands as long as the running sum is positive, capturing the highest peak of "gain". |
Three Parallel Lines (O(N)) |
Draw three straight, non-overlapping horizontal lines representing the independent linear passes over the arrays. |
Draw overlapping brackets for `L` and `R` repeatedly overwriting a dummy sum variable. |
Draw a single Integer variable (`current_sum`, `max_sum`) updating iteratively without altering the original arrays. |
| 2322 |
Minimum Score After Removals on a Tree |
Iterate through all pairs of edges to remove. For each pair, run a full DFS to find the XOR sum of the three resulting disconnected components. |
N-Cubed Graph Shattering (O(N^3)) |
Draw a tree. Erase two edges. Draw three separate scanlines traversing the newly formed distinct islands, repeating for every pair of edges. |
DFS Subtree Precomputation + Ancestor Check |
3-Piece Subtree Pruning |
Run one DFS to compute the XOR sum of every subtree and record entry/exit times. Then iterate pairs of edges. Use entry/exit times to instantly know if one cut subtree is nested inside the other, allowing $O(1)$ XOR calculation for the 3 parts. |
Draw a tree with a bounding box around every subtree. Write the XOR sum inside the box. Make two cuts. Use the pre-written box values and total XOR to calculate the 3 remaining pieces instantly. |
N-Squared Grid of Pairs (O(N^2)) |
Draw an N x N grid. Inside each cell, draw a tiny $O(1)$ mathematical operation rather than a full graph traversal. |
Draw a massive Call Stack repeating the same graph traversals over and over. |
Draw three 1D Arrays: `xor_sums[]`, `entry_time[]`, and `exit_time[]`. |
| 2323 |
Find Minimum Time to Finish All Jobs II (Premium) |
Generate all permutations of assigning `N` jobs to `N` workers. Calculate the maximum time taken for each permutation and find the minimum of those maximums. |
Factorial Tree (O(N!)) |
Draw a tree where the first node branches N times, the next level branches N-1 times, cascading down to a massive bottom layer. |
Greedy Sorting Alignment |
Zipped Parallel Timelines |
Sort the `jobs` array ascending. Sort the `workers` array ascending. Pair `jobs[i]` with `workers[i]`. The answer is the maximum of `ceil(jobs[i] / workers[i])` across all pairs. |
Draw two arrays side-by-side, both sorted small to large. Draw straight horizontal arrows connecting index `i` to index `i`. Write the division result next to the arrow and circle the largest one. |
Sorting Funnels (O(N log N)) |
Draw two wide funnels narrowing down to sorted lines, followed by one quick zip-line connecting them. |
Draw a massive permutation Call Stack array. |
Draw the two 1D Arrays being mutated (sorted in place), plus one `max_time` Integer variable. |
| 2324 |
Product Sales Analysis IV (SQL Premium) |
(Conceptual) Cross join all users with all products, filter out combinations they didn't buy, aggregate totals, and scan the whole list again to find the max. |
Cartesian Product Explosion |
Draw two small tables multiplying into a giant grid of mostly empty or invalid relationships. |
Window Functions (Dense_Rank / Max over Partition) |
Partitioned Data Buckets |
Group by `user_id` and `product_id` to get total spending. Then use a Window Function to partition by `user_id` and rank the spending descending. Filter for rank 1. |
Draw a table. Draw thick horizontal lines separating different `user_id`s (partitions). Inside each partition, sort the rows by spending and circle the top row(s). |
Partitioned Linear Scan |
Draw a vertical pipeline where data is grouped into distinct horizontal chunks, sorted internally, and truncated. |
Draw an immense temporary memory table holding a Cartesian join. |
Draw a structured Result Set mapping `user_id` directly to a Hash Map of `product_id` totals. |
| 2325 |
Decode the Message |
For every character in the message, scan the `key` string from the beginning to find its first appearance index to determine its alphabetical substitute. |
Nested Scanning Lines (O(M * K)) |
Draw the message string. From each character, draw a long arrow sweeping across the entire key string until it finds a match. |
Hash Map / Array Substitution Cipher |
Dictionary Lookup Frame |
Iterate the `key` once. If a letter hasn't been seen, assign it the next alphabetical character ('a', then 'b', etc.) in a Hash Map. Then iterate `message` and instantly swap using the Map. |
Draw a 2-column translation table. Read the `key` left-to-right, filling out the table. Then look at the `message` and draw lines pointing straight to the table and out to the final decoded string. |
Two Independent Scans (O(M + K)) |
Draw a short line representing the key processing, followed completely separately by a longer line representing the message translation. |
Draw no extra memory, just index pointers darting back and forth. |
Draw a 26-element Array (or a Hash Map) storing character-to-character mappings. |
| 2326 |
Spiral Matrix IV |
Simulate the spiral by hardcoding boundary checks (if top, if right, etc.) repeatedly and popping from the Linked List until empty, filling a pre-sized grid. |
Grid Collision Path (O(M * N)) |
Draw a matrix. Draw an arrow starting top-left, moving right until it hits the edge, then abruptly drawing a new arrow down, repeating until trapped. |
Direction Array + Matrix Simulation |
Concentric Spiraling Inward |
Use a `[row, col]` direction matrix: `[[0,1], [1,0], [0,-1], [-1,0]]`. Walk the Linked List. If the next cell is out of bounds or already filled (!= -1), change direction by rotating the index `(dir + 1) % 4`. |
Draw a matrix filled with -1. Draw a continuous, looping line that curls inward like a snail shell, writing the Linked List values along the line. |
Single Continuous Thread (O(M * N)) |
Draw a single, unbranching line that coils up tightly. Even though it turns, it never overlaps itself. |
Draw the original Linked List being modified/destroyed as nodes are pulled. |
Draw an M x N Matrix pre-filled with -1, and two simple pointers `(r, c)` tracking position. |
| 2327 |
Number of People Aware of a Secret |
Maintain a giant list of every individual person. Each day, loop through the entire list to update their "days known" and append new people if they fall in the sharing window. |
Exponential Population List (O(2^N)) |
Draw a list of stick figures that doubles or triples in size every few steps, becoming too massive to count. |
1D Dynamic Programming / Sliding Window |
Sliding "Active Sharer" Window |
Use a DP array where `dp[i]` is the number of new people who found out on day `i`. The number of new people on day `i` is the sum of `dp[i - forget]` to `dp[i - delay]`. Keep a running window sum to avoid re-looping. |
Draw a timeline of days. Above the timeline, draw a rectangular bracket representing the "sharing window" (from delay to forget). As days pass, slide the bracket right, summing the numbers inside it to generate the next day's value. |
Linear Window Slide (O(N)) |
Draw a timeline. Draw a fixed-width block sliding smoothly from left to right along the timeline. |
Draw a massive, dynamically expanding Array simulating individual people. |
Draw a fixed-size Circular Queue or a 1D DP Array of size N, storing counts instead of individuals. |
| 2328 |
Number of Increasing Paths in a Grid |
Run a standard DFS from every single cell in the grid, exploring all possible strictly increasing paths without saving previous results. |
Explosive Overlapping Trees (O(4^(M*N))) |
Draw a grid. From every single cell, draw branching arrows to neighbors, which branch to their neighbors, creating an unreadable tangled web. |
DFS + Memoization (or Sorting + DP) |
Directed Acyclic Graph (DAG) Flow |
Create a `memo` matrix. Run DFS from a cell. If a neighbor is strictly greater, add its DFS result to the current path count. Save the total in `memo`. If a cell has a `memo` value, return it instantly. |
Draw a grid with numbers. Draw arrows strictly pointing from smaller numbers to adjacent larger numbers. Write the total path count in each cell as you backtrack, preventing you from ever tracing the same arrow twice. |
Flat Matrix Fill (O(M * N)) |
Draw the matrix. Draw a single dot in each cell appearing exactly once as the memo table gets populated. |
Draw an astronomically deep Call Stack that repeatedly visits the same cells. |
Draw a 2D `memo` Matrix storing integers, and a bounded Call Stack (max depth M*N). |
| 2329 |
Product Sales Analysis V (Premium SQL) |
(Conceptual) For every user, run a separate subquery scanning the entire sales table to calculate their total spending, then sort the final results. |
N-Scans over Database |
Draw a table. Draw an arrow scanning the entire table from top to bottom, then repeat this full scan for every unique user. |
GROUP BY + Aggregation (SUM) |
Data Bucketing and Weighing |
Join the Sales and Product tables. Group the results by `user_id`. Select the `user_id` and the `SUM(quantity * price)` as total spending. Order the results descending by total spending. |
Draw a messy pile of receipts. Draw boxes labeled with user names. Sort the receipts into the boxes. Write the total sum on the outside of each box, then line the boxes up from heaviest to lightest. |
Single Aggregation Pipeline |
Draw a wide stream of data funneling into a few distinct buckets, which then drop onto a sorted conveyor belt. |
Draw numerous temporary tables generated by correlated subqueries. |
Draw a Hash Map grouping `user_id` directly to a single `total_spent` integer. |
| 2330 |
Valid Palindrome IV (Premium) |
Generate every possible string by making 1 or 2 character changes, then run a standard $O(N)$ palindrome check on every generated string. |
Branching String Permutations (O(N * 26^2)) |
Draw a word. Draw branches turning one letter into every other letter, then branching again, checking the whole word each time. |
Two Pointers (Inward Convergence) |
Mismatch Counter Allowance |
Place `left` pointer at 0, `right` at end. Move inward. If `s[left] != s[right]`, increment a `mismatch` counter. If `mismatch > 2`, return false. If pointers cross and `mismatch <= 2`, return true. |
Draw a word. Put an arrow at the start and end. Move them inward. If letters don't match, cross them out and draw a strike on a tally counter. Stop early if the tally hits 3. |
Single Half-Pass (O(N)) |
Draw a line. Draw two arrows starting at the ends and meeting in the exact middle, never crossing. |
Draw massive Memory Allocation for creating new string copies to test. |
Draw two Integer pointers (`left`, `right`) and one Integer variable (`mismatches`) using $O(1)$ space. |
| 2331 |
Evaluate Boolean Binary Tree |
Repeatedly scan the tree to find leaf nodes, evaluate them, and replace their parent nodes with the result until only the root remains. |
Repeated Tree Shrinking (O(N^2)) |
Draw a full tree. Erase two leaves and their parent, replacing them with a single T/F node. Redraw the entire rest of the tree. Repeat until one node is left. |
Post-Order Traversal (DFS) |
Bottom-Up Truth Bubbling |
Go down to the leaves. Return their boolean values up. At an OR node, return `left || right`. At an AND node, return `left && right`. Stop early if short-circuiting applies. |
Draw a tree. Write T or F at the leaves. Draw arrows pointing UP from the leaves to their parent. Cross out the parent's operator (AND/OR) and write the resulting T/F, continuing up to the root. |
Single Perimeter Trace (O(N)) |
Draw a single continuous line that traces the outline of the tree, starting at the root, dipping into every leaf, and ending back at the root. |
Draw a heavily modified tree structure taking up memory with each pass. |
Draw a Call Stack sized to the height of the tree (O(H)), with simple Boolean variables resolving at each frame. |
| 2332 |
The Latest Time to Catch a Bus |
Simulate every single possible minute from 1 up to the last bus departure, running a boarding simulation for every minute to see if you successfully get on. |
Massive Timeline Iteration (O(Max_Time * N)) |
Draw a massive number line starting at 0 and ending at millions. Tick every single number to check if it's a valid arrival time. |
Sorting + Two Pointers + Backtracking |
Zipped Boarding & Step-Back |
Sort buses and passengers. Use pointers to load passengers onto buses up to capacity. Find the arrival time of the last boarded passenger (or the bus departure time if not full). Step backward by 1 minute until you find a time no other passenger arrived. |
Draw a timeline. Draw square boxes (buses) at specific times. Draw dots (passengers) at their times. Draw arrows putting dots into boxes until full. Find the last dot/box, and draw an arrow stepping leftwards finding the first empty space. |
Sorting Funnel + Two Scans (O(N log N + M log M)) |
Draw two wide funnels (sorting), then a straight timeline where two arrows advance together, stopping at the end to make one small jump backwards. |
Draw a large redundant Array keeping track of every simulated minute. |
Draw two sorted 1D Arrays in place, plus a few Integer pointers (`bus_idx`, `pass_idx`, `capacity_left`). |
| 2333 |
Minimum Sum of Squared Difference |
Calculate the absolute difference for each pair. For `k1 + k2` times, find the absolute maximum difference in the array, decrement it by 1, and recalculate the squared sum. |
Repeated Max Finding (O((K1+K2) * N)) |
Draw a bar chart of differences. Scan the whole chart to find the tallest bar, erase a tiny slice off the top, and then scan the whole chart all over again. |
Bucket Sort / Frequency Map + Greedy Flattening |
Bulldozing the Highest Peaks |
Total operations `k = k1 + k2`. Create an array of frequencies for each difference. Iterate from the highest difference down to 0. Greedily use `k` to turn the current max difference into the next smaller difference, shifting the frequencies down. |
Draw a histogram representing difference frequencies. Draw a bulldozer pushing the tallest columns to the left (into shorter difference buckets) until it runs out of gas (`k` operations). |
Linear Histogram Pass (O(N + Max_Diff)) |
Draw a histogram and a single horizontal line sweeping from right (max diff) to left (0), pushing counts over as it goes. |
Draw the original array constantly modifying and re-sorting itself. |
Draw a fixed-size 1D Array `freq` up to size 10^5 (max difference), acting as the histogram buckets. |
| 2334 |
Subarray With Elements Greater Than Varying Threshold |
Generate all possible subarrays `(O(N^2))`, find the minimum element in each subarray `(O(N))`, and check if that minimum > `threshold / length`. |
Cubic Bracket Combinations (O(N^3)) |
Draw a line. Draw brackets for every possible segment length. Inside each bracket, scan across all numbers to find the smallest one. |
Monotonic Stack (Next Smaller Element) |
Maximal Expanding Rectangles |
For each number, assume it is the absolute minimum of a subarray. Use a monotonic stack to find the nearest smaller element to its left and right. The distance between them gives the max length `L` where this number is the minimum. Check `num > threshold / L`. |
Draw a bar chart. Pick a bar. Draw horizontal arrows extending left and right from its top until they hit a shorter bar. The width between the shorter bars is `L`. Evaluate the math formula. |
Two Linear Stack Passes (O(N)) |
Draw an array. Draw a stack pointer that only moves forward, occasionally throwing old items away, passing over the array exactly twice (left-to-right, right-to-left). |
Draw a massive 2D matrix storing the minimums of all possible subarrays. |
Draw two 1D Arrays (`left_smaller`, `right_smaller`) and a Stack data structure holding indices. |
| 2335 |
Minimum Amount of Time to Fill Cups |
Recursively try every combination of filling two cups or one cup at a time, branching out to find the path with the minimum depth to reach `[0,0,0]`. |
Exponential Pouring Tree (O(3^Sum)) |
Draw an array of 3 numbers. Draw branches for decrementing (0,1), (1,2), (0,2), or just one alone. Repeat until all reach zero. |
Greedy Math / Max Priority Queue |
Leveling the Two Tallest Towers |
Sort the 3 numbers. Always decrement the two largest numbers. If the sum of the two smaller ones is less than the largest, the answer is just the largest. Otherwise, math trick: `ceil((a+b+c)/2)`. |
Draw 3 stacks of coins. Take one coin from the tallest stack and one from the second tallest. Repeat. If one stack is empty, just take from the tallest remaining. |
$O(1)$ Math Block (or $O(\text{Sum})$ PQ loop) |
Draw 3 numbers instantly transforming into the final answer via one math equation. |
Draw a deep Call Stack holding arrays of size 3 in various stages of depletion. |
Draw a Priority Queue (size 3) or literally just zero extra memory using the $O(1)$ math formula. |
| 2336 |
Smallest Number in Infinite Set |
Maintain a full list of all numbers from 1 to 1000. When a number is "popped," scan the entire list to find the next minimum. |
Linear Min Search (O(N^2)) |
Draw a long row of numbered boxes. Cross one out. Start at box 1 and point at every box until you find one that isn't crossed out. |
Min-Heap + Hash Set (or Min_Tracker) |
Priority Queue Overflow Catch |
Use a variable `smallest` starting at 1. If a number is "added back" and it's less than `smallest`, put it in a Min-Heap (and a Set to avoid duplicates). `popSmallest` checks the Heap first; if empty, it returns `smallest++`. |
Draw a number line with a pointer at `smallest`. Draw a small "bucket" (Heap) to the side. If someone throws a number back, it goes in the bucket. Always check the bucket for the smallest item before moving the main pointer. |
Logarithmic Extraction (O(log N)) |
Draw a vertical Heap tree. An item is pulled from the top, and the tree reshuffles itself in a few quick steps. |
Draw a massive Boolean array of 1000 elements. |
Draw a small Tree (Heap) and a Hash Set, plus one Integer variable (`smallest`). |
| 2337 |
Move Pieces to Obtain a String |
Use BFS to generate every possible string configuration by moving 'L' and 'R' into adjacent '_' spaces until you reach the target. |
State Space Explosion (O(3^N)) |
Draw a string. Draw branches for every possible single move of an 'L' or 'R'. Each branch creates a new string that branches again. |
Two Pointers (Relative Order & Constraints) |
Zipped Character Alignment |
Ignore '_' and check if 'L' and 'R' appear in the same relative order in both strings. Then, ensure each 'L' in `start` is at an index >= its index in `target`, and each 'R' is at an index <= its index in `target`. |
Draw two strings. Draw lines connecting the 1st 'L' in start to the 1st 'L' in target, 2nd to 2nd, etc. Check if the lines slant in the correct direction (L can only move left, R only right). |
Single Linear Pass (O(N)) |
Draw two parallel timelines. Two arrows move forward together, stopping only when they hit a letter to compare positions. |
Draw a massive Queue holding thousands of string copies. |
Draw two Integer pointers (`i`, `j`) moving across the original strings. |
| 2338 |
Count the Number of Ideal Arrays |
Backtracking: Build every possible array of length `n` where each element is a multiple of the previous one, and count them. |
Recursive Multiplier Tree |
Draw a root node. Branch to every multiple (e.g., if 2, branch to 2, 4, 6...). Go `n` levels deep. |
Math (Combinatorics + Stars and Bars) |
Prime Factorization Buckets |
The values in an ideal array change at most 14 times (since 2^14 > 10,000). Use DP to find how many sequences of length `k` (where each element strictly increases and divides the next) exist. Use "Stars and Bars" to distribute the remaining `n-k` spots. |
Draw a sequence of distinct multipliers (e.g., 1 -> 2 -> 4). Draw "Stars and Bars" dividers to show how many times each number is repeated to fill the total length `n`. |
DP + Combinatorial Product (O(MaxV * log MaxV)) |
Draw a small DP table (MaxV x 14) and a quick factorial calculation for the combinations. |
Draw a deep recursion stack storing partial arrays. |
Draw a 2D DP Table (10000 x 14) and a precomputed Factorial array. |
| 2339 |
All the Matches of the League |
Write manual pairs or complex subqueries mapping IDs iteratively. |
Manual Mapping Matrix |
Draw Team A connecting to B, C, D manually, then B to A, C, D manually. |
CROSS JOIN / SELF JOIN |
The Cartesian Scheduler |
Use `SELECT t1.team_name, t2.team_name FROM Teams t1 JOIN Teams t2 ON t1.team_name != t2.team_name`. |
Draw the list of teams vertically and horizontally. Draw a grid. Check every box where the row name and column name are different. |
Cartesian Product $O(N^2)$ |
Draw two lists multiplying into a square grid of size N \times N. |
N/A |
DB result buffer. $O(N^2)$ space. |
| 2340 |
Minimum Adjacent Swaps to Make a Valid Array (Premium) |
Try every possible sequence of adjacent swaps until the smallest element is at index 0 and the largest is at index n-1, tracking the minimum steps. |
Factorial Permutation Search (O(N!)) |
Draw an array. Draw a web of branches where every branch represents one swap, leading to a new array state. |
Greedy (Extreme Finding) |
Two-Way Slide to Edges |
Find the index of the first occurrence of the minimum element and the last occurrence of the maximum element. The swaps needed = `min_idx + (n - 1 - max_idx)`. Subtract 1 if the min is to the right of the max (they cross). |
Draw an array. Circle the min and the max. Draw an arrow from min to the front and max to the back. Count the "steps" (indices) the arrows pass over. |
Single Pass Scan (O(N)) |
Draw one horizontal timeline. Mark two points (min and max) and draw two straight lines to the boundaries. |
Draw a BFS queue holding all array permutations. |
Draw two Integer variables (`min_idx`, `max_idx`) and two more for the values. |
| 2341 |
Maximum Number of Pairs in Array |
Repeatedly scan the array to find any two identical numbers, remove them, increment a counter, and repeat until no pairs remain. |
Repeated Linear Scans (O(N^2)) |
Draw an array. Circle two '3's, erase them. Redraw the array. Circle two '1's, erase them. Repeat until only a few scattered numbers remain. |
Frequency Map (Hash Table) |
Modulo 2 Bucket Tally |
Count the frequency of each number using a Hash Map. For each count, `pairs += count / 2` and `leftover += count % 2`. |
Draw a table with two columns: "Number" and "Count". Read the array once to fill the table. Then, for each count, draw a circle around groups of two and a square around the remainder. |
Single Pass Scan (O(N)) |
Draw a straight, horizontal timeline. One pass to build the map, one very short pass (max 100 entries) to sum the results. |
Draw multiple copies of the array as it shrinks in size. |
Draw a 101-element Integer Array (or Hash Map) and two Integer result variables. |
| 2342 |
Max Sum of a Pair With Equal Sum of Digits |
Nested loops: Compare every pair `(i, j)`. Calculate the digit sum for both. If equal, update the global maximum sum. |
N-Squared Comparison (O(N^2)) |
Draw an N x N grid. In each cell, draw a small calculator icon representing the digit sum logic and an addition operation. |
Hash Map of Max Values |
Digit Sum Bucketing |
Iterate once. Calculate `digitSum`. Check a Hash Map: `map[digitSum]`. If it exists, update `maxTotalSum` using `map[digitSum] + currentNum`. Always update `map[digitSum]` with the larger of the two. |
Draw a series of numbered buckets (0-81). As you read a number, calculate its digit sum and try to put it in the corresponding bucket. If the bucket already has a number, "duel" them: add them for a potential score, but only keep the bigger one in the bucket for the next round. |
Linear Scan with Constant Map (O(N)) |
Draw a timeline. Below it, draw a fixed-size row of 82 boxes. Each step in the timeline only interacts with one box. |
Draw a 2D matrix storing every possible pair's metadata. |
Draw a Hash Map (or Array of size 82) storing only the largest Integer seen for each digit sum. |
| 2343 |
Query Kth Smallest Trimmed Number |
For every query, manually trim every string in the array, sort the newly created trimmed strings, and pick the Kth one. |
Repeated Full Sorting (O(Q * N * L log N)) |
Draw a query list. For each query, draw a copy of the entire string array being sliced and then rearranged by a sorting algorithm. |
Radix Sort Logic / Precomputed Sorted States |
Incremental Character Sorting |
Since trimming always starts from the right, the order of `trim=1` helps determine the order of `trim=2`. Use a stable sort (like Radix Sort) or sort based on suffixes. |
Draw strings as vertical columns. Start at the rightmost column. Sort based on that digit. Move one column left. Sort again, keeping the relative order of the previous step. |
Linear Suffix Scan (O(L * N + Q)) |
Draw a grid of N x L. Draw a vertical line moving from right to left, with the rows shifting positions slightly at each step. |
Draw thousands of temporary "trimmed" string objects being created and garbage collected. |
Draw an Array of Indices `[0, 1, 2...]` being reordered, avoiding string copies. |
| 2344 |
Minimum Deletions to Make Array Divisible |
Sort `nums`. For each number in `nums`, check if it divides every single element in `numsDivide`. If not, delete it and move to the next. |
Nested Divisibility Checks (O(N * M)) |
Draw two arrays. Point to the first element of Array A. Draw arrows from it to every element of Array B. If any arrow "breaks" (doesn't divide), move to the next in A. |
GCD + Sorting |
Greatest Common Target |
Find the GCD of all numbers in `numsDivide`. Sort `nums`. The first number in the sorted `nums` that divides the `GCD` is your winner. All numbers before it must be deleted. |
Draw a "Master Key" (the GCD). Line up your "Potential Keys" (sorted `nums`) in a row. Test each key against the Master Key. The first one that fits determines how many keys you discard. |
Logarithmic GCD + Sorting (O(M log M + N log N)) |
Draw a funnel for `numsDivide` that outputs one single number (GCD). Draw a sorted line for `nums` that hits that GCD. |
Draw a massive checklist for every element in `numsDivide` for every `num`. |
Draw one Integer (`targetGCD`) and a sorted version of the `nums` Array. |
| 2345 |
Finding the Number of Visible Mountains (Premium) |
For every mountain, check if its triangle is completely contained within any other mountain's triangle by comparing slopes and peaks. |
N-Squared Triangle Overlap (O(N^2)) |
Draw N triangles on a coordinate plane. For each triangle, draw a "shadow" from every other triangle to see if it's swallowed up. |
Interval Sorting + Monotonic Scan |
1D Shadow Coverage |
Convert each mountain `[x, y]` into an interval `[x-y, x+y]`. Sort intervals by start point ascending (and end point descending). Iterate: if a mountain's end point is covered by the current maximum end point, it's hidden. |
Draw a horizontal line. Represent each mountain as a bracket `[start, end]`. Sort the brackets. If a new bracket's end is inside the current longest bracket's end, it's "invisible." Count the unique, non-covered ones. |
Sorting + Linear Scan (O(N log N)) |
Draw a wide sorting funnel. Below it, draw a single horizontal line with an arrow moving left-to-right, occasionally marking a "max_reach" point. |
Draw a 2D matrix of coordinate comparisons. |
Draw a 1D Array of intervals (Pairs) and one Integer variable (`max_right`). |
| 2346 |
Compute the Rank as a Percentage (SQL Premium) |
(Conceptual) For every student in a department, run a subquery to count how many students have a higher mark, then divide by the total count of students in that department minus one. |
Nested Departmental Scans |
Draw a table of students. For each student, draw an arrow that scans only the rows belonging to the same department to find their rank. |
Window Functions (RANK() / PERCENT_RANK()) |
Partitioned Score Tiers |
Use `PERCENT_RANK() OVER (PARTITION BY dept_id ORDER BY mark DESC)`. This calculates `(rank - 1) / (total_rows - 1)` automatically for each row within its group. |
Draw a table with students grouped by department. Inside each group, sort by marks. Write a "1, 2, 3" rank next to each, then convert that rank to a decimal (0.0 to 1.0) based on group size. |
Single Pass Window Sort |
Draw a vertical stream of data being split into parallel departmental pipes, sorted, and tagged with a percentage. |
Draw multiple temporary tables for each department calculation. |
Draw one Result Set stream with an added "Percentage" column. |
| 2347 |
Best Poker Hand |
Generate every possible combination of 5 cards to see if any subset forms a flush, three-of-a-kind, or a pair. |
Sub-Hand Combinations (O(2^5)) |
Draw 5 cards. Draw arrows showing every way to pick 2, 3, 4, or 5 cards to check for matching patterns. |
Frequency Counting (Hash Map/Array) |
Bucket Category Priority |
Check if all suits are the same (Flush). If not, count rank frequencies. If any rank count >= 3 (Three-of-a-Kind), if >= 2 (Pair), else (High Card). |
Draw 4 "Suit" boxes and 13 "Rank" boxes. Toss the 5 cards into them. If one Suit box has all 5, call "Flush". Otherwise, check the Rank box with the most cards. |
Fixed Constant Pass (O(1)) |
Draw a tiny, 5-step timeline that ends at a simple "If-Else" decision tree. |
Draw a list of all possible poker hand permutations. |
Draw a 4-element Suit Array and a 13-element Rank Array. |
| 2348 |
Number of Zero-Filled Subarrays |
Generate every possible subarray `(i, j)`. For each, check if every single element in it is zero. Count the ones that are. |
Cubic Scanning (O(N^3)) |
Draw an array. Draw brackets for every segment. For each segment, draw a tiny internal arrow scanning it to confirm all are '0'. |
Linear Strike Counting (Math) |
Consecutive Zero Streaks |
Iterate once. Keep a `current_streak` counter. If you see a '0', increment `streak` and add `streak` to the `total`. If you see a non-zero, reset `streak` to 0. |
Draw an array. Every time you hit a '0', draw a vertical tally mark that grows longer (1, 2, 3). Add the height of the current tally to your total sum. When you hit a '1', erase the tally. |
Single Linear Pass (O(N)) |
Draw a straight horizontal timeline. A single "streak" variable pulses up and down like a heart monitor as it moves. |
Draw a massive 2D matrix storing boolean "isZero" flags for every subarray. |
Draw two Integer variables: `streak` and `total_count`. |
| 2349 |
Design a Number Container System |
Store numbers in a simple Array. For `find(number)`, scan the entire array from index 0 to find the first occurrence of that number. |
Linear Search per Query (O(Q * N)) |
Draw a massive array. For every query, draw an arrow starting at index 0 and moving right until it finds a specific value. |
Two Hash Maps + Min-Heap (Sorted Set) |
Bidirectional Indexed Lookup |
Map 1: `index -> number`. Map 2: `number -> Min-Heap of indices`. When updating an index, update Map 1 and push the new index to Map 2's heap. `find` just returns the top of the heap. |
Draw a dictionary for "What's at this index?" and a row of "Sorted Folders" for each number. When a number is assigned to an index, drop a sticky note with that index into the number's folder. The smallest index is always at the front. |
Logarithmic Update/Query (O(log N)) |
Draw a Hash Map pointing to a small Tree (Heap). The search only travels down the height of the tree. |
Draw an immense amount of duplicate index pointers in memory. |
Draw two Hash Maps: one mapping Integers to Integers, and one mapping Integers to Min-Heaps (or Sorted Sets). |
| 2350 |
Shortest Impossible Sequence of Rolls |
Generate all possible sequences of length 1, then length 2, and so on. For each sequence, scan the `rolls` array to see if it can be formed as a subsequence. |
Exponential Sequence Search (O(K^N)) |
Draw a tree of all possible roll sequences (1,1; 1,2...). For each leaf, draw a full scan across the input `rolls` array. |
Greedy Set Partitioning |
Complete Set Collection Rounds |
Try to find a "complete set" (all numbers 1 to K). Once you find all K numbers, start a new "round." The number of complete rounds + 1 is the length of the shortest impossible sequence. |
Draw the array of rolls. Draw a vertical line (a "fence") every time you have seen all numbers from 1 to K. Count the number of fences you built and add 1. |
Single Pass Set Filling (O(N)) |
Draw a horizontal line. Draw dots of different colors. When you have all colors, draw a thick divider and start again. |
Draw a huge recursion stack for every possible roll combination. |
Draw one Hash Set (or Boolean Array of size K) and one Integer counter (`rounds`). |
| 2351 |
First Letter to Appear Twice |
Double loop: For each character, scan the rest of the string to see if it appears again. Keep track of the one with the smallest "second appearance" index. |
N-Squared Lookahead (O(N^2)) |
Draw a string. Pick the first letter, draw arrows to all subsequent letters. Pick the second letter, repeat. Mark the first "hit" you find. |
Hash Set / Boolean Array (Bitmask) |
Single Pass Existence Check |
Iterate through the string once. For each character, check if it's already in the Hash Set. If yes, return it immediately. If no, add it to the Set. |
Draw a string and an empty "seen" bucket. As you move along the string, drop each letter into the bucket. The moment you try to drop a letter that’s already in the bucket, circle it—that's your answer. |
Single Pass Scan (O(N)) |
Draw a straight horizontal timeline. A single pointer moves forward and stops at the first duplicate. |
Draw the string being copied and scanned multiple times in memory. |
Draw a 26-element Boolean Array or a single 32-bit Integer (Bitmask) to track seen characters. |
| 2352 |
Equal Row and Column Pairs |
Nested loops: For every row, iterate through every column and compare every single element (row[i] == col[i]) to check for equality. |
Cubic Matrix Comparison (O(N^3)) |
Draw a grid. Draw a horizontal box (row) and a vertical box (column). Draw tiny arrows comparing every cell inside the intersection and the rest of the boxes. |
Hash Map (Stringified Rows) |
Frequency Key Matching |
Convert each row into a string/tuple and store its frequency in a Hash Map. Then, iterate through each column, convert it to a string/tuple, and add the frequency from the Map to your total. |
Draw a grid. Next to it, draw a "Row Dictionary." For each row, write its pattern and how many times it appeared. Then, look at each column and check the dictionary. If the column pattern is in the dictionary, add the count to your score. |
Linear Matrix Scan (O(N^2)) |
Draw two separate passes: one vertical (to build the map) and one horizontal (to check columns). No nested element-by-element re-scans. |
Draw thousands of temporary coordinate variables for the triple nested loop. |
Draw a Hash Map where keys are Row Tuples and values are Integers (counts). |
| 2353 |
Design a Food Rating System |
Store food in a List. For `changeRating`, find the food in the list and update it. For `highestRated`, scan the entire list to find the food with the max rating for that cuisine. |
Linear Search per Query (O(Q * N)) |
Draw a long list of food items. For every "Highest" request, draw an arrow scanning every single item from top to bottom. |
Two Hash Maps + Priority Queues (Sorted Sets) |
Cuisine-Scoped Max Heaps |
Map 1: `food -> [cuisine, rating]`. Map 2: `cuisine -> Max-Heap of [rating, food_name]`. To handle updates, push the new rating to the heap. When querying, "lazy delete" by popping the top of the heap until the rating matches Map 1. |
Draw a master directory (Map). Draw "Kitchen Cabinets" for each cuisine. Inside each cabinet, keep a "Leaderboard" (Heap). When a rating changes, put a new sticky note on the board. When asking for the best, look at the top; if the note is old, throw it away and look at the next one. |
Logarithmic Update/Query (O(log N)) |
Draw a Hash Map pointing to a Balanced BST or Heap. The search path is a short zigzag down the tree. |
Draw a massive redundant list of food objects in a flat array. |
Draw a Hash Map for metadata and a Map of Max-Heaps/Trees for each cuisine category. |
| 2354 |
Number of Excellent Pairs |
Nested loops: For every pair `(num1, num2)`, calculate `bits(num1 OR num2) + bits(num1 AND num2)` and check if it’s >= `k`. |
N-Squared Bitwise Logic (O(N^2)) |
Draw an N x N grid. In each cell, draw the binary representation of two numbers, perform OR/AND, and count the 1s. |
Bit Count Frequency + Inclusion-Exclusion |
1D Bit-Count Histogram |
Key insight: `bits(a OR b) + bits(a AND b) == bits(a) + bits(b)`. Get unique numbers, count their set bits, and store frequencies of these counts (0-30). Use a nested loop over the 30 possible bit-counts (30x30) to find valid pairs. |
Draw a "Bit-Count Bin" (0 to 30). Count how many unique numbers have 1 bit, 2 bits, etc. Then, pick two bins (e.g., bin 10 and bin 20). If 10+20 >= k, multiply the number of items in both bins and add to your total. |
Unique Pass + Constant Grid (O(N + 30^2)) |
Draw a single line scanning the array, followed by a tiny fixed 30x30 grid calculation. |
Draw a 2D matrix storing bitwise results for every pair. |
Draw a Hash Set for unique numbers and a 31-element Frequency Array. |
| 2355 |
Maximum Number of Books You Can Take (Premium) |
For every index `i`, try all possible ways to take books from `i, i-1, ... 0` such that the number of books strictly decreases, and track the maximum sum. |
Exponential Backtracking (O(2^N)) |
Draw a row of shelves. From each shelf, draw branches representing different choices of how many books to take from the previous shelf. |
Monotonic Stack + Dynamic Programming |
Sliding Trapezoid Sums |
Define `dp[i]` as the max books ending at shelf `i`. Use a monotonic stack to find the first shelf `j` to the left where `books[j] < books[i] - (i - j)`. The books between `j` and `i` form an arithmetic progression (trapezoid). `dp[i] = trapezoid_sum + dp[j]`. |
Draw a bar chart. Pick a bar. Draw a diagonal "limit line" slanting down to the left. The books you take are the area under the bars but below the limit line. The stack helps you find where your "limit line" hits a bar that is already shorter than the line. |
Linear Stack Pass (O(N)) |
Draw an array. Draw a stack that only grows when a bar is "tall enough" and shrinks when a bar is "too short," passing over the data once. |
Draw a massive recursion tree for every shelf. |
Draw a 1D `dp` Array and a Monotonic Stack storing indices. |
| 2356 |
Number of Unique Subjects Taught by Each Teacher (SQL Premium) |
(Conceptual) For every teacher, scan the entire teaching table to find all subjects, put them in a set to find unique ones, and count them. |
Teacher-by-Teacher Scanning |
Draw a table of teachers and subjects. For each unique teacher ID, draw a circle around all their subjects, then cross out the duplicates within that circle. |
GROUP BY + COUNT(DISTINCT) |
Relational Data Bucketing |
Group the table by `teacher_id`. For each group, use the `COUNT(DISTINCT subject_id)` function to find the number of unique subjects. |
Draw a table. Draw horizontal lines grouping rows by `teacher_id`. In each group, count the unique subject names and write the total in a new "count" column. |
Single Pass Aggregation |
Draw a stream of data entering a hash map where keys are teacher IDs and values are sets of subjects. |
Draw multiple temporary result sets for each teacher-to-subject scan. |
Draw one Result Set stream with `teacher_id` and `cnt` columns. |
| 2357 |
Make Array Zero by Subtracting Equal Amounts |
Find the smallest non-zero element, subtract it from all non-zero elements, and repeat this process until all elements are zero. Count the number of steps. |
Repeated Linear Subtraction (O(N^2)) |
Draw an array. Find the smallest number, subtract it from everyone. Redraw the array. Repeat until the array is all zeros. |
Unique Positive Integers (Hash Set) |
Distinct Value Counting |
The number of operations is exactly equal to the number of distinct positive integers in the array. Each operation removes one unique value level. |
Draw an array. Count how many different numbers (greater than 0) are in it. Each unique number represents one "floor" in a building; you are counting the number of floors. |
Single Pass Set Fill (O(N)) |
Draw a straight horizontal timeline. Each unique number encountered adds one tick to a counter. |
Draw multiple copies of the array as it is modified in each step. |
Draw a Hash Set or a 101-element Boolean Array to track seen numbers. |
| 2358 |
Maximum Number of Groups Entering a Competition |
Try all possible ways to group students into groups with increasing sizes and increasing sums of grades using a backtracking or greedy approach. |
Exponential Grouping Tree |
Draw a list of students. Branch out by picking 1 student, then 2 students, then 3, checking if the sum of grades also increases at each step. |
Greedy Math (Arithmetic Progression) |
Quadratic Growth Approximation |
Since we can sort students by grade, the sum condition will always be met if we just pick groups of sizes 1, 2, 3... until we run out of students. Solve x(x+1)/2 \le n for x. |
Draw n dots. Circle 1 dot, then circle the next 2 dots, then the next 3. Count how many full circles you can draw before you run out of dots. |
Constant Time Math (O(1)) |
Draw a single mathematical formula or a very short loop that increments a counter until it exceeds n. |
Draw a deep recursion stack for every possible student grouping. |
Draw zero extra memory (just one or two Integer variables for the math). |
| 2359 |
Find Closest Node to Given Two Nodes |
From node 1, explore all paths to find all reachable nodes. Repeat for node 2. For every node, calculate the maximum of the two distances and pick the minimum. |
BFS/DFS from Every Node (O(N^2)) |
Draw a graph. Color all nodes reachable from node 1. Color all nodes reachable from node 2. For the overlapping nodes, compare their "distance" labels. |
Two Independent BFS/DFS Passes |
Parallel Distance Maps |
Run one BFS starting from `node1` to fill a `dist1` array. Run another BFS from `node2` to fill a `dist2` array. Iterate through all nodes i and find the one that minimizes \max(\text{dist1}[i], \text{dist2}[i]). |
Draw a graph. Trace a path from node 1 and write the step count on each node. Trace a path from node 2 and do the same. Compare the two numbers on each node and pick the best one. |
Two Linear Graph Traversals (O(V+E)) |
Draw two separate, non-nested timelines (one for each BFS). No re-scanning of the graph for every node. |
Draw a massive 2D matrix storing distances between all pairs of nodes. |
Draw two 1D Arrays (`dist1`, `dist2`) of size N. |
| 2360 |
Longest Cycle in a Graph |
For every node, start a DFS to see if it eventually leads back to itself. Keep track of the path length and the maximum cycle found. |
Exhaustive Path Searching (O(N^2)) |
Draw a graph. From every node, draw a long arrow following the edges until it hits a dead end or circles back. Repeat for every single node. |
DFS with Timestamping (Kahn’s or Visited Array) |
Cycle Entry-Point Tracking |
Run DFS and mark each node with a "time" it was visited. If you hit a node already visited *in the current path*, the cycle length is `currentTime - startTime`. Use a global `visited` array to avoid re-processing nodes. |
Draw a graph. Move along the edges, writing "1, 2, 3..." on the nodes. If you land on a node that already has a number from your *current* trip, subtract the numbers to find the cycle length. |
Single Graph Pass (O(V+E)) |
Draw a line that visits every node exactly once. When it hits a "tail," it stops; when it hits itself, it records a cycle. |
Draw an immense number of redundant path arrays for every node's DFS. |
Draw one `visited` Boolean Array and one `time_visited` Integer Array. |
| 2361 |
Minimum Costs Using the Train Line (Premium) |
Exhaustively calculate every possible sequence of "Regular" and "Express" stops for all stations to find the minimum cost to reach each one. |
Exponential Path Tree (O(2^N)) |
Draw a station line. At every station, branch into two paths: "Stay Regular" or "Switch to Express". Repeat N times. |
1D Dynamic Programming (Two States) |
State-Toggle Track Switch |
Maintain two DP values: `reg[i]` (min cost at station i on regular track) and `exp[i]` (min cost at station i on express track). Transition: `reg[i] = min(reg[i-1] + cost, exp[i-1] + cost)`, etc. |
Draw two parallel lines (tracks). At each station, draw arrows going straight and arrows crossing over to the other track. Write the "cheapest price so far" on each dot. |
Single Pass DP (O(N)) |
Draw two parallel timelines moving forward together. No branching back or re-calculating previous stations. |
Draw a massive recursion tree with N levels of depth. |
Draw two 1D Arrays (or just four variables: `prevReg`, `prevExp`, `currReg`, `currExp`). |
| 2362 |
Generate the Invoice (SQL Premium) |
(Conceptual) For every invoice, join all products, calculate total price per invoice, find the max price, and then re-fetch all items for that specific invoice. |
Multiple Full Table Joins |
Draw the `Invoices` table. For every single ID, draw an arrow to the `Products` table to find prices, sum them up, and then scan again for the winner. |
CTE + Window Functions (RANK) |
Aggregated Winner Filter |
Use a Common Table Expression (CTE) to sum `price * quantity` grouped by `invoice_id`. Rank them by total price DESC (and ID ASC). Join the top-ranked ID back to the original table. |
Draw a table. Group by ID. Write the "Total " next to each group. Circle the biggest total. Then, draw a box around only the rows belonging to that circled ID. |
Single Aggregation + Join |
Draw a data stream into a "Summing Bucket," then through a "Ranking Filter," then back to the "Source" for details. |
Draw several large temporary tables for every sub-sum. |
Draw one Intermediate Result Set with `invoice_id` and its calculated `total_price`. |
| 2363 |
Merge Similar Items |
Iterate through the first list. For each item, scan the entire second list to see if the ID matches, add the weights, and then sort the final combined list. |
Nested Comparison + Sort (O(N*M)) |
Draw two lists. Pick an item from List A. Draw an arrow scanning every item in List B looking for a matching ID. Repeat for all of List A. |
Treemap (Sorted Dictionary) |
Ordered Bucket Collection |
Use a Map that automatically keeps keys sorted (like `TreeMap` in Java or a sorted array in Python). Iterate both lists once, adding weights to the corresponding ID key. |
Draw a row of numbered boxes (IDs). As you read List A and List B, toss the weights into the matching boxes. Since the boxes are already in order, just read them left to right at the end. |
Two Linear Scans + Map Sort (O(N+M + K log K)) |
Draw two timelines merging into a single sorted dictionary structure. |
Draw numerous intermediate list copies during the re-scans. |
Draw one Sorted Map (Red-Black Tree structure) or a fixed-size 1001-element Frequency Array. |
| 2364 |
Count Number of Bad Pairs |
Nested loops: Check every pair `(i, j)`. If `j - i != nums[j] - nums[i]`, increment the "bad pair" counter. |
N-Squared Pair Validation (O(N^2)) |
Draw an N x N grid. In every cell, perform the subtraction logic for both indices and values and compare them. |
Complement Counting (Total - Good) |
Key Normalization (nums[i] - i) |
Equation rewrite: `nums[j] - nums[i] == j - i` is same as `nums[j] - j == nums[i] - i`. Total pairs is n(n-1)/2. Count occurrences of `nums[i] - i` in a Hash Map to find "good" pairs, then subtract from total. |
Draw a list. For each number, calculate `val - index`. Draw a "Frequency Table" for these results. If you see a result you've seen before, those are "Good Pairs." Subtract those from the total possible pairs. |
Single Pass Map Build (O(N)) |
Draw a straight horizontal timeline. Each step updates one entry in a Hash Map and adds to a running "Good Pair" count. |
Draw an N x N boolean matrix marking every pair as good or bad. |
Draw one Hash Map storing Integers (difference) and Longs (counts). |
| 2365 |
Task Scheduler II |
Simulate every single day. If a task can't be done yet, skip the day. Check every task against a "last completed" log for its type. |
Day-by-Day Simulation (O(Total_Days)) |
Draw a calendar. Write the task on the day it's done. If a "break" is needed, leave the calendar square blank and move to the next. |
Greedy Time Calculation (Hash Map) |
Cooldown Jump Logic |
Iterate through tasks. `currentTime++`. If task T was last done at `lastTime`, and `currentTime - lastTime <= space`, jump `currentTime` to `lastTime + space + 1`. Update `lastTime` map. |
Draw a timeline. For each task, check your "Last Done" log. If too soon, draw a long arrow skipping forward to the next valid day. Mark the new day in the log. |
Linear Task Pass (O(N)) |
Draw a timeline that "warps" forward. It only has N steps, but the "value" of each step can jump significantly. |
Draw a massive "Calendar" array that grows with the number of idle days. |
Draw one Hash Map storing `Task_Type -> Last_Day_Completed` (Integer). |
| 2366 |
Minimum Replacements to Sort the Array |
Try every possible way to split each number into smaller parts such that the entire array becomes non-decreasing, using recursion or backtracking. |
Exponential Splitting Tree (O(2^N)) |
Draw a number. Branch out into every possible pair of numbers that sum up to it (e.g., 10 becomes 1+9, 2+8, etc.). Repeat for each new number. |
Greedy (Right-to-Left) + Math Division |
Reverse Limit Propagation |
Start from the end. Keep a `last` limit. For the current `num`, if `num > last`, calculate `parts = ceil(num / last)`. The new `last` becomes `floor(num / parts)`. Add `parts - 1` to total operations. |
Draw the array. Start at the far right. Move left. If a bar is taller than the one to its right, draw "cut lines" through it to slice it into equal pieces just small enough to fit. Write the new height. |
Single Reverse Pass (O(N)) |
Draw a straight timeline from right to left. No branching. Only one variable `last` is updated at each step. |
Draw a deep recursion stack storing thousands of split-number combinations. |
Draw one Long/Integer variable (`total_operations`) and one Integer (`last_limit`). |
| 2367 |
Number of Arithmetic Triplets |
Triple nested loops: Check every combination of `(i, j, k)` to see if `nums[j] - nums[i] == diff` and `nums[k] - nums[j] == diff`. |
Cubic Triplet Scan (O(N^3)) |
Draw an array. Draw three pointers (i, j, k) moving in all possible combinations, checking the subtraction result for each. |
Hash Set / Boolean Lookahead |
Direct Difference Indexing |
Iterate through the array. For each `num`, check if `num - diff` and `num - 2*diff` both exist in a Hash Set of the array elements. |
Draw the array and a "Checklist" (Hash Set). For every number you see, look back exactly `diff` steps and `2*diff` steps in your checklist. If both boxes are ticked, you've found a triplet. |
Single Pass + Constant Lookup (O(N)) |
Draw a straight horizontal timeline. Each step performs two "teleport" checks to previous values in the Hash Set. |
Draw a 3D matrix representing all potential triplet states. |
Draw one Hash Set (or a 201-element Boolean Array) to store seen numbers. |
| 2368 |
Reachable Nodes With Restrictions |
From node 0, run a full DFS/BFS. For every edge, check if the neighbor is in the `restricted` list by scanning the list repeatedly. |
Graph Search + List Scanning (O(V * R)) |
Draw a graph. From node 0, draw arrows to neighbors. For every arrow, draw a separate line scanning the entire "Restricted" list to see if you can pass. |
Hash Set + Single BFS/DFS |
Blocked Edge Pruning |
Convert the `restricted` list into a Hash Set for $O(1)$ lookup. Run a standard BFS/DFS starting from node 0, but never move into a node that exists in the Hash Set. |
Draw a graph. Color the "Restricted" nodes red. Start at node 0 and "flood" the graph with blue paint. The paint can't enter red nodes. Count the blue nodes. |
Linear Graph Traversal (O(V + E)) |
Draw a single traversal path that visits each non-restricted node and edge exactly once. |
Draw a massive call stack that repeatedly re-checks the restricted list for the same nodes. |
Draw an Adjacency List (Array of Lists) and one Hash Set for restricted nodes. |
| 2369 |
Check if There is a Valid Partition For The Array |
Backtracking: Try every possible partition (size 2 or 3) from the start. If one path fails, backtrack and try a different partition length. |
Exponential Partition Tree (O(2^N)) |
Draw an array. Branch into "Cut at 2" and "Cut at 3". From each, branch again into "Cut at 2" and "Cut at 3". Go N levels deep. |
1D Dynamic Programming (Boolean State) |
Three-Step Validity Buffer |
`dp[i]` is true if the prefix `nums[0...i-1]` has a valid partition. `dp[i]` depends only on `dp[i-2]` (if last 2 are equal) or `dp[i-3]` (if last 3 are equal/consecutive). |
Draw a timeline. For each index, look back 2 or 3 steps. If a previous step was "Safe" AND the current segment (2 or 3 items) is "Valid," mark the current step as "Safe." |
Linear DP Pass (O(N)) |
Draw a straight line. Each node only looks back at its 2nd and 3rd neighbors. No branching forward. |
Draw a deep recursion stack representing the exploration of all partition combinations. |
Draw a 1D Boolean Array of size N (or just 4 boolean variables for space optimization). |
| 2370 |
Longest Ideal Subsequence |
Generate every possible subsequence (2^N), check if every adjacent character pair in the subsequence has a distance <= `k`. |
Exponential Subsequence Tree (O(2^N)) |
Draw a string. At each letter, branch into "Include" or "Exclude". If you include, check the distance against the last included letter. |
1D DP (Character Bucket State) |
Alphabet Max-Height Bars |
Maintain a DP array `dp[26]` where `dp[c]` is the length of the longest ideal subsequence ending with character `c`. For a new char `i`, `dp[i] = 1 + max(dp[i-k...i+k])`. |
Draw 26 vertical bars (a to z). As you read a letter (e.g., 'm'), look at the bars from 'm-k' to 'm+k'. Find the tallest bar in that range, add 1 to its height, and make the 'm' bar that new height. |
Linear Scan + Constant Alphabet (O(26 * N)) |
Draw a timeline of length N. At each step, draw a small fixed-size scan over 26 characters. |
Draw a massive recursion stack storing all valid/invalid subsequence fragments. |
Draw a 26-element Integer Array `dp` to track the longest sequence ending at each letter. |
| 2371 |
Minimize Maximum Value in a Grid (Premium) |
Try all possible permutations of assigning values 1 to M*N to the grid cells such that row and column order constraints are preserved. |
Factorial Grid Permutations (O((M*N)!)) |
Draw an M x N grid. For every cell, branch into every possible number from 1 to M*N. Check if the row/column order is still valid for every number. |
Sorting + Greedy Row/Col Max Tracking |
Value-Based Incremental Filling |
Store all `[value, row, col]` in a list and sort by value. Maintain `rowMax[M]` and `colMax[N]` initialized to 0. Iterate sorted cells: `newVal = max(rowMax[r], colMax[c]) + 1`. Update `rowMax[r]` and `colMax[c]` with `newVal`. |
Draw the grid. List all numbers in the grid from smallest to largest. Pick the smallest, look at its row and column. Give it a '1'. Pick the next smallest, look at the max value already placed in its row/column, and give it `max + 1`. |
Sorting + Linear Grid Scan (O(MN log MN)) |
Draw a sorting funnel for all cells. Below it, draw a single pass through the sorted list, updating two 1D arrays (`rowMax`, `colMax`). |
Draw a massive recursion stack for all possible grid numberings. |
Draw two 1D Arrays (`rowMax`, `colMax`) and a sorted list of `[val, r, c]` triplets. |
| 2372 |
Calculate the Influence Score (SQL Premium) |
(Conceptual) For every user, run a separate query to count their followers, then another to count the followers of their followers, and sum them up. |
Nested User-Follower Scans |
Draw a User table. For each user, draw arrows to their followers. For each follower, draw arrows to *their* followers. Count all unique arrows. |
JOIN + SUM Aggregation |
Two-Step Relational Expansion |
Join the `Follows` table with itself on `follower_id = user_id` to get second-level connections. Group by the original `user_id` and sum the influence. |
Draw a table of connections. Copy the table. Line them up so "Follower" in Table A matches "User" in Table B. Group by the first "User" and count the rows. |
Two-Pass Relational Join |
Draw a data stream entering a Join block, then a Grouping block, then an Aggregation block. |
Draw multiple temporary tables for every user's recursive follower scan. |
Draw one Result Set stream with `user_id` and `influence_score`. |
| 2373 |
Largest Local Values in a Matrix |
For every cell `(i, j)` in the result matrix, iterate through all 9 cells in the corresponding 3x3 subgrid in the original matrix to find the maximum. |
Nested 3x3 Window Scans (O(N^2 * 9)) |
Draw an N x N grid. Draw a small 3x3 red box. Slide it one step at a time. Inside each red box, draw a tiny arrow checking all 9 numbers. |
Sliding Window Maximum |
3x3 Kernel Max-Pooling |
Iterate `i` from 0 to N-3 and `j` from 0 to N-3. For each `(i, j)`, use two nested loops (0 to 2) to find the max in `grid[i+r][j+c]`. Store in `res[i][j]`. |
Draw the matrix. Place a 3x3 cardboard cutout with a hole in the middle over the top-left. Find the max, write it down. Slide the cardboard right. Repeat. |
Flat Matrix Traversal (O(N^2)) |
Draw a 2D grid. Draw a single line scanning row by row. Each point on the line represents a fixed 9-step calculation. |
Draw a massive amount of temporary 3x3 subgrid copies in memory. |
Draw one `(N-2) x (N-2)` Result Matrix. No extra data structures needed. |
| 2374 |
Node With Highest Edge Score |
For every node, scan the entire `edges` array to find all nodes that point to it, sum their indices, and then compare all sums. |
N-Squared Edge Scanning (O(V^2)) |
Draw a graph. For node 0, scan every edge to see if it points to 0. For node 1, scan every edge again. Repeat for all nodes. |
In-Degree Accumulator (Array) |
Bucket Score Tally |
Initialize a `scores` array of size N. Iterate through the `edges` array once: for `edges[i] = j`, add `i` to `scores[j]`. Then find the index of the maximum value in `scores`. |
Draw N buckets labeled 0 to N-1. Walk through the `edges` array. If index `i` points to `j`, throw a "weight" equal to `i` into bucket `j`. At the end, find the heaviest bucket. |
Single Pass Scan (O(V)) |
Draw a straight horizontal timeline. Each step adds a value to one of N buckets. A final short scan finds the max bucket. |
Draw a 2D adjacency matrix just to calculate scores. |
Draw one 1D Long Array `scores` of size N. |
| 2375 |
Construct Smallest Number From DI String |
Generate all permutations of numbers 1-9 (9!), check if each permutation follows the 'D' and 'I' pattern, and pick the smallest one. |
Factorial Permutation Search (O(9!)) |
Draw a string like "IDID". Branch into every possible starting number (1-9). For 'I', branch into larger numbers; for 'D', branch into smaller. Find the first valid leaf. |
Stack-Based Segment Reversal |
Incremental Number Reversing |
Iterate through `pattern` and numbers `1` to `N+1`. Push numbers onto a stack. If you hit an 'I' or the end of the string, pop everything from the stack and append to the result. |
Draw the pattern. Write numbers 1, 2, 3... under it. If you see 'D', put the number in a "waiting room" (stack). When you hit 'I', let everyone out of the waiting room in reverse order. |
Single Pass with Stack (O(N)) |
Draw a timeline. Numbers flow into a stack and then immediately out into the result string. No branching back. |
Draw a massive recursion tree of all numeric permutations. |
Draw one Stack and one Result String (or Character Array). |
| 2376 |
Count Special Integers |
Iterate from 1 up to N. For every single number, convert it to a string or use a Hash Set to check if all its digits are unique. Count the ones that are. |
Brute Force Iteration (O(N * log N)) |
Draw a timeline from 1 to N. At every tick, draw a small sub-scan checking all the digits of that number for duplicates. |
Digit Dynamic Programming (Bitmask) |
Constraint-Based Digit Filling |
Use a recursive function `count(index, mask, isLess, isStarted)`. `mask` tracks used digits. `isLess` handles the boundary of N. `isStarted` handles leading zeros. Memoize the results. |
Draw a tree where each level is a digit position (10s, 100s). Each branch is a digit (0-9). Cross out branches that lead to digits already used in that path (using the bitmask). |
Logarithmic Digit Depth (O(log10(N) * 2^10)) |
Draw a shallow tree (max 10 levels deep). Each node represents a state in the memoization table. |
Draw a huge boolean array for every number up to N. |
Draw a 2D/3D `memo` table and a 10-bit integer (Bitmask). |
| 2377 |
Sort the Olympic Table (SQL Premium) |
(Conceptual) Manually compare every country's gold medals. If equal, compare silver, then bronze, and then alphabetical names. |
Manual Multi-Level Comparison |
Draw the medal table. Pick two rows. Compare Gold. If tie, compare Silver. Repeat until a winner is found for that pair. |
ORDER BY Multiple Columns |
Relational Multi-Key Sorting |
`SELECT * FROM Olympic ORDER BY gold_medals DESC, silver_medals DESC, bronze_medals DESC, country_name ASC`. |
Draw a table. Sort by the first column. For rows that are identical, sort only those rows by the second column. Repeat for third and fourth. |
Log-Linear Database Sort |
Draw a data stream entering a multi-stage sorting funnel (Gold -> Silver -> Bronze -> Name). |
Draw multiple intermediate table copies for each sorting criteria. |
Draw one Result Set stream with all columns sorted. |
| 2378 |
Choose Edges to Maximize Score in a Tree (Premium) |
Generate all possible subsets of edges. For each subset, check if any node has more than one chosen edge. If valid, calculate the total weight and find the max. |
Exponential Edge Subsets (O(2^E)) |
Draw a tree. Draw branches for "Pick Edge A" and "Don't Pick Edge A". Repeat for every edge. Cross out paths where a node gets two edges. |
Tree Dynamic Programming (House Robber Style) |
State-Based Parent Selection |
For each node, compute two values: `dp[u][0]` (max weight in subtree where no edge connects u to a child) and `dp[u][1]` (max weight where one edge connects u to a child). |
Draw a tree. Next to each node, write two numbers in a box. The numbers are calculated by looking at the boxes of the children and deciding whether to "link" to one child or remain "free." |
Single Tree Traversal (O(N)) |
Draw a single line tracing the perimeter of the tree (DFS), performing a small math check at each node. |
Draw a massive checklist for every possible combination of edges. |
Draw the Tree nodes, each containing a small size-2 array. |
| 2379 |
Minimum Recolors to Get K Consecutive Black Blocks |
Generate every possible substring of length K. For each, count how many 'W' (white) characters it contains. Pick the minimum count. |
Nested Substring Scanning (O(N * K)) |
Draw a string. Draw a fixed-width bracket of size K. Slide it one step at a time. Inside each bracket, draw a tiny arrow counting 'W's. |
Sliding Window (Constant Space) |
Running White-Count Frame |
Maintain a count of 'W' in the first K characters. Then, slide the window: if the character leaving was 'W', decrement count; if the character entering is 'W', increment count. Track the minimum count. |
Draw a string. Place a fixed-width "Window" over it. As the window slides, just update the "W-Count" based on the two characters at the window's edges. |
Single Pass Scan (O(N)) |
Draw a straight horizontal timeline. Each step only updates the edges of a sliding box. |
Draw many temporary string copies of length K in memory. |
Draw two Integer variables: `min_recolors` and `current_w_count`. |
| 2380 |
Time Needed to Rearrange a Binary String |
Repeatedly scan the string. Every time you see "01", change it to "10". Count how many full passes (seconds) it takes until no "01" remains. |
Step-by-Step Simulation (O(N^2)) |
Draw the string. Circle every "01". Rewrite the string with those changed to "10". Count that as 1 second. Repeat until no circles can be drawn. |
Dynamic Programming / Mathematical Greedy |
Leading Zero Delay Tracking |
Iterate from left to right. Keep track of the number of zeros seen so far (`zeros`). If you hit a '1' and `zeros > 0`, the time it reaches its spot is `max(prev_time + 1, zeros)`. |
Draw the string. Count the zeros behind every '1'. Imagine the '1's are cars moving left. If a '1' is blocked by another '1', it has to wait 1 extra second. Otherwise, it takes as many seconds as there are zeros in front of it. |
Single Pass Scan (O(N)) |
Draw a straight horizontal timeline. One pass calculates the "wait time" for each '1'. |
Draw a full copy of the string for every second of the simulation. |
Draw two Integer variables: `seconds` and `zeros_count`. |
| 2381 |
Shifting Letters II |
For every shift in the list, iterate through the string from `start` to `end` and manually change each character's value. |
Nested Segment Updates (O(Q * N)) |
Draw a string. For every shift query, draw a long bracket. Inside the bracket, draw tiny arrows pointing to each letter, changing 'a' to 'b' or 'z' to 'y'. |
Difference Array (Prefix Sum of Shifts) |
Cumulative Net-Shift Timeline |
Initialize an array `diff` of size N+1. For each shift `[start, end, dir]`, add `val` (1 or -1) to `diff[start]` and subtract it from `diff[end + 1]`. Then, compute prefix sums of `diff` to find the net shift for each index. |
Draw an empty array. For a shift from 3 to 6, put a '+1' at 3 and a '-1' at 7. After all shifts, sweep from left to right, carrying the sum forward. The sum at each index is the total "push" that letter receives. |
Two Linear Passes (O(N + Q)) |
Draw two horizontal lines. One pass marks the "start" and "end" points of shifts. The second pass sweeps across to calculate final positions. |
Draw numerous modified copies of the string for every shift. |
Draw a 1D Integer Array `diff` of size N+1. |
| 2382 |
Maximum Segment Sum After Removals |
Actually remove the element, splitting the array. Recalculate the sum of all remaining segments to find the max. $O(N^2)$. |
Shattering Array Re-sums |
Draw the array. Smash a hole in it. Manually re-add the left pieces and right pieces. Repeat for every smash. |
Reverse Processing + Union Find (DSU) |
The Reverse Builder |
Work backwards! Start with an empty array. Add elements back in the reverse order of the queries. When adding, use DSU to merge it with adjacent existing elements, track the component sum, and update `global_max`. |
Draw an empty line. Drop numbers into it backwards. When two numbers touch, they fuse into a bigger block. Write the weight on the block. Record the heaviest block seen so far. Reverse the recorded answers. |
Union-Find $O(N \\text{cdot alpha}(N)$) |
Draw a timeline moving right-to-left. Above it, draw $O(1)$ DSU merges and sum updates. |
Massive arrays of subarray slices. |
DSU parent and sum arrays. $O(N)$ space. |
| 2383 |
Minimum Hours of Training to Win a Competition |
Simulate the competition. If your energy or experience is too low for an opponent, increment a "training" counter and restart the entire simulation from the first opponent. |
Repeated Linear Simulation (O(N^2)) |
Draw a list of opponents. Try to beat the first. If you fail, go back to the start, "train," and try again. Repeat for every opponent you lose to. |
Single Pass Greedy Training |
Pre-emptive Stat Boosting |
Iterate through opponents. If `currentEnergy <= opponentEnergy`, training needed = `opponentEnergy - currentEnergy + 1`. Add to total training and update `currentEnergy`. Do the same for experience. |
Draw two meters: "Energy" and "Exp." For each opponent, check if your meters are high enough. If not, draw a "plus" sign to fill the gap before you "fight." Move to the next. |
Single Pass Scan (O(N)) |
Draw a straight horizontal timeline. Meters are updated and training is tallied in one go. |
Draw a full log of every failed simulation attempt. |
Draw three Integer variables: `total_training`, `current_energy`, `current_exp`. |
| 2384 |
Largest Palindromic Number |
Generate every possible subsequence, check if it's a palindrome, and find the maximum one by comparing strings numerically. |
Exponential Subsequence Search (O(2^N)) |
Draw a list of digits. Branch into "Include" or "Exclude" for every digit. For every leaf, check if the string reads the same backward and forward. |
Frequency Map + Greedy Construction |
Mirrored Digit Placement |
Count the frequency of each digit (0-9). Build the left half by picking pairs of the largest digits (9, 8... 0). Pick the largest single digit left for the center. Reverse the left half to get the right half. Handle leading zeros. |
Draw 10 buckets (0-9). Put the digits in. Pull out two '9's and put them at the ends: 9_9. Pull out two '8's: 98_89. Finally, pick the largest single digit left (like '7') for the middle: 98789. |
Constant Alphabet Scan (O(N + 10)) |
Draw a linear pass to count digits, followed by a fixed 10-step pass to build the string. |
Draw a massive recursion stack storing thousands of subsequence strings. |
Draw a 10-element Integer Frequency Array and two string builders. |
| 2385 |
Amount of Time for Binary Tree to Be Infected |
From every node, run a search to find the "start" node, then from there, perform a search to find the longest path, manually tracking parent pointers for every node. |
Multi-Pass Graph Search (O(N^2)) |
Draw a tree. For every node, draw a search to find 'start'. Then from 'start', draw a search to find the most distant leaf. |
Adjacency List + BFS (Graph Conversion) |
Ripple-Effect Graph Traversal |
Convert the tree into an undirected graph (Adjacency List) where each node points to its children and its parent. Then, run a BFS starting from the `start` node to find the maximum distance. |
Draw a tree. Draw arrows both down (to children) and up (to parents) to turn it into a web. Start at the infected node and draw "ripples" (circles) expanding outward. Count how many ripples it takes to hit the last node. |
Linear Graph Traversal (O(N)) |
Draw a single pass to build the graph, followed by one expanding ripple pass. |
Draw numerous redundant searches to find the start node and its neighbors. |
Draw an Adjacency List (Map of Lists) and a `visited` Set. |
| 2386 |
Find the K-Sum of an Array |
Generate all 2^N possible subsequences, sum them up, sort the massive list of sums, and pick the K-th largest. $O(2^N \log(2^N)$). |
Exponential Array Explosion |
Draw an array. Branch out into every possible combination. Calculate the sum for each. Try to sort an impossibly long list. |
Max Heap + Absolute Value Sorting |
The Subtractive Max-Heap |
Find the absolute maximum sum by adding all positive numbers. Then, use a Min-Heap to systematically subtract the smallest possible absolute values from this maximum to find the 2nd, 3rd... Kth sums. |
Draw the absolute max sum in a box. Draw an array of absolute values sorted smallest to largest. Use a Priority Queue to branch out, subtracting the smallest numbers one by one to step down from the max. |
Heap Extraction $O(N \log N + K \log K)$ |
Draw a sorting pass over the array, followed by K extractions from a priority queue of size K. |
Memory crash from 2^N elements. |
A Priority Queue of size K. $O(K)$ space. |
| 2387 |
Median of a Row-Wise Sorted Matrix (Premium) |
Flatten the entire M x N matrix into a single 1D array, sort it, and pick the middle element. |
Flatten and Sort (O(MN log MN)) |
Draw an M x N grid. Draw an arrow collecting all numbers into one long line, then draw a sorting funnel for that line. |
Binary Search on Range + Upper Bound |
Converging Value Guessing |
The median must be between the matrix min and max. Binary search for a value X. For each row, use `bisect_right` to count elements <= X. If total count > (M x N) / 2, X might be the median. |
Draw a number line from `min` to `max`. Pick the middle number. For every row in the matrix, count how many numbers are to the left of your pick. Adjust your pick left or right based on the total count. |
Logarithmic Range Search (O(M \log N \log (\text{Max-Min}))) |
Draw a horizontal range [min, max] shrinking by half at each step, with M small arrows pointing into the matrix rows. |
Draw a large temporary 1D array holding all matrix elements. |
Draw zero extra memory (just M row-pointers and 3 variables for Binary Search). |
| 2388 |
Change Null Values in a Table to the Previous Value (SQL Premium) |
(Conceptual) For every row, scan all preceding rows manually to find the most recent non-null value and copy it. |
Nested Row Back-Scanning |
Draw a table with gaps. For each gap, draw a finger pointing upward, moving one row at a time until it hits a value. |
Window Functions with IGNORE NULLS |
Vertical Value "Filling" |
Use `LAST_VALUE(column IGNORE NULLS) OVER (ORDER BY row_id)`. This treats the table as a stream where the "current" state is the last seen value. |
Draw a table. Imagine a "Paint Bucket" at the top. As you move down, if a cell is empty, it gets painted with the color of the cell above it. |
Single Pass Window Scan |
Draw a data stream entering a "State Buffer" that only updates when a non-null value passes through. |
Draw multiple subqueries for every single null cell. |
Draw one Result Set stream with a "Sticky Value" buffer. |
| 2389 |
Longest Subsequence With Limited Sum |
For every query Q, generate all subsequences of `nums`, find those with sum <= Q, and track the max length. |
Exponential Subsequence Search (O(Q \times 2^N)) |
Draw a query value. Below it, draw a massive branching tree of all possible number combinations from the array. |
Sorting + Prefix Sum + Binary Search |
Accumulated Growth Threshold |
Sort `nums` ascending. Calculate the prefix sum array. For each query, use `binary search` (upper bound) on the prefix sums to find the largest index where the sum is <= query. |
Draw the array from smallest to largest. Stack the numbers on top of each other to create a "staircase" (prefix sums). For a query, draw a horizontal line at that height; the number of steps below the line is your answer. |
Sorting + Query Binary Search (O(N \log N + Q \log N)) |
Draw a sorting funnel, a single linear prefix-sum line, and then Q quick binary search "pokes" into the line. |
Draw a 2D matrix of all subsequences for every query. |
Draw one 1D Array (Prefix Sums) of size N. |
| 2390 |
Removing Stars From a String |
Scan the string. Every time you find a '*', look at all previous characters to find the nearest non-star, delete both, and start the scan over. |
Repeated Deletion & Re-scanning (O(N^2)) |
Draw a string. Circle a '*', find the letter to its left, erase both with a big "X", then shift the whole string left. Repeat. |
Stack (LIFO) / Two Pointers |
Incremental Character Buffer |
Iterate through the string. If the character is not a '*', push it onto a stack. If it is a '*', pop the top character from the stack. Join the stack at the end. |
Draw a string and an empty box (Stack). For every letter, drop it in the box. For every star, reach into the box and pull out the last letter you dropped. |
Single Pass Scan (O(N)) |
Draw a straight horizontal timeline. A stack grows and shrinks as the pointer moves across the input. |
Draw thousands of intermediate string copies created during deletions. |
Draw one Stack (or Character Array) to act as the result buffer. |
| 2391 |
Minimum Amount of Time to Collect Garbage |
Simulate three separate trucks. For each house, count the garbage types and move the truck one house at a time, calculating travel time repeatedly. |
Triple Linear Simulation (O(3 * N)) |
Draw three truck icons (M, P, G). For each house, draw an arrow moving the truck, then a tiny sub-scan to count the letters in the house string. |
Prefix Sums + Last Occurrence Tracking |
Cumulative Travel "Milestone" |
Calculate the prefix sum of travel times. For each garbage type (M, P, G), find its total count and the index of its **last** occurrence. Total time = (Sum of all garbage counts) + (Prefix Sum of travel up to each last index). |
Draw a timeline of houses with travel times between them. Mark the last house where "Metal" appears. Draw one long arrow from the start to that last house. Repeat for Paper and Glass. Add the lengths of those three arrows to the total garbage count. |
Two Linear Passes (O(N)) |
Draw a horizontal line. One pass to find the "Finish Lines" for each truck, and one pass to sum the travel costs up to those lines. |
Draw three separate arrays tracking every individual truck's movement history. |
Draw three Integer variables (`lastM`, `lastP`, `lastG`) and one Prefix Sum Array of travel times. |
| 2392 |
Build a Matrix With Conditions |
Generate every possible K x K matrix. For each matrix, check if the row and column order constraints are satisfied for all numbers from 1 to K. |
Exhaustive Matrix Permutations (O((K^2)!)) |
Draw a K x K grid. Branch out by placing '1' in every possible cell, then '2' in every remaining cell. Check constraints at every leaf. |
Topological Sort (Kahn's Algorithm) |
Directed Acyclic Graph (DAG) Sequencing |
Treat row and column constraints as directed graphs. Perform Topological Sort on the row graph to get row indices, and on the column graph to get column indices. If a cycle exists, return empty. Otherwise, place i at `(row_idx[i], col_idx[i])`. |
Draw two sets of nodes (1 to K). Draw arrows for "Before/After" rules. Flatten the arrows into a straight line. Use the position in the "Row Line" as the vertical coordinate and the "Column Line" as the horizontal coordinate. |
Linear Graph Traversal (O(K + E)) |
Draw two separate DAGs being flattened into linear sequences. No 2D grid searching; just two 1D sorts. |
Draw a massive recursion stack for all possible grid placements. |
Draw two Adjacency Lists and two 1D "Index Maps" of size K. |
| 2393 |
Count Strictly Increasing Subarrays (Premium) |
Generate every possible subarray (i, j). For each, scan it to see if every element is strictly greater than the previous one. Count valid ones. |
Cubic Subarray Scanning (O(N^3)) |
Draw an array. Draw brackets for every segment. Inside each bracket, draw a tiny arrow checking the "greater than" condition between neighbors. |
Dynamic Programming / Linear Counting |
Continuous Growth Streaks |
Iterate through the array. Maintain a `length` of the current increasing streak. At each step, if `nums[i] > nums[i-1]`, `length++`. Add `length` to the total count. Else, reset `length = 1`. |
Draw an array. Underneath, draw a bar that grows as long as numbers increase (1, 2, 3...). Every time the bar grows, add its current height to your total score. When numbers drop, reset the bar. |
Single Pass Scan (O(N)) |
Draw a straight horizontal timeline. A single "streak" variable pulses up and resets as it moves across the data. |
Draw a massive 2D matrix storing validity flags for every subarray. |
Draw two Integer variables: `current_streak` and `total_count`. |
| 2394 |
Employees With Deductions (SQL Premium) |
(Conceptual) For every employee, manually sum their work hours, then manually calculate the "ceiling" for every single log entry to see if they met the quota. |
Nested Logging Scans |
Draw an Employee list. For each, draw an arrow to the `Logs` table, scan all entries, perform a `CEIL` math check on each, and sum them. |
CEIL + SUM + LEFT JOIN |
Relational Aggregation Filter |
Select employees from the `Employees` table. `LEFT JOIN` with `Logs`. Calculate `SUM(CEIL(duration / 60))` per employee. Filter those whose sum is less than their `needed_hours`. |
Draw two tables. Join them by ID. In the "Logs" part, round every minute count up to the next hour. Group by Name and compare the total hours to their contract. |
Single Pass Aggregation |
Draw a data stream entering a "Rounding" block, then a "Summing" block, then a "Comparison" filter. |
Draw multiple temporary tables for each employee's hour rounding. |
Draw one Result Set stream with `employee_id`. |
| 2395 |
Find Subarrays With Equal Sum |
Nested loops: For every pair of adjacent elements (i, i+1), iterate through all other adjacent pairs (j, j+1) to see if their sums are equal. |
N-Squared Sum Comparison (O(N^2)) |
Draw an array. Circle a pair, calculate sum. Then draw an arrow scanning every other pair in the array to see if their sum matches. Repeat for all pairs. |
Hash Set (Single Pass) |
Sum Occurrence Tally |
Iterate through the array once from 0 to N-2. Calculate `sum = nums[i] + nums[i+1]`. If `sum` is already in a Hash Set, return true. Otherwise, add it to the Set. |
Draw an array and an empty "Sum Bucket" (Set). Walk through the array, picking up two numbers at a time. Add them and try to throw the result in the bucket. If the bucket already has that number, you win! |
Single Pass Scan (O(N)) |
Draw a straight horizontal timeline. Each step performs a single $O(1)$ "look up and insert" into a Hash Set. |
Draw a list of all possible sums being compared against each other repeatedly. |
Draw one Hash Set to store previously seen Integer sums. |
| 2396 |
Strictly Palindromic Number |
For every base b from 2 to n-2, convert n to base b, store it as a string, and check if it's a palindrome. |
Base Conversion + Palindrome Scan (O(N * log N)) |
Draw the number n. For every base (2, 3, 4...), draw a sub-process that divides n repeatedly to build a string, then scans that string from both ends. |
Mathematical Insight (Constant Return) |
Boolean False Logic |
For any n > 4, the number n in base n-2 is always "12", which is never a palindrome. Therefore, no number n > 4 can be strictly palindromic. Simply return `false`. |
Draw the number n. Write its representation in base n-2 (it's always 12). Since '1' != '2', it fails immediately. No need to check any other bases. |
Constant Time (O(1)) |
Draw a single, fixed "Return False" block. The input size n does not change the visual complexity. |
Draw numerous temporary strings created for each base conversion. |
Draw zero extra memory (no data structures used). |
| 2397 |
Maximum Rows Covered by Columns |
Generate all possible combinations of picking `numSelect` columns (^C_k). For each combination, check every row to see if all its '1's are within the selected columns. |
Combinatorial Column Selection (O(2^C * R)) |
Draw a grid. Branch out by picking every possible subset of columns. For each leaf, scan every row to see if it's "covered." |
Bitmasking + Gosper's Hack |
Bitwise Row-Column Masking |
Represent each row as a bitmask. Iterate through all bitmasks of length C that have exactly `numSelect` bits set. For each mask, count how many rows satisfy `(rowMask & mask) == rowMask`. |
Draw the grid as a vertical stack of binary numbers. Create a "Selection Mask" (a horizontal binary number). If a "row number" ANDed with the "mask" equals the original "row number," that row is covered. |
Bitwise Iteration (O(comb(C, k) * R)) |
Draw a list of column combinations. Each step is a fast bitwise comparison against all rows. |
Draw a massive recursion tree for all column combinations. |
Draw a 1D Integer Array `rowMasks` and one Integer variable for the current `selectionMask`. |
| 2398 |
Maximum Number of Robots Within Budget |
Nested loops: For every possible subarray (i, j), find the max `chargeTime` in that range and the sum of `runningCosts`, calculate the formula, and check against `budget`. |
Cubic Window Calculation (O(N^3)) |
Draw two arrays. Draw a bracket for every possible segment. Inside each bracket, scan for the max value and calculate the sum. |
Sliding Window + Monotonic Deque |
Amortized "Max-Sum" Window |
Use a sliding window with `left` and `right` pointers. Use a Monotonic Deque to track the maximum `chargeTime` in the current window in $O(1)$. If the cost exceeds budget, shrink the window from the left. |
Draw two arrays. Draw a sliding box. Inside the box, keep a running total of the sum. Use a small "side-queue" (Deque) to keep track of the biggest number currently inside the box as it slides. |
Linear Two-Pointer Pass (O(N)) |
Draw a straight horizontal timeline. Two arrows move forward, and a small Deque updates at each step without re-scanning the whole window. |
Draw a massive 2D matrix storing max values and sums for all subarrays. |
Draw one Deque (Double-Ended Queue) and one Long variable for the running sum. |
| 2399 |
Check Distances Between Same Letters |
For every letter in the alphabet, scan the entire string to find its two occurrences, calculate the distance between them, and compare it to the `distance` array. |
Multi-Pass Alphabet Scanning (O(26 * N)) |
Draw the string. For 'a', scan for two 'a's. For 'b', scan for two 'b's. Repeat 26 times, checking the subtraction result against the provided array. |
Single Pass First-Occurrence Map |
Index Difference Validation |
Iterate through the string once. Store the index of the first time you see a character in a Hash Map (or Array). When you see it a second time, check if `curr_idx - prev_idx - 1 == distance[char]`. |
Draw the string. As you walk, write the index above each letter. If you see 'a' at index 3, and then 'a' again at index 7, check if 7 - 3 - 1 matches the number in the 'a' slot of the distance table. |
Single Linear Pass (O(N)) |
Draw a straight horizontal timeline. One pass updates a "First Seen" table and validates distances on the fly. |
Draw 26 separate timelines for each letter's search. |
Draw one 26-element Integer Array to store the first occurrence of each character. |
| 2400 |
Number of Ways to Reach a Position After Exactly k Steps |
Backtracking: From `startPos`, branch into `left` and `right` for every step. After k steps, count how many paths ended at `endPos`. |
Exponential Movement Tree (O(2^K)) |
Draw a starting point. At every step, branch left and right. Go K levels deep. Circle the leaf nodes that land on the `endPos` coordinate. |
Combinatorics (Pascal's Triangle / Math) |
Binomial Coefficient Selection |
Total steps k, net distance d = |start - end|. We need R right steps and L left steps such that R + L = k and R - L = d. Solving gives R = (k + d) / 2. The answer is C(k, R). |
Draw a grid of steps. Realize that to get from 0 to 2 in 4 steps, you MUST take 3 steps right and 1 step left in any order. This is just choosing which of the 4 "step-slots" will be "left turns." |
Constant Time Math (O(1) with Factorials) |
Draw a single "Choose" formula: kCr. The complexity is a single mathematical calculation. |
Draw an immense recursion tree with 2^K nodes. |
Draw zero extra memory (or a small 2D DP table if using iterative Pascal's Triangle). |
| 2401 |
Longest Nice Subarray |
Nested loops checking all possible subarrays; bitwise ANDing every pair inside to ensure it equals 0. |
N x N Iteration Grid / Nested Tree |
Draw a 2D matrix of indices (i, j). Shade cells where j >= i. Write $O(N^3)$ next to it since verifying each pair takes $O(N)$. |
Sliding Window / Two Pointers with Bitmask Running OR |
Expanding/Contracting Window over Binary Grids |
Imagine a window. Keep a running 'OR' integer. If new num AND running OR != 0, shrink window from left, XORing out left elements until AND == 0. |
Draw array as a tape. Write binary representations above each number. Draw a bracket [ ] for the window. Cross out bits as L pointer moves right. |
Two-Pointer Timeline Array |
Draw a number line 0 to N. Draw an 'R' arrow moving monotonically right N times. Draw an 'L' arrow moving right at most N times. Label: 2N steps total = $O(N)$. |
Draw an array of size N allocated for every subarray check to store pairs, showing $O(1)$ extra but heavy pointer reuse. |
Draw a single 32-bit block. Shade in 1s and erase them to represent the single integer running bitmask. (O(1) space). |
| 2402 |
Meeting Rooms III |
Iterate time second-by-second. For each second, check all meetings and all rooms to assign the lowest available index. |
Time-Series Matrix |
Draw a matrix where rows = time, cols = rooms. Fill cells one by one. Write $O(\text{Time} \\text{cdot Rooms})$ indicating massive wasted iterations. |
Two Min-Heaps (Priority Queues): One for unused rooms, one for engaged rooms (endTime, roomIdx). |
Dual Bucket Sifting |
Draw two funnels (Heaps). Meetings drop in based on start time. If meeting ends, move room from "Engaged Funnel" to "Unused Funnel". Assign lowest room from Unused. |
Draw an array sorted by start time. Draw two inverted trees (heaps) below. Erase and rewrite root nodes as meetings start/end. |
Event-Driven Flowchart |
Draw N meetings. From each, draw arrows to Heap operations (Log R). Total arrows = N, weight = Log R. Label: $O(M \log M + M \log R)$. |
Draw a massive boolean array [Rooms][MaxTime] to show room occupancy status over time. |
Draw two tree structures (Heaps) and a frequency array `count[n]` tracking meetings per room. |
| 2403 |
Minimum Time to Kill All Monsters |
Try every possible permutation of which monster to kill first, second, third, etc. $O(N!)$. |
Factorial Permutation Combat |
Draw N monsters. Branch out N ways for the first attack, N-1 for the second. The tree is too wide to map. |
Bitmask DP |
The State-Dependent Mana Pool |
Use a bitmask to represent which monsters are dead. `dp[mask]` is the minimum days to reach this state. The mana gained depends on the number of set bits in the mask. |
Draw a row of lightbulbs (monsters). When a bulb is off (dead), you gain a passive mana multiplier. Try turning off remaining bulbs one by one, recording the cheapest path to each light configuration. |
Exponential State Grid $O(N \cdot 2^N)$ |
Draw a table of 2^N rows. Each row has at most N transitions to compute the next state. |
Recursive tracking of all permutations. |
A DP array of size 2^N. $O(2^N)$ space. |
| 2404 |
Most Frequent Even Element |
Nested loops to count frequency of every even element by scanning the whole array for each element. |
Cross-Referencing Arrows |
Draw curved arrows from every element to every other element in the array. Label $O(N^2)$ total comparisons. |
Hash Map / Dictionary Counting |
Frequency Bucketing |
Pass through array once. If even, throw into a labeled bucket. Keep track of the bucket with the highest count and lowest label. |
Draw an array. Draw a table below it (Key/Value). As you point to array elements, update tally marks in the table. |
Linear Scan Line |
Draw a single straight line from index 0 to N. Label: 1 Pass = $O(N)$ time. |
Draw a single variable tracking max, showing $O(1)$ space but redundant time. |
Draw a 2-column table (Hash Map) dynamically expanding. Label $O(K)$ space where K is unique even numbers. |
| 2405 |
Optimal Partition of String |
Generate all possible string partitions (recursive backtracking) and check which one yields minimum partitions with unique chars. |
Explosive Decision Tree |
Draw a root node. Branch out 2^N paths showing every "cut or don't cut" decision. Label: $O(2^N)$. |
Greedy + Bitmask (or HashSet) |
Typewriter Carriage Return |
Read characters one by one. If char exists in current "memory", "hit return" (add to partition count) and clear memory. |
Write string out. Draw vertical lines '|' the moment you spot a duplicate letter. Reset your mental "seen" list at each line. |
Single Pass Line with check marks |
Draw a line 0 to N. Above it, draw small constant $O(1)$ lookup circles. Label: $O(N)$ total. |
Draw deep call stack frames showing $O(N)$ recursive depth and string substrings being held in memory. |
Draw a 26-bit integer box (or boolean array size 26). Shade bits for 'seen' chars. Erase all on duplicate. $O(1)$ space. |
| 2406 |
Divide Intervals Into Minimum Number of Groups |
Sort intervals. Create groups list. For each interval, iterate through all existing groups to find one where it doesn't overlap. |
List Traversal Chains |
Draw intervals. Draw lines from current interval checking every single established group one by one. Label $O(N^2)$ worst case. |
Line Sweep Algorithm (Prefix Sum over time) OR Min-Heap |
Elevation Map / Active Event Counter |
Plot start and end times on a timeline. +1 for start, -1 for end+1. Sweep left to right keeping a running sum. Peak sum = min groups. |
Draw a number line. Draw overlapping line segments above it. Draw a histogram below showing how many segments stack over each point. Find the tallest peak. |
Timeline Sort & Sweep |
Draw sorting block (O(N log N)). Draw a single sweep line over 2N events (O(N)). Total dominates: $O(N \log N)$. |
Draw a list of lists `List>` showing heavy dynamic allocation $O(N)$. |
Draw a single Map (TreeSet/TreeMap in Java/C++) or two arrays (starts, ends) tracking $O(N)$ events. |
| 2407 |
Longest Increasing Subsequence II |
Standard Dynamic Programming (DP). For every element, look back at all previous elements to find valid smaller numbers within difference 'k'. |
Backward Arrow Web |
Draw numbers in a line. From each number, draw curved arrows pointing to every single number before it. Label $O(N^2)$. |
Segment Tree / Fenwick Tree (Range Maximum Query) |
Value-Indexed Binary Tree |
Instead of searching indices, search values. When you see 'num', ask the tree: "What's the max LIS in range [num-k, num-1]?" Add 1, update tree at index 'num'. |
Draw a tree where leaf nodes represent actual numbers (1 to max_val). Shade the range [num-k, num-1]. Point to the highest number in that shaded region. |
Tree Traversal Path |
Draw a line for N elements. From the line, draw an arrow up to a tree of height Log(M). Label $O(N \log M)$ where M is max value. |
Draw a 1D DP array of size N storing lengths. $O(N)$ space. |
Draw a complete binary tree block representing $O(M)$ space for the Segment Tree. |
| 2408 |
Design SQL |
Use nested lists to store table rows. Search through the list linearly for every 'Select' or 'Insert' operation. |
Linear Table Scan |
Draw a row of boxes. Draw an arrow checking every box for an ID. Label $O(N)$ per query. |
Hash Map of Lists (Indexed Access) |
Key-Value Catalog |
Map table names to a List. Since IDs are auto-incrementing, use the ID as a direct index `list[ID-1]` for $O(1)$ access. |
Draw a Map. Key: "TableA", Value: [Row1, Row2, Row3]. Draw a finger pointing directly to Row 2 when ID=2 is asked. |
Constant Time Access |
Draw a single box. Label $O(1)$ per operation. |
List storage $O(\text{Total Rows})$. |
Hash Map overhead + List storage. $O(\text{Total Rows})$. |
| 2409 |
Count Days Spent Together |
Iterate day-by-day from Jan 1 to Dec 31. For each day, check if it falls within both Alice's and Bob's date ranges. |
Calendar Tick-Marks |
Draw a 365-cell grid. Put a checkmark in every cell that satisfies the condition. Label $O(365)$ or $O(\text{Days in Year})$. |
Math / Line Intersection (Convert MMDD to Day of Year Integer) |
Overlapping 1D Segments |
Convert dates to integers (1-365). Find the max of their start dates, and the min of their end dates. Subtract start from end + 1. |
Draw a number line. Draw a blue line for Alice's dates and a red line for Bob's dates below it. Shade the region where they vertically overlap. |
Constant Time $O(1)$ Target |
Draw four variables merging into a single calculation box. Label $O(1)$ Time. |
Draw an array of size 365 (if precomputing days of months). |
Draw just 4 integer boxes in memory. $O(1)$ space. |
| 2410 |
Maximum Matching of Players With Trainers |
For each player, scan the entire trainer array to find the smallest capacity trainer that meets their needs. Mark trainer as used. |
Bipartite Spiderweb |
Draw two columns: Players and Trainers. Draw lines from every player to multiple trainers checking validity. Label $O(N \cdot M)$. |
Sorting + Two Pointers (Greedy) |
Parallel Conveyor Belts |
Sort both arrays. Point to weakest player and weakest trainer. If trainer fits, both move forward. If not, only trainer moves forward. |
Draw two sorted arrays, one above the other. Draw pointer 'i' on top, 'j' on bottom. Draw a checkmark if Top[i] <= Bottom[j] and advance both. Cross if not, advance j. |
Logarithmic sorting blocks + Linear scan |
Draw two big blocks labeled "O(N log N)" and "O(M log M)". Next to it, draw parallel straight lines labeled "O(N+M)". Total = $O(N \log N + M \log M)$. |
Draw a boolean array "used_trainers[]" of size M. |
Draw two pointer variables i, j. Assuming in-place sort, $O(1)$ extra space. |
| 2411 |
Smallest Subarrays With Maximum Bitwise OR |
For each index 'i', start a nested loop 'j' to the end. Calculate running OR. Find the max OR, then find the shortest length that achieves it. |
Expanding Triangle |
Draw an array. Under index 0, draw lines extending to 1, 2, 3... Under index 1, lines to 2, 3... Shape forms a right triangle. Label $O(N^2)$. |
Reverse Traversal + 32-Bit Position Tracking |
Sliding Maximum Index Window |
Traverse right-to-left. Keep an array of 32 integers tracking the *nearest* index where each bit is '1'. For current 'i', max of these 32 indices gives the subarray end. |
Draw a table of 32 rows (bits) and update the index numbers as you walk backward through the array. The answer for index 'i' is the largest number currently in the table. |
Linear Pass with $O(1)$ vertical checks |
Draw an arrow going right-to-left. At each step, draw a small vertical box of constant size 32. Label $O(32 \cdot N)$ = $O(N)$. |
Draw massive overlapping variables tracking running ORs for every nested loop. |
Draw a fixed-size 32-element array called `nearest_bit_idx[32]`. Label $O(1)$ space. |
| 2412 |
Minimum Money Required Before Transactions |
Generate all permutations of transactions. For each permutation, simulate the money flow and track the lowest dip. Find the worst-case lowest dip. |
Factorial Decision Tree |
Draw a root node splitting into N branches, then N-1, etc. Label $O(N!)$ Time. |
Greedy / Math Accumulator |
Worst-Case Valley Plot |
Assume you take all net-loss transactions first. Calculate total losses. The maximum money needed is total losses + the maximum cost of a "winning" transaction (or the cashback of a losing one). |
Draw a line graph starting at 0, dipping down with every loss. Add a variable 'max_extra_needed' representing the deepest single drop before a recovery. |
Single Pass Accumulation Line |
Draw one straight line across N transactions, accumulating a 'loss' sum. Label $O(N)$ Time. |
Draw massive call stacks for permutations, $O(N)$ depth, plus tracking arrays. |
Draw two variables: `total_losses` and `max_cashback_or_cost`. $O(1)$ space. |
| 2413 |
Smallest Even Multiple |
Loop from n up to 2n, checking at every step if the current number is divisible by both 2 and n. |
Linear Step Ladder |
Draw a number line starting at 'n'. Draw steps forward, writing modulo checks at each step. Label $O(N)$ worst case. |
Math (Modulo Arithmetic / Bitwise) |
Branching Decision Node |
Check if 'n' is even. If it is, the answer is 'n'. If it is odd, the answer is 'n * 2'. (e.g., n << 1 if n & 1). |
Draw a diamond (decision box) containing "n % 2 == 0?". Draw a "Yes" arrow pointing to 'n', and a "No" arrow pointing to '2n'. |
Constant Time $O(1)$ Box |
Draw a single square box representing one mathematical operation. Label it $O(1)$ Time. |
Draw a single loop counter variable in memory. |
Draw a single integer block. $O(1)$ Space. |
| 2414 |
Length of the Longest Alphabetical Continuous Substring |
Nested loops starting at every character, iterating forward to check if the subsequent characters form an alphabetical sequence. |
Expanding Substring Triangle |
Draw the string. Under index 0, draw lines checking 1, 2, 3. Under index 1, lines to 2, 3. Label $O(N^2)$. |
Single Pass / State Tracking (Current Streak) |
Broken Chain Link |
Walk through the string. If the current char's ASCII value is exactly previous + 1, increment your streak. Otherwise, "break the chain" and reset streak to 1. |
Write the string. Draw a solid line under consecutive characters. Break the line when the sequence fails. Write the length above each line segment. |
Linear Line with Checkmarks |
Draw a single straight line from 0 to N. Above it, draw small constant time checkmarks. Label $O(N)$ Time. |
Draw overlapping string allocations for every substring checked. $O(N)$ or $O(1)$ depending on implementation. |
Draw two small boxes: `max_len` and `curr_len`. $O(1)$ Space. |
| 2415 |
Reverse Odd Levels of Binary Tree |
Traverse the tree level by level. Extract odd level values into an array, reverse the array, then traverse again to overwrite the node values. |
Extraction & Insertion Funnel |
Draw a tree. Draw arrows pulling nodes out into a horizontal array block. Draw an arrow reversing it, then pushing values back into the tree. $O(N)$ Time. |
DFS/BFS with Symmetrical Dual-Pointers |
Mirror Reflection Traversal |
Start at children of root (left, right). Swap their values (Level 1). For the next level, pass (left.left, right.right) and (left.right, right.left). Swap if level is odd. |
Draw a perfect binary tree. Draw curved double-headed arrows swapping nodes at level 1. Then draw curved arrows swapping outer nodes, and inner nodes at level 3. |
Symmetrical Descent Paths |
Draw a tree outline. Draw two arrows descending simultaneously down opposite sides of the tree. Label $O(N)$ Time. |
Draw a large array queue storing $O(N)$ node values for reversal. $O(N)$ Space. |
Draw a deep stack representing $O(\log N)$ recursive depth for a balanced tree. |
| 2416 |
Sum of Prefix Scores of Strings |
For every string, extract all its prefixes. For every prefix, loop through the entire array of strings to count how many start with that prefix. |
N x N String Matching Web |
Draw a list of strings. From each prefix of String A, draw lines checking against every other string in the list. Label $O(N^2 \cdot L)$ where L is string length. |
Trie (Prefix Tree) with Frequency Counters |
Weighted Prefix Tree (Trie) |
Phase 1: Insert all strings into a Trie. Every time you pass through a node, increment its `count`. Phase 2: For each string, walk its path in the Trie and sum up the `count` of all visited nodes. |
Draw a Trie tree structure. Inside each node circle, write a number (the count of times it was visited). Draw a highlighted path down the tree, showing a running sum of those numbers. |
Trie Traversal Path |
Draw a root node branching into paths. Label "Build Trie: $O(N \cdot L)$". Draw a line walking down a path. Label "Search: $O(N \cdot L)$". Total $O(N \cdot L)$. |
Draw massive arrays holding thousands of substring copies. $O(N \cdot L^2)$ Space. |
Draw a Trie structure graph. Label $O(N \cdot L)$ space representing the Trie nodes and character arrays. |
| 2417 |
Closest Fair Integer |
Increment 'n' one by one. For each number, count even and odd digits to see if they are equal. |
Brute Force Incrementer |
Draw a number line. Tick off every number until a "fair" one is hit. Label $O(\text{Search Distance})$. |
Digit DP / Constructive Greedy |
Digit Slot Filling |
If 'n' has odd number of digits, the next fair integer must have one more digit (e.g., 100011). Otherwise, try modifying digits from left to right. |
Draw slots [ ][ ][ ][ ]. Fill half with even, half with odd. If sum of digits must be >= N, find the first position to increment. |
Logarithmic Digit Scan |
Draw a box for each digit. Label $O(Log10 N)$. |
$O(1)$ |
$O(Log10 N)$ to store digit counts. |
| 2418 |
Sort the People |
Use a basic Bubble Sort or Selection Sort. Find the tallest height, swap it to the front of the heights array, and simultaneously swap the corresponding names in the names array. |
Parallel Array Swapping |
Draw two arrays side-by-side (names, heights). Draw looping crossing lines over them indicating $O(N^2)$ nested swaps across both structures. |
Hash Map Binding / Array of Objects + Sort |
Key-Value Zipper |
Zip the names and heights together into a Map or pairs. Sort these pairs based on the height value in descending order. Unzip the sorted names into a final array. |
Draw a 2-column table (Height, Name). Draw a big downward arrow on the Height column labeled "Sort Descending", pulling the attached Names along with it. |
Standard Sorting Block |
Draw a single large block labeled "Sort Algorithm". Label $O(N \log N)$ Time. |
Draw $O(1)$ space, as swaps happen in-place within the existing arrays. |
Draw an array of Tuple/Pair objects or a Hash Map. Label $O(N)$ extra Space for the mapping. |
| 2419 |
Longest Subarray With Maximum Bitwise AND |
Nested loops checking every possible subarray. Calculate the bitwise AND of each and keep track of the max value and its length. |
Nested Matrix Sweep |
Draw a matrix where row = start, col = end. Fill with AND results. Label $O(N^2)$. |
Linear Scan (Max Property Observation) |
Peak Island Finder |
The max AND value is just the max element in the array. Pass once to find max. Pass again to find the longest consecutive streak of that max value. |
Draw the array. Circle the highest numbers. Draw a bracket around the longest consecutive group of those circled numbers. |
Linear Timeline |
Draw a single horizontal line from 0 to N. Label $O(N)$ Time. |
Draw multiple variables storing AND results for every index pair. |
Draw three variables: `max_val`, `current_streak`, `max_streak`. $O(1)$ Space. |
| 2420 |
Find All Good Indices |
For every index 'i', run two loops: one 'k' steps back to check if non-increasing, and one 'k' steps forward to check if non-decreasing. |
Double-Sided Search Arms |
Draw an index 'i'. Draw two long arrows extending k units in both directions. Repeat for all N indices. Label $O(N \cdot K)$. |
Prefix/Suffix Dynamic Programming (Precomputation) |
Dual Waveform Precomputation |
Pre-calculate `left[i]` (streak of non-increasing ending at i) and `right[i]` (streak of non-decreasing starting at i). An index is 'good' if left[i-1] >= k and right[i+1] >= k. |
Draw two arrays below the original. One fills streaks left-to-right, one right-to-left. Highlight indices where both corresponding cells are >= k. |
Parallel Precompute Blocks |
Draw two horizontal bars (prefix and suffix). Label "Precompute: $O(N)$". Label "Final Scan: $O(N)$". Total $O(N)$. |
Draw a simple results list. $O(1)$ extra beyond output. |
Draw two auxiliary arrays of size N. Label $O(N)$ Space. |
| 2421 |
Number of Good Paths |
From every node, run a DFS/BFS to find all paths where all nodes in the path have values less than or equal to the endpoints. |
Recursive Spiderweb Growth |
Draw a graph. From every node, draw paths branching out. Label $O(N^2)$ or $O(N \cdot (N+E)$). |
Disjoint Set Union (DSU) + Sorting by Value |
Bottom-Up Graph Construction |
Sort nodes by value. Add nodes and their edges to the DSU one by one. When connecting two components, the number of "good paths" is the product of how many nodes in each component have that current max value. |
Draw nodes in clusters. As you add a node, draw lines to neighbors with smaller/equal values. Inside each DSU bubble, track `[maxValue: count]`. |
DSU Union-Find Path |
Draw N nodes. Label sorting $O(N \log N)$. Draw edges being added with α(N) complexity. Total $O(N \log N)$. |
Draw deep recursion stacks for DFS on every node. $O(N)$ Depth. |
Draw the DSU `parent` array and a `count` map/array. Label $O(N)$ Space. |
| 2422 |
Merge Operations to Make Array Palindrome |
Recursive backtracking: in each step, either merge the first two elements, the last two, or both. Check if the resulting array is a palindrome. |
Exponential Merge Tree |
Draw a root array. Branch into "Merge Left" or "Merge Right". Label $O(2^N)$. |
Two Pointers (Greedy) |
Inward Squeeze Collapsing |
Start `L` at 0 and `R` at N-1. If `arr[L] == arr[R]`, move both inward. If `arr[L] < arr[R]`, merge `arr[L]` with `arr[L+1]`. Else, merge `arr[R]` with `arr[R-1]`. |
Draw two fingers at the ends of the array. If the numbers are unequal, draw a circle around the smaller one and its neighbor to "glue" them together. |
Linear Converging Scan |
Draw one line from both ends meeting in the middle. Label $O(N)$ Time. |
Stack depth $O(N)$. |
Two integer pointers. $O(1)$ Space. |
| 2423 |
Remove Letter To Equalize Frequency |
Try removing every single character one by one. For each removal, recount all frequencies and check if they are all equal. |
N-Iteration Brute Check |
Draw the string. Under each char, draw a "check" arrow to a full frequency-count operation. Label $O(N \cdot 26)$. |
Frequency of Frequencies (Count Map) |
Frequency Histogram Levelling |
Count character frequencies. Then, count the frequency of those counts. There are only a few cases (e.g., all same, one char occurs once, one char occurs one more time than others) where removing one char works. |
Draw a frequency map (a:2, b:2, c:3). Draw a secondary map (2:2, 3:1). See if adjusting one "3" to a "2" makes the map uniform. |
Constant Constant Scan |
Draw a 26-slot array. Label $O(26)$ or $O(1)$ Time since alphabet size is fixed. |
Draw a new frequency array for every iteration. $O(26)$. |
Draw two small 26-slot arrays/hash maps. $O(1)$ Space. |
| 2424 |
Longest Uploaded Prefix |
Every time a "longest" query is made, iterate from the last known prefix + 1 to see how many consecutive numbers exist in the "uploaded" set. |
Step-by-step Pointer Reset |
Draw a number line. For every query, draw an arrow starting from 1. Label $O(Q \cdot N)$ worst case. |
Persistent Pointer (Amortized Analysis) |
Water Level Rising |
Use a boolean array for uploads. Keep a `max_prefix` variable. Only move it forward when the next number is uploaded. It never moves backward. |
Draw an array of boxes. When a number is uploaded, put an 'X' in its box. Keep an arrow 'P' that only slides right when the box it’s looking at gets an 'X'. |
Amortized Linear Line |
Draw a single line 1 to N. The pointer 'P' only travels this line once across ALL queries. Label $O(N)$ total = $O(1)$ amortized. |
Draw a HashSet or Boolean array of size N. |
Draw a single Boolean array and one integer variable. $O(N)$ Space. |
| 2425 |
Bitwise XOR of All Pairings |
Iterate through every element in nums1 and every element in nums2. Calculate XOR for every pair and accumulate in a running XOR total. |
N x M Bipartite Web |
Draw two columns of nodes. Draw lines from every node in A to every node in B. Label $O(N \cdot M)$ total lines. |
XOR Parity Property (Even/Odd Counts) |
Cancellation Pulse |
If nums2.length is even, every element in nums1 is XORed an even number of times (cancels to 0). If odd, XOR the element. Apply same logic to nums2. |
Draw the two arrays. Write "Count" next to them. If Count is even, draw a big '0' or cross out the array. If odd, draw a 'Σ' (XOR sum) symbol. |
Dual Linear Scan Line |
Draw two separate lines representing the pass through each array. Label $O(N + M)$ Time. |
Draw a massive list of all pairing results (if stored). $O(N \cdot M)$. |
Draw one integer variable `result`. $O(1)$ Space. |
| 2426 |
Number of Pairs Satisfying Inequality |
Nested loops to check every pair (i, j) where i < j and see if nums1[i] - nums1[j] <= nums2[i] - nums2[j] + diff. |
Upper Triangle Matrix |
Draw a grid of pairs. Shade the top-right half. Label $O(N^2)$. |
Merge Sort (Divide & Conquer) or Fenwick Tree after transforming to (nums1[i]-nums2[i]) |
Sorted Segment Comparison |
Rearrange to: (nums1[i]-nums2[i]) <= (nums1[j]-nums2[j]) + diff. While merging two sorted halves, count how many elements in the left half satisfy the condition for elements in the right. |
Draw two sorted blocks side by side. Draw a sliding pointer on the left block that counts how many values are <= (right_val + diff). |
Recursive Tree height Log N |
Draw a Merge Sort tree. At each level, label "O(N)". Total height is Log N. Label $O(N \log N)$. |
Draw a single integer result. $O(1)$. |
Draw the recursion stack and temporary arrays for merging. Label $O(N)$ Space. |
| 2427 |
Number of Common Factors |
Iterate from 1 up to the smaller of 'a' and 'b'. For each number, check if both 'a' and 'b' are divisible by it. |
Linear Search Line |
Draw a line from 1 to Min(a, b). Draw a "Check" box at every integer. Label $O(\text{Min}(a, b)$). |
GCD + Factor Counting |
Greatest Common Divisor Reduction |
Find G = GCD(a, b). Any common factor of a and b is simply a factor of G. Find G, then find all its factors up to sqrt(G). |
Draw 'a' and 'b' as overlapping circles. Draw their intersection as 'G'. Draw a tree of factors for 'G'. |
Logarithmic GCD + Square Root Scan |
Draw a small box for GCD (Log N) and a short line for factors (sqrt(G)). Label $O(\log(\text{min}(a,b)$) + sqrt(G)). |
Draw one counter variable. $O(1)$. |
Draw one GCD variable and a loop counter. $O(1)$ Space. |
| 2428 |
Maximum Sum of an Hourglass |
Iterate through every possible 3x3 center. For each, manually add all 7 elements that form the hourglass shape. |
Scanning Window Mesh |
Draw a grid. Draw an 'I' shape and show it shifting cell by cell. Label $O(R \cdot C)$. |
Sliding Window (Optimised Summing) |
Template Overlay Scan |
Since the hourglass is small (7 cells), a direct sum is essentially $O(1)$ per center. Standard iteration is already optimal at $O(R \cdot C)$. |
Draw the grid. Draw one hourglass. Use an arrow to show it shifting one column. Show which cells are "dropped" and which are "added". |
Grid Traversal Area |
Draw a rectangle with area R*C. Label $O(R \cdot C)$. |
Draw the input matrix in memory. $O(R\cdot C)$. |
Draw only one `maxSum` variable. $O(1)$ extra Space. |
| 2429 |
Minimize XOR |
Check every number 'x' from 0 upwards. Calculate its set bits. If set bits match nums2, calculate x XOR nums1. Keep the minimum. |
Exhaustive Number Line Search |
Draw a number line. Draw a checkmark at every integer up to a very large N. Label $O(\text{Brute Search})$. |
Greedy Bit Construction |
Bitwise Priority Fill |
Count set bits in nums2 (say 'k'). To minimize XOR with nums1, try to copy '1's from nums1 to 'x' from MSB to LSB. If you have bits left, fill from LSB to MSB in empty spots. |
Draw 32 boxes for bits. Write binary of nums1. Below it, place '1's in 'x' wherever nums1 has '1' (starting from left). If you run out of 'k', stop. If you have extra 'k', fill from right. |
Constant 32-Bit Scan |
Draw a box with 32 slots. Label $O(32)$ or $O(\log N)$. |
Draw multiple tracking variables. $O(1)$. |
Draw one 32-bit integer. $O(1)$ Space. |
| 2430 |
Maximum Deletions on a String |
Recursive backtracking: try every possible prefix length 'i'. If prefix matches next 'i' chars, delete and recurse. |
Recursive Tree Branches |
Draw a root string. Branch out for every possible valid deletion. Label $O(2^N)$. |
DP + Longest Common Prefix (LCP) with Rolling Hash or Suffix Array |
LCP Overlap Matrix |
Let `dp[i]` be max deletions for suffix starting at `i`. `dp[i] = max(1 + dp[i+j])` if `LCP(i, i+j) >= j`. Calculate LCP in $O(1)$ using precomputed $O(N^2)$ table. |
Draw a 1D DP array. For each cell `i`, draw arrows to cells `i+j` only if the string repeats. Use a precomputed LCP grid to validate arrows instantly. |
Quadratic DP Grid |
Draw an N x N matrix for LCP precomputation. Label $O(N^2)$ Time. |
Draw recursive call stacks of depth N. $O(N)$. |
Draw an N x N LCP table and a 1D DP array. Label $O(N^2)$ Space. |
| 2431 |
Maximize Total Tastiness of Purchased Fruits |
Try every combination of buying, skipping, or using a coupon for each fruit. (Recursive Backtracking). |
3-Way Ternary Decision Tree |
Draw a root node splitting into 3 branches. Each level represents a fruit. Label $O(3^N)$ total paths. |
3D Dynamic Programming (Knapsack Variant) |
Layered 2D Budget-Coupon Matrix |
`dp[i][j][k]` is max tastiness using `i` fruits, `j` money, and `k` coupons. For each fruit, decide: skip, buy full, or buy half. |
Draw a stack of 2D grids. Each grid represents 'Number of Coupons Used'. In each cell, store max tastiness for (money, items). |
Volume Space Block |
Draw a cube (N x Money x Coupons). Label $O(N \cdot M \cdot C)$. Total operations are volume of the cube. |
Draw a recursion stack of depth N. $O(N)$. |
Draw a 3D array block (or 2D if space-optimized). Label $O(M \cdot C)$ space. |
| 2432 |
The Employee That Worked on the Longest Task |
For every log entry, subtract the previous entry's time from the current. Store all durations, then sort to find the max. |
Interval Mapping List |
Draw a timeline. Mark points. Draw segments between points. Label $O(N \log N)$ if sorting, $O(N)$ if scanning. |
Single Pass Tracking (Max/Min Greedy) |
Running Record Holder |
Keep track of `lastStartTime` (starts at 0). For each log: calculate `duration = time - lastStartTime`. Update global max and ID. Update `lastStartTime`. |
Draw a table with columns: ID, Duration, MaxDuration, BestID. Fill row by row as you read logs. |
Single Horizontal Arrow |
Draw a line from 0 to N logs. Label $O(N)$ Time. |
Draw an array storing all durations. $O(N)$ Space. |
Draw two variables: `maxDur` and `resultID`. $O(1)$ Space. |
| 2433 |
Find The Original Array of Prefix XOR |
For each index `i`, solve the equation `pref[i] = A[0] ^ A[1] ^ ... ^ A[i]` by testing all possible numbers for `A[i]`. |
Iterative Equation Solver |
Draw a chain of XOR symbols. For each link, show a search for the missing piece. Label $O(N \\text{cdot Range})$. |
XOR Inverse Property |
Bitwise Difference Chain |
Since `pref[i] = pref[i-1] ^ A[i]`, then `A[i] = pref[i] ^ pref[i-1]`. Just XOR adjacent elements. |
Draw the `pref` array. Draw a 'V' shape between `pref[i]` and `pref[i-1]`. Put an XOR symbol in the V and write the result below. |
Linear Stream XOR |
Draw a single line with XOR gates between indices. Label $O(N)$ Time. |
Draw a workspace for testing values. $O(1)$. |
Draw the result array `A`. $O(N)$ (or $O(1)$ if modifying in place). |
| 2434 |
Using a Robot to Print the Lexicographically Smallest String |
Try every possible sequence of "Push to Stack" and "Pop from Stack" to generate all permutations, then pick the smallest. |
Catalan-Number Branching Tree |
Draw a stack 'S'. Branch out for every Push/Pop decision. Label $O(2^N)$. |
Greedy + Stack + Suffix Minimums |
Three-Stage Conveyor Belt |
Pre-calculate the smallest character remaining in the string (suffix min). If the top of the stack is ≤ current suffix min, pop it (it's the best we'll get). Otherwise, push current char. |
Draw three boxes: Input, Stack (vertical), Output. Write suffix mins below Input. Move letters from Input -> Stack -> Output using the rule. |
Linear Pass with Suffix Table |
Draw one line for suffix precomputation and one for robot simulation. Label $O(N)$ Time. |
Draw deep recursion frames for all states. $O(N)$. |
Draw a Stack structure and a Suffix Min array. Label $O(N)$ Space. |
| 2435 |
Paths in Matrix Whose Sum Is Divisible by K |
Use DFS to find every possible path from (0,0) to (m-1, n-1). Calculate sum of each and check `sum % k == 0`. |
Recursive Grid Flood |
Draw a grid. Draw every possible right/down path as a zig-zag line. Label $O(2^(M+N)$). |
3D Dynamic Programming (Grid + Modulo State) |
Modulo-Layered Grid |
`dp[r][c][rem]` is the number of paths to `(r,c)` with `sum % k == rem`. The answer is `dp[m-1][n-1][0]`. |
Draw a grid. In each cell, draw a small array of size `k`. Fill the array using the sums from top and left neighbors (shifted by current cell's value). |
Grid Volume Search |
Draw a 3D block (M x N x K). Label $O(M \cdot N \cdot K)$. Every cell in the grid takes K work. |
Draw a recursion stack. $O(M+N)$. |
Draw a 3D DP array (or 2D + K if space-optimized). Label $O(M \cdot N \cdot K)$ Space. |
| 2436 |
Minimum Split Into Subarrays With GCD Greater Than One |
Test all subarray splits using backtracking, calculating the GCD for every segment from scratch. $O(2^N \cdot N)$. |
Recursive Split & Recalculate |
Draw an array. Put a divider at index 1. Calculate GCDs. Move divider to index 2. Calculate again. |
Greedy / Running GCD |
The GCD Collapse Boundary |
Iterate through the array maintaining a running GCD. When the `GCD(current_running_gcd, nums[i]) == 1`, you MUST split the array here. Reset the running GCD to `nums[i]` and increment the subarray count. |
Draw the array. Keep a "Current GCD" box. For each number, merge it into the box. If the box turns into '1', draw a hard vertical wall, count it, and put the current number into a fresh box. |
Linear Scan $O(N \log(\text{Max}_\text{Val})$) |
Draw a single straight line. The log factor comes from the Euclidean algorithm at each step. |
Array slices and deep recursion. |
A single integer tracking the running GCD. $O(1)$ space. |
| 2437 |
Number of Valid Clock Times |
Iterate through all 1440 possible minutes in a 24h day (00:00 to 23:59). For each, check if it matches the pattern with '?'. |
Complete Search Timeline |
Draw a clock face with a sweep line covering all 1440 ticks. Label $O(1440)$ which is $O(1)$. |
Rule-Based Combinatorics (Independent Slots) |
Permutation Slots |
Break the time into HH and MM. Calculate options for HH based on '?' positions (taking 24 into account) and MM (60). Multiply the two results. |
Draw 4 empty slots: [ ][ ] : [ ][ ]. Write the number of possibilities in each box based on the characters. Draw an 'X' (multiply) between them. |
Decision Tree (Fixed Depth) |
Draw a small tree with 4 levels. Label $O(1)$ Time as it depends only on 5 characters. |
Draw a string buffer for pattern matching. |
Draw 2-3 integer variables. $O(1)$ Space. |
| 2438 |
Range Product Queries of Powers |
For each query [left, right], iterate from left to right in the powers array and calculate the product modulo 10^9 + 7. |
Nested Query Iteration |
Draw the powers array. Below it, draw multiple brackets representing queries, some overlapping. Label $O(Q \cdot N)$. |
Precomputation (Prefix Products) |
Cumulative Product Array |
Decompose 'n' into powers of 2. Create an array of these powers. Precompute prefix products such that product(L, R) = Prefix[R] / Prefix[L-1]. *Note: Use modular inverse if needed, or simple product since N is small.* |
Draw the powers array. Draw a second "Prefix" array below it where each cell is the product of everything to the left. Circle two indices to show the division/subtraction logic. |
Linear Precompute + $O(1)$ Query |
Draw one long bar (Precompute: $O(\log N)$) and small dots (Queries: $O(Q)$). Label $O(\log N + Q)$. |
Draw one result variable. |
Draw an array of size log(N) (approx 30-32). $O(\log N)$ Space. |
| 2439 |
Minimize Maximum Value in Array |
Use Binary Search on the answer. For a target 'X', iterate through the array to see if you can reduce all elements to ≤ X by moving values left. |
Binary Search Range Shrinking |
Draw a number line from Min to Max. Draw a "guess" pointer moving left/right. Inside each guess, show a linear scan. Label $O(N \log(\text{Max})$). |
Prefix Sum Average (Greedy Ceiling) |
Water Levelling in Containers |
As you move through the array, the values can only move left. Thus, for any prefix, the best you can do is distribute the total sum evenly. Max value is `ceil(PrefixSum / (i+1))`. |
Draw bar charts of different heights. Draw an arrow showing "fluid" moving from right-side bars to left-side bars. The max height is the highest average seen so far. |
Single Pass Line |
Draw a single horizontal arrow across the array. Label $O(N)$ Time. |
Draw binary search state variables. |
Draw one `prefixSum` and one `maxResult` variable. $O(1)$ Space. |
| 2440 |
Create Components With Same Value |
Try every possible way to delete edges from the tree and check if all resulting components have the same sum. |
Exponential Edge Cutting (2^E) |
Draw a tree. Draw scissors cutting different combinations of edges. Label $O(2^N)$. |
Divisor Search + Post-order DFS |
Subtree Sum Sieve |
Total sum must be divisible by the component sum `S`. For each divisor `S`, run a DFS. If a subtree sum equals `S`, "cut" the edge (reset sum to 0). Check if all pieces = `S`. |
Draw the tree. Write subtree sums at each node. If a node hits the target `S`, draw a big 'X' on its parent edge and write '0' for the node's contribution upward. |
Factor-Count DFS |
Draw one DFS arrow. Label $O(\text{Divisors} \cdot N)$. |
Recursion stack $O(N)$. |
Adjacency list. $O(N)$ Space. |
| 2441 |
Largest Positive Integer That Exists With Its Negative |
Nested loops: for every positive number, search the rest of the array for its negative counterpart. Track the max positive found. |
All-Pairs Matching |
Draw nodes representing numbers. Draw lines connecting every 'x' to every 'y'. Label $O(N^2)$. |
Hash Set / Two Pointers (after Sort) |
Mirror Search in a Set |
Add all numbers to a Hash Set. Iterate through the array again; if `num > 0` and `-num` is in the set, update the max. |
Draw an array and a "Bucket" (Set). Drop all numbers into the bucket. Then, point at a number in the array and "look inside" the bucket for its mirror. |
Parallel Scan & Lookup |
Draw a line for the set build and a line for the lookup. Label $O(N)$ Time. |
Draw a max_val variable. |
Draw a Hash Set structure containing N elements. $O(N)$ Space. |
| 2442 |
Count Number of Distinct Integers After Reverse Operations |
For each number, convert to string, reverse, convert back, and add both original and reversed to a list. Finally, sort the list and count unique. |
String-Conversion Pipeline |
Draw a number -> String -> Reversed String -> number flow for every element. Label $O(N \cdot \log10(\text{val})$). |
Digit Manipulation + Hash Set |
Numerical Mirroring Set |
Use modulo/division to reverse the integer mathematically. Add the original and the mirror directly into a Hash Set. The Set size is the answer. |
Draw a set (circle). Point to a number '123'. Write '123' in the set. Mentally flip it to '321' and write it in the set. Move to next. |
Single Pass with $O(1)$ Reverse |
Draw a line through N elements. Each element has a small constant-time math block. Label $O(N)$. |
Draw a large temporary list of 2N strings. $O(N)$. |
Draw a Hash Set storing up to 2N integers. $O(N)$ Space. |
| 2443 |
Sum of Number and Its Reverse |
For a given number `n`, iterate `i` from 0 to `n`. Reverse `i` and check if `i + reverse(i) == n`. |
Full Range Search |
Draw a number line from 0 to `num`. At each point, perform a reversal math check. Label $O(N)$. |
Math (Direct Search is already efficient given N <= 10^5) |
Mirror Sum Scanner |
Since N is small, a simple loop is optimal. For each `i`, calculate its reverse mathematically. Check the sum condition and exit early if found. |
Draw a number `i` and its mirror `i'`. Draw a '+' sign between them and an '==' sign pointing to `num`. Repeat for `i+1`. |
Linear Iteration Block |
Draw one straight line across the search space. Label $O(N)$. |
Draw a variable for current `i`. |
Draw integer variables: `i`, `rev_i`, `temp`. $O(1)$ Space. |
| 2444 |
Count Subarrays With Fixed Bounds |
Nested loops checking every subarray (i, j). For each, scan to see if min equals 'minK' and max equals 'maxK', and no element is outside [minK, maxK]. |
Triple Nested Loop Grid |
Draw a 3D-like stack of arrays. Label $O(N^3)$ (Subarrays * verification scan). |
Three-Pointer Sliding Window (Tracking Indices) |
Elastic Boundary Snap |
Keep 3 indices: last invalid, last minK, last maxK. Valid subarrays ending at 'i' start anywhere between 'lastInvalid' and 'min(lastMin, lastMax)'. |
Draw the array. Use three colored arrows (Red for invalid, Blue for minK, Green for maxK). At each step, count = max(0, min(Blue, Green) - Red). |
Single Pass Line |
Draw a single horizontal arrow from 0 to N. Label $O(N)$ Time. |
Draw a results variable. |
Draw three integer variables in memory. $O(1)$ Space. |
| 2445 |
Number of Nodes With Value One |
For every query, run a DFS to flip the value of the node and all its descendants. $O(Q \cdot N)$. |
Overlapping Triangle Flips |
Draw a tree. For each query, shade a massive triangle under a node. Massive overlapping shades. |
Prefix Sum on Trees (Parity) |
The Falling Tally |
Count how many times each node is queried (flipped). Run one DFS from the root, passing down the total flips. Node value is (flips % 2). |
Draw the tree. Write query counts next to nodes. Draw an arrow dropping from root to leaves, accumulating the sum. If sum is odd, write '1'. |
Single DFS Pass $O(N + Q)$ |
Draw a timeline for recording queries, then a single line tracing the tree top-to-bottom. |
Multiple full-tree traversals. |
Array of query frequencies. $O(N)$ space. |
| 2446 |
Determine if Two Events Have Conflict |
Convert times to minutes. Generate a list of all minutes for Event 1 and check if any exist in Event 2's list. |
Set Intersection Plot |
Draw two circles with thousands of points inside. Check for common points. Label $O(\text{Time}_\text{Range})$. |
String Comparison / Line Overlap |
Segment Collision Check |
Events conflict if Event1_Start <= Event2_End AND Event2_Start <= Event1_End. String comparison works directly for "HH:MM". |
Draw two horizontal lines. Label Start/End for each. Check if the start of one is before the end of the other and vice-versa. |
Boolean Comparison Box |
Draw a single decision box with 2 comparisons. Label $O(1)$ Time. |
Draw a boolean array of 1440 minutes. |
Draw four string variables. $O(1)$ Space. |
| 2447 |
Number of Subarrays With GCD Equal to K |
Nested loops (i, j). Maintain a running GCD for the subarray. If current GCD < K, break (it can't recover). If GCD == K, increment count. |
Pruned Nested Search |
Draw a right triangle (N^2). Color the cells that get "broken" early by the GCD property. Label $O(N^2 \cdot \log(\text{MaxVal})$). |
Optimal Brute (Observation: GCD only decreases) |
Stepping Stone Reduction |
Since GCD can only stay the same or decrease as you add numbers, you can't optimize much further than $O(N^2)$, but you can stop early when GCD < K. |
Draw an array. Under index 'i', draw a chain of GCD results. Stop drawing the chain as soon as a number < K appears or GCD becomes < K. |
Sum of Arithmetic Series |
Draw a triangle. Label $O(N^2)$. Note: For larger constraints, use a Map to track "count of current GCDs" in $O(N \cdot \log(\text{MaxVal})$). |
Draw one running GCD variable. |
Draw a variable for count and current GCD. $O(1)$ Space. |
| 2448 |
Minimum Cost to Make Array Equal |
Try making all elements equal to every possible value between min(nums) and max(nums). Calculate total cost for each. |
Cost Function Curve (Convex) |
Draw a U-shaped curve. Label the x-axis as "Target Value". Label $O(N \\text{cdot Range})$. |
Weighted Median / Binary Search on Answer |
Gravity Center (Balance Point) |
Sort pairs (val, cost). Find the "weighted median"—the point where the cumulative cost weight reaches half of the total cost weight. |
Draw a number line with "weights" (costs) hanging off each number. Find the point where the scale balances. |
Sort + Single Pass |
Draw a sorting block (N log N) followed by a line (N). Label $O(N \log N)$ Time. |
Draw cost variables for every target. |
Draw an array of pairs (val, cost). $O(N)$ Space. |
| 2449 |
Minimum Number of Operations to Make Arrays Similar |
Recursively try +/- 2 on every element to match the target array. $O(\text{Exponential})$. |
Exploding +/- 2 Tree |
Draw a number. Branch it up by 2 and down by 2 infinitely until it hits a target. |
Sorting + Parity Segregation |
The Odd/Even Parallel Tracks |
Since you can only add/sub 2, evens stay even, odds stay odd. Split both arrays into Odd and Even lists. Sort all 4 lists. Compare them index by index, summing positive differences and dividing by 2. |
Draw two funnels: "Evens" and "Odds". Pour nums inside. Sort them. Draw straight horizontal lines connecting `sorted_nums[i]` to `sorted_target[i]`. |
Sorting Bottleneck $O(N \log N)$ |
Draw a merge-sort tree, followed by two parallel linear scans. |
Deep recursive stack. |
Two separate arrays for Odds and Evens. $O(N)$ space. |
| 2450 |
Number of Distinct Binary Strings After Operations |
Manually simulate flipping substrings of length 'k' and store all resulting strings in a Set. |
Set-based Simulation (2^N) |
Draw a binary string. Branch for every possible 'flip' at every index. Label $O(2^N)$. |
Mathematical Observation (Powers of 2) |
Independent Decision Slots |
Each operation at index `i` is independent. There are `n - k + 1` possible starting positions for the flip. Each position doubles the unique combinations. Answer: `2^(n-k+1) % MOD`. |
Draw a string. Draw a sliding box of length K. Count how many positions the box can start in. Each position is a bit in a new virtual string. |
Logarithmic Exponentiation |
Draw a `pow(2, x)` box. Label $O(\log N)$. |
Set storage of $O(2^N)$. |
$O(1)$ extra space. |
| 2451 |
Odd String Difference |
For every string, calculate its difference array. Store all arrays in a list. Run nested loops to compare every array with every other array to find the one that is different. |
Difference Array Comparison Matrix |
Draw strings. Next to them, draw their [n-1] diff arrays. Draw lines comparing every array. Label $O(N^2 \cdot L)$. |
Hash Map Counting (Frequency of Arrays) |
Pattern Bucketing |
Convert each string to a difference string (comma-separated). Put them in a Map: `{diff_pattern: [count, original_string]}`. The one with count 1 is the answer. |
Draw a bucket for each unique pattern you see. Drop the strings into the buckets. Pick the string from the bucket that has only one occupant. |
Linear Pass + Map Ops |
Draw a line through N strings. Above it, show a Map lookup. Label $O(N \cdot L)$ Time. |
Draw massive lists of integer arrays. |
Draw a Map storing string keys. $O(N \cdot L)$ Space. |
| 2452 |
Words Within Two Edits of Dictionary |
For every query word, iterate through every dictionary word. Manually count the number of differing characters between them. |
Nested Search Matrix (M x N) |
Draw a grid where rows are queries and columns are dictionary words. Label each cell "O(L)" where L is word length. Total $O(M \cdot N \cdot L)$. |
Optimized Linear Scan (Early Exit) |
Char-by-Char Comparison Pipeline |
For each query, scan dictionary words. While comparing, if differences exceed 2, stop immediately and move to the next dictionary word. |
Write two words vertically aligned. Draw a line between differing characters. Use a counter (1, 2, STOP) to show the early exit logic. |
Bounded Nested Loop |
Draw a grid. Shade only the first few characters of failed matches. Label $O(M \cdot N \cdot L)$ worst case, but $O(M \cdot N)$ average. |
Draw a results list. |
Draw a single integer `diffCount` variable. $O(1)$ Space beyond output. |
| 2453 |
Destroy Sequential Targets |
For every number in the array, treat it as the starting point. Count how many other numbers 'x' satisfy (x - start) % space == 0. |
Quadratic Web of Modulo Checks |
Draw points on a line. From each point, draw arrows to all subsequent points checking the modulo condition. Label $O(N^2)$. |
Hash Map (Remainder Frequency) |
Modulo Remainder Bucketing |
Groups are formed by `nums[i] % space`. Map each remainder to its frequency and the minimum starting number found for that remainder. |
Draw a set of buckets labeled 0, 1, ... (space-1). Drop each number into the bucket corresponding to its remainder. The largest bucket wins. |
Two Linear Passes |
Draw one line for counting (O(N)) and one for finding the min element (O(N)). Label $O(N)$ Total. |
Draw a maxCount variable. |
Draw a Hash Map `{remainder: [count, min_val]}`. Label $O(N)$ Space. |
| 2454 |
Next Greater Element IV |
For each index 'i', run a nested loop to find the first index 'j' > i where nums[j] > nums[i], then another loop from 'j' to find the second greater element. |
Double Search Scan |
Draw an index. Draw an arrow finding the 1st peak, then a 2nd arrow finding the 2nd peak. Label $O(N^2)$. |
Two Monotonic Stacks + Priority Queue |
Sifting Stacks Conveyor |
Elements move from `Stack1` (no greater found) to `Stack2` (one greater found) to `Result` (two greater found). Use a Min-Heap for Stack2 to process multiple "pending" elements. |
Draw two vertical bins. When a new number is larger than Bin1's top, move the top to Bin2. If larger than Bin2's top, it's the 2nd greater; write it down. |
Amortized Linear Flow |
Draw a line with elements jumping between three containers. Every element enters and leaves each stack at most once. Label $O(N \log N)$ (due to heap/sorting). |
Draw a 1D result array. |
Draw two stacks and one Min-Heap. Label $O(N)$ Space. |
| 2455 |
Average Value of Even Numbers Divisible by Three |
Iterate through the array, check each number for `n % 2 == 0` and `n % 3 == 0`. Store matches in a list, then calculate average. |
Linear Filter and Sum |
Draw a line with a "Filter" box. Show numbers passing through or being blocked. Label $O(N)$. |
Single Pass (Running Sum and Count) |
Accumulator Funnel |
Condition `n % 2 == 0 && n % 3 == 0` is equivalent to `n % 6 == 0`. One pass, track `sum` and `count`. Answer is `sum / count`. |
Draw a single loop. Inside, draw two boxes: `S` (sum) and `C` (count). Add to them only if `n % 6 == 0`. |
Single Linear Line |
Draw a straight arrow from start to finish. Label $O(N)$ Time. |
Draw a temporary list to store filtered numbers. $O(N)$. |
Draw two integer variables: `sum` and `count`. $O(1)$ Space. |
| 2456 |
Most Popular Video Creator |
Nested loops: for each creator, sum all their view counts. Then for each creator, scan all their videos to find the one with the highest views (lexicographically smallest title for ties). |
Map + Multi-Scan |
Draw a list of creators. For each, draw a sub-list of videos. Label $O(N^2)$ if not using maps, or $O(N)$ with maps. |
Hash Map (Aggregate & Track Max) |
Leaderboard Tracking Map |
Use two maps. Map 1: `{creator: total_views}`. Map 2: `{creator: [max_video_views, video_id]}`. Update both in one pass through the input. |
Draw a table with columns: Creator, TotalViews, BestVideo, BestVideoViews. Update rows as you process each entry. Highlight rows with the highest TotalViews. |
Linear Map Aggregate |
Draw one straight line over the input list. Label $O(N)$ Time. |
Draw multiple tracking structures. |
Draw two Hash Maps storing up to N entries. Label $O(N)$ Space. |
| 2457 |
Beautiful Number / Minimum Addition to Make Integer Beautiful |
Keep adding 1 to 'n' and recalculate the digit sum until the sum is less than or equal to 'target'. |
Iterative Step Ladder |
Draw a number line. Draw tiny steps (n+1, n+2...). Label $O(10^\text{LogN})$ which is worst-case huge. |
Greedy Zero-ing (Place Value Increment) |
Right-to-Left Carry Wave |
If digit sum > target, round up to the next power of 10 (e.g., 467 -> 470 -> 500 -> 1000). Each step zeros out the last non-zero digit and carries the 1. |
Write the number. Circle the rightmost non-zero digit. Change it to 0 and add 1 to the digit to its left. Re-check the digit sum. Repeat. |
Digit-Length Scan |
Draw a box for each digit (max 12-15). Label $O(\log10(N)$) Time. |
Draw a loop counter. |
Draw 2-3 long-type variables. $O(1)$ Space. |
| 2458 |
Height of Binary Tree After Subtree Removal Queries |
For each query (node), physically or logically "remove" the subtree rooted at that node and perform a fresh DFS to calculate the tree height. |
Query-Wise Full Tree DFS |
Draw a tree. For Query 1, circle a node and draw red 'X's on its children. Redraw the tree. Label $O(Q \cdot N)$. |
DFS + Precomputation (Level-wise Max Depths) |
Symmetric DFS traversal with Shadow Tracking |
Record heights for all nodes. For each level, keep the top 2 maximum heights. If a removed node was the max, the new height uses the 2nd max. |
Draw the tree. For each node, write its depth and height. Group nodes by level. For each level, circle the two highest "height+depth" values. |
Double DFS Pass |
Draw two arrows over the tree (Pre-order and Post-order). Label $O(N)$ for precompute and $O(Q)$ for queries. Total $O(N + Q)$. |
Draw a recursion stack for every query. |
Draw Map/Arrays for: `node_height`, `level_max1`, `level_max2`. Label $O(N)$ Space. |
| 2459 |
Sort Array by Moving Items to Empty Space |
Standard BFS to find shortest path to target state. $O(N!)$. |
Factorial Graph Search |
Draw an array. Branch out to every possible array state achievable by swapping with 0. |
Graph Cycle Decomposition |
The Permutation Loop Tracker |
Treat the array as a graph of indices pointing to where elements *should* be. Find cycles. A cycle of length L takes L-1 swaps if 0 is inside it, or L+1 swaps if 0 must be brought in. Check two targets: 0 at start vs 0 at end. |
Draw the array. Draw an arrow from `nums[i]` to where it belongs. The arrows form loops. Count the nodes in each closed loop. |
Linear Cycle Tracing $O(N)$ |
Draw a single straight line visiting each element. Once an element is part of a cycle, mark it seen. |
Queue holding millions of array states. |
A single boolean 'visited' array. $O(N)$ space. |
| 2460 |
Apply Operations to an Array |
Iterate and modify. Then, create a new array and loop through the original twice: once to pick non-zeros and once to fill with zeros. |
Two-Pass Auxiliary Copy |
Draw two arrays. Show arrows moving non-zero elements to the top array. Label $O(N)$. |
In-Place Two-Pointer Swap |
Snowball/Zero-Bubble Pushing |
Step 1: If `nums[i] == nums[i+1]`, double `nums[i]` and zero `nums[i+1]`. Step 2: Use a write-pointer to overwrite non-zeros and fill the rest with zero. |
Draw the array. Use an 'R' (Read) and 'W' (Write) arrow. If R sees a number, move it to W and increment both. If R sees 0, only R moves. |
Single Pass Pointer Line |
Draw one line with two pointers moving left-to-right. Label $O(N)$ Time. |
Draw a second array of size N. $O(N)$. |
Draw the original array with two pointers. $O(1)$ extra Space. |
| 2461 |
Maximum Sum of Distinct Subarrays With Length K |
Nested loops: for every index `i`, check the subarray of length `k`. Check for distinctness using a Set and then sum. |
Nested Window Set-Check |
Draw the array. Draw a sliding bracket. Inside the bracket, draw a Hash Set. Label $O(N \cdot K)$. |
Sliding Window + Frequency Map (or Set) |
Distinct Sliding Window Accumulator |
Keep a running sum. Add new element, remove the oldest. Use a Map to track frequencies. If `map.size() == k`, it's a valid candidate for max. |
Draw the array with a box of size K. Write the running sum above. Maintain a list of counts for the numbers inside the box. Slide box right. |
Constant-Work Sliding Window |
Draw a single line. Draw a box moving right. Label $O(N)$ Time. |
Draw K-size arrays for every starting point. |
Draw a Hash Map and two sum variables. $O(K)$ Space. |
| 2462 |
Total Cost to Hire K Workers |
For each hiring round, scan the first `c` and last `c` workers, find the minimum, remove them, and repeat `k` times. |
N-Iteration Minimum Scan |
Draw an array. Circle the ends. Draw a scan arrow for each of the K rounds. Label $O(K \cdot N)$. |
Two Min-Heaps (Priority Queues) |
Double-Ended Priority Sifter |
Fill `leftHeap` with first `c` workers and `rightHeap` with last `c`. Compare roots. Pop the smaller, then pull the next available worker from the appropriate end. |
Draw two inverted trees (Heaps). Draw an array with two pointers moving toward the center. Show nodes moving from array to trees. |
K-Log-C Event Timeline |
Draw a line of K events. Each event is a Heap op (Log C). Label $O(K \log C)$. |
Draw one result variable. |
Draw two Min-Heaps of size C. $O(C)$ Space. |
| 2463 |
Minimum Total Distance Traveled |
Recursive backtracking: For every robot, try assigning it to every available factory and recurse for the remaining robots. |
Explosive Assignment Tree |
Draw a robot. Draw branches to all factories. Repeat for each robot. Label $O(F^R)$. |
DP (Sorted Robots & Factories) |
Monotonic Assignment Grid |
Sort robots and factories. `dp[i][j]` = min distance for `i` robots using `j` factories. Robots never "cross" each other in an optimal solution. |
Draw a grid where rows = Robots, cols = Factories. Fill cells by choosing between "Skip factory" or "Use factory for X robots." |
Quadratic DP Surface |
Draw an R x F matrix. Label $O(R \cdot F \\text{cdot Capacity}_\text{avg})$. Total $O(R \cdot F \cdot R)$. |
Draw massive recursion stacks. |
Draw an R x F 2D DP table. Label $O(R \cdot F)$ Space. |
| 2464 |
Minimum Subarrays in a Valid Split |
Generate all possible partitions of the array. For each partition, check if the GCD of the first and last element of every subarray is > 1. |
Exponential Partition Tree |
Draw a root node. Branch out for every possible "cut" in the array. Label $O(2^N)$. |
1D Dynamic Programming + GCD Check |
Stepping Stone Pathfinding |
`dp[i]` is the min subarrays to split prefix `0...i`. To find `dp[i]`, look at all `j < i` where `gcd(nums[j], nums[i]) > 1` and take `min(dp[j-1] + 1)`. |
Draw the array. For each index, draw backward-pointing arrows to indices where the GCD condition is met. Write the min-cost inside each array cell. |
Quadratic DP Scan |
Draw a 1D array of size N. From each cell, show up to N backward checks. Label $O(N^2 \cdot \log(\text{MaxVal})$). |
Draw a recursion stack of depth N. |
Draw a single 1D DP array of size N. $O(N)$ Space. |
| 2465 |
Number of Distinct Averages |
Find the min and max, calculate average, remove them, and repeat until empty. Store averages in a list, then sort and count unique. |
Iterative Shrinking Array |
Draw an array. Draw arrows pointing to min/max. Erase them. Repeat. Label $O(N^2)$ if searching for min/max every time. |
Sorting + Two Pointers |
Inward Squeeze Map |
Sort the array. Pair `arr[i]` with `arr[n-1-i]`. Calculate `(arr[i] + arr[j]) / 2` and insert into a Hash Set. The size of the set is the answer. |
Draw a sorted array. Draw an arrow at index 0 and index N-1. Move them toward the center one step at a time, writing the sum of the pointed values. |
Sorting Block + Linear Scan |
Draw a block labeled "O(N log N)" followed by a line labeled "O(N)". Total $O(N \log N)$. |
Draw the result list of averages. |
Draw a Hash Set containing up to N/2 values. $O(N)$ Space. |
| 2466 |
Count Ways To Build Good Strings |
Recursive backtracking: starting from length 0, branch out by adding 'zero' ones or 'one' ones until length reaches 'high'. Count valid paths. |
Binary String Growth Tree |
Draw a root 0. Branch 'zero' and 'one'. Repeat until height reaches 'high'. Label $O(2^(\text{high})$). |
1D Dynamic Programming (Climbing Stairs Variant) |
Incremental Length Accumulator |
`dp[i]` = number of ways to reach length `i`. `dp[i] = dp[i - zero] + dp[i - one]`. Sum values of `dp[low...high]`. |
Draw a line from 0 to 'high'. For a point 'i', draw two backward "jump" arrows of lengths 'zero' and 'one'. Add the values at the landing spots. |
Linear Iteration Line |
Draw a single straight line 0 to 'high'. Label $O(\text{high})$. |
Draw a recursion stack of depth 'high'. |
Draw a 1D array of size 'high'. $O(\text{high})$ Space. |
| 2467 |
Most Profitable Path in a Tree |
Find Bob's path to root first. Then, run a DFS for Alice to explore every leaf, checking the time Bob reaches each node to determine the split. |
Dual BFS/DFS Tree Traversal |
Draw a tree. Draw a blue path for Bob and a red path for Alice. At each node, write the time step. Label $O(N)$. |
Two-Pass DFS (Time Map + Profit DFS) |
Temporal Graph Overlay |
Pass 1: DFS from Bob's start to find his path and node arrival times. Pass 2: DFS for Alice. At each node, compare `Alice_time` vs `Bob_time` to decide reward/cost. |
Draw the tree. Mark Bob's path nodes with `t=0, 1, 2...`. While running Alice's DFS, compare her current depth with Bob's recorded time at that node. |
Linear Tree Traversal |
Draw two tree outlines with scan arrows. Label $O(N)$ Time. |
Draw the full adjacency list and Bob's path. |
Draw adjacency list and a `bobArrival` array. $O(N)$ Space. |
| 2468 |
Split Message Based on Limit |
Try every possible number of total parts `k` from 1 to 10,000. For each `k`, simulate the message split and check if it fits within the limit. |
Search by Simulation |
Draw a search range for 'k'. For each k, draw a split message. Label $O(K \\text{cdot Message}_\text{Length})$. |
Math (Suffix Length Precalculation) |
Suffix Suffix Metadata Fit |
The length of suffix `` changes at powers of 10. Calculate total suffix overhead for a given `k` mathematically. Find the smallest `k` where `Length(Message) + TotalSuffixLength <= Limit * k`. |
Write the equation: `k * limit - overhead >= len(msg)`. Draw a table of overheads for ranges (1-9, 10-99, etc.). |
Logarithmic/Linear Search for K |
Draw a search line for `k`. Label $O(k_\text{limit})$. Total $O(N + K)$. |
Draw multiple string builder buffers. |
Draw 1D result string list. $O(N)$ Space. |
| 2469 |
Convert the Temperature |
Directly apply the conversion formulas given in the problem description. |
Formula Application |
Draw an input 'C' and two output arrows to 'K' and 'F'. Label $O(1)$. |
Arithmetic Computation |
Static Flow Diagram |
Simply take the input float, add 273.15 for Kelvin, and multiply/add for Fahrenheit. Return as an array. |
Draw a box with 'Celsius' entering and an array `[K, F]` exiting. Write the formulas inside the box. |
Constant Time Box |
Draw a single box. Label $O(1)$. |
Draw two float variables. |
Draw an array of size 2. $O(1)$ Space. |
| 2470 |
Number of Subarrays With LCM Equal to K |
Nested loops to check every subarray. Calculate the LCM of each subarray iteratively. If LCM exceeds K, break early. |
Pruned Iterative Search |
Draw a 2D grid. Color cells where the inner loop breaks early because LCM > K. Label $O(N^2 \cdot \log(\text{max}_\text{val})$). |
Optimized Brute Force with LCM Early Exit |
LCM Accumulator Chain |
For each `i`, compute LCM with `nums[j]`. If `k % nums[j] != 0`, break (LCM will never be K). If `currLCM == k`, increment count. |
Draw the array. For each start index, draw a sequence of "LCM results." Mark an 'X' where the result becomes > K or indivisible. |
Sub-Quadratic Grid |
Draw an N x N matrix but shade only valid "factor" segments. Label $O(N^2)$. |
Draw one variable for current LCM. |
Draw one variable for total count. $O(1)$ Space. |
| 2471 |
Minimum Number of Operations to Sort a Binary Tree by Level |
Perform BFS. For each level, extract values, and for every value, search for its correct position and swap manually. |
Level-wise Selection Sort |
Draw a tree. Extract a level into an array. Show nested swap arrows for each level. Label $O(N^2)$ in worst case per level. |
BFS + Cycle Decomposition (Minimum Swaps) |
Permutation Cycle Mapping |
Extract level values. Sort them to know target positions. Map `value -> target_index`. Count cycles; swaps per cycle = `length - 1`. |
Draw the level array. Draw an arrow from each element's current index to its sorted index. Group arrows into "closed loops" (cycles). |
Linear-Log BFS + Sort |
Draw a tree BFS scan (O(N)). Next to it, a sorting block (O(N log N)). Label $O(N \log N)$. |
Draw a Queue and a temporary array for each level. |
Draw a Queue and a Map for cycle detection. $O(N)$ Space. |
| 2472 |
Maximum Number of Non-overlapping Palindrome Substrings |
Find all palindromes of length >= K. Use backtracking to find the maximum non-overlapping set. $O(N^3 + 2^P)$. |
Palindrome Combination Web |
Bracket every palindrome. Draw lines connecting valid non-overlapping sets. |
DP / Center Expansion + Greedy |
The Early-Exit Palindrome Grab |
Expand around centers to find palindromes. If you find one of length K or K+1, greedily take it! Continuing to expand it to K+5 doesn't help maximize the *count* of non-overlapping substrings. |
Draw the string. Pick a center. Expand. As soon as the bracket width hits K (or K+1 for even), snap it shut, count it, and jump your scanner past the end of that bracket. |
Linear Center Scan $O(N \cdot K)$ |
Draw a straight line for centers. The expansion is capped at K, making the inner loop strictly bounded. |
2D array of all palindromes. |
Pointers and a counter. $O(1)$ space. |
| 2473 |
Minimum Cost to Buy Apples |
Run Dijkstra from every single city independently to find the cheapest apple. $O(V \cdot E \log V)$. |
Redundant Ripple Grids |
Draw the graph. From City 1, draw expanding ripples. Erase. From City 2, draw ripples. Lots of repeated pathing. |
Multi-Source Dijkstra / Graph Reversal |
The Apple-Centric Collapse |
Create a "Super Source" connected to all cities with apples, weight = apple_cost. Run Dijkstra *backwards* from this super source. Or, initialize Dijkstra queue with ALL cities and their `apple_cost`. |
Draw a giant cloud (Super Source). Draw arrows dropping from the cloud down to every city holding an apple. Run the pathfinding outwards from there. |
Single Dijkstra $O(E \log V)$ |
Draw a standard log-height heap tree above a single scan of the edge list. |
V separate distance arrays. |
One priority queue and one distance array. $O(V)$ space. |
| 2474 |
Customers With Strictly Increasing Purchases (SQL) |
Self-joins checking `year = year + 1` iteratively. $O(N^2)$. |
Year-Over-Year Linking Chains |
Draw a customer. Draw an arrow from 2020 to 2021, then a separate check for 2021 to 2022. |
Window Functions (LAG / Difference) |
The Consecutive Delta Check |
Extract the Year. Group by Customer and Year. Use `LAG(price)` to get the previous year's total. Filter for `current > prev` and `current_year - prev_year == 1`. |
Draw a timeline. Write purchase totals above years. Draw a minus sign between adjacent years. If the result is positive AND years are consecutive, it passes. |
Sorting + Window Scan $O(N \log N)$ |
Draw a sorting pipeline, followed by a single read-head scanning the differences. |
Nested subquery tables in memory. |
Internal DB window buffer. $O(N)$ space. |
| 2475 |
Number of Unequal Triplets in Array |
Triple nested loops (i, j, k) to check every combination of three indices to see if all three values are different. |
Cubic Selection Cube |
Draw a 3D grid or a nested tree with 3 levels. Label $O(N^3)$. |
Frequency Counting + Combinatorics |
Weighted Triple Segment Split |
Count frequencies of each number. For a specific number with count `curr`, triplets = `(elements_before) * (curr) * (elements_after)`. |
Draw a frequency table. Draw three boxes: "Past", "Current", "Future". As you iterate through the table, slide frequencies between boxes and multiply. |
Linear Frequency Scan |
Draw a line through the unique elements of the array. Label $O(N)$ or $O(\text{Unique Elements})$. |
Draw three index variables. |
Draw a Hash Map or Frequency Array. $O(N)$ Space. |
| 2476 |
Closest Nodes Queries in a Binary Search Tree |
For each query, traverse the entire BST to find the closest smaller and larger values to the query integer. |
Query-Wise Full Tree Search |
Draw a tree. For each query, draw an arrow visiting every single node. Label $O(Q \cdot N)$. |
In-order Traversal + Binary Search (Sorted Array) |
Tree Flattening & Interval Search |
Convert the BST into a sorted array via in-order traversal. For each query, use binary search on the array to find indices of neighbors. |
Draw a tree. Below it, draw a straight line (array) where the tree nodes fall into place. Mark the query point 'x' on the line and identify neighbors. |
Linear Pre-processing + Log Query |
Draw a single line for traversal (O(N)) and log-steps for queries. Label $O(N + Q \log N)$. |
Draw the tree in memory. $O(N)$. |
Draw a sorted array of size N. $O(N)$ Space. |
| 2477 |
Minimum Fuel Cost to Report to the Capital |
Iterate through every possible road path. For every city, manually count passengers and simulate car assignments at every junction. |
Recursive Traffic Simulation |
Draw a graph. Draw individual car icons moving towards the center, recalculating at every intersection. Label $O(N^2)$ for naive re-calculations. |
DFS + Subtree Size Math |
Inward Flow Accumulation |
Perform DFS. For each node, the total people moving to its parent is `1 + sum(people from children)`. Fuel cost for this road is `ceil(people / seats)`. |
Draw a tree. At each node, write the count of people it "sends" upward. Draw fuel canisters on the edges based on `count/seats`. |
Single Tree Traversal |
Draw an arrow sweeping from leaves to root. Label $O(N)$ Time. |
Draw deep recursion frames. |
Draw the adjacency list and one `fuel` variable. $O(N)$ Space. |
| 2478 |
Number of Beautiful Partitions |
Use recursion to try every possible partition point that meets the "prime start/non-prime end" criteria. |
Decision Tree Branching |
Draw a root. At each beautiful split point, branch into all remaining split possibilities. Label $O(2^N)$. |
2D Dynamic Programming with Prefix Sum Optimization |
Layered Split-Grid |
`dp[i][j]` is ways to split prefix `i` into `j` parts. Use a prefix sum to calculate `dp[i][j]` from `dp[k][j-1]` in $O(1)$ time. |
Draw a grid (Indices x Number of Splits). Fill each cell by referencing a running sum of the previous split count row. |
Quadratic DP Surface |
Draw an N x K matrix. Label $O(N \cdot K)$. Each cell is filled in $O(1)$ via prefix sums. |
Draw a massive call stack. |
Draw a 2D DP array (or 1D space-optimized). $O(N \cdot K)$ Space. |
| 2479 |
Maximum XOR of Two Non-Overlapping Subtrees |
Find all subtree sums. For every pair of non-overlapping subtrees, calculate XOR. $O(N^2)$. |
Quadratic Subtree Comparison |
Draw the tree. For Node A, compare to Node B, C, D... checking overlap each time. |
DFS + Trie (Bitwise) |
The Boundary Trie Query |
1. DFS to get subtree sums. 2. DFS again to track max XOR. Keep a Trie of valid (non-overlapping) subtree sums. Add a branch to the Trie *after* processing its subtree to ensure no overlap. |
Draw the tree. On the right, draw a Trie (binary tree of 0s and 1s). As you leave a node in DFS, push its sum into the Trie. For the current node, query the Trie for the opposite bits. |
Tree Traversal + Trie Lookup $O(N \cdot 40)$ |
Draw a single tree trace. At each node, draw a quick 40-step descent down the Trie (constant time). |
2D array of all possible pair XORs. |
A Bit Trie of depth ~40. $O(N)$ space. |
| 2480 |
Form a Chemical Bond (SQL) |
Write complex subqueries separating Metals and Non-Metals, then joining them manually. $O(N^2)$. |
Manual Subquery Funnels |
Draw a table. Filter out Metals to a box. Filter Non-metals to a box. Manually draw lines between them. |
CROSS JOIN |
The Combinatorial Matrix |
Create two CTEs (or simple queries): one for Metals, one for Non-Metals. Use `CROSS JOIN` to generate all possible pairs. |
Draw a column of Metals and a row of Non-Metals. Draw a grid where they intersect, forming the bonds. |
Cartesian Product $O(N \cdot M)$ |
Draw two input lines entering a multiplication node. |
N/A |
Database result buffer. $O(N\cdot M)$ space. |
| 2481 |
Minimum Cuts to Divide a Circle |
Simulate drawing lines and counting pieces manually for various cases. |
Manual Geometric Case Study |
Draw circles and lines. Count the resulting pie slices. Label $O(1)$. |
Parity-Based Math (Even/Odd Geometry) |
Radial Symmetry Check |
If `n=1`, cuts=0. If `n` is even, cuts = `n/2` (lines cross the center). If `n` is odd, cuts = `n` (lines go from center to edge). |
Draw a circle. Draw 4 lines (8 pieces). Draw a circle. Draw 3 lines (3 pieces, center-to-edge). |
Constant Time Decision |
Draw a single decision diamond. Label $O(1)$. |
Draw a variable for n. |
Draw one integer result. $O(1)$ Space. |
| 2482 |
Difference Between Ones and Zeros in Row and Column |
For every cell (i, j) in the grid, manually iterate through its entire row and its entire column to count 1s and 0s. |
Scanning Crosshair Sweep |
Draw a grid. For one cell, draw a horizontal line and a vertical line. Label $O(M\cdot N \cdot (M+N)$). |
Precomputation (Row/Col Sum Arrays) |
Marginal Accumulation Projection |
Pre-calculate 1s in each row and column once. Store them in 1D arrays. Use the formula: `diff = onesRow + onesCol - zerosRow - zerosCol`. |
Draw a grid. Outside the rows, draw a column of sums. Below the columns, draw a row of sums. Fill the grid by adding the corresponding side-sums. |
Quadratic Surface Fill |
Draw two 1D bars (O(M+N)) and one 2D grid (O(M*N)). Label $O(M\cdot N)$. |
Draw the result matrix. |
Draw two 1D arrays for row/col metadata. $O(M+N)$ Space. |
| 2483 |
Minimum Penalty for a Shop |
For every possible closing hour `j` (from 0 to n), iterate through the entire string to calculate the penalty. |
N-Iteration Penalty Scan |
Draw a timeline. Below each hour, draw a scan line checking the whole string. Label $O(N^2)$. |
Prefix Sums / Single Pass Logic |
Running Score Delta |
Start with initial penalty (all 'Y'). Iterate once: if 'Y', penalty decreases; if 'N', penalty increases. Track the index of the global minimum. |
Draw the 'Y/N' string. Below it, write a running score. Every 'Y' is a -1, every 'N' is a +1. Circle the lowest number in the sequence. |
Linear Progress Line |
Draw one straight horizontal arrow. Label $O(N)$ Time. |
Draw a penalty variable. |
Draw two integer variables: `min_penalty` and `best_hour`. $O(1)$ Space. |
| 2484 |
Count Palindromic Subsequences |
Generate all 5-length subsequences and check if they are palindromes. $O(N^5)$. |
Quintic Expansion Grid |
Draw 5 nested loops represented by 5 overlapping brackets. Practically unrunnable. |
Prefix/Suffix DP (Length 5) |
The Pivot Expansion |
A 5-palindrome looks like `xy_yx`. Iterate through every index as the center `_`. Count how many times the prefix has the sequence `xy` and the suffix has the sequence `yx`. Multiply them. |
Draw the string. Pick a middle letter. Look Left: Count occurrences of "12", "13", etc. Look Right: Count occurrences of "21", "31". Multiply the matches. |
Linear Scan with 100-State Check $O(N \cdot 100)$ |
Draw a timeline. At each step, update a fixed 10x10 grid of 2-digit combinations. |
Full subset generation arrays. $O(N^5)$. |
Prefix and Suffix 3D arrays tracking 2-digit counts. $O(N \cdot 100)$ -> $O(N)$ space. |
| 2485 |
Find the Pivot Integer |
For every `x` from 1 to `n`, calculate the sum of [1, x] and [x, n] manually using a loop and compare. |
Iterative Sum Comparison |
Draw a number line. For each point, draw two brackets (left and right). Label $O(N^2)$. |
Math (Perfect Square Property) |
Algebraic Balance Point |
The sum of 1 to x is `x(x+1)/2`. The total sum is `n(n+1)/2`. Pivot exists if `sqrt(totalSum)` is an integer. |
Draw a triangle representing the sum. Cut it. Solve `x^2 = n(n+1)/2`. |
Constant Time Box |
Draw a single calculation box. Label $O(1)$. |
Draw loop variables. |
Draw 2-3 float/int variables. $O(1)$ Space. |
| 2486 |
Append Characters to String to Make Subsequence |
Generate all possible suffixes of the target string `t` and check if each is a subsequence of `s`. |
Exponential Subsequence Check |
Draw string `t`. Branch out into all possible character choices. Label $O(2^T)$. |
Two-Pointer Greedy Matching |
Parallel Character Snapping |
Iterate through `s`. If `s[i] == t[j]`, increment `j`. The number of characters to append is `t.length - j`. |
Draw strings `s` and `t`. Draw arrows from characters in `s` to their matching partners in `t`. See where the arrows stop in `t`. |
Single Pass Stream |
Draw one line for `s`. Label $O(S)$ Time. |
Draw a list of suffixes. |
Draw two index pointers. $O(1)$ Space. |
| 2487 |
Remove Nodes From Linked List |
For every node, iterate through all following nodes to check if any have a strictly greater value. If so, remove the current node. |
N-Squared Lookahead Scan |
Draw a linked list. From each node, draw arrows to all subsequent nodes. Label $O(N^2)$. |
Monotonic Stack or Reverse Recursion |
Right-to-Left Wavefront Removal |
Reverse the list. Keep track of the maximum value seen so far. If a node is less than the max, remove it. Reverse back. |
Draw a linked list. Imagine a wall moving from right to left. The wall height is the max value seen. If a node is shorter than the wall, it gets crushed (removed). |
Linear Multi-Pass |
Draw three linear passes (Reverse, Scan, Reverse). Label $O(N)$ Time. |
Draw a pointer variable. |
Draw a stack structure (if using stack) or recursion frames (O(N)). $O(N)$ Space. |
| 2488 |
Count Subarrays With Median K |
Find the index of 'k'. Generate all subarrays containing that index. For each, check if the count of elements > k and < k satisfies the median condition. |
Nested Subarray Scan |
Draw the array. Circle 'k'. Draw brackets of all sizes expanding around 'k'. Label $O(N^2)$. |
Prefix Sums + Frequency Map (Balance Tracking) |
Balance Beam Accumulator |
Replace numbers > k with +1, < k with -1. Calculate prefix sums. Count subarrays ending after 'k' where the sum is 0 or 1. |
Draw a line of numbers. Write +1, 0, -1 above them. Create a Map. On the left of 'k', store prefix sum frequencies. On the right, check for matching sums. |
Two-Pass Linear Scan |
Draw two arrows moving out from index 'k'. Label $O(N)$ Time. |
Draw a results variable. |
Draw a Hash Map storing up to N prefix sum counts. $O(N)$ Space. |
| 2489 |
Number of Substrings With Fixed Ratio |
Generate all subarrays, count 0s and 1s, check ratio. $O(N^2)$. |
Sliding Window Matrix |
Draw nested brackets checking every possible slice. |
Prefix Sum + Hash Map (Math Restructuring) |
The Ratio Balancer |
Ratio equation: `zeros / ones = num1 / num2`. Restructure it: `zeros * num2 - ones * num1 = 0`. Track this "balance" score. If you see the same score again, the subarray between them has the perfect ratio. |
Draw the string. Maintain the balance score. If the score is 3, and you see 3 again later, the slice between them is valid. Use a Map to count frequencies of scores. |
Single Pass Lookups $O(N)$ |
Draw a straight line. Update a math formula and query a Map at each step. |
Storing N^2 substring counts. |
A Hash Map of balance frequencies. $O(N)$ space. |
| 2490 |
Circular Sentence |
Split the sentence into an array of words. Loop through the array and compare the last character of `word[i]` with the first character of `word[i+1]`. |
Linear Word Matching |
Draw a circle of boxes. Draw arrows between adjacent boxes. Label $O(N)$. |
Single Pass (Space Detection) |
Boundary Check Pulse |
Iterate through the string. If a space is found, check if the character before and after the space are the same. Check string[0] and string[last] at the end. |
Write the sentence. Draw vertical bars at every space. Put an '=' sign above the space if the letters on the left and right match. |
Constant Constant Pass |
Draw one straight horizontal line. Label $O(N)$ Time. |
Draw an array of words (extra space). $O(N)$. |
Draw only the original string pointer. $O(1)$ extra Space. |
| 2491 |
Divide Players Into Teams of Equal Skill |
Generate all possible pairings of players and check if the sum of skills for each team is the same. |
Recursive Pairing Tree |
Draw nodes for players. Branch out every possible pair combination. Label $O(N!)$. |
Sorting + Two Pointers |
Inward Folding Mirror |
Sort players. Pair the weakest with the strongest. If any pair sum differs from the first pair sum, return -1. Otherwise, sum their products (chemistries). |
Draw a sorted array. Draw an arrow from 0 and N-1. Move them inward. Write the sum of the pair. If consistent, multiply and add. |
Sort Block + Linear Scan |
Draw a sorting block (N log N) and a single scan line (N). Label $O(N \log N)$. |
Draw the result sum variable. |
Draw a single integer/long for total chemistry. $O(1)$ extra Space. |
| 2492 |
Minimum Score of a Path Between Two Cities |
Use BFS/DFS to find all possible paths between city 1 and city n. Track every edge in every path and find the overall minimum weight. |
Exhaustive Path Search |
Draw a graph. Highlight every possible route. Label $O(E \cdot P)$ where P is the number of paths. |
Graph Connectivity (BFS/DFS or Union-Find) |
Component Edge Sieve |
The "minimum score" is just the minimum weight edge in the entire connected component containing city 1 and city n. Simply traverse the component once. |
Draw a graph. Color all nodes reachable from city 1. Look at every edge connected to a colored node. Pick the one with the smallest number. |
Linear Graph Traversal |
Draw a traversal arrow visiting nodes and edges. Label $O(V + E)$ Time. |
Draw recursion frames for all paths. |
Draw the adjacency list and a "visited" array. $O(V + E)$ Space. |
| 2493 |
Divide Nodes Into the Maximum Number of Groups |
Try every possible starting node. Use BFS to assign levels. Check if levels satisfy the "adjacent nodes differ by 1" condition for all edges. |
Full Graph Brute BFS |
Draw a graph. For every node, draw a BFS tree. Label $O(V \cdot (V + E)$). |
Bipartite Check + Component BFS Max Depth |
BFS Layer Maximization |
Check if each component is bipartite. If yes, for each component, find the max BFS depth by trying all nodes in that component as root. Sum these maxes. |
Draw the components. For each, draw two BFS trees starting at different nodes. Write the height of each tree. Circle the tallest tree per component. |
Quadratic Component Traversal |
Draw BFS scans for each node. Label $O(V \cdot (V + E)$). *Note: Necessary due to lack of specific tree structure.* |
Draw recursion stack. |
Draw adjacency list, visited arrays, and a BFS queue. $O(V + E)$ Space. |
| 2494 |
Merge Overlapping Events in the Same Hall |
For every event, compare it with every other event. If they overlap and are in the same hall, merge them. Repeat until no more merges are possible. |
Recursive Collision Web |
Draw events as lines. Draw arrows between every pair of lines. Label $O(N^2)$ or $O(N^3)$ depending on merge restarts. |
Sorting + Linear Interval Merge |
Horizontal Segment Consolidation |
Group by Hall. Sort events by start time. Maintain a `current_end`. If the next event's start <= `current_end`, extend `current_end` to `max(current_end, next_end)`. |
Draw a timeline. Plot intervals for one hall. If two bars overlap horizontally, draw a single thick bar spanning the total start-to-end range. |
Sort Block + Linear Scan |
Draw a sorting block for Hall ID and Start Time. Label $O(N \log N)$. Draw a single sweep line. Label $O(N)$. |
Draw a list of lists tracking potential merge sets. |
Draw one `prev_event` object per hall. $O(N)$ for sorting space. |
| 2495 |
Number of Subarrays Having Even Product |
Generate every subarray (i, j). Calculate the product of all elements in each. Check if the product is even (`product % 2 == 0`). |
Nested Subarray Scan |
Draw a right-triangle grid of all possible (start, end) pairs. Label $O(N^2)$. |
Complementary Counting (Total - Odd) |
Negative Space Subtraction |
A product is odd ONLY IF every element in the subarray is odd. Count subarrays with only odd numbers (using streaks). Subtract this from the total subarrays `n(n+1)/2`. |
Draw the array. Circle the "Islands" of consecutive odd numbers. For an island of length L, write `L(L+1)/2` inside. Subtract these from the total. |
Linear Streak Scan |
Draw a single horizontal arrow. Label $O(N)$ Time. |
Draw a `long` variable for the product (risk of overflow). |
Draw one `total` and one `odd_streak` variable. $O(1)$ Space. |
| 2496 |
Maximum Value of a String in an Array |
For each string, try to parse it as an integer using a try-catch block. If it fails, take the length of the string. Compare all to find max. |
Iterative Exception Scan |
Draw a list of strings. For each, draw a "Parse Gate". If it passes, value is N. If it crashes, value is Length. Label $O(N \cdot L)$. |
Linear Scan (Manual Digit Check) |
Character Class Filter |
Loop through each string. Check if every character is a digit. If yes, convert to int. If not, use length. Track max. |
Draw a string. Check each character '0'-'9'. If any char is 'a'-'z', immediately draw a line to "Length". Otherwise, draw to "Value". |
Linear Iteration |
Draw one horizontal line through the array. Label $O(N \cdot L)$ Time. |
Draw a temporary string for parsing. |
Draw one integer variable `maxVal`. $O(1)$ Space. |
| 2497 |
Maximum Star Sum of a Graph |
For every node, calculate the sum of all its edges. Then generate all subsets of edges for each node and find the max sum of size ≤ k. |
Node-wise Subset Generation |
Draw a node with many neighbors. Branch out every possible group of neighbors. Label $O(V \cdot 2^E)$. |
Greedy (Sort Neighbors per Node) |
Pruned Neighbor Selection |
For each node, look at neighbors with positive values. Sort them descending. Take the top `min(k, positive_neighbors)` and add to node's value. |
Draw a node and its neighbors with values. Cross out negative neighbors. Rank the positive ones: 1st, 2nd, 3rd. Circle the top K. |
Graph Scan + Local Sort |
Draw a traversal arrow. Label $O(V + E \log E)$ or $O(V + E)$ with min-priority queue. |
Draw recursive stacks for subsets. |
Draw adjacency list. $O(V + E)$ Space. |
| 2498 |
Frog Jump II |
Try every possible combination of stones for the path forward and back. Use recursion to find the minimum possible maximum jump. |
Exponential Path Search |
Draw stones. Draw every possible jump sequence forward/back. Label $O(2^N)$. |
Greedy (Skipping Alternate Stones) |
Alternating Path Interleaving |
To minimize the max jump, jump to every second stone on the way there, and the missed stones on the way back. Max jump is `max(stones[i+2] - stones[i])`. |
Draw a line of stones. Draw blue arcs over the top skipping one stone each. Draw red arcs underneath filling in the gaps. |
Single Pass Line |
Draw a single straight line from stone 0 to N. Label $O(N)$ Time. |
Draw a results variable. |
Draw one `maxDiff` variable. $O(1)$ extra Space. |
| 2499 |
Minimum Total Cost to Make Arrays Unequal |
Try swapping every possible pair to break equality. $O(N!)$. |
Factorial Swapping Web |
Draw the arrays. Draw chaotic lines swapping elements randomly. |
Greedy / Majority Element |
The Dominant Element Breaker |
Find indices where `A[i] == B[i]`. If one number is the "majority" (appears more than half the time in these indices), you MUST swap it with elements *outside* this set to break the majority. |
Draw the bad indices in a box. Find the most common number. If it dominates, look at the rest of the array. Find the smallest indices where `A[j] != B[j]` and neither is the dominant number. Swap them. |
Linear Scan $O(N)$ |
Draw a single pass to collect bad indices, and a second pass to fix the majority element if needed. |
Recursion tracking all array states. |
Variables tracking max frequency and cost sums. $O(1)$ space. |
| 2500 |
Delete Greatest Value in Each Row |
In each iteration, scan every row manually to find the max, remove it, find the max of those removed values, and repeat. |
Iterative Matrix Reduction |
Draw a grid. Circle the biggest number in each row. Cross them out. Label $O(N \cdot M^2)$. |
Sorting Rows |
Vertical Maximum Column Sweep |
Sort every row individually. Now the "greatest values" are all in the last column. Iterate through columns from end to start, taking max of each. |
Draw a grid. Show arrows sorting each row. Draw a vertical box over the last column and pick the largest number. Move the box one column left. |
Row Sorting + Grid Scan |
Draw M rows being sorted. Label $O(M \cdot N \log N)$. Label scan $O(M \cdot N)$. |
Draw the result sum. |
Draw the original grid. $O(1)$ extra Space if sorting in-place. |
| 2501 |
Longest Square Streak in an Array |
For every number, check if its square exists in the array. If yes, repeat with the square. Continue until no more squares found. |
Recursive Square Search |
Draw a number. Draw an arrow to its square, then to its square's square. Label $O(N \cdot \log(\log(\text{MaxVal})$)). |
Hash Set + Greedy Growth |
Exponential Jump Tracking |
Put all numbers in a Set. For each number, if it's not a square of another number in the set, start a streak. Square it and look it up in $O(1)$. |
Draw a Hash Set. Point to '2'. Is '4' in? Yes. Is '16' in? Yes. Is '256' in? No. Streak = 3. Mark all as "visited" or skip to avoid redo. |
Set Build + Linear Pass |
Draw a line for Set creation (O(N)) and a line for checks. Label $O(N)$ Time. |
Draw a recursion stack. |
Draw a Hash Set of size N. $O(N)$ Space. |
| 2502 |
Design Memory Allocator |
Linear scan through a memory array of size N to find consecutive 0s for allocation, and full array scan to clear mID for freeing. |
Sliding window highlighting contiguous segments moving across a static array structure. |
Draw a grid of boxes. Slide a bracket of length size across the boxes, stopping when all enclosed boxes are empty (0). |
1D Array tracking with consecutive free-block counting and slice assignment. |
1D grid with color-coded segments representing allocated blocks and blank/white segments for free spaces. |
Color size number of contiguous white boxes with a specific color representing the mID. To free, locate all boxes of that specific color and erase them back to white. |
Draw a contiguous row of squares. Fill squares with mID values. To allocate, scan left-to-right with a tally of empty squares, resetting the tally if a filled square is hit. |
Worst-case linear traversal line graph showing $O(N)$ scanning for both the allocate and free methods. |
Draw an array of size N. Draw a straight arrow from left to right representing the pointer scanning the array for each query, showing $O(N)$ operations per call. |
Flat integer array. |
Flat integer array. |
| 2503 |
Maximum Number of Points From Grid Queries |
Run a standard Breadth-First Search (BFS) starting from [0,0] independently for every single query. |
Multiple overlapping BFS expansion trees expanding outward from the root node. |
Draw the matrix repeatedly for each query. Shade the cells that can be reached from the top left without exceeding the specific query value. |
Offline Queries (Sort Queries) + Min-Heap (Priority Queue) + BFS to prevent re-processing nodes. |
Min-Heap tree structure alongside an incrementally expanding grid boundary frontier. |
Sort queries in ascending order. Simulate a rising water level on the grid. Min-heap stores boundary cells. Pop boundary cells strictly less than the water level and flood them. |
Draw the grid. Circle the cells currently added to the min-heap. Cross out a cell when it is popped and tallied, then circle its unvisited valid neighbors. |
Heap insertion/extraction operations visualizer bounded strictly by the matrix size M*N. |
Draw a binary tree (heap) bounded to size M*N. Show elements entering and leaving sequentially, annotating the $O(\log(M\cdot N)$) cost per node to prove overall efficiency. |
Multiple queue instances duplicating memory footprints for each independent query. |
Single boolean visited matrix and a single Min-Heap data array. |
| 2504 |
Concatenate the Name and the Profession (SQL) |
Fetch all database rows into application-level memory and use a loop to format strings line-by-line. |
Loop iteration sequence over an active list of objects in RAM. |
Draw a table, draw a looping arrow pulling out each row, applying a string function manually, and appending the result to a new list. |
SQL String Functions (CONCAT, LEFT) running directly on the database engine. |
Relational Database Projection visually mapping two distinct columns merging into one. |
Look at the name and profession columns. Isolate the first letter of profession, wrap it in parentheses visually, and glue it next to name. |
Draw a table with name and profession. Draw a funnel that takes name and profession[0], outputting the merged string into a new output column. |
Database table sequential scan visualization. |
Draw a downward arrow traversing alongside the table representing a single $O(N)$ database engine table scan. |
In-memory arrays holding duplicated string data. |
Database engine cursor pointing to the active memory row (minimal footprint). |
| 2505 |
Bitwise OR of All Subsequence Sums |
Generate all 2^N possible subsequences, compute the sum of each explicitly, and bitwise OR the final results. |
Massive binary decision tree mapping the combinatorial inclusion/exclusion paths of each element. |
Draw a tree where each branch splits into "include nums[i]" and "exclude nums[i]". The leaf nodes represent all explicit subsequence sums. |
Bit contribution counting array tracking 1s, coupled with right-shift carry propagation logic. |
64-bit frequency array simulating binary addition and structural carry logic across bits. |
Create an array of 64 buckets. For each number, drop a token into the bucket for each 1-bit. Sweep from bucket 0 to 63, moving half the tokens to the next bucket (carry logic). |
Draw a table with 64 columns. Write the binary form of the array numbers in rows. Count the 1s in each column. Shift count / 2 to the left column to simulate carries. |
Single array traversal followed by a constant, fixed 64-step loop. |
Draw the input array with an $O(N)$ scan arrow underneath it, then draw the fixed 64-element bit array with an $O(1)$ constant scan arrow next to it. |
Enormous exponential array storing 2^N explicit sums. |
Fixed-size 64-element integer array cnt. |
| 2506 |
Count Pairs Of Similar Strings |
Compare every single string with every other string using a nested loop, converting each to a set of characters to check equality. $O(N^2 \cdot L)$ |
Complete graph where every node (string) has a directed edge pointing to every subsequent node. |
Draw the list of strings. Draw lines connecting the first string to all strings below it, then the second string to all below it, forming a dense web. |
Bitmasking for character presence + Hash Map frequency counting. |
Strings funneling into a 26-bit integer representation, dropping into Hash Map buckets. |
Convert "aba" to a 26-bit binary where 'a' and 'b' bits are 1. Look up this integer in a hash map. Add the current count to your answer, then increment the map count. |
Write out a string. Below it, write a 26-slot array of 0s and 1s. Convert that array to a single decimal number. Group matching numbers together and use the formula n*(n-1)/2. |
Single linear timeline for $O(N\cdot L)$ traversal, followed by an $O(1)$ hash map lookup. |
Draw a single arrow scanning down the list of strings. Beside each string, write its bitmask. Show that you only scan the list exactly once. |
Array of HashSets for every string. |
Integer-to-Integer Hash Map. |
| 2507 |
Smallest Value After Replacing With Sum of Prime Factors |
Recursively calculate the sum of prime factors, potentially branching wildly if implemented poorly without a while loop. |
Redundant Factorization Trees |
Draw a number. Branch it out into its primes. Sum them. Re-draw the entire tree for the new number. |
Simulation + Prime Factorization |
The Prime Sum Collapse |
Factorize the number N into its primes and sum them. If the sum equals N, stop (it cannot get smaller). Otherwise, set N = sum and repeat. |
Draw a large number block. Smash it into its prime building blocks. Add their values together to form a new block. Keep smashing until the block stops shrinking. |
Iterative Factorization $O(\text{Answer} \cdot √N)$ |
Draw a loop that runs until stabilization. Inside, draw a fast $O(√N)$ factorization pass. |
Deep recursion stack. |
A few integer tracking variables. $O(1)$ space. |
| 2508 |
Add Edges to Make Degrees of All Nodes Even |
Iterate through all pairs of nodes, try adding 1 or 2 edges, and run a full graph traversal each time to check if all degrees are even. $O(V^4)$ worst case. |
Massive decision tree branching out for every possible edge combination. |
Draw the graph. Lightly sketch dashed lines between every non-connected pair. Methodically erase and try the next combination, checking all node degrees each time. |
Graph Theory (Degree counting). Odd-degree nodes must total 0, 2, or 4. Check specific adjacency rules. |
Bipartite matching visual focusing strictly on the isolated odd-degree nodes and their mutual/shared neighbors. |
Count odd-degree nodes. If 0: return True. If 2: check if they can connect directly or share a common neighbor. If 4: check if they can be paired up perfectly. Any other count is False. |
Extract *only* the nodes with odd degrees (ignoring the rest of the graph). Draw lines between them if they don't share an edge, or to a shared "dummy" even node. |
Linear $O(V + E)$ pass to build degrees, followed by $O(1)$ conditional logic. |
Draw an array representing the degree of each node. Draw an arrow scanning it once to find odd numbers. Then draw a small bounded box for the maximum 3 if-statements. |
Deep recursive call stacks or multiple graph copies. |
Adjacency Set for $O(1)$ edge lookups. |
| 2509 |
Cycle Length Queries in a Tree |
Construct the full explicit tree in memory. For each query, run a Breadth-First Search (BFS) to find the shortest path between u and v. |
Expanding ripple (BFS frontier) moving through a massive, explicit binary tree structure. |
Draw a massive tree. Pick two nodes. Trace layer by layer outwards from node u until you bump into node v. |
Lowest Common Ancestor (LCA) via integer division (node / 2) in a Complete Binary Tree. |
Two pointers climbing up a virtual tree hierarchy simultaneously by halving their values until they collide. |
Compare u and v. While they aren't equal, divide the larger one by 2 (moving up one level). Add 1 to your step counter. Add 1 at the end for the query edge. |
Write the two numbers. Draw an upward arrow from the larger number, writing its value divided by 2. Repeat until both numbers match. Count the arrows. |
$O(\log N)$ tree height traversal per query. |
Draw a vertical line representing the height of the tree. Show an arrow jumping upwards, halving the remaining distance each step, proving logarithmic time. |
$O(N)$ explicit Node objects and edge pointers. |
$O(1)$ extra space (no tree is actually built in memory). |
| 2510 |
Check if There is a Path With Equal Number of 0's And 1's |
Recursively explore every valid path (moving right and down). $O(2^(M+N)$) |
Exponential recursion tree where every cell splits into two distinct future realities. |
Draw the grid. Start top-left. Trace a line down, then trace a line right. For every step, split your line into two new lines, writing the sequence of 0s and 1s. |
Dynamic Programming (DP) tracking the minimum and maximum possible sum of `1s - 0s` at each cell. |
Grid matrix where each cell contains a mathematical range/interval [min, max]. |
If path length is odd, impossible (return false). Treat 1 as +1, 0 as -1. For each cell, calculate the lowest and highest possible running sum coming from the top or left. Check if 0 is in the range at the bottom-right cell. |
Draw the grid. Inside cell (0,0), write its value as `[val, val]`. Moving right and down, add the current cell's value to the `[min, max]` of the previous cells. Merge bounds. |
$O(M\cdot N)$ grid traversal. |
Draw a matrix. Draw a single arrow snaking through every cell exactly once from top-left to bottom-right, updating a couple of numbers per cell. |
Massive $O(M+N)$ recursion call stack memory. |
$O(M\cdot N)$ DP array, or $O(N)$ optimized 1D array. |
| 2511 |
Maximum Enemy Forts That Can Be Captured |
Nested loops iterating $O(N^2)$. For every command fort (1), scan the rest of the array to find every empty fort (-1), checking if exclusively enemy forts (0) exist between them. |
Two nested loop pointers forming a dense network of pairwise segment boundary checks across an array. |
Draw the array. Put pointer i on a 1. Scan a second pointer j down the line to find a -1, drawing a connecting arch for every single pair checked to see if the gap is purely 0s. |
Two Pointers / Single-Pass Array Traversal checking alternating non-zero boundary states. |
Sliding window or segment highlighter bounding distinct contiguous blocks clamped by opposite non-zero integers (1 and -1). |
Track a starting pointer. Whenever you encounter a 1 or -1, check if it's the mathematical opposite of the last non-zero number seen. If yes, the distance between them minus 1 is your captured forts. Update the start pointer. |
Draw the array. Use your index finger as an anchor tracking the last seen 1 or -1. Slide another finger forward. When a new non-zero is found, calculate the gap if they have opposite signs. |
A single, continuous linear arrow scanning the array left-to-right, highlighting $O(N)$ operations. |
Draw a number line with array indices. Draw one continuous forward-moving arrow showing no backtracking, proving linear $O(N)$ time complexity. |
Minimal overhead, standard array. |
Constant $O(1)$ space tracking just two index integers (current anchor and iterator). |
| 2512 |
Reward Top K Students |
Loop over each student's report, split the words, and do a linear search in the positive/negative raw arrays to calculate scores. Sort the final list $O(N \log N)$. |
Nested loops mapping report words against raw arrays, followed by a heavy data sorting block. |
Draw the report words. Draw lines mapping each word to every single word in the positive and negative lists, creating a tangled mapping web. |
Hash Set for $O(1)$ word lookup + Custom Comparator Sorting (or Min-Heap for top K selection). |
Words funneling through a fast Hash Set filter, dropping point values into an array of student tuples, which then pass through a sorting filter. |
Read a report word by word. Mentally pass it through a "good" filter (+3) or "bad" filter (-1). Keep a tally. Package the (score, id) and rank them descending by score, ascending by ID. |
Make a T-chart for positive/negative words. Write a student ID. Read their report, marking tally strokes (+3 or -1). Finally, physically re-order the student IDs based on final tallies. |
Array-to-Hash-Set conversion node flowing into an $O(N\cdot M)$ text processing stream, ending in an $O(N \log N)$ sorting block. |
Draw a box representing the $O(1)$ Hash Set lookups. Show an $O(\text{words})$ text processing loop connecting to it. Finally, draw a sorting step at the end. |
Keeping all raw duplicate strings in active memory during the loop. |
Two Hash Sets (Positive, Negative) and an array of N tuple elements mapping scores to IDs. |
| 2513 |
Minimize the Maximum of Two Arrays |
Linearly increment numbers from 1 upwards. Try placing them in arr1 or arr2 based on divisibility rules until both array counts are strictly satisfied. |
Number line generator pushing integers into two distinct buckets based on modulo conditions until buckets are full. |
Write 1, 2, 3, 4, 5... Cross out multiples of the divisors. Keep a running tally of valid numbers for arr1 and arr2 until you hit the required targets. |
Binary Search on Answer Space + Number Theory (Inclusion-Exclusion Principle using LCM). |
Venn diagram representing sets of valid divisible numbers bounded by an expanding/contracting maximum limit limit. |
Pick a massive middle number m. Calculate total numbers NOT divisible by divisor1, NOT by divisor2, and NOT by their LCM. If all counts satisfy the requirements, search a smaller max. If not, search larger. |
Draw a number line. Pick a midpoint m. Calculate valid counts using integer division. If valid, cross out the right half (search smaller). Else, cross out the left half. |
Logarithmic scale zooming in on a single target value in a massive search space. |
Draw an interval from 0 to 2^31. Draw vertical lines repeatedly splitting the remaining interval in half, mathematically showing $O(\log(\text{MAX})$) steps. |
Expanding arrays arr1 and arr2 storing explicit integer sequences in memory. |
$O(1)$ space. Just holding low, high, mid, and calculated count variables. |
| 2514 |
Count Anagrams |
Generate all actual permutations for every word in the string, store them in a set to filter duplicates, and multiply the sizes. $O(N!)$ Time. |
Explosive recursive permutation tree for each word generating millions of branches. |
Take a word like "too". Physically write all literal combinations: "too", "oto", "oot". Count unique strings. Multiply the word counts together. |
Combinatorics (Permutations with Repetition) + Modular Multiplicative Inverse. |
Mathematical formula pipeline: Word length mapped to a factorial numerator, and character frequencies mapped to factorial denominators. |
For the word "too": Length = 3. Numerator = 3!. Frequencies: t=1, o=2. Denominator = 1! * 2!. Result = 6 / 2 = 3 distinct anagrams. Multiply word results modulo 10^9+7. |
Write the combinatorics formula fracn!c_1! c_2! dots under each word. Calculate each fraction. Multiply all the results together.
[Image of Permutations with Repetition formula]
|
Character frequency histogram feeding directly into $O(1)$ array lookups for precomputed factorials. |
Draw a string. Show one sweep to count characters (O(N)), one pass over frequencies (max $O(26)$), and an $O(1)$ block for the final math formula. |
Massive RAM consumption storing exponentially many explicit string permutations. |
Precomputed Factorial/Inverse arrays (size N) and a 26-element character frequency array. |
| 2515 |
Shortest Distance to Target String in a Circular Array |
Run a Breadth-First Search (BFS) stepping +1 and -1 simultaneously from the starting index until the target is found. |
Two overlapping wavefronts expanding outwards in opposite directions around a circle. |
Draw a circle of words. Put a pin on startIndex. Physically hop +1 and -1 step-by-step in alternating directions until you land on the target. |
Linear Array Scan with Modulo Arithmetic (comparing absolute distance vs circular wrap-around distance). |
Circular clock face showing both the direct clockwise chord distance and the counter-clockwise chord distance. |
Loop the array once. When you find the target at index i, calculate direct distance |i - start| and wrap-around distance N - |i - start|. Record the minimum. |
Draw the array as a straight line. Draw a curved arrow from start to target (direct distance). Draw another curved arrow going out one end and wrapping back into the other (wrap-around distance). Keep the smaller number. |
Linear timeline scanning the array exactly once, calculating two constant-time $O(1)$ math equations per match. |
Draw an array of size N. Draw a straight, unbroken arrow from left to right representing one $O(N)$ sweep to find the absolute shortest path. |
Queue for BFS traversal, holding state variables and expanding step distances. |
Constant $O(1)$ space holding just a min_distance tracking integer. |
| 2516 |
Take K of Each Character From Left and Right |
Recursive backtracking: at each step, branch into two realities—taking the leftmost character or the rightmost character—until constraints are met. $O(2^N)$ time. |
Massive, exponentially expanding binary decision tree branching left and right at every level. |
Write the string. Draw two diverging arrows from it: one crossing out the left char, one crossing out the right char. Repeat this for every new string state. |
Inverse Sliding Window (Two Pointers) seeking the maximum middle subarray to *leave behind*. |
A highlighted sliding window expanding and contracting over the middle of the array, leaving unhighlighted "taken" margins on the edges. |
First, count all 'a', 'b', and 'c' in the string. If any count is less than K, return -1. Then, use two pointers (left and right) to create a window. If the window contains too many of any character (meaning the edges don't have enough), shrink the window from the left. Track the maximum window size. |
Draw the string. Place two brackets `[ ]` representing the window. Keep a tally of characters *outside* the brackets. Move the right bracket right. If outside tallies drop below K, move the left bracket right until valid again. |
Two pointers moving in a single forward direction across the array, bounded by 2N steps. |
Draw an array. Draw one arrow for the right pointer and one for the left. Show both moving strictly left-to-right without ever resetting, proving $O(N)$ complexity. |
Deep recursive call stack proportional to string length. |
Constant $O(1)$ space for a 3-element frequency map/array. |
| 2517 |
Maximum Tastiness of Candy Basket |
Generate all possible combinations of size K from the array. For each combination, find the minimum absolute difference between any two elements. Find the max of those minimums. |
Combinatorial explosion web connecting every subset of K items. |
Write the array. Manually list out every group of K items. Connect every pair in a group, calculate the difference, circle the smallest. Then circle the largest of those smallest differences. |
Sort the array + Binary Search on the Answer Space + Greedy Checking. |
A sorted number line (the array) overlaid with a binary search dividing the potential "answer" range. |
Sort the prices. Set a search range for the answer from 0 to (max_price - min_price). Pick a midpoint `mid`. Greedily walk through the sorted array picking items that are at least `mid` apart. If you can pick K items, search higher. Else, search lower. |
Draw a sorted array. Write a target gap `G`. Circle the first number. Scan right until you find a number >= first + `G`. Circle it. Repeat. Count circled items. If count >= K, increase `G`. |
A logarithmic halving of the answer space, with an $O(N)$ linear scan happening inside each halving step. $O(N \log(\text{Max Diff})$). |
Draw a timeline from 0 to Max Diff. Draw brackets cutting the timeline in half repeatedly. For each cut, draw a quick linear arrow under the sorted array representing the greedy check. |
Massive array storing all combinations of size K. |
$O(1)$ extra space (or $O(\log N)$ for the in-place sorting algorithm). |
| 2518 |
Number of Great Partitions |
Generate all 2^N possible partitions (subsets) of the array. For each, sum the elements in group A and group B. Check if both sums are >= K. |
Binary inclusion/exclusion tree generating all possible 2^N subsets. |
Draw the array. For each element, draw a branch putting it in "Box A" and a branch putting it in "Box B". Calculate the sum of both boxes at the bottom of every branch. |
0/1 Knapsack Dynamic Programming (Inverse Problem). Find subsets summing to strictly less than K, and subtract from total subsets. |
A 1D Dynamic Programming state array updating values iteratively, focusing only on the small boundary `[0, K-1]`. |
Calculate total possible subsets (2^N). Using a 1D array of size K, iterate through the numbers. For each number, update the array to count how many subsets form sums from 0 to K-1. Multiply this "bad" count by 2 (since a bad subset in Box A implies Box B is the other part) and subtract from 2^N. |
Draw a row of K boxes (indices 0 to K-1). Set box 0 to 1 (one way to make sum 0). Pick an array number `num`. Starting from the right of your boxes, add the value from index `i - num` to index `i`. |
An $O(N)$ loop wrapping an inner $O(K)$ loop, bounded by constraints. Time is $O(N \cdot K)$. |
Draw the input array. Below it, draw the DP array of size K. Show an arrow sweeping the DP array backwards once for every element in the input array. |
Exponential space for storing 2^N combinations. |
$O(K)$ 1D array space for the DP states. |
| 2519 |
Count the Number of K-Big Indices |
For every single index `i`, loop from 0 to `i-1` to count smaller elements, and loop from `i+1` to N-1 to count smaller elements. If both counts >= K, tally it. $O(N^2)$ time. |
Nested loops where each node sends scanning rays spanning outwards to the left and right ends of the array. |
Put your finger on an index. Point your other finger left and count strictly smaller numbers. Then point right and count strictly smaller numbers. Repeat for every single number. |
Two Passes (Prefix and Suffix) using Max-Heaps of size K. |
Two separate arrays accumulating boolean valid states (Left valid, Right valid) populated by a bounding priority queue. |
Create a Left-Valid array. Sweep left-to-right pushing elements into a Max-Heap. If the heap size exceeds K, pop the max. If the heap has exactly K elements and the current number is strictly greater than the heap's max, mark Left-Valid as true. Repeat backwards for Right-Valid. Count where both are true. |
Draw the array. Draw a "Heap Box" that holds max K items. Sweep left-to-right. Write the max item in the box above the current array number. Sweep right-to-left doing the same. Circle indices where the array number is larger than both written maxes. |
Two linear passes $O(N)$, with each step doing an $O(\log K)$ heap insertion. Overall $O(N \log K)$. |
Draw the array. Draw an arrow sweeping left-to-right, and another right-to-left. Beside each step, draw a mini tree of size K showing a push/pop operation. |
$O(1)$ auxiliary space, but terrible time complexity overhead. |
Two boolean arrays of size N, and a Max-Heap of max size K. $O(N + K)$ space. |
| 2520 |
Count the Digits That Divide a Number |
Convert the integer to a String. Loop through the characters, parse each back to an integer, and check if the original number modulo the parsed digit is 0. |
Data-type coercion sequence (Int -> String -> Char -> Int). |
Write the number. Draw a box around each digit to pretend it's text. Pull out the text, convert it to a number, do the division. |
Mathematical Modulo-10 Digit Extraction. |
A while-loop peeling off the rightmost digit mathematically using `% 10` and `/ 10`. |
Store the original `num`. Create a temporary copy `temp = num`. While `temp > 0`, extract `digit = temp % 10`. Check if `num % digit == 0`. Then chop off the digit with `temp = temp / 10`. |
Write `num = 124`. Write `temp = 124`. Look at the last digit (4). Does 124 % 4 == 0? Yes, tally 1. Cross out the 4. Now `temp = 12`. Repeat. |
Logarithmic (base 10) decomposition of the integer. $O(\log10(N)$) time. |
Draw a long number. Draw an arrow slashing through the last digit one by one, shrinking the number. Since it shrinks by a factor of 10 each time, it takes very few steps. |
$O(D)$ string character array allocation where D is number of digits. |
$O(1)$ constant space using primitive integers. |
| 2521 |
Distinct Prime Factors of Product of Array |
Multiply every single number together into one giant integer (which causes data overflow), then mathematically factorize that massive result. |
A massive, single multiplication node bursting into a gigantic, top-heavy factor tree. |
Write 2 * 4 * 3 = 24. Draw branches extending downwards from 24, breaking it into its absolute prime roots. |
On-the-fly Trial Division + Hash Set deduplication. |
Array elements acting as funnels, processing individually and dropping their prime factors into a single shared Hash Set bucket. |
Take the first array number. Divide it by i=2 upwards. If it divides cleanly, throw i into a Set and divide the number down. Move to the next array element. Count the final Set size. |
Draw the array. Below each number, draw a mini factor tree. Circle the prime leaf nodes. Draw arrows moving all circled primes into a single box (the Set). Count the unique numbers inside the box. |
$O(N \\text{cdot sqrt}(\text{MAX}_\text{VAL})$) sequence of independent, small mathematical loops. |
Draw an array. Under each element, draw a small, bounded vertical line representing the maximum square-root iterations, showing the work scales linearly with the array size. |
Massive integer string allocation or BigInt library overhead. |
$O(P)$ Hash Set space, where P is the strictly bounded maximum number of distinct primes. |
| 2522 |
Partition String Into Substrings With Values at Most K |
Recursive backtracking to generate every single possible way to slice the string, validating at the end if all slices are strictly less than or equal to K. |
Exponential decision tree of knife cuts occurring sequentially between characters. |
Write the string. Draw a line after the 1st character and branch. Draw another line after the 2nd character and branch. Repeat until you have drawn every combination of cuts. |
Greedy Algorithm / String Parsing with continuous accumulation. |
A sliding window expanding like a pac-man, eating digits left-to-right until it "gags" (exceeds K), making a cut and starting fresh. |
Start a running value at 0. Read the next digit. Multiply running value by 10 and add the digit. If the new value exceeds K, increment your "cut" tally and reset the running value to just the new digit. |
Write the string. Slide your finger over the numbers, reading the growing number aloud. When the spoken number is bigger than K, draw a vertical line before the last digit, tally 1, and resume reading from the line. |
A single, continuous $O(N)$ linear pass with constant-time math checks. |
Draw the string of numbers. Draw a single, unbroken arrow from left to right, making quick vertical tick marks whenever a cut is triggered. |
$O(N)$ recursive call stack frames. |
Constant $O(1)$ memory, tracking just the running value and cut tally. |
| 2523 |
Closest Prime Numbers in Range |
Iterate from left to right. For every number, run a manual $O(\text{sqrt}(N)$) primality check. Keep track of the last seen prime to measure the gap. |
Dense looping timeline over the range with heavy square-root mathematical operations embedded inside every step. |
Write numbers Left to Right. Check each one manually for prime status. Circle the primes. Draw arches between adjacent circles and calculate the mathematical gap. |
Sieve of Eratosthenes (Precomputation) + Linear Array Scan. |
A number grid with multiples systematically crossed out, leaving a clean list of primes to measure sequentially. |
Create a boolean array up to right. Cross out all multiples of 2, 3, 5, etc. Extract the remaining 'true' numbers that are >= left. Scan this extracted list, comparing the gap between index i and i-1. |
Write numbers 1 to right in a grid. Cross out multiples. Write the remaining uncrossed primes in a list. Draw a jumping arrow between them, writing down the difference. Keep the smallest difference. |
$O(R \log \log R)$ precomputation sweep followed by a rapid $O(R)$ linear scan. |
Draw a massive grid representing the Sieve. Beside it, draw a straight timeline representing the final quick scan, showing the heavy lifting is done efficiently upfront. |
No extra memory, but massive Time Limit Exceeded (TLE) risk. |
$O(R)$ Boolean Array for the Sieve logic. |
| 2524 |
Maximum Frequency Score of a Subarray |
For every possible starting index i and ending index j, build a brand new Hash Map to count frequencies, then calculate the score. $O(N^2)$. |
Constantly recreating and destroying Hash Maps from scratch for overlapping array segments. |
Draw the array. Bracket the first 3 elements. Tally them. Erase your tallies. Bracket elements 2 to 4. Tally them. Erase. Repeat. |
Fixed Sliding Window + Persistent Hash Map (or Array Cache) for $O(1)$ incremental score updates. |
A highlighted moving window over the array that dynamically updates a single persistent frequency counter (adding the front element, removing the back element). |
Initialize a Hash Map for the first K elements. Slide the window 1 step right: add the new right element to the Map (and increase the score variable), and remove the left-most element from the Map (and decrease the score variable). Keep track of the maximum score seen. |
Draw the array. Put a physical, bounded box over K elements. Keep a tally sheet beside it. Slide the box right by 1 index. Add a tally for the new number, erase a tally for the old left number. |
$O(N)$ single linear pass with $O(1)$ map updates. |
Draw the array. Draw a bracket of size K. Draw an arrow sliding the bracket smoothly from left to right without ever resetting or jumping backwards. |
$O(K)$ temporary map structures duplicated N^2 times in memory over time. |
$O(U)$ space where U is the number of unique elements inside the window (strictly bounded by K). |
| 2525 |
Categorize Box According to Criteria |
A convoluted sequence of nested if-else statements checking volume, mass, and dimension limits repeatedly in a tangled flow. |
A messy, overlapping flowchart with redundant decision nodes evaluating the same math multiple times. |
Draw a flowchart. First box: "Is it Bulky?". Branch yes/no. Under *both* branches, write another box: "Is it Heavy?". |
Pre-evaluated Boolean Variables mapping to strict logic combinations. |
Two parallel logic gates evaluating independently, flowing into a final, clean 2x2 combination matrix. |
Calculate volume. Evaluate a strict boolean isBulky = (dim >= 10^4 or vol >= 10^9). Evaluate isHeavy = (mass >= 100). If both are true, return "Both". If neither, "Neither". Else, return whichever is true. |
Write Bulky = [True/False]. Write Heavy = [True/False]. Look at the two answers and immediately pick the category based on the word combination without re-doing the math. |
$O(1)$ constant time evaluating exact mathematical limits with no loops. |
Draw a single box representing the CPU. Draw an input going in, a single math symbol inside, and the output category coming out. |
$O(1)$ constant space. |
$O(1)$ constant space using exactly two boolean variables. |
| 2526 |
Find Consecutive Integers from a Data Stream |
Store every single incoming integer in a dynamically growing list. For every query, iterate backward reading the last k elements to check if they all match the target value. |
An endlessly growing array with a heavy, backward-scanning loop dragging across the end of it for every single query. |
Draw a long queue of numbers. For every new number added, put your finger on it and jump backwards k times to check the history. |
State Machine / Single Counter tracking contiguous valid states. |
A single tally counter that increments on success and violently resets to zero on failure. |
Maintain a count variable. Read the incoming stream. If the number equals value, increment count. If it doesn't, reset count = 0. Return true strictly if count >= k. |
Write the target `value` and target `k`. Draw a box for your `count`. As a number arrives, if it matches, draw a tally mark. If it fails, erase all tallies. If tallies reach `k`, you win. |
$O(1)$ constant time stream processing. |
Draw a single box representing the CPU. Draw an incoming arrow for the data stream, a simple math operation inside, and an immediate boolean output. No loops. |
$O(N)$ unbounded list storing the entire history of the data stream. |
$O(1)$ space holding exactly one integer counter. |
| 2527 |
Find Xor-Beauty of Array |
Generate all possible triplets (i, j, k) using three nested loops. Compute ((nums[i] | nums[j]) & nums[k]) for each, and bitwise XOR the massive resulting list together. $O(N^3)$ time. |
A dense 3D cubic matrix of combinations where every point calculates a bitwise operation. |
Write the array three times. Pick one number from the first, one from the second, one from the third. Do the math. Repeat this exhausting process for every combination. |
Mathematical Bitwise Cancellation (Symmetry). The expression simplifies to just XORing all elements in the array. |
A funnel taking all array elements, canceling out duplicates via symmetry, leaving just a single XOR aggregate at the bottom. |
Ignore the complex triplet formula. Mathematical symmetry dictates that all cross-terms cancel out to 0. Simply iterate through the array once, keeping a running XOR of all numbers. |
Write the array of numbers. Put a `^` (XOR) symbol between all of them. Calculate them left to right like a simple chain of dominoes. |
A single, continuous $O(N)$ linear pass performing an $O(1)$ bitwise operation per element. |
Draw the array. Draw a single, unbroken arrow from left to right representing the single sweep required to get the final answer. |
Variables to store combinations, though theoretically $O(1)$ if computed on the fly. |
Constant $O(1)$ space tracking a single integer for the running XOR result. |
| 2528 |
Maximize the Minimum Powered City |
Iteratively pick the city with the lowest power, place one power station there, update the power of all cities in its range, and repeat k times. $O(k \cdot N \cdot R)$ time. |
Repeatedly dropping a single pebble into a shallow pool and recalculating the ripple effect across the entire surface. |
Draw the cities as a bar chart. Find the lowest bar. Add 1 to it and its neighbors. Recalculate everything. Repeat this `k` times. |
Binary Search on the Answer Space + Greedy Sliding Window. |
A binary search tree zooming in on a target minimum power, validated by a moving sliding window covering the cities. |
Guess a "target minimum power" using binary search. Use a sliding window to calculate current power at each city. If a city is below the target, greedily place required stations at the furthest right possible edge of its range. If total stations used <= k, guess higher. |
Draw a number line for the possible answers. Pick a middle number. Do a linear sweep across the cities, adding "temporary" stations when needed. If you run out of stations, cross out the right half of the number line. |
$O(N \log(\text{Max Power})$) combining a logarithmic search space with a linear validation sweep. |
Draw a timeline of possible answers halving repeatedly. Inside each halving step, draw a quick linear arrow under the array representing the greedy check. |
Array mutation overhead. |
$O(N)$ space for a difference array or sliding window tracking states. |
| 2529 |
Maximum Count of Positive Integer and Negative Integer |
Iterate through the array from left to right, checking each number. If it's less than 0, increment a negative counter. If greater than 0, increment a positive counter. $O(N)$ time. |
A simple linear timeline checking every single item one by one. |
Put your finger on the first number. Ask "Is it positive or negative?" Tally it. Move finger to the next. Repeat until the end. |
Two separate Binary Searches (Upper Bound for negatives, Lower Bound for positives) leveraging the sorted nature of the array. |
An array split into distinct color zones (negatives, zeroes, positives) with binary search arrows targeting the exact boundary lines. |
Use binary search to find the index of the first number >= 0. That index tells you exactly how many negative numbers exist. Use binary search again to find the index of the first number > 0. Subtract that from the array length to get the positive count. Keep the max. |
Draw the array. Pick the middle element. If it's negative, jump halfway to the right. If positive, jump halfway to the left. Pinpoint exactly where the numbers switch from negative to 0 to positive. |
$O(\log N)$ logarithmic steps jumping through the sorted data. |
Draw an array. Draw a massive bracket halving the array, then halving the remaining half, demonstrating that you skip checking the vast majority of elements. |
$O(1)$ counter variables. |
$O(1)$ pointers for the binary search bounds. |
| 2530 |
Maximal Score After Applying K Operations |
For each of the K operations, linearly scan the entire array to find the maximum element, add it to the score, and update it to its ceiling third. $O(K \cdot N)$ time. |
Repeated, exhaustive full-array sweeps looking for the highest peak. |
Draw the array. Scan your eyes across all numbers to find the biggest. Cross it out, write its new value (ceil(val/3)), tally your score. Repeat from scratch K times. |
Max-Heap (Priority Queue) to maintain the largest element dynamically. |
A Max-Heap tree structure where the largest number naturally bubbles to the top root node instantly after every change. |
Push all array elements into a Max-Heap. Loop K times: pop the top element (the maximum), add it to your score, divide it by 3 (ceiling), and push the new value back into the heap. |
Draw a pyramid of numbers with the biggest on top. Take the top number, add it to your score, divide it by 3, and drop it back into the pyramid, letting it sink to its proper level. Repeat. |
$O(N + K \log N)$ execution. Building the heap is $O(N)$, and each of the K operations does an $O(\log N)$ tree rebalancing. |
Draw the array transforming into a tree once. Then, draw K loops. Inside each loop, draw an element traveling strictly down the height of the tree (log N steps). |
Constant space if done in-place, but highly inefficient time-wise. |
$O(N)$ space to maintain the elements within the Max-Heap structure. |
| 2531 |
Make Number of Distinct Characters Equal |
Try every possible swap of one character from word1 with one character from word2. For each swap, calculate the number of unique characters in both words from scratch. $O(N \cdot M)$ or $O(N^2)$. |
A bipartite graph where every character in Word A attempts to link and switch places with every character in Word B. |
Draw two lists of characters. Draw lines connecting every character in list A to every character in list B. For every line, imagine the swap and count unique letters. |
26x26 Frequency Map Simulation. |
A small 26x26 grid representing all possible character-to-character swaps between lowercase English letters. |
Count frequencies of 'a'-'z' for both words. Iterate i from 0-25 and j from 0-25. If char(i) is in word1 and char(j) is in word2, simulate the swap by updating counts by pm 1. Check if distinct counts match. |
Draw two frequency tables (26 rows). Pick a row from Table 1 and a row from Table 2. Mentally decrement one, increment the other, and count how many rows have a value > 0. |
Constant time $O(26 \cdot 26)$ after a single linear pass to count frequencies. $O(N + M)$. |
Draw Word A and Word B. Draw a single arrow over each to build the frequency map. Then draw a small 26x26 box representing the nested loop which doesn't grow with input size. |
New HashSets created for every single potential swap iteration. |
Two fixed-size integer arrays (size 26) to store character frequencies. |
| 2532 |
Time to Cross a Bridge |
Simulate every single second of time. At each second, check the status of all 4 potential queues and the bridge, moving workers one step at a time. $O(\text{Time} \cdot N)$. |
A granular timeline where every millisecond is a discrete state change for all workers. |
Draw a timeline. For every tick mark, redraw the bridge and the position of every worker. This becomes unmanageable as time increases. |
Event-Driven Simulation using 4 Priority Queues (Heaps). |
A "State Machine" where workers jump between four priority heaps based on their readiness and efficiency scores. |
Manage workers in heaps: leftWait, rightWait (sorted by efficiency), leftFree, rightFree (sorted by time). Always prioritize rightWait crossing left. Jump time to the next available event (worker finishing a task). |
Draw a bridge. On each side, draw two boxes (Waiting and Working). Use arrows to move worker IDs between boxes. Always pick the worker from the "Waiting" box with the highest efficiency value. |
$O(N \log W)$ where N is boxes and W is workers. Each worker movement is a heap operation. |
Draw the bridge. Draw 4 triangles (heaps). Show worker IDs moving from one triangle to the next. Annotate each move with a log W cost. |
A massive array or list tracking every worker's position for every second of time. |
Exactly 4 Heaps storing worker objects/tuples. |
| 2533 |
Number of Good Binary Strings |
Recursively generate all possible binary strings by adding '0' (zero times) or '1' (one times) until the length is between minLen and maxLen. $O(2^N)$. |
A binary tree that branches exponentially, though branches are restricted to specific "chunk" sizes of 0s and 1s. |
Start with an empty string. Draw two branches: add zero zeros or one ones. Repeat for every new string until you hit the length limit. |
Linear Dynamic Programming (DP) - Staircase variation. |
A 1D array where each index i represents the number of ways to form a string of length i. |
For a length i, the number of ways is dp[i - zero] + dp[i - one]. Fill the array from 1 to maxLen. Sum the values in the range [minLen, maxLen]. |
Draw a row of boxes from 0 to maxLen. Box 0 = 1. For each box i, look back zero steps and one steps. Add those two numbers and write the result in box i. |
$O(\text{maxLen})$ linear traversal. |
Draw an array of size maxLen. Draw a single arrow moving left to right. At each step, show two "look-back" arrows pointing to previous results. |
Massive recursion stack and memory for billions of generated strings. |
A single 1D array of size maxLen + 1. |
| 2534 |
Time Taken to Cross the Door |
Check every second from 0 to the last arrival. At each second, scan the entire input list to see who is waiting at the door and apply the priority rules. $O(\text{Time} \cdot N)$. |
A timeline with a "searchlight" scanning the entire input pool at every discrete moment. |
Draw a clock. At 1:00, look at all people. At 1:01, look at all people again. If no one arrives for 100 seconds, you waste 100 steps. |
Two Queues (Enter and Exit) with State Tracking. |
Two parallel queues feeding into a single "Door" bottleneck that switches states based on previous usage. |
Put people in an enterQueue or exitQueue based on their direction. At each second where someone is waiting, use the priority rules (Exit > Enter if door was unused or used for Exit). If the door is idle, jump time to the next person's arrival. |
Draw two columns: "Enter" and "Exit". Place person IDs in them sorted by arrival time. Use a "Last State" variable (0, 1, or Idle). Pop from the top of the correct column based on the state. |
$O(N)$ linear pass to process each person once. |
Draw two horizontal queues. Draw a single "Door" exit point. Show an arrow pulling one person from a queue at a time until both are empty. |
Large temporary lists for people waiting at each specific second. |
Two standard queues storing indices or timestamps. |
| 2535 |
Difference Between Element Sum and Digit Sum of an Array |
Convert every number to a string, split the string into characters, parse characters back to integers to get digit sums, then calculate the total. |
Multiple type-conversion steps (Int -> String -> List[Char] -> Int) for every element. |
Write a number like 123. Draw a circle around it (Element). Then draw a box around '1', '2', and '3' (Digits). Add the digits. Subtract the totals at the end. |
Single-Pass Accumulation with Modulo Digit Extraction. |
Two running counters (Sum A, Sum B) updated in a single linear loop. |
Iterate through the array. Add nums[i] to elementSum. While nums[i] > 0, add nums[i] % 10 to digitSum and divide nums[i] by 10. Return the absolute difference. |
Draw two columns: "Element Sum" and "Digit Sum". For each number in the array, write the full number in column 1, and write its individual digits in column 2. Add both columns and subtract. |
$O(N \\text{cdot average}_\text{digits})$ which is effectively $O(N)$ since digits are capped by the 32-bit integer limit. |
Draw an array. Draw a single arrow passing over it. Above the arrow, show a "peeling" animation where digits fall off the numbers into the sum. |
Extra string/char array memory for every number. |
Constant $O(1)$ space for two sum variables. |
| 2536 |
Increment Submatrices by One |
For each query [r1, c1, r2, c2], use nested loops to iterate through every cell from r1 to r2 and c1 to c2, adding 1 to each. $O(Q \cdot N^2)$. |
A grid being repeatedly colored in with overlapping brushstrokes, where each brushstroke requires checking every pixel. |
Draw a 5x5 grid. For query 1, shade a 3x3 area. For query 2, shade a different 2x2 area. Count the overlapping shades in each box at the end. |
2D Difference Array (Prefix Sums). |
A grid where only the corners of the query rectangles are marked with +1 or -1, later "melting" to fill the entire area. |
For each query, mark grid[r1][c1]++, grid[r1][c2+1]--, grid[r2+1][c1]--, and grid[r2+1][c2+1]++. After all queries, compute 2D prefix sums by sweeping rows then columns. |
Draw a grid. Put a '+1' at the top-left of the query box and a '-1' just outside the top-right. Do a running sum across the row to "fill" it, then a running sum down the columns. |
$O(Q + N^2)$. $O(Q)$ to mark corners and $O(N^2)$ for the final sweep. |
Draw a grid with 4 dots. Draw a single horizontal arrow filling the row, then vertical arrows filling the columns, proving we only touch each cell once after marking. |
N/A (No extra per-query storage). |
$O(N^2)$ space for the 2D grid/difference array. |
| 2537 |
Count the Number of Good Subarrays |
Generate every possible subarray (i, j). For each, count the number of pairs (a, b) where nums[a] == nums[b]. $O(N^3)$. |
A nested loop within a nested loop, creating a "scanning beam" that restarts and re-counts from scratch constantly. |
Draw an array. Use two bookmarks to mark a start and end. For every possible position of the bookmarks, list all matching pairs inside. |
Sliding Window with Frequency Map. |
An elastic window expanding until it finds k pairs, then shrinking from the left while "collecting" all possible rightward extensions. |
Expand right pointer. New pairs added = count[nums[right]]. While pairs >= k, every index from right to N-1 is a valid endpoint. Shrink left, removing count[nums[left]]-1 pairs. |
Draw the array. Slide a bracket `[ ]`. Keep a tally of pairs. When tally >= k, calculate (N - right) and add to total. Move the left bracket and repeat. |
$O(N)$ - Each element is visited by the left and right pointers exactly once. |
Draw the array with two arrows (Left, Right). Show both moving only forward, never backward, proving linear time. |
$O(1)$ if not counting the frequency map. |
$O(N)$ for the frequency map of element counts in the current window. |
| 2538 |
Difference Between Maximum and Minimum Price Sum |
For every node, treat it as the root. Run a DFS to find the longest path to a leaf and subtract the price of that leaf. $O(N^2)$. |
A forest of search trees, one for every node, recalculating overlapping paths repeatedly. |
Pick a node. Trace all paths to leaves. Pick the longest. Repeat for every single node in the tree. |
Tree Dynamic Programming (Rerooting or Diameters). |
A dual-value propagation where each node knows the "longest path with a leaf" and "longest path without a leaf" from its subtrees. |
Run DFS to calculate two values per node: maxSumWithLeaf and maxSumWithoutLeaf. The answer for a node is the max of current.price + child.maxSumWithoutLeaf and current.price + child.maxSumWithLeaf (cross-referencing with other children). |
Draw a tree. At each node, write two numbers. The first is the max price-sum including a leaf, the second is excluding a leaf. Combine these as you bubble up from children to parent. |
$O(N)$ - Two DFS passes (one to collect, one to distribute/reroot). |
Draw a tree with a downward arrow (first pass) and an upward/sideways arrow (second pass), showing each edge is traversed a constant number of times. |
$O(N)$ recursion stack per root (N times). |
$O(N)$ to store the adjacency list and the DP state values. |
| 2539 |
Count the Number of Good Subsequences |
Generate every possible subsequence (2^N). For each, count character frequencies and check if they are all equal. $O(2^N \cdot 26)$. |
An massive, branching decision tree where most paths are invalid. |
Take the string "aabb". Write out every combination: "a", "aa", "ab", "aab", etc. Count the letters in each and verify they match. |
Combinatorics + Frequency Counting. |
A character frequency table serving as the base for a series of binomial coefficient multiplications. |
Count frequencies of each letter. For a fixed frequency f, a letter with count c contributes Comb(c, f) ways if we pick f instances, or 1 way if we pick none. Multiply these contributions for all letters and repeat for all possible f. |
Write "a:3, b:2". Pick frequency f=1. Ways = (Comb(3,1)+1) * (Comb(2,1)+1) - 1. Repeat for f=2 and f=3. Sum the results. |
$O(26 \cdot N)$ where N is string length (to precompute factorials and iterate through possible frequencies). |
Draw a table of frequencies (26 rows). Show a loop iterating through possible "counts" from 1 to N. In each loop, show a quick calculation across the 26 rows. |
Exponential space for subsequences. |
$O(N)$ to store precomputed factorials for the Combinations formula. |
| 2540 |
Minimum Common Value |
Nested loops: For every element in nums1, check every element in nums2 to see if they match. $O(N \cdot M)$. |
Two arrays where every element in the first sends a "search ray" across the entirety of the second. |
Draw two lists. Start at the first item of List 1. Look through all of List 2. Not found? Move to the second item of List 1. Repeat. |
Two Pointers (Sorted Array Property). |
Two synchronized pointers "racing" through their respective arrays, only moving forward when they are "behind" the other. |
Compare nums1[i] and nums2[j]. If equal, that's your answer. If nums1[i] < nums2[j], increment i. Otherwise, increment j. Stop when a match is found or an array ends. |
Draw two sorted arrays. Put one finger on the start of each. Move the finger pointing to the smaller number. If they point to the same number, you found it. |
$O(N + M)$ linear time. |
Draw two arrays. Draw a single arrow over each moving strictly left-to-right, showing we never "go back" to re-check. |
N/A. |
$O(1)$ - Just two index variables. |
| 2541 |
Minimum Operations to Make Array Equal II |
Try every possible combination of adding/subtracting k to elements in nums1 to match nums2, checking all permutations. $O(\text{Exponential})$. |
A massive branching tree of state changes where each node represents a new version of the array. |
Draw the array. From each element, branch out +k and -k possibilities. This grows into a messy web of potential arrays. |
Greedy Difference Tracking + Parity Check. |
A "Balance Scale" where the total positive deviations must exactly equal the total negative deviations, and all gaps must be multiples of k.
[Image of balancing a scale with weights]
|
For each index, calculate diff = nums1[i] - nums2[i]. If k=0, check if nums1 == nums2. If k>0, ensure diff % k == 0. Sum the positive differences and negative differences. If posSum + negSum == 0, the answer is posSum / k. |
Draw a table with 3 columns: nums1, nums2, and Difference. Mark each difference as a multiple of k. Check if the sum of all differences is 0. If yes, count the "up-moves" (+ differences). |
$O(N)$ - A single linear scan through the array. |
Draw the array with one arrow moving left to right. Above the arrow, show a running tally of "needed additions" vs "needed subtractions." |
N/A. |
$O(1)$ - Just a few long/integer variables for sums. |
| 2542 |
Maximum Subsequence Score |
Generate all possible subsequences of size k. For each, find the sum of elements from nums1 and multiply by the minimum element in nums2. $O(\text{Comb}(N, k)$). |
A combinatorial explosion of all possible groups of k indices. |
Manually list every group of k items. For each group, calculate the sum and the min, multiply them, and write it down. Keep the biggest. |
Sorting + Min-Heap (Sliding Window of Top K). |
A "Priority Filter" that keeps the largest values of nums1 while sliding across nums2 sorted in descending order. |
Pair (nums2[i], nums1[i]) and sort by nums2 descending. Iterate through the pairs, pushing nums1 values into a Min-Heap. If heap size > k, pop the smallest. When size == k, calculate heapSum * current_nums2. |
Draw the sorted pairs. Draw a "Bucket" (Min-Heap) that holds k numbers. As you slide down the list, replace the smallest number in the bucket with the new one if the bucket is full. Multiply the bucket's sum by the current row's nums2. |
$O(N \log N)$ for sorting + $O(N \log k)$ for heap operations. |
Draw the sorted list. Draw a single arrow moving down. Beside it, show the heap shrinking/growing by exactly one element per step (log k). |
Exponential space for all combinations. |
$O(N)$ for sorting pairs + $O(k)$ for the priority queue. |
| 2543 |
Check if Point Is Reachable |
Simulate all possible moves (x, y+x), (x, y-x), (2x, y), (x, 2y) using BFS/DFS until (1, 1) is reached or coordinates exceed bounds. |
An infinite grid expansion where every coordinate pair can trigger four new paths. |
Start at (x, y). Draw arrows for all 4 operations. Follow every path. If you hit (1, 1), stop. |
Number Theory (GCD + Power of Two). |
A reverse-engineered math puzzle where the core components are stripped away until only powers of 2 remain.
[Image of Greatest Common Divisor calculation]
|
The only way to reach (1, 1) using these specific moves is if the GCD(targetX, targetY) is a power of 2. Simply calculate g = GCD(x, y) and check if (g & (g-1)) == 0. |
Write down x and y. Perform the Euclidean algorithm (repeated subtraction/modulo) to find the GCD. Once you have the GCD, check if it can be repeatedly divided by 2 until it becomes 1. |
$O(\log(\text{min}(x, y)$)) due to the efficiency of the Euclidean algorithm. |
Draw a division ladder (Euclidean algorithm). Show that the number of steps is very small relative to the size of the coordinates. |
Massive recursion stack or queue for BFS. |
$O(1)$ - Just the space needed to store the GCD result. |
| 2544 |
Alternating Digit Sum |
Convert the integer to a string. Loop through characters, convert to int, and multiply by (-1)^i. |
Data-type transformation pipeline (Int -> String -> Chars). |
Write "521". First digit: +5. Second: -2. Third: +1. Sum = 4. |
Math-based digit extraction (Modulo/Division). |
A stack-like extraction where signs are toggled, with a final correction if the total number of digits is even. |
Extract digits using n % 10 and store in a list (or use a recursive approach). Alternate signs starting from the *first* digit. If extracting from right-to-left, the sign of the last digit extracted depends on the total count of digits. |
Write the number. Peel off the last digit. Write it with a minus. Peel next, write with a plus. If you end on a minus but it was the first digit, flip all signs in your head. |
$O(\log10 N)$ - Linear relative to the number of digits. |
Draw a single horizontal line representing the digits. Show an arrow jumping between '+' and '-' for each digit. |
$O(D)$ where D is number of digits (if string converted). |
$O(1)$ if using math-based extraction. |
| 2545 |
Sort the Students by Their Kth Score |
Create a new list of objects or pairs containing the student's index and their k-th score. Sort this list, then reconstruct the matrix. $O(M \log M + M\cdot N)$. |
A mapping process where the original matrix is disassembled and rebuilt based on a secondary index. |
Draw the matrix. Circle the k-th column. Write those numbers on a separate sticky note with the row ID. Sort the sticky notes. Re-arrange the rows of the matrix to match. |
Custom Comparator / Lambda Sorting. |
A "Row-Swap" operation where rows are treated as single units and reordered based on a specific "Key" column. |
Use the built-in sort function on the matrix. Provide a custom comparison rule: "Compare Row A and Row B based on RowA[k] and RowB[k] in descending order." |
Draw the matrix. Look only at column k. Identify the largest number in that column—move that entire row to the top. Identify the second largest—move that row to second. Repeat. |
$O(M \log M)$ where M is the number of students (rows). Sorting takes M log M comparisons, each comparison is $O(1)$. |
Draw a vertical arrow pointing at column k. Draw a "Sorting Machine" symbol that takes the whole rows as input and outputs them reordered. |
$O(M\cdot N)$ to store the intermediate object mapping. |
$O(1)$ extra space if the sorting is done in-place (excluding the matrix itself). |
| 2546 |
Apply Bitwise Operations to Make Strings Equal |
Simulate every possible bitwise operation (s[i] OR s[j]) and (s[i] XOR s[j]) on all pairs of indices to see if s can transform into target. |
A state-space search tree where each node is a version of the string, branching into N^2 possibilities per level. |
Draw the string. Pick two bits, apply the rule, and draw the new string. Repeat until you find the target or run out of new strings. |
Logical Invariance (Existence of '1'). |
A simple "Presence Filter" where the only thing that matters is if at least one '1' exists to "seed" the operations. |
Check if '1' exists in s and if '1' exists in target. The operations allow a '1' to create more '1's or delete others, but they cannot create a '1' from an all-zero string, nor can they delete the very last '1'. Thus, (s.contains('1') == target.contains('1')). |
Write s and target. Simply circle any '1' you see in both. If both have at least one circle, or neither has a circle, it's possible. |
$O(N)$ to check for the character '1' in both strings. |
Draw two horizontal lines. Draw a single arrow over each. If a '1' is hit, stop and move to the next line. |
Massive recursion or queue for BFS state tracking. |
$O(1)$ - Just two boolean flags. |
| 2547 |
Minimum Cost to Split an Array |
Try every possible way to partition the array (2^N) and calculate the cost for each partition by checking trimmed lengths. |
A binary tree of "cut" decisions at every index, leading to exponential leaf nodes. |
Draw the array. Draw a vertical line at every possible gap. Calculate the "trimmed" cost of each segment. Sum them up for every combination. |
1D Dynamic Programming with Frequency Map optimization. |
A linear array of "best prices" where each index i stores the minimum cost to split the prefix nums[0...i]. |
Let dp[i] be the min cost for first i elements. For each j < i, dp[i] = min(dp[i], dp[j] + cost(j, i)). To compute cost(j, i) efficiently, use a frequency map to track how many elements appear more than once in the subarray. |
Draw an array of boxes for dp. At box i, look back at all previous boxes j. Calculate the cost of the segment from j to i, add it to dp[j], and pick the smallest result for dp[i]. |
$O(N^2)$ - Nested loops where the outer loop iterates through the array and the inner loop calculates the segment cost. |
Draw a matrix-like structure of look-backs. Show that for each element, you only look back at previous elements once. |
Exponential recursion stack. |
$O(N)$ for the DP table and a frequency array/map. |
| 2548 |
Maximum Price to Fill a Bag (Premium) |
Try all combinations of items (fractions included) to fill the bag, similar to the 0/1 Knapsack but with floating-point complexity. |
A complex search space of continuous variables (fractions). |
List items. Try taking 10% of one, 50% of another. This is impossible to draw manually for many items. |
Greedy Algorithm (Price-per-Weight Ratio). |
An "Efficiency Sort" where items are ranked by their value density and consumed from most to least dense. |
Calculate price/weight for each item. Sort items by this ratio descending. Fill the bag with full items as long as capacity > weight. For the last item, take a fraction remaining_capacity / weight * price. |
Write items as fractions: Price / Weight. Sort them. Pick the biggest fraction, subtract its weight from your bag's capacity. If it doesn't fit, multiply the fraction by your remaining capacity. |
$O(N \log N)$ for sorting the items by ratio. |
Draw a bar chart of ratios. Draw a "Bag" container. Fill the bag with the tallest bars first until it's full. |
N/A. |
$O(N)$ to store the items and their calculated ratios. |
| 2549 |
Count Distinct Numbers on Board |
Simulate the board day by day. For every number x on the board, check every i from 1 to n to see if x mod i == 1. Add new numbers and repeat for 10^9 days. |
A rapidly expanding set of numbers, with each number triggering N checks every single "day". |
Day 1: {n}. Day 2: Find all i where n mod i == 1. Add them to the set. Repeat. |
Mathematical Observation (Cascade Effect). |
A "Domino Effect" where n always brings in n-1, which brings in n-2, until every number down to 2 is on the board. |
If n > 1, n modn-1 = 1 is always true. Therefore, n-1 is added on Day 1. Then (n-1) modn-2 = 1 is true, adding n-2. This continues until 2. The only number never added is 1 (since x mod 1 is always 0). Result: n - 1. If n=1, result is 1. |
Write n. Note that n-1 always fits the rule. Then n-2 fits for n-1. Draw a line of numbers falling like dominoes. |
$O(1)$ - The answer is simply max(1, n-1). |
Draw a single box. Write the number n-1 inside. No movement or loops required. |
$O(N)$ to store all distinct numbers on the board across 10^9 days. |
$O(1)$ - No extra storage needed. |
| 2550 |
Count Collisions of Monkeys on a Polygon |
Generate all 2^n movement combinations. For each, check if any two monkeys land on the same vertex or cross paths. |
An exponential tree of 2^n binary choices (Clockwise vs. Counter-clockwise). |
Draw a triangle. Monkey 1 can go L or R. Monkey 2 can go L or R. List all 8 combinations and see which ones don't have collisions. |
Complementary Counting + Binary Exponentiation. |
A "Total minus Non-Colliding" logic where only two specific cases result in NO collisions. |
Total movements = 2^n. The ONLY ways monkeys *don't* collide are if all move clockwise or all move counter-clockwise (2 ways). Answer = (2^n - 2) mod10^9+7. Use pow(2, n, mod) for efficiency. |
Write 2^n. Subtract 2. Apply modulo. Use "Square and Multiply" to calculate 2^n on paper. |
$O(\log N)$ to calculate 2^n using modular exponentiation. |
Draw a ladder of powers: 2^1, 2^2, 2^4, 2^8... showing that we only need log n steps to reach 2^n. |
Exponential space for combinations. |
$O(1)$ - Just storing the result of the power function. |
| 2551 |
Put Marbles in Bags |
Generate all possible ways to partition the array into k non-empty subarrays. For each, calculate the score (sum of first and last elements of each bag) and find the max and min difference. $O(\text{Exponential})$. |
A combinatorial explosion of "cut" points across the array. |
Draw the array. Try placing k-1 dividers in every possible combination of slots. Calculate the score for each. |
Sorting Pair Sums (Boundary Logic). |
A "Divider Optimization" visual where we only care about the values adjacent to the cuts. |
A cut between `nums[i]` and `nums[i+1]` adds `nums[i] + nums[i+1]` to the total score. Collect all N-1 possible adjacent pair sums. Sort them. The max score uses the k-1 largest sums; the min score uses the k-1 smallest. Subtract to get the answer. |
Write the array. Calculate sums of every two adjacent numbers (1+2, 2+3, etc.). List these sums. Pick the k-1 biggest and the k-1 smallest. Subtract the totals. |
$O(N \log N)$ due to sorting the pair sums. |
Draw the array with N-1 "plus" signs between elements. Draw a sorting box for these sums, and a subtraction sign between the top k and bottom k results. |
Exponential recursion stack for partitions. |
$O(N)$ to store the N-1 pair sums. |
| 2552 |
Count Increasing Quadruplets |
Four nested loops checking every combination of i < j < k < l such that nums[i] < nums[k] < nums[j] < nums[l]. $O(N^4)$. |
A 4D hypercube of index comparisons, incredibly dense and slow. |
Write 4 indices. Manually check the "zigzag" condition (i < j < k < l and the specific value order) for every single possible set of 4 numbers. |
2D Prefix Sums / Precomputation of "Smaller" and "Greater" counts. |
A "Pivot-Point" visual focusing on the middle pair (j, k) and counting valid i's and l's using precomputed tables. |
Fix j and k. We need the count of i < j where nums[i] < nums[k] and the count of l > k where nums[l] > nums[j]. Precompute a 2D array `less[x][val]` (count of elements before index x smaller than `val`) to answer these in $O(1)$ during the $O(N^2)$ loop over j and k. |
Draw the array. Fix two middle fingers on j and k. Look left for small numbers and right for large numbers. Use a pre-written table to instantly get those counts instead of manual counting. |
$O(N^2)$ to precompute the prefix tables and $O(N^2)$ to iterate through all (j, k) pairs. |
Draw an N x N grid for precomputation. Below it, draw a standard nested loop diagram (triangle) representing the j, k search. |
$O(1)$ extra space (excluding input). |
$O(N^2)$ to store the precomputation tables (e.g., `greaterThan` or `smallerThan` arrays). |
| 2553 |
Separate the Digits in an Array |
Convert the whole array to a single string, then iterate through the string to create a new integer array. |
A string concatenation pipeline that creates massive temporary objects in memory. |
Write [13, 25]. Write "1325". Then write [1, 3, 2, 5]. |
Iterative Digit Extraction (Modulo & Stack). |
A "Digit Peeler" where each number is broken down from right to left, then reversed or appended to a result list. |
For each number in the array, extract digits using % 10. Since this gives digits in reverse (e.g., 13 -> 3, 1), store them in a temporary stack or list and reverse them, then append to the final answer. |
Draw the array. Under each number, draw a small vertical list of its digits. Then read the entire page left-to-right, top-to-bottom. |
$O(\text{Total Number of Digits})$, which is effectively $O(N)$ given constraints. |
Draw an arrow moving through the array. At each stop, draw a "mini-loop" that spins until the number is 0. |
$O(D)$ where D is the total string length of all numbers. |
$O(N)$ to store the final result list. |
| 2554 |
Maximum Number of Integers to Choose From a Range I |
Generate all possible subsets of integers from 1 to n that don't contain banned numbers, check if the sum <= maxSum, and find the largest subset size. $O(2^n)$. |
A massive power-set search tree. |
List all numbers from 1 to n. Try picking every combination. If it's banned or too heavy, cross it out. |
Greedy Selection + Hash Set Lookup. |
A "Sieve and Sack" approach: filter the banned numbers and pack the smallest remaining numbers into a "sack" until it's full. |
Put `banned` into a Hash Set for $O(1)$ lookup. Iterate i from 1 to n. If i is not in the set and currentSum + i <= maxSum, add i to the count and update the sum. Because we start from 1 (the smallest), we naturally maximize the count. |
Write 1 to n. Cross out the banned numbers. Start circling the remaining numbers from left to right. Stop when the sum of circled numbers exceeds maxSum. |
$O(N + B)$ where B is the size of the banned list. |
Draw a timeline from 1 to n. Draw a single arrow moving left to right. Mark "X" for banned and "O" for chosen. |
Exponential space. |
$O(B)$ to store the banned numbers in a Hash Set. |
| 2555 |
Maximize Win From Two Segments |
Try every possible pair of segments (s1, e1) and (s2, e2) of length k. For each pair, count the number of prizes covered and find the max. $O(N^2)$ or $O(N^4)$. |
A dense search of overlapping or separate windows across the prize line. |
Draw the prize positions. Take two physical rulers of length k. Try placing them in every possible way and count the dots under them. |
Sliding Window + Dynamic Programming (Prefix Max). |
Two "Competitive Sliders" where the first slider finds the best single segment for every endpoint, and the second slider uses that info to maximize the total. |
Use two pointers to find the max prizes covered by a single segment of length k ending at or before index i (store this in dp[i]). Then, for a second segment ending at j, the total prizes = (count in current segment) + dp[j - current_segment_length]. |
Draw the prizes. Slide a window of length k. Write down the "best score so far" in a row of boxes below. Then, at each step, add the "current window score" to the "best score found before this window started." |
$O(N)$ - Linear scan with two pointers. |
Draw the prize array. Draw two sliding windows. Show the first one leaving a trail of "max values" that the second one picks up. |
$O(N^2)$ to store counts of all possible segments. |
$O(N)$ for the DP array to store the prefix maximums. |
| 2556 |
Disconnect Path in a Binary Matrix by at Most One Flip |
Generate every possible path from top-left to bottom-right. For every cell in the grid, try flipping it to 0 and re-check if any path still exists. $O(M x N x 2^M+N)$. |
A massive recursion tree where each leaf represents a grid state being searched for paths. |
Draw a grid. Pick a cell, cross it out. Try to find a path using only Right and Down moves. Repeat this for every single cell in the grid. |
Double DFS / Max Flow Min Cut (Path Neutralization). |
A "Path Erosion" visual: finding a path, removing it from the grid entirely, and seeing if a second path can still survive. |
Run a DFS to find any path from (0,0) to (M-1,N-1). If no path exists, return True (already disconnected). If a path exists, "burn" the path by setting all its cells (except start and end) to 0. Run a second DFS. If no second path exists, return True. |
Draw a grid. Trace a path with a pencil. Erase that pencil line so those cells are now "walls." Try to draw a new path with a pen. If you can't reach the end, one flip is enough. |
$O(M \cdot N)$ - Two passes of DFS. |
Draw two grid diagrams. Draw a single arrow path in the first. Draw an "X" over that path in the second. Draw a second arrow attempting to bypass the "X"s. |
Exponential recursion stack for all grid states. |
$O(M \cdot N)$ for the recursion stack and visited matrix. |
| 2557 |
Maximum Number of Integers to Choose From a Range II (Premium) |
Similar to the basic version, but with N up to 10^9. Iterating 1 to 10^9 will result in Time Limit Exceeded (TLE). $O(N)$. |
A billion-step loop that crashes the browser/environment. |
Draw a line from 1 to 1,000,000,000. Start counting and adding. You will run out of paper. |
Sorting + Binary Search on Answer Space. |
A "Jump Search" over the number line, using mathematical formulas (Arithmetic Progression) to skip large empty gaps. |
Sort the `banned` list. Binary search for the maximum integer X such that the sum of 1 to X (minus banned numbers <= X) is <= `maxSum`. The number of chosen integers is X minus the count of banned numbers <= X. |
Write the banned numbers. Guess a number X=100. Calculate sum 1...100 using n(n+1)/2. Subtract the sum of banned numbers < 100. If too small, guess X=200. Use binary search to narrow it down. |
$O(B \log B + \log N)$ where B is the number of banned elements. Sorting takes B log B, and binary search takes log N. |
Draw a timeline with a few "banned" clusters. Draw a large bracket jumping across the timeline, showing it lands on the optimal X in very few steps. |
$O(N)$ array to track used numbers. |
$O(B)$ to store and sort the banned list. |
| 2558 |
Take Gifts From the Richest Pile |
For each of the k seconds, sort the entire array to find the maximum, square root it, and replace it. $O(k x N \log N)$. |
Repeatedly shuffling a deck of cards just to find the top card, k times. |
Write 5 numbers. Sort them. Square root the biggest. Re-write the list. Sort again. Repeat k times. |
Max-Heap (Priority Queue). |
A "King of the Hill" structure where the largest value is always at the top and easily replaceable. |
Convert the array into a Max-Heap (O(N)). Repeat k times: Pop the largest value, calculate its square root, and push it back (O(log N)). After k steps, sum all values in the heap. |
Draw a triangle (heap). Put the biggest number at the top. Remove it, root it, put the smaller result back. Watch it "sink" into the triangle. Repeat k times. |
$O(N + k \log N)$. Heapify is linear, and k extractions/insertions are logarithmic. |
Draw a tree of height log N. Show k arrows traveling down the height of the tree. |
New sorted array copies. |
$O(N)$ to store the elements in the priority queue. |
| 2559 |
Count Vowel Strings in Ranges |
For every query [l, r], loop through the array from l to r and check each string if it starts and ends with a vowel. $O(Q x N)$. |
A searchlight scanning over the same parts of the array over and over for different queries. |
Draw the list of strings. For Query A, count the vowels from index 2 to 10. For Query B, count from 3 to 11. Notice you are counting index 3 to 10 twice. |
Prefix Sum Array. |
A "Cumulative Scorecard" where the answer for any range is found by subtracting two pre-calculated values. |
Create a binary array where 1 means "vowel string" and 0 means "not." Build a prefix sum array P where P[i] is the total vowel strings from index 0 to i. For any query [l, r], the answer is P[r] - P[l-1] in $O(1)$. |
Draw the strings. Below them, write '1' or '0'. Below that, write the running total (e.g., 0, 1, 1, 2, 3...). To find the count between two points, just subtract the two numbers at those points. |
$O(N + Q)$. Linear time to build the prefix sum, then constant time per query. |
Draw an array of strings. Draw one single arrow sweeping across to build the sum array. Then draw Q small dots representing the instant lookups. |
N/A. |
$O(N)$ to store the prefix sum array. |
| 2560 |
House Robber IV |
Find all possible combinations of non-adjacent houses to rob such that you pick at least k houses, then find the minimum of the maximum values in those combinations. $O(2^N)$. |
An enormous decision tree where every branch checks non-adjacency constraints. |
Draw the houses. Try picking every possible group of k houses that aren't neighbors. Write down the highest value in each group. |
Binary Search on Answer Space + Greedy Counting. |
A "Threshold Filter" - picking a maximum capability and seeing if you can still rob k houses under that limit. |
Binary search for the "minimum maximum capability" X. For a fixed X, use a greedy approach: walk through the houses and rob every house <= X as long as you didn't rob the previous one. If you can rob >= k houses, try a smaller X. |
Write the house values. Pick a target X=10. Go through the list: "Can I rob this house? (Is it <= 10 and neighbor not robbed?)". Count how many. If count >= k, try X=5. |
$O(N \log(\text{Max}_\text{Value})$). Linear check inside a logarithmic search. |
Draw a range from min to max house value. Draw brackets halving the range. Inside each bracket, draw a quick linear arrow under the houses. |
Exponential space for combinations. |
$O(1)$ extra space (excluding input). |
| 2561 |
Rearranging Fruits |
Generate every possible sequence of swaps to make the frequency of each fruit identical in both baskets. $O(\text{Factorial}/\text{Exponential})$. |
A chaotic web of fruit exchanges, trying every fruit with every other fruit. |
Draw two baskets. Try swapping Apple 1 with Orange 2. Then try Apple 1 with Banana 1. Track the cost each time. |
Frequency Mapping + Greedy Pairing + Min-Cost Observation. |
A "Difference List" visualization where only the fruits that need to move are sorted and paired with the cheapest available fruit in either basket.
[Image of frequency distribution chart]
|
Calculate target frequency (sum of counts / 2). Identify "excess" fruits in both baskets. Sort all excess fruits in one list. Pair the smallest excess fruits with the smallest from the other side. Note: you can also use the absolute minimum fruit in either basket as a "bridge" (cost = 2 * min_fruit). |
List the fruits that need to be moved from Basket A and those from Basket B. Sort them. Compare the cost of swapping them directly vs. using the global cheapest fruit twice. Sum the minimums. |
$O(N \log N)$ for sorting the differences. |
Draw two frequency tables. Draw a single list of "Fruits to Swap." Show a sorting box and a final math comparison (Direct vs. Bridge). |
N/A. |
$O(N)$ to store the fruit frequencies and the list of fruits to be swapped. |
| 2562 |
Find the Array Concatenation Value |
While the array is not empty, convert the first and last elements to strings, concatenate them, convert back to integer, and add to sum. Remove the elements. $O(N^2)$ due to array resizing. |
A shrinking array where the middle is repeatedly re-indexed and strings are constantly created. |
Write [10, 5, 3]. Pick 10 and 3. Write "103". Delete 10 and 3. Now you have [5]. |
Two-Pointer Iteration + Mathematical Concatenation. |
Two pointers closing in on the center of the array, calculating concatenation values without string conversion. |
Set i = 0, j = N-1. While i < j, calculate concatenation: nums[i] * 10^(digits in nums[j]) + nums[j]. Add to sum. Increment i, decrement j. If i == j, add the remaining middle element. |
Draw the array. Put left and right fingers on the ends. Calculate the "merged" value. Move fingers inward. If they meet on one number, just add that number. |
$O(N)$ - Single pass over the array with constant time math per step. |
Draw an array. Draw two arrows starting at the ends and meeting in the middle. Show a "Concatenation" box above them. |
$O(N)$ for string copies and array slicing. |
$O(1)$ - Just pointers and a sum variable. |
| 2563 |
Count the Number of Fair Pairs |
Use two nested loops to check every pair (i, j) where i < j and see if their sum falls in the range [lower, upper]. $O(N^2)$. |
A triangle of index checks (N x N / 2) covering all possible pairs. |
Draw the array. Pick the first number. Check its sum with every other number. Pick the second number. Repeat. |
Sorting + Two Pointers (or Binary Search). |
A "Sliding Boundary" on a sorted array where pointers find the valid range of j for every i. |
Sort the array. For each index i, find the range of indices [left, right] such that nums[i] + nums[left] >= lower and nums[i] + nums[right] <= upper. Total count is the sum of (right - left + 1) for all i. |
Draw a sorted array. Pick a number. Use two "boundary markers" to find the first and last numbers that, when added to your picked number, stay within the limits. Count the distance between markers. |
$O(N \log N)$ for sorting. The two-pointer search is $O(N)$. |
Draw a sorted number line. Draw a fixed pointer i and a "sliding window" for j that shifts smoothly as i moves. |
N/A. |
$O(1)$ extra space beyond the sorting overhead. |
| 2564 |
Substring XOR Queries |
For every query [val, target], calculate xor_sum = val ^ target. Convert xor_sum to binary, then search for that binary string in the main string using s.find(). $O(Q \cdot N)$. |
A repeated text search where the "search term" changes for every single query. |
Query: 5 XOR 2 = 7 (111). Look through "10110111..." for "111". Found it? Note the indices. Repeat for next query. |
Precomputation of All Substrings (up to 30 bits) + Hash Map. |
A "Binary Dictionary" where every possible numerical value found in the string is indexed by its first occurrence. |
Since values are 10^9, they fit in 30 bits. Iterate through the string and for every index i, look at substrings of length 1 to 30. Convert to integer and store {value: [start, end]} in a map (only if not already present). Answer queries in $O(1)$ by calculating val ^ target and looking it up. |
Draw the string. Write down every number formed by 1-3 digits. Index them: "1" at 0, "10" at 0, "101" at 0, "0" at 1.... To answer a query, just check your index list. |
$O(N \cdot 30 + Q)$. Linear scan to build the map (max 30 look-ahead), then constant time queries. |
Draw the string. Draw a "sliding window" of max length 30 moving across. Show the values being stored in a central "Map" box. |
N/A. |
$O(N \cdot 30)$ to store the starting and ending indices in the map. |
| 2565 |
Subsequence With the Minimum Score |
Try deleting every possible substring from t. For each remaining part, check if it's a subsequence of s. $O(M^3)$. |
A brute-force check of all M^2 substrings being validated against string s. |
Write string t. Delete "abc". Is the rest in s? No. Delete "bc". Is the rest in s? Yes. Keep track of the shortest deletion. |
Two-Pass Prefix/Suffix Matching + Sliding Window. |
A "Match-from-Ends" visual: finding how far `t` can match `s` from the left and how far from the right, then finding the smallest gap. |
Precompute left[i]: the furthest index in s that matches t[0...i]. Precompute right[j]: the furthest index in s that matches t[j...M-1]. Use a sliding window to find indices i and j such that left[i] < right[j], minimizing j - i - 1. |
Draw strings s and t. Match t from the left as far as possible. Match t from the right as far as possible. Find where the "left-match" and "right-match" can meet or overlap. |
$O(N + M)$. One pass for prefix matching, one for suffix, and one to find the minimum score. |
Draw string s in the middle. Draw t matching from the left above it and t matching from the right below it. Show the gap between them shrinking. |
N/A. |
$O(M)$ to store the prefix and suffix match indices. |
| 2566 |
Maximum Difference by Remapping a Digit |
Try remapping every digit (0-9) to 9 to find the maximum, and remapping every digit to 0 to find the minimum. Compare all results. $O(10 \cdot 10 \\text{cdot Digits})$. |
A "Brute Force Replacement" table where every digit takes a turn being swapped out and tested. |
Write the number. Change all '1's to '9's, then all '2's to '9's. Pick the biggest. Then change all '1's to '0's, then '2's to '0's. Pick the smallest. Subtract. |
Greedy First-Digit Replacement. |
A "Priority Swap" visual where we target the leftmost non-9 digit for the max and the leftmost digit for the min. |
To Maximize: Find the first digit that is not '9' and replace all occurrences of that digit with '9'. To Minimize: Take the very first digit and replace all occurrences of it with '0'. Subtract the two resulting numbers. |
Write the number. For Max: Circle the first digit that isn't a 9. Turn every digit like it into a 9. For Min: Circle the first digit. Turn every digit like it into a 0. Subtract the results. |
$O(\text{Digits})$ - A single pass to find the target digit and another to replace. |
Draw a horizontal line of digits. Draw one arrow to find the "target" and another arrow to perform the swap. |
N/A. |
$O(\text{Digits})$ to store the number as a string for easy replacement. |
| 2567 |
Minimum Score by Changing Two Elements |
Try changing every possible pair of elements to every other possible value and calculate the score (High-Low + MaxDiff). $O(N^2 \cdot V^2)$. |
A massive combinatorial grid of "what if" scenarios for changing two values. |
Write 5 numbers. Change the first and second to 10. Check score. Change first and third to 10. Check score. This is impossible for large N. |
Boundary Analysis (Sorting). |
A "Targeting the Extremes" visual: since only the max and min affect the score, we only ever care about changing the 2 smallest or 2 largest elements. |
Sort the array. You have three choices to minimize the range: 1) Change the two smallest elements. 2) Change the two largest elements. 3) Change the smallest and the largest element. The answer is the minimum of: nums[n-1] - nums[2], nums[n-3] - nums[0], and nums[n-2] - nums[1]. |
Draw a sorted line of numbers. Pick the 3 smallest and 3 largest. Draw brackets for the three scenarios above and measure the width of the remaining "active" numbers. |
$O(N \log N)$ for sorting the array. |
Draw a sorted array. Draw three different brackets over the elements, showing we only check three specific configurations of the endpoints. |
Exponential space for all combinations. |
$O(1)$ extra space (or sorting overhead). |
| 2568 |
Minimum Impossible OR |
Generate every possible subsequence, calculate the bitwise OR for each, and store them in a Hash Set. Then check 1, 2, 3... until one is missing. $O(2^N)$. |
A massive power-set branching tree for OR combinations. |
List the array. XOR 1 with 2, 1 with 4, 1 with 2 with 4... Keep a list of all results and find the first missing integer. |
Power of Two Check (Bit Manipulation). |
A "Binary Completeness" visual: the only way to NOT be able to form a power of two (2^x) via OR is if that specific power of two is missing from the input. |
Store the array in a Hash Set. Check if 1 is in the set. If not, 1 is the answer. If yes, check 2. If yes, check 4, 8, 16... The first power of 2 (2^n) that is *not* in the array is the first number that cannot be formed by an OR sum. |
Write the array. Check: Is 1 there? Yes. Is 2 there? Yes. Is 4 there? No. Answer is 4. |
$O(N)$ - Linear pass to build the set and 30 constant-time lookups. |
Draw a set box. Draw an arrow sweeping the array into the box. Then draw a small loop 1, 2, 4, 8... pointing into the box. |
Exponential space for all possible OR sums. |
$O(N)$ to store the elements in a Hash Set. |
| 2569 |
Handling Sum Queries After Update |
For every "flip" query, loop through the array and flip bits. For "sum" queries, count 1s in nums1 and multiply. $O(Q \cdot N)$. |
A heavy "Array Toggle" operation that touches every element for every update. |
Draw the bits. Flip index 2 to 5. Manually flip them. Then count all the 1s in the whole array. Repeat for every query. |
Segment Tree with Lazy Propagation. |
A "Hierarchy of Ranges" where we flip entire blocks of the array at once without visiting individual elements. |
Build a Segment Tree where each node stores the count of 1s in its range. "Flip" becomes a range-update: for a range [L, R], the number of 1s becomes (R - L + 1) - current_ones. Use a lazy tag to delay updates to children. Query 3 is a constant time sum update based on SegmentTree.root.totalOnes * p. |
Draw a tree where each leaf is a bit. Each parent shows the sum of 1s below it. When flipping a range, just flip the parent and mark a "Pending Flip" tag on the children. |
$O((N + Q)$ log N). Building and updating the Segment Tree are logarithmic per query. |
Draw a balanced binary tree. Highlight a path from the root down to a range, showing we only touch $O(\log N)$ nodes. |
N/A. |
$O(N)$ - Specifically 4 x N to store the Segment Tree array. |
| 2570 |
Merge Two 2D Arrays by Summing Values |
Combine both arrays into one, sort by ID, and then iterate through to merge duplicate IDs. $O((N+M)$ log (N+M)). |
A "Shuffle and Sort" visual where everything is thrown into a pile before being organized. |
Write all pairs from both arrays into one long list. Sort by the first number. If you see two IDs that are the same, add their second numbers together. |
Two-Pointer Merging (Sorted Property). |
A "Zipper Merge" where two sorted streams are combined into one in a single pass. |
Set i = 0, j = 0. Compare nums1[i][0] and nums2[j][0]. If i.ID < j.ID, add nums1[i] to result and move i. If j.ID < i.ID, add nums2[j] and move j. If i.ID == j.ID, sum values and move both. |
Draw the two sorted lists. Place a finger at the start of each. Move the finger pointing to the smaller ID. If they match, sum the values. Record the results on a third piece of paper. |
$O(N + M)$ - Linear time because the inputs are already sorted. |
Draw two horizontal arrays. Draw a single "Merge" funnel below them that takes elements from the pointers and outputs a single sorted list. |
$O(N + M)$ for the combined unsorted array. |
$O(N + M)$ for the output array only. |
| 2571 |
Minimum Operations to Reduce an Integer to 0 |
Recursively try adding or subtracting every possible power of 2 (2^x) at each step until the number reaches 0. $O(\text{Exponential})$. |
A wide-branching recursion tree where each node represents a number and branches represent pm 2^x. |
Write the number 39. Try 39-32=7, 39+32=71. From 7, try 7-8, 7-4, etc. Find the shortest path to 0. |
Greedy Bit Manipulation (Low-bit Analysis). |
A "Bitwise Cleanup" visual where we handle clusters of 1-bits by either clearing them one-by-one or jumping past them with an addition. |
Look at the binary representation. If you see a lone '1', subtract it (1 op). If you see a cluster of two or more '1's (e.g., `...0111`), add 1 to the lowest bit to turn it into `...1000` (1 op), effectively clearing the whole cluster in fewer steps. |
Write the number in binary. Circle clusters of 1s. If a cluster has length 1, cross it out. If length > 1, add 1 to the end of it and handle the carry. Count each "fix" as one operation. |
$O(\text{Number of Bits})$ - Linear relative to the binary length of the number. |
Draw the binary string. Draw a single arrow moving right-to-left, making "tally marks" whenever you encounter a 1-bit or start a carry. |
Massive recursion stack for all power-of-2 combinations. |
$O(1)$ - Just a few integer variables to track the number and the count. |
| 2572 |
Count the Number of Square-Free Subsets |
Generate all 2^N subsets. For each, check if the product of its elements is "square-free" (not divisible by any x^2 > 1). $O(2^N \cdot N)$. |
An enormous power-set tree with a heavy primality/square-free check at every leaf. |
List the array. Write every combination. Check if any combo has a product divisible by 4, 9, 25. Count the valid ones. |
Bitmask Dynamic Programming (Primes as Bits). |
A "Prime Puzzle" where each number is a piece that covers specific prime "slots." You can't use two pieces that cover the same slot. |
Only numbers up to 30 matter. Primes < 30 are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 (10 total). Represent each square-free number as a 10-bit mask of its prime factors. Use DP: `dp[mask]` is the number of subsets using these primes. For each number, if its mask doesn't overlap with the current DP state, add it. |
Draw 10 slots (for the 10 primes). Take a number like 6 (mask: 2 and 3). If you have a subset already using 5, you can add 6. If you have one already using 2, you can't. Record the number of ways in a table of 2^10 (1024) rows. |
$O(N \cdot 2^{10})$ - N elements multiplied by the small constant bitmask space. |
Draw the array. Below it, draw a table with 1024 rows. Show each array element updating multiple rows in the table simultaneously. |
Exponential space for 2^N subsets. |
$O(1024)$ - A fixed-size array for the DP states. |
| 2573 |
Find the String with LCP |
Try every possible string of length N using lowercase letters and check if its Longest Common Prefix (LCP) matrix matches the input. $O(26^N)$. |
An impossible branching tree of all possible strings of length N. |
Start with 'a'. Then 'aa', 'ab', 'ac'... For each, build an N x N matrix and compare it to the input. |
Union-Find / Greedy Coloring + LCP Verification. |
A "Connectivity Map" where the LCP matrix tells us which characters *must* be identical, followed by a suffix-link validation. |
If `LCP[i][j] > 0`, then `s[i]` must equal `s[j]`. Group these indices using Union-Find. Assign the smallest possible characters ('a' to 'z') to groups greedily. Finally, verify the generated string: `LCP[i][j]` should equal `(s[i] == s[j] ? 1 + LCP[i+1][j+1] : 0)`. |
Draw N circles. Look at the LCP matrix: if `LCP[i][j] > 0`, draw a line between circle i and circle j. Color connected circles with the same letter. Then, double-check that the "prefix length" rules are actually followed. |
$O(N^2)$ - To iterate through the matrix for Union-Find and the final verification. |
Draw the N x N matrix. Draw one arrow sweeping the matrix to build groups, and another arrow performing the DP-based verification. |
N/A. |
$O(N^2)$ to store the input matrix and $O(N)$ for Union-Find/string storage. |
| 2574 |
Left and Right Sum Differences |
For every index i, run one loop from 0 to i-1 for the left sum and another loop from i+1 to N-1 for the right sum. $O(N^2)$. |
An array where every element triggers two full scans of its neighbors. |
Write [10, 4, 8]. For 4: Left is 10, Right is 8. Diff is 2. Repeat for 10 and 8. |
Prefix and Suffix Running Totals. |
A "Total Balance" visual: subtracting the current prefix sum from the total sum to find the suffix sum in $O(1)$. |
Calculate the total sum of the array first. Iterate through the array, maintaining a `leftSum`. The `rightSum` is simply `totalSum - leftSum - nums[i]`. Calculate the absolute difference and update `leftSum` for the next step. |
Write the array. Calculate the total. Start a "Running Left Sum" at 0. At each number, calculate `Total - LeftSum - Current`. Write the result. Add `Current` to `LeftSum`. |
$O(N)$ - One pass to get the total, one pass to calculate the differences. |
Draw the array. Draw one arrow getting the total sum. Draw a second arrow moving through, with a "running tally" counter updating as it goes. |
N/A. |
$O(N)$ to store the result array. |
| 2575 |
Find the Divisibility Array of a String |
For every prefix of the string, convert it to a BigInteger and check if `prefix % m == 0`. $O(N^2)$ due to string/BigInt handling. |
A growing list of massive numbers being re-calculated and re-parsed. |
String "121", m=3. Check 1%3. Then check 12%3. Then check 121%3. |
Modular Arithmetic (Iterative Remainder). |
A "Rolling Remainder" visual: building a number one digit at a time and only keeping the remainder to prevent overflow. |
Initialize `currentRemainder = 0`. For each character `c` in the string: `currentRemainder = (currentRemainder * 10 + digit(c)) % m`. If the remainder is 0, the answer for that index is 1, otherwise 0. |
Write "121", m=3. Start with 0. 1st digit: (0 x 10 + 1) % 3 = 1. 2nd digit: (1 x 10 + 2) % 3 = 0. 3rd digit: (0 x 10 + 1) % 3 = 1. Result: `[0, 1, 0]`. |
$O(N)$ - A single pass through the string with constant-time math at each step. |
Draw the string. Draw an arrow moving left to right. Above the arrow, show a small "box" that only ever holds a number smaller than m. |
$O(N^2)$ for substring and BigInt allocations. |
$O(N)$ for the final result array (O(1) extra space excluding result). |
| 2576 |
Find the Maximum Number of Marked Indices |
Check every possible combination of pairs (i, j) such that 2 * nums[i] <= nums[j] and maximize the number of unique indices used. $O(\text{Exponential})$. |
A massive matching web where every element tries to find a partner that satisfies the 2x constraint. |
Write the array. Draw lines connecting numbers to their 2x counterparts. Try different pairings to see which set covers the most numbers. |
Sorting + Greedy Two-Pointer (Split Search). |
A "Lower-Half to Upper-Half" matching visual, where we only try to pair the smallest elements with the elements in the second half of the array. |
Sort the array. Split it into two halves. Place pointer `i` at the start of the first half (index 0) and pointer `j` at the start of the second half (index n/2). If 2 * nums[i] <= nums[j], it's a valid pair; increment both and add 2 to score. Else, just increment `j`. |
Draw a sorted array. Draw a vertical line in the middle. Put your left finger at the very start and right finger at the middle line. If the right is >= 2x the left, "match" them and move both fingers. If not, only move the right finger. |
$O(N \log N)$ for sorting, followed by $O(N)$ for the single-pass two-pointer scan. |
Draw the sorted array. Draw a horizontal arrow for the first half and another for the second half, showing they only move forward once. |
N/A. |
$O(1)$ extra space beyond the sorting overhead. |
| 2577 |
Minimum Time to Visit a Cell In a Grid |
Use Breadth-First Search (BFS) to explore all paths, but since time depends on the cell value, the number of states can explode if you wait in place. $O(\text{Exponential})$. |
A grid expansion where every cell creates "wait" cycles, making the search tree infinitely deep. |
Start at (0,0). Move to (0,1) at time 1. If (0,2) requires time 10, try moving back and forth between (0,0) and (0,1) until it's time 10. |
Dijkstra's Algorithm + Parity Waiting Logic. |
A "Weighted Pathfinding" visual where the time spent at each cell is calculated based on the distance and the parity of the waiting time. |
If `grid[0][1] > 1` and `grid[1][0] > 1`, you can never leave the start; return -1. Otherwise, use a Priority Queue to store `(time, r, c)`. When moving to a neighbor, if `time + 1 >= grid[nr][nc]`, the arrival time is `time + 1`. If not, you must wait: the arrival time is `grid[nr][nc]` plus a parity offset (either 0 or 1). |
Draw the grid. In each cell, write the earliest time you can reach it. Use a priority queue to always expand the cell with the smallest time. If you hit a wall too early, "ping-pong" between your current and previous cell to waste time. |
$O(M \cdot N \cdot \log(M \cdot N)$) due to Dijkstra's priority queue operations on the grid. |
Draw a grid. Draw "wavefronts" of time values expanding from the top-left, with specific time jumps annotated on cells with high threshold values. |
N/A. |
$O(M \cdot N)$ for the Priority Queue and the visited/dist matrix. |
| 2578 |
Split With Minimum Sum |
Generate all possible ways to split the digits into two numbers and find the pair with the smallest sum. $O(\text{Exponential})$. |
A combinatorial tree of digit assignments (e.g., digit 1 goes to Num A or Num B). |
Write the digits of 4325. Try (4, 325), (43, 25), (42, 35)... Calculate all sums and pick the minimum. |
Sorting + Greedy Alternating Distribution. |
A "Digit Alternation" visual where sorted digits are dealt out like cards to two players to keep the leading digits as small as possible. |
Sort the digits of the number in ascending order. Iterate through the sorted digits and alternate adding them to `num1` and `num2`. For example, digits `[2, 3, 4, 5]` become `num1 = 24` and `num2 = 35`. Sum them up. |
Write the number 4325. Sort the digits: 2, 3, 4, 5. Write two empty slots: `_ _` and `_ _`. Put the 2 in the first slot of Num A, 3 in the first slot of Num B, 4 in the second of Num A, 5 in the second of Num B. Add 24 + 35. |
$O(D \log D)$ where D is the number of digits. (D is small, so practically $O(1)$). |
Draw the sorted digits. Draw two arrows pointing to two different buckets, alternating for each digit. |
N/A. |
$O(D)$ to store the digits in a list for sorting. |
| 2579 |
Count Total Number of Colored Cells |
Simulate the coloring process step-by-step for n minutes, tracking the coordinates of every colored cell in a set. $O(n^2)$. |
A growing diamond shape on a grid where new cells are added to the perimeter every minute. |
Minute 1: 1 cell. Minute 2: Add 4 cells around it. Minute 3: Add the next layer of 8 cells. Count them manually. |
Mathematical Progression (Sum of Arithmetic Series). |
A "Geometric Expansion" visual where the diamond area is decomposed into a central square and four triangles, or simply a quadratic formula. |
The number of new cells added at minute k is 4 * (k-1). The total after n minutes is 1 + sum_i=1^n-1 4i. This simplifies to 1 + 4 * (n * (n-1) / 2), which is 1 + 2 * n * (n-1). Or visually, n^2 + (n-1)^2. |
Draw the diamond for n=3. Notice it looks like a 3 x 3 grid but with the corners missing? Or look at it as a 3 x 3 square plus a 2 x 2 square nested inside. Write the formula: 3^2 + 2^2 = 13. |
$O(1)$ - Constant time using the derived formula. |
Draw a single box with the formula n^2 + (n-1)^2 written inside. No loops or iterations. |
$O(n^2)$ to store all coordinates in a Set. |
$O(1)$ - Just the space for the long integer result. |
| 2580 |
Count Ways to Group Overlapping Ranges |
Check every possible grouping of ranges (2^N) and for each, verify if overlapping ranges are in the same group. $O(2^N \cdot N)$. |
A power-set tree of group assignments with a heavy overlap check for each. |
Range A, B, C. Try (A, B) in Group 1, C in Group 2. If A and C overlap, this is invalid. Try all combinations. |
Sorting + Merge Intervals + Modular Exponentiation. |
A "Range Merging" visual where overlapping intervals collapse into "islands," and each island can independently be in one of two groups. |
Sort the ranges by their start time. Iterate through and merge all overlapping intervals into distinct groups. If there are G non-overlapping groups, each can be assigned to either group 1 or group 2 independently. The total ways are 2^G mod10^9+7. |
Draw the intervals as horizontal lines. If two lines overlap, "glue" them together. Count how many separate "glued" segments you have. Calculate 2 to the power of that count. |
$O(N \log N)$ for sorting the ranges, followed by $O(N)$ to merge them. |
Draw a timeline. Draw the sorted intervals. Draw a single arrow merging them left-to-right. Finally, draw a power function box (2^G). |
N/A. |
$O(1)$ extra space (excluding sorting storage). |
| 2581 |
Count Number of Possible Roots |
For every node in the tree, perform a full DFS/BFS rooted at that node. Count how many guesses (u, v) match the parent-child relationship in that specific tree. $O(N^2)$. |
A forest of N trees, where each tree is traversed completely to validate a set of guesses. |
Pick Node 0 as root. Do DFS. Count correct guesses. Pick Node 1 as root. Do DFS again. Repeat for all N nodes. |
Tree DP with Rerooting (Change of Root). |
A "Dynamic Parent-Child Flip" visual where we move the root to an adjacent neighbor and only update the count for that specific edge. |
1. Root the tree at 0 and count correct guesses (K). 2. Perform a second DFS. When moving from parent u to child v: if (u, v) was a guess, K decreases by 1 (it's no longer a parent-child relationship). If (v, u) was a guess, K increases by 1. Check if K >= k at each node. |
Draw a small tree. Root it at 0. Write down the score. Move the root to an adjacent node. Only look at the edge connecting the old root and new root. Flip its direction and update the score. |
$O(N + G)$ where N is nodes and G is number of guesses. Two DFS passes are linear. |
Draw a tree. Draw a downward arrow for the first DFS. Draw "outward" arrows from the root for the rerooting pass, showing only local edge updates. |
Massive $O(N^2)$ traversal memory. |
$O(N + G)$ to store the adjacency list and the set of guesses. |
| 2582 |
Pass the Pillow |
Simulate the pillow passing second-by-second for `time` seconds. Keep track of the current person and the direction of movement. $O(T)$. |
A linear timeline of pillow hand-offs moving back and forth across a line of people. |
Time 1: Person 1 -> 2. Time 2: 2 -> 3. At the end (Person N), flip direction. Repeat for `time` steps. |
Modular Arithmetic (Cycles). |
A "Zig-Zag" mathematical visual where the pillow moves in cycles of 2(N-1) steps. |
One full round trip (1 to N and back to 1) takes (N-1) x 2 steps. Calculate `full_cycles = time / (N-1)` and `extra_steps = time % (N-1)`. If `full_cycles` is even, you are moving forward: result is `1 + extra_steps`. If odd, you are moving backward: result is `N - extra_steps`. |
Write down N and `time`. Subtract (N-1) repeatedly until you can't. If you subtracted an even number of times, start at 1 and add the remainder. If odd, start at N and subtract the remainder. |
$O(1)$ - A few arithmetic operations regardless of time or number of people. |
Draw a single box representing the CPU. Write the "Even/Odd" logic inside. No loops or arrows needed. |
N/A. |
$O(1)$ - Constant memory. |
| 2583 |
Kth Largest Sum in a Binary Tree |
Traverse the tree and find every possible subset of nodes that could form a "level." Sum them and sort. $O(N \log N)$. |
A chaotic collection of node sums before they are organized by level. |
List every node. Manually figure out which nodes are on level 1, 2, 3... Sum them up. Sort the sums. |
Level Order Traversal (BFS) + Sorting/Min-Heap. |
A "Horizontal Slice" visual where the tree is cut into layers, each layer's sum is calculated, and then ranked. |
Use a queue for BFS. For each level, process all current nodes in the queue, add their values to a `levelSum`, and push their children. Store all `levelSums` in a list. Sort the list descending and return the k-th element. |
Draw a tree. Draw horizontal lines through each level. Add the numbers on each line. Write the sums in a list. Sort the list and pick the k-th largest. |
$O(N + L \log L)$ where N is nodes and L is number of levels. BFS is $O(N)$. |
Draw the tree. Draw a vertical arrow pointing to each level. Next to the tree, draw a small sorted list of the level sums. |
Recursive stack memory for all paths. |
$O(W + L)$ where W is the max width of the tree (queue size) and L is number of levels. |
| 2584 |
Split the Array to Make Coprime Products |
For every possible split point i, calculate the product of the left and right parts. Calculate their GCD. $O(N^2 \log(\text{Product})$). (Product will overflow 64-bit). |
A massive multiplication operation that crashes due to number size, followed by a GCD check. |
Split after index 0. Multiply left, multiply right. Find GCD. If 1, success. Else, move to index 1. |
Prime Factorization + Range Merging / Interval Coverage. |
A "Prime Span" visual: for every prime factor, we find its first and last occurrence in the array. A split is only valid if it doesn't "cut" through any prime's span. |
1. For each number, find its prime factors. 2. For each prime, record its first index (`left[p]`) and last index (`right[p]`). 3. This creates a set of intervals `[left, right]`. We need to find the first index i that is not inside any interval that started before i and ends after i. This is a "Gap" in the overlapping intervals. |
Write the array. Below each number, list its primes. For each prime (like 2), draw a line from the first time it appears to the last. Look for a vertical gap where no lines are crossing. |
$O(N √\text{max}(\text{nums})$) to factorize and $O(N)$ to find the gap. |
Draw a horizontal line for the array. Above it, draw "arches" for each prime factor. Find the first point where no arches are "flying" over. |
Number overflow issues and $O(N^2)$ GCD checks. |
$O(N + \text{Unique Primes})$ to store the first/last occurrences and factor counts. |
| 2585 |
Number of Ways to Earn Points |
Recursively try taking 0, 1, 2... up to count[i] items of the current type to reach the target. $O(\text{count}^\text{types})$. |
An enormous multi-way decision tree where each node branches out many times based on the item count. |
Target 6. Item 1 (val 2, count 2). Try taking zero 2s, one 2, or two 2s. From each, repeat for the next item type. |
Bounded Knapsack Dynamic Programming. |
A "Grid-Filling" visual where we build up the number of ways to reach every score from 0 to target using one item type at a time. |
Let `dp[i]` be the ways to get `i` points. For each item type `(count, val)`: update the `dp` table backwards (from `target` down to 0). For a score `s`, `new_dp[s] = dp[s] + dp[s - 1*val] + dp[s - 2*val] ...` up to `count`. |
Draw a row of boxes 0 to `target`. Start with box 0 = 1. For each item type, update the boxes by adding values from "backwards" boxes that are a multiple of `val` away. |
$O(\text{Types} x \text{Target} x \text{AvgCount})$. Triple nested loop (Items, Score, Count). |
Draw a 1D array. Draw multiple "jump" arrows from previous cells into the current cell, representing the different counts of the same item type. |
Exponential recursion stack. |
$O(\text{Target})$ - We only need a 1D array to store the current ways to reach each score. |
| 2586 |
Count the Number of Vowel Strings in Range |
Iterate through every string in the array. For each string, check if its first and last characters are vowels. $O(N x L)$. |
A linear scan with a magnifying glass over the start and end of every word. |
Draw words in a list. Put a circle around the first and last letters. If both are in {a, e, i, o, u}, tally it. |
Direct Linear Scan with Set Lookup. |
A "Vowel Filter" visual where each string passes through a gate that only checks two specific points (index 0 and length-1). |
Iterate from index left to right. Extract s[0] and s[-1]. Check if both exist in the constant set {'a', 'e', 'i', 'o', 'u'}. Increment counter if true. |
Write down the indices from left to right. Under each, write the string. Mark the first and last character. Tick the ones that match. |
$O(N)$ where N is the length of the range. Constant time $O(1)$ per string check. |
Draw a horizontal array. Draw a single arrow spanning only the segment from left to right. |
N/A. |
$O(1)$ - No extra data structures besides a small constant set. |
| 2587 |
Rearrange Array to Maximize Prefix Score |
Try all N! permutations of the array. For each, calculate the prefix sums and count how many are positive. $O(N! x N)$. |
A massive factorial explosion of possible array orderings. |
Write [2, -1, 1]. Try [2, -1, 1], [2, 1, -1], [-1, 2, 1]... Calculate prefixes for all. |
Greedy Sorting (Descending Order). |
A "Descending Staircase" visual where the prefix sum is kept as high as possible for as long as possible by adding the largest numbers first. |
Sort the array in descending order. Maintain a runningSum. For each number, add it to runningSum. If runningSum > 0, increment the score. Once the sum becomes non-positive, all subsequent prefix sums in a descending sorted array will likely decrease further. |
Write the numbers from largest to smallest. Below them, write the cumulative sum. Count how many numbers stay above zero. |
$O(N \log N)$ for sorting the array. |
Draw a descending bar chart. Draw a line graph above it representing the running total, showing it peaking early and then descending. |
Exponential space for permutations. |
$O(1)$ extra space beyond sorting. |
| 2588 |
Count the Number of Beautiful Subarrays |
Check every possible subarray (i, j). For each, calculate the XOR sum. If the XOR sum is 0, it means all bits can be paired and removed (beautiful). $O(N^3)$. |
A dense nested-loop grid where every subarray is re-calculated from scratch. |
Draw the array. Pick a start and end. XOR all numbers in between. If 0, it's "beautiful." Repeat for all start/end pairs. |
Prefix XOR + Hash Map (Frequency Counting). |
A "Mirror Matching" visual: if the prefix XOR at index i is the same as prefix XOR at index j, the subarray between them must have an XOR of 0. |
A subarray is "beautiful" if its XOR sum is 0. This is true if prefixXOR[i] == prefixXOR[j]. Maintain a runningXOR and a Hash Map to store the frequency of each XOR value encountered. For every new runningXOR, add its current frequency in the map to the total count, then increment the frequency. |
Write the array. Calculate a running XOR (e.g., 0, 3, 1, 3...). Use a tally sheet (Map) to count how many times you've seen each result. If you see '3' for the second time, it means one beautiful subarray was just completed. |
$O(N)$ - One pass through the array with $O(1)$ map lookups. |
Draw the array. Draw one arrow moving forward. Next to it, draw a "Frequency Table" that grows as the arrow moves. |
$O(N^2)$ for subarray storage. |
$O(N)$ for the Hash Map to store prefix XOR frequencies. |
| 2589 |
Minimum Time to Complete All Tasks |
Try every possible combination of 1s and 0s for every second in the timeline [1, 2000] to satisfy task durations. $O(2^2000)$. |
A binary choice tree of "turn on computer" or "turn off computer" for every second. |
Timeline 1...2000. Try turning it on at sec 1, off at sec 2. Check if all tasks finish. Repeat for all combos. |
Greedy Interval Scheduling (End-Point Prioritization). |
A "Greedy Backfilling" visual: tasks are sorted by their end times, and their required duration is filled from the end of the interval backwards to maximize overlap with future tasks. |
1. Sort tasks by their end time. 2. For each task, check how many seconds are already "on" in its range [start, end]. 3. If more time is needed, turn on the computer starting from the end of the interval moving backwards, but only for seconds that are currently "off". |
Draw a timeline. Sort tasks by end-point. For the first task, mark the last few available seconds. For the second task, count how many marks are already in its range, then add more marks starting from its end-point. |
$O(N \log N + N x \text{Timeline})$. Sorting plus a nested loop over the timeline. |
Draw task bars on a timeline. Show a "filling" animation that starts at the right edge of each bar and moves left. |
N/A. |
$O(\text{Timeline})$ - specifically a boolean array of size 2001 to track the computer's state. |
| 2590 |
Design a Todo List (Premium) |
Store all tasks in a single list. For every query (getTasks, completeTask), iterate through the entire list and filter/modify. $O(N x Q)$. |
A messy, unorganized pile of notes that you have to read from top to bottom every time someone asks for a specific task. |
Write every task on a piece of paper. To find "Work" tasks, read every paper. To complete Task 5, find it in the pile and cross it out. |
Hash Map (User to Task-List) + Sorting/Filtering. |
A "Filing Cabinet" visual where each user has their own folder, and tasks are sorted by due date within that folder. |
Use a Hash Map where keys are userId and values are a list of Task objects. Each Task contains an ID, description, due date, tags, and a completion status. To getTasksForUser, filter the user's list for incomplete tasks (and tags if specified), then sort by dueDate. |
Draw a Map. Key 1 points to a list of tasks. Sort that list by the "Date" field. When a task is completed, change its status but keep it in the list (or remove it). |
$O(1)$ for adding tasks. $O(N \log N)$ for getting tasks (due to sorting). $O(N)$ for completing/deleting. |
Draw the Hash Map structure. Show an arrow pointing from a UserID to a sorted list, then show a "Filter" box that removes completed tasks. |
N/A. |
$O(T)$ where T is the total number of tasks created across all users. |
| 2591 |
Distribute Money to Maximum Children |
Try every possible combination of distributing money to children such that each gets at least 1 and no one gets 4, then count the 8s. $O(\text{Money}^\text{Children})$. |
A massive recursion tree exploring all possible partitions of an integer. |
Write 20 money, 3 children. Try (8, 8, 4) - invalid. Try (8, 9, 3). Count the 8s. Repeat for all combinations. |
Greedy Case-Based Logic. |
A "Bucket Filling" visual where we give everyone 1 first, then fill as many buckets with 7 more as possible, handling leftovers at the end. |
1. Give each child 1. If money < children, return -1. 2. Remaining money = money - children. 3. Count how many 7 chunks fit in remaining money (max children). 4. Adjust for edge cases: If 1 child left with 3 (total 4), decrement count. If 0 children left and money > 0, decrement count. |
Draw 5 circles. Put 1 in each. You have X left. Put 7 in the first circle, then the second... Stop if you have 3 left for the last person or if you run out of money. |
$O(1)$ - Constant time logic based on a few conditional checks. |
Draw a single decision tree with 3-4 branches representing the edge cases (Money=4, All-8s-with-leftover, etc.). |
Exponential recursion stack. |
$O(1)$ - Constant space. |
| 2592 |
Maximize Greatness of an Array |
Generate all N! permutations of the array. For each, compare it to the original and count how many elements are strictly greater. $O(N! \cdot N)$. |
A combinatorial explosion of array re-orderings. |
Write [1, 3, 5]. Try [3, 5, 1], [5, 1, 3]... Count matches where perm[i] > original[i]. |
Sorting + Greedy Two-Pointer. |
A "Race Track" visual where two copies of the sorted array compete; the faster pointer only advances to "beat" the slower pointer. |
Sort the array. Use two pointers, i and j, both starting at 0. Pointer i represents the original elements, and j represents the permuted candidates. If nums[j] > nums[i], we found a "great" match: increment i (and the total count). Always increment j. |
Draw two identical sorted rows of numbers. Put left finger on Row 1, right finger on Row 2. If right is bigger than left, move both fingers and tally. If not, only move the right finger. |
$O(N \log N)$ for sorting. The two-pointer scan is linear $O(N)$. |
Draw two horizontal lines. Draw a single arrow for i and a faster-moving arrow for j, showing j leads the way. |
N/A. |
$O(1)$ extra space (excluding sorting overhead). |
| 2593 |
Find Score of an Array After Marking All Elements |
In each step, scan the whole array to find the minimum unmarked value. Mark it and its neighbors. Repeat until all are marked. $O(N^2)$. |
A series of full-array sweeps, with elements "disappearing" one by one. |
Draw [2, 1, 3, 4]. Smallest is 1. Mark 1, 2, 3. Remaining is 4. Add 1 and 4. Total 5. |
Sorting with Index Tracking + Boolean Marking. |
A "Sorted Worklist" visual where we process elements from smallest to largest, skipping those already "shadowed" by a neighbor. |
Create a list of pairs (value, index) and sort it by value (then index). Maintain a boolean array marked. Iterate through the sorted list: if marked[index] is false, add value to score and set marked[index-1], marked[index], marked[index+1] to true. |
Write the array. List all numbers on the side from smallest to largest. Cross out the smallest number on your list AND its neighbors in the array. Move to the next smallest *not* crossed out. |
$O(N \log N)$ for sorting the pairs. |
Draw a "Processing Queue" sorted by value. Draw the original array below it. Show arrows from the Queue marking cells in the Array. |
N/A. |
$O(N)$ for the sorted list of pairs and the boolean marked array. |
| 2594 |
Minimum Time to Repair Cars |
Try every possible distribution of cars to mechanics. For each distribution, calculate the max time taken by any mechanic and find the minimum. $O(\text{Exponential})$. |
A partition problem of distributing N identical items into M distinct bins. |
10 cars, 2 mechanics (ranks 4, 2). Try (5, 5) cars. Time = max(4*5^2, 2*5^2). Try (4, 6) cars. Find the best split. |
Binary Search on Answer Space (Time). |
A "Capacity Check" visual: given a fixed amount of time, we calculate the maximum cars each mechanic can handle and see if the sum meets the goal. |
The answer range is [1, min(ranks) * cars^2]. For a mid-point T, a mechanic with rank r can repair sqrt(T/r) cars. If sum(sqrt(T/r)) >= total_cars, then T is possible; try smaller time. Else, try larger. |
Pick a time (e.g., 100 minutes). If rank is 4, 4*n^2 <= 100 rightarrow n^2 <= 25 rightarrow n=5 cars. Calculate for all mechanics. If they can do >= target cars, 100 is "Safe." Try 50. |
$O(N \log(\text{MaxTime})$). Linear check inside a logarithmic search. |
Draw a timeline of possible times. Draw brackets halving the range. For each "Guess," draw a list of mechanics and their car capacities. |
N/A. |
$O(1)$ - Constant space besides the input storage. |
| 2595 |
Number of Even and Odd Bits |
Convert the number to a binary string. Loop through the string, check the index parity, and count 1s. |
A string-based transformation (Int -> Binary String -> Array). |
17 rightarrow "10001". Index 0: '1' (even). Index 4: '1' (even). Result: [2, 0]. |
Bitwise Shift and Masking. |
A "Bit Peeler" visual where we examine the last bit, record its parity, and shift the number right until it's zero. |
Initialize even = 0, odd = 0, index = 0. While n > 0: if (n & 1) == 1, increment even if index % 2 == 0, else increment odd. Right-shift n by 1 and increment index. |
Write the number. Look at the last digit. Is it 1? If yes, tally it (count if you've moved an even or odd number of times). Cross out the last digit. Repeat. |
$O(\log N)$ - Proportional to the number of bits in the integer. |
Draw a binary number. Draw a single arrow moving from right to left, with two "Scoreboard" boxes (Even/Odd) updating as it moves. |
$O(\log N)$ for string storage. |
$O(1)$ - Constant memory. |
| 2596 |
Check Knight Tour Configuration |
For every number k from 0 to n^2-2, search the entire grid to find where k and k+1 are located, then check if the distance between them is a valid knight move. $O(N^4)$. |
A "Where's Waldo" search for every sequential number in a grid, repeated N^2 times. |
Draw the grid. Find '0'. Then scan the whole grid for '1'. Check the L-shape. Then scan the whole grid for '2'. Repeat until N^2-1. |
Coordinate Mapping (Direct Indexing). |
A "Jump Tracker" visual where we store the coordinates of each number in an array first, then simply verify the jumps between adjacent array indices. |
Create an array pos of size N^2. Iterate through the grid and set pos[grid[r][c]] = (r, c). Then, iterate from i=0 to N^2-2: calculate the row difference dr = |pos[i].r - pos[i+1].r| and column difference dc = |pos[i].c - pos[i+1].c|. Valid if (dr*dc == 2). Also, ensure grid[0][0] == 0. |
Write a list of numbers 0, 1, 2... Next to each, write its (row, col). Check the "L-step" (2 squares one way, 1 square the other) between each pair in the list. |
$O(N^2)$ - One pass to map the coordinates and one pass to check the moves. |
Draw a list of coordinates. Draw a single arrow jumping from one coordinate to the next, with a small "L-shape" icon above each jump. |
N/A. |
$O(N^2)$ to store the coordinate map. |
| 2597 |
The Number of Beautiful Subsets |
Generate every possible subset (2^N). For each subset, check every pair of elements to see if their absolute difference is k. $O(2^N x N^2)$. |
A massive power-set tree where most branches are pruned by a "difference" constraint. |
List the array. Try picking subsets. If you pick '5' and k=2, you can't pick '3' or '7'. Count all valid combinations. |
Recursive Backtracking with Frequency Map (or House Robber DP). |
A "Conditional Selection" tree where the path to include an element is blocked if its "forbidden partner" (val - k) was already chosen. |
Sort the array (optional but helps). Use recursion: dfs(index). At each step, you can either skip the element or include it. You can only include it if count[nums[index] - k] == 0 and count[nums[index] + k] == 0. Return the total count minus 1 (for the empty subset). |
Draw a decision tree. At each number, draw two branches: "Pick" and "Don't Pick." If you "Pick," check your "Already Picked" list to see if the forbidden partner is there. If yes, that branch dies. |
$O(2^N)$ in worst case, but significantly faster with pruning. Can be $O(N \log N)$ if modeled as a DP problem grouped by remainders of k. |
Draw a recursion tree with limited depth. Highlight the "invalid" branches with an 'X' to show pruning. |
$O(2^N)$ to store all subsets. |
$O(N)$ for the recursion stack and the frequency map. |
| 2598 |
Smallest Missing Non-negative Integer After Operations |
Try every possible addition/subtraction of value for every element to see if you can form 0, then 1, then 2... $O(\text{Exponential})$. |
A chaotic search trying to fit numbers into specific "slots" using infinite shifts. |
Array: [1, 2], value: 3. Can I make 0? No. Smallest missing is 0. |
Modulo Frequency Mapping (Remainders). |
A "Remainder Bucket" visual: any number x can represent any value y as long as x mod v == y mod v. We just need to fill the smallest values first. |
Count the frequency of each remainder nums[i] % value. The smallest missing integer MEX can be formed if we have a remainder MEX % value available. We can use each instance of a remainder only once to "cover" a number in the sequence 0, 1, 2... |
Draw "buckets" labeled 0 to value-1. Put each array number into a bucket based on its remainder. Start at 0. Is there a number in Bucket 0? Yes, take it and move to 1. Is there one in Bucket 1? Yes, take it. Repeat until a bucket is empty. |
$O(N + \text{value})$ - One pass to count remainders and one pass to find the MEX. |
Draw a row of buckets. Draw an arrow moving through the sequence 0, 1, 2... and "pulling" an item from the corresponding bucket at each step. |
N/A. |
$O(\text{value})$ to store the frequency of each remainder. |
| 2599 |
Make the Prefix Sum Non-negative (Premium) |
Try moving every possible combination of negative numbers to the end of the array and check prefix sums. $O(2^\text{negatives})$. |
A combinatorial search of "Which negative should I move?" to keep the running total above zero. |
Array: [2, -3, 1]. Prefix: 2, -1 (Fail!). Move -3 to end: [2, 1, -3]. Prefixes: 2, 3, 0 (Pass!). |
Greedy with Min-Heap (Priority Queue). |
A "Safety Reserve" visual: we move forward normally, but if our "bank balance" (prefix sum) drops below zero, we retroactively "undo" the worst transaction (most negative number) we've made so far. |
Maintain a runningSum and a Min-Heap of all negative numbers encountered so far. Iterate through the array. Add the current number to runningSum. If it's negative, push it to the heap. If runningSum < 0, pop the smallest (most negative) number from the heap, subtract it from runningSum, and increment the "moved" counter. |
Write the numbers and a "Running Total." When the total goes negative, look back at the negative numbers you've passed. Pick the biggest "debt" (like -10), cross it out, and add that 10 back to your total. |
$O(N \log N)$ because each negative number is pushed and potentially popped from the heap once. |
Draw a timeline. Below it, draw a "Trash Can" (the Heap). Show an arrow moving right; when the sum drops, a number from the timeline flies into the trash can. |
$O(2^N)$ for combination states. |
$O(N)$ for the priority queue. |
| 2600 |
K Items With the Maximum Sum |
Generate an array containing all 1s, 0s, and -1s, then pick the first k elements. $O(\text{numOnes} + \text{numZeros} + \text{numNegOnes})$. |
Physically laying out all items in a line before picking the top k. |
Ones: 2, Zeros: 1, Negs: 2, k: 4. Array: [1, 1, 0, -1, -1]. Sum of first 4: 1+1+0-1 = 1. |
Greedy Case-Based Logic. |
A "Prioritized Selection" visual: take all available 1s first, then 0s, and only take -1s if absolutely necessary. |
1. If k <= numOnes, return k. 2. If k <= numOnes + numZeros, return numOnes. 3. Otherwise, you must take some -1s. Return numOnes - (k - numOnes - numZeros). |
You want the biggest sum. You have a pile of 1 bills, a pile of 0 bills, and a pile of -1 bills. Take k bills. Take all the 1s you can first. If you still need more, take the 0s. If you still need more, you're forced to take the -1s. |
$O(1)$ - Constant time math checks. |
Draw three buckets (1, 0, -1). Draw an arrow taking from the '1' bucket first, then '0', then '-1'. |
$O(N)$ to store the explicit array of items. |
$O(1)$ - Constant space. |
| 2601 |
Prime Subtraction Operation |
Nested loops calculating primes via trial division for every element. |
Branching execution tree |
Draw nested loops as repeating blocks; write $O(N \cdot M)$ beside each step. |
Sieve of Eratosthenes + Binary Search (Greedy) |
Number Line & Precomputed Lookup |
Use two fingers: one on the array, one binary-searching the Sieve array to find the largest valid prime. |
Draw `nums` array and `primes` array. Draw arrows from `nums[i]` to valid prime strictly less than `nums[i] - nums[i-1]`. |
Time Distribution Timeline |
Write Sieve setup (N log log N) + Array traversal with binary search (N log P) as sequential timeline blocks. |
Isolated variables memory trace |
Contiguous memory block diagrams for Sieve boolean[] array. |
| 2602 |
Minimum Operations to Make All Array Elements Equal |
Iterate array for each query and sum absolute differences. |
Bipartite mapping (Queries to Array) |
Draw lines from one query to every single array element, label $O(N\cdot Q)$ total lines. |
Sorting + Prefix Sums + Binary Search |
Area Under Curve / Prefix Sum Blocks |
Slide a divider (binary search point) in a sorted array; calculate left side cost and right side cost using prefix blocks. |
Draw sorted array and prefix sum array. Draw a vertical line for the query value; compute differences using block sums. |
Logarithmic scale tree |
Draw sort cost $O(N \log N)$ + Q queries tracing down a binary tree $O(Q \log N)$. |
Call stack layout |
Two parallel contiguous block arrays (Sorted Nums, Prefix Sums). |
| 2603 |
Collect Coins in a Tree |
DFS/BFS from every single node to calculate exact distances and paths. |
Multi-root Tree Expansion |
Draw N trees, each highlighting traversal paths; write $O(N^2)$ total nodes visited. |
Topological Sorting (Peeling leaves like an onion) |
Concentric Graph Layers |
Erase leaf nodes with no coins step-by-step, then erase remaining leaves twice to simulate the 2-jump distance. |
Draw the graph. Cross out 0-coin leaves. Then draw circle around remaining leaves, cross them out. Repeat once more. |
Linear Graph Reduction |
Draw $O(N)$ linear timeline showing degree arrays dropping to zero sequentially. |
Recursive call stack depth visualization |
Graph adjacency list (Array of lists) and a flat Degree array. |
| 2604 |
Minimum Time to Eat All Grains |
Simulate all permutations of hen-to-grain assignments. |
Combinatorial Explosion Tree |
Draw a massive branching tree of choices (O(N!)) fading into ellipses. |
Binary Search on Answer + Greedy |
Sliding Window / Interval Checking |
Assume a max time T. See how far the first hen can sweep left/right. If grains remain, pass to next hen. |
Draw a 1D number line. Plot hens (H) and grains (G). Draw brackets [ ] around the range each hen covers in time T. |
Red/Blue Binary Search Domain |
Draw a timeline of Time limits; color left half red (fail), right half blue (pass). Cost per check is $O(N+M)$. |
Heap memory allocation diagram |
Two pointers on sorted arrays visualization blocks. |
| 2605 |
Form Smallest Number From Two Digit Arrays |
Nested loops comparing all pairs to find minimum common or minimum combination. |
Cartesian Product Grid |
Draw an N x M grid checking every cell for minimum formed number. |
Hash Set / Bitmask + Math.min |
Set Intersection Venn Diagram |
Check for intersection. If none, take minimum from Array 1 and Array 2, sort them, combine them. |
Draw two circles (Sets). Find min in overlap. If empty, pick smallest from circle A and circle B and concatenate. |
Constant Time Block Diagram |
Write $O(N)$ for Set creation, $O(1)$ for lookups. Draw linear $O(N+M)$ bar. |
2D array matrix representation |
Hash map / Bit-array memory footprint. |
| 2606 |
Find the Substring With Maximum Cost |
Generate all possible substrings and sum their costs. |
Triangle Substring Grid |
Draw an N x N grid matrix where cells below the diagonal are crossed out, showing $O(N^2)$ pairings. |
Kadane's Algorithm |
1D Array with Running Sum Tracker |
Move a pointer right. Add to running sum. If the sum drops below zero, reset it to zero immediately. Keep track of the max seen. |
Write the array of values. Below it, write a running total. Circle the total whenever you write a new maximum. Strike out negatives when you reset. |
Linear Timeline Strip |
Draw a single straight line spanning N elements, representing a single $O(N)$ pass. |
Nested looping pointer diagrams |
Constant space variable boxes (MaxSum, CurrentSum) and a Hash Map for char values. |
| 2607 |
Make K-Subarray Sums Equal |
Brute force trial and error of values to satisfy sliding window sums. |
System of Linear Equations |
Write out the mathematical equations for every window sum, showing overlapping and exploding complexity. |
Graph Cycles + Median Math |
Cyclic Permutation Rings |
Group indices that jump by K (modulo N). For each isolated group, find the median value, and make all items in that ring equal to the median. |
Draw the array indices in a circle. Draw lines jumping by K. Pull out connected components into separate lists, find median of each. |
Logarithmic sorting bars |
Draw N bars being grouped into smaller arrays, then sorted. Label $O(N \log N)$ for the sorting steps of components. |
Heavy recursive tree stack |
Disjoint set / separate temporary arrays for each cycle. |
| 2608 |
Shortest Cycle in a Graph |
DFS starting from every node, exploring all paths to find loops. |
Massive Backtracking Tree |
Draw a deeply nested, sprawling tree showing paths revisiting nodes, labeling $O(2^V)$. |
BFS from every node (or Edge Removal) |
Radial Expansion Layers |
Start BFS from a node. Treat it as dropping a stone in a pond. When two "ripples" (paths) hit the same unvisited node, a cycle is found. |
Draw the start node at the center. Draw concentric circles for distances 1, 2, 3. Stop and sum distances when two nodes on the active edge connect. |
V * BFS Iterations Box |
Draw V boxes representing iterations. Inside each, write $O(V+E)$, concluding with $O(V \cdot (V+E)$). |
Deep Call Stack |
Queue representation (horizontal tube) and a Distance Array tracking shortest path lengths. |
| 2609 |
Find the Longest Balanced Substring of a Binary String |
Extract every substring, count 0s and 1s, verify format. |
Nested String Slices |
Draw brackets under the string extracting increasingly smaller chunks, label $O(N^3)$ or $O(N^2)$. |
Two Variables / Counting Consecutive Blocks |
Step Function / Bar Chart |
Scan left to right. Count consecutive 0s. When 1s start, count them. The valid length is 2 * min(zeros, ones). Reset on a new 0. |
Draw the string. Below the 0s, draw ascending steps (1, 2, 3). Below the 1s, draw ascending steps (1, 2). Box the matching pair and compute length. |
Single Scan Arrow |
Draw a one-directional arrow across the array length N, labeling $O(N)$. |
Sub-array memory allocations |
Two integer variable boxes (zerosCount, onesCount). Space is $O(1)$. |
| 2610 |
Convert an Array Into a 2D Array With Conditions |
Iterate array, for each element search existing 2D rows iteratively to find a spot without duplicates. |
Row-by-Row Linear Scanning |
Draw an element trying to slot into row 1, getting blocked, then checking row 2. Write $O(N^2)$ for worst-case scanning. |
Frequency Map / Hash Table |
Frequency Histogram / Stacking Blocks |
Tally the frequency of each number. The number of rows equals the highest frequency. Place element `x` into row index equal to its current running count. |
Draw a tally chart for numbers. Draw empty arrays (rows). Deal out numbers like cards: 1st '3' goes to row 0, 2nd '3' goes to row 1, etc. |
Flat Array to Hash Map Map |
Draw input array N pointing to a Hash Map setup $O(N)$, pointing to result building $O(N)$. |
Growing 2D jagged array lists |
1D Array acting as a Frequency Map. |
| 2611 |
Mice and Cheese |
Combinatorial backtracking to test all possible choices of picking K cheeses. |
Combinatorial Decision Tree |
Draw a branching tree where each node splits into "Mouse 1 eats" or "Mouse 2 eats". Write $O(N \text{choose} K)$. |
Greedy Algorithm + Sorting |
Sorted Differential Bar Chart |
Compute `reward1[i] - reward2[i]`. Sort these differences descending. Give the top K to Mouse 1, and the rest to Mouse 2. |
Write Row 1, Row 2, and Row 3 (Diff). Sort columns by the Diff row. Draw a box around the first K items for Mouse 1. |
Sorting Timeline Block |
Draw a large $O(N \log N)$ sorting block, followed by a smaller $O(N)$ array summation block. |
Deep recursive call stack |
1D Difference Array and Sorted Indices Array. |
| 2612 |
Minimum Reverse Operations |
Standard BFS exploring every possible valid reverse window of size K. |
Exploding Graph BFS |
Draw a node branching out to $O(K)$ possible reverse states, resulting in a massive $O(N\cdot K)$ unpruned web. |
BFS + Ordered Sets (Parity sets) |
Bipartite Parity Number Line |
Maintain two sets of unvisited indices (Evens and Odds). From current index, calculate reachable min/max window. Search the set within that window, remove them, add to Queue. |
Draw a number line. Color evens blue, odds red. Draw a bracket [L, R] for the reachable range. Erase numbers in that range from the sets as they are visited. |
Set Deletion Amortized Timeline |
Draw N elements. Draw arrows crossing them out exactly once. Label $O(N \log N)$ for tree-set lookups. |
Massive overlapping Queue space |
Two Balanced Binary Search Trees / Sets (Even Set, Odd Set). |
| 2613 |
Beautiful Pairs |
Nested loops comparing the Manhattan distance of every single pair. |
Complete Graph Network |
Draw N dots. Draw lines connecting every single dot to every other dot, labeling $O(N^2)$. |
Divide and Conquer / Sweep Line |
2D Plane Partitioning Strip |
Sort by X. Divide in half. Find min distance `d` on left and right. Check the middle "strip" of width `2d` for closer points across the boundary. |
Plot points on an X/Y axis. Draw a solid vertical line down the middle. Draw dashed lines at `mid - d` and `mid + d`. Only compare points inside the dashed strip. |
Master Theorem Recursion Tree |
Draw a binary tree. At each level, write $O(N)$ for merge work. Total height log N, overall $O(N \log N)$. |
Two looping variables (i, j) |
Point objects sorted in separate Left and Right contiguous arrays. |
| 2614 |
Prime In Diagonal |
Iterate all elements, check primality in $O(X)$ time. |
Iterative Division Array |
Draw the matrix. Next to each diagonal element, draw a long list of divisions up to X. $O(N \\text{cdot Max}_\text{Val})$. |
Matrix Traversal + $O(√N)$ Prime Check |
Matrix Cross (X) Pattern |
Traverse `i` from 0 to N-1. Check `nums[i][i]` and `nums[i][n-1-i]`. Run a square-root prime check loop. Keep the max prime. |
Draw a square grid. Draw a big 'X' through it highlighting the diagonals. Next to each highlighted cell, write checks up to √Val. |
Linear * Sqrt Block |
Draw an $O(N)$ loop box. Inside it, draw two smaller $O(√\text{Max}_\text{Val})$ calculation boxes. |
Matrix copy in memory |
$O(1)$ Constant Space variables (maxPrime tracker). |
| 2615 |
Sum of Distances |
Nested loops. For each `nums[i]`, scan the array for matching values and sum distances. |
N x N Scanning Grid |
Draw the array. Draw arrows from index `i` looping all the way through the array to find matches. $O(N^2)$. |
Hash Map + Prefix Sum |
Running Prefix / Suffix Balance |
Group indices by value. Calculate total distance for the 1st index. As you slide to the next index, the left side distances grow longer, right side distances grow shorter by the exact gap size. |
Draw grouped indices on a line (e.g., [0, 2, 5]). Draw a fulcrum moving left to right. Write equations showing Left side += (gap * count), Right side -= (gap * count). |
Parallel $O(N)$ Timelines |
Draw an $O(N)$ grouping operation block, followed directly by an $O(N)$ prefix sliding window block. |
Isolated variables tracking sums |
Hash Map pointing to dynamically sized lists of Indices. |
| 2616 |
Minimize the Maximum Difference of Pairs |
Generate all possible subsets of pairs of size P and find the minimum of their maximum differences. |
Combinatorial Explosion Branching |
Draw a massive tree picking pairs, calculating $O(N \text{choose} 2P)$. |
Sort + Binary Search on Answer + Greedy |
Red/Blue Domain Number Line |
Assume a max difference 'mid'. Scan sorted array: if nums[i+1] - nums[i] <= mid, count the pair and jump 2 spots. If we hit P pairs, 'mid' is valid (blue), try smaller. |
Draw the sorted array. Write a "mid" value. Loop through array drawing brackets [ ] around adjacent elements that fit the difference limit. Count brackets. |
Logarithmic Search over Range |
Draw sorting block $O(N \log N)$ + Binary search block $O(N \log M)$ where M is the max possible difference. |
Deep recursive stack |
Constant space variables (left, right, mid) with sorted input array in place. |
| 2617 |
Minimum Number of Visited Cells in a Grid |
Standard DFS exploring every single reachable cell from every current cell. |
Exploding DFS Tree |
Draw a grid, and from one cell, draw arrows to all reachable cells in its row/col, leading to $O(M^2 \cdot N^2)$ overlapping paths. |
BFS + Priority Queue / Monotonic Stack |
Graph Level-Order Traversal |
Jump along the grid keeping track of the minimum jumps to reach a row/col. Use a priority queue to skip cells we already found faster paths to. |
Draw a grid. Label starting cell as '1'. Draw arrows to furthest jumps. Only update a cell's number if the incoming jump count is strictly smaller. |
PQ Operations Timeline |
Draw an $O(M\cdot N)$ grid traversal loop enclosing $O(\log(M+N)$) heap operations. |
Deep recursive stack array |
Min-Heaps (Priority Queues) maintaining active reachability per row and column. |
| 2618 |
Check if Object Instance of Class (JS) |
Manually checking properties or constructor names (flawed). |
Literal Property Search |
Draw a box representing an object and try to find a hardcoded "class" string inside it. |
JavaScript Prototype Chain Traversal |
Linked List Traversal (Prototypes) |
Take the object. Look at its `__proto__`. Does it match the Class's `prototype`? If not, move up to `__proto__.__proto__`. Stop at null. |
Draw an Object box. Draw an arrow pointing up to its Prototype object. Draw an arrow from the Class to its `.prototype`. Check if the arrows ever land on the same box. |
Depth Traversal Arrow |
Draw an $O(D)$ arrow where D is the depth of the prototype chain. |
N/A |
Object reference pointers in Heap memory. |
| 2619 |
Array Prototype Last (JS) |
Iterate through the array with a loop until the end is reached. |
Linear Scan Array |
Draw an array and point a finger at index 0, moving it right one-by-one until you hit an empty spot. |
Array Length Property (`this.length`) |
Direct Index Mapping |
Look at the internal `length` property of the array context (`this`). Subtract 1. Access that index directly in memory. Return -1 if length is 0. |
Draw an array block. Read length variable (e.g., L=5). Point arrow directly to index 4. |
$O(1)$ Access Block |
Write $O(1)$. Draw a single arrow skipping straight to the end of the array. |
Loop index variable |
Context binding (`this`) referencing existing array in Heap. |
| 2620 |
Counter (JS) |
Use a global variable to track state across function calls. |
Global State Diagram |
Draw a big "WINDOW" box and put a variable inside it. Draw multiple functions pointing to it, risking collision. |
Lexical Scope / Closures |
Nested Environment Boxes |
Call the outer function, it creates a "backpack" (closure) with the starting number `n`. Return the inner function. Every time inner is called, it reaches into its specific backpack, increments, and returns the value. |
Draw a big box (Outer Function). Put variable `n` inside. Draw a smaller box inside (Inner Function). Draw an arrow from Inner reaching out to `n`. |
$O(1)$ Execution Dot |
Write $O(1)$ for execution. State preservation is the core concept, not time complexity. |
Global execution context |
Heap-allocated Closure maintaining the lexical environment. |
| 2621 |
Sleep (JS) |
Blocking `while` loop checking `Date.now()` (Busy waiting). |
Infinite Loop Block |
Draw a circular arrow on the Main Thread spinning out of control, blocking everything else. $O(\text{Time})$. |
Promises + setTimeout |
Asynchronous Event Loop / Macrotask Queue |
Call function. Return a Promise. Push `setTimeout` to Web APIs. Main thread finishes immediately. Once timer pops, callback goes to queue, Event Loop pushes to Call Stack, Promise resolves. |
Draw three boxes: Call Stack, Web APIs, Callback Queue. Draw the timer moving to Web APIs, waiting, then dropping into the Queue to resolve the Promise. |
$O(1)$ Execution Timeline |
Draw a flat $O(1)$ line representing immediate execution, and a dashed line for the asynchronous waiting period. |
CPU Registers locked |
Promise object in Heap memory + Timer reference. |
| 2622 |
Cache With Time Limit (JS) |
Array storing `{key, value, expiry}`. Scan the whole array on every single `get()` or `count()`. |
Linear Array Scan |
Draw a long list. Draw a pointer checking every single row's timestamp against `Date.now()`. $O(N)$ per operation. |
Hash Map + clearTimeout |
Hash Map with Attached Timer Threads |
`set(key)`: If key exists, clear its old timer. Save new value and new `setTimeout` ID in Map. `get()`: Direct $O(1)$ lookup. `count()`: $O(1)$ using Map.size. |
Draw a Hash Map box. Next to each key-value pair, draw a little ticking stopwatch. If a key is overwritten, cross out the old stopwatch and draw a new one. |
Constant Time Lookup Diagram |
Write $O(1)$. Draw a single straight arrow pointing directly from the Key to the Value in the Map. |
Unbounded array size (if no cleanup) |
Map holding keys, values, and timeout IDs. |
| 2623 |
Memoize (JS) |
Execute the heavy function every single time, regardless of whether the inputs have been seen before. |
Redundant Execution Trees |
Draw a function call `f(2,2)` computing steps. Draw `f(2,2)` again right next to it doing the exact same math steps. $O(N)$ redundant work. |
Closure + Hash Map (Caching) |
Look-Up Table (LUT) Gateway |
Stringify arguments. Check if string exists in Map. If yes, return stored result immediately. If no, run function, store result in Map, then return. |
Draw a toll booth (the Map). Car (args) arrives. Toll booth checks list. If on list, gate opens instantly. If not, car goes to factory, gets a product, toll booth writes it down, gate opens. |
Amortized $O(1)$ Timeline |
Draw a high spike for the first call (O(Work)), then a flat $O(1)$ baseline for all subsequent identical calls. |
Zero extra memory used |
Growing Hash Map strictly contained inside a closure. |
| 2624 |
Snail Traversal (JS) |
Manually tracking exact x,y coordinates with a complex direction-switching state machine. |
Chaotic Coordinate Tracking |
Draw a matrix. Scribble numbers trying to keep track of boundaries, `x`, `y`, and `direction` variables simultaneously. |
Math-based column parity (Odd/Even columns) |
Up/Down Alternating Matrix Columns |
Iterate 1D array. Column = `Math.floor(i / rows)`. If column is even, row = `i % rows` (down). If odd, row = `rows - 1 - (i % rows)` (up). |
Draw an empty grid. Draw arrows: Column 0 points DOWN. Column 1 points UP. Column 2 points DOWN. Fill array numbers strictly along the arrows. |
$O(N)$ Single Pass |
Draw a single straight line representing 1D array length N being mapped directly to a 2D space. |
Complex state objects |
Pre-allocated 2D Result Array. |
| 2625 |
Flatten Deeply Nested Array (JS) |
Convert entire array to string, strip brackets via regex, parse back to array (fails on string inputs). |
String Manipulation Block |
Draw the array as a giant string, cross out all `[` and `]`. Slow, error-prone, and destroys data types. |
Recursive DFS with Depth Tracking |
Tree Pruning by Depth |
Loop items. If item is an array AND current depth < n, recursively call flatten on it with depth+1. Otherwise, push item to result array. |
Draw a nested array as a Tree. Top level is depth 0. Draw a horizontal line at depth `n`. Anything above the line gets its brackets removed. Anything below stays intact. |
Linear Node Traversal Block |
Draw a linear block representing N elements visited exactly once, $O(N)$. |
Huge intermediate strings |
Call stack memory proportional to max depth `n` + Result Array. |
| 2626 |
Array Reduce Transformation (JS) |
Recursive calls generating new arrays and tearing them down (unnecessary stack). |
Deep Call Stack |
Draw $O(N)$ recursive frames stacked vertically, risking maximum call stack size exceeded. |
Iterative Accumulator Update |
Conveyor Belt Accumulator |
Start with `init`. Pass `init` and `arr[0]` to the function. Take the result, make it the new `init`. Move to `arr[1]`. |
Draw a box labeled "Accumulator". Draw array items on a conveyor belt. Each item drops into the box, changes the number, and the next item drops in. |
$O(N)$ Linear Pipeline |
Draw a single straight arrow through N elements, $O(N)$ time. |
$O(N)$ Call Stack memory |
$O(1)$ Constant Space variable (the accumulator). |
| 2627 |
Debounce (JS) |
Calling the function on every single user input/event directly. |
Spam Execution Timeline |
Draw a timeline. Every time the user types a letter, draw a massive spike indicating a heavy API call (O(Spam)). |
Closure + clearTimeout / setTimeout |
Resetting Fuse / Timer Bar |
Trigger event -> start timer. Trigger again before timer ends -> destroy old timer, start new timer. Timer hits 0 -> execute function. |
Draw a timeline. Draw an event as a dot. Start drawing a horizontal line (the timer). If another dot appears, erase the line and start over. When the line reaches length 'T', draw an execution star. |
Delayed $O(1)$ Execution |
Draw the timeline showing execution shifted by `t` ms after the final event. |
Clogged Event Queue |
Single integer memory (Timer ID variable in closure). |
| 2628 |
JSON Deep Equal (JS) |
`JSON.stringify(o1) === JSON.stringify(o2)` (Fails on object key order). |
Rigid String Comparison |
Draw two JSON strings. Show how `{a:1, b:2}` and `{b:2, a:1}` mismatch strictly due to character position. |
Recursive DFS Type Checking |
Parallel Tree Traversal |
Check types. If primitive, `===`. If Array, check length, then recursively compare `arr1[i]` to `arr2[i]`. If Object, check key count, then recursively check values for every key. |
Draw two Trees (Objects). Put a finger on the root of both. Move down to child nodes simultaneously. If fingers point to different types/values, return false. |
Linear Node Visit Block |
Draw a block representing $O(N)$ where N is total nested keys/values visited once. |
Massive String allocations |
Call stack depth $O(D)$ where D is object nesting depth. |
| 2629 |
Function Composition (JS) |
Manually nesting calls: `fn1(fn2(fn3(x)))` which is rigid and hardcoded. |
Deeply Nested Parentheses |
Write out the mathematical expression `f(g(h(x)))` showing how deep and unscalable it is. |
Right-to-Left Array Reduce |
Reverse Assembly Line |
Start with input `x`. Feed `x` into the LAST function in the array. Take its output, feed it into the second-to-last function. Repeat to index 0. |
Draw a pipe. Put array of functions in boxes backwards. Push value `x` in from the right. Draw the transformed value moving left through each box. |
Sequential Processing Arrow |
Draw a right-to-left $O(N)$ timeline through the array of functions. |
Multiple intermediate variables |
$O(1)$ State variable carrying the transformed result. |
| 2630 |
Memoize II (JS) |
`JSON.stringify(args)` as a cache key. (Fails on un-stringifyable objects or Object References). |
String Builder Bottleneck |
Draw a complex object failing to serialize, or two different objects serializing to the same string `"[object Object]"`. |
Nested Maps / Prefix Tree (Trie) |
Deep Map Tree (Trie) Node Hopping |
Arg 1 is a Map key pointing to another Map. Arg 2 is a key in *that* Map. The final Map holds the `result`. `Map` allows object references as keys! |
Draw a Tree. Root is an empty Map. Edge to child is `arg1`. Edge from child to grandchild is `arg2`. The leaf node contains the cached result. Follow the path. |
$O(1)$ Map Lookups Sequence |
Draw an $O(K)$ timeline, where K is the number of arguments (depth of the Map tree). |
Massive redundant string keys |
Trie / Nested Maps utilizing Javascript Heap object references. |
| 2631 |
Group By (JS) |
Nested loops: For each element, check all existing groups in an array of objects; if not found, create new. |
Linear Scan Grouping |
Draw an array of items and an array of buckets. For every item, draw an arrow checking every bucket. $O(N^2)$. |
Hash Map (Object Literal) Accumulator |
Categorical Bucketing |
Iterate array. Apply `fn` to get key. If key exists in Map, push item to its array. Else, create new array with item. |
Draw a set of items. Draw a "Black Box" (the function). Items pass through and fall into labeled buckets (the Map keys). |
$O(N)$ Single Pass |
Draw one long arrow through the input array, labeling $O(N)$ total time complexity. |
Intermediate temporary arrays |
Single Map object containing multiple array references in Heap. |
| 2632 |
Curry (JS) |
Manually returning nested anonymous functions for a fixed number of arguments. |
Hardcoded Function Nest |
Draw boxes inside boxes, but only to a depth of 3 or 4. Fails if the function expects 10 args. |
Recursive Closure / Function Arity |
Argument Collection Reservoir |
Check `args.length` against `fn.length`. If enough, call `fn`. If not, return a new function that `concat`s new args with old. |
Draw a tank (the closure). Pour in drops (args). Once the water level hits the "Arity Line" (fn.length), the tank empties (executes). |
$O(N)$ Argument accumulation |
Draw a timeline of function calls until N arguments are met. $O(N)$ where N is arity. |
Global variable tracking |
Recursive closure stack holding persistent argument arrays. |
| 2633 |
Convert Object to JSON String (JS) |
Using string concatenation manually without handling escaping or nested types. |
Flat String Append |
Draw a string growing character by character, failing to account for nested structures. |
Recursive DFS Serialization |
Tree-to-String Transformation |
Check type. If null/string/num, return formatted value. If Array/Object, recursively call for each element/key and wrap in brackets. |
Draw a Tree. At each node, write its JSON representation. Combine strings as you bubble back up the tree. |
$O(N)$ Node Traversal |
Draw a block representing every key and value being visited exactly once. $O(N)$. |
Large intermediate string buffers |
Call stack depth $O(D)$ + efficient string builder patterns. |
| 2634 |
Filter Elements from Array (JS) |
Using `Array.splice()` inside a loop to remove elements that don't pass the test. |
Shifting Element Grid |
Draw an array. Cross an item out. Draw arrows showing every element to the right shifting left. $O(N^2)$. |
Iterative New Array Push |
Selection Sieve |
Create empty result array. Iterate input. If `fn(arr[i], i)` is truthy, push to result. Return result. |
Draw the input array. Below it, draw a "Pass/Fail" row based on the function. Draw arrows only from "Pass" items to a new array. |
$O(N)$ Linear Scan |
Draw a single pass arrow over the array, labeling $O(N)$. |
In-place modification costs |
Standard $O(N)$ space for the new result array. |
| 2635 |
Apply Transform Over Each Element (JS) |
Modifying the original array in place (mutating input). |
Destructive Update |
Draw an array. Scratch out old values and write new ones. Data loss occurs if original is needed later. |
Iterative Mapping (New Array) |
Transformation Pipeline |
Create new array. For each index `i`, calculate `fn(arr[i], i)` and store at `res[i]`. |
Draw an input array. Above it, draw the "Transformation Function". Draw arrows up, through the function, and into a new array. |
$O(N)$ Linear Scan |
Draw a single pass arrow over the array, $O(N)$. |
Zero extra space (if modifying input) |
$O(N)$ space for the new resulting array. |
| 2636 |
Promise Pool |
Launch all promises simultaneously using `Promise.all()`. |
Exploding Parallel Spikes |
Draw a single point in time and N arrows shooting out at once. No limit/control. $O(N)$. |
Recursive Chain / Worker Pool |
Moving Window of Concurrency |
Start `n` promises. When one finishes, immediately start the next pending function from the list. Maintain exactly `n` active workers. |
Draw a pipe with width `n`. Draw functions entering the pipe. As one exits (resolves), another enters the other side. |
Parallel Execution Timeline |
Draw N blocks of varying lengths packed into `n` horizontal rows. Total time = sum(durations) / n. |
Memory spike for N promises |
$O(n)$ active promise handles in the heap at any given time. |
| 2637 |
Promise Time Limit |
Waiting for the promise to finish and manually checking time elapsed via `Date.now()`. |
Post-hoc Time Check |
Draw a task finishing, then looking at a clock. If it's too late, it's already done too much work. |
Promise.race() with Timer |
Dual-Track Race |
Create two promises: the original task and a `setTimeout` that rejects after `t`. Use `Promise.race([task, limit])`. First one to finish wins. |
Draw two parallel runners: "Worker" and "Clock". Draw a finish line at time `t`. If "Clock" crosses first, the race ends with an Error. |
Constant Overhead Block |
Draw the task block $O(T)$ and a small $O(1)$ box for the timer setup. |
N/A |
Closure holding timer ID and resolve/reject references. |
| 2638 |
Count the Number of K-Free Subsets |
Generate all 2^N subsets and check the condition for each. |
Exponential Subset Tree |
Draw a binary tree of depth N where each path is a subset. Total nodes = 2^N. |
Sorting + DP on Chains |
Connected Chain DP |
Group numbers by their remainders mod `K`. In each group, sort numbers. If two numbers differ by `K`, they are "conflicting". Use DP (like House Robber) to count valid subsets for each group. |
Draw chains of numbers: e.g., (1 -> 3 -> 5) if K=2. For each chain, calculate subset counts using `dp[i] = dp[i-1] + dp[i-2]`. Multiply results. |
Linear Sorting Block |
Draw sorting $O(N \log N)$ followed by a linear $O(N)$ pass for DP calculations. |
Massive subset storage |
Frequency map + DP array or constant space variables per chain. |
| 2639 |
Find the Width of Columns of a Grid |
Iterate through every cell, convert to string, and update a max width variable for the column. |
Cell-by-Cell Stringification |
Draw the grid. For every cell, draw a "ToString()" conversion and a length check. $O(R \cdot C)$. |
Column-Wise Linear Scan |
Vertical Scanner Bar |
Traverse column-by-column. For each column, find the maximum string length of its elements. |
Draw a grid. Draw a vertical rectangle highlighting Column 1. Find the longest string. Move the rectangle to Column 2. |
$O(R \cdot C)$ Scan |
Draw a block representing R rows and C columns being visited exactly once. |
N/A |
$O(C)$ space for storing width of each column. |
| 2640 |
Find the Score of All Prefixes of an Array |
For every prefix, find the max, calculate "conver" values, and sum them up (Nested loops). |
Nested Prefix Summations |
Draw a triangle of operations: for prefix 1, do 1 step; for prefix 2, do 2 steps. $O(N^2)$. |
Running Max + Prefix Sum (Single Pass) |
Rolling Maximum Snowball |
Maintain a `runningMax`. Calculate `conver[i] = nums[i] + runningMax`. The score is the prefix sum of the `conver` values. |
Draw the input array. Below it, write the `runningMax` for each index. Below that, write the sum. Draw an arrow moving left to right. |
$O(N)$ Linear Flow |
Draw a single line arrow across N elements, $O(N)$. |
Intermediate prefix arrays |
In-place conversion or $O(N)$ result array. |
| 2641 |
Cousins in Binary Tree II |
For every node, perform a full BFS/DFS to find its depth, find its parent, and then sum all other nodes at that depth. |
Recursive Redundant Traversal |
Draw a tree. For every single node, draw a new scan of the entire level. Label $O(N^2)$. |
Two-Pass BFS (Level Sums) |
Level-by-Level Bucket Sums |
Pass 1: BFS to calculate the total sum of each level. Pass 2: BFS where each node's value = (Total Level Sum) - (Sum of Sibling values). |
Draw a tree. Next to each level, write the "Total Sum". At each node, look at its children; subtract their combined sum from the NEXT level's total sum. |
Linear BFS Flow |
Draw two sequential $O(N)$ blocks (Pass 1 and Pass 2). |
Deep recursion stack for every node |
Queue for BFS + Array to store Level Sums. |
| 2642 |
Design Graph Shortest Path Calculator |
Run BFS or DFS from scratch every time `shortestPath` is called. |
Unoptimized Path Search |
Draw a graph. For every query, draw a sprawling web of paths being recalculated. $O(Q \cdot (V+E)$). |
Dijkstra's Algorithm (with Priority Queue) |
Expanding Dijkstra Frontiers |
Use a Priority Queue to always expand the shortest known distance. When `addEdge` is called, update the adjacency list. |
Draw the start node. Draw a circle (frontier). Expand the circle to the nearest neighbors first. Label edges with weights. |
Logarithmic Heap Operations |
Draw a loop for Q queries, inside it a Dijkstra block $O(E \log V)$. |
Adjacency Matrix (N^2) |
Adjacency List (V+E) + Min-Heap. |
| 2643 |
Row With Maximum Ones |
Nested loops scanning every cell in the matrix to count 1s. |
Full Grid Scan |
Draw a grid. Draw a pointer hitting every single cell (0s and 1s) one by one. $O(R \cdot C)$. |
Linear Row Scan + Tracker |
Horizontal Progress Bars |
Iterate row by row. Maintain `maxCount` and `maxRowIndex`. If current row's count is strictly greater, update both. |
Draw a matrix of 0s and 1s. To the right of each row, write the count of 1s. Circle the largest number and its row index. |
$O(R \cdot C)$ Linear Scan |
Draw a block representing R * C visits. Note: This is theoretically optimal for an unsorted binary matrix. |
N/A |
$O(1)$ space (two integer variables). |
| 2644 |
Find the Maximum Divisibility Score |
Nested loops: For each divisor, iterate through all numbers to check divisibility. |
Divisor-to-Array Mapping |
Draw a list of divisors. For each one, draw arrows to every element in the array. $O(D \cdot N)$. |
Frequency Map + Divisibility Check |
Tally Counter / Sieve-lite |
Count frequencies of numbers in `nums`. Then, for each unique divisor, multiply the frequency of its multiples in the map to get the score. |
Draw a frequency table for `nums`. For each divisor, look up its multiples in the table and sum their counts. |
$O(D \cdot N)$ or $O(D \\text{cdot unique}(N)$) |
Draw an $O(N)$ grouping block followed by an $O(D \\text{cdot unique}_N)$ check block. |
N/A |
Hash Map for number frequencies. |
| 2645 |
Minimum Additions to Make Valid String |
Backtracking or BFS to find the shortest path from current string to a valid "abc...abc" sequence. |
State Space Search Tree |
Draw a tree where each branch is adding 'a', 'b', or 'c'. The tree explodes in size. $O(3^N)$. |
Greedy / Math-based Cycle Counting |
Pattern Cycle Filling |
Iterate through the string. Every time the current character is less than or equal to the previous (e.g., 'b' followed by 'a'), a new "abc" cycle must have started. Total additions = 3 * (number of cycles) - original length. |
Draw the string. Draw a vertical line whenever the alphabetical order breaks (e.g., ab | a | c | b). Count the blocks. Additions = 3 * Blocks - Length. |
$O(N)$ Single Pass |
Draw a single arrow scanning the string once. $O(N)$. |
Recursive state storage |
$O(1)$ space (variable to track cycles and previous character). |
| 2646 |
Minimize the Total Price of the Trips |
Exhaustive search for every possible combination of "halved" nodes (2^N) and calculating trip costs. |
Exponential Decision Tree |
Draw a tree where each node splits into "Halve" or "Don't Halve". Label $O(2^N \\text{cdot Trips} \cdot N)$. |
Tree DP + Frequency Map (BFS/DFS) |
Weighted Node Frequency Map |
1. For each trip, use BFS/DFS to find the path and increment a "contribution" counter for each node. 2. Use Tree DP: for each node, the cost is `(Freq * Price)`. Recurse to find min cost if current is halved (children cannot be halved) vs not halved. |
Draw the tree. Write a number inside each node representing how many trips pass through it. Use DP: `dp[u][0]` (not halved) and `dp[u][1]` (halved). |
Linear Tree Traversal |
Draw $O(\text{Trips} \cdot N)$ for path finding followed by $O(N)$ for the DP pass. |
N/A |
Frequency array and DP table/memoization map. |
| 2647 |
Color the Triangle Red |
Try every possible coloring combination and check if it follows the "triangle sum" rule. |
Recursive Grid Permutation |
Draw a triangle of size N. Branch out every cell into "Red" or "Blue". $O(2^(N^2)$). |
Constructive Pattern / Mathematical Observation |
Geometric Grid Tiling |
Notice the pattern for small N. The coloring follows a specific modular pattern based on the row index. Usually, it involves filling the base and working upward with specific offsets. |
Draw a triangle of rows. Label rows 1 to N. Fill the cells according to the observed pattern (e.g., specific cells in the last row, then every few cells in higher rows). |
$O(N)$ Construction |
Draw a single pass that iterates through rows to generate coordinates. $O(N)$. |
N/A |
List to store result coordinates. |
| 2648 |
Generate Fibonacci Sequence (JS) |
Calculate all Fibonacci numbers up to N and store them in an array before returning. |
Pre-calculated Array Buffer |
Draw an array filling up with numbers. If the user only needs the 5th number, you've wasted memory on 100. |
Generators (`yield`) |
Lazy Evaluation Stream |
Use `function*`. Maintain two variables `a` and `b`. Inside a `while(true)` loop, `yield a`, then update `[a, b] = [b, a + b]`. The sequence is generated only as requested. |
Draw a machine with a lever. Every time the lever is pulled (`next()`), one number pops out. The machine then "freezes" its internal state until the next pull. |
$O(1)$ per step |
Draw a point representing a single execution step. Total time is $O(N)$ only if N numbers are requested. |
$O(N)$ Array storage |
$O(1)$ persistent state (two variables inside the generator scope). |
| 2649 |
Nested Array Generator (JS) |
Flatten the entire array into a 1D list first, then iterate. |
Eager Flattening Scan |
Draw a deeply nested array being copied into a flat list. High initial memory and time cost. $O(N)$. |
Recursive Yield* (Delegation) |
Recursive Lazy Traversal |
Iterate the array. If an element is a number, `yield` it. If it is an array, use `yield*` to delegate to the same generator recursively. |
Draw a tree. The generator walks down a branch. When it hits a leaf (number), it yields it. It "remembers" its path and resumes from the exact spot. |
$O(N)$ Total Traversal |
Draw a single DFS path through the nested structure. Each element is visited exactly once. |
$O(N)$ Flat Array copy |
$O(D)$ memory where D is the maximum depth of nesting (stack size). |
| 2650 |
Design Cancellable Function |
Use global state variables to track if a function should stop, requiring manual checks inside every loop of the generator. |
Messy Global Flags |
Draw a function box connected to a giant red "STOP" button that constantly has to be polled. |
JavaScript Generators & Promises |
The Yield Interceptor |
Wrap the generator in a Promise. Create a `cancel` function that forces the generator to throw an error (`generator.throw()`). Handle the yields recursively, passing resolved values back via `generator.next()`. |
Draw a conveyer belt (Generator) yielding boxes (Promises). An overseer resolves the box and feeds the result back. If the "Cancel" lever is pulled, the overseer throws a wrench into the belt. |
Asynchronous Resolution $O(N)$ |
Draw a timeline of yielded promises resolving sequentially. |
Callback hell and memory leaks. |
Closure scopes storing the generator state. $O(1)$ auxiliary space. |
| 2651 |
Calculate Delayed Arrival Time |
Using a 24-hour clock logic with multiple `if-else` conditions to handle overflow. |
Conditional Branching Tree |
Draw a flowchart: Is time > 24? Subtract 24. Is it still > 24? Subtract again. $O(1)$ but messy logic. |
Modulo Arithmetic (%) |
Circular Clock Face |
Add `arrivalTime` and `delayedTime`. Apply `% 24`. This instantly "wraps" any value back into the 0-23 range. |
Draw a circle with 24 notches (0-23). Draw an arrow starting at `arrival`, moving `delayed` steps forward. Where it lands is the answer. |
$O(1)$ Calculation Block |
Draw a single mathematical operation box. $O(1)$. |
N/A |
$O(1)$ constant space for the result. |
| 2652 |
Sum Multiples |
Iterate from 1 to N, check if each number is divisible by 3, 5, or 7. Sum the matches. |
Linear Filter Scan |
Draw a list of numbers 1 to N. Draw a checkbox next to each one that passes the divisibility test. $O(N)$. |
Inclusion-Exclusion Principle (Math) |
Overlapping Venn Diagrams |
Sum multiples of 3, 5, and 7 using the formula for arithmetic progression S = fracn2(first + last). Subtract overlaps (multiples of 15, 21, 35) and add back the triple overlap (105). |
Draw three circles (3, 5, 7). Label the overlaps. Use the formula Sum = S(3)+S(5)+S(7) - S(15)-S(21)-S(35) + S(105). |
$O(1)$ Algebraic Formula |
Draw a single block containing the sum formulas. Total $O(1)$. |
N/A |
$O(1)$ constant space. |
| 2653 |
Sliding Subarray Beauty |
For every window of size K, sort the elements and pick the X-th smallest negative number. |
Nested Sort Window |
Draw a sliding bracket. Inside the bracket, draw a sorting tree. Label $O((N-K)$ * K log K). |
Sliding Window + Frequency Array (Counting Sort) |
Sliding Frequency Bucket |
Since values are limited (-50 to 50), use an array of size 101 to track frequencies in the current window. Move window: add new element to freq, remove old. Iterate freq array to find X-th smallest. |
Draw a small array of 101 buckets. As the window slides, increment/decrement buckets. To find beauty, count buckets from the left (index 0) until reaching X. |
Linear Window Scan |
Draw an $O(N)$ loop. Inside it, draw a small $O(101)$ constant scan of the frequency array. |
Copied sub-arrays for sorting |
$O(\text{Range})$ space for the frequency bucket array (constant size 101). |
| 2654 |
Minimum Number of Operations to Make All Array Elements Equal to 1 |
Exhaustively try all possible subarray GCDs to find the shortest subarray that results in 1. |
Nested GCD Subarrays |
Draw an N x N matrix. Each cell represents a GCD of a subarray. Find the smallest distance `j-i` where GCD is 1. $O(N^2)$. |
Iterative GCD + Greedy Expansion |
GCD Cascade / Reduction |
Find the smallest subarray whose GCD is 1. If 1 already exists, the answer is `N - count(1)`. If not, find min length `L` of a subarray with GCD 1. Answer is `(L - 1) + (N - 1)`. |
Draw the array. Pick two numbers, find GCD. Replace one. Repeat until a 1 appears. Use that 1 to "infect" every other number in the array. |
$O(N^2)$ Matrix Traversal |
Draw an $O(N^2)$ block for the nested loops to find the smallest GCD 1 subarray. |
N/A |
$O(1)$ space if modifying in place or using variables. |
| 2655 |
Find Maximal Uncovered Ranges |
Create a boolean array of size N, mark all intervals, then scan for False values. |
Boolean Coverage Map |
Draw a giant array of bits. Color segments based on intervals. Scan for white gaps. $O(N + \text{Intervals})$. Fail if N is very large. |
Sorting + Merging Intervals |
Timeline Gap Analysis |
Sort ranges by start time. Merge overlapping ranges. The gaps between the merged ranges (and at the boundaries 0 and N-1) are your uncovered ranges. |
Draw a line 0 to N. Draw intervals as bars above the line. "Squash" overlapping bars together. Draw circles in the empty spaces on the line. |
$O(M \log M)$ Sort and Merge |
Draw a sorting block $O(M \log M)$ for M intervals, followed by a single $O(M)$ pass to find gaps. |
$O(N)$ Boolean array |
$O(M)$ space to store the intervals and the result list. |
| 2656 |
Maximum Sum With Exactly K Elements |
Simulate the process: Find max, add to sum, increment it, put it back. Repeat K times. |
Iterative Simulation Timeline |
Draw a loop running K times. Inside, draw a "Search Max" arrow $O(N)$. Total $O(N\cdot K)$. |
Greedy + Arithmetic Progression |
Step-up Arithmetic Series |
Find the maximum element `m` once. The next elements will be `m+1, m+2, ..., m+(k-1)`. Use the sum formula: Sum = k * m + frack(k-1)2. |
Draw the array. Circle the max value `m`. Draw K boxes, starting with `m` and increasing by 1. Sum them using the formula. |
$O(N)$ Max Search |
Draw a single pass $O(N)$ to find max, followed by an $O(1)$ math block. |
$O(K)$ to store the simulated sequence |
$O(1)$ constant space (only the max and sum variables). |
| 2657 |
Find the Prefix Common Array of Two Arrays |
For every index `i`, use nested loops to check how many elements in `A[0...i]` exist in `B[0...i]`. |
Nested Prefix Intersection |
Draw two arrays. For each prefix, draw lines comparing every element. $O(N^3)$ or $O(N^2)$ with sets. |
Frequency Map / Bitset (Single Pass) |
Parallel Frequency Counters |
Iterate through both arrays simultaneously. Use a frequency array to track occurrences. When a number's count hits 2, it's "common." Update a running count. |
Draw arrays A and B. Below them, draw a frequency array. As you move right, increment counts for `A[i]` and `B[i]`. If a count hits 2, increment your "common" tracker. |
$O(N)$ Linear Scan |
Draw a single pass arrow over the length of the arrays. $O(N)$. |
Nested sub-arrays for intersection |
$O(N)$ frequency array or Set. |
| 2658 |
Maximum Number of Fish in a Grid |
Start a DFS/BFS from every single cell to calculate the total fish in connected water components. |
Redundant Grid Search |
Draw a grid. From every cell, draw a sprawling DFS. Show how many cells are revisited. $O(R^2 \cdot C^2)$. |
DFS / BFS + Grid Traversal (Visited tracking) |
Flood Fill Component Sum |
Iterate through the grid. If a cell has fish and is unvisited, start a DFS to sum all fish in that "pond." Mark cells as visited to ensure each pond is only counted once. |
Draw a grid with "water" (numbers) and "land" (0). Pick a water cell, "color" the whole connected pond, and sum the values. Move to the next uncolored water cell. |
$O(R \cdot C)$ Single Visit |
Draw a block representing R * C. Each cell is visited exactly once by the overall iteration and the DFS combined. |
Recursive stack for every cell |
$O(R \cdot C)$ for the visited matrix and recursive call stack. |
| 2659 |
Make Array Empty |
Simulate the rotation: if not min, move to end. If min, remove. |
Queue Simulation |
Draw a circular queue. Show elements jumping from front to back. In worst case (sorted descending), this is $O(N^2)$. |
Sorting + Fenwick Tree (Binary Indexed Tree) |
Indexed Gap Counting |
Sort elements with original indices. Use a BIT to track how many elements have been removed. The "jumps" between sorted elements' original indices (accounting for removals) tell you the rotation count. |
Draw the array with indices. Sort them. Draw arrows jumping between the original indices. Use a BIT to "subtract" the spots where elements were already removed. |
$O(N \log N)$ BIT Operations |
Draw a sorting block $O(N \log N)$ and N operations on a Fenwick Tree $O(\log N)$. |
N/A |
$O(N)$ for the BIT and sorted index mapping. |
| 2660 |
Determine the Winner of a Bowling Game |
Complex simulation with nested lookbacks to check if previous strikes occurred. |
Simulation with Lookback |
Draw the score sequence. For each score, draw arrows looking back at the last two indices. $O(N)$. |
Linear Scan with State Tracker |
State-Based Scoring |
Iterate through the pins. Keep a "multiplier" state. If either of the last two scores was 10, double the current score. Reset or maintain state as you move. |
Draw two rows of scores. For each score, check the previous two. If a 10 exists, write "x2" below the current score. Sum them up and compare. |
$O(N)$ Single Pass |
Draw two parallel $O(N)$ arrows, one for each player. |
N/A |
$O(1)$ space to store player scores and the lookback state. |
| 2661 |
First Completely Painted Row or Column |
For every number in the painting sequence, search the matrix, paint the cell, and then scan its entire row and column to check if they are full. |
Full Matrix Re-scanning |
Draw a matrix. For every step in the 'arr', draw a cross-hair scan of the row and column. $O(K \cdot (R + C)$). |
Hash Map + Frequency Counters |
Coordinate Lookup & Tally |
1. Map each matrix value to its (r, c) coordinates. 2. Create two arrays: `rowCount` and `colCount`. 3. Iterate through 'arr', lookup the (r, c), and increment `rowCount[r]` and `colCount[c]`. The first time a count equals the total size, return the index. |
Draw a Coordinate Map (Value -> R, C). Draw two tally bars (Rows, Cols). As you process 'arr', add a tick to the corresponding Row and Col bar. Return when a bar is full. |
$O(R \cdot C + K)$ Total Time |
Draw an $O(R\cdot C)$ setup block followed by a single $O(K)$ pass. |
N/A |
$O(R\cdot C)$ for the coordinate map and $O(R + C)$ for the counters. |
| 2662 |
Minimum Cost of a Path With Special Roads |
BFS/DFS exploring every single coordinate point on a 10^5 x 10^5 grid. |
Infinite Grid Exploration |
Draw a coordinate plane. Draw a sprawling web of paths trying to visit every integer point. Complexity is effectively infinite/unbound. |
Dijkstra's on a Coordinate Graph |
Inter-Point Shortest Path |
Treat the start, end, and all special road endpoints as "nodes" in a graph. The distance between any two nodes is either the Manhattan distance or the special road cost. Run Dijkstra from Start to End. |
Draw only the relevant points (Start, End, and special road endpoints). Draw edges between every pair of points with Manhattan distance. Replace some with special road costs. Find the shortest path. |
$O(N^2 \log N)$ where N is # of special roads |
Draw a Dijkstra block where V = 2 * number of special roads. |
Full grid state matrix |
Priority Queue and a Map for node distances. |
| 2663 |
Lexicographically Smallest Beautiful String |
Generate the next lexicographical string, check if it has palindromes. If yes, generate the next. $O(26^N)$. |
Endless Lexicographical Checking |
Write the string. Increment the last letter. Scan the whole string for palindromes. Repeat millions of times. |
Greedy String Mutation (Right-to-Left) |
The Local Suffix Fixer |
Work backwards from the end of the string. Increment a character. To keep it "beautiful", the new character only needs to differ from `string[i-1]` and `string[i-2]`. Once a valid increment is found, fill the rest of the string with the smallest valid characters. |
Draw the string. Point to the last letter. Bump it up by 1. Check the 2 letters to its left. If it matches either, bump it again. Once safe, move to the right and fill with 'a', 'b', or 'c' while avoiding local pairs. |
Linear Scan & Fill $O(N)$ |
Draw a line moving right-to-left to find the pivot, then left-to-right to fill the suffix. |
Millions of generated strings. |
A character array. $O(N)$ space. |
| 2664 |
The Knight's Tour |
Exhaustive backtracking trying every move without any heuristic. |
Exponential Backtracking Tree |
Draw a 5x5 grid. At each step, draw 8 branching arrows. Show the tree depth reaching 25. $O(8^(R\cdot C)$). |
Backtracking (Warnsdorff’s Rule optional) |
Recursive Path Finding |
Use standard backtracking. From (r, c), try all 8 knight moves. If move is valid and unvisited, recurse. If you reach R*C steps, you are done. |
Draw the grid. Number the start cell '0'. Try a move, number it '1'. If stuck, erase '1' and try a different '1'. Continue until the grid is full. |
$O(8^(R\cdot C)$) (Worst case) |
Draw the recursive stack depth showing it reaches exactly R * C nodes. |
Deep recursion stack |
$O(R \cdot C)$ for the result matrix and recursion depth. |
| 2665 |
Counter II (JS) |
Using a global variable and separate functions that don't share a state correctly. |
Fragmented Global State |
Draw three separate functions and a global `n`. Any function can mess with `n` at any time. $O(1)$. |
Closures / Factory Pattern |
Encapsulated State Object |
Create a function that takes `init`. Declare a local `currentCount`. Return an object with three methods: `increment`, `decrement`, and `reset` that all reference `currentCount`. |
Draw a "Container" (the closure). Put `init` and `val` inside. Draw three buttons on the container: (+), (-), and (Reset). All buttons change the same `val` inside the container. |
$O(1)$ per method |
Write $O(1)$ for each property access. |
Global scope pollution |
Persistent closure memory for the `val` variable. |
| 2666 |
Allow One Function Call |
Using a global counter and checking if count > 0 before every execution. |
Global State Dependency |
Draw a function and a global "Called" flag. Show how other functions might accidentally reset the flag. $O(1)$. |
Closure / Higher-Order Function |
One-Way Gate Pattern |
Return a new function. Inside the closure, keep a boolean `hasBeenCalled`. If false, flip to true and execute the original function. If true, return undefined. |
Draw a gate with a latch. The first person (call) trips the latch and passes through. The latch stays locked for everyone else. |
$O(1)$ Execution |
Draw a single logic branch: `if(!called)`. Total $O(1)$. |
Global variable pollution |
Private boolean flag stored in the function's lexical environment. |
| 2667 |
Create Hello World Function |
Hardcoding a function that ignores all inputs and returns a string. |
Static Return |
Draw a box that always spits out "Hello World" regardless of what is put inside. $O(1)$. |
Higher-Order Function (Factory) |
Function Factory |
Define a function that returns another function. The inner function, when invoked, returns "Hello World". This demonstrates the fundamental JS pattern of returning executable code. |
Draw a machine (Outer) that builds a smaller machine (Inner). The Inner machine's only job is to say "Hello World". |
$O(1)$ |
Write $O(1)$. It is a constant time operation. |
N/A |
Minimal memory for the function reference in the heap. |
| 2668 |
Find Latest Salaries (SQL) |
Using a self-join to compare every row with every other row to find the maximum date per employee. |
Quadratic Join Scan |
Draw a table joined to itself. For N rows, show N^2 comparisons to find the max date. $O(N^2)$. |
Window Functions (`RANK()` or `MAX() OVER`) |
Partitioned Sorting |
Use `RANK() OVER (PARTITION BY emp_id ORDER BY salary_date DESC)`. Then filter for rows where rank = 1. This groups and sorts within groups efficiently. |
Draw the table. Draw brackets around rows with the same Employee ID. Within each bracket, sort by date. Pick the top row from each bracket. |
$O(N \log N)$ Sorting |
Draw a block representing the partitioned sort. The database engine optimizes this as a single pass after sorting. |
Temporary Join Tables |
Memory used by the SQL engine for the internal sort and windowing partition. |
| 2669 |
Count Artist Occurrences On Spotify (SQL) |
Iterating through rows and using `LIKE` or substring matches for every single entry. |
String Pattern Scan |
Draw a table. For every row, draw a "Search" operation scanning the text for an artist name. $O(N \cdot M)$. |
GROUP BY + COUNT |
Categorical Aggregation |
Group the table by the `artist` column and use the `COUNT(*)` aggregate function. Order the results by the count in descending order. |
Draw a pile of records. Sort them into stacks by artist name. Count the height of each stack. Arrange stacks from tallest to shortest. |
$O(N \log N)$ (due to sorting) |
Draw a grouping block $O(N)$ and a final sorting block $O(N \log N)$. |
N/A |
Hash-map based grouping in the SQL engine memory. |
| 2670 |
Find the Distinct Difference Array |
For every index `i`, use nested loops to count unique elements in the prefix `0...i` and suffix `i+1...n-1`. |
Nested Unique Scans |
Draw an array. For every index, draw two separate scans looking for duplicates. $O(N^2)$. |
Two-Pass Hash Set (Prefix/Suffix) |
Parallel Set Accumulation |
1. Scan left to right, adding to a Set to track prefix unique counts. 2. Scan right to left, adding to a Set to track suffix unique counts. Result at `i` is `prefixCount[i] - suffixCount[i+1]`. |
Draw the array. Above it, write the count of unique items seen from the left. Below it, write unique items seen from the right. Subtract the two rows. |
$O(N)$ Linear Pass |
Draw two sequential $O(N)$ arrows (Forward and Backward). |
Repeated sub-array slicing |
Two integer arrays of size N + two Sets (max size N). |
| 2671 |
Frequency Tracker |
Iterate through the entire data structure every time 'hasFrequency' is called to count occurrences. |
Linear Search Scan |
Draw a list of numbers. When asked for frequency 'f', scan the whole list and count every number's occurrence. $O(N)$ per query. |
Dual Hash Maps (Count of Counts) |
Nested Frequency Mapping |
Maintain two maps: 1. `numberToFreq` (Value -> Count) and 2. `freqToCount` (Count -> How many values have this frequency). On add/remove, update both maps in $O(1)$. |
Draw two tables. Table A: Number | Freq. Table B: Freq | Count. When adding a number, increment its Freq in A, and update the corresponding tally in B. |
$O(1)$ Constant Time |
Draw a single lookup arrow into the `freqToCount` map. $O(1)$. |
Rescanning the entire list |
Two Hash Maps (or fixed-size arrays if range is known). |
| 2672 |
Number of Adjacent Elements With the Same Color |
For every query, iterate through the whole array and count how many pairs `(i, i+1)` have the same non-zero color. |
Full Array Pair Scan |
Draw an array. For every single update, draw a pointer scanning all adjacent pairs. $O(Q \cdot N)$. |
Local Incremental Update |
Neighborhood Change Tracking |
Before coloring `arr[i]`, check if it already matches `arr[i-1]` or `arr[i+1]` (decrement total if so). Change color. Check again if the new color matches neighbors (increment total). |
Draw three cells: [i-1, i, i+1]. Only look at these three. If i matches a neighbor, add 1 to a running counter. If it stops matching after a change, subtract 1. |
$O(1)$ per Query |
Draw a small logic box checking index `i-1` and `i+1`. $O(1)$. |
N/A |
$O(N)$ for the color array + $O(1)$ for the running total. |
| 2673 |
Make Costs of Paths Equal in a Binary Tree |
Try every possible increment combination for every node to equalize all leaf-to-root path sums. |
Brute Force Path Balancing |
Draw a tree. Branch out with different increment values for every node. $O(\text{Exponential})$. |
Bottom-Up Greedy (Post-order Traversal) |
Recursive Level Balancing |
Start from the bottom-most leaves. For any two siblings, find the difference in their path costs. Add that difference to the smaller sibling's cost (increments result). Pass the max of the two up to the parent. |
Draw a tree with leaf values. Pick two sibling leaves. Add to the smaller one to match the larger. Treat their parent as having the new balanced cost. Repeat upward. |
$O(N)$ Linear Traversal |
Draw a single bottom-up pass through the tree nodes. $O(N)$. |
Recursive state explosion |
$O(1)$ or $O(\log N)$ for the recursion stack (array-based tree). |
| 2674 |
Split a Circular Linked List |
Traverse the circular list to find the total length, then traverse again to find the midpoint and break the links. |
Two-Pass Length Scan |
Draw a circle. Draw a pointer going around once to count N, then again to N/2. $O(N)$. |
Fast and Slow Pointers (Tortoise and Hare) |
Midpoint Intersection |
Use `slow` and `fast` pointers. When `fast` (or `fast.next`) reaches the end (back to head), `slow` is at the midpoint. Break the circle into two smaller circles. |
Draw a circle. Draw a 'Slow' turtle and a 'Fast' rabbit. When rabbit finishes the loop, the turtle is halfway. Draw new lines to close two smaller loops. |
$O(N)$ Single Pass |
Draw the pointers moving in tandem. Total steps are $O(N)$. |
N/A |
$O(1)$ constant space (pointer references). |
| 2675 |
Array of Objects to Matrix |
Iteratively scan every object to find all possible keys, then scan again to fill rows, handling nesting via string manipulation. |
Flattening with Re-scanning |
Draw a list of complex objects. For every object, draw a recursive search for keys. Then for every key, search every object again. $O(N \cdot K)$. |
Recursive DFS Flattening + Sorted Key Set |
Key-Value Tree Flattening |
1. Recursively flatten each object into a `key_path: value` map. 2. Collect all unique `key_paths` into a sorted list (headers). 3. Iterate objects again to build matrix rows based on the sorted headers. |
Draw a nested object. Flatten it: `a: {b: 1}` becomes `a.b: 1`. Collect all unique "a.b" style names, sort them as column headers, and fill the rows. |
$O(\text{Total Elements})$ |
Draw a DFS traversal for each object $O(N)$ plus a sorting step for headers $O(K \log K)$. |
String concatenation overhead |
Map of flattened paths + Result matrix. |
| 2676 |
Throttle |
Execute the function every time the event triggers, ignoring the time limit entirely. |
High-Frequency Execution Spike |
Draw a timeline with 100 dots (events) and 100 stars (executions). $O(N)$. |
Closure + setTimeout + Stored Arguments |
The "Cooling Down" Pipe |
If called and not in "cooling down" state, execute immediately and start a timer. If called while cooling down, save the latest arguments. Once the timer ends, if there were saved arguments, execute again and restart the timer. |
Draw a timeline. Event 1 starts a "Busy" block. Any events during the block are ignored except the very last one. When the "Busy" block ends, the last one executes and starts a new "Busy" block. |
$O(1)$ Overhead per Event |
Draw a timeline showing only one execution per interval T. $O(1)$. |
Event listener buildup |
Closure memory storing the `timeoutId` and `nextArgs`. |
| 2677 |
Chunk Array |
Use `slice` inside a loop but manually calculate start and end indices with complex if-statements. |
Manual Index Calculation |
Draw an array and show a pointer moving index by index, checking if a new sub-array is needed. $O(N)$. |
Iterative Slicing (Step = Size) |
Fixed-Size Block Partitioning |
Iterate from 0 to array length, incrementing the index by `size` in each step. In each iteration, `slice` from current index to index + size. |
Draw a long loaf of bread. Draw vertical lines at every 'size' interval. Each piece becomes a sub-array in the result. |
$O(N)$ Total Linear Pass |
Draw one $O(N)$ arrow representing the single loop that "jumps" by the chunk size. |
N/A |
$O(N)$ space to store the new chunked 2D array. |
| 2678 |
Number of Senior Citizens |
Convert each string into an array of characters, find the age indices, and parse them. |
String-to-Array Conversion |
Draw a list of strings. For each, draw a conversion to a char list, then scanning for indices 11 and 12. $O(N\cdot M)$. |
Substring Slicing + Direct Integer Comparison |
Fixed-Offset Extraction |
Iterate through the strings. Use `substring(11, 13)` to extract the age. Convert to an integer and check if it is > 60. |
Draw a 15-character string. Highlight characters at index 11 and 12. "Age is here." Compare it to 60. |
$O(N)$ Constant Time per String |
Draw a single pass through the N strings. Since string length is fixed (15), it is $O(N)$. |
N/A |
$O(1)$ constant extra space. |
| 2679 |
Sum in a Matrix |
Exhaustively search for the maximum in every row, add the global max to score, and delete those elements. |
Iterative Row Searching |
Draw a grid. Circle the max in row 1, then row 2... Repeat this N times. $O(C \cdot R^2)$. |
Row Sorting + Column Maximums |
Aligned Sorted Matrix |
Sort every row individually. Now, for each column (from 0 to C-1), the maximum value must be the "score contribution" for that round. Sum these column maximums. |
Draw a matrix. Sort the numbers in each row. Now look at the vertical columns. Pick the biggest number in each column and add them up. |
$O(R \cdot C \log C)$ Row Sorting |
Draw R blocks of $O(C \log C)$ sorting, followed by one $O(R \cdot C)$ pass to find column maximums. |
N/A |
$O(1)$ if sorting in place, or $O(R\cdot C)$ for a copy. |
| 2680 |
Maximum OR After Operations |
Try every possible `(num << k)` for every single number and calculate the global OR. |
Exponential Combination Search |
Draw a list of N numbers. Branch each one out with "Shifted" or "Not Shifted". Label $O(2^N)$. |
Prefix/Suffix OR + Greedy Power of 2 |
Bitwise Cumulative Coverage |
1. Precalculate `prefixOR` (OR of 0 to i-1) and `suffixOR` (OR of i+1 to N-1). 2. For each number `i`, calculate `(nums[i] << k) | prefixOR[i] | suffixOR[i]`. The max is your answer. |
Draw three rows. Row 1: OR sum from left. Row 2: OR sum from right. Row 3: Current number shifted by K. Combine all three for each index and find the peak. |
$O(N)$ Linear Passes |
Draw three sequential $O(N)$ arrows (Prefix, Suffix, Comparison). |
Combinatorial state recursion |
Two $O(N)$ arrays for Prefix and Suffix OR values. |
| 2681 |
Power of Heroes |
Generate all possible non-empty subsets, find the max and min of each, and calculate the sum of (max² * min). |
Exponential Subset Generation |
Draw a power set tree for N elements. Total subsets = 2^N. Label $O(2^N)$. |
Sorting + Dynamic Programming (Prefix Sum) |
Cumulative Weighting Transform |
1. Sort the array. 2. For each element `nums[i]`, it is the maximum of any subset formed with elements to its left. The sum of minimums of those subsets follows a specific DP pattern: `s = (s * 2 + nums[i-1])`. Total power += `nums[i]² * (nums[i] + s)`. |
Draw the sorted array. For each number, calculate its "Power" by multiplying its square with its own value plus a running "weighted sum" of everything to its left. |
$O(N \log N)$ Sorting |
Draw a sorting block $O(N \log N)$ followed by a single $O(N)$ pass with modulo math. |
Storing all 2^N subsets |
$O(1)$ extra space (excluding sorting) if using a single running sum variable. |
| 2682 |
Find the Losers of the Circular Game |
Simulate the game with a large array, but use a set and check for collisions manually without a clear exit condition. |
Unbounded Simulation |
Draw a circle of people. Show an arrow jumping around indefinitely until you manually stop it. $O(N\cdot K)$. |
Boolean Array + Step Increment |
Modular Circular Traversal |
Use a `visited` boolean array. Current position starts at 0. In round `i`, move `i * k` steps forward using `(pos + i * k) % n`. Stop when you land on a `true` value. Return all indices that remain `false`. |
Draw a clock with N numbers. Start at 0. Jump 1k, then 2k, then 3k. Mark the numbers you land on. Stop when you hit a marked one. List the unmarked ones. |
$O(N)$ Total Jumps |
Draw a single loop that runs at most N times before hitting a repeat. $O(N)$. |
N/A |
$O(N)$ for the boolean visited array. |
| 2683 |
Neighboring Bitwise XOR |
Try to reconstruct the original array by guessing the first element (0 or 1) and checking if the entire sequence is valid. |
Binary Guess and Check |
Draw two branching paths (Start with 0, Start with 1). Follow each to the end to see if they satisfy the XOR condition. $O(N)$. |
XOR Sum Property |
Cumulative Parity Check |
Notice that `derived[i] = original[i] ^ original[i+1]`. If you XOR all elements of `derived`, the result is `original[0] ^ original[1] ^ original[1] ^ ... ^ original[n-1] ^ original[0]`, which equals 0. A valid array exists if `XOR_sum(derived) == 0`. |
Draw the `derived` array. XOR all numbers together. If the final result is 0, write "True". |
$O(N)$ Single Pass |
Draw a single pass arrow XORing elements. $O(N)$. |
N/A |
$O(1)$ constant space (one XOR accumulator). |
| 2684 |
Maximum Number of Moves in a Grid |
DFS from every cell in the first column, exploring all paths through the grid. |
Redundant DFS Paths |
Draw a grid. From the first column, draw three branching arrows (up-right, right, down-right) for every step. $O(3^N)$. |
DP / BFS (Visited Grid) |
Frontier Expansion |
Iterate column by column. For each cell in column `j`, check if any of the three reachable cells in column `j-1` were "reachable" and had a smaller value. Track the furthest column reached. |
Draw a grid. Mark column 0 as "active". For column 1, mark cells that can be reached from active cells in column 0 with a strictly larger value. Move to column 2. |
$O(R \cdot C)$ Matrix Scan |
Draw a block representing R * C. Each cell is processed exactly once per column. |
Deep recursive stack |
$O(R)$ to store the current reachable "frontier" in the current column. |
$O(R)$ |
| 2685 |
Count the Number of Complete Components |
DFS/BFS to find components and then manually check every pair in the component for an edge. |
Brute Force Edge Validation |
Draw a graph. Find a component. For a component of size M, draw M² checks for edges. $O(V²)$. |
DFS + Degree Counting |
Node/Edge Symmetry Check |
During DFS/BFS for a component, count the total number of nodes `V_c` and the total number of edges `E_c`. A component is "complete" if `E_c == V_c * (V_c - 1)`. |
Draw a graph. Highlight a cluster. Count nodes (V) and lines (E). If E = fracV(V-1)2 (undirected), it's a complete component. |
$O(V + E)$ Linear Traversal |
Draw a single DFS traversal of the graph. $O(V + E)$. |
N/A |
$O(V)$ for the visited array and adjacency list. |
| 2686 |
Immediate Food Delivery III (SQL) |
Using multiple nested subqueries to calculate percentages for every single day individually. |
Correlated Subquery Scan |
Draw a table. For every row, draw a lookup into the entire table to count total vs. immediate orders. $O(N^2)$. |
Group By + CASE WHEN + ROUND |
Aggregated Ratio Calculation |
Group by `order_date`. Use `SUM(CASE WHEN order_date = customer_pref_delivery_date THEN 1 ELSE 0 END)` divided by `COUNT(*)` to get the ratio per day. |
Draw a table. Group rows by date. For each group, highlight rows where the two dates match. Divide highlighted count by total count in that group. |
$O(N \log N)$ Grouping |
Draw a grouping block $O(N)$ followed by a single aggregation pass $O(N)$. |
N/A |
Hash-map based grouping in SQL engine memory. |
| 2687 |
Bikes Last Time Used |
Join the table to itself to compare times, or pull all data into the app to sort and slice. $O(N^2)$. |
App-Side Sorting |
Draw all bike logs poured into application memory to sort by time and filter manually. |
Window Function (MAX) / GROUP BY |
The Group-and-Grab |
Simply `GROUP BY bike_id` and select the `MAX(end_time)`. If location is needed, use `ROW_NUMBER() OVER(PARTITION BY bike_id ORDER BY end_time DESC)` and filter for rank 1. |
Draw buckets for each Bike ID. Toss all ride logs into their buckets. Pull out the log with the highest timestamp from each bucket. |
Partitioned Sort $O(N \log N)$ |
Draw data flowing through a grouping node and outputting the max. |
Application-side memory. |
DB internal sort/group buffer. $O(N)$ space. |
| 2688 |
Find Active Users |
Self-join the table on `user_id` and `date`, checking if `course_id_1 != course_id_2`. $O(N^2)$. |
Quadratic Self-Join |
Draw lines connecting every row for a user to every other row for that same user. |
GROUP BY + COUNT(DISTINCT) |
The Date-User Pivot |
`GROUP BY user_id, date` and use `HAVING COUNT(DISTINCT course_id) >= 2`. This is much cleaner and faster than a self-join. |
Draw a table. Group rows into buckets by exact User + Date combination. Count the unique courses inside each bucket. Keep buckets with 2+. |
Hash Aggregation $O(N)$ |
Draw a single pass through the table building a hash map of groupings. |
Large temporary join tables. |
Hash map in DB memory. $O(N)$ space. |
| 2689 |
Extract Kth Character From The Rope Tree |
Recursively concatenate all leaf strings until the full "rope" is built, then access index K. |
Full String Concatenation |
Draw a tree of strings. Show them merging into one giant string $O(N)$. If K is small, you've wasted 99% of the work. |
Recursive Length-Based Search |
Tree-Based Index Routing |
At each internal node, check the length of the left child. If `K <= left_length`, go left. Else, `K = K - left_length` and go right. Only access the leaf that contains K. |
Draw a tree where nodes have numbers (lengths). Start at the root. If K is smaller than the left number, follow the left branch. If larger, subtract the left number and go right. |
$O(H)$ where H is tree height |
Draw a single path from root to leaf. $O(\log N)$ for a balanced tree. |
$O(N)$ for the concatenated string |
$O(H)$ for the recursive call stack. |
| 2690 |
Infinite Method Objects (JS) |
Trying to hardcode every possible method name on an object. |
Hardcoded Mapping |
Draw a box. Try to write every word in the dictionary as a property. Impossible/Infinite. |
JavaScript Proxy (`get` trap) |
Dynamic Property Interception |
Use `new Proxy({}, { get: (target, prop) => () => prop })`. The `get` trap catches any property access (method name) and returns a function that returns that name. |
Draw an object with a "Shield" (the Proxy). When a hand (code) reaches for a property that doesn't exist, the Shield "catches" the request and generates a response on the fly. |
$O(1)$ Interception |
Draw a single dot for the property access. Logic is $O(1)$. |
N/A |
Minimal Proxy object metadata in the Heap. |
| 2691 |
Immutability Helper (JS) |
Deep cloning the entire object using `JSON.parse(JSON.stringify(obj))` for every single small update. |
Massive Serialized Copy |
Draw a large tree. To change one leaf, draw the entire tree being copied into a new box. $O(N)$ per update. |
Proxy + Structural Sharing |
Path-Based Cloning (Copy-on-Write) |
Use a Proxy to intercept set operations. When a property is changed, only clone the path from the root to that property. Unchanged branches are shared between the old and new versions. |
Draw a tree. Change one leaf. Draw a new root and a new path to that leaf, but draw arrows from the new path pointing to the existing, unchanged branches of the old tree. |
$O(D)$ where D is depth |
Draw a single path from root to leaf. Only D nodes are copied. $O(D)$. |
Redundant heap duplicates |
Structural sharing memory (only updated nodes consume new space). |
| 2692 |
Make Object Immutable |
Manually checking every property modification with `if` statements, failing on nested objects or array pushes. |
Manual Property Guards |
Draw a bouncer at the door of an object checking every single read/write request manually. |
Proxy Object / Recursive Object.freeze |
The Recursive Ice Block |
Use a JS `Proxy` to intercept `set`, `defineProperty`, and `setPrototypeOf` traps, throwing an error. Or recursively use `Object.freeze()` on all keys that are objects/arrays. |
Draw an object tree. Pour liquid nitrogen over the root, watching it freeze solid down through all its branches and leaves, rejecting any attempt to bend them. |
Recursive Traversal $O(N)$ |
Draw a tree representing the object structure. A single line traces through all shared nodes. |
Creating massive deep copies. |
Call stack depth matching object nesting. $O(\text{Depth})$ space. |
| 2693 |
Call Function with Custom Context (JS) |
Manually passing the context as an argument to the function (if the function allows it). |
Argument Injection |
Draw a function call where you "sneak" the context object into the parameters. $O(1)$. |
Function.prototype.apply / Symbol Key |
Context Binding (Temporary Property) |
Attach the function to the context object using a unique `Symbol` key. Invoke the function using `context[symbol](...args)`, then delete the property. |
Draw an Object (Context). Draw a "Temporary Slot" (Symbol). Place the Function in the slot, pull the lever to run it, then remove the Function from the slot. |
$O(1)$ Execution |
Draw a single property assignment and deletion. $O(1)$. |
N/A |
Temporary property allocation in the context object. |
| 2694 |
Event Emitter (JS) |
Using a single global array for all events and scanning the whole array for every emission. |
Global Event Scan |
Draw a giant list of mixed events. To trigger "click", scan every entry to find "click" listeners. $O(N)$. |
Hash Map of Sets (Callback Registry) |
Subscription Mapping |
Use a `Map` where keys are event names and values are `Sets` (or Arrays) of callback functions. `subscribe` returns an object with an `unsubscribe` method that removes the specific callback. |
Draw a Filing Cabinet (the Map). Each drawer is labeled with an event name. Inside each drawer is a list of phone numbers (callbacks). When an event happens, call all numbers in that drawer. |
$O(1)$ lookup, $O(K)$ emit |
Draw a direct Map lookup $O(1)$ followed by a loop through K listeners. |
Zombie listeners (memory leaks) |
Map-based registry with automatic cleanup via the unsubscribe closure. |
| 2695 |
Array Wrapper (JS) |
Iteratively summing elements and building strings manually every time the wrapper is used. |
Repetitive Aggregation |
Draw an array. Every time you need its sum, loop through it. Every time you need its string, loop again. $O(N)$. |
valueOf() and toString() Overriding |
Operator Overloading (Implicit) |
Define `valueOf` to return the pre-calculated sum (allowing `+` operations) and `toString` to return the formatted string. |
Draw an array wrapped in a "Magic Box". When the box is put next to a plus sign, a number pops out. When put next to a string, a string pops out. |
$O(1)$ after pre-calculation |
Draw a single property access for the pre-calculated sum. $O(1)$. |
N/A |
Internal variables to cache the sum and the string. |
| 2696 |
Minimum String Length After Removing Substrings |
Repeatedly search for "AB" or "CD" in the string and replace them with empty strings using `String.replace()`. |
Iterative String Rescan |
Draw a string. Highlight "AB", erase it, then draw the string again. Repeat until no "AB" or "CD" remains. $O(N^2)$. |
Stack-Based Character Matching |
Single-Pass Eraser |
Iterate through the string. Push characters onto a stack. If the top of the stack and current character form "AB" or "CD", pop the stack instead of pushing. |
Draw a vertical stack. As characters arrive, check if they "cancel out" the top item. If yes, pop. If no, push. The final stack size is the answer. |
$O(N)$ Linear Scan |
Draw a single pass arrow over the string. $O(N)$. |
Creating multiple string copies |
$O(N)$ space for the stack (or a character array). |
| 2697 |
Lexicographically Smallest Palindrome |
Generate all possible palindromes of length N and pick the lexicographically smallest one. |
Exponential Palindrome Generation |
Draw a branching tree where each leaf is a potential palindrome. $O(26^(N/2)$). |
Two-Pointer Greedy Replacement |
Symmetric Comparison |
Use two pointers (left at start, right at end). Compare `s[left]` and `s[right]`. Replace the larger character with the smaller one to maintain the smallest lexicographical value. |
Draw the string. Place fingers at both ends. Move them toward the center. At each step, change the "bigger" letter to match the "smaller" letter. |
$O(N)$ Single Pass |
Draw two arrows meeting in the middle of the string. $O(N)$. |
N/A |
$O(N)$ for the character array if the string is immutable. |
| 2698 |
Find the Punishment Number of an Integer |
Calculate `i*i`, then use a nested loop to try every possible split, but without memoization or efficient recursion. |
Brute Force Partitioning |
Draw the digits of `i*i`. Branch out every possible way to slice the string. $O(N \cdot 2^D)$ where D is number of digits. |
Recursion with Backtracking |
Digit Partition Tree |
For each `i` from 1 to `n`, square it. Use a recursive function to check if any partition of the digits of `i*i` sums up to `i`. |
Write the number (e.g., 1296). Draw lines splitting it: 1|296, 12|96, 1|2|9|6, etc. If any branch sums to the target, it's a valid punishment number. |
$O(N \cdot 2^(\log10(N^2)$)) |
Draw a limited-depth recursion tree for each number up to N. |
N/A |
$O(D)$ recursive stack depth where D is digits in `i*i`. |
| 2699 |
Modify Graph Edge Weights |
Try every combination of values (1 to 2*10^9) for the "-1" weight edges. |
Impossible Infinite Search |
Draw a graph with edges labeled -1. Show them changing to every possible integer. Complexity is unbound. |
Dual-Pass Dijkstra (Target Distance Matching) |
Dijkstra Boundary Adjustment |
1. Run Dijkstra ignoring -1 edges. If shortest path < target, return impossible. 2. Run Dijkstra again, treating -1 edges as 1. If shortest path > target, return impossible. 3. Adjust -1 weights dynamically during a second Dijkstra pass to "hit" the target exactly. |
Draw the graph. Path A is fixed. Path B has "stretchy" edges (-1). Stretch the -1 edges until the total length of Path B matches the target distance exactly. |
$O(E \log V)$ Dijkstra |
Draw two sequential Dijkstra execution blocks. $O(E \log V)$. |
N/A |
$O(V+E)$ for adjacency list and distance arrays. |
| 2700 |
Differences Between Two Objects |
Flat comparison loops that fail on nested structures, requiring messy `JSON.stringify` hacks that break on unordered keys. |
Stringified Mismatch Mess |
Draw two giant JSON strings. Try to draw lines between matching properties. The lines become a chaotic web due to key ordering. |
Recursive DFS (Object Traversal) |
The Deep-Diff Tree Walker |
Recursively walk both objects simultaneously. If types differ or they are primitives, return the difference array. If they are arrays/objects, recurse into matching keys. Ignore keys not present in both. |
Draw two matching tree structures (Objects/Arrays). Trace down both simultaneously with two fingers. If a leaf node differs, circle it and write `[val1, val2]`. |
Node Traversal $O(N)$ |
Draw a tree representing the object structure. A single line traces through all shared nodes. |
Deep copies of objects via JSON parsing. |
Call stack depth matching object nesting. $O(\text{Depth})$ space. |
| 2701 |
Consecutive Transactions with Increasing Amounts (SQL) |
Self-join on dates and amounts to find all possible consecutive pairs, then group. |
Nested Loop / Cross Join Grid |
Draw a 2D grid (Rows = T1, Cols = T2). Highlight cells where T2.date = T1.date + 1 and T2.amount > T1.amount. The visual area grows as $O(N^2)$. |
Row-by-Row Memory Copy (Intermediate tables filling up Cartesian space). |
Gaps and Islands Pattern (Window Functions / Sessionization) |
Timeline Partitioning |
Plot transactions on a horizontal timeline grouped by customer. Highlight consecutive days with increasing amounts as unified blocks (islands). |
Draw rows of data. Add a column amount > prev_amount. Add a column date - row_number(). Box the rows that share the same calculated group ID. |
Data Flow Pipeline |
Draw three boxes connected by arrows: Sort $O(N \log N)$ → Window Match $O(N)$ → Aggregate $O(N)$. |
Partition Window Buffer (Draw a sliding window retaining only the current partition in memory). |
| 2702 |
Minimum Operations to Make Numbers Non-positive |
Simulate step-by-step: Find the max element, subtract X, subtract Y from everything else. Repeat until all elements ≤ 0. |
Recursion Tree / Array State Mutation |
Draw the initial array. For each step, cross out the max value, subtract X, and subtract Y from others. Write the new array below it. The depth of this stack represents time complexity. |
Array modification tracking (snapshotting the entire array state at each simulated step). |
Binary Search on Answer Space |
Number Line Partitioning (True/False boundary) |
Pick a midpoint mid. Map elements to the number of extra X operations needed. If total extra ops ≤ mid, go left; else go right. |
Draw a horizontal axis representing total operations [0, MAX_VAL]. Mark L, R, and mid. Under mid, list array elements and tally max(0, ceil((val - mid*y) / (x-y))). |
Search Space Reduction Tree |
Draw a box representing the space [L, R]. Halve the box at each downward level, writing the $O(N)$ check cost next to it. Total height is $O(\log(\text{MAX})$), width is $O(N)$. |
Variable state tracking (Draw 4 boxes for pointers: L, R, mid, extra_ops. No extra arrays needed, $O(1)$ space). |
| 2703 |
Return Length of Arguments Passed |
Iterate through the arguments object using a for loop and increment a counter. |
Linear Iterator Trace |
Draw a contiguous block representing arguments. Draw a pointer starting at index 0 moving to N, keeping a tally +1 for each move. |
Call Stack & Arguments Object frame allocation. |
Rest Operator (...args) and .length property lookup |
Pointer to Array Metadata |
Visualize args as an array object containing a metadata header. Read the .length property directly without looping. |
Draw a single box labeled args with items inside. Point an arrow labeled .length to a sub-box holding the integer size. |
Constant Time Box |
Draw a single node or state representing the .length property lookup. Write $O(1)$ inside it to show no scaling with input size. |
Array Object Header visualization (Draw the hidden class/metadata showing the length property, avoiding a full array copy). |
| 2704 |
To Be Or Not To Be (JS) |
Store val in a global/outer variable, then use verbose traditional functions with if/else statements to return boolean or throw errors. |
Closure Scope Chain Map |
Draw concentric circles representing variable scope. Place val in the outer circle, and draw arrows from the inner circles (the toBe methods) reaching out to read it. |
Heap memory allocation map (Drawing separate object allocations in memory for every closure context created). |
ES6 Arrow Functions with Object Literals and concise condition evaluation. |
Object Map / Data Flow Block |
Pass val into the factory block. Show the block emitting an object with two buttons: toBe and notToBe. Pushing a button feeds val2 into a strict equality === gate with the stored val. |
Draw a box labeled expect(val). Inside, draw an object bracket { } containing two arrows. One points to a val === val2 diamond, the other to val !== val2. |
Constant Time $O(1)$ Execution Block |
Draw a single, solid square representing the comparison step. Write $O(1)$ in the center to show it happens instantly regardless of input scaling. |
Execution Context Stack (Draw a stack: Push expect, pop it, then push toBe, pop it. Shows minimal memory footprint). |
| 2705 |
Compact Object |
Iterate over all keys. If truthy, push to a new array/object. If it's a nested object, make a full recursive copy, repeating the truthy check. |
Deep Recursive Copy Tree |
Draw a large tree where every node is duplicated onto the right side of the paper. Cross out the duplicated nodes that hold falsy values. Visually bulky. |
Call Stack & Redundant Object Allocation (Draw stacked boxes for deep recursion + identical clone structures in heap). |
Recursive Depth-First Search (DFS) with In-Place Deletion / Array Filtering |
Graph Traversal with Pruning |
Start at the root JSON node. If a branch leads to a falsy value (0, false, null), visually cut the branch. If it leads to an array/object, traverse deeper before filtering. |
Draw the JSON object as a tree graph. Draw scissors cutting the edges to leaf nodes that evaluate to falsy. |
Post-order Traversal Complexity (O(N)) |
Draw the tree structure. Write $O(1)$ next to each node, and write Σ = $O(N)$ at the bottom, indicating time scales linearly with the total number of keys/values. |
Call Stack Depth Map (Draw a stack of frames. The maximum height is exactly the deepest nested level of the JSON object: $O(D)$ Space). |
| 2706 |
Buy Two Chocolates |
Nested loop (O(N²)): Check every single pair prices[i] + prices[j] to find the combination with the lowest sum. |
Complete Graph / 2D Grid |
Draw a 2D matrix (Prices × Prices). Cross out the diagonal (can't buy same chocolate twice). Fill cells with sums. Visual area grows as $O(N²)$. |
Loop pointers footprint (Draw i and j pointers constantly jumping back and forth across an array). |
Single Pass State Tracking (O(N) Time, $O(1)$ Space) |
Linear Scan with 2-Pointer State Updates |
Slide a pointer across the array once. Maintain two buckets: min1 and min2. When you find a smaller number, shift min1 into min2, and update min1. |
Draw the array as a row of boxes. Draw two small boxes below labeled m1 and m2. Point an arrow scanning left to right, erasing and rewriting m1 and m2 as needed. |
Linear Time Sweep |
Draw a single straight horizontal line passing through N items. Label the arrow $O(N)$ to denote a single, uninterrupted pass. |
State Variable Cells (Draw exactly two small memory cells, updated in place. No extra arrays or data structures needed). |
| 2707 |
Extra Characters in a String |
Backtracking/Recursion: Try splitting the string at every possible index. If a substring is in the dictionary, branch again. Calculate the minimum extra characters across all exponential paths. |
Full Recursion Tree (Exploding) |
Draw the string. Draw branching arrows for every valid dictionary word match and every single character skip. The tree grows exponentially $O(2^N)$. |
Deep Call Stack Grid (Showing massive stack frames for $O(N)$ depth and $O(2^N)$ repeated states). |
1D Dynamic Programming (Bottom-Up) with HashSet/Trie lookup |
1D Array Forward Jumping |
Create a DP array of size N+1. Iterate through the string. At each index, either skip 1 char (dp[i+1] = dp[i]+1) or check if a dictionary word matches starting here, and "jump" forward to update that index's minimum cost. |
Draw a row of boxes (the DP array). Write the base case 0. Draw curved arrows jumping forward by word lengths. Write the calculated "extra cost" above each jump. |
Filled 1D DP Table |
Draw a single array length N. Label it $O(N^2)$ (or $O(N^3)$ depending on substring extraction cost) showing a loop inside a loop over the string length. |
Array State Map (A single 1D array of size N+1 tracking integers, plus a fast-lookup HashSet for the dictionary). |
| 2708 |
Maximum Strength of a Group |
Generate all possible subsets (2^N - 1 subsets). Multiply the elements of each non-empty subset. Keep track of the absolute maximum value. |
Binary Choice Subset Tree |
Draw nodes representing array elements. Branch left for "Include", right for "Exclude". Leaves calculate the product. Highlight the max. Width is $O(2^N)$. |
Exponential State Tracking (Visualizing memory holding all subsets simultaneously or deep recursion tree). |
Greedy Array Partitioning (Math rules) |
Bucket Sorting & Pruning |
Separate numbers into Positives, Negatives, and Zeros. Multiply all positives. Sort negatives; multiply them in pairs. If an odd number of negatives exists, discard the one closest to zero. Ignore zeros (unless all zeros/one negative). |
Draw three distinct buckets: `+`, `-`, `0`. Cross out the `0` bucket. Pair up elements in the `-` bucket with a lasso. If one is left over, cross it out. Multiply remaining. |
Linear Pipeline Filter |
Draw a single straight arrow passing through the numbers once. Label it $O(N)$ (or $O(N \log N)$ if sorting the negatives bucket). |
$O(1)$ Accumulator Registers (Draw a few single-cell variables: `max_product`, `min_product`, or just standard accumulators updating in place). |
| 2709 |
Greatest Common Divisor Traversal |
Build a graph where an edge exists if GCD(nums[i], nums[j]) > 1. Iterate all N^2 pairs to calculate GCD, then run BFS/DFS to check if the graph is fully connected. |
Dense N^2 Adjacency Matrix |
Draw nodes in a circle. Draw intersecting lines between every single pair where GCD > 1. It becomes an unreadable spiderweb (O(N^2) time). |
Massive NxN Grid Matrix (Highlighting the memory waste of storing every direct edge). |
Prime Factorization + Disjoint Set Union (Union-Find) |
Bipartite Component Merging |
Factorize each number. Instead of linking numbers to numbers, link numbers to their Prime Factors using DSU. If two numbers share a prime factor, they naturally fall into the same connected component. Check if the DSU has only 1 component left. |
Draw squares for array indices and circles for prime numbers. Draw lines connecting squares to their respective prime circles. Lasso the connected components to see if they merge into one. |
Sieve + DSU Tree Forests |
Draw a shallow, wide tree showing path compression. Label operations $O(α(N)$). Combine with prime factorization time $O(N √M)$ or $O(N \log \log M)$. |
Parallel Arrays (Draw two arrays `parent` and `size/rank` of size N + Max Prime, demonstrating minimal linear space mapping). |
| 2710 |
Remove Trailing Zeros From a String |
Iterate from the end of the string. If a character is '0', slice the string to remove it. Re-evaluate the new string repeatedly until a non-zero is found. |
Decreasing String Slices |
Draw the string. Erase the last character if it's '0'. Redraw the whole slightly shorter string below it. Repeat. |
Heap Allocation Overload (Visualize multiple intermediate string objects piling up in memory due to immutable string slicing). |
Single Pass Right-to-Left Pointer / Built-in rstrip("0") |
1D Array Boundary Marker |
Place a pointer at the rightmost edge. Move left until you hit a non-zero character. Mark that index, then take one final slice from index 0 to that mark. |
Draw the string as an array of boxes. Draw an arrow starting at the end, hopping left over the 0s. Stop at a non-zero and draw a giant bracket covering the valid prefix. |
Constant Reverse Sweep |
Draw a single straight line moving right-to-left. Label it $O(N)$ to denote checking characters at most once. |
Single Integer Pointer (Draw a single memory cell i moving backwards, plus one final memory allocation for the resulting substring). |
| 2711 |
Difference of Number of Distinct Values on Diagonals |
For every single cell (i, j), run a while loop upwards-left and another downwards-right, inserting elements into two Sets, then subtract their sizes. $O(M\cdot N\\text{cdot min}(M,N)$). |
Starburst Traversal Overlap |
Draw a grid. For one cell, draw arrows shooting top-left and bottom-right. Repeat for every cell. The lines will heavily overlap, visually demonstrating redundant work. |
Disposable HashSets (Draw hundreds of temporary Sets being created and garbage-collected for every individual cell). |
Diagonal Sweepline with Two-Pass Prefix/Suffix Sets |
Isolated Diagonal Processing |
Isolate each diagonal line. Run down the diagonal keeping a "running Set" of seen values (prefix). Then run back up keeping a running Set of the other side (suffix). Update answers in place. |
Draw a single isolated diagonal of boxes. Slide an "accumulator bucket" down the line, dropping unique values in. Slide another bucket back up. |
Parallel Independent Lines |
Draw diagonal parallel lines across the entire grid. Label the total area $O(M\cdot N)$ to show every cell is processed a constant number of times. |
Reusable HashSet State (Draw exactly two Set structures being cleared and reused per diagonal, saving massive memory overhead). |
| 2712 |
Minimum Cost to Make All Characters Equal |
Backtracking: At every differing character, branch into two universes: flip the left prefix, or flip the right suffix. Explore all 2^N states to find the minimum cost. |
Binary Decision Tree Explosion |
Draw the initial string at the root. Branch left for "Flip Prefix", right for "Flip Suffix". The tree grows exponentially wide. |
Deep Recursion Stack (Visualizing maximum stack depth $O(N)$ but an exploding number of string copies across states). |
Greedy Boundary Fixing |
Distance-to-Edge Penalty comparison |
Scan left to right. When s[i] != s[i-1], you MUST flip something to unify them. You greedily choose the cheaper flip: either flip everything to the left (cost i) or everything to the right (cost n-i). Add min(i, n-i) to total cost. |
Draw the string. Put a vertical line where characters differ. Write distance to the left edge, and distance to the right edge. Circle the smaller number and add it to your tally. |
Single Linear Pass |
Draw a single horizontal arrow across the string. Label it $O(N)$. |
$O(1)$ Accumulator Registers (Draw a single variable ans tallying the integer costs. No string modification required in memory). |
| 2713 |
Maximum Strictly Increasing Cells in a Matrix |
DFS from every cell. Search its entire row and column for strictly greater values, branching recursively. $O((M\cdot N)$!). |
N-ary Graph Expansion |
Draw a grid. Pick a cell. Draw arrows to all larger cells in its row and column. From those, draw more arrows. Looks like an uncontrollable web. |
Unbounded Call Stack (Deep recursion for every valid path permutation). |
Value Sorting + 1D Array Dynamic Programming |
Value-Based Layer DP |
Group cells by value and sort ascending. To calculate the longest path ending at value X at (i,j), look at the best previous results recorded in rowMax[i] and colMax[j]. Update answers simultaneously for identical values. |
Draw two 1D arrays outside the grid (one for rows, one for cols). Process values in order. Draw an arrow pulling the max from the row/col arrays, calculating +1, and pushing the new max back. |
Map-Reduce Pipeline |
Draw a funnel showing the sort step $O(\text{MN} \\text{log MN})$, feeding into a single iteration block $O(M\cdot N)$ processing the DP states. |
Orthogonal DP Arrays (Draw one array of size M and one of size N. This compresses the $O(M\cdot N)$ graph space into $O(M+N)$ tracking space). |
| 2714 |
Find Shortest Path with K Hops |
DFS to find all paths from source to destination. For every edge, branch into "take normally (cost W)" or "hop (cost 0)". Exponential time $O(2^E)$. |
Combinatorial Edge Branching |
Draw a path. For every line connecting nodes, split it into two parallel lines: one solid (normal cost), one dashed (0 cost hop). |
Brute Force Path Memory (Storing every conceivable route configuration simultaneously). |
Dijkstra's Algorithm on 2D State Space (Node, Hops Used) |
Multi-layered Graph Traversal |
Treat the graph as having K+1 parallel "floors". Taking a normal edge keeps you on the same floor. Taking a hop edge drops you down to the next floor with 0 cost. Run standard Dijkstra to find the shortest path to the destination on any floor. |
Draw 3 stacked planes of nodes (for K=2). Draw vertical dashed lines representing "hops" falling from node U on layer 0 to node V on layer 1. |
Priority Queue Expansion Sphere |
Draw the Dijkstra expansion radius. Note the complexity as $O((V+E)$ log V) * K, showing the base algorithm scaled by the state dimension. |
2D Distance Matrix & Min-Heap (Visualize a grid dist[V][K+1] alongside a priority queue ordering active states). |
| 2715 |
Timeout Cancellation (JS) |
Let the `setTimeout` run its full course, but use a boolean flag like `isCancelled` inside the callback to prevent the actual execution of the target function. |
Timeline with Wasted Execution Block |
Draw a timeline arrow. Mark the target execution time. If cancelled, put an "X" over the function, but show the timer arrow still traveling all the way to the end unnecessarily. |
Floating Closure Memory (The callback and its lexical environment stay in memory until the timer naturally finishes). |
clearTimeout Interception |
Timer Abort Timeline |
Start the timer and capture its ID. Return a cancel function. If the cancel function is invoked before the delay, immediately pass the ID to clearTimeout, destroying the timer instantly. |
Draw a horizontal timeline arrow. At the timestamp where `cancelFn` is called, draw a literal brick wall blocking the arrow from reaching the target time. |
$O(1)$ Execution Block |
Draw a single, solid square representing the `clearTimeout` call. Write $O(1)$ in the center. |
Reclaimed Timer ID (Visualize the timer ID integer being passed to the JS engine to garbage collect the pending callback). |
| 2716 |
Minimize String Length |
Simulate the operations: find duplicates `c` at indices `i < j`, delete one, shift the rest of the string over to fill the gap. Repeat until no duplicates exist. $O(N^2)$. |
Repeated Array Shifting |
Draw the string in boxes. Find two 'a's. Cross one out. Redraw the entire slightly shorter string below it. Visual area represents $O(N^2)$ shifting work. |
Massive String Reallocations (Immutable strings mean creating a brand new string in memory for every deletion). |
HashSet Unique Character Extraction |
Set Insertion Filter |
Realize the problem effectively just asks for the number of unique characters in the string, since any duplicates can be targeted and destroyed. Dump characters into a Set and return its size. |
Draw the string as a block. Draw an arrow pointing into a circle labeled "Set". Inside the set, write only the unique letters. |
Linear Set Insertion |
Draw a single straight line passing through N characters. Label it $O(N)$ time. |
Fixed Size HashSet (Draw an array of exactly 26 buckets. Space complexity is $O(1)$ since the alphabet size is constant). |
| 2717 |
Semi-Ordered Permutation |
Simulate exactly: Find 1, swap it left iteratively. Then find N, swap it right iteratively. Physically modify the array with each step. |
Step-by-Step Swap Trace |
Draw the array. Swap 1 to the left, redraw. Swap again, redraw. Do the same for N. Shows redundant $O(N)$ modifications. |
In-place array mutations (Unnecessary write operations to memory). |
Index Distance Math (O(N) Time, $O(1)$ Space) |
Pointer Distance with Crossing Overlap |
Find index of 1 (`idx1`) and N (`idxN`). Steps for 1 = `idx1`. Steps for N = `Length - 1 - idxN`. Total = `idx1 + steps_for_N`. If 1 started to the right of N (`idx1 > idxN`), they cross paths during swapping, saving 1 step, so subtract 1. |
Draw the array. Mark 1 and N. Draw a left arrow from 1 (write distance). Draw a right arrow from N (write distance). If the arrows overlap, write "-1" above the intersection. |
Single Array Scan |
Draw one horizontal arrow scanning the array to find the two indices. Label it $O(N)$. |
$O(1)$ Integer Pointers (Draw exactly two variables, `idx1` and `idxN`, holding integers). |
| 2718 |
Sum of Matrix After Queries |
Allocate an N×N matrix. Iterate through all queries in order, looping $O(N)$ times to overwrite rows/cols. Sum the final matrix. $O(Q\cdot N + N^2)$. |
Overwriting 2D Grid |
Draw a grid. Shade a row. Shade a column over it (overwriting). Shade another row. Highly redundant work. |
$O(N^2)$ 2D Array Allocation (Massive memory waste for large N). |
Reverse Query Processing with Seen Sets |
Reverse Timeline Shadowing |
Process queries from last to first. The last query applied to a row/col is the one that survives. Maintain a count of available rows/cols. If processing a new row, add `val * available_cols` to total, and mark row as seen. Decrement available rows. |
Draw the queries array and a backwards arrow. Draw two buckets: `seen_rows`, `seen_cols`. If a row is NOT in `seen_rows`, add it, and tally its score based on remaining available columns. |
$O(Q)$ Backwards Scan |
Draw an arrow going right-to-left through the queries array. Write $O(Q)$. |
Two Boolean Arrays/Sets (Draw two 1D arrays of size N for rows and columns. Reduces space from $O(N^2)$ to $O(N)$). |
| 2719 |
Count of Integers |
Iterate from `num1` to `num2`. Convert each number to a string, sum its characters, and check if it falls between `min_sum` and `max_sum`. TLEs massively on 10^22. |
Massive Number Line Scanning |
Draw a giant number line. Draw a magnifying glass iterating over every single tick mark. Label it $O(N)$ where N is the massive numeric difference. |
Trillions of temporary string allocations for digit extraction. |
Digit DP + Memoization `solve(num2) - solve(num1 - 1)` |
Digit DP State Tree with Tight Bounds |
Build the number digit by digit (0-9). Track `current_sum`. If `is_tight` is true, the loop stops at the digit of the upper bound number. If `current_sum > max_sum`, prune the branch immediately. Cache states `(index, current_sum, is_tight)`. |
Draw a tree branching 0-9. Snip branches where sum exceeds limits. Highlight the "tight" path along the rightmost edge mirroring the target number's actual digits. |
3D State Space Grid |
Draw a 3D box labeled Length (23) × MaxSum (400) × Tight (2). Write $O(L \cdot S)$ to show bounded constant time. |
3D Memoization Array (Draw a compact 3D array table to store integer counts, avoiding recalculation). |
| 2720 |
Popularity Percentage |
Two separate massive queries counting user1 and user2 occurrences, followed by a slow full outer join and manual math. |
Disjointed Tally Tables |
Draw two separate tables. Count friends on the left. Count friends on the right. Try to manually merge the lists. |
UNION CTE + Window/Aggregate |
The Undirected Graph Flattener |
Friendships are bidirectional. Create a CTE that `UNION`s `(user1, user2)` and `(user2, user1)`. This creates a flat list of ALL friends for every user. Then group by user, count distinct friends, and divide by the total distinct users in the network. |
Draw a directed graph. Flip it so arrows go both ways. List every user and simply count the arrows touching them. Divide by total nodes. |
Linear Scan & Group $O(N)$ |
Draw a single pipeline: UNION rightarrow Hash Aggregate rightarrow Math calculation. |
Massive temporary tables for outer joins. |
SQL internal hash map for distinct counts. $O(U)$ space. |
| 2721 |
Execute Asynchronous Functions in Parallel (JS) |
Execute each function one after another in a for...of loop with await, pushing results to an array. This is sequential, not parallel. |
Sequential Timeline |
Draw a timeline. Draw "Task 1", then "Task 2" starting only after Task 1 finishes. Total length is the sum of all task times. |
Blocking Execution Context (One task occupies the stack while others wait in the queue). |
Promise.all Manual Implementation (Counter Pattern) |
Parallel Racing Gates |
Start all functions immediately. Maintain a resolvedCount and a results array. Each time a promise resolves, place the result at its specific index and increment the count. If count equals the total, resolve the main promise. |
Draw a vertical starting line with N arrows firing simultaneously. Draw a "Finish Line" bucket. When an arrow hits, increment a tally mark. When tally = N, the bucket is full. |
$O(N)$ Event Loop Management |
Draw a fan-out shape from one point to N points, then a fan-in shape back to one resolution point. |
Resolution Buffer (Draw a fixed-size array in the heap being filled non-sequentially as promises finish). |
| 2722 |
Join Two Arrays by ID |
Nested loop (O(N*M)): For every object in `arr1`, iterate through `arr2` to find a matching ID. If found, merge; otherwise, add to result. |
N x M Matching Grid |
Draw `arr1` on the left and `arr2` on the right. Draw lines from every element in 1 to every element in 2 looking for a match. |
Temporary Object Accumulation (Creating massive amounts of intermediate merged objects). |
HashMap Merging (O(N+M) Time) |
Key-Value Aggregator |
Create a single Map. Iterate through `arr1` and put every object into the Map using `id` as the key. Iterate through `arr2`; if an ID exists, merge properties into the existing object. Sort keys at the end. |
Draw a "Registry" (the Map). Drop items from list 1 into it. Drop items from list 2 in; if a box is already occupied, merge the contents inside that box. |
Linear Hash Map + Sort |
Draw two sequential arrows (one for each array) followed by a sort block. Total: $O(N+M + K \log K)$. |
Dictionary Heap Space (Draw a Map structure showing unique IDs pointing to merged object values). |
| 2723 |
Add Two Promises |
Await `promise1`, store it. Then await `promise2`, store it. Add them. (Unnecessarily slow if both could have been resolving at the same time). |
Step-wise Resolution |
Draw a "Waiting" block for P1. Once it ends, draw a "Waiting" block for P2. |
Serialized Memory Wait (The closure for the addition waits twice). |
Destructured Promise.all |
Concurrent Value Fetching |
Trigger Promise.all([promise1, promise2]). This allows both to resolve in parallel. Destructure the resulting array [val1, val2] and return the sum. |
Draw two parallel pipes leading into a single addition (+) operator. Both pipes flow at the same time. |
$O(1)$ Concurrent Logic |
Draw two dots resolving simultaneously. Write $O(1)$ as the logic is independent of input size (fixed at 2). |
Microtask Queue Visualization (Draw two microtasks entering the queue simultaneously). |
| 2724 |
Sort By |
Implement a manual Bubble Sort or Selection Sort, calling the fn selector for every comparison (O(N^2 * cost_of_fn)). |
Nested Comparison Matrix |
Draw the array. Compare adjacent elements by calling `fn` on both. Swap. Repeat. The number of swaps/calls is $O(N^2)$. |
Repeated Function Execution Stack (Multiple redundant calls to the selector function). |
Native .sort() with Custom Comparator |
Optimized Sort Algorithm (Timsort) |
Pass a comparator to the native sort: (a, b) => fn(a) - fn(b). The engine uses $O(N \log N)$ comparisons, minimizing the calls to the selector function. |
Draw the array being split into small sorted chunks and merged back together. At each comparison point, show a small "transformer" block (the `fn`) converting the values before they are compared. |
$O(N \log N)$ Complexity Tree |
Draw a binary tree of height log N. At each level, work done is $O(N)$. |
Temporary Sort Buffer (Visualize the $O(N)$ space often used by stable sort algorithms like Timsort in modern engines). |
| 2725 |
Interval Cancellation (JS) |
Use a recursive setTimeout where the next call is scheduled only after the previous one finishes. This can lead to "drift" where the interval time isn't consistent. |
Staggered/Drifting Timeline |
Draw a timeline. Mark "Task 1", then a delay, then "Task 2". Show how the total time between start points is delay + execution_time instead of just delay. |
Accumulating Closure Scopes (Each timeout creates a new closure, potentially keeping old variables in memory longer). |
setInterval with Immediate Invocation |
Fixed Frequency Pulse |
Call the function immediately. Then, start a setInterval. Return a function that calls clearInterval. This ensures the first run happens at t=0 and subsequent runs follow a strict heartbeat. |
Draw a timeline with dots at perfect intervals (0, 100, 200ms). Draw a "Stop" button that, when pressed, removes all future dots. |
$O(1)$ Scheduling |
Draw a single box representing the JS Timer API. Write $O(1)$ as the registration cost is independent of the number of ticks. |
Timer Registry Slot (Visualize a single slot in the browser's timer table being occupied and then freed). |
| 2726 |
Calculator with Method Chaining |
Create a class where every method performs an operation and stores the result, but doesn't return this, forcing the user to call calc.add(5); calc.sub(2); on separate lines. |
Disconnected Command Sequence |
Draw a box (the object). Draw separate arrows for each operation, each returning to the start before the next can begin. |
Multiple Statement Contexts (Each call is a separate statement in the execution stack). |
Fluent Interface (Method Chaining) |
Pipeline Flow |
In every method (add, subtract, etc.), perform the math and then return this;. This allows the output of one method to be the context for the next. |
Draw a horizontal pipeline. Elements enter "Add", flow directly into "Subtract", then into "Multiply", without ever leaving the object's context. |
$O(1)$ Per Operation |
Draw a chain of circles. Each circle is $O(1)$. The total time is $O(\text{number of operations})$. |
Persistent Object State (Draw one "Result" variable in the object's heap space that is updated in place during the chain). |
| 2727 |
Is Object Empty |
Use Object.keys(obj).length === 0. This is $O(N)$ because it must iterate through and create an array of all keys before checking the length. |
Full Key Extraction Scan |
Draw an object with 1,000 keys. Watch as Object.keys painstakingly writes every key into a brand-new array just to see if it's empty. |
Intermediate Array Allocation (Visualize a potentially massive array of strings being created in memory just for a boolean check). |
for...in Loop Short-circuit |
Early Exit Sentinel |
Start a for...in loop. If the loop executes even once, return false immediately. If the loop finishes without executing, return true. |
Draw a door. Peek inside. If you see even one item, close the door and say "Not Empty". You don't need to count the rest. |
$O(1)$ Average Time |
Draw a single dot for the first property check. Label it $O(1)$. |
Zero Allocation Logic (Draw the execution pointer entering the object and immediately exiting; no new memory structures created). |
| 2728 |
Count Houses in a Circular Street |
Walk in one direction counting houses. Without a "stopping" condition, you will loop infinitely. |
Infinite Loop Spiral |
Draw a circle. Draw a person walking around it, passing the same house over and over while the counter keeps going up. |
Unbounded Integer Accumulator (Memory usage of the counter variable growing as it fails to terminate). |
State Marking (Two-Pass Reset) |
Reset and Count Cycle |
Loop 1000 times (max possible n) and close all doors. Then open the door at the current house. Walk and count until you hit an open door. |
Draw a circle of houses. Draw a hand closing every door in one lap. Open one door. Walk until you find that "Flag" door again. |
Linear $O(k)$ Sweep |
Draw two circles representing the two laps. Label it $O(k)$ where k is the maximum possible houses. |
$O(1)$ Auxiliary Space (Draw one integer count and one iterator i). |
| 2729 |
Check if The Number is Fascinating |
Calculate 2n and 3n. Convert all to strings. Use a nested loop to check if each digit 1-9 appears exactly once. |
String Manipulation and Nested Search |
Draw n, 2n, and 3n. For each number 1, 2, 3... search through the combined string. $O(D^2)$ where D is number of digits. |
Temporary String Buffers (Visualizing multiple string concatenations and copies). |
Frequency Array / Boolean Bucket (O(1) Time/Space) |
Digit Bucket Sort |
Concatenate n, 2n, and 3n into one string. If length isn't 9, return false. Use a boolean array of size 10 to mark seen digits. If a digit is '0' or seen twice, return false. |
Draw 9 empty buckets labeled 1-9. Take the digits from the concatenated string and drop them into the buckets. If a bucket is already full or a digit is 0, the check fails. |
Constant Time $O(1)$ |
Draw a single box. Since n is limited to 3 digits, the total digits are always <= 10. Write $O(1)$. |
Fixed size 10-bit Mask (Visualize a single integer being used as a bitmask to track seen digits). |
| 2730 |
Find the Longest Semi-Repetitive Substring |
Generate all possible substrings $O(N²)$. For each substring, count adjacent equal characters. If count ≤ 1, update max length. Total $O(N³)$. |
N³ Substring Enumeration |
Draw a string. Use two brackets to mark a substring. Count duplicates inside. Shift brackets, repeat. Visual area is a massive pyramid of checks. |
String Slice Memory (Draw many temporary substring copies being created in the heap). |
Sliding Window (Two Pointers) |
Flexible Elastic Window |
Expand `right` pointer. If `s[right] == s[right-1]`, increment a `duplicates` counter. While `duplicates > 1`, move `left` pointer forward; if `s[left] == s[left+1]`, decrement `duplicates`. Track max `right - left + 1`. |
Draw the string. Draw a "window" box. When a duplicate enters, the box turns red. Slide the left edge until the box turns green again. |
Linear $O(N)$ Sweep |
Draw a single horizontal line with two pointers (L, R) moving only right. Label it $O(N)$. |
$O(1)$ Window Variables (Draw exactly four variables: `left`, `right`, `duplicates`, `max_len`). |
| 2731 |
Movement of Robots |
Simulate second by second. When two robots share a position, swap their directions. $O(T \cdot N)$. For large T, this is impossible. |
Step-by-Step Collision Trace |
Draw robots on a line. Move them 1 unit. If they touch, draw arrows reversing. Repeat T times. Very cluttered. |
Temporal State Snapshots (Visualizing the position of every robot at every tick of time). |
Collision Transparency + Prefix Sums |
Independent Particle Flow |
Key Insight: Robots "passing through" each other is mathematically identical to bouncing. Calculate final positions: `pos + (dir * d)`. Sort them. Use Prefix Sums to calculate all-pairs distances in $O(N)$. |
Draw two robots moving toward each other. Instead of bouncing, draw them ghosting through. Mark final spots. Draw a "Sum of Distances" formula triangle. |
Sorting $O(N \log N)$ + Linear Sum |
Draw a sorting block followed by a single linear pass. Label the bottleneck as $O(N \log N)$. |
Sorted Position Array (Draw a 1D array of long integers representing the final coordinates). |
| 2732 |
Find a Good Subset of Matrix |
Check every subset of rows. For a subset of size k, check if the sum of each column is <= k/2. Exponential $O(2^\text{Rows} \\text{cdot Cols})$. |
Subset Power Set Tree |
Draw a tree where each row is either "In" or "Out". With 10^4 rows, the tree is too large to draw. |
Combinatorial Row Storage (Visualizing all row combinations in memory). |
Bitmask Compression + Pigeonhole Principle |
Bitwise Intersection Grid |
Each row has only <= 5 columns. Convert each row to a bitmask (2^5 = 32 possible masks). If any row is 0, return it. Otherwise, check all pairs of existing masks. If `(maskA & maskB) == 0`, those two rows form a good subset. |
Draw a small 32-entry table. Map 10,000 rows into these 32 buckets. Compare only the buckets. It’s like sorting colors into 32 jars. |
$O(\text{Rows} + 2^(2\\text{cdot Cols})$) |
Draw a funnel: 10,000 rows → 32 masks → Constant time pair check (32 x 32). Write $O(N)$. |
Static Mask Map (Draw an array of size 32 storing the original row index for each bitmask). |
| 2733 |
Neither Minimum nor Maximum |
Sort the entire array. Return the second element. $O(N \log N)$. |
Full Array Reordering |
Draw the whole array. Sort it. Cross out the first and last. The work is overkill for just one middle value. |
Sort Buffer (Visualize the $O(N)$ or $O(\log N)$ extra space used by sorting). |
Constant Sample Selection |
Fixed Window Filter |
If array length < 3, return -1. Otherwise, just take the first three elements. Sort only those three (constant time). Return the one that isn't the min or max. |
Draw a giant array. Circle the first three boxes. Ignore the rest. Pick the "middle" value of those three. |
Constant Time $O(1)$ |
Draw a single tiny box. Label it $O(1)$ because we only ever look at 3 elements regardless of array size. |
Register Memory (Draw exactly 3 memory cells used for the comparison). |
| 2734 |
Lexicographically Smallest String After Substring Operation |
Try every possible substring. For each, decrement all characters (a → z). Compare all results to find the lexicographically smallest. $O(N³)$. |
$O(N³)$ Comparison Matrix |
Draw a string. List every substring below it. Change the letters in each. Compare them all like a dictionary. |
Exponential String Allocation (Visualize the heap filling with modified versions of the string). |
Greedy Leading "a" Avoidance |
First-Non-'a' Segment Flip |
Find the first character that is NOT 'a'. Start the operation there. Continue the operation until you hit the next 'a' or the end of the string. If the string is all 'a's, flip only the very last 'a' to 'z'. |
Draw a string. Draw a "Flip Zone" box that starts at the first non-'a' and stops at the next 'a'. Draw arrows showing letters moving one step back (b → a). |
Single Pass $O(N)$ |
Draw a single arrow moving left to right. It stops or passes over 'a's. Label it $O(N)$. |
In-place Character Array (Draw the string being converted to an array, modified, and joined. Space $O(N)$). |
| 2735 |
Collecting Chocolates |
Simulate every possible number of rotations (0 to N-1). For each rotation count, calculate the total cost by iterating over all chocolates. $O(N³)$. |
Triple Nested Loop Grid |
Draw a 3D cube of operations. For each "rotation" layer, draw a 2D scan of the array. Very dense and slow. |
Redundant Array Rotation Buffers (Storing the state of the array for every single shift). |
Rotation-Minimizing DP (O(N²) Time) |
Row-wise Minimum Tracking |
Iterate k from 0 to N-1 (rotations). Maintain an array min_costs where min_costs[i] is the minimum price found for chocolate i across all rotations so far. Sum min_costs at each k and add the shifting cost k * x. |
Draw a grid where rows are rotations. For each column, highlight the smallest value seen from the top down to the current row. Tally the sum of highlighted values. |
$O(N²)$ Area Sweep |
Draw a 2D square (N x N). Label it $O(N²)$ to show we visit each rotation/chocolate pair exactly once. |
1D Running Minimum Array (Draw a single array of size N that is updated in-place at each rotation step). |
| 2736 |
Maximum Sum Queries |
For every query [x, y], iterate through all pairs (nums1[i], nums2[i]). Check if nums1[i] ≥ x and nums2[i] ≥ y. Track the max sum. $O(Q \cdot N)$. |
Linear Search over Pairs |
Draw queries as dots and pairs as stars on a 2D plane. For each dot, draw a giant "L" shape and count all stars inside it. Repeat for every dot. |
Query/Pair Stack (Drawing the search range for every individual query). |
Sorting + Monotonic Stack + Binary Search / Segment Tree |
Offline Query Processing (Coordinate Compression) |
Sort pairs by nums1 descending and queries by x descending. As you process a query, add all pairs that now satisfy nums1 ≥ x to a monotonic stack (tracking nums2 and sum). Binary search the stack for the best y. |
Draw a "Processing Line" moving left. As it passes pairs, they drop into a "Bucket" (the stack). For each query, peak into the bucket to find the highest value. |
$O((N+Q)$ log N) Sort & Search |
Draw a sorting block followed by a search tree. Label the bottleneck as $O((N+Q)$ log N). |
Monotonic Stack / Segment Tree Structure (Draw a stack where elements are pruned if they are smaller in both Y and Sum). |
| 2737 |
Find the Closest Marked Node |
Run Dijkstra's algorithm from the source node to find distances to all other nodes. Then, iterate through the list of marked nodes and pick the minimum distance. |
Single-Source Shortest Path (SSSP) Trace |
Draw the graph. Shade it in waves starting from the source until all marked nodes are reached. |
Distance Array + Priority Queue (Drawing the standard Dijkstra memory footprint). |
Reverse Multi-Source Dijkstra (or Simple Dijkstra) |
Shortest Path Tree Pruning |
Since we only need the closest marked node, standard Dijkstra from the source is already quite efficient. To optimize for multiple starts, one could run a single Dijkstra starting with all marked nodes in the PQ (if the edges were reversed). |
Draw the source node. Draw expanding circles of distance. Stop the moment a marked node is "touched" by an expanding circle. |
$O(E \log V)$ |
Draw the Dijkstra complexity: $O((E+V)$ log V) using a Min-Heap. |
Priority Queue & Dist Map (Visualize the heap-sorting nodes by their current shortest distance from the source). |
| 2738 |
Count Occurrences in Text (SQL) |
Use a LIKE or REGEXP join for every word in a provided list against the entire text column. $O(\text{Words} \\text{cdot Rows})$. |
Cross-Join String Matching |
Draw a table of words and a table of text. Draw lines from every word to every row, checking for a match. Visual area is W * R. |
Buffer Scan (Visualizing the database engine reading the text column repeatedly for each word). |
String Concatenation + Pattern Aggregation |
Unionized Pattern Scanning |
Use a CASE statement or UNION ALL to check for " bull " and " bear " within spaces to avoid partial matches. Group by the word name and sum the counts. |
Draw a funnel. Text goes in; two counters ("Bull", "Bear") increment as the text flows through filters. |
$O(N)$ Text Scan |
Draw a single horizontal line through the data. Label it $O(N)$ to indicate a single pass per word type. |
Aggregation Hash Table (Draw two small memory slots for the counts of the two specific words). |
| 2739 |
Total Distance Traveled |
Use a while loop to decrement the main tank. Every time the "liters used" reaches 5, check the additional tank and move 1 liter if available. $O(\text{MainTank})$. |
Simulation Step Trace |
Draw two tanks with fuel units. Cross out 5 from tank A, move 1 from tank B to A. Repeat until tank A is empty. |
Integer State Mutation (Visualizing the variables main and additional changing over time). |
Mathematical Simulation (Math-Based) |
Cycle-Based Calculation |
Total distance is (mainTank + min((mainTank - 1) / 4, additionalTank)) * 10. This formula accounts for the "bonus" liters earned every 5 liters used. |
Draw a timeline of 5km blocks. For every 5 blocks, draw a tiny "+1" liter icon appearing above the line, up to the limit of the second tank. |
Constant Time $O(1)$ |
Draw a single calculation box. Write $O(1)$ because no loops are required. |
Zero Extra Space (Draw a single ans variable). |
| 2740 |
Find the Value of the Partition |
Generate all possible partitions of the array into two non-empty sets. For each, find max(nums1) and min(nums2), then find the absolute difference. $O(2^N)$. |
Subsets Comparison Tree |
Draw a tree where each element is branched into "Set A" or "Set B". With 10^5 elements, the tree is infinitely wide. |
Partition Memory Sets (Visualizing two massive separate heaps for every single partition attempt). |
Sorting + Consecutive Difference (O(N log N)) |
Sorted Array Gap Analysis |
Sort the array. The minimum difference between any max(nums1) and min(nums2) must occur between two adjacent elements in the sorted version. Iterate once and find min(nums[i] - nums[i-1]). |
Draw the array as a sorted line of boxes. Draw small vertical "ruler" marks between every adjacent pair. The smallest ruler mark is your answer. |
Sort Bottleneck $O(N \log N)$ |
Draw a standard sorting block (O(N log N)) followed by a single horizontal scan line (O(N)). |
$O(1)$ Auxiliary Space (Draw the array in-place; no extra data structures besides a single min_diff variable). |
| 2741 |
Special Permutations |
Generate all N! permutations. For each, check if nums[i] % nums[i+1] == 0 or nums[i+1] % nums[i] == 0 for all i. $O(N! \cdot N)$. |
Factorial Permutation Tree |
Draw a tree where each level has N-1, N-2 branches. Even for N=14, this results in over 87 billion leaf nodes. |
Stack Frame Explosion (Visualizing a call stack N-levels deep repeated billions of times). |
Bitmask Dynamic Programming (O(N^2 * 2^N)) |
State Space Compression |
Use a DP state dp(mask, last_index). mask tracks used elements; last_index ensures the next element is "special" relative to the previous. Sum up recursive results with memoization. |
Draw a grid where rows are 0 to 2^N (binary numbers) and columns are array indices. Draw arrows from mask to mask | (1 << next) if the special condition is met. |
Exponential Bound $O(2^N)$ |
Draw a 2D table of size N x 2^N. Label it $O(N^2 2^N)$ to show it scales with the bitmask. |
Memoization Table (Draw a 2D array in memory where each cell stores a previously computed count of permutations). |
| 2742 |
Painting the Walls |
Recursion: For each wall, choose either the paid painter or the free painter. Explore all 2^N combinations to find the minimum cost. |
Binary Choice Tree |
Draw a wall. Branch "Paid" (high cost, saves time) vs "Free" (0 cost, takes time). The tree grows exponentially $O(2^N)$. |
Redundant Decision Paths (Visualizing same wall counts being re-calculated in different branches). |
0/1 Knapsack style DP (O(N^2) Time) |
Resource Exchange DP |
Key insight: Buying time[i] + 1 walls of time allows the free painter to paint the rest. State: dp[rem_walls] is min cost to paint rem_walls. Update dp[j] = min(dp[j], dp[j - time[i] - 1] + cost[i]). |
Draw a DP array of size N. For each wall, slide from right to left, updating the "min cost" to reach that many walls. |
$O(N^2)$ Nested Loop |
Draw a grid N x N. Label it $O(N^2)$ to show each wall is considered against all possible remaining wall counts. |
1D DP Array (Draw a single row of memory that evolves with each "Paid" wall option). |
| 2743 |
Count Substrings Without Repeating Character |
Extract every possible substring $O(N^2)$. For each, check for duplicates using a Set $O(N)$. Total $O(N^3)$. |
Nested Sliding Slices |
Draw the string. Highlight every possible contiguous segment and check them one by one. |
Heap Fragment Memory (Visualizing thousands of temporary string objects created during slicing). |
Sliding Window (Shrinkable) |
Continuous Range Counter |
Move right pointer. If s[right] is already in the window, move left until it's removed. For every right, the number of valid substrings ending there is right - left + 1. Sum these. |
Draw a string. Use a "Lasso" that grows to the right. If it catches a duplicate, the back of the lasso pulls forward. Write the current length under the right pointer at each step. |
Linear Amortized $O(N)$ |
Draw a single horizontal arrow. Note that left and right only ever move forward. $O(N)$. |
Frequency Hash/Array (Draw an array of 26 integers tracking the current count of characters in the window). |
| 2744 |
Find Maximum Number of String Pairs |
Double loop $O(N^2)$: For each string words[i], look at all words[j] to see if words[i] == reverse(words[j]). |
N x N Comparison Grid |
Draw strings in a column and the same strings reversed in a row. Mark the intersections that match. |
Temporary Reversed String Buffers (Creating a reversed copy for every comparison). |
HashMap / Frequency Counting |
Symmetric Complement Search |
Iterate through words. For each word, check if its reverse is already in a seen Set. If yes, increment count and remove from Set. Else, add the word to the Set. |
Draw a "Mirror" (the Set). As words walk past, they look into the mirror to see if their "reverse self" is already inside. |
Linear Pass $O(N \cdot L)$ |
Draw a single arrow passing through N words. Label it $O(N)$ (assuming constant word length). |
Unique String Set (Draw a hash set in the heap storing current unmatched strings). |
| 2745 |
Construct the Longest New String |
Recursive Backtracking: Try appending "AA", "BB", or "AB" at each step while respecting the "no AAA/BBB" constraints. Explore all valid paths. $O(3^N)$. |
Branching Decision Tree |
Draw a tree where each node branches into three possibilities. Cross out branches that violate constraints. Depth is the total number of blocks. |
Recursive Call Stack (Visualizing depth-first search for the longest possible valid string path). |
Greedy Mathematical Observation |
Pattern Balancing Tally |
Observe that "AB" can always be placed next to itself. "AA" and "BB" must alternate. The longest sequence of "AA" and "BB" is 2 * min(x, y) + (x != y ? 1 : 0). Add all z ("AB") blocks. Multiply total blocks by 2. |
Draw three piles of blocks (x, y, z). Pair up one 'x' with one 'y' repeatedly. If one is left over, add it. Then stack all 'z's on top. Count the height. |
Constant Time $O(1)$ |
Draw a single formula box. Write $O(1)$ because it uses a direct math calculation. |
Zero Extra Space (Draw a single integer result variable). |
| 2746 |
Decremental String Concatenation |
Recursion: For each new word, try appending it to the front OR the back of the current joined string. Calculate the final length for all 2^N paths. |
Exponential String Growth Tree |
Draw a tree where each level doubles. Each node represents a fully concatenated string. With N=1000, this is 2^1000 strings. |
Massive String Heap (Visualizing huge strings being copied and stored at every level of recursion). |
Dynamic Programming (State: first_char, last_char, index) |
Boundary-Only DP Table |
Key insight: Only the first and last characters of the current string matter for future merges. State: dp[i][first][last] is the min length using words up to i with specific start/end chars. Transition by checking if word's edge matches string's edge. |
Draw a 3D grid: 1000 (Index) x 26 (First Char) x 26 (Last Char). Fill the grid level by level using the previous level's results. |
$O(N \cdot 26 \cdot 26)$ Linear Bound |
Draw a rectangle representing N x 676. Label it $O(N)$ since 676 is a constant overhead. |
Compact DP Array (Draw a 2D array 26x26 that is overwritten for each new word to save space). |
| 2747 |
Count Zero Request Servers |
For every query time, iterate through the entire logs array. Check if time - queries[i] <= log_time <= queries[i]. Count unique servers. $O(Q \cdot L)$. |
Query-by-Log Comparison Matrix |
Draw a timeline of logs. For each query, draw a "window" box on the timeline and manually count the distinct server IDs inside it. |
Linear Search Pointers (Drawing the search range for every individual query). |
Sliding Window + Sorting (Offline Queries) |
Moving Timeline Window |
Sort logs by time and queries by time. Use two pointers (left and right) to maintain a window of logs within [queries[i]-x, queries[i]]. Use a frequency map to track the number of active servers in the window. |
Draw a timeline. Slide a fixed-width "Window" to the right. As it passes log entries, they "enter" the frequency map. As it leaves them, they "exit". |
$O((L + Q)$ log (L + Q)) Sorting Bottleneck |
Draw a sort block followed by a single sweep line. Label the sweep $O(L + Q)$. |
Frequency Map & Active Count (Visualize a hash map tracking server IDs and a single integer activeServers). |
| 2748 |
Number of Beautiful Pairs |
Nested loop $O(N²)$: For every pair (i, j), get the first digit of nums[i] and the last digit of nums[j]. Calculate GCD. If 1, increment count. |
Full N x N Pairwise Matrix |
Draw a grid. Fill cells with the GCD of the first digit of the row and the last digit of the column. Count the '1's. |
Repeated Digit Extraction (Drawing the logic to pull digits from numbers inside the nested loops). |
Frequency Array + GCD Pre-calculation |
Digit Frequency Bucket Sweep |
Iterate through nums. For the current nums[j], its last digit can pair with the first digits of all nums[i] seen so far. Use a frequency array of size 10 to store counts of "first digits" seen. Check GCD(1..9, last_digit) against the frequency array. |
Draw 10 buckets for first digits (0-9). As you walk the array, check the current number's last digit against all buckets, then put its first digit in its bucket. |
$O(N \cdot 10)$ Linear Pass |
Draw a single horizontal arrow. Note that the inner loop is constant (size 10). Write $O(N)$. |
Fixed-size Frequency Array (Draw an array of exactly 10 integers tracking first-digit counts). |
| 2749 |
Minimum Operations to Make the Integer Zero |
Backtracking/BFS: From num1, try subtracting 2^i + num2 for all i. Search for the shortest path to 0. $O(\text{Branching}^\text{Depth})$. |
Unbounded Search Graph |
Draw num1. Draw 40-60 arrows coming out of it representing different subtractions. The state space explodes immediately. |
Queue Memory (Visualizing the BFS queue filling with millions of possible intermediate numbers). |
Bit Manipulation + Brute Force on k (Steps) |
Binary Representation Bound Check |
Let k be the number of operations. Then num1 - k*num2 must be representable as the sum of k powers of 2. This is true if bitCount(num1 - k*num2) <= k and k <= (num1 - k*num2). Iterate k from 1 to 100. |
Draw a table with k in one column and num1 - k*num2 in the next. Check the binary bits of the result. If the number of '1's is <= k, you found the answer. |
Constant Time $O(1)$ / $O(60)$ |
Draw a tiny loop that runs at most 60 times. Label it $O(1)$ or $O(\log N)$. |
Zero Extra Space (Draw a single integer k and a long integer diff). |
| 2750 |
Ways to Split Array Into Good Subarrays |
Backtracking: Explore every possible split point in the array. Check if each resulting subarray contains exactly one '1'. $O(2^N)$. |
Exponential Partition Tree |
Draw the array. Draw a binary tree where each node decides to "split" or "not split" after the current element. Cross out branches with >1 or 0 ones. |
Recursive Call Stack (Visualizing the depth-first search through all valid and invalid partition combinations). |
Product of Gaps (Combinatorics) |
Slot-and-Multiplier Timeline |
Find indices of all '1's. The number of ways to split between two '1's at indices i and j is the number of zeros between them + 1 (j - i). Multiply all these "gap counts" together. |
Draw the array. Circle the '1's. Draw a double-headed arrow between each adjacent pair of '1's. Write the distance (index difference) above each arrow and multiply them. |
Linear Pass $O(N)$ |
Draw a single horizontal arrow passing through the array. Label it $O(N)$ as you only need to find indices of '1's once. |
$O(1)$ Accumulator (Draw a single ans variable being updated by multiplication and a prev_idx variable). |
| 2751 |
Robot Collisions |
Simulation: Move all robots by 0.5 units at each step. Check for collisions, update health, and remove robots. $O(\text{Time} \cdot N)$. |
Temporal Step Simulation |
Draw robots on a line. Move them in increments. When they overlap, draw a "Boom" icon and decrement health. Very slow for large coordinates. |
State Array Snapshots (Drawing the entire array state for every microscopic time increment). |
Sorting + Monotonic Stack |
Directional Collision Stack |
Sort robots by position. Use a stack to store robots moving 'R'. When a robot moving 'L' appears, pop 'R' robots from the stack one by one to collide. Update health accordingly. Only survivors remain. Sort back to original order. |
Draw a conveyor belt. Robots moving Right go into a "Waiting Room" (the stack). When a Left-moving robot comes by, it "fights" the first one in the room. Winner stays. |
Sorting $O(N \log N)$ |
Draw a sorting block followed by a single linear pass using a stack. Label it $O(N \log N)$. |
Stack & Position Map (Visualize a stack holding robot indices and an array for health tracking). |
| 2752 |
Customers with Maximum Number of Transactions on Consecutive Days (SQL) |
Self-join the transaction table on date = date + 1 for every possible chain length. $O(N^k)$ where k is the chain length. |
Recursive Self-Join Grid |
Draw the table. Draw arrows from Row A to Row B if dates are consecutive. Then from B to C. The complexity grows exponentially with the sequence length. |
Temporary Join Tables (Visualizing the SQL engine creating massive intermediate tables for each join). |
Gaps and Islands (Row Number Difference) |
Grouped Sequence timeline |
Use ROW_NUMBER() OVER(PARTITION BY customer_id ORDER BY transaction_date). Subtract this from the date. Consecutive dates will result in the same "base date" (the island). Group by this base date. |
Draw a column of dates and a column of 1, 2, 3... Subtract them. Notice how "2023-01-05" - 1 and "2023-01-06" - 2 both equal "2023-01-04". Highlight that constant group. |
$O(N \log N)$ Sorting |
Draw a sort/partition block followed by a window function scan. Label it $O(N \log N)$. |
Partition Buffer (Draw the database memory dividing rows into customer buckets before sorting). |
| 2753 |
Count Houses in a Circular Street II |
Randomly walk around the circle and count houses until you think you've seen them all. No guarantee of correctness. |
Infinite Random Walk |
Draw a circle. Draw a person wandering aimlessly. The path line never closes or terminates predictably. |
Unbounded Step Counter. |
Marker Placement & Seek (O(k) where k is max possible) |
Flag and Lap Sweep |
Close the door at the start. Move k houses (max limit), closing all doors as you go. Then open the door at the start. Walk until you hit that open door. The number of steps is the count. |
Draw a circle of houses. Draw a hand closing every door in one lap. Open one door. Walk until you find that "Flag" door again. |
Linear $O(k)$ |
Draw two circles representing the two laps. Label it $O(k)$. |
$O(1)$ State Variables (Draw one integer steps). |
| 2754 |
Bind Function to Context (JS) |
Wrap the function in a new function that manually sets context.fn = originalFn, calls it, and then delete context.fn. (Risk of overwriting existing properties). |
Property Injection Trace |
Draw an object. Draw a new arrow pointing into it representing the injected function. Show it being deleted immediately after. |
Temporary Property Allocation (Mutation of the target object). |
Native apply / call Closure |
Context-Bound Execution Frame |
Return a new function that uses originalFn.apply(context, args). This leverages the engine's ability to switch the this binding without modifying the context object. |
Draw a function block and an object block. Draw a "Pipe" (apply) that plugs the function into the object's power supply (this) temporarily. |
Constant Time $O(1)$ |
Draw a single wrapper box. Write $O(1)$ as the binding creation is a fixed overhead. |
Closure Reference (Draw a small memory bubble holding references to the function and the context object). |
| 2755 |
Deep Merge of Two Objects (JS) |
Recursive for...in loop that overwrites properties. If a key exists in both, recursively call merge. Doesn't handle arrays or non-object edge cases properly. |
Recursive Branching Trace |
Draw two tree structures (Obj A and Obj B). Draw arrows merging nodes at the same path. Show how nested branches trigger new function calls. |
Deep Call Stack (Visualize memory frames for every nested level of the JSON structure). |
Recursive DFS with Type Discrimination |
Graph-Based Tree Union |
Traverse both objects. If both values are objects (and not arrays), recursively merge. If both are arrays, return obj2. Handle null and primitives as leaf nodes where obj2 always wins. |
Draw two trees. For each shared path, draw a "Merge Gate". If inputs are primitives, the gate outputs Value B. If they are objects, it outputs a new combined node. |
$O(N + M)$ Total Keys |
Draw a single tree representing the union of all keys in both objects. Label it $O(\text{Total Nodes})$. |
Heap Object Graph (Visualize the creation of a new combined object structure without mutating the originals). |
| 2756 |
Query Batching (JS) |
Every call to getValue immediately triggers an API request. This results in N network calls for N requests within the same millisecond. |
Congested Network Timeline |
Draw a timeline. For every function call, draw a separate arrow firing toward a "Server" box. The server is overwhelmed by simultaneous requests. |
Network Socket Overload (Visualizing multiple open connections consuming system file descriptors). |
Microtask/Tick-based Accumulator |
Batch Funneling Timeline |
When a call comes in, push it to a pending queue. Use a Promise.resolve().then() or setTimeout(0) to schedule a single flush that processes all accumulated queries in one batch call. |
Draw a funnel. Multiple "Request" balls drop in. At the bottom, a "Gate" opens only once per tick, letting all balls pass through as a single "Batch" block. |
$O(1)$ amortized Scheduling |
Draw a single event loop cycle. Highlight the "Microtask" phase where the batch is processed. Label it $O(1)$ scheduling overhead. |
Pending Queue Buffer (Draw an array in memory that grows linearly with calls but is cleared completely after each tick). |
| 2757 |
Generate Circular Array Values |
Simulate the rotation by actually slicing and concatenating the array or moving an index one-by-one in a while loop. $O(\text{Steps})$. |
Step-by-Step Index Hopping |
Draw a circle of boxes. Draw an arrow moving one box at a time for 1,000,000 steps. Very inefficient visual. |
Iterative Pointer Mutation (Visualizing the CPU cycle overhead for millions of small increments). |
Modular Arithmetic Indexing |
Coordinate Wrap-Around |
Calculate the new index directly using (current + steps % n + n) % n. This handles large positive and negative steps instantly in one operation. |
Draw a linear array and a "Wrap" arrow connecting the end back to the start. Show the math equation jumping from any index to another. |
Constant Time $O(1)$ |
Draw a single "Modulus" operator box. Write $O(1)$ as the calculation time doesn't depend on the number of steps. |
Zero Extra Space (Draw a single integer index variable). |
| 2758 |
Next Day (JS) |
Manually calculate the next day by checking if current day is 28, 30, or 31, then checking leap years for February, then rolling over months and years. Extremely error-prone. |
Heuristic Decision Tree |
Draw a massive "If/Else" forest: Is it February? Is it a leap year? Is it December 31st? The logic is a mess. |
Multiple Boolean Flags (Visualizing all the manual state variables needed for date math). |
Epoch Timestamp Offset / Date Constructor |
Linear Timeline Shift |
Get the current date time, add 24 * 60 * 60 * 1000 milliseconds, and create a new Date object. The built-in engine handles all roll-overs and leap years automatically. |
Draw a timeline. Mark "Today". Draw a single arrow of size "1 Day" pointing to "Tomorrow". |
Constant Time $O(1)$ |
Draw a single box for the Date API. Write $O(1)$. |
Date Object frame (Visualize a single object in the heap storing the internal UTC timestamp). |
| 2759 |
Convert JSON String to Object |
Using `eval()` (security risk) or writing a massive regex engine that fails on nested brackets. |
Regex Spaghetti |
Draw a massive regular expression trying to capture infinite depths of `{}` and `[]`. It loops back on itself and crashes. |
Recursive Descent Parser / Stack |
The Token-Consumer Loop |
Iterate the string character by character. When you see `{`, recursively parse an object until `}`. When you see `[`, recursively parse an array until `]`. Parse strings, numbers, and booleans sequentially. |
Draw the string. Draw a "Consumer" pac-man. It eats a `{`, opens a new empty Object box, and calls a mini-pac-man to eat the keys/values until it hits `}`. |
Single Pass Parsing $O(N)$ |
Draw a straight timeline of the string. Above it, draw the call stack growing and shrinking for nested structures. |
Massive string slicing/substring allocations. $O(N^2)$. |
Recursive call stack. $O(\text{Depth})$ space. |
| 2760 |
Longest Even Odd Subarray With Threshold |
Check every possible subarray [i, j] (O(N²)). For each, verify if it starts with even, elements are <= threshold, and parity alternates. Total $O(N³)$. |
Nested Interval Verification |
Draw a string of numbers. Use two pointers to define a window. For every window, scan it to check conditions. Area grows as $O(N³)$. |
Intermediate Subarray Slices (Visualizing the heap filling with transient array segments). |
Sliding Window / Two-Pointer Pass |
Continuous Condition Sweep |
Scan the array. When you find an even number <= threshold, start a window. Expand while nums[i] <= threshold and nums[i] % 2 != nums[i-1] % 2. Update max length and jump the start pointer to the end of the failed condition. |
Draw the array. Shade a region that follows the rule. When the rule breaks, immediately jump the shading start to the next valid starting point. |
Linear Amortized $O(N)$ |
Draw a single horizontal line. Note that the pointer only moves forward. Label it $O(N)$. |
$O(1)$ Pointers (Draw two integer variables: left and right). |
| 2761 |
Prime Pairs With Target Sum |
Check every number up to N for primality $O(√N)$, then check if n - i is prime. $O(N \cdot √N)$. |
Repeated Prime Testing |
Draw the number line. For every single number, draw a mini-loop calculating its divisors. Redundant checks everywhere. |
Sieve of Eratosthenes + Two Pointers |
The Sieve & Meet-in-Middle |
1. Precompute primes up to N using the Sieve in $O(N \log \log N)$. 2. Iterate i from 2 to n/2. If `isPrime[i]` and `isPrime[n-i]` are both true, it's a valid pair. |
Draw a grid of numbers 1 to N. Cross out multiples of 2, 3, 5. Then, put a left finger on 2 and right finger on N-2. If both fingers are on uncrossed numbers, record them. Slide fingers inward. |
Sieve Precomputation $O(N \log \log N)$ |
Draw a grid with crossing-out lines, followed by a single linear scan up to N/2. |
Calling primality tests without caching. |
A boolean array of size N. $O(N)$ space. |
| 2762 |
Continuous Subarrays |
Check every subarray $O(N²)$. For each, find the min and max element. If max - min <= 2, increment the count. Total $O(N³)$. |
N³ Brute Force Search |
Draw the array. For every pair of indices, scan the interior to find the range. Very repetitive. |
Redundant Min/Max Scans (Drawing a search arrow within every window). |
Sliding Window + Monotonic Deque / TreeMap |
Shrinkable Min-Max Window |
Use a sliding window. Maintain a data structure (like two Deques or a TreeMap) to keep track of the current min and max in $O(1)$ or $O(\log K)$. If max - min > 2, shrink the window from the left. |
Draw the array. Draw a "Range Bracket". As it moves right, keep a "Min" and "Max" label above it. If the difference > 2, the left bracket snaps forward. |
Linear Amortized $O(N)$ |
Draw a single horizontal line with two pointers. Label it $O(N)$ (using Deque) or $O(N \log K)$ (using TreeMap). |
Monotonic Deques (Draw two double-ended queues storing indices of elements in increasing/decreasing order). |
| 2763 |
Sum of Imbalance Numbers of All Subarrays |
For every subarray, sort it and count the number of adjacent elements with a difference > 1. $O(N³ \log N)$. |
N³ Sorting Trace |
Draw all possible contiguous segments of an array. For each, draw a second "Sorted" version, then count gaps. |
Massive Sort Buffer Allocation (Drawing the memory used to sort N^2 subarrays). |
Incremental HashSet / Contribution Technique |
Neighbor-Check Accumulator |
Iterate with a fixed start and move end right. Keep a Set of numbers seen. When adding x, an imbalance decreases if x-1 or x+1 was already there, but increases if it's a "new" gap. Maintain a running current_imbalance. |
Draw an empty set. Add a number. If its neighbor is already in the set, draw a line connecting them (removing an imbalance). If not, it's a new island. |
$O(N²)$ Quadratic Pass |
Draw a 2D matrix representing start vs end. Each cell is $O(1)$. Label it $O(N²)$. |
$O(N)$ Frequency/Set State (Draw a single hash set or boolean array updated in the inner loop). |
| 2764 |
Is Array a Preorder of Some Binary Tree |
Recursively attempt to build every possible valid BST shape from the array. $O(\text{Exponential})$. |
Tree Shape Permutations |
Draw the root. Branch out trying to fit the next number as a left child, then a right child. Backtrack constantly. |
Monotonic Stack (Parent Tracking) |
The Right-Branch Verifier |
In a preorder traversal represented as nodes with depths, the depth must increment by exactly 1 (going left) or decrease/stay same (going right up the tree). Use a stack to track the path. Pop the stack if the next node's depth is <= the stack top's depth. |
Draw a vertical tube (stack). Push the root. Read the next node. If its depth is deeper, push it. If it's shallower, pop the tube until you find its parent depth. If the parent doesn't exist, it's invalid. |
Single Linear Scan $O(N)$ |
Draw an array timeline. Show $O(1)$ amortized stack push/pop operations at each step. |
Generating physical tree nodes in memory. |
A stack storing node depths. $O(H)$ space. |
| 2765 |
Longest Alternating Subarray |
Check every possible subarray [i, j] (O(N²)). For each, verify if s[k+1] - s[k] alternates between 1 and -1, starting with 1. Total $O(N³)$. |
N³ Brute Force Validation |
Draw a sequence of numbers. Use two brackets to isolate every segment. For each segment, check the differences between neighbors. Area is $O(N³)$. |
Subarray Buffer (Visualizing the heap filling with transient slices of the input array). |
Sliding Window with Restart Logic |
State-Driven Pointer Jump |
Iterate through the array. If a pair (i, i+1) has a difference of 1, start a window. Expand as long as the difference alternates. When it breaks, if the current difference is 1, restart from the previous element; otherwise, look for the next 1. |
Draw the array. Draw a zigzag line above it representing +1, -1, +1. When the zigzag breaks, jump the pointer and start a new zigzag. |
Linear $O(N)$ |
Draw a single horizontal arrow. Note that each element is visited at most twice. Label it $O(N)$. |
$O(1)$ Pointers (Draw two variables: maxLen and currentLen). |
| 2766 |
Relocate Marbles |
Maintain an array of all marble positions. For each move from old to new, iterate through the array, find all marbles at old, and change their value to new. $O(\text{Moves} \\text{cdot Marbles})$. |
Massive Array Search/Replace |
Draw a list of marble positions. For every move, scan the whole list and erase/rewrite numbers. Work scales as the product of moves and marbles. |
Linear Memory Scan (Visualizing the CPU reading the entire marbles array for every single instruction). |
HashSet Position Tracking |
Dynamic Set Transformation |
Store initial positions in a Set. For each move, remove the from position and add the to position. The Set handles the "all marbles at this position" rule automatically. Sort the final Set keys. |
Draw a coordinate line with marbles on it. When a move happens, "pick up" the dot at from and "drop" it at to. The number of dots stays constant or decreases. |
$O(N \log N)$ Sorting |
Draw an $O(M)$ move block followed by an $O(N \log N)$ sort block. Label the bottleneck as $O(N \log N)$. |
HashSet / Sorted Array (Draw a hash set in memory storing only the unique occupied coordinates). |
| 2767 |
Partition String Into Minimum Beautiful Substrings |
Generate all possible partitions of the string. Convert each to decimal and check if it's a power of 5. $O(2^N)$. |
Exponential Partition Forest |
Draw the string. At every character gap, branch: Split or Don't Split. Tree width is massive. |
Dynamic Programming (1D) |
The Valid-Jump Tracker |
`dp[i]` = min substrings for the prefix of length `i`. To calculate `dp[i]`, look back at all previous indices `j`. If `substring(j, i)` has no leading zeros and is a power of 5, `dp[i] = min(dp[i], dp[j] + 1)`. |
Draw the binary string. Below it, draw a DP array. From index `i`, draw backward arcs to previous valid split points `j`. Write the minimum arc path length in `dp[i]`. |
Quadratic Substring Checks $O(N^2)$ |
Draw an array of length N. At each index, draw a backward-scanning loop of max length N. Since N <= 15, this is extremely fast. |
Massive recursion depth and string slicing. |
A 1D DP array of size N. $O(N)$ space. |
| 2768 |
Number of Black Blocks |
Allocate an M x N 2D array. Mark black cells. Iterate through every possible 2x2 subgrid and count the black cells inside. $O(M \cdot N)$. |
Full Grid Density Map |
Draw a giant grid. Shade black cells. Use a 2x2 square "lens" and slide it across every single possible position. Total positions are (M-1)*(N-1). |
$O(M\cdot N)$ Matrix Allocation (Massive memory waste for grids like 10^5 x 10^5). |
Sparse Matrix HashMap / Coordinate Hashing |
Anchor-Based Frequency Counting |
A black cell at (r, c) affects up to four 2x2 blocks. Use a HashMap to store the count of black cells for each 2x2 block, identified by its top-left corner. Iterate only over the provided black cells. Calculate the "zero-black-cell" count by subtracting found blocks from the total. |
Draw only the black dots on a void. Around each dot, draw the four 2x2 squares it touches. Tally how many dots fall into each square using a list on the side. |
$O(B)$ where B = Black Cells |
Draw a single arrow passing through the list of black cells. Label it $O(B)$. Note that it's independent of grid size M, N. |
HashMap of Coordinates (Draw a dictionary mapping "r,c" strings to integer counts). |
| 2769 |
Find the Maximum Achievable Number |
BFS: From num, explore all possible numbers reachable in t steps by incrementing/decrementing both num and an unknown x. $O(2^T)$. |
Expanding Range Tree |
Draw num. Branch to num+1 and num-1. For each, branch again. Do this for t levels. |
BFS Queue (Visualizing the search space widening with every time step). |
Mathematical Maximum Bounds |
Linear Range Expansion |
In each of the t steps, you can increase num by 1 and decrease x by 1 to bring them closer. To maximize x, assume x starts far above num. They meet in the middle after 2 * t total distance relative to each other. Result: num + 2 * t. |
Draw a number line. Place num. Draw t arrows of size 2 jumping to the right. The landing spot is the answer. |
Constant Time $O(1)$ |
Draw a single formula box. Write $O(1)$. |
Zero Extra Space (Draw a single integer result). |
| 2770 |
Maximum Number of Jumps to Reach the Last Index |
Recursive Backtracking: From index i, try jumping to every index j > i where abs(nums[j] - nums[i]) <= target. Explore all paths. $O(2^N)$. |
Exponential Jump Tree |
Draw a line of nodes. From node 0, draw arrows to every reachable node. From those, draw more. The number of paths to the end can be massive. |
Recursive Call Stack (Visualizing deep paths and redundant calculations of the same sub-problems). |
1D Dynamic Programming (Longest Path in DAG) |
Optimal Jump Accumulator |
Let dp[i] be the max jumps to reach index i. For each i, iterate through all j < i. If dp[j] != -1 and the jump condition is met, dp[i] = max(dp[i], dp[j] + 1). |
Draw the array. For each box, look back at all previous boxes. If a "valid jump" arrow exists and the source has a value, update the current box with Source + 1. |
$O(N²)$ Quadratic DP |
Draw a 2D matrix representing the i vs j comparisons. Label it $O(N²)$. |
1D DP Array (Draw a single array of size N initialized to -1, storing the max jump counts). |
| 2771 |
Longest Non-decreasing Subarray From Two Arrays |
Check every possible subarray $O(N²)$. For each position, try picking from nums1 or nums2 to maintain the non-decreasing property. $O(2^N \cdot N²)$. |
Dual-Choice Path Explosion |
Draw two parallel arrays. At each step, you can pick Top or Bottom. Draw arrows for all valid paths. It looks like a lattice with 2^N routes. |
Exponential State Memory (Visualizing the storage of all valid subarray combinations). |
Iterative DP with Two State Variables |
Parallel State Transition |
Maintain dp1[i] (max length ending at i using nums1[i]) and dp2[i] (using nums2[i]). Transition by checking nums1[i] against nums1[i-1] and nums2[i-1]. $O(N)$. |
Draw two rows of boxes. Draw arrows from the previous two boxes to the current two boxes if the non-decreasing rule holds. Write the max length inside each box. |
Linear $O(N)$ |
Draw a single horizontal line passing through the pairs. Label it $O(N)$. |
Two State Variables (Draw only two variables per step, or two 1D arrays of size N). |
| 2772 |
Apply Operations to Make All Array Elements Zero |
For each element nums[i] > 0, subtract nums[i] from nums[i...i+k-1]. If any element becomes negative or you run out of range, fail. $O(N \cdot K)$. |
Repeated Range Subtraction |
Draw the array. For the first element, draw a bracket of size K and subtract its value from all. Redraw the array. Repeat. Visual area is N * K. |
In-place Array Mutations (Visualizing the CPU repeatedly writing to memory for every range update). |
Difference Array / Sliding Window Sum |
Aggregated Offset Tracking |
Keep track of a current_reduction. As you move right, subtract the reduction that "expires" (from i-k). The value needed to zero nums[i] is nums[i] - current_reduction. If positive, add it to the reduction. |
Draw the array and a "Reduction Tank" below it. As the tank moves right, it drains from the left and fills from the right. Check if the tank level ever exceeds the array box height. |
Linear $O(N)$ |
Draw a single horizontal arrow. Label it $O(N)$ because each element is processed once. |
Difference Array / Queue (Draw an array tracking where reductions end, plus one sum variable). |
| 2773 |
Height of Special Binary Tree |
Perform a standard BFS/DFS to find the height. Use a Set to track visited nodes to avoid getting stuck in the "special" leaves that point back to ancestors. $O(N)$. |
Graph Traversal with Cycle Detection |
Draw the tree. Draw the "back-links" from leaves. Show the traversal path circling back. Highlight the visited nodes. |
Visited Node HashSet (Visualizing extra memory to store every node ID to prevent infinite loops). |
Recursive DFS with Leaf Logic |
Pure Tree Depth Recursion |
Key insight: A node is a "special leaf" if its left child's right is itself, or similar. In DFS, if a node is a leaf, return 0. Otherwise, return 1 + max(leftHeight, rightHeight). No visited set needed if logic is leaf-specific. |
Draw the tree. At each node, write the height of its subtrees. If you hit a node that points back up (leaf), stop and return 0. |
Linear $O(N)$ |
Draw a single DFS path through the tree. Label it $O(N)$. |
Recursion Stack (Draw a stack of frames representing the current depth of the tree). |
| 2774 |
Array Upper Bound (JS) |
Iterate from the end of the array to the beginning. The first index where arr[i] == target is the upper bound. $O(N)$. |
Linear Reverse Scan |
Draw the array. Start at the last box and move left until you find the target number. Circle the index. |
Minimal Variable State (Only index i). |
Binary Search (O(log N)) |
Logarithmic Range Narrowing |
Use low and high pointers. While low <= high, check mid. If arr[mid] <= target, move low to mid + 1. The final answer is the last valid index found. |
Draw the array. Mark L and R. Half the distance at each step. Draw a "focus box" that gets smaller and smaller until it lands on the target. |
Logarithmic Time $O(\log N)$ |
Draw a binary tree. Write $O(\log N)$ to show the height of the search tree. |
$O(1)$ Pointers (Draw exactly three integer variables: low, high, mid). |
| 2775 |
Undefined to Null (JS) |
Recursive for...in loop. If a value is undefined, change it to null. If it's an object or array, call the function recursively. Doesn't handle circular references or complex types well. |
DFS Object Traversal |
Draw a JSON tree. Highlight every node. If a leaf is 'undefined', draw an arrow changing it to 'null'. Show recursive arrows for nested objects. |
Recursive Call Stack (Visualize memory frames for every nested level of the object). |
Recursive Mapping / JSON.parse with Reviver |
Functional Tree Transformation |
Use a recursive function that returns the transformed value. For arrays, use map(). For objects, use reduce() or Object.entries(). If value is undefined, return null. |
Draw an input tree on the left and an output tree on the right. Show a "Filter" in the middle that swaps undefined for null as data passes through. |
$O(N)$ where N is Total Nodes |
Draw a single tree. Label it $O(N)$ to show every key/value is visited exactly once. |
New Object Graph (Visualize the creation of a new transformed object in the heap to avoid mutating the original). |
| 2776 |
Convert Callback to Promise (JS) |
Manually create a new function that calls the original function. Use a global variable to store the result when the callback fires, then poll that variable. |
Polling / Busy-Waiting Trace |
Draw a function call. Draw a loop that keeps checking "Is result ready?". Very inefficient. |
Blocking Main Thread (Visualizing the CPU stuck in a loop waiting for the async task). |
Promisification Wrapper |
Promise Wrapper Pattern |
Return a new function that returns new Promise((resolve, reject) => { ... }). Inside, call the original function, passing a custom callback that resolves or rejects the promise. |
Draw a "Box" (the Promise) around the original "Function". When the function finishes, it "unlocks" the box with a value (resolve). |
Constant Time $O(1)$ |
Draw a single wrapper box. Write $O(1)$ as the conversion logic is fixed overhead. |
Closure Reference (Draw a memory bubble holding the resolve/reject handles and the original function). |
| 2777 |
Date Range Generator (JS) |
Calculate the total number of days between dates. Create an array of that size. Fill it with date strings. Return the array. $O(N)$ memory. |
Pre-allocated Date Array |
Draw two dates. Draw a giant array being filled with every single date in between. Show the memory consumption for a 10-year range. |
Heap Array Allocation (Visualizing thousands of string objects being stored simultaneously). |
Generator Function (yield) |
Lazy Stream Production |
Use function*. In a while loop, yield the current date string, then increment the date by one day. This only computes the next date when requested. |
Draw a "Ticker Tape" (the timeline). Draw a "Window" (the generator). Every time you pull the tape, a new date appears, and the previous one is discarded. |
$O(N)$ Time, $O(1)$ Space |
Draw an arrow moving along a timeline. Label it $O(1)$ Space since only one date is in memory at a time. |
Generator State Machine (Visualize a single "Current Date" variable that persists between yield calls). |
| 2778 |
Sum of Squares of Special Elements |
Iterate through the array. For each element at index i, check if n % (i + 1) == 0. If it is, square it and add to sum. $O(N)$. |
Linear Conditional Scan |
Draw the array. For every box, perform a division check. If it passes, draw a "Square" above it and move to the sum. |
$O(1)$ State Variables (Draw one sum and one i). |
Divisor Enumeration (O(√N)) |
Symmetric Divisor Sweep |
Instead of checking all numbers up to N, find all divisors of N by iterating only up to √N. For each divisor d, both d and N/d are indices to check. |
Draw a number line. Only pick specific boxes that are factors of the total length. Highlight how many boxes you skip. |
Square Root Time $O(√N)$ |
Draw a loop that stops halfway. Label it $O(√N)$ to show significant speedup for large arrays. |
Register Accumulator (Draw a single 64-bit integer cell for the sum). |
| 2779 |
Maximum Beauty of an Array After Applying Operation |
Try every possible target value v. For each, count how many nums[i] can reach v within range k. $O(\text{Range} \cdot N)$. |
Value-based Search Grid |
Draw a vertical axis of values. For every number, draw a bar of height 2k. Find the point where the most bars overlap. |
Frequency Map over Range (Visualizing a large array tracking every possible integer value). |
Sorting + Sliding Window |
Difference-Bounded Window |
Sort the array. Find the longest subarray where max - min <= 2k. Use two pointers: expand right, and if the condition breaks, move left. |
Draw a sorted array. Draw a "Bracket" of fixed width 2k. Slide it over the boxes. Count how many boxes are inside the bracket at its densest point. |
$O(N \log N)$ Sorting |
Draw a sort block followed by a single linear pass. Label the bottleneck as $O(N \log N)$. |
In-place Array (Draw the array being sorted in memory; no extra data structures needed). |
| 2780 |
Minimum Index of a Valid Split |
For every index i, split the array. Find the dominant element (mode) for both subarrays and check if it's the same and satisfies the frequency condition. $O(N²)$. |
Nested Frequency Counting |
Draw an array. Draw a vertical line moving from index 0 to N. At each stop, redraw two frequency tables for the left and right sides. Visual area is $O(N²)$. |
Dual Frequency Maps (Visualizing two HashMaps being fully rebuilt for every possible split point). |
Boyer-Moore Voting + Prefix Frequency |
Global-to-Local Frequency Mapping |
First, find the dominant element of the whole array (only one can exist). Then, iterate once more, keeping a running count x of that element. At index i, check if x * 2 > i + 1 and (totalCount - x) * 2 > (n - i - 1). |
Draw the array. Label the "King" (dominant element). As you walk, tally how many times the King appears. At each box, compare the tally against the "Success" formula. |
Linear $O(N)$ |
Draw a single horizontal arrow. Label it $O(N)$ to show two simple linear passes. |
$O(1)$ Auxiliary Space (Draw three variables: candidate, totalCount, and runningCount). |
| 2781 |
Length of the Longest Valid Substring |
Generate every substring $O(N²)$. For each, check if it contains any of the forbidden strings as a substring. Total $O(N³)$. |
N³ Forbidden Search |
Draw a string. Highlight a segment. Run a search for every forbidden word within that segment. Repeat for every possible segment. |
Redundant String Slicing (Visualizing thousands of temporary substring copies being checked against a HashSet). |
Sliding Window + Right-Side Constraint |
Truncated Right-to-Left Check |
Move right pointer. For the new character at right, check only the last 10 characters (since forbidden strings length <= 10). If a forbidden word is found at right - k, update left to right - k + 1. |
Draw the string. Slide the right edge. At each step, peek back only a small fixed distance (10 steps). If you see a "Danger" word, pull the left edge past the danger. |
Linear $O(N \\text{cdot MaxForbiddenLen})$ |
Draw a single arrow. Above it, draw a small "Scanner" box of size 10 moving with the arrow. Label it $O(N)$. |
HashSet of Forbidden Words (Draw a set in memory containing only the strings that are illegal). |
| 2782 |
Number of Unique Categories |
For every item i, compare it with every item j < i using the haveSameCategory API. If it doesn't match any previous item, it's a new category. $O(N²)$. |
N² Pairwise API Calls |
Draw a list of items. Draw lines from the 5th item to the 4th, 3rd, 2nd, and 1st. Repeat for the 6th. The number of lines (API calls) is $O(N²)$. |
Minimal Memory (Only tracking unique category representatives). |
Union-Find / Representative Grouping |
Component Disjoint Sets |
Maintain a list of "Representative" items (one for each category found so far). For a new item, check it against the representatives. If no match, add it to the representatives. |
Draw several "Bucket" nodes. For a new node, ask each bucket "Are we the same?". If all say no, the node becomes the head of a new bucket. |
$O(N \\text{cdot UniqueCategories})$ |
Draw a grid where one axis is N and the other is the number of categories. Label it $O(N \cdot K)$. |
Representative List (Draw an array storing the indices of the first item found for each category). |
| 2783 |
Flight Occupancy and Waitlist Analysis (SQL) |
Join Flights and Bookings. For each flight, count bookings. Then use a complex IF/ELSE logic in application code to separate them into "Booked" and "Waitlisted". |
Post-Query Conditional Processing |
Draw two tables joined. Manually count rows and compare against a "Capacity" column. |
Large Intermediate Join (Visualizing the DB loading every single booking record into memory before counting). |
Left Join + Least/Greatest Scalar Functions |
Aggregated Capacity Capping |
LEFT JOIN Bookings to Flights. GROUP BY flight_id. Calculate booked_cnt as LEAST(COUNT(booking_id), capacity) and waitlist_cnt as GREATEST(COUNT(booking_id) - capacity, 0). |
Draw a flight "Container" with a capacity line. Pour "Bookings" in. Anything below the line is booked; the overflow is waitlist. |
$O(N \log N)$ Sorting/Grouping |
Draw a grouping block. Label it $O(N \log N)$ based on the database index performance. |
Aggregation Hash Table (Draw a small table in memory storing flight_id and its current running count). |
| 2784 |
Check if Array is Good |
Sort the array $O(N \log N)$. Check if the first n-1 elements are 1, 2, dots, n-1 and the last element is also n-1. $O(N)$. |
Sorted Sequence Scan |
Draw the array boxes. Rearrange them in order. Check if they match a perfect 1, 2, 3... n-1, n-1 template. |
Sort Buffer (Visualizing the $O(N)$ or $O(\log N)$ extra space used by the sorting algorithm). |
Frequency Counting / Bucket Array |
Value-to-Index Validation |
If arr.length != n (where n = max + 1), return false. Use a frequency array. Every number 1 dots n-2 must appear once, and n-1 must appear twice. |
Draw max number of buckets. Drop the array numbers into them. Check if the last bucket has 2 balls and all others have 1. |
Linear $O(N)$ |
Draw a single horizontal line. Label it $O(N)$ to show no sorting is needed. |
Frequency Array (Draw a 1D array of size max(nums)). |
| 2785 |
Sort Vowels in a String |
Find all vowels and their indices. For every vowel found, compare it with every other vowel and swap them in the string if they are out of order. $O(N²)$. |
In-place Bubble Sort for Vowels |
Draw a string. Circle the vowels. Draw arrows swapping vowels repeatedly until they are sorted alphabetically, while consonants stay put. |
String Mutation Buffer (Visualizing repeated string recreations for each swap in languages with immutable strings). |
Extraction + Sort + Reconstruction |
Two-Pass Vowel Re-injection |
Iterate through the string to extract all vowels into a list. Sort the list of vowels. Iterate through the original string again; whenever you hit a vowel position, replace it with the next vowel from the sorted list. |
Draw a string. Draw a "Side Bucket" where all vowels fall into. Sort the bucket. Draw arrows pouring the sorted vowels back into the empty "vowel slots" in the original string. |
$O(N \log N)$ Sorting |
Draw a linear scan $O(N)$, a sort block $O(N \log N)$, and another linear scan $O(N)$. Bottleneck is $O(N \log N)$. |
Vowel List / Character Array (Draw a temporary array to store vowels and a char array for the final string reconstruction). |
| 2786 |
Visit Array Positions to Maximize Score |
Recursion with Backtracking: At each index i, try jumping to every index j > i. Calculate the score based on parity changes. Explore all paths. $O(2^N)$. |
Exponential Jump Tree |
Draw a line of numbers. From node 0, branch out to every single following node. The tree depth is N, width is 2^N. |
Recursive Call Stack (Visualizing the massive overhead of re-calculating the best path for the same index multiple times). |
Dynamic Programming with Parity States |
Two-Lane State Transition |
Maintain two variables: even_max and odd_max (the best scores ending on an even or odd number so far). For the current number, if it's even, its best score is nums[i] + max(even_max, odd_max - x). Update the parity maxes. |
Draw two rows labeled "Even" and "Odd". As you move through the array, update the corresponding row with the new high score, potentially pulling from the other row with a "-x" penalty. |
Linear $O(N)$ |
Draw a single horizontal arrow. Note that you only check two variables at each step. Label it $O(N)$. |
$O(1)$ State Variables (Draw exactly two 64-bit integer cells: lastEven and lastOdd). |
| 2787 |
Ways to Express an Integer as Sum of Powers |
Recursion: For each number i from 1 up to n, decide to either include i^p in the sum or not. Check if the total equals n. $O(2^n)$. |
Subset Sum Decision Tree |
Draw a tree where each level represents a number. Branch "Add i^p" or "Skip". Leaves that sum to n are counted. |
Exponential State Search (Visualizing all possible combinations of powers being summed). |
0/1 Knapsack Dynamic Programming |
Tabulation Row Update |
Create a DP array dp where dp[i] is the number of ways to sum to i. For each number v = j^p, iterate the DP array backwards: dp[i] = (dp[i] + dp[i - v]) % mod. |
Draw a row of boxes 0 to N. For a power (e.g., 8), slide a "Modifier" from right to left, adding the value from 8 steps back into the current box. |
$O(N \cdot N^(1/P)$) |
Draw a grid where the number of rows is the number of available powers. Label it $O(N \cdot n^{1/p})$. |
1D DP Array (Draw a single array of size N+1 storing the counts for each sum). |
| 2788 |
Split Strings by Separator |
Iterate through each word. Use a manual nested loop to build a temporary string character by character. When the separator is hit, push the temp string and clear it. $O(\text{Total Characters})$. |
Manual Character Buffering |
Draw a string with separators. Scan left-to-right. Build a "LEGO" block for each segment. When you hit a separator, put the block in a box and start a new one. |
Repeated String Concatenation (Visualizing memory churn from adding one char at a time to a string). |
Native split + filter |
Stream Transformation Pipeline |
For each string, call s.split(separator). Flatten the results into one list. Filter out any empty strings "" produced by adjacent separators or leading/trailing separators. |
Draw a funnel. Strings go in. A "Splitter" blade cuts them at the separator. A "Filter" sieve at the bottom catches the empty pieces, letting only valid words through. |
Linear $O(N)$ |
Draw a single straight line through all input strings. Label it $O(\text{Sum of Lengths})$. |
Result List Buffer (Draw an array in memory holding only the final valid string segments). |
| 2789 |
Largest Element in an Array after Merge Operations |
Iterate from left to right. If nums[i] <= nums[i+1], merge them. Repeat this multiple times until no more merges are possible. $O(N²)$. |
Repeated Array Contraction |
Draw the array. Merge a pair, redraw a shorter array. Merge another, redraw. The total area of redrawing is quadratic. |
Intermediate Array Reallocations (Visualizing the heap creating new arrays for every merge pass). |
Reverse Greedy Accumulation |
Right-to-Left Snowball |
Start from the last element. Move left. If nums[i] <= current_sum, add nums[i] to current_sum (snowball effect). If not, current_sum resets to nums[i]. The answer is the max current_sum found. |
Draw a snowball rolling from right to left. As it hits smaller numbers, it absorbs them and gets bigger. If it hits a giant number it can't absorb, it shatters and starts as a new snowball from that giant number. |
Linear $O(N)$ |
Draw a single arrow moving from right to left. Label it $O(N)$ to show one pass is sufficient. |
$O(1)$ Accumulator (Draw a single 64-bit variable currentSum). |
| 2790 |
Maximum Number of Groups With Increasing Lengths |
Try to build groups of length 1, then 2, then 3... by picking elements from usageLimits. Use a priority queue to always pick the most available elements. $O(K \cdot N \log N)$. |
Iterative Group Construction with PQ |
Draw several buckets. Try to fill them with balls from different colors. For each group, redraw the remaining ball counts. Very complex to track manually. |
Priority Queue Heap State (Visualizing the heap re-balancing for every element used in a group). |
Sorting + Greedy Prefix Sum Accumulation |
Cumulative Resource Staircase |
Sort usageLimits. Maintain a total sum of available slots. A group of size k+1 can be formed if the total available elements is >= frac(k+1)(k+2)2. |
Draw the sorted limits as bars. Draw a "Staircase" line (1, 3, 6, 10...) over them. As long as your total bar area stays above the staircase line, you can add another step. |
$O(N \log N)$ Sorting |
Draw a sort block followed by a single linear pass. Label the bottleneck as $O(N \log N)$. |
$O(1)$ Auxiliary Space (Draw a single count and total variable; the sort is in-place). |
| 2791 |
Count Paths That Can Form a Palindrome in a Tree |
For every pair of nodes (u, v), find the path between them. Count character frequencies. If at most one character has an odd frequency, it's a palindrome path. $O(N³)$. |
N² Path Frequency Analysis |
Draw a tree. Pick two nodes, highlight the path. Write down every letter and check for parity. Repeat for all pairs. Massive $O(N³)$ work. |
Path Frequency Maps (Visualizing thousands of HashMaps created to check character counts for every path). |
Bitmasking + DFS + HashMap (Two-Sum Pattern) |
XOR Mask Tree Traversal |
Represent characters 'a'-'z' as bits in a 26-bit integer. Perform DFS to calculate the cumulative XOR mask from root to each node. A path between u and v is palindromic if mask(u) ^ mask(v) has 0 or 1 bits set. Use a HashMap to count mask frequencies. |
Draw a tree. At each node, write its 26-bit XOR mask. Use a "Frequency Table" on the side to count how many nodes share a mask or differ by exactly one bit. |
$O(N \cdot 26)$ Linear Bound |
Draw a DFS pass $O(N)$ followed by a map lookup cycle (26 iterations). Label it $O(N \cdot 26)$. |
Mask Frequency Map (Draw a HashMap in memory storing int masks and their frequency counts). |
| 2792 |
Count Nodes That Are Great Ancestors |
For every node, perform a full DFS/BFS on its subtree to count how many descendants have a value strictly less than the node's value. $O(N²)$. |
Recursive Subtree Scans |
Draw a tree. Pick a node, circle its entire subtree. Manually count smaller nodes. Repeat for every node in the tree. |
Redundant Traversal Stack (Visualizing the CPU re-visiting the same bottom nodes for every ancestor). |
DFS with Fenwick Tree / Segment Tree |
Temporal Value Range Tracking |
Perform a DFS. When entering a node, query a Fenwick Tree for the count of values already present that are smaller than node.val. Add node.val to the Fenwick Tree. Recurse. When leaving, subtract the entry count from the current count to get the subtree-specific total. |
Draw a DFS path. Maintain a "Live Value Count" board (the Fenwick Tree). As you go down, add the current value. As you go up, erase it. Use the delta between entry and exit to find subtree results. |
$O(N \log M)$ where M is Max Value |
Draw a tree with a Fenwick Tree box on the side. Label it $O(N \log M)$. |
Fenwick Tree Array (Draw an array of size Max_Value used for logarithmic range sums). |
| 2793 |
Status of Flight Tickets (SQL) |
Join Flights and Tickets. For each ticket, check its booking time against all other tickets for the same flight to determine its rank. Use a correlated subquery. $O(N²)$. |
Correlated Subquery Scan |
Draw two tables. For one row in Table A, scan every row in Table B to see if the timestamp is earlier. Visual area is N². |
Row-by-Row Comparison Buffer (Visualizing the SQL engine re-scanning the bookings table for every single record). |
Window Function ROW_NUMBER() + Case Logic |
Ranked Partition Pipeline |
Use ROW_NUMBER() OVER(PARTITION BY flight_id ORDER BY booking_time) as rn. A ticket is 'Confirmed' if rn <= capacity, otherwise 'Waitlisted'. |
Draw the table. Group rows by Flight ID. Sort rows inside groups by time. Draw a line at the "Capacity" mark. Everything above is Green; everything below is Yellow. |
$O(N \log N)$ Sorting |
Draw a partition/sort block. Label it $O(N \log N)$ based on the index-backed sorting efficiency. |
Partition Sort Buffer (Draw the memory structure of a sorted partition in the DB engine). |
| 2794 |
Create Object from Two Arrays (JS) |
Iterate through keysArr. For each key, search valuesArr for the corresponding value. If found, add to object. $O(N²)$. |
N² Array Index Search |
Draw two arrays. Pick Key 1, search the entire Value array for index 1. Pick Key 2, search again. |
Linear Search Overhead (Visualizing indexOf being called repeatedly). |
Single Pass Linear Mapping |
Index-Synchronized Transformation |
Iterate through keysArr once using index i. Use obj[keysArr[i]] = valuesArr[i]. If the key already exists in the object (using in operator), skip it to maintain the first-occurrence rule. |
Draw two parallel arrays. Draw an arrow pointing at both keysArr[0] and valuesArr[0]. Connect them to a property in a new Object. Move both arrows together. |
Linear $O(N)$ |
Draw a single horizontal arrow passing through both arrays. Label it $O(N)$. |
Result Object (Draw a single dictionary in the heap storing the key-value pairs). |
| 2795 |
Parallel Execution of Promises for Individual Results Retrieval |
Awaiting promises in a `for` loop, destroying the parallel nature of Promises. Time = sum of all execution times. |
The Sequential Waterfall |
Draw 3 runners. Runner 1 runs, finishes. Runner 2 runs, finishes. Runner 3 runs. Highly inefficient. |
Promise.allSettled Polyfill |
The Racing Lanes |
Fire all promises simultaneously. Attach `.then()` and `.catch()` to each to capture the `{status, value/reason}` object. Keep a counter of finished promises. When the counter hits the array length, resolve the main wrapper promise. |
Draw 3 runners starting at the exact same time. Draw a "Finish Line Clerk" with a clipboard. As each runner crosses (success or fail), the clerk writes it down. When 3 names are written, the clerk hands over the clipboard. |
Parallel Asynchronous $O(\text{Max}(\text{Time})$) |
Draw a Gantt chart. All tasks start at T=0. The total time is the length of the longest task. |
Blocking the main thread with massive arrays. |
An array of result objects identical in size to the input. $O(N)$ space. |
| 2796 |
Repeat String (JS) |
Create an empty string and use a for loop to concatenate the original string n times. $O(N²)$ in some engines due to immutable string re-allocation. |
Iterative String Concatenation |
Draw a small block. Add an identical block to it. Redraw the now-double block. Add another. Redraw. The area of "redrawing" is $O(N²)$. |
Heap Allocation Churn (Visualizing the heap filling with intermediate string fragments: "a", "aa", "aaa"...). |
Binary String Doubling / Array.join |
Logarithmic String Building |
Native repeat(n) uses bitwise doubling: "a" -> "aa" -> "aaaa". Alternatively, new Array(n + 1).join(s) creates the final size once and fills it, avoiding intermediate copies. |
Draw a single block. Copy it to make 2. Copy those 2 to make 4. This doubling reaches the target in only log n steps. |
Linear $O(N)$ Total Length |
Draw a single allocation block of size N x len. Label it $O(N)$ to show linear time for the final copy. |
Single Buffer Allocation (Draw one contiguous block of memory allocated for the final string). |
| 2797 |
Partial Function with Placeholders (JS) |
Create a wrapper that uses arguments. Use a nested loop to find "_" placeholders and replace them one-by-one with incoming arguments. $O(N \cdot M)$. |
N * M Placeholder Replacement |
Draw a function template with holes. Take a bucket of "Values". Pick a value, search the template for the first hole, and plug it. Repeat. |
Argument Object Cloning (Visualizing the memory used to copy the arguments list for every call). |
Single Pass Injection with Pointer |
Index-Linked Arg Injection |
Return a function that merges args (fixed) and restArgs (dynamic). Iterate through args; if it's the placeholder, take the next element from restArgs and increment a pointer. Use ...rest to catch extras. |
Draw a row with some holes. Draw a second row of values. Draw an arrow pointing to the first value. As you fill a hole, move the arrow to the next value. |
Linear $O(N)$ |
Draw a single horizontal pass through the arguments list. Label it $O(N)$. |
Closure Closure Context (Draw a memory bubble holding the original function, the template, and the placeholder symbol). |
| 2798 |
Number of Employees Who Met the Target |
Sort the array of hours. Use binary search to find the first index where hours[i] >= target. Return n - index. $O(N \log N)$. |
Sorted Search Path |
Draw the list. Sort it. Draw a "Cut Line" at the target value. Count everyone to the right of the line. Overkill for a simple count. |
Sort Buffer (Visualizing the $O(N)$ memory used to rearrange the array). |
Single Pass Filter/Count |
Linear Threshold Sweep |
Iterate through the array once. Maintain a counter. If hours[i] >= target, increment the counter. Return count. |
Draw the array. Move an arrow from left to right. Every time the number in the box is >= Target, put a checkmark in a "Success" bucket. |
Linear $O(N)$ |
Draw a single horizontal arrow. Label it $O(N)$ to show a single pass with no sorting. |
Register Accumulator (Draw a single integer count variable in the stack). |
| 2799 |
Count Complete Subarrays in an Array |
First, find total unique elements K. Then, for every possible subarray [i, j], count unique elements. If count equals K, increment answer. $O(N³)$. |
N³ Unique Sub-segment Scan |
Draw the array. For every pair of pointers, create a new Set and count its size. The total number of Sets created is N^2. |
Massive Set Allocation (Visualizing thousands of HashSets being created and destroyed in memory). |
Sliding Window with Frequency Map |
Elastic Window Subarray Counter |
Find total unique K. Use two pointers. Move right until the window contains K unique elements. Once it does, all subarrays starting at left and ending at or after right are "Complete" (there are n - right such subarrays). Move left and repeat. |
Draw the array. Expand a "Golden Bracket" until it has all unique values. Every time it turns golden, all space to the right of the bracket is automatically counted. Shrink the left side and repeat. |
Linear $O(N)$ |
Draw a single horizontal line with two pointers. Label it $O(N)$ to show each element is visited twice. |
Window Frequency Map (Draw a HashMap in memory tracking the counts of elements currently inside the window). |
| 2800 |
Shortest String That Contains Three Strings |
Concatenate the three strings in all 6 possible permutations (A+B+C, A+C+B, etc.). For each, just stick them together without checking for overlaps. Compare the lengths. |
Permutation Stick-Joining |
Draw three colored blocks. Show 6 different ways to stack them horizontally. Note the total length is always the sum of individual lengths. |
String Concatenation Buffer (Visualizing the creation of 6 massive new strings in the heap). |
Greedy Overlap Merging |
Suffix-Prefix Intersection |
For each of the 6 permutations, merge strings by checking if one is a substring of the other, or by finding the maximum overlap between the suffix of the first and prefix of the second. Track the smallest resulting string lexicographically. |
Draw two overlapping rectangles. Shade the intersection area where characters match. The "Merged" block is the total width minus the shaded overlap. |
Constant $O(1)$ Permutations * $O(L^2)$ Merge |
Draw a small flow chart for 6 paths. Each path has 2 merge nodes. Label it $O(L²)$ where L is string length. |
Temporary Merge Strings (Draw a few string buffers in memory used during the comparison phase). |
| 2801 |
Count Stepping Numbers in Range |
Iterate from low to high. For each number, check if the absolute difference between every adjacent digit is 1. $O(N \cdot D)$. |
Linear Range Digits Scan |
Draw a number line. For every number, pull its digits apart and check the "steps". With a range of 10^100, this is impossible to finish. |
Trillions of Digit Arrays (Visualizing the CPU bottleneck from converting numbers to strings repeatedly). |
Digit Dynamic Programming (Digit DP) |
Recursive Digit Decision Tree |
Calculate count(high) - count(low-1). Use a DP state: (index, last_digit, is_less, is_started). Place digits 0-9 while ensuring they differ by 1 from last_digit and stay within the upper bound. |
Draw a tree where each level is a digit position. Branches only exist if the next digit is prev ± 1. Highlight the "Tight" path along the number's limit. |
$O(\text{Length} \cdot 10 \cdot 2)$ |
Draw a 3D table: 100 (Digits) x 10 (Last Digit) x 2 (Tight). Label it $O(D)$ to show it scales with length, not value. |
Memoization Table (Draw a 3D array in the heap storing pre-calculated counts for sub-problems). |
| 2802 |
Find The K-th Lucky Number |
Generate all lucky numbers (strings of 4s and 7s) in level-order (BFS) and put them in a list. Return the K-th element. $O(K)$. |
BFS Lucky Tree Expansion |
Draw a root. Branch to '4' and '7'. From '4', branch to '44' and '47'. Continue until you have K nodes. |
Queue Memory (Visualizing the BFS queue growing linearly with K, potentially millions of strings). |
Binary Representation Mapping |
Logarithmic Number Mapping |
Observe that lucky numbers are effectively a binary tree. The number of nodes in levels 1 to L is 2^L+1-2. Find the length L of the K-th number, then map the remainder of K to a binary string where 0='4' and 1='7'. |
Draw a binary tree. Label the nodes by their rank (1, 2, 3...). Notice that the K-th node's value corresponds to the binary path from the root. |
$O(\log K)$ |
Draw a single path down a tree. Label it $O(\log K)$ because we only calculate the digits of the answer. |
$O(\log K)$ String Buffer (Draw a single small character array for the final answer). |
| 2803 |
Factorial Generator (JS) |
Pre-calculate all factorials up to a certain limit and store them in an array. When called, return from the array. $O(N)$ memory. |
Pre-calculated Factorial Table |
Draw a giant table. Fill it with numbers 1!, 2!, 3!... up to 100!. Most of the memory is wasted if the user only asks for 5!. |
Static Array Memory (Visualizing a large block of heap memory occupied by fixed integers). |
Generator Function (yield) |
Lazy Infinite Sequence |
Use function* factorial(). Initialize res = 1 and i = 1. Inside a while(true) loop, yield res, then update res *= ++i. This computes the next value only on demand. |
Draw a "Factory Machine" with a lever. Every time the lever is pulled (.next()), the internal multiplier turns once, and a factorial drops out. |
$O(1)$ Space, $O(1)$ Per Call |
Draw an infinite timeline. Label it $O(1)$ Space since only the current product is stored. |
Generator State Object (Visualize a small memory cell holding res and i that persists between calls). |
| 2804 |
Array Prototype ForEach (JS) |
Iterate through the array. For each element, use eval() to execute the callback string or a try-catch inside the loop. |
Heavy Eval Execution |
Draw an array. For every box, draw a "Lightning Bolt" (eval) hitting it. Slow and dangerous. |
Execution Context Overhead (Visualizing the engine creating and destroying complex scopes for every iteration). |
Standard Prototypal for Loop |
Linear Execution Pass |
Add forEach to Array.prototype. Use a simple for loop to iterate from 0 to this.length. Call callback.call(thisArg, this[i], i, this). |
Draw an array. Draw an arrow pointing at the first box. Show it triggering the "Callback" function, then moving to the second box. |
Linear $O(N)$ |
Draw a single horizontal line through the array. Label it $O(N)$. |
Function Frame Stack (Draw a stack showing the forEach frame at the bottom and the callback frame appearing/disappearing on top). |
| 2805 |
Custom Interval |
Use JavaScript's native setInterval, relying on the browser's engine to handle timing, which drifts and overlaps if callbacks take longer than the interval delay. |
Overlapping Timelines Diagram |
Draw a horizontal timeline axis. Draw blocks representing execution time. Show blocks stacking on top of each other at fixed intervals, illustrating a clogged call stack. |
Recursive setTimeout via Closure |
Event Loop Macrotask Pipeline |
Trace the execution: Function runs -> finishes -> schedules a *new* setTimeout for the next delay. This guarantees strict spacing regardless of callback execution time. |
Draw a circle. Label the top "Execute Callback". Draw an arrow to the bottom labeled "Wait Delay". Draw an arrow back to the top. This forms a controlled loop. |
Constant Time Step Chart |
Draw a flat horizontal line at y=1. Each tick marks a scheduling operation $O(1)$, independent of how long the callback runs. |
Visualize multiple orphaned timer IDs floating in memory, causing potential memory leaks if clearInterval fails. |
Visualize a single, isolated closure environment holding exactly one active timerId, easily garbage-collected when cleared. |
| 2806 |
Account Balance After Rounded Purchase |
Use multiple if/else statements to check the last digit of the purchase amount (e.g., if ending in 1-4, round down; if 5-9, round up) and subtract from 100. |
Branching Decision Tree |
Draw a root node with the amount. Draw 10 branches (one for each possible last digit 0-9). Group them into two buckets: "Round Up" and "Round Down". |
Arithmetic Snapping / Modulo Math |
Number Line Snapping |
Take amount + 5. Divide by 10 (floor it) to shift the decimal. Multiply by 10 to snap to the nearest decade. Subtract this from 100. |
Draw a number line with multiples of 10. Plot the purchase amount X. Draw an arc moving X exactly 5 units right, then an arrow pointing to the nearest multiple of 10 below it. |
Single Constant Node |
Write down $O(1)$. Draw a single box representing the 1-step math formula. There is no scaling with input size. |
Visualize scattered boolean flags and temporary variables in the stack to track the conditions. |
Visualize exactly two 32-bit integers in memory: the input amount and the output balance. No extra overhead. |
| 2807 |
Insert Greatest Common Divisors in Linked List |
Iterate the linked list, extract all values to an array. Iterate the array to compute GCDs and build a completely new array. Convert the new array back into a linked list. |
Array Extraction Flowchart |
Draw a Linked List. Draw a downward arrow creating an Array. Draw another Array inserting GCDs between elements. Draw an upward arrow building a brand new Linked List. |
In-Place Pointer Splicing + Euclidean Algorithm |
In-Place Pointer Splicing Diagram |
Place curr and next pointers. Calculate GCD of their values. Create a new node. Point curr.next to the new node, and new_node.next to the next pointer. Advance curr. |
Draw two circles (Node A and Node B) connected by an arrow. Erase the arrow. Draw a third circle (Node C) below them. Draw arrows A → C and C → B. |
Linear Traversal with Cyclic Math Steps |
Draw a line of N nodes. Under each gap, write $O(\log(\text{min}(a,b)$)) representing the Euclidean step. Total time is $O(N \cdot \log M)$. |
Visualize heavy heap allocation: $O(N)$ extra memory allocated for the temporary dynamic arrays. |
Visualize $O(1)$ auxiliary stack space for pointers, plus the exact memory needed for the N-1 newly allocated Node objects on the heap. |
| 2808 |
Minimum Seconds to Equalize a Circular Array |
For every unique element, simulate the second-by-second spreading process throughout the entire array, keeping track of the minimum seconds it takes for the whole array to match that element. |
Multi-Grid Simulation Map |
Draw the array repeatedly as rows. Shade elements as they "spread" left and right per second. Do this entirely for each unique number, showing $O(N^2)$ redundant work. |
Hash Map Grouping + Circular Maximum Gap Calculation |
Circular Gap Measurement |
Group all indices of the same number using a Map. For each number, calculate the distance (gap) between adjacent indices, including the wrap-around from the last index to the first. The time to fill the largest gap is floor(max_gap / 2). |
Draw a circle. Mark positions (dots) where a specific number exists. Draw arcs along the perimeter between adjacent dots. Identify the longest arc and cut it in half. |
Two-Pass Linear Scan Chart |
Draw two parallel bars representing length N. Pass 1: Build Hash Map $O(N)$. Pass 2: Calculate Gaps $O(N)$. Time complexity: $O(N)$. |
Visualize a massive 2D matrix or repeated array cloning, taking $O(N^2)$ space to model the simulation state. |
Visualize a single HashMap<Integer, List<Integer>>. Keys are unique values; values are dynamic arrays of indices. Total memory strictly bounded by $O(N)$. |
| 2809 |
Minimum Time to Make Array Sum At Most x |
Recursively simulate every possible combination of setting an element to 0 at every second `t`. This explodes exponentially as `t` increases. |
Exploding Recursive Tree |
Draw a starting node (time 0). Branch out N times for second 1 (representing choosing index i to clear). From each of those N nodes, branch N times again. Show how quickly the tree width becomes unmanageable: $O(N^t)$. |
Sorting + 1D Dynamic Programming (Knapsack variant) |
1D DP Array Progression |
Sort arrays by `nums2` (growth rate). Visualize a 1D DP array where `dp[j]` is the max reduction possible using exactly `j` operations. Iterate through the sorted elements and update the DP table from right to left. |
Draw a row of N+1 boxes (your DP array). Underneath, write the sorted pairs of `(nums1, nums2)`. Draw arrows pointing from `dp[j-1]` to `dp[j]` showing how adding the current element's reduction updates the max value. |
Nested Loop Bounding Box |
Draw an outer loop representing N elements. Inside, draw an inner loop progressing up to N. The total area is an N x N square, proving $O(N^2)$ time complexity. |
Visualize a massive, deep call stack holding the state of the arrays at every second, consuming $O(N \cdot t)$ memory. |
Visualize exactly one 1D Array of size N+1 holding integer reduction values. Memory is strictly bounded to $O(N)$. |
| 2810 |
Faulty Keyboard |
Iterate through the string. Whenever 'i' is encountered, take the string built so far and run a full string reversal operation. |
String Reallocation Graph |
Draw the string building up. At every 'i', draw an arrow to a completely new block of memory with the reversed characters. Label the cost of this reversal as $O(K)$ where K is current length. |
Double Ended Queue (Deque) / Two Pointers |
Deque Insertion Flow |
Maintain a boolean flag `reverse`. When hitting 'i', toggle `reverse`. If `reverse` is false, append to the tail of the Deque. If true, prepend to the head. At the end, read left-to-right (or right-to-left if `reverse` is still true). |
Draw a box with open ends. Use a coin to represent the `reverse` flag (heads=normal, tails=reversed). As you process characters, add them to the right side if heads, left side if tails. Flip the coin when you see 'i'. |
Linear Timeline |
Draw a straight timeline. Each character processed represents one tick. Since Deque insertions at either end are $O(1)$, the entire timeline is simply $O(N)$. |
Visualize a pile of abandoned strings in memory (garbage collection nightmare) as new reversed strings are constantly allocated. $O(N^2)$ overall space churn. |
Visualize a single block of contiguous memory or a linked list of nodes (the Deque) growing strictly to size N, with $O(N)$ space. |
| 2811 |
Check if it is Possible to Split Array |
Recursively try splitting the array at every valid position, computing the sum of the subarrays to ensure they meet the >= m requirement. |
Overlapping Subproblems Tree |
Draw the full array. Draw branches showing all valid split points. For each subarray, draw further splits. Highlight identical subarrays being calculated multiple times. |
Greedy / Math Observation |
Adjacent Pair Highlight |
Realize that if you can find just *one* adjacent pair whose sum is >= m, you can peel off elements one by one until you reach that pair. The problem reduces to finding a valid adjacent pair. |
Write out the array. Draw a sliding bracket of size 2 moving left to right. Write the sum above each pair. Stop and circle the pair if the sum >= m. |
Single Pass Scan |
Draw an array of length N. Draw an arrow moving strictly from index 0 to N-1. Note that checking the sum takes $O(1)$, so total is $O(N)$. |
Visualize a recursion tree call stack depth of $O(N)$, potentially storing subarray copies or indices at each level. |
Visualize a purely $O(1)$ memory footprint. No extra structures needed, just an index pointer and a sum variable traversing the input. |
| 2812 |
Find the Safest Path in a Grid |
Find every single possible path from top-left to bottom-right. For each path, calculate the safeness factor. Find the max. |
Maze Path Combinatorics |
Draw a grid. Draw dozens of distinct squiggly lines from start to finish. Show how the number of paths grows factorially/exponentially with grid size. |
Multi-source BFS + Max-Heap/Dijkstra (or Binary Search + BFS) |
Topological Heatmap & Max-Spanning Tree |
Step 1: Multi-source BFS from all thieves to compute the "safeness" (distance) of every cell. Step 2: Use a Max-Heap to traverse the grid from (0,0), always picking the adjacent cell with the highest safeness factor until reaching the end. |
Draw the grid. Shade the "thief" cells dark. Draw expanding ripples (numbers 1, 2, 3) from the thieves to fill the grid. Next, draw a path from (0,0) prioritizing the highest numbers possible. |
Two-Stage Network Flow |
Draw two boxes. Box 1: Multi-source BFS taking $O(N^2)$ time. Box 2: Dijkstra using a priority queue taking $O(N^2 \log N)$ time. Sum them up to show the bottleneck is the priority queue. |
Visualize infinite path arrays being stored in memory simultaneously, causing immediate Out-of-Memory errors. |
Visualize a 2D integer array (the safeness grid) of size N x N, and a Max-Heap queue storing coordinate tuples. Max space is strictly bounded to $O(N^2)$. |
| 2813 |
Maximum Elegance of a K-Length Subsequence |
Generate all possible combinations of size K using recursion. Calculate the total profit and distinct categories squared for each, keeping track of the absolute maximum. |
Combinatorial Explosion Tree |
Draw a massive binary tree where every node is a choice to "include" or "skip" an item. Show the tree width expanding drastically to $O(2<\text{sup}>N\text{sup}>)$ or $O(N \text{choose} K)$. |
Greedy Sorting + Stack-based Substitution |
Stack Replacement Diagram |
Sort by profit descending. Greedily pick the top K. For items beyond K, if it's a new category, pop the lowest-profit item from the "duplicate categories" stack and replace it. |
Draw the sorted array. Circle the first K items. Draw a bucket (stack) holding items that share a category. When a new category item appears, cross out the bottom of the bucket and swap it in. |
Linear Scan after Sorting Box |
Draw a large box labeled $O(N \log N)$ for the initial sort, followed by a straight, flat arrow labeled $O(N)$ representing the single substitution pass. |
Visualize hundreds of temporary arrays holding K-length combinations, eating up $O(N \text{choose} K)$ memory in the heap. |
Visualize exactly one HashSet for tracking unique categories and one Stack for duplicate-category profits. Space is strictly bounded to $O(N)$. |
| 2814 |
Minimum Time Takes to Reach Destination Without Drowning |
Recursively explore every single path from the start to the destination, recalculating the water expansion at every single step of every path. |
Overlapping Grid Recursion |
Draw the grid multiple times. Scribble winding paths that get arbitrarily cut off by water. Show the same grid state being recalculated repeatedly, taking $O(4<\text{sup}>(R\cdot C)$). |
Multi-source BFS (Water) + Standard BFS (Player) |
Expanding Boundaries Map |
Run BFS from all water sources first to populate a grid of "water arrival times". Then run BFS for the player, only allowing moves into cells where the player's time is strictly less than the water's arrival time. |
Draw two empty grids. On Grid 1, write increasing numbers radiating outward from water cells. On Grid 2, trace the player's shortest path, checking Grid 1 to ensure the player's step count is smaller. |
Two-Pass Grid Sweep |
Draw two identical rectangles (grids). Label the first $O(R × C)$ for water. Label the second $O(R × C)$ for the player. Total time is linear relative to grid size. |
Visualize a massive call stack depth of R×C, with deep recursive frames cloning the grid state over and over. |
Visualize a 2D integer array for water times, and two distinct FIFO Queues (one for water coords, one for player coords), utilizing max $O(R × C)$ space. |
| 2815 |
Max Pair Sum in an Array |
Use nested loops. Check every possible pair (i, j). Extract the maximum digit of both numbers; if they match, update the global maximum sum. |
$O(N<\text{sup}>2\text{sup}>)$ Pairwise Connection Graph |
Draw the array elements in a circle. Draw a straight line connecting every single number to every other number, creating a dense web of redundant checks. |
Hash Map / Array Grouping by Max Digit |
10-Bucket Sorting Diagram |
Maintain an array of size 10 (representing digits 0-9) to store the maximum number seen so far for each max-digit. Iterate the array: update the max sum using the current number and its corresponding bucket, then update the bucket. |
Draw 10 buckets numbered 0 to 9. Read the array left to right. Find the max digit of the number, check the bucket for a pair, calculate sum, and drop the highest number into the bucket. |
Single Flat Timeline |
Draw a single, straight horizontal arrow representing the array traversal. Since finding a max digit and checking a bucket takes $O(1)$, the total is strictly $O(N)$. |
Visualize $O(1)$ space, but with a highly inefficient CPU utilization due to the nested loops. |
Visualize exactly one static integer array of size 10. Perfect $O(1)$ auxiliary space footprint. |
| 2816 |
Double a Number Represented as a Linked List |
Traverse the list to extract all digits. Build a massive string or BigInt. Multiply by 2. Convert the resulting string back into a brand new Linked List. |
String Allocation Pipeline |
Draw a Linked List feeding into a massive String Box, passing through a Math block, outputting a new String Box, and feeding into a new Linked List. |
Single Pass with Lookahead (In-Place) |
Look-ahead Carry Pointer |
Traverse left to right. Double the current node's value and take modulo 10. Look at the NEXT node; if its value is 5 or greater, it will generate a carry, so add 1 to the CURRENT node. Handle a new head node if the first digit is ≥ 5. |
Draw the linked list. Above each node, write its doubled value. Draw a small arrow pointing from the right neighbor to the current node with a "+1" if the neighbor is ≥ 5. Update the node values in place. |
Linear Traversal Line |
Draw a single straight line from the Head to the Tail of the list. Mark it $O(N)$. |
Visualize huge, temporary String or BigInt objects dynamically allocated on the heap, wasting $O(N)$ memory. |
Visualize strict $O(1)$ auxiliary space. No new nodes are created (except potentially one new head node). Everything is modified in-place. |
| 2817 |
Minimum Absolute Difference Between Elements With Constraint |
Nested loops. For every element at index `i`, loop through all elements from `i + x` to the end of the array, calculating the absolute difference and tracking the minimum. |
Segmented Sliding Window |
Draw the array. Place pointer `i`. Place pointer `j` exactly `x` steps away and drag it to the end. Repeat for every `i`, showing a shrinking $O(N<\text{sup}>2\text{sup}>)$ triangle of operations. |
Balanced Binary Search Tree (TreeSet) + Sliding Pointer |
Dynamic BST Insertion |
Iterate `i` from `x` to the end. Maintain a Balanced BST of "valid" elements (inserting `nums[i - x]` at each step). For `nums[i]`, query the BST for the closest values (floor and ceiling) and update the min difference. |
Draw the array. Draw a box spanning from index 0 to `i - x` labeled "Active BST". As `i` moves right, add the left-trailing element to the box. Draw an arrow from `nums[i]` into the box to find the nearest match. |
Loop surrounding a Logarithmic Query |
Draw an outer loop representing $O(N)$ elements. Inside, draw a smaller block labeled $O(\log N)$ representing the tree search and insertion. Total is $O(N \log N)$. |
Visualize $O(1)$ extra space, but terrible time complexity due to exhaustive scanning. |
Visualize an $O(N)$ dynamic Balanced Binary Tree (like a Red-Black Tree) existing in the heap alongside the original array. |
| 2818 |
Apply Operations to Maximize Score |
Generate all possible subarrays, calculate the prime score for each element, find the maximum prime score in each subarray, and perform K operations by exhaustively searching the highest scores. |
Subarray Combinatorics Map |
Draw an array of size N. Draw all possible brackets representing subarrays. For each bracket, draw a list of prime factors for every number. Show the $O(N^3)$ or $O(N^2 √M)$ overlap. |
Monotonic Stack + Sieve of Eratosthenes + Greedy (Contribution Technique) |
Contribution Range Visualization |
1. Precompute prime counts using a Sieve. 2. Use a Monotonic Stack to find the 'left' and 'right' boundaries where the current element is the "king" (max prime score). 3. Calculate how many subarrays it dominates: (i - left) x (right - i). 4. Greedily multiply the largest values. |
Draw the array. Under each element, write its prime score. Draw "expansion arrows" left and right from each number until they hit a number with a higher/equal prime score. Use these boundaries to calculate subarray counts. |
Multi-Stage Pipeline (Sieve → Stack → Sort) |
Draw three sequential boxes: $O(M \log \log M)$ for Sieve, $O(N)$ for Stack, $O(N \log N)$ for sorting elements by value. Total time is dominated by the Sieve or Sort. |
Visualize nested loops causing redundant calculations and large temporary lists of subarrays in memory. |
Visualize three linear arrays: prime_counts, left_boundaries, and right_boundaries. $O(N + M)$ space. |
| 2819 |
Minimum Relative Loss After Buying K Items |
For each query, sort the available items or use a heap to pick K items and calculate the relative loss based on the given rules for every possible combination. |
Query-by-Query Re-sorting |
Draw Q query boxes. For each box, draw a full sorting process of the N items. Show the $O(Q \cdot N \log N)$ repetitiveness. |
Sorting + Prefix Sums + Binary Search (Two-Pointer Optimization) |
Loss Function Inflection Point |
Sort items once. Realize loss depends on whether price is <= 2 x m. For each query, use binary search to find the split point and use prefix sums to calculate the total loss of the K cheapest/most expensive items in $O(1)$ or $O(\log N)$. |
Draw a sorted bar chart of prices. Draw a vertical line representing the "relative loss" threshold. Shade the areas representing prefix sums to show how $O(1)$ math replaces $O(N)$ summation. |
Precomputed Cumulative Sum Chart |
Draw a single large $O(N \log N)$ block for sorting. Then draw Q tiny $O(\log N)$ ticks. Total: $O(N \log N + Q \log N)$. |
Visualize repeated memory allocation for sorted subarrays during each query. |
Visualize one sorted array and one prefix sum array. Total $O(N)$ persistent space. |
| 2820 |
Election Results (SQL/Logic) |
Iterate through every vote, look up the candidate, check for ties manually, and handle the logic of "who won" by scanning the entire result set multiple times. |
Nested Scan Execution Plan |
Draw a "Votes" table and a "Candidates" table. Draw arrows scanning the whole Votes table for Candidate A, then again for Candidate B, etc. |
Common Table Expressions (CTE) + Window Functions (RANK/DENSE_RANK) |
Ranking Partitioning |
Group votes by candidate to get counts. Use RANK() partitioned by the election ID and ordered by vote count descending. Filter where rank = 1 to handle ties automatically. |
Draw a table. Group rows by candidate. Add a "Count" column. Add a "Rank" column. Circle all rows where Rank is 1. |
Index-Assisted Aggregation |
Draw a B-Tree index structure. Show how the database "pumps" data through the Group-By and Sort nodes in $O(N \log N)$. |
Visualize temporary "spill to disk" files if the vote counts are calculated in-memory without proper grouping. |
Visualize a Hash Map or Hash Aggregate in memory storing CandidateID -> VoteCount pairs. |
| 2821 |
Delay the Resolution of Each Promise |
Using `while` loops to block the thread until time passes, completely freezing the browser. |
Thread-Blocking Brick Wall |
Draw the JS Call Stack completely jammed by an infinite loop, preventing any other code from running. |
setTimeout + Promise Wrapper |
The Asynchronous Waiting Room |
Wrap the original function call in a new Promise. Inside, use `setTimeout` with the specified delay. When the timeout fires, execute the original function and `resolve()` or `reject()` the wrapper promise with its result. |
Draw a function entering a Waiting Room. Set a timer. The JS engine leaves and does other things. When the timer rings, the engine comes back, runs the function, and ships the result out. |
Non-Blocking Event Loop $O(1)$ |
Draw the JS Event Loop. The task is handed to the Web APIs, leaving the main stack empty and fast. |
Memory leaks from un-cleared intervals. |
Closure holding the resolve/reject references. $O(1)$ space. |
| 2822 |
Inversion of Object |
Using `for...in` loops without checking `hasOwnProperty`, accidentally grabbing prototype chain methods. |
Prototype Pollution Grid |
Draw an object. The loop accidentally grabs built-in functions like `toString` and tries to invert them, causing chaos. |
Object.entries() + Array.reduce() |
The Key-Value Swapper |
Extract `[key, value]` pairs using `Object.entries(obj)`. Iterate and assign `newObj[value] = key`. Array values require special handling to either stringify or map effectively. |
Draw a list of name tags `[Key: A, Value: 1]`. Take the tags, flip them over to read `[Key: 1, Value: A]`, and stick them onto a brand new blank object. |
Linear Object Iteration $O(N)$ |
Draw a single pass over the object's keys. $O(1)$ hash map insertion per key. |
Modifying the object in place and breaking references. |
A brand new Object with N keys. $O(N)$ space. |
| 2823 |
Deep Object Filter |
Recursively traverse every key in the object. For every value found, apply the filter. If a value is another object, start a brand new recursive branch without managing empty parents. |
Recursive Depth-First Search (DFS) Tree |
Draw a tree where each node is a key. Show branches growing for every nested object. Mark nodes "Keep" or "Discard". Show the $O(N)$ traversal where N is the total number of keys. |
Post-Order Recursive Reconstruction |
Bottom-Up Filtering |
Traverse to the deepest leaf first. Apply the filter. As recursion "bubbles up," only include keys whose values are either valid primitive data OR non-empty objects returned from child calls. |
Draw an object tree. Start at the leaves. Cross out invalid leaves. For parent nodes, if all children are crossed out, cross out the parent too. Circle only the remaining connected paths. |
Single Pass Tree Traversal |
Draw a single line that touches every node exactly once (the Euler tour). Total time is $O(N)$. |
Visualize a deep call stack for highly nested objects, potentially causing "Maximum call stack size exceeded." |
Visualize a clean, reconstructed object in the heap that only contains references to the "surviving" data. |
| 2824 |
Count Pairs Whose Sum is Less than Target |
Use two nested loops: for i from 0 to n-1 and for j from i+1 to n-1. Check if nums[i] + nums[j] < target and increment a counter. |
$O(N<\text{sup}>2\text{sup}>)$ Pairwise Matrix |
Draw a square grid of size N x N. Shade the upper triangle above the diagonal. Each shaded cell represents a comparison. Area = N^2/2. |
Sorting + Two Pointers |
Shrinking Search Space |
Sort the array. Place left at start and right at end. If sum < target, then every element between left and right paired with left is also valid. Add right - left to count and move left. |
Draw a sorted number line. Mark L and R. Draw a bracket from L+1 to R to represent the "freebie" pairs counted instantly when nums[L] + nums[R] < target. |
N log N Sort + N Scan |
Draw a box for Sorting (O(N log N)) followed by a single pass of the Two Pointers (O(N)). The sort is the bottleneck. |
Visualize $O(1)$ extra space but $O(N^2)$ time wastage. |
Visualize $O(1)$ or $O(\log N)$ space depending on the sorting algorithm used. |
| 2825 |
Make String a Subsequence Using Cyclic Increments |
Try every possible combination of incrementing or not incrementing each character in str1, then check if str2 is a subsequence of any resulting string. |
Binary Choice Decision Tree |
For a string of length N, draw a tree that splits twice at every character (Stay vs. Increment). The tree has 2^N leaves. |
Two Pointers (Greedy Subsequence Match) |
Parallel Pointer Sync |
Pointer i on str1 and j on str2. If str1[i] == str2[j] OR (str1[i] + 1) % 26 == str2[j], move both. Otherwise, only move i. If j reaches the end, return true. |
Draw two strings one above the other. Draw arrows from str2 characters to str1 characters, showing either a direct match or a "+1" cyclic match. |
Linear Comparison Line |
Draw a single line of length N (length of str1). Each step is a constant time comparison. $O(N)$. |
Visualize massive memory usage from storing 2^N temporary string variations. |
Visualize exactly two integer variables (the pointers i and j). $O(1)$ auxiliary space. |
| 2826 |
Sorting Three Groups |
Try all possible "valid" non-decreasing configurations of the array (e.g., all 1s, then all 2s, then all 3s) and calculate the number of changes needed for each. |
Brute Force Partition Testing |
Draw the array. Draw two dividers that can be placed anywhere. Everything before divider 1 becomes '1', between dividers becomes '2', after becomes '3'. There are $O(N^2)$ ways to place dividers. |
Dynamic Programming (LIS Variation) |
State Transition Table |
Let dp[i][j] be the min changes to make the first i elements non-decreasing ending with value j (1, 2, or 3). Alternatively, subtract the Longest Non-Decreasing Subsequence length from the total length. |
Draw a 3 x N table. Each cell (j, i) stores the min cost to end the i-th element with value j. Draw arrows from dp[j][i-1] to valid dp[k][i] (where k >= j). |
Flat DP Row Scan |
Draw a grid of size 3 x N. Since 3 is constant, this is effectively a linear $O(N)$ scan. |
Visualize $O(N^2)$ combinations being recalculated. |
Visualize a 1D DP array of size 3 (or 4) that is updated N times. $O(1)$ auxiliary space (since 3 is constant). |
| 2827 |
Number of Beautiful Integers in the Range |
Iterate through every integer from low to high. For each, check if the number of even digits equals the number of odd digits and if the number is divisible by k. |
Exhaustive Range Search |
Draw a number line from 1 to 10^9. For every tick, draw a sub-process that splits the number into digits and checks divisibility. Show the $O(10^9)$ scale. |
Digit DP with Remainder State |
Multidimensional Cache |
State: (index, diff_even_odd, remainder, tight, is_leading_zero). Calculate how many numbers satisfy the even/odd balance and end with a remainder of 0 when divided by k. |
Draw a recursion tree for choosing digits 0-9. At each level, track the balance (e.g., +1 for even, -1 for odd) and the running modulo k. Use a memoization table to skip repeat states. |
Bounded State Volume Viz |
Draw a 3D block representing the state space: Digits(10) x Balance(20) x K(20). Total operations = 10 x 20 x 20 = 4000 per number length. Very fast. |
Visualize the CPU hitting 100% for several minutes while trying to iterate a billion numbers. |
Visualize a 5D/4D array used for memoization. Though it has many dimensions, the total size is small (e.g., 11 x 21 x 21 x 2 x 2). |
| 2828 |
Check if a String Is an Acronym of Words |
Iterate through all words, extract the first character of each, concatenate them into a new string, and then compare that string with the target acronym. |
String Concatenation Pipeline |
Draw a series of "Word" boxes. For each, draw an arrow pulling out the first letter into a "Buffer" box. Finally, draw a comparison arrow to the "Acronym" string. |
Early-Exit Linear Comparison |
One-to-One Pointer Mapping |
First, check if words.length != acronym.length (immediate return). Then, iterate through words using index i and compare words[i][0] with acronym[i]. Exit at the first mismatch. |
Draw the list of words. Draw the acronym string below it. Draw vertical dashed lines connecting the first letter of each word to the corresponding letter in the acronym. |
Single Pass Scan |
Draw a straight line $O(N)$ where N is the number of words. Since each char check is $O(1)$, total time is strictly linear. |
Visualize a new "Acronym Builder" string being dynamically reallocated in memory as letters are added (O(N) extra space). |
Visualize $O(1)$ auxiliary space—no new strings created, just direct character-to-character comparisons. |
| 2829 |
Determine the Minimum Sum of a k-avoiding Array |
Start from 1 and keep adding numbers to a set. For each new number x, check if k - x is already in the set. If not, add it. Stop when the set size reaches n. |
Set-Search Iteration |
Draw a number line starting at 1. Draw a "Bucket" (Set). For every number on the line, draw a "Search" arrow into the bucket before deciding to drop it in. |
Mathematical Greedy Partitioning |
Arithmetic Series Summation |
Take numbers 1, 2, ..., k/2. These are safe because their complements are larger than themselves. Then, skip numbers from k/2 + 1 to k-1. Start taking numbers again from k onwards until you have n elements. |
Write numbers 1 to k. Cross out the numbers from k/2 + 1 to k-1. Circle the first n numbers that are NOT crossed out. Use the sum formula n(a+l)/2 for the two segments. |
Constant Time Formula |
Draw a single box representing the math formula. Since we can calculate the sum of two segments directly, it's $O(1)$ if n and k are used in a formula, or $O(n)$ for a simple loop. |
Visualize a HashSet growing to size n, consuming $O(n)$ space. |
Visualize a single totalSum variable. Pure $O(1)$ space. |
| 2830 |
Maximize the Profit as the Salesman |
Recursively try every possible combination of house offers, skipping those that overlap, to find the maximum possible profit. |
Overlapping Intervals Search Tree |
Draw a horizontal line representing houses. Draw brackets above for offers. Show the recursive tree branching for "Accept Offer" vs "Reject Offer," illustrating exponential overlap. |
DP with Interval Grouping (Bucket Sort style) |
DP State Transition |
Create a 1D DP array where dp[i] is max profit using houses up to i-1. Group all offers by their end position. For each house i, dp[i] = max(dp[i-1], ...dp[start] + gold) for all offers ending at i. |
Draw the DP array. For each index i, draw arrows coming from dp[i-1] and from dp[start] of any offer ending at i. Label arrows with profit values. |
Linear DP with Pre-processing |
Draw a box for "Grouping Offers" $O(N + M)$ and a box for "DP Sweep" $O(N + M)$. Total complexity is linear with respect to houses and offers. |
Visualize a massive recursion stack with $O(2^M)$ potential states. |
Visualize a 1D DP array of size n+1 and a list of lists (the buckets) for offers. Space is $O(n + m)$. |
| 2831 |
Find the Longest Equal Subarray |
For every unique number in the array, find all subarrays where that number can be made "equal" by deleting at most k other elements. Compare lengths. |
Multi-pass Sliding Window |
Draw the array once for every unique element. For "1s", draw a sliding window. For "2s", draw another. Show massive redundant scanning. |
Hash Map of Indices + Sliding Window |
Index Compression Windowing |
Map each number to a list of its indices. For each list, use a sliding window: the number of deletions needed for a window [L, R] is (indices[R] - indices[L]) - (R - L). If deletions > k, shrink L. |
Pick a number (e.g., '1'). Write down its positions: [0, 2, 5]. Sliding window on these indices: (5-0) - (2-0) = 3 deletions. Compare 3 against k. |
Single Pass with Map Update |
Draw an array scan. For each element, update its specific window in the map. This is $O(n)$ because each index is processed by a window exactly once. |
Visualize repeated array slices or sub-arrays being created in memory for every check. |
Visualize a HashMap<Integer, List<Integer>>. Total elements across all lists is N. Space is $O(N)$. |
| 2832 |
Maximal Range of Each Element |
For each element at index i, use two pointers to expand left and right as long as the neighbors are strictly smaller than nums[i]. |
$O(N<\text{sup}>2\text{sup}>)$ Radial Expansion |
Draw an array. For each element, draw two arrows pointing outwards until they hit a larger number. Show the "Scan Overlap" where pointers cross the same elements repeatedly. |
Monotonic Stack (Next Greater Element) |
Range Boundary Logic |
Run a monotonic stack twice: once to find the index of the nearest greater element to the left (L[i]) and once for the right (R[i]). The range is R[i] - L[i] - 1. |
Draw the array. Use a stack to "block" smaller numbers. When a larger number arrives, pop the stack and mark the right boundary for the popped elements. Repeat for the left. |
Two Linear Passes |
Draw two parallel lines, one for the "Left Pass" and one for the "Right Pass". Each is $O(n)$. Total time $O(n)$. |
Visualize $O(1)$ space but $O(N^2)$ time wastage in the worst case (e.g., a sorted array). |
Visualize two arrays of size N (for L and R boundaries) and one stack. Space is $O(N)$. |
| 2833 |
Furthest Point From Origin |
Recursively simulate every possible choice for each underscore ('_'), choosing either 'L' or 'R', and track the max absolute distance. |
Decision Tree Explosion |
Draw a tree where each '_' node branches into 'L' and 'R'. For a string of N underscores, show the tree reaching 2^N leaves. |
Greedy Absolute Displacement |
Vector Summation |
Count fixed 'L's and 'R's. Calculate the net displacement abs(countL - countR). Treat all underscores as moving in the *same* direction that currently has the lead to maximize the distance. |
Draw a number line. Draw arrows for 'L' and 'R'. Group all '_' into a single large arrow pointing toward the furthest side. Total distance = abs(L - R) + underscoreCount. |
Single Pass Counting |
Draw a single horizontal arrow for the string scan. Each character is a $O(1)$ increment. Total $O(n)$. |
Visualize a massive call stack holding 2^N recursive states. |
Visualize three integer counters: l, r, and blank. $O(1)$ auxiliary space. |
| 2834 |
Find the Minimum Possible Sum of a Beautiful Array |
(Identical logic to 2829 with different constraints). Start from 1, use a set to avoid pairs that sum to k, and stop when the set has n elements. |
Sequential Search Map |
Draw a "Checked Numbers" box. For each number, show a lookup to see if (k - current) exists. Show the $O(n)$ search time. |
Arithmetic Series Segmentation (Modulo Math) |
Mathematical Summation |
Split the array into two segments: 1 to min(n, k/2) and then jumping to k and continuing until n elements are reached. Use (n * (a + l) / 2) % mod. |
Draw two separate arithmetic progression bars. Label the first "Lower Half" and the second "Upper Offset". Use the formula to calculate the sum of each in one step. |
Constant Time $O(1)$ Calculation |
Draw a single math formula block. No loops are required if utilizing direct summation formulas. |
Visualize a HashSet consuming $O(n)$ memory. |
Visualize a single long variable for the result. Pure $O(1)$ space. |
| 2835 |
Minimum Operations to Form Subsequence with Target Sum |
Generate all possible subsequence sums from the given powers of 2. If the target isn't found, try splitting larger powers and repeat. |
Recursive Subset Sum Tree |
Draw a tree of all subset sums. When target is missed, draw a branch where an element is split (2^x rightarrow 2^x-1, 2^x-1). Show exponential state growth. |
Greedy Bit Manipulation + Min-Priority Queue (or Frequency Array) |
Bitwise Greedy Filling |
Sort powers. Use smaller powers to fill bits of target. If a bit cannot be filled, find the next available larger power and "split" it repeatedly until it fits the required bit, counting operations. |
Write target in binary. List available powers. Draw arrows "filling" the binary 1s from smallest to largest. If a gap exists, draw a "Split" arrow from a larger number. |
Logarithmic Bit Scan |
Draw a bar with 31 slots (for 2^0 to 2^30). Each slot is processed once. Total $O(n + \log(\text{target})$). |
Visualize $O(2^n)$ combinations stored in memory. |
Visualize an array of size 31 to store counts of each power of 2. $O(1)$ auxiliary space. |
| 2836 |
Maximize Value of Function in a Ball Passing Game |
For each starting player, simulate k passes by following the receiver array and summing up the IDs. |
$O(n \cdot k)$ Simulation Trace |
Draw n players. For each, draw a path of k arrows. Show the massive overlap where paths merge but are still recalculated. |
Binary Lifting (Sparse Table) |
Jump Table Power-of-2 |
Precompute jumps for 2^0, 2^1, 2^2... steps. Each entry stores (destination, sum_of_ids). To find k steps, decompose k into powers of 2 (binary) and "jump" through the table. |
Draw a table where rows are players and columns are powers of 2 (1, 2, 4, 8). In each cell, write the destination and the score. To move 13 steps, jump 8 rightarrow 4 rightarrow 1. |
$O(n \log k)$ Table Construction |
Draw a grid of size n x log k. Construction is $O(n \log k)$ and each query is $O(\log k)$. Total $O(n \log k)$. |
Visualize $O(1)$ extra space but timeout on time complexity. |
Visualize a 2D matrix of size n x log k. Space is $O(n \log k)$. |
| 2837 |
Total Traveled Distance (SQL) |
For every user, run a subquery that sums all distances in the Rides table. Handle the null cases manually by checking if a user exists in the rides table. |
Nested Loop Join Plan |
Draw a "Users" table and "Rides" table. For every row in Users, scan every row in Rides looking for a match. |
LEFT JOIN with COALESCE / IFNULL |
Relationship Mapping |
Join Users to Rides on user_id. Group by user_id. Use SUM(distance) and wrap it in COALESCE(..., 0) to ensure users with no rides show 0 instead of NULL. |
Draw two circles (Users and Rides) overlapping. Color the entire Users circle. Write "Sum" in the overlap and "0" in the non-overlapping User section. |
Hash Join / Index Scan |
Draw a Hash Map where keys are user_id and values are summed distances. Total time $O(\text{Users} + \text{Rides})$. |
Visualize temporary disk storage for huge intermediate join results. |
Visualize a Hash Aggregate table in memory during the GROUP BY phase. |
| 2838 |
Maximum Coins Heroes Can Collect |
For each hero, iterate through all monsters. If the hero's power is ≥ monster's power, add the monster's coins to that hero's total. |
$O(H \cdot M)$ Nested Loop Matrix |
Draw a grid with Heroes as rows and Monsters as columns. Shade a cell if the hero can beat the monster. Total operations = H x M checks. |
Sorting + Prefix Sums + Binary Search |
Cumulative Reward Mapping |
Sort monsters by power. Create a prefix sum array of their coins. For each hero, use binary search (upper bound) to find the strongest monster they can defeat and retrieve the total coins in $O(1)$ from the prefix sum. |
Draw a sorted monster list. Below it, draw a "Treasure Bar" (Prefix Sums). For a hero with power P, draw an arrow pointing into the monster list, then drop a vertical line to the corresponding treasure value. |
$O(M \log M + H \log M)$ |
Draw a box for Monster Sorting $O(M \log M)$. Draw H small ticks representing Binary Search $O(\log M)$. Total time is log-linear. |
Visualize $O(1)$ auxiliary space but massive time waste leading to TLE. |
Visualize two arrays: one for sorted monsters/powers (O(M)) and one for coin prefix sums (O(M)). Total space $O(M)$. |
| 2839 |
Check if Strings Can be Made Equal With Operations I |
Try every possible swap of characters at indices i and i+2 in the 4-character string to see if it eventually matches the target string. |
Permutation State Space |
Draw the string "abcd". Show arrows for valid swaps (a↔c, b↔d). List all possible 4 results. Compare each to the target. |
Parity-Based Character Comparison |
Index Parity Check |
Recognize that characters at even indices (0, 2) can only swap with each other, and odd indices (1, 3) can only swap with each other. Group chars by index parity and check if the sets match. |
Write the string. Circle indices 0 and 2 in blue; circle 1 and 3 in red. Do the same for string 2. If the blue sets match and red sets match, the answer is "Yes". |
Constant Time $O(1)$ |
Draw a single comparison block. Since the input size is fixed at 4, the operation count is constant. |
Visualize a small recursion stack or a set of generated strings. |
Visualize two small sets or arrays of size 2. Pure $O(1)$ space. |
| 2840 |
Check if Strings Can be Made Equal With Operations II |
Similar to 2839, but for strings of length N. Use recursion or BFS to explore all possible swap states until the strings match. |
State Space Explosion Tree |
Draw a starting string. Branch out for every possible index i and i+2 swap. Show the number of states growing exponentially. |
Frequency Mapping by Index Parity |
Frequency Histograms by Parity |
Separate characters of both strings into "Even-indexed" and "Odd-indexed" groups. Use a frequency map (or sorted array) to compare the even group of string 1 with the even group of string 2. Repeat for odd groups. |
Draw two buckets for each string: "Even" and "Odd". Sort characters into these buckets. Compare the contents of the "Even" buckets and "Odd" buckets between the two strings. |
Linear Scan $O(N)$ |
Draw a single line for the string scan. Each character is dropped into a parity bucket. Total time $O(N)$. |
Visualize a massive memory footprint from a BFS queue storing unique string permutations. |
Visualize four frequency arrays (size 26) or two sorted arrays (O(N)). Auxiliary space $O(N)$ or $O(1)$ (if character set is limited). |
| 2841 |
Maximum Sum of Almost Unique Subarray |
Generate all subarrays of length K. For each, use a Set to check uniqueness and a loop to calculate the sum. $O(N \cdot K)$. |
Redundant Subarray Re-checking |
Draw the array. Draw a box of size K. Recalculate everything. Slide box by 1. Recalculate everything from scratch. |
Sliding Window + Hash Map (Frequencies) |
The State-Preserving Window |
Maintain a window of size K, a running sum, and a frequency Map. When sliding: Add the new right element (update sum & map). Remove the old left element (update sum & map). If `Map.size >= M`, update `max_sum`. |
Draw a window frame over the array. Slide it right. Take the exiting number, subtract from total, remove from Map. Take entering number, add to total, add to Map. Check Map size. |
Single Pass $O(N)$ |
Draw a single timeline. $O(1)$ math and Map updates at each step. |
Creating new Set objects for every subarray. |
A Hash Map holding at most K elements. $O(K)$ space. |
| 2842 |
Count K-Subsequences of a String With Maximum Beauty |
Generate all possible K-length subsequences and manually calculate the beauty (frequency sum) of each. $O(\text{Combinations})$. |
Combinatorial Nightmare Tree |
Draw the string. Branch out to pick every possible combination of K characters. Compute frequencies for millions of strings. |
Greedy Frequency Sorting + Combinatorics |
The Frequency-Ranked Bucket Math |
Count frequencies of all chars. Sort descending. Greedily pick the top K frequencies. If the Kth frequency ties with others, use combinations (nCr) to calculate ways to pick the remaining slots. Multiply by frequencies. |
Draw buckets for A-Z based on frequency height. Sort buckets tallest to shortest. Grab top K buckets. If the last bucket ties with leftovers, use math to calculate permutations. |
Sorting + Math $O(N + 26 \log 26)$ |
Draw a linear scan to count, a tiny $O(1)$ sort of 26 items, and a constant time math calculation. |
Storing full subsequences. |
Frequency array of size 26. $O(1)$ space. |
| 2843 |
Count Symmetric Integers |
Iterate through every integer from low to high, convert to string, check if length is even, and then manually sum the first half and second half of characters. |
Integer-to-String Pipeline |
Draw a number line. For each number, draw a "Magnifying Glass" showing the string conversion, the split, and two "Summation" boxes. Note the overhead of $O(\log N)$ string work per number. |
Direct Digit Extraction (Modulo/Div) |
Digit Balance Scale |
For each number, determine its length. If length is odd, skip. If even (e.g., 4 digits), use num % 100 to get the last two and num / 100 to get the first two. Sum the digits of these components using a simple while loop. |
Write a 4-digit number. Draw a vertical dashed line in the middle. Write the math operations (%100, /100) above each half. Add arrows pointing to a central "Equals?" check. |
Linear Arithmetic Scan |
Draw a straight line $O(N)$. Each step involves a fixed number of arithmetic operations (max 6 digits), making it extremely efficient. |
Visualize repeated heap allocations for string objects for every single integer in the range. |
Visualize $O(1)$ auxiliary space—purely stack-allocated integers. |
| 2844 |
Minimum Operations to Make a Special Number |
Generate all possible subsequences of the string by deleting digits and check if the resulting number is divisible by 25. Find the shortest string. |
Power Set Subsequence Tree |
Draw a tree where each node is "Keep" or "Delete" a digit. For a 100-digit string, show the tree exploding to 2^100 states. |
Suffix Greedy Search (Targeting "00", "25", "50", "75") |
Reverse Scan Matching |
A number is divisible by 25 if it ends in 00, 25, 50, or 75. Scan the string from right to left. Find the first occurrence of '0' or '5'. Once found, keep scanning left for the corresponding required partner (e.g., if you found '5', look for '2' or '7'). |
Write the string. Highlight the 4 target patterns (00, 25, 50, 75). Draw an arrow starting from the end of the string moving left, stopping once a valid pair is formed. Count the "skipped" digits. |
Single Pass Scan $O(N)$ |
Draw a line representing the string length N. Each digit is visited at most once for each of the 4 conditions. Total $O(N)$. |
Visualize an exponential number of temporary string objects being created in the heap. |
Visualize $O(1)$ space using just two pointers and a few boolean flags. |
| 2845 |
Count Interesting Subarrays |
Use nested loops to find every possible subarray. For each, count how many elements satisfy nums[i] % modulo == value and check if that count % modulo == k. |
$O(N^2)$ Nested Scan |
Draw the array. Draw all possible brackets. Inside each bracket, draw a loop that counts "Interesting" elements. Area = N^2. |
Prefix Sums + Hash Map (Frequency of remainders) |
Remainder Offset Logic |
Transform the array into 0s and 1s (1 if nums[i] % modulo == value). Calculate prefix sums of this 0/1 array. The problem becomes finding pairs (i, j) such that (prefix[j] - prefix[i]) % modulo == k. This rearranges to prefix[i] % modulo == (prefix[j] - k) % modulo. |
Draw a "Remainder Tracker" Hash Map. As you scan the array, calculate current prefix % modulo. Look in the map for (current - k + modulo) % modulo and add its count to the answer. |
Single Pass $O(N)$ |
Draw a linear scan line. Each map lookup and update is $O(1)$. Total $O(N)$. |
Visualize the CPU stalling as it performs billions of redundant sum operations. |
Visualize a Hash Map that stores at most modulo keys. Space $O(N)$ in the worst case (if modulo is large). |
| 2846 |
Minimum Edge Weight Equilibrium Queries in a Tree |
For each query (u, v), find the unique path in the tree. Count the frequency of all 26 possible edge weights, then find the most frequent weight. The answer is pathLength - maxFrequency. |
$O(Q \cdot N)$ Path Traversal |
Draw a tree with Q arrows connecting nodes. For each arrow, show a "Crawl" along the edges to collect weights. Total time Q x N. |
LCA (Lowest Common Ancestor) + Binary Lifting + Prefix Frequencies |
Hierarchical Prefix Counting |
Precompute the path from the root to every node, storing a 26-length frequency array of edge weights. For query (u, v), use LCA to find the split point. The frequency of weight W in the path is freq[u][W] + freq[v][W] - 2 * freq[LCA(u,v)][W]. |
Draw the tree. For each node, attach a small table of 26 numbers. For a path between nodes, show a "Vector Subtraction" of these tables to find the resulting edge distribution. |
$O((N+Q)$ * 26 * log N) |
Draw a box for Precomputation (N log N). Draw Q ticks representing LCA + Frequency math (Q * 26). Total time is logarithmic-linear. |
Visualize a massive memory overhead if storing full paths for every possible pair. |
Visualize a 2D array freq[N][26] and a binary lifting table up[N][logN]. Space $O(26N + N \log N)$. |
| 2847 |
Smallest Number with Given Product of Digits |
Starting from 1, check every integer sequentially. Calculate the product of its digits and stop when the product equals N. |
Exhaustive Integer Search |
Draw a number line starting at 1. For every number, draw a "Product" calculation box. Show the search potentially reaching astronomical numbers for large N. |
Greedy Prime Factorization (Reverse Digits) |
Reverse Factor Breakdown |
Since we want the smallest number, we want the *fewest* digits, which means using the *largest* single-digit factors (9, 8, 7...). Divide N by 9 until impossible, then by 8, then 7, etc. Store these digits and sort them in ascending order. |
Write N. Draw arrows branching off for divisions by 9, then 8... down to 2. Collect the divisors at the bottom. Arrange the collected divisors from smallest to largest to form the result. |
Logarithmic Factorization $O(\log N)$ |
Draw a division ladder. Each step reduces N significantly. The number of steps is proportional to the number of digits in N. |
Visualize $O(1)$ auxiliary space but massive time wastage leading to TLE. |
Visualize a small List or String to store the resulting digits. Space $O(\log N)$. |
| 2848 |
Points That Intersect With Cars |
Create a boolean array (or Set) of size 101. For every car interval [start, end], loop from start to end and mark each point in the array as occupied. Count the true values. |
Point-by-Point Marking Map |
Draw a number line from 1 to 100. For each car, draw a bracket. Below the bracket, draw a series of dots marking every single integer point it covers. Show the overlap where points are marked multiple times. |
Difference Array / Prefix Sums |
Sweep Line Events |
Create an array diff of size 102. For each car [s, e], do diff[s]++ and diff[e+1]--. Run a prefix sum (running total) across diff. If sum > 0, the current point is covered. |
Draw a number line. Mark +1 at every start point and -1 at every end + 1 point. Draw a "Running Total" graph above it; whenever the graph is above zero, shade the area. |
Single Pass Scan $O(N + \text{MaxCoord})$ |
Draw two boxes: "Interval Marking" $O(N)$ and "Prefix Sum Sweep" $O(100)$. Total is linear and extremely fast. |
Visualize a HashSet that might store up to 100 integers, which is small but less efficient than a primitive array. |
Visualize a fixed-size primitive integer array of 102 elements. $O(\text{MaxCoord})$ space. |
| 2849 |
Determine if a Cell Is Reachable at a Given Time |
Perform a Breadth-First Search (BFS) from the starting cell (sx, sy) to find if the target (fx, fy) can be reached in exactly t seconds. |
Exponential BFS Expansion |
Draw a grid. Start at a cell. Draw 8 arrows to neighbors for second 1. Draw 64 arrows for second 2. Show the expansion area growing as a square, becoming massive for large t. |
Chebyshev Distance (Math/Geometry) |
8-Directional Bound Box |
In a grid where you can move diagonally, the minimum time to reach (fx, fy) is max(abs(sx-fx), abs(sy-fy)). If minTime <= t, it's reachable, unless minTime == 0 and t == 1 (cannot leave and return in 1 second). |
Plot start and finish on a grid. Draw a square boundary centered at start that expands by 1 unit per second. Check if the finish point is inside or on the boundary of the square at time t. |
Constant Time $O(1)$ Logic |
Draw a single decision box. Calculation involves 3 subtractions and 1 comparison. $O(1)$ time. |
Visualize a BFS Queue potentially storing millions of coordinates for large time values. |
Visualize exactly zero extra data structures. Pure $O(1)$ space. |
| 2850 |
Minimum Moves to Spread Stones Over Grid |
Use recursion/backtracking to simulate every possible way to move an "extra" stone (from cells with >1 stone) to an "empty" cell (0 stones). |
Permutation Backtracking Tree |
Draw a list of "Giver" cells (stones > 1) and "Receiver" cells (stones = 0). Draw a bipartite graph showing all possible matching permutations. $O(9!)$ combinations. |
Backtracking with Pruning / BFS for State Space |
Recursive Assignment Search |
Identify all coordinates of empty cells and all coordinates of cells with surplus stones. Use recursion to pick an empty cell and try filling it with a stone from any available surplus cell, calculating Manhattan distance abs(r1-r2) + abs(c1-c2). |
Write down the coordinates of the zeros: (0,1), (2,2)... and the extras: (0,0) has 2 extra.... Draw lines connecting them in different patterns, summing the "lengths" of the lines. Pick the smallest sum. |
Factorial/Permutation Complexity |
Draw a branching tree labeled $O(N!)$ where N is the number of empty cells (max 9). Since 9! = 362,880, this fits well within time limits. |
Visualize deep recursion stacks if not handling state correctly. |
Visualize small coordinate lists for "zeros" and "extras." Space is $O(1)$ because the grid is fixed at 3 x 3. |
| 2851 |
String Transformation |
Simulate the transformation step-by-step for k operations. At each step, generate all possible cyclic shifts and count how many match the target string. |
$O(K \cdot N^2)$ Simulation |
Draw string S. Draw N-1 arrows to all possible shifts. For each shift, draw another N-1 arrows. Repeat K times. Show the state count exploding. |
KMP (String Matching) + Matrix Exponentiation (DP) |
State Transition Matrix |
1. Use KMP to find all indices where s matches target in the circular string. 2. Define two states: dp[0] (matches target) and dp[1] (doesn't match). 3. Create a 2 x 2 transition matrix. 4. Use Binary Exponentiation to raise the matrix to power k in $O(\log K)$. |
Draw two circles labeled "Match" and "No Match." Draw weighted arrows between them representing the number of ways to transition. Show a "Fast Power" box that squares the transition matrix repeatedly. |
$O(N + \log K)$ |
Draw a box for KMP/Z-algorithm $O(N)$. Draw a tiny box for Matrix Power $O(\log K)$. Total time is dominated by the initial string match. |
Visualize $O(N \cdot K)$ space if trying to store DP states for every step. |
Visualize a 2 x 2 matrix and the KMP pi array. Space $O(N)$. |
| 2852 |
Sum of Remoteness of All Cells |
For every non-blocked cell (r, c), perform a BFS/DFS to find all other reachable cells, sum their values, and calculate the "remoteness." Repeat for every single cell. |
$O((R \cdot C)$^2) Repeated Traversal |
Draw a grid. For cell A, shade all reachable cells. For cell B, shade all reachable cells. Show the massive overlap where the same components are traversed thousands of times. |
Connected Components (BFS/DFS) + Global Totals |
Island Component Analysis |
1. Calculate the total sum of all non-blocked cells and the total count. 2. Use BFS/DFS to find each "island" (connected component). 3. For each island, calculate its sum_i and count_i. 4. The remoteness contribution of each cell in that island is (TotalSum - sum_i). Multiply by count_i for the whole island. |
Draw a grid with a few "islands" separated by 'X's. Circle each island. Next to each island, write its sum and size. Calculate (GrandTotal - IslandSum) * IslandSize for each. |
Single Pass Grid Sweep $O(R \cdot C)$ |
Draw a line that visits every cell in the grid exactly once. Total time is linear relative to the number of cells. |
Visualize multiple redundant sets of visited nodes being created in memory. |
Visualize one visited 2D array and a single queue for BFS. Space $O(R \cdot C)$. |
| 2853 |
Highest Salary Difference (SQL) |
Write multiple subqueries to find the max salary for Department A, then a separate subquery for Department B, then manually subtract them in a final select. |
Nested Selection Tree |
Draw two separate tables. Draw an arrow finding the max in Table 1, another for Table 2, and a third arrow joining them at a "Subtraction Node." |
MAX() with Conditional Aggregation (CASE/IF) |
Pivot-style Aggregation |
Group the entire table. Use MAX(CASE WHEN dept='A' THEN salary ELSE 0 END) and subtract it from the same logic for Dept 'B'. Use ABS() for the final difference. |
Draw one table. Color Dept A rows blue and Dept B rows red. Circle the largest blue number and the largest red number. Draw a minus sign between them. |
Single Pass Scan |
Draw a single straight line through the table $O(N)$. Since we only need two values (max A, max B), a single scan suffices. |
Visualize temporary result tables being cached in memory for each subquery. |
Visualize two registers (variables) in memory holding maxA and maxB as the DB engine scans. |
| 2854 |
Rolling Average Steps (SQL) |
For every row in the user activity table, run a subquery that looks back 2 days and calculates the average, manually checking if those dates exist. |
$O(N<\text{sup}>2\text{sup}>)$ Self-Join Map |
Draw a table. For row 3, draw arrows to rows 1 and 2. For row 4, draw arrows to 2 and 3. Show the quadratic increase in "lookback" arrows as N grows. |
Window Functions (AVG ... OVER ROWS BETWEEN 2 PRECEDING) |
Sliding Window Frame |
Partition by user_id and order by activity_date. Use AVG(steps) OVER(PARTITION BY user_id ORDER BY activity_date ROWS BETWEEN 2 PRECEDING AND CURRENT ROW). Check COUNT(*) OVER(...) to ensure exactly 3 days exist. |
Draw a table with a sliding 3-row box. Move the box down one row at a time. Write the average of the box contents in a new "Result" column. |
Linear Window Scan $O(N \log N)$ (due to Sort) |
Draw a "Sorting" box followed by a "Sliding Window" box. Sorting is the bottleneck, followed by a single linear pass for the window. |
Visualize massive temporary join tables if using a self-join approach. |
Visualize a small "buffer" in memory that only holds the last 3 rows for the current partition. |
| 2855 |
Minimum Right Shifts to Sort the Array |
Try every possible number of right shifts from 0 to N-1. After each shift, check if the resulting array is sorted. |
Rotational Simulation Loop |
Draw the array. Draw an arrow showing one rotation. Re-draw the array. Check if sorted. Repeat N times. Total $O(N^2)$. |
Single-Pivot Circularity Check |
Circular Array Breakdown |
Find the "dip" where nums[i] > nums[i+1]. There should be at most one such dip for the array to be a rotated sorted array. If a dip exists, check if nums[last] <= nums[0]. The answer is n - 1 - i. |
Draw the array. Find the only point where the numbers go "down." If you find more than one, return -1. Count how many numbers are to the right of that "down" point. |
Single Pass $O(N)$ |
Draw a single straight line scanning the array once. Each comparison is $O(1)$. Total $O(N)$. |
Visualize repeated array cloning or re-allocation for each shift. |
Visualize exactly one index pointer and a "dip" counter. Pure $O(1)$ space. |
| 2856 |
Minimum Array Length After Pair Removals |
Use a greedy approach with a Max-Heap to always remove the two most frequent elements until no two distinct elements remain. |
Priority Queue Simulation |
Draw a frequency map. Put frequencies into a Max-Heap. Pop two, decrement, and push back. Show the heap operations repeating until the heap is empty. $O(N \log N)$. |
Frequency Dominance / Median Comparison |
Frequency Bar Chart |
In a sorted array, the most frequent element's count maxFreq determines everything. If maxFreq <= n/2, we can pair everything (result 0 or 1). If maxFreq > n/2, the remaining elements are maxFreq - (n - maxFreq). |
Draw the array. Find the middle element. Count how many times it appears. If it's more than half the array, it's the "Boss." The result is the Boss's count minus everyone else's count. |
Binary Search for Median Frequency $O(\log N)$ |
Draw a box for Binary Search. Since the array is sorted, we can find the frequency of the median element in $O(\log N)$ to determine if it dominates. |
Visualize a Max-Heap or Hash Map storing all unique elements $O(N)$. |
Visualize zero extra data structures. Using only pointers on the sorted array, space is $O(1)$. |
| 2857 |
Count Pairs of Points With Distance k |
Nested loops to check every pair of points (i, j) and calculate (x1 XOR x2) + (y1 XOR y2) == k. |
$O(N<\text{sup}>2\text{sup}>)$ Exhaustive Pair Scan |
Draw points on a 2D plane. Draw lines connecting every point to every other point. Total lines = N(N-1)/2. |
Hash Map + Target XOR Decomposition |
XOR Target Distribution |
If (x1 XOR x2) = i, then (y1 XOR y2) = k - i. For each point (x1, y1), iterate i from 0 to k. Calculate required x2 = x1 XOR i and y2 = y1 XOR (k - i). Look up (x2, y2) in a Hash Map. |
Draw a Hash Map of seen points. For a new point, write a list of k+1 "Target Points" by XORing the x and y with values that sum to k. Check the Map for these targets. |
Linear Scan with Constant K-factor $O(N \cdot K)$ |
Draw an outer loop $O(N)$. Inside, draw a small fixed loop of size K. Since K is small (max 100), this is very efficient. |
Visualize $O(1)$ extra space but $O(N^2)$ time timeout. |
Visualize a Hash Map storing coordinate pairs. Space $O(N)$. |
| 2858 |
Minimum Edge Reversals So Every Node Is Reachable |
For every node i in the graph, perform a BFS/DFS to count how many edges must be reversed to reach all other N-1 nodes. |
$O(N^2)$ Repeated Traversal |
Draw a tree. For node 1, draw arrows to everyone, counting reversals. For node 2, start over. Show the total work as N x (Edges). |
Tree DP / Re-rooting Technique |
Directional Influence Shift |
1. Pick an arbitrary root (node 0) and find the cost for it. 2. Use a second DFS to "shift" the root. If moving from parent u to child v, the reversal count changes based on whether the original edge was u to v or v to u. |
Draw a tree. At node 0, write its total cost. For its child, calculate the cost using the parent's cost: subtract 1 if the edge needs to be reversed for the child, add 1 otherwise. |
Two-Pass DFS $O(N)$ |
Draw two lines tracing the tree. Pass 1: Bottom-up. Pass 2: Top-down. Total time is strictly linear. |
Visualize a massive call stack and redundant traversal paths in memory. |
Visualize an adjacency list with "weighted" directions and two integer arrays for DP states. Space $O(N)$. |
| 2859 |
Sum of Values at Indices With K Set Bits |
Iterate from i = 0 to n-1. For each i, convert to binary or use a loop to count set bits. If count equals k, add nums[i] to sum. |
Bit-Count Extraction Scan |
Draw an array. Above each index, draw a "Bit Counter" box that performs $O(\log N)$ work per index. |
Built-in Bit Manipulation (popcount) |
Parallel Bit Processing |
Use the language's optimized bit-counting function (like Integer.bitCount(i) in Java). This typically uses a hardware instruction or a precomputed table to find the set bits in $O(1)$ effectively. |
Draw the array. For each index, write the binary version. Circle the ones. If the number of circles equals k, draw an arrow from the array value to a "Sum" bucket. |
Linear Scan $O(N)$ |
Draw a single line for the array traversal. Since bit-counting for 32-bit integers is constant time, total time is $O(N)$. |
Visualize $O(1)$ extra space but slower execution due to manual bit-looping. |
Visualize zero extra data structures. Pure $O(1)$ auxiliary space. |
| 2860 |
Happy Students |
Generate all possible subsets of students. For each subset, check if both conditions (size > selected students' requirements AND size < unselected students' requirements) are met. |
$O(2^N)$ Subset Generation |
Draw a decision tree with 2^N leaves. Each path is a student selection. Mark valid leaves "Happy." |
Sorting + Greedy Boundary Check |
Sorted Threshold Step-Graph |
Sort the requirements. If we select k students, we should select those with the k smallest requirements. Check if k > nums[k-1] and k < nums[k]. These are the only valid configurations. |
Write the sorted requirements. Draw a "Divider" at every possible position. For each position, check if the index count is strictly between the numbers on either side of the divider. |
Sort-Bottlenecked Linear Scan $O(N \log N)$ |
Draw a box for Sorting $O(N \log N)$ followed by a single pass $O(N)$. Total time is logarithmic-linear. |
Visualize the heap filling with 2^N student selection sets. |
Visualize a single sorted array of size N. Space $O(N)$ or $O(1)$ depending on sort. |
| 2861 |
Maximum Number of Alloys |
Starting from 0, try building X alloys. For each X, calculate the cost for each machine and see if any machine stays under budget. Increment X until the budget is blown for all machines. |
Sequential Simulation Search |
Draw a "Budget Tank." For 1 alloy, subtract cost. For 2 alloys, subtract cost. Show the search taking millions of steps for large budgets. |
Binary Search on Answer |
Range Reduction Search |
The ability to build X alloys is monotonic. If you can build 100, you can build 99. Binary search the range [0, 2 * 10^8]. For each mid, calculate the cost for each machine in $O(\text{Machines} x \text{Compositions})$. |
Draw a number line of possible alloy counts. Mark a "Low" and "High." Pick the middle. If possible, move "Low" to mid. If not, move "High" to mid-1. |
$O(M \cdot C \cdot \log(\text{MaxAlloys})$) |
Draw a box for Binary Search (~30 iterations). Inside, draw a loop for Machines (M) and Compositions (C). Total time is very fast. |
Visualize $O(1)$ extra space but TLE due to linear search. |
Visualize zero extra data structures. Pure $O(1)$ auxiliary space. |
| 2862 |
Maximum Element-Sum of a Complete Subset of Indices |
For every possible "complete subset" (where product of any two indices is a perfect square), calculate the sum of nums. |
Subset Combinatorics Search |
Draw a set of indices. Check all pairs. Show the complexity of identifying valid subsets as the bottleneck. |
Square-Free Part Grouping |
Mathematical Grouping |
An index i and j belong to the same complete subset if their square-free parts are equal (e.g., 12 = 2^2 x 3 and 27 = 3^2 x 3; both share square-free part 3). Find the square-free part of every index and group them. |
Draw a list of indices 1 to N. For each, divide out all perfect square factors. Group indices that have the same remainder. Sum the values of nums within each group and take the max. |
Linear Sieve or Math Scan $O(N)$ |
Draw a line scanning indices. For each i, find its "core" in $O(\text{small})$. Alternatively, iterate all x and all perfect squares k^2 such that x * k^2 <= N. Total is $O(N)$. |
Visualize complex nested lists storing every potential subset. |
Visualize a simple frequency map or array to store the sum for each square-free "core." Space $O(N)$. |
| 2863 |
Maximum Length of Semi-Decreasing Subarrays |
Use nested loops to find all pairs (i, j) where i < j and nums[i] > nums[j]. Calculate the length j - i + 1 and keep the maximum. |
$O(N<\text{sup}>2\text{sup}>)$ Triangle Search |
Draw an array. Draw arrows connecting every element to every subsequent element. Label connections "Valid" if decreasing. Note the N(N-1)/2 connections. |
Monotonic Stack + Two Pointers (Right-to-Left) |
Boundary Anchoring |
Build a monotonic decreasing stack from the left (only push if nums[i] is greater than stack top). Then, scan the array from the right. While the right element is smaller than the stack top, pop the stack and update the max length. |
Draw the array. Circle the "Peaks" (left-to-right increasing elements) to form the stack. Use a finger to move from right-to-left. When your finger points to a value smaller than a peak, draw a bracket from the peak to your finger. |
Linear Scan $O(N)$ |
Draw two parallel lines. Line 1: Left-to-right stack build. Line 2: Right-to-left pointer scan. Each index is touched twice. $O(N)$. |
Visualize $O(1)$ extra space but TLE in execution. |
Visualize a Stack storing indices of "peaks." Memory $O(N)$. |
| 2864 |
Maximum Odd Binary Number |
Generate all possible permutations of the binary string. Convert each to decimal and check if it's odd. Pick the maximum value. |
Permutation Factorial Tree |
Draw a string like "0110". Draw a tree branching for every digit arrangement (4!). Show the search space becoming huge for 100-bit strings. |
Greedy Bit Alignment |
Bit Bucket Sorting |
Count the number of '1's in the string. To make it odd, one '1' *must* be at the last position. To make it maximum, all remaining '1's must be at the very front. Fill the middle with '0's. |
Count the ones (e.g., 3 ones). Draw a line of boxes. Put a '1' in the very last box. Put the other 2 ones in the very first boxes. Fill the gaps with '0'. |
Single Pass Count $O(N)$ |
Draw a line scanning the string once (O(N)) and a line writing the new string (O(N)). Total $O(N)$. |
Visualize $O(N!)$ space if storing all permutations. |
Visualize a single integer counter or a character array. Space $O(N)$. |
| 2865 |
Beautiful Towers I |
For every possible "peak" index i, iterate outwards to calculate the maximum heights possible while maintaining the mountain shape (height[j-1] <= height[j] for left, etc.). |
$O(N<\text{sup}>2\text{sup}>)$ Peak Simulation |
Draw the array. Pick a peak. Draw a mountain shape by trimming neighbors. Repeat for every single element in the array as the potential peak. |
Monotonic Stack + Prefix/Suffix DP |
Mountain Slope Area |
1. Use a monotonic stack to find the nearest smaller element to the left for every index, calculating a running sum leftSum[i]. 2. Repeat for the right to get rightSum[i]. 3. The total height for peak i is leftSum[i] + rightSum[i] - maxHeights[i]. |
Draw a bar chart. For each bar, find the nearest bar to the left that is shorter. Everything between them is "capped" at the current bar's height. Sum these "capped" values using a DP array. |
Three Linear Passes $O(N)$ |
Draw three horizontal arrows. Pass 1: Left DP. Pass 2: Right DP. Pass 3: Maximize sum. All $O(N)$. |
Visualize $O(1)$ auxiliary space but redundant $O(N^2)$ math steps. |
Visualize two DP arrays of size N and a stack. Space $O(N)$. |
| 2866 |
Beautiful Towers II |
(Identical problem to 2865 but with N = 10^5). The $O(N^2)$ brute force will now Time Limit Exceeded (TLE). |
$O(N<\text{sup}>2\text{sup}>)$ Overlap Chart |
Draw a grid 10^5 x 10^5. Shade the area being processed. 10^10 operations is too many for any standard CPU. |
Optimised Monotonic Stack + Dynamic Programming |
Slope Aggregation |
Same logic as 2865: maintain a stack of indices st such that maxHeights[st] is increasing. When processing i, pop elements > maxHeights[i]. The new sum is (i - st.top) * maxHeights[i] + leftSum[st.top]. |
Draw the bars. Use the stack to "flatten" preceding bars that are taller than the current one. The stack allows you to calculate the new total sum in $O(1)$ by referencing the previous DP state. |
Amortized Linear Time $O(N)$ |
Draw a single pass through the array. Although there are while loops inside, each element is pushed and popped from the stack exactly once. |
Visualize memory fragmentation from billions of temporary sum variables. |
Visualize two long DP arrays (e.g., 64-bit integers) and a stack. Space $O(N)$. |
| 2867 |
Count Valid Paths in a Tree |
Generate all possible paths between every pair of nodes (u, v) in the tree. For each path, check if it contains exactly one prime number. |
$O(N<\text{sup}>2\text{sup}>)$ Path Validation |
Draw a tree. Draw a path between every pair of nodes. For each path, check every node against a prime list. Total $O(N^2 \\text{cdot pathLength})$. |
Sieve of Eratosthenes + Disjoint Set Union (DSU) or DFS |
Prime Node Isolation |
1. Sieve to find primes. 2. Remove all prime nodes to find "Islands" of non-prime nodes. 3. For each prime node, find the sizes of its adjacent non-prime islands. 4. Use combinatorics: A valid path either stays in one island + prime, or connects two islands via the prime. |
Draw a tree. Color prime nodes red and non-primes blue. Circle the "blue islands." For each red node, count the blue nodes in each connected neighbor. Multiply and sum the counts to get path totals. |
Linear Tree Traversal $O(N \\text{cdot small factor})$ |
Draw a box for the Sieve (O(N log log N)) and a box for the DFS/DSU (O(N)). Total time is essentially linear. |
Visualize a massive list of all N^2 paths being stored in the heap. |
Visualize a Sieve array, a visited array, and island size counters. Space $O(N)$. |
| 2868 |
The Wording Game |
Recursively simulate every possible move for Alice and Bob, exploring all branches of the word lists to find if a winning strategy exists. |
Minimax Game Tree |
Draw a tree starting with Alice's first word. Each level alternates players. Show branches for every legal next word. The tree depth could be N, leading to exponential paths. |
Greedy Game State Simulation (Two Pointers) |
Linear Turn Simulation |
Since words are sorted and players must pick a word that is lexicographically larger with specific starting char rules, simply track the current "best" word and the current player. Iteratively pick the first valid word from the next player's list. |
Write the two lists side-by-side. Use a "token" to represent the current word. Move the token to the other list by finding the first word that satisfies the "next-char" or "same-char-larger" rule. Stop when no move is possible. |
Linear Scan $O(N + M)$ |
Draw a single line passing through both word lists once. Each word is considered once. Total $O(N+M)$. |
Visualize a massive recursion stack storing string copies of the game state. |
Visualize two pointers (indices) moving through the arrays. Space $O(1)$. |
| 2869 |
Minimum Operations to Collect Elements |
In each operation, remove the last element. After each removal, check the entire "collected" list to see if it contains all numbers from 1 to k. |
$O(N^2)$ Repeated Search |
Draw an array. Draw an arrow removing the last item. Below, draw a "Search" box that scans a set for numbers 1 to k. Show this search happening after every pop. |
Backward Scan + Boolean Frequency Array |
Suffix Checklist Search |
Start from the end of the array. Use a boolean array of size k+1 (or a Set) to mark numbers as you see them if they are <= k. Count unique sightings. Stop when the count reaches k. |
Draw the array. Write numbers 1 to k on a separate "Checklist." Move from right-to-left in the array. Every time you hit a number on your checklist, cross it off. The index where you finish is your answer. |
Single Pass Scan $O(N)$ |
Draw a single straight line from the end of the array moving left. Each check is $O(1)$. Total $O(N)$. |
Visualize a growing "Collection" list and redundant $O(k)$ searches inside a loop. |
Visualize a fixed-size boolean array (size k). Space $O(k)$. |
| 2870 |
Minimum Number of Operations to Make Array Empty |
Try every combination of removing 2 or 3 identical elements. Use backtracking to find the path that empties the array in the fewest steps. |
Greedy vs. Backtracking Tree |
For a count of 10, draw branches for -2 and -3. Show the tree searching for the shortest path to 0. |
Frequency Counting + Greedy Math |
Remainder Pattern Mapping |
Count frequencies of all numbers. For each frequency f: if f=1, return -1. Otherwise, the number of operations is ceil(f / 3). This handles cases like 4 (2+2) and 5 (3+2) optimally. |
List the unique numbers and their counts. For each count, try to divide by 3. If there's a remainder of 1 or 2, you just need one extra step (e.g., 7 is 3+2+2, 3 steps). Total the steps. |
Linear Pass + Hash Map $O(N)$ |
Draw a box for counting frequencies $O(N)$ and a tiny box for the math $O(\text{Unique Elements})$. Total $O(N)$. |
Visualize an exponential search tree for each unique number's count. |
Visualize a Hash Map or Frequency Array. Space $O(N)$. |
| 2871 |
Split Array Into Maximum Number of Subarrays |
Try every possible way to partition the array into subarrays, calculating the Bitwise AND of each and checking if the sum of these ANDs is minimized. |
$O(2<\text{sup}>N\text{sup}>)$ Partition Combinatorics |
Draw the array with "Divider" slots between numbers. Show 2^N-1 ways to place dividers. For each, calculate the AND-Sum. |
Greedy AND-Reset Logic |
Bitwise Minimal Segmenting |
The minimum possible score is the AND of the whole array. If that score is >0, the max subarrays is 1. If it's 0, greedily close a subarray as soon as its AND becomes 0, then start a new one. |
Write the numbers. Keep a "Current AND" variable starting at the first number. Move right, ANDing each number. As soon as the result hits 0, draw a vertical line (split) and reset the AND to the next number. |
Single Pass $O(N)$ |
Draw a straight line through the array. Each bitwise operation is $O(1)$. Total $O(N)$. |
Visualize the heap clogging with all possible partition results. |
Visualize one integer variable (the running AND). Space $O(1)$. |
| 2872 |
Maximum Number of K-Divisible Components |
Try removing every possible set of edges in the tree. For each set, check if all resulting components have a sum divisible by k. |
$O(2<\text{sup}>N\text{sup}>)$ Edge Deletion Search |
Draw a tree with N-1 edges. Each edge is a "Cut" or "Keep" decision. Show the 2^N-1 tree configurations. |
Post-Order Traversal (Bottom-Up Summing) |
Recursive Greedy Cutting |
DFS from the root. For each node, calculate the sum of its subtree. If a subtree sum is divisible by k, it *can* be cut off to form a valid component. Return sum % k to the parent. |
Draw the tree. Starting at the leaves, write their values. Move up to parents, adding the leaf values. If a node's total sum is a multiple of k, draw a "Scissor" icon on the edge above it and don't pass that sum up. |
Single DFS Pass $O(N)$ |
Draw a single line tracing the tree (Euler Tour). Each node and edge is visited once. Total $O(N)$. |
Visualize thousands of temporary graph objects representing different partitions. |
Visualize the recursion stack and an adjacency list. Space $O(N)$. |
| 2873 |
Maximum Value of an Ordered Triplet I |
Use three nested loops: for i, for j > i, for k > j. Calculate (nums[i] - nums[j]) * nums[k] for every possible triplet and track the maximum. |
$O(N<\text{sup}>3\text{sup}>)$ Nested Cube |
Draw a 3D grid or a series of nested brackets. Show that for an array of size N, the number of triplets is N(N-1)(N-2)/6, leading to cubic growth. |
Prefix Maximum & Suffix Maximum (or Pre-calculation) |
Boundary Extremes Tracking |
To maximize (nums[i] - nums[j]) * nums[k], for a fixed j, we need the largest nums[i] to its left and the largest nums[k] to its right. Precompute prefixMax and suffixMax. |
Draw the array. Above it, write the max seen from the left. Below it, write the max seen from the right. For each index j, subtract nums[j] from the value above its left neighbor and multiply by the value below its right neighbor. |
Linear Pass $O(N)$ |
Draw three horizontal lines. Pass 1: Compute Left Max. Pass 2: Compute Right Max. Pass 3: One scan to find the max triplet value. All $O(N)$. |
Visualize $O(1)$ auxiliary space but massive time wastage. |
Visualize two arrays of size N to store precomputed maximums. Space $O(N)$. |
| 2874 |
Maximum Value of an Ordered Triplet II |
(Identical problem to 2873 but with N = 10^5). The $O(N^3)$ brute force will now Time Limit Exceeded (TLE). |
$O(N<\text{sup}>3\text{sup}>)$ Volume Scan |
Draw a cube labeled 10^5 on each side. Note that 10^15 operations would take years on a standard PC. |
Dynamic Prefix Maximum & Max-Difference Tracking |
Incremental State Update |
Maintain two variables while scanning: max_val (max nums[i] seen so far) and max_diff (max nums[i] - nums[j] seen so far). At each step k, the potential triplet value is max_diff * nums[k]. |
Write the numbers. Carry two "Running Max" boxes. As you move to the next number, update the "Max Single" box. Use that to update the "Max Difference" box (Single - Current). Use that to calculate the final answer. |
Single Pass $O(N)$ |
Draw one straight line through the array. Each step is $O(1)$ logic with no precomputed arrays needed. Total $O(N)$. |
Visualize memory thrashing if trying to store intermediate results in lists. |
Visualize exactly three variables (registers). Absolute $O(1)$ auxiliary space. |
| 2875 |
Minimum Size Subarray in Infinite Array |
Concatenate the array with itself many times to simulate the "infinite" nature, then use a sliding window to find the target sum. |
$O(\text{Target} × N)$ Multi-Array Scan |
Draw the array repeating forever. Draw a window trying to find the target. Show the window potentially crossing thousands of array copies. |
Modulo Math + Sliding Window on Doubled Array |
Infinite Expansion Logic |
1. Calculate totalSum of the array. The number of full arrays needed is target / totalSum. 2. The remaining target % totalSum must be found as a subarray in nums + nums (to handle wrap-around). 3. Use standard sliding window/HashMap. |
Draw the array twice: `[A, B, C, A, B, C]`. Calculate how many "Whole Cycles" of the array fit in the target. Then, use two pointers to find the shortest "Fragment" that sums to the remainder. |
Linear Scan $O(N)$ |
Draw a box for the sum $O(N)$ and a pass for the sliding window $O(2N)$. Total $O(N)$. |
Visualize the heap exploding if you actually try to create an "infinite" array in memory. |
Visualize a single doubled array (size 2N) or just use modulo indexing. Space $O(1)$ or $O(N)$. |
| 2876 |
Count Visited Nodes in a Directed Graph |
For every node i, start a traversal (DFS/BFS) and follow the single outgoing edge until you hit a node you've already visited in that specific path. |
$O(N<\text{sup}>2\text{sup}>)$ Path Traversal |
Draw N nodes. From each node, draw a long chain of arrows. Show that you might traverse the same long paths thousands of times. |
Functional Graph Decomposition (Cycles & Tails) |
Cycle-Base Detection |
In a graph where each node has exactly one outgoing edge, every component consists of a cycle with some trees (tails) rooted on the cycle. Find cycles using 2-pointers (Floyd's) or DFS. All nodes in a cycle have a visit count equal to cycle length. Tail nodes = distance to cycle + cycle length. |
Draw a "Lollipop" shape (a circle with a stick). Any node on the circle gets a number equal to the circle's size. Any node on the stick gets that number plus its distance from the circle. |
Linear Component Scan $O(N)$ |
Draw two passes. Pass 1: Detect cycles and their sizes. Pass 2: Calculate distances for "tail" nodes using memoization/DP. Total $O(N)$. |
Visualize a deep recursion stack that could cause a stack overflow for large linear chains. |
Visualize three arrays of size N: visited, distance, and result. Space $O(N)$. |
| 2877 |
Create a DataFrame from List (Pandas) |
Manually iterate through the 2D list and create a dictionary for each row, then convert that list of dictionaries into a table-like structure. |
Row-by-Row Object Creation |
Draw a 2D grid of data. Draw arrows converting each row into a `{key: value}` pair. Show the overhead of creating N dictionary objects. |
Native Pandas Constructor (Vectorized Internal Logic) |
Columnar Data Storage |
Pass the 2D list and a list of column names directly into pd.DataFrame(data, columns=['name', 'age']). Pandas handles the memory allocation and alignment efficiently in C/Cython. |
Draw a 2D list of values. Draw a single large "Constructor" box that takes the list and outputs a structured table with headers. |
Linear Construction $O(N \cdot M)$ |
Draw a single pass that moves data from the list into the DataFrame's internal block manager. Total time $O(\text{Total Elements})$. |
Visualize N small dictionary objects scattered in memory. |
Visualize a single contiguous block of memory managed by Pandas/NumPy. |
| 2878 |
Get the Size of a DataFrame |
Iterate through the rows to get the row count, then iterate through the first row's keys to get the column count. |
Iterative Counter Diagram |
Draw a table and tally each row one by one. Write "N" for rows and "M" for columns. |
df.shape Attribute Access |
Direct Metadata Access |
Visualize a "Header" block attached to the DataFrame that already contains the integers (Rows, Columns). No traversal is needed. |
Draw a box labeled "Metadata" with two slots: [R] and [C]. Point an arrow from the DataFrame to these slots. |
Constant Time $O(1)$ |
Draw a single dot. No matter how large the table, the size is stored in a fixed location. |
$O(N\cdot M)$ - Accessing all elements to count. |
$O(1)$ - Accessing a small tuple. |
| 2879 |
Display the First Three Rows |
Iterate from index 0 to 2, copy each row manually into a new list or structure. |
Row-by-Row Copy Trace |
Draw the first three rows of a table being moved into a separate smaller box. |
df.head(3) (Slicing) |
Buffer Slicing |
Visualize a "window" that only looks at the first three indices of the underlying memory buffer. |
Draw a vertical list of numbers. Draw a small bracket around the top 3 items. |
Constant Time $O(1)$ in terms of metadata/view creation. |
Draw a horizontal line with a short segment at the start marked "Slice". |
$O(N\cdot M)$ if copying the whole structure. |
$O(1)$ (View) or $O(3\cdot M)$ (Copy). |
| 2880 |
Select Data (Filtering) |
Loop through every row, check the value of the 'id' column, and if it matches 101, add that row to a result list. |
Linear Scan Search |
Draw a magnifying glass moving down a column until it finds "101". |
Boolean Indexing: df[df['id'] == 101] |
Masking Overlay |
Imagine a "Stencil" (Boolean Mask) placed over the table where only the row with 101 is "cut out" and visible. |
Draw a table. Draw a column of "True/False" next to it. Draw an arrow showing only "True" rows passing through a filter. |
Linear $O(N)$ |
Draw a straight line y=x representing one check per row. |
$O(N)$ for intermediate boolean mask array. |
$O(N)$ Vectorized processing in C. |
| 2881 |
Create a New Column |
Iterate through the DataFrame row by row using a loop, calculate salary * 2, and append it to a new list, then assign the list to a new column. |
Row-wise Iteration Pipeline |
Draw a column being built one cell at a time by looking at a neighbor cell. |
Vectorized Assignment: df['bonus'] = df['salary'] * 2 |
SIMD (Single Instruction Multiple Data) |
Visualize a "multi-lane highway" where the multiplication operation is applied to the entire column simultaneously. |
Draw two vertical parallel bars. Draw many horizontal arrows across at once representing the multiplication. |
Linear $O(N)$ (Vectorized) |
Draw a line with a fast slope, indicating highly efficient low-level loops. |
$O(N)$ for a Python list overhead. |
$O(N)$ but stored in a contiguous NumPy array block. |
| 2882 |
Drop Duplicate Rows |
Keep a set of "seen" IDs. Loop through the data; if an ID is in the set, delete that row; otherwise, add it to the set. |
Hash Set Comparison |
Draw a table and a separate "trash bin". For each row, check the set, and move duplicates to the bin. |
df.drop_duplicates(subset=['id']) |
Unique Mapping |
Visualize a "sieve" that only allows the first occurrence of a unique key to fall through to the final table. |
Draw several duplicate items. Draw a "Filter" box. Show only one of each item coming out the other side. |
$O(N)$ using Hash-based detection. |
Draw a sorting-then-scanning line or a hash-building line. |
$O(N)$ for storing the Hash Set. |
$O(N)$ Optimized in-place or new buffer. |
| 2883 |
Drop Missing Data |
Iterate through every row. Check the 'name' column for None or NaN. If found, manually delete that row index from the structure. |
Row-Scan Flagging |
Draw a table. Mark 'X' next to rows where the name is missing. Draw a new table without those 'X' rows. |
df.dropna(subset=['name']) |
Row Masking |
Visualize a "Scanner" passing over a column. When it hits a "hole" (Null), it triggers a signal to ignore that entire row's memory address. |
Draw a grid. Draw a red circle around empty cells. Draw an arrow showing only the "Solid" (non-empty) rows passing through a filter. |
Linear $O(N)$ |
Draw a single straight line. The time spent is exactly proportional to the number of rows checked. |
$O(N)$ - Storing a list of indices to drop. |
$O(N)$ - Highly optimized C-level masking. |
| 2884 |
Modify Columns |
Use a for loop to iterate through the indices of the 'salary' column, multiply each value by 2, and update the cell directly. |
Element-wise Iteration |
Draw a column of numbers. Draw a small "x 2" box next to every single cell. |
df['salary'] *= 2 (Vectorized Math) |
Columnar Transformation |
Visualize the entire 'salary' column being fed into a "Math Block" that outputs a doubled column in one swift motion. |
Draw one vertical rectangle. Draw a broad arrow pointing to a second vertical rectangle of the same size, labeled "Double". |
Linear $O(N)$ (Vectorized) |
Draw a very shallow line, indicating that while it's $O(N)$, the constant factor is tiny due to hardware acceleration. |
$O(N)$ for Python object overhead in the loop. |
$O(N)$ using contiguous memory blocks (NumPy arrays). |
| 2885 |
Rename Columns |
Create a brand new DataFrame. While copying data, manually assign the new names to the header of the new structure. |
Structure Reconstruction |
Draw an old table and a new table. Draw arrows moving data from "id" to "student_id", "first" to "first_name", etc. |
df.rename(columns={...}) |
Metadata Relabeling |
Visualize the underlying data staying exactly where it is. Only the "Label" attached to the top of the column is swapped out. |
Draw a column. Erase the name "A" at the top and write "B" over it. The data below doesn't move. |
$O(M)$ where M is the number of columns renamed. |
Draw a few dots (one per column name). It doesn't matter how many rows exist (N); only columns (M) matter. |
$O(N\cdot M)$ - Creating a full copy of the data. |
$O(1)$ - If done in-place, or $O(M)$ for the label mapping. |
| 2886 |
Change Data Type |
Iterate through the 'grade' column. For each value, call int(value) and put it back into the DataFrame. |
Type-Casting Loop |
Draw a column of floats (e.g., 85.0). Draw a "Caster" box that chops off the decimal for each row. |
df['grade'].astype(int) |
Memory Buffer Reinterpretation |
Visualize the memory block changing from "Wide" (Float64) to "Narrow" (Int32) representation. |
Draw a sequence of wide boxes. Draw a "Squeezer" that turns them into narrow, solid boxes. |
Linear $O(N)$ |
Draw a straight line y=x. Every element must be converted. |
$O(N)$ - Storing temporary Python integer objects. |
$O(N)$ - One-time allocation of a new typed array. |
| 2887 |
Fill Missing Data |
Scan the 'quantity' column. If a cell is null, look up the default value and write it into that cell manually. |
Conditional Iteration |
Draw a table with gaps. Draw a "Fill" bucket. Draw arrows pouring the bucket into the gaps. |
df['quantity'].fillna(0) |
Imputation Masking |
Visualize a "0" constant being broadcasted only into the indices where the "Null Mask" is True. |
Draw a grid with holes. Draw a layer of "0"s behind the grid. The "0"s only show through where there are holes. |
Linear $O(N)$ |
Draw a straight line. Every row is checked for nullity once. |
$O(N)$ - Iterating via Python is slow and memory-heavy. |
$O(N)$ - Efficiently handled via bitmasks in C. |
| 2888 |
Reshape Data: Concatenate |
Create a new list. Loop through all rows of df1 and append them, then loop through df2 and append them. Convert the final list back to a DataFrame. |
Sequential Row Copying |
Draw two separate boxes. Draw a third long box and show arrows moving rows from the first two into the third, one by one. |
pd.concat([df1, df2]) |
Vertical Stacking |
Visualize two memory blocks being "glued" together vertically. The column headers are aligned, and df2 is simply appended to the end of df1's address space. |
Draw two rectangles. Draw a "Plus" sign between them. Draw a single long rectangle as the result. |
Linear $O(N + M)$ |
Draw two line segments end-to-end. The total length is the sum of both table lengths. |
$O(N + M)$ - Storing every row in a Python list before conversion. |
$O(N + M)$ - One-shot block allocation in memory. |
| 2889 |
Reshape Data: Pivot |
Create a dictionary where keys are "month" and values are "city". Manually iterate through the original data and populate the dictionary to build a wide-format table. |
Manual Data Restructuring |
Draw a long table. Draw a new square grid. For every row in the long table, find its "Coordinates" (City, Month) in the square grid and write the value. |
df.pivot(index='month', columns='city', values='temperature') |
Pivot Table Transformation |
Visualize a single column (e.g., 'city') "rotating" 90 degrees to become headers, while the values "unfold" to fill the newly created intersections. |
Draw a 3-column table. Draw an arrow to a wide 2D grid. Show how the unique values of one column become the new column names. |
$O(N)$ - Linear pass to distribute values. |
Draw a line. Every row is touched once to be placed in its new (row, col) slot. |
$O(N)$ - High overhead due to dictionary nested structures. |
$O(N)$ - Optimized sparse-to-dense memory mapping. |
| 2890 |
Reshape Data: Melt |
Iterate through each wide row. For every column (Quarter), create a new row entry containing the Quarter name and the corresponding value. |
Column Unrolling |
Draw a wide row with 4 quarter columns. Draw 4 narrow rows. Show an arrow from the wide row generating 4 distinct narrow rows. |
df.melt(id_vars=['product'], ...) |
Data Melting |
Visualize a wide table being "liquefied" and poured into a long, thin vertical container. Column names become values in a new 'variable' column. |
Draw a wide horizontal rectangle. Draw a vertical downward arrow. Draw a long, thin vertical rectangle. |
$O(N \cdot C)$ where C is number of columns. |
Draw a line that gets longer as you add more columns to "unroll." Total work is the size of the final long table. |
$O(N \cdot C)$ - Massive object creation in Python loops. |
$O(N \cdot C)$ - Vectorized expansion in C. |
| 2891 |
Method Chaining |
Step 1: Filter the data and save to temp_df. Step 2: Sort temp_df and save to temp_df2. Step 3: Select columns from temp_df2. |
Intermediate State Pipeline |
Draw a sequence of tables with arrows between them. Each arrow represents a full stop and save operation. |
Chained Operations: df.loc[...].sort_values(...)[['name']] |
Fluid Processing Pipeline |
Visualize a "Stream" of data passing through various filters and sorters without ever stopping to be stored as a named variable until the very end. |
Draw a pipe with different filters (shapes) inside. Data goes in one end and the final result comes out the other. |
Combined $O(N \log N)$ |
Draw the bottleneck (Sorting) as the main slope. Chained filtering is just a linear subtraction before the sort. |
$O(N \\text{cdot Steps})$ - Multiple copies of the data are stored in temp variables. |
$O(N)$ - Often allows Pandas to optimize memory by avoiding full copies between steps. |
| 2892 |
Minimizing Array After Replacing Pairs With Their Product |
Try multiplying every possible adjacent pair using backtracking to find the sequence that yields the shortest array. $O(2^N)$. |
Recursive Array Collapse |
Draw the array. Pick a pair, multiply, branch. Pick a different pair, multiply, branch. Track the shortest branch. |
Greedy Array Compression |
The Running-Product Accumulator |
Iterate linearly. Maintain a `current_product`. If `current_product * nums[i] <= k`, update the product (they fuse). Otherwise, the fusion breaks; reset `current_product = nums[i]` and increment the final array length counter. |
Draw the numbers. Roll a snowball left to right. As it rolls over a number, multiply it. If the snowball gets bigger than k, it shatters. Start rolling a new snowball and add 1 to your count. |
Single Linear Scan $O(N)$ |
Draw a single straight line. Each element undergoes one $O(1)$ multiplication and comparison. |
Storing thousands of array variations. |
A single `current_product` variable. $O(1)$ space. |
| 2893 |
Calculate Orders Within Each Interval |
Iterate through all orders and for each order, check which time interval it falls into by comparing against a list of interval boundaries. |
Sequential Boundary Check |
Draw a list of intervals. For every single order, draw a "Search" arrow that tests every interval until it finds a match. |
Mathematical Binning (Floor Division) |
Fixed-Width Histogram |
Divide each order's timestamp by the interval length and use the floor result as a key in a frequency map or an index in a result array. |
Draw a timeline. Mark segments of 6 (e.g., 0-5, 6-11). For any number X, write the formula lfloor X/6 rfloor to show it maps directly to a segment index. |
Linear $O(N)$ |
Draw a straight line. Every order is processed in a single math operation without searching. |
$O(I)$ where I is intervals if using a search tree. |
$O(N/I)$ - Memory corresponds only to the number of resulting buckets. |
| 2894 |
Divisible and Non-divisible Sums Difference |
Iterate through every integer from 1 to n. Check if it's divisible by m. If yes, add to num2; if no, add to num1. Subtract at the end. |
$O(N)$ Iteration Loop |
Draw a sequence of numbers from 1 to N. Below each, write "Yes" or "No" for divisibility. Add up the two groups separately. |
Arithmetic Progression (AP) Formula |
Summation Formula |
Calculate the total sum of 1 to n using n(n+1)/2. Calculate the sum of multiples of m using the same formula scaled by m. The difference is derived purely from these totals. |
Draw two large blocks. Block A is the sum of all numbers. Block B is the sum of only multiples of m. Write the formula m x (k(k+1)/2) where k = n/m. |
Constant Time $O(1)$ |
Draw a single dot. The calculation is independent of the size of n. |
$O(1)$ - No extra structures, but $O(n)$ time. |
$O(1)$ - No extra structures and near-zero time. |
| 2895 |
Minimum Processing Time |
Try all possible assignments of tasks to processors using recursion/backtracking to find the one that minimizes the finish time. |
$O(N!)$ Permutation Tree |
Draw 4 processors and 16 tasks. Draw branches showing every possible way to give 4 tasks to each processor. |
Greedy (Dual Sorting) |
Opposite Sorting Alignment |
Sort processors in ascending order. Sort tasks in descending order. Pair the earliest processor with the 4 longest tasks. The finish time is max(processor[i] + task[i*4]). |
Draw a list of small numbers (Processors) and a list of large numbers (Tasks). Pair the smallest P with the largest T to "level out" the workload. |
$O(N \log N)$ |
Draw a sorting-slope. The time taken is dominated by the initial sort of both arrays. |
$O(N!)$ - Storing every permutation in memory. |
$O(N)$ - Storing only the sorted arrays. |
| 2896 |
Apply Operations to Make Two Strings Equal |
Recursively try flipping every possible pair of indices or every adjacent pair to match the strings, exploring all paths to find the minimum cost. |
Recursive Search with Overlap |
Draw two strings. Branch out for every possible index pair you could flip. Show how the same string state is reached via different flip orders. |
1D Dynamic Programming (Memoization) |
Cost-Minimization State Table |
Identify indices where the strings differ. Let dp[i] be the min cost to fix the first i differences. At each step, choose between fixing the current one with the next one (cost: distance) or with a "free" remote pair (cost: x/2). |
List the indices where s1[i]
eq s2[i]. Draw a line of boxes (DP table). For each box, look at the previous box and the one two steps back to decide the cheapest "bridge." |
Linear $O(N)$ |
Draw a straight line. After identifying the D differences, the DP takes $O(D)$ time. |
$O(2^N)$ - Massive recursion depth. |
$O(N)$ - One DP array and a list of mismatch indices. |
| 2897 |
Apply Operations on Array to Maximize Sum of Squares |
Randomly pick pairs of numbers (i, j) and apply the operation (nums[i] AND nums[j], nums[i] OR nums[j]) repeatedly to see if the sum of squares increases. |
Stochastic Simulation |
Draw two numbers. Show bits moving from one to the other. Repeat this for thousands of random pairs without a clear termination. |
Bit-Counting + Greedy Reconstruction |
Bit-Vertical Stacking |
Count the total occurrences of each bit (0-30) across all numbers. To maximize the sum of squares, "push" as many bits as possible into the same numbers to create the largest possible values (since 10^2 + 2^2 > 6^2 + 6^2). |
Draw 30 buckets (one for each bit power). Toss every number's bits into their respective buckets. Then, build the first number by taking one bit from every non-empty bucket. Repeat for k numbers. |
Linear $O(N)$ |
Draw a line. Scan all numbers to fill bit-counters (O(31N)), then reconstruct k numbers (O(31k)). |
$O(N)$ - Storing the history of operations. |
$O(1)$ - Using only a fixed-size array of 31 integers to store bit counts. |
| 2898 |
Maximum Linear Stock Score |
For every index i, try to find all other indices j such that the stock prices form a linear sequence (price difference equals index difference). |
$O(N^2)$ Pairwise Validation |
Draw a stock chart. For every point, draw lines to every other point to check if the slope is exactly 1. |
Frequency Mapping (Coordinate Transformation) |
Slope-Intercept Grouping |
Rewrite the condition price[j] - price[i] = j - i as price[j] - j = price[i] - i. Calculate K = price[i] - i for every element and sum values with the same K. |
Draw a table with columns: Index, Price, and (Price - Index). Group all rows that have the same (Price - Index) value and sum their prices. |
Linear $O(N)$ |
Draw a single straight line. One pass to compute the key, one pass to update the hash map. |
$O(1)$ - If using nested loops. |
$O(N)$ - To store the sums in a Hash Map. |
| 2899 |
Last Visited Integers |
For every "prev" string encountered, manually iterate backwards through the entire history array to find the k-th integer, ignoring previous "prev" strings. |
$O(N^2)$ Backward Search |
Draw a sequence of inputs. For every "prev", draw an arrow scanning backwards through all preceding boxes. |
List Maintenance + Pointer Tracking |
Two-Pointer History Buffer |
Keep a separate list of integers seen so far. Track a variable `k` that resets when a number is seen and increments when "prev" is seen. Access `seen_list[len - k]`. |
Draw a "Seen" box. When a number arrives, put it in the box and set k=0. When "prev" arrives, increment k and point to the k-th item from the end of the box. |
Linear $O(N)$ |
Draw a straight line. Each input is processed in constant time using index math. |
$O(N)$ - Storing history. |
$O(N)$ - Storing the list of integers. |
| 2900 |
Longest Unequal Adjacent Groups Subsequence I |
Generate all possible subsequences of the strings, and for each, check if adjacent group IDs are unequal. Track the longest. |
$O(2^N)$ Subsequence Tree |
Draw a binary tree of choices (include/exclude) for each string. Mark paths that satisfy the unequal condition. |
Greedy Alternation |
One-Pass Toggle Match |
Iterate through the array. Keep a "last_group" variable. If the current group ID is different from "last_group", add the string to the result and update "last_group". |
Draw the list of IDs. Whenever the number changes (0 to 1 or 1 to 0), circle the corresponding string. |
Linear $O(N)$ |
Draw a single horizontal line. Every element is checked exactly once. |
$O(N)$ - Storing subsequences. |
$O(N)$ - Only storing the result strings. |
| 2901 |
Longest Unequal Adjacent Groups Subsequence II |
Check all combinations of strings to find the longest chain where adjacent strings have the same length, Hamming distance of 1, and different group IDs. |
$O(2^N)$ Complex Subsequence |
Draw a graph where strings are nodes and valid jumps are edges. Find the longest path in this Directed Acyclic Graph. |
Dynamic Programming (LIS Variation) |
State-Space Pathfinding |
Let `dp[i]` be the length of the longest valid subsequence ending at index i. For each i, look at all j < i and update if all three conditions (length, Hamming, group) are met. |
Draw a grid with N boxes. For each box, draw arrows from all previous valid boxes. Write the length of the longest path in each box. |
$O(N^2 \cdot L)$ where L is string length. |
Draw a triangular nested loop area. For each pair of indices, perform a string comparison of length L. |
$O(N^2)$ - For the graph or DP table. |
$O(N)$ - To store DP values and parent pointers for path reconstruction. |
| 2902 |
Count of Sub-Multisets With Bounded Sum |
Generate every possible sub-multiset (combination of elements considering frequencies) and calculate their sums. Count those within [L, R]. |
$O(2^N)$ Combinatorial Scan |
Draw a tree of choices where branches represent taking 0, 1, 2... F copies of a number. |
DP with Frequency Map + Sliding Window Optimization |
Generating Functions / Knapsack with Optimization |
This is a bounded knapsack problem. Use a frequency map. For each unique value, update the DP table using a sliding window to keep the complexity to $O(\text{Sum})$. |
Draw a DP array representing possible sums. For each unique number, use a "Sliding Window Sum" to update the counts without re-calculating from scratch. |
$O(\text{Sum} \\text{cdot sqrt}(N)$) or $O(\text{Unique} \\text{cdot Sum})$ |
Draw a grid representing (Unique Elements) by (Total Sum). Shaded area represents the DP updates. |
$O(2^N)$ - Infeasible. |
$O(\text{Sum})$ - Using a rolling 1D DP array. |
| 2903 |
Find Indices With Index and Value Difference I |
Nested for-loops comparing every index pair (i, j). |
Upper Triangular Matrix |
Draw an N x N grid. Put an 'X' in cells where i < j and distance conditions meet. Shows N^2/2 checks. |
Two Pointers / Tracking Min & Max limits |
Variable Line Trackers |
Move an 'i' pointer forward. Maintain a 'j' pointer (i - indexDifference). Update running min/max of elements up to j. |
Draw a 1D array. Put a vertical dashed line separating the "eligible past" (indices <= i-diff) from the present 'i'. |
Single Horizontal Axis Traverse |
Draw a single straight line from 0 to N. Annotate constant $O(1)$ operations at each step. T(N) = N * $O(1)$ = $O(N)$. |
Two integer boxes for nested loop counters (i, j). $O(1)$ space. |
Four integer boxes: `min_val`, `max_val`, `min_idx`, `max_idx` dynamically updating. $O(1)$ space. |
| 2904 |
Shortest and Lexicographically Smallest Beautiful String |
Generate all substrings, filter for 'k' ones, sort by length then lexicographically. |
Inverted Pyramid of Substrings |
Draw a pyramid: N blocks top row (len 1), N-1 blocks second row (len 2)... summing to N(N+1)/2 substrings. |
Sliding Window |
Expanding/Contracting Bracket `[ ]` |
Place [ ] at index 0. Expand `]` until `1`s count == k. Then shrink `[` to minimize length while keeping `1`s count == k. |
Write out the binary string. Draw a physical bracket around a subset. Tally the '1's above the bracket. |
Two Independent Linear Timelines |
Draw two parallel tracks for Left and Right pointers. Both move forward maximum N times. $O(2N)$ -> $O(N)$. |
List of Strings: Draw a large list block containing N^2 allocated string variables in memory. $O(N^2)$ space. |
Three Scalar Variables: Draw boxes for `left_ptr`, `right_ptr`, and `ones_count`. $O(1)$ aux space (excluding output). |
| 2905 |
Find Indices With Index and Value Difference II |
Nested for-loops comparing every pair (i, j). (Will TLE here due to constraints). |
Upper Triangular Matrix |
Draw a massive N x N grid (N=10^5) and shade it red to signify Time Limit Exceeded (N^2 ops). |
Two Pointers + Prefix Min/Max Tracking |
Separated Window pointers |
Identical to 2903, but visually emphasize that prefix min/max are tracked *strictly* at index `i - indexDiff`. |
Draw array. Circle the element at `i`. Circle elements from `0` to `i-diff`, drawing a funnel combining them into a `min_val` box. |
Single Horizontal Axis Traverse |
Write T(N) = N. Draw one loop timeline. Show that looking up the max/min of the valid window is $O(1)$. |
Standard nested loop counters. |
Standalone register boxes: `min_val`, `max_val`, `min_id`, `max_id`. Space strictly $O(1)$. |
| 2906 |
Construct Product Matrix |
For every cell, loop through the entire matrix again to multiply all other elements, applying modulo. |
Star/Hub-and-Spoke Mapping |
Draw a 3x3 grid. Pick one target cell. Draw 8 arrows originating from all other cells pointing into the target. Represents $O((N\cdot M)$^2). |
Prefix & Suffix Products (Flattened 2D to 1D) |
Forward & Backward Sweeping Arrays |
Sweep top-left to bottom-right saving running products. Sweep backwards saving running products. Multiply intersecting prefix and suffix. |
Draw a single flattened array. Draw one arrow sweeping left-to-right (Prefix), and another right-to-left (Suffix). |
Two Parallel Timelines |
Draw two parallel straight lines of length N*M. T(N,M) = 2*(N*M) = $O(N\cdot M)$. Constant time cell multiplication. |
Single scalar box for the running product accumulator. Space $O(1)$. |
Two large 1D array blocks (prefix/suffix) sized N*M. Space $O(N\cdot M)$. |
| 2907 |
Maximum Profitable Triplets With Increasing Prices I |
Three nested loops to test every combination of i < j < k ensuring prices increase. |
3D Cubic Grid |
Draw an isometric cube showing X(i), Y(j), Z(k) axes. Represents $O(N^3)$ combinations checked. |
Middle Element Fix + Left/Right Max Search |
Center Pivot with Left/Right Scanners |
Fix 'j'. Scan all elements to the left for max profit where price < price[j]. Scan all right for max profit where price > price[j]. |
Draw array. Circle a middle element `j`. Draw a left-pointing cone to find max valid `i`, and right-pointing cone for valid `k`. |
N independent $O(N)$ tasks |
Draw a horizontal timeline of length N. Under each point, draw a vertical line of length N. Area = $O(N^2)$. |
Three scalar boxes for loop variables i, j, k. Space $O(1)$. |
Standard variables. $O(1)$ space if re-scanning, $O(N)$ if using Fenwick Trees (for harder constraints). |
| 2908 |
Minimum Sum of Mountain Triplets I |
Three nested loops checking all triplets for the `i < j > k` mountain condition. |
Overlapping Triangles |
Draw three points forming a mountain peak. Draw multiple nested instances representing N^3 checks. |
Prefix Min & Suffix Min Arrays |
Valley & Peak Overlays |
Precalculate the minimums from the left up to `i`, and minimums from the right up to `i`. Check if current `j` forms a peak over both. |
Draw original array. Below it, draw LeftMin array (values drop or stay flat). Below that, RightMin array. Stack them to visually compare. |
Three Sequential Passes |
Draw 3 distinct, non-overlapping straight horizontal lines. Time = $O(N)$ + $O(N)$ + $O(N)$ = $O(N)$. |
Three integer variables for loops. Space $O(1)$. |
Two linear 1D arrays (`left_min`, `right_min`) alongside the input. Space $O(N)$. |
| 2909 |
Minimum Sum of Mountain Triplets II |
Nested for-loops checking every combination (TLE due to 10^5 constraints). |
3D Cubic Grid |
Draw a massive cube (N=10^5) shaded red to indicate Time Limit Exceeded (N^3). |
Prefix Min & Suffix Min Arrays (Identical to 2908) |
Valley & Peak Overlays |
Same as 2908: Maintain minimums on both sides of the pivot element to avoid redundant scanning. |
Draw array. Circle `j`. Draw arrows from the precomputed `left_min[j-1]` and `right_min[j+1]` pointing up to `j` to form a mountain. |
Linear Sweep Timeline |
Draw 3 non-overlapping line segments of length N. Equation: T(N) = 3N. $O(N)$. |
Loop counters. |
Two 1D Arrays of size N. Space $O(N)$. Show memory blocks sitting side-by-side. |
| 2910 |
Minimum Number of Groups to Create a Valid Assignment |
Try dividing the array into group sizes 1, then 2, then 3... up to N, validating frequencies each time. |
Iterative Division Blocks |
Draw the whole array. Under it, draw it split into 1s, then 2s, etc., representing N iterations over N items (O(N^2)). |
Hash Map Frequencies + Greedy Math Downward Search |
Histogram Frequency Buckets |
Count frequencies. Find the smallest frequency `min_f`. Try group sizes `s` from `min_f` down to 1. Use division/modulo to verify valid groupings. |
Draw a bar chart of frequencies. Draw a horizontal line `s` moving down from the shortest bar. Calculate splits above the line. |
Shrinking Range Search |
Draw a line of length N (counting). Then a short line of length min_freq. T(N) = $O(N)$ + $O(\text{min}_\text{freq} \\text{cdot unique}_\text{nums})$ ≈ $O(N)$. |
Multiple temporary arrays to hold partitioned elements. Space $O(N)$. |
Key-Value Map visual: Draw a two-column table (Number -> Frequency). Space $O(\text{Unique Numbers})$. |
| 2911 |
Minimum Changes to Make K Semi-palindromes |
Generate all combinations of k partitions. For each, test all divisors to find minimum changes. |
Exploding N-ary Recursion Tree |
Draw a massive tree where each node represents a string split, branching $O(N)$ times to a depth of K, causing combinatorial explosion. |
Precomputation + 2D Partition Dynamic Programming |
2D DP Grid mapping String Index to Partitions |
Precompute costs for all substrings. On a 2D grid, compute min cost to partition first 'i' characters into 'j' parts by looking at costs of part(m, i) + dp[m][j-1]. |
Draw a grid. X-axis: Parts (1 to K). Y-axis: String length (1 to N). Draw arrows from previous column's rows to the current cell adding precomputed transition costs. |
Cubic Cost Grid Traversal |
Write T(N) = N^3 (precomputation) + N^2 * K (DP). Draw three nested squares representing N^3. Space is N^2. |
Huge Call Stack: Stacked vertical boxes up to N deep holding massive string slices. Space $O(N^2)$. |
Two 2D Matrices: Draw one matrix for precomputed costs and another for DP states. Space $O(N^2)$. |
| 2912 |
Number of Ways to Reach Destination in the Grid |
BFS/DFS exploring every valid jump in the grid for exactly K steps. |
Massive Expanding Web Graph |
Start at one cell. Draw N+M-2 arrows expanding outward. Repeat for each new cell K times. Shows $O((N+M)$^K). |
Combinatorics / 4-State DP (Markov Chain approach) |
4-Node State Machine Diagram |
Track 4 states: Source, Same Row, Same Col, Different Row/Col. Update their counts simultaneously K times using multiplication and grid dimensions. |
Draw 4 circles. Label them. Draw directed arrows between them showing valid transitions. Write formulas on the arrows (e.g., multiply by N-2 or M-2). |
Single Horizontal Timeline |
Draw a single straight line from 1 to K. Each tick represents updating 4 variables. T(N) = $O(K)$. |
Queue Data Structure overflowing with millions of coordinate pairs. Space $O((N+M)$^K). |
Four simple scalar boxes dynamically updating. Strictly $O(1)$ space. |
| 2913 |
Subarrays Distinct Element Sum of Squares I |
Generate all $O(N^2)$ subarrays. For each, put elements in a set to count distinct, square it, and sum. |
Redundant Array Slicing |
Draw the full array. Underneath, draw brackets isolating every single contiguous subarray, emphasizing redundant recalculations. |
Nested Loop Sliding Window with Running Set |
Expanding Window with Anchor |
Pin an 'i' pointer. Move 'j' to the right. Keep a running HashSet. Add nums[j] to the set, immediately take set.size()^2, and add to total. |
Draw array. Put an anchor pin at 'i'. Draw a sliding bracket 'j' moving right. Below it, draw a single expanding circle representing the HashSet. |
Upper Triangular Grid |
Draw an N x N grid. Shade half of it to represent the inner loop executing N-i times. Area = $O(N^2)$. |
$O(N^2)$ HashSets allocated and destroyed in memory repeatedly. Space $O(N^3)$. |
A single HashSet box being cleared and refilled. Max Space $O(N)$. |
| 2914 |
Minimum Number of Changes to Make Binary String Beautiful |
Try flipping every character, checking if the string can be partitioned validly. (O(2^N) checks). |
Binary Decision Tree |
Draw a binary tree. At each depth, branch left (keep '0') and right (change to '1'). Size explodes to 2^N. |
Greedy (Adjacent Pair Checking) |
2-Element Bounding Boxes |
Chunk the array strictly into pairs (index 0-1, 2-3, 4-5). If the two items in a pair are different, 1 change is needed. Count mismatches. |
Write out the binary string. Draw vertical walls separating every 2 characters. Circle any pair where the two bits are different. |
Single Segmented Timeline |
Draw a line with N/2 segments. Each segment requires 1 comparison (O(1)). Total time $O(N)$. |
Deep recursion call stack. Depth $O(N)$. |
A single integer counter box. Space strictly $O(1)$. |
| 2915 |
Length of the Longest Subsequence That Sums to Target |
Generate all 2^N subsequences. Filter by sum == target, return max length. |
Take/Skip Binary Tree |
Draw a binary tree tracking (current_sum, current_length). Depth N. Leaves represent 2^N possible subsequences. |
0/1 Knapsack Dynamic Programming |
1D Array Backwards Traversal |
Create `dp` array of size `target+1` initialized to -1, `dp[0]=0`. For each num, traverse `dp` backwards. Update `dp[j] = max(dp[j], dp[j-num] + 1)`. |
Draw a 1D array from 0 to Target. Draw an arrow pointing from `j-num` jumping forward to `j` to carry the max sequence length. |
Matrix Area Grid |
Draw a rectangle representing N (elements) by T (target). Show that traversing the inner loop takes T steps N times. $O(N \cdot T)$. |
Call stack depth N. |
A single 1D Array of size `Target+1`. Space $O(T)$. |
| 2916 |
Subarrays Distinct Element Sum of Squares II |
Generate all $O(N^2)$ subarrays, populate HashSets to count distincts, square, and sum. (TLE) |
Nested Overlapping Brackets |
Draw the array. Draw physical brackets underneath grouping every possible sub-segment, highlighting the massive redundant counting. |
Segment Tree with Lazy Propagation + Sweepline |
Hierarchical Range Tree |
Sweep right. When adding A[i], find its last occurrence `j`. Add +1 to the segment tree range [j+1, i]. The tree dynamically tracks the sum of (x+1)^2 - x^2. |
Draw a binary tree representing array indices. Trace a path down the tree to update ranges, placing "lazy" tags on nodes to defer work. |
N Paths Down a Log(N) Tree |
Draw an array of length N. From each element, draw a squiggly arrow pointing down a tree of height Log(N). Total Area = $O(N \log N)$. |
$O(N^2)$ individual HashSet memory blocks. $O(N^3)$ space. |
Two arrays: `tree` of size 4N and `lazy` of size 4N. Plus a HashMap for last seen indices. Space $O(N)$. |
| 2917 |
Find the K-or of an Array |
Check every bit position for every single number. Count numbers with the bit set. |
2D Bit Matrix Traversal |
Draw an N x 32 grid. Write 1 or 0 in each cell. Tally up every single column sequentially. |
Bit Manipulation (Column-wise Bit Counting) |
Vertical Column Summing |
Iterate bits 0 to 31. For each bit, loop the array `if ((num >> bit) & 1)`. If total count >= K, set that bit in the final answer using `ans |= (1 << bit)`. |
Write 3 numbers in binary, stacked vertically. Draw a vertical box around one bit column. Sum the 1s inside the box. Compare to K. |
Fixed Grid (N x 32) |
Draw a rectangle representing 32 columns and N rows. Time is strictly 32 * N, which simplifies to $O(N)$. |
Array of 32-character binary strings. $O(N \cdot 32)$ space. |
Two integer boxes: `ans` and `count`. Space strictly $O(1)$. |
| 2918 |
Minimum Equal Sum of Two Arrays After Replacing Zeros |
Try substituting every '0' with 1, then 2, then 3... recursively until sums match. |
Infinite Recursion Tree |
Draw a tree node for a '0'. Draw infinite branches coming out of it for choices 1, 2, 3, ∞. |
Greedy Sum Matching |
Balance Scales with Minimum Weights |
Calculate sum1 and sum2 assuming all 0s are 1s. Count 0s. If one sum is strictly less than the other but has NO zeros to grow, it's impossible (-1). Else, return max(sum1, sum2). |
Draw a balance scale. Put base sums on each side. Add '1' blocks for every zero. If the lighter side has no '0' slots left to add weight, draw an 'X'. |
Two Parallel Linear Sweeps |
Draw two parallel straight lines of length N and M. No overlapping loops. Time $O(N + M)$. |
Call stack exploring exponential combinations. |
Four scalar variables: `sum1`, `sum2`, `zero1`, `zero2`. Space $O(1)$. |
| 2919 |
Minimum Increment Operations to Make Array Beautiful |
Backtracking to try incrementing different combinations of elements to satisfy the size 3 window rule. |
Exploding N-ary Tree |
Draw a tree where each depth is an array index, branching out by adding +0, +1, +2... up to K. |
1D Dynamic Programming |
3-Element Sliding Lookback Window |
State: `dp[i]` is min cost to fix array up to `i`, strictly assuming we increment `nums[i]`. `dp[i] = max(0, k - nums[i]) + min(dp[i-1], dp[i-2], dp[i-3])`. |
Draw the `nums` array. Below it, the `dp` array. For a cell `i`, draw three arrows pointing backward to `i-1`, `i-2`, `i-3` to find the minimum previous state. |
Linear Sweep with $O(1)$ Lookback |
Draw a single line of length N. At each tick, write "x3" to represent checking the previous 3 states. Time $O(N)$. |
Recursion stack tracking array states. Space $O(N)$. |
Three scalar variables rotating (dp1, dp2, dp3) to save space, or a 1D DP array. Space $O(1)$ optimized. |
| 2920 |
Maximum Points After Collecting Coins From All Nodes |
Pure DFS on the tree without memoization, branching twice at every single node. |
Binary Tree over a Graph |
Draw the given tree graph. At every node, draw a split into two parallel universes (Option 1 vs Option 2). Size is $O(2^N)$. |
Tree DP + Memoization (State Reduction via Bit Shifts) |
Node-Attached State Arrays |
Key insight: Shifting a max value of 10^4 right by 14 bits makes it 0. Track state as `(node, shifts)`. Shifts cap at 14. Option 1 costs k. Option 2 increases shift. |
Draw the tree structure. Next to EVERY node, draw a tiny 1D array of 14 slots representing the memoized answers for 0 to 14 shifts. |
State Grid Overlaid on Tree |
Draw a grid of N rows and 14 columns. Show that each of the N nodes is processed exactly 14 times. Time $O(14 \cdot N)$ = $O(N)$. |
$O(2^N)$ call stack frames. |
A 2D memoization table `memo[N][15]`. Space $O(14 \cdot N)$ = $O(N)$. |
| 2921 |
Maximum Profitable Triplets With Increasing Prices II |
Three nested loops checking every combination of i < j < k ensuring prices increase. (TLE due to N=50,000 constraint). |
3D Cubic Grid |
Draw an isometric cube (X=i, Y=j, Z=k axes). Shade it red to represent Time Limit Exceeded at $O(N^3)$. |
Binary Indexed Tree (Fenwick Tree) / Segment Tree |
Two-Way Range Maximum Queries |
Fix 'j'. Use a Segment Tree to query the max profit on the left where price < price[j]. Use a second tree to query max profit on the right where price > price[j]. Add them up. |
Draw the `prices` array. Circle pivot `j`. Draw a tree above the left side querying for max valid profit, and a tree above the right side. |
N queries against Log(N) Depth Trees |
Draw a horizontal line of N items. From each item, draw an arrow going up into a tree of height Log(N). Total Area = $O(N \log N)$. |
Three scalar boxes for nested loops. Space $O(1)$. |
Two 1D arrays of size max(prices) for Fenwick Trees. Space $O(\text{Max}_\text{Price})$ or $O(N)$ with coordinate compression. |
| 2922 |
Market Analysis III (SQL) |
Multiple nested subqueries or massive self-joins counting seller items, grouping, and filtering highest. |
Cartesian Product Web |
Draw two tables. Draw a line from EVERY row in Table A to EVERY row in Table B to show the explosive row counts of bad joins. |
SQL Window Functions (`RANK()` or `DENSE_RANK()`) |
Segmented Data Frames |
Group by seller to get counts. Apply `RANK() OVER (ORDER BY count DESC)`. Filter for `RANK = 1` in the outer query to get top sellers instantly. |
Draw a single table. Draw thick horizontal lines grouping rows by seller ID. Write a small 'Rank' number next to each block based on their count size. |
Single Sequential Sort & Filter Pipeline |
Draw 3 blocks in sequence: [Aggregate] -> [Sort/Rank: $O(N \log N)$] -> [Filter]. Time mostly dominated by sorting. |
Massive temporary tables filling up disk/memory. $O(N^2)$ space. |
One clean sorted temporary table in memory holding aggregated metrics. Space $O(\text{Unique Sellers})$. |
| 2923 |
Find Champion I |
Nested loops comparing every team. If a team has N-1 wins (1s in its row), it is the champion. $O(N^2)$ scanning. |
Full Adjacency Matrix Scan |
Draw the N x N grid. Shade every single cell to represent reading the whole matrix to count wins. |
Graph In-Degree Counting / Row Sum Optimization |
Elimination Bracket / Array Sum |
Since it's guaranteed one team beats all others (directly or indirectly), just find the row with a sum of N-1. The team with 0 losses (column sum = 0) is the champion. |
Draw the N x N matrix. Draw a vertical box around each column. Look for the column entirely filled with '0's (meaning no one beat them). |
Single Pass Vector Scan |
Draw one straight line scanning down the columns or rows. Time $O(N)$ if columns are optimized, or $O(N^2)$ simply reading input. |
Two integer variables holding loops. Space $O(1)$. |
A single integer holding the row sum or max-index. strictly $O(1)$ space. |
| 2924 |
Find Champion II |
Run DFS/BFS from every single node to see if it can visit all other N-1 nodes. |
N Overlapping Search Trees |
Draw the graph. From every single node, draw a massive web spreading to all other nodes. $O(V \cdot (V+E)$). |
Directed Acyclic Graph (DAG) - Count In-Degrees |
Nodes with Incoming Arrows |
Iterate through edges. For every edge `u -> v`, increment `in_degree[v]`. A champion must have `in_degree == 0`. If exactly ONE node has 0 in-degree, return it. Else, -1. |
Draw a network of circles (nodes) and directed arrows (edges). Write a tally mark inside the circle for every arrow pointing *into* it. Find circles with 0 tallies. |
Two Sequential Linear Passes |
Draw a line representing E (edges pass). Then a line representing V (nodes pass). Time $O(V + E)$. |
Deep recursion call stacks and N separate `visited` arrays. Space $O(V^2)$. |
A single 1D Array of size V tracking `in_degrees`. Space $O(V)$. |
| 2925 |
Maximum Score After Applying Operations on a Tree |
Generate all 2^N combinations of keeping/removing node values, checking if every leaf path has >0 sum. |
Exponential Subset Tree |
Draw a binary tree of depth N representing "Keep" vs "Lose" for each node, blowing up to 2^N leaves. |
Tree Dynamic Programming (Min Cost to Satisfy) |
Bottom-Up Bubble Sinking |
Total Score = Total Sum - Min Cost. For a node, we must either "pay" its value (leaving it) OR "pay" the sum of the min costs of all its children. `cost[node] = min(val[node], sum(cost[children]))`. |
Draw the tree. Write the original values inside nodes. Starting from leaves, write the `cost` outside the node, bubbling up the `min(value, children_costs)` to the root. |
Bottom-Up Post-Order Traversal |
Draw the tree, and trace a single continuous line wrapping around every node from bottom to top. Time strictly $O(N)$. |
Call stack exploring 2^N states. |
$O(N)$ recursion call stack depth (or $O(1)$ extra space if iterative). Graph represented by Adjacency List $O(V+E)$. |
| 2926 |
Maximum Balanced Subsequence Sum |
Generate all 2^N subsequences, check the balance condition (nums[i] - i <= nums[j] - j), and find max sum. |
Exponential Subset Tree |
Draw a binary tree of depth N. Each level is an index. Left = Skip, Right = Take if balanced. Leaves = 2^N. |
LIS-style DP + Coordinate Compression + Fenwick Tree |
Sorted Value Mapping (Coordinate Compression) |
Transform condition to B[i] = nums[i] - i. Sort all B[i]. As you iterate, query the Fenwick Tree for the max sum ending at a value ≤ B[i] and update. |
Draw a 1D array of original values. Below it, draw a "Compressed Map" (Sorted indices 0, 1, 2...). Draw arrows from the array to the Fenwick Tree blocks. |
N Queries against a Log(N) Structure |
Draw N dots on a line. From each dot, draw a line segment of length Log(N) representing the tree traversal. Total $O(N \log N)$. |
Recursion stack depth N. |
1D array for Fenwick Tree (O(N)) + Hash map for coordinate mapping (O(N)). |
| 2927 |
Distribute Candies Among Children II |
Triple nested loops (i, j, k) to find all combinations where i+j+k = n and each is <= limit. |
3D Coordinate Cube |
Draw an isometric cube representing N^3. Shade the region that satisfies i+j+k=n. |
Combinatorics (Inclusion-Exclusion Principle) |
Venn Diagram of Overlapping Constraints |
Total ways (Stars & Bars) - (Ways where child 1 > limit) - (Child 2 > limit)... + (Ways where 2 children > limit) and so on. |
Draw three large overlapping circles. Label each circle "Child X > Limit". Use the formula: Total - ΣA + Σ(A∩B) - (A∩B∩C). |
Constant Time Mathematical Formula |
Draw a single dot. Write "O(1)" next to it. The calculation is just a few additions and subtractions of combinations. |
Three integer variables for loops. |
No extra memory used beyond the result variable. Space $O(1)$. |
| 2928 |
Distribute Candies Among Children I |
Nested loops (i, j, k) where i+j+k == n and each <= limit. (N is small here, so brute force is fine). |
Nested Loop Pyramid |
Draw a triangle. Top row has 1 dot, next has 2... up to N. This represents the valid search space for 3 variables. |
Iterative Brute Force (Optimized Range) |
Nested Variable Scopes |
Fix child 1 (i). Child 2 (j) can range from 0 to min(limit, n-i). Child 3 is then fixed as (n-i-j). Verify if child 3 <= limit. |
Draw two nested boxes (i and j). Inside the j box, draw a logic gate checking if n-i-j is valid. |
Bounded Quadratic Area |
Draw a square of side N. Shade the portion where i+j <= n and i,j <= limit. Area is $O(\text{min}(N, \text{limit})$^2). |
Three scalar counters. |
Single result counter. Space $O(1)$. |
| 2929 |
Distribute Candies Among Children III |
Nested loops (TLE due to N=10^12 constraint). |
Massive 3D Space (Red) |
Draw a cube with side 10^12. Label it "IMPOSSIBLE TO LOOP" in red. |
Inclusion-Exclusion (Math) |
Stars and Bars Formula Visualization |
Same as 2927. The logic for 10^12 is identical to 10^5, requiring only long long math. |
Draw "n" stars and 2 "bars" to divide them into 3 children. Formula: (n+2 choose 2). |
$O(1)$ Math Logic |
Draw a single calculation box. Note that complexity does not depend on N. |
Counters. |
A few long long variables. Space $O(1)$. |
| 2930 |
Number of Strings Which Can Be Rearranged to Contain Substring |
Generate all 26^N strings and count those containing 'l'x1, 'e'x2, 't'x1. |
26-ary Search Tree |
Draw a root node branching 26 times. Repeat for depth N. Leaves = 26^N. Huge! |
Inclusion-Exclusion Principle with Modular Exponentiation |
Venn Diagram of "Missing" requirements |
Total strings (26^N) - (Strings missing 'l') - (Strings missing 't') - (Strings with <2 'e's) + Overlaps. |
Draw three circles for 'l', 'e', and 't'. Calculate sizes using powers like 25^N, 24^N. Add/Subtract based on the intersection counts. |
Logarithmic Power Function |
Draw a line of length Log(N) representing the binary exponentiation steps. $O(\log N)$. |
Massive string storage. |
Only 5-10 long long variables for modular arithmetic. Space $O(1)$. |
| 2931 |
Maximum Spending After Buying Items |
Try every possible permutation of buying items from M shops over D days. |
Factorial Permutation Tree |
Draw a root. Branch out M times for day 1, then M times for day 2. Complexity $O((M\cdot D)$!). |
Greedy (Min-Heap / Sorting) |
Sorted Linear Stream |
Since we want larger multipliers for larger prices, we should buy the cheapest items first. Put all items in one list, sort ascending, and multiply by 1, 2, 3... |
Draw all items as dots on a single line. Label them with their prices. Sort them. Draw a second line underneath showing the day number increasing. |
Standard Sorting Timeline |
Draw a line of length N (where N=M*D). T(N) = N log N for sorting. Linear $O(N)$ for the sum. |
Massive recursion stack for permutations. |
A single 1D array of size M*D. Space $O(M\cdot D)$. |
| 2932 |
Maximum Strong Pair XOR I |
Nested loops (i, j) checking every pair for |x-y| <= min(x,y) and tracking max XOR. |
Upper Triangular Matrix |
Draw an N x N grid. Shade the diagonal and upper half. N=50 means 1,225 checks. $O(N^2)$. |
Brute Force (Small Constraints) |
Nested Loop Scan |
Iterate i from 0 to N. Iterate j from i to N. Check the "strong pair" condition. If true, calculate XOR and update max. |
Draw the array. Use two fingers (i, j) to point at elements. Note down the XOR value if the condition is met. |
Quadratic Area |
Draw a square of side N. The area (N^2/2) represents the operations. |
Two integer variables. |
Single integer for `maxXor`. Space $O(1)$. |
| 2933 |
High-Access Employees |
For each employee, check every subset of 3 access times to see if they fall within 60 mins. |
Combinatorial Time Slices |
Draw a clock. Mark points for every access time. Draw segments to find triplets within 60 mins. $O(E \cdot T^3)$. |
Sorting + Sliding Window (Fixed Size 3) |
Sorted Timeline per Employee |
Group access times by employee. Sort times (HHMM -> minutes). For each employee, check if `time[i] - time[i-2] < 60`. |
Draw a timeline for "Alice". Mark points at 0800, 0820, 0850. Draw a 60-min bracket. See if 3 points fit inside. |
Grouped Sorting Cost |
T = $O(N \log N)$ to sort all access times. $O(N)$ to sweep. Draw a sorted array being scanned by a 3-element wide box. |
Nested lists of access strings. |
A Hash Map (Name -> List of Integers). Space $O(N)$. |
| 2934 |
Minimum Operations to Maximize Last Elements |
Try every subset of swaps (2^N) to see if the condition `nums1[i] <= nums1[n-1]` and `nums2[i] <= nums2[n-1]` holds. |
Binary Swap Tree |
Draw a tree where each node is an index. Left = Don't Swap, Right = Swap. Depth N. $O(2^N)$. |
Greedy (Two Scenarios) |
Two Parallel Simulations |
Only two possible ending states: either you swap the last elements or you don't. For each case, greedily swap any `i` that violates the condition. |
Draw two versions of the arrays. Case A: Last elements as is. Case B: Last elements swapped. Use a checkmark for valid pairs. |
Two Linear Sweeps |
Draw two horizontal lines of length N. T(N) = 2 * N = $O(N)$. |
Recursion stack for 2^N swaps. |
Two integer counters for swaps. Space $O(1)$. |
| 2935 |
Maximum Strong Pair XOR II |
Nested loops (TLE due to N=50,000 constraint). |
Massive Quadratic Grid |
Draw a grid of 50,000 x 50,000. Label it "TIME LIMIT EXCEEDED" in red. |
Sliding Window + Binary Trie |
Moving Window over a Trie |
Sort array. Move a window `[L, R]` such that `nums[R] <= 2 * nums[L]`. Add `nums[R]` to Trie. As `L` moves, remove `nums[L]` from Trie. Query Trie for max XOR. |
Draw a sorted array. Draw a sliding bracket. To the side, draw a Binary Trie where nodes are added/removed as the bracket slides. |
N log(MaxVal) Operations |
Draw a line of length N. For each point, draw a path down a tree of height 20 (bits). Total $O(N \cdot 20)$. |
Quadratic pair storage. |
A Binary Trie structure. Space $O(N \cdot 20)$ or $O(N)$ with compression. |
| 2936 |
Number of Equal Numbers Blocks |
Linear scan checking every single element to count consecutive identical number blocks. |
Single Horizontal Line Sweep |
Draw a line of length N. Mark every single point with a tick. T(N) = $O(N)$. |
Binary Search / Jump Search |
Skipping Stones on Water |
Start at index `i`. Use binary search to find the *last* index `j` that has the same value as `i`. Jump directly to `j+1`. Repeat. |
Draw a long array. Draw a large arc "jumping" over 10 elements. Inside the arc, write "Binary Search". Repeat for the next block. |
Step-ladder Logarithmic Decline |
Write T(N) = K * log(N), where K is the number of blocks. Draw K small arcs. |
Standard index counter. |
Binary search recursion stack (Log N). Space $O(\log N)$. |
| 2937 |
Make Three Strings Equal |
Check all prefix lengths for all three strings to find a common match. |
Overlapping Circles (Venn) |
Draw three lines of different lengths. Shade the section where they overlap at the start. |
Greedy Prefix Matching |
Parallel Scanning Head |
Iterate index `i` from 0. Compare `s1[i], s2[i], s3[i]`. If they differ or `i` exceeds a length, stop. Common length is `i`. Total operations = (len1+len2+len3) - 3*i. |
Stack the three strings vertically. Draw a vertical line through them. Move the line right until the letters at the line don't match. |
Single Pass Linear Scan |
Draw a straight line of length min(L1, L2, L3). T(N) = $O(\text{min}_\text{length})$. |
Storing all possible prefix combinations. |
Three integer variables for lengths and one index counter. Space $O(1)$. |
| 2938 |
Separate Black and White Balls |
Simulate every single swap needed to move '0's to the left and '1's to the right (like Bubble Sort). |
Quadratic Swap Grid |
Draw N items. Show one ball moving across N positions. Repeat for N balls. $O(N^2)$. |
Two Pointers / Greedy (Counting 1s) |
Accumulating "Weight" of Ones |
Traverse left to right. Every time you see a '1', increment a `ones` counter. Every time you see a '0', add the current `ones` count to your `total_swaps`. |
Write "11001". Above it, track a tally. For '0', draw an arrow back to all '1's it must pass. |
Single Pass Timeline |
Draw a single straight line of length N. Each step is $O(1)$. T(N) = $O(N)$. |
N/2 swap operations recorded. |
Two long long variables (`swaps`, `ones`). Space $O(1)$. |
| 2939 |
Maximum Xor Product |
Try all 2^n values of `x` (where n is the bit count) and find the one maximizing (a^x) * (b^x). |
Binary Decision Tree |
Draw a tree branching into 0 or 1 for each bit position. Depth n. Leaves 2^n. |
Bit Manipulation (Greedy Bit-by-Bit) |
Bit-wise Balance Scale |
Iterate bits from n-1 down to 0. If bits in `a` and `b` are same, set `x` bit to make them both 1. If different, set `x` to give the 1 to the smaller current number to keep them balanced. |
Write `a` and `b` in binary. For each column, decide where to put the '1' to keep the two totals close to each other (maximizing product). |
Fixed 64-bit Sweep |
Draw a line with 50 segments. T(N) = $O(n \text{bits})$. $O(1)$ in practical terms. |
Recursion stack for all binary combinations. |
Three 64-bit integer variables. Space $O(1)$. |
| 2940 |
Find Building Where Alice and Bob Can Meet |
For each query, scan the buildings to the right of max(Alice, Bob) to find the first height > both. |
N Queries x N Scan Matrix |
Draw a grid of Q x N. Shade it to show worst case scanning N buildings for every query. $O(Q \cdot N)$. |
Offline Queries + Monotonic Stack / Priority Queue |
Sweeping Building Skyline |
Sort queries by their rightmost index. Sweep through buildings. Keep a min-heap of active queries. When current building height > query height, answer it. |
Draw building heights as a bar chart. Draw query "pointers" sitting on bars. As you move right, "pop" queries that are satisfied by the current tall bar. |
Sorted Processing Timeline |
Draw a timeline for N buildings and a timeline for Q queries. Total Time $O((N+Q)$ log Q). |
$O(Q \cdot N)$ traversal states. |
A Priority Queue of size Q and an answer array of size Q. Space $O(Q)$. |
| 2941 |
Maximum GCD-Sum of a Subarray |
Generate all $O(N^2)$ subarrays, compute GCD for each, and multiply by subarray sum. |
Quadratic Subarray Grid |
Draw an N x N grid. Each cell represents a GCD calculation. Label it $O(N^2 \cdot \log(\text{max}_\text{val})$). |
Sparse Table / GCD Property (Unique Prefix GCDs) |
Logarithmic GCD "Steps" |
At each index i, maintain a list of unique GCD values ending at i. Because GCD only decreases by factors, there are only $O(\log M)$ such values. |
Draw an array. Below each element, list its GCD with predecessors. Show how the list "collapses" as duplicate values are removed. |
N Linear Steps with Log Factor |
Draw a horizontal line of N points. Above each point, draw a small vertical stack of height log M. Total Area = $O(N \log M)$. |
Storing N^2 GCD results. |
A small map or list of pairs (GCD, count) at each step. Space $O(N + \log M)$. |
| 2942 |
Find Words Containing Character |
Iterate through each word, and for each word, iterate through its characters to find the target. |
Linear Search Timeline |
Draw a series of boxes (words). Inside each box, draw dots (characters). Touch every dot. $O(\text{sum word}_\text{length})$. |
Simple Linear Scan |
Pointer Filtering |
Iterate index i from 0 to words.length - 1. Use a built-in `find` or `contains` method. If true, add i to the result list. |
Draw a list of strings. Draw an arrow pointing to each word. Circle the index if the character 'x' is found inside. |
Total String Length Line |
Draw one straight line representing the total number of characters in all words combined. T = $O(L)$. |
Temporary character arrays for each word. |
A single list of integers (result indices). Space $O(N)$. |
| 2943 |
Maximize Area of Square Hole in Grid |
Check all possible k x k square combinations by removing bars. |
Exhaustive Grid Search |
Draw a grid. Attempt to fit squares of size 2, 3, 4... by checking all possible row/column removals. $O(2^H \cdot 2^V)$. |
Longest Consecutive Sequence (Greedy) |
Bar Connectivity Histogram |
Sort the removed bars. Find the longest consecutive sequence in `hBars` (h_max) and `vBars` (v_max). The side of the largest square is min(h_max + 1, v_max + 1). |
Draw a line representing horizontal bars. Circle consecutive numbers (e.g., 2, 3, 4). The "gap" size is count + 1. Repeat for vertical. |
Sorting + Linear Sweep |
Draw two lines: one for H bars, one for V bars. T = $O(H \log H + V \log V)$. |
Storing all subset combinations of bar removals. |
Sorting the bars in place or a new list. Space $O(H + V)$. |
| 2944 |
Minimum Number of Coins for Fruits |
Recursion with all choices: pay for fruit i, which gives the next i fruits for free. |
Recursive Choice Tree |
Draw a tree where each node branches into many possible "next paid fruit" indices. $O(2^N)$. |
Dynamic Programming + Monotonic Queue (Sliding Window) |
DP Value Lookback Window |
dp[i] is the min cost for first i fruits. To get dp[i], look back at all j such that paying for j covers i. dp[i] = prices[j-1] + dp[j-1]. |
Draw the `prices` array. Below it, draw the `dp` array. For index i, draw a bracket showing the range of "ancestors" that could have covered it. |
Linear DP with Deque Optimization |
Draw a line for N. If using a simple loop, $O(N^2)$. If optimized with a Deque, $O(N)$. |
Deep recursion call stack. |
A 1D DP array of size N+1. Space $O(N)$. |
| 2945 |
Find Maximum Non-decreasing Array Length |
Try all ways to partition the array into subarrays such that their sums are non-decreasing. |
Partition Bell Tree |
Draw all ways to split "1, 2, 3, 4" (e.g., [1,2,3,4], [1|2,3,4], [1,2|3,4]...). Exponential growth. |
Greedy DP + Prefix Sums + Monotonic Queue |
Optimal Split Point Tracker |
Maintain dp[i] (max length up to i) and last[i] (sum of the last group in that optimal partition). We want to find the largest j < i such that sum(j dots i) >= last[j]. |
Draw the prefix sum array. For each i, use a monotonic queue to find the best j in $O(1)$ that satisfies the greedy condition. |
Linear Scan with Deque Lookups |
Draw a line for N. Mark $O(1)$ operations per element thanks to the monotonic property. Total T = $O(N)$. |
Storing all partition possibilities. |
Two 1D arrays (dp and last) and a Deque. Space $O(N)$. |
| 2946 |
Matrix Similarity After Cyclic Shifts |
Perform k cyclic shifts on each row and then compare the entire matrix with the original. |
Iterative Matrix Transformation |
Draw a grid. Show each row shifting one-by-one k times. $O(k \cdot N \cdot M)$. |
Modulo Arithmetic Indexing |
Circular Buffer Mapping |
Instead of shifting, check if mat[i][j] == mat[i][(j+k) % M]. The actual shift doesn't matter; only the "wrap-around" position does. |
Draw a single row. Label indices 0 to M-1. Draw an arrow from index j to (j+k) % M to show the expected match. |
Single Matrix Pass |
Draw a rectangle representing N x M. Each cell is visited exactly once. T = $O(N \cdot M)$. |
Storing a copy of the entire matrix for each shift. |
No extra memory used beyond input. Space $O(1)$. |
| 2947 |
Count Beautiful Substrings I |
Generate all $O(N^2)$ substrings, count vowels and consonants, and check the "beautiful" condition. |
Quadratic Substring Scan |
Draw an N x N grid. Each cell is a substring check. $O(N^2)$. |
Prefix Sums + Hash Map (Frequency Tracking) |
Coordinate Grid of Counts |
Condition 1: v == c means v - c == 0. Condition 2: (v * c) % k == 0. Since v=c, this is v^2 % k == 0. Find the smallest x such that x^2 % (4k) == 0. |
Draw a 1D array of prefix differences (v-c). Use a map to store `(diff, v % x)` and count occurrences. |
Linear Sweep with Map Lookups |
Draw a line of length N. Mark $O(1)$ operations at each index. T = $O(N)$. |
Storing all substring slices. |
A Hash Map of size up to N. Space $O(N)$. |
| 2948 |
Make Lexicographically Smallest Array by Swapping Elements |
Try all possible swaps of elements with difference <= limit and sort them greedily. |
Graph Permutation Web |
Draw nodes for array elements. Add edges if |a-b| <= limit. Find all paths. $O(N!)$. |
Sorting + Grouping (Disjoint Connectivity) |
Island Formation |
Sort elements with their original indices. If |sorted[i] - sorted[i-1]| <= limit, they belong to the same group. For each group, sort the original indices and place elements. |
Draw a line. Cluster elements that are close together. Sort these clusters individually and map them back to their original positions. |
Sorting + Linear Grouping |
Draw a timeline. T = $O(N \log N)$ for initial sort + $O(N)$ for grouping. |
Graph adjacency lists for all possible swaps. |
Storing sorted pairs (value, index) and group lists. Space $O(N)$. |
| 2949 |
Count Beautiful Substrings II |
Same as 2947 (Nested loops). TLE due to N=5 * 10^4. |
Massive Quadratic Grid |
Draw a 50,000 x 50,000 grid. Label "RED/TLE". |
Math Optimization + Prefix Map (Advanced) |
Modular State Space |
Solve for v in v^2 equiv 0 modL where L is derived from k. Use a Map to store `(v - c, v % L)` states to find matches in $O(1)$. |
Draw a state-transition diagram where each index updates its (diff, mod) pair. |
Linear Pass with Math Precomputation |
Draw a line of length N. T = $O(N + √k)$. |
Quadratic storage. |
A Hash Map of prefix states. Space $O(N)$. |
| 2950 |
Number of Divisible Substrings |
Generate all $O(N^2)$ substrings, map characters to digits, and check if the sum is divisible by length. |
Double Loop Substring Sums |
Draw a triangle representing N^2/2 operations. $O(N^2)$. |
Prefix Sums (Brute Force is expected for N=1000) |
Running Average Tracker |
Use a mapping table for 'a'-'z'. Calculate the prefix sum of mapped values. For each i, j, check if (pref[j] - pref[i]) % (j-i) == 0. |
Draw the string. Below it, draw its numeric mapped values. Draw a sliding window and calculate its average. |
Quadratic Timeline |
Draw a line of length N, with N checks at each point. T = $O(N^2)$. |
Storing all numeric mapping lists. |
Prefix sum array of size N. Space $O(N)$. |
| 2951 |
Find the Peaks |
Iterate from index 1 to N-2 and check if current is greater than neighbors. (This is already the optimal scan). |
Single Horizontal Line Sweep |
Draw a line of dots. Draw a "V" shape above any dot that is higher than its immediate left and right dots. T(N) = $O(N)$. |
Linear Array Scanning |
Three-Element Sliding Bracket |
Slide a window of size 3. If the middle element is the maximum of the three and no ties exist, mark the index. |
Draw a bar chart. Circle any bar that is strictly taller than both of its side-neighbors. |
Single Pass Timeline |
Draw a straight line of length N. One constant time check per index. T = $O(N)$. |
Simple integer variables for loop counters. |
A result list to store peak indices. Space $O(N)$ worst-case. |
| 2952 |
Minimum Number of Coins to be Added |
Recursive/Backtracking to find all obtainable sums for every possible coin addition. |
Infinite Branching Tree |
Draw a tree where each node represents a missing sum. Branching into adding coin 1, 2, 3... to infinity. |
Greedy Range Extension (Patching) |
Expanding Interval Bar |
Maintain `reachable_range` [0, current_max]. If the next coin > current_max + 1, "patch" the gap by adding a coin of value current_max + 1, doubling the range. |
Draw a horizontal number line. Shade the part you can reach. If there's a gap, draw a "patch" block and show the shaded area doubling in size. |
Sorting + Logarithmic Growth Pass |
Draw a line of N items (coins). For each gap, draw a jump. T = $O(N \log N)$ for sorting + $O(\\text{log target})$. |
Deep recursion stacks tracking obtainable subsets. |
Three long long variables: `max_reachable`, `count`, and `index`. Space $O(1)$. |
| 2953 |
Count Complete Substrings |
Check all $O(N^2)$ substrings for character counts and adjacent difference conditions. |
Quadratic Matrix Area |
Draw an N x N grid. Each cell represents a complex string check. Label "TLE" for N=10^5. |
Sliding Window + Segment Splitting |
Bracketed Valid Segments |
1. Split string into segments where |word[i] - word[i-1]| <= 2. 2. For each segment, test windows of size 1k, 2k dots 26k. Count if all chars appear exactly k times. |
Draw the string. Draw vertical "walls" where the adjacent diff > 2. Inside each room, draw sliding brackets of fixed sizes (k, 2k, 3k). |
N Linear Passes x 26 Window Sizes |
Draw a line of length N. Above it, draw 26 parallel lines. Total operations T = $O(26 \cdot N)$. |
Storing N^2 substring character maps. |
Frequency array of size 26 and a few counters. Space $O(1)$ or $O(26)$. |
| 2954 |
Count the Number of Infection Sequences |
Generate all possible permutations of the infection order using backtracking and check if they are valid. $O(N!)$. |
Factorial Infection Tree |
Draw a line of healthy/infected nodes. Branch out for every possible "next infected" node. The tree grows infinitely. |
Combinatorics + Modular Inverse |
The Gap Permutation Math |
Identify "gaps" of uninfected people. For a gap bounded by two infected people, there are 2^length-1 ways to infect them. Multiply these variations and use combinations (nCr) to interleave the different gap sequences. |
Draw the array. Bracket the "gaps" of healthy nodes. Write a math formula under each gap, and multiply them together using a large combinatorial equation. |
Linear Scan + Fast Math $O(N \\text{log MOD})$ |
Draw a single pass to find gaps, followed by fast modular exponentiation. |
Storing millions of sequence arrays. |
A few integer variables. $O(1)$ space. |
| 2955 |
Number of Same-End Substrings |
For each query [L, R], generate all substrings and check if ends are same. |
Query Count x Subarray Area |
Draw a Q x N^2 grid. Label "TLE" for Q=10^5, N=10^5. |
Prefix Sums + Combinatorics (nC2) |
Character Occurrence Map |
For a character that appears X times in a range, it forms X (single-char) + X(X-1)/2 (pairs) same-end substrings. Use prefix sums to find X in $O(1)$. |
Draw the string. Below it, draw 26 prefix sum lines. For a query, calculate X = pref[R] - pref[L-1] for each char and apply the formula. |
Preprocessing (26N) + Query (26Q) |
Draw a line for N. Below it, a line for Q. Each Q point has 26 constant-time lookups. T = $O(26(N+Q)$). |
Storing all substrings per query. |
2D Prefix Sum Array of size 26 x N. Space $O(26N)$. |
| 2956 |
Find Common Elements Between Two Arrays |
For each element in nums1, loop through all of nums2 to check for existence. Repeat for nums2. |
Nested Loop Scan |
Draw two arrays. Draw an arrow from every element in A to every element in B. $O(N \cdot M)$. |
Hash Set Lookups |
Venn Diagram Set Intersection |
Place nums1 in Set A and nums2 in Set B. For each element in the original nums1, check if it exists in Set B. Increment count if true. |
Draw two circles representing Sets. List distinct numbers inside. For each number in the array, draw a "check" if it falls in the other circle. |
Two Sequential Passes |
Draw two parallel lines of length N and M. T = $O(N + M)$. |
Standard integer counters. |
Two Hash Sets storing unique elements. Space $O(N + M)$. |
| 2957 |
Remove Adjacent Almost-Equal Characters |
Try all combinations of character changes and verify if adjacent characters are "almost equal". |
Exponential Decision Tree |
Draw a tree where each node is a character, branching into "change" or "keep". $O(2^N)$. |
Greedy (Pairs Comparison) |
Pair-wise Bounding Box |
Traverse the string. If `abs(s[i] - s[i-1]) <= 1`, you MUST change one. The most efficient change is to change the second character and skip the next check. |
Write "aaaaa". Draw a bracket over the first 'aa'. Mark the second 'a' with an 'X' (changed). Move the bracket to the next UNCHANGED pair. |
Single Linear Sweep |
Draw a line of length N. One constant-time check per step. T = $O(N)$. |
Deep recursion stack. |
A single integer counter for changes. Space $O(1)$. |
| 2958 |
Length of Longest Subarray With at Most K Frequency |
Generate all $O(N^2)$ subarrays and check if every element's frequency <= k. |
Quadratic Matrix Area |
Draw a triangle representing N^2/2 operations. Label "TLE" for N=10^5. |
Sliding Window (Two Pointers) |
Expanding/Contracting Accordion |
Move `right` pointer to include elements. If frequency of `nums[right] > k`, move `left` pointer forward until the frequency is restored to k. |
Draw an array. Draw a bracket `[ ]`. Show the bracket expanding right, then "shrinking" from the left when a frequency limit is hit. |
Linear Sweep (2N total moves) |
Draw a line of length N. Both `left` and `right` move only forward. T = $O(N)$. |
Storing N^2 frequency maps. |
A Hash Map tracking frequencies of elements in the current window. Space $O(N)$. |
| 2959 |
Number of Possible Sets of Closing Branches |
Check all 2^N subsets of branches. For each, run Dijkstra/Floyd-Warshall to verify distances. |
Exponential Bitmask + All-Pairs Shortest Path |
Draw 2^N small graphs. For each, draw all-pairs distance lines. $O(2^N \cdot N^3)$. |
Bitmask DP + Floyd-Warshall |
Binary Toggle Grid |
Iterate bitmask from 0 to 2^N - 1. For active bits, run Floyd-Warshall on the subgraph. If all distances between active nodes <= maxDistance, count it. |
Draw a 10-bit binary number. For each '1', highlight that node in the graph. Run a 3-loop Floyd-Warshall on paper for a small case. |
Sub-cubic complexity over subsets |
Write T = 2^N * N^3. With N=10, 1024 * 1000 approx 10^6, which fits in time limits. |
Recursion stack for subsets. |
Adjacency matrix for the graph. Space $O(N^2)$. |
| 2960 |
Count Tested Devices After Test Operations |
For each device i, if battery > 0, loop through all devices i+1 dots N and decrement their batteries. |
Nested Loop Simulation |
Draw a series of batteries. For each "success", draw arrows hitting every battery to the right. $O(N^2)$. |
Greedy (Running Offset) |
Global Decrement Filter |
Instead of decrementing everyone, keep a count of successful tests. A device is "successful" if `initial_battery - current_success_count > 0`. |
Draw a line of batteries. Maintain a tally. For each battery, subtract the tally and see if it's >0. If yes, increment the tally. |
Single Pass Timeline |
Draw a straight line of length N. One comparison per element. T = $O(N)$. |
Temporary arrays for each state of batteries. |
One integer for the running count. Space $O(1)$. |
| 2961 |
Double Modular Exponentiation |
Calculate (a^b mod10)^c modm using standard loops for exponentiation. |
Linear Power Chains |
Draw a chain of multiplications: a x a x dots x a (b times). Repeat for c. $O(b+c)$. |
Binary Exponentiation (Modular Pow) |
Logarithmic Successive Squaring |
Break exponent b into binary bits. For each bit, either square the result or square and multiply by base. |
Draw a base number. Draw arrows showing it squaring at each step. If the bit is 1, draw an extra multiplication node. |
N Steps x Log(Exponent) |
Draw a line of N tasks. Above each, a tree of height log(exponent). Total T = $O(N \log(\text{max}_\text{exp})$). |
Large intermediate integers before modulo. |
Constant number of variables for modular results. Space $O(1)$. |
| 2962 |
Count Subarrays Where Max Element Appears at Least K Times |
Generate all $O(N^2)$ subarrays and count the frequency of the global max in each. |
Subarray Scan Grid |
Draw a triangle area N^2/2. Label "TLE" for N=10^5. |
Sliding Window (Two Pointers) |
Expanding Right, Shrinking Left |
Identify the max element M. Expand `right` until count of M is k. All subarrays from this `right` to the end are valid. Move `left` to find more. |
Draw array. Circle all occurrences of max value. Draw a bracket that expands to the k-th circle. Add (N - right) to total. |
Two Sequential Passes (Linear) |
Draw a straight line of length N. Each pointer only moves forward. T = $O(N)$. |
Storing frequency maps for all subarrays. |
One integer for `max_val` and one `count` variable. Space $O(1)$. |
| 2963 |
Count the Number of Good Partitions |
Try all 2^N-1 ways to partition the array and check if each value stays in one partition. |
Exponential Partition Tree |
Draw a tree of depth N branching into "cut" or "don't cut". $O(2^N)$. |
Merge Intervals + Combinatorics |
Connecting Identical Element Spans |
Find the first and last occurrence of every number. These form "must-stay-together" intervals. Merge all overlapping intervals. If there are G groups, answer is 2^G-1. |
Draw dots for elements. Draw a physical arc from the first '5' to the last '5'. Merge overlapping arcs into single blocks. |
Sorting + Linear Sweep |
Draw a timeline. T = $O(N \log N)$ or $O(N)$ with a Hash Map. |
Storing all partition results. |
A Hash Map for first/last indices. Space $O(N)$. |
| 2964 |
Number of Divisible Triplets |
Triple nested loops (i, j, k) to check if sum is divisible by d. $O(N^3)$. |
3D Coordinate Cube |
Draw an isometric cube. Shade the region where i < j < k. Area N^3/6. |
Prefix Sum Hash Map / Two-Sum Pattern |
Complementary Modulo Lookup |
Fix j. We need (nums[i] + nums[j] + nums[k]) equiv 0 mod d. Pre-calculate counts of nums[i] for i < j and look up required nums[k] for k > j. |
Draw a line. Put a "divider" at j. On the left, maintain a frequency map of mods. For each k on the right, calculate required mod. |
Quadratic Loop with Map |
Draw a square of size N. Inside, $O(1)$ map lookups. T = $O(N^2)$. |
Three scalar counters. |
A Hash Map of size d. Space $O(d)$. |
| 2965 |
Find Missing and Repeated Values |
Sort all numbers in the N x N grid and scan to find the duplicate and missing gap. |
Sorting-Based Scan |
Draw N^2 boxes. Show them being rearranged. T = $O(N^2 \log N^2)$. |
Frequency Array / Math (Sum & Squares) |
Tally Chart / Bucket Sort |
Create a frequency array of size N^2. Fill it by scanning the grid once. The index with 2 is repeated; the index with 0 is missing. |
Draw a grid of boxes labeled 1 to N^2. Put a coin in a box for every number seen. Find the box with 2 coins and 0 coins. |
Single Grid Pass |
Draw a square N x N. Visit each cell once. T = $O(N^2)$. |
Storing a copy of the grid for sorting. |
A 1D frequency array of size N^2. Space $O(N^2)$. |
| 2966 |
Divide Array Into Arrays With Max Difference |
Try all permutations of the array to find groups of 3 that satisfy the difference condition. |
Factorial Permutation Tree |
Draw a root node branching N times, then N-1 times... $O(N!)$. Impossible for large N. |
Greedy (Sorting + Linear Grouping) |
Sequential Triplet Buckets |
Sort the array. Check every consecutive triplet `(i, i+1, i+2)`. If `nums[i+2] - nums[i] > k`, return an empty list. Else, add to results. |
Draw a sorted line of numbers. Draw vertical dividers every 3 elements. Measure the distance between the first and third in each box. |
Sorting + Single Pass |
Draw a timeline. T = $O(N \log N)$ for sort + $O(N)$ for sweep. |
Recursive stack for permutations. |
A result list to store triplets. Space $O(N)$. |
| 2967 |
Minimum Cost to Make Array Equalindromic |
Check every possible palindrome number from 1 to max(nums) and calculate the cost for each. |
Infinite Linear Search |
Draw a number line. At every integer, calculate sum |nums[i] - p|. $O(\text{Range} \cdot N)$. |
Median + Palindrome Generation |
Mountain Peak Targeting |
The optimal target must be near the median. Find the median M. Generate the closest palindromes above and below M. Calculate costs for both and take min. |
Draw a bell curve of costs. Mark the median M at the bottom. Draw two nearby points (palindromes) and compare their "heights" (costs). |
Sorting + Constant Search |
Draw a line of length N. T = $O(N \log N)$ to find the median. Palindrome generation is $O(\text{digits})$. |
No extra memory. |
A few long long variables for median and palindromes. Space $O(1)$. |
| 2968 |
Apply Operations to Maximize Frequency Score |
Generate all $O(N^2)$ subarrays and find the min operations to make all elements equal to some value in the range. |
Quadratic Subarray Scan |
Draw a triangle N^2/2. Label "TLE" for N=10^5. |
Sorting + Sliding Window + Prefix Sums |
Expanding Centered Window |
Sort array. In a window `[L, R]`, the optimal value to match is the median. Use prefix sums to calculate total operations in $O(1)$. If operations <= k, expand; else shrink. |
Draw a sorted bar chart. Draw a sliding bracket. Calculate the area between the median bar and other bars in the bracket using prefix sum subtraction. |
Sorting + Linear Window Pass |
Draw a timeline. T = $O(N \log N)$ for sort + $O(N)$ for sliding window. |
Storing cost maps for all subarrays. |
A prefix sum array of size N. Space $O(N)$. |
| 2969 |
Minimum Number of Coins for Fruits II |
Same as 2944 (Recursion + Memoization). TLE due to N=10^5 and $O(N^2)$ DP. |
Dense DP Grid |
Draw a square N x N. Shade it to show lookback for each i. $O(N^2)$. |
DP + Monotonic Queue (Deque) |
Sliding Window Minimum |
Optimize 2944. Instead of searching $O(i)$ for the min dp[j], use a Deque to maintain the minimum of the range that can cover the current fruit in $O(1)$. |
Draw the dp array. Below it, draw a Deque box. Show values entering the right and "best" values popping off the left as they fall out of range. |
Single Linear DP Pass |
Draw a straight line of length N. Each element is added/removed from Deque once. T = $O(N)$. |
Deep recursion call stack. |
A 1D DP array and a Deque. Space $O(N)$. |
| 2970 |
Count the Number of Incremovable Subarrays I |
Try removing every possible subarray and check if the remaining array is strictly increasing. |
Nested Loop Verification |
Draw a line. Shade a segment to "remove". Check the rest. Repeat N^2 times. $O(N^3)$. |
Two Pointers (Prefix/Suffix Scan) |
Mirror-Image Increasing Segments |
Find the longest increasing prefix and suffix. For each prefix index, find the first suffix index that can be appended to keep the array strictly increasing. |
Draw array. Highlight the increasing head and tail. Draw a "bridge" between them that skips a middle section. Count valid bridges. |
Single Linear Pass (After head/tail scan) |
Draw a line of length N. The two pointers move towards each other. T = $O(N)$. |
Storing all subarray copies. |
Standard variables. Space $O(1)$ or $O(N)$ depending on implementation style. |
| 2971 |
Find Polygon With the Largest Perimeter |
Try every possible subset of sides (2^N) and check the polygon inequality for each. |
Exponential Subset Tree |
Draw a binary tree of depth N. Branch into "Take" or "Skip" for each side. Leaves = 2^N. |
Greedy (Sorting + Prefix Sums) |
Incremental Boundary Check |
Sort sides. Keep a running sum of the first i sides. If `sum(0 to i-1) > side[i]`, a polygon is possible with perimeter `sum + side[i]`. Track the max. |
Draw a sorted array. Below it, draw a "Sum Bar" that grows. For each new element, check if the Bar is longer than the new element. |
Sorting + Single Pass |
Draw a timeline. T = $O(N \log N)$ for sort + $O(N)$ for prefix sum scan. |
Massive recursion stack for subsets. |
A single long long for the running sum. Space $O(1)$ (ignoring sort). |
| 2972 |
Count the Number of Incremovable Subarrays II |
Same as 2970 (Brute force removal and verification). $O(N^3)$. |
Subarray Removal Grid |
Draw an N x N grid of shaded removal segments. Label "TLE" for N=10^5. |
Two Pointers (Optimized Prefix/Suffix) |
Dual-End Increasing Anchors |
Find the max increasing prefix [0, i] and suffix [j, N-1]. For each prefix index, binary search or use a second pointer to find the valid suffix start. |
Draw the array. Shade the "Head" and "Tail" that are increasing. Draw a sliding window between them that "skips" the middle junk. |
Two Sequential Scans |
Draw a line of length N. The two pointers move towards each other once. T = $O(N)$. |
Storing all subarray configurations. |
Standard integer pointers. Space $O(1)$. |
| 2973 |
Find Number of Coins to Place in Tree Nodes |
For each node, find all subtree nodes, try all triplets, and calculate products. |
Nested DFS + Triplet Search |
Draw a tree. From each node, draw a web to all descendants. $O(N^2 \\text{cdot descendants})$. |
Tree DP (Post-order Traversal) |
Bottom-Up Value Filtering |
Each node returns the top 3 largest and top 2 smallest (most negative) values from its subtree. Calculate max product using `max3` or `max1 * min2`. |
Draw a tree. At each node, draw a small "box" holding 5 numbers. Show children passing their boxes up to the parent to be merged. |
Linear Tree Traversal |
Draw a tree and trace a single line visiting every node and edge once. T = $O(N \cdot 5 \log 5)$ approx $O(N)$. |
Storing full descendant lists at each node. |
Each node stores exactly 5 integers in the recursion stack. Space $O(N)$. |
| 2974 |
Minimum Number Game |
Repeatedly scan the array to find the two smallest elements, swap them, and add to the result. |
Sequential Min-Search |
Draw an array. Draw an arrow searching the whole thing. Repeat N/2 times. $O(N^2)$. |
Sorting + Adjacent Swaps |
Paired Leap-frog |
Sort the array. For every pair (i, i+1), append nums[i+1] then nums[i] to the result list. |
Draw a sorted list. Draw a bracket over the first two. "Flip" them into a new list. Move to the next pair. |
Sorting + Linear Sweep |
Draw a timeline. T = $O(N \log N)$ for sort + $O(N)$ for swap-move. |
Temporary arrays for each game round. |
A single result array. Space $O(N)$. |
| 2975 |
Maximum Square Area by Removing Fences |
Try every combination of horizontal and vertical fence removals to form a square. |
Exhaustive Subset Removal |
Draw a grid. Branch into 2^H x 2^V removal states. Impossible for large N. |
Hash Set Intersection (Difference Checking) |
Venn Diagram of Segment Lengths |
Calculate all possible distances between any two horizontal fences and store in Set H. Do the same for vertical in Set V. The max common value in both sets is the side of the square. |
Draw horizontal lines. Write all possible gap sizes (e.g., fence 1-3, 1-4, 2-4). Put them in a circle. Find the biggest number that appears in the vertical circle too. |
Quadratic Set Population |
Draw two squares representing H^2 and V^2. T = $O(H^2 + V^2)$. |
Storing all subset grid states. |
Two Hash Sets of sizes H^2 and V^2. Space $O(H^2 + V^2)$. |
| 2976 |
Minimum Cost to Convert String I |
For each character change, run Dijkstra to find the minimum cost to transform char A to B. |
N Separate Graph Searches |
Draw 26 nodes (a-z). For every character in source, trace a path to target. $O(N \cdot (V+E)$log V). |
Floyd-Warshall (All-Pairs Shortest Path) |
26x26 Adjacency Matrix |
Precompute a 26 x 26 matrix `dist`. For each intermediate char `k`, update `dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])`. Then simply sum `dist[src[i]][tgt[i]]`. |
Draw a 26 x 26 grid. Fill with direct costs. Pick three nodes (i, j, k) and show how the path through 'k' might be cheaper. |
Constant Graph Size (26^3) + Linear Sweep |
Draw a small cube (26 side). Then a single line of length N. T = $O(26^3 + N)$. |
Many redundant priority queues. |
A 26 x 26 distance matrix. Space $O(1)$ relative to N. |
| 2977 |
Minimum Cost to Convert String II |
Same as 2976 but with variable-length substrings. Try every possible string partition and every replacement. |
Exponential Recursive Tiling |
Draw a tree where each node branches into all possible substring splits. $O(2^N)$. |
Trie + Floyd-Warshall + DP |
Prefix Tree with Distance Mapping |
Map each unique conversion string to an ID using a Trie. Run Floyd-Warshall on IDs. Use DP where dp[i] is min cost to convert first i chars: dp[i] = min(dp[j] + cost(j dots i)). |
Draw a Trie to ID strings. Draw a 1D DP array. For index i, draw arrows from all j < i where s[j dots i] has a known conversion. |
String Length x Unique Substrings |
Draw a square N x N. For each row, show a Trie traversal. T = $O(N^2 + U^3)$ where U is unique strings. |
Deep recursion call stack. |
Trie nodes, a distance matrix, and a DP array. Space $O(\text{Total Chars} + U^2)$. |
| 2978 |
Symmetric Coordinates |
A raw Cartesian self-join checking every row against every other row, leading to massive duplicate pairs. $O(N^2)$. |
Unfiltered Cartesian Web |
Draw Table A. Draw lines from every row in A to every row in a copy of Table A, circling matches but capturing duplicates. |
Self-Join with ROW_NUMBER() |
The Unique-ID Matcher |
Assign a unique ID (ROW_NUMBER) to each coordinate. Join the table to itself where `A.X = B.Y` and `A.Y = B.X`, but enforce `A.ID != B.ID` and `A.X <= A.Y` to prevent reverse duplicates. |
Draw the table. Add a unique "ID" sticker to each row. Draw a selective bridge only between rows that mirror each other AND have different ID stickers. |
Indexed Join $O(N \log N)$ |
Draw an index lookup tree feeding into a filtered join node. |
Massive temporary memory for N^2 joins. |
Database Hash/Merge join buffer. $O(N)$ space. |
| 2979 |
Most Expensive Item That Cannot Be Bought |
Try representing every number from 1 to N as a * x + b * y using two loops. |
Nested Coefficient Search |
Draw a grid of possible x, y values. Check if they sum to target. $O(\text{Target}^2)$. |
Frobenius Coin Problem (Math) |
Gaps in the Number Line |
The largest number that cannot be represented as ax + by for coprime a, b is exactly a * b - a - b. |
Draw a number line. Mark multiples of a and b. Show the "holes" where you can't reach. Highlight the last hole. |
Constant Time Calculation |
Draw a single dot. Write the formula: a x b - a - b. T = $O(1)$. |
Storing a "reachable" boolean array. |
No extra memory. Space $O(1)$. |
| 2980 |
Check if Bitwise OR Has Trailing Zeros |
Generate all $O(N^2)$ pairs, calculate bitwise OR, and check if the result is even. |
Quadratic Pair Grid |
Draw an N x N grid. Each cell is an OR operation. $O(N^2)$. |
Greedy (Count Even Numbers) |
Even Number Filter |
A bitwise OR has a trailing zero if the result is even. For the OR of two numbers to be even, both numbers must be even. Just check if there are at least two even numbers in the array. |
Draw the array. Circle any number divisible by 2. If you find two circles, you are done. |
Single Linear Pass |
Draw a straight line of length N. One modulo check per element. T = $O(N)$. |
Storing all pair results. |
One integer counter. Space $O(1)$. |
| 2981 |
Find Longest Special Substring That Occurs Thrice I |
Generate all $O(N^2)$ substrings, check if they are "special" (one char), and count frequencies in a map. |
Subarray Frequency Grid |
Draw an N x N triangle. Shade cells where all characters are identical. $O(N^3)$. |
Sliding Window + Frequency Map |
Grouped Character Tally |
Identify consecutive blocks of the same character (e.g., "aaaa"). A block of length L contributes to counts for lengths L, L-1, dots, 1. Find the max length with count >= 3. |
Write "aaaaabbb". Under "a", list lengths: 5, 4, 3. Under "b", list: 3, 2, 1. See which length across all letters has at least 3 occurrences. |
Single Linear Pass |
Draw a straight line of length N. One sweep to find blocks. T = $O(N)$. |
Storing all N^2 string slices in a map. |
A 2D array or map `count[26][N]`. Space $O(26N)$. |
| 2982 |
Find Longest Special Substring That Occurs Thrice II |
Same as 2981 (Brute force). TLE due to N=5 * 10^5. |
Massive Quadratic Area |
Draw a massive 500,000^2 grid. Label "CRITICAL TLE". |
Top-3 Length Tracking per Character |
Priority Queue per Character |
For each character, find all consecutive block lengths. You only need the top 3 longest lengths to determine if a substring of length X occurs 3 times. |
Draw 26 small buckets. For 'a', drop in block lengths [10, 5, 5]. The 3rd largest length (5) is your candidate. Or 10-2, or max(5, 10-1). |
Linear Sweep with Constant Sort |
Draw a line for N. For each block, sort 3 numbers. T = $O(N)$. |
Quadratic map storage. |
26 lists of size 3. Space $O(1)$ relative to N. |
| 2983 |
Palindrome Rearrangement Queries |
For each query, try all permutations of the specified ranges to see if the resulting string is a palindrome. |
Factorial Range Permutations |
Draw a string. Highlight two ranges. Show them branching into (R-L)! variants. $O(Q \cdot N!)$. |
Prefix Sums + Parity Symmetry Check |
Mirror-Image Frequency Balance |
A string is a palindrome if character counts in S[i dots j] match those in the "mirror" range in the second half. Use 2D prefix sums (26 chars) to verify range counts in $O(1)$. |
Draw the string with a center line. For a query, compare the char-count "boxes" of the left range and its corresponding mirror on the right. |
Preprocessing (26N) + Constant Query (26Q) |
Draw a line for N, then a line for Q. T = $O(26(N+Q)$). |
Storing permutation copies for every query. |
2D Prefix Sum array [26][N]. Space $O(26N)$. |
| 2984 |
Find Peak Calling Hours for Each City |
Group by City and Hour, get counts, then write a correlated subquery to rescan and find the max count for that specific city. |
Redundant Subquery Scan |
Draw City buckets. Inside, draw Hour buckets. Draw a magnifying glass that rescans every Hour bucket twice. |
Window Function (RANK) |
The Peak-Hour Ranker |
Group by City and Hour to get call counts. Wrap this in a CTE, and use `RANK() OVER (PARTITION BY City ORDER BY call_count DESC)`. Select where rank = 1. |
Draw City buckets. Sort the Hour blocks inside them by height (call count). Slap a "#1" sticker on the tallest block(s) in each bucket and toss the rest. |
Partitioned Sort $O(N \log N)$ |
Draw a pipeline: Group rightarrow Sort rightarrow Rank rightarrow Filter. |
Temp tables for subquery processing. |
DB sorting buffer. $O(\text{Cities})$ space. |
| 2985 |
Calculate Compressed Mean |
Expand the compressed data into individual rows (e.g., generating 5 rows if count=5), then running `AVG()`. |
Row-Unrolling Explosion |
Draw a compressed row `[Value: 10, Count: 5]`. Draw a machine blowing it up into 5 separate `[10]` rows before averaging. |
Weighted Average Formula |
The Weighted Math Node |
Do the math directly on the compressed data: `SUM(item_value * count) / SUM(count)`. Round the result as needed. |
Draw a row. Multiply the two columns to get a "Total Weight". Sum all weights, sum all counts, and divide the two giant numbers. |
Single Linear Pass $O(N)$ |
Draw a single straight line through the rows applying constant $O(1)$ math. |
Massive RAM to hold unrolled rows. |
Two running sum variables in the DB engine. $O(1)$ space. |
| 2986 |
Find Third Transaction |
Use nested subqueries with `COUNT` or `GROUP BY` to find users with >= 3 transactions, then join back to filter. |
Nested Loop Join Web |
Draw two tables. Show arrows from the filter query scanning the main table N times. $O(N^2)$. |
Window Function (`RANK()` / `ROW_NUMBER()`) |
Segmented Row Enumeration |
Partition the data by `user_id` and order by `transaction_date`. Assign a number to each row. Filter where number is 3. |
Draw a table. Group rows by User ID. Write 1, 2, 3... next to each group. Highlight the 3rd row in each block. |
Single Pass Partition Scan |
Draw a line for N. The sort-and-partition step takes $O(N \log N)$. T = $O(N \log N)$. |
Multiple temporary tables in memory. |
One sorted data frame in memory. Space $O(N)$. |
| 2987 |
Find Expensive Cities |
Join the `Listings` table with a subquery that calculates the overall average price of all cities. |
Cross-Product Average Mapping |
Draw a table and a single "Global Avg" box. Show every row pointing to that box for comparison. $O(N^2)$. |
Aggregate Comparison (HAVING Clause) |
Group-Level Thresholding |
Group by `city` and calculate the average. Use the `HAVING` clause to filter cities where `AVG(price)` > (Global Avg). |
Draw city clusters. Calculate the mean for each cluster. Compare each cluster's mean against the global mean line. |
Single Grouped Pass |
Draw a horizontal line of N records. Total T = $O(N)$. Sorting by city takes $O(N \log N)$. |
Cartesian join memory overhead. |
Hash map of city averages. Space $O(\text{Unique Cities})$. |
| 2988 |
Manager of the Largest Department |
Find department sizes using `GROUP BY`, then use a subquery with `MAX()` to find the ID, then join to find the manager. |
Multi-Join Hub |
Draw three interconnected circles representing three separate query steps. $O(N^2)$. |
Window Function (`DENSE_RANK()`) |
Department Size Ranking |
Count employees per department. Use `DENSE_RANK()` to rank these counts. Filter where `rank = 1` and `position = 'Manager'`. |
Draw a bar chart of department sizes. Order them from tallest to shortest. Assign '1' to the tallest bar. |
Sorted Aggregation Timeline |
Draw a timeline of N employees. Sorting into departments takes $O(N \log N)$. T = $O(N \log N)$. |
Multiple intermediate result sets stored on disk. |
A single grouped data frame in memory. Space $O(\text{Departments})$. |
| 2989 |
Class Performance |
Calculate the sum of three scores for every student, then use `ORDER BY` and `LIMIT 1` twice to get Max and Min. |
Dual Sorting Pass |
Draw two lines. Show the array being sorted twice (once ascending, once descending). $O(2N \log N)$. |
Aggregate Math (`MAX` - `MIN`) |
Extremity Difference Mapping |
Calculate the total score per student. Simply select `MAX(total) - MIN(total)` from this derived set. |
Draw a number line. Mark the furthest left dot (Min) and the furthest right dot (Max). Draw a bracket showing the distance between them. |
Single Sweep with Scalars |
Draw a straight line of length N. Track two variables (min, max). T = $O(N)$. |
Storing two sorted copies of the dataset. |
Two scalar integer variables. Space $O(1)$ relative to N. |
| 2990 |
Loan Types |
Self-join the `Loans` table to find users who have both 'Mortgage' and 'Refinance' entries. |
Self-Join Intersection |
Draw two identical tables. Draw lines connecting matching `user_id`s that have different `loan_type`s. $O(N^2)$. |
Grouping + `COUNT(DISTINCT)` with `HAVING` |
Subset Filtering Diagram |
Group by `user_id`. Filter where specific loan types exist using a `CASE` statement or `IN` clause within a `HAVING` count condition. |
Draw circles for users. Inside each circle, list their loan types. Circle the user only if 'Mortgage' AND 'Refinance' are both inside. |
Single Grouped Sweep |
Draw a line of N loan records. T = $O(N)$. Sorting for grouping takes $O(N \log N)$. |
Quadratic row growth during the self-join. |
A single bit-map or hash set per user. Space $O(\text{Users})$. |
| 2991 |
Top Three Wineries |
Use multiple self-joins and `DISTINCT` counts to find the top three wineries per country. |
Nested Loop Join Web |
Draw three identical tables. Connect rows from A to B to C to find ranking. $O(N^3)$. |
Window Function (`RANK()`) + Pivoting |
Ranked List Transformation |
Rank wineries by points within each country. Use `CASE` statements with `MAX()` to pivot the top 3 into columns. |
Draw a table. Group by Country. Write "1", "2", "3" next to wineries. Then "rotate" the top 3 into one row. |
Single Sorted Sweep |
Draw a timeline. T = $O(N \log N)$ for ranking + $O(N)$ for pivoting. |
Massive temporary tables for multiple self-joins. |
One grouped result set in memory. Space $O(\text{Countries})$. |
| 2992 |
Number of Self-Divisible Permutations |
Generate all N! permutations and check if each index i satisfies i % perm[i] == 0 or perm[i] % i == 0. |
Factorial Decision Tree |
Draw a root branching N times, then N-1... Depth N. $O(N!)$. |
Backtracking with State Pruning (Bitmask) |
Pruned Recursion Tree |
Pick a number for the first position. Only proceed if it satisfies the divisibility condition. Use a bitmask to track used numbers. |
Draw a tree. For each branch, write the divisibility check. If it fails, draw a "stop" sign and don't branch further. |
Exponential Search with Early Exit |
Draw a tree where most branches are cut short. T ll $O(N!)$, closer to $O(2^N)$ in practice. |
Storing all valid permutations in a list. |
Recursion stack and a single integer mask. Space $O(N)$. |
| 2993 |
Friday Purchases I |
Scan the entire `Purchases` table and use a subquery for every row to check if the date is a Friday in November 2023. |
Linear Scan with Row-wise Check |
Draw a table. Point to every row and calculate `DAYOFWEEK`. $O(N)$. |
Date Filtering + Grouping |
Calendar Highlighting |
Filter rows where `DATE_FORMAT` is Friday and month is November. Group by week of month and sum the amounts. |
Draw a calendar for November 2023. Circle the Fridays. Sum the amounts for each circled date. |
Single Filtered Pass |
Draw a straight line of length N. T = $O(N)$. |
Temporary strings for every date conversion. |
One aggregated result table. Space $O(1)$ (only 4-5 Fridays). |
| 2994 |
Friday Purchases II |
Same as 2993 but use complex joins to include Fridays with zero purchases. |
Join against Constant List |
Draw a table of all 30 days. Join with your purchase data. $O(30 \cdot N)$. |
Recursive CTE (Date Generation) + Left Join |
Timeline Filling Diagram |
Generate all 4 Fridays in November 2023 using a Recursive CTE. `LEFT JOIN` these against the `Purchases` table. Use `COALESCE(sum, 0)`. |
Draw 4 empty boxes (Fridays). Pour purchase data into them. If a box stays empty, write "0". |
Constant-Time Generation + Linear Join |
Draw a line of 4 items. T = $O(N)$. |
Redundant row storage for zero-purchase days. |
A small fixed-size date table. Space $O(1)$. |
| 2995 |
Viewers Turned Streamers |
Use subqueries to find the first session of every user, then filter the original table in another pass to find streamers. |
Two-Pass Scan Web |
Draw a table. Scan once for "Firsts", then again for "Streamers". $O(N^2)$. |
Window Function (`FIRST_VALUE`) / `RANK()` |
Attribute Tagging |
Assign a "first session type" to every row using `FIRST_VALUE() OVER(...)`. Filter for rows where `first_type = 'Viewer'` and current is `Streamer`. |
Draw a table. Add a "First Type" column. Fill it by looking at the earliest session for each ID. Circle rows that are 'Streamer' but have 'Viewer' in the new column. |
Sorted Linear Pass |
Draw a timeline. T = $O(N \log N)$ for the window function. |
Multiple intermediate CTE tables. |
One augmented data frame in memory. Space $O(N)$. |
| 2996 |
Smallest Missing Integer Greater Than Sequential Prefix Sum |
Calculate the sequential prefix sum, then iterate through the entire array for every integer starting from that sum until one is missing. |
Sequential Loop Search |
Draw a line. Scan the prefix. Then draw many overlapping loops back to the original array for each check. $O(N^2)$. |
Simulation + Hash Set |
Prefix Breakpoint + Membership Set |
Identify the first index where `nums[i] != nums[i-1] + 1`. Sum the prefix. Use a Hash Set to find the first integer >= sum missing in $O(1)$. |
Draw the array. Shade the sequential part. Below it, list all unique numbers in a "Membership Box". Start a counter at the sum and "bounce" off the box. |
Single Pass + Constant Membership Checks |
Draw a line of length N. The Set population is $O(N)$, and the final missing search is at most $O(N)$. Total T = $O(N)$. |
Storing multiple copies of the array for searches. |
A Hash Set of unique integers from the array. Space $O(N)$. |
| 2997 |
Minimum Number of Operations to Make Array XOR Equal to K |
Try flipping every possible bit in every element recursively to see if the resulting XOR equals k. |
Exponential Bit-flip Tree |
Draw a tree where each node branches 32 times (bits) for each array element. Depth N. $O(2^N \cdot 32)$. |
Bitwise XOR Properties + Hamming Distance |
Binary Column Summation |
XOR all elements to get `totalXOR`. The number of flips is the number of bits where `totalXOR` differs from k. Use `totalXOR ^ k` and count set bits. |
Write all numbers and k in binary stacked vertically. XOR the columns. Circle the columns where the result doesn't match k. Count circles. |
Single Linear XOR Reduction |
Draw a straight line of length N. One XOR operation per number. T = $O(N)$. |
Deep recursion stack for all flip combinations. |
One or two 32-bit integer variables. Space $O(1)$. |
| 2998 |
Minimum Number of Operations to Make X and Y Equal |
Explore every sequence of the 4 operations (increment, decrement, divide by 5, divide by 11) without memoization. |
Exploding 4-ary Search Tree |
Draw a root branching 4 times. Each child branches 4 more. Size grows as 4^steps. |
Breadth-First Search (BFS) / Shortest Path |
Graph Layer Expansion |
Treat each number as a node in a graph. Operations are edges with weight 1. Run BFS starting from x until you hit y. |
Draw circles for numbers. Draw 4 arrows from x to new numbers. Put new numbers in a "Queue" box. Keep track of "Visited" nodes in another box. |
State Space Search (Linear with respect to X) |
Draw a circle representing numbers from 0 to X+11. Each node is visited once. T = $O(X)$. |
Infinite recursion stack. |
A Queue and a "Visited" Set/Array. Space $O(X)$. |
| 2999 |
Count the Number of Powerful Integers |
Iterate through every integer from `start` to `finish` and check if each digit <= limit and if it ends with s. |
Brute Force Range Sweep |
Draw a massive timeline from 1 to 10^15. Mark $O(10^15)$ checks. Impossible. |
Digit Dynamic Programming (Digit DP) |
State Tree with Tight Constraints |
Process digit by digit. dp(pos, isTight) counts valid suffixes. If remaining length matches s, verify s is valid. Range [L, R] is count(R) - count(L-1). |
Draw a tree where each depth is a digit position (0-9). Add branches for each digit 0 dots min(limit, current_digit). Use a "Tight" flag to stay under the limit. |
Logarithmic in Value (Linear in Number of Digits) |
Draw a line of length log_10(finish). Each step has at most 10 branches. T = $O(\text{digits} \cdot 10)$. |
Not applicable (time too high). |
Memoization table of size `digits x 2`. Space $O(\text{digits})$. |
| 3000 |
Maximum Area of Longest Diagonal Rectangle |
Calculate diagonal for all rectangles, sort them by diagonal, then pick the one with max area among ties. |
Sort-based Selection |
Draw N rectangles. Rearrange them by size. $O(N \log N)$. |
Single Pass Comparison (Pythagorean Theorem) |
Max-Tracker Variable |
Iterate through rectangles. Compute L^2 + W^2. If > currentMax, update maxDiagonal and maxArea. If == currentMax, update maxArea = max(maxArea, L * W). |
Draw rectangles. Write L^2+W^2 inside each. Maintain two scalar boxes: "Best Diagonal" and "Best Area". Cross them out and update as you scan. |
Single Pass Timeline |
Draw a straight line of length N. One constant-time math check per item. T = $O(N)$. |
Storing a sorted list of all rectangle data. |
Two integer variables for tracking. Space $O(1)$. |
| 3001 |
Minimum Moves to Capture The Queen |
BFS/DFS to explore all valid Rook and Bishop moves on the board until the Queen is captured (up to depth 2). |
State-Space Search Tree |
Draw the root node as the initial board. Branch out 14 lines for all Rook moves and 13 for Bishop moves. Label tree depth. |
Math / Geometry (Line of Sight checks) |
8x8 Coordinate Grid |
Plot coordinates. Trace straight horizontal/vertical lines for the Rook and diagonal lines for the Bishop. Check if the Queen is hit and if the other piece blocks the path. |
Sketch an 8x8 square grid. Mark R, B, Q. Draw solid arrows for lines of sight and an 'X' if a piece blocks the line. |
$O(1)$ Constant Time Box |
Draw a single, solid square box labeled "O(1) Math Operations". No loops, just conditional variable checks. |
Call Stack or Queue, drawn as a list of state tuples: [(rx, ry, bx, by, depth)]. |
Six isolated memory cells (small boxes) holding the integer coordinates: rx, ry, bx, by, qx, qy. |
| 3002 |
Maximum Size of a Set After Removals |
Generate all possible combinations of removing exactly n/2 elements from both arrays, then calculate the union size for each. |
Combinatorial Decision Tree |
Draw a root node splitting into "Pick / Don't Pick" for elements in nums1, then cascading into nums2. Label branches to show exponential $O(2^N)$ growth. |
Greedy Selection + Hash Sets |
Venn Diagram |
Draw Set 1 and Set 2. Place unique numbers in the left circle, unique in the right, and shared in the intersection. Greedily take up to n/2 from unique sides first, then fill remaining capacity from the intersection. |
Draw two overlapping circles. Write numbers: n1_only, n2_only, shared. Write the formula: min(n/2, n1_only) + min(n/2, n2_only) + shared capped at n. |
Linear Sequence Diagram |
Draw three sequential blocks on a timeline: "Array1 to Set $O(N)$", "Array2 to Set $O(N)$", and "Set Intersection $O(N)$". |
Overlapping stack frames representing recursion, drawn as an array subset shrinking at each step. |
Two Hash Tables, drawn as arrays with buckets containing the unique integers from the input. |
| 3003 |
Maximize the Number of Partitions After Operations |
Modify each of the N characters to all 26 lowercase letters one by one, then run the greedy partition algorithm for all 26*N resulting strings. |
Modification Array + Simulation Timeline |
Draw N main branches (one for each character index). From each, draw 26 sub-branches. Draw a linear array next to each leaf to represent the $O(N)$ evaluation. |
Dynamic Programming with Bitmasking (State Compression) |
State Transition Graph |
Track current index, a boolean changed flag, and a bitmask of current partition characters. When changing a letter or exceeding 'k' unique chars, visually jump to the new updated state block. |
Create a DP table with columns: Index, Changed (T/F), Bitmask (binary). Draw directed arrows showing how adding a new character updates the bitmask or forces a partition reset. |
3D Memoization Bounds |
Draw a 3D grid cube. Label the axes: Length N, Changed (0/1), and Bitmask State Space. |
A massive list of strings, drawn as 26*N separate full string arrays stacked on top of each other. |
A Key-Value HashMap table mapping the tuple (index, changed, bitmask) to the integer max_partitions. |
| 3004 |
Maximum Subtree of the Same Color |
For every single node in the tree, launch a fresh DFS to check if all nodes in its subtree match its color. Track the maximum size found. |
Nested Trees (Tree inside a Tree) |
Draw the main tree. Next to each node, draw a mini-version of its subtree to represent the $O(N^2)$ repetitive traversal. |
Bottom-Up Post-Order DFS (Tree DP) |
Upward Propagation Tree |
Start at the leaf nodes. Pass up a tuple: [size, is_valid, color]. If children match the parent's color and are valid, combine their sizes. If not, mark is_valid=False but keep tracking the global max. |
Draw the tree. Write [size, T/F, color] next to each node. Draw thick arrows pointing upward from children to parents, showing how the tuples merge. |
Single-Pass Node Highlighting |
Draw the tree. Highlight each node exactly once with a highlighter, writing $O(N)$ next to the root. |
A deep Call Stack representing DFS(node) triggering repeatedly inside an outer loop over all nodes. |
A single Call Stack where each frame holds an array [size, is_valid] immediately returning its memory to the parent caller. |
| 3005 |
Count Elements With Maximum Frequency |
Nested loops. For each element, iterate through the entire array to count its occurrences. Find the max, then iterate again to sum. |
Arrow-Matrix Scanning |
Write the array horizontally. From each element, draw a looping arrow that bounces across the entire array. |
Single/Double Pass Hash Map (Frequency Array) |
Frequency Histogram / Bins |
Read the array left to right. Drop each number into a labeled bucket, visually increasing its height. Find the tallest bucket(s) and sum their heights. |
Draw an array of items. Below it, draw buckets (squares). Add tally marks. Circle the bucket(s) with the most tallies. |
Linear Scan Bar |
Draw two horizontal bars representing $O(N)$ array passes: "Map Building" and "Max Summing". |
Primitive counter variables shifting constantly with $O(1)$ extra space but heavy time overhead. |
A Hash Map drawn as a 2-column table: [Number | Frequency]. |
| 3006 |
Find Beautiful Indices in the Given Array I |
Using built-in string searches, find an index `i` matching string `a`, then scan the whole string to find all indices `j` matching `b`, checking `|i-j| <= k`. |
Two-Pointer Sliding Window Overlap |
Draw string `s`. Underline `a` matches in red, `b` in blue. Draw lines connecting every red line to every blue line, crossing out distances > `k`. |
KMP String Matching + Binary Search / Two Pointers |
Parallel Number Lines (Sorted Arrays) |
Find all indices of `a` (list A) and `b` (list B). Place pointers `p1` on A and `p2` on B. Move `p2` monotonically to catch up to `p1 - k`. Check if `p2` is within `p1 + k`. |
Draw two horizontal number lines. Place dots for indices A and B. Draw a bracket [ -k, +k ] centered on a dot on line A to see if line B's dots fall inside. |
3-Phase Timeline |
Draw three blocks: "KMP(A) $O(N)$", "KMP(B) $O(N)$", "Two Pointers $O(A+B)$". |
Variables mapping `s.substring(i, i+len)` creating heavy temporary string allocations in memory. |
Two distinct, sorted integer arrays indicesA and indicesB loaded sequentially in memory. |
| 3007 |
Maximum Number That Sum of Prices Is Less Than or Equal to K |
Iterate num from 1 upwards. For each number, convert to binary, check bits at `x`, `2x`, `3x`... Add to total price until limit `K` is hit. |
Binary Accumulation Table |
Draw a table with columns: Number, Binary, Bits at x, Total Price. Fill row by row until Total > K. |
Binary Search on Answer + Bit Digit DP (Math) |
Binary Column Cycle Counting |
Binary search a massive mid. To get the price of mid, look at bit columns vertically. Each column i flips exactly every 2^i numbers. Calculate the math formula for 1s in valid columns. |
Draw a grid of binary numbers. Highlight vertical columns `x`, `2x`. Bracket the repeating 0-1 blocks (size 2^i). Write the cycle formula. |
Logarithmic Search Tree |
Draw a wide horizontal line from 1 to 10^15. Draw binary search jumps halving the space, with $O(\log N)$ math calculations per jump. |
A single accumulator integer variable total_price incrementing indefinitely. |
Variables `low`, `mid`, `high` shifting across a massive 64-bit integer address space. |
| 3008 |
Find Beautiful Indices in the Given Array II |
(Same as 3006, but constraints are 10^5, so Brute Force will result in Time Limit Exceeded). |
Explosion Graphic |
Draw a clock on fire. The $O(N^2)$ string matching will mathematically fail the 1-second execution limit. |
KMP Prefix Function (LPS) + Monotonic Two Pointers |
KMP State Machine Automaton |
Draw the LPS (Longest Prefix Suffix) array as backward arrows. As you scan `s`, if characters match, move right. On mismatch, follow the backward arrow to avoid re-evaluating characters. |
Write the pattern string in square boxes. Draw curved fallback arrows pointing leftwards from each box to its LPS index. |
Linear Monotonic Arrows |
Draw two arrays. Draw pointers `i` and `j` that only point to the right, signifying strictly $O(N)$ traversal. |
Call stack overflow or massive garbage collection from native `.indexOf()` string slicing. |
An LPS Array (Longest Prefix Suffix), drawn as an integer array mapping character indices back to their prefix fallback indices. |
| 3009 |
Maximum Number of Intersections on the Chart |
Test every single Y-coordinate where a line segment starts or ends, and for each one, iterate through all line segments to count intersections. |
Horizontal Scan-Lines |
Draw a jagged line chart. Draw dense horizontal lines crossing through every peak and valley. Draw circles everywhere these horizontal lines intersect the chart lines. |
Line Sweep Algorithm / Difference Array |
Vertical Event Sorting |
Sweep a horizontal line from bottom to top. When the line hits the lower bound of a segment, add 1. When it hits the upper bound, subtract 1. Track the running maximum. |
Draw the jagged chart. On the Y-axis, write '+1' where a segment goes up through a point, and '-1' where it stops. Keep a running tally as you point your pencil up the axis. |
1D Event Array Timeline |
Draw an array of events sorted by Y-coordinate. Show a single forward-moving arrow calculating the prefix sum in $O(N \log N)$. |
A massive 2D matrix or map testing every Y-value against an array of all line segments. |
A 1D array of Tuples [(y_coord, +1), (y_coord, -1)] sorted sequentially in memory. |
| 3010 |
Divide an Array Into Subarrays With Minimum Cost I |
Use three nested loops to test every possible way to drop two partition lines into the array, calculate the cost of the 3 resulting subarrays, and track the minimum. |
Array Slicing Combinations |
Draw the array. Draw two vertical lines cutting the array. Redraw the array multiple times below it, shifting the lines rightwards sequentially to show the $O(N^3)$ combinations. |
Greedy Selection (Math/Sorting) |
Fixed Anchor + Top 2 Selection |
Notice the first subarray must start at index 0, so nums[0] is an unavoidable cost. The problem then reduces to simply finding the two absolute smallest numbers in the rest of the array. |
Draw the array. Put a heavy box around index 0 (Anchor). Scan the rest of the array and circle the two smallest numbers. Connect the three boxed/circled numbers with a plus sign. |
Single Linear Pass |
Draw one straight arrow across the array from index 1 to N, doing constant $O(1)$ checks. |
Indices i, j, k keeping track of recursive boundary cuts. |
Three isolated integer variables: cost1 (anchor), min1, and min2. |
| 3011 |
Find if Array Can Be Sorted |
Run a standard Bubble Sort. Every time you need to swap two elements, count their set bits. If the bit counts differ, abort and return false. |
Conditional Bubble Sort |
Draw the array. Draw swapping arrows between adjacent elements. Put a big red 'X' on an arrow if the binary 1-counts of the two numbers don't match. |
Array Grouping by Set Bits + Min/Max Tracking |
Segmented Array Blocks |
Group adjacent numbers that share the same bit-count into contiguous blocks. For the array to be sortable, the maximum value of the previous block must be less than or equal to the minimum value of the current block. |
Draw the array. Draw vertical walls between numbers with different bit-counts. In each walled section, write the Min and Max. Draw an arrow checking if Prev_Max <= Curr_Min. |
Segmented Linear Scan |
Draw a single pass timeline. Show block boundaries being evaluated in $O(N)$ time without actually sorting the elements. |
The full array constantly shifting elements around in memory. |
Four integer variables: prev_max, curr_max, curr_min, and current_bit_count. |
| 3012 |
Minimize Length of Array Using Operations |
Simulate the game: recursively try taking every pair of elements, replacing them with their modulo if it's strictly greater than zero, and branching to see which path yields the shortest array. |
State Space Explosion Tree |
Draw an array. Branch it out into N^2 new arrays, showing every possible pairing and modulo result. |
Math / Number Theory (Global Minimum modulo reduction) |
Modulo Reduction Flowchart |
Find the absolute smallest number. If any number in the array modulo this minimum is > 0, that remainder becomes the new, strictly smaller unique minimum, destroying everything else (Length = 1). Otherwise, the minimums can only cancel each other out. |
Draw a funnel. Throw all numbers in. The smallest number sits at the bottom. Check if any number can "chip away" at the minimum using modulo. If yes, write "Ans: 1". If no, tally the minimums and divide by 2. |
2-Pass Scan Box |
Draw two $O(N)$ blocks. Block 1: "Find Min". Block 2: "Check Modulos & Count Min occurrences". |
Deep recursive call stacks holding cloned arrays of shrinking sizes. |
A single integer variable tracking the global_min and another tracking its frequency_count. |
| 3013 |
Divide an Array Into Subarrays With Minimum Cost II |
Generate all possible combinations of selecting k-1 starting indices within the distance constraint dist. |
Windowed Combinatorics |
Draw a sliding window over the array. Inside the window, draw branching lines selecting every valid combination of k-1 elements. |
Sliding Window + Two Heaps (or Balanced BST) |
Dynamic Top-K Window |
Fix nums[0]. Slide a window of size dist + 1 over the rest of the array. Inside this window, you need to track the sum of the k-1 smallest elements. As the window moves, add the new element to the active set and remove the outgoing element, rebalancing the heaps. |
Draw the array with a sliding bracket. Below it, draw a line splitting elements into two boxes: "Active (k-1 smallest)" and "Reserve". When moving the bracket, show elements swapping between Active and Reserve to maintain the smallest sum. |
Logarithmic Shift Wave |
Draw a horizontal line for the sliding window $O(N)$. For every step, draw a small vertical wave representing the $O(\log N)$ heap rebalancing. |
A brute-force array subset that gets fully re-sorted $O(N \log N)$ every time the window shifts by one. |
Two Priority Queues (Min-Heap and Max-Heap) or an Indexed Tree managing the sliding subset. |
| 3014 |
Minimum Number of Pushes to Type Word I |
Generate all mathematical permutations of 26 letters assigned to 8 keys and calculate the typing cost for each combination. |
Permutation Tree |
Draw a root node branching out 8 ways, representing the first letter assignment. From each branch, draw 8 more branches. Label it as $O(8^N)$. |
Greedy Chunking (Math) |
8-Bin Overflow Array |
Letters are distinct. Fill the 8 available keys (cost 1 push). The next 8 overflow to the second position on the keys (cost 2 pushes), and so on. |
Draw 8 empty buckets. Write the string letters sequentially into the buckets one by one. Count the vertical depth of each letter to get its push cost. |
Constant Math Block |
Draw a single box labeled $O(N)$. Inside, write the formula: `cost += (index / 8) + 1`. |
A massive recursive call stack holding partial string permutations. |
No extra structures. A single integer variable `total_pushes` accumulating cost. |
| 3015 |
Count the Number of Houses at a Certain Distance I |
Run a standard Breadth-First Search (BFS) starting from every single house to find the shortest path to all other houses. |
N-Layered BFS Trees |
Draw a straight line of nodes (houses). Below it, draw N separate radial expanding circle graphs, showing BFS exploring outward from every single node. |
Floyd-Warshall Algorithm (All-Pairs Shortest Path) |
3D State Matrix Update |
Initialize a distance matrix. For every intermediate node 'k', check if the path from 'i' to 'j' through 'k' is shorter than the direct path. If yes, update the cell `(i, j)`. |
Draw a grid. Pick an intermediate column/row. Draw arrows from cell `(i, k)` and `(k, j)` pointing to `(i, j)` to see if their sum is smaller than the current value. |
$O(N^3)$ Cubed Loop Box |
Draw a 3D cube. Label the axes `i`, `j`, and `k` to represent the three nested loops traversing the nodes. |
N separate `Queue` structures and `Visited` sets instantiated repeatedly. |
A 2D integer array `dist[N][N]` dynamically updating in-place. |
| 3016 |
Minimum Number of Pushes to Type Word II |
Backtracking to test all combinations of mapping high-frequency characters to the shortest key depths. |
Combinatorial Backtracking Tree |
Draw a decision tree assigning the most frequent character to key 2, then key 3, etc., backtracking on suboptimal paths. |
Greedy Assignment + Frequency Sorting |
Sorted Frequency Histogram |
Count all characters. Sort them so the highest frequency characters are grouped first. Greedily assign the top 8 to depth 1, the next 8 to depth 2, multiplying frequency by depth. |
Draw a bar chart where height is frequency. Sort bars descending. Draw vertical lines slicing the bars into chunks of 8. Multiply bar height by its chunk number (1, 2, 3...). |
Sorting Timeline Bar |
Draw a block for "Count Freq $O(N)$", followed by a block for "Sort Array $O(26 \log 26)$". |
Heavy recursive state arrays tracking mapped keys. |
A Hash Map (or size 26 integer array) mapping `Character -> Frequency`. |
| 3017 |
Count the Number of Houses at a Certain Distance II |
Apply Floyd-Warshall or BFS. (This results in Time Limit Exceeded because N is 10^5, leading to $O(N^3)$ or $O(N^2)$ complexity). |
Explosion Graphic |
Draw a clock on fire. A 10^5 matrix requires 10 billion operations, making brute force impossible. |
Prefix Sums / Difference Array (Line Sweep) |
Overlapping 1D Intervals |
Instead of checking node by node, identify ranges of distances affected by the extra edge. Add `+1` at the start of an affected distance interval and `-1` right after it ends, then sweep across to calculate actual counts. |
Draw a horizontal number line representing distances. Draw brackets `[start, end]` for paths. Write `+1` on the start tick and `-1` on the end tick. Sweep left-to-right to accumulate the running sum. |
Linear Pass Arrow |
Draw a single straight arrow sweeping across an array representing strictly $O(N)$ operations. |
A memory-crashing 10^5 x 10^5 2D matrix (exceeds heap space). |
A 1D integer Difference Array `diff[N+1]` resolving the overlapping ranges. |
| 3018 |
Maximum Number of Removal Queries That Can Be Processed I |
Recursively try both options: process the query by taking the left element, and branch again by taking the right element. |
Binary Decision Tree |
Draw the root array. Draw two branches splitting downwards: "Remove Left" and "Remove Right", tracking the query index. Shows $O(2^Q)$ explosion. |
2D Dynamic Programming (Interval DP) |
Shrinking Matrix Table |
Use a DP table where row `i` and col `j` represent the remaining array `nums[i...j]`. If the left element matches the query, move down. If the right matches, move left. Take the max valid path. |
Draw a 2D grid. The top-right cell represents the full array `(0, n-1)`. Draw arrows moving strictly Down (picking left) or Left (picking right), filling cells with the max queries matched. |
$O(N^2)$ Matrix Fill |
Draw a grid highlighting only the upper triangle, showing the $O(N^2)$ state space being filled iteratively. |
Exponential Call Stack frames holding array indices and query pointers. |
A 2D DP Array `dp[left_index][right_index]` caching overlapping subproblems. |
| 3019 |
Number of Changing Keys |
Convert the entire string to lowercase first, then loop through comparing index `i` with `i-1` and incrementing a counter. |
Two-Step Array Transformation |
Draw the original string. Below it, draw the fully lowercased string. Draw looping arrows between adjacent characters counting the differences. |
Single-Pass Constant Space Scan |
In-Place Sliding Window (Size 2) |
Read the string left to right. Convert characters to lowercase on the fly. Compare the current lowercase character strictly to the previous lowercase character. |
Write the original string. Use a two-finger sliding window. If the letters under your fingers differ (ignoring case), put a tally mark above them. |
Single $O(N)$ Timeline |
Draw one straight arrow across the string. Label it $O(N)$ Time, $O(1)$ Space. |
A newly allocated full string in memory to hold the lowercase version, taking $O(N)$ space. |
A single character variable `prev_char` and an integer `count` taking $O(1)$ space. |
| 3020 |
Find the Maximum Number of Elements in Subset |
Generate all possible subsets of the array, then validate each subset to see if it perfectly matches the required peak pattern (x, x^2, x^4... x^2, x). |
Subset Explosion Tree |
Draw the array branching out into 2^N paths representing "Include" or "Exclude" for every single element. |
Hash Map Frequencies + Mathematical Chaining |
Directed Graph of Squares |
Count all frequencies. Start at the smallest keys. If a key has count >= 2, draw an arrow to its square. Keep chaining until the square doesn't exist or count is 1. Special case for `1` (count must be odd). |
Draw circles for unique numbers. Write their frequencies inside. Draw arrows from `x` to `x^2`. Trace the longest valid path of arrows where intermediate nodes have frequency >= 2. |
Logarithmic Chain Search |
Draw short sequential chains. Because numbers square rapidly (x, x^2, x^4, x^8...), the max chain length is strictly bound by $O(\log(\log(\text{Max}_\text{Val})$)). |
Massive recursive call stacks holding arrays of generated subsets. |
A Frequency Hash Map mapping `Integer -> Count`. |
| 3021 |
Alice and Bob Playing Flower Game |
Double nested loop: iterate `x` from 1 to `n`, and `y` from 1 to `m`. Check if `x + y` is odd to count valid pairs. |
2D Grid Traversal |
Draw a grid of size N x M. Check every single cell one by one, writing "Odd" or "Even". Tally the odds. $O(N \cdot M)$ time. |
$O(1)$ Combinatorics (Parity Math) |
4-Quadrant Multiplication Box |
Recognize that an odd sum only happens when you add an (Odd + Even) or (Even + Odd). Calculate total odd/even numbers in `n` and `m` using simple division. Multiply them. |
Draw a 2x2 matrix. Rows are `N (Odd, Even)`, Cols are `M (Odd, Even)`. Draw an 'X' in (Odd, Odd) and (Even, Even). Circle the other two cells and write the multiplication formula. |
$O(1)$ Constant Time Box |
Draw a single solid square box labeled "O(1) Math Operations". No loops at all. |
Accumulator variables nested inside a double loop. |
Four isolated integer variables: `odd_n`, `even_n`, `odd_m`, `even_m`. |
| 3022 |
Minimize OR of Remaining Elements Using Operations |
Use Backtracking/DFS to try all possible valid ways to merge adjacent elements `k` times, calculate the final OR sum, and find the minimum. |
Decision Tree of Array Merges |
Draw the array. Branch off showing different adjacent pairs combining via bitwise AND, creating $O(2^N)$ nested states. |
Greedy Bitwise Masking (MSB to LSB) |
Bit Matrix Filtering |
Build a target answer bit by bit from most significant to least. Assume we can force a bit to 0. Test if we can group the array elements (using bitwise AND) within `k` operations to achieve this target mask. |
Write the numbers in binary stacked vertically. Read columns left to right. Try to "cross out" (force to 0) the leftmost column. Group adjacent numbers until their AND result has a 0 in that column. If it takes <= `k` groups, keep it crossed out. |
30-Bit Linear Check |
Draw a loop of exactly 30 iterations (for 32-bit integers). Inside the loop, draw an $O(N)$ linear array scan. |
Deep recursive stacks holding modified array states. |
A few integer variables for bit masking: `ans`, `target`, `current_mask`. |
| 3023 |
Find Pattern in Infinite Stream I |
Sliding window. Keep an array of the last `P` elements of the stream. Every time a new element arrives, loop through the window to check if it matches the pattern. |
Shifting Window Overlap |
Draw the infinite stream tape. Draw the pattern below it. Slide the pattern right by 1 on every mismatch and re-check all characters. $O(N \cdot P)$. |
Knuth-Morris-Pratt (KMP) Automaton |
LPS Array & State Transitions |
Precompute the LPS (Longest Prefix Suffix) array for the pattern. As stream bits arrive, update the matching state index using the LPS array to avoid redundant checks. $O(N)$ strictly. |
Draw the pattern array. Below it, draw the LPS array. Draw a state pointer. When a stream bit matches, move pointer right. On mismatch, follow the LPS arrow backward to the next valid prefix. |
Linear Monotonic Timeline |
Draw the infinite stream as a straight line. Draw a single forward-moving arrow representing the $O(1)$ state transition per incoming bit. |
A shifting array buffer of size `P` constantly doing memory copies. |
An integer array `LPS` of size `P` and a single integer `state_index`. |
| 3024 |
Type of Triangle |
Check every possible combination of sides using complex nested if-else structures without sorting first. |
Decision Tree Logic |
Draw a messy tree with many branches for `a+b>c`, `b+c>a`, `a+c>b` and all equality checks. |
Sorting + Comparison Math |
Ascending Side-Length Bar Chart |
Sort the 3 sides. Check `side[0] + side[1] > side[2]`. If valid, compare the number of unique elements in the set of sides. |
Draw three bars of increasing height. Draw a dashed line from the sum of the first two to see if it clears the third. Label as Equilateral, Isosceles, or Scalene. |
$O(1)$ Constant Time Box |
Draw a small square labeled "O(1) Comparison". Even with sorting 3 elements, it is constant. |
Multiple boolean flag variables in memory. |
A sorted array of size 3 and a `Set` of size up to 3. |
| 3025 |
Find the Number of Ways to Place People I |
Triple nested loop: Pick person A, pick person B, then loop through all other people to see if anyone is inside the rectangle formed by A and B. |
$O(N^3)$ Cubed Loop Box |
Draw a 3D cube representing three nested iterations over the set of points. |
Coordinate Sorting + Monotonic Optimization |
Sweep-Line Rectangle Search |
Sort points primarily by X-coordinate (asc) and secondarily by Y (desc). For each point A, iterate through points B to its right. Track the "best" Y-coordinate seen so far to ensure no one is inside the rectangle. |
Draw a 2D plane with points. Draw a rectangle between two points. Draw a horizontal "ceiling" line that moves down as you check points to ensure the area stays empty. |
$O(N^2)$ Matrix Sweep |
Draw a 2D grid representing the two nested loops over sorted points. |
Temporary lists of points for every rectangle check. |
A single sorted list of point coordinates (x, y). |
| 3026 |
Maximum Good Subarray Sum |
Nested loops to find all possible subarrays `[i...j]`. Check if `abs(nums[i] - nums[j]) == k`, then calculate the sum. |
$O(N^2)$ Triangular Iteration |
Draw a triangle where the base is the array. Show lines connecting every pair of elements. |
Prefix Sum + Hash Map (Minimum Prefix Tracking) |
Prefix Sum Number Line |
As you traverse, store the current Prefix Sum in a Hash Map indexed by the value of the current number. If `nums[i] - k` or `nums[i] + k` exists in the map, the subarray sum is `current_prefix_sum - min_prefix_sum_at_that_value`. |
Draw a running total line graph. Below it, draw a Hash Map table. When you hit a value `X`, look up `X-k` and `X+k` in the table to find the lowest previous "floor" to subtract. |
Linear Scan $O(N)$ |
Draw one straight horizontal arrow across the array. |
$O(N^2)$ summation variables and subarray copies. |
A Hash Map mapping Value -> Minimum Prefix Sum. |
| 3027 |
Find the Number of Ways to Place People II |
(Same as 3025, but with N=1000. $O(N^3)$ will fail). |
Clock on Fire (TLE) |
Draw a timer exploding. $O(N^3)$ with 1000 points is 1 billion operations, too slow for 1s. |
Sorting + Single Pass Optimization |
Monotonic Y-Limit Sweep |
After sorting by X (asc) and Y (desc), for each point `i`, we only care about points `j` where `y[j]` is less than `y[i]` but greater than the maximum `y` seen so far between them. |
Draw points on a grid. For a fixed point A, move a horizontal line downwards. Only count point B if it's the "highest" point seen so far that is still below A. |
$O(N^2)$ Optimization |
Draw a 2D grid showing the two nested loops over 1000 points (1 million operations). |
Large coordinate matrices. |
Sorted array of point objects and a few integer tracking variables. |
| 3028 |
Ant on the Boundary |
Simulate every single step the ant takes. For every move, update the position and check if it is zero. |
Step-by-Step Timeline |
Draw a number line. Draw a sequence of arrows representing each move, with a circle around the '0' mark. |
Prefix Sum Simulation |
Running Balance Tracker |
Treat moves as positive/negative integers. Calculate the prefix sum. Every time the prefix sum equals 0 (after a full move), increment the boundary count. |
Write the numbers in a row. Below them, write the cumulative sum. Circle every '0' that appears in the cumulative sum row. |
Linear $O(N)$ Pass |
Draw a single horizontal arrow passing through the array once. |
A full history of the ant's coordinates. |
Two integer variables: current_position and boundary_count. |
| 3029 |
Minimum Time to Revert Word to Initial State I |
Repeatedly slice the string by k characters and use a string comparison function to see if the suffix matches the original prefix. |
Staggered String Alignment |
Draw the word on a strip of paper. Draw the same word on a strip below it, but shifted by k. Check if overlapping parts match. Repeat until match. |
KMP Prefix Function (LPS Array) |
LPS Chain Linkage |
Construct the LPS array. The longest suffix that is also a prefix gives us the "overlap". If that overlap is at a multiple of k, we find the answer. |
Draw the word. Below it, write the LPS values. Draw an arrow from the end of the string jumping back to the prefix length. |
Linear Scan $O(N)$ |
Draw one straight line across the string length. Label it $O(N)$. |
Creation of multiple new string objects via slicing s[k:] in memory. |
An integer array LPS[N] and a single integer k. |
| 3030 |
Find the Grid of Region Average |
For every cell, iterate through all 3 x 3 regions it belongs to, check the "threshold" condition for every neighbor pair, then average them. |
Overlapping Grid Stencils |
Draw a large grid. Cut a 3 x 3 square out of paper and slide it across the grid, performing 9 checks at every single stop. |
Simulation with Condition Validation |
Region Centroid Mapping |
Pre-calculate if a 3 x 3 block is "valid" (neighbors ≤ threshold). Store sums/counts in a secondary grid. Divide total sum by total counts at the end. |
Draw the grid. For a valid 3 x 3 block, place a dot in all 9 cells. After scanning, count dots in each cell and write the average. |
$O(\text{Rows} \\text{cdot Cols})$ Constant Sub-grid Pass |
Draw a grid and show a single pass with a constant-sized window (3 x 3). |
Recursive checks for neighbors within the nested loops. |
Two auxiliary 2D arrays: sumGrid and countGrid of size M x N. |
| 3031 |
Minimum Time to Revert Word to Initial State II |
(Identical logic to 3029, but N is 10^5, making slicing $O(N^2)$ and causing TLE). |
Explosion Graphic |
Draw a clock on fire. $O(N^2)$ for 10^5 is 10 billion operations. |
Z-Algorithm / KMP Prefix Function |
Z-Box Alignment |
Use the Z-algorithm to find the length of the longest common prefix between S and S[i:] for all i that are multiples of k. |
Draw the string. Below it, draw "Z-boxes" representing segments that match the beginning of the string. |
Linear $O(N)$ Scan |
Draw a single pass across the string. Label as $O(N)$ for Z-array construction. |
Memory fragmentation from high-frequency string slicing. |
A Z-array or LPS array of size N in a single contiguous memory block. |
| 3032 |
Count Numbers With Unique Digits II |
Loop from a to b. For each number, convert it to a string or use a frequency array to check for duplicate digits. |
Range Scanning List |
Draw a number line from a to b. For every tick, draw a small sub-process checking 1-10 digits. |
Precomputation / Bitmasking |
Bitmask Presence Set |
Represent the seen digits of a number as bits in an integer. If (mask & (1 << digit)) > 0, it's a duplicate. Move to next number. |
Write a number. For each digit, flip a bit in a 10-bit sequence (0000000000). If you try to flip an already-on bit, mark the number as invalid. |
$O(N \cdot D)$ where D is number of digits |
Draw a timeline from a to b. For each step, draw a tiny $O(\log10(N)$) loop. |
String conversion overhead for every single number in the range. |
A single 10-bit integer mask reused for every number. |
| 3033 |
Modify the Matrix |
Iterate through the matrix to find -1s. For each -1, launch a separate loop to find the max of that specific column, then replace it. |
Nested Column Scanning |
Draw the matrix. Draw a vertical line for every -1 found, scanning the same column multiple times. |
Column-Wise Max Pre-calculation |
Vertical Maximum Strip |
First, scan each column once to find its maximum value and store it in an array. Then, iterate through the matrix and replace all -1s with the pre-calculated max of that column. |
Draw the matrix. Below each column, write the MAX value. Then, rewrite the matrix replacing -1 with the number written below it. |
$O(M \cdot N)$ Linear Pass |
Draw a grid. Show two distinct arrows: one scanning down columns, one scanning row-by-row. |
Multiple redundant scans of the same column elements. |
A 1D array of size N (number of columns) to store max values. |
| 3034 |
Number of Subarrays That Match a Pattern I |
Iterate through every possible subarray of length m+1. For each, compare the relative order of elements against the pattern. |
Sliding Window Matrix |
Draw the main array. Below it, draw N-M overlapping boxes, each doing M internal comparisons. Label as $O(N \cdot M)$. |
Pattern Conversion + KMP Algorithm |
Trend Sequence Matching |
Convert the nums array into a "trend" array of 1, 0, -1. Treat this as a string matching problem. Use KMP to find the pattern in the trend array. |
Draw nums. Below it, write the trends (up arrow, flat line, down arrow). Draw the pattern as a separate trend line. Slide the pattern trend across the main trend. |
Linear Scan $O(N)$ |
Draw one straight arrow across the trend array. Label it $O(N+M)$. |
Creating new temporary subarray objects for every comparison. |
A 1D "trend" array of integers and an LPS (Longest Prefix Suffix) array for the pattern. |
| 3035 |
Maximum Palindromes After Operations |
Try all possible character swaps across all words to see which combination allows forming the most palindromes. |
Permutation Tree |
Draw a pool of all characters. Branch out every possible way to distribute characters into word slots. Shows exponential growth. |
Greedy Counting + Sorting lengths |
Bucket Filling (Pairs vs Singles) |
Count total pairs of characters and total singles across all words. Sort word lengths ascending. Fill the shortest words first using pairs (and 1 single if the length is odd). |
Draw a "Pool" of character pairs. Draw empty word boxes of different lengths. Drag pairs into boxes. If a box is odd-sized, use a single char for the center. |
$O(N \log N)$ Sorting Bar |
Draw an $O(N)$ frequency count block followed by an $O(N \log N)$ block for sorting the word lengths array. |
Massive recursive state tracking of every character position. |
A frequency map of 26 integers and a sorted integer array of word lengths. |
| 3036 |
Number of Subarrays That Match a Pattern II |
(Identical to 3034, but with N=10^6. Brute force $O(N \cdot M)$ will result in TLE). |
Explosion Graphic |
Draw a clock on fire. A 10^6 x 10^5 operation is mathematically impossible for a 1-second limit. |
KMP / Z-Algorithm on Trend Array |
State Transition Automaton |
Convert nums to a trend array. Run KMP. If j (pattern pointer) reaches pattern.length, increment count and fallback using the LPS array. |
Draw the trend array. Below it, draw the LPS array. Trace the pointer j jumping back and forth as you scan the trend array. |
Linear Monotonic Pass |
Draw a single pass across the 10^6 array. Label it $O(N)$. |
Memory fragmentation from creating N * M small slices. |
One large integer array for trends and one for LPS, allocated once to maximize cache locality. |
| 3037 |
Find Pattern in Infinite Stream II |
Read bits one by one. For every new bit, check the last M bits against the pattern. |
Bitwise Window Shift |
Draw a stream of 0s and 1s. Draw a sliding box of size M shifting one bit at a time, re-checking the entire box. |
KMP with Stream State |
Continuous State Machine |
Maintain a single state variable (index in pattern). As a new bit arrives, look up the next state in the LPS logic. When state == pattern.length, record the index. |
Draw the pattern. Above it, draw a "Current Match" pointer. As a stream bit comes in, show the pointer moving forward or jumping back via LPS. |
$O(1)$ Per Bit |
Draw the stream. At each bit, draw a single "Next State" box. Total time $O(\text{Stream}_\text{Length})$. |
A shifting bit-buffer that requires frequent resizing or copying. |
A single integer current_match_index and the precomputed LPS array. |
| 3038 |
Maximum Number of Operations With the Same Score I |
Use recursion to try taking any two elements, but realize the problem forces taking only the first two. (Even BF is simple here). |
Linear Simulation |
Draw the array. Circle the first two elements. If sum equals score, cross them out and repeat. Stop when sum differs. |
Greedy Simulation |
Iterative Queue Processing |
Calculate the sum of the first two elements. Keep a loop running while the array has >= 2 elements and the next two elements equal the initial sum. |
Draw the array. Draw a bracket over the first pair, write the sum. Move the bracket to the next pair. If the sum changes, draw a red "Stop" line. |
Single Linear Pass $O(N)$ |
Draw a straight arrow through the array. It terminates as soon as a sum mismatch occurs. |
Sub-array slicing or copying in every step. |
A simple pointer or index variable i moving in increments of 2. |
| 3039 |
Apply Operations to Make String Empty |
Simulate the deletion process step-by-step: in each round, find the first occurrence of every distinct character and remove it. Repeat until the string is empty. |
Layered Deletion Stacks |
Draw the string. Below it, draw a "strike-through" version for each iteration. Label the iterations to show how many rounds it takes. |
Frequency Counting + Last Occurrence Mapping |
Frequency Bar Chart |
Count the total frequency of each character. Find the maximum frequency max_f. The result consists of characters that appeared max_f times, in the order of their last appearance. |
Draw the string. Write the frequency above each unique letter. Identify the letters with the highest count. Scan the string from right to left to find their final positions. |
Two-Pass Linear Scan |
Draw two horizontal arrows: one for "Count" and one for "Build Result". Label as $O(N)$. |
A list of strings or multiple modified string copies in memory. |
A frequency array of size 26 and an array to store the last index of each character. |
| 3040 |
Maximum Number of Operations With the Same Score II |
Use simple recursion to try all three options (first two, last two, or first and last) at every step to see which path yields the longest chain. |
Ternary Decision Tree |
Draw the root array. Branch out into 3 child nodes for each possible operation. Label as $O(3^N)$. |
Interval DP (Top-Down Memoization) |
Recursive Cache Matrix |
Fix the score based on the first operation (only 3 possible scores). For each score, use dp(i, j) to find the max operations in the range [i, j]. |
Draw a 2D grid where axes are start_index and end_index. Color cells as they are calculated to show overlapping subproblems being solved once. |
$O(N^2)$ State Space |
Draw a triangle (half-matrix). Label the axes and show that we visit at most N^2 states for each of the 3 possible scores. |
Deep recursive stack with redundant recalculations of the same array segments. |
A 2D memo[N][N] table storing the max operations for each range. |
| 3041 |
Maximize Consecutive Elements in an Array After Modifications |
Generate all 2^N possible arrays by either adding 1 or 0 to each element, then find the longest consecutive sequence in each. |
Binary Power Set Tree |
Draw the array. For each element, branch into "+0" and "+1". Show the exponential growth of possible resulting arrays. |
Sorting + Dynamic Programming |
Staircase DP Table |
Sort the array. Let dp[x] be the longest consecutive sequence ending with the value x. For each num, update dp[num+1] and dp[num] based on dp[num] and dp[num-1]. |
Draw the sorted array. Below it, draw a frequency-like table for DP values. Show arrows jumping from v-1 to v as you process each element. |
$O(N \log N)$ Sorting + $O(N)$ Scan |
Draw an $O(N \log N)$ sorting block followed by a single linear $O(N)$ pass. |
A massive list of all 2^N generated array permutations. |
A Hash Map or a large array dp[max_val] to store sequence lengths. |
| 3042 |
Count Prefix and Suffix Pairs I |
Nested loops (i, j) where i < j. For each pair, check if words[i] is both a prefix and a suffix of words[j]. |
$O(N^2 \cdot L)$ Pairwise Check |
Draw the list of words. Draw arrows from every word to every word that follows it, labeling each check with its string length. |
Brute Force (Small Constraints) / Trie (Optimal) |
String Matching Visual |
For each word j, check if words[i] matches the start and end of words[j]. Since N is small, simple string methods work. |
Write word[i]. Write word[j] below it. Highlight the first len(i) characters and last len(i) characters of word[j] to see if they match. |
Quadratic Loop |
Draw a nested loop diagram showing i from 0 to N and j from i+1 to N. |
Temporary substrings created during prefix/suffix checks. |
Constant extra space beyond the input list. |
| 3043 |
Find the Length of the Longest Common Prefix |
For every number in arr1, compare it against every number in arr2. Convert to strings and find the common prefix length. |
$O(N \cdot M \cdot D)$ Nested Search |
Draw two lists of numbers. Draw lines connecting every pair. For each line, show a digit-by-digit comparison. |
Prefix Hash Set / Trie |
Prefix Tree (Trie) / Set Search |
Iterate through arr1 and store every possible prefix of every number in a Hash Set. Then, iterate through arr2 and check if its prefixes exist in the set. |
Draw a number. Write all its prefixes (e.g., 123 -> "1", "12", "123"). Put them into a "Vault" (Set). For numbers in the second list, check their prefixes against the vault. |
$O((N + M)$ * D) Linear-ish |
Draw two separate passes. Pass 1: "Insert Prefixes". Pass 2: "Search Prefixes". Each takes $O(\text{total digits})$. |
Millions of string slices or digit comparisons stored in the call stack. |
A Hash Set storing all unique numerical prefixes encountered in the first array. |
| 3044 |
Most Frequent Prime |
For every cell, travel in all 8 directions. Build numbers digit by digit, convert to integer, and check primality using a basic loop for every single number formed. |
Radial Star Search |
Draw an 8-way arrow star from a central cell. Label it $O(M \cdot N \\text{cdot max}(M,N)$ * √Value). |
Directional Ray Casting + Primality Sieve |
Vector Ray Tracing |
Iterate grid. For each direction vector (dr, dc), update num = num * 10 + grid[r][c]. If num > 10, check against a precomputed Sieve or a fast primality test. |
Draw the grid. From one cell, draw a straight arrow in one direction. Write the growing number next to the arrow. Circle it if it's prime. |
Linear Matrix Scan |
Draw a nested loop for the grid, an inner loop for direction (constant 8), and a ray length loop. Total $O(M \cdot N \\text{cdot max}(M,N)$). |
Many temporary string allocations for number building. |
A Frequency Hash Map int -> int and a boolean isPrime array (Sieve). |
| 3045 |
Count Prefix and Suffix Pairs II |
Check every pair (i, j) where i < j. Use startsWith() and endsWith() for string comparison. $O(N^2 \cdot L)$ total. |
Pairwise Comparison Matrix |
Draw a triangle representing all word pairs. Label it $O(N^2 \cdot L)$. |
Trie with Pairwise Character Keys |
Combined Prefix-Suffix Trie |
For each word, traverse a Trie where each node is keyed by a pair (word[i], word[len-1-i]). At each node, add the count of words that ended there previously to your answer. |
Draw a tree where edges are labeled with pairs like (a, b). Write a count inside nodes where a word finishes. |
Sum of Lengths $O(∑L)$ |
Draw a single pass through all characters of all words. |
Repeated $O(L)$ substring memory objects created for every check. |
A custom Trie where each Node contains a Map. |
| 3046 |
Split the Array |
Backtracking to try every combination of splitting elements into two groups and checking if each group contains unique elements. |
Binary Decision Tree |
Draw a root branching 2^N times for "Group A" or "Group B". |
Pigeonhole Principle (Frequency Counting) |
Frequency Tally |
Count how many times each number appears. If any number appears more than twice, you cannot split it into two unique sets. Return false immediately. |
List the numbers. Write a tally mark below each. If any number gets 3 tallies, draw a big red "X". |
Linear $O(N)$ Pass |
Draw one straight arrow across the input array. |
Massive recursion stack holding partial sets. |
A simple frequency array of size 101. |
| 3047 |
Find the Largest Area of Square Inside Two Rectangles |
Iterate through all pairs of rectangles. Find their geometric intersection, calculate the max square that fits, and track the global max. |
Pairwise Intersection Grid |
Draw a matrix where each cell (i, j) represents the overlap calculation of two rectangles. |
Coordinate Min-Max Comparison |
Overlapping Interval Mapping |
For rectangles i and j, width = min(x2_i, x2_j) - max(x1_i, x1_j). height = min(y2_i, y2_j) - max(y1_i, y1_j). Side = min(width, height). Area = side^2. |
Draw two overlapping rectangles. Shade the overlapping region. Draw a square inside and label its side as min(w, h). |
$O(N^2)$ Nested Loop |
Draw two nested loops (i, j) with $O(1)$ math operations inside. |
Geometric objects or temporary coordinate arrays. |
A few long integer variables for maxSide and currentSide. |
| 3048 |
Earliest Second to Mark Indices I |
Try every possible sequence of "Decrement" or "Mark" actions second by second using recursion. |
State-Space Search Tree |
Draw a tree branching at every second. Depth equals total time, width equals actions. |
Binary Search on Answer + Greedy Verification |
Timeline Reverse Marking |
Binary search for time T. To verify T: Work backwards from T to 1. The first time you see an index, it MUST be marked then. Calculate if you have enough prior seconds to decrement all values to 0. |
Draw a timeline from 1 to T. Mark "M" at the last occurrence of each index. Check if available slots before each "M" can cover the required decrements. |
$O((N + T)$ log T) |
Draw the binary search range halving. Inside, draw a linear scan across the timeline of length T. |
Recursive stack frames storing array states at each second. |
An array of size N to store the last_occurrence of each index. |
| 3049 |
Earliest Second to Mark Indices II |
Recursively explore every possible action (decrement, reset, mark) at every second to find the minimum time. |
State-Space Search Tree |
Draw a root node branching out for every action choice. Show the depth as T (max time), leading to $O(3^T)$ explosion. |
Binary Search + Greedy Priority Queue |
Timeline Slot Filling |
Binary search for total time T. Working backwards from T to 1, if you hit an index's first appearance, use a Priority Queue to decide if it's "worth" resetting to 0 based on its value. |
Draw a horizontal line with T slots. Place index numbers in their "earliest reset" spots. Use a small box next to it to track your "Banked" seconds available for marking. |
$O((N+T)$ log T) Binary Search |
Draw a range [1, T] halving iteratively. Inside, draw a linear scan across the timeline with a Min-Heap. |
Deep recursive stack holding array states at each second. |
A Min-Heap (Priority Queue) to track the values being reset and an array for earliest appearances. |
| 3050 |
Pizza Toppings Cost Analysis (SQL) |
Use a triple cross join (Topping1 x Topping2 x Topping3) and then apply filters to exclude duplicates and handle alphabetical sorting. |
3D Cartesian Product Cube |
Draw a 3D grid where axes are T1, T2, and T3. Every cell represents a triplet, showing the massive redundant search space. |
Join Filtering + Order By Clause |
Venn Diagram (Self-Joins) |
Join the table to itself twice. Use conditions like T1.name < T2.name and T2.name < T3.name to automatically eliminate permutations and identical pairings. |
Draw three identical overlapping circles. Shade only the intersection where Name A < Name B < Name C. Write the price sum formula: P1+P2+P3. |
$O(N³)$ Joins (Reduced by B-Trees) |
Draw a nested loop flow where each inner loop is smaller than the outer one due to the "less than" sorting constraint. |
Temporary tables containing every possible triplet combination. |
Database Index (B-Tree) on the Topping Name to speed up comparison filters. |
| 3051 |
Find Candidates for Data Scientist Position (SQL) |
Filter the table for each required skill separately, then perform an intersection (AND) of all results. |
List Intersection |
Draw three separate lists of IDs. Draw lines connecting the same ID across all three lists. |
Group By + Having Count Clause |
Bucket Aggregation |
Filter for the three specific skills. Group the rows by candidate_id and count how many rows each ID has. If count == 3, they are the candidate. |
Draw a table with Candidate ID and Skill. Circle the rows with 'Python', 'Tableau', and 'PostgreSQL'. Tally the occurrences per ID. Draw a trophy next to IDs with 3 tallies. |
$O(N)$ Scan |
Draw a single pass through the Skills table. Label it $O(N)$ because the aggregation happens in one pass. |
Multiple sub-queries or CTEs stored in memory. |
A Hash Map (internally used by SQL) for grouping IDs and their respective counts. |
| 3052 |
Maximize Items in Partitions (SQL) |
Simulate filling every combination of partitions with items to find the maximum possible count. |
Greedy Fill Simulation |
Draw different sized bins. Show items being placed one by one into random bins until full. |
Window Functions + Floor Math |
Volume Fill Chart |
Calculate total square footage for 'prime' items. Divide available space by this total to find 'prime' batches. Use the remaining space to fill 'non-prime' items. |
Draw a giant container representing 500k sqft. Slice off a block for Prime. Divide it by Prime size. Take the leftover "empty" space and fill it with Non-Prime blocks. |
$O(N)$ Aggregation |
Draw two separate arrows: "Prime Analysis" and "Non-Prime Analysis". Each scans its portion of the table once. |
Recursive calculation of space for every item type. |
CTE (Common Table Expressions) storing intermediate area totals and remaining space values. |
| 3053 |
Classifying Triangles by Lengths (SQL) |
Manually check every row with multiple nested if-statements in a procedural loop. |
Nested Decision Tree |
Draw a flowchart with branches for A+B>C, then A=B=C, then A=B, etc. |
Case When Logic (Geometric Constraints) |
Categorical Flowchart |
First, validate if it's a triangle using A+B > C. If true, nested logic checks for number of equal sides (3 = Equilateral, 2 = Isosceles, 0 = Scalene). |
Draw a 3-column table for A, B, C. Write "Invalid" for any row where the sum of two isn't > third. For the rest, write the category based on the number of unique values. |
$O(N)$ Row-Wise Pass |
Draw one straight vertical arrow moving down the database table. Label it $O(N)$. |
Buffer for row-by-row string concatenation. |
Zero extra structure; the logic is applied to each row in a single stream. |
| 3054 |
Binary Tree Nodes (SQL) |
Run three separate queries to find Roots (P is null), then Leaves (N not in P), then Inner (everything else). Union them. |
Disjoint Set Buckets |
Draw three separate circles for Root, Leaf, and Inner. Show the engine scanning the whole table three times. |
Case When + Correlated Subquery (or In/Not In) |
Vertical Node Classification |
Scan each node N once. Check: Is P null? (Root). Is N found in the P column of any row? (Inner). Otherwise, it's a Leaf. |
Draw a simple tree. For each node, look at its parent and children. Write 'R', 'I', or 'L' next to it based on its connections in the adjacency list. |
$O(N \log N)$ with Indexing |
Draw a single vertical pass through the table. Label it $O(N)$ for the scan + $O(\log N)$ for the index lookup on the Parent column. |
Temporary tables for each subset (Root, Leaf, Inner). |
Zero extra structure; classification happens on-the-fly during a single scan. |
| 3055 |
Top Percentile Fraud |
Calculate total rows, calculate top 5% threshold manually, then use `LIMIT` or row numbers in a complex subquery. |
Manual Threshold Math |
Draw a calculator dividing row counts, passing the number back into a second query. |
Window Function (PERCENT_RANK) |
The Built-In Percentile Gauge |
Use `PERCENT_RANK() OVER (PARTITION BY state ORDER BY fraud_score DESC)`. The engine handles the relative ranking (0.0 to 1.0). Filter for `<= 0.05`. |
Draw data sorted by fraud score. Draw a ruler next to it marked from 0% to 100%. Draw a red line at the top 5% mark and slice the data there. |
Partitioned Sort $O(N \log N)$ |
Draw a pipeline that sorts within partitions and assigns a float rank. |
Temporary tables for manual counts. |
DB sorting buffer. $O(N)$ space. |
| 3056 |
Snaps Analysis (SQL) |
Perform a full join between Age, Activities, and Snaps tables. Then, use nested loops to sum 'open' and 'send' times for each age group. |
Cartesian Product Matrix |
Draw a grid representing Age x Activity x Snaps. Highlight the massive number of redundant combinations. |
Join + Group By with Filtered Aggregation |
Activity Flow Pipeline |
Join Age to Activities on user_id. Group by age bucket. Calculate SUM(case when type='open'...) and SUM(case when type='send'...). Divide by total time. |
Draw three buckets labeled with age groups. Funnel all 'open' and 'send' activity rows into these buckets. Write the percentage formula on the side of the bucket. |
$O(N)$ Hash Join Pass |
Draw a Hash Map creation for User IDs followed by a single linear scan through Activities. |
A massive joined table residing in temporary disk storage. |
Internal Hash Tables for age grouping and a single pass through the activity log. |
| 3057 |
Employees Project Allocation (SQL) |
For every employee, calculate their average task duration. Then, join with the projects table and check if their project task duration is higher than their personal average. |
Pairwise Average Check |
Draw a list of employees. For each one, draw a sub-list of all their tasks to calculate an average, then another check for the current project. |
Window Function (AVG over Partition) |
Layered Average Strips |
Use AVG(duration) OVER(partition by employee_id) to get the employee average in a new column. Simply compare the row's project duration to this column value. |
Draw a table with a "Duration" column. Add a dashed "Personal Average" line that changes for each employee group. Circle any project bar that exceeds its dashed line. |
$O(N)$ Analytical Pass |
Draw one vertical pass over the sorted data. Analytical functions compute averages without a second full scan. |
Recursive calculation of averages for every row-project pair. |
Memory-efficient frame buffer used by the window function engine. |
| 3058 |
Friends With No Common Friends (SQL) |
For every pair of friends (A, B), generate the full set of friends for A and the full set for B. Compare the intersection. If empty, keep the pair. |
Set Intersection Grid |
Draw a matrix of friend pairs. For each cell, draw two Venn diagrams and check if they overlap. |
CTEs + Not In / Except (Set Difference) |
Friendship Network Filter |
Create a CTE of all friend pairs. Join to find "common" pairs where A and B both have a third friend C. Use NOT EXISTS or EXCEPT to remove these common pairs from the total list. |
Draw a graph of nodes and edges. Pick an edge (A-B). Look at their neighbors. If no neighbor is shared, color the edge green. If a neighbor is shared, color it red. |
$O(N² / \log N)$ using Indexes |
Draw two separate passes: "Neighbor Discovery" and "Set Comparison". |
Massive lists of ID sets for every possible user pair. |
B-Tree Indexes on the user_id columns and a Hash Set for set comparison during the join. |
| 3059 |
Find All Unique Email Domains (SQL) |
Use a regular expression or nested REPLACE/SUBSTRING calls inside a SELECT DISTINCT to strip prefixes and find domains. |
Sequential String Stripping |
Draw an email address. Draw an eraser removing everything before the '@'. Draw a circle around the remaining domain. $O(N \cdot L)$ pass. |
SUBSTRING_INDEX / Regex + Group By |
Domain Extraction Pipe |
Use SUBSTRING_INDEX(email, '@', -1). This acts like a "right-to-left" search until it hits the '@' symbol. Filter for specific domains like '@gmail.com' and count unique occurrences. |
Draw a table with Email and Domain columns. Use an arrow to "slice" the string at '@'. Cross out duplicate domain rows to show DISTINCT. |
$O(N)$ Full Table Scan |
Draw a single vertical line moving down the emails column. Each row takes constant time $O(L)$ to parse. |
Multiple temporary string buffers in the DB engine for each row. |
Hash Set (internally) for domain uniqueness; stores only unique domain strings. |
| 3060 |
User Activities Queries (SQL) |
Join all activity tables and use multiple nested SUM(CASE...) statements to find users who performed specific sequences of actions. |
Cartesian Sequence Grid |
Draw a matrix where rows are users and columns are activity types. Show the engine checking every cell for every user. |
Common Table Expressions (CTE) + Aggregation |
Activity Funnel |
Create a CTE to filter for "Valid Sessions." Then, use GROUP BY user_id and HAVING COUNT(DISTINCT activity_type) >= threshold to find high-activity users. |
Draw a funnel. Dump all activity rows in. At the bottom, show "User Filters" that only let through IDs with the correct count of unique action tags. |
$O(N \log N)$ Sorting Pass |
Draw an $O(N)$ filtering block followed by an $O(N \log N)$ grouping block (usually performed via sorting or hashing). |
Large temporary join results stored in the TempDB. |
Filtered index scan; only relevant activity rows are pulled into memory. |
| 3061 |
Calculate Trapping Rain Water (SQL) |
(Custom SQL implementation) For each bar, find the max height to its left and right using correlated subqueries for every row. |
Nested Scanning Pillars |
Draw the bars. From each bar, draw a scan line left and a scan line right. Total $O(N^2)$ complexity. |
Window Functions (Max Over Partition) |
Boundary Level Overlay |
Use MAX(height) OVER(ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) for left and UNBOUNDED FOLLOWING for right. Water = min(L, R) - height. |
Draw the bar chart. Draw a "blue" horizontal line representing the lower of the two max boundaries. Color the gap between the blue line and the bar. |
$O(N)$ Analytical Scan |
Draw two parallel arrows: one scanning from start-to-end and one from end-to-start. $O(2N)$ rightarrow $O(N)$. |
$O(N^2)$ temporary results for nested subqueries. |
Memory-efficient frame buffer used by the analytical engine to keep running maxes. |
| 3062 |
Winner of the Linked List Game |
Traverse the linked list and store every pair into an array or list, then iterate through the array to compare elements. |
Array Mirroring |
Draw a Linked List. Below it, draw an Array with the same values. Show the pointer moving through the array to compare pairs. |
Two-Pointer Jump (Step of 2) |
Pointer Leapfrog |
Maintain a pointer curr. In each step, compare curr.val with curr.next.val. Increment a "Even" or "Odd" score. Move curr by two nodes: curr = curr.next.next. |
Draw the nodes with arrows. Draw a loop around pairs of nodes. Write the score (+1 for Even, +1 for Odd) next to each loop. Use a "skip" arrow to move to the next pair. |
$O(N)$ Single Pass |
Draw one straight arrow jumping over the Linked List nodes in pairs. Label as $O(N/2)$. |
$O(N)$ space to store the copy of the Linked List in an array. |
$O(1)$ auxiliary space; only two integer variables even_score and odd_score. |
| 3063 |
Linked List Frequency |
For every node, traverse the entire rest of the list to count how many times its value appears. |
Nested Traversal Loops |
Draw the list. From each node, draw an arrow that scans all subsequent nodes. $O(N^2)$ total. |
Hash Map + Result Linked List Construction |
Frequency Mapping |
Traverse the list once, storing Value -> Frequency in a Hash Map. Then, iterate through the map and create new nodes for each frequency. |
Draw the Linked List. Below it, draw a Hash Map box. As you pass each node, increment a tally in the map. Finally, draw a new list where each node contains one of the tally totals. |
$O(N)$ Hash Pass |
Draw two distinct $O(N)$ arrows: "Count Pass" and "Construction Pass." |
Recursive stack frames or multiple nested pointers. |
A Hash Map of size $O(\text{Unique}_\text{Elements})$ and a new list of the same size. |
| 3064 |
Guess the Number Using Bitwise Questions I |
Guess every number from 1 to 2^31 sequentially using the interactive API. Time Limit Exceeded instantly. |
Linear API Spam $O(N)$ |
Draw a line of billions of numbers. Draw an arrow pointing to 1, then 2, then 3. |
Interactive Bit Manipulation |
The 32-Bit Interrogator |
A 32-bit integer is just 32 true/false questions. Query the API for the exact bit position using `1 << i`. Reconstruct the target number bit by bit using bitwise OR (`target |= (1 << i)`). |
Draw 32 empty boxes (0 to 31). Ask the API: "Is box 0 a 1?". If yes, write 1. If no, write 0. Move to box 1. Rebuild the number instantly. |
Strictly Constant Time $O(32)$ |
Draw exactly 32 discrete API call boxes. Execution time is fixed regardless of number size. |
None, purely sequential. |
A single `target` integer variable. $O(1)$ space. |
| 3065 |
Minimum Operations to Exceed Threshold Value I |
Sort the array first, then iterate from the start to count how many elements are strictly less than the threshold k. |
Sorted Array Scan |
Draw the unsorted array. Below it, draw the sorted array. Show an arrow stopping at the first number >= k. $O(N \log N)$ total. |
Single-Pass Filtering |
Linear Threshold Barrier |
Traverse the array once. For every element, check if (num < k) count++. The order doesn't matter, so sorting is unnecessary overhead. |
Write the numbers in a row. Draw a tall vertical "Wall" labeled k. Every number that falls to the left of the wall is counted. |
$O(N)$ Linear Arrow |
Draw one straight arrow passing through the input array once. Label as $O(N)$. |
A newly allocated sorted copy of the array (if not sorting in-place). |
A single integer counter ops taking $O(1)$ extra space. |
| 3066 |
Minimum Operations to Exceed Threshold Value II |
Repeatedly sort the array, pick the two smallest elements, perform the operation (min x 2 + max), and re-insert. Repeat until all elements >= k. |
Nested Sorting Loops |
Draw the array. Circle the two smallest. Draw an arrow to a "Resort" box, then back to the array. $O(N^2 \log N)$. |
Min-Priority Queue (Heap) |
Bubble Heap Up/Down |
Push all elements into a Min-Heap. While heap.peek() < k, poll two elements, calculate the new value, and push it back. The heap automatically maintains the smallest at the top. |
Draw a binary tree (Heap). Show the two smallest nodes being plucked from the top and a new node "bubbling" down into its correct spot. |
$O(N \log N)$ Heap Operations |
Draw a linear scan to build the heap $O(N)$, followed by a series of $O(\log N)$ spikes representing heapify operations. |
Multiple array clones created during each re-sorting phase. |
A single PriorityQueue object storing the integers in a balanced binary tree structure. |
| 3067 |
Count Pairs of Connectable Servers in a Weighted Tree |
For every node, use BFS to find all other nodes. Then, for every pair of nodes, find their lowest common ancestor and check path weights. |
All-Pairs Tree Traversal |
Draw a tree. From every node, draw lines to every other node. Label as $O(N^3)$ or $O(N^2 \\text{cdot Path})$. |
DFS + Combinatorics (Product of Subtree Counts) |
Tree Splitting Centroids |
For each node i, treat it as the root. For each neighbor j, run a DFS to count nodes whose distance from i is divisible by signalSpeed. Multiply counts from different branches to find pairs. |
Draw a node as a "hub". Draw its subtrees as separate bubbles. Write the count of "Valid Nodes" inside each bubble. Show Count_A x Count_B for all bubble pairs. |
$O(N^2)$ DFS Matrix |
Draw a nested loop: Outer loop N (for each node) x Inner DFS $O(N)$. Total $O(N^2)$. |
Large adjacency matrix or deep recursion stack for every pair check. |
A List> adjacency list and a single recursion stack of max depth H (tree height). |
| 3068 |
Find the Maximum Sum of Node Values |
Try every possible subset of edges to flip (XOR with k) and calculate the total sum. $O(2^E)$ where E is number of edges. |
Edge Selection Power Set |
Draw the graph. Branch into 2^N-1 paths for "Flip" or "Don't Flip" for each edge. Label as $O(2^N)$. |
Greedy + Delta Sorting (or Simple DP) |
Profit/Loss Gain Bar |
For each node, calculate the "Gain" if XORed: (node XOR k) - node. Sort these gains. Pairs of flips are allowed. Take pairs as long as their combined gain is positive. |
Draw a bar for each node representing its current value. Draw a "Potential Change" bar (positive or negative). Group the largest positive changes in pairs. |
$O(N \log N)$ or $O(N)$ Greedy |
Draw a single pass to calculate gains, then a sort $O(N \log N)$, then a final linear pass. |
Massive recursive tree tracking every possible XOR state of the entire graph. |
A 1D array of "Difference" (delta) values and a few tracking variables. |
| 3069 |
Distribute Elements Into Two Arrays I |
Iterate through the array. For each element, check the last elements of both `arr1` and `arr2` and append accordingly. Small N allows simple simulation. |
Sequential Branching List |
Draw an input array. Below it, draw two expanding lists. Show an arrow from each input element to its chosen list. $O(N)$. |
Simple Greedy Simulation |
Two-Pointer Array Growth |
Maintain two dynamic arrays. For each number starting from the third, compare it with `arr1.back()` and `arr2.back()`. Append to the one with the larger last element. |
Draw two horizontal bars. Write the first two numbers. For the next, circle the larger of the two "tips" of the bars and place the number there. |
$O(N)$ Linear Flow |
Draw one straight arrow through the array. It’s already optimal because you must visit every element once. |
$O(N)$ extra space to store the two result arrays. |
Two contiguous memory blocks (Arrays) that grow as elements are added. |
| 3070 |
Count Submatrices with Top-Left Element and Sum Less Than k |
For every possible bottom-right corner (r, c), iterate through all cells from (0, 0) to (r, c) to calculate the sum and compare with k. |
4-Nested Loop Volume |
Draw a 3D grid representing R x C x R x C. It shows a massive amount of re-calculation for overlapping areas. $O(R^2 \cdot C^2)$. |
2D Prefix Sum (In-Place) |
Area Accumulation Matrix |
Calculate prefix sums for the grid where `sum[i][j] = grid[i][j] + sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1]`. If `sum[i][j] <= k`, increment the count. |
Draw a grid. For cell (i, j), draw arrows coming from the top cell, the left cell, and a "subtraction" arrow from the top-left diagonal cell. |
$O(\text{Rows} \\text{cdot Cols})$ Matrix Pass |
Draw a single pass through the matrix. Each cell is calculated in $O(1)$ after looking at its 3 immediate neighbors. |
Redundant sum variables calculated from scratch for every sub-rectangle. |
A 2D array of the same size as the grid, or the grid itself modified to store cumulative sums. |
| 3071 |
Minimum Operations to Write the Letter Y on a Grid |
Try every combination of values (0, 1, 2) for the "Y" cells and the "Non-Y" cells (9 combinations total). For each, count operations needed. |
Permutation Decision Grid |
Draw a 3 x 3 grid of "Y-color" vs "Non-Y-color". Each cell shows the cost of that choice. $O(9 \cdot N^2)$. |
Frequency Counting (Y vs. Non-Y) |
Two-Region Histogram |
Count frequencies of 0s, 1s, and 2s in the "Y" region and the "Non-Y" region separately. Iterate through the 6 valid (different color) pairs and find the min cost. |
Draw the grid. Highlight the 'Y' shape (diagonals + vertical tail). Below, draw two tables: "Y-Counts" and "Other-Counts". Plug counts into the formula `Total - (Y_count + Other_count)`. |
$O(N^2)$ Single Pass |
Draw one pass to identify and count region types. The final comparison takes constant time (O(6)). |
A copy of the grid with "Y" and "Non-Y" cells flagged separately. |
Two small arrays of size 3 to store the frequencies of values 0, 1, and 2. |
| 3072 |
Distribute Elements Into Two Arrays II |
For each element, count how many elements in `arr1` and `arr2` are strictly greater than it by iterating through both full lists. |
$O(N^2)$ Nested Searching |
Draw an element. Draw two arrows scanning through the entire history of `arr1` and `arr2`. Show N operations growing to N^2. |
Fenwick Tree (BIT) / Segment Tree + Coordinate Compression |
Dynamic Frequency Tree |
Compress all unique values to a 1-N range. Use two Fenwick Trees to track counts of values. Use `Tree.query(N) - Tree.query(compressed_val)` to get the count of greater elements in $O(\log N)$. |
Draw a Fenwick Tree (Binary Tree structure). Show a "Value" entering, and highlight the path of nodes being updated as it climbs. Draw a "Query" as a path down to get a sum. |
$O(N \log N)$ Tree Ops |
Draw an $O(N \log N)$ block for sorting/compression, followed by an $O(N)$ loop with $O(\log N)$ tree spikes. |
Storing full array copies and re-sorting them at every single step. |
Two Fenwick Tree arrays and one sorted "Compression Map" array. |
| 3073 |
Maximum Increasing Triplet Value |
Three nested loops to check i < j < k and arr[i] < arr[j] < arr[k]. $O(N^3)$. |
Cubic Triplet Hunting |
Draw the array. Pick an element. Draw lines to every future element, and from those, to every future element. |
Right Max Array + Sorted Set |
The Peak-and-Valley Tracker |
To maximize arr[i] - arr[j] + arr[k], we want a large arr[i], small arr[j], and large arr[k]. Precompute the maximum valid elements to the right. Use a Sorted Set while iterating to find the optimal valid arr[i] strictly smaller than arr[j]. |
Draw the array. Above it, track the maximum elements to the right. Below it, maintain a sliding "Best Left" box. Combine Top, Middle, and Bottom for the max score. |
Set Insertion + Scan $O(N \log N)$ |
Draw a linear scan. At each step, do an $O(\log N)$ lookup/insertion in a Tree/Set. |
None. |
A suffix max array and a balanced BST (Set). $O(N)$ space. |
| 3074 |
Apple Redistribution into Boxes |
Generate all possible combinations of boxes to see which subset can hold the total apples, then pick the smallest subset size. |
Subset Power Set Tree |
Draw a root branching 2^N times for "Take Box" or "Leave Box". Label as $O(2^N)$. |
Sorting + Greedy Accumulation |
Poured Liquid Visualization |
Calculate the total sum of apples. Sort the boxes in descending order. "Pour" the total apple sum into the largest boxes first until the "Apple Reservoir" is empty. |
Draw a large rectangle (Total Apples). Draw boxes of varying widths. Cross off the widest boxes first until their combined width covers the rectangle. |
$O(N \log N)$ Sorting Bar |
Draw an $O(N \log N)$ block for sorting followed by a single linear $O(N)$ pass for counting. |
A massive recursive stack tracking current weight and box count for every subset. |
A single integer totalApples and a sorted 1D array of box capacities. |
| 3075 |
Maximize Happiness of Selected Children |
For k rounds, try selecting every possible child and simulate the happiness decay of all other children to see which sequence yields the max. |
Permutation Selection Tree |
Draw a tree where each level represents a round. Branch N, N-1, N-2... times. Label as $O(N!)$. |
Greedy + Decay Offset |
Descending Waterfall with Floor |
Sort children by happiness descending. For each of the k children picked, subtract the current round number (decay) from their happiness, ensuring a minimum of 0. |
Draw a bar chart of happiness. For each step, shade a horizontal strip at the bottom of all remaining bars. Pick the tallest remaining bar. |
$O(N \log N)$ Sorting Pass |
Draw an $O(N \log N)$ sorting block followed by a loop that runs exactly k times. |
Cloning the happiness array in every round to track decay states. |
A single integer decay_counter and the sorted input array. |
| 3076 |
Shortest Uncommon Substring in an Array |
For every string, generate all possible substrings. For each substring, check every other string in the array to see if it's a substring there. |
$O(N² \cdot L³)$ Substring Grid |
Draw a string. From it, branch out every substring. For each leaf, draw arrows to all other strings. Shows massive $O(N^2 \cdot L^3)$ redundancy. |
Hash Map Frequency + Sorting |
Substring Dictionary Mapping |
Map every unique substring to the set of indices of the strings it appears in. For each string, iterate through its substrings (by length) and return the first one whose map-set size is 1. |
Draw a "Master Table" with columns: Substring | Frequency. Tally up every substring found. Highlight the shortest ones with Frequency = 1. |
$O(N \cdot L²)$ Mapping |
Draw one pass to generate and map $O(L^2)$ substrings per string. Label the lookup as $O(1)$ via Hash Map. |
A massive 2D matrix of all pairwise substring comparisons. |
A HashMap<String, Integer> storing substring frequencies. |
| 3077 |
Maximum Strength of K Disjoint Subarrays |
Try every possible way to partition the array into k disjoint subarrays using recursion/backtracking. |
Partition Tree Explosion |
Draw the array. Draw vertical "cut lines" in every possible gap. Branch for every k-cut combination. $O(N^k)$. |
Dynamic Programming (Pick/Skip State) |
DP Transition Ribbon |
Let dp[i][j] be the max strength using j subarrays from the first i elements. States include: "Starting new subarray", "Continuing current", or "Skipping". Multiply by alternating coefficients (k, -(k-1), k-2...). |
Draw a grid: Rows (Subarrays k), Cols (Array Index N). Draw diagonal arrows showing "Continue" and horizontal arrows showing "Start New". |
$O(k \cdot N)$ Matrix Fill |
Draw a K x N grid. Show that each cell depends only on the previous row and previous column values. |
An exponential number of array slices stored in recursive stack frames. |
Two 1D arrays (current and previous DP rows) to optimize space from $O(K \cdot N)$ to $O(N)$. |
| 3078 |
Match Alphanumerical Pattern in Matrix I |
For every cell in the 2D grid, overlay the pattern and do a full character-by-character validation loop. $O(R \cdot C \cdot P_R \cdot P_C)$. |
Brute Force Stamping |
Draw the grid. Take the pattern "stamp" and press it onto every single cell, checking every pixel under the stamp. |
2D Sliding Window / Submatrix Hashing |
The Consistent-Mapping Window |
Treat the pattern as a 2D window. As you slide it over the board, verify that letters in the pattern consistently map to single digits in the board. Reset the bijection map for each window shift. |
Draw the pattern matrix. Slide it over the main grid. When a letter touches a number, draw a string attaching them. If a letter tries to attach to *two different* numbers in the same window, snap the string and slide forward. |
Optimized Window Scan |
Draw a window moving across a grid. Inside the window, constant-time Hash Map checks occur. |
Massive deep copies of sub-matrices. |
Two small arrays (size 26 and 10) for character mapping. $O(1)$ space. |
| 3079 |
Find the Sum of Encrypted Integers |
Convert each number to a string, find the maximum character, replace all characters with that max character, and convert back to an integer. |
String Transformation Tape |
Draw an integer. Show it splitting into a sequence of characters, a loop finding the max, and a "stamp" tool overwriting all slots. |
Mathematical Digit Decomposition |
Digital Register Shift |
Iteratively use num % 10 and num / 10 to find the max digit and the digit count. Reconstruct the number as maxDigit * (111...1). |
Write the number. Below it, list each digit. Circle the largest. Draw a "Reconstruction formula": Max * ((10^len - 1)/9). |
$O(N \\text{cdot Digits})$ Linear Pass |
Draw a single pass through the array. For each element, draw a tiny sub-loop of max 4-10 steps. Label as $O(N \cdot D)$. |
String buffers and temporary char arrays allocated for every single number in the list. |
$O(1)$ extra space; only three integer variables: max_d, temp_sum, and len. |
| 3080 |
Mark Elements on Array by Performing Queries |
For each query, mark the index. Then, perform a full scan or sort of the array to find the k smallest unmarked elements. |
$O(Q \cdot N \log N)$ Repeated Sort |
Draw the array. For every query, draw a "Sorting Machine" box that processes the entire array to find the minima. |
Min-Heap + Boolean Visited Array |
Priority Queue "Popping" |
Pre-load all (value, index) pairs into a Min-Heap. Use a boolean array to track "Marked" status. For each query, mark the specific index, then pop k valid elements from the heap. |
Draw a Heap (Binary Tree) and a horizontal bit-array (0s and 1s). Show nodes being "plucked" from the heap and their index being flipped to '1' in the array. |
$O((N + Q)$ log N) |
Draw one heap-build block $O(N)$. Then draw Q query spikes, each having a small $O(\log N)$ heap-pop overhead. |
Generating a filtered and sorted copy of the unmarked array for every single query. |
A PriorityQueue and a boolean[] of size N to track visited states. |
| 3081 |
Replace Question Marks in String to Minimize Its Value |
Generate all possible character substitutions for '?' and calculate the total "cost" (frequency-based) for each to find the minimum. |
Exponential Choice Tree |
Draw the string with '?' gaps. Branch out 26 ways for every gap. Show the 26^count explosion. |
Greedy Frequency Counting + Min-Heap |
Balanced Bucket Filling |
Count current frequencies of a-z. Put all counts into a Min-Heap. For each '?', pick the top (lowest frequency) char, increment its count, and push back. Sort the final chosen chars to maintain lexicographical order. |
Draw 26 buckets (a-z) with different water levels (frequencies). Pour "extra water" (the '?' marks) into the lowest buckets first until they all level out. |
$O(N + (Q \log 26)$ + Q log Q) |
Draw an $O(N)$ frequency pass, a small $O(Q \log 26)$ heap loop, and a sorting block for the Q question mark replacements. |
Massive recursive state space storing all possible string permutations. |
An integer array of size 26 and a list of characters to be inserted. |
| 3082 |
Find the Sum of the Power of All Subsequences |
Generate every possible subsequence. For each, find all sub-subsequences that sum to k. |
Nested Power Set Fractal |
Draw a Power Set Tree. From each leaf node, draw another Power Set Tree. Label as $O(3^N)$ or higher. |
3D Dynamic Programming (Knapsack Variant) |
State Transition Cube |
Let dp[i][j][len] be the number of subsequences of length len that sum to j using first i elements. Result is Sum(dp[n][k][len] * 2^(n-len)). |
Draw a 2D grid (Sum vs. Length). For a new number x, show how it shifts values diagonally (adding 1 to length and x to sum). |
$O(N^2 \cdot K)$ DP Grid |
Draw a grid of size N x K. Each cell represents a constant-time update. Label total as $O(N^2 \cdot K)$. |
Exponential recursion stack tracking every possible subsequence combination. |
A 2D DP table dp[sum][length] (space-optimized from 3D). |
| 3083 |
Existence of a Substring in a String and Its Reverse |
Generate all substrings of length 2. Reverse the whole string. For each original substring, check if reverse_s.contains(sub). |
$O(N^2)$ String Matching |
Draw the string and its reverse. Draw arrows connecting every 2-char block in String A to String B. |
2D Bitset / Hash Set of Pairs |
Adjacency Matrix Mapping |
Iterate once to find all 2-length substrings ab. Check if ba was already seen. Use a 26x26 boolean matrix for $O(1)$ lookups. |
Draw a 26x26 grid (a-z by a-z). For each pair s[i], s[i+1], mark the cell. Then check if the symmetric cell (row/col swapped) is also marked. |
$O(N)$ Linear Scan |
Draw one straight arrow through the string. Label the lookup as $O(1)$. Total $O(N)$. |
Creating N new string objects and a full reversed string in memory. |
A 26x26 boolean matrix (676 bits) or a single HashSet. |
| 3084 |
Count Substrings Starting and Ending with Given Character |
Generate all possible substrings of the string. For each substring, check if the first and last characters match the target character. |
$O(N²)$ Substring Matrix |
Draw a triangle where each cell (i, j) represents a substring. Shade cells where both boundaries match the target. Label as $O(N^2)$. |
Combinatorics (Handshake Lemma) |
Bucket Selection Logic |
Count the total frequency c of the target character. Any pair of these characters (including the character with itself) forms a valid substring. Total is fracc(c+1)2. |
Write the string. Circle every instance of the target character. Connect every circled character to every other circled character (and itself). Count the lines. |
$O(N)$ Linear Pass |
Draw one straight arrow through the string. Label the final calculation as $O(1)$. |
Storing every generated substring in a list or set. |
A single integer variable count to store frequencies. |
| 3085 |
Minimum Deletions to Make String K-Frequency Special |
Try every possible subset of characters to delete and check if the remaining frequencies satisfy the |f1 - f2| <= k condition. |
Power Set Decision Tree |
Draw a tree for each character occurrence (delete/keep). Label the exponential growth of states. |
Frequency Sorting + Sliding Threshold |
Histogram Leveling |
Get character frequencies and sort them. For each unique frequency f as a potential "minimum," calculate the cost to bring all higher frequencies down to f+k and remove all lower frequencies. |
Draw a bar chart of frequencies in ascending order. Pick a "base" bar. Draw a line k units above it. Everything below the base and above the line must be "erased" (shaded). |
$O(26 \log 26 + N)$ |
Draw an $O(N)$ frequency pass followed by a small $O(26^2)$ nested loop for the thresholds. |
Massive recursive tree tracking deleted character counts. |
An integer array of size 26 for frequencies. |
| 3086 |
Minimum Moves to Pick K Ones |
Try every possible starting position and every possible sequence of "adjacent swaps" and "remote additions" to collect k ones. |
Global Search State Space |
Draw a grid of positions and current 1s. Show branches for every possible move type. $O(\text{Exponential})$. |
Sliding Window + Median Distance + Prefix Sums |
Elastic Band Shrinking |
Collect all indices of 1s into a list. Use a sliding window of size k' (ones to be moved). The median of these indices minimizes total distance. Use prefix sums to calculate total distance in $O(1)$ per window. |
Draw a number line with dots (1s). Draw a sliding bracket over k dots. Mark the dot in the middle of the bracket (median). Draw lines from all dots in the bracket to that median. |
$O(N)$ Linear Window |
Draw one pass to collect indices, followed by one pass of a sliding window. $O(N)$. |
Deep recursion for move combinations. |
A list of indices of 1s and a prefix sum array of those indices. |
| 3087 |
Find Trending Hashtags (SQL) |
Extract all hashtags from the tweet text for every row, then join the results to a temporary table and count occurrences. |
Row-by-Row String Splitting |
Draw a tweet. Show it exploding into a list of words. Draw a filter for words starting with '#'. |
Regex Extraction + Group By + Order By |
Frequency Aggregation Funnel |
Use REGEXP_SUBSTR or SUBSTRING_INDEX to extract the first hashtag. Group by the hashtag, count, and sort by count descending. Limit to top 3. |
Draw a table with Tweet and Hashtag columns. Use an arrow to "extract" tags. Group identical tags into buckets and count the height of the buckets. |
$O(N \log N)$ Sorting Pass |
Draw a single pass to extract tags $O(N)$, followed by a sorting block for the counts. |
Temporary tables containing every word from every tweet. |
Index-assisted grouping; the engine uses a Hash Map internally to tally hashtags. |
| 3088 |
Make String Anti-palindrome |
Generate all permutations of the string and check each one to see if it is "anti-palindrome" (no s[i] == s[n-1-i]). |
$O(N!)$ Permutation Tree |
Draw a tree branching for every character placement. $O(N!)$. |
Sorting + Greedy Swapping |
Mirror Conflict Resolution |
Sort the string. Check the middle where conflicts (s[i] == s[n-1-i]) are most likely. If they occur, swap the conflicting characters with the next available different characters. |
Write the sorted string. Draw a mirror line in the center. Use arrows to compare opposite characters. If they match, draw a swap arrow to the first character to the right that is different. |
$O(N \log N)$ Sorting |
Draw an $O(N \log N)$ block for sorting followed by a linear $O(N)$ scan for conflicts. |
Full set of string permutations in memory. |
In-place character array swaps $O(1)$ extra space beyond input. |
| 3089 |
Find Bursty Behavior (SQL) |
Self-join the table on the condition that abs(t1.date - t2.date) <= 6 and count entries for every user across all possible 7-day windows. |
Nested Interval Overlap |
Draw a calendar. For every day, draw a 7-day bracket. Show the engine re-scanning every bracket for every user. $O(N^2)$. |
Window Functions (COUNT with Range) |
Sliding Window Frame |
Use COUNT(*) OVER(PARTITION BY user_id ORDER BY date RANGE BETWEEN INTERVAL 6 DAY PRECEDING AND CURRENT ROW). Filter users where the max count is >= 2 x their avg weekly count. |
Draw a timeline. Move a "7-Day" box across it. In each step, write the number of dots inside the box. Compare this to a "Global Average" line drawn below. |
$O(N \log N)$ Sorting Pass |
Draw one vertical pass over sorted user data. The database engine calculates running counts in a single stream. |
Temporary tables containing millions of joined rows. |
Memory-efficient frame buffer (sliding window internal state). |
| 3090 |
Maximum Length Substring With Two Occurrences |
Generate every substring, build a frequency map for each from scratch, and check if any count exceeds 2. $O(N^3)$. |
Resetting Frequency Tally |
Draw a string. Bracket a section. Tally all letters. Erase tally. Move bracket. Re-tally. |
Sliding Window (Two Pointers) |
The Expand-and-Contract Caterpillar |
Use `left` and `right` pointers. Expand `right`, adding characters to a frequency map. If a character hits 3, pause `right` and shrink `left` until that specific character's frequency drops back to 2. Update max length. |
Draw the string. A caterpillar stretches right, eating letters. It eats a 3rd 'a' and gets sick. Its tail pulls forward, spitting out letters until it spits out an 'a'. It stretches right again. |
Single Pass $O(N)$ |
Draw a single line. The `left` and `right` pointers only ever move forward, making 2N steps total. |
Creating new maps for N^2 substrings. |
A frequency array of size 26. $O(1)$ space. |
| 3091 |
Apply Operations to Make Sum Greater Than or Equal to k |
BFS to try every possible combination of "Increment element" or "Duplicate element" until the sum reaches k. |
State-Space Growth Tree |
Draw a root node branching into "Inc" and "Dup". Label it as $O(2^S)$ where S is the number of operations. |
Math / Square Root Optimization |
Optimal Dimension Grid |
Realize you should increment the single element to a value v and then duplicate it d times. Total ops: (v-1) + lceil k/v rceil - 1. The optimal v is close to √k. |
Draw a grid representing Sum = Value x Count. Show how changing the width (value) or height (count) affects the "perimeter" (total operations). |
$O(\text{sqrt}(k)$) Scan |
Draw a short timeline from 1 to √k. Label as $O(√k)$. |
Deep recursive stack storing current array state. |
Zero extra structure; just a few variables for v, d, and min_ops. |
| 3092 |
Most Frequent IDs |
For every update, iterate through the entire frequency map of IDs to find which one has the highest current frequency. |
$O(N \cdot U)$ Linear Search |
Draw the frequency table. For every update, show a magnifying glass scanning the entire table. |
Hash Map + Max-Priority Queue (Lazy Removal) |
Dynamic Tally Scale |
Update the frequency in a HashMap. Push the new (frequency, id) to the Max-Heap. If the top of the heap's frequency doesn't match the Map, pop it (it's stale). |
Draw a Tally Table and a Max-Heap (Tree). Update the table. Add the new pair to the Heap. Cross out the top node if its value is "old." |
$O(N \log N)$ Heap Ops |
Draw N spikes representing heap push/pop operations. |
Creating a full copy of the ID list for every max check. |
A HashMap for frequencies and a PriorityQueue for the rolling maximum. |
| 3093 |
Longest Common Suffix Queries |
For each query, iterate through every string in the dictionary and manually compare suffixes from right to left. |
$O(Q \cdot N \cdot L)$ Brute Search |
Draw the query string. Below it, draw the dictionary. Draw arrows for every character comparison. |
Reverse Trie (Suffix Trie) with Precomputed Min |
Branching Suffix Tree |
Insert dictionary strings into a Trie in **reverse order**. At each node, store the index of the string that has the shortest length and smallest index. For queries, traverse reversed. |
Draw a tree where each node represents a character. At each node, write the ID of the "Best String" found so far. To query, follow the characters of the word from end to beginning. |
$O(\text{Total Length})$ Construction |
Draw a single pass through all dictionary characters once, then a single pass for each query. |
N separate comparisons stored in the call stack for every query. |
A TrieNode structure where each node has a children[26] array and a minIndex integer. |
| 3094 |
Guess the Number Using Bitwise Queries II |
Test every possible number from 0 to 2^31-1 using bitwise XOR queries one by one. |
Exhaustive Search Timeline |
Draw a massive binary number line. Show the query pointer checking every single integer. $O(2^30)$. |
Bit-by-Bit Reconstruction |
32-Bit Toggle Switch |
For each bit i from 0 to 29, query (1 << i). Check if the set bit count increases or decreases. If the count decreases, it means the hidden number had that bit set. |
Draw a row of 30 empty boxes. For each bit, write a '1' or '0' based on the change in the total bit count reported by the query. |
$O(1)$ Constant Queries |
Draw 30 distinct vertical bars representing the 30 fixed queries. Label as $O(30)$ approx $O(1)$. |
A massive array of query results stored in memory. |
Zero extra structure; just a single integer variable to accumulate the result bitwise. |
| 3095 |
Shortest Subarray With OR at Least K I |
Generate all possible subarrays using nested loops (i, j). Calculate the bitwise OR for each and track the shortest one that meets the k threshold. |
$O(N²)$ Subarray Matrix |
Draw a triangle of all pairs. For each cell, show the OR calculation. $O(N^2)$. |
Two Pointers / Sliding Window |
Elastic Band Shrinking |
Expand the right pointer. Since N is small (50), simple simulation works. Shrink the left pointer when the condition is met to find the minimum length. |
Write the numbers. Slide a bracket to the right. When the OR >= k, move the left side of the bracket until OR < k. Measure the bracket length. |
$O(N)$ Linear Scan |
Draw a straight arrow through the string. Pointers L and R move forward monotonically. |
Storing every subarray in a list to find the minimum. |
A single integer variable for the current OR and the min length. |
| 3096 |
Minimum Levels to Gain More Points |
For every possible split point i, calculate the total sum of points for Alice (levels 0 to i) and Bob (levels i+1 to N-1). |
Nested Scanning Tally |
Draw an array. Draw a "split line" that moves through every gap. For each gap, draw two scan arrows (left and right). $O(N^2)$. |
Prefix Sum / Running Total |
Balance Scale Overlap |
Calculate the total sum of the entire array once (treating 0 as -1). Use a prefix sum to get Alice's score in $O(1)$ and Bob's score as Total - Alice. Find the first index where Alice > Bob. |
Draw the levels as a row of +1 and -1. Write the running prefix sum below it. Compare the prefix sum at each step against the "Remaining Total" calculated once. |
$O(N)$ Linear Pass |
Draw one horizontal arrow across the array. Label it $O(N)$. |
Two separate arrays for Alice's and Bob's scores for every split. |
A single integer for totalSum and currentSum taking $O(1)$ extra space. |
| 3097 |
Shortest Subarray With OR at Least K II |
Identical to 3095 but with N=10^5. Brute force $O(N^2)$ will fail. |
Clock on Fire (TLE) |
Draw an exploding timer. 10^10 operations exceed the 1s limit. |
Sliding Window + Bit Count Array |
Frequency-based Bit Register |
Maintain a 32-element array tracking the frequency of each bit in the current window. When adding/removing numbers, update the bit counts. If a count > 0, that bit is "active" in the OR sum. |
Draw the array. Below it, draw 32 vertical "tally boxes." When a number enters the window, add its bits to the boxes. When it leaves, subtract. If a box has >0 tallies, that bit is 1. |
$O(N \cdot 32)$ Window |
Draw a linear scan $O(N)$. Inside each step, show a constant-time bit-count update (32 operations). |
Deep recursion for move combinations. |
An integer array bitCounts[32] and two window pointers. |
| 3098 |
Find the Sum of Subsequences Powers |
Generate every possible subsequence of size k (O(2^N) or (N Choose k)), find the minimum difference in each, and sum them. |
Combinatorial Decision Tree |
Draw a root branching 2^N times. At each leaf, draw a nested loop for min-diff. $O(2^N \cdot k^2)$. |
5D Dynamic Programming + Sorting |
State Transition Hypercube |
Sort the array. Let dp[index][count][last_val][min_diff] be the count of subsequences. Since min_diff is large, use a Map or coordinate compress the potential differences. |
Draw a complex grid where axes are Index and Count. Each cell contains a Map of "Difference -> Frequency." Show arrows adding new elements and updating the "Global Min" of the subsequence. |
$O(N³ \cdot K)$ DP Grid |
Draw a grid of size N x K. Each cell represents a complex update. Label as $O(N^3 \cdot K)$ depending on state reduction. |
Exponential state space tracking every subsequence. |
A 3D or 4D DP table (with space optimization) or a nested HashMap. |
| 3099 |
Harshad Number |
Convert the number to a string, iterate through each character, convert back to integer to sum, then check divisibility. |
String-Integer Pipeline |
Draw a number being "unpacked" into a string, then each character being "cast" back to an int into a summation box. |
Digit Extraction (Modulo Arithmetic) |
Modulo Loop Cycle |
Use while(n > 0) with n % 10 to extract digits. Sum them up and check if original_n % sum == 0. |
Write the number. Draw a circular arrow showing the last digit being "plucked" off using %10 and the rest shifting down using /10. |
$O(\log N)$ Digital Scan |
Draw a short arrow for each digit of the number. Label as $O(\text{number of digits})$. |
String buffer allocation for the character representation of the number. |
Three integer variables: sum, temp, and original. $O(1)$ space. |
| 3100 |
Water Bottles II |
Recursive simulation: for every possible step, calculate whether to drink, exchange, or wait. (Though a simple greedy loop is almost BF here). |
State-Transition Flowchart |
Draw boxes for "Full", "Empty", and "Exchange Rate". Draw arrows showing the movement of units between them. |
Greedy Simulation (While Loop) |
Resource Depletion Tank |
Maintain full, empty, and total_drunk. Drink all full, add to empty. While empty >= numExchange, swap for 1 bottle and increment numExchange. |
Draw three buckets. Mark tallies as you "drink" from one to the other. Draw a "Price Tag" next to the exchange bucket that increases by 1 each time. |
$O(\text{sqrt}(N)$) Arithmetic Series |
Draw a shrinking bar. Because the exchange cost increases by 1 each time, the number of swaps is bounded by $O(√N)$. |
Call stack frames tracking the "state" of bottles at each exchange. |
Zero extra structure; just four integer counters. |
| 3101 |
Count Alternating Subarrays |
Nested loops (i, j) to generate all subarrays. For each, iterate through all elements to verify if every adjacent pair differs. |
$O(N³)$ Brute Checker |
Draw a triangle of all pairs. From each cell, draw a horizontal sub-scan. Label as $O(N^3)$. |
One-Pass DP / Sliding Window (Arithmetic Progressions) |
Consecutive Streak Counter |
Traverse once. If nums[i] != nums[i-1], your current "alternating streak" increases by 1. Add the current streak length to the total answer. |
Write the array. Draw a bracket that grows as long as numbers alternate. When they repeat, "break" the bracket. The count is the sum of the bracket lengths. |
$O(N)$ Linear Pass |
Draw one straight arrow across the array. Label it $O(N)$. |
Storing every valid alternating subarray in a list. |
A long variable for the total count and an int for the current streak. |
| 3102 |
Minimize Manhattan Distances |
Nested loop to calculate Manhattan distance |x1-x2| + |y1-y2| for all N^2 pairs of points. Find the max, then try removing each point one by one. |
$O(N³)$ Point Removal Search |
Draw a grid with points. Show N different "missing point" scenarios, each requiring an $O(N^2)$ scan. |
Coordinate Rotation (Chebyshev Transformation) |
45-Degree Axis Pivot |
Transform (x, y) to (u, v) where u = x+y and v = x-y. The max Manhattan distance is max(max(u)-min(u), max(v)-min(v)). Use a Multiset to efficiently find the new max after removing a point. |
Draw a standard X-Y grid. Draw a second grid rotated 45 degrees. Show how a diamond-shaped distance becomes a square-shaped distance (Chebyshev). |
$O(N \log N)$ with Multiset |
Draw a linear pass to transform points, then show N operations of $O(\log N)$ for removing/re-inserting from the Multiset. |
Large 2D distance matrix storing all pairwise results. |
Two TreeMap or Multiset structures to track x+y and x-y values. |
| 3103 |
Find Trending Hashtags II (SQL) |
Use a nested subquery to split every tweet into words, filter for '#' prefix, and then perform a GROUP BY on the entire mess. |
Recursive Text Splitting |
Draw a tweet bubble. Show it shattering into words. Draw a "Hashtag Magnet" pulling only the # terms. |
REGEXP_SUBSTR + Window Aggregation |
Frequency Ranking Funnel |
Use REGEXP_SUBSTR(text, '#[[:alnum:]]+', 1, occurrence) to pull hashtags. Group by tag, count, and use RANK() or ORDER BY to find the top 3 in a specific month. |
Draw a table. Draw an arrow "extracting" the tags. Group identical tags. Draw a pedestal for the top 3 tallest groups. |
$O(N \log N)$ Sorting Pass |
Draw a single pass through the tweets $O(N)$, followed by a sorting block for the hashtag frequencies. |
Massive temporary table containing every word from every tweet. |
The database's internal Hash Map used for the GROUP BY operation. |
| 3104 |
Find Longest Self-Contained Substring |
Generate all substrings, map character counts, and scan main string to check bounds. $O(N^3)$ |
Triangle of all combinations overlaid with dense character frequency checks. |
Bracket a substring. Draw arrows from inside characters to matching outside characters to show failure. |
Interval Merging / Prefix Sums |
Bounding Box Overlaps |
Mark [First, Last] occurrences of chars. Expand substring bounds to swallow overlapping character intervals completely. |
Write string. Underneath, draw horizontal colored line segments spanning the [first, last] index of each character. |
Set union diagram tracking a fixed 26-character alphabet. |
Draw the outer loop bounded to 26 characters max, and a single array pass for the inner loop. $O(26 x N)$ rightarrow $O(N)$. |
Huge list of frequency dictionaries for every single substring combination. |
One array of size 26 for bounds, and one integer tracking max valid length. |
| 3105 |
Longest Strictly Inc. or Dec. Subarray |
Check every possible subarray from start to finish for strict monotonicity. $O(N^2)$ |
Overlapping sub-segments dropping off midway when conditions fail. |
Start at i, draw line right until monotonicity breaks. Move to i+1, repeat. See nested overlap. |
Greedy / One-Pass State Machine |
Directional State Arrows |
Read left to right. If up, increment `inc`, reset `dec`. If down, increment `dec`, reset `inc`. Track `max`. |
Draw numbers. Draw upward or downward arrows between them. Count the longest unbroken chain of same arrows. |
Single vector traversal graph. |
Draw a single straight line moving index 0 rightarrow N. No backwards steps. |
Call stack visualization or array of saved subarray arrays. |
Three literal boxes: `max_len`, `inc`, `dec`. Show them overwriting in place. |
| 3106 |
Lexicographically Smallest String After Ops |
Backtracking to generate all valid string mutations within distance K, then sorting. **O(26^N)** |
Massive 26-ary decision tree expanding at each character index. |
Draw root string. Draw 26 branches for the first char, subtracting K. Repeat for all permutations. |
Greedy Left-to-Right / Math |
Fuel Gauge / Budget Bar |
Move left to right. If distance to 'a' ≤ K, change to 'a' and deduct from K. If > K, shift char backward by K, set K=0, stop. |
Write string. Under each char, write circular distance to 'a'. Draw a running K "budget" box above and deduct as you mutate. |
Single horizontal timeline. |
Draw a straight 1D line of length N. Mark an early exit point if K hits 0. **O(N)** runtime. |
Deep call stack memory holding thousands of string combinations. |
In-place modification: Single character array and one integer variable for K. **O(1)** aux space. |
| 3107 |
Min Operations to Make Median Equal to K |
Iteratively applying +1 or -1 to random elements, re-sorting, and checking median. **O(2^N * N log N)** |
State space graph of chaotic array mutations and sorts. |
Write array, draw +1/-1 arrows on random indices, draw a funnel to represent re-sorting every time. |
Sorting + Greedy Target Matching |
Seesaw Balancing / Histogram Leveling |
Sort array. Snap median to K. Sweep left: if element > K, chop down to K. Sweep right: if element < K, build up to K. |
Draw a sorted bar chart. Draw a horizontal target line at height K. Shade the "chop off" parts left of median and "fill in" parts right of median. |
Sort Funnel followed by a 1D scan. |
Draw an N log N branching tree (sort phase), followed by a single linear array pass evaluating differences. |
Queue of array copies for state searching. |
The original array sorted in-place, plus one long integer for `total_operations`. |
| 3108 |
Min Cost Walk in Weighted Graph |
DFS/BFS to find all possible paths from source to target, tracking bitwise ANDs. Will infinite loop due to cycles. |
Tangled web with infinite recursive loops. |
Draw a cyclic graph. Use colored pens to trace multiple infinite loops bouncing back and forth between nodes. |
Disjoint Set Union (DSU) / Connected Components |
Puddle Merging / Color-coded Islands |
Group connected nodes. As they merge, bitwise AND all their edge weights into one "island total". For queries: if nodes share an island, return the total. Else -1. |
Draw nodes as dots. Draw circles grouping connected dots. Inside the circle, write the cumulative Bitwise AND value of all inner edges. |
Forest of shallow, flat trees (Union-Find). |
Draw nodes pointing to a common root. The tree height is nearly flat. **O(E α(N) + Q α(N))**. |
Exponential call stack holding visited paths and bitmasks. |
Two arrays of size N: `parent[]` (for DSU) and `component_and[]` (storing the bitwise value). |
| 3109 |
Find the Index of Permutation |
Generate permutations in lexicographical order sequentially until matching the input array. **O(N!)** |
Odometer spinning through all factorials. |
Write the numbers 1 to N. Swap them systematically in dictionary order, tallying a massive count. |
Combinatorics + Fenwick Tree (BIT) |
Factorial Weight Scales |
For each number at index `i`, count available unused smaller numbers. Multiply by `(N-1-i)!`. Mark number used. Add to total. |
Write the array. Below it, list available digits. Draw an arrow from array element to smaller available digits, cross them out, and write `count * factorial`. |
Array iteration + logarithmic updates. |
Draw a linear pass of length N. At each step, draw a small binary tree representing a log N Fenwick update. **O(N \log N)**. |
Massive array storing millions of permutation lists. |
A `fenwick[]` array of size N and a precomputed `factorial[]` array of size N. |
| 3110 |
Score of a String |
Creating pairs of all adjacent chars into a new structure, then mapping absolute differences. **O(N)** time, **O(N)** space. |
Separating the string into overlapping string objects. |
Write string. Draw out separate 2-character strings below it, then map values. |
Linear Simulation / Iteration |
Sliding Window of Size 2 |
Iterate from index 0 to N-2. Subtract ASCII value of `s[i]` from `s[i+1]`, take absolute value, add to sum. |
Write string. Draw a 2-character box. Move it right step-by-step. Write the numeric difference inside the box. |
A straight line with sequential, discrete steps. |
Draw an array. Draw short curved arrows strictly between index `i` and `i+1`. Label each arrow **O(1)**. |
An array storing N-1 numeric differences before summing. |
A single scalar variable `score` tracking the sum. **O(1)** aux space. |
| 3111 |
Minimum Rectangles to Cover Points |
Iterate all subsets of points to find valid bounds, or check every point against every other point. **O(N^2)** or exponential. |
Overlapping 2D bounding boxes scattered chaotically across a coordinate plane. |
Draw random dots on a 2D grid. Attempt to draw boxes covering them randomly, crossing out redundant overlapping boxes. |
1D Greedy / Sorting |
1D Number Line Sweeping (Ruler Method) |
Ignore Y-coordinates entirely. Sort X-coords. Place a "ruler" of length W starting at the first point. Skip all points under the ruler. Repeat. |
Draw a horizontal line. Mark dots for X-coordinates. Use your thumb to represent width W, sliding left to right and covering dots. |
A sorting funnel followed by a linear timeline sweep. |
Draw an **O(N log N)** branching tree for the sort, then a straight horizontal line **O(N)** skipping chunks. |
Large matrix holding combinations of point subsets. |
Two scalar registers: `rect_count` and `current_limit` (the W boundary). **O(1)** aux space. |
| 3112 |
Minimum Time to Visit Disappearing Nodes |
Explore all possible graph paths recursively (DFS/BFS) without pruning, checking disappearance times at the end. **O(V!)** |
Exploding, infinitely branching tree where branches randomly vanish or hit dead ends. |
Draw nodes. Trace every single path from 0 to target with different colored pens, manually checking a clock array at every step. |
Modified Dijkstra's Algorithm (Min-Heap) |
Expanding Wavefront with Ticking Bombs |
Pop closest node from Heap. If current time ≥ node's disappearance time, skip it (it exploded). Otherwise, relax neighbors. |
Draw nodes as circles with a "bomb timer" inside. Track a "current time" tally. Draw arrows out, immediately crossing out bombs that have exploded. |
Dynamic priority queue tree. |
Draw a standard **O(E log V)** binary tree (heap) where subtrees are dynamically pruned/erased midway. |
Enormous recursive call stack storing all traversed paths. |
A priority queue array and a distance array of size V. **O(V)** space. |
| 3113 |
Find the Number of Subarrays Where Boundary Elements Are Maximum |
Generate all possible subarrays, then linearly scan each one to find the maximum element. **O(N^3)** |
A dense triangle of all subarrays, calculating the max for every single bracket iteratively. |
Write the array. Draw overarching brackets for every combination. Physically scan inside every bracket to find the max and check both ends. |
Monotonic Stack |
Histogram Bars Flattening Smaller Elements |
Iterate right. If current element is taller than stack top, pop stack (smaller elements are "blocked"). If equal, increment count. Push current. |
Draw a bar chart. As you move right, if a bar is taller, physically erase all shorter bars to its left. Tally up matching heights that "see" each other. |
Elements entering and leaving a vertical tube at most once. |
Draw an array. Draw exactly one arrow going into a stack box and one arrow leaving it per element. **O(N)**. |
A massive array storing every generated subarray sequence. |
A stack structure of maximum size N storing `[value, count]` pairs. **O(N)** space. |
| 3114 |
Latest Time You Can Obtain After Replacing Characters |
Generate all possible time combinations (up to 1440 minutes), filter by the '?' pattern, and take the maximum. **O(N)** |
A branching tree of digits 0-9 filtering out invalid time formats. |
Write `??:??`. Draw arrows down creating all 1440 minutes, cross out non-matching ones sequentially. |
Greedy Constraint Matching |
Left-to-Right Slot Machine |
Evaluate digits independently. If `s[0] == '?'`, make it '1' if `s[1]` is '0' or '1', else '0'. `s[3]` is '5', `s[4]` is '9'. |
Draw 4 empty boxes. Fill them left to right based on immediate local max rules (max 11 hours, max 59 mins). No backtracking needed. |
Constant time execution, 4 discrete steps. |
Draw exactly 4 dots connected by 4 straight lines. Label it **O(1)**. |
An array of 1,440 generated string variables. |
Modifying the 5-character string in-place. **O(1)** space. |
| 3115 |
Maximum Prime Difference |
Nested loops comparing every single pair of indices (i, j) and running a prime check on both. **O(N^2 * sqrt(M))** |
An N x N matrix calculating distance and primality redundantly. |
Draw array. Connect every element to every other element with an arc, run a prime division check manually on both ends of every arc. |
Two Pointers (Inward Search) |
Pincers Moving Inwards |
Scan left-to-right to find the first prime, log index. Scan right-to-left to find the first prime, log index. Return `right - left`. |
Draw array. Put left finger on start, move right until prime. Put right finger on end, move left until prime. Subtract the indices. |
1D sweep from both ends stopping early. |
Draw a straight line of length N. Draw one arrow starting left stopping early, and one starting right stopping early. **O(N * sqrt(M))**. |
A redundant 2D matrix tracking distances of all valid prime pairs. |
Two integer pointer variables `left` and `right`. **O(1)** space. |
| 3116 |
Kth Smallest Amount With Single Denomination Combination |
Generate multiples for all coins, throw them in a massive array, sort, and find the Kth element. $O(K x N \log(\text{KN})$) |
Multiple endless tape measures unrolling at different speeds, merging into a chaotic pile. |
Write out the multiplication tables for each coin side-by-side. Manually circle numbers and cross out duplicates until you hit K circles. |
Binary Search + Inclusion-Exclusion (PIE) |
Venn Diagram inside a Search Space |
Guess a midpoint amount. Use PIE to count how many valid coin multiples exist below this amount (Add single coins, subtract pairs, add triples). Adjust bounds. |
Draw a number line. Pick a guess `M`. Below `M`, draw overlapping circles for coin multiples. Put `+` in single areas, `-` in overlaps. |
Binary search tree shrinking over a constant mathematical calculation. |
Draw a timeline. Halve it. At the midpoint, draw a small $O(2^N)$ equation tree. Repeat logarithmically. |
A massive array holding potentially millions of generated multiples. |
$O(1)$ space or small 2^N precomputed LCM array for the coin combinations. |
| 3117 |
Minimum Sum of Values by Dividing Array |
Generate all 2^N-1 possible array partitions using bars/dividers, calculate the Bitwise AND for every segment. $O(2^N x N)$ |
A massive, exponentially exploding fractal tree of array splits. |
Write the array. Draw random vertical lines (dividers). Manually perform Bitwise AND for the elements between every single line. |
DP + Memoization + Bitwise AND |
Decision Tree with Dead-End Pruning |
Move index by index. Current state: AND value so far. Two choices: 1) Absorb into current subarray. 2) End subarray (only if AND matches target). |
Draw array. Move finger right, updating a running AND value. Draw a split path: one continuing, one breaking off with a "fresh start" box. |
3D State Space Grid |
Draw a grid of `index` x `subarray_count` x `current_AND`. Shade in boxes to represent $O(N x M x \log(\text{Max})$) visited states. |
Deep recursive call stack with redundant paths filling up memory exponentially. |
A 3D Memoization table/dictionary tracking visited states. |
| 3118 |
Friday Purchase III (SQL) |
Cartesian product of all dates and all users, followed by heavy row-by-row filtering. (Inefficient DB Execution) |
Massive N x M matrix where 99% of the cells are blanked out sequentially. |
Draw every user connected to every day in November with string. Cut the strings that aren't Fridays or specific memberships. |
Recursive CTE + LEFT JOIN |
Assembly Line / Data Pipeline |
Generate a strict list of 4 Fridays. Generate a strict list of 2 Memberships. Cross join them into a perfect 8-row base. Left Join actual sales onto this base. |
Draw 3 separate mini-tables (Fridays, Members, Sales). Draw clean arrows routing from the Sales table into the perfectly pre-structured base table. |
Pipeline / Directed Acyclic Graph (DAG) |
Draw three parallel data streams merging cleanly into one output node. |
Temporary memory holding an unindexed Cartesian explosion. |
Tight, 8-row temporary table stored in cache before the final JOIN. |
| 3119 |
Maximum Number of Potholes That Can Be Fixed |
Try repairing every possible contiguous subset of potholes and checking if it fits the budget. $O(2^N)$ |
Trying to fit a single Tetris block into thousands of random gaps to see what fits best. |
Draw the road. Randomly shade different groups of potholes, subtract budget, realize you ran out, erase, and start over. |
Greedy + Counting / Bucket Sort |
Histogram Leveling / Top-Down Chopping |
Count lengths of contiguous potholes. Sort lengths descending. Buy the longest blocks first (best cost-per-pothole ratio) until budget runs out. |
Draw horizontal bars for each group of potholes. Stack them tallest to shortest. Use a highlighter to color from the top down until budget is 0. |
Linear Scan + Sorting phase. |
Draw an $O(N)$ straight line to count, followed by an $O(N \log N)$ sorting funnel, followed by a final linear timeline. |
Call stack mapping thousands of combinations of budget allocations. |
A frequency map or array of size N storing pothole counts. |
| 3120 |
Count the Number of Special Characters I |
For every character, loop through the entire string again to check if its opposite case exists. $O(N^2)$ |
Spaghetti web of lines pointing from every character to every other character in the string. |
Point to 'a'. Scan your finger all the way to the end looking for 'A'. Point to 'B'. Scan your finger from the start looking for 'b'. |
Hash Set / Boolean Arrays |
Two-Row Switchboard |
Create a Lowercase array and Uppercase array. Scan string once. Flip the switch for the characters seen. AND the two boards together. |
Draw two rows of 26 checkboxes (a-z and A-Z). Read the string left to right, ticking the corresponding box. Count columns with two ticks. |
Single pass timeline + constant time check. |
Draw one straight line of length N. Then draw a tiny fixed box of size 26. $O(N)$ time. |
None (if done in place, but highly inefficient time-wise). |
Two tiny fixed arrays of size 26, representing $O(1)$ auxiliary space. |
| 3121 |
Count the Number of Special Characters II |
For every lowercase character, scan the entire rest of the string to find its uppercase counterpart and verify no later lowercase matches exist. $O(N^2)$ |
Nested loops firing sequential, chaotic arrows scanning forward and backward across the string. |
Write the string. Put your finger on 'a'. Move your other finger right scanning for 'A'. If found, rescan to make sure no more 'a's exist. |
Hash Table / Array Mapping (Single Pass) |
Dual Timestamp Arrays |
Read string left to right. Record the *last* seen index of every lowercase char. Record the *first* seen index of every uppercase char. If `last_lower[c] < first_upper[c]`, it's special. |
Draw two boxes of size 26. As you read the string once, write the current index into the boxes. At the end, compare the two boxes element by element. |
1D timeline sweep + fixed constant-time check. |
Draw a line of length N. Follow it with a tiny, fixed box representing exactly 26 constant operations. $O(N)$. |
Pointers moving dynamically within a double for-loop call stack. |
Two arrays of size 26 (representing lowercase and uppercase tracking). $O(1)$ auxiliary space. |
| 3122 |
Min Operations to Satisfy Conditions |
Recursively try changing every grid cell to every number from 0 to 9 to see which combination fits the rules and costs the least. $O(10^M x N)$ |
Massive, exploding tree with 10 branches stemming from every single grid cell. |
Draw the matrix. Physically erase and rewrite numbers 0-9 randomly, checking rows/cols, erasing again when it fails. |
Dynamic Programming (Column by Column) |
State Transition Wave (Moving Left to Right) |
Precompute frequencies of 0-9 per column. DP State: If column `i` is made entirely of digit `k`, add the operations `(rows - freq[k])` to the best valid cost of column `i-1`. |
Draw an N x 10 DP table. Fill it left to right. Draw arrows from valid states in column `i-1` to compatible states in column `i`. |
N x 10 grid filling up left to right sequentially. |
Draw an array of size 10. Physically cross out and rewrite the values inside it N times as you traverse columns. $O(N x 10)$ rightarrow $O(N)$. |
Enormous call stack holding deep recursive state grids. |
An N x 10 memoization table, or two 1 x 10 arrays (current and previous state). $O(N)$. |
| 3123 |
Find Edges in Shortest Paths |
Use DFS to find *all* possible paths from start to finish, sum their weights, and filter for edges inside the minimum paths. $O(V!)$ |
A tangled web of every possible route branching endlessly through the nodes. |
Draw nodes. Use different colored pens to trace every single path. Sum them up manually and circle the ones matching the lowest sum. |
Dijkstra's (Bi-directional) + Edge Relaxation |
Colliding Wavefronts |
Run Dijkstra from node 0 (save distances to `dist0`). Run Dijkstra from node N-1 (save distances to `dist1`). For any edge (u,v,w), if `dist0[u] + w + dist1[v] == min_path`, it's valid. |
Draw graph. Write `dist0` on top of nodes, `dist1` below them. For an edge, add `top(u) + weight + bottom(v)`. Does it equal the total shortest path? Check mark it. |
Two expanding Priority Queue trees + 1D array scan. |
Draw two $O(E \log V)$ binary trees (heaps). After they complete, draw a linear array sweep representing the $O(E)$ edge check. |
Exhaustive path arrays tracking visited nodes for every route. |
Two distance arrays of size V and a Priority Queue. $O(V + E)$ space. |
| 3124 |
Find Longest Calls (SQL) |
Perform a full cross-join of the tables without filtering, load everything into memory, and manually sort. |
A massive Cartesian product matrix ballooning horizontally and vertically. |
Draw lines connecting every single call row to every single contact row. Manually cross out the ones that don't match IDs. |
JOIN + Window Function (RANK) |
Data Partitioning Funnel |
`JOIN` tables on ID. Use `RANK() OVER (PARTITION BY type ORDER BY duration DESC)`. This splits data into 'incoming' and 'outgoing' buckets and sorts them internally. Filter `rank <= 3`. |
Draw a big funnel. Split it into two buckets (incoming/outgoing). Inside the buckets, stack rows highest to lowest. Draw a line cutting off anything below the 3rd row. |
Pipeline / Directed Acyclic Graph (DAG) |
Draw two parallel data streams merging into one node, partitioning into two, then hitting a filter node. |
Unindexed Cartesian explosion in memory holding $O(A x B)$ rows. |
Temporary memory holding the partitioned and ranked sets. |
| 3125 |
Max Number That Makes Result of Bitwise AND Zero |
Loop backward from N-1 to 1. Check if `N & i == 0`. Return the first one that matches. $O(N)$ |
Iterating backward step-by-step on a number line, running a bitwise operation at each tick. |
Write the binary of N. Write binary of N-1, N-2, etc. manually stacking them and performing an AND until the result is 0. |
Bit Manipulation / Math |
Flipping the Most Significant Bit |
Find the highest set bit (MSB) of N. The answer is mathematically guaranteed to be the maximum number with all bits set *strictly below* that MSB. If MSB is at index `i`, answer is (1 ll i) - 1. |
Write N in binary (e.g., `10110`). Cross out the leftmost `1`. Write `1`s everywhere to the right of it (`01111`). Convert to decimal. |
Single $O(1)$ discrete mathematical jump. |
Draw a binary string, erase the first 1, fill the rest with 1s. Write $O(1)$ or $O(\log N)$ depending on how bits are counted. |
A loop counter variable tracking the backward countdown. |
A single scalar integer variable. $O(1)$ space. |
| 3126 |
Server Utilization Time (SQL) |
Self-joining the table on every possible pair of timestamps and manually checking if they are adjacent "start" and "stop" events. $O(N^2)$ |
N-to-N connectivity graph where most lines are invalid. |
Draw two columns of timestamps. Draw lines between every timestamp in col 1 and every timestamp in col 2. Cross out 99% of them. |
Window Function (LEAD) + CTE |
Ordered Sequence Pairing |
Sort by `server_id` and `timestamp`. Use `LEAD()` to "peek" at the next row. If current is 'start', subtract current from peek. Sum the results. |
Draw a vertical list of rows. Draw a small arrow from row i to row i+1. Label the difference in seconds next to the arrow. |
Single-pass linear scan on sorted data. |
Draw a single straight line representing the sorted index. $O(N \log N)$ due to sorting, then $O(N)$ scan. |
Massive temporary table containing all N^2 row combinations. |
One sorted cursor and a running `sum` variable. |
| 3127 |
Make a Square with the Same Color |
Try changing every single cell (9 cells) and then for each change, check every 2x2 square (4 squares). $O(9 x 4)$ |
A small decision tree with 10 branches (no change + 9 possible changes). |
Draw the 3x3 grid 10 times. For each, circle the four 2x2 areas and check if all colors match. |
Sliding Window (Fixed 2x2) / Counting |
Quadrant Inspection |
Check each of the four 2x2 squares. If any square has >= 3 Black or >= 3 White cells, return True. |
Draw the 3x3 grid. Use a 2x2 "viewfinder" (cut out of paper or traced) to frame the 4 corners. Tally 'B' and 'W' inside. |
Constant-time check of 4 fixed zones. |
Draw four discrete boxes. Label each as $O(1)$. Total $O(4)$ = $O(1)$. |
10 separate copies of the 3x3 grid in the recursion stack. |
Two integer counters (`black`, `white`) reused for each quadrant. $O(1)$. |
| 3128 |
Right Triangles |
Iterate through all combinations of 3 cells in the matrix where each cell is '1' and check if they form a right triangle. $O(N^6)$ or $O((N^2)$^3) |
Combinatorial explosion graph connecting every triple of '1's. |
Draw a grid with '1's. Try every possible group of 3 '1's, drawing a triangle and checking the angle at each vertex. |
Precomputation / Combinatorics |
Cross-Hair Counting |
Count total '1's in each row and column. For every '1' at (r, c), the number of right triangles with (r, c) as the vertex is (row_count[r]-1) x (col_count[c]-1). |
Draw the grid. Next to rows, write the sum of 1s. Below columns, write the sum of 1s. At a '1', multiply the neighboring sums (minus 1). |
Two linear scans + one matrix pass. |
Draw a horizontal sweep arrow (rows), a vertical sweep arrow (cols), and a final grid traversal. $O(R x C)$. |
List of all valid coordinate triples. |
Two 1D arrays of size R and C respectively. $O(R+C)$. |
| 3129 |
Find All Possible Stable Binary Arrays I |
Recursive backtracking to generate all permutations of `zero` and `one`, checking the `limit` constraint at each step. $O(2^Z+O)$ |
Binary tree with depth Z+O. |
Draw a tree starting at an empty array. Branch '0' and '1'. Cross out any branch that has more than `limit` consecutive same digits. |
DP + Memoization (State: zeros, ones, last_bit) |
3D DP Grid Transition |
`dp[i][j][k]` = ways with i zeros, j ones, ending in bit k. To get dp[i][j][0], sum dp[i-1][j][0] + dp[i-1][j][1] and subtract cases that exceed the limit. |
Draw a grid with Z rows and O columns. Each cell has two numbers (ending in 0 or 1). Draw arrows showing how values flow from previous counts. |
State-space traversal of a Z x O x 2 grid. |
Draw a Z x O table. Mark $O(Z x O)$ operations. |
Deep recursion stack with millions of active branches. |
A 3D array of size Z x O x 2. $O(Z x O)$. |
| 3130 |
Find All Possible Stable Binary Arrays II |
Same as 3129, using the $O(Z x O x \text{limit})$ transition. Under high constraints, this TLEs. |
DP grid where each cell transition involves a long loop back of size `limit`. |
In the DP grid, draw an arrow that sums the last `limit` cells for every single transition. |
DP + Prefix Sum Optimization |
Sliding Window Sum in DP State |
Optimize the "Limit subtraction" by observing that the sum needed is a range of previous DP values. Use a running prefix sum to calculate the subtraction in $O(1)$. |
Draw the DP table. Beside it, draw a "Prefix Sum" version of the table. Show that calculating a cell only requires 2-3 lookups in the prefix table. |
Flattened $O(1)$ transition DP. |
Draw the same Z x O table as 3129, but mark each cell calculation as a constant number of lookups. $O(Z x O)$. |
Same as 3129. |
3D array of size Z x O x 2, plus auxiliary prefix sum tables. $O(Z x O)$. |
| 3131 |
Find the Integer Added to Array I |
Try every possible integer x and for each, check if all elements in nums1 + x exist in nums2. $O(N^2 \log N)$ or $O(N^2)$ |
Multi-layer comparison grid where every element of A checks every element of B. |
Draw two arrays. Draw lines from every element in the first to every element in the second to calculate potential x. |
Min-Element Comparison / Math |
Scale Balance |
Find the smallest element in nums1 and nums2. The difference is the only possible x. |
Draw two boxes. Label them `min1` and `min2`. Draw an arrow between them showing the subtraction. |
Single pass through each array. |
Draw two parallel lines of length N. Mark a single comparison step at the end. $O(N)$. |
Temporary storage for all potential x candidates. |
Two scalar variables for minimums. $O(1)$. |
| 3132 |
Find the Integer Added to Array II |
Generate all possible subsets of nums1 with 2 elements removed, then check if they can be transformed into nums2. $O(N^3)$ |
Combination tree for removing elements paired with comparison loops. |
Draw nums1. Cross out two numbers. Compare remaining with nums2. Repeat for every combination of 2 crosses. |
Sorting + Small Constant Search |
Candidate Filtering |
Sort both arrays. Since only 2 elements are removed, the added integer x *must* be nums2[0] - nums1[i] where i in 0, 1, 2. Try only these 3 cases. |
Draw two sorted arrays. Draw 3 arrows from nums2[0] to the first 3 indices of nums1. Validate each "path" using two pointers. |
Sort funnel followed by 3 linear checks. |
Draw $O(N \log N)$ sort tree, then 3 straight lines representing $O(N)$ pointer passes. |
Storing all generated subarrays after removing elements. |
In-place sorting or a copy of the array. $O(N)$ or $O(1)$ depending on implementation. |
| 3133 |
Minimum Array End |
Iteratively check every number starting from x and count how many have (num AND x) == x until reaching n. $O(n \\text{cdot bits})$ |
A slow number line "tally" counter skipping invalid numbers. |
Write x in binary. Write x+1, x+2... underneath. Perform bitwise AND for each until you've found n valid matches. |
Bit Manipulation (Zero-Bit Filling) |
Binary Bit-Mask Inlay |
Identify all '0' bit positions in x. Take binary representation of n-1 and "pour" its bits into these '0' slots of x. |
Write x in binary. Circle the zeros. Write (n-1) in binary above it. Draw arrows dropping (n-1) bits into the circled zeros. |
Single bit-by-bit scan of the number's length. |
Draw a 64-bit register. Mark a single pass of length 64. $O(\log N + \log X)$. |
A large list storing every number that satisfies the AND condition. |
A few 64-bit integer variables. $O(1)$. |
| 3134 |
Median of Uniqueness Array |
Generate every single subarray, count unique elements in each, put counts in an array, sort, find median. $O(N^3 \log N)$ |
Dense triangle of subarray statistics leading to a sorting funnel. |
Draw the array. Bracket every possible segment. Count unique numbers in each bracket. Write counts in a long list and sort it. |
Binary Search on Answer + Sliding Window |
Monotonic "Uniqueness Threshold" Slider |
Binary search for the median M in range [1, N]. For a guess M, use a sliding window to count how many subarrays have <= M unique elements. |
Draw a number line 1 to N. Pick midpoint. Below it, draw an array with two pointers L and R and a frequency map, counting valid windows. |
log N iterations of an $O(N)$ scan. |
Draw a Binary Search tree where each node contains a horizontal $O(N)$ timeline. $O(N \log N)$. |
Massive $O(N^2)$ array storing counts for every subarray. |
A frequency hash map of size N for the sliding window. $O(N)$. |
| 3135 |
Equalize Strings by Adding or Removing Characters at Ends |
Try every possible substring of s1 and see if it is a substring of s2. Calculate costs for each. $O(N^4)$ or $O(N^3)$ |
Nested loops comparing all window combinations of two strings. |
Write s1 and s2. Draw brackets on s1, try to find a matching segment in s2 by scanning. Tally add/remove ops. |
Longest Common Substring (LCS Variant) |
Sliding Window Matcher |
Find the longest common substring between s1 and s2. The answer is (len(s1) - LCS_len) + (len(s2) - LCS_len). |
Draw s1 and s2 on top of each other. Slide s2 across s1 until the largest overlap is found. Box the overlap. |
2D DP matrix or a linear sliding window comparison. |
Draw an N x M grid for DP or a sequence of N+M slides. $O(N x M)$. |
Storing every substring of both strings. |
An N x M DP table or $O(1)$ if using smart sliding (for space-optimized LCS). $O(N x M)$. |
| 3136 |
Valid Word |
For each requirement (length, vowel, consonant), run a full independent scan of the string. $O(3N)$ rightarrow $O(N)$ |
Parallel linear scans checking distinct conditions. |
Draw three horizontal lines representing the string. On line 1, mark length. On line 2, circle vowels. On line 3, circle consonants. |
Single-Pass Flagging |
Logic Gate / Status LED Board |
Iterate once. Set `hasVowel`, `hasConsonant`, and `isInvalid` flags. Check all flags at the end. |
Draw three checkboxes labeled 'V', 'C', 'ValidChars'. Walk through the word; check the box as soon as the condition is met. |
Linear sequence of constant-time operations. |
Draw one straight line with a single "Check" box at the end. $O(N)$. |
Multiple boolean arrays storing the status of every character. |
Three boolean flags (1 bit each). $O(1)$. |
| 3137 |
Minimum Number of Operations to Make Word K-Periodic |
Generate every possible K-periodic string, compare it against the original, and count differences. $O(N \\text{cdot Variations})$. |
Infinite Periodic Generation |
Draw the string. Below it, draw 50 different repeating patterns, scanning character by character to find the best match. |
Hash Map / Chunk Frequency |
The Block Dominance Grab |
Slice the word into chunks of size K. Use a Hash Map to count chunk frequencies. The optimal strategy is to keep the most frequent chunk and replace all other chunks with it. Operations = `Total Chunks - Max Chunk Frequency`. |
Draw the string. Slice it with vertical lines every K letters. Stack identical slices into piles. Find the tallest pile. The answer is the number of slices in all the *other* shorter piles combined. |
Linear Chunking $O(N)$ |
Draw a single pass that hops by K steps at a time, updating a hash map in $O(1)$. |
Millions of generated strings. |
A Hash Map holding N/K strings. $O(N)$ space. |
| 3138 |
Minimum Length of Anagram Concatenation |
Try every possible length L from 1 to N. Check if every L-length block is an anagram of the first. $O(N x \text{Divisors} x 26)$ |
Branching divisor tree checking block symmetry. |
Write the string. Try splitting into blocks of size 1, 2, 3... For each split, count characters in every block and compare. |
Divisor Iteration + Freq Map Comparison |
Synchronized Histogram Overlay |
Iterate through divisors d of N. For each d, compare the 26-char frequency counts of all N/d blocks. Stop at the first valid d. |
Draw string blocks. Below each, draw a tiny 26-slot bar chart. If all bar charts in a row match, you found the answer. |
Multi-pass filter on divisors. |
Draw a timeline. Below it, draw a few "checkpoints" only at divisor indices. $O(\text{Divisors} x N)$. |
Storing every possible permutation of the string for comparison. |
One or two arrays of size 26 for frequency counting. $O(1)$ auxiliary (ignoring alphabet size). |
| 3139 |
Minimum Cost to Make Array Elements Equal |
Try all possible target values T from `max(nums)` to 2 x max, and for each, calculate $O(1)$ cost using greedy pairs. $O(N \\text{cdot Range})$ |
A parabolic cost curve calculated point-by-point. |
Draw a number line. Pick a height. Calculate total gaps. Try to "fill" gaps using pairs (cost c2) or singles (cost c1). Repeat for every height. |
Greedy Math + Case Analysis |
Gap Filling / Water Leveling |
Target = Max. Calculate total "gap" to fill. If 2 x c1 <= c2, only use c1. Otherwise, use as many c2 pairs as possible. Check Target and Target+1. |
Draw bars of different heights. Shade the empty space. Use "2-cell bricks" for c2 and "1-cell bricks" for c1. Solve like a puzzle. |
Constant-time math after a linear scan. |
Draw a single straight line to find Max/Min, followed by a single math equation. $O(N)$. |
Recursive tree of all possible cost combinations. |
Two scalar variables: `sum`, `max_val`. $O(1)$. |
| 3140 |
Consecutive Available Seats II |
Try flipping every possible 3-element window randomly using backtracking to find the shortest path to all 1s. $O(2^N)$. |
Exploding Flip Tree |
Draw the array. Branch out into every possible 3-window flip combination. State space grows exponentially. |
Greedy Sliding Window |
The Forced-Hand Flipper |
Iterate left to right. If `nums[i] == 0`, you *must* flip the window starting at `i`. If you don't, `nums[i]` will forever remain 0. Flip `i, i+1, i+2`. If you reach the end and the last two aren't 1s, it's impossible. |
Draw the array. Slide a 3-block bracket left-to-right. If the first number in the bracket is a 0, flip all 3. If it's a 1, just slide forward. |
Single Pass $O(N)$ |
Draw a straight timeline. At each step, perform max 3 bit flips. |
Recursive state history. |
Modified array in-place. $O(1)$ space. |
| 3141 |
Maximum Hamming Distances |
Actually physically flip all elements from `i` to the end of the array every time you see a 0. $O(N^2)$. |
Cascading Array Waves |
Draw the array. When hitting a 0, draw a massive wave flipping every single element to the right. Do this repeatedly. |
State Tracking (Parity / Flip Count) |
The Virtual Toggle Switch |
Don't physically flip anything. Track the total `flip_count`. The *actual* value of `nums[i]` is `(nums[i] + flip_count) % 2`. If the actual value is 0, increment `flip_count`. |
Draw the array. Hold a physical "Toggle Switch" in your hand (starts at 0). As you walk, mentally apply the switch to the number. If the result is 0, flip the switch in your hand and add a tally mark. |
Strict Linear Scan $O(N)$ |
Draw a single straight line. Each element checked with a single $O(1)$ modulo operation. |
Continuous full-array rewrites. |
A single integer `flip_count`. $O(1)$ space. |
| 3142 |
Check if Grid Satisfies Conditions |
For every cell (i, j), check all other cells in the same column and adjacent rows to see if they match the rules. $O((N x M)$^2) |
A web of comparison lines connecting every cell to its neighbors. |
Draw a grid. Put your finger on cell (0,0). Scan all other cells to check the column/row rules. Repeat for every cell. |
Matrix Traversal (Local Constraint) |
Scanner Beam |
Iterate through the grid. Only check if grid[i][j] == grid[i+1][j] and grid[i][j]
eq grid[i][j+1]. One bad check returns false. |
Draw a grid. Draw a small "L-shaped" bracket that moves across the grid. The bracket checks the cell below and the cell to the right. |
Sequential grid scan. |
Draw a snake-like path through the grid. $O(N x M)$. |
A full adjacency list of all cell relations. |
No extra space. $O(1)$ auxiliary. |
| 3143 |
Maximum Points Inside Square |
Try every possible square side length S. For each S, check all points to see if they fit and if tags are unique. $O(\text{Range} x N)$ |
A pulsating square growing and shrinking, counting points inside. |
Draw points on a graph. Draw a square of size 1. Count points. Draw size 2. Count... until you see a duplicate tag. |
Sorting / Binary Search on Answer |
The Expanding Bounding Box |
For each point, calculate its "critical size": max(|x|, |y|). Sort points by this size. Add points to a set one by one; stop before the size that introduces a duplicate tag. |
Draw points. Next to each, write its distance d = max(|x|, |y|). List points in a table sorted by d. Sweep down the table until a tag repeats. |
Sort funnel + Linear scan. |
Draw an $O(N \log N)$ sorting tree followed by a single line of length N. |
A dictionary for every possible square size tested. |
A Frequency Map/Set of size 26 (alphabet). $O(1)$ auxiliary. |
| 3144 |
Min Substring Partition of Equal Character Frequency |
Generate all possible partitions of the string and check if each substring is "balanced" (all present chars have same frequency). $O(2^N)$ |
An exponential recursion tree of "cut" positions. |
Write the string. Draw vertical lines (dividers) in every possible position. Check balance for every segment created. |
Dynamic Programming + Freq Counting |
Shortest Path in a Partition Graph |
`dp[i]` is the min partitions for prefix `s[0...i]`. For each i, look back at all j < i. If `s[j...i]` is balanced, `dp[i] = min(dp[i], dp[j] + 1)`. |
Draw the string. Below it, draw a 1D DP array. For a cell i, draw arrows pointing back to previous valid "balanced" split points. |
$O(N^2)$ grid of transitions. |
Draw an N x N lower-triangular matrix representing the look-back loops. $O(N^2)$. |
A list of all possible partition strings. |
A 1D DP array of size N and a freq map of size 26. $O(N)$. |
| 3145 |
Find Products of Elements of Big Array |
Generate the "Big Array" by concatenating binary powers of every number, then calculate the product of the range. $O(\text{Exponential})$ |
An unrolling tape of numbers that grows too large for memory. |
Write 1, 2, 3... in binary. List their powers of 2. 1 rightarrow [2^0], 2 rightarrow [2^1], 3 rightarrow [2^0, 2^1]. Concatenate these into one long array. |
Binary Search + Bit Counting Math |
The Bit-Waterfall (Digit DP Style) |
Use binary search to find which integer the `from` and `to` indices land in. Use combinatorial math to count how many 2^0, 2^1... exist up to that integer. |
Draw a table of bit positions (2^0, 2^1, 2^2). Use a "Digit DP" logic to calculate how many times each bit flips in a range. Use modular exponentiation for the product. |
Logarithmic search space with constant bitwise math. |
Draw a Binary Search tree (O(log (total bits))). At each node, draw 64 small boxes representing the bit positions. $O(\log^2(\text{Value})$). |
The entire concatenated Big Array. |
$O(1)$ auxiliary space (just math variables). |
| 3146 |
Permutation Difference between Two Strings |
For each char in s, search for its index in t using a nested loop. $O(N^2)$ |
A web of lines connecting characters in s to distant positions in t. |
Write s and t. For each char in s, draw an arc to its match in t. Tally the "length" of the arc. |
Hash Map / Frequency Indexing |
Dual-Address Directory |
Map chars of s to their indices in a fixed array. Then iterate through t, looking up the stored index to calculate the diff. |
Draw an array of 26 boxes. Fill them with the indices from s. Then read t and subtract the value in the box from the current index. |
Linear one-pass timeline. |
Draw a straight line 0 rightarrow N. Label it $O(N)$. |
None (re-scanning the string). |
A fixed array of size 26. $O(1)$ auxiliary. |
| 3147 |
Taking Maximum Energy From the Mystic Dungeon |
From every possible starting index i, simulate the jumps of size k until the end, summing energy. $O(N^2/k)$ |
A forest of sparse jump-paths starting at every index. |
Write the array. Draw arrows from 0 to k, 2k... Then from 1 to 1+k, 1+2k... Tally each chain separately. |
Dynamic Programming (Suffix Sum with Jump) |
Reverse Waterfall |
Start from the end of the array. The max energy at index i is `energy[i] + energy[i+k]` (if within bounds). Carry the sum backward. |
Write the array. Start at the end. Draw an arrow from index i back to i-k, adding the value. Only one pass needed. |
One-pass linear traversal. |
Draw a single straight line from N rightarrow 0. $O(N)$. |
Stack of energy sums for every starting point. |
Modifying the energy array in-place or a single 1D DP array. $O(1)$ or $O(N)$. |
| 3148 |
Maximum Difference Score in a Grid |
For every cell (r, c), try moving to every possible cell (r', c') where r' >= r and c' >= c. $O((M x N)$^2) |
An explosive grid where every cell points to all cells in its bottom-right quadrant. |
Draw a grid. Pick a cell. Draw arrows to every single cell below and to the right of it. Sum the diffs. |
2D DP (Prefix Minimum) |
The Growing Shadow |
As you move through the grid, track the minimum value seen so far in the current row and column. Score at (r, c) = grid[r][c] - min(prev_row, prev_col). |
Draw the grid. In each cell, write the minimum of the cell above it and the cell to its left. Use that min to calculate the max score locally. |
Single grid scan. |
Draw a snake-path through the grid $O(M x N)$. |
A 2D matrix storing all possible path scores. |
Reusing the input grid or a 1D "row" array for min-tracking. $O(1)$ or $O(N)$. |
| 3149 |
Find the Minimum Cost Array Permutation |
Generate all N! permutations and calculate the cost for each. $O(N \cdot N!)$ |
A factorial tree branching N times at every level. |
Write 0...N. Try every order. 0,1,2..., 0,2,1..., etc. Calculate |perm[i] - adj[perm[i+1]]| for each. |
Bitmask DP (TSP Variant) |
The Subset State-Space Graph |
`dp(mask, last)`: min cost to complete the permutation given the set of used numbers (`mask`) and the previous number added (`last`). Use bitmask to represent the set. |
Draw a column of binary numbers (masks). Draw arrows between them representing adding a new number. Use memoization to avoid repeating the same mask-last state. |
Exponential state-space (2^N x N) with $O(N)$ transitions. |
Draw a grid of size 2^N x N. Label each cell calculation as $O(N)$. Total $O(2^N \cdot N^2)$. |
Massive N! permutation lists in memory. |
A 2D DP table of size 2^N x N. $O(2^N \cdot N)$. |
| 3150 |
Invalid Tweets II (SQL) |
Load all tweets, then use a procedural loop to check string length and character counts (@, #). |
Sequential row-by-row inspection with heavy regex. |
Draw a table of tweets. For each row, count characters with your finger, check against 140, and tally hashtags. |
String Predicate Filtering |
The Sieve |
Use `LENGTH()` and `LENGTH(REPLACE())` or `REGEXP_LIKE` to filter rows directly in the SQL engine. |
Draw a table. Draw a "filter" box. Rows that fail any condition (len > 140, counts > 3) get dropped. Remaining rows are the result. |
Linear scan of the database rows. |
Draw a single straight arrow through the table rows. $O(N)$. |
Temporary memory holding all row copies. |
In-engine pointer filtering. $O(1)$ auxiliary. |
| 3151 |
Special Array I |
Check every adjacent pair in the array using a loop. $O(N)$ time, but the logic is so simple brute force is effectively optimal. |
Linear scan line. |
Draw an array. Draw small arcs between i and i+1. Tally "even/odd" or "odd/even" pairs. |
Single-Pass Parity Check |
Step-by-Step Toggle |
Iterate from 0 rightarrow N-2. If `nums[i] % 2 == nums[i+1] % 2`, return False immediately. |
Draw the array. Use a finger to point at two numbers at once. If they both have the same "parity sticker" (E or O), cross the array out. |
Discrete linear progression. |
Draw a single straight line with N nodes. $O(N)$. |
None (direct iteration). |
Zero auxiliary space. $O(1)$. |
| 3152 |
Special Array II |
For every query [from, to], run a loop to check if all adjacent elements have different parity. $O(Q x N)$ |
A series of overlapping horizontal bars (queries) over a base array. |
Draw the array. Below it, draw 5 lines of varying lengths representing queries. For each line, manually scan the array elements above it. |
Prefix Sum (Parity Violations) |
Cumulative Penalty Track |
Precompute a `prefix_sum` array where `P[i]` is the count of parity violations (nums[j] % 2 == nums[j+1] % 2) up to index i. A query is "special" if `P[to] - P[from] == 0`. |
Write parity: E, O, E, E, O. Below it, write violations: 0, 0, 0, 1, 0. Below that, write the running sum: 0, 0, 0, 1, 1. Use the subtraction rule for queries. |
Two-stage process: $O(N)$ build + $O(Q)$ lookups. |
Draw a horizontal line $O(N)$, followed by Q discrete dots representing $O(1)$ subtraction checks. $O(N+Q)$. |
An array of all query results stored before processing. |
One integer array of size N for the prefix sums. $O(N)$. |
| 3153 |
Sum of Digit Differences of All Pairs |
Compare every pair of numbers (i, j) and count different digits at each position. $O(N^2 x \text{digits})$ |
A massive N x N matrix where each cell performs a digit-by-digit comparison. |
Draw N numbers. Draw a line connecting every number to every other number. On each line, tally the digit differences. |
Contribution Technique (Position-wise Counting) |
Vertical Digit Buckets |
For each digit position (e.g., units, tens), count how many times 0-9 appear. Contribution to total = sum (count x (N - count)) / 2. |
Write numbers in a column. Look only at the 1st digit. Count how many 5s, how many 3s. Multiply (count of 5) x (count of non-5s) and add to total. Repeat for all positions. |
Multi-pass fixed-column scan. |
Draw a grid of size N x 10. Mark D (digit length) horizontal passes. $O(N x D)$. |
A huge list of all compared pairs. |
A D x 10 frequency grid. $O(D x 10)$ approx $O(1)$ since digits are fixed. |
| 3154 |
Number of Ways to Reach the K-th Stair |
Exhaustive DFS/BFS starting from stair 1, trying "Jump" and "Down" at every step. $O(2^\text{steps})$ |
An exponentially branching tree. |
Draw "1". Draw two branches: "0" (down) and "2" (jump). From "2", draw "1" and "6". Continue until you hit K or exceed it. |
DP + Memoization / Combinatorics |
State-Space Compression |
State: `(current_stair, jump_power, can_go_down)`. Many paths lead to the same stair with the same power; memoize the results to avoid re-calculation. |
Draw a grid with columns as `jump_power` and rows as `current_stair`. Mark the paths that converge. Show that only small `jump_power` (up to 30) is needed. |
Search space traversal of memoized states. |
Draw a grid of size 30 x 2 (representing the jumps and the toggle). Total $O(\log K)$. |
The entire execution tree stored in a call stack. |
A Hash Map (Dictionary) storing the state tuples. $O(\log K)$. |
| 3155 |
Maximum Number of Upgradable Servers |
Incrementally upgrade laptops 1 by 1, subtracting costs in a while loop until funds run out. $O(\text{Answer})$. |
Iterative Wallet Drain |
Draw a wallet. Draw an arrow buying one upgrade, updating the wallet, and repeating until empty. |
Binary Search on Answer / Math |
The Feasibility Threshold |
Binary search the number of laptops `mid`. Calculate the total cost to upgrade `mid` laptops. If `cost <= budget`, try a higher `mid`. Otherwise, lower `mid`. |
Draw a number line of possible laptop counts. Drop a pin in the middle. Calculate the cost formula. If you can afford it, shade the left half green and drop a new pin on the right. |
Logarithmic Search $O(N \log(\text{Max})$) |
Draw a timeline cut in half repeatedly. Each check takes $O(N)$ to validate the cost. |
Iterative loop trackers. |
Pointers for Binary Search. $O(1)$ space. |
| 3156 |
Employee Task Duration and Concurrent Tasks |
Join task tables, run unoptimized subqueries to check overlaps per employee. |
Cross-Join Overlap Grid |
Draw every task checked against every other task manually. |
CTE + Interval Merging (Sweep Line SQL) |
The Flattened Timeline |
Unpivot start and end times into +1 and -1 events. Use window functions `SUM() OVER(ORDER BY time)` to find concurrent tasks, and calculate duration by merging overlapping intervals. |
Draw a timeline. Plot +1 when a task starts, -1 when it ends. The "height" of the line is the concurrent task count. The base of the line is the total duration. |
Sorting & Windowing $O(N \log N)$ |
Draw a sorting pass for times, followed by a linear window aggregation. |
Massive self-join memory. |
Internal sort/window buffer. $O(N)$ space. |
| 3157 |
Find the Level of Tree with Minimum Sum |
Recursive DFS that explores every path, storing all sums in a dictionary or deep list. $O(N)$ but higher overhead. |
Branching tree where every node carries its depth "weight" to the root. |
Draw a tree. Next to every node, write its depth. Then make a list of depths and sum all nodes for each depth manually. |
BFS (Level Order Traversal) |
Horizontal Slicing |
Use a queue to process the tree level by level. Sum all nodes in the queue before moving to the next level. Track the min sum. |
Draw a tree. Draw horizontal "cut" lines between levels. Sum the nodes on each "shelf" and write the total at the end of the line. |
Discrete level-by-level progression. |
Draw an $O(N)$ straight line split into H (height) segments. |
Call stack memory proportional to tree height H. |
A Queue holding at most the width of the tree W. $O(W)$. |
| 3158 |
Find the XOR Sum of All Numbers Appears Twice |
Nested loops: for each number, count occurrences by scanning the whole array, then XOR if count is 2. $O(N^2)$ |
A grid of N x N comparisons with a toggle bit at the end. |
Draw an array. Point to 1st number, scan the rest. If found again, write it down. Repeat for all. XOR the final list. |
Hash Set / Frequency Counting |
The Sieve / Filter |
One pass with a Set. If number exists in Set, it's the second appearance—XOR it into the result. If not, add to Set. |
Draw an array and an empty "Set" box. Move through the array; if number is in the box, circle it. XOR all circled numbers. |
Linear one-pass timeline. |
Draw a straight line 0 rightarrow N with a single constant check per node. $O(N)$. |
A list of every number's occurrence count. |
A single Hash Set or a frequency array (if numbers are small). $O(N)$ or $O(1)$. |
| 3159 |
Find Occurrences of an Element in an Array |
For every query, scan the entire array from start to find the k-th occurrence of x. $O(Q x N)$ |
Multiple overlapping scanners traversing the same array repeatedly. |
Draw the array. For each query "3rd occurrence of 5", count 1, 2, 3 fives starting from the beginning. |
Pre-processing (Index Collection) |
The Address Book |
One pass: store the indices of all occurrences of x in a new list. For queries, just do a direct index lookup in the new list. |
Draw the array. Below it, draw a small list called `pos`. Every time you see x, write its index in `pos`. Queries just point to `pos[k-1]`. |
$O(N)$ pre-processing + $O(Q)$ constant lookups. |
Draw one horizontal $O(N)$ line, followed by Q discrete dots. $O(N+Q)$. |
None (re-scanning). |
One array to store indices of x. $O(N)$. |
| 3160 |
Find the Number of Distinct Colors Among the Balls |
For every update, maintain the full ball-color array and scan it entirely to count distinct colors. $O(Q x N)$ |
A massive state-matrix recalculated from scratch for every move. |
Draw 10 balls. Paint ball 1 Red. Count distinct. Paint ball 2 Blue. Count distinct. Re-paint ball 1 Green. Count distinct again. |
Dual Hash Maps (Frequency Tracking) |
The Color Dashboard |
Map 1: `ball -> color`. Map 2: `color -> count`. On update: decrement count of old color (remove if 0), increment count of new. Distinct count = size of Map 2. |
Draw two boxes: `Balls` and `ColorCount`. When a ball changes color, cross out its old color in `Balls`, update its frequency in `ColorCount`. The size of `ColorCount` is the answer. |
Linear query processing. |
Draw Q discrete steps, each involving exactly two $O(1)$ map updates. $O(Q)$. |
Large array of N ball colors updated repeatedly. |
Two Hash Maps storing only active balls and non-zero color counts. $O(N)$. |
| 3161 |
Block Placement Queries |
For every query, scan all placed obstacles to find the largest gap between any two adjacent ones. $O(Q^2)$ |
A set of dynamic lines being cut into smaller pieces repeatedly. |
Draw a long line. Every time a block is added, draw a tick. For queries, manually measure every gap between ticks with a ruler. |
Segment Tree + Balanced BST (Sorted Set) |
The Gap Summary Tree |
Use a Sorted Set to find immediate neighbors of a new block. Use a Segment Tree to store and query the maximum gap in the range [0, x]. |
Draw a tree where each node stores the "max gap" of its children. When a leaf (gap) changes, update the path to the root. |
Logarithmic update and query path. |
Draw a Binary Tree. Circle one leaf and the path to the root. $O(Q \log (\text{min}(N, Q)$)). |
A simple list of obstacles that grows with every query. |
A Segment Tree (array of size 4N) and a TreeSet. $O(N + Q)$. |
| 3162 |
Find the Number of Good Pairs I |
Nested loop checking if nums1[i] is divisible by nums2[j] x k. $O(N x M)$ |
A grid where every element of A "talks" to every element of B. |
Draw two columns of numbers. Draw a line for every "good" connection and count them. |
Simple Iteration (Small Constraints) |
The Multiplier Matcher |
Since N, M <= 50, brute force is sufficient. Simply multiply nums2[j] by k and check divisibility. |
Write nums2 as x * k. For each nums1[i], check if any x * k divides it perfectly. |
Single N x M matrix scan. |
Draw a grid N x M and fill all cells. $O(N x M)$. |
None (direct scalar count). |
Zero auxiliary space. $O(1)$. |
| 3163 |
String Compression III |
Building strings by concatenation in a loop (depending on language, this can be $O(N^2)$). |
A growing snowball of string memory. |
Write the string. Write "1a", then "1a1b", then "1a1b1b"... Rewrite the whole thing every time. |
Two-Pointer / Greedy Counting |
The Compression Buffer |
Scan the string. Count consecutive identical characters. Once you hit 9 or the character changes, append count and char to a list. |
Draw a string. Draw a "counter" box. Move through characters; if same, increment box. If box == 9, reset and write to result. |
Single linear pass. |
Draw a straight line 0 rightarrow N. $O(N)$. |
Repeatedly creating new string objects. |
A string builder or character array. $O(N)$. |
| 3164 |
Find the Number of Good Pairs II |
$O(N x M)$ TLE. (Same logic as 3162 but with 10^5 constraints). |
A grid with 10^10 cells—physically impossible to scan. |
Try drawing 10^5 lines connecting 10^5 dots. You'll run out of ink. |
Frequency Map + Multiples / Divisors |
The Sieve of Multiples |
Count frequencies of nums2[j] x k. Iterate through multiples of each val in nums2_freq, or count all divisors of nums1[i] and check the map. |
Write nums2 values in a freq map. For each nums1[i], find all its divisors and see if they exist in the map. Sum the counts. |
Sub-linear divisor scan or Harmonic series sum. |
Draw $O(N √\text{max})$ operations or $O(V \log V)$ where V is max value. |
10^10 possible pair comparisons in memory. |
A frequency map of size 10^6. $O(\text{Max}_\text{Value})$. |
| 3165 |
Max Sum of Subsequence With Non-adjacent Elements |
For every update, run DP on the whole array. $O(Q x N)$. |
A wave of DP recalculations washing over the array Q times. |
Draw the array. Run "House Robber" DP logic. Update one number. Re-run "House Robber" from scratch. Repeat Q times. |
Segment Tree (DP State Merging) |
The 4-State Merge Node |
Each Segment Tree node stores 4 values: max sum including/excluding its left/right boundary. Merging two nodes is $O(1)$ based on these states. |
Draw a Segment Tree node. Inside it, draw 4 checkboxes: [0,0], [0,1], [1,0], [1,1] representing the boundary inclusion states. |
Logarithmic point updates. |
Draw a Binary Tree. Mark a path from leaf to root. $O(Q \log N)$. |
$O(Q x N)$ state space from repeated DP. |
A Segment Tree array storing 4 states per node. $O(N)$. |
| 3166 |
Calculate Parking Fees and Duration |
Using correlated subqueries for every aggregate column, forcing the DB to re-scan for every row. $O(N^2)$ |
Nested Loop Join Diagram |
Draw two tables. For every row in Table A, draw N arrows to Table B to calculate sums. Repeat N times. |
CTE / Window Functions |
Data Flow Pipeline |
Group by `car_id` to get totals. Use `RANK()` over `car_id` ordered by stay duration to find the "most visited lot." |
Draw three separate "buckets": Totals, Averages, and Rankings. Show them merging into a single final row. |
Linear Execution Plan |
Draw a single vertical line through the dataset representing one scan + one sort. $O(N \log N)$. |
Intermediate Cartesian product storage in TEMP DB. |
Sorted hash-aggregates in memory. $O(N)$. |
| 3167 |
Better Compression of String |
Decompress the string into its full raw form, then re-compress it from scratch. $O(N x \text{MaxFreq})$ |
Ballooning Buffer |
Write "a3". Draw a huge bubble with three 'a's. Repeat for every pair until the page is full of letters. |
Hash Table + Alphabetical Sorting |
The Sorter/Aggregator |
Parse the string: if it's a letter, read following digits. Add to `count[char]`. Sort keys and join. |
Draw an array of 26 slots. Read the string; as you find counts, add them into the corresponding slot. Write the non-zero slots in order. |
Linear Scan + Constant Sort |
Draw a straight line $O(N)$, followed by a tiny fixed-size sort of 26 items. $O(N)$. |
Gigantic character array holding the uncompressed string. |
Fixed array or Map of size 26. $O(1)$ auxiliary space. |
| 3168 |
Min Number of Chairs in a Waiting Room |
Generate all subsets of people and check if they can all sit simultaneously. $O(2^N)$ |
Exponential Subsets |
Draw a tree where every "E" branches into "has a chair" or "needs new chair" combinations. |
Greedy / Simulation (Peak Tracking) |
The Watermark Line |
Initialize `curr = 0, max_c = 0`. For 'E', `curr++`. For 'L', `curr--`. Update `max_c = max(max_c, curr)`. |
Draw a horizontal timeline. Draw a line going up for 'E' and down for 'L'. The highest point reached is your answer. |
1D Linear Sweep |
Draw a single straight arrow through the string. Label it $O(N)$. |
Recursive state-space stack. |
Two scalar integer variables. $O(1)$. |
| 3169 |
Count Days Without Meetings |
Create a boolean array of size `days` (10^9) and mark every meeting day as true. $O(\text{Days})$ - Memory TLE. |
Memory Overflow Grid |
Draw a grid of a billion squares. Try to shade each square covered by a meeting. Hand will cramp before finishing. |
Interval Merging |
Overlapping Shingles |
Sort meetings by start time. Merge overlapping intervals. Total free days = Total days - Total covered days. |
Draw a ruler from 1 to 10. Draw colored bars for meeting intervals. Merge overlapping bars. Count the white space left. |
Sort Funnel + Linear Pass |
Draw an $O(M \log M)$ sorting tree (where M is number of meetings), followed by a linear merge scan. |
A massive bitset/boolean array of size 10^9. |
The sorted meetings array or a few interval variables. $O(M)$ or $O(1)$. |
| 3170 |
Lexicographically Minimum String After Removing Stars |
Every time you see a star, scan the entire string backwards to find the smallest character and delete it. $O(N^2)$. |
Backtracking Eraser |
Draw the string. Hit a star. Draw an arrow scanning all the way left to find the best letter, erase it, and shift the array. |
Priority Queue / Array of Stacks |
The 26-Bin Tie-Breaker |
Maintain 26 stacks (one for each letter a-z) storing their indices. When hitting a `*`, iterate from 'a' to 'z'. Pop from the first non-empty stack (smallest letter). The stack ensures you pop the *largest index* (closest to the star) for tie-breaking. |
Draw 26 vertical tubes. When reading 'c' at index 4, drop '4' into tube 'c'. Read '*'? Look at tube 'a', 'b', then 'c'. Pull the top number out of the first non-empty tube and cross out that index in your string. |
Linear Scan + Constant Lookup $O(N)$ |
Draw a timeline. At each step, inserting takes $O(1)$. Popping takes max 26 steps (O(1)). |
Full string copies. |
26 arrays/stacks and a boolean "deleted" array. $O(N)$ space. |
| 3171 |
Find Subarray With Bitwise OR Closest to K |
Generate all N^2 subarrays, calculate Bitwise AND from scratch for each, compare to K. $O(N^2)$. |
Overlapping AND Brackets |
Draw the array. Draw brackets covering every possible subarray, recalculating the AND at every step. |
Shrinking Bitwise Set |
The 32-State Sieve |
Bitwise AND only strictly decreases or stays the same. At index `i`, the number of unique AND results ending at `i` is at most 32. Maintain a Set of current AND results. Update it with `nums[i]`, check distance to K, and carry the Set to `i+1`. |
Draw the array. Below current number, draw a small box of max 32 numbers. Draw an arrow pulling the *next* number in, applying `&` to everything in the box, throwing out duplicates, and checking the K distance. |
Linear Scan * 32 $O(N \log(\text{Max})$) |
Draw a single line. At each node, a tiny fixed-size loop of max 32 operations occurs. |
Subarray storage. |
Two sets of max size 32. $O(1)$ space. |
| 3172 |
Second Day Verification |
Subqueries using `MIN(date)` and `NOT IN` to find the second date manually. |
Exclusion Funnels |
Draw a list. Find the first date. Put it in a box. Scan the list again for the lowest date NOT in the box. |
Window Function (DENSE_RANK) |
The Ordered Podium |
Use `DENSE_RANK() OVER(PARTITION BY user_id ORDER BY date ASC)`. Filter for `rank = 2`. |
Draw buckets for users. Sort dates chronologically. Hand out medals: Gold (1), Silver (2). Keep only the Silver rows. |
Partitioned Sort $O(N \log N)$ |
Pipeline: Partition rightarrow Sort rightarrow Rank rightarrow Filter. |
Temp tables for exclusions. |
DB Window buffer. $O(N)$ space. |
| 3173 |
Bitwise OR of Adjacent Elements |
Creating new temporary objects for every OR pair calculation. |
Paired Step Graph |
Draw the array. Draw brackets over every two elements. Write the result in a new array below. |
Single-Pass Array Mapping |
Adjacent Zipper |
Iterate 0 rightarrow N-2. Compute `nums[i] | nums[i+1]` and store in index i of the result array. |
Draw the array. Draw a "zipper" moving across. At each teeth-close, write the OR result. |
Linear Timeline |
Draw a straight line with N-1 nodes. $O(N)$. |
Array copies for every intermediate result. |
A single output array of size N-1. $O(N)$. |
| 3174 |
Clear Digits |
Find a digit, scan left for a char, delete both, and shift the string. $O(N^2)$. |
The Eraser Shift |
Write the string. Find a digit. Use an eraser to rub it and the char to its left out. Close the gap. Repeat. |
Stack (LIFO) |
The Character Sieve |
Iterate through the string. If char, `push`. If digit, `pop`. The stack content at the end is the result. |
Draw a vertical tube. Drop letters in. When a digit appears, "blow" the top letter out of the tube. |
Single-Pass Buffer |
Draw a straight line 0 rightarrow N. $O(N)$. |
Recursive string manipulation stack. |
A single character array or stack of size N. $O(N)$. |
| 3175 |
Find The First Player to win K Games in a Row |
Physically simulate the deque: move losers to the back, track wins. $O(N \cdot K)$. |
Circular Queue Carousel |
Draw players in a circle. Move the loser to the back every "round" until someone hits K wins. |
Greedy / One-Pass Simulation |
King of the Hill |
The current "winner" stays at the front. Iterate once. If a challenger is stronger, they become the new winner (reset count). Stop at K or end of array. |
Draw players. Place a "Crown" on the first player. Move to next player. If next is stronger, move the crown. Keep a tally of crown "defenses." |
Linear Pass stopping early |
Draw a line 0 rightarrow N. No backtracking. $O(N)$. |
A full Deque data structure. |
A few integer variables: `current_winner`, `consecutive_wins`. $O(1)$. |
| 3176 |
Max Length of a Good Subsequence I |
Recursion checking every subsequence for the "at most k different neighbors" rule. $O(2^N)$. |
Exponential Decision Tree |
Draw a root. Branch for "include" or "exclude" for every element. Tally the cost k at each node. |
Dynamic Programming (O(N^2 * k)) |
2D State Grid |
`dp[i][j]` is max length ending at index i with j changes. For each i, look back at all p < i. If same value, no cost. Else, use j-1 changes. |
Draw a grid with N rows and k columns. For each cell, draw arrows pointing back to all previous valid indices in the grid. |
Nested Loop Matrix Fill |
Draw a square (N x N) and a layer for k. Shade the area being processed. $O(N^2 k)$. |
Deep recursion stack for 2^N paths. |
A 2D array of size N x k. $O(\text{Nk})$. |
| 3177 |
Max Length of a Good Subsequence II |
Using the $O(N^2 k)$ DP from 3176 (will TLE due to N=5000). |
Dense Connection Web |
Draw N dots. From each dot, draw N lines backward. It becomes a black ink blob quickly. |
DP + Global Max Tracking (O(Nk)) |
Leaderboard Optimization |
Instead of scanning all p < i, maintain a `max_for_k[j]` and `max_for_val[val][j]`. The current value is just `max(same_val, diff_val) + 1`. |
Draw the DP table. Next to it, draw a "Top 1" leaderboard for each change-count j. Update the leaderboard at every step. |
Single pass with auxiliary lookups. |
Draw a line 0 rightarrow N. At each step, draw a small "Lookup" box for constant time check. $O(\text{Nk})$. |
$O(N^2 k)$ state storage if not optimized. |
Two maps/arrays: `best_per_k` and `best_per_val_k`. $O(\text{Nk})$. |
| 3178 |
Find the Child Who Has the Ball After K Seconds |
Simulate the ball moving 1 step at a time, reversing direction at the ends. $O(K)$. |
Linear Oscillation Graph |
Draw n dots. Draw a zig-zag line moving from dot 1 to n, then back to 1. Tally K segments. |
Math (Modulo Arithmetic) |
Reflecting Coordinate Plane |
The ball completes a full round-trip in 2(n-1) steps. Find `K % (2n-2)`. If result < n, it's moving forward; else, backward. |
Draw a number line 0 to n-1. Draw a circle representing the "virtual" path of length 2n-2. Mark the K-th point on the circle. |
Constant Time Calculation |
Draw a single dot. Label it $O(1)$. |
No significant memory used. |
Zero auxiliary space. $O(1)$. |
| 3179 |
Find the N-th Value After K Seconds |
Simulate the prefix sum array update K times. $O(N \cdot K)$. |
Layered Prefix Sum Waves |
Draw an array of 1s. Below it, write the prefix sums. Repeat K times, stacking the arrays like a cake. |
Combinatorics (Stars and Bars) |
Pascal's Triangle Slice |
The value at index n after k seconds corresponds to the binomial coefficient (n+k-1 Choose k) or (n+k-1 Choose n-1). |
Draw Pascal's Triangle. Circle the value that corresponds to your N and K coordinates. |
Logarithmic Modular Inverse Math |
Draw a single formula box. Label it $O(N)$ or $O(1)$ with precomputation. |
Storing K copies of the N-length array. |
Factorial and Inverse Factorial arrays. $O(N)$. |
| 3180 |
Maximum Total Reward Using Operations I |
Backtracking to try every combination of rewards that satisfy the x > reward condition. $O(2^N)$. |
Constrained Branching Tree |
Draw rewards. Branch if x > sum. Stop branch if not. Tally max sum at leaves. |
DP / Bitset Optimization |
Reachability Bitmask |
Sort rewards. Use a bitset where `bit[i]` means reward i is possible. For each `x`, `bit |= (bit & mask_less_than_x) << x`. |
Draw a long binary string (0s and 1s). For each reward, "Shift and OR" the string with itself. |
Linear Scan with Bitwise Parallelism |
Draw a timeline 0 rightarrow N. Each node has a bitwise OR operation of length MaxReward. $O(N \\text{cdot MaxReward} / 64)$. |
Recursive stack for combinations. |
A Bitset of size 2 x max(reward). $O(\text{MaxReward})$. |
| 3181 |
Maximum Total Reward Using Operations II |
Recursive backtracking trying every subset of rewards where current reward is less than the candidate. $O(2^N)$ |
Branching Decision Tree |
Draw root '0'. Branch for every valid reward choice. Show exponential growth as paths split. |
DP + Bitset (Bit-Level Parallelism) |
Sliding Binary Bitmask |
Sort rewards. Maintain a `std::bitset` where `b[i] = 1` if reward `i` is reachable. For each `v`, update `b |= (b << (50000-v) >> (50000-v)) << v`. |
Draw a long 1D tape of 0s and 1s. For reward `v`, copy the tape, shift it by `v` positions, and OR it back into the original. |
Linear Scan with Bitwise Chunking |
Draw an $O(N)$ timeline. Above each node, draw a small block representing 64-bit parallel operations. $O(N \cdot M / 64)$. |
Exhaustive recursion stack for all subsets. |
A single fixed-size bitset of 50,000 bits. $O(M)$ space. |
| 3182 |
Find Top Scoring Students |
Correlated subqueries or large Cartesian Joins checking every student against every course. $O(S x C)$ |
Dense Adjacency Web |
Draw a column of Students and a column of Courses. Connect everyone. Filter by major manually. |
JOIN + Aggregation (HAVING Count Match) |
Relational Sieve / Bucket Comparison |
Join `Students` with `Courses` on major. Filter `Enrollments` for grade 'A'. Count matching courses per student; if count equals total courses in major, student is "Top." |
Draw 3 tables. Use arrows to filter 'A' grades. Group results by Student ID. Compare the "Count of As" with the "Count of Required Courses." |
Relational Algebra DAG |
Draw a data pipeline: Join → Filter → Group → Aggregate Check. $O(N \log N)$ (Sort/Join). |
Massive intermediate join results in temporary storage. |
Hash-aggregates in-memory for counts. $O(S)$. |
| 3183 |
The Number of Ways to Make the Sum |
Recursive backtracking to find every coin combination for values [1, 2, 4, 6] with constraints. $O(2^N)$ |
Exponential Path Tree |
Draw root 'n'. Branch for every coin subtraction. Cross out branches that use more than two 4s. |
Unbounded Knapsack + Case Addition |
Layered Coin Build-up |
Run $O(N)$ Knapsack for coins {1, 2, 6}. For the result, consider 0, 1, or 2 coins of value 4. Total = f[n] + f[n-4] + f[n-8]. |
Draw a 1D DP table. Fill it using 1, then 2, then 6. At the very end, draw 3 "jump" arrows representing the inclusion of coin 4. |
Multi-pass 1D DP Fill |
Draw 3 parallel horizontal lines (one per coin type). Label it $O(N)$. |
Deep recursive call stack with millions of states. |
A 1D array of size N. $O(N)$. |
| 3184 |
Count Pairs That Form a Complete Day I |
Nested loop checking `(hours[i] + hours[j]) % 24 == 0`. $O(N^2)$ |
N x N Comparison Matrix |
Draw a square grid. Fill every cell (i, j) with the sum check result. $O(N^2)$. |
Frequency Array / Hashing (Modulo 24) |
24-Slot Distribution Table |
For each hour, calculate `rem = x % 24`. Look for complement `(24 - rem) % 24` in a count array. Add to answer, then increment `count[rem]`. |
Draw 24 boxes (0-23). Read hours; for each, look in the "Complement" box. Add the number inside to your total. Put a tick in the current box. |
Linear Scan |
Draw a single straight line of length N. Each node does $O(1)$ box lookup. $O(N)$. |
List of all valid pair indices. |
Fixed array of size 24. $O(1)$ space. |
| 3185 |
Count Pairs That Form a Complete Day II |
Same as 3184. $O(N^2)$ (TLE due to N=5 x 10^5). |
Infinite Comparison Web |
Draw 500,000 dots. Try connecting every pair. The page will turn solid black. |
Frequency Array / Hashing (Long Int) |
Scaled Bucket Counter |
Identical logic to 3184, but ensure the answer is a `long long` to prevent overflow. The fixed 24-bucket logic remains optimal. |
Exactly like 3184: Draw 24 buckets. The key is the high speed of processing large N through tiny constant buckets. |
Linear Scan (Scalable) |
Draw a single horizontal arrow through a long array of N elements. $O(N)$. |
$O(N^2)$ matrix storage (Impossible). |
Fixed array of size 24. $O(1)$ space. |
| 3186 |
Maximum Total Damage With Spell Casts |
Generate all subsets of spells and check if any two spells have damage d1, d2 such that |d1 - d2| <= 2. $O(2^N)$. |
Exponential Decision Tree |
Draw a tree starting with no spells. For each spell, branch into "take" and "don't take," pruning branches that violate the distance-2 rule. |
DP + Freq Map + Two Pointers |
House Robber with Variable Gaps |
Count spell frequencies. Sort unique damage values. `dp[i]` is max damage using first i unique values. Look back to the largest index j where val[i] - val[j] > 2 using two pointers. |
Draw unique spell damages on a number line. At each point, draw an arrow to the furthest valid "previous" spell that can be combined. Tally the running max. |
Linear Scan with Two-Pointer Look-back |
Draw an $O(N)$ timeline. Above each node, draw an arrow jumping back a small variable distance. $O(N \log N)$ (due to sort). |
Recursive call stack for all valid combinations. |
Frequency map and a 1D DP array of size N. $O(N)$. |
| 3187 |
Peaks in Array |
For every update, change the element. For every query, scan the range [L, R] and count peaks. $O(Q x N)$. |
Sequential Range Scan |
Draw an array. For each query, use a magnifying glass to scan from L to R, counting local maxima. Repeat for every query. |
Segment Tree / Fenwick Tree |
Dynamic Cumulative Sums |
Define a "Peak" as a 1 or 0. Use a Segment Tree to store these 1s. On update (i), re-evaluate indices i-1, i, i+1 and update the tree nodes. Query range sum in $O(\log N)$. |
Draw a Binary Tree where leaf nodes are 1 (peak) or 0. Circle the nodes that get updated when one leaf changes. Draw the "merge" logic at each parent. |
Logarithmic Update and Query Paths |
Draw a Binary Tree. Shade one path from bottom to top for update; shade a few subtrees for query. $O(Q \log N)$. |
Multiple full copies of the array for every query's state. |
A tree array of size 4N or N (for Fenwick). $O(N)$. |
| 3188 |
Find Top Scoring Students II (SQL) |
Nested subqueries for GPA, credits, and grade counts. $O(N^2)$ execution. |
Nested Table Loop Join |
Draw Students, Enrollments, and Courses. Draw arrows matching all three, calculating counts row-by-row manually. |
Window Functions + CTE Aggregation |
Data Pipeline Filtering |
Calculate GPA and total credits in one CTE. Count 'A' grades in another. Filter for students who meet all criteria (GPA >= 3.75, credits >= 150, etc.). |
Draw a funnel. Top: All Students. Middle: Those with GPA >= 3.75. Bottom: Those with enough 'A's. Output is the final sieve. |
Relational Execution Plan |
Draw a linear flow: Join → Aggregate → Multiple Filter Nodes. $O(N \log N)$. |
Memory-intensive temporary tables for sorting and joining. |
Hash-aggregates in memory. $O(N)$. |
| 3189 |
Minimum Moves to Get a Peaceful Board |
Try every possible permutation of row/column assignments for the rooks. $O(N!)$. |
Factorial Permutation Grid |
Draw an N x N board. List all ways to place N non-attacking rooks. Tally distance for each. |
Greedy / Independent Sorting |
Orthogonal Coordinate Matching |
Rows and columns are independent. Sort rooks by current row, and match them to target rows 0 dots N-1. Repeat for columns. Total moves = sum |curr - target|. |
Draw two columns: Current Rows and Target Rows. Sort both. Draw horizontal lines connecting them in order. Tally the absolute differences. |
Linear Scan after Sorting |
Draw two $O(N \log N)$ sorting trees followed by a single $O(N)$ linear pass. |
A massive list of all valid rook positions. |
Two arrays of size N for sorting coordinates. $O(N)$. |
| 3190 |
Find Minimum Operations to Make All Elements Divisible by Three |
Check all possible +1/-1 combinations for every element to find divisibility. $O(2^N)$. |
Binary Decision Tree |
Draw an array. For each number, branch "add 1" or "subtract 1". Count which path reaches a 3-multiple faster. |
Modulo Simulation |
Single-Pass Remainder Check |
For each element, if x mod 3
eq 0, it takes exactly 1 operation (either +1 or -1) to reach a multiple of 3. |
Draw the array. Below each number, write its remainder when divided by 3. If it's 1 or 2, write "1 operation." Sum the counts. |
Discrete Linear Scan |
Draw a straight line 0 rightarrow N. $O(N)$. |
None (direct scalar tally). |
Zero auxiliary space. $O(1)$. |
| 3191 |
Minimum Operations to Make Binary Array Elements Equal to One I |
Recursively try flipping every possible 3-element window. $O(2^N)$. |
Exponential Decision Tree |
Draw a root. Branch "flip" or "no flip" for index 0, then 1... Tally 1s at leaves. |
Greedy / Fixed Window Flip |
The Window Sliding Light Switch |
Scan 0 to N-3. If `nums[i] == 0`, you *must* flip [i, i+1, i+2]. It's the only way to fix i. |
Draw bits. Place a 3-cell bracket. If left-most is 0, flip all 3. Move bracket 1 step right. |
Linear Sequential Timeline |
Draw a straight line 0 to N. Each node is $O(3)$ = $O(1)$. Total $O(N)$. |
Deep recursive stack of 2^N states. |
In-place modification or single integer `ans`. $O(1)$. |
| 3192 |
Minimum Operations to Make Binary Array Elements Equal to One II |
For every 0 found, flip every single element to the right of it. $O(N^2)$. |
Cascading Update Wave |
Draw bits. At every 0, draw an arrow to the right and rewrite all following bits. $O(N^2)$. |
Greedy / State-Flip Parity |
The Toggle Relay |
Track `flips`. Current bit value is `(bit + flips) % 2`. If it's 0, increment `flips`. |
Draw bits. Draw a box `Flips`. If `bit` (after applying `Flips`) is 0, add 1 to box. Do NOT rewrite array. |
Single-Pass Linear Scan |
Draw a straight line 0 to N. $O(N)$. |
Repeatedly creating new array objects for flips. |
One scalar integer `flips`. $O(1)$. |
| 3193 |
Find the Number of Inversions in Permutation |
Generate all N! permutations and count inversions for each. $O(N \cdot N!)$. |
Factorial Path Explosion |
Draw all permutations of [0, 1, 2]. Count pairs where i < j but P[i] > P[j]. |
Dynamic Programming (Prefix Sum Opt) |
Layered Staircase Accumulation |
`dp[i][j]` is ways to have `j` inversions using first `i` numbers. `dp[i][j] = sum(dp[i-1][j-k])` for 0 <= k < i. |
Draw an N x MaxInv grid. For each cell, draw a bracket covering a range of the previous row. Use prefix sums for $O(1)$ range sum. |
$O(N x \text{MaxInv})$ Matrix Scan |
Draw a grid and shade it row by row. Total $O(N x \text{MaxInv})$. |
Storing millions of permutation strings. |
2D DP table (can be space-optimized to 1D). $O(\text{MaxInv})$. |
| 3194 |
Minimum Average of Smallest and Largest Elements |
Randomly pick pairs, calculate averages, and try every combination to find the minimum. $O(N!)$. |
Stochastic Matching Web |
Draw dots. Connect them in every possible pairing. Tally the averages for each. |
Sorting + Two Pointers |
Inward Pincer Movement |
Sort array. Pair `nums[left]` with `nums[right]`. Calculate average. Increment `left`, decrement `right`. |
Draw sorted bars. Put fingers on the tallest and shortest. Move fingers inward, recording averages. |
Sort Funnel + Linear Pass |
Draw $O(N \log N)$ sort tree, then a line with N/2 steps. $O(N \log N)$. |
Exhaustive list of all pairing combinations. |
A list of N/2 averages. $O(N)$. |
| 3195 |
Find the Minimum Area to Cover All 1s I |
Generate every possible rectangular subgrid and check if it contains all 1s. $O((M x N)$^2). |
Quad-Loop Bounding Box Search |
Draw a grid with 1s. Try drawing every possible box. Check if any 1s are left outside. |
Min-Max Coordinate Tracking |
The Elastic Bounding Box |
Find global minRow, maxRow, minCol, maxCol. Area = (maxRow - minRow + 1) x (maxCol - minCol + 1). |
Draw a grid. Circle the 1s. Draw a tight box touching the outermost 1s on all 4 sides. Measure height and width. |
Single Matrix Scan |
Draw a snake-path through the grid. $O(M x N)$. |
List of all possible rectangular objects. |
Four integer variables for boundaries. $O(1)$. |
| 3196 |
Maximize Total Cost of Alternating Subarrays |
Recursive backtracking to explore all possible partition points for the alternating subarrays. $O(2^N)$. |
Exponential Branching Tree |
Draw root. For each index, branch into "start new subarray" or "continue current." Tally alternating sums. |
1D Dynamic Programming (2 States) |
State Transition Wave |
`dp[i][0]` (elem at i is positive) and `dp[i][1]` (elem at i is negative). Transition based on the previous index state. |
Draw a row of numbers. Below each, draw two boxes. Draw arrows showing which box values flow into the next based on max. |
Linear Matrix Fill |
Draw an N x 2 grid. Shade it column by column. $O(N)$. |
Deep recursive stack of 2^N states. |
A 1D DP table or two scalar variables. $O(1)$ aux. |
| 3197 |
Find the Minimum Area to Cover All 1s II |
Try every combination of 3 non-overlapping rectangles across all possible grid coordinates. $O((M x N)$^6). |
Chaotic Coordinate Explosion |
Draw a grid. Try sketching three random boxes. Re-draw if they overlap. Tally the area. $O(N^6)$. |
Grid Partitioning + Bounding Box |
The Butcher's Slice |
Divide the grid into 3 regions using horizontal and vertical "cuts." There are 6 fixed layouts (e.g., all 3 horizontal, T-shaped, etc.). Find min area for each. |
Draw 6 small grids. In each, draw lines to cut them into 3 non-overlapping zones. For each zone, find the min/max 1s coordinates. |
Nested Multi-pass Scans |
Draw a snake path through the grid $O(M x N)$ to find bounding boxes for each of the 6 layout partitions. |
Gigantic list of all possible rectangle triples. |
Variables for min/max coordinates in each sub-region. $O(1)$ aux. |
| 3198 |
Find Cities in Each State (SQL) |
Iterate through states, then for each state, run a separate query to find and join all city names. |
Nested Loop Query Pattern |
Draw a State table. For each row, draw N lines to the City table. Manually string them together. |
String Aggregation (GROUP_CONCAT) |
The Data Sieve |
`GROUP BY state` and use `GROUP_CONCAT(city ORDER BY city SEPARATOR ', ')` to aggregate names into a single cell. |
Draw a table with States. Next to each state, draw a "collector" bucket where city names are dropped and sorted. |
Linear Aggregate Pipeline |
Draw a single pass through the sorted city data. $O(N \log N)$ (due to sort). |
Temporary buffers for every string concatenation. |
In-memory hash-aggregates or sorted string buffers. $O(N)$. |
| 3199 |
Count Triplets with Even XOR Sum |
Triple nested loops to iterate through all combinations of three arrays and calculate XOR. $O(N^3)$. |
3D Voxel Grid of Comparisons |
Draw 3 arrays. Draw lines connecting every i, j, k. Tally if val1 oplus val2 oplus val3 is even. |
Bitwise Parity Counting |
Even/Odd Probability Buckets |
Count even and odd numbers in each array. Triplets with even XOR sum must have 0 or 2 odd numbers. Calculate using combinations of these counts. |
Draw three boxes (A, B, C). In each, write the count of `even` and `odd`. Multiply the combinations that yield an even sum. |
Discrete Scalar Math |
Draw a small formula box. Label it $O(N)$. |
Massive list of all triplet XOR results. |
Six integer variables (2 per array). $O(1)$. |
| 3200 |
Maximum Height of a Triangle |
Recursively try building the triangle using every possible permutation of red and blue balls. $O(2^N)$. |
Branching Tower Tree |
Draw a ball tower. Branch left to use Red, right to use Blue. Stop when count exceeds availability. |
Greedy Simulation (Two Cases) |
The Alternating Layer Stack |
Try two starting scenarios: 1) Red at top, 2) Blue at top. In each, subtract the required balls for each row (1, 2, 3 dots) alternating colors. |
Draw two triangles. Start Triangle A with 1 Red. Start Triangle B with 1 Blue. Keep adding rows until you run out of balls. Compare heights. |
Linear Loop with Early Exit |
Draw a short vertical line representing the height. $O(√N)$. |
Deep recursion stack for ball placements. |
Four integer variables (counts and height). $O(1)$. |
| 3201 |
Find the Maximum Length of Valid Subsequence I |
Generate all subsequences (O(2^N)), filter to check if parity of elements strictly alternates. |
Binary Recursion Tree |
Draw a root node branching into two (Include/Exclude). Continue branching N times. Count the bottom leaves to prove $O(2^N)$ time. |
State Machine / 1D Dynamic Programming |
State Transition Diagram |
Set up a 2-column table tracking 'max alternating ending in Even' and 'max alternating ending in Odd'. Update counts sequentially. |
Draw two variables (Even, Odd). Cross them out and update their scalar values as your finger moves left-to-right across the array. |
Linear Timeline Pipeline |
Draw a single straight horizontal line mapping N elements. Add a small box at each node stating "O(1) update", proving $O(N)$ total time. |
Deep Call Stack Diagram (depth N). |
Two independent scalar boxes (O(1) space). |
| 3202 |
Find the Maximum Length of Valid Subsequence II |
Backtracking to build subsets, checking every pair's modulo sum (a+b)%k == val. |
N-ary Branching Tree |
Draw the array. Pick an element, then draw K possible branches based on the target modulo, demonstrating factorial/exponential explosion. |
2D Dynamic Programming (Tracking mod pairs) |
K x K Grid Mapping |
Draw a grid of size K by K. For each number, update cell (prev%k, curr%k) using the value from (curr%k, prev%k) + 1. |
Draw a matrix. Point a directional arrow from the incoming element to specific row/col index intersections and update the max lengths. |
Matrix Fill Animation |
Draw an outer loop representing N, pointing to an inner loop block of size K. Write $O(N \cdot K)$ next to the nested block. |
Massive memory tree showing array subset duplications. |
A K x K spatial matrix diagram proving $O(K^2)$ fixed space. |
| 3203 |
Find Minimum Diameter After Merging Two Trees |
Run BFS/DFS from every node in Tree 1 and Tree 2, connect all pairs across trees, recalculate diameter each time. |
Complete Bipartite Graph |
Draw two clusters of nodes. Draw a line connecting every single node in cluster A to every node in cluster B. Label as $O(N^2 \cdot M^2)$. |
Graph Tree Diameter (2-Pass BFS/DFS) |
Longest Path / Core Midpoint Highlighting |
Draw both trees. Trace the longest edge-to-edge path in each. Pick the exact middle nodes. Draw one single connecting line. |
Sketch Tree 1, highlight its diameter D1. Sketch Tree 2, highlight D2. Mark their centers. Write out max(D1, D2, ceil(D1/2) + ceil(D2/2) + 1). |
Sequential Block Diagram |
Draw 2 sequential, non-overlapping blocks for Tree 1 passes, and 2 for Tree 2. Sum them linearly: $O(N)$ + $O(M)$ = $O(N + M)$. |
Heavy Adjacency Matrix representing all cross-connections. |
Two compact Adjacency Lists and a single Queue structure. |
| 3204 |
Bitwise User Permissions Analysis (SQL) |
Cartesian product / Multiple subqueries checking bit flags iteratively. |
Relational Algebra Tree |
Draw massive tables duplicating rows for every bitwise check. Show exponential row growth before filtering. |
Bitwise AND (&) Operator in SELECT/WHERE |
Bitmask Alignment Grid |
Write the integer permissions in binary form stacked vertically. Draw a vertical line performing logical AND to filter matching permissions. |
Draw a column of integers. Next to it, draw their binary equivalents. Circle the specific bit index being tested. |
Single-Pass Table Scan |
Draw one large rectangular block (Table). Draw a single horizontal arrow passing through it, signifying an $O(N)$ sequential read. |
Temporary memory tables stacking up. |
Single execution memory buffer (O(1) extra space). |
| 3205 |
Maximum Array Hopping Score I |
DFS/Backtracking to try all possible jump combinations from start to end. |
Exponential Decision Tree |
Draw a tree starting at index 0. Branch out to indices 1, 2, ..., N. From each, branch out again. Label leaves to show $O(2^N)$ paths. |
1D Dynamic Programming / Greedy |
Jump Progression Timeline |
Draw the array. Put a token at index 0. Look ahead to find the max reachable score, draw an arc landing there. Repeat. |
Draw an array. Point an arrow from a cell to a future cell and write the computed `score + max_future_score` above it. |
Linear Scan / 1D DP Array |
Draw an array of length N. Draw a finger sweeping strictly left-to-right once, assigning $O(1)$ ops per step. $O(N)$ total. |
Deep call stack (O(N) depth) storing thousands of recursive frames. |
A single DP array of size N (O(N) space) or variable tracking (O(1)). |
| 3206 |
Alternating Groups I |
Iterate through every index and manually check if the 3-element window strictly alternates. |
Fixed-Size Moving Box |
Draw the array. Draw a box around elements 0,1,2. Check. Draw a new box around 1,2,3. Check. |
Modulo Sliding Window (Size 3) |
Circular Array Mapping |
Draw the array in a circle. Place a transparent 3-slot window over it. Rotate the window one slot clockwise per step. |
Draw the array elements in a ring. Draw lines connecting 3 adjacent nodes. Move your pen one node clockwise and repeat. |
Overlapping Subproblem Line |
Draw a straight array. Show the window moving linearly $O(N)$, with modulo math wrapping the pointer at the end. |
Multiple copies of small arrays in memory. |
Three scalar variables representing the window (O(1) space). |
| 3207 |
Maximum Points After Enemy Battles |
Recursive state exploration: simulate choosing to attack vs. marking every enemy in all combinations. |
State-Space Explosion Graph |
Draw nodes containing `(current_energy, points, unmarked_enemies)`. Branch every node by the two choices. Show exponential bloom. |
Greedy + Sorting (Two-Pointer logic) |
Min-Max Balance Scale |
Sort the array. Always subtract energy from the absolute minimum element (left) to gain points. Harvest energy from the max element (right). |
Draw a sorted array. Put a green dot on the 0th index (attack) and a red dot on the last index (harvest). Move the red dot leftwards as you harvest. |
Sorting Bottleneck Pipeline |
Draw a block labeled "Sort" $O(N \log N)$. Draw a second block labeled "Linear Scan" $O(N)$. Circle the sort block as the dominating factor. |
Heavy recursive stack and duplicate array states. |
In-place sorted array (O(1) or $O(\log N)$ space depending on sort). |
| 3208 |
Alternating Groups II |
Check every window of size K independently. $O(N \cdot K)$ time. |
Nested Loop Grid |
Draw N rows. In each row, draw K boxes. Shade the boxes to show the inner loop repeating work that the previous row already did. |
Variable Sliding Window / State Counting |
Accordion Sliding Window |
Start at index 0. Move right pointer. If colors alternate, expand window. If not, snap left pointer to right pointer. When length >= K, increment count. |
Draw array with virtual appended elements to simulate the circle. Use two fingers (L, R). Widen fingers if alternating. If not, jump L to R. |
Amortized Pointer Movement |
Draw the array. Draw arrows showing the Left and Right pointers *only* moving rightwards. Conclude that 2N steps = $O(N)$ time. |
Redundant substrings held in memory. |
Two pointers (L, R) and a counter (O(1) space). |
| 3209 |
Number of Subarrays With AND Value of K |
Nested loops generating every subarray, calculating Bitwise AND. $O(N^2)$. |
Expanding Triangle Grid |
Draw an N x N half-matrix. Shade cells representing subarray bounds (i, j). Point out that calculating each cell takes redundant time. |
LogTrick / Hash Map (Monotonic Bitwise AND) |
Shrinking Bitmask Set |
At each step, maintain a map of valid AND results ending at the current index. Bitwise AND only strictly decreases, meaning at most 32 unique values exist per index. |
Draw an array. Under index `i`, list a small set of numbers (max 32). Draw arrows to index `i+1`, performing AND with the new element and merging duplicates. |
Linear Scan with Bounded Inner Loop |
Draw a long horizontal line (N elements). Attach a small, fixed-size box (height 32) at each node. Write $O(32 \cdot N)$ -> $O(N)$. |
No extra space, just nested pointers (O(1)). |
Two Hash Maps of max size 32 ping-ponging data (O(1) effective space). |
| 3210 |
Find the Encrypted String |
Loop through string, manually calculate (i+k)%n for each character and build a new string. $O(N)$. |
Linear Character Map |
Draw the string characters in boxes. Draw an arrow from index i to index (i+k) wrapping around. Do this for all N boxes. |
String Slicing / Cyclic Shift |
Circular Array Rotation |
Draw the string in a circle. Rotate the entire circle counter-clockwise by `k % n` steps simultaneously. |
Write the string twice (e.g., "abcabc"). Put a window of size N starting at index `k % n`. Read the characters inside the window. |
String Slicing Block |
Draw one block representing string `s`. Draw a cut at index `k`. Swap the left and right chunks. Label it $O(N)$ time for copying. |
New string built char by char (O(N) space). |
Two sliced string allocations combining into one (O(N) space). |
| 3211 |
Generate Binary Strings Without Adjacent Zeros |
Generate all 2^N binary strings, then linearly scan each to filter out "00". $O(N \cdot 2^N)$. |
Full Binary Tree + Filter Layer |
Draw a complete binary tree of depth N. Cross out all entire branches that contain "00". Show the massive wasted work. |
Constrained Backtracking / DFS |
Pruned Decision Tree |
Start at empty string. If last char is '1', branch to '0' and '1'. If last char is '0', ONLY branch to '1'. |
Draw the root. Draw a branch to '1' and '0'. From '0', draw a single straight line to '1'. From '1', draw a fork to '0' and '1'. |
Fibonacci Sequence Growth Chart |
Draw the number of nodes at each level. Write the sequence: 2, 3, 5, 8... Write $O(\text{Fibonacci}(N)$) to show sub-exponential growth compared to 2^N. |
List storing all 2^N strings before filtering. |
Recursion call stack of depth N + List of valid strings. |
| 3212 |
Count Submatrices With Equal Frequency of X and Y |
Generate all submatrices starting at (0,0) and manually count X and Y in each. $O(N^3)$. |
Overlapping Rectangles |
Draw a grid. Draw a small 1x1 box at the top left. Then 1x2, 2x1, 2x2. Show that you are repeatedly recounting the top-left cell. |
2D Prefix Sum Matrix |
Matrix Expansion Strategy |
Create a prefix sum matrix for X counts and Y counts. To get counts for a submatrix ending at (i,j), look at the prefix sum cell (i,j). |
Draw a grid. For cell (i,j), draw an arrow from (i-1,j), an arrow from (i,j-1), subtract (i-1,j-1), and add the current cell's value. |
Single Matrix Pass |
Draw an N x M grid. Draw a single sweeping line starting top-left and ending bottom-right. Label $O(N \cdot M)$ time. |
Recounting local variables (O(1) extra space). |
Two N x M integer matrices storing cumulative frequencies (O(N * M) space). |
| 3213 |
Construct String with Minimum Cost |
Try every target word at every position in the string via DFS. $O(\text{Branching} ^ N)$. |
Massive Backtracking Web |
Draw the target string. Under index 0, branch out for every word that matches the prefix. Repeat for the remaining suffix. |
Aho-Corasick / Trie + 1D Dynamic Programming |
State Transition Matching |
Build a Trie of the target words. Use a DP array where dp[i] is the min cost to build string up to index i. Use the Trie to rapidly find all matching words starting at index i. |
Draw a 1D DP array of size N. Draw a Trie on the side. For DP[i], trace down the Trie using characters from index i onwards, updating future DP states when reaching a valid word. |
Automaton State Jump |
Draw the target string timeline. Draw multiple forward-jumping arcs representing matched words, labeled with their cost. Show it's $O(N^2 + \text{Trie Building})$. |
Extremely deep recursion stack branching indefinitely. |
Trie structure (O(sum of word lengths)) + DP Array of size N. |
| 3214 |
Year on Year Growth Rate (SQL) |
Self-joins or Cartesian products matching records from year N to year N-1. |
Relational Algebra Explosion |
Draw two massive tables side-by-side. Draw lines connecting every row in Table A to every row in Table B to show the $O(N^2)$ join penalty before filtering. |
Window Functions (LAG / LEAD) |
Rolling Window Table |
Draw a single table sorted by date. Point a downward arrow from the 'Current Year' row to a new column in the *same* row pulling data from 'Previous Year'. |
Sketch a table column. Draw an arrow curling backwards from index `i` to index `i-1` indicating the LAG operation pulling the previous value locally. |
Single-Pass Table Scan |
Draw one large rectangular block representing the sorted table. Draw a single straight horizontal arrow passing through it, signifying an $O(N)$ sequential read. |
Duplicated temporary tables holding intermediate joins. |
In-memory sorting buffer + sliding row pointers (O(1) extra space). |
| 3215 |
Count Triplets with Even XOR Set Bits II |
Triple nested loop generating every combination of A, B, C and checking `popcount(A^B^C)`. $O(N^3)$. |
3D Iteration Cube |
Draw a 3D cube representing axes i, j, k. Shade the entire volume to visually demonstrate the massive cubic time complexity scaling. |
Bitwise Parity Math / Combinatorics |
Probability Tree Diagram |
Count elements with even and odd set bits in each array. The XOR parity is even if the number of odd-parity elements chosen is 0 or 2. Multiply the combination counts. |
Draw three buckets for arrays A, B, C. Inside each, write the count of 'Evens' and 'Odds'. Draw paths connecting valid combinations (e.g., Even-Even-Even, Even-Odd-Odd) and multiply. |
Independent Linear Scans |
Draw three separate horizontal lines of length N. Sum them to $O(N + M + K)$. Beside it, draw a small $O(1)$ box for the final mathematical multiplication. |
$O(1)$ space, but high CPU register churn. |
Six scalar integer variables storing frequency counts (O(1) space). |
| 3216 |
Lexicographically Smallest String After a Swap |
Find all valid adjacent swaps with matching parity, generate the new strings, sort them, and pick the smallest. |
String Branching Tree |
Write the string. Draw branches for every possible valid swap, creating full copies of the string at the end of each branch. |
Greedy Linear Scan |
Two-Pointer Sliding Window (Size 2) |
Slide a window of size 2 across the string. If `parity(left) == parity(right)` AND `left_val > right_val`, swap immediately and stop. |
Write the string. Put your index and middle fingers on the first two digits. If they match parity and the left is bigger, swap them. Otherwise, shift fingers one spot right. |
Early-Exit Pipeline |
Draw a line of length N. Shade only the first portion of it red, stopping early with a break symbol to represent $O(N)$ worst-case but often $O(1)$ best-case. |
Multiple string array allocations in memory. |
In-place character array modification (O(N) space for mutable string conversion). |
| 3217 |
Delete Nodes From Linked List Present in Array |
For every node in the linked list, iterate through the entire array to check if it exists. $O(N \cdot M)$. |
Nested Traversal Lines |
Draw the Linked List. From the first node, draw M arrows pointing to every element in the array. Repeat for the next node. |
HashSet + Dummy Node 1-Pass |
Hash-Backed Pointer Jump |
Dump the array into a HashSet. Create a dummy node pointing to head. Traverse the list; if `next.val` is in the set, bypass it (`curr.next = curr.next.next`). |
Draw a Linked List. Draw a box labeled "O(1) Set". Trace over the nodes. When reaching a target node, draw an arched arrow skipping completely over it to the next valid node. |
Two Sequential Blocks |
Draw a block labeled "Build Set" $O(M)$. Draw a second, non-overlapping block labeled "List Scan" $O(N)$. Result: $O(N + M)$. |
No extra space, but huge time penalty. |
A HashSet structure containing up to M elements (O(M) space). |
| 3218 |
Minimum Cost for Cutting Cake I |
Recursively simulate cutting the cake horizontally and vertically in every possible order. $O(\text{Exponential})$. |
Matrix Partition Tree |
Draw a grid. Branch it into two smaller grids (horizontal cut) and two others (vertical cut). Continue branching indefinitely until 1x1 pieces remain. |
Greedy Sorting (Largest Cost First) |
Cost-Weighted Grid Slicing |
Sort horizontal and vertical cut costs descending. Always pick the most expensive available cut. Multiply its cost by the number of existing perpendicular pieces. |
Draw two descending lists of numbers (H and V). Track two variables: `h_pieces = 1`, `v_pieces = 1`. Cross off the highest number. If it's H, add `val * v_pieces` to total, and `h_pieces++`. |
Sorting Bottleneck |
Draw two blocks labeled "Sort H" and "Sort V". Draw a linear merge process after. Label the whole diagram $O(N \log N + M \log M)$. |
Massive recursion stack holding grid states. |
In-place sorted arrays (O(1) to $O(\log N)$ space depending on sort). |
| 3219 |
Minimum Cost for Cutting Cake II |
Recursive matrix partitioning (trying every possible cut order horizontally and vertically). |
Exponential Grid Split Tree |
Draw a single grid. Branch into two smaller subgrids representing a horizontal cut, and two representing a vertical cut. Branch indefinitely. |
Greedy Sorting / Two Pointers |
Cost-Weighted Axis Slicing |
Sort cut costs descending. Compare the top remaining Horizontal and Vertical cuts. Take the larger. Multiply its cost by the number of perpendicular pieces already formed. |
Draw two sorted arrays (H and V). Track two multipliers (H_pieces=1, V_pieces=1). Cross off the highest element, add (value * opposite_multiplier) to total, increment your multiplier. |
Linear Merge Timeline |
Draw two $O(N \log N)$ / $O(M \log M)$ sort blocks. Draw a single sweeping line merging them in $O(N+M)$ time. |
Massive call stack proportional to grid permutations. |
In-place sorted array (O(1) auxiliary space). |
| 3220 |
Odd and Even Transactions (SQL) |
Self joins or multiple heavy subqueries filtering individually for odd and even amounts. |
Relational Cartesian Product |
Draw a giant table intersecting with itself, showing rows exponentially expanding before filtering by modulo operations. |
Conditional Aggregation (SUM + IF/CASE) |
Split-Stream Pipeline |
Group by date. For each row, check modulo parity. If odd, add to 'Odd' bucket. If even, add to 'Even' bucket. |
Draw a row moving through a diamond decision node. Draw an arrow routing it to an "Odd Sum" box or an "Even Sum" box based on amount % 2. |
Single-Pass MapReduce |
Draw a timeline of $O(N)$ row scanning, feeding directly into a constant $O(1)$ mathematical routing operation per row. |
Duplicate temporary tables stacking up in memory. |
$O(N)$ Hash map space for the Group By result set. |
| 3221 |
Maximum Array Hopping Score II |
DFS trying every single valid forward jump combination. $O(2^N)$. |
Exponential Path Tree |
Draw the array indices as nodes. Draw lines from index 0 to every index > 0. From index 1, draw lines to > 1. Label leaves to show explosion. |
Monotonic Stack / Greedy Suffix Max |
Mountain Peak Hopping |
Traverse strictly backwards. Keep track of the highest peak seen so far. At each step, add the current highest peak to your running total score. |
Draw the array elements as a bar chart. Trace a line backwards from the right, extending horizontally to create a "staircase" covering the bars. Jump only to these step edges. |
Single Sweep Array Scan |
Draw a single finger sliding exactly once from right-to-left across the array, assigning $O(1)$ ops per step. $O(N)$. |
Deep recursion call stack $O(N)$. |
A single scalar variable tracking max peak (O(1) space). |
| 3222 |
Find the Winning Player in Coin Game |
Recursive Game Tree simulation tracking whose turn it is and subtracting coins until one loses. |
Minimax Decision Tree |
Draw a root node with (Coins X, Coins Y). Draw a branch subtracting (1, 4). Label nodes Alice and Bob alternately until failure. |
Mathematical Parity / Bottleneck Check |
Bottleneck Resource Graph |
Since exactly 115 must be made (1x75 + 4x10), calculate maximum possible turns: min(x, y // 4). If turns is odd, Alice wins. Even, Bob wins. |
Draw two buckets (X and Y). Write the formula min(X, floor(Y/4)). Write the result modulo 2 to determine the winner without simulating turns. |
$O(1)$ Constant Time Block |
Draw a single box containing a basic division and modulo operation, labeling it strictly $O(1)$ time. |
Call stack matching the number of turns. |
$O(1)$ constant scalar variables. |
| 3223 |
Minimum Length of String After Operations |
Manually simulating string deletions, shifting array elements left and right to close gaps. $O(N^2)$. |
Array Shifting Pipeline |
Draw an array. Erase two elements. Draw arrows forcing all elements on the right to manually slide leftward one by one to fill the hole. |
Frequency Counting Map / Parity Math |
Histogram Parity Pruning |
Count letter frequencies. The order of deletions doesn't matter. If a count is >= 3, mathematically reduce it to 1 (if odd) or 2 (if even). Sum the remains. |
Draw a frequency table for A-Z. Cross out any number >= 3 and replace it using the rule `count % 2 == 0 ? 2 : 1`. Sum the final column. |
Two-Pass Timeline |
Draw a block for $O(N)$ string traversal to count. Draw a second block for $O(26)$ traversal to sum. Overall $O(N)$. |
New string allocations for every deletion. |
Fixed size $O(26)$ integer frequency array (O(1) space). |
| 3224 |
Minimum Array Changes to Make Differences Equal |
Iterate through all possible difference values X (from 0 to K). For each X, iterate through the N/2 pairs to calculate the cost. $O(N \cdot K)$. |
Nested Loop Grid Expansion |
Draw a massive matrix. Rows are target differences (0 to K), columns are array pairs (0 to N/2). Shade the whole grid to show the multiplicative $O(N\cdot K)$ work. |
Difference Array / Sweep Line Algorithm |
Overlapping Interval Histogram |
For each pair, calculate ranges of target differences that cost 0, 1, or 2 operations. Mark these boundaries on a difference array. Compute the prefix sum to find the minimum cost. |
Draw a horizontal number line (0 to K). Draw colored blocks spanning intervals (e.g., cost 1 block, cost 2 block). Stack the blocks. The lowest stack height is the answer. |
Two Sequential Linear Scans |
Draw a line of length N/2 for interval generation, and a line of length K for prefix sum calculation. Result: strictly $O(N + K)$. |
Variables tracking local minimums and nested counters (O(1)). |
A 1D array of size K+2 tracking interval boundary increments (O(K) space). |
| 3225 |
Maximum Score From Grid Operations |
Recursive backtracking testing all possible coloring combinations (black/white) for every single column configuration. $O(\text{Exponential})$. |
Massive State Matrix Tree |
Draw an N x N grid. Branch out for every single column showing all 2^N possible coloring states, creating an impossibly wide tree. |
Dynamic Programming (Column State Transitions) |
Sliding Column Window |
Maintain states based on the number of black cells in the previous column. Calculate score contributions from the current column compared to the previous one to avoid recalculating the whole grid. |
Draw three adjacent columns. Highlight the middle column. Draw arrows pointing from the left column to the middle, calculating adjacency scores. Move the 3-column window one step right. |
Nested N^3 Cube |
Draw a 3D block representing the transitions: iterating through N columns, previous state K, and current state J. Label it $O(N^3)$. |
Thousands of distinct 2D grid copies in the call stack. |
A 2D DP table of size N x N tracking max scores (O(N^2) space). |
| 3226 |
Number of Bit Changes to Make Two Integers Equal |
Convert integers to binary strings. Pad with leading zeros. Compare strings character by character. |
String Character Alignment |
Write the binary strings of n and k stacked. Draw vertical lines connecting each character to compare them manually. |
Bit Manipulation (XOR, AND) |
Bitwise Logical Pipeline |
Check if `(n & k) == k`. If true, there are no invalid 0-to-1 changes required. The answer is simply the number of set bits in `n ^ k`. |
Write n and k in binary. Draw an '&' gate underneath to check validity. Then draw an XOR '^' gate, producing a final binary number. Count its '1's. |
Constant Time $O(1)$ Block |
Draw a single, small square box labeled "CPU Register Math". No loops. Strictly $O(1)$. |
Two new string allocations in memory. |
A few processor registers (Strictly $O(1)$ space). |
| 3227 |
Vowels Game in a String |
Minimax game tree simulation. Recursively test all possible valid substring removals for Alice and Bob until a base case is hit. $O(N^3 \text{or worse})$. |
Explosive Turn-Based Game Tree |
Draw a root node with the string. Branch out for every possible odd-vowel substring Alice can pick. From those, branch for Bob's even picks. |
Mathematical Invariant / Game Theory |
Boolean True/False Switch |
If the string has 0 vowels, Bob wins. If the string has 1 or more vowels, Alice can always force a win. Therefore, just check if the string contains *any* vowel. |
Draw the string. Sweep a scanner from left to right. Stop immediately at the first vowel and write "Alice Wins". |
Early-Exit Linear Line |
Draw a line representing the string. Mark an 'X' early in the line indicating a break statement. Worst case $O(N)$, best case $O(1)$. |
Deep recursion stack storing many substring fragments. |
No extra allocations (O(1) space). |
| 3228 |
Maximum Number of Operations to Move Ones to the End |
Iteratively find the first "10" pattern, convert it to "01", and repeat from the beginning until no "10" exists. $O(N^2)$. |
Shifting Array Timeline |
Draw the array. Find "10", erase, write "01". Redraw the entire array. Repeat. Show the cascading redundant work. |
Greedy Counting / Cumulative Sum |
Obstacle Jumping Graph |
Scan left to right. Count the number of '1's seen so far. Every time you encounter a block of '0's (following a '1'), add the current count of '1's to your total operations. |
Draw the array. Put a box over blocks of '1's and track the running total. Point an arrow from the '1's to the next '0', adding the running total to the final answer. |
Single Sweep Pipeline |
Draw a straight line moving strictly left to right. Draw a small "O(1) addition" node at every '0'. Total time $O(N)$. |
Intermediate string creations or heavily mutated char arrays. |
Two scalar integers tracking ones count and total operations (O(1) space). |
| 3229 |
Minimum Operations to Make Array Equal to Target |
Iteratively find subarrays that need incrementing/decrementing, apply +1/-1 step-by-step. $O(N \\text{cdot MaxDiff})$. |
Cascading Array Updates |
Draw the target array. Cross out and rewrite elements linearly over and over to simulate adding +1 to ranges until they match. |
Difference Array / Greedy Peaks |
Elevation Delta Graph |
Calculate `diff[i] = target[i] - nums[i]`. Traverse left-to-right. Only add to total operations if the current difference requires *new* operations that the previous difference didn't already cover. |
Draw a bar chart of the required differences. When a bar is taller than the previous one, shade the top portion and write its height delta. The sum of these shaded deltas is the answer. |
Single Linear Scan Block |
Draw a single straight line sweeping from index 0 to N. Label it strictly $O(N)$ time with $O(1)$ mathematical checks per node. |
Multiple copies of the array being iteratively modified. |
A single 1D difference array (O(N) space). |
| 3230 |
Customer Purchasing Behaviors Analysis (SQL) |
Heavy Cartesian products to compare every transaction of a customer against every other transaction. |
Relational Cross-Join Matrix |
Draw a table joined against itself. Show lines connecting a single customer's row to every other row, squaring the intermediate dataset. |
Window Functions / CTE (Common Table Expressions) |
Partitioned Data Streams |
Use `PARTITION BY customer_id` to isolate transaction histories. Use `ORDER BY date` and analytical functions to find gaps, sums, and averages locally. |
Draw a large table split into distinct blocks by Customer ID. Inside each block, draw a vertical arrow moving row-by-row calculating rolling metrics. |
Sequential Table Scan Pipeline |
Draw a single pass over the table representing the sorting $O(N \log N)$, followed by a linear scan $O(N)$ for window calculations. |
Huge intermediate temp tables holding $O(N^2)$ rows. |
In-memory sorting buffer (O(1) extra space outside of sort). |
| 3231 |
Minimum Number of Increasing Subsequence to Be Removed |
Generate all combinations of subsequences. Recursively remove valid ones and track the minimum count. $O(\text{Exponential})$. |
Explosive Subset Tree |
Draw the array. Branch out to pick every possible increasing combination, creating massive duplication of remaining elements. |
Patience Sorting / Segment Tree (LIS variant) |
Card Solitaire Stacks |
Iterate through the array. Place each element on the leftmost possible "stack" where it is smaller than the top element. The number of stacks needed is the answer. |
Draw open buckets. Take the first number, put it in bucket 1. Take the next; if it's smaller, put it on top. If it's strictly larger than all tops, open a new bucket. |
Binary Search Pipeline |
Draw an outer loop line (O(N)). Inside, draw a smaller block labeled `Binary Search $O(\log N)$`. Result: $O(N \log N)$. |
Deep recursive stack storing partial arrays. |
A 1D array representing the top of each stack (O(N) space). |
| 3232 |
Find if Digit Game Can Be Won |
Recursively simulate every possible subset Alice could pick, check if the sum beats the remaining elements. $O(2^N)$. |
Full Binary Subset Tree |
Draw a tree where each node branches into "Include" or "Exclude". Calculate the sum at every single leaf node. |
Greedy Summation / Math |
Balance Scale Comparison |
Alice can simply choose *all* single-digit numbers or *all* double-digit numbers. Calculate `sum(single)` and `sum(double)`. If they are not exactly equal, Alice wins. |
Draw two buckets: "Singles" (<10) and "Doubles" (>=10). Tally the sum into each. Write `sum1 != sum2 -> Alice Wins`. |
Constant Time Decision Node |
Draw a single sweeping line to sum the array $O(N)$. Point to a single `!=` comparison box labeled $O(1)$. |
Recursion call stack of depth N. |
Two scalar integer variables for the sums (O(1) space). |
| 3233 |
Find the Count of Numbers Which Are Not Special |
Iterate from L to R. For each number, iterate from 1 to sqrt(N) to count its exact divisors. $O((R-L)$ * sqrt(R)). |
Nested Divisor Loop |
Draw a number line from L to R. For every number, draw an inner loop checking all possible divisors. Show massive redundant calculations. |
Number Theory / Sieve of Eratosthenes |
Prime Square Projection |
A number has exactly 3 divisors ONLY if it is the square of a prime number. Generate primes up to `sqrt(R)` using a Sieve, square them, and count how many fall between L and R. Subtract from total range. |
Draw a number line of integers up to `sqrt(R)`. Cross out non-primes. Take the remaining circled primes, draw arrows squaring them to land in the [L, R] boundary. |
Sieve Bottleneck Block |
Draw a block representing Sieve generation `O(sqrt(R) log log sqrt(R))`. Draw a second fast block counting the squared primes `O(Primes)`. |
Variables constantly overwritten in the inner loop. |
A boolean array of size `sqrt(R)` (O(sqrt(R)) space). |
| 3234 |
Count Substrings With Dominant Ones |
Nested loops generating all $O(N²)$ substrings and counting 1s and 0s manually (O(N³)). |
Dense Nested Loop Matrix |
Draw an N x N grid. Shade every single cell. Label the work in each cell as $O(N)$ scan. Total $O(N³)$. |
Enumeration by Zero-Count (O(N√N)) |
Square Root Threshold Graph |
Since count(0)² ≤ count(1) ≤ N, max count(0) is ≈ 200 for N=40,000. Group substrings by how many 0s they contain (0 to √N). |
Draw the binary string. Mark positions of all 0s. Use a sliding window to capture exactly 'k' zeros and calculate the '1s' buffer available mathematically. |
Bucket Progression Chart |
Draw √N blocks. Each block is an $O(N)$ sweep. Label as $O(N \cdot √N)$. Conclude why √N is the boundary using k^2 <= N. |
Massive collection of substring objects (O(N³)). |
A list of indices for '0' characters (O(N) space). |
| 3235 |
Check if Rectangle Corner Is Reachable |
Model the rectangle as a high-resolution pixel grid and run BFS/DFS pixel-by-pixel. $O(X \cdot Y)$. |
Ultra-Dense Pixel Grid |
Draw a rectangle filled with a tiny mesh of dots. Shade circles. Show how pathfinding must visit every single dot. |
Graph connectivity (Union Find / BFS on Circles) |
Boundary-to-Boundary Barrier Graph |
Check if any path of connected circles connects (Top or Left) to (Bottom or Right). If they connect, the path from (0,0) to (X,Y) is blocked. |
Draw the rectangle. Draw circles. If two circles intersect, draw a line between their centers. If a "wall" of lines cuts from top-left boundary to bottom-right boundary, path is impossible. |
N² Connection Matrix |
Draw N nodes (circles). Draw lines for every pair checked (N² checks). Label as $O(N²)$ time complexity. |
Huge 2D Boolean Grid (O(X*Y) space). |
Disjoint Set Union (DSU) array of size N (O(N) space). |
| 3236 |
CEO Subordinate Hierarchy (SQL) |
Repeated self-joins for every possible level of hierarchy (Join Table 1 to 2, 2 to 3, etc.). |
Staircase Table Joins |
Draw Table A. Join it to Table B. Join that to Table C. Show that for depth D, you need D manual joins. |
Recursive CTE (WITH RECURSIVE) |
Tree Traversal Pipeline |
Start with the CEO (manager_id IS NULL). Recursively find employees whose manager is in the previous result set. Track "Level" as you go. |
Draw the CEO at the top. Draw arrows to direct reports (Level 1), then arrows to their reports (Level 2). Label the Salary Delta at each node. |
Depth-First Table Scan |
Draw a tree growing downwards. Label the scan as $O(N)$ because each employee is visited exactly once via their manager ID link. |
Dozens of intermediate temporary join tables. |
Single execution stack for the recursion (O(Depth) space). |
| 3237 |
Alt and Tab Simulation |
Simulate the stack: for every query, find the window in the list, remove it, and move it to the front. $O(N \cdot M)$. |
Array Shifting Animation |
Draw an array. Circle element 'X'. Erase it. Shift all elements to the right of 'X' one spot left. Re-insert 'X' at index 0. Repeat for every query. |
Reverse Traversal + HashSet |
Latest-First Order Stream |
The most recently queried window always ends up on top. Process queries from last-to-first. If a window hasn't been seen, it's next in the final order. |
Write queries in reverse. Cross out duplicates. Then list any remaining original windows that weren't in the query set. |
Linear Timeline Pass |
Draw a line for M queries (reverse) and a line for N windows. Label as $O(N + M)$. No nested work. |
$O(N)$ array being shifted millions of times. |
HashSet of size N (O(N) space) to track "seen" windows. |
| 3238 |
Find the Number of Winning Players |
For every pick, re-scan the entire pick history to check if that player now has enough same-colored balls. $O(P²)$. |
Redundant Pick Scanner |
Draw the list of picks. For the 100th pick, draw 99 arrows looking back at previous picks. Repeat for every pick. |
2D Frequency Matrix (Counting) |
Player-Color Grid Tally |
Create a grid where rows = players and columns = colors. Increment cell (player, color). If cell > player_id, they win. |
Draw a small table (Rows 0-N). As you read `[player, color]`, put a tally mark in that cell. If a cell reaches `player_id + 1`, circle the row. |
One-Pass Hash Mapping |
Draw a single line for the 'P' picks. Draw an $O(N)$ scan of the summary grid. Total $O(P + N\\text{cdot Colors})$. |
Massive log of all raw pick events. |
A small 2D array of size N x 11 (O(N) space, as colors are fixed at 0-10). |
| 3239 |
Minimum Number of Flips to Make Binary Grid Palindromic I |
Try every possible subset of bit flips to see if the grid becomes palindromic row-wise or column-wise. $O(2^(R\cdot C)$). |
State Space Explosion Tree |
Draw a small 2x2 grid. Branch it into two 2x2 grids (flip vs no flip for cell 1). Repeat for all 4 cells. Show the tree reaches 16 leaves for just 4 cells. |
Independent Row/Column Counting |
Parallel Axis Scan |
Count flips needed to make all rows palindromes. Separately, count flips to make all columns palindromes. The answer is the minimum of these two sums. |
Draw a grid. Use one finger to trace left-to-right on row 1, comparing symmetric ends. Then trace top-to-bottom on column 1. Write down "Row Cost" and "Col Cost" tallies. |
Linear Table Scan Pass |
Draw one block for Row Pass (O(R*C)) and one for Col Pass (O(R*C)). Conclude $O(R\cdot C)$ total. |
Deep recursion stack storing grid copies. |
Two scalar integer variables for the costs (O(1) space). |
| 3240 |
Minimum Number of Flips to Make Binary Grid Palindromic II |
Check all combinations of flips to satisfy both row and column symmetry simultaneously. $O(2^(R\cdot C)$). |
Exponential Decision Web |
Draw a grid with interconnected lines showing that flipping one cell affects both its row and column symmetry. Label it "Interdependent constraints." |
Symmetry Grouping (2x2 Blocks + Centroids) |
Quadrant Fold-over Map |
Group the grid into sets of 4 symmetric cells. For each group, calculate the cost to make them all 0 or all 1. Handle special cases for the middle row/column (pairs) and the center cell. |
Draw a grid. Mark 4 corners with 'A', then move inward and mark the next 4 with 'B'. Circle the middle cross (if R or C is odd). Tally the bits in each lettered group. |
Grouped Element Scan |
Draw the grid split into groups of 4. Show that you visit each cell exactly once. Label $O(R\cdot C)$ time. |
Massive memory stack for backtracking search. |
Scalar variables to track pair counts and 1-bit counts (O(1) space). |
| 3241 |
Time Taken to Mark All Nodes |
Run DFS from every single node to find the time taken for that node to mark all others. $O(N^2)$. |
Radial Wave Propagation (Multiple) |
Draw the tree. Pick a node, draw expanding circles representing time. Erase everything, pick the next node, and redraw the circles. Show the $O(N^2)$ redundancy. |
Tree DP (Rerooting / 2-Pass DFS) |
Directional Edge Weighting |
Pass 1 (Bottom-up): Compute time for each subtree. Pass 2 (Top-down): Compute time from the parent's side. The result for a node is the max of these two values. |
Draw a tree. Draw upward arrows labeling "Subtree Max Time." Then draw downward arrows from parents to children labeling "External Max Time." At any node, result = max(up, down). |
Double Sequential Tree Scan |
Draw two tree diagrams. Label the first "Bottom-Up $O(N)$" and the second "Top-Down $O(N)$." Result: $O(N)$. |
High call stack depth (N) repeated N times. |
Two DP arrays of size N + Recursion stack depth N (O(N) space). |
| 3242 |
Design Neighbor Sum Service |
For every `adjacentSum` or `diagonalSum` query, scan the entire grid to find the value `v`, then check its neighbors. $O(Q \cdot R \cdot C)$. |
Scan-Search Loop |
Draw a grid. For a query "Sum(5)", draw a search path through every cell until you find '5', then look at its 4 neighbors. Repeat Q times. |
Coordinate Mapping (Precomputation) |
Hash-Linked Grid Map |
Store the (r, c) coordinates of each value in a Hash Map or array during initialization. During queries, jump directly to the neighbors using these coordinates. |
Draw a Hash Map on the left and a grid on the right. Draw an arrow from a query "5" to its map entry (row 1, col 1), then circle the adjacent cells in the grid. |
Amortized Constant Query Block |
Draw a large block for "Initialization $O(R\cdot C)$" and small tiny dots for "Queries $O(1)$". Label total $O(R\cdot C + Q)$. |
No extra space, just nested pointers (O(1)). |
A coordinate array/map of size N² (O(R*C) space). |
| 3243 |
Shortest Distance After Road Addition Queries I |
After every road addition, run a full BFS or Dijkstra from node 0 to node N-1. $O(Q \cdot (N + E)$). |
Repeated Graph Traversal |
Draw a graph. Add an edge. Draw a BFS wave from 0 to N-1. Add another edge. Draw the whole wave again. Show the repetitive nature across Q queries. |
Dynamic BFS / Incremental DP |
Shortest Path Propagation |
Since all edges are weight 1, use BFS for each query. Because N is small (500), running a BFS $O(N+E)$ after each of the Q queries is efficient enough. |
Draw nodes in a line. Draw a new shortcut edge. Start at the target of the new edge and update its distance if it's shorter. Propagate this update forward to neighbors. |
Query-Bounded Iteration |
Draw a timeline with Q segments. Inside each, draw an $O(N+E)$ block. Result: $O(Q \cdot (N+E)$). |
Adjacency list being rebuilt or multiple BFS queues. |
Adjacency list (O(N+E)) and a distance array (O(N)). |
| 3244 |
Shortest Distance After Road Addition Queries II |
Run BFS or Dijkstra after every query. Since edges are weight 1, $O(Q \cdot (N+E)$). |
Repeated Wavefront Propagation |
Draw the graph. For each query, shade the entire reachable area layer-by-layer. Repeat Q times to show the redundant $O(Q\cdot N)$ overlap. |
Greedy Range Removal (Set/Segment Tree) |
Path Compression Timeline |
Use an ordered Set (or Segment Tree) to track active nodes. When a "shortcut" from U to V is added, remove all intermediate nodes between U and V. The distance is always the current size of the Set - 1. |
Draw nodes 0 to N on a line. Draw a big arched arrow from 2 to 7. Erase nodes 3, 4, 5, and 6. The "path" now jumps straight. Count the remaining "hops". |
Logarithmic Range Update Block |
Draw a timeline. For each query, draw an $O(\log N)$ "Erase" operation. Total: $O(N \log N + Q \log N)$. |
Multiple BFS queues in memory. |
A single Ordered Set or Segment Tree structure (O(N) space). |
| 3245 |
Alternating Groups III |
Generate all substrings, build frequency maps, and check if one map contains the other. $O(N^3)$. |
Sliding Frequency Grids |
Draw overlapping brackets. Count everything inside from scratch repeatedly. |
Sliding Window + Deficit Counter |
The Missing-Chars Debt Tracker |
Count required chars in target. Use a sliding window. Track `deficit` (how many required chars are still missing). As window expands, reduce deficit. When `deficit == 0`, ALL substrings ending from `right` to the end of the string are valid. Add `N - right` to total, then shrink `left`. |
Draw the string. A window slides right. A "Debt" counter ticks down. When Debt hits 0, freeze the right pointer. Draw a giant bracket covering the rest of the string—count them all! Slide left to re-trigger debt. |
Two Pointer Pass $O(N)$ |
Draw two arrows sliding left-to-right exactly once. |
N^2 frequency maps. |
Two frequency arrays (size 26). $O(1)$ space. |
| 3246 |
Premier League Table Ranking (SQL) |
Self-joins to count how many teams have more points than the current team. $O(N²)$. |
Nested Comparison Loop |
Draw a table. For Team A, look at every other row to see who has more points. Repeat for Team B. Label it $O(N²)$. |
Window Function (RANK) |
Sorted Ranking Stream |
Use `RANK() OVER (ORDER BY points DESC, team_name ASC)`. This assigns a rank based on the sort order, handling ties automatically by skipping the next rank value. |
Draw the table sorted by points. Draw a vertical arrow. Next to the values, write 1, 2, 2, 4 (notice the skip after the tie). This is the "Rank" column. |
Sorting Bottleneck Pipeline |
Draw a block labeled "Sort" $O(N \log N)$. Draw a single-pass ranking block $O(N)$. Total $O(N \log N)$. |
Redundant temporary tables for joins. |
Sorting buffer in memory (O(1) extra space outside of the sort). |
| 3247 |
Number of Subsequences with Odd Sum |
Generate all 2^N subsequences and check the sum of each. $O(N \cdot 2^N)$. |
Exponential Decision Tree |
Draw a tree branching for every element (Include/Exclude). At each leaf, sum the elements. Show the $O(2^N)$ leaf count. |
Combinatorics / DP (Parity Switch) |
Binary State Toggle |
If there is at least one odd number, exactly half the subsequences will be odd and half will be even. The total subsequences are 2^N, so the answer is 2^(N-1). |
Draw two boxes: "Odd Sums" and "Even Sums". Take an odd number. Show how adding it to an "Even" makes it "Odd" and vice-versa, perfectly balancing the counts. |
Constant Time Math Block |
Draw a single $O(N)$ pass to check if an odd number exists. Then draw a single box for the 2^(N-1) calculation. Total $O(N)$. |
Exponential list of all subsets. |
$O(1)$ space to track if an odd number was seen. |
| 3248 |
Snake in Matrix |
Map the grid to a graph and use BFS to find the snake's final position. $O(N²)$. |
Graph Traversal Map |
Draw an N x N grid. Represent the snake as a node. For every command, "search" for the neighboring node. Show unnecessary complexity for a simple grid. |
Coordinate Math (i, j) Simulation |
1D to 2D Index Mapping |
Track `row` and `col`. Up: `row--`, Down: `row++`, Left: `col--`, Right: `col++`. The final position is `(row * n) + col`. |
Draw the grid. Start a pen at (0,0). Move the pen according to the commands "RIGHT", "DOWN". At the end, read the number under the pen. |
Linear Command Scan |
Draw a line for the 'K' commands. Label each command as an $O(1)$ coordinate update. Total $O(K)$. |
Adjacency list of the entire grid. |
Two scalar integers for row and column (O(1) space). |
| 3249 |
Count the Number of Good Nodes |
For every node, initiate a separate DFS to calculate the size of each child's subtree and compare them. $O(N²)$. |
Redundant Subtree Scanning |
Draw a tree. Pick node A. Draw circles around all its children's subtrees. Erase. Pick node B. Repeat. Show the "double counting" of nodes in the circles. |
Post-Order DFS (Bottom-Up Size Tally) |
Subtree Weight Propagation |
Start at leaves (size 1). Return size to parent. Parent checks if all incoming size values are identical. If yes, count as "Good". Return total size (sum + 1) upwards. |
Draw the tree. At each leaf, write "1". Draw arrows up. At a parent, list the incoming numbers (e.g., 2, 2, 2). If all match, circle the parent. Write the sum + 1 next to it. |
Single Tree-Traversal Pass |
Draw a single line tracing the tree in a DFS manner (down and then back up). Label the upward path as the $O(N)$ calculation step. |
Multiple recursion stacks and arrays for setiap node's check. |
Single recursion stack depth H (O(H) space) + Subtree size variables. |
| 3250 |
Find the Count of Monotonic Pairs I |
Recursive backtracking trying all possible values for arr1[i] and arr2[i] that satisfy the sum and monotonic constraints. $O(\text{Max}_\text{val}^N)$. |
Exponential Value Decision Tree |
Draw a root. Branch out for every valid value of arr1[0] (0 to nums[0]). From each, branch for arr1[1]. Show the tree width exploding. |
2D Dynamic Programming (State: Index, Last Value) |
2D DP Grid Filling |
Create `dp[i][v]` as the count of pairs up to index `i` where `arr1[i] = v`. Transition by summing `dp[i-1][prev_v]` where `prev_v` satisfies monotonicity. |
Draw a grid: Rows = Indices, Cols = Values (0-1000). For cell (i, j), draw arrows from all valid cells in row (i-1). Tally the counts. |
Nested Loop Complexity Block |
Draw a block with two loops: one for N and one for Max_val. Label the inner work as another loop for prev_v. Result: $O(N \\text{cdot Max}_\text{val}²)$. |
Deep recursion stack storing state tuples. |
2D DP table (O(N * Max_val) space) or 1D rolling array. |
| 3251 |
Find the Count of Monotonic Pairs II |
Standard 2D DP $O(N \\text{cdot Max}^2)$ as in the previous version, which is too slow for the increased constraints. |
Redundant Range Summation |
Draw the DP grid. For a single cell in row `i`, draw 1000 arrows from row `i-1`. Show that the next cell in row `i` recalculates 999 of those same arrows. |
DP + Prefix Sum Optimization |
Sliding Sum Window |
Observe that the valid range of `prev_v` is a continuous interval. Instead of a loop, use a prefix sum of the previous row to get the sum of the interval in $O(1)$. |
Draw the DP row. Below it, draw a "Prefix Sum" row where each cell is the cumulative sum of the one above. Use one subtraction to find the value for the next DP row. |
Linearized Nested Loop |
Draw two non-nested blocks: "Build Prefix Sum" and "Update DP Row". Show that $O(N \cdot (\text{Max} + \text{Max})$) = $O(N \\text{cdot Max})$. |
Large 2D DP table. |
Two 1D arrays (DP row and Prefix Sum row) of size Max_val (O(Max_val) space). |
| 3252 |
Premier League Table Ranking II (SQL) |
Complex subqueries to find the percentage rank for every team individually, recalculating totals for each. |
Nested Table Aggregations |
Draw the team table. For row 1, run a query on the whole table. For row 2, run it again. Show the $O(N²)$ row reads. |
Window Functions (RANK, COUNT, CEIL) |
Tiered Bucket Partitioning |
Calculate `RANK()` for positions. Calculate `total_teams` using `COUNT() OVER()`. Use `CASE` logic with `CEIL(N * 0.33)` to assign Tiers 1, 2, and 3. |
Draw the table sorted by points. Mark the boundaries at 33% and 66% with horizontal lines. Label the sections Tier 1, 2, and 3. |
Sort-Based Ranking Pipeline |
Draw an $O(N \log N)$ sorting block. Follow it with a single $O(N)$ pass where RANK and TIER are assigned. |
Temporary memory buffers for nested subqueries. |
Single in-memory sorting buffer + result set storage. |
| 3253 |
Construct String with Minimum Cost (Easy) |
Try every word in the dictionary at the current position, then recurse for the suffix. $O(\text{Exponential})$. |
Recursive String Matching Web |
Draw the target string. Under index 0, draw branches for every word in the list. Label the branches that match the prefix. Repeat for suffixes. |
Iterative Dynamic Programming (Substring Check) |
1D DP Progression |
`dp[i]` is the min cost to build the string up to index `i`. At each `i`, look back at all words `w`; if `target.substr(i-len, len) == w`, update `dp[i]`. |
Draw a 1D array of size N. Under index `i`, draw arrows pointing back to `i - word_length`. If the word matches, update the minimum cost at `i`. |
Nested String Comparison Block |
Draw an outer loop (N) and an inner loop (Words). Label the inner operation "Substr Compare". Total $O(N \\text{cdot Words} \\text{cdot Length})$. |
Heavy recursion stack with string slices. |
1D DP array of size N (O(N) space). |
| 3254 |
Find the Power of K-Size Subarrays I |
Iterate through every subarray of size K and check if all elements are consecutive and sorted. $O(N \cdot K)$. |
Sliding Fixed-Window Check |
Draw the array. Draw a box of size K. Scan inside the box to check `A[i] == A[i-1] + 1`. Slide the box one step and repeat the scan. |
Linear Count Tracker |
Consecutive Streak Counter |
Maintain a variable `consecutive_count`. As you move the right pointer, if `A[r] == A[r-1] + 1`, increment the count; otherwise, reset it to 1. If `consecutive_count >= k`, the subarray power is `A[r]`. |
Draw the array. Place a finger on the start. Move right; if the next number is +1, draw a "+" above it. When you have K-1 "+" marks in a row, circle the current number as the result. |
Single-Pass Timeline |
Draw a straight line for N elements. Draw a single arrow moving left-to-right. Label it $O(N)$ because each element is visited once and the "check" is $O(1)$. |
Multiple temporary copies of subarrays (O(N*K) space). |
A single integer `consecutive_count` (O(1) auxiliary space). |
| 3255 |
Find the Power of K-Size Subarrays II |
The same brute force as 3254 (O(N * K)), which will Time Limit Exceeded (TLE) here due to N = 10^5. |
Nested Loop Redundancy |
Draw the array. Show the window moving. Highlight that the brute force re-checks K-1 elements that were already verified in the previous window. |
Amortized Linear Scan / Precomputation |
Precomputed Validity Array |
Identical logic to 3254 but essential here: track the "length of the increasing streak" ending at each index. Use this precomputed info to answer each window query in $O(1)$. |
Draw the input array. Below it, draw a "Streak" array where you write how many consecutive increasing numbers end at that index. For any window, just check if `Streak[end] >= k`. |
Precomputation + Query Block |
Draw a block for "Building Streak Array $O(N)$" and a second block for "Extracting Results $O(N)$". Result: $O(N)$. |
Storage for all K-size subarrays. |
An integer array of size N (O(N) space) or a rolling variable (O(1) space). |
| 3256 |
Maximum Value Sum by Placing Three Rooks I |
Triple nested loops over all cells (r1, c1), (r2, c2), (r3, c3) to find the max sum where rows and columns are distinct. $O((R x C)$^3). |
Hexagonal Loop Explosion |
Draw a small 3x3 grid. Try to pick 3 cells. Show that even for 9 cells, the combinations are (9 Choose 3) = 84. Scale this to show why 100^3 fails. |
Top-3 Row Candidates + Backtracking |
Candidate Pruning Map |
For each row, keep only the top 3 maximum values (and their column indices). This reduces the grid to R x 3. Use DFS/Backtracking on these 3R candidates to pick 3 with distinct rows/cols. |
Draw the grid. For each row, circle the 3 largest numbers and cross out the rest. Now, pick 3 circled numbers such that no two are in the same column. |
Pruned Search Tree |
Draw a tree where each level is a row. Level 1 has 3 choices. Level 2 has 3 choices. Level 3 has 3 choices. Total complexity: $O(R x C + R^3 x 3^3)$. |
Massive recursive stack with grid state copies. |
A 2D array of size R x 3 to store top candidates (O(R) space). |
| 3257 |
Maximum Value Sum by Placing Three Rooks II |
The $O(R x C + R^3)$ candidate approach might still be slow if R is large. Standard brute force is impossible. |
State Space Bottleneck |
Draw a diagram showing that even with top-3 candidates, checking every combination of rows is $O(R^3)$. For R=500, 500^3 = 125 million. |
2D Prefix/Suffix Max + Greedy |
Spatial Maximum Boundary Map |
For each row i, consider it the "middle" rook. The other two rooks must come from rows above 0 dots i-1 and rows below i+1 dots R-1. Use prefix/suffix max arrays to find best column values in these regions. |
Draw the grid. Highlight row 'i'. Draw a "Max-So-Far" box above row 'i' and another "Max-So-Far" box below it. Pick the best from the top box, row 'i', and bottom box. |
Multi-Pass Sequential Block |
Draw three blocks: "Prefix Max Scan $O(\text{RC})$", "Suffix Max Scan $O(\text{RC})$", and "Middle Row Iteration $O(\text{RC})$". Total $O(\text{RC})$. |
Exhaustive coordinate searching. |
2D arrays for prefix and suffix column maximums (O(R*C) space). |
| 3258 |
Count Substrings That Satisfy K-Constraint I |
Generate all substrings $O(N^2)$ and count 0s and 1s for each. $O(N^3)$. |
Quadratic Substring Grid |
Draw an N x N matrix. For each cell (i, j), show an inner loop counting 0s and 1s in S[i dots j]. Label as $O(N³)$. |
Sliding Window (Two Pointers) |
Elastic Substring Expansion |
Expand the right pointer. If both count(0) and count(1) exceed K, shrink the left pointer. The number of valid substrings ending at 'right' is `right - left + 1`. |
Draw the binary string. Place two pointers (L, R). Slide R right. If you hit k+1 zeros and k+1 ones, move L right until one condition is met. Add the distance (R-L+1) to your total. |
Amortized Linear Timeline |
Draw a single line for the string. Show L and R moving only forward. Label as $O(N)$. |
Storing all valid substring strings in a list. |
Two integer counters for 0s and 1s (O(1) space). |
| 3259 |
Maximum Energy Boost From Two Drinks |
Recursive backtracking trying every combination of drinking A or B, including the 1-hour wait to switch. $O(2^N)$. |
Parallel Decision Tree |
Draw two vertical lines (A and B). At each hour, draw arrows staying on the line or jumping to the other line (with a 1-hour gap). Show the branching paths. |
2D Dynamic Programming (State Switching) |
Dual-Rail Track Diagram |
Maintain two DP arrays: `dpA[i]` (max boost ending with A) and `dpB[i]` (max boost ending with B). Transition: `dpA[i] = A[i] + max(dpA[i-1], dpB[i-2])`. |
Draw two parallel rows of numbers. Use your left finger for A and right for B. To calculate A[i], look at the cell directly left (A[i-1]) and the one diagonal-left-twice (B[i-2]). Take the max. |
Two-Pass Linear Sweep |
Draw two horizontal lines of length N. Show a single arrow moving left-to-right updating both lines simultaneously. Label as $O(N)$. |
Exponential call stack storing every switch combination. |
Two 1D arrays of size N (O(N) space) or four scalar variables for $O(1)$ space. |
| 3260 |
Find the Largest Palindrome Divisible by K |
Generate all palindromes of length N in descending order and check divisibility by K. $O(10^(N/2)$). |
Palindromic Search Space |
Draw a number line. Mark all palindromes. Show the massive gaps between them and the time wasted checking each one for divisibility. |
Greedy + Remainder DP |
Symmetry State Grid |
For a palindrome of length N, only the middle digits are "free". Use DP where `dp[i][rem]` is whether a prefix of length `i` can result in a total remainder `rem`. Fill greedily from largest digit (9 to 0). |
Draw a table where rows are "digit positions from edges" and columns are "remainders 0 to K-1". Mark 'True' if a remainder is reachable. Trace back from `dp[mid][0]` to find the digits. |
Remainder Transition Block |
Draw a block for N positions. Inside, draw a loop for 10 digits and a loop for K remainders. Label as $O(N \cdot 10 \cdot K)$. |
Storing all N-digit palindromes as strings. |
A DP table of size (N/2) x K (O(N * K) space). |
| 3261 |
Count Substrings That Satisfy K-Constraint II |
For each query [L, R], run the $O(N)$ sliding window from 3258. Total $O(Q \cdot N)$. |
Repeated Linear Window Scan |
Draw a long array. For query 1, show a window sliding from L to R. For query 2, redo the whole slide. Highlight the $O(Q\cdot N)$ overlap. |
Sliding Window + Prefix Sums |
Area Under the Validity Curve |
Precompute the "leftmost valid index" `L[i]` for every `i` using a sliding window. For a query, find the "pivot" where the window is no longer restricted by the query boundary. Use prefix sums to calculate the counts for both sides of the pivot in $O(1)$. |
Draw the array. Plot a line graph showing the distance `i - L[i] + 1` for each index. A query is a "slice" of this graph. Use prefix sums to find the "area" under the line in that slice. |
Precomputed Area Query Block |
Draw a block for "Precomputing L[i] and Prefix Sums $O(N)$". Draw a small $O(1)$ box for "Query Mathematical Calculation". Total $O(N + Q)$. |
Recalculating counters for every query. |
Two prefix sum arrays of size N (O(N) space). |
| 3262 |
Find Overlapping Shifts |
Iterate from L to R. For each number, calculate its divisors to check if it has exactly 3. $O((R-L)$ * √R). |
Brute Force Divisor Search |
Draw the range. For every single number, draw a loop factoring it. Too slow. |
Sieve of Eratosthenes + Math |
The Prime-Square Identifier |
A number has exactly 3 divisors *only* if it is the square of a prime number (e.g., 4, 9, 25). Find all primes up to √R. Count how many prime squares fall between L and R. Subtract this from total numbers in range. |
Draw a number line of primes. Square them. Drop these "Special" tokens onto the main range line [L, R]. Count the tokens. Subtract from the total length. |
Sieve Precomputation $O(√R \log \log √R)$ |
Draw a quick crossing-out grid up to √R, then a simple counting pass. |
Tracking all divisors. |
Boolean array up to √R. $O(√R)$ space. |
| 3263 |
Convert Doubly Linked List to Array II |
Traverse the list, store values in an array, then sort the array. $O(N \log N)$. |
Collect and Sort Map |
Draw the linked list. Draw an array. Show nodes being moved into the array and then "shuffled" into sorted order. |
Linear Traversal (Bidirectional) |
Pointer-Follow Stream |
If the list is already sorted or if the problem requires a specific order (like original sequence), simply follow the `next` pointers once and store values. |
Draw the DLL. Put a pen on the head. Move the pen following `next` arrows, writing the value in an array at each step. |
Single-Pass Pipeline |
Draw a single line for the traversal. Label it $O(N)$ because each node is visited exactly once. |
Temporary sorting buffers. |
An array of size N to hold the result (O(N) space). |
| 3264 |
Final Array State After K Multiplication Operations I |
Iterate K times: scan the array for the minimum value (O(N)), multiply it, and update. $O(K \cdot N)$. |
Nested Loop Timeline |
Draw a list of N elements. Circle the smallest. Cross it out and write the new value. Draw the entire list K times to show the redundant $O(K\cdot N)$ scans. |
Min-Priority Queue (Heap) |
Binary Heap Tree |
Store all (value, index) pairs in a Min-Heap. Pop the top, multiply, and push it back K times. |
Draw a triangle (Heap). Point to the root (min). Show it being removed and replaced by the last node. Draw arrows for the "bubble down" and "bubble up" logic. |
Logarithmic Scaling Chart |
Draw a block representing K iterations. Inside, draw a smaller box labeled $O(\log N)$. Result: $O(K \log N)$. |
Multiple modified copies of the array. |
Priority Queue internal array of size N (O(N) space). |
| 3265 |
Count Almost Equal Pairs I |
For every pair (i, j), check if swapping two digits in one number makes it equal to the other. $O(N² \cdot D²)$. |
Quadratic Pair Matrix |
Draw an N x N grid. In each cell, draw a nested loop checking all possible digit swaps for that pair. Label as "Computationally Heavy." |
Hash Map + Digit Perturbation |
Set-Based Collision Map |
For each number, generate all possible "almost equal" variations (by swapping two digits). Store the original in a map. Count how many times each variation exists in the map. |
Draw a number "123". Draw lines to its neighbors: "213", "321", "132". Store these in a box (HashMap). Check if the target number is already in that box. |
Linearized Frequency Pass |
Draw one block for $O(N \cdot D²)$ to generate variations. Draw a second $O(N)$ pass to tally results. Result: $O(N \cdot D²)$. |
$O(N²)$ temporary string storage. |
A HashMap storing N entries and their variations (O(N * D²) space). |
| 3266 |
Final Array State After K Multiplication Operations II |
Standard Min-Heap simulation (same as 3264). Fails because K can be 10^9. |
Infinite Simulation Loop |
Draw the heap process. Draw a "Wait" icon. Show that even with $O(\log N)$, 10^9 iterations will never finish within the time limit. |
Simulation + Modular Exponentiation |
Stable State Transition / Cycle Mapping |
Simulate until all numbers reach a "stable" state (minimum > original maximum). Then, use `pow(multiplier, K / N, mod)` to calculate the final bulk increase for all elements simultaneously. |
Draw the array. Simulate a few steps until all numbers are roughly equal. Draw a "Fast Forward" arrow that jumps through the remaining 10^9 steps using a single math formula. |
Hybrid Complexity Block |
Draw an $O(N \log N)$ block for initial simulation. Draw a tiny $O(\log K)$ block for Modular Exponentiation. Result: $O(N \log N + \log K)$. |
$O(1)$ in-place updates. |
$O(N)$ heap storage. |
| 3267 |
Count Almost Equal Pairs II |
Check pairs using the 3265 logic, but allow up to two swaps. $O(N² \cdot D⁴)$. |
High-Dimensional Search Space |
Draw a pair. Branch out for the first swap, then branch again from *each* result for the second swap. Show the exponential growth of possibilities per pair. |
Optimized BFS / DFS on Digit States |
Multi-Level Neighbor Graph |
Similar to 3265, but generate all variations reachable within 2 swaps. Use a Set to avoid double-counting same variations for one number. Use a HashMap for global counts. |
Draw a number. Draw 1st-level swap neighbors. From those, draw 2nd-level swap neighbors. Use a "Seen" set for this specific number before adding to the global "Global" counter. |
State-Limited Linear Scan |
Draw a block for $O(N)$ and an inner block representing the fixed number of digit-swap combinations. Label as $O(N \cdot (D⁴)$). |
$O(N²)$ string allocations. |
HashMap and temporary "Per-Number" Sets (O(N * D⁴) space). |
| 3268 |
Find Overlapping Shifts II |
Try every pair of people (top-left, bottom-right). For each pair, scan all other people to see if they are inside the box. $O(N^3)$. |
Quadratic Box Checking |
Draw pairs. Draw a box. Scan the entire grid for trapped points. |
Sorting + Sweeping Max-Y |
The Descending Ceiling Check |
Sort points by X (ascending), then Y (descending). Iterate `i` (top-left). Iterate `j` from `i+1` (bottom-right). To ensure the box is empty, maintain a `max_y` of any point seen between `i` and `j`. If `points[j].y < points[i].y` AND `points[j].y > max_y`, it's a valid empty box! Update `max_y`. |
Plot points on a graph. Lock a top-left point. Scan rightwards. Track the "highest point seen so far." If the next point is below your top-left but *above* the highest point seen, the box between them is empty. |
Nested Linear Pass $O(N^2)$ |
Draw a sorting pass, followed by an NxN loop with $O(1)$ interior checks. |
Storing lists of box contents. |
In-place sorting. $O(1)$ space. |
| 3269 |
Constructing Two Increasing Arrays |
Recursive backtracking trying every possible number assignment for both arrays while maintaining the increasing property. $O(2^(M+N)$). |
Bifurcating Decision Tree |
Draw a starting node. Branch out: "Next from nums1" vs "Next from nums2". Show the tree depth reaching M+N. Label the leaves to show exponential growth. |
2D Dynamic Programming (dp[i][j]) |
Grid State Transition |
Maintain a DP table where `dp[i][j]` stores the minimum possible largest value for the first `i` elements of nums1 and `j` elements of nums2. Transition: `dp[i][j] = min(f(dp[i-1][j], nums1[i-1]), f(dp[i][j-1], nums2[j-1]))`. |
Draw a matrix with nums1 on the rows and nums2 on the columns. For each cell, draw arrows from the cell above and the cell to the left. Calculate the min value based on the previous cell and the current element's parity/magnitude. |
Matrix-Filling Pipeline |
Draw a 2D grid. Draw a single sweeping arrow starting from (0,0) and ending at (M,N). Label as $O(M\cdot N)$ total work. |
Massive call stack holding depth M+N. |
A 2D DP matrix of size (M+1) x (N+1) (O(M*N) space). |
| 3270 |
Find the Key of the Numbers |
Convert all numbers to strings, pad with leading zeros using `zfill(4)`, and iterate character-by-character to find the minimum. |
String Character Alignment |
Write the three 4-digit strings stacked. Draw vertical boxes around each column (index 0-3). Circle the smallest character in each box. |
Arithmetic Digit Extraction |
Modular Digit Breakdown |
Avoid strings. Use `/ 1000 % 10`, `/ 100 % 10`, etc., to extract digits at each position. Find the minimum of extracted digits and reconstruct the key using `sum * 10 + current_min`. |
Draw three numbers. Underneath, draw 4 rows (thousands, hundreds, tens, units). Tally the digits for each number into these rows and circle the winner in each. |
Constant Time Math Block |
Draw a single box labeled "4 iterations". Inside, draw three "min" operations. Label strictly $O(1)$ time. |
Storing three padded strings in memory. |
Four local integer variables for digit extraction (O(1) space). |
| 3271 |
Hash Divided String |
Slice the string into chunks of size K. For each chunk, convert to a list of characters, sum their ASCII values, and append to a result string. |
Fragmented String Slicing |
Draw the string. Draw "slashes" every K characters. Draw separate circles for each fragment. Sum them and map to a letter. |
Single-Pass Index Traversal (Step K) |
Linear Accumulator Stream |
Use a single loop that jumps by `K`. Inside, use a nested loop or slice to sum character values `(s[j] - 'a')`. Take `sum % 26` and convert back to a character. |
Draw the string as a timeline. Draw brackets of width K. For each bracket, draw an arrow pointing to a single letter result below it. |
Linear Scan Timeline |
Draw a line of length N. Show the pointer moving in "steps" of size K. Label total work as $O(N)$. |
Multiple substring slices and intermediate lists. |
A single result array of size N/K (O(N) space). |
| 3272 |
Find the Count of Good Integers |
Iterate from 10^n-1 to 10^n - 1. For each, check if it's a palindrome and divisible by k. If so, check all its permutations for divisibility. $O(\text{Range} \cdot n!)$. |
Exhaustive Permutation Web |
Draw a number line. At each number, draw a "flower" of branches representing every possible digit permutation. Label as "Computationally Impossible." |
Palindrome Generation + Combinatorial Counting |
Symmetry-Based Search Tree |
Only generate palindromes (half the digits). For each valid palindrome (divisible by k), count its unique anagrams using the formula: fracn!f_1! f_2! dots where f_i is digit frequency. Subtract cases with leading zeros. |
Draw half the digits (e.g., N=4, draw slots 1 and 2). Branch digits 0-9. Reflect to form a palindrome. If divisible by K, list its digit frequencies (e.g., {1:2, 2:2}). Use the formula to count unique arrangements. |
Factorial-Based Complexity Map |
Draw a block for Palindrome generation $O(10^n/2)$. Draw a second block for Frequency Math $O(n)$. Result: $O(10^n/2 \cdot n)$. |
Factorial permutations stored as strings. |
A HashSet to store unique digit-frequency sorted strings of valid palindromes (O(10^{n/2}) space). |
| 3273 |
Minimum Amount of Damage Dealt to Bob |
Recursive simulation trying every possible sequence of attacking enemies to find the minimum damage. $O(N!)$. |
Full Factorial Permutation Tree |
Draw a root. Branch out for N enemies. From each, branch for N-1. Label as "O(N!)" to show the combinatorial explosion. |
Greedy Sorting (Smith's Rule) |
Ratio-Weighted Priority Map |
Define "Time to Kill" as `ceil(health / power)`. Sort enemies by the ratio `damage / time_to_kill` in descending order. Kill the "highest damage per unit of time" enemy first. |
Draw a table with columns: Damage, Time. Add a third column: Ratio (D/T). Sort the table. Highlight that killing the top row first minimizes the damage Bob takes from them while fighting others. |
Sorting Bottleneck Pipeline |
Draw a block labeled "Calculate Ratios $O(N)$". Draw a second block "Sort $O(N \log N)$". Draw a third "Simulation $O(N)$". Total: $O(N \log N)$. |
Massive recursion stack for permutations. |
Storage for calculated ratios and sorted indices (O(N) space). |
| 3274 |
Check if Two Chessboard Squares Have the Same Color |
Create a 2D 8x8 matrix, manually fill it with 0 (black) and 1 (white), and look up the two coordinates. $O(1)$ but inefficient setup. |
Static Grid Lookup |
Draw an 8x8 grid. Shade it like a chessboard. Circle the two target squares and check if both are shaded or both are white. |
Parity Summation |
Coordinate Parity Toggle |
Calculate (char - 'a') + (digit - '1'). If the sum is even, it's one color; if odd, it's the other. Compare the parity of both squares. |
Write the two coordinates (e.g., a1, c3). Convert to numbers: (0,0) and (2,2). Sum them: 0 and 4. Both are even, so they match. |
Constant Logic Block |
Draw a single box with the formula (c+r) mod 2. Label it strictly $O(1)$ time. |
An 8x8 integer array (64 integers). |
Two local integer variables (Strictly $O(1)$ space). |
| 3275 |
K-th Nearest Obstacle Queries |
For every query, add the new distance to a list and sort the entire list to find the K^th element. $O(Q \cdot N \log N)$. |
Repeated List Sorting |
Draw a list that grows longer with every query. After each addition, draw arrows "shuffling" everything to sort it. Show the increasing time taken. |
Fixed-Size Max-Heap |
Binary Heap Limiter |
Maintain a Max-Heap of size K. For each query, if distance < `heap.top()`, pop and push the new one. The answer is always `heap.top()` if size is K. |
Draw a triangle (Heap) with exactly K slots. As you process queries, show larger values being "ejected" from the top and smaller values entering the bottom. |
Logarithmic Query Pipeline |
Draw a timeline of Q queries. Inside each, draw a small box for "Heap Push/Pop $O(\log K)$". Total: $O(Q \log K)$. |
A growing list of all Q obstacles. |
A Max-Heap of exactly K elements ( $O(K)$ space). |
| 3276 |
Select Cells in Grid with Maximum Score |
Backtracking: For every row, try picking every possible value and recurse, checking if the value was used before. $O(2^R x C)$. |
Exponential Decision Tree |
Draw a root. Branch out for every cell in Row 1. From those, branch for Row 2. Show the tree width becoming unmanageable almost immediately. |
Bitmask DP + Sorting Values |
Value-Driven State Transition |
Group coordinates by their cell values and sort values descending. Use a bitmask where the i^th bit represents if Row i has been used. dp(val_idx, mask) is the max score. |
List all values from the grid in descending order. For each value, try assigning it to one of the rows it appears in (if that row's bit in the mask is 0). |
Masked Subproblem Matrix |
Draw a grid where rows = Unique Values (V) and columns = 2^Rows bitmask states. Label as $O(V \cdot 2^\text{Rows} \\text{cdot Rows})$. |
Deep recursion stack storing full grid snapshots. |
A DP table of size V x 2^Rows (where Rows <= 10). $O(1024 x V)$. |
| 3277 |
Maximum XOR Score Subarray Queries |
For every query (L, R), iterate through all subarrays within that range to calculate XOR scores and find the max. $O(Q \cdot N^2)$. |
Triangular Range Scan |
Draw the array. For one query, shade the "triangle" of all subarrays. Repeat this for every query, showing massive overlapping work. |
2D DP (Subarray XOR Triangle + Range Max) |
Pascal’s Triangle of XORs |
Precompute `score[i][j]` (XOR score of A[i dots j]) using the property score[i][j] = score[i][j-1] oplus score[i+1][j]. Then precompute `max_score[i][j]` using a second 2D DP. |
Draw a 2D matrix. Fill the diagonal (size 1 subarrays). Fill the next diagonal by XORing the two elements below it. Then create a second matrix to find the max in each rectangle. |
Precomputed Quadratic Grid |
Draw a block for "Precompute XORs $O(N^2)$", another for "Precompute Maxes $O(N^2)$", and a tiny box for "Query $O(1)$". Total: $O(N^2 + Q)$. |
Recalculating XORs millions of times for overlapping queries. |
Two 2D DP tables of size N x N ( $O(N^2)$ space). |
| 3278 |
Find Candidates for Data Scientist Position II |
Complex joins using `NOT IN` or subqueries to check specific skill strings. |
Iterative Skill Filtering |
Draw a candidate. Scan their skills. Cross-reference manually against a hardcoded list. |
GROUP BY + HAVING COUNT() |
The Exact-Match Checklist |
Filter the table for the required skills. Group by Candidate ID. Use `HAVING COUNT(skill) = required_amount`. |
Draw candidates. Give them a checklist of required skills. If they have the skill, check the box. Filter out anyone who doesn't have 100% of the boxes checked. |
Hash Aggregation $O(N)$ |
Draw a filter node followed by a grouping node. |
N/A |
DB grouping buffer. $O(\text{Candidates})$ space. |
| 3279 |
Maximum Total Area Occupied by Pistons |
Generate all possible rectangles in the grid, check if they contain all 1s. $O((R \cdot C)$^2). |
Expanding Bounding Boxes |
Draw the grid. Draw thousands of random rectangles hoping to perfectly enclose the 1s. |
Linear Scan (Min/Max Tracking) |
The 4-Wall Shrink |
Initialize `min_row`, `max_row`, `min_col`, `max_col`. Iterate the grid once. Whenever you see a 1, update these boundaries. Area = `(max_r - min_r + 1) * (max_c - min_c + 1)`. |
Draw the grid. Push 4 walls (Top, Bottom, Left, Right) inward from the edges. Stop each wall the exact moment it touches a '1'. The remaining box is your answer. |
Single Matrix Pass $O(R \cdot C)$ |
Draw a single sweeping arrow across the 2D grid updating 4 variables. |
Storing subgrids. |
Four integer variables. $O(1)$ space. |
| 3280 |
Convert Date to Binary |
Manually divide the year, month, and day integers by 2 repeatedly to build binary strings. $O(L)$. |
Manual Bit-Stream Building |
Write "2024". Do the long division by 2 multiple times. Repeat for month and day. Label the effort for each part. |
Standard Library formatting (bin/format) |
String Split-Transform-Join |
Split the string by '-', convert each component to binary using built-in methods (removing '0b'), and join them back with '-'. |
Draw the string "2024-08-25". Draw scissors cutting it into three blocks. Pass each block through a "Binary Converter" box. Glue them back together. |
Linear String Transformation |
Draw a timeline of the input string length. Label the split, conversion, and join as $O(L)$. |
Multiple intermediate string fragments. |
Temporary list of 3 strings (effectively $O(L)$ space). |
| 3281 |
Maximize Score of Numbers in Ranges |
Try every possible integer value for the "minimum absolute difference" and use backtracking to see if it can be achieved. $O(\text{Range}^N)$. |
Exhaustive Interval Search |
Draw three intervals on a line. Try placing a point in each such that the gap is 10. Then try 11. Show the exponential number of placements to check. |
Binary Search on Answer + Greedy |
Feasibility Boundary Test |
Binary search for the largest possible "score" X. For a fixed X, greedily place the first number at the start of the first interval and each subsequent number as early as possible (but at least X away). |
Draw a horizontal number line with intervals. Pick a "Score" X. Place a pin in the first interval. Measure X distance with a ruler. If the next interval starts after the ruler ends, place the next pin at the interval start. Otherwise, place it exactly where the ruler ends. |
Logarithmic Search over Linear Check |
Draw a Binary Search tree for the answer range. At each node, draw an $O(N)$ linear scan block. Total: $O(N \log N + N \log(\text{MaxRange})$). |
Massive recursion stack for backtracking placements. |
Sorted input array of intervals (O(N) space). |
| 3282 |
Reach End of Array With Maximum Score |
Standard Dynamic Programming: `dp[i]` is the max score to reach `i` from any `j < i`. $O(N^2)$. |
Nested Dependency Graph |
Draw the array. For the last element, draw arrows from every single previous element. Show the N incoming checks for every index. |
Greedy (Monotonic Suffix Max) |
High-Point Hopping |
Only jump when you find a value larger than your current value. Your score is accumulated by the distance multiplied by the current "best" value you are holding. |
Draw the array as a bar chart. Stand on the first bar. Look right. Jump to the next bar that is *taller* than your current one. Repeat. |
Single-Pass Linear Timeline |
Draw a straight line moving left-to-right once. Label it $O(N)$. |
DP array of size N. |
A single variable tracking the "current max" value (Strictly $O(1)$ space). |
| 3283 |
Maximum Number of Moves to Kill All Pawns |
Generate all permutations of the order in which to kill pawns. $O(P! \cdot N^2)$. |
Factorial Path Explosion |
Draw 15 pawns on a board. Try to list every sequence of killing them. Show how the number of sequences (15!) is over a trillion. |
BFS Precomputation + Bitmask DP |
State-Space Game Tree |
1. Use BFS to find the shortest distance between all pairs of pawns (and the knight). 2. Use Bitmask DP `dp(mask, last_pawn)` to find the max moves for Alice/Bob. |
Draw a table where one axis is "Which pawns are dead" (as binary 1011...) and the other is "Which pawn was killed last". Fill cells by picking the best next move from the BFS distances. |
Combinatorial Mask Grid |
Draw a block for "BFS P x N^2". Draw a second block for "DP 2^P x P". Label as the dominating factors. |
Massive recursion stack for factorial search. |
2D Distance Matrix (P^2) and DP table (2^P * P) ( $O(2^P \cdot P)$ space). |
| 3284 |
Sum of Consecutive Subarrays |
Find all subsequences, check if they are consecutive (difference of 1), sum them. $O(2^N)$. |
Exponential Subsequence Tree |
Draw the array. Branch out to pick elements. Verify if they form a step-by-step sequence. |
Dynamic Programming (State: Value & Direction) |
The Ascending/Descending Chains |
Use DP Maps: `inc[val]` (sum of increasing sequences ending at `val`) and `dec[val]` (decreasing). When you see `val`, `inc[val] = inc[val-1] + count[val-1] * val + val`. Update a global sum. |
Draw numbers. For '5', look at the "Increasing Chain" bucket for '4'. Attach '5' to all those chains. Add the new sum to the total. Do the same for decreasing (look at '6'). |
Linear Scan + Map Update $O(N)$ |
Draw a straight timeline. $O(1)$ map lookups and math at each step. |
Storing lists of sequences. |
Two Hash Maps. $O(N)$ space. |
| 3285 |
Find Indices of Stable Mountains |
Iterate through the mountains. For each mountain i, run a nested loop to check all previous mountains 0 dots i-1 for stability. $O(N^2)$. |
Redundant Lookback Scan |
Draw the mountains. For mountain 5, draw 4 arrows looking back. For mountain 6, draw 5 arrows. Show the quadratic increase in arrows. |
Single-Pass Linear Scan |
Neighbor-Check Pipeline |
Iterate from i=1 to N-1. Simply check if `height[i-1] > threshold`. If true, index i is "stable". |
Draw a row of mountains with heights. Place your left finger on mountain i-1 and right finger on mountain i. If the left height is above threshold, circle the right index. Slide both fingers one step right. |
Linear Timeline Pass |
Draw a single line with N nodes. Show a single arrow moving left-to-right once. Label as $O(N)$. |
Storing all heights and their previous dependencies. |
A result list to store valid indices (O(N) space in worst case). |
| 3286 |
Find a Safe Walk Through a Grid |
DFS/Backtracking to explore all possible paths from (0,0) to (M,N), keeping track of health. $O(3^M x N)$. |
Recursive Path Explosion |
Draw a small grid. From (0,0), draw arrows to all neighbors. From each neighbor, draw arrows to their neighbors. Show the exponential "web" of possible paths. |
0-1 BFS or Dijkstra |
Least-Cost Wavefront Expansion |
Treat the grid as a graph where cells with '1' have weight 1 and '0' have weight 0. Find the shortest path (minimum health loss) from start to end. If min_loss < health, the walk is safe. |
Draw the grid. Use a pen to draw "ripples" expanding from (0,0). For each cell, write the minimum health lost to reach it. If you reach the end with a number smaller than the starting health, you win. |
Dijkstra/BFS State Grid |
Draw an M x N grid. Label the work as $O(M x N)$ since each cell is processed with its minimum possible cost. |
Massive recursion stack and path history. |
A 2D distance/health array of size M x N (O(M x N) space). |
| 3287 |
Find the Maximum Sequence Value |
Try every possible split point p. For each p, generate all subsequences of length k from the left and right, calculate their OR-sums, and XOR them. $O(2^N)$. |
Bifurcating XOR Subgraph |
Draw the array. Split it in the middle. From both sides, branch out into all possible k-length combinations. Show the XOR operation at the bottom. |
DP with Bitset (Prefix/Suffix ORs) |
Bitset Reachability Matrix |
dp[i][j][v] is true if a subsequence of length j using first i elements can have OR-sum v. Since v < 128, use bitsets to store reachable OR-sums. Compute prefix and suffix DPs, then find the max XOR. |
Draw a table where rows = length j and columns = bitsets of reachable values. Move through the array, updating the bitset by OR-ing the current value with all previous reachable values. Repeat from the end (suffix). |
Bounded DP Cube |
Draw a 3D block representing N elements, K length, and 128 possible OR-sums. Label as $O(N \cdot K \cdot 128)$. |
Exponential storage of all k-length OR results. |
Two 3D DP tables of size N x K x 128 (O(N * K * 128) space). |
| 3288 |
Length of the Longest Increasing Path Through Two Points |
Find all possible paths from the start of the coordinate plane to the end, filter those that pass through the target indices, and find the longest. $O(2^N)$. |
Filtered Coordinate Tree |
Plot all points on a graph. Draw all possible "zig-zag" upward paths. Cross out any path that doesn't hit the specific mandatory point. |
Sort + Binary Search LIS |
Segmented LIS Filtering |
1. Filter points into two sets: those that can come *before* the target point (x < x_t, y < y_t) and those that come *after* (x > x_t, y > y_t). 2. Run $O(N \log N)$ LIS on both sets independently. The result is LIS_before + 1 + LIS_after. |
Plot the points. Draw a vertical and horizontal line through the target point, creating four quadrants. Only keep points in the bottom-left and top-right quadrants. Run the LIS "staircase" algorithm on each quadrant. |
Sort-Bounded LIS Pipeline |
Draw an $O(N \log N)$ sort block, followed by two $O(N \log N)$ LIS blocks. Total: $O(N \log N)$. |
Storing every possible valid increasing path. |
A tails array for binary search LIS (O(N) space). |
| 3289 |
The Two Sneaky Numbers of Digitville |
Use a nested loop to compare each number with every other number to find duplicates. $O(N^2)$. |
Nested Comparison Matrix |
Draw a square grid where rows and columns are array indices. Shade every cell where i
eq j. Point out that each shading is a comparison. |
XOR Math or Frequency Array |
Bitwise Cancellation Map |
XOR all numbers from 0 to n-1, then XOR all numbers in the input array. The result is a oplus b. Use the first set bit to partition the numbers and find a and b individually. |
Draw two circles. In one, write 0 dots n-1. In the other, write the input. Draw lines connecting identical numbers between circles. The two "unconnected" numbers in the input are the sneaky ones. |
Single-Pass Pipeline |
Draw a straight line for the array scan. Label it $O(N)$. Draw a small box for the XOR result. |
Storing counts in a large Hash Map. |
Strictly $O(1)$ auxiliary space using variables for XOR sums. |
| 3290 |
Maximum Multiplication Score |
Recursive backtracking trying all possible indices i_0 < i_1 < i_2 < i_3 in array b. $O(N^4)$. |
Explosive 4-Level Decision Tree |
Draw a root node. Branch it N times for the first index, then N-1 for the second. Label as "Combinatorial Explosion." |
1D Rolling DP (4 Stages) |
Layered State Transition |
Maintain four DP variables/arrays representing the max score using the first 1, 2, 3, and 4 elements of a. At each element in b, update states from right to left. |
Draw 4 slots labeled dp1, dp2, dp3, dp4. As you slide your finger over array b, update dp4 using dp3, then dp3 using dp2, and so on. |
Linear Progression Block |
Draw a single pass of length N. Inside, draw 4 constant-time update boxes. Total: $O(N)$. |
Massive recursion stack and path history. |
Four scalar variables or a small array of size 4 (O(1) space). |
| 3291 |
Minimum Number of Valid Strings to Form Target I |
Try every possible prefix of 'target' against every string in 'words' using recursion. $O(\text{Exponential})$. |
Recursive String Branching Web |
Draw the target string. Under index 0, draw arrows for every word that matches a prefix. Label the depth as target length. |
Trie-Based Dynamic Programming |
Prefix-Jump Timeline |
Build a Trie of all words. Let `dp[i]` be the min strings to form `target[0...i]`. At each `i`, use the Trie to find all matching prefixes of `target[i...]` and update future DP states. |
Draw a 1D DP array. Under each index, draw "jump" arrows of various lengths based on the Trie matches found at that index. Pick the path with the fewest jumps. |
Trie-Search Bottleneck |
Draw a block for Trie construction $O(\text{Words} x \text{Length})$. Draw a nested loop block for DP $O(N^2)$. Total: $O(\text{Words} \cdot L + N^2)$. |
Deep recursion stack with multiple string slices. |
Trie structure + DP array of size N (O(Words * L + N) space). |
| 3292 |
Minimum Number of Valid Strings to Form Target II |
Same Trie + DP approach from 3291. $O(N^2)$ fails due to N=50,000. |
Quadratic State Table |
Draw the DP table. Show that for a large N, the number of "jump" arrows being checked at each index becomes too large for the time limit. |
Aho-Corasick + Greedy Jump / Segment Tree |
Automaton State Jump Map |
Use Aho-Corasick to find the longest prefix match at each position in $O(N)$. Then, solve the "Minimum Jumps to reach the end" using a Segment Tree or monotonic queue. |
Draw the target string. At each index, write a number L (longest match). This turns the problem into "At index i, you can jump to any j <= i+L." Use a Segment Tree to find the min jumps in that range. |
Linearized Automaton Pipeline |
Draw an $O(\text{Words} \cdot L)$ block for the automaton and an $O(N \log N)$ or $O(N)$ block for the greedy/queue jump. Total: $O(\text{Words} \cdot L + N \log N)$. |
Large 2D DP table. |
Aho-Corasick state tree + Segment Tree (O(Words * L + N) space). |
| 3293 |
Calculate Product Final Cost (SQL) |
Use multiple correlated subqueries to calculate discounts for each product one by one. $O(N^2)$. |
Nested Table Aggregations |
Draw the product table. For row 1, draw a box representing a full scan of the discounts table. Repeat for every row. |
LEFT JOIN + COALESCE (Conditional Logic) |
Relational Mapping Stream |
Join the product table with the discounts table on category. Use `COALESCE(price * (1 - discount), price)` to handle products with no applicable discounts. |
Draw two tables. Draw a line from a Product row to its matching Category in the Discount table. Write the math result in a new "Final Cost" column. |
Single-Pass Hash Join |
Draw a single horizontal pass through the joined data. Label it $O(N + M)$ for the join and $O(N)$ for the calculation. |
Redundant temporary tables for subqueries. |
Standard SQL join buffer (O(M) space for the smaller table). |
| 3294 |
Convert Doubly Linked List to Array II |
From the given node, traverse forward to find all following nodes, then traverse backward to find all preceding nodes. Store and reverse the backward part. $O(N)$. |
Bi-directional Collection Map |
Draw the node with arrows pointing both ways. Draw two "collection buckets." Fill the right bucket moving forward and the left bucket moving backward. Show the concatenation step. |
Two-Pass Linear Traversal (Head-to-Tail) |
Head-First Pointer Stream |
1. Move backward using `node.prev` until you reach the head (where `prev` is NULL). 2. Traverse forward from the head to the tail, adding values to your result array. |
Draw the DLL. Put your pen on the given node. Draw a dashed line moving left until the start. From the start, draw a solid line all the way to the right, labeling each node value. |
Two-Stage Sequential Pass |
Draw a straight line of length N. Draw an arrow moving left, then an arrow moving the full length right. Total: $O(2N)$ rightarrow $O(N)$. |
Two separate arrays for backward/forward results. |
A single result array and a single pointer (O(1) extra space). |
| 3295 |
Report Spam Message |
For every word in the message, iterate through the entire `bannedWords` array to see if it matches. Count the matches. $O(M x B)$. |
Nested Comparison Grid |
Draw the `message` words as rows and `bannedWords` as columns. Shade the intersections where words match. Label as $O(M x B)$. |
HashSet Lookup |
Set-Filtered Stream |
Convert `bannedWords` into a HashSet. Iterate through the `message` once. If a word is in the set, increment a counter. If the counter reaches 2, return true. |
Draw a "Filter Box" representing the HashSet. Throw each word from the message into the box. If it hits a "banned" slot, increment a tally on the side. Stop when the tally hits 2. |
Linear Hashing Pipeline |
Draw an $O(B)$ block for Set construction and an $O(M)$ block for the scan. Total: $O(M + B)$. |
Multiple string comparison buffers. |
A HashSet containing B unique strings (O(B) space). |
| 3296 |
Minimum Number of Seconds to Make Mountain Height Zero |
Simulate every worker's progress second-by-second, checking if the total height reduction has reached H. $O(\text{TotalTime} x N)$. |
Time-Step Simulation |
Draw a vertical "Mountain" and N clocks. For every tick, calculate the height reduction for each worker. Show the massive waste of time for large H. |
Binary Search on Answer / Priority Queue |
Work-Rate Feasibility Curve |
Binary search for the minimum time T. For a fixed T, calculate the maximum height reduction each worker can achieve in T seconds using the quadratic formula t >= fracx(x+1)2 x factor. Sum these and check if total reduction >= H. |
Draw a timeline. Pick a middle time. For each worker, draw a block showing how much "Mountain" they can eat. If the blocks together cover the mountain, try a smaller time. |
Logarithmic Search Block |
Draw a Binary Search tree for time. At each node, draw an $O(N)$ loop for the math check. Total: $O(N \log(\text{MaxTime})$). |
Detailed per-second state of every worker. |
$O(1)$ space for the math check (using the quadratic formula). |
| 3297 |
Count Substrings That Can Be Rearranged to Contain a String I |
Generate all $O(N^2)$ substrings and for each, count character frequencies to see if it contains `word2`. $O(N^3)$. |
Exhaustive Substring Matrix |
Draw an N x N matrix. In each cell, draw a 26-slot frequency table. Show the massive redundant counting for overlapping substrings. |
Sliding Window (Two-Pointers) |
Dynamic Frequency Balance |
Use two pointers (L, R). Expand R until the window contains all characters of `word2`. For a fixed R, all substrings starting from 0 dots L and ending at R are valid. |
Draw the string. Place two fingers (L, R). Widen R until you have the target. Every step you can shrink L while staying valid adds a "Count" for all remaining suffixes. |
Amortized Linear Pipeline |
Draw a line of length N. Show L and R moving only right. Label as 2N steps = $O(N)$. |
Storing all valid substring strings. |
Two fixed-size frequency arrays (O(26) rightarrow $O(1)$ space). |
| 3298 |
Count Substrings That Can Be Rearranged to Contain a String II |
Same sliding window as 3297, but with tighter memory/time constraints (e.g., N = 10^6). |
High-Performance Window Map |
Draw the window moving. Highlight that even a Hash Map might be slow; use a fixed integer array `int[26]` for speed. |
Optimized Sliding Window (Variable Frequency) |
Rolling Delta Tracker |
Instead of checking the whole frequency map at each step, maintain a "Needs" counter. Decrement it when a required character count is met. This makes the inner check $O(1)$ instead of $O(26)$. |
Draw the 26-slot array. Circle the "Needs" counter. As you slide R, update a slot and, if it hits zero, decrement the counter. When the counter is zero, you've hit a "Good Window." |
Strictly Linear Timeline |
Draw a straight line. Label the work at each node as exactly $O(1)$. Total: $O(N)$. |
Standard Map overhead memory. |
Single integer array of size 26 (Strictly $O(1)$ auxiliary space). |
| 3299 |
Sum of Consecutive Subsequences |
Generate all 2^N subsequences and check if they are consecutive (x, x+1, x+2 or x, x-1, x-2). $O(N \cdot 2^N)$. |
Binary Decision Tree |
Draw a tree branching for every element (Include/Exclude). Mark the path "Consecutive" only if the property holds. Label as $O(2^N)$. |
Dynamic Programming (DP with Hash Table) |
State-Based Accumulator Map |
Count subsequences ending at x using dp[x] = dp[x-1] + 1. The sum of all dp[x] gives the count. Use prefix/suffix counts to calculate the total sum contribution of each element. |
Draw a row of numbers. Underneath, draw a "Count Box" for each number. As you scan, update the count: "If I see a 5 and have 10 sequences ending in 4, I now have 10 new sequences ending in 5." |
Linear Scan Pipeline |
Draw a straight line for the array scan. Label it $O(N)$ with $O(1)$ Hash Map lookups. Total: $O(N)$. |
Massive recursion stack for all subsequence branches. |
Two Hash Tables (Prefix/Suffix) of size N (O(N) space). |
| 3300 |
Minimum Element After Replacement With Digit Sum |
Convert each integer to a string, iterate characters, sum them, and store in a list. Find the min. $O(N \cdot D)$. |
String Transformation Map |
Draw the array. For each number, draw a small loop converting it to a string and summing characters. Label as $O(N x \text{Digits})$. |
Arithmetic Digit Summation |
Modulo Reduction Stream |
Use a while loop with `num % 10` and `num /= 10` to sum digits mathematically. Track the minimum sum encountered. |
Draw a number. Draw a "Whirlpool" arrow showing digits being pulled off the end via `% 10` and added to a "Sum" bucket until the number is 0. |
Single-Pass Constant Operation |
Draw a line for N elements. Each element has a fixed max number of digits (e.g., 5-10). Label as $O(N)$. |
Storing all intermediate string objects. |
Strictly $O(1)$ auxiliary space (just min_val and current_sum). |
| 3301 |
Maximize the Total Height of Unique Towers |
Try all permutations of heights within the given limits and check for uniqueness. $O(N! \\text{cdot MaxHeight})$. |
Permutation Search Web |
Draw the towers. Try every possible height for Tower A, then B. Cross out paths where heights are not unique. Label as exponential. |
Greedy (Sort + Boundary Cap) |
Descending Constraint Ladder |
Sort the maximum allowed heights descending. Assign the largest possible height to the first tower. For each subsequent tower, assign `min(limit, previous_height - 1)`. If height hits 0, return -1. |
Draw a sorted list of limits. Place a "Cap" variable. For each limit, update `Cap = min(limit, Cap - 1)`. Tally these `Cap` values into your total sum. |
Sorting Bottleneck Pipeline |
Draw an $O(N \log N)$ sorting block, followed by an $O(N)$ linear pass. Total: $O(N \log N)$. |
Multiple copies of the height array for permutation checks. |
In-place sorted array or a single copy (O(N) space). |
| 3302 |
Find the Lexicographically Smallest Valid Sequence |
Brute force all possible 1-character replacements in `word1` and check if `word2` is a subsequence. $O(N \cdot M)$. |
Nested Validation Grid |
Draw the string `word1`. For every index, try changing it to match `word2[j]`. Then run a full $O(M)$ subsequence check. Label as $O(N \cdot M)$. |
Greedy + Suffix Matching Precomputation |
Suffix-Matchability Map |
Precompute a suffix array where `last[i]` is the rightmost index in `word1` that can match `word2[i...]`. Use this to greedily decide whether to use the "one-change" allowance at each index. |
Draw `word1`. Above it, write the precomputed suffix values. As you build the result, check: "If I skip this character, can the remaining suffix still accommodate the rest of word2?" |
Double Linear Pass |
Draw one $O(N)$ pass for suffix precomputation and one $O(N)$ pass for the greedy result. Total: $O(N)$. |
Generating every modified string variation. |
A suffix match array of size M (O(M) space). |
| 3303 |
Find the Occurrence of First Almost Equal Substring |
Slide a window across `s` and count mismatches against `pattern` at every position. $O(N \cdot M)$. |
Sliding Window Mismatch Count |
Draw `s`. Align `pattern` under it at index 0. Compare. Shift by 1. Compare. Show the M comparisons for each of the N shifts. |
Z-Algorithm (Prefix & Suffix Matching) |
Bi-directional Z-Array Projection |
Compute Z-array for `pattern + # + s` to find prefix matches. Compute Z-array for `reversed_pattern + # + reversed_s` to find suffix matches. A match exists if `prefix_len + suffix_len >= pattern_len - 1`. |
Draw the Z-array as a series of bar charts over the string. At index i, look at the prefix bar and the suffix bar for the window. If their combined length covers the pattern (minus one mismatch), you found it. |
Linearized Z-Algorithm Pipeline |
Draw two blocks for $O(N+M)$ Z-array computations. Draw a final $O(N)$ pass to combine results. Total: $O(N + M)$. |
Nested loops creating many substring slices. |
Two Z-arrays of size N+M (O(N + M) space). |
| 3304 |
Find the K-th Character in String Game I |
Simulate exactly: start with "a", shift characters, append, repeat until length >= K. |
Exponential String Doubling Tree |
Write "a". Draw an arrow to "ab". Draw arrows from "ab" to "abbc". The width doubles every line, visualizing $O(K)$ space and time. |
Bit Manipulation (Popcount) / Math |
Binary Representation Grid |
Convert K-1 to binary. Count the set bits (1s). Add that count to the character 'a'. |
Write the number K-1. Divide by 2 repeatedly to build binary. Circle every '1'. Count the circles to find the character offset. |
Logarithmic Shrinking Block |
Draw a long bar of length K. Cut it in half, then half again, until reaching 1. This shows the $O(\log K)$ reduction. |
A dynamically expanding array that doubles in size repeatedly, eating $O(K)$ memory. |
A single 32-bit register block showing 0s and 1s. Represents strictly $O(1)$ space. |
| 3305 |
Count of Substrings Containing Every Vowel and K Consonants I |
Generate all possible $O(N^2)$ substrings, iterate through each to count vowels and consonants. |
Substring Triangle Grid |
Draw an N x N matrix (start index vs end index). Fill half of it with counts, showing the $O(N^3)$ total work. |
Sliding Window (atLeast(k) - atLeast(k+1)) |
Caterpillar / Expanding-Shrinking Window |
Use left and right pointers. Expand right to collect chars. When condition is met, shrink left. Subtract results of k+1 from k. |
Draw the string. Use physical brackets [ and ] for pointers. Keep a tally box of 'a,e,i,o,u' and 'consonants' that updates as brackets move. |
Two Pointers Racing in 1D |
Draw a line for the array. Draw a 'left' arrow and 'right' arrow. Move both exclusively to the right to prove $O(N)$ max steps. |
Temporary string slices or loop iteration variables (O(1) space). |
A small Hash Map/Frequency Array with exactly 5 slots for vowels and 1 integer tally for consonants (O(1) space). |
| 3306 |
Count of Substrings Containing Every Vowel and K Consonants II |
Generate all possible substrings, manually count vowels and consonants for each one. |
Start-End Matrix Grid |
Draw an N x N grid (start vs end index). Fill every cell with the tally of vowels/consonants. This visually proves $O(N^3)$ or $O(N^2)$ work. |
Sliding Window: exact(k) = atLeast(k) - atLeast(k+1) |
Expanding & Shrinking Brackets |
Expand right pointer until valid. Shrink left pointer to count minimum valid windows. Subtract the result of `atLeast(k+1)` from `atLeast(k)`. |
Draw the string. Place physical brackets [ ] representing pointers. Keep a tally box for a,e,i,o,u and consonants. Shift brackets and update the tally. |
Double Pointer Linear Track |
Draw a single straight line (N). Draw L and R arrows. Move them exclusively rightward. They traverse the line at most twice, proving $O(N)$. |
Creating thousands of temporary string variables or slices in memory. |
A 5-slot Hash Map/Array for vowels and a single integer counter for consonants (O(1) space). |
| 3307 |
Find the K-th Character in String Game II |
Simulate the exact game rules: copy the string, apply operations, concatenate, until length hits K. |
Exponential String Doubling |
Write the base string. Draw a line to the next string (twice as long). Repeat. Visually map the massive memory explosion to $O(K)$. |
Recursion / Divide and Conquer |
Binary Search Tree Shrinking |
Find the nearest power of 2 >= K. Check if K falls in the first half or second half. If second, map K to its original position in the first half and apply the operation rule. |
Draw a long bar for length N. Cut it in half. Mark where K sits. If it's on the right, draw an arrow mapping it to the left half. Repeat until size is 1. |
Logarithmic Depth Bar |
Draw a bar of length K. Halve it, then halve it again. Count the number of cuts to prove $O(\log K)$ time complexity. |
A continuously re-allocated string array that eats $O(K)$ memory. |
A deep vertical stack of activation records (call stack) representing $O(\log K)$ space. |
| 3308 |
Find Top Performing Driver (SQL) |
(Imperative conceptualization) Nested loops iterating over every Trip, Vehicle, and Driver to match IDs and calculate. |
Nested Table Iteration |
Draw three distinct tables. Draw spaghetti lines connecting every row in Trips to every row in Vehicles, visualizing $O(N \cdot M)$ cross-joins. |
SQL JOINs + Window Functions (RANK) |
Relational Data Pipeline Flowchart |
Join on IDs. Group by fuel_type and driver. Compute AVG rating. Partition by fuel_type and apply RANK() ordered by rating DESC. Filter rank = 1. |
Draw three small blocks. Draw funnels merging them (JOIN). Draw a bucket (GROUP BY). Draw a sorted list inside the bucket (RANK). Pick the top item. |
Sort-Merge Join / Hash Join Track |
Draw unsorted data blocks, an arrow pointing to a Hash Table, and an arrow to a Sorted Block showing $O(N \log N)$ grouping and ranking. |
Loading all tables entirely into raw memory (Cartesian Product visualization). |
Intermediate temporary tables and Hash maps used by the DB engine for the partitions. |
| 3309 |
Maximum Possible Number by Binary Concatenation |
Generate all permutations of the given numbers, concatenate their binary strings, convert back to decimal, and find the max. |
Permutation Branching Tree |
Draw 3 root branches, splitting into 2, then 1. Write the concatenated binary result at the 6 leaf nodes. |
Custom Greedy Sorting |
Binary Block Swap Comparisons |
Convert numbers to binary strings. Sort them using a custom comparator: Compare (A + B) against (B + A). Concatenate the fully sorted array. |
Write binary for A and B in boxes. Place A before B. Below it, place B before A. Circle the combination that forms the larger binary value. |
Constant Time Scale (O(1)) |
Since there are strictly 3 numbers, draw exactly 3 balance scales representing the constant $O(1)$ number of comparisons required. |
Building and storing all 6 combined string permutations in memory simultaneously. |
$O(1)$ space. Merely swapping references or shifting bits in a 3-element array. |
| 3310 |
Remove Methods From Project |
Start at the suspicious method, recursively find all calls. Check if ANY external method calls ANY suspicious method by looping blindly. |
Exhaustive Spaghetti Traversal |
Draw circles (methods). Draw arrows (calls). For every non-suspicious circle, trace its entire path to see if it ever hits a suspicious one. |
Graph Traversal (DFS/BFS) + Reachability |
Graph Coloring / Flood Fill |
Run DFS from the target method. Color all reachable nodes "Red". Iterate over all given edges: if a "White" node points to a "Red" node, removal is invalid. |
Draw a directed graph. Take a red pen and shade the connected component from the target. Then, scan arrows. If an uncolored node points into the red blob, draw a big X. |
Edge List Linear Scan |
Draw the Adjacency List. Draw one single line through the graph for DFS $O(V+E)$. Draw one line through the edge list $O(E)$. |
Unbounded recursive call stack without a visited set, leading to stack overflow. |
A `visited` Boolean Array of size V, neatly storing state in exactly $O(V)$ space. |
| 3311 |
Construct 2D Grid Matching Graph Layout |
Backtracking to test every possible permutation of nodes into a 2D matrix until adjacencies match edges. |
Permutation Tree |
Draw a root node splitting into N branches, which split into N-1 branches. The massive width visualizes the $O(N!)$ time complexity. |
Graph Degree Analysis + BFS |
Node-Degree Puzzle Pieces |
Count edges per node. Corners have degree 2, edges 3, inner nodes 4. Place a corner at (0,0), then use BFS to place its neighbors, filling row by row. |
Draw nodes as jigsaw puzzle pieces with 2, 3, or 4 pegs. Physically align the 2-peg pieces in the corners and fill inward using the connections. |
Linear Graph Traversal Line |
Draw the V nodes and E edges. Trace a single highlighter line through them exactly once to prove $O(V + E)$ complexity. |
A very deep recursive call stack holding grid state arrays, eating massive memory. |
A standard Queue for BFS and a flat 1D "visited" array (O(V) space). |
| 3312 |
Sorted GCD Pair Queries |
Iterate all N^2 pairs, compute GCD for each, store in an array, sort the array, and answer queries. |
Complete Graph Edge Matrix |
Draw N points. Draw lines connecting every single point to every other point. Write the GCD on each line. Visualizes $O(N^2 \log N)$. |
Divisor Counting + Inclusion-Exclusion |
Overlapping Frequency Buckets |
Count multiples of `x`. Pairs with `x` as a common divisor = `count * (count-1) / 2`. Subtract pairs where GCD is `2x, 3x...` to get exact GCD counts. Prefix sum for queries. |
Draw overlapping Venn diagrams. One circle is "Divisible by 2", another "Divisible by 4". Subtract the inner circle to find exactly GCD=2. |
Harmonic Series Bar Chart |
Draw bars of decreasing height: N/1, N/2, N/3... The area under these bars visually sums to $O(N \log N)$. |
A massive array storing $O(N^2)$ integers simultaneously before sorting. |
A frequency array of size M (where M is the maximum value in the input) and a prefix sum array. $O(M)$ space. |
| 3313 |
Find the Last Marked Nodes in Tree |
Run a full BFS/DFS starting from every single node in the tree to find its farthest target. |
Expanding Multi-Ripples |
Draw the tree N times. On each copy, pick a different start node and draw expanding concentric circles to find the last node. $O(N^2)$. |
Tree Diameter Endpoints (2/3 DFS Passes) |
Two-Pole Magnetic Anchors |
Find the tree's diameter endpoints (A and B). For ANY node in the tree, the farthest node (last marked) will ALWAYS be either A or B. |
Draw a messy tree. Find the two absolute extremes and mark them A and B. Pick any random node and draw lines to A and B; one of them is the answer. |
Parallel Traversal Timelines |
Draw 3 horizontal lines stacked vertically. Each represents one $O(N)$ DFS pass (Find A, Find B, Calculate Distances). |
N separate queue structures initialized and destroyed repeatedly over time. |
Two static 1D integer arrays of size N, storing distances from endpoint A and endpoint B. |
| 3314 |
Construct the Minimum Bitwise Array I |
Loop `x` from 0 to `p`. For each, check if `x OR (x+1) == p`. Return the first one that matches. |
Linear Trial-and-Error Track |
Write the target prime `p`. Below it, write 0, 1, 2, 3 in binary. Manually perform the OR operation line by line until you find the match. |
Bit Manipulation (Flipping Trailing Ones) |
Binary Bit-Flip Timeline |
Odd primes end in a sequence of 1s in binary. `x OR (x+1)` turns the lowest 0 into a 1. To reverse this, find the highest trailing 1 in `p` and flip it to 0. |
Write the prime `p` in binary. Box the block of 1s at the far right. Cross out the leftmost '1' in that box and write a '0'. Convert back to decimal. |
Constant Time Box |
Draw a single square box. Inside write `O(1)`. No matter how large the number, the math calculation takes one step. |
A standard loop counter variable in the stack. |
A single integer in a CPU register (O(1) auxiliary space). |
| 3315 |
Construct the Minimum Bitwise Array II |
Same as 3314, but because constraints are massive, the linear loop will result in Time Limit Exceeded (TLE). |
Infinite Loop Track |
Draw a timeline line that extends off the page and into the distance, representing a loop that takes too long to finish. |
Bitwise Shift & Subtract |
Bitmask Isolation Diagram |
Count the trailing ones algebraically (e.g., using `~p & (p+1)` logic to find the flip bit). Subtract exactly that power of 2: `p - (1 << (trailing_ones - 1))`. |
Write the large prime in binary. Below it, write a binary mask that has a '1' only at the highest trailing one's position. Draw a minus sign and subtract them. |
Single Math Operation Node |
Draw one circle containing the bitwise subtraction formula. This emphasizes that large constraints don't change the $O(1)$ time. |
Large iterative states attempting to count up to 10^9. |
A 64-bit integer (Long) register, strictly requiring $O(1)$ space. |
| 3316 |
Find Maximum Removals From Source String |
Generate all 2^M subsets of target removal indices, apply them, and check if the pattern is still a subsequence. |
Binary Inclusion/Exclusion Tree |
Draw a root node. For every target index, branch left (keep) and right (remove). The bottom row has 2^M leaf nodes. |
2D Dynamic Programming (Source Idx vs Pattern Idx) |
2D Grid Matrix Transition |
`dp[i][j]` tracks max removals using `source[i:]` matching `pattern[j:]`. If characters match, take the diagonal. If `i` is a target, try adding 1 to the score and moving right. |
Draw a grid: Source string on the top (columns), Pattern on the left (rows). Draw diagonal arrows for matches, and horizontal arrows for skips/removals, writing the max score in the box. |
Area of a Rectangle |
Draw a box with width N (source length) and height M (pattern length). Shading the entire box proves the $O(N \cdot M)$ time complexity. |
Deep recursive call stack branching exponentially, holding full string copies. |
A clean 2D integer array (or two 1D rows for space optimization) taking exactly $O(N \cdot M)$ memory. |
| 3317 |
Find the Number of Possible Ways for an Event |
Try every possible assignment of N people to X events, then assign Y possible scores to every used event. |
Bipartite Spaghetti Mapping |
Draw N dots (people) and X dots (events). Draw chaotic crossing lines assigning every person to an event, visualizing $O(X^N)$. |
Math / Combinatorics (Stirling Numbers of the Second Kind) |
Bucket Grouping Pipelines |
Iterate `k` (number of active events from 1 to X). Ways = (Stirling2(N, k)) * (Permutations(X, k)) * Y^k. |
Draw N stick figures. Draw `k` empty buckets. Draw an arrow dropping figures into buckets (Stirling). Multiply by how you label the buckets (Permutation), multiply by a score multiplier box (Y). |
1D Iteration Bar |
Draw a single straight line from 1 to X. Since the combinatorial math takes constant or linear time per step, the line proves $O(X)$ or $O(N\cdot X)$ time. |
Massive recursive tree tracking who is assigned to which event in $O(N)$ depth. |
A 2D DP table to precompute Stirling numbers taking $O(N^2)$ space, plus a few $O(1)$ integer variables. |
| 3318 |
Find X-Sum of All K-Long Subarrays I |
For each window of size K, extract all elements, count frequencies, sort the elements by frequency/value, and sum the top X. |
Redrawing Histograms |
Draw the array. Bracket a window. Below it, draw a bar chart of frequencies. Move the bracket 1 step, erase the whole chart, and redraw it from scratch. $O(N \cdot K \log K)$. |
Sliding Window + Ordered Set / Hash Map |
Frequency Shift & Balance Scales |
Maintain a frequency map. As the window slides, add the new element, remove the old one. Update the top X sum dynamically. |
Draw the array with a sliding bracket [ ]. Below, draw a Hash Map box. When sliding, draw a "+1" arrow for the incoming char and "-1" for outgoing. Maintain a small "Top X" VIP list next to it. |
Rolling Wheel Timeline |
Draw a long road (the array). Draw a wheel rolling over it. The wheel never stops or goes backward, representing the smooth $O(N \log K)$ transition. |
Creating and destroying an array of size K, plus a sorting stack, over and over. |
A static Hash Map of frequencies and a balanced BST (like `std::set` or TreeMap) taking exactly $O(K)$ space. |
| 3319 |
K-th Largest Perfect Subtree Size in Binary Tree |
At every single node, run a full DFS downward to check if all left/right branches form a perfect tree. $O(N^2)$. |
Overlapping Triangle Scans |
Draw a large tree. Pick the root, trace a huge triangle over it. Pick a child, trace another triangle inside it. The heavy overlapping ink shows redundant $O(N^2)$ work. |
Bottom-Up DFS (Post-order Traversal) |
Bubbling Up Information Data-Packets |
Process children first. A node is perfect if: Left is perfect, Right is perfect, and Left Height == Right Height. Pass `(isPerfect, height)` up to the parent. |
Draw a tree. Start at the bottom leaves. Write `(True, 1)` next to them. Draw arrows pointing UP to their parents. Combine the pairs at the parent to form `(True, 2)`. |
Single-Pass Node Highlighting |
Draw the tree once. Take a marker and touch every node exactly one time from bottom to top, visualizing strict $O(N)$ time. |
$O(N)$ recursive call stack combined with repeated $O(N)$ inner-call stacks. |
$O(H)$ recursion stack for the tree height, plus a Min-Heap array of size K to track the largest sizes. |
| 3320 |
Count The Number of Winning Sequences |
Generate all 3^N combinations of Rock, Paper, Scissors for Bob, check consecutive rules, and tally points. |
Ternary (3-Way) Branching Tree |
Draw a starting node. Branch out 3 ways (R, P, S). From each of those, branch 3 ways again. The massive explosion visualizes $O(3^N)$. |
3D Dynamic Programming (Index, Last Move, Score Diff) |
3D Floating Cube Matrix |
`dp[i][last_move][score_diff]`. For step `i`, try moves that aren't `last_move`. Calculate points against Alice. Add to the new `score_diff` state. |
Draw a timeline representing `i`. At a specific `i`, draw 3 buckets (Rock, Paper, Scissors). Inside each bucket, draw a number line (the score difference from -N to +N) and track the counts moving between buckets as `i` advances. |
Rectangular Prism Area |
Draw a 3D box. Length is N (turns), Width is 3 (moves), Height is 2N (score span). The total volume is exactly $O(N^2)$. |
Recursive stack depth of N, holding string builders for every generated sequence. |
Two rotating 2D arrays (current state and next state) sized `3 x (2N+1)`, strictly using $O(N)$ memory to avoid 3D allocation. |
| 3321 |
Find X-Sum of All K-Long Subarrays II |
For every window of size K, count all frequencies, completely sort the unique elements by frequency/value, and sum the top X. |
Redrawing Histograms |
Draw the array. Bracket a window. Below it, draw a bar chart of frequencies. Move the bracket 1 step, erase the whole chart, and completely redraw it. Visually proves $O(N \cdot K \log K)$. |
Sliding Window + Two Balanced BSTs (Heaps) |
The "VIP Room" and "Waiting Area" |
Maintain a "Top X" Set (VIP) and a "Rest" Set (Waiting). As the window slides, update frequencies. If a Waiting element beats a VIP element, swap them and update a running sum. |
Draw two boxes: VIP (max size X) and Waiting. When sliding the window, erase/update tally marks. Draw physical arrows swapping numbers between the two boxes based on the new tallies. |
Dual Logarithmic Balancing |
Draw a smooth line for the $O(N)$ sliding window. At each step, draw two small tree structures showing the $O(\log N)$ rebalancing act. |
Creating, populating, sorting, and destroying an array of size K for every single window shift. |
Two `SortedList` or `TreeSet` structures mapping `(frequency, value)` strictly bounding $O(N)$ memory. |
| 3322 |
Premier League Table Ranking III (SQL) |
(Imperative conceptualization) Use nested loops to compare every team against every other team to calculate their relative standings. |
Cartesian Product Spaghetti |
Draw the table of teams twice. Draw lines connecting every row on the left to every row on the right, showing $O(N^2)$ cross-comparisons. |
SQL Window Functions (RANK / DENSE_RANK) |
Partitioned Sorting Buckets |
Partition data by a specific column. Within that partition, sort by points DESC. Assign sequential ranks 1, 2, 3... to the sorted rows. |
Draw several separate "buckets" (partitions). Write team names inside them. Physically rewrite the list inside the bucket in descending order and number them 1 to N. |
Hash Partition & Sort Pipeline |
Draw unsorted data flowing into separate buckets (O(N) Hash Partitioning), then draw an internal sorting diagram for each bucket (O(K log K)). |
$O(N^2)$ cross-joined temporary tables eating up database memory before filtering. |
$O(N)$ sequential blocks of memory allocated for the partitions by the database engine. |
| 3323 |
Minimize Connected Groups by Inserting Interval |
Try inserting the new interval starting at every single coordinate point. Recalculate overlapping groups from scratch every time. |
Exhaustive Placement Timeline |
Draw a number line with existing intervals. Draw your new interval at position 0, count groups. Erase it, draw it at position 1, count groups. Very slow $O(N^2)$. |
Merge Intervals + Binary Search |
Bridging the Gaps (The Ruler Method) |
Merge all overlapping intervals first. For each merged interval's end point `e`, use binary search to find the furthest interval that starts before `e + k + 1`. |
Draw the merged intervals as solid blocks. Create a physical paper "ruler" of length `k`. Place the start of the ruler at the end of a block. Count how many other blocks the ruler covers. |
Logarithmic Jump Arrows |
Draw an array of starting positions. From an endpoint, draw one sweeping arrow directly landing on the target index, proving $O(\log N)$ search time. |
Deep iteration stacks and temporary array allocations for every theoretical interval placement. |
A single, neatly compacted 2D array of merged intervals taking $O(N)$ space. |
| 3324 |
Find the Sequence of Strings Appeared on the Screen |
Strictly simulate key presses, appending strings and looping blindly until strings match. |
Typewriter Ribbon Simulation |
Write the target word. Below it, write 'a'. Erase it, write 'b'. Keep erasing and re-writing the very last character until you get the final word. |
Prefix Expansion / Direct String Construction |
Staircase Construction |
Iterate through the target string. For each character, start at 'a' and increment up to the target character, appending the current prefix to the result list each time. |
Write the target word. In a column below, write 'a'. Next row, write the prefix + 'a', then prefix + 'b'. The shape will look like a staircase stepping down. |
Bounded Linear Grid |
Draw an N (length) by 26 (alphabet) grid. You only ever trace downwards and rightwards through this grid, proving $O(26 \cdot N)$ -> $O(N)$ complexity. |
A massive array holding strings that are constantly being reallocated and copied under the hood. |
An array of strings collecting exactly the intermediate steps, taking $O(N^2)$ total characters in memory. |
| 3325 |
Count Substrings With K-Frequency Characters I |
Generate all possible $O(N^2)$ substrings. Scan each one individually to see if any character count is >= K. |
Substring Triangle Cross-out |
Write every single substring combo in a pyramid shape. Manually count the chars in every single word and cross out the invalid ones. $O(N^3)$ total work. |
Sliding Window (Monotonic Property) |
Expanding Right, Trailing Left (Caterpillar) |
Expand `r` to add characters. When ANY char hits frequency `k`, the window is valid. Because it's valid, ALL substrings ending at `r` and starting anywhere up to `l` are also valid. Shrink `l` to find the bound. |
Draw the string. Place [ and ] brackets. When a letter hits count `k`, draw arrows from index 0 pointing to your left bracket. The number of arrows is the number of valid substrings you just found. |
Parallel Pointer Tracks |
Draw a line. Draw an 'r' arrow moving right. Draw an 'l' arrow trailing behind it. Since neither ever moves left, it proves strict $O(N)$ time. |
$O(1)$ space, but $O(N)$ time spent constantly slicing identical substrings into memory just to read them. |
A Hash Map or a flat integer array of size 26, requiring strictly $O(1)$ space to maintain window state. |
| 3326 |
Minimum Division Operations to Make Array Non Decreasing |
From left to right, try dividing every number by all of its proper divisors recursively to find a valid non-decreasing sequence. |
Exponential Divisor Tree |
Draw an array. Under a number like 24, branch out to 12, 8, 6, 4, etc. Branch out again from those. The massive tree visualizes $O(K^N)$. |
Greedy Traversal (Right-to-Left) + Smallest Prime Factor (SPF) |
Reverse Array Waterfall |
Precompute SPFs using a Sieve. Traverse right-to-left. If `nums[i] > nums[i+1]`, directly replace `nums[i]` with its SPF (which mathematically equals its original value divided by its Largest Proper Divisor). |
Draw the array. Draw a Left-pointing arrow starting at the end. When a number is too big, draw a "zap" replacing it with its pre-calculated SPF. If it's still too big, draw a big red X (return -1). |
Two Parallel Timelines |
Draw a block for the $O(M \log \log M)$ Sieve precomputation. Next to it, draw a single straight line of length N representing the $O(N)$ array traversal. |
Deep recursive stacks branching out on every divisor iteration. |
A 1D integer array `lpf` up to 10^6 acting as an $O(M)$ lookup table, plus $O(1)$ auxiliary variables for the traversal. |
| 3327 |
Check if DFS Strings Are Palindromes |
Run a full DFS from every single node, construct its specific string, and manually run a two-pointer palindrome check. |
Redundant String Building |
Draw the tree N times. Extract N different strings. Draw crossing arrows on each string to check if it's a palindrome. Visualizes $O(N^2)$ work. |
DFS Tree Flattening + Manacher's Algorithm |
1D Array Expansion Bubbles |
Run DFS once to flatten the tree into a single string, recording the start/end index of each subtree. Run Manacher's Algorithm to precompute palindrome radii in $O(N)$. Check if a node's boundaries fit within the radius. |
Draw the tree. Below it, draw a straight 1D array representing the flattened DFS string. Draw brackets denoting a node's boundaries. Draw a "Manacher radius" expanding from the center of those brackets. |
Linear Contiguous Track |
Draw the flattened string of length 2N (with delimiters). Sweep one arrow across it from left to right, representing the strict $O(N)$ linear time of Manacher's. |
Thousands of fragmented, duplicated string objects existing in memory simultaneously. |
Three flat 1D arrays of size N (start indices, end indices, Manacher radii) representing tightly packed $O(N)$ memory. |
| 3328 |
Find Cities in Each State II (SQL) |
(Imperative conceptualization) Nested loops running through the entire database repeatedly to group states and check prefixes. |
Cartesian Product Spaghetti |
Draw the raw table twice. Draw chaotic lines connecting every state to every city row, visualizing $O(N^2)$ unoptimized scanning. |
SQL GROUP BY + String Aggregation + HAVING |
Hash Partitioning Buckets |
Group data by state into buckets. Inside each bucket, sort cities, concatenate them, and sum up a boolean condition `(LEFT(city, 1) == LEFT(state, 1))`. Filter via HAVING. |
Draw a big funnel splitting data into labeled State buckets. Inside a bucket, draw a list of cities getting chained together into one long string. Keep a tally mark for prefix matches. |
Hash Pipeline Diagram |
Draw scattered data mapping directly into $O(N)$ hash groups, followed by an $O(K \log K)$ internal sort per group for the concatenation ordering. |
Full raw table loaded into cross-joined temporary database memory blocks. |
Temporary sorted partition spaces handled by the DB execution engine, taking strictly $O(N)$ overall space. |
| 3329 |
Count Substrings With K-Frequency Characters II |
Generate all $O(N^2)$ substrings. Build a frequency map for every single one to check if any char hits count K. |
Substring Triangle Grid |
Draw an N x N matrix. Every cell is a substring. Inside every cell, draw a mini frequency table. Visualizes massive $O(N^3)$ overlapping work. |
Sliding Window (Expanding Right, Shrinking Left) |
Caterpillar with a Trailing Anchor |
Expand right pointer `r`. Track frequencies. When ANY char hits count `k`, it means the window is valid. Because it's valid, ALL substrings ending at `r` and starting anywhere from `0` to `l` are valid. Add `l` to the answer. Shrink `l`. |
Draw the string with [ and ] brackets. When a letter hits `k`, draw a long bracket from index 0 all the way to `l`. That bracket represents a "batch" of answers you just found instantly without counting them 1-by-1. |
Parallel Traversal Arrows |
Draw a horizontal line. Draw `r` moving right. Draw `l` moving right. Neither pointer ever moves backwards, proving $O(N)$ time complexity. |
$O(1)$ space, but $O(N)$ time spent constantly slicing identical strings into memory just to read them. |
A static Hash Map or a flat integer array of size 26, requiring strictly $O(1)$ space to maintain window state. |
| 3330 |
Find the Original Typed String I |
Generate every possible combination of string compressions for repeating characters and count the unique results. |
Permutation Branching Tree |
Write the string. At every duplicated character, draw a fork in the road: one branch deletes it, one keeps it. Tree explodes exponentially. |
Linear Scan / Adjacent Identical Pairs Math |
Connected Character Chain Links |
Since Alice made at most ONE mistake, each pair of adjacent identical characters adds exactly one alternative possibility. The answer is simply `1 + count(adjacent identical pairs)`. |
Write the string out. Take a pen and draw a little physical "link" bridge between any two adjacent letters that are the same. Count the links. Add 1. |
Single-Pass Array Scan |
Draw an array of length N. Draw a simple arrow jumping from index `i-1` to `i`, proving strict $O(N)$ time. |
Thousands of generated substring variants dumped into a Hash Set to check for uniqueness. |
A single integer counter keeping a running tally (Strictly $O(1)$ auxiliary space). |
| 3331 |
Find Subtree Sizes After Changes |
For every node, physically rebuild the tree by scanning upwards for the closest matching character, then run a size calculation. $O(N^2)$. |
Dynamic Re-linking Web |
Draw a tree. Rip a node off, scan up to the root to find a match, and glue it back. Repeat for all nodes. |
DFS + Ancestor Hash Map |
The Virtual Re-Parenting Trace |
Do a single DFS. Keep an array/map of the "last seen node" for each of the 26 characters. When visiting a node, check the map for its character. That is its *new* parent. Add the current node's size to the new parent's size upon return. |
Draw the tree. As you walk down, drop colored breadcrumbs (one for each letter). When a node looks up, it grabs the most recent breadcrumb of its own color. |
Single Tree Traversal $O(N)$ |
Draw a single trace down and up the tree. Updating the 26-size map is $O(1)$. |
Deep recursive stack building physical new tree nodes. |
A map/array of size 26 and a sizes array. $O(N)$ space. |
| 3332 |
Maximum Points Tourist Can Earn |
Explore all 2^K paths (stay or move to any city every day). $O(N^K)$. |
Exponential Travel Graph |
Draw City 1. Branch to all N cities for Day 1. Branch again for Day 2. |
2D Dynamic Programming |
The City-Day Value Grid |
`dp[day][city]` is the max score ending at `city` on `day`. For the next day, you can either stay (add `stay[city]`) or travel from `prev_city` to `city` (add `travel[prev_city][city]`). |
Draw a matrix (Cities x Days). To fill Day 2 for City A, look at Day 1 for City A (stay) and Day 1 for all other Cities (travel). Take the max. |
State Transition $O(K \cdot N^2)$ |
Draw the matrix. Each cell takes a loop of size N to compute. |
Massive recursion tracking every path. |
A 2D DP table (or two 1D rows for space opt). $O(N)$ space. |
| 3333 |
Find the Original Typed String II |
Generate every possible string variation and count them. $O(\text{Exponential})$. |
Variation Generation Tree |
Draw the string. At every repeated character, branch out for all possible typing lengths. |
DP + Sliding Window (Prefix Sums) |
The Bounded Knapsack Scanner |
Compress consecutive same chars into "blocks". We need to pick 1 to `length` chars from each block such that total length >= K. Use DP with a sliding window to optimize the transition to $O(1)$. |
Draw blocks of numbers. Use a DP array to track "ways to reach length L". To update the next block, use a sliding window over the previous DP row to sum up valid combinations instantly. |
Sliding Window DP $O(\text{Blocks} \cdot K)$ |
Draw a grid. A window slides across the previous row to calculate the current cell in $O(1)$. |
Storing all string variations. |
A 1D DP array of size K. $O(K)$ space. |
| 3334 |
Find the Maximum Factor Score of Array |
For every element, remove it, loop through the rest to find the GCD, loop again for LCM. $O(N^2)$. |
Quadratic GCD/LCM Scanning |
Draw the array. Remove index 0, scan the rest. Remove index 1, scan the rest. |
Prefix & Suffix Arrays |
The Precomputed Bounds |
Precompute Prefix GCD/LCM and Suffix GCD/LCM arrays. To find the score without `nums[i]`, just combine `Prefix[i-1]` and `Suffix[i+1]` in $O(1)$ time. |
Draw the array. Draw a row above it accumulating GCD left-to-right. Draw a row below accumulating right-to-left. To "delete" index 2, just combine the box at top-index 1 and bottom-index 3. |
Three Linear Passes $O(N)$ |
Draw three parallel horizontal lines. Two for precomputation, one for the final check. |
Recalculating math functions infinitely. |
Four arrays of size N (Pref/Suff for GCD/LCM). $O(N)$ space. |
| 3335 |
Total Characters in String After Transformations I |
Generate the massive string by actually replacing 'z' with 'ab' repeatedly. $O(2^T)$. |
String Explosion Simulator |
Draw the string. After 50 transformations, the string is billions of characters long and crashes memory. |
Frequency Array / Matrix Exponentiation |
The 26-Bucket Shift |
Keep an array of size 26 for frequencies. In each step, everything shifts right. The value at 'z' goes to 'a' AND gets added to 'b'. Loop this T times. |
Draw 26 buckets. Pick up the contents, move them one bucket right. Take the 'z' bucket, dump it into 'a', and also dump a copy into 'b'. |
Fixed Size Simulation $O(T \cdot 26)$ |
Draw a loop running T times, updating a tiny, fixed 26-element array. |
Massive string allocations. |
Two arrays of size 26. $O(1)$ space. |
| 3336 |
Find the Number of Subsequences With Equal GCD |
Generate all possible pairs of subsequences (S_1, S_2) and compute GCD for each to check equality. |
Dual Subset Power Set |
Draw two separate power set trees. Draw lines connecting every leaf in Tree A to every leaf in Tree B. Proves $O(2^N \cdot 2^N)$ impossibility. |
3D Dynamic Programming |
Layered GCD Slices |
`dp[i][g1][g2]` tracks ways to form two subsequences with GCDs `g1` and `g2` using elements up to `i`. |
Draw a 3D cube. Each horizontal slice is an element index. Each cell in the slice represents a coordinate (g1, g2). Draw arrows "falling" from the previous slice to the current one as you include or skip numbers. |
State-Space Volume |
Draw a box with dimensions N x 100 x 100. The total volume represents the $O(N \\text{cdot MaxGCD}^2)$ complexity. |
Two massive lists of all subsequence GCDs stored in memory simultaneously. |
A 2D integer array (using space optimization to discard the `i` dimension), size 101 x 101. |
| 3337 |
Total Characters in String After Transformations II |
Simulate each of the T transformations by replacing every character with its nums[i] successors. |
Exponential String Growth |
Write "a". Draw nums[0] arrows to new letters. Repeat T times. The paper fills up instantly, showing $O(\text{Length} \cdot 2^T)$. |
Matrix Exponentiation |
Character Transition Graph |
Build a 26 x 26 adjacency matrix where M[i][j]=1 if char i transforms into char j. Compute M^T using binary exponentiation. |
Draw 26 dots in a circle. Draw arrows showing char transitions. Then draw the 26 x 26 grid. Shade the cells that have a '1'. Highlight the squaring process (M^2, M^4, M^8). |
Logarithmic Step Timeline |
Draw a line of length T. Mark only the powers of 2 (1, 2, 4, 8...). The few marks prove $O(26^3 \log T)$ efficiency. |
Gigabytes of string data expanding and being re-allocated in the heap. |
A single 26 x 26 integer matrix (strictly constant auxiliary space $O(1)$ relative to T). |
| 3338 |
Second Highest Salary II (SQL) |
For each department, select distinct salaries, sort them, and pick the second one via nested subqueries. |
Nested Loop Scanning |
Draw the table. For Row 1, scan the whole table to find higher salaries. Repeat for all rows. $O(N^2)$. |
Window Functions (DENSE_RANK) |
Partitioned Ranking Buckets |
Group by Department. Sort salaries DESC. Assign `DENSE_RANK()`. Filter where rank is 2. |
Draw horizontal "Buckets" for each Dept. Write salaries inside. Draw a number next to each (1, 2, 2, 3) based on the rank. Circle all the '2's. |
Hash + Sort Pipeline |
Draw an $O(N)$ grouping arrow into buckets, followed by an $O(K \log K)$ sort line inside each bucket. |
Temporary tables containing Cartesian products of departments and salaries. |
$O(N)$ memory used for the sorting window buffer by the database engine. |
| 3339 |
Find the Number of K-Even Arrays |
Generate all M^N possible arrays and count how many satisfy the k-even condition. |
M-ary Search Tree |
Draw a root. Branch M ways. From each, branch M ways again. The total leaf count is M^N, visualizing the brute force wall. |
DP (Index, Remaining K, Last Parity) |
State Transition Ribbon |
`dp[i][j][parity]` = ways to fill i slots with j pairs left, ending in even/odd. Multiply by `cntEven` or `cntOdd`. |
Draw a grid: columns are 1 dots N, rows are 0 dots K. Each cell has two sub-boxes (Even/Odd). Draw arrows from (i-1, j) and (i-1, j-1) into the current cell. |
Bounded Grid Area |
Draw an N x K rectangle. Shading it shows $O(N \cdot K)$ work, where M is just a constant multiplier. |
An array of all M^N generated arrays in memory. |
A 3D DP table (or two 2D layers) of size K x 2 (strictly $O(N \cdot K)$). |
| 3340 |
Check Balanced String |
Split the string into two separate lists (even/odd indices), sum each list, and compare. |
Two-Pass List Splitting |
Write the string. Below it, write two new strings. Sum both. Proves $O(N)$ but with extra $O(N)$ space. |
One-Pass Parity Tally |
Alternating Balance Scale |
Initialize `balance = 0`. Iterate through the string. If index is even, add digit; if odd, subtract. Check if `balance == 0`. |
Draw a balance scale. For every number you read, draw a weight on the left (even) or right (odd) side. See if the scale stays level at the end. |
Single-Pass Linear Arrow |
Draw a single straight line through the string length N. No branching, no jumping. Strict $O(N)$. |
Two newly allocated list objects taking $O(N)$ space. |
Exactly two integer variables (or one) in the stack. $O(1)$ space. |
| 3341 |
Find Minimum Time to Reach Last Room I |
DFS with backtracking to find all possible paths from (0,0) to (n-1,m-1), tracking the wait time at each room. |
Exploding Path Tree |
Draw a grid. From (0,0), draw arrows to all 4 neighbors. From each neighbor, draw 4 more. The "spaghetti" of paths shows $O(4^N \cdot M)$. |
Dijkstra's Algorithm |
Concentric Ripple Expansion |
Use a Priority Queue to store `(time, r, c)`. Always expand the room with the smallest "arrival time". Arrival time = `max(current_time, move_time) + 1`. |
Draw the grid. Write a number in each cell representing its threshold. Use a highlighter to "shade" cells as they are visited, writing the actual arrival time in a circle. |
Log-Linear Grid Sweep |
Draw the grid area N x M. Inside, draw a small "log" symbol to represent the Heap operations. Proves $O(\text{NM} \log(\text{NM})$). |
Deep recursive stack holding every coordinate of the current path, potentially $O(\text{NM})$ depth but with massive branching. |
A 2D `dist` array of size N x M and a Priority Queue (Min-Heap) holding active "frontiers". |
| 3342 |
Find Minimum Time to Reach Last Room II |
Same as 3341, but try all paths while alternating move costs (1 then 2 then 1...). |
Stateful Path Branching |
Draw the same grid as 3341, but each node in your tree now needs to store a "parity" bit (is the next move 1 or 2?). Doubling the states. |
Modified Dijkstra (State-Space Expansion) |
Bicolor Wavefront |
Dijkstra where the state is `(time, r, c, parity)`. The cost to move depends on the parity of the current move count. |
Draw the grid. Use two different colored pens (e.g., Red for parity 0, Blue for parity 1). When you move from a Red state, the neighbor becomes a Blue state. |
Layered Grid Volume |
Draw two copies of the grid (Layer 0 and Layer 1). Draw arrows jumping between layers. Total volume is 2 x N x M log(NM). |
Recursive stack with extra parity variables for every step. |
A 3D distance array `dist[N][M][2]` to store minimum time for each parity state at each cell. |
| 3343 |
Count Number of Balanced Permutations |
Generate all unique permutations of the digits and check the sum of even vs odd indices. |
Permutation Leaf Counting |
Draw a tree starting with all available digits. Each level picks a digit. Count the valid leaf nodes. $O(N! / (\text{freq of digits}!)$). |
DP + Combinatorics (Digits, Count, Sum) |
Recursive Partitioning Grid |
`dp(digit, even_count, even_sum)`: Number of ways to place `k` instances of `digit` into even/odd slots to reach a target sum. Use combinations (nCr) for ways to arrange. |
Draw a table where rows are digits (0-9) and columns are possible sums. For each digit, draw arrows showing how many you "give" to the even-indexed slots vs odd-indexed slots. |
Bounded State Volume |
Draw a 3D block: 10 (digits) x N/2 (slots) x TotalSum/2. Shading it proves $O(10 \cdot N \\text{cdot Sum})$. |
Storing every generated permutation string in a Hash Set to count unique valid ones. |
A 3D DP table or a memoization map storing calculated states for (index, count, sum). |
| 3344 |
Maximum Sized Array |
Generate all possible combinations of removing N/2 elements from both arrays and calculate the distinct union for each. $O(\text{Exponential})$. |
Combinatorial Deletion Tree |
Draw two arrays. Branch out for every possible combination of crossing out half the numbers. |
Greedy / Set Intersection |
The Venn Diagram Filler |
Find unique elements in A, unique in B, and their intersection. Greedily keep elements unique to A up to N/2, then unique to B up to N/2. Fill any remaining quota from the intersection. |
Draw a Venn Diagram (A, B, Shared). Pick dots from the "A-only" crescent until you hit N/2. Do the same for "B-only". If you still need dots, grab them from the "Shared" middle. |
Hash Set Operations $O(N)$ |
Draw two arrays pouring into three buckets (Unique A, Unique B, Shared). |
Generating thousands of arrays. |
Three Hash Sets. $O(N)$ space. |
| 3345 |
Smallest Divisible Digit Product I |
Check every number starting from n upwards. Calculate its digit product and check divisibility by t. |
Linear Search Sequence |
Write n, n+1, n+2 dots. For each, draw a bubble and calculate d_1 x d_2 dots. Stop when you find a multiple of t. |
Brute Force with Early Exit (Small Constraints) |
Incremental Checker |
Since n is small (up to 100), the gap to the next valid number is very small. A simple loop is sufficient and efficient. |
Draw a number line. At each integer, draw a small calculator box. Show the check failing until one "ticks" green. |
Small Constant Step Line |
Draw a short line of length approx 10 (since digit products change rapidly). Total complexity $O(\text{dist} x \text{digits})$. |
N/A (no heavy data structures). |
$O(1)$ auxiliary space (just a few integer variables for calculation). |
| 3346 |
Maximum Frequency of an Element After Performing Operations I |
For every number in the array, try applying +k to -k, and recount the frequency of every resulting number from scratch. $O(N^2 \cdot K)$. |
Range-Shift Tally Grid |
Draw the array. Pick a number. Try shifting it. Rescan the entire array to see how many match it. Repeat. |
Sliding Window / Sweep Line |
The Overlapping Auras |
Sort the array. For each nums[i], its "reach" is [nums[i]-k, nums[i]+k]. Use a sliding window to find the max number of elements whose reaches overlap at a single point, bounded by the operation limit. |
Draw numbers on a number line. Draw a "cloud" of size 2k around each. Slide a vertical scanner left to right to find the spot where the most clouds overlap. |
Sorting + Sliding Window $O(N \log N)$ |
Draw a sorting tree, followed by a two-pointer sliding window that passes over the array once. |
Frequency maps for every shift. |
Pointers. $O(1)$ auxiliary space. |
| 3347 |
Maximum Frequency of an Element After Performing Operations II |
Same as above but fails due to massive constraint sizes, causing memory/time limits if using raw arrays. |
Memory-Crashing Range Array |
Draw a number line from 1 to 10^9. Try to place +1 and -1 marks on it. Out of memory. |
Coordinate Compression / Sweep Line Map |
The Sparse Timeline Tally |
Use a TreeMap (or sort unique critical points) to track only the exact start [x-k] and end [x+k+1] of overlaps. Sweep through these sparse, critical points to maintain the active overlap count. |
Draw a huge empty number line. Only drop pins at the exact start and end of a cloud. Sweep only from pin to pin, skipping the massive empty spaces in between. |
Map Sorting + Sweep $O(N \log N)$ |
Draw N points plotted into a balanced BST, followed by an $O(N)$ traversal of the tree. |
Massive 10^9 sized arrays. |
A TreeMap/Dictionary of size 3N. $O(N)$ space. |
| 3348 |
Smallest Divisible Digit Product II |
Check every string lexicographically larger than num, calculate its digit product, and check divisibility by t. |
Lexicographical Tree Path |
Draw a tree of all possible numbers. Start from num and follow every right-hand branch. The tree is effectively infinite. |
Greedy + Backtracking + Prime Factorization |
Factor-Filling Slots |
Factorize t into 2s, 3s, 5s, and 7s. Starting from the end of num, try to increment a digit and fill the remaining suffixes with the minimum digits needed to satisfy the remaining factors of t. |
Write num. At a certain digit, change it to something higher. Calculate the "missing" factors. Draw empty slots and fill them with the smallest digits (like 9s then 8s) that cover those factors. |
Depth-Limited Backtrack |
Draw a tree with depth N. Show the search "pruning" early when factors cannot be satisfied. $O(N x \text{const})$. |
N/A. |
A recursive stack of depth N, plus a small frequency array for prime factors of t. |
| 3349 |
Adjacent Increasing Subarrays Detection I |
Check every possible pair of adjacent subarrays of length K and verify if both are strictly increasing. |
Nested Subarray Scan |
Draw the array. Bracket two adjacent windows. Move them one index at a time. For each move, re-verify all 2K elements. $O(N \cdot K)$. |
One-Pass Precomputation |
Increasing Block Counter |
Calculate the length of the increasing sequence ending at each index. Then check if inc[i] >= K and inc[i+K] >= K. |
Draw the array. Above it, write the length of the "increasing streak" so far (e.g., 1, 2, 3, 1, 2). To check for K=2, look for two 2s that are K distance apart. |
Single-Pass Linear Arrow |
Draw a straight line N. One pass to build the `inc` array, one pass to check. $O(N)$. |
$O(N)$ to store results of all N^2 checks in a matrix. |
A single 1D array of size N (or $O(1)$ if checking on the fly). |
| 3350 |
Adjacent Increasing Subarrays Detection II |
Try every possible K from N/2 down to 1, and for each K, run the check from 3349. |
Binary Search over Linear Scan |
Draw a vertical line for K and a horizontal line for N. The grid of checks shows $O(N^2)$. |
Two Pointers / Maximum Overlap |
Peak and Valley Tracking |
Find all "strictly increasing" blocks. For any two adjacent blocks of size L_1 and L_2, the max K is min(L_1, L_2). Also, a single block of size L can provide K = L/2. |
Draw the array. Color code the increasing blocks. Write the length of each block. The answer is the maximum of min(Block_i, Block_i+1) across the whole array. |
Block-Compressed Scan |
Draw the array. Condense increasing segments into single "super-nodes" with a length value. Total $O(N)$. |
N/A. |
A list of block lengths, taking $O(N)$ space. |
| 3351 |
Sum of Good Subsequences |
Generate all 2^N subsequences, check if adjacent elements differ by exactly 1, and sum them. |
Power Set Branching |
Draw a root. For each element, branch "Include" or "Exclude". Massive tree width $O(2^N)$. |
DP with Frequency & Sum Mapping |
Value-based Contribution Buckets |
Maintain `count[x]` and `sum[x]` for "good" subsequences ending in x. count[x] = count[x-1] + count[x+1] + 1. |
Draw 3 buckets: (x-1), x, (x+1). Draw arrows showing "Sum" and "Count" flowing from neighbors into the current value bucket. |
Linear Value Sweep |
Draw a single line of length N. Each element update is $O(1)$ because it only looks at its immediate neighbors in the map. |
Storing every single valid subsequence string in a list. |
Two Hash Maps or flat arrays for `counts` and `sums` up to MaxVal. $O(N)$ space. |
| 3352 |
Count K-Reducible Numbers Less Than N |
Iterate from 1 to N. For each, repeatedly replace it with its set bit count until it becomes 1. |
Linear Reduction Sequence |
Write 1 dots N. For each, draw a chain of numbers until 1. Total work $O(N \log \log N)$. |
Digit DP + Precomputed Sieve |
Tight/Limit State Tree |
Use Digit DP to count numbers with X set bits. Precompute which bit counts reduce to 1 in <= K-1 steps. |
Draw a tree where each node is `(index, current_count, is_less)`. Show how the "is_less" flag prunes half the branches. |
Bounded State Matrix |
Draw a matrix of size Length(N) x Count(Bits). Filling this once is $O(\log N \\text{cdot bits})$. |
Massive integer list of all N results. |
A 2D memoization table of size approx 800 x 800. $O(\log^2 N)$. |
| 3353 |
Minimum Total Operations |
Simulate adding/subtracting 1 to subarrays iteratively until the target is reached. $O(N \\text{cdot Max}_\text{Diff})$. |
Iterative Subarray Sculpting |
Draw the array. Draw a block over a mismatched section and shift it up by 1. Check target. Repeat hundreds of times. |
Difference Array / Greedy |
The Step-Delta Tracker |
Create a difference array `diff[i] = target[i] - nums[i]`. Iterate through `diff`. An operation is required whenever the current difference changes magnitude or sign compared to the previous difference. |
Draw a bar chart of the differences. You only pay a "cost" when a bar is taller than the bar to its left (in the same direction). Add up these positive vertical step-ups. |
Linear Scan $O(N)$ |
Draw a single straight line reading the differences, updating a total sum in $O(1)$. |
Constantly mutating array states. |
A single `diff` tracking variable. $O(1)$ space. |
| 3354 |
Make Array Elements Equal to Zero |
For every index i where nums[i] = 0, simulate the movement left and right to see if it clears the array. |
Recursive Path Simulation |
Draw the array. Pick a 0. Draw a ball bouncing back and forth, decrementing numbers until it hits an edge. $O(N \\text{cdot Sum})$. |
Prefix Sum Balance |
Seesaw Balance Beam |
A start is valid if the sum of elements to the left equals the sum of elements to the right (or differs by 1). |
Draw a horizontal line (the array). Put a triangle (pivot) at each 0. Write the total weight on the Left and Right sides. If they balance, it's a "Yes". |
Two-Pass Prefix Sum |
Draw a horizontal line. One pass to get the total sum, second pass to check pivots. $O(N)$. |
N/A. |
Two integer variables: `left_sum` and `right_sum`. $O(1)$ auxiliary space. |
| 3355 |
Zero Array Transformation I |
For each query [l, r], iterate through the array from l to r and decrement values. Check if all <= 0. |
Query-Range Overlap Matrix |
Draw the array. For every query, draw a horizontal bracket. Count the overlaps manually for every index. $O(Q \cdot N)$. |
Difference Array (Prefix Sum of Queries) |
Step-Function Accumulator |
Create a `diff` array. For each query, `diff[l]++` and `diff[r+1]--`. Compute prefix sums to get total decrements per index. |
Draw a line of zeros. For a query [2, 5], write +1 at index 2 and -1 at index 6. Draw a "running total" line below that adds up these markers. |
Linear Sequence (Query + Array) |
Draw a line for queries (Q) and a line for the array (N). Total $O(N + Q)$. |
A 2D matrix of Q rows to track updates. |
A single 1D difference array of size N. $O(N)$. |
| 3356 |
Zero Array Transformation II |
For every possible number of queries k (from 1 to Q), apply the first k queries to the array and check if all elements become <= 0. |
Query-Level Sequential Scan |
Draw the array. Below it, draw the first query. Check. Erase. Draw first two queries. Check. Total work $O(Q \cdot (Q + N)$). |
Binary Search on Answer + Difference Array |
Pass/Fail Number Line |
Binary search for the minimum k. For a mid-point k, use a Difference Array to apply k queries in $O(N+k)$ and verify. |
Draw a line 1 dots Q. Mark k in the middle. Below, draw a Difference Array (markers for +v and -v). Compute prefix sums. If array is zeroed, mark k "Green" and move Left. |
Log-Linear Grid Block |
Draw a horizontal line N. Draw a vertical logarithmic tower (log Q). The rectangle represents $O((N+Q)$ log Q). |
Multiple 2D query-application matrices stored in memory. |
A single 1D Difference Array of size N. $O(N)$. |
| 3357 |
Minimize the Maximum Adjacent Element Difference |
Try filling missing elements with every possible number from 1 to 10^9. $O(\text{Infinite})$. |
Infinite Guessing Grid |
Draw an array with blanks. Try slotting 1, then 2, then 3 into the blanks. |
Binary Search on Answer |
The Tolerance Tester |
Binary search the maximum allowed difference D. For a given D, determine the valid range [L, R] for the missing numbers that satisfies the difference constraint with their known neighbors. If valid, try a smaller D. |
Draw a number line of possible differences. Guess D=5. Look at the array blanks. "Can I pick a number that is within 5 of the left neighbor AND right neighbor?" If yes, guess a tighter D. |
Logarithmic Search $O(N \log(\text{Max}_\text{Val})$) |
Draw a binary search tree of answers. At each node, draw an $O(N)$ validation scan. |
Storing every filled array permutation. |
Range tracking variables. $O(1)$ space. |
| 3358 |
Books with NULL Ratings |
Pull all books into application memory and use `if (rating == null)` to filter them. |
App-Side Filtering Loop |
Draw all database rows transferring over a network wire to be checked one by one in code. |
SQL IS NULL |
The DB-Native Null Catcher |
Use `SELECT book_id FROM Books WHERE rating IS NULL`. |
Draw the table. The database engine drops a net that only catches rows where the rating slot is completely empty. |
Single Index Scan $O(N)$ |
Draw a direct query path through the table. |
Wasted network bandwidth. |
DB Query Result Buffer. $O(N)$ space. |
| 3359 |
Find Sorted Submatrices With Maximum Element at Most K |
(SQL Context) Complex self-joins attempting to simulate window functions across categories and bounds. |
Nested Subquery Matrix |
Draw multiple tables joined together with confusing `MAX()` and `GROUP BY` logic that drops rows. |
CASE WHEN / Aggregate Filtering |
The Conditional Category Sorter |
Use `CASE WHEN element <= K THEN 1 ELSE 0 END` to flag items, then aggregate or filter based on these specific conditional rules. |
Draw the rows. Stick a green label on items <= K and a red label on others. Group them into buckets and only keep the buckets with all green labels. |
Linear Scan / Hash Agg $O(N)$ |
Draw a single pass applying a logical switch and grouping. |
N/A |
Internal DB buffer. $O(N)$ space. |
| 3360 |
Stone Removal Game |
Simulate the game recursively with Minimax, exploring every possible sequence of moves. $O(2^N)$. |
Recursive Minimax Tree |
Draw a pile of stones. Branch out for Alice's moves, then Bob's moves, checking win states at the bottom. |
Math / Simulation |
The Deterministic Subtractor |
The game rules are fixed (Alice takes 10, Bob takes 9, Alice takes 8...). Just simulate it directly with a while loop, alternating turns until someone can't make a move. |
Draw a pile of stones. Alice grabs a handful of 10. Bob grabs 9. Keep shrinking the pile by a strictly decreasing number until someone's hand hits the bottom of an empty bucket. |
Constant Time Iteration $O(1)$ |
Draw a loop that runs at most 10 times. |
Recursive call stack. |
A boolean turn flag. $O(1)$ space. |
| 3361 |
Shift Distance Between Two Strings |
For each character in the string, try all possible shift steps (clockwise and counter-clockwise) while summing the costs at each unit step. |
Cyclic Graph Traversal |
Draw a circle with 26 dots ('a' to 'z'). To move from 'a' to 'c', draw arrows for every unit step ('a'->'b'->'c') and label each with a cost. Repeat for all N characters. $O(N x 26)$. |
Prefix Sums (Cost Optimization) |
Segmented Circular Track |
Precompute the prefix sum of costs for shifting from 'a' to any character. The cost from X to Y is a simple subtraction (handling circular wrap-around). |
Draw the circle again. This time, mark each segment with a fixed weight. Use a "cut" and "subtract" method on the circle's circumference to find distances instantly. |
Constant String Sweep |
Draw a single line of length N. Each node in the line has exactly two arrows (Clockwise vs. Counter-clockwise Math). Proves $O(N)$. |
Recursive calls or repeated loops per character. |
Two arrays of size 26 (Prefix sums for forward/backward costs). $O(1)$ relative to N. |
| 3362 |
Zero Array Transformation III |
Try every possible subset of queries and for each, check if the array can be zeroed. |
Subset Power Set Tree |
Draw a root. For Query 1, branch "Use" or "Skip". Repeat for Q queries. Leaf count 2^Q is the complexity wall. |
Greedy + Max-Heap + Difference Array |
Query Reservoir Management |
Iterate array. Collect all available queries starting at i into a Max-Heap (sorted by end-index). If nums[i] > 0, pick queries that end furthest. |
Draw the array. Above it, draw "Water Buckets" (queries) at their start points. When a number is positive, "reach" into the bucket and pull out the longest query. Mark the decrease using a Difference Array. |
Log-Linear Sweep |
Draw one line for N and one for Q. Mark "Heap Pop" points. Proves $O((N+Q)$ log Q). |
Storing 2^Q state combinations in memory. |
A Max-Heap storing up to Q query end-times and one Difference Array of size N. |
| 3363 |
Find the Maximum Number of Fruits Collected |
Generate all possible paths for the three children (one on diagonal, one in top-right, one in bottom-left) and find the max sum. |
3D Path Spaghetti |
Draw a grid. Draw three different colored paths. The number of combinations for three independent paths is massive (O(3^N * 3^N)). |
Dynamic Programming (State Independence) |
Grid-Slicing Heatmap |
The diagonal path is fixed. The other two children move in restricted triangles. Solve two independent 2D DP problems for the two triangles. |
Draw the grid. Color the diagonal. Shade the top-right triangle and bottom-left triangle separately. Write DP transitions (max of 3 neighbors) inside the cells. |
Triangle Area Fill |
Draw two triangles within an N x N box. Shading the triangles proves $O(N^2)$. |
Deep recursion stack for three concurrent pathing states. |
Two 2D arrays (or optimized 1D rows) of size N x N for the two triangles. |
| 3364 |
Minimum Positive Sum Subarray |
Generate all subarrays of length [l, r], calculate their sums, and find the minimum positive one. |
Triangular Matrix Scan |
Draw an N x N grid. Shade the diagonal band where length is between L and R. Count the cells. $O(N \cdot (R-L)$). |
Sliding Window + Prefix Sums |
Expanding Rubber Band |
Use a fixed-size window or prefix sums to calculate range sums in $O(1)$. Slide the window for each valid length k in [l, r]. |
Draw the array. Draw a bracket of length L. Slide it across. Then draw a bracket of length L+1. Keep a "Global Minimum" sticky note on the side. |
Bounded Window Sweep |
Draw the array line. Show the window moving. Since we check at most N positions for each length in [L, R], complexity is $O(N \cdot (R-L)$). |
N/A (no heavy data structures). |
Exactly one prefix sum array of size N (or $O(1)$ if using sliding window). |
| 3365 |
Rearrange K Subsets to Form Target String |
Generate all K! permutations of the split subsets of the first string and compare each to the target string. |
Permutation Factorial Tree |
Draw K boxes. Draw arrows showing all ways to arrange them. K=10 leads to 3.6 million leaves. $O(K! \cdot N/K)$. |
Hash Map (Frequency Counting) |
Multi-Box Matching |
Split both strings into K equal parts. Use a Hash Map to count the frequency of each "chunk" in string s and compare it to string t. |
Draw two rows of boxes. In row 1, label each box with its string chunk. In row 2, do the same. Use lines to connect identical boxes. If all find a pair, return true. |
Linear Chunk Scan |
Draw the string length N. Divide it into K blocks. One pass through blocks proves $O(N)$. |
Large list of all possible K! string permutations. |
A Hash Map containing K strings of length N/K, taking $O(N)$ space. |
| 3366 |
Minimum Array Sum |
Try every possible order and combination of applying Operation 1 and Operation 2 to every element in the array. |
Recursive Decision Tree |
Draw a root. For element i, branch into 4 paths: (None, Op1, Op2, Op1+Op2). Repeat for all N. Height N, branching factor 4. $O(4^N)$. |
3D Dynamic Programming |
State-Space Volume Block |
`dp[i][op1_left][op2_left]` tracks the minimum sum. At each i, check if you have enough operations left to apply Op1, Op2, or both (considering the order). |
Draw a grid for each index i. Rows = Op1 counts, Columns = Op2 counts. For a cell (k, j), draw arrows from the previous index's grid showing the best "cost-so-far". |
Iterative Grid Filling |
Draw a 3D rectangular prism (N x K_1 x K_2). Shading the volume shows $O(N \cdot K_1 \cdot K_2)$. |
Deep recursive stack with $O(N)$ depth and exponential leaf nodes. |
A 3D integer array (or two 2D layers for space optimization). $O(K_1 \cdot K_2)$. |
| 3367 |
Maximize Sum of Weights after Edge Removals |
Generate all possible subsets of edges and check if every node satisfies the degree constraint K. |
Edge-Selection Power Set |
Draw a tree with E edges. For each edge, branch "Keep" or "Remove". Leaf count 2^E is the complexity wall. |
Tree DP with Greedy Sorting |
Recursive Bubble Up |
For each node, calculate two values: (Max weight keeping the parent edge) and (Max weight cutting it). Sort children based on the "gain" of keeping their edge. |
Draw a node and its children. Write the "Keep" and "Cut" scores next to each child. Draw a "Leaderboard" sorting these differences. Circle the top K or K-1 winners. |
Linear Tree Traversal |
Draw a tree once. Highlight each node being visited twice (down and up). Show a small sorting icon $O(\text{deg} \\text{log deg})$ at each node. $O(N \log N)$. |
Storing 2^E edge configurations. |
$O(N)$ recursive call stack and a `dp[N][2]` result table. |
| 3368 |
First Letter Capitalization I (SQL) |
(Imperative) Iterate through every character of every word, check if it follows a space, and change its case. |
Char-by-Char Scanner |
Draw a string. Draw an arrow pointer moving through it. At every space, circle the next character for a "Transformation". $O(N x L)$. |
SQL String Functions (INITCAP / Regex) |
Pattern-Matching Funnel |
Use `INITCAP()` or a combination of `UPPER(SUBSTR)` and `LOWER(SUBSTR)` to transform words based on space boundaries. |
Draw a column of messy text. Draw it passing through a "Sieve" (SQL function). The output is a column of clean, capitalized text. |
Single-Pass Stream |
Draw a horizontal arrow $O(N)$. As data flows, it's transformed in-place by the engine's internal string processor. |
Repeated string buffer reallocations. |
$O(1)$ auxiliary space (stream processing by the DB engine). |
| 3369 |
Design an Array Statistics Tracker |
Maintain a simple list. For every `getMedian` or `getMode` call, sort the list or build a frequency map from scratch. |
On-Demand Sorting Plot |
Draw the array. For every request, draw a sorting diagram (bubbles or branches). Total work $O(Q \cdot N \log N)$. |
Two Heaps (Median) + Hash Map & Treap/SortedSet (Mode) |
Balanced Balancing Act |
Use a Max-Heap and Min-Heap for $O(1)$ median. Use a Hash Map for frequencies and a `SortedSet` of `(freq, value)` for $O(\log N)$ mode. |
Draw two triangles (Heaps) meeting at the tips. Draw a "Balance Scale" between them. Next to it, draw a "Leaderboard" (SortedSet) for the mode. |
Logarithmic Update Timeline |
Draw a line of Q queries. At each point, draw a small log N staircase. Total complexity $O(Q \log N)$. |
N/A (Repeated allocations). |
$O(N)$ space to store the heaps, maps, and the raw element list. |
| 3370 |
Smallest Number With All Set Bits |
Start from N, increment by 1, and check if the binary representation consists only of '1's. |
Incremental Binary Search |
Write N. Convert to binary. Increment N to N+1 dots. Check for '0's in each binary string. Stop when none are left. |
Bit Manipulation (Power of 2 - 1) |
Binary Bit-Filling |
Find the number of bits in N. The answer is 2^bit_count - 1. Alternatively, keep shifting N right and count. |
Write N in binary. Count the digits. Draw that many empty boxes square square square. Fill them all with '1's. Calculate the decimal value. |
Constant Time/Log-Bits |
Draw a single bitwise operation box. Even for a 64-bit number, this takes 1-2 steps. $O(\log N)$. |
N/A. |
Exactly one integer register. $O(1)$ space. |
| 3371 |
Identify the Largest Outlier in an Array |
For every possible element x, assume it is the outlier. For every other element y, assume it is the sum of the remaining n-2 elements. |
Nested Iteration Grid |
Draw an N x N matrix. Rows are candidate outliers, columns are candidate sums. Check the "validity" of each cell. $O(N^2)$. |
Frequency Hash Map + Sum Equation |
Balance Scale Equation |
Total Sum S = sum + sum + outlier. Therefore, outlier = S - 2 * sum. Iterate through potential sums and check if the required outlier exists in the Hash Map. |
Write the Total Sum S. Draw a box labeled "Potential Sums". For each y in the array, calculate S - 2y. Draw a line to the Frequency Map to see if that value is available. |
Linear Frequency Scan |
Draw a single straight line N. Each lookup in the map is $O(1)$, proving $O(N)$. |
Creating temporary array slices or sub-lists for every pair of candidates. |
A Frequency Map (Hash Table) of size N, taking $O(N)$ space. |
| 3372 |
Maximize the Number of Target Nodes After Connecting Trees I |
Try connecting every node i in Tree 1 to every node j in Tree 2. For each pair, run BFS to count reachable nodes within distance K. |
All-Pairs BFS Traversal |
Draw two trees. Draw a line between every possible pair of nodes (N x M). For each line, draw expanding ripples. $O(N \cdot M \cdot (N+M)$). |
Independent Precomputed BFS |
Concentric Distance Rings |
Precompute the count of nodes within distance K for all nodes in Tree 1, and nodes within K-1 for Tree 2. The result for node i is Count1(i, K) + max(Count2(j, K-1)). |
Draw Tree 1 and Tree 2. For each node, draw rings at distance 1, 2, ... up to K. Write the "inside-ring" count next to each node. Pick the highest count from Tree 2 to add to every node in Tree 1. |
Dual-Pass Linear Scan |
Draw a line for Tree 1 and a line for Tree 2. Each node is visited once per BFS. $O(N^2 + M^2)$ (or $O(N+M)$ with Re-rooting). |
Storing millions of path combinations in a 2D adjacency matrix. |
Two 1D arrays of size N and M to store the reachable counts. |
| 3373 |
Maximize the Number of Target Nodes After Connecting Trees II |
Similar to 3372, but distance K is infinite and the constraint is on parity (even/odd) rather than a fixed limit. |
Global Connectivity Tree |
Draw the same connection spaghetti as 3372. Count even-distance nodes for every connection pair. $O(N \cdot M \cdot (N+M)$). |
Bipartite Coloring (Parity Counting) |
Red-Blue Node Coloring |
Trees are bipartite. In Tree 2, the max nodes you can add is max(count of even nodes, count of odd nodes). In Tree 1, every node's "even" neighbors are its same-color buddies. |
Color Tree 1 like a checkerboard (Red/Blue). Do the same for Tree 2. For any node in Tree 1, the answer is (Count of same-colored nodes in T1) + (Max color count in T2). |
Single-Pass Tree Coloring |
Draw two trees. Trace one DFS pass through each to assign colors. Proves $O(N+M)$. |
Huge recursive stack depth combined with N x M pair storage. |
Four integer variables: Count of Red1, Blue1, Red2, Blue2. $O(N+M)$ for the adjacency lists. |
| 3374 |
First Letter Capitalization II (SQL) |
(Imperative) Split every word by spaces AND hyphens, capitalize the first letter, and rejoin. |
Regex/Split Pattern Matcher |
Draw a messy string with hyphens like "pro-grade". Circle the 'p' and the 'g'. Draw arrows showing the "Upper Case" shift. $O(N x L)$. |
SQL REGEXP_REPLACE / Nested String Functions |
Multi-Delimiter Funnel |
Use string transformations that recognize both ' ' and '-' as word boundaries. Capitalize the char following either delimiter. |
Draw a text block. Draw a "Delimiter Mask" that highlights characters after spaces or dashes. Those highlighted bits pass through an "UPPER" filter. |
Streamed Transformation |
Draw an $O(N)$ single-pass arrow. The SQL engine processes the string buffer linearly. |
Repeated temporary string allocations and concatenations. |
$O(1)$ auxiliary space (handled internally by DB string buffers). |
| 3375 |
Minimum Operations to Make Array Values Equal to K |
Repeatedly find the maximum value in the array and reduce it to some value x >= K until all elements are K. |
Iterative Reduction Steps |
Draw the array as bars of different heights. Pick the tallest bar, lower it to the next tallest. Repeat until they hit floor K. $O(N^2)$. |
Set-Based Unique Value Counting |
Step-Down Staircase |
Each operation can reduce ALL instances of the current maximum value. The number of operations is the count of unique values strictly greater than K. |
Draw a staircase where each step is a unique number from the array. Count the number of steps above the "K-line". If any value is < K, draw a big red X (return -1). |
Linear Set Construction |
Draw a number line. Mark the unique values with dots. One pass to count dots. $O(N)$. |
Multiple copies of the array created during sorting or reduction steps. |
A single Hash Set to store unique values. $O(N)$. |
| 3376 |
Minimum Time to Break Locks I |
Try every possible permutation of the N locks and calculate the total time for each order. |
Permutation Tree |
Draw a root node branching into N locks, then N-1, etc. Total leaves = N!. $O(N!)$. |
Backtracking / Greedy (Small N) |
Decision Timeline |
For each lock in the chosen order, calculate the time required based on the current X (which increases after each break). |
Draw a horizontal timeline. Mark "Break Lock" events. After each event, draw an "Up Arrow" showing X increasing by K. Sum the segments. |
Pruned Search Tree |
Draw the same tree but "cut" branches that are obviously worse than the current minimum. $O(N!)$. |
Massive array of all N! possible time sums. |
Recursive call stack of depth N (O(N) space). |
| 3377 |
Digit Operations to Make Two Integers Equal |
Try every possible single-digit change recursively to find the path from n to m, avoiding primes. |
Exhaustive State Graph |
Draw n in the center. Draw lines to all neighbors (changing 1 digit). Repeat for neighbors. $O(10^D)$. |
Dijkstra’s Algorithm + Prime Sieve |
Expanding Cost Wavefront |
Precompute primes using a Sieve. Use a Min-Heap to explore integers with the lowest cumulative "cost" (the value of the number). |
Draw n as a dot. Draw a "circle" around it of numbers reachable by 1 step. Color prime dots red (dead ends). Write the "value" inside each dot. |
Priority Queue Expansion |
Draw a 1D number line 1 dots 10000. Mark jumps between dots. The shortest path is the one with the lowest sum of labels. $O(V \log V + E)$. |
A list of all possible paths explored, leading to massive memory usage. |
A `dist` array of size 10,000 and a Min-Heap. $O(\text{Range})$. |
| 3378 |
Count Connected Components in LCM Graph |
Calculate the LCM for every pair (i, j) and build an edge if LCM <= threshold. Run DFS. $O(N^2)$. |
Dense Quadratic Graph |
Draw N dots. Draw lines between every single pair to check their LCM. Graph becomes too dense. |
DSU + Multiples (Sieve-like) |
The Factor-Bridge Connector |
Instead of connecting numbers to numbers, connect numbers to their *multiples* up to the threshold using a Disjoint Set Union (DSU). If x is in the array, union x with 2x, 3x... if those multiples also exist. |
Draw the numbers. Instead of checking pairs, take '2'. Draw bridges from '2' to '4', '6', '8'. Then take '3'. Draw bridges to '6', '9'. The shared multiples merge the components automatically. |
Harmonic Series Scan $O(M \log M)$ |
Draw a Sieve-like loop where the inner loop runs M/i times. Highly optimized. |
Adjacency matrix of size N x N. |
DSU parent array up to max threshold. $O(\text{Threshold})$ space. |
| 3379 |
Transformed Array |
For each index i, manually step forward or backward in the array nums[i] times, looping around the ends. |
Linear Step Simulation |
Draw an array. For index i, count jumps one by one until you hit the limit. $O(N \\text{cdot max}(\text{nums})$). |
Modulo Arithmetic (Circular Indexing) |
The Clock-Face Map |
Calculate the new index using (i + nums[i] % N + N) % N to handle positive, negative, and wrap-around. |
Draw the array in a circle (like a clock). For each index, draw one "teleportation" arrow that lands on the target index. |
Constant-Time Index Mapping |
Draw a single line of length N. Each index has exactly one arrow. Total work $O(N)$. |
N/A. |
A single output array of size N. $O(N)$ or $O(1)$ auxiliary. |
| 3380 |
Maximum Area Rectangle With Point Constraints I |
Check every possible combination of 4 points to see if they form a valid rectangle, and check all other points to ensure they aren't inside. $O(N^5)$. |
Quintic Geometry Search |
Draw a scatter plot. Pick 4 random points. Check angles. Scan all other points. |
Diagonal Iteration + Hash Set |
The Bounding Box Verifier |
Put all points in a Hash Set. Iterate over every pair of points, treating them as the *diagonal* of a rectangle. Check if the other two required corners exist in the Set. If they do, verify no other points fall inside their bounding box. |
Draw the grid. Pick two points (top-left, bottom-right). Instantly check the Map for the other two corners. If present, draw the box and quickly scan the remaining points to ensure the box is empty. |
Diagonal Pair Scan $O(N^3)$ |
Draw an N^2 loop to pick diagonals, followed by an $O(N)$ interior point check. |
N/A |
A Hash Set of points. $O(N)$ space. |
| 3381 |
Maximum Subarray Sum With Length Divisible by K |
Generate all subarrays. Check if length is divisible by k. Calculate sum. $O(N^2)$. |
Modulo Subarray Brackets |
Draw the array. Bracket lengths of K, 2K, 3K. Sum everything from scratch. |
Prefix Sum + Hash Map (Modulo Tracking) |
The Modulo-K Minimizer |
Maintain a running prefix sum. To find a subarray of length divisible by k ending at i, we need a previous prefix sum at index j where j mod k == i mod k. Keep a Map storing the *minimum* prefix sum seen so far for each index modulo k. |
Draw the array. As you walk, keep a tally. Put the tally in one of k buckets based on your step number. To maximize your score, subtract the smallest tally sitting in your current modulo bucket. |
Single Linear Pass $O(N)$ |
Draw a single straight line. $O(1)$ map lookup and update at each step. |
Storing sums for all N^2 subarrays. |
An array/map of size K. $O(K)$ space. |
| 3382 |
Maximum Area Rectangle With Point Constraints II |
Same as I, but fails due to 10^5 constraints. $O(N^3)$ times out instantly. |
Memory-Crashing Point Scan |
Try to check interior points for a million possible rectangles. |
Sweep Line + Segment Tree |
The Y-Axis Scanner |
Group points by X-coordinate. Sweep a vertical line left-to-right. Use a Segment Tree to efficiently track valid Y-intervals and answer queries about the maximum empty rectangle area formed between the current X and previous X values. |
Draw the points. A vertical laser sweeps left to right. It records the Y-height of pairs of points. If it sees the *exact same* Y-pair later, it calculates the box area, using the tree to ensure no points sneaked in. |
Sweep Line $O(N \log N)$ |
Draw a timeline. At each step, update a Segment Tree in $O(\log N)$ time. |
$O(N^3)$ search space. |
Segment Tree. $O(N)$ space. |
| 3383 |
Minimum Runes to Add to Cast Spell |
Try casting the spell by manually testing combinations of runes to add. |
Manual Combination Search |
Draw a spell circle and randomly guess which runes are missing. |
Graph Reachability / SCC (Tarjan's) |
The Crystal Component Linker |
Treat crystals/runes as a directed graph. Find Strongly Connected Components (SCCs). Condense the graph into a Directed Acyclic Graph (DAG). The answer is the number of SCCs with an in-degree of 0 (sources that must be manually activated). |
Draw nodes and arrows. Circle groups of nodes that loop into each other (SCCs). Treat each circle as one giant node. Count the circles that have absolutely zero arrows pointing *into* them. |
Tarjan's DFS $O(V + E)$ |
Draw a single DFS traversal to identify components, followed by an in-degree scan. |
Matrix of all reachability states. |
DFS stacks, `low-link` arrays. $O(V+E)$ space. |
| 3384 |
Team Dominance (SQL) |
(Imperative) For every goal, look back at all previous goals to see which team was leading or "dominating" the timeline. |
$O(N^2)$ Timeline Scan |
Draw a timeline of goals. For Goal #10, scan Goals #1-9 to calculate the score. Repeat for every goal. |
Window Functions (SUM OVER) + CASE |
Running Score Tally |
Use `SUM(CASE WHEN...) OVER (ORDER BY time)` to get the score at every second. Calculate the duration where Team A score > Team B score. |
Draw a scoreboard with two columns: Team A and Team B. As you scroll down the "Goals" table, update the counts. Highlight the rows where A > B. |
Single-Pass Result Set |
Draw a horizontal arrow $O(N)$. The DB engine calculates the running sum in one pass over the sorted time. |
Temporary tables for every single point in time. |
A single pass through the result set with $O(1)$ state variables. |
| 3385 |
Minimum Time to Break Locks II |
Try all permutations of which lock to break first. $O(N!)$. |
Factorial Lock Sequence |
Draw N locks. Branch out for picking lock 1, 2, or 3 first. Tree explodes. |
Bitmask DP |
The Multiplier State Grid |
Use a bitmask to represent broken locks. Your multiplier `X` increases based on how many locks are broken. `dp[mask]` is the minimum time to reach this state. Calculate the wait time for the next lock using `ceil(energy_needed / X)`. |
Draw a row of locks. Flip them open one by one. Each open lock increases your "Sword Power". Try different orders of opening them, recording the total waiting time for each exact combination of open/closed locks. |
Exponential State Transitions $O(N \cdot 2^N)$ |
Draw a table of 2^N rows. Transitioning to the next state requires checking N possible next locks. |
Recursive tracking of permutations. |
A DP array of size 2^N. $O(2^N)$ space. |
| 3386 |
Button with Longest Push Time |
For every event, iterate through all previous events to find the time difference, store in a list, then sort to find the max. |
Nested Event Comparison |
Draw a timeline. For every dot, draw a line back to every other dot. $O(N^2)$. |
Single-Pass Linear Scan |
Interval Gap Measuring |
Track `currentTime` and `lastTime`. Calculate `gap = currentTime - lastTime`. Update `maxGap` and `buttonId` if the current gap is larger or equal with a smaller ID. |
Draw a horizontal line with timestamps. Draw brackets between stamps. Write the gap value inside each bracket. Circle the widest bracket. |
Single Linear Arrow |
Draw a straight line N. Each step is one $O(1)$ calculation. Total $O(N)$. |
A list of all N calculated time intervals. |
Exactly three variables: `maxTime`, `resultId`, and `prevTime`. $O(1)$. |
| 3387 |
Maximize Amount After Two Days of Conversions |
Try every possible sequence of currency conversions for Day 1 and Day 2 using recursion with no pruning. |
Exponential Conversion Tree |
Draw a starting currency. Branch out to all neighbors. From each neighbor, branch again. The tree depth is effectively infinite. |
BFS / Dijkstra (Day-by-Day) |
Layered Graph Expansion |
Run BFS on Day 1 to find the max amount of every currency reachable from `initialCurrency`. Then use those results as start points for BFS on Day 2 to get back to `initialCurrency`. |
Draw two separate graphs (Day 1 and Day 2). For Day 1, draw concentric circles showing the best "rate" to reach each node. Repeat for Day 2 starting from those rates. |
Dual Layer Traversal |
Draw two horizontal blocks representing the two $O(V+E)$ passes. Total $O(V+E)$. |
Massive recursive stack and rate-combination lists. |
Two Hash Maps (one per day) storing `currency: max_amount`. $O(V)$. |
| 3388 |
Count Beautiful Splits in an Array |
Try every possible pair of split indices (i, j) and physically compare the resulting substrings. $O(N^3)$. |
Nested Split String Comparisons |
Draw the array. Put two dividers. Run a loop to compare slice 1 to slice 2, and slice 2 to slice 3. |
LCP Array (Longest Common Prefix) / Z-Algorithm |
The Precomputed Prefix Matcher |
Precompute an `lcp[i][j]` table: the length of the longest common prefix starting at indices i and j in $O(N^2)$. To check if `str1` is a prefix of `str2`, simply check if `lcp[start1][start2] >= length(str1)` in $O(1)$ time. |
Draw the string. Build a 2D matrix storing how many letters match starting from any two points. Put two dividers in the string. Instead of comparing letters, instantly look up the matrix cell to see if the prefix condition holds. |
$O(N^2)$ Precompute + $O(N^2)$ Checks |
Draw a 2D matrix fill, followed by a double loop (i, j) checking conditions in $O(1)$. |
Generating thousands of substrings. |
A 2D integer array `lcp`. $O(N^2)$ space. |
| 3389 |
Minimum Operations to Make Character Frequencies Equal |
Try every possible target frequency f in [0, N]. For each f, try all ways to shift, add, or delete characters. |
Exhaustive State Search |
Draw 26 buckets. For a target f, draw arrows moving tallies between any two buckets. $O(N \cdot 3^26)$. |
Dynamic Programming (Frequency Transitions) |
Linear Frequency Waterfall |
`dp[i]` is the min cost for the first i characters. At step i, you can either handle char i independently or "bridge" it with char i-1 (moving excess from i-1 to i). |
Draw 26 boxes. Below them, draw a DP array. For box i, draw an arrow from `dp[i-1]` and a "combo" arrow from `dp[i-2]` if you are moving excess characters. |
Linear 26-Step Sweep |
Draw a line of 26 dots. For each target f (up to N), sweep through the 26 dots. Total $O(26 \cdot N)$. |
Massive state-space tree for all possible tally shifts. |
A 1D DP array of size 26 and a frequency map. $O(1)$ relative to N. |
| 3390 |
Longest Team Pass Streak |
Explore every possible path through the grid using DFS, tracking negative values manually. $O(2^R+C)$. |
Exponential Path Grid |
Draw a grid. From the top-left, branch right and down. Continue branching at every cell. The overlapping paths are too dense to trace. |
3D Dynamic Programming |
The Layered Grid Extractor |
Use a 3D DP table `dp[r][c][k]` where `k` (0, 1, or 2) represents the number of negative values you've neutralized. Transition by taking the max of moving from top or left, factoring in whether you use a neutralization on the current cell. |
Draw 3 identical grids stacked like glass panes. Layer 0 has no neutralizations, Layer 1 has one, Layer 2 has two. To fill a cell in Layer 1, look at the cell above/left in Layer 1, OR pull from Layer 0 and "spend" a neutralization to ignore a negative number. |
State-Space Matrix $O(R \cdot C \cdot 3)$ |
Draw three parallel grid passes. Constant $O(1)$ lookups at each cell. |
Massive recursion stack tracking path states. |
A 3D array of size R x C x 3. $O(R \cdot C)$ space. |
| 3391 |
Design a 3D Binary Matrix with Efficient Layer Tracking |
Iteratively subtract 1 or try random divisions to reach the target from max value. $O(\text{Target})$. |
Linear Countdown |
Draw a number line. Start at target, draw a million tiny -1 arrows backwards. |
Greedy / Math (Reverse Operations) |
The Halving Shortcut |
Work backwards from the target to the start. If the target is even, divide by 2 (costs 1 operation). If it's odd, subtract 1 to make it even. This optimally minimizes operations. |
Draw the target number. If it ends in an even digit, cut the block in half. If odd, shave off 1 block, then cut the rest in half. Continue until you hit the start score. |
Logarithmic Reduction $O(\log N)$ |
Draw a tree plunging straight down, halving at almost every step. |
Tracking all states in a BFS queue. |
A single integer variable. $O(1)$ space. |
| 3392 |
Count Subarrays of Length Three With a Condition |
Nested loops to extract every subarray of length 3 and check if 2 x (nums[i] + nums[i+2]) == nums[i+1]. |
Sliding Window Matrix |
Draw the array. Bracket the first 3 elements. Check. Move the bracket 1 step. Check. $O(N x 3)$. |
Linear Scan / Fixed Sliding Window |
The 3-Slot Viewfinder |
Iterate from index 1 to N-2. Treat i as the center. Check the neighbors i-1 and i+1 against the condition. |
Draw the array. Place a "3-cell" physical paper template over the array. Slide it. Write "Match" or "No" under each center element. |
Single-Pass Linear Arrow |
Draw a straight line N. One pass, $O(N)$. |
N/A. |
$O(1)$ auxiliary space (just a counter). |
| 3393 |
Count Paths with the Given XOR Value |
DFS with backtracking to find all paths from (0,0) to (n-1, m-1), calculating XOR at each step. |
Grid-XOR Path Explosion |
Draw a grid. From start, draw every possible path to the end. For each path, keep a running XOR. $O(2^N+M)$. |
3D Dynamic Programming |
Layered XOR Bit-Slices |
`dp[i][j][current_xor]` is the count of paths to (i, j) resulting in `current_xor`. Max XOR is usually small (up to 15 or 31). |
Draw the grid. For each cell, draw a small table (0 to 15). To fill cell (i, j) with XOR value V, add paths from (i-1, j) and (i, j-1) that XOR with `grid[i][j]` to reach V. |
Volume-Filling Scan |
Draw a 3D block: N x M x 16. Shading the volume proves $O(N \cdot M \cdot 16)$ rightarrow $O(\text{NM})$. |
Massive path list storing every single coordinate sequence. |
A 3D array (or two 2D layers) of size N x M x 16. $O(\text{NM})$. |
| 3394 |
Check if Grid can be Cut into Sections |
Try every horizontal and vertical line to see if it doesn't intersect any rectangle, splitting the grid into 3+ pieces. |
Exhaustive Line-Sweep Grid |
Draw the grid with rectangles. Draw a line. Check if it hits any box. Repeat for all possible coordinates. $O(H \cdot N + W \cdot N)$. |
Dimension Reduction + Interval Merging |
Flattened Shadow Tracks |
Project all rectangles onto the X-axis (as intervals) and Y-axis. If the merged intervals have at least 2 gaps, the grid can be cut into 3 sections. |
Draw the rectangles. Below the grid, draw their "shadows" on the X-axis. Draw a circle around any "white space" between shadows. Count the circles. |
Log-Linear Sort & Merge |
Draw an $O(N \log N)$ sort box for intervals, followed by a linear $O(N)$ merge. Total $O(N \log N)$. |
2D occupancy matrix of the entire grid. |
Two lists of intervals, size $O(N)$. |
| 3395 |
Subsequences with a Unique Middle Mode I |
Generate all possible subsequences of length 5, find the middle element, count frequencies, and verify the mode. $O(N^5)$. |
Quintic Subsequence Forest |
Draw the array. Pick 5 numbers. Check the mode. Repeat for every combination. |
Combinatorics + Prefix/Suffix Maps |
The Pivot Combinations |
Treat every index i as the middle element. Use prefix and suffix frequency arrays to calculate how many valid pairs can be picked from the left and right such that `nums[i]` remains the strict mode. |
Draw the array. Lock a middle element. Look left: calculate combinations of choosing 2 numbers. Look right: do the same. Subtract invalid combinations where another number ties or beats your locked middle element's frequency. |
Linear Scan + Map Math $O(N \\text{cdot Unique}_\text{Vals})$ |
Draw a single pass timeline. At each step, iterate over a fixed-size frequency map. |
Storing millions of length-5 arrays. |
Prefix and Suffix Hash Maps. $O(N)$ space. |
| 3396 |
Minimum Number of Operations to Make Elements in Array Distinct |
Try deleting elements from the front in batches of 3. After each batch, check if all remaining elements are distinct. |
Iterative Sub-list Scanning |
Draw the array. Cross out the first 3. Scan the rest for duplicates. Repeat. $O(N^2 / 3)$. |
Hash Set (Backward Scan) |
Suffix Distinct Window |
Scan the array from right to left. Stop at the first element that is already in your Hash Set. Everything to the left of this point (plus its batch-of-3 rounding) must be deleted. |
Draw the array. Start at the end and move a "Clearance Pointer" left. If you hit a duplicate, stop. Draw boxes of size 3 from the start until you cover the duplicate's index. |
Single-Pass Linear Scan |
Draw a single arrow moving from right to left once. Total work $O(N)$. |
Repeated creation of new sub-arrays or frequency maps. |
A single Hash Set storing at most N elements. $O(N)$. |
| 3397 |
Maximum Number of Distinct Elements After Operations |
For every element i, try every integer in the range [nums[i]-k, nums[i]+k] and check all combinations to maximize unique values. |
Combinatorial State Tree |
Draw a root. Branch into 2k+1 options for element 1. Repeat for all N. Height N. $O((2k+1)$^N). |
Sorting + Greedy Allocation |
Tight-Packing Timeline |
Sort the array. Keep track of the `lastValue` assigned. For each element, assign it the value max(lastValue + 1, nums[i] - k), provided it doesn't exceed nums[i] + k. |
Draw a number line. Sort your numbers as dots. For the first dot, move it as far left as possible (to x-k). For the next, place it at last+1 or its own x-k, whichever is higher. |
Log-Linear Sorted Sweep |
Draw an $O(N \log N)$ sort box, followed by a single straight line N representing the greedy scan. |
Massive tree of all possible assignments. |
$O(1)$ auxiliary space beyond the sorted array. |
| 3398 |
Smallest Substring With Identical Characters I |
Try changing every combination of K characters to see which one minimizes the longest identical block. $O(2^N)$. |
Combinatorial Mutation Tree |
Draw the string. Branch out by changing '0' to '1' at index 0, then index 1. Calculate block lengths for every variation. |
Binary Search on Answer |
The Tolerance Slicer |
Binary search the *maximum allowed identical streak* L. For a block of X identical characters, the minimum operations to break it into chunks of size <= L is X / (L+1). If total operations <= K, L is possible! |
Draw the string. Group identical characters into blocks (e.g., "00000" is a block of 5). Guess a max length of 2. You need to "slice" the block of 5 every 3rd character. 5 / (2+1) = 1 slice. Sum the slices needed for all blocks. |
Logarithmic Search $O(N \log N)$ |
Draw a binary search number line. Above each guess, draw a quick linear pass calculating required slices. |
Tracking all mutated string states. |
Variables for binary search pointers. $O(1)$ space. |
| 3399 |
Smallest Substring With Identical Characters II |
Same as above, but with 10^5 constraints, standard backtracking instantly hits Time Limit Exceeded. |
Memory-Crashing Recursion |
The call stack overflows trying to mutate 10^5 characters. |
Binary Search on Answer + Edge Cases |
The Optimized Tolerance Slicer |
Identical to 3398, but you must carefully handle the edge case where L=1 (which requires the string to be perfectly alternating like '0101' or '1010'). Check L=1 manually in $O(N)$, then binary search for L >= 2. |
For L=1, compare the string against "0101..." and "1010..." to count mismatched characters. For L >= 2, use the exact same slicing math: X / (L+1). |
Log Search + Edge Check $O(N \log N)$ |
Draw the alternating string check, followed by the binary search timeline. |
N/A |
Pointers and accumulators. $O(1)$ space. |
| 3400 |
Maximum Number of Matching Indices After Right Shifts |
Physically shift the second array right by 1, compare all elements. Shift again, compare. Repeat N times. $O(N^2)$. |
Quadratic Array Spinning |
Draw two arrays. Compare them. Rotate the bottom one. Compare them all again. |
KMP / String Matching (or $O(N^2)$ if constraints allow) |
The Offset Frequency Counter |
If constraints are small, brute force is fine. If large, note that an element `A[i]` matches `B[j]` if `B` is shifted by `(j - i + N) % N`. Calculate this required shift offset for every matching pair of values and find the most frequent offset. |
Draw array A and B. For a '5' at A[2] and a '5' at B[5], the shift needed is (5 - 2) = 3. Toss a coin into the "Shift by 3" bucket. Do this for all matching values. The heaviest bucket is the answer. |
Linear Map / Sorting $O(N)$ |
Draw a single pass mapping values to indices, then counting offset frequencies. |
Creating N physical copies of the shifted array. |
A frequency map of required shifts. $O(N)$ space. |
| 3401 |
Find Circular Gift Exchange Chains |
Unconstrained DFS/Joins tracing all paths, leading to exponential paths or redundant cycle checks. |
Unpruned Recursion Tree. |
Draw a root node, branch out to every receiver. Keep branching even if a node repeats, creating a massive, tangled tree. |
Recursive CTE (SQL) / Graph Cycle Detection with Visited Set. |
Directed Graph with Cycle Highlighting. |
Trace an arrow from giver to receiver. Stop and highlight the path when you hit a node you've already colored. |
Draw nodes as circles (people). Draw directed arrows between them. Color loops in red once closed. |
Linear Graph Traversal (O(V + E)). |
Draw V nodes and E edges. Check off each edge/node exactly once to show linear time bounding. |
Deeply stacked rectangular boxes representing max depth of recursive Call Stack frames. |
A 1D array representing a Hash Set (Visited Array) alongside the graph to track state. |
| 3402 |
Minimum Operations to Make Columns Strictly Increasing |
Iterate row by row per column; if `val <= prev`, add 1 in a `while` loop until it's strictly greater. |
Step-by-step Matrix State Changes. |
Draw the matrix. Cross out an invalid number, write the `+1` increment, cross it out again, repeat until valid. |
Greedy Prefix Maximum Tracking (O(N x M)). |
Column-by-column Downward Sweep. |
Sweep down a column carrying a `max_so_far + 1` value. Apply difference directly to cell. |
Draw straight arrows pointing down each column, with a box at the tip holding the `running_max` variable. |
Single Pass Shading (Matrix Coloring). |
Shade each grid cell once as you visit it, proving constant $O(1)$ work per cell. |
In-place matrix modification visually overwriting previous states heavily. |
A single small box labeled `prev_max` drawn above each column (representing $O(1)$ extra space). |
| 3403 |
Find the Lexicographically Largest String From the Box I |
Generate all valid string partitions, isolate substrings, and compare them lexicographically (O(N^3)). |
Substring Generation Tree. |
Write the string, draw brackets for every single start/end index combo, and list all combinations below. |
Two Pointers / Suffix Analysis / Greedy Char Selection. |
Pointer Sliding on a 1D Array. |
Place pointer `i` at the largest char found. Slide pointer `j` to compare subsequent chars. Update `i` if a larger sequence is found. |
Draw the string in array boxes. Draw arrows `i` and `j` below. Shift `j` right sequentially. |
Linear Scan Timeline. |
Draw a horizontal timeline of length N. Mark it with a single continuous forward line to show $O(N)$ execution. |
A massive table/list storing every newly generated string allocation. |
Two distinct dot-markers (integers `i`, `j`) pointing strictly to indices on the original string array. |
| 3404 |
Count Special Subsequences |
4-level nested loops to pick indices `(p, q, r, s)` and mathematically validate the condition (O(N^4)). |
Nested Loops Tree. |
Draw 4 concentric circles or nested curly braces, listing the permutations multiplier effect at each depth. |
Hash Map with Math Ratio (GCD) and Middle-element Fixing (O(N^2)). |
Split Array Ratio Mapping. |
Fix `q` and `r`. Map left ratios `(p, q)` to a frequency dictionary. Query right ratios `(r, s)` against the dictionary. |
Draw the array. Draw a vertical line between `q` and `r`. Left side maps into a table, right side reads from it. |
Area Bounding Box. |
Draw a 2D grid representing pairs. Show that we only iterate half the grid, proving $O(N^2)$ instead of $O(N^4)$. |
Gigantic list of combinations held in memory / deeply nested stack trace. |
A Hash Map Key-Value table (fraction -> count) drawn separately beside the 1D Array. |
| 3405 |
Count the Number of Arrays with K Matching Adjacent Elements |
Recursively generate all valid arrays of length n, then iterate through each to count if exactly k adjacent pairs match. (O(m^n)) |
Exponential N-ary Decision Tree. |
Draw a root node branching into m choices, each of those branching m times up to depth n, creating a massive explosion of paths. |
Combinatorics (nCr) + Fast Power Math. (O(N)) |
Combinatorial "Slots and Dividers" Block Grouping. |
Group the k matching pairs into joined blocks. Fill the first block with m options, and the remaining blocks with (m-1) options to avoid matching. |
Draw an array of n boxes. Draw connecting bridges between k pairs of boxes. Write 'm' in the first group, and 'm-1' in the rest. Multiply them. |
Math Formula Evaluation Timeline. |
Draw a linear array showing $O(N)$ precomputation of factorials, leading directly into an $O(1)$ math equation box. |
Extremely deep call stack storing the current array state being generated. |
Two 1D arrays of size N caching precomputed factorials and inverse factorials. |
| 3406 |
Find the Lexicographically Largest String From the Box II |
Generate all valid partitions of the string into numFriends parts, extract all substrings, and find the lexicographical max. (O(N^3)) |
Partition Generation Tree + Sorting List. |
Draw the string, mark combinations of cut points, and list every resulting chunk beneath to be evaluated. |
Largest Suffix Algorithm (Two Pointers) + Substring Truncation. (O(N)) |
Two-Pointer Race on a 1D String Array. |
Place pointers i and j. Compare characters at offset k. If one sequence is smaller, jump the losing pointer completely past the overlapping prefix. |
Draw the string as a char array. Place arrows i, j, and k below it. Cross out the losing pointer and redraw it jumped forward. |
Linear Progression Line with Skips. |
Draw a horizontal timeline of length N. Draw curved jumps skipping over chunks of the line to prove no character is checked more than twice. |
A massive 2D array or list storing every generated substring partition allocation. |
Three distinct dot-markers (integers i, j, k) pointing strictly to indices on the string array. |
| 3407 |
Substring Matching Pattern |
Test all possible replacements of the '*' wildcard with strings of length 0 to N, checking if it matches the text. (O(2^N)) |
Wildcard Expansion Tree. |
Draw the pattern. From the '*', draw branches replacing it with nothing, 1 char, 2 chars, etc., running full string matches on each. |
Greedy String Matching (Split by wildcard, search Prefix then Suffix). (O(N)) |
Two-Phase Linear Search Block Matching. |
Split pattern into pref and suff. Slide pref over string s until it matches. Mark the end index. Then slide suff over s starting strictly after that index. |
Draw s as a long rectangle. Draw pref and suff as two smaller colored blocks. Slide pref to snap it onto s. Then slide suff to snap onto the remainder. |
Sequential String Scanning. |
Draw two non-overlapping sliding windows moving strictly left-to-right across the string s, showing no backward backtracking. |
Generating and holding countless string permutations in memory. |
Two short string variables (prefix, suffix) and a single integer index pointer. |
| 3408 |
Design Task Manager |
Store tasks in a simple unsorted list. To execute the top task, scan the entire list to find the max priority. (O(N)) |
Linear Scan Line for every operation. |
Draw an unordered array. For every execTop or edit query, draw a looping arrow from index 0 to N-1 examining every element. |
Hash Map + Max-Heap/SortedList with Lazy Deletion. (O(log N)) |
Synchronized Dual-Structure Mapping. |
Add: Map ID to priority, push tuple to Heap. Edit: Update Map, push NEW tuple to Heap (leave old one). Exec: Pop Heap until popped priority matches Map priority. |
Draw a Map (Key->Value) on the left. Draw a Max-Heap (Tree) on the right. Show an edit updating the Map but leaving a "stale" crossed-out node in the Tree. |
Hash Table Direct Access + Binary Tree Traversal. |
Draw an $O(1)$ direct arrow into a map bucket, paired with a traversal path down a binary tree of height log N. |
A single 1D array of task objects. |
A Hash Table mapping IDs to metadata, alongside a balanced Tree or Max-Heap storing tuples. |
| 3409 |
Longest Subsequence With Decreasing Adjacent Difference |
Generate all 2^N subsequences. For each, check if absolute differences between adjacent elements are non-increasing. (O(N * 2^N)) |
Binary Subsequence Inclusion/Exclusion Tree. |
Draw an array. From each element, branch into "include" or "exclude", calculating differences for every valid path to create a massive tree. |
2D Dynamic Programming with Suffix Max Optimization (State: dp[num][diff]). (O(N * M)) |
2D DP Table with Suffix Max Collapsing. |
Iterate array. For current num, calculate diffs with previous values. Update cell based on prev state. Run a reverse loop to maintain suffix maximums for valid diffs. |
Draw a 2D grid (rows=nums, cols=diffs). Fill a cell by looking at the previous row, then draw a sweeping arrow right-to-left updating suffix maxes. |
2D Grid Traversal. |
Draw an outer N loop enclosing an inner max_val loop, represented as a bounded rectangle matrix being shaded cell by cell. |
Call stack depth N storing current subsequence elements and their difference constraints. |
A fixed-size 2D matrix of dimensions max_val by max_val (e.g., 301 x 301). |
| 3410 |
Maximize Subarray Sum After Removing All Occurrences of One Element |
For every unique element, create a copy of the array with that element removed, then run Kadane's algorithm. (O(N x K)) |
Multi-Array Linear Scans. |
Draw the original array. Below it, draw N smaller arrays, each missing a specific number, with an arrow running across each one. |
Segment Tree (Point Updates) tracking Max Subarray Sum or DP Prefix mapping. (O(N log N)) |
Segment Tree Node bubbling. |
Group indices by value. For a target value, update its tree leaves to 0. Bubble up the `maxSubarray` state to the root. Check root. Restore leaves. |
Draw a binary tree. Point to specific leaf nodes (occurrences of 'X'), cross them out, and draw upward arrows updating the parent nodes' max sum. |
Tree Height Traversal. |
Draw N operations, each traveling up a tree path of height log N, bounding the time cleanly. |
N separate arrays held in memory for testing permutations. |
A 1D array of size 4N representing the Segment Tree structure. |
| 3411 |
Maximum Subarray With Equal Products |
Nested loops checking all subarrays. Calculate Product, LCM, and GCD from scratch for every single sub-segment. (O(N^3)) |
Triply Nested Loops. |
Draw the array. Bracket indices i to j. Below, draw three separate looping arrows re-calculating Prod, LCM, and GCD from scratch. |
Incremental Accumulation + Upper Bound Pruning (O(N^2)). |
Sliding Right Bound with Running Accumulators. |
Fix left pointer. Slide right pointer. Multiply running prod, update running LCM/GCD with just the new element. Break early if prod exceeds maximum possible LCM. |
Draw the array. Box i to j. Below the box, keep three variables (Prod, LCM, GCD). As j moves right, cross out the old variable value and write the new one. |
Upper Half Matrix with Pruned Corners. |
Draw a 2D grid of pairs (i,j). Shade the upper triangle, but cross out large chunks of the grid to show the pruning optimization. |
Call stack or memory storing intermediate sliced arrays. |
Three $O(1)$ integer variables (`prod`, `lcm`, `gcd`). |
| 3412 |
Find Mirror Score of a String |
For each character, scan backwards character-by-character to find the closest unmarked mirror letter. (O(N^2)) |
Left-to-Right Scan with Backward Searching. |
Draw the string. For index i, draw an arrow looping backwards all the way to index 0, searching for a match. |
Array of 26 Stacks / Deques mapping available indices. (O(N)) |
26 Bucket Stacks. |
Read char. Find its mirror. Check the mirror's stack. If not empty, pop the index and calculate score. Else, push current index into char's stack. |
Draw 26 vertical slots. Read 'a', put its index in 'a' slot. Read 'z', look at 'a' slot, pull out the top index, and connect them with a line. |
Single Horizontal Pass. |
Draw a single continuous arrow moving strictly left to right across the string array. |
A boolean array or set tracking the "marked" state of every character. |
An array of 26 Stacks, storing integer indices as they appear. |
| 3413 |
Maximum Coins From K Consecutive Bags |
Test every start position on the number line from `min(li)` to `max(ri)` and sum coins within the `k` window. (O(Max_Coordinate)) |
Dense Sliding Window over Sparse Line. |
Draw a massive 1..10^9 number line. Draw a `k` sized bracket sliding exactly 1 unit right repeatedly, calculating empty spaces needlessly. |
Sort Intervals + Sliding Window snapped to Interval Boundaries (Two passes: Left/Right). (O(N log N)) |
Interval Snapping Window. |
Sort intervals. Snap window's left edge to an interval's left edge. Sum fully enclosed intervals. Add partial overlap of the rightmost interval. Repeat reversed. |
Draw intervals as horizontal blocks. Draw a rigid bracket of length `k`. Snap the bracket's edge perfectly to the start of a block and shade the contents. |
Two Pointers on Array Timeline. |
Draw a sorting step tree, followed by two pointers (j chasing i) sliding over an array of size N, proving linear traversal post-sort. |
A massive dense array of size 10^9 representing the whole number line. |
An $O(N)$ array holding the parsed `[left, right, coins]` intervals. |
| 3414 |
Maximum Score of Non-overlapping Intervals |
Generate all combinations of up to 4 intervals. Filter out the ones that overlap. Sum the weights and find the max. (O(N^4)) |
Combinatorial Explosion Tree. |
Draw the list of intervals. Draw 4 branching lines pointing to different combinations. Draw a big red X if they overlap. |
Sort by End Time + Binary Search + 2D Dynamic Programming (dp[i][quota]). (O(N log N)) |
DP Table with Binary Search Jumps. |
At interval i with `quota`, calculate `skip` (move to i+1). For `pick`, add weight and do a binary search to jump to the first non-overlapping interval. |
Draw intervals sorted by end time. From one block, draw a "skip" arrow to the next, and a "pick" arrow jumping backwards to the first non-overlapping block. |
N x 4 Grid Traversal with Log N Steps. |
Draw an N x 4 grid matrix. Inside each cell, draw a small binary search tree to indicate the log N cost per state calculation. |
Call stack depth up to 4, holding countless intermediate list allocations. |
An N x 5 DP Memoization Table storing Tuples of `(Weight, [Indices])`. |
| 3415 |
Find Products with Three Consecutive Digits |
Nested loops checking every 3-character substring of the string to see if all three are numeric digits. $O(N^2)$ |
Overlapping Substring Brackets. |
Draw the string. Draw a bracket over chars 0-2, then 1-3, then 2-4, evaluating each block completely from scratch. |
Sliding Window / Regex Pattern Matching. $O(N)$ |
Rigid 3-Slot Sliding Window. |
Create a 3-slot window. Slide it one character right. If the new char is a digit, keep checking; if not, jump the window past the failure. |
Draw the string. Draw a box around 3 chars. Slide the box right continuously, highlighting consecutive digits in green. |
Single Horizontal Pass. |
Draw one straight line above the string pointing right to represent an $O(N)$ single scan. |
Multiple temporary 3-character string allocations in memory. |
Two integer pointers (start, end) or a compiled Regex state machine. |
| 3416 |
Subsequences with a Unique Middle Mode II |
Same as 3395 but with larger constraints. $O(N^5)$ is mathematically impossible to run. |
Combinatorial Nightmare |
(See 3395) |
Advanced Combinatorics + Inclusion-Exclusion |
The Math-Driven Pivot |
Instead of checking all pairs, calculate the *total* possible valid prefixes/suffixes for a locked middle element, and strictly subtract the exact invalid patterns (where another number appears 2 or 3 times in the subsequence of 5) using precomputed frequency maps. |
Lock the middle element. Calculate total ways to pick 2 from the left and 2 from the right. Subtract the specific subsets where a competing number out-frequencies your locked middle. |
Linear Scan with Constant Math $O(N)$ |
Draw a timeline. The math calculations inside the loop are $O(1)$ combinations based on tracked frequencies. |
Memory crash. |
Frequency tracking maps. $O(N)$ space. |
| 3417 |
Zigzag Grid Traversal With Skip |
Traverse the grid cell by cell keeping a boolean toggle variable. Conditionally add to result and manually manage boundary direction changes. $O(M \cdot N)$ |
Winding Path with Checkmarks. |
Draw a grid. Draw a snake-like path through it. Place a checkmark on the 1st cell, an X on the 2nd, checkmark on 3rd, etc. |
Row-based Parity Processing + Array Slicing. $O(M \cdot N)$ |
Alternating Row Reversals. |
Read rows top to bottom. If row index is odd, reverse the row. Then flat-map the grid and take every alternating element. |
Draw the grid. Draw a reverse arrow next to odd rows. Redraw the grid with odd rows flipped, then circle every other element. |
Row-by-Row Block Processing. |
Draw M boxes (rows). Shade them sequentially to show $O(M \cdot N)$ total operations, completely avoiding complex coordinate math. |
A complex set of state variables (x, y, dx, dy, skip_flag) updated per cell. |
A single 1D result array, building elements sequentially. |
| 3418 |
Maximum Amount of Money Robot Can Earn |
Recursive DFS finding all paths from top-left to bottom-right, branching into "use charge" or "take penalty" at every negative cell. $O(3^(M+N)$) |
Exploding 3-Way Grid Path Tree. |
Draw a start node. Branch to Right and Down. At a negative cell, branch into "Neutralize Right", "Neutralize Down", "Take Hit Right", "Take Hit Down". |
3D Dynamic Programming / Grid DP (State: row, col, neutralizations_left). $O(M \cdot N \cdot K)$ |
Layered 2D DP Grids. |
Imagine 3 identical grids stacked on each other (for 0, 1, and 2 charges left). Update a cell by checking the max of adjacent cells in its layer AND the layer below it (if neutralizing). |
Draw 3 grids side-by-side. Draw arrows from Grid 1 (1 charge) to Grid 0 (0 charges) representing a neutralization jump. |
3-Layer Matrix Traversal. |
Draw a 3D box of size M x N x 3. Shade it from top-left-front to bottom-right-back to prove bounded polynomial time. |
Call stack depth up to M+N, repeatedly calculating overlapping subproblems. |
A 3D DP Matrix of dimensions [M][N][3] storing the max money at that state. |
| 3419 |
Minimize the Maximum Edge Weight of Graph |
Try every possible weight threshold from 1 to Max_W. For each, run DFS from all N nodes to see if they can reach node 0. $O(W \cdot V \cdot E)$ |
Repeated Global DFS Scans. |
Draw the graph. Below it, write threshold 1, 2, 3... For each number, draw N separate search trees trying to reach node 0. |
Binary Search on Answer + Reversed Graph Traversal. $O(E \log W)$ |
Reversed Flow with Binary Search Pruning. |
Reverse all directed edges. Binary search a weight W. Start BFS/DFS only from node 0. Ignore edges > W. If you visit all nodes, W is valid. |
Draw the graph with arrows pointing BACKWARDS from 0. Erase any arrow heavier than threshold W. Check if all nodes are colored. |
Log W Number of BFS Trees. |
Draw a binary search timeline. At a few points, drop an arrow down to a single V+E graph traversal box. |
Standard adjacency list, but memory thrashes heavily on the recursive stack. |
A single reversed Adjacency List `g[destination].append(source)` and a Boolean Visited Array. |
| 3420 |
Count Non-Decreasing Subarrays After K Operations |
Generate all subarrays, determine operations needed to make each non-decreasing, and sum. $O(N^3)$. |
Sliding Re-Calculation Window |
Bracket every subarray. Traverse the bracket to calculate leveling costs. |
Monotonic Stack + Two Pointers |
The Bounded Leveling Tool |
Use a monotonic decreasing stack to efficiently calculate the cost to "level up" elements in a sliding window to maintain a non-decreasing order. If the cost exceeds K, shrink the window from the left and update the cost dynamically. |
Draw the array. Slide a window right. If a number dips, you must "fill" that dip with operations to match the previous max. Track these filling costs in a stack. If you run out of K operations, move the left bound forward and refund the operations. |
Amortized Two-Pointer $O(N)$ |
Draw two pointers moving strictly left-to-right. Stack pushes/pops are $O(1)$ amortized. |
Tracking costs for all N^2 subarrays independently. |
A Monotonic Stack storing indices and costs. $O(N)$ space. |
| 3421 |
Find Students Who Improved |
For every student record, scan the entire dataset again to find earlier dates and compare scores. $O(N^2)$ |
N x N Cross-Referencing Matrix. |
Draw a list of students. For the first student, draw looping arrows pointing to every other row to check for date/score matches. |
Group By / Sort by ID & Date + Linear Scan. $O(N \log N)$ |
Grouped & Chronological Timelines. |
Sort data by Student ID, then by Date. Read top to bottom. If the ID matches the previous row, compare the current score to the stored "first score". |
Draw the table rows. Group identical IDs into color-coded blocks. Draw a straight downward arrow tracking the first and last score in each block. |
Sorting Tree + Linear Scan Array. |
Draw a Merge Sort tree (O(N log N)), pointing to a flat array that gets scanned exactly once (O(N)). |
Massive call stack or memory holding N^2 cross-joined table rows. |
In-place sorting space or a single Hash Map tracking the "first_score" for each student ID. |
| 3422 |
Minimum Operations to Make Subarray Elements Equal |
Extract every subarray of size K. Sort each subarray to find the median, then calculate absolute differences. $O(N \cdot K \log K)$ |
Repeated Array Slicing & Sorting. |
Draw the array. Box a window of size K. Copy it out, draw a sort operation, find the middle, and tally differences. Repeat for next window. |
Sliding Window + Two Heaps (Min/Max) to maintain dynamic median. $O(N \log K)$ |
Dual Balancing Scales (Heaps). |
Keep lower half of window in Max-Heap, upper half in Min-Heap. Slide window: remove old element, insert new element, rebalance scales, calculate cost dynamically. |
Draw the array. Draw a Max-Heap triangle and Min-Heap triangle below it. As the window moves, cross out one node and draw a new one, showing rebalancing. |
Logarithmic Update Steps. |
Draw a single pass over the array (O(N)), with each step taking a short traversal down a binary heap tree (O(log K)). |
Memory thrashing from creating and destroying subarrays of size K endlessly. |
Two balanced Tree/Heap structures, strictly capped at combined size K. |
| 3423 |
Maximum Difference Between Adjacent Elements in a Circular Array |
Iterate using modulo arithmetic `(i+1)%n` for every element to wrap around, repeatedly executing modulo division. $O(N)$ but high constant time. |
Circular Clock-Face Traversal. |
Draw the array as a circle. Point an arrow from each number to the next, calculating the division remainder at every single step. |
Linear loop checking `nums[i]-nums[i-1]` + one explicit edge check for `nums[N-1]-nums[0]`. $O(N)$ |
Straight Line with a Wrap-around String. |
Scan the array left-to-right updating `max_diff`. At the end, imagine the array folding in half so the first and last elements touch, and compare them. |
Draw the array horizontally. Draw arching arrows between adjacent cells, then draw one giant arching line from the last box back to the first. |
Linear Track + 1 Jump. |
Draw a horizontal timeline representing N steps, plus one distinct dot at the end representing the final $O(1)$ jump. |
Redundant variables calculated in the call stack per iteration. |
Two $O(1)$ tracking integers (`current_diff`, `max_diff`). |
| 3424 |
Minimum Cost to Make Arrays Identical |
Generate all N! permutations of pairings between the two arrays to find the absolute minimum cost mapping. $O(N!)$ |
Bipartite Graph with Exploding Mappings. |
Draw Array A and Array B. Draw criss-crossing lines from every element in A to every element in B, creating an unreadable web. |
Sort Both Arrays + Sequential Pairing. $O(N \log N)$ |
Parallel Sorted Arrays with Vertical Zippers. |
Sort both arrays independently in ascending order. Pair the smallest with the smallest, the second smallest with the second smallest, etc., zipping them together. |
Draw Array A and Array B. Write 'SORT' and redraw them ordered. Then, draw straight vertical lines connecting index 0 to 0, 1 to 1, etc. |
Sort Trees followed by Linear Match. |
Draw two parallel merge-sort trees to represent the $O(N \log N)$ step, funneling into a single $O(N)$ flat array comparison step. |
N! permutations overwhelming the memory stack. |
In-place sorting modifies the original arrays, requiring only $O(1)$ or $O(\log N)$ auxiliary space. |
| 3425 |
Longest Special Path |
Run DFS from every single node. For each path, check if all node values are unique using a Set. $O(N^2)$ |
N-rooted DFS Tree Forest. |
Draw the graph N times. In each copy, highlight a different node as the root and draw arrows exploring all paths from it. |
DFS with Sliding Window on Tree Paths + Hash Map. $O(N)$ |
Path Deque with Ancestor Value Mapping. |
Traverse DFS. Keep a map of "Value -> Last Depth Seen". If current value exists in map at depth D, the special path must start below D. |
Draw a tree. Draw a vertical line next to the current path. Mark indices on the line and arrows jumping to previous occurrences of values. |
Single Global DFS Traversal. |
Draw one tree. Shade each edge and node exactly twice (on entry and exit) to show $O(N)$ total work. |
N separate sets created and destroyed in the heap during exploration. |
One global Hash Map and one path array (acting as a manual stack) of size H (height of tree). |
| 3426 |
Manhattan Distances of All Arrangements of Pieces |
Generate all (R x C Choose K) piece arrangements. For each, calculate pairwise Manhattan distances. $O(\text{Exponential})$. |
Factorial Grid Layouts |
Draw a grid. Place K pieces. Measure them. Move one piece. Measure again. |
Math (Contribution to Sum) + Combinatorics |
The Single-Axis Separator |
Instead of looking at grids, calculate how much a single pair of coordinates (x_1, x_2) contributes to the TOTAL sum across ALL valid boards. Distance on X-axis and Y-axis are independent. Multiply the distance by the number of ways to place the remaining K-2 pieces. |
Pick two columns, c_1 and c_2. The horizontal distance is |c_1 - c_2|. If two pieces are placed in these columns, there are (R x C - 2 Choose K - 2) ways to place the rest of the pieces. Multiply distance x combinations. Sum for all column pairs and row pairs. |
Mathematical Formulation $O(R + C)$ |
Draw two simple loops (one for rows, one for columns) calculating formulas. |
Generating physical grids. |
A few large integer accumulators for modulo math. $O(1)$ space. |
| 3427 |
Sum of Variable Length Subarrays |
For each index i, determine the start index. Then, use a loop to sum all elements from start to i. $O(N^2)$ |
Dynamic Width Subarray Brackets. |
Draw the array. For index 0, box it. For index 1, box 0-1. For index 2, box it according to the rule, and manually sum values in each box. |
Prefix Sum Array. $O(N)$ |
Sub-segment Subtraction. |
Pre-calculate the running sum. For any range [start, i], the sum is simply `prefix[i] - prefix[start-1]`. |
Draw the array and a "Prefix Sum" row below it. Draw two vertical lines on the prefix row; the difference between them is the subarray sum. |
Two Sequential Linear Passes. |
Draw one arrow for building the prefix sum (O(N)), then another arrow for calculating the final total (O(N)). |
No extra memory, but redundant CPU cycles re-summing overlapping ranges. |
A single 1D array of size N to store the prefix sums. |
| 3428 |
Maximum and Minimum Sums of at Most K Subsequences |
Generate every possible subsequence of size 1 to K. For each, find the min and max, then sum them up. $O(2^N)$ |
Bounded Subsequence Tree. |
Draw a tree that branches for "take" or "skip", but prune all branches deeper than K. Even pruned, it remains massive. |
Sorting + Contribution Technique + Combinatorics. $O(N \log N)$ |
Sorted Element Contribution Mapping. |
Sort the array. For `nums[i]`, count how many subsequences of size 1..K it is the "Maximum" in (all elements to its left) and "Minimum" in (all elements to its right). |
Draw the sorted array. Pick an element. Draw arrows to all smaller elements. Write the math formula (nCr) for choosing K-1 neighbors from those arrows. |
Sorting + Linear Math Pass. |
Draw an $O(N \log N)$ sort step, then a single $O(N)$ loop that calls an $O(1)$ combination function at each step. |
A list of all generated subsequences stored in the heap. |
Two 1D arrays for factorials/inverse factorials (to compute nCr in $O(1)$). |
| 3429 |
Paint House IV |
Try every possible color combination for every house, checking constraints for adjacent houses and the "equidistant" house from the end. $O(3^N)$ |
Decision Tree with Constraint Pruning. |
Draw a row of houses. At house 1, branch into 3 colors. At house 2, branch again, crossing out paths that violate the adjacency or "House IV" rule. |
Dynamic Programming (State: index, last_color_left, last_color_right). $O(N)$ |
2D DP Table of color pairs. |
Process houses from outside-in (pairs i and n-i-1). DP state stores the min cost for the current pair given the colors of the previous outer pair. |
Draw the row of houses. Draw arrows pointing from both ends toward the middle. In the middle, draw a 3x3 grid of possible color pairings. |
Linear Progress toward Center. |
Draw a line of length N/2. Shade it block by block to show $O(N)$ total complexity. |
Recursive call stack depth N. |
A 3D DP table or memoization map of size [N/2][3][3]. |
| 3430 |
Maximum and Minimum Sums of at Most Size K Subarrays |
Generate every subarray of length 1 to K, find the min and max for each, and sum them. $O(N \cdot K)$ |
Sliding Window Brackets of Variable Sizes. |
Draw the array. Below it, draw brackets of size 1, then size 2... up to K. In each bracket, circle the largest and smallest numbers. |
Monotonic Stack + Contribution of Each Element + Math (Counting valid subarrays). $O(N)$ |
Boundary Range Bars (Left & Right Limits). |
For each element, find the nearest smaller/larger elements to the left and right. Calculate how many subarrays of size <= K it dominates as min/max. |
Draw the array. For one element, draw a horizontal bar reaching left and right until it hits a larger/smaller value. Label the bar length. |
Two Stack-Based Linear Passes. |
Draw a horizontal timeline representing a single pass for "Min" and a single pass for "Max" (using Monotonic Stacks). |
A massive list of min/max pairs stored for every possible subarray length. |
Two 1D arrays (`left_limit`, `right_limit`) of size N and a single stack structure. |
| 3431 |
Minimum Unlocked Indices to Sort Nums |
Try every subset of 'locked' indices to unlock and see if any combination allows sorting the array (1s, then 2s, then 3s). $O(2^N)$ |
Subset Power Set Decision Tree. |
Draw a root node branching into "unlock index 0" or "keep locked", repeating for N indices until reaching 2^N leaves. |
Finding Bound Indices (Last 1, First 3) + Linear locked-state count. $O(N)$ |
Three-Zone Segmentation. |
Identify where 1s must end and 3s must start. Any 1 appearing after a 3 makes it impossible. Count locked indices in the wrong zones that must be moved. |
Draw the array. Divide it into three colored boxes (1s, 2s, 3s). Any number that is in the "wrong" box and is 'locked' gets a red cross. |
Single Linear Array Scan. |
Draw one straight arrow moving from index 0 to N-1, highlighting the $O(N)$ traversal. |
Recursion stack storing 2^N branching states. |
$O(1)$ auxiliary space using 4-5 integer variables to store key boundary indices. |
| 3432 |
Count Partitions with Even Sum Difference |
Iterate through all split points. For each, sum the left side and right side, then check if their difference is even. $O(N^2)$ |
Dividing Line Sweep. |
Draw the array. Draw a vertical line after index 0, then 1, etc. At each step, write the sum of elements on both sides and their difference. |
Parity Logic (Difference is even iff Total Sum is even). $O(N)$ |
Total Sum Parity Bucket. |
Calculate the total sum of the array. If the total sum is even, every single split point (N-1 total) results in an even difference. Otherwise, 0. |
Draw the whole array as one big block. Write the "Total Sum" above it. If totalSum % 2 == 0, write "All N-1 splits valid". |
Single Reduction Operation. |
Draw an arrow pointing to a single summation box, representing the $O(N)$ sum calculation. |
N pairs of sums (Left/Right) stored in the heap. |
One $O(1)$ integer variable for the `totalSum`. |
| 3433 |
Count Mentions Per User |
For every message event, iterate through all users to check if they are "online" and increment their mention count. $O(M \cdot N)$ |
Global User Status Matrix. |
Draw a table with Users as columns and Events as rows. For every message row, fill in status for every single user column. |
Sorting Events + Lazy Counter for "ALL" mentions. $O(M \log M + N)$ |
Event Simulation Timeline. |
Sort all events by timestamp. Process "offline" events to update user online-status. For "ALL" mentions, increment a global counter instead of updating every user. |
Draw a horizontal timeline. Place 'M' (Message) and 'O' (Offline) marks. Below, draw a single "Global Counter" box that increments on 'ALL'. |
Sorted Timeline Traversal. |
Draw a sorting tree followed by a single line with M segments, proving $O(M \log M + M)$ complexity. |
N x M matrix holding the history of user statuses. |
Two 1D arrays of size N: `mentions_count` and `next_online_time`. |
| 3434 |
Maximum Frequency After Subarray Operation |
Try every possible subarray [i, j] and every possible value to add, then re-count the frequency of K. $O(N^3 \\text{cdot Val})$ |
Subarray Shifting Brackets. |
Draw the array. Shade a subarray. Write "+X" inside it. Count all 'K's in the whole array again. Repeat for every possible subarray and X. |
Modified Kadane's Algorithm for each distinct value T. $O(50 \cdot N)$ |
Gain/Loss Waveform. |
For a target value T, treat T as +1 and K as -1. Use Kadane's to find the max subarray sum (the "Gain"). Result = Total K count + Max Gain. |
Draw a bar graph for value T. T nodes go UP, K nodes go DOWN. Circle the highest mountain (subarray) in the graph. |
Constant-Factor Linear Passes. |
Draw 50 parallel lines, each representing an $O(N)$ Kadane's scan, showing the total $O(50N)$ complexity. |
Massive 3D matrix storing all frequency outcomes of subarray operations. |
A small fixed-size frequency map and two 1D arrays for current/max sums. |
| 3435 |
Frequencies of Shortest Supersequences |
Generate all permutations of merging strings, find the shortest, and count frequencies. $O(\text{Exponential})$. |
String Merging Web |
Draw two strings. Interleave them in every possible way to find the shortest overlap. |
DP on Strings / Bitmasking |
The Character-Overlap Maximizer |
Find the Longest Common Subsequence (LCS). The Shortest Common Supersequence length is L_1 + L_2 - LCS. To track frequencies, trace back the DP table, tracking character choices that lead to optimal paths. |
Draw a 2D grid comparing String 1 and String 2. Trace the path of the LCS. Every character not in the LCS must be included exactly once. Characters in the LCS are shared. Build a frequency map from this optimal path. |
2D Matrix Processing $O(N \cdot M)$ |
Draw an N x M matrix being filled, followed by a linear traceback path. |
Storing thousands of merged string variations. |
A 2D DP matrix. $O(N \cdot M)$ space. |
| 3436 |
Find Valid Emails |
Manually split string by '@' and '.', check every character in each substring for alphanumeric rules using nested loops. $O(N^2)$ |
Substring Fragmentation Map. |
Draw the email string. Draw several boxes around split segments. Inside each box, draw arrows checking every char index. |
Regular Expression (Regex) Parsing. $O(N)$ |
Finite Automata (FSM) State Diagram. |
Start in "User" state. Read chars until '@', move to "Domain" state. Read until '.', move to "TLD" state. If a bad char is met, move to "Reject". |
Draw 4 circles (Start, User, Domain, TLD). Draw arrows between them labeled with allowed character types (e.g., [a-z], @, .). |
Single Pass Stream. |
Draw a single conveyor belt with the email string moving through a "Regex Filter" box exactly once. |
Creating multiple intermediate string objects for each split part. |
A single boolean state variable or a pointer to the compiled Regex engine. |
| 3437 |
Permute Adjacent Array Elements |
Generate all N! permutations and check which ones only involve adjacent swaps from the original. $O(N \cdot N!)$ |
Factorial Permutation Tree. |
Draw a root. Branch it N times. Branch each N-1 times. The tree will be too large to finish drawing. |
Greedy Swapping / Parity-Based Reordering. $O(N)$ |
Bubble-Hop Visualization. |
Identify target positions. If an element is at index i and needs to go to j, check if |i-j| = 1. If not, it's impossible. |
Draw the array twice (Before/After). Draw short "X" shaped arrows between adjacent indices that swapped. |
Linear Pairwise Scan. |
Draw a line with N-1 segments. Mark each segment once to show you only check each adjacent pair. |
A massive table storing N! array configurations. |
In-place array modification or one auxiliary 1D array. |
| 3438 |
Find Valid Pair of Adjacent Digits in String |
For every index i, check if s[i] == s[i+1]. If true, run another loop over the entire string to count frequencies of that digit. $O(N^2)$ |
Nested Scanning Loop. |
Draw the string. Circle index i and i+1. Then draw a giant looping arrow that circles back to index 0 and scans everything to count. |
Precomputed Frequency Map + Single Pass. $O(N)$ |
Frequency Tally + Sliding Pointer. |
First, tally all digits into a 0-9 array. Then, slide through the string once. If s[i] == s[i+1] AND both counts equal the digit value, stop. |
Draw 10 buckets (0-9). Fill them. Then draw an arrow sliding under the string checking two digits at a time against the buckets. |
Double-Pass Timeline. |
Draw one $O(N)$ line for tallying, followed by a second $O(N)$ line for finding the pair. Total 2N steps. |
Potentially N temporary frequency maps if created inside the loop. |
A fixed-size array of 10 integers (counts for digits 0-9). |
| 3439 |
Reschedule Meetings for Maximum Free Time I |
Try moving every meeting to every possible start/end time and calculate the resulting gaps. $O(N^2)$ |
Exhaustive Interval Shifting. |
Draw a timeline. Pick a block (meeting). Draw dotted arrows moving it to 10 different spots. Repeat for all blocks. |
Sliding Window over Gap Arrays. $O(N)$ |
Gap Sum Window. |
Convert meetings into a list of "Gap" sizes between them. If you can move k meetings, you can merge k+1 adjacent gaps. Use a sliding window to find the max sum of k+1 gaps. |
Draw the gaps as numbers in an array. Draw a bracket of size k+1. Slide the bracket right and write the sum above each position. |
Sliding Window Timeline. |
Draw a timeline of N gaps. Draw one bracket moving from left to right to show it visits each gap exactly twice (entry/exit). |
N/A - Mostly high time complexity from nested loops. |
A single 1D array of size N+1 to store the gap lengths. |
| 3440 |
Reschedule Meetings for Max Free Time II |
For each meeting, try moving it to every possible empty millisecond in the entire event duration. $O(N x \text{eventTime})$ |
Dense Pixel-by-Pixel Grid. |
Draw a timeline. For one meeting block, draw thousands of tiny arrows pointing to every single empty spot on the line. |
Top-3 Largest Gaps + Prefix/Suffix Max Gaps. $O(N)$ |
Gap "Podium" and Sliding Window. |
List all gaps. Keep the 3 largest. For meeting i, merge the gap before and after it. Check if meeting i fits into any OTHER large gap. |
Draw the gaps as circles. Write the sizes inside. Circle the 3 biggest. Draw a "Bridge" over meeting i connecting its adjacent gaps. |
Constant-Lookback Linear Pass. |
Draw a timeline of N meetings. At each meeting, draw a single arrow checking a "Top 3" list (O(1) check). |
Minimal, but huge overhead from nested loops. |
A small array of size 3 (the "Podium") tracking the largest gap sizes and their indices. |
| 3441 |
Minimum Cost Good Caption |
Try all 26^N strings where every character appears in groups of at least 3. $O(26^N)$ |
Exponential Character Decision Tree. |
Draw a root. Branch 26 times. At depth 2, branch 26 times again. It becomes an unreadable cloud. |
DP with Lexicographical Greedy Path. $O(26 x N)$ |
2D Grid (Chars x Indices) with Backpointers. |
Fill a grid where `dp[i][char]` is min cost. For each cell, look at the min cost of previous cells that allow a group of 3+. |
Draw a 26 x N grid. In cell (c, i), draw arrows back to indices i-3, i-4, i-5 of the same character. |
Bounded Search Space (26 x N). |
Draw a rectangle representing the 26 x N DP table. Shade it row-by-row to show total operations. |
Recursive stack depth N storing 26^N possible states. |
A 26 x N 2D array of integers, or a rolling 1D array if only the current cost is needed. |
| 3442 |
Max Diff Between Even and Odd Frequencies I |
Nested loops to compare every character's frequency with every other character's frequency. $O(26^2)$ |
All-Pairs Comparison Matrix. |
Draw a 26x26 grid of letters. Draw a line between every possible pair of letters to compare their counts. |
Extreme Frequency Identification. $O(N)$ |
Bucket Sorting for Max/Min. |
Count all characters. Filter into "Odd Bucket" and "Even Bucket". Pick the highest from Odd and lowest from Even. |
Draw two boxes: "Odd" and "Even". Put frequencies in them. Circle the biggest in Odd and smallest in Even. |
Single Scan Line. |
Draw one straight line for the string scan, and a small dot representing the 26-element loop. |
Storing all frequency differences in a list. |
A fixed-size array of 26 integers. |
| 3443 |
Max Manhattan Distance After K Changes |
Try every possible combination of K character flips in the string. $O((N \text{Choose} K)$) |
Combinatorial Choice Tree. |
Draw the string. Circle K characters to flip. Repeat for every possible set of K circles. |
Greedy Quadrant Invariance. $O(N)$ |
Quadrant Force Vectors. |
Assume the goal is NE (North-East). Any S or W move is "bad". Use K to flip as many bad moves to good as possible. Repeat for 4 quadrants. |
Draw a compass (N, S, E, W). Pick a quadrant (e.g., top-right). Cross out "S" and "W" and draw them as "N" and "E" instead. |
Four Linear Scans. |
Draw 4 parallel lines, each representing one $O(N)$ pass for a specific quadrant direction. |
Massive list of all possible resulting coordinate paths. |
$O(1)$ space using simple integer counters (N, S, E, W). |
| 3444 |
Min Increments for Target Multiples |
Exhaustively try every combination of `nums` elements to cover the `target` array. $O(N^\text{target}_\text{len})$ |
Bipartite Matching Expansion. |
Draw `nums` on left and `target` on right. Draw lines from every `num` to every `target`, then try all subsets of lines. |
Bitmask DP over Target Array + LCM. $O(N x 2^|\text{target}|)$ |
State Transition Lattice. |
For each `num`, calculate cost to cover any subset of `target` (using LCM). Update `dp[mask]` with the min cost. |
Draw 16 nodes (for bitmask 0000 to 1111). Draw arrows between nodes representing adding a new `num` to cover more targets. |
2D DP Grid (N x 16). |
Draw a table with N rows and 16 columns. Shade it row by row to show the bounded complexity. |
Huge recursion stack depth from exploring all possible pairings. |
A 1D array of size 16 (or 2^|target|) to store current min costs for each mask. |
| 3445 |
Max Difference Between Even and Odd Frequency II |
Iterate all substrings of length ≥ k, calculate frequencies of all digits 0-4, and find max diff. $O(N^2)$ |
Triangular Subarray Grid. |
Draw a triangle where each row i has i cells representing all substrings ending at i, each requiring a full count scan. |
Prefix Parity State + Sliding Window on Pair Combinations (20 pairs). $O(20 \cdot N)$ |
2x2 Parity Transition Matrix. |
For a pair (a, b), track counts. Maintain min prefix difference for each of the 4 parity states (Even-Even, Even-Odd, etc.). |
Draw a 2x2 grid. Move a marker between quadrants as you scan. Record the minimum value seen in each quadrant to subtract. |
20 Parallel Linear Tracks. |
Draw 20 horizontal lines of length N. Shade each once to show the constant-multiplier linear time. |
N² frequency maps or massive list of substring stats. |
Five integer counters and a 4-element "min-prefix" array per pair. |
| 3446 |
Sort Matrix by Diagonals |
For every diagonal, extract elements into a list, sort them, and manually place them back based on coordinates. $O(N² \log N)$ |
Diagonal Sweep Arrows. |
Draw the matrix. Draw arrows starting from column 0 and row 0. Each arrow represents an independent list sort. |
Diagonal Indexing (i - j) + HashMap/Bucket Sort. $O(N²)$ |
Color-coded Coordinate Groups. |
Group cells by (i - j). Diagonals share the same result. Sort each bucket and re-map based on the non-increasing/non-decreasing rule. |
Draw the matrix. In each cell, write the value (i - j). Circle all cells with the same number to reveal the diagonals. |
Linear Matrix Pass. |
Draw a grid and shade it in one continuous S-shaped pass to show you visit each cell exactly twice. |
Dozens of temporary list allocations during diagonal extraction. |
A single Hash Map where keys are (i - j) and values are sorted arrays. |
| 3447 |
Assign Elements to Groups with Constraints |
For each group size G, iterate through every element E to find the first divisor. $O(G \cdot E)$ |
Dense Connection Web. |
Draw Groups on the left and Elements on the right. Draw lines from every group to every element to test divisibility. |
Sieve of Eratosthenes / Harmonic Series Mapping. $O(M \log M + N)$ |
Number Line Multiples Marking. |
For each unique element X, jump along a number line at 2X, 3X, etc., marking the first index of X that hits that multiple. |
Draw a 1D array of size Max(Groups). For element '2' at index '0', write '0' at indices 2, 4, 6, 8... across the array. |
Harmonic Progression Curve. |
Draw a sequence of decreasing jumps (N/2, N/3, N/4...) to illustrate the log N summation of work. |
Negligible, but extremely high CPU time due to redundant division checks. |
A single "Best Index" array of size Max_Value (10^5). |
| 3448 |
Count Substrings Divisible By Last Digit |
Check every substring (i, j) by converting to a number and dividing by digit at j. $O(N²)$ with BigInt handling. |
Triangular State Matrix. |
Draw a triangle of substring results. Each cell requires a division operation on a potentially large number. |
DP with Remainder State for each Divisor (1-9). $O(10 \cdot 10 \cdot N)$ |
Rolling Remainder Frequency Table. |
For current digit X and divisor D, update counts: `new_rem = (old_rem * 10 + X) % D`. Add count of `rem == 0`. |
Draw 9 rows (for divisors 1-9). Each row has boxes for remainders. Update box counts as you scan each digit. |
9-Layer Linear Scanning. |
Draw 9 parallel tracks. Move a single cursor across the string, updating all 9 tracks simultaneously. |
Massive string slicing or BigInt objects filling the heap. |
A fixed-size 9x10 2D array of integers to store remainder counts. |
| 3449 |
Maximize the Minimum Game Score |
Backtracking simulation of every possible move sequence (up/down) up to m moves. $O(2^m)$ |
Exponential Move Tree. |
Draw a root node branching to "Left" or "Right" moves. At depth m, you have 2^m leaf nodes to evaluate. |
Binary Search on Answer + Greedy Traversal. $O(N \log(\text{Max}_\text{Score})$) |
Score Threshold Waterline. |
Pick a target score X. Greedily calculate moves needed to bring every gameScore[i] to ≥ X. Check if total moves ≤ m. |
Draw the points array. Draw a horizontal line at height X. For each point, calculate X/points[i] to find the required "visits." |
Binary Search Tree + Linear Scan. |
Draw a BS tree of height log(Score). In each node, draw a simple $O(N)$ progress line. |
Deep recursion stack with state snapshots per move. |
$O(1)$ auxiliary space using a few variables to track current moves and positions. |
| 3450 |
Maximum Students on a Single Bench |
Iterate through all student-bench pairs. For each bench, create a list of students and manually check for duplicates by comparing every new student with existing ones. $O(N²)$ |
Nested Loop Verification. |
Draw benches as rows. For each student entering a row, draw arrows pointing back to every student already sitting there to check for a name match. |
Hash Map of Hash Sets. $O(N)$ |
Grouped Bucket Sets. |
Read student data. Use bench_id as a key in a map. Add student_id to a set (duplicates auto-removed). Finally, find the max set size. |
Draw 100 numbered boxes. Drop "student IDs" into the boxes. If a student is already in a box, just leave them as one entry. Circle the box with the most IDs. |
Single Linear Pass. |
Draw one straight horizontal arrow scanning the input array once. |
Large temporary lists for each bench, potentially storing redundant student IDs. |
A Map where each key points to a unique Set, utilizing efficient internal hashing for $O(1)$ average lookups. |
| 3451 |
Find Invalid IP Addresses |
Loop through strings, split by the '.' character. For each part, check length, leading zeros, and range (0-255) using multiple nested if-statements. $O(N × L)$ |
Character-by-Character Octet Parsing. |
Draw the IP string. Draw brackets around each segment. For each segment, draw arrows checking every digit for a '0' or a value > 255. |
Regex (Regular Expressions) or SQL Pattern Matching. $O(N)$ |
Pattern Mask Overlay. |
Apply a Regex pattern that enforces the 4-octet rule and range constraints. Any string that doesn't "fit" the mask is invalid. |
Draw the IP address. Below it, draw a "Filter Plate" with 4 holes. If the IP fits through the holes (segments), it’s valid. |
State Machine Progression. |
Draw a 4-state diagram. One pass through the string moves the pointer through states 1, 2, 3, and 4. Failure at any point kills the process. |
Creating multiple intermediate string objects for every IP segment. |
$O(1)$ extra space if using a streaming Regex engine or simple integer pointers. |
| 3452 |
Sum of Good Numbers |
For every element at index i, check all elements at index j to see if they are k distance away, then verify if nums[i] is greater. $O(N²)$ if done with nested search. |
Redundant Distance Checks. |
Draw the array. For index i, draw a search arrow that scans the entire array looking for indices i-k and i+k. |
Single Pass Bound Check. $O(N)$ |
Lookback/Lookahead Pointers. |
Traverse the array once. For current index i, check strictly if nums[i] > nums[i-k] (if i-k exists) and nums[i] > nums[i+k] (if i+k exists). |
Draw the array. Put your finger on index i. Look left exactly k units, then right exactly k units. If i is the "king," add it to the sum. |
Linear Scan Timeline. |
Draw one straight line across the array to represent the $O(N)$ single-loop traversal. |
N/A - Mostly wasted time complexity. |
$O(1)$ space using one single "sum" variable. |
| 3453 |
Separate Squares I |
Test every possible Y coordinate from the lowest to highest in increments of 0.00001, calculating areas above and below for each. $O(10^5 \cdot N)$ |
Dense Scanning "Y-Line". |
Draw the squares. Draw a dashed horizontal line that moves up 1 pixel at a time, recalculating everything at every step. |
Binary Search on Answer (Y-coordinate). $O(N \log(\text{Range}/\text{Epsilon})$) |
Horizontal Waterline Balancing. |
Pick a middle Y. Calculate AreaAbove and AreaBelow (O(N)). If Above > Below, move Y up; else move Y down. Repeat until precise. |
Draw the squares. Draw a "waterline" halfway. If the top half has more "water" (area), raise the waterline. |
BS Tree Height with Linear Check. |
Draw a Binary Search tree of depth 60-100 (for precision). Each node contains an $O(N)$ scan box. |
Minimal, but massive CPU time. |
$O(1)$ space, storing only the target area and current Y bounds. |
| 3454 |
Separate Squares II |
Similar to Part I, but for every candidate Y, calculate the union of horizontal segments to avoid double-counting overlaps. $O(N² \log N)$ or worse. |
Nested Union Area Calculations. |
Draw overlapping squares. For every Y, draw the horizontal shadow they cast, then manually calculate the length of the merged shadow. |
Sweep Line + Segment Tree (with Lazy Propagation/Coverage Count). $O(N \log N)$ |
Vertical Scanning Beam with Interval Merging. |
Sweep a horizontal line from bottom to top. Use a Segment Tree to track the total X-coverage (union width) as you move. Area = Σ (width * ΔY). |
Draw the squares. Draw a vertical ruler on the side. As the horizontal sweep line moves up, color in the "active" horizontal segments in the Segment Tree. |
Sorted Event Timeline + Tree Traversal. |
Draw an $O(N \log N)$ sorting step for Y-events, then an $O(N \log N)$ traversal where each move updates a tree of height log N. |
Massive lists of overlapping interval coordinates. |
A Segment Tree of size 4N and an Event list of size 2N. |
| 3455 |
Shortest Matching Substring |
Generate all substrings and check if each matches the pattern with wildcards using nested loops. $O(N^3)$ |
Triangular Pattern Search. |
Draw the string. Below it, draw brackets for every substring and a "Wildcard Checker" box for each. |
KMP (LPS Array) + Three-Pointer Greedy Slide. $O(N + M)$ |
Split Pattern Matching Tracks. |
Split pattern into 3 fixed parts. Use KMP to find all occurrences of each. Use three pointers to find the smallest range [i, k] that contains all parts in order. |
Draw 3 horizontal lines below the string. Mark the indices where part A, B, and C start. Draw a bracket encompassing one of each in sequence. |
Multi-Linear Pass Timeline. |
Draw 3 parallel lines for KMP scans, followed by a single combined line for the sliding window. |
Large intermediate substring copies for pattern validation. |
Three 1D LPS arrays and three integer lists of match indices. |
| 3456 |
Find Special Substring of Length K |
Generate every substring of length K and check all characters for equality and neighboring constraints. $O(N \cdot K)$ |
Sliding Window with Full Verification. |
Draw a K-sized box sliding across the string. Inside each box, draw K arrows checking if all letters match. |
Linear Scan with Consecutive Counter. $O(N)$ |
Counter Waveform with Boundary Checks. |
Iterate. If s[i] == s[i-1], increment counter. If not, check if old counter == K (and verify neighbors). Reset counter. |
Draw the string. Underneath, write a running number that resets when characters change. Circle the number 'K' if it satisfies boundaries. |
Single Pass Progress Line. |
Draw one straight arrow moving once across the string array. |
Temporary character lists or substring objects. |
Two $O(1)$ integer variables (`count` and `result_found`). |
| 3457 |
Eat Pizzas! |
Generate all possible daily combinations of 4 pizzas and calculate the total weight gain. $O(N!)$ or complex recursion. |
Factorial Combinatorial Tree. |
Draw a root. Branch it into every set of 4 pizzas. It becomes a massive, dense web. |
Greedy Selection on Sorted Array. $O(N \log N)$ |
Sorted "Top-Shelf" Pizza Selection. |
Sort pizzas. Calculate number of odd/even days. For odd days, take the absolute largest available. For even days, skip one large and take the next largest. |
Draw the sorted array. Color the last X pizzas for odd days. Skip every other pizza moving left for the next Y even days. |
Sort Tree + Summing Sub-array. |
Draw an $O(N \log N)$ sorting box followed by a single pass summing specific indices. |
Recursive stack depth storing pizza permutations. |
$O(1)$ extra space after sorting the input array. |
| 3458 |
Select K Disjoint Special Substrings |
Identify all substrings, check "special" condition (containment), and try all 2^M subsets of these. $O(N^2 \cdot 2^M)$ |
Nested Condition Decision Tree. |
Draw all intervals. For each, draw a decision branch "Include" or "Exclude" while checking for overlap. |
Interval Consolidation + Greedy Activity Selection. $O(N)$ |
Greedy Interval Scheduling Bars. |
For each character, find its min range [L, R]. Expand R if internal chars have occurrences outside. Filter special substrings. Sort by end-time and pick K disjoint ones. |
Draw intervals as horizontal bars on a timeline. Pick the bar that ends first. Remove overlapping bars. Count how many you picked. |
Multi-Linear Pass (Tally -> Expand -> Schedule). |
Draw 3 linear blocks: one for frequency map, one for range expansion, and one for interval counting. |
Storing all possible N^2 substrings in a list. |
Fixed-size maps (26 keys) and a list of at most 26 valid special intervals. |
| 3459 |
Length of Longest V-Shaped Diagonal Segment |
From every cell, explore every possible diagonal path sequence including turns without memoization. $O(4 \cdot (N \cdot M)$^2) |
Exploding Path Traversal. |
Draw a grid. From one cell, draw hundreds of branching paths that wrap and turn, eventually filling the whole page. |
DFS + Memoization / DP (State: r, c, dir, turn_taken, next_val). $O(N \cdot M)$ |
Directional State Table. |
For each cell with '1', try 4 directions. DFS carries the state: expected next number (2, 0, 2, 0) and whether the 90-degree turn is used. |
Draw the grid. Draw an arrow with a 90-degree "joint." Label the cells along the path with the alternating 2, 0, 2 sequence. |
Bounded State Traversal. |
Draw a grid and imagine 16 layers (4 dirs x 2 turn-states x 2 numbers). Shade each layer to show total work is $O(16 \cdot N \cdot M)$. |
Recursive stack overflow from trillions of re-calculated paths. |
A 5D Memoization table of size [N][M][4][2][2] or a Hash Map of states. |
| 3460 |
Longest Common Prefix After at Most One Removal |
Iterate through string s and for each index i, create a new string with s[i] removed, then find LCP with t. $O(N^2)$ |
N-Line Character Matching Grid. |
Draw string s. Below it, draw N different versions of s (each missing one char) and a matching arrow for each against t. |
Two Pointers with "Skip" Flag. $O(N)$ |
Staggered Parallel Pointers. |
Place pointer i on s and j on t. If s[i] == t[j], increment both. If not and flag is false, skip s[i] (inc i only) and set flag true. |
Draw s and t as parallel arrays. Draw an arrow i and j. If a mismatch occurs, "bend" the i arrow to the next cell while keeping j still. |
Single Pass Timeline. |
Draw one straight line above the arrays to show a single $O(N)$ pass. |
$O(N^2)$ storage if all modified strings are saved; otherwise high heap churn. |
$O(1)$ extra space using only two integer pointers and one boolean flag. |
| 3461 |
Check If Digits Are Equal in String After Operations I |
Iteratively calculate the new digit string row by row until only two digits remain. $O(N^2)$ |
Inverted Pascal's Triangle. |
Draw the original string at the top. Below, draw N-1 digits, then N-2, forming a pyramid pointing downwards. |
Simulation (due to small N=100). $O(N^2)$ |
Layered Reduction Map. |
Calculate each layer's values. Each cell (i, j) is (val[i-1][j] + val[i-1][j+1]) mod10. |
Draw the string. Draw "V" shapes between adjacent digits and write the sum mod10 at the tip of each "V." |
2D Matrix Area. |
Draw a square of size N x N and shade the lower triangle to show frac12N^2 work. |
A 2D array or a list of lists representing the entire pyramid. |
A single 1D array of size N updated in-place (rolling row). |
| 3462 |
Maximum Sum With at Most K Elements |
Sort the entire grid of N x M elements and pick the top K, ignoring row limits. $O(\text{NM} \\text{log NM})$ |
Global Sorting Block. |
Draw all matrix elements in a single long list. Draw a giant "Sort" funnel that outputs them in descending order. |
Row Sorting + Global Priority Queue. $O(N \cdot M \log M + \text{NM} \log K)$ |
Bucket Filter followed by Min-Heap. |
Sort each row (M log M). Take the largest `limits[i]` from each row. Push all these candidates into a Max-Heap and pop K times. |
Draw each row. Circle the largest elements (up to limit). Draw an arrow from each circled number into a central "K-Bucket." |
N sorting trees + 1 Heap tree. |
Draw N small sort boxes (each M log M) feeding into a single heap structure of size K. |
Large auxiliary array to store and sort NM elements. |
Fixed-size priority queue of size K and in-place row sorting. |
| 3463 |
Check If Digits Are Equal in String After Operations II |
Simulate the process as in Part I. For N=10^5, this fails. $O(N^2)$ |
Dense Pyramid Matrix. |
Draw the same pyramid as Part I, but note that for 10^5, the number of "V" tips is 5 x 10^9, exceeding time limits. |
Combinatorics (nCr mod10) using Lucas Theorem & CRT. $O(N)$ |
Weighted Contribution Coefficient Map. |
Final digits are sum ((N-2 Choose i) * s[i]) mod10. Compute mod 2 and mod 5 separately then combine. |
Draw the string. Below each digit i, write its weight (N-2 Choose i). Draw lines summing them into the final two slots. |
Single Pass Modular Calculation. |
Draw one horizontal line for the loop through N digits, with a small "Math Box" at each step. |
Trillions of simulated state integers. |
A few arrays for factorials and inverse factorials up to size N. |
| 3464 |
Maximize the Distance Between Points on a Square |
Generate all (N Choose k) combinations of points and calculate the minimum Manhattan distance for each. $O(N^k)$ |
Combinatorial Explosion Tree. |
Draw the square. Branch into picking point 1, then point 2... the tree becomes a dense fog. |
Perimeter Unwrapping + Binary Search on Answer + Greedy. $O(N \log N + N \\text{log side})$ |
1D Line Circular Greedy Scan. |
Unwrap square boundary to a 1D line of length 4 * side. BS for distance D. Greedily pick points at distance >= D. |
Draw a circle/loop. Place points. Pick a starting point. "Jump" clockwise by at least D to pick the next point. Repeat k times. |
Sort Timeline + BS Binary Tree. |
Draw an $O(N \log N)$ sort step, followed by a Binary Search tree where each node is an $O(N)$ greedy check. |
Storing all possible k-sized subsets of points. |
Sorted 1D array of points along the perimeter (size N). |
| 3465 |
Find Products with Valid Serial Numbers |
Manually scan every substring of the description to check if it follows the SNXXXX-XXXX pattern. $O(N x L^2)$ |
Nested String Scanning Brackets. |
Draw the description. Draw a sliding bracket of length 11, checking every possible starting position manually. |
Regular Expression (Regex) Matching. $O(N)$ |
Finite Automata (FSM) State Map. |
Apply the pattern `SN[0-9]{4}-[0-9]{4}`. The engine scans the string once, transitioning through "S", then "N", then 4 digits, etc. |
Draw the pattern components in boxes: [SN] -> [4 Digits] -> [-] -> [4 Digits]. Highlight matching text in the string. |
Single Linear Pass. |
Draw a single horizontal line across the description string representing the one-pass Regex scan. |
Multiple temporary substring copies in memory. |
$O(1)$ auxiliary space beyond the string storage. |
| 3466 |
Maximum Coin Collection |
Exhaustively search every possible entry mile, every possible exit mile, and every possible lane switch combination. $O(2^N)$ |
Exponential Decision Path Tree. |
Draw Mario at Mile 0. Branch into Lane 1 or 2. At each mile, branch again into "Switch" or "Stay" until depth N. |
Dynamic Programming (State: mile, lane, switchesLeft). $O(N)$ |
3-Layered Grid Traversal. |
Imagine 3 versions of the 2-lane road (0, 1, and 2 switches remaining). At each mile, move Mario to the best neighbor in his layer or jump to a lower switch-layer. |
Draw 2 rows of road. Above them, write the "Max Coins" possible at each mile for 0, 1, and 2 switches. Connect them with "switch" arrows. |
Linear Progress through Matrix Layers. |
Draw a 3 x 2 x N block and shade it mile by mile to show bounded complexity. |
Trillions of overlapping paths in the recursion stack. |
A 3 x 2 x N DP table or memoization map. |
| 3467 |
Transform Array by Parity |
Iterate once to change values (Even to 0, Odd to 1), then sort the entire array. $O(N \log N)$ |
Sort Funnel Processing. |
Draw the array being modified. Then draw it entering a "Sort" box that splits into multiple levels (merge sort tree). |
Counting & Filling (Stable Parity). $O(N)$ |
Count-Based Bucket Filling. |
Count the number of even numbers. Create a result array. Fill the first `evenCount` slots with 0, and the rest with 1. |
Draw a tally mark for every even number. Draw an empty array and fill a "0" block and a "1" block based on that tally. |
Two-Pass Linear Scan. |
Draw one line for counting and one line for filling. Total 2N operations. |
Sort-overhead memory (stack space). |
$O(1)$ extra space if modifying in-place; $O(N)$ for a new result array. |
| 3468 |
Find the Number of Copy Arrays |
Pick every possible value for copy[0] in its range, generate the whole array, and check if every element fits in its bounds. $O(\text{Range} x N)$ |
Multiple Number Line Probes. |
Draw N number lines. For every value in the first range, draw a path through the other N-1 ranges. |
Range Narrowing (Iterative Intersection). $O(N)$ |
Squeezing Sliding Range. |
Maintain a possible range [L, R] for copy[i]. Update it using the difference from `original` and intersecting it with the bounds for the next element. |
Draw a horizontal bar representing the current valid range. As you move to the next index, shift the bar and "trim" it where it overflows the new bounds. |
Single Linear Array Pass. |
Draw one straight arrow moving once from index 1 to N-1. |
N/A - Primarily excessive time complexity. |
$O(1)$ auxiliary space (just 2 variables for `currentL` and `currentR`). |
| 3469 |
Find Minimum Cost to Remove Array Elements |
Try every possible pair from the first 3 elements in a recursive tree without saving results. $O(3^N)$ |
Tri-branching Recursion Tree. |
Draw a root. Branch it 3 times (choosing pairs (1,2), (1,3), or (2,3)). Repeat at each level. |
DP with State (lastRemainingIndex, nextIndex). $O(N^2)$ |
2D Grid of Remaining Elements. |
Use DP to store the min cost to finish if element X is currently the "orphan" and the next available elements are at index i, i+1. |
Draw a 2D table where rows are "last leftover" and columns are "current start." Trace a path through the table. |
Matrix Shading (N^2 states). |
Draw a square matrix of size N x N and shade it cell by cell to show polynomial complexity. |
Massive recursion stack depth with redundant calculations. |
A 2D memoization array of size N x N. |
| 3470 |
Permutations IV |
Generate all n! permutations, filter those with alternating parity, sort them, and pick the k-th. $O(n \cdot n!)$ |
Factorial Permutation Explosion. |
Draw a root node branching into n numbers, then each into n-1, creating a massive unreadable cloud of leaf nodes. |
Combinatorial Counting + Digit-by-Digit Construction. $O(n)$ |
Decision Tree with Weight Values. |
For the current position, calculate how many valid alternating suffixes exist starting with an odd vs even number. Subtract from k to pick the digit. |
Draw a vertical line. For each index, list available numbers. Write the count of valid ways next to the "Odd" and "Even" groups. Draw an arrow to the choice that contains k. |
Linear Digit Selection. |
Draw a horizontal timeline of length n. Mark it with single dots for each choice to show $O(n)$ total work. |
Massive list storing trillions of permutations. |
A few integer variables and a boolean "visited" array of size n. |
| 3471 |
Find the Largest Almost Missing Integer |
Iterate through every subarray of size k, count occurrences of every integer in each, and find the largest occurring once globally. $O(n^2)$ |
Sliding Window Matrix. |
Draw the array. Below it, draw all overlapping boxes of size k. For each box, list its elements and tally them in a giant table. |
Case-Based Boundary Analysis. $O(n)$ |
Case-Logic Flowchart. |
If k=1, find unique max. If k=n, find max of all. If 1 < k < n, only the first or last elements can be almost missing; check if they appear elsewhere. |
Draw a flowchart with three diamonds (If k=1, If k=n, Else). For the "Else" branch, circle the first and last elements and cross out all middle elements. |
Constant Number of Global Scans. |
Draw two parallel horizontal lines representing at most 2-3 passes over the array to show $O(n)$ time. |
A Hash Map storing frequency counts for every possible subarray. |
A single 51-element frequency array or Hash Map for global counts. |
| 3472 |
Longest Palindromic Subsequence After at Most K Operations |
Try every possible subsequence (2^n) and for each, calculate the minimum circular operations to make it a palindrome. $O(n \cdot 2^n)$ |
Recursive Subsequence Tree with Operation Branches. |
Draw a tree where each character branches into "Keep" or "Discard." From "Keep," branch again for every possible letter change. |
3D Dynamic Programming (State: i, j, kRemain). $O(n^2 \cdot k)$ |
Layered 2D DP Grids. |
Imagine a stack of k grids. If you match s[i] and s[j] at cost c, move to a grid c layers below. Otherwise, stay in the same layer. |
Draw a 2D table (i vs j). Inside each cell, draw a small stack of 3-4 boxes (for k values). Draw arrows jumping between the boxes. |
3D Block Traversal. |
Draw a cube with dimensions n x n x k. Shade it layer by layer to show polynomial complexity. |
Trillions of recomputed states in a deep recursive stack. |
A 3D DP table or memoization map of size [n][n][k]. |
| 3473 |
Sum of K Subarrays With Length at Least M |
Recursive DFS picking any k non-overlapping segments of size >= m. $O((n \text{Choose} k \cdot m)$) |
Combinatorial Segment Picker. |
Draw the array. Draw k brackets. Try sliding and resizing each bracket independently, resulting in an explosive number of configurations. |
DP with Prefix Sum Optimization + "Ongoing" State. $O(n \cdot k)$ |
State Machine on Array Track. |
Track current index, how many subarrays remain, and if a subarray is currently being extended. Use prefix sums for $O(1)$ range sum calculations. |
Draw the array. Below it, draw a "Skip" arrow and a "Take m block" arrow. Label the arrows with the cost/sum and number of k left. |
2D DP Grid Traversal. |
Draw a table with n rows and k columns. Shade it to show the $O(n \cdot k)$ work. |
Massive recursion stack without memoization. |
A 2D memoization table of size [n][k] or [n][2][k]. |
| 3474 |
Lexicographically Smallest Generated String |
Try all 26^(n+m-1) possible strings and check if they satisfy the str1 conditions for str2. $O(26^L)$ |
Exponential Character Decision Tree. |
Draw a root. Branch it 26 times ('a' to 'z'). Repeat for length n+m-1. The tree fills the universe before the first valid string is found. |
Greedy Template Filling + Contradiction Check (KMP/Suffix). $O(n \cdot m)$ |
Constraint Propagation over Template. |
Pre-fill all 'T' requirements into the result string. For 'F' indices, find the earliest character that ensures the substring
eq str2 without breaking 'T' rules. |
Draw the result string as empty boxes. Shade boxes where 'T' forces characters. For remaining boxes, write 'a' and draw an "Alert" symbol if it matches str2 at an 'F' position. |
Template Pass followed by Verification Pass. |
Draw two parallel linear arrows scanning the template string to show linear-multiplicative time complexity. |
Heap overflow from generating trillions of strings. |
A single character array for the result string and a few integer pointers. |
| 3475 |
DNA Pattern Recognition |
Iterate through every row in the Samples table and manually use string search functions for each of the 4 patterns. $O(N x L)$ |
Character-by-Character Pattern Tally. |
Draw a sequence of DNA. Draw 4 magnifying glasses over it, each checking a different rule (start, end, motif, repeats). |
SQL `CASE` statements with `LIKE` and `REGEXP` for vectorized pattern matching. $O(N)$ |
Binary Feature Matrix. |
Apply 4 filters simultaneously to the DNA string. Record 1 if a filter "catches" a pattern and 0 otherwise. |
Draw a table with columns: `has_start`, `has_stop`, `has_atat`, `has_ggg`. For each DNA string, check off the boxes. |
Single Table Scan. |
Draw one straight arrow moving down the Sample rows to show $O(N)$ row-level processing. |
Temporary string allocations for regex matching. |
$O(1)$ extra space as the processing happens in-stream within the database engine. |
| 3476 |
Maximize Profit from Task Assignment |
Exhaustively try every permutation of matching workers to tasks that meet their skill requirement. $O(N!)$ |
Bipartite Matching Expansion. |
Draw workers on left, tasks on right. Draw lines between all valid skill matches and try to find the max sum. |
Greedy Assignment + Hash Map of Max-Heaps + Special Worker Greedy choice. $O((N+M)$ log M) |
Priority Queue Bucket Assignment. |
Group tasks by skill in a Map. For each worker, pop the highest profit from their skill bucket. Finally, give the special worker the absolute max remaining profit. |
Draw buckets for each skill level. Put profits in each bucket. Draw a worker "taking" the top value. Draw a "Special" worker taking the best from any bucket. |
Sorting/Heap Tree Traversal. |
Draw an $O(M \log M)$ sorting step followed by a linear worker pass with $O(\log M)$ heap pops. |
Massive permutation tree in the recursion stack. |
A Hash Map containing several Priority Queues or sorted lists. |
| 3477 |
Fruits Into Baskets II |
For each fruit, iterate through all baskets from index 0 to N-1 until a suitable basket is found. $O(N^2)$ |
Nested Scanning Brackets. |
Draw the fruits array. For each fruit, draw a search arrow that scans the entire basket array from the start. |
Simulation with Leftmost Greedy Search. $O(N^2)$ is acceptable given N=100. |
Sequential Basket Exclusion. |
Try placing fruit i in the first available basket j that fits. If found, "mark" basket j as full and move to the next fruit. |
Draw the baskets as boxes. For a fruit, slide your finger over boxes until you find a big enough one. Draw a big 'X' over it. |
Upper Triangle Matrix Area. |
Draw an N x N grid. Shade the cells checked to show at most N^2 comparisons. |
Minimal extra memory. |
A boolean array of size N to track which baskets are occupied. |
| 3478 |
Choose K Elements With Maximum Sum |
For each index i, scan the entire array to find all j where nums1[j] < nums1[i], then sort those nums2[j] values. $O(N^2 \log N)$ |
Sub-problem Sorting Forest. |
Draw the array. For one element, circle all "smaller" partners. Draw a sort funnel for the partners' values. Repeat for every element. |
Sorting + Sliding Window with Min-Heap of size K. $O(N \log N + N \log K)$ |
Threshold-Gated Running Heap. |
Sort elements by nums1. As you move the "threshold," add nums2 values to a Min-Heap. If size > K, pop the smallest. Current heap sum is the answer for that threshold. |
Draw a horizontal timeline of sorted nums1. Place a sliding "gate." Values passing the gate go into a "K-Basket." If it's too full, the smallest falls out. |
Sorting Tree + Logarithmic Updates. |
Draw an $O(N \log N)$ sort box followed by an arrow passing through a heap structure of height log K. |
Repeatedly creating and storing partner lists for N indices. |
A single Min-Heap of size K and a sorted array of tuples. |
| 3479 |
Fruits Into Baskets III |
Identical to Part II, but with N=10^5, the $O(N^2)$ approach will time out. $O(N^2)$ |
Dense Search Matrix. |
Draw the same search arrows as Part II, but note that for 10^5 fruits, you would need 10^10 comparisons. |
Segment Tree (Max-Range) + Binary Search for First Index. $O(N \log N)$ |
Binary Range "Fit" Tree. |
Build a Max-Segment Tree of basket capacities. For fruit X, if `tree.root.max < X`, it's unplaced. Otherwise, walk down the tree to find the leftmost child with `max >= X`. |
Draw a binary tree. Each node stores the max of its children. For a fruit, highlight the path to the leftmost leaf that is >= fruit size. Then set that leaf to 0. |
Tree Traversal per Fruit. |
Draw N paths down a tree of height log N, showing $O(N \log N)$ total time. |
Trillions of CPU comparisons. |
A 1D array of size 4N representing the Segment Tree structure. |
| 3480 |
Maximize Subarrays After Removing One Conflicting Pair |
For each pair, remove it and count all valid subarrays by checking every i,j against all remaining M-1 pairs. $O(M \cdot N^2)$ |
Nested Loop Cuboid. |
Draw an array. Draw brackets for every possible subarray. For each bracket, draw a list of conflict rules it must pass. |
Two-Pointer / Boundary Tracking (Min and Second Min). $O(N + M)$ |
Dual Conflict Boundary Lines. |
Scan right-to-left. Track b1 (closest conflict index) and b2 (second closest). Benefit of removing the rule at b1 is b2 - b1. |
Draw a horizontal array. For index i, draw two vertical dashed lines (b1, b2). The gap between them is the "potential gain." |
Single Linear Sweep. |
Draw one straight arrow traversing the array once, with a small "boundary box" updating at each step. |
Massive list of valid subarray coordinates. |
Two 1D arrays (`limit1`, `limit2`) of size N to store conflict boundaries. |
| 3481 |
Apply Substitutions |
Repeatedly scan the entire string for '%' symbols, replace the first one found, and start over until no '%' remain. $O(L^\text{depth})$ |
Exponential Recursive Expansion. |
Draw a short string. Replace one word with three words. Replace one of those with five words. The string line grows until it goes off the page. |
DFS with Memoization / Dependency Graph Resolve. $O(\text{Final Length})$ |
Directed Acyclic Graph (DAG) Traversal. |
Treat each placeholder as a node. Recursively resolve leaf-nodes (static text) and cache the result. Combine strings during backtracking. |
Draw bubble nodes for variables. Draw arrows to other variables they contain. Cross out bubbles as you "cache" their final string. |
Linear String Construction. |
Draw a timeline representing the final string. Each character is written exactly once. |
Deep recursion stack with millions of intermediate string fragments. |
A Hash Map for the dictionary and a memo-table for resolved placeholders. |
| 3482 |
Analyze Organization Hierarchy |
For every employee record, use a loop to traverse up the hierarchy (manager of manager) to calculate depth/team size. $O(N^2)$ |
N-rooted Path Traversal. |
Draw an org chart (Tree). For every leaf node, draw a long arrow all the way back up to the CEO (Root). |
Recursive CTE (SQL) / DFS with Aggregate Accumulation. $O(N)$ |
Tree Bubble-up Summation. |
Perform a single DFS. On the return path (post-order), sum the salaries/counts of children and add to the current node. |
Draw a tree. Write a number in each leaf. Draw "up-arrows" pushing those numbers to the parent. Parent sums them up and pushes further. |
Linear Tree Scan. |
Draw a tree and shade it from top to bottom (exactly N nodes visited). |
Massive result sets from redundant self-joins. |
An adjacency list (Map) and a single recursive stack. |
| 3483 |
Unique 3-Digit Even Numbers |
Generate all P(N, 3) permutations of digits, convert to numbers, and filter for uniqueness, evenness, and no leading zeros. $O(N^3)$ |
Permutation Tree Expansion. |
Draw 3 blank slots. Branch from slot 1 to all N digits, then from slot 2 to N-1 digits. |
Fixed-Space Iteration (100..998) + Frequency Map Tally. $O(N + 450)$ |
Tally Bucket Comparison. |
Count occurrences of 0-9 in the input. Iterate through even numbers from 100 to 998. Check if each number's digits fit in your tally. |
Draw 10 buckets (0-9). For number "246", check if buckets 2, 4, and 6 have >= 1 item. |
Constant Time Post-Scan. |
Draw one $O(N)$ line followed by a small fixed-size grid of 450 dots. |
Huge HashSet storing all generated numeric strings. |
A fixed array of size 10 to store the digit counts. |
| 3484 |
Design Spreadsheet |
Store all possible cells in a 2D array. For formulas, re-calculate the entire grid on every update. $O(N \cdot M)$ |
Full Matrix Grid Refresh. |
Draw a large grid. When one cell changes, shade the entire grid to represent it being re-processed. |
Hash Map (Sparse Storage) + Direct Formula Parsing. $O(1)$ set / $O(L)$ get. |
Key-Value Map with Direct Access. |
Use a Map to store "CellID -> Value". Formulas simply look up the required keys. Sparse storage ignores the thousands of empty "0" cells. |
Draw two columns: ID (e.g., A1) and Value. Only write rows for cells that actually have data. |
Point-to-Point Hashing. |
Draw a formula cell and draw two direct arrows pointing to its operand cells in the Map. |
Static N x 26 grid, mostly filled with memory-wasting zeros. |
A dynamic Hash Map storing only "Set" cells (O(SetCells)). |
| 3485 |
Longest Common Prefix of K Strings After Removal |
Generate all combinations of removing characters, and check the common prefix for each. $O(\text{Exponential})$. |
Combinatorial Deletion Forest |
Cross out characters randomly in K strings. Compare their prefixes. |
Trie + Dynamic Programming |
The Pruned Prefix Tree |
Insert all strings into a Trie. Use DP on the Trie to calculate the minimum removals required to make a specific Trie node (representing a prefix) common among K strings. |
Draw a Trie. To make the prefix "APP" common across 3 strings, look at how many letters you have to delete from strings that diverge from the "APP" path. Use DP to find the cheapest way to force K strings down that exact path. |
Trie Traversal + DP $O(\text{Total Chars} \cdot K)$ |
Draw a Trie. At each node, compute a small DP state merging child costs. |
Storing modified strings. |
A Trie data structure and DP state arrays. $O(\text{Total Chars})$ space. |
| 3486 |
Longest Special Path II |
Check every path in the tree. For each, verify if all node values are unique using a Set. $O(N^2)$ |
All-Paths DFS Forest. |
Draw the tree N times. In each copy, highlight a different node as the root and draw arrows exploring all paths from it. |
DFS + Sliding Window on Path + Hash Map for Last Depth. $O(N)$ |
Left-Boundary Depth Pointer. |
Traverse DFS. Keep a map of "Value -> Last Depth Seen". Maintain a `leftBoundary` for the current path; if a duplicate is seen, move the boundary to `max(leftBoundary, lastSeen[val])`. |
Draw a tree path. Draw a sliding bracket alongside the path. If you hit a duplicate value, "shrink" the top of the bracket down to the old value's position. |
Single Pass Tree Shading. |
Draw one tree and shade each edge once during the DFS traversal. |
Multiple sets created and destroyed in the heap during exploration. |
One global Hash Map and a recursive call stack. |
| 3487 |
Maximum Unique Subarray Sum After Deletion |
Generate all 2^N deleted versions of the array. For each, find the max sum of a unique-element subarray. $O(2^N \cdot N)$ |
Subset Power Set Decision Tree. |
Draw a root. Branch into "Keep" or "Delete" for every element. For each leaf, draw a subarray scan. |
Greedy (Sum of Unique Positive Numbers). $O(N)$ |
Positive-Unique Bucket Filter. |
Since you can delete any elements, delete all negative numbers and all duplicate occurrences of positive numbers. The answer is simply the sum of unique positive elements. |
Draw the array. Circle every unique positive number. Write "Delete" over all negative numbers and duplicate positives. Sum the circles. |
Single pass with a Set. |
Draw one straight arrow moving once from index 0 to N-1. |
Trillions of array versions in memory. |
A single Set to track seen positive integers. |
| 3488 |
Closest Equal Element Queries |
For each query i, scan left and right from nums[i] until you find another instance of the same value. $O(Q \cdot N)$ |
Nested Scanning Loop Forest. |
Draw the array. For each query dot, draw two search arrows radiating outwards until they hit a match. |
Bi-directional Linear Scan with Last-Seen Map. $O(N + Q)$ |
Two-Pass Distance Projection. |
Scan left-to-right to find nearest identical elements on the left. Scan right-to-left for the nearest on the right. Store the minimum of both for each index. |
Draw the array. Above it, draw arrows pointing left to previous occurrences. Below it, draw arrows pointing right to next occurrences. Record the shorter arrow length. |
Two Linear Pass Timelines. |
Draw two parallel horizontal lines representing the two passes over the array. |
Negligible, but extremely high CPU time for large Q. |
A single distance array and a small Hash Map for "Last Index." |
| 3489 |
Zero Array Transformation IV |
Iteratively subtract values from subarrays, checking if all elements reach zero. $O(N \cdot Q)$. |
Iterative Array Flattening |
Draw the array. Subtract from a range. Scan the whole array to check for zeros. |
Difference Array / Sweep Line |
The Overlapping Operations Tally |
You want to know if queries can reduce the array to zero. Use a difference array to apply all queries at once in $O(Q)$ time. Sweep it in $O(N)$ to get the total reduction at each index. Compare against the original array. |
Draw a blank line. Drop +V at the start of a query range and -V at the end. Sweep left-to-right to build the total "reduction power" at each index. If the power >= the original number everywhere, it works! |
Two-Pass Linear $O(N + Q)$ |
Draw a pass over the queries, then a single sweep pass over the array. |
Modifying the array continuously. |
A single difference array of size N+1. $O(N)$ space. |
| 3490 |
Count Beautiful Numbers |
Iterate through every integer from L to R. For each, compute the product and sum of digits, then check divisibility. $O(R)$ |
Linear Search Timeline. |
Draw a long horizontal line. Mark points L, L+1... R. Draw a "Check" box above every single point. |
Digit Dynamic Programming (State: index, tight, productMod, sum). $O(\text{digits} \\text{cdot sum} \\text{cdot prod})$ |
Decision Tree with Memoized Pruning. |
Build the number digit-by-digit. Use a DP table to cache results for the same (index, currentSum, currentProductMod) state. |
Draw a grid where rows are digit positions and columns are current sums. Draw arrows for each digit (0-9) transitioning to a new sum. |
Multi-Dimensional State Cube. |
Draw a small box representing the 10 x 162 x 162 state space to show it is independent of R. |
Minimal extra memory but astronomical CPU cycles. |
A 4D or 5D DP array (Memoization table) of fixed size. |
| 3491 |
Phone Number Prefix |
Compare every pair of phone numbers (i, j) using `startsWith()`. $O(N^2 \cdot L)$ |
N x N Comparison Matrix. |
Draw a grid of all numbers. For cell (i, j), draw an arrow checking if number i is inside number j. |
Sorting + Adjacent Comparison OR Trie Insertion. $O(N \log N \cdot L)$ |
Prefix Tree (Trie) Branching. |
Insert numbers into a Trie. If you pass an "End-of-Word" node while inserting, or if you reach the end of your word and children exist, a prefix exists. |
Draw a tree where each node is a digit (0-9). As you trace a number, circle the nodes. Mark "Word Ends" with a star. |
Logarithmic Tree Height Traversal. |
Draw one tree. Highlight the path of one word (length L) to show $O(L)$ work per word. |
Trillions of string comparisons in the CPU stack. |
A Trie structure where each node contains an array of 10 pointers. |
| 3492 |
Maximum Containers on a Ship |
Simulate adding one container at a time to the n x n deck and checking the total weight against maxWeight. $O(N^2)$ |
Iterative Filling Grid. |
Draw an n x n grid. Color in one cell at a time until you hit the weight limit or run out of cells. |
Direct Math (Division & Min). $O(1)$ |
Capacity Constraint Threshold. |
Calculate total cells (n^2). Calculate how many containers the weight allows (maxWeight / w). The answer is the smaller of the two. |
Draw two boxes: "Space Limit" and "Weight Limit." Take the smallest number between them. |
Single Unit Block (Constant Time). |
Draw a single dot to represent that the calculation happens instantly regardless of N. |
An n x n matrix held in memory. |
Zero auxiliary space (only input variables). |
| 3493 |
Properties Graph |
Check every pair of nodes (i, j). Use two nested loops to find the intersection of their property arrays. $O(N^2 \cdot M)$ |
All-Pairs Intersection Web. |
Draw N dots. Draw lines between every pair. Next to each line, write the size of the intersection. |
Set-Based Adjacency List + DFS/BFS for Components. $O(N^2 \cdot M)$ (Optimized constant factor). |
Connected Components Forest. |
Convert arrays to Sets. Build the graph. Run DFS from every unvisited node to mark its component. Count the number of DFS starts. |
Draw the dots and edges. Circle each group of connected dots. Count the circles. |
Linear Graph Shading (V + E). |
Draw the graph and shade each node/edge exactly once. |
Massive N x N matrix of intersection counts. |
An Adjacency List (Map) and a boolean "Visited" array. |
| 3494 |
Find the Minimum Amount of Time to Brew Potions |
Simulate every wizard and potion in real-time, checking for collisions at every millisecond. $O(\text{TotalTime} \cdot N)$ |
Dense Discrete Event Timeline. |
Draw a gantt chart. For every second, check if wizard i is free to take potion j. |
Prefix Sums of Skill + Gap Analysis Formula. $O(N \cdot M)$ |
Assembly Line Bottleneck Search. |
Use prefix sums to get wizard work offsets. For each potion pair, find the maximum "wait time" caused by any wizard bottleneck. |
Draw the potions as blocks. For each block, calculate the "Safe Start Time" by looking at the previous potion's finish time at every wizard. |
N x M Matrix of Constraints. |
Draw a rectangle of size N x M. Shade it to show you visit each potion-wizard pair exactly once. |
Massive simulation state array. |
A single 1D array of size N for skill prefix sums. |
| 3495 |
Minimum Operations to Make Array Elements Zero |
For each query [l, r], explicitly construct the array and simulate the pairing of elements to divide by 4 until all are zero. $O(Q \cdot N \log(\text{max} V)$) |
Nested Loop Simulation Timeline. |
Draw a horizontal query line. For each, draw N vertical bars representing elements. Draw "scissor" marks cutting bars into 1/4 size repeatedly. |
Math + Prefix Sums of "Division Counts". $O(Q \log(\text{Range})$) or $O(Q \cdot 1)$. |
Parallel Reduction "Bucket" Logic. |
Each number x needs h(x) = lceil log_4(x+1) rceil divisions. For a range, the answer is max(lceil (sum h(i)) / 2 rceil, max h(i)). Use prefix sums to find the total divisions instantly. |
Draw a number line. Mark intervals [4^0, 4^1-1], [4^1, 4^2-1], etc. Color each interval with its h(x) value. Use prefix sums to count elements in each "color block". |
Range Sum Calculation. |
Draw a prefix sum array. For a query, draw two arrows pointing to l-1 and r. The gap represents the $O(1)$ answer calculation. |
Storing thousands of intermediate array states in memory. |
A fixed-size 1D prefix sum array (size sim 10^5 or a sparse map). |
| 3496 |
Maximize Score After Pair Deletions |
Try all combinations of removing two from front, two from back, or one from each using recursion/backtracking. $O(3^N/2)$ |
Tri-Branching Decision Tree. |
Draw a root node. Branch it into "Front", "Back", and "Both" options. Each branch explodes into 3 more until the array is empty. |
Greedy (Complementary Minimum Tracking). $O(N)$ |
Survival of the Smallest. |
Each operation removes exactly 2 elements. For odd N, 1 stays; for even N, a consecutive pair stays. Max score = Total Sum - min(possible leftovers). |
Draw the array. If N is odd, circle the smallest element. If N is even, circle the smallest adjacent pair sum. Everything else is "eaten" (summed). |
Single Pass Scan. |
Draw one straight horizontal arrow scanning the array once. |
Massive recursion stack depth N/2. |
$O(1)$ extra space using a single "min_seen" variable. |
| 3497 |
Analyze Subscription Conversion |
Join the UserActivity table with itself multiple times to find 'paid' after 'free_trial' for every user in a nested loop. $O(N^2)$ |
Self-Join Cartesian Product. |
Draw the table. Draw lines connecting every row to every other row to find chronological matches. |
SQL Common Table Expression (CTE) with Filtering and Grouping. $O(N)$ |
User Conversion Funnel. |
Filter for users who have a 'paid' record. Group by `user_id` and `activity_type`. Calculate `AVG(duration)` for 'free_trial' and 'paid' separately. |
Draw three boxes: "Activity Pool" to "Converted Users" to "Avg Metrics". Use arrows to show the filtering and aggregation flow. |
Hashed/Grouped Scan. |
Draw a database index scan (B-Tree traversal) to show $O(\log N)$ or $O(N)$ row-level processing. |
Massive temporary tables for the cross-joins. |
$O(U)$ memory where U is the number of unique converted users. |
| 3498 |
Reverse Degree of a String |
Nested loop: for each character, map its letter to a reversed alphabet list and then multiply by its index. $O(N \cdot 26)$ |
Double-Loop Processing. |
Draw the string. For each character, draw a secondary search scan across a 26-letter "reversed" alphabet. |
Single-Pass Simulation with ASCII Math. $O(N)$ |
Linear Product Accumulator. |
Calculate value V = 26 - (char - 'a') and multiply by index i+1. Sum these directly in one loop. |
Draw the string in boxes. Below each, write its string position. Below that, write its reverse-alpha value. Multiply and add. |
Linear Timeline. |
Draw one straight arrow moving once from index 0 to N-1. |
N/A - Primarily wasted CPU time. |
$O(1)$ extra space using a single "total_sum" variable. |
| 3499 |
Maximize Active Section with Trade I |
For every possible "1-block" to remove and "0-block" to convert, simulate the string and count the 1s. $O(N^3)$ |
Brute Force Triple Scan. |
Draw the binary string. Draw a bracket to remove 1s, then another to add 1s. Count all 1s in the result. Repeat for all pairs of brackets. |
Greedy (Adjacent Zero-Segment Merging). $O(N)$ |
Bridges over 1-Islands. |
Identify all contiguous segments of 0s. A "trade" merges two adjacent 0-segments by deleting the 1-segment between them. Max 1s = Original 1s + max(sum of two adjacent 0-segments). |
Draw segments like `00 | 111 | 0000`. Circle the 0-blocks. Connect any two with a "bridge" (trade). The bridge that covers the most 0s is the winner. |
Two-Pass Linear Scan. |
Draw one line to identify segments (O(N)), and a second to find the max adjacent pair (O(N)). |
Storing all possible modified binary strings in memory. |
A list of integer segment lengths of size sim N/2. |
| 3500 |
Minimum Cost to Divide Array Into Subarrays |
Recursive partitioning picking any i number of split points and calculating the cost formula for each. $O(2^N)$ |
Exponential Cut Tree. |
Draw a timeline. At every index, branch into "Cut" or "Keep Going". The tree width doubles at every step. |
DP with Convex Hull Trick (CHT) or prefix sum optimization. $O(N^2)$ |
Lower Convex Hull Envelope. |
Use DP state `dp[i][j]` (min cost using j subarrays for first i elements). The formula (P_nums[i] + k * j) x P_cost[p..i] can be viewed as a line y=mx+c. Maintain the hull to find the min in $O(1)$. |
Draw a 2D DP grid. For each cell, draw a line. The "best" choice is the lowest intersection on a vertical scan-line. |
Quadratic Matrix Shading. |
Draw a square grid of size N x N. Shade it row by row to show bounded polynomial complexity. |
Deep recursion stack with trillion-level overlapping states. |
A 2D memoization table or 1D rolling array of size N x (subarrays). |
| 3501 |
Maximize Active Section with Trade II (Hard) |
Generate all subsets of valid sections & test trades. |
Exponential Call Tree (Recursion). |
Draw a binary tree. Each node branches into 'Keep' or 'Trade'. Count total leaf nodes. |
Line Sweep Algorithm + DP with Segment Tree. |
1D Timeline Sweeping with active intervals. |
Slide a vertical ruler left-to-right over horizontal interval blocks, updating max values. |
Draw a horizontal axis. Stack intervals vertically. Draw dashed vertical lines at start/end events. |
Event-Sorting Pipeline (Linear array of events). |
Draw an array of N events. Next to it, draw a Segment Tree update taking log(N) steps. N * log(N). |
Call Stack Tower: Draw deep, nested boxes showing overlapping state frames. |
Array mapping: Draw a flat array for DP and a binary tree diagram for the Segment Tree memory. |
| 3502 |
Minimum Cost to Reach Every Position (Easy) |
BFS / Dijkstra's from start to all possible positions. |
Graph Traversal Map (Node expansion). |
Draw a starting dot, branch out to every valid next index. Write cumulative cost on edges. |
Greedy (Rightward free, Leftward paid). |
State Transition Diagram. |
Point a finger at current index. If moving right, draw a green arrow (cost 0). Left, red arrow (cost +X). |
Draw boxes for indices. Draw arched arrows jumping between boxes, labeling weights (0 or C). |
Linear Scan Pipeline. |
Draw a single straight line passing through N nodes. Write $O(1)$ ops under each node. |
BFS Queue memory: Draw a growing list of queue elements holding (index, cost). |
Single pointer tracking: Draw just two integer variables (Current Pos, Total Cost) overwriting themselves. |
| 3503 |
Longest Palindrome After Substring Concatenation I (Med) |
Concatenate all possible substring pairs, verify palindrome. |
Nested N^4 Loop Grid. |
Draw a 4D grid mapping (i, j) of str1 to (x, y) of str2. Shade cells that form palindromes. |
String Hashing + Center Expansion. |
Symmetry Mirroring Strings. |
Place a mirror line at each character/gap. Expand left and right pointers checking hash equality. |
Write the concatenated string. Draw a vertical line at the center. Draw symmetric arcs expanding outward. |
2-Pointer expansion over N centers. |
Draw N dots. From each dot, draw small expanding brackets. Max expansions = N. |
Massive Substring Allocation: Draw hundreds of string blocks duplicated in RAM. |
Prefix Hash Array: Draw two 1D arrays (forward hash, reverse hash) representing constant space lookups. |
| 3504 |
Longest Palindrome After Substring Concatenation II (Hard) |
DP checking all possible split and merge points. |
2D DP Matrix filling. |
Draw a huge N x N grid. Draw arrows showing cell (i,j) depends on (i+1, j-1). |
Manacher's Algorithm + Suffix Automaton / Hash. |
Radius Expansion Timeline. |
Track the rightmost palindrome boundary. Use previous symmetry to skip redundant character checks. |
Write string with # delimiters. Below each char, write its palindrome radius. Draw boundary brackets [L, R]. |
Right-Boundary shifting. |
Draw an axis. Draw a bracket [L, R]. Show R strictly moving rightward without backtracking. $O(N)$. |
N x N DP Table memory: Draw a vast grid of integers. |
1D Radius Array: Draw a single flat array of length 2N+1 holding radius integers. |
| 3505 |
Minimum Operations to Make Elements Within K Subarrays Equal (Hard) |
Iterate all target values, calculate differences for subarrays. |
3D Loop Box (Subarrays * Targets * Elements). |
Draw multiple nested arrays. For every subarray, draw a loop iterating over every possible target value. |
Sliding Window + Running Medians (Two Heaps). |
Balancing Scales (Max Heap / Min Heap). |
Slide a window of size K. Add incoming, remove outgoing. Keep lower half in Max Heap, upper in Min Heap. |
Draw two triangles (Heaps) balancing on a scale. Moving window: cross out old number, insert new. |
Heap rebalancing over linear time. |
Draw N elements entering a funnel (Heap insertion = log K). N * log K. |
Frequency Maps + Target Arrays: Draw massive hash maps for every subarray state. |
Two Heaps: Draw two fixed-size binary tree structures (size K/2) acting as real-time priority queues. |
| 3506 |
Find Time Required to Eliminate Bacterial Strains (Hard) |
Simulate spread step-by-step for every node/strain without caching. |
Multi-stage Graph Collapse. |
Draw original graph. Redraw the entire graph for time T=1, T=2, crossing out nodes. |
Multi-source BFS + Priority Queue (Dijkstra Variant). |
Wavefront Expansion on Graph. |
Color infected source nodes red. Draw expanding "ripples" to neighbors, writing timestamps. |
Draw nodes. Draw concentric dashed circles outward from sources, labeling each ring with time +T. |
Queue Processing Timeline. |
Draw a funnel (Priority Queue). N nodes go in, log(N) cost per node. Total: $O(V + E \log V)$. |
Deep Call Stack / Graph Copies: Draw multiple identical network graphs stacked on each other. |
Distance Array + Min-Heap: Draw a flat array of integers and a small binary tree (Heap). |
| 3507 |
Minimum Pair Removal to Sort Array I (Easy) |
Generate all subsequences, check if sorted, find minimum removals. |
Power Set Generation Tree. |
Draw a binary tree. Each level adds/drops an element. Check all 2^N leaf nodes. |
Dynamic Programming (LIS Variant). |
Bar Chart with Ascending Envelopes. |
Draw array as a bar chart. Draw a line connecting strictly increasing peaks. Removals = N - LIS. |
Write array. Draw arrows backward from current element to smaller previous elements. |
$O(N^2)$ Matrix Scan. |
Draw a 1D array. Under each cell, draw a line scanning all previous cells. Area of a triangle. |
Massive Subsequence Lists: Draw thousands of small arrays floating in memory. |
1D DP Array: Draw a single horizontal array tracking the max length ending at each index. |
| 3508 |
Implement Router (Med) |
Store routes in a List, linear string matching for every packet. |
Linear List Scan. |
Draw a vertical list of strings. Draw an arrow sliding top-to-bottom until a match is found. |
Trie (Prefix Tree) with Wildcard/Parameter Support. |
Branching Decision Tree. |
Split URL by '/'. Trace each segment down the tree. Fork paths for exact matches vs wildcards. |
Draw circles for path segments (e.g., 'api', 'users'). Draw lines connecting parent to child paths. |
Path Traversal Depth. |
Draw a tree. Highlight a single vertical line from root to a leaf. $O(L)$ where L is URL length. |
Array of Massive Strings: Draw a long table containing heavy, duplicated text data. |
Trie Nodes HashMaps: Draw circles (nodes) containing mini-tables pointing to next circles. |
| 3509 |
Max Product of Subsequences With an Alternating Sum Equal to K (Hard) |
Recursive combination generation, computing sum and product. |
Exponential Combination Tree. |
Draw a massive tree. Each node splits into 'Include (flip sign)' or 'Exclude'. |
3D Dynamic Programming (Knapsack with Sign State). |
State Machine DP Grid. |
Map transitions. If you include X, toggle between 'adding' and 'subtracting' states. |
Draw two parallel rows of boxes (+ state, - state). Draw crisscrossing arrows to move between them. |
2D Grid Filling. |
Draw a matrix of N (items) x K (sums). Shade cells left to right, constant work per cell. |
Huge Recursion Stack: Draw an endless stack of frames holding (index, sum, product, sign). |
Rolling DP Arrays: Draw just two 1D arrays (current state, next state) overwriting each other. |
| 3510 |
Minimum Pair Removal to Sort Array II (Hard) |
$O(N^2)$ DP (Same as 3507, but times out on large inputs). |
N-Squared Backward Arrows. |
Draw N nodes in a line. From the last node, draw N-1 arrows backwards. Area = $O(N^2)$. |
Segment Tree or Fenwick Tree (BIT) for $O(N \log N)$ LIS. |
Range Max Query Tree Updating. |
For each number, query max in range [0, num]. Add 1. Update tree at index 'num'. |
Draw array of values at bottom, binary tree hierarchy bridging over them. Update path to root. |
Tree Traversal per Element. |
Draw N steps horizontally. Above each step, draw a log(N) vertical path up a tree. $O(N \log N)$. |
Full NxN DP Matrix (if 2D used): Draw a massive unoptimized square grid. |
1D Fenwick/Segment Tree Array: Draw a single 1D array of size 4*N or M (max value). |
| 3511 |
Make a Positive Array (Med) |
Simulate all possible operations step-by-step to maintain positivity. |
Branching State Tree. |
Draw a tree where each node is an array state. Branch for every valid operation. Count leaf nodes. |
Greedy Accumulation / Prefix Sum tracking. |
Water Level Graph. |
Plot array values as a line graph. Identify 'dips' below zero. Add operation value to lift the entire curve above the x-axis. |
Draw an x-y axis. Plot a running sum line. Mark lowest negative peaks. Draw an upward arrow showing the greedy 'lift' needed. |
Single Linear Sweep. |
Draw a straight horizontal line of length N. Write $O(1)$ ops below each segment. |
Array Copies: Draw multiple identical array blocks stacked vertically, representing memory-heavy state copies. |
Running Counters: Draw two integer variables (Current Sum, Min Dip) updating in place. |
| 3512 |
Minimum Operations to Make Array Sum Divisible by K (Easy) |
Generate all subsets to remove/modify, checking if sum % K == 0. |
Subset Power Set Tree. |
Draw a binary tree. Each level decides to keep or modify an element. Check mod K at all 2^N leaves. |
Modular Arithmetic & Hash Map (Prefix Modulos). |
Circular Modulo Clock. |
Calculate total sum % K. Target is to remove subarrays matching this remainder. Map prefix sums to the clock face. |
Draw a circle with K tick marks. Plot running prefix sums on the clock. Draw chords between identical tick marks to find valid subarrays. |
Linear Scan with Constant Lookups. |
Draw an array of size N. Underneath, draw a single hash map box with arrows pointing to it in $O(1)$ time. |
Subset Arrays: Draw thousands of disjointed mini-arrays scattered across memory. |
Frequency Map: Draw a small, fixed-size table (size K) mapping remainder keys to index values. |
| 3513 |
Number of Unique XOR Triplets I (Med) |
Three nested loops (i, j, k) to compute and check XOR for every triplet. |
3D Loop Cube. |
Draw an N x N x N 3D grid. Shade the valid (i < j < k) triangular pyramid volume. Volume = $O(N^3)$. |
Bitwise Prefix XOR & Frequency Counting. |
XOR Cancellation Matrix. |
Use property A ^ B == 0 implies A == B. Track prefix XOR frequencies in a map to eliminate the innermost loop. |
Draw an array. Underneath, draw a prefix XOR array. Draw brackets connecting matching prefix values which denote XOR sum of 0. |
2D Nested Loop Equivalent. |
Draw a square grid, cutting it in half diagonally (representing $O(N^2)$). |
Loop Iterators: Draw three isolated pointers (i, j, k) constantly resetting. |
Prefix Array + Map: Draw one 1D array of size N, and a HashMap storing frequency counts. |
| 3514 |
Number of Unique XOR Triplets II (Med) |
$O(N^2)$ prefix XOR matching (fails on strict time limits). |
2D Diagonal Grid. |
Draw an N x N grid. Shade half of it. Area represents $O(N^2)$ operations. |
Bit-by-Bit Counting / Mathematical Combinatorics. |
Vertical Bit Matrix. |
Instead of horizontal array evaluation, look at the array vertically bit-by-bit. Count 1s and 0s at each bit position across all valid boundaries. |
Write numbers in binary, stacked vertically. Draw vertical boxes around each column. Count (zeros * ones) to find contribution to total XOR. |
Linear Scan over 32 bits. |
Draw an array of length N. Draw 32 layers stacked on top. $O(32 \cdot N)$ -> linear. |
Massive Hash Maps: Draw a bloated hash table holding up to N unique XOR sums. |
Constant Size Array: Draw a small, fixed array of size 32 holding integer counts. |
| 3515 |
Shortest Path in a Weighted Tree (Hard) |
BFS/DFS from source to destination for every single query. |
Repeated Graph Flooding. |
Draw the tree. For query 1, color paths red. Erase. For query 2, color paths blue. Repeat Q times. Cost: $O(Q \cdot N)$. |
Lowest Common Ancestor (LCA) with Binary Lifting. |
Ancestral V-Shape Paths. |
Distance(U, V) = Dist(Root, U) + Dist(Root, V) - 2 * Dist(Root, LCA(U, V)). Precompute root distances. |
Draw a tree. Pick nodes U and V. Trace upward to their highest shared parent (LCA). Draw the mathematical equation next to the V-shape. |
Logarithmic Tree Climbing. |
Draw a node jumping up the tree in exponentially increasing steps (1, 2, 4, 8). $O(\log N)$ per query. Total: $O(N \log N + Q \log N)$. |
Call Stack Overload: Draw deep recursive stacks for every individual DFS query. |
Sparse Table / 2D Array: Draw an N x log(N) matrix for jump pointers, and a 1D array for root-distances. |
| 3516 |
Find Closest Person (Easy) |
Iterate through all coordinates, calculate absolute distance to target, find minimum. |
Linear Scan / Measuring Tape. |
Draw the target as a star. Draw N people. Draw lines from the star to every single person, labeling the distance. |
Binary Search (if sorted) or Single Pass Min-Tracker. |
Bisection / Pincer Search. |
Place L and R pointers at the ends of the array. Find Mid. Compare distance. Move L or R to halve the search space. |
Draw a sorted array. Draw brackets [L, R]. Draw an arrow at Mid. Cross out the half of the array that is further away. |
Logarithmic Halving. |
Draw a block of length N. Below it, a block of N/2, then N/4, down to 1. $O(\log N)$. |
Full Array Scan: No extra memory, but mentally visualizing checking every index holding data. |
Two Pointers: Draw two distinct variables (L, R) jumping across indices. |
| 3517 |
Smallest Palindromic Rearrangement I (Med) |
Generate all string permutations, check if palindrome, sort lexicographically, pick first. |
Factorial Permutation Tree. |
Draw a massive branching tree where each level adds the next character. N! leaves at the bottom. |
Character Frequency Counting + Greedy Symmetric Placement. |
Mirror & Bucket Fill. |
Count char frequencies. If valid (at most 1 odd count), place half of each char alphabetically. Mirror it. Insert odd char in middle. |
Draw 26 buckets for a-z. Draw a blank template `[ _ _ (mid) _ _ ]`. Fill left side from bucket 'a' upwards. Mirror to right side. |
Linear Scan & Build. |
Draw an array of length N scanned once to build a map, then a loop of N/2 to build the string. $O(N)$. |
Permutation Array: Draw millions of string variations flooding the heap memory. |
Frequency Map + StringBuilder: Draw a fixed size-26 integer array, and one character array. |
| 3518 |
Smallest Palindromic Rearrangement II (Hard) |
Backtracking to try all valid swap sequences to enforce palindrome constraints. |
Constrained Backtracking Tree. |
Draw a decision tree with deep branches. Draw big red 'X's on branches that violate constraints early. |
Two-Pointer Greedy Swapping (Bubble Swaps for target positions). |
Inward Pincer with Bubble Swaps. |
L at start, R at end. If mismatch, find closest matching char to R starting from L's right, bubble-swap it over. |
Write the string. Draw inward arrows from L and R. If L != R, draw a curved arrow jumping a matching character over to the left side. |
$O(N^2)$ Bubble Decay. |
Draw an inverted triangle representing the shrinking search space for character matching. |
Deep Recursion Stack: Draw nested stack frames holding partial string states. |
In-Place Char Array: Draw a single string array being mutated directly via index swaps. |
| 3519 |
Count Numbers with Non-Decreasing Digits (Hard) |
Loop from 1 to N, convert each number to string, check if digits are non-decreasing. |
Number Line Filtering. |
Draw a long timeline from 1 to N. Draw checkmarks on valid numbers (e.g., 123) and cross out invalid ones (e.g., 210). |
Digit DP (Dynamic Programming) / Combinatorics. |
State Transition Grid (DAG). |
For D digits, transition from previous digit 'k' to next digit 'j' only where j >= k. |
Draw a 10 x D grid (Rows 0-9, Cols = digit positions). Draw arrows connecting cells, only allowing arrows that go straight right or down-right. |
DP Table Fill. |
Draw a 10 x log10(N) matrix. Shade cells left to right indicating constant work per state. $O(10 \cdot \log N)$. |
No memory, but $O(N)$ time visualizes as an endlessly spinning CPU cycle. |
2D Memoization Table: Draw a small grid `memo[position][last_digit]` caching integer counts. |
| 3520 |
Minimum Threshold for Inversion Pairs Count (Med) |
Test all possible thresholds linearly, apply to array, count inversions via nested loops. |
Nested Loop Matrix Scan. |
Draw a master loop for thresholds. For each threshold, draw an N x N matrix counting crossing lines. |
Binary Search on Answer + Fenwick Tree (BIT) / Merge Sort for Inversions. |
Binary Search Over Merge Sort. |
Pick threshold M. Transform array. Count inversions using Merge Sort logic. If count <= K, try a smaller threshold (search left). |
Draw a number line for thresholds. Pick Mid. Below it, draw an array splitting and merging, counting crisscrossing elements. |
Log(Max) * N log N. |
Draw a binary search tree of depth log(Max). Inside each node, draw an N log N merge sort operation. |
Continuous Array Duplication: Draw endless copies of the original array being mutated for threshold testing. |
Fenwick Tree / Temp Arrays: Draw a single size N BIT array reused and zeroed out for each binary search step. |
| 3521 |
Find Product Recommendation Pairs (Med) |
Cross-join all users and products, manually calculating similarity scores for every pair. |
Complete Bipartite Graph Grid. |
Draw a massive matrix (Users x Products). Draw arrows from every user to every product, tallying interaction scores. |
Graph Traversal (BFS) / Collaborative Filtering with Inverted Index. |
Bipartite V-Shape Traversal. |
Pick a target user. Traverse to their bought products, then traverse back to other users who bought those, then forward to new products. |
Draw two columns: Users (L) and Products (R). Draw a V-shaped path: User A -> Product 1 -> User B. |
Sparse Matrix Traversal. |
Draw a mostly empty matrix. Trace a thin branching tree representing only the 2-hop active edges. $O(U + E)$. |
Dense NxM Matrix: Draw a massive, mostly empty 2D array consuming huge memory. |
Adjacency List: Draw a vertical array of Users, with linked lists pointing only to interacted products. |
| 3522 |
Calculate Score After Performing Instructions (Med) |
Simulate the instruction string step-by-step, updating coordinates directly for every single query. |
Winding Path Tracing. |
Draw a grid. For Q queries, draw the entire winding path taking up to N steps each time. Total area = $O(Q \cdot N)$. |
Prefix Sums on 2D Coordinates / Hash Map caching. |
Displacement Vector Chart. |
Instead of walking every step, use a lookup table to instantly jump to the net displacement after K instructions. |
Plot a start point. Instead of squiggly lines, draw one straight vector arrow pointing directly to the final coordinate. |
$O(1)$ Vector Jump. |
Draw an array of N prefix states. Draw a query resolving instantly in 1 step by subtracting prefix[R] - prefix[L]. |
Massive State Logs: Draw endless lists recording every tiny coordinate change per query. |
Prefix State Array: Draw a single 1D array of (x, y) vectors representing cumulative movement. |
| 3523 |
Make Array Non-decreasing (Med) |
Try all possible valid increments at each step to satisfy condition, backtracking if total cost is sub-optimal. |
Exponential State Space Tree. |
Draw an array. From each element, branch out lines representing +1, +2, +3 operations. Results in an explosive tree. |
Greedy Single-Pass / Max-Tracker. |
Staircase Leveling. |
Walk right. If the next step is lower than the current step, physically 'lift' the next step to match. Accumulate lift cost. |
Draw a bar chart. Draw a horizontal dashed line from the top of the highest bar seen. Shade the empty space to fill. |
Single Rightward Sweep. |
Draw a horizontal axis. Draw one straight arrow scanning from left to right. $O(N)$. |
Recursion Call Stack: Draw deep stack frames holding copied, slightly modified array states. |
Max-Tracker Variable: Draw just one integer box holding "Max Seen So Far" overwriting itself. |
| 3524 |
Find X Value of Array I (Med) |
Iterate all possible candidate values for X, applying the formula to the entire array to check validity. |
Nested Domain Loop. |
Draw a timeline of X values. Under each tick, draw an inner loop scanning the entire N-length array. $O(\text{Max}_X \cdot N)$. |
Bitwise Evaluation / Prefix Counts. |
Bit-level Decision Tree. |
Construct the ideal X bit-by-bit from MSB to LSB, making local greedy decisions to maximize/minimize the target. |
Write 32 blank slots `_ _ _ _`. For each slot, evaluate if a '1' or '0' is better using array bit counts. Fill left to right. |
32-Step Linear Scan. |
Draw 32 vertical levels. At each level, draw an $O(N)$ scan. $O(32 \cdot N)$. |
Heavy CPU Iteration: CPU registers visualized constantly overwriting during deep nested loops. |
Bit Count Array: Draw an array of size 32 holding counts of set bits at each position across the array. |
| 3525 |
Find X Value of Array II (Hard) |
$O(N^2)$ pairing or iterative domain search (times out on large constraints). |
Dense Grid Re-evaluation. |
Draw a massive 2D grid representing X domain vs Array indices. Shade the entire grid. |
Binary Search on Answer + Sliding Window / Segment Tree. |
Range Query Funnel. |
Use binary search to guess X. Validate X in $O(N)$ using a sliding window to check subarray constraints efficiently. |
Draw a binary search tree of X values. For a node (guess), draw a sliding window `[L...R]` smoothly moving across the array. |
Logarithmic Search over Linear Scan. |
Draw a binary tree of depth log(Range). Inside each node, draw a straight $O(N)$ sliding window line. $O(N \log(\text{Range})$). |
Huge Search Space Maps: Draw massive lists of evaluated candidates. |
Window Pointers: Draw two variables (L, R) acting as boundaries on a flat array. |
| 3526 |
Range XOR Queries with Subarray Reversals (Hard) |
Physically reverse the subarray elements, then loop to calculate the XOR sum for each query. |
Array Flipping & Scanning. |
Draw an array. For each query, cross out a section, rewrite it backwards, then draw a bracket to XOR sum it. $O(Q \cdot N)$. |
Implicit Treap (Randomized Binary Search Tree) / Splay Tree with Lazy Propagation. |
Tree Splitting and Merging. |
Split the tree into 3 parts: [Left, Target, Right]. Tag the Target root with a "reverse" flag. Merge them back. |
Draw a binary tree. Cut edges to isolate a subtree. Draw a circular arrow (reverse flag) on its root. Reattach the edges. |
Logarithmic Tree Operations. |
Draw a tree of depth log N. Draw a path down the tree splitting nodes, taking log N steps per query. |
Continuous Array Reallocation: Draw heavily duplicated arrays flooding memory for every reverse operation. |
Pointer/Node Graph: Draw isolated circle nodes connected by left/right pointers, holding "lazy" boolean flags. |
| 3527 |
Find the Most Common Response (Med) |
Iterate through all responses, use nested loops to count occurrences, keep track of maximum. |
Nested Loop Tallying. |
Write down the list. Pick word 1, scan the whole list counting it. Pick word 2, scan whole list. $O(N^2)$. |
Hash Map Counting + Single-Pass Max Tracking. |
Key-Value Bins with a High-Water Mark. |
Drop each word into its designated bin. If a bin's height exceeds the current "max height" marker, update the winner. |
Draw squares labeled with words. Add a tally mark inside each time you see the word. Keep a separate "Winner" box updated. |
Linear Scan to $O(1)$ Lookup. |
Draw a straight timeline of N inputs pointing directly into a Hash Map (O(1) operation per step). Total $O(N)$. |
Unstructured String Lists: Draw raw, unsorted arrays holding heavy string data over and over. |
Hash Table Structure: Draw a 2-column table mapping unique strings to integer frequencies. |
| 3528 |
Unit Conversion I (Med) |
Run a BFS or DFS graph traversal for every single conversion query to find the multiplier path. |
Wandering Graph Search. |
Draw nodes (units) and edges (rates). For each query, trace a winding path from start to target multiplying edges. |
Floyd-Warshall (Precomputation) or Weighted Disjoint Set Union (DSU). |
Precomputed Conversion Matrix / Star Graph. |
Precalculate all pairs or relate everything to a single "base unit". To convert A to B, calculate (A to Base) * (Base to B). |
Draw a grid with units on X and Y axes. Point your finger to cell (A, B) to instantly get the multiplier value. |
$O(1)$ Matrix Lookup / Tree Jump. |
Draw a query instantly pointing to a 2D matrix coordinate. $O(1)$ per query after $O(V^3)$ or $O(V)$ setup. |
Deep Recursion Call Stack: Draw deep stack frames for DFS paths holding intermediate conversion floats. |
Dense 2D Matrix: Draw a compact N x N grid populated with precomputed floating-point rates. |
| 3529 |
Count Cells in Overlapping Horizontal and Vertical Substrings (Med) |
Check every single cell in the grid against all horizontal and vertical constraints. |
Grid Cell-by-Cell Scanning. |
Draw an N x M grid. For every cell, draw a horizontal line and a vertical line checking boundary conditions. $O(N \cdot M \cdot K)$. |
Line Sweep / Prefix Sums / 2D Difference Arrays. |
Orthogonal Shadow Intersections. |
Find valid horizontal ranges, project them as vertical bands. Find valid vertical ranges, project as horizontal bands. |
Draw a grid. Lightly shade valid horizontal rows blue. Lightly shade valid vertical columns yellow. Count the green overlapping squares. |
Independent 1D Array Scans. |
Draw an array of size N and an array of size M. $O(N + M)$ logic instead of nested $O(N \cdot M)$. |
Multiple Boolean Grids: Draw several N x M grids overlaid, wasting memory on binary states. |
Two 1D Prefix Arrays: Draw just two single-row arrays (Row bounds, Col bounds) tracking coordinate limits. |
| 3530 |
Maximum Profit from Valid Topological Order in DAG (Hard) |
Generate all valid topological permutations, calculate profit for each sequence, return max. |
Factorial Path Permutations. |
Draw a massive branching tree. Each branch represents picking a valid 0-indegree node. $O(N!)$ leaf nodes. |
Dynamic Programming with Bitmask (State Compression). |
State Transition DAG. |
Represent visited nodes as a bitmask (e.g., 0101). Transition to valid next states by flipping bits, carrying max profit forward. |
Write binary states like `0011`. Draw arrows to next states like `0111` or `1011`, labeling the edges with the profit gained. |
$O(N \cdot 2^N)$ Subproblem Expansion. |
Draw levels grouped by the number of '1' bits in the state. Draw edges connecting N to N+1 levels. |
Massive Sequence Arrays: Draw heavy memory blocks storing every possible path string. |
1D DP Bitmask Array: Draw a single array of size 2^N storing integer profits, indexed by the bitmask. |
| 3531 |
Count Covered Buildings (Med) |
Iterate through all buildings, and for each, check against every single coverage interval. |
Many-to-Many Overlap Grid. |
Draw N buildings as vertical bars. Draw M intervals above them. Draw lines from every interval down to every building it covers. $O(N \cdot M)$. |
Difference Array / Line Sweep. |
Sweeping Vertical Scanner. |
Sweep left to right. Add +1 to a running total when an interval starts, -1 when it ends. If total > 0 at a building, it's covered. |
Draw a number line. Mark +1 at start coordinates and -1 at end coordinates. Plot a staircase graph showing the running sum going up and down. |
Linear Scan on Sorted Points. |
Draw an array of sorted coordinates. Draw a single straight arrow sweeping across it, updating one variable. $O(N \log N)$. |
Boolean Arrays/Hash Sets: Draw a massive boolean array storing the covered state individually for every coordinate point. |
Event Array + Counter: Draw an array of `[coordinate, +1/-1]` tuples, and a single integer variable for the active count. |
| 3532 |
Path Existence Queries in a Graph I (Med) |
Run a BFS or DFS from the start node to the destination for every single query. |
Repeated Graph Flooding. |
Draw a graph. For query 1, color a path red. Erase it. For query 2, color a path blue. Repeat Q times. $O(Q \cdot (V + E)$). |
Disjoint Set Union (DSU) / Connected Components. |
Merging Component Bubbles. |
Process all edges once. If two nodes connect, put them in the same "bubble". For queries, just check if start and end are in the same bubble. |
Draw nodes as scattered dots. Draw circles around connected dots, merging circles as you add edges. Queries just check if two dots share a circle. |
Near $O(1)$ Query Lookups. |
Draw edges funnelling into a setup box (O(V+E)). Then draw queries instantly hitting an $O(1)$ check. |
Call Stack/Queue Overload: Draw deep recursion stacks or long queue arrays for each individual graph search. |
Parent Pointer Array: Draw a single 1D array of size V, where each index points to its component's "root" node. |
| 3533 |
Concatenated Divisibility (Hard) |
Concatenate every possible pair of numbers as strings, parse to integer, and check modulo K. |
N^2 String Concatenation. |
Draw a massive N x N grid. In every cell, write "Num1 + Num2", followed by a long division sign. $O(N^2)$. |
Modular Arithmetic + Hash Map (Digit Length Bins). |
Mathematical Complement Bins. |
`Concatenated % K == 0` means `(X * 10^len(Y) + Y) % K == 0`. Precompute remainders of Y, group by length, and search for the mathematical complement needed by X. |
Draw bins labeled by digit lengths (1-digit, 2-digit). Put `Y % K` values inside. For a given X, calculate its required complement and draw an arrow directly to the matching bin. |
Linear Scan + $O(1)$ Lookup. |
Draw an array of N numbers. Under each number, draw an arrow to a hash map taking $O(1)$ time. $O(N)$. |
Massive String Allocations: Draw hundreds of thousands of newly allocated concatenated strings flooding heap memory. |
2D Frequency Map: Draw a small grid `map[digit_length][remainder]` storing integer counts. |
| 3534 |
Path Existence Queries in a Graph II (Hard) |
Run constrained BFS/DFS for each query, strictly ignoring edges that violate the current query's threshold. |
Filtered Graph Traversals. |
Redraw the graph for every query. Manually cross out edges that are too heavy/light, then attempt to trace a path. |
Offline Queries + DSU with Sorting. |
Gradual Graph Construction (Line Sweep). |
Sort edges and queries by threshold. Progressively add edges to the DSU as the threshold allows. Answer queries using the current DSU state exactly when their threshold is met. |
Draw two queues: Edges and Queries. Move a vertical "threshold" ruler to the right. As edges pass the ruler, drop them into a DSU bubble. As queries pass, answer them instantly. |
Two Sorted Timelines Merging. |
Draw two sorted arrays being processed by a single two-pointer sweep. $O(E \log E + Q \log Q)$. |
Full Graph Copies: Storing the entire graph in memory and duplicating sub-graphs for constraint filtering. |
Offline Query Array + DSU: Draw an array storing `[query_weight, u, v, original_index]` to remember where to place the answer. |
| 3535 |
Unit Conversion II (Med) |
BFS/DFS for every query to find the conversion multiplier, handling disconnected subgraphs dynamically. |
Blind Maze Running. |
Draw a map of units. Start at unit A, wander around multiplying edge weights until hitting unit B. If blocked, return -1.0. |
Graph Precomputation (Anchored Weights) / Component Ratios. |
Anchored Weight Networks (Star Graphs). |
For each isolated group of units, pick a "root" node and assign it a value of 1.0. Precalculate every other node's value relative to that root. Query = value(A) / value(B). |
Draw isolated groups of stars. The center is 1.0. Branch nodes have floating point values. A query draws a line between two nodes, instantly dividing their values if they share a star. |
Linear Build, Constant Query. |
Draw an $O(V+E)$ initial setup sweeping the graph. Draw Q queries pointing instantly to a division operation. $O(V+E+Q)$. |
Recursive Call Stacks: Draw stacks holding intermediate conversion floats during deep graph walks. |
Component & Ratio Arrays: Draw two flat arrays: `component_id[node]` and `relative_value[node]`. |
| 3536 |
Maximum Product of Two Digits (Easy) |
Extract all digits, use a double loop to multiply every possible pair. |
Handshake Matrix. |
Draw an N x N grid of all extracted digits. Shade the lower triangle and calculate products for each cell. $O(N^2)$. |
Single Pass Max/Min Tracker (Greedy). |
Podium Ranking. |
Scan digits once. Maintain a 1st Place and 2nd Place slot for the largest digits (and smallest if negatives are allowed). Multiply them at the end. |
Draw two boxes labeled 'Max1' and 'Max2'. Draw an arrow sweeping across the digits, bumping values down the podium if a larger one is found. |
Linear Scan to $O(1)$ Math. |
Draw a single straight line through N digits. Draw a single multiplication sign at the end. $O(N)$. |
Digit Arrays: Draw an array storing every single extracted digit, wasting space for a simple max-find. |
Two Integer Variables: Draw just two independent boxes holding the top values, overwriting in place. |
| 3537 |
Fill a Special Grid (Med) |
Backtracking DFS to try placing every valid number in every empty cell, rolling back on failure. |
Deep Recursion Tree. |
Draw a massive branching tree. Each node is a grid state. Draw red 'X's on branches that violate row/col rules and backtrack. $O(K^(N\cdot M)$). |
Constructive Algorithm / Greedy Pattern Filling. |
Tessellation / Offset Staggering. |
Use mathematical offsets (like `(row + col) % K`) to predictably drop numbers into valid slots without needing to check constraints repeatedly. |
Draw a blank grid. Instead of guessing, write a simple math formula next to the grid and fill cells diagonally in a predictable, repeating pattern. |
Single Grid Sweep. |
Draw a matrix. Draw a single continuous snake-like arrow passing through every cell exactly once. $O(N \cdot M)$. |
Call Stack Overload: Draw thousands of stacked grid states taking up massive memory during recursion. |
In-Place Matrix: Draw the output 2D array being filled exactly once, with $O(1)$ auxiliary space. |
| 3538 |
Merge Operations for Minimum Travel Time (Hard) |
Simulate all possible edge merging sequences using factorial/exponential DFS paths. |
Explosive State Graph. |
Draw a network. Branch off by picking edge A to merge, then branch again. Creates a massive web of overlapping simulation states. |
Disjoint Set Union (DSU) / Kruskal's Variant with DP. |
Component Gravity. |
Sort edges by travel time. Greedily merge closest nodes into expanding component "bubbles", carrying a minimum time state within each bubble. |
Draw nodes. Draw circles expanding and eating other nodes based on edge weights. Write a running "min time" counter inside each expanding bubble. |
Sorted Edge Processing. |
Draw an array of edges being sorted $O(E \log E)$, then a linear scan $O(E)$ feeding into a DSU. |
Deep Simulation States: Draw heavy memory blocks storing entire modified adjacency lists for every recursion step. |
DSU Parent Array: Draw a simple 1D array representing tree roots, using near-zero extra space. |
| 3539 |
Find Sum of Array Product of Magical Sequences (Hard) |
Generate every valid magical subsequence, calculate their products iteratively, and sum them up. |
Combinatorial Power Set. |
Draw an expanding binary tree deciding to include/exclude elements to form valid sequences. Calculate product at each of the 2^N leaves. |
Dynamic Programming with Mathematical Contribution (Prefix Arrays). |
State Transition Multipliers. |
Track the sum of products of sequences ending at index `i`. Current state = `Previous Sum * Current Element + Current Element`. |
Draw a 1D DP array. Draw an arrow from `DP[i-1]` to `DP[i]`, writing the formula `(val * DP[i-1]) + val` on the arrow to show the math cascade. |
Linear Sweep with Modulo Math. |
Draw an array of size N. Draw a straight arrow left to right, performing constant $O(1)$ math at each step. $O(N)$. |
Massive Subsequence Lists: Draw gigabytes of memory storing millions of individual arrays before doing the math. |
Rolling Variable DP: Draw just two integer variables (Previous Sum, Current Sum) overwriting themselves. |
| 3540 |
Minimum Time to Visit All Houses (Med) |
Permutation generator to try every possible order of visiting houses, checking distance. |
Factorial Pathing. |
Draw N dots. Draw every possible tangled web of lines connecting all dots. Calculate total length for N! paths. |
Sorting / 1D Greedy Sweep (Assuming 1D coordinate plane). |
Bounding Box / Extremes First. |
If houses are on a line, sort them. The minimum time is simply traversing from the smallest coordinate to the largest. |
Draw dots on a number line. Draw one large arc from the leftmost dot directly to the rightmost dot. No zigzagging required. |
Sorting Bottleneck. |
Draw an array of points. Show an $O(N \log N)$ sorting step, followed by an $O(1)$ math check `Max - Min`. |
Path Permutation Arrays: Draw arrays holding every valid sequence of house indices. |
In-Place Sort: Draw the original array being reordered, requiring $O(1)$ or $O(\log N)$ stack space. |
| 3541 |
Find Most Frequent Vowel and Consonant (Easy) |
Two separate passes: one to find all vowels and count, another for consonants. |
Double String Scan. |
Draw two parallel arrows passing over the same string. Tally each type into long lists. $O(2N)$. |
Single Pass with Hash Map/Frequency Array. |
Sorting Bins (Vowel vs Consonant). |
Scan the string once. For each char, check if it's in "aeiou". Increment the respective vowel/consonant map counter. Update max trackers. |
Draw two small tables (5 rows for vowels, 21 for consonants). Mark tallies as you read left-to-right. Circle the winner in each table. |
$O(N)$ Single Stream. |
Draw a single straight arrow through the string. Highlight constant-time $O(1)$ map updates below it. |
Massive Sub-strings: Draw memory blocks storing extracted vowel-only and consonant-only strings. |
Fixed Size Maps: Draw two small grids (size 5 and size 26) storing integer counts. |
| 3542 |
Min Ops to Convert All Elements to Zero (Med) |
Iteratively subtract 1 from every non-zero element until all are zero. |
Gradual Element Decay. |
Draw an array. Repeatedly cross out numbers and write (Value-1) below them. Count total operations. $O(N \\text{cdot Max}_\text{Val})$. |
Greedy Selection + Difference Array / Sorting. |
Staircase Collapse. |
Sort unique elements. Instead of -1 repeatedly, subtract the difference between the current smallest and the next. All equal elements drop together. |
Draw a bar chart. Draw a horizontal line at the lowest non-zero bar. "Cut" the top off and shift it down. Count the distinct bar heights. |
$O(N \log N)$ Sorting. |
Draw an unsorted array. Draw a sorted version below it. Show $O(N)$ traversal of the unique elements. |
Operation Logs: Draw a huge list recording every single subtraction operation performed. |
Set/Sorted Array: Draw a single 1D array or a Set containing only unique values from the input. |
| 3543 |
Maximum Weighted K-Edge Path (Med) |
Find all possible paths of length K using DFS and track the maximum weight. |
Recursive Path Explosion. |
Draw a node. Branch out to neighbors. From each neighbor, branch again K times. $O(V^K)$. |
Dynamic Programming (Bellman-Ford variant). |
Layered Wavefront. |
Define `DP[k][u]` as the max weight path of length `k` ending at node `u`. Update `DP[k]` using results from `DP[k-1]`. |
Draw K columns of nodes. Draw arrows between column `i` and `i+1`. Label each node with the max weight found so far. |
Iterative Edge Relaxation. |
Draw K boxes. Each box represents $O(E)$ work (looping over all edges). Total: $O(K \cdot E)$. |
Recursion Stack: Draw deep stack frames for every possible path branch up to depth K. |
2 x V DP Array: Draw two 1D arrays of size V (current layer and previous layer) representing current maxes. |
| 3544 |
Subtree Inversion Sum (Hard) |
For every node, extract its entire subtree, count inversions using a nested loop, and sum them. |
Repeated Subtree Scanning. |
Draw a tree. At each node, circle its descendants and draw an N x N inversion grid for that subset. $O(N^2)$. |
DFS + Fenwick Tree (BIT) / Merge Sort Tree. |
Time-In/Time-Out Tree Flattening. |
Flatten tree into an array (Euler Tour). A subtree becomes a contiguous range. Use a BIT to count inversions as you traverse. |
Draw a tree. Map nodes to an array based on visit order. For each node, query the BIT for its range [In, Out]. |
$O(N \log N)$ Traversal. |
Draw a tree traversal path. At each node, draw a log(N) vertical line representing a BIT query/update. |
Subtree Copies: Draw multiple copies of parts of the tree as arrays for manual inversion counting. |
Euler Array + BIT: Draw one 1D array for the tree order and one Fenwick Tree (size N). |
| 3545 |
Min Deletions for At Most K Distinct Characters (Easy) |
Generate all substrings, check if distinct chars <= K, pick longest, deletions = Total - Longest. |
All-Pairs Substring Matrix. |
Draw an N x N grid of substrings. Check each one for distinct characters. $O(N^3)$. |
Sliding Window (Two Pointers). |
Expanding/Shrinking Frame. |
Move Right pointer to add characters. If distinct count > K, move Left pointer until distinct count <= K. Track max width. |
Draw the string. Place a transparent "window" (two brackets). Slide it right, expanding and shrinking while keeping a tally in a map. |
Linear Scan. |
Draw a string with two arrows (L and R) moving only forward. $O(2N)$ -> $O(N)$. |
Substring List: Draw a list of every valid substring stored in memory. |
Char Frequency Map: Draw a small hash map (max size 26) tracking characters in the current window. |
| 3546 |
Equal Sum Grid Partition I (Med) |
Iterate through every possible horizontal or vertical split line and sum both sides. |
Grid Scanning per Split. |
Draw a grid. Draw a dashed line after column 1, then scan and sum. Redraw dashed line after column 2, rescan. $O(N \cdot M \cdot (N+M)$). |
2D Prefix Sums (Inclusion-Exclusion). |
Integral Image Grid. |
Calculate cumulative sum from top-left. To get the sum of any partition, use the formula: `S(x,y) = Pref[x][y]`. Compare against `TotalSum / 2`. |
Draw a grid with cumulative totals. Draw a single cut line. Subtract the sum of the left/top block from the total instantly. |
$O(N \cdot M)$ Precompute, $O(1)$ Query. |
Draw a grid filled with arrows pointing top-left (precompute). Then draw a single line splitting the grid (O(1)). |
Repeated Sub-grid Copies: Draw multiple smaller grids being created in memory for every split attempt. |
Prefix Matrix: Draw one 2D array of the same size as the grid, storing running totals. |
| 3547 |
Maximum Sum of Edge Values in a Graph (Hard) |
Generate all possible spanning trees or subgraphs and calculate the sum of edges. |
Combinatorial Graph Explosion. |
Draw nodes. Draw every possible edge combination. Tally sums for the millions of valid structures. $O(2^E)$. |
Greedy (Kruskal's) or Tree DP (if constrained). |
Edge Weight Ranking. |
Sort all edges by weight descending. Add edges to the graph unless they violate a constraint (like degree limit or cycle). |
Draw a list of edges sorted by weight. Draw nodes as dots. Connect nodes using the heaviest edges first until you hit a limit. |
$O(E \log E)$ Sorting. |
Draw a sorted list of edges. Draw a single pass through the list with a DSU 'Check-and-Merge' step. |
Subgraph Lists: Draw heaps of individual edge-list objects representing different graph configurations. |
DSU / Adjacency Map: Draw a parent array for connectivity or a map of node degrees. |
| 3548 |
Equal Sum Grid Partition II (Hard) |
Try every combination of two cuts (one horizontal, one vertical) and check all four quadrants for equal sums. |
Dual-Axis Permutations. |
Draw a grid. Draw all combinations of a crosshair (+) at every (i, j) intersection. Sum all 4 quadrants for each. $O(N^2 \cdot M^2)$. |
2D Prefix Sums + Hash Map / Binning. |
Crosshair Complement Search. |
Fix the horizontal cut. Use 1D prefix sum logic on the row-sums to find the vertical cut that splits the total exactly in half. |
Draw a grid with horizontal splits. For one split, write the sums of the top and bottom halves. Search for a vertical line that bisects both. |
$O(N \cdot M)$. |
Draw a grid. Draw one vertical sweep through rows and one horizontal sweep through columns. $O(N \cdot M)$. |
Nested Sum Loops: Visualizing the CPU recalculating quadrant sums for every coordinate. |
1D Row/Col Sum Arrays: Draw two small 1D arrays tracking the total mass of each row and column. |
| 3549 |
Multiply Two Polynomials (Hard) |
Standard nested loop (convolution): multiply every term of Poly A by every term of Poly B. |
All-to-All Term Mapping. |
Draw two lists (A and B). Draw arrows from every element in A to every element in B. Tally into result indices. $O(N \cdot M)$. |
Fast Fourier Transform (FFT) or Karatsuba. |
Frequency Domain Butterfly. |
Convert polynomials to "Point-Value" form using complex roots of unity. Multiply point-wise. Inverse FFT back to coefficients. |
Draw a 'Butterfly Diagram': pairs of values merging and splitting through layers. |
$O(N \log N)$. |
Draw a recursive tree of depth log N. At each level, show N work. $O(N \log N)$. |
Result Coefficient Array: Draw a large array of size N+M, but visualized as being updated $O(N\cdot M)$ times. |
Complex Value Arrays: Draw two arrays of complex numbers (real + imaginary) being transformed in-place. |
| 3550 |
Smallest Index With Digit Sum Equal to Index (Easy) |
Convert index to string, sum characters, compare to index. Repeat until found. |
Linear Search with String Conversion. |
Draw a number line. For each number, draw a balloon showing its digits. Sum them and check if it equals the coordinate. $O(N \cdot \log N)$. |
Linear Scan with Mathematical Digit Extraction. |
Single Stream Evaluation. |
Loop from 0 to N. Use `% 10` and `/ 10` to get digits. If `sum == index`, return immediately. |
Draw a table: `Index | Digits | Sum`. Write numbers 0, 1, 2... and stop as soon as the last two columns match. |
$O(N)$ or $O(\text{Constant})$ if limit is small. |
Draw a straight arrow through the number line. Stop at the first "Golden Index." |
String Buffer: Draw temporary string objects being created and destroyed in the heap for every number. |
Integer Variables: Draw one 'sum' variable and one 'temp' variable being reused for every loop iteration. |
| 3551 |
Minimum Swaps to Sort by Digit Sum (Med) |
Generate all permutations of the array and find the one that matches the digit-sum sort order with minimum swaps. |
Factorial Permutation Forest. |
Draw a tree where each node is a full array state. Every edge is a swap. N! states total. |
Cycle Decomposition (Permutation Graph). |
Directed Cycle Loops. |
Map each element's current index to its target index in the sorted-by-digit-sum version. Total swaps = Total Elements - Number of Cycles. |
Draw dots for indices. Draw an arrow from where a number is to where it should be. Count the closed loops. |
$O(N \log N)$ Sorting + $O(N)$ Scan. |
Draw an arrow for sorting. Then draw a linear array with loops connecting indices. $O(N \log N)$. |
Permutation Heap: Draw millions of array copies representing possible swap states. |
Visited Array: Draw a single 1D boolean array (size N) to mark elements as you traverse cycles. |
| 3552 |
Grid Teleportation Traversal (Med) |
Simple BFS/DFS visiting every neighbor and checking all possible teleportation coordinates at every step. |
Explosive Grid Branching. |
Draw a grid. From one cell, draw arrows to 4 neighbors PLUS arrows to every other valid teleport cell. |
Multi-Source BFS / Dijkstra with Coordinate Mapping. |
Layered Wavefront Expansion. |
Group cells by teleportation properties. Use a queue to process distance layers. Teleports act as "shortcuts" to distant clusters. |
Draw a grid. Color the start cell. Draw "lightning bolt" lines for teleports and regular arrows for steps. Label each cell with min distance. |
$O(N \cdot M)$ or $O(V + E)$. |
Draw a graph where nodes are cells. Total edges = adjacent + teleport rules. Draw a single BFS wavefront. |
Massive Path History: Draw a list of every single path sequence ever explored. |
Distance Grid: Draw a single 2D array of integers (size N x M) holding only the minimum distance to each cell. |
| 3553 |
Min Weighted Subgraph With Required Paths II (Hard) |
Generate all possible subgraphs and check if the three specific nodes (s1, s2, dest) are connected. |
Combinatorial Edge Selection. |
Draw a graph. Draw every possible combination of 2^E subgraphs. Check connectivity for each. |
Dijkstra's x3 (Steiner Tree on 3 Nodes variant). |
Triple Source Intersection. |
Run Dijkstra from S1, S2, and Dest (on reversed graph). The optimal meeting point 'M' is where `Dist(S1,M) + Dist(S2,M) + Dist(M,Dest)` is minimum. |
Draw three "ripples" (contour lines) starting from S1, S2, and Dest. Mark the point where the sum of distances to all three is smallest. |
$O(E \log V)$. |
Draw three Dijkstra runs sequentially. Then a linear scan over all nodes to find the minimum sum. |
Multiple Adjacency Matrix Copies: Draw several full graph matrices in memory. |
Three Distance Arrays: Draw three 1D arrays (size V) storing min-distances from each source. |
| 3554 |
Find Category Recommendation Pairs (Hard) |
Double loop through all users and categories to find shared interests and calculate correlation scores. |
User-Category Matrix Scan. |
Draw a Users x Categories table. For every pair of categories, scan all users to count commonalities. $O(C^2 \cdot U)$. |
Inverted Index + Bitsets / Matrix Multiplication. |
Bitwise Overlap (AND operation). |
Represent each category as a bitmask where the i-th bit is 1 if User i likes it. The common count for Cat A and B is `popcount(BitmaskA & BitmaskB)`. |
Draw two long binary strings (0101...). Draw a vertical line matching the 1s. Count how many times both strings have a 1 at the same position. |
$O(C^2 \cdot U / \text{WordSize})$. |
Draw a grid of category pairs. Highlight a single bitwise AND operation (very fast) for each cell. |
Nested Maps/Lists: Draw hundreds of user-interest objects scattered across heap memory. |
Compressed Bitsets: Draw a small number of long, dense bitset blocks (64 bits per word). |
| 3555 |
Smallest Subarray to Sort in Every Sliding Window (Med) |
For every window of size K, find the smallest unsorted range by checking all inner sub-ranges. |
Window-by-Window Sorting Checks. |
Draw a sliding window. For each position, redraw the window and highlight the messy part. $O(N \cdot K)$. |
Monotonic Deque / Two Pointers + Sliding Window Minimum. |
Sliding Bound Trackers (Left/Right Mismatches). |
Track the leftmost and rightmost elements that violate the "sorted" property within the window as it slides. Use a deque to find local mins/maxes. |
Draw a window moving right. Use a red pen to mark the first "dip" (arr[i] < arr[i-1]) and the last "peak" within the current window. |
$O(N)$. |
Draw a timeline. Below it, draw a window moving. Show only $O(1)$ work (deque updates) per shift. |
Sub-window Slices: Draw N copies of small arrays, each of size K, taking up massive total space. |
Monotonic Deque: Draw a small, fixed-size queue (size K) that only stores indices of increasing/decreasing values. |
| 3556 |
Sum of Largest Prime Substrings (Med) |
Extract all possible substrings, convert to numbers, check primality for each, and keep max. |
Substring Explosion + Primality Testing. |
Draw an N x N matrix of substrings. For each cell, draw a "Primality Machine" doing $O(√\text{Value})$ work. |
Sieve of Eratosthenes + Rolling Hash / DP. |
Prime Filtering Mask. |
Precompute primes up to max value. For the string, use DP: `DP[i]` is max sum of prime substrings ending at `i`. |
Draw a number line. Below it, draw a "Sieve" grid with crossed-out composites. Use arrows to jump between prime-substring indices. |
$O(N^2)$ or $O(N \\text{cdot MaxDigitLength})$. |
Draw an array of length N. From each index, draw a lookback arrow of max length 10 (max integer digits). |
Massive Substring Set: Draw thousands of string objects being converted to BigInts in memory. |
Sieve Boolean Array: Draw a single 1D boolean array (size MaxValue) for instant prime lookups. |
| 3557 |
Find Max Number of Non Intersecting Substrings (Med) |
Generate every valid substring and use recursion to try every combination of non-overlapping sets. |
Recursive Subset Tree. |
Draw a tree. Each node splits into "Include this substring" or "Skip". Branching factor = number of overlaps. |
Greedy Interval Scheduling (Earliest Deadline First). |
Overlapping Gantt Chart. |
Identify boundaries for each character. Treat these as intervals. Sort intervals by their end times and pick the first available. |
Draw horizontal bars representing substrings. Place a vertical line at the end of the first bar. Skip all bars that touch the line. Pick next. |
$O(N)$ Boundary Scan + $O(N \log N)$ Sorting. |
Draw a sorted list of intervals. Draw a single pass scanning them left to right. |
Recursion Stack: Draw deep stack frames holding lists of "currently picked" substrings. |
Boundary Arrays: Draw three arrays of size 26 (First occurrence, Last occurrence, Is valid). |
| 3558 |
Number of Ways to Assign Edge Weights I (Med) |
Backtracking DFS to try every possible weight (1 to K) for every edge and check path constraints. |
Weight Permutation Tree. |
Draw a graph. Each edge has a slot `[ ]`. Branch for every possible number you can put in the slot. K^E total. |
Dynamic Programming on Trees (Tree DP). |
Subtree State Accumulation. |
At each node, store the number of ways to weight its subtree given the weight of the edge to its parent. |
Draw a tree. At each node, write a small table of "Ways to sum to X". Pass values upward from leaves to root. |
$O(N \cdot K)$. |
Draw a tree. At each of the N nodes, show a loop of size K combining child results. |
Exhaustive Permutation Lists: Draw huge arrays storing every single valid weight configuration. |
2D DP Table: Draw an N x K grid where `DP[node][current_sum]` stores the count. |
| 3559 |
Number of Ways to Assign Edge Weights II (Hard) |
$O(N \cdot K)$ DP (as in 3558), which fails when K is very large. |
Dense DP Grid (Huge Columns). |
Draw a DP grid with 10^5 columns. Shading this grid takes too much time/memory. |
DP + Generating Functions / Polynomial Interpolation or NTT. |
Coefficient Extraction from Series. |
Represent weight choices as polynomials. Multiplying polynomials (using NTT) represents combining ways across edges. |
Draw two polynomials being merged into one large polynomial. Use a "Fast Fourier" box to speed up the multiplication. |
$O(N \log N \log K)$ or $O(N \log^2 N)$. |
Draw a recursion tree (Divide & Conquer) where at each level you perform an NTT (N log N). |
Massive DP Tables: Draw the RAM being choked by a 2D array of size N x 100,000. |
Coefficient Vectors: Draw small, dense arrays of coefficients being transformed in-place via NTT. |
| 3560 |
Find Minimum Log Transportation Cost (Easy) |
Simulate all possible routes and transport methods for logs, calculating cost for each. |
Route Permutation Map. |
Draw a map with multiple paths. Tally the cost for every single path individually. $O(N!)$. |
Greedy / Single-Source Shortest Path (Dijkstra) or Prefix Min. |
Cheapest Lead-in Path. |
Sort transport points. At each point, the min cost is the cost to reach it plus the local log-handling fee. |
Draw a sequence of points. Write the min-cost-to-reach below each point. For the next point, just pick `min(previous_costs) + current`. |
$O(N \log N)$ Sorting. |
Draw an array. Draw a single arrow passing through it, maintaining one `min_cost` variable. |
Path Logs: Draw lists recording every intermediate movement and cost ever calculated. |
Single State Variable: Draw one integer box `min_so_far` being updated. |
| 3561 |
Resulting String After Adjacent Removals (Med) |
Repeatedly scan the string and remove any adjacent identical characters until no more removals are possible. |
Iterative String Shrinking. |
Draw a string. Circle 'aa', redraw string without 'aa'. Repeat. $O(N^2)$ total scans. |
Stack-based Single Pass. |
Character Plate Stacking. |
Iterate through characters. If current char matches top of stack, pop stack. Else, push char. |
Draw a vertical bin. For "abba", push 'a', push 'b', 'b' matches top so pop 'b', 'a' matches top so pop 'a'. |
Linear Scan. |
Draw a single straight arrow passing over the string. $O(N)$. |
String Buffer Reallocation: Draw multiple copies of slightly shorter strings being created in memory. |
Stack Structure: Draw a single 1D array/list acting as a stack of characters. |
| 3562 |
Max Profit from Trading Stocks with Discounts (Hard) |
Try every possible combination of buy/sell days and every possible way to apply limited discounts. |
Exponential Decision Tree. |
Draw a tree where each node splits into "Buy", "Sell", "Apply Discount", or "Do Nothing". 2^N branches. |
3D Dynamic Programming. |
State Transition Grid (Days x Inventory x Discounts). |
Define `DP[i][j][k]` as max profit on day `i` with `j` stocks and `k` discounts left. Transition based on current day's price. |
Draw a grid where rows are days and columns represent (stocks held, discounts left). Draw arrows showing profit flow. |
$O(N \cdot S \cdot D)$. |
Draw a 3D block representing the state space. Each cell takes $O(1)$ to fill. |
Deep Recursion: Draw a massive stack of function calls holding intermediate profit totals. |
Rolling DP Matrix: Draw two 2D layers (today vs yesterday) to save space. |
| 3563 |
Lexicographically Smallest String After Adjacent Removals (Hard) |
Generate all possible removal sequences and compare the final strings to find the smallest one. |
Permutation Ranking. |
Draw a tree of strings. Each branch is a different removal choice. N! leaves at the bottom. |
Greedy + Monotonic Stack + Frequency Counting. |
Monotonic "Cleanup" Scanner. |
Keep a stack of characters. If current char is smaller than stack top and stack top can be removed later, pop. |
Draw a horizontal line. Place characters. If a 'smaller' char arrives, erase the 'larger' ones to its left if they appear again later. |
$O(N)$. |
Draw a single arrow with a "Backtrack/Erase" condition. Every char is pushed/popped at most once. |
Massive String List: Draw memory blocks for every possible resulting string. |
Fixed Size Array: Draw one 1D array for the result and one size-26 array for character counts. |
| 3564 |
Seasonal Sales Analysis (Med) |
Iterate through every sale record, group by season, and calculate averages using nested loops or heavy sorting. |
Iterative Grouping. |
Draw sales logs. For each season (Spring, Summer, etc.), scan the entire log and tally. $O(N \cdot S)$. |
Hash Map Aggregation / SQL-style GroupBy. |
Data Bucketing. |
Use a hash map where keys are seasons. For each record, add value to `map[season].sum` and `map[season].count`. |
Draw 4 large buckets labeled by season. Toss each sale record into its bucket. Divide sum by count at the end. |
$O(N)$. |
Draw a single pass through the sales data records. $O(1)$ bucket update per record. |
Sorted Log Duplicates: Draw multiple sorted versions of the raw sales data. |
Small Hash Table: Draw a map with exactly 4 entries, each holding two integers (Sum, Count). |
| 3565 |
Sequential Grid Path Cover (Med) |
Try every possible path starting from (0,0) that covers every cell in sequence, backtracking on dead ends. |
Path Exploration Tree. |
Draw a grid. From (0,0), draw every possible winding path. Count how many reach the end covering all nodes. |
BFS / Dijkstra on State Space (Grid + Bitmask). |
Breadth-First Front. |
The state is (Current Cell, Mask of Visited Cells). Use BFS to find the shortest sequence that visits all cells. |
Draw a grid. Shade cells as they are visited. Show multiple "ghost" paths expanding until one covers the whole grid. |
$O(N \cdot M \cdot 2^(N\cdot M)$). |
Draw a tree of depth N*M. Branching is limited to 4 neighbors. State compression limits re-work. |
Path History Stacks: Draw endless lists of coordinate pairs for every path being explored. |
Bitmask Visited Array: Draw a 1D array of size 2^(N*M) storing boolean "visited" states. |
| 3566 |
Partition Array into Two Equal Product Subsets (Med) |
Generate all 2^N subsets, calculate the product for each, and check if it equals the product of the remaining elements. |
Exponential Subset Tree. |
Draw a binary tree of height N. Each path represents a subset. Calculate total product at each of the 2^N leaf nodes. |
Dynamic Programming (Knapsack on Log-Sums) / Prime Factorization. |
Logarithmic Scaling. |
Since products grow too fast, convert to sums using log(a * b) = log(a) + log(b). Solve as an Equal Sum Partition problem. |
Draw a table of prime factor counts for each number. The goal is to split the counts of each prime (2s, 3s, 5s) exactly in half. |
$O(N \\text{cdot TargetSum})$. |
Draw a 2D grid. Rows = Array elements, Columns = Possible log-sums. Shade cells from left to right. |
Subset Product Lists: Draw massive lists of extremely large integers (potentially causing overflow) in memory. |
1D Boolean DP Array: Draw a single array of size (TotalLogSum/2) tracking reachable sums. |
| 3567 |
Minimum Absolute Difference in Sliding Submatrix (Med) |
For every possible K x K submatrix, iterate through all pairs of elements to find the minimum absolute difference. |
Nested Window-Pair Scan. |
Draw a grid. Move a square window. For each position, draw arrows connecting every pair of cells inside the window. $O(N \cdot M \cdot K^4)$. |
Sliding Window + 2D Data Structure (Segment Tree/Fenwick Tree) or Sorted Set. |
Rolling sorted window. |
Slide the window. As it moves, remove the left-column elements and add the new right-column elements into a sorted container (BST). Find the closest neighbors. |
Draw the submatrix. Use a side-list (sorted). For a new element X, draw arrows to the elements immediately above and below X in the sorted list. |
$O(N \cdot M \cdot K \log K)$. |
Draw the grid scan. For each step, show K insertions/deletions into a tree of size K^2. |
Matrix Slices: Draw thousands of K x K integer arrays being created during simulation. |
Sorted Container (Treap/AVL): Draw a single binary search tree that updates its nodes as the window slides. |
| 3568 |
Minimum Moves to Clean the Classroom (Med) |
Simulate every possible movement sequence for the cleaner, checking the "clean" status of every cell at each step. |
Path Permutation Search. |
Draw the classroom. From the starting point, draw every possible path. Use a counter to track moves. Stop when all cells are clean. |
BFS / Dijkstra on Grid State. |
Concentric Wavefront. |
Treat the cleaner's position as a node in a graph. BFS finds the shortest path. If cleaning is sequential, use a Greedy/Line-Sweep approach. |
Draw the grid. Shade the "dirty" cells. Draw a snake-like line passing through all shaded cells, labeling the number of steps. |
$O(N \cdot M)$. |
Draw a single straight arrow passing through every cell of the grid once. |
Call Stack of States: Draw memory blocks for every "visited" coordinate and the current grid status. |
Distance Grid: Draw a single 2D array of integers tracking the cleaner's min steps to reach each cell. |
| 3569 |
Maximize Count of Distinct Primes After Split (Hard) |
Try every possible split point in the array. For each split, find all prime factors for both halves and count the total distinct ones. |
Full Sub-array Factorization. |
Draw the array. Draw a vertical line at every gap. For each gap, redraw the left/right parts and list all their prime factors. $O(N^2 \cdot √V)$. |
Sieve of Eratosthenes + Prefix Prime Frequencies. |
Prime Contribution Tracker. |
Precompute prime factors for each number. Build a prefix sum array for the counts of each distinct prime. Calculate "split" counts in $O(1)$. |
Draw a table where columns are primes and rows are array indices. Fill with prefix counts. At any split, subtract Pref[i] from Pref[N]. |
$O(N \\text{cdot omega}(V)$) where omega is max prime factors. |
Draw a single scan of the array. Highlight the constant-time difference calculation at each split point. |
Prime Factor Sets: Draw memory-intensive sets for every possible sub-array slice. |
Prefix Count Matrix: Draw a compact 2D array (Size N x UniquePrimes) storing frequency trends. |
| 3570 |
Find Books with No Available Copies (Easy) |
Double loop: for every book in the library, scan the entire "checked-out" list to see if all copies are gone. |
Linear Search per Item. |
Draw a list of Books. Draw a list of Loans. For each Book, draw an arrow checking every entry in the Loans list. $O(B \cdot L)$. |
Hash Map (Inventory Counter). |
Checklist Tally. |
Build a map of `TotalCopies`. Scan the `Loans` list and subtract. Any book with `RemainingCount == 0` is the answer. |
Draw a two-column table (BookID, Copies). As you read the loan log, cross out a copy. Circle rows that reach zero. |
$O(B + L)$. |
Draw one arrow scanning Books, then one arrow scanning Loans. $O(1)$ map access for each. |
Multiple Filtered Lists: Draw newly created lists of "Available" vs "Unavailable" books repeatedly. |
Tally Map: Draw a single small table mapping Book IDs to their current integer count. |
| 3571 |
Find the Shortest Superstring II (Easy) |
Try every permutation of strings and concatenate them with maximum possible overlap. |
Factorial Orderings. |
Draw N strings. Branch into every possible order (N!). For each order, calculate the overlap between adjacent strings. |
Greedy Overlap Selection. |
Overlap Merge-Chain. |
Pick two strings with the maximum overlap, merge them into one, and repeat until only one string remains. |
Draw strings as rectangles. Shade the overlapping parts. Draw an arrow showing two rectangles "snapping" together into one. |
$O(N^3 \cdot L^2)$. |
Draw an N x N matrix of overlaps. Highlight the maximum value being picked and the matrix being reduced. |
Permutation Storage: Draw millions of string orderings being generated in RAM. |
Distance Matrix: Draw a single 2D array storing the overlap lengths between every pair of strings. |
| 3572 |
Maximize Y‑Sum by Picking a Triplet of Distinct X‑Values (Med) |
Generate all combinations of three distinct X-values, sum their corresponding Y-values, and track the maximum. |
N^3 Combinatorial Grid. |
Draw three nested loops. For every triplet (x_i, x_j, x_k), check if they are distinct and sum y_i, y_j, y_k. |
Sorting + Greedy / Two-Pass Max Search. |
Top-K Filtering. |
For each distinct X, keep only the highest Y-value. Sort these top Y-values and simply pick the top three. |
Draw a table of (X, Y) pairs. Group by X. Highlight the "champion" Y in each group. Sort the champions and circle the top three. |
$O(N \log N)$. |
Draw an arrow sorting the N points, then a single pass through the top-three list. |
Full Triplet List: Draw a massive array storing every possible triplet sum calculated. |
Frequency Map + Top-3 Array: Draw a map (X -> MaxY) and three integer variables representing the leaderboard. |
| 3573 |
Best Time to Buy and Sell Stock V (Med) |
Try every possible pair of buy and sell days for multiple transactions using deep recursion. |
Explosive Transaction Tree. |
Draw a decision tree: "Buy", "Sell", "Wait". Each level is a day. For N days, paths grow exponentially. |
One-Pass Greedy (Peak-Valley). |
Ascending Slope Accumulation. |
Iterate through prices. Whenever today's price is higher than yesterday's, add the difference to the total profit. |
Draw a line graph of prices. Draw vertical arrows between every point where the line goes "up". Sum the lengths of these arrows. |
$O(N)$. |
Draw a single straight arrow passing over the prices. $O(1)$ math per step. |
Recursion Stack: Draw deep stack frames tracking every transaction state and balance. |
Constant State: Draw just one integer variable `total_profit` updating as you sweep. |
| 3574 |
Maximize Subarray GCD Score (Hard) |
Check every possible subarray, compute its GCD, and multiply by its length to find the max score. |
N^3 Nested Subarray Scans. |
Draw an N x N matrix of subarrays. For each, draw a "GCD Machine" looping through its elements. $O(N^3)$. |
Sparse Table + Decreasing GCD Property. |
GCD Segment Compression. |
The number of unique GCDs starting at any index is logarithmic (log MaxVal). Store these "active" GCDs and their ranges in a list. |
Draw an array. Below it, draw brackets showing ranges where the GCD remains constant. When the GCD changes, "split" the bracket. |
$O(N \log N \cdot \\text{log MaxVal})$. |
Draw a sparse table structure (logarithmic layers) being queried for each index. |
Full GCD Cache: Draw a massive 2D matrix storing precomputed GCDs for all pairs. |
Sparse Table / Active GCD List: Draw a compact array of logarithmic depth and a small list of "current" GCD values. |
| 3575 |
Maximum Good Subtree Score (Hard) |
Iteratively check every possible subtree by removing edges, and calculate the "goodness" score for each. |
Edge-Removal Permutations. |
Draw a tree. Try removing edge 1, then edge 2... For each resulting forest, calculate all subtree scores. $O(2^E \cdot N)$. |
Tree Dynamic Programming (Bottom-Up). |
Subtree Contribution Waves. |
Define DP[u] as the max score of a subtree rooted at u. Combine child scores into the parent based on the "goodness" criteria. |
Draw a tree. Start at the leaves. Pass scores up to parents. At each node, draw a "Decision Box" choosing the best child branches to keep. |
$O(N)$. |
Draw a single DFS traversal path (curved arrow) through the tree, visiting each node exactly once. |
Forest Snapshots: Draw dozens of whole-tree copies representing different edge-removal states. |
1D DP Array: Draw a single array of size N storing the calculated score for each node's subtree. |
| 3576 |
Transform Array to All Equal Elements (Med) |
Try every value currently in the array as the "target," calculating total operations for each. |
Iterative Target Testing. |
Draw an array. Pick element 1, draw arrows from every other element to it. Pick element 2, repeat. $O(N^2)$. |
Median-based Greedy. |
Geometric Center Minimization. |
Sort the array. The value that minimizes the sum of absolute differences is the median. Operations = sum |x_i - median|. |
Draw dots on a number line. Draw a central line (median). Draw arcs from every dot to that central line. |
$O(N \log N)$ or $O(N)$ with QuickSelect. |
Draw an arrow for the sort step, then a single pass summing differences. |
Operation Logs: Draw a list of every subtraction/addition step taken for every possible target. |
In-Place Sort: Draw the array being rearranged, using only logarithmic stack space. |
| 3577 |
Count the Number of Computer Unlocking Permutations (Med) |
Generate all N! permutations of keys and check if each fulfills the "unlocking" sequence rules. |
Factorial Permutation Tree. |
Draw a tree where each node is a key. Each path to a leaf is a permutation. Count valid paths. |
Dynamic Programming with Bitmask. |
State Transition DAG. |
State = `(current_key, mask_of_used_keys)`. Transition to an unused key only if the "intermediate" key on the path is already used. |
Draw circles for keys. Shade keys in a "mask" (e.g., 1011). Draw a valid arrow to an unshaded key. |
$O(N^2 \cdot 2^N)$. |
Draw a grid of size N x 2^N. Shade cells as they are filled based on previous column states. |
Exhaustive Path Lists: Draw massive lists of coordinate sequences in memory. |
Memoization Table: Draw a 2D array of size N x 2^N storing integer counts. |
| 3578 |
Count Partitions With Max-Min Difference at Most K (Med) |
Recursive partitioning: try splitting at every index and check constraints on every resulting sub-segment. |
Exponential Split Tree. |
Draw an array. Branch into "split here" or "don't split" at every gap. Check Max-Min for every segment. |
DP + Monotonic Deque / Sliding Window. |
Constraint-Based Window Sliding. |
Define DP[i] as ways to partition up to i. Use two deques to find the range [L, i] where Max - Min <= K. DP[i] = sum DP[j] for j in [L, i-1]. |
Draw a window moving right. Use a ruler to mark the furthest left point where the segment is still "good." Update DP sum. |
$O(N)$. |
Draw a single arrow with two sliding "boundary" lines following it. $O(1)$ deque work per step. |
Call Stack: Draw deep recursion frames for every possible split combination. |
Rolling Prefix Sum DP: Draw one DP array and one Prefix-Sum-of-DP array for $O(1)$ range sums. |
| 3579 |
Minimum Steps to Convert String with Operations (Hard) |
BFS to explore all possible string states reachable via the given operations until the target is found. |
Explosive State Graph. |
Draw the initial string. Draw arrows for every possible operation (swap, delete, etc.). Count levels to reach Target. |
Dijkstra / BFS + A* Search or Dynamic Programming. |
Shortest Path in State Space. |
Map strings to nodes. Use a priority queue to explore the most "promising" string transformations first based on a heuristic. |
Draw a "Cloud" of strings. Highlight the shortest path of arrows connecting the Start string to the Target string. |
$O(V + E)$ where V is the number of reachable string states. |
Draw a wavefront expanding from the source node, stopping immediately at the target. |
Visited Set: Draw a massive hash set storing every string variation ever encountered. |
Queue + Map: Draw a small queue for current frontier and a map for min-steps-to-string. |
| 3580 |
Find Consistently Improving Employees (Med) |
For every employee, sort their performance reviews by date and check if the scores are strictly increasing. |
Per-Employee Linear Scan. |
Draw a list of Employees. For each, draw a graph of their scores. Manually check if the line always goes up. $O(E \cdot R \log R)$. |
Hash Map Grouping + Single Pass Validation. |
Slope Direction Check. |
Group data by Employee ID. Sort reviews by timestamp. Iterate once: if `Score[i] <= Score[i-1]`, mark as "Not Improving." |
Draw buckets for each employee. Put review pairs (Date, Score) inside. Draw a green checkmark only if every score is > the previous. |
$O(N \log N)$ where N is total reviews. |
Draw a single sort arrow for the entire dataset, then a linear sweep. |
Grouped Sub-lists: Draw multiple newly created list objects for every employee. |
In-Place Grouped Scan: Draw the original table sorted by (ID, Date), scanning it in one pass. |
| 3581 |
Count Odd Letters from Number (Easy) |
Convert the number to a string, then loop through each character and count the frequency of odd digits. |
String Conversion Scan. |
Draw a number. Draw a box representing the string version. Draw an arrow hopping through each digit. $O(\log_10 N)$. |
Mathematical Digit Extraction. |
Modulo & Division Loop. |
Use `n % 10` to get the last digit and check if it's odd. Use `n / 10` to strip it. Repeat until `n` is 0. |
Write the number. Circle the last digit. Check parity. Scratch it out and write the remaining number below. Repeat. |
$O(\log_10 N)$. |
Draw a shrinking number line. Each step removes one digit from the right. Constant time per digit. |
String Heap Allocation: Draw a string object in memory taking up space proportional to the number of digits. |
Register Variables: Draw two small integer boxes (`digit`, `count`) that reuse the same memory. |
| 3582 |
Generate Tag for Video Caption (Easy) |
Manually search through the caption for specific keywords using nested loops for string matching. |
Nested String Search. |
Draw the caption. Draw a list of keywords. For each keyword, draw an arrow sliding it across the entire caption. $O(C \cdot K)$. |
Hash Set Lookup / Single Pass Tokenization. |
Keyword Filtering Bin. |
Split the caption by spaces. Put all words into a frequency map. If a word matches a predefined "tag" list, include it. |
Draw the sentence. Draw a circle around "important" words. Transfer the circled words into a sorted "Tags" box. |
$O(C + K)$. |
Draw an arrow scanning the caption once. Draw another arrow scanning the tags. $O(N)$ linear time. |
Multiple Substring Objects: Draw many small string slices being created during manual indexing. |
Hash Set & Result List: Draw one Set of "Target Keywords" and one List for the generated tags. |
| 3583 |
Count Special Triplets (Med) |
Three nested loops to iterate through all possible indices (i, j, k) and check the special condition. |
3D Loop Cube. |
Draw a cube of dimension N x N x N. Shade the valid triangular volume where i < j < k. $O(N^3)$. |
Prefix Sums / Frequency Mapping. |
Middle-Element Pivot. |
Fix the middle element j. Count valid elements to its left and right using precomputed frequency maps or prefix sums. Total = LeftCount * RightCount. |
Draw an array. Point to element j. Draw a bracket to the left (elements < arr[j]) and a bracket to the right. Write their counts above. |
$O(N^2)$ or $O(N)$ depending on condition. |
Draw a 1D array with a sliding j pointer. Show constant-time prefix lookups at each step. |
Nested Iterator Pointers: Draw three pointers constantly scanning the same array. |
Prefix/Frequency Arrays: Draw two 1D arrays storing running counts for left and right conditions. |
| 3584 |
Max Product of First and Last Elements of a Subsequence (Med) |
Generate every possible subsequence, find their first and last elements, and calculate their products. |
Power Set Permutations. |
Draw an array. Draw a binary tree of 2^N leaves. Each leaf is a subsequence. Note the start/end and product. |
Two-Pointer Greedy / Sorting. |
Extreme Pairs Convergence. |
Sort the array. The maximum product will come from either the two largest elements or the two smallest (most negative). |
Draw a sorted line. Draw an arc between the two largest numbers and an arc between the two smallest. Calculate both; pick max. |
$O(N \log N)$. |
Draw an arrow representing the sort. Highlight the two $O(1)$ product calculations at the ends of the sorted array. |
Subsequence Heap: Draw massive lists of subsequence objects in RAM before performing the math. |
Two-Pointer In-Place: Draw a sorted array with two fixed pointers at the 0th and last index. |
| 3585 |
Find Weighted Median Node in Tree (Hard) |
For every node, calculate the sum of weighted distances to all other nodes and find the node with the minimum sum. |
Repeated Tree Traversal. |
Draw a tree. For node 1, run BFS to all other nodes. Reset. For node 2, repeat. $O(N^2)$. |
Tree Centroid Decomposition / Subtree Weight Sums. |
Weight Balance Gravity. |
Total weight W is the sum of all node weights. The weighted median is the node where every subtree has weight <= W/2. |
Draw a tree with numbers in nodes. Calculate the total sum. Start at the root. Move to the child whose subtree weight is > W/2. Stop when no such child exists. |
$O(N)$. |
Draw a single DFS traversal (calculating weights) and a single downward path search. $O(N)$. |
Distance Matrices: Draw an N x N matrix storing weights between every possible pair of nodes. |
1D Weight Array: Draw a single array storing the total weight of each node's subtree. |
| 3586 |
Find COVID Recovery Patients (Med) |
Scan all patient records for 'Positive' status, then for each, scan subsequent dates for 'Negative' results. |
Nested Record Scan. |
Draw a list of patients. For each patient, draw a secondary loop scanning their specific medical history timeline. $O(P \cdot H)$. |
Hash Map Grouping + Sort & Sweep. |
Patient Timeline Filtering. |
Group records by Patient ID. Sort each group by date. Identify the first 'Positive' and search for two consecutive 'Negative' tests after it. |
Draw a folder for each patient. Put dated sticky notes inside. Flip through chronologically, marking the recovery window. |
$O(N \log N)$ where N is total records. |
Draw a single sorted list of all records. Highlight the linear pass checking the "Positive -> Negative" transition. |
Redundant Sorting: Draw multiple copies of the entire database sorted in different ways. |
Map of Lists: Draw a hash map where keys are IDs and values are small, sorted chronological arrays. |
| 3587 |
Minimum Adjacent Swaps to Alternate Parity (Med) |
Generate all permutations of the array, keep those that alternate parity, and find the minimum swap distance. |
Factorial Swap Tree. |
Draw a tree where each branch is an adjacent swap. Count levels to reach any valid alternating state. $O(N!)$. |
Greedy Positioning (Two-Target Comparison). |
Parity Slot Mapping. |
There are two targets: [Even, Odd...] or [Odd, Even...]. Calculate the total swap distance to fit the elements into these fixed slots. |
Draw two blank arrays with 'E' and 'O' labels. Draw arrows from original Even elements to the 'E' slots. Count the "jump" lengths. |
$O(N)$. |
Draw two linear arrays. Highlight a single pass through the original array to collect Even/Odd indices. |
Full Permutation Heap: Draw millions of array states being stored during BFS search. |
Index Lists: Draw two small 1D arrays storing the original positions of Even and Odd numbers. |
| 3588 |
Find Maximum Area of a Triangle (Med) |
Three nested loops to try every combination of three points (P_1, P_2, P_3) and calculate the area. |
$O(N^3)$ Triple Loop. |
Draw N points. Draw every possible triangle connecting them. Calculate Area = 0.5 * |x_1(y_2 - y_3) + ...|. |
Convex Hull + Rotating Calipers. |
Bounding Polygon Expansion. |
The max area triangle always has vertices on the convex hull. Use rotating calipers to find the max area in near-linear time. |
Draw a "rubber band" around the points (Convex Hull). Pick one base edge. Move the third point until area stops increasing. Rotate the base. |
$O(N \log N)$ or $O(N)$ on Hull. |
Draw a sorted hull. Show the three pointers moving in one direction around the perimeter. |
Triangle List: Draw a list of every calculated area for every possible triplet of points. |
Hull Points Array: Draw a small array of only the outer boundary points of the set. |
| 3589 |
Count Prime-Gap Balanced Subarrays (Med) |
For every subarray, calculate the gaps between adjacent primes within it and check if they are "balanced." |
Subarray Iteration + Gap Check. |
Draw an N x N matrix. For each cell, draw a secondary loop scanning the subarray for primes and calculating diffs. $O(N^3)$. |
Sieve + Sliding Window / Prefix Sums. |
Gap Sequence Stream. |
Precompute primes. Transform the array into a sequence of "gaps" between primes. A "balanced" subarray corresponds to a range in the gap sequence. |
Draw the array. Below, write the gaps: 2, 4, 2... Use a sliding window to find ranges where the sum/count of gaps meets the criteria. |
$O(N)$. |
Draw a sequence of gap values. Draw a single straight arrow (sliding window) moving through the gap list. |
Nested Prime Checks: Draw the CPU repeatedly checking if a number is prime for every subarray. |
Prefix Gap Array: Draw a 1D array of gaps and a prefix sum array to instantly calculate gap totals. |
| 3590 |
Kth Smallest Path XOR Sum (Hard) |
Use DFS to find all possible paths from (0,0) to (N,M), calculate the XOR sum for each, sort them, and pick Kth. |
Path Permutation Explosion. |
Draw a grid. Branch into "Right" or "Down" at every cell. Count paths (up to 2^N+M). Sort the huge result list. |
Meet-in-the-Middle + Binary Search / Trie. |
Midpoint Collision. |
Calculate all path XORs from (0,0) to the diagonal, and from (N,M) back to the diagonal. Use a Trie or Binary Search to count pairs that sum to X. |
Draw a grid. Draw a diagonal line. Shade paths from Top-Left to Diagonal, and Bottom-Right to Diagonal. Compare at the meeting line. |
$O(2^(N+M)$/2 * log(MaxXOR)). |
Draw two smaller exponential trees (depth (N+M)/2) and a binary search step over the Trie. |
Full Path Result List: Draw a massive list of path XORs taking up gigabytes of memory. |
Mid-Diagonal Maps: Draw two hash maps/Tries storing XOR counts for only the half-paths. |
| 3591 |
Check if Any Element Has Prime Frequency (Easy) |
Count frequencies of all elements using nested loops, then check primality for each count using a standard loop. |
Nested Search & Test. |
Draw an array. For each unique element, draw a scan of the whole array to count, then draw a "Primality Machine" loop. $O(N^2)$. |
Hash Map + Sieve of Eratosthenes. |
Frequency Binning + Lookup. |
Scan the array once, dropping elements into a Map. Then, check the counts against a precomputed Boolean prime array (Sieve). |
Draw a tally table. Write counts. Check these counts against a "Prime List" (2, 3, 5, 7...). Circle any match. |
$O(N)$. |
Draw a single straight arrow (one pass for counts) followed by a constant-time check. $O(N)$. |
Manual Count Lists: Draw multiple copies of the array being filtered to find specific elements. |
Frequency Map: Draw a single table mapping unique integers to their count values. |
| 3592 |
Inverse Coin Change (Med) |
Try every possible combination of coin values and see which set produces the target number of ways for value V. |
Recursive Choice Tree. |
Draw a tree where each node is a potential set of coins. Test standard Coin Change DP for each. $O(2^K \cdot V)$. |
Dynamic Programming (Generating Functions Reconstruction). |
Coefficient Extraction. |
Treat the number of ways as coefficients of a polynomial. Use the relationship between DP[i] and DP[i-coin] to "subtract" the contribution of a coin and find the base set. |
Draw a DP array. Start from the first index where DP[i] > 0. That's your first coin. "Reverse-subtract" its combinations from the rest of the array. |
$O(N \cdot V)$. |
Draw a DP array of size V. Show a single pass "cleaning up" the array for each discovered coin. |
Massive Set Permutations: Draw thousands of candidate coin-sets being simulated in RAM. |
In-Place DP Array: Draw a single 1D array representing the "Ways to make Sum" being updated/reduced. |
| 3593 |
Minimum Increments to Equalize Leaf Paths (Med) |
Try every possible increment value for every edge in the tree to make all root-to-leaf paths equal. |
Exhaustive Path Testing. |
Draw a tree. Branch for every possible "+1" on every edge. Check all path sums. Stop at the minimum total. $O(\text{Val}^E)$. |
Bottom-Up Tree DP (Post-order Traversal). |
Level Balancing. |
At each node, find the max path sum from its children. Increment the shorter branches to match the maximum. Propagate the sum upward. |
Draw a tree. Start at the leaves. Write the max path sum at each parent. Add the "diff" to the edges to make them match. |
$O(N)$. |
Draw a single DFS traversal (bottom-up arrow). Each node is visited exactly once. $O(N)$. |
Full Path Permutation Map: Draw lists of every path sum for every possible increment combination. |
Recursion Stack: Draw a single call stack of depth H (height of tree). |
| 3594 |
Minimum Time to Transport All Individuals (Hard) |
Simulate every possible transport sequence and timing for every individual from Start to End. |
Factorial Schedule Search. |
Draw a list of people. Branch for "Person A goes now," "Person B goes now," etc. Calculate total time for each. $O(N!)$. |
Binary Search on Answer + Greedy/Flow. |
Threshold Feasibility Check. |
Guess a total time T. Check if N individuals can be transported within T given capacity constraints using a greedy scan or interval matching. |
Draw a timeline. For a fixed T, draw "capacity boxes." Try fitting individuals' travel intervals into these boxes greedily. |
$O(N \log N \cdot \log(\text{MaxTime})$). |
Draw a binary search tree. Inside each node, draw an $O(N \log N)$ sorting and linear check step. |
Schedule Log: Draw a massive database of every person's movement across every second of simulation. |
Priority Queue / Sorted Array: Draw a small array or heap holding current availability intervals. |
| 3595 |
Once Twice (Med) |
Generate all subsequences and check if each element appears exactly once or twice. |
2^N Power Set Search. |
Draw an array. Draw a binary tree (2^N leaves). For each leaf, scan for frequency constraints. $O(2^N \cdot N)$. |
Sliding Window + Frequency Map / Bitmask. |
Validity Frame. |
Move a window. Maintain counts. If any count exceeds 2, shrink left. Count valid subarrays or use DP for subsequences based on bitmasks. |
Draw the string. Place two brackets. If a character appears a 3rd time, move the left bracket past its first occurrence. |
$O(N)$. |
Draw a single string with two arrows (L and R) moving only forward. $O(N)$. |
Subsequence Heap: Draw massive lists of valid subsequences in memory. |
Fixed-Size Frequency Array: Draw an array of size 26 (or 128) storing integer counts. |
| 3596 |
Minimum Cost Path with Alternating Directions I (Med) |
Standard BFS/Dijkstra that ignores the "alternating" rule, checking only for minimum weight. |
Blind Graph Flood. |
Draw a grid. Draw arrows in all directions. Trace the shortest path without regard for the previous move. $O(N \cdot M)$. |
State-Layered Dijkstra (BFS with 2-Layer States). |
Parallel Directional Layers. |
Create two "ghost" grids: Layer H (arrived horizontally) and Layer V (arrived vertically). You can only move from H to V or V to H. |
Draw two stacked grids. Draw "downward" arrows from the top grid to the bottom grid, and "upward" arrows vice-versa. Label with costs. |
$O(N \cdot M)$. |
Draw a graph where each (r, c) has two nodes. Total nodes = 2NM. Draw a single shortest-path search. |
One-dimensional Visited Set: Draw a 1D boolean array that only tracks coordinates, losing the directional context. |
3D Distance Array: Draw a `dist[N][M][2]` array representing cost at each coordinate for both incoming directions. |
| 3597 |
Partition String (Med) |
Backtracking to try every possible split point in the string and checking if each part is valid. |
Exponential Split Tree. |
Draw a string. At every gap between letters, branch into "Split" or "No Split". 2^(N-1) leaf strings. |
Greedy Single Pass with Hash Set. |
Window of Uniqueness. |
Move right. If the current character is already in your "seen" set, it means you MUST split before this character. Reset set. |
Draw a string. Move a finger letter-by-letter. Toss letters into a "Current Part" bin. If you see a duplicate, draw a vertical line and empty the bin. |
$O(N)$. |
Draw a single straight arrow passing through the string. $O(1)$ set check per character. |
Recursive String Fragments: Draw hundreds of substrings stored in memory for every possible partition path. |
Hash Set: Draw one small character set (max size 26) that clears itself periodically. |
| 3598 |
Longest Common Prefix Between Adjacent Strings After Removals (Med) |
Try every combination of string removals, then for the remaining list, find the LCP of every adjacent pair. |
Combinatorial Subsequence Search. |
Draw the list of strings. Branch for "Remove string i" or "Keep string i". Calculate min(LCP) for each 2^N list. |
Dynamic Programming / Monotonic Stack. |
Prefix Slope Analysis. |
The LCP between any two strings is the minimum value in a Range LCP Query. Use DP to find the best selection to maximize this minimum. |
Draw a bar chart where heights are LCPs between adjacent strings. Your goal is to remove "dips" (low bars) to keep the highest "floor" possible. |
$O(N \cdot L)$ where L is string length. |
Draw a 1D DP array. Each index i shows the best score ending at string i. $O(N)$ linear scan. |
Massive Sub-list Combinations: Draw arrays of string pointers for every 2^N possibility. |
1D DP Array: Draw one array of integers storing the max length possible for each position. |
| 3599 |
Partition Array to Minimize XOR (Med) |
Try every possible way to split the array into two parts and calculate their XOR difference. |
Brute Force Partitioning. |
Draw the array. Draw a vertical line. Shift the line one by one, calculating XOR_left oplus XOR_right at each step. $O(N^2)$. |
Prefix XOR + Target Search. |
XOR Balance Point. |
Precompute Prefix XORs. Total XOR is T. We want to find a split point P such that P oplus (T oplus P) is minimized. |
Draw a line. Write "Running XOR" values below each element. Calculate (Value) vs (Total oplus Value) for each. Pick the closest pair. |
$O(N)$. |
Draw an array of N elements. Highlight the two passes (one for total XOR, one for best split). |
Subset XOR Logs: Draw a database recording the XOR result of every possible subarray. |
Two Integer Variables: Draw `totalXor` and `minDiff` variables that update in place. |
| 3600 |
Maximize Spanning Tree Stability with Upgrades (Hard) |
Generate every possible spanning tree and try every possible combination of edge upgrades within budget. |
Double Exponential Explosion. |
Draw the graph. Branch into all Spanning Trees. For EACH tree, branch into all budget permutations. $O(\text{Trees} \cdot 2^\text{Budget})$. |
Prim's/Kruskal's + Greedy / DP with Knapsack. |
Weighted Connectivity Expansion. |
Find the MST first. Then, prioritize upgrading edges in the MST that provide the highest "stability" per unit cost using a Knapsack DP. |
Draw a "skeleton" (MST) of the graph. Draw "Price Tags" on each edge. Use your "Budget Wallet" to buy the best tags greedily or via DP. |
$O(E \log V + \text{Edges} \\text{cdot Budget})$. |
Draw a Kruskal's sorting pass followed by a Knapsack grid (Edges x Budget). |
Graph State Permutations: Draw billions of graph variations with different edge weights in RAM. |
DSU + DP Array: Draw a parent array (for MST) and a 1D/2D DP array for the budget optimization. |
| 3601 |
Find Drivers with Improved Fuel Efficiency (Med) |
(SQL/Data) Nested subqueries for every single driver row to calculate half-year averages, filtering line by line. |
Relational Algebra Tree / Nested Loop join visualization. |
Draw a massive "for loop" box. Inside, draw an arrow pulling ONE driver out, then an arrow iterating over EVERY trip to filter by month. Write $O(N \cdot M)$ beside it. |
Common Table Expressions (CTEs) + GROUP BY aggregation + Self JOIN. |
Data Flow Pipeline / Table Funneling. |
Draw the base `trips` table. Draw a funnel showing `CASE WHEN month <= 6` splitting data into two buckets (Half 1, Half 2). Draw a combine step averaging each bucket. |
Draw two separate mini-tables (CTE1: first_half, CTE2: second_half). Draw a line matching `driver_id` between them, crossing out rows where `H1_avg >= H2_avg`. |
Pipeline Stage Complexity Map. |
Draw 3 horizontal blocks: "Scan/Group Trips $O(T)$", "Scan/Join Drivers $O(D)$", "Sort $O(K \log K)$". Add them up sequentially. |
Draw RAM holding copies of the entire table multiple times for subqueries. |
Draw RAM holding a hash map: Keys are driver_ids, Values are [Sum_H1, Cnt_H1, Sum_H2, Cnt_H2]. Shows exact space efficiency. |
| 3602 |
Hexadecimal and Hexatrigesimal Conversion (Easy) |
Using string concatenation `res = newChar + res` inside the division loop (causes $O(N)$ memory shifting per char). |
String Re-allocation Cascade. |
Draw a string. For every new character, draw a completely new box copying the old string over and adding one letter to the front. |
Mathematical Base Conversion (N % K, N // K) using a StringBuilder/Byte Array, followed by a single Reverse operation. |
Modulo-Division Stack / Remainder Tree. |
Take N. Write `N % 16`. Point down to a remainder. Write `N / 16`. Pass that new N to the next step. Map remainders > 9 to A-Z. |
Draw an upside-down division bracket. Write quotients on bottom, remainders on the right. Read remainders from bottom to top. |
Linear Array Fill timeline. |
Draw an array of size `log_base(N)`. Shade one slot per division step. Write $O(\log_16(N)$ + log_36(N)) to show time bounds based on output length. |
Draw overlapping, growing string arrays in memory being orphaned to garbage collection. |
Draw a single, fixed-size contiguous array block. Fill slots left to right, then draw an arrow showing an in-place two-pointer swap to reverse it. |
| 3603 |
Minimum Cost Path with Alternating Directions II (Med) |
Standard DFS/Backtracking trying all possible paths while forcing alternating directions. |
Exponential Recursion Tree. |
Draw a tree node. Branch it out 4 ways. For each child, branch 3 ways. Note the depth is V. Write $O(4^V)$ to show path explosion. |
State-Space Dijkstra's Algorithm. State = (Node, Arriving_Direction). |
Layered Graph Visualization. |
Draw two parallel versions of the grid. Layer 1: "Arrived Horizontally". Layer 2: "Arrived Vertically". Edges only cross between layers. |
Draw a Min-Heap. Pull the lowest cost node. If it arrived Horizontal, ONLY draw lines to its top/bottom neighbors, pushing them to the Vertical layer. |
Priority Queue Flowchart. |
Draw the V*2 possible states. Write E*2 possible edges. Write standard Dijkstra formula: $O((E + V)$ log V), noting V and E are just multiplied by 2 (constant factor). |
Draw a massive Call Stack frame pile representing deep recursion paths. |
Draw a 2D array `dist[node][direction_arrived]`. Visually overwrite infinity symbols with actual integer costs as they are relaxed. |
| 3604 |
Minimum Time to Reach Destination in Directed Graph (Med) |
Bellman-Ford algorithm or unoptimized BFS (if weights are unequal). |
V * E Relaxation Grid. |
Draw a matrix of V rows (iterations) and E columns (edges). Shade every cell to show redundant checks. Write $O(V \cdot E)$. |
Standard Dijkstra's Algorithm using an Adjacency List and a Min-Heap (Priority Queue). |
Expanding Water Ripple (Wavefront). |
Start at source. Color nodes based on current shortest known time. Always process the node with the absolute lowest time next, expanding its "ripple". |
Draw circles for nodes, lines with weights. Keep a tally box for `currentTime`. Update node labels by crossing out old values and writing smaller ones. |
Heap Operations Bar Chart. |
Draw a bar for "Extract Min" (V times, $O(\log V)$) and "Decrease Key / Add" (E times, $O(\log V)$). Sum them up visually. |
Draw a massive 2D Adjacency Matrix filled with mostly empty/infinite space (O(V^2)). |
Draw an Array of Arrays (Adjacency List) and a Binary Tree shape representing the active Priority Queue in memory. |
| 3605 |
Minimum Stability Factor of Array (Hard) |
Generate all possible contiguous subarrays (O(N^2)) and calculate stability for each (O(N)), tracking the minimum. |
Subarray Triangle Grid. |
Draw an N x N grid. Shade the upper triangle. For each cell (i, j), draw a loop inside it. Write $O(N^3)$ or $O(N^2)$ if optimized slightly. |
Sliding Window with Monotonic Deque OR Segment Tree (depending on exact stability constraint). |
Caterpillar/Inchworm Movement. |
Draw a bracket [ ] over the array. Expand the right side until stability is achieved. Shrink the left side to minimize the factor. |
Draw the array. Keep two pointers (L, R). Below it, draw a Monotonic Queue tracking max/min in current window. Cross out elements as they fall out of window. |
Two-Pointer Timeline / Amortized Analysis graph. |
Draw an axis from 0 to N. Plot the L pointer and R pointer. Show that neither pointer EVER moves backwards. Thus, 2N total steps = $O(N)$. |
Draw a massive 2D array storing intermediate states of every possible subarray. |
Draw a Double-Ended Queue (Deque). Show numbers entering the back, and older/smaller numbers getting "popped" out to maintain strict order. |
| 3606 |
Coupon Code Validator (Easy) |
Looping through the string multiple times to check individual rules (length, uppercase, digits, special chars). |
Redundant String Traversal Lines. |
Draw the string 4 times. Draw an arrow traversing the whole string for Rule 1, then again for Rule 2, etc. Write $O(4N)$ ≈ $O(N)$. |
Single-pass state machine or boolean flag tracking within a single iteration. |
State Flag Switchboard. |
Read char by char. If it's a digit, flip the "Has_Digit" switch to ON. If it's a symbol, flip the "Has_Symbol" switch to ON. Check all switches at the end. |
Draw the string. Below it, draw 4 checkboxes (Length, Digit, Upper, Special). Iterate left to right, checking off boxes as conditions are met. |
Single Linear Timeline. |
Draw an array of size N. Shade it left to right exactly once. Write strictly $O(N)$ with a single pass limit. |
Multiple boolean arrays or creating new substrings for regex matches. |
Four boolean variables drawn as simple binary switches (0 or 1). $O(1)$ space. |
| 3607 |
Power Grid Maintenance (Med) |
Try removing/modifying every node/edge one by one and running a full DFS/BFS to check grid connectivity each time. $O(E \cdot (V+E)$). |
Flipbook of Redundant Graphs. |
Draw the full graph. Erase one edge. Trace a path through all nodes to see if it's connected. Redraw the full graph. Repeat. |
Kruskal's Algorithm with Disjoint Set Union (DSU) or Tarjan's Bridge Finding Algorithm. |
Expanding Connected Components (Blobs). |
Sort edges by cost. Try adding them one by one. If an edge connects two separate "blobs" (grids), keep it and merge the blobs. If they are already in the same blob, discard it. |
Draw nodes as isolated dots. As edges are processed, draw circles grouping the connected nodes into larger and larger sets. |
Sorting + Tree Path Compression Map. |
Draw a bar representing $O(E \log E)$ for sorting edges. Next to it, draw a tiny nearly-flat line representing $O(E α(V)$) for DSU operations. |
Creating full Adjacency Matrix copies for every single iteration/edge removal attempt. $O(V^2)$. |
Two 1D arrays: `parent[]` and `rank[]`. Draw them tracking which nodes belong to which "root" power station. Space $O(V)$. |
| 3608 |
Minimum Time for K Connected Components (Med) |
Simulate time step by step. At each second, add active edges and run full BFS to count remaining components. $O(T \cdot (V+E)$). |
Time-Step Graph Snapshots. |
Draw a clock. For t=1, draw active edges, count blobs. For t=2, draw active edges, count blobs again from scratch. |
Sort edges by time, use Disjoint Set Union (DSU). Start with C=V components. Decrement C for every successful union. Stop when C == K. |
Component Countdown Timeline. |
Start a counter at N. Process edges chronologically. Every time an edge connects two isolated groups, slash the counter and subtract 1. Stop instantly at K. |
List edges ordered by time. Draw N separate dots. Draw lines for edges. Cross out the current Component Count and write the new one until you hit target K. |
Edge Processing Bottleneck Chart. |
Write the formula: $O(E \log E)$ to sort the timeline + $O(E \cdot α(V)$) to process unions. The sort is the dominant time factor. |
Storing full adjacency lists for every discrete second in time. |
Just the `parent` array for DSU and a single integer variable for `components_count`. Space $O(V)$. |
| 3609 |
Minimum Moves to Reach Target in Grid (Hard) |
Standard BFS checking only `(row, col)`, leading to infinite loops or re-visiting cells incorrectly because movement direction isn't tracked. |
Exploding Queue Tree. |
Draw a massive tree where every grid cell branches out 4 ways, looping back on itself infinitely. Write "Memory Limit Exceeded". |
0-1 BFS (Deque) or Dijkstra's Algorithm with a 3D State Space `(row, col, direction/momentum)`. |
3D State Space Matrix. |
Instead of visiting a cell, you visit a "state". Treat arriving at `[2,3]` from the North as a completely different room than arriving at `[2,3]` from the East. |
Draw a grid. Instead of putting a single checkmark for "visited", draw tiny directional arrows in the cell to show *how* it was reached and if it can be reused. |
State Space Multiplication map. |
Write Grid Size (R * C) multiplied by number of possible states (e.g., 4 directions). Total Time = $O(R \cdot C \cdot 4)$. |
A queue extending infinitely off the page holding redundant cyclic paths. |
A 3D boolean array `visited[R][C][4]` acting as checkboxes for specific arrival vectors. Space $O(R\cdot C\cdot 4)$. |
| 3610 |
Minimum Number of Primes to Sum to Target (Med) |
Deep backtracking recursion. Try subtracting every prime number smaller than the target, branching out infinitely. |
Infinite Branching Recursion Tree. |
Write Target. Branch down with `-2`, `-3`, `-5`... For each child, repeat. The tree becomes infinitely wide and recalculates identical subproblems. |
Sieve of Eratosthenes (precompute primes) + Unbounded Knapsack Dynamic Programming (Coin Change variant). |
DP Look-Back Array. |
Precompute primes. To find answer for N, look at the answers for `N - prime1`, `N - prime2`, etc. Take the minimum of those answers and add 1. |
Draw a row of boxes from 0 to Target. Fill `dp[0]=0`. For `dp[i]`, draw arrows pointing back to `i - prime` boxes. Pick the smallest, add 1. |
Nested Loop Coverage Grid. |
Draw an array of length Target. For each cell, draw P arrows pointing back (P = number of primes). Time complexity is strictly $O(\text{Target} \cdot P)$. |
Call Stack Overflow due to millions of redundant recursive frames. |
Two 1D arrays: `is_prime` (boolean array from Sieve) and `dp` (integer array of size Target). Space $O(\text{Target})$. |
| 3611 |
Find Overbooked Employees (Med) |
(SQL) Using nested subqueries per row to calculate the sum of meeting durations, filtering week by week iteratively. |
Tangled Cartesian Join Lines. |
Draw an employee table. Draw dozens of arrows pointing from ONE employee to every single row in the meetings table. Write $O(E \cdot M)$. |
Common Table Expressions (CTEs) to group by employee_id, year, week, aggregate sums, filter > 20, then self-join. |
Data Pipeline / Funnel Stages. |
Draw a funnel. Stage 1: Raw Meetings. Stage 2: Weekly Sums per Employee. Stage 3: Filter out sums < 20. Stage 4: Count remaining weeks, keep >= 2. |
Draw 3 boxes (representing CTE temporary tables). Draw rows of data moving between boxes, crossing out rows that don't meet the threshold. |
SQL Execution Plan Tree. |
Draw a Hash-Aggregate node (O(M)), feeding into a Filter node (O(M)), feeding into a Hash-Join node with Employees (O(E)). Total $O(M + E)$. |
Draw large, unoptimized temporary tables taking up massive blocks of server RAM. |
Draw a small Hash Table grouping keys (EmpID, Week) mapping to a single integer (Total_Hours). |
| 3612 |
Process String with Special Operations I (Med) |
Using string concatenation str = str.substring() + new_char or `.replace()` for every single operation. |
String Shift Dominoes. |
Draw an array of characters. Insert a character in the middle, then draw arrows shifting every character to its right by one slot. Write $O(N^2)$. |
Single-pass Simulation using a Stack or a dynamically sized Array/StringBuilder. |
Vertical Stack Pushing. |
Read string left to right. Push valid characters into a bucket. When a special operation occurs, look at the top item in the bucket and mutate/pop it. |
Draw the input string on top. Draw an empty vertical box (Stack) below. Cross off characters from the string and re-write them inside the box one by one. |
Single Horizontal Timeline. |
Draw an arrow moving strictly left-to-right across the input string exactly once. Write $O(N)$. |
Draw overlapping, slightly mutated copies of the entire string piling up in memory to be garbage-collected. |
Draw one contiguous array (StringBuilder buffer) filling up linearly. Space $O(N)$. |
| 3613 |
Minimize Maximum Component Cost (Med) |
Iterate threshold `X` from 1 to Max Cost. For each `X`, build the graph and check if components are valid. $O(\text{Max}_\text{Cost} \cdot (V+E)$). |
Linear Search Iteration Grid. |
Draw a number line from 0 to 100. For 1, 2, 3... draw a tiny graph above it and test if it works. Cross it out and move to the next. |
Binary Search on Answer + Disjoint Set Union (DSU) / Connected Components Check. |
Binary Search Halving + Blob Merging. |
Pick a middle cost `M`. Add edges with cost `<= M`. If nodes merge into valid blobs, `M` is valid; cut the top half of the search space. |
Draw a number line. Drop a pin in the middle. Draw dots grouping together. If it succeeds, cross out the entire right half of the line in one stroke. |
Logarithmic Depth Chart. |
Draw a tall bar for search space. Cut it in half. Cut it in half again. Write $O(\log(\text{Max}_\text{Cost})$ * (V+E)). |
Draw full Adjacency Matrix copies generated for every single iteration. |
Draw two 1D arrays: parent[] and size[] used for DSU. Space strictly $O(V)$. |
| 3614 |
Process String with Special Operations II (Hard) |
Simulating range updates or deep nested operations character by character, leading to Time Limit Exceeded (TLE). |
Nested Loop Matrix. |
Draw a string. For a range update [2 to 5000], draw 5000 individual arrows pointing to each character. Write $O(N \cdot Q)$ where Q is operations. |
Difference Array (Sweep Line) or Fenwick Tree (Binary Indexed Tree) to mathematically track shifts. |
Delta (+1 / -1) Overlay. |
Don't touch the string! If range [2, 5] gets shifted, write "+1" at index 2, and "-1" at index 6. After all operations, sweep left to right to apply changes. |
Draw the string. Below it, draw an array of 0s. Apply a +1 and -1 boundary for an operation. At the end, do a running sum across the array to find final shifts. |
Constant Time Operation Dots. |
Draw Q dots representing $O(1)$ operations. Then draw one solid line across N representing the final sweep. Write $O(N + Q)$. |
Draw out-of-memory errors from copying and shifting massive string instances recursively. |
A single integer array delta[N+1] holding small mathematical increments. Space $O(N)$. |
| 3615 |
Longest Palindromic Path in Graph (Hard) |
Running a full DFS from every node, accumulating path strings, and checking isPalindrome() at the end of every path. |
Exponential Path Tree. |
Start at Node A. Branch to B, C, D. For each, branch again. The tree grows infinitely. Write $O(V \cdot 2^E)$. |
Bi-directional Dynamic Programming (Meet-in-the-Middle) / Graph BFS. State = (u, v). |
Pincer Movement (Closing the Gap). |
Place a finger on start node `u` and end node `v`. Move `u` forward and `v` backward simultaneously. If the letters match, the palindrome length grows by 2. |
Draw a grid where rows are Node `u` and columns are Node `v`. Shade cells dp[u][v] where a valid palindrome path connects them. |
State-Space Matrix Area. |
Draw a box of size V by V. The algorithm only computes each cell once. Write $O(V^2 + E)$ transition time. |
A massive Call Stack holding thousands of strings in memory. |
A 2D array dp[V][V] storing integer lengths, or a Queue storing pairs (u, v). Space $O(V^2)$. |
| 3616 |
Number of Student Replacements (Med) |
Simulating every single replacement step-by-step, physically mutating arrays and re-scanning them to check if the target configuration is met. $O(N^2)$. |
Cascading Array Copies. |
Draw the original array. Cross out one element, draw a completely new array below it representing the state change. Repeat until it matches the target. |
Frequency Maps / Discrepancy Counting. (Compare counts of what you have vs. what you need). |
Bipartite Balancing Scale. |
Count all elements in the current array. Count all elements in the target array. Match identicals. The sum of the unmatched remaining items divided by 2 is the replacement cost. |
Draw two columns of numbers/letters (Current vs Target). Draw lines connecting identical pairs. Count the items left over that have no lines. |
Linear Hash Map Pass. |
Draw one arrow scanning Current (O(N)), one arrow scanning Target (O(N)), and one scanning the Alphabet/Key space (O(26) or $O(K)$). |
Towers of redundant arrays piled up in memory for each replacement step. |
Two small arrays of size 26 (or Hash Maps) tracking simple integer frequencies. $O(1)$ space if character set is fixed. |
| 3617 |
Find Students with Study Spiral Pattern (Hard) |
Picking every possible cell as a center point, and manually running a `while` loop tracing a spiral outward to check constraints. $O(N^3)$ or worse. |
Overlapping Spaghetti Loops. |
Draw a grid. Pick a cell and draw a spiral. Pick the immediate next cell and draw another spiral that completely overwrites the first one's ink. |
2D Prefix Sums + Binary Search for Radius, treating the "spiral rings" as concentric square boundaries. |
Expanding Concentric Boundaries. |
Instead of walking in a spiral, treat it as rings. Ring 1 is radius 1. Ring 2 is radius 2. Use 2D Prefix Sums to calculate the total values inside the outer boundary, minus the inner boundary, in $O(1)$ time. |
Draw a grid. Draw a thick red square boundary. To find its sum, point to the bottom-right corner of the outer square, and subtract the inner square's prefix sum. |
Matrix Lookup Target Practice. |
Draw an arrow from your target center directly to 4 specific corners in a Prefix Sum matrix. Write $O(1)$ lookup, making the total algorithm $O(N^2 \log N)$. |
Thousands of temporary coordinate pairs pushed to the call stack during manual spiral tracing. |
A single prefix_sum[R+1][C+1] 2D matrix storing pre-calculated block sums. Space $O(R\cdot C)$. |
| 3618 |
Split Array by Prime Indices (Med) |
Iterating through the array, and for every index, running a `for(i=2 to sqrt(index))` loop to check if it's prime. $O(N \\text{cdot sqrt}(N)$). |
Redundant Division Trees. |
Draw an array. For index 7, write "7%2, 7%3". For index 11, write "11%2, 11%3". Notice how you keep recalculating primes. |
Sieve of Eratosthenes (precompute primes up to N) + Single Pass Prefix/Suffix sums. |
Boolean Sieve Overlay Mask. |
Generate a True/False list of primes up to N. "Overlay" this list on top of your array indices. Only add values to your running sums where the overlay says "True". |
Draw an array of indices 0 to N. Highlight the prime ones. Below it, draw the actual array. Only pull down the values that sit under a highlighted index. |
Two-Phase Segmented Line. |
Draw a small block labeled "Sieve: $O(N \log \log N)$". Draw a long straight line labeled "Array Pass: $O(N)$". Add them together. |
Variables created inside nested loops losing scope and recalculating math constantly. |
A simple boolean array isPrime[N] where true means prime. Space $O(N)$. |
| 3619 |
Count Islands With Total Value Divisible by K (Med) |
DFS without properly marking a global `visited` set, causing the algorithm to re-traverse the same islands from different starting cells. |
Endless Meandering DFS. |
Draw a grid. Draw a line snaking around forming an island. Then start at a different cell in the same island and draw the exact same snaking line again. |
Standard BFS/DFS Connected Components. Accumulate a `running_sum` during the traversal. Modulo K at the very end of the island. |
Expanding Flood-Fill with a Bucket. |
Drop paint on an unvisited land cell. As the paint spreads to adjacent land, throw their values into a bucket. When the paint stops spreading, check `bucket % K == 0`. |
Draw a grid. Shade cells as you "visit" them. Write a tally mark outside the grid summing up the shaded cells. When the island is done, write `% K`. |
One-Dot-Per-Cell Matrix. |
Draw a grid. Place exactly ONE dot inside every single cell to prove that no cell is processed more than once. Write $O(R \cdot C)$. |
A massive implicit call stack from runaway recursion trying to backtrack over water and land. |
A visited[R][C] boolean matrix and an explicit Queue for BFS. Space $O(R \cdot C)$. |
| 3620 |
Network Recovery Pathways (Hard) |
Generate all possible permutations of nodes/paths to find the cheapest recovery order. $O(V!)$. |
Factorial Explosion Tree. |
Start at Node A. Branch to all V-1 nodes. From those, branch to V-2 nodes. The tree gets so wide the paper turns completely black. |
Dijkstra's Algorithm with Bitmask DP (State Space Search). State = (Current_Node, Visited_Mask). |
Bitmask "Keyring" Expansion. |
Imagine walking through a graph. Every time you fix a server, you add its "key" to your keyring (the bitmask). You can visit the same node twice, but only if you have a *different* set of keys. |
Draw nodes as circles. Next to a node, instead of writing one distance, write multiple distances mapped to binary strings (e.g., 1010 : Cost 45, 1110 : Cost 60). |
Exponential yet Bounded Grid. |
Draw V rows (nodes) and 2^K columns (where K is number of critical servers to recover). The graph size is bounded to $O(E \cdot 2^K)$. |
Storing millions of full path integer arrays in a massive list to compare totals at the end. |
A 2D array dist[V][1 << K] initialized to infinity, storing minimum costs for every mask state. Space $O(V \cdot 2^K)$. |
| 3621 |
Number of Integers With Popcount-Depth Equal to K I (Hard) |
Iterate from 1 to N, calculate the popcount recursively for every single number, and count how many hit exactly depth K. $O(N \log N)$. |
Endless Number Crunching Grid. |
Draw a massive grid of numbers 1 to N. Next to each, write its binary form, then count the 1s, write that number, count its 1s... cross out the ones that don't match K. |
Digit DP / Combinatorics. Precompute valid target "set bit counts", then build valid numbers bit by bit using combinations (nCr). |
Binary Prefix Tree Branching. |
Look at the binary string of N. Scan left to right. Every time you see a '1', imagine a branch where you put a '0' instead. In that '0' branch, you can freely place any remaining bits using combinations. |
Draw the binary string of N. Under every '1', drop a vertical arrow down, write a '0', and next to it write the combination formula nCr for the remaining slots. |
State Space Matrix. |
Draw a matrix of length log(N) (bits) by log(N) (possible set bits). Write $O(\log^2 N)$ to show we only process combinations of bits, not the numbers themselves. |
Arrays holding step-by-step depth calculations for millions of individual numbers. |
A small 1D array DP mapping [number_of_set_bits] -> depth. Max size is 32 or 64. $O(1)$ space. |
| 3622 |
Check Divisibility by Digit Sum and Product (Easy) |
Modulo loop to extract digits, sum them, multiply them, then perform two modulo checks at the very end. |
Sequential Extraction Boxes. |
Write the number N. Draw arrows extracting each digit one by one into two separate accumulator boxes (Sum and Product). Do division at the end. |
Early Short-Circuit Simulation. If any digit is '0', the product becomes 0 instantly (cannot divide by zero), so return false immediately. |
Short-Circuit Logic Gate. |
Scan the digits. The moment you hit a '0', pull an emergency brake lever. Stop all math, return false. Otherwise, calculate sum/product normally. |
Draw an array of digits. Sweep left to right. If you hit a 0, draw a massive red 'X' and stop. If you finish, draw a green check. |
Single Linear Scan Line. |
Draw an array representing the digits. Draw a single arrow going left to right. Write $O(\log10 N)$ which equals the number of digits. |
Converting the integer to a String and allocating a new character array in memory. |
In-place integer modulo operations (N % 10, N / 10). Strict $O(1)$ space usage. |
| 3623 |
Count Number of Trapezoids I (Med) |
Four nested loops to pick every combination of 4 points, calculating slopes for all pairs to check if exactly two sides are parallel. $O(N^4)$. |
4-Point Combinatorial Mesh. |
Draw a scatter plot of dots. Draw a 4-loop nested block. Pick 4 random dots, connect them to make a shape, check slopes. Repeat endlessly. |
Group line segments by slope using a Hash Map. A trapezoid is formed by picking 2 segments with the same slope (bases) and ensuring they don't share points. |
Grouped Slope Bins. |
Calculate the slope and midpoint between ALL pairs of points (O(N^2)). Throw these segments into buckets labeled by their slope. Pick combinations of 2 from within the same bucket. |
Draw several buckets labeled with fractions (slopes). Throw segment lines into them. Inside a bucket, draw lines connecting pairs of segments to form shapes. |
Pair Combinations Flowchart. |
Write "Find Pairs $O(N^2)$". Draw an arrow to "Group by Slope $O(N^2)$". Draw an arrow to "Count Combinations $O(N^2)$". Total time $O(N^2)$. |
Storing every single 4-tuple of points in a massive list before validation. |
A Hash Map where Keys are reduced Fractions (Slopes) and Values are Lists of point-pairs. Space $O(N^2)$. |
| 3624 |
Number of Integers With Popcount-Depth Equal to K II (Hard) |
Same as part I, but N is given as a massive string (up to 10^5 bits). Attempting standard iteration results in an instant Time Limit Exceeded. |
Heat Death Timeline. |
Draw a string of 100,000 ones. Attempt to draw a loop that runs 2^100000 times. Cross the entire page out. |
Advanced Digit DP + Precomputed Combinatorics Modulo 10^9+7. Find valid popcounts up to Length L, then use nCr to place bits. |
Bounded String Slicing. |
The max popcount is the string length L (10^5). Find which target popcounts `p <= L` take exactly K-1 steps to reach 1. Then find how many numbers `<= N` have exactly `p` set bits. |
Draw a long binary string. Scan left to right. When you hit a '1', add the mathematical combination of (Remaining Length) choose (Target Bits - Current Bits). |
Length-Bounded Pascal's Triangle. |
Draw a matrix for precomputing nCr up to L. Time is dominated by the string scan and combination lookups. Write $O(L^2)$ or $O(L)$ if combinations are precomputed $O(1)$. |
Infinite recursion stack crashing the program. |
Arrays of size L (10^5) for factorials, inverse factorials, and DP states. Space strictly bounded to $O(L)$. |
| 3625 |
Count Number of Trapezoids II (Hard) |
Same as part I, but larger constraints mean $O(N^4)$ or even unoptimized $O(N^2)$ combinatorial grouping fails. |
Dense Point Cloud Rendering. |
Draw thousands of points, attempting to draw overlapping segment lines between every single one. Visual chaos. |
Inclusion-Exclusion Principle. (Total Trapezoids = All shapes with at least 1 pair of parallel sides MINUS Parallelograms which have 2 pairs). |
Inclusion-Exclusion Venn Diagram. |
Find all parallel segment pairs. Count them. That gives you Trapezoids + Parallelograms. Then strictly identify Parallelograms (same slope AND matching midpoints) and subtract them out. |
Draw a large circle labeled "At least 1 parallel pair". Draw a smaller inner circle labeled "Exactly 2 parallel pairs (Parallelograms)". Subtract the inner from the outer. |
Sweep Line / Map Lookup Graph. |
Draw a timeline. Finding segments is $O(N^2)$. Sorting/grouping them by slope is $O(N^2 \log N)$. Subtracting parallelograms is $O(N^2)$. Dominant time is $O(N^2 \log N)$. |
Exhausted heap space from storing raw coordinate matrices. |
Optimized Hash Maps storing structural metadata (slope, distance, midpoint) mapped to integer counts, not full object lists. Space $O(N^2)$. |
| 3626 |
Find Stores with Inventory Imbalance (Med) |
Nested loops comparing every store's inventory items against a global target, re-calculating sums constantly. $O(N \cdot M)$. |
Redundant Loop Arrows. |
Draw Store 1. Draw arrows to every single item to sum them. Draw Store 2. Draw arrows to every single item again. Write $O(\text{Stores} \\text{cdot Items})$. |
Hash Map Aggregation / Group By (if SQL). Accumulate counts in a single pass, then compare against the precomputed average. |
Map-Reduce Funnel. |
Draw raw items flowing into individual "Store Buckets". Once all items are sorted, place each bucket on a balance scale against the "Target Weight". |
Draw an array of items. Below it, draw a few boxes (Stores). Draw lines funneling items into their respective boxes. Compare final box numbers to the target. |
Two-Phase Linear Pipeline. |
Draw one long arrow for "Scan & Group $O(N)$". Draw a second shorter arrow for "Filter Stores $O(K)$". Total time $O(N)$. |
In-memory copies of filtered arrays created for every single store check. |
A single Hash Map where Keys are store_id and Values are current_inventory_sum. Space $O(\text{Unique}_\text{Stores})$. |
| 3627 |
Maximum Median Sum of Subsequences of Size 3 (Med) |
Generate all combinations of size 3 (nC3), find the median of each, sum them up to find the maximum possible configuration. $O(N^3)$. |
Combinatorial Explosion Tree. |
Draw an array. Branch out to pick the first element, then branch to pick the second, then the third. The paper fills with redundant triplets. |
Greedy Algorithm + Sorting. Sort the array. To maximize medians, pair the largest available, the *next* largest (the median), and the smallest available. |
Greedy Two-Pointer Pinch. |
Sort the numbers. The smallest numbers are "sacrificed" as the left side of the triplets. The largest numbers are the right side. The second-largest numbers become your precious medians. |
Draw a sorted array. Place pointer L at start, pointer R at end. Group elements: [arr[L], arr[R-1], arr[R]]. The median is always arr[R-1]. Move L right by 1, R left by 2. |
Sorting Bottleneck Block. |
Draw a large block labeled "Sort: $O(N \log N)$". Next to it, draw a tiny block labeled "Greedy Scan: $O(N)$". Dominant time is sorting. |
Massive lists of lists storing every generated triplet combination. |
In-place pointers on the original array (or a sorted copy). Space $O(1)$ or $O(N)$ depending on sort implementation. |
| 3628 |
Maximum Number of Subsequences After One Inserting (Med) |
Try inserting character '0' at every position, then '1' at every position, recounting the target subsequences from scratch each time. $O(N^2)$. |
Shifting Array Matrix. |
Draw N versions of the array stacked vertically, each with the new character wedged into a different spot. Loop through all of them. |
Prefix and Suffix Counts. Count existing '0's and '1's. Inserting '0' at the start pairs with all existing '1's. Inserting '1' at the end pairs with all existing '0's. |
Balance Beam / Seesaw. |
You don't need to check the middle! Putting the first character at the extreme left, or the second character at the extreme right, strictly maximizes the new pairs formed. |
Draw the string. Count total 'char1's. Count total 'char2's. The max increase is simply max(total_char1, total_char2) added to the base subsequence count. |
Single Linear Sweep. |
Draw an arrow sweeping left to right once to count base subsequences and frequencies. Write $O(N)$. |
Hundreds of modified string copies cluttering the heap memory. |
Three integer variables: count_char1, count_char2, and total_subsequences. Space strictly $O(1)$. |
| 3629 |
Minimum Jumps to Reach End via Prime Teleportation (Med) |
Standard BFS trying every single valid prime jump distance from every single index. Re-checks the same jumps constantly. $O(N \\text{cdot Primes}_\text{in}_\text{Range})$. |
Tangled Spaghetti Graph. |
Draw nodes 1 to N. From node 2, draw arcs of length 2, 3, 5... From node 3, draw overlapping arcs of length 2, 3, 5. Visually chaotic and slow. |
Sieve of Eratosthenes + BFS with a "furthest reached" pointer to strictly avoid re-scanning identical prime gaps. |
Frog Jumping over Lily Pads. |
Precompute primes. The frog sits at index `i`. It looks at primes to jump forward. Crucially, it drags a "checked boundary" line behind it so it never evaluates a landing pad twice. |
Draw an array. Keep a variable max_reach. When jumping from i, only consider landing on j if j > max_reach. Update max_reach as you jump. |
Bounded Reach Timeline. |
Draw the Sieve $O(N \log \log N)$. Draw the BFS timeline. Because of max_reach, each index is queued at most once. Write BFS $O(N)$. |
A queue inflating infinitely because the same target indices are pushed from different starting points. |
A boolean isPrime[] array and a standard BFS Queue. Space $O(N)$. |
| 3630 |
Partition Array for Maximum XOR and AND (Hard) |
Backtracking to find all 2^(N-1) possible array partitions, calculating the XOR and AND for every single configuration. |
Binary Partition Tree. |
Draw the array. At every gap between numbers, branch left ("Split Here") and right ("Don't Split"). The tree width explodes exponentially. Write $O(2^N)$. |
Greedy Bit-by-Bit Construction (from MSB to LSB). Check if a partition can satisfy the current bit mask using a linear scan. |
Bit-by-Bit Sieve/Filter. |
Build the answer one bit at a time, starting from the 30th bit down to 0. "Can I partition this array such that the 30th bit stays a 1?" If yes, lock it in. If no, accept a 0 and move to the 29th bit. |
Draw 30 horizontal layers (bits). Pour the array through the top layer. Run a quick greedy check to see if it "passes" the bit test. If it does, keep that bit 1 in your result tally. |
Constant Factor Loop. |
Draw a loop running exactly 30 times (for 32-bit integers). Inside, draw an $O(N)$ array scan. Write strictly $O(30 \cdot N)$ ≈ $O(N)$. |
Massive recursive call stacks attempting to hold the state of thousands of sub-arrays. |
A few integer variables for bitmasks (target, current_mask) and an $O(1)$ space linear scan. |
| 3631 |
Sort Threats by Severity and Exploitability (Med) |
Implementing a naive $O(N^2)$ sorting algorithm (like Bubble Sort) with messy, heavily nested if-else conditions to handle the multi-level sorting rules. |
Tangled Swap Lines. |
Draw an array of items. Draw overlapping, chaotic arrows showing elements swapping places hundreds of times as different rules clash. |
Built-in $O(N \log N)$ Sort with a strictly defined Custom Comparator function returning -1, 0, or 1 based on a prioritized rule cascade. |
Decision Tree Plinko Board. |
Pick two items. Drop them into a funnel. Rule 1: Is Severity different? If yes, route left/right. If tie, drop to Rule 2: Exploitability. If tie, drop to Rule 3. |
Draw two boxes (Item A, Item B). Draw a vertical list of rules. Draw a line comparing A and B at Rule 1. If equal, draw the line down to Rule 2, until a winner is found. |
Clean N log N Block. |
Draw a solid block labeled "Language-Native TimSort/QuickSort $O(N \log N)$". The comparator runs in $O(1)$ time per comparison, maintaining the bound. |
Thousands of temporary variable allocations during manual, unoptimized swaps. |
In-place sorting using the language's native optimized memory management. Space $O(\log N)$ to $O(N)$ depending on the engine. |
| 3632 |
Subarrays with XOR at Least K (Hard) |
Nested loops iterating over every possible subarray `(i, j)`, calculating the running XOR and checking if it's `>= K`. $O(N^2)$. |
Subarray Triangle Grid. |
Draw an N x N grid. Shade the upper right triangle. Inside every shaded cell, write the XOR computation. Takes way too long. |
Prefix XOR Array combined with a Binary Trie (Prefix Tree) to count valid pairs in $O(N \log(\text{Max}_\text{Value})$) time. |
Binary Tree Traversal (Trie). |
Store all previous Prefix XORs in a Trie as 32-bit binary paths. For the current Prefix XOR, walk down the Trie. If going down a specific bit-branch guarantees the XOR with that branch will be `> K`, count the whole subtree instantly and stop. |
Draw a tree where left branches are '0' and right branches are '1'. Start at the root. Compare your current bit with K's bit. Draw an arrow cleanly bypassing entire subtrees that are mathematically guaranteed to win. |
Trie Depth Bounding. |
Draw an array scan $O(N)$. For each element, draw an arrow pointing to a tree of max depth 32. Write $O(32 \cdot N)$ = $O(N)$. |
Massive 2D matrices attempting to memoize the XOR of every possible subarray pair. |
A Binary Trie structure. Each node has at most 2 children and a `count` variable. Max space is strictly bounded by $O(N \cdot 32)$. |
| 3633 |
Earliest Finish Time for Land and Water Rides I (Easy) |
Trying every single permutation of land and water rides to see which ordering finishes first. $O(N!)$. |
Factorial Branching Tree. |
Write Ride 1. Branch to Ride 2 or Ride 3. Branch again. The tree explodes instantly even for small arrays. |
Greedy Algorithm / Sorting. Match the longest land rides with the shortest water rides (or vice versa, depending on exact problem constraints) to minimize the maximum bottleneck. |
Interlocking Gantt Chart Blocks. |
Think of rides as physical wooden blocks. You want to stack one Land block and one Water block. To keep the tallest stack as short as possible, pair your tallest Land block with your shortest Water block. |
Draw two arrays of numbers. Sort one ascending, sort the other descending. Draw straight vertical lines connecting index 0 to index 0, index 1 to 1. Find the max sum. |
Sorting Bottleneck Line. |
Draw two long blocks labeled "Sort $O(N \log N)$". Draw one short block labeled "Linear Pair Scan $O(N)$". Dominant time is sorting. |
Call stack overflow from recursive permutation generation. |
In-place sorting of the two input arrays. Space $O(1)$ or $O(\log N)$. |
| 3634 |
Minimum Removals to Balance Array (Med) |
Physically removing an element, shifting the rest of the array left, and recalculating the sum of even and odd indices from scratch. $O(N^2)$. |
Array Shift Cascades. |
Draw the array. Cross out index 2. Draw arrows moving index 3 to 2, 4 to 3... Then draw a loop summing it all up. Repeat for every index. |
Prefix and Suffix Sums. Precalculate even/odd sums. When you "remove" an element, the suffix even/odd sums simply swap roles! |
The "Index Shift" Swap mechanism. |
Imagine the array as a train. If you remove a car in the middle, all the cars behind it shift forward by one. Therefore, all odd-indexed cars behind it become even, and evens become odd. Just swap your precalculated suffix variables. |
Draw an array. Write `PrefEven`, `PrefOdd` before a cut point. Write `SuffEven`, `SuffOdd` after it. To test the cut, sum `PrefEven + SuffOdd` and `PrefOdd + SuffEven`. |
Three-Pass Linear Scan. |
Draw one arrow scanning right (build prefix), one scanning left (build suffix), one scanning right (test cuts). 3 * $O(N)$ = $O(N)$. |
N copies of the array created in memory to test each removal scenario. |
Four 1D arrays of size N for Prefix/Suffix Even/Odd sums. Space $O(N)$. (Can be optimized to $O(1)$ space with running variables). |
| 3635 |
Earliest Finish Time for Land and Water Rides II (Med) |
Simulating the rides minute by minute, advancing a time counter and checking which rides are available. $O(\text{Max}_\text{Time} \cdot N)$. |
Infinite Clock Ticks. |
Draw a clock. Tick to minute 1: loop through all rides. Minute 2: loop through all rides. Very slow if times are huge. |
Binary Search on the Answer. Guess a "Finish Time" T. Write a greedy $O(N)$ checker to see if all rides can be completed within time T. |
The "Will It Fit?" Halving Line. |
Guess a time: "Can we finish in 100 mins?" Run a quick check. "Yes! Okay, can we finish in 50?" "No. Okay, how about 75?" Keep slicing the search space in half. |
Draw a number line from 0 to Max_Possible_Time. Drop a pin in the middle. If the $O(N)$ check passes, cross out the right half. If it fails, cross out the left. |
Binary Search Logarithmic Scale. |
Write the formula: $O(N \cdot \log(\text{Max}_\text{Time})$). Draw the log(Max_Time) as the number of guesses, and N as the work done per guess. |
Massive state arrays tracking minute-by-minute status of every single ride. |
A few integer variables for binary search bounds (low, high, mid). Space strictly $O(1)$. |
| 3636 |
Threshold Majority Queries (Hard) |
Iterate over every query range [L, R], scan the subarray to count frequencies of all elements, and check if any exceed the threshold. $O(Q \cdot N)$. |
Full Array Scan Per Query. |
Draw an array. Draw Q brackets. For each bracket, draw an arrow scanning every single element inside it to build a tally. Write $O(Q \cdot N)$. |
Segment Tree with Boyer-Moore Voting or Random Sampling + Range Binary Search (using a map of indices). |
Candidate Filtering + Verification. |
Pick a few random elements from the range [L, R]. If a majority exists, there is a very high mathematical probability one of these random picks is the candidate. Then, use a Hash Map of indices to check its frequency in $O(\log N)$. |
Draw a subarray. Circle 5 random elements. For each circled number, look it up in a precomputed "Sorted Indices Map" and subtract `upper_bound - lower_bound` to get the count. |
Probabilistic log-time Chart. |
Write $O(Q \cdot K \cdot \log N)$, where K is a small constant (number of samples). Draw a flat line for queries compared to the steep brute force slope. |
A massive frequency map created and destroyed for every single query, causing heap fragmentation. |
A single Hash Map where Keys are value and Values are List of indices. Space $O(N)$. |
| 3637 |
Trionic Array I (Easy) |
Triple nested loops to check every possible triplet (i, j, k) to see if they satisfy the "Trionic" sum/property. $O(N^3)$. |
3D Iteration Cube. |
Draw a cube. Each axis represents an index (i, j, k). Shade the whole volume of the cube. It’s too dense to compute for N > 500. |
Two-pointer approach or Hash Map tracking based on the property target - (arr[i] + arr[j]). |
Running Sum Balance Beam. |
Fix one element i. Now you just need to find two other elements j, k that sum to a specific remainder. This is just the "Two Sum" problem repeated N times. |
Draw an array. Point to index i. For the rest of the array, place pointers L and R at the ends and move them inward based on the sum. |
Nested Linear Block. |
Draw an outer loop (O(N)). Inside it, draw a two-pointer scan (O(N)). Write $O(N^2)$. |
A massive list of all 3-tuples generated before checking. |
In-place pointer arithmetic. Space $O(1)$. |
| 3638 |
Maximum Balanced Shipments (Med) |
Generating all possible ways to partition the array into shipments and checking each for "balance". $O(2^N)$. |
Binary Partition Tree. |
Draw an array. At every gap, branch "Cut" or "No Cut". The tree grows to 2^N leaves. Write "TLE" at the bottom. |
Dynamic Programming with a Fenwick Tree or Segment Tree to find the maximum shipments ending at index `i`. |
Step-by-Step Cumulative Peak. |
For each item i, you want to know: "What is the most shipments I could have made before this, where the balance condition is met?" Query a Fenwick tree for the max value in a specific range. |
Draw an array. Below it, draw a Fenwick Tree (series of boxes). For each element, look up the "best previous score" from the boxes, add 1, and update the boxes. |
Point Query Timeline. |
Draw a linear scan (O(N)). Above each step, draw a small tree lookup (O(log N)). Write $O(N \log N)$. |
Huge recursive tree structures stored in memory. |
A single 1D array representing the Fenwick Tree. Space $O(N)$. |
| 3639 |
Minimum Time to Activate String (Med) |
Trying every possible activation order of characters and simulating the time taken for each. $O(N!)$. |
Factorial Order Explosion. |
Write character A. Branch to all others. Write character B. Branch again. The number of paths is astronomical. |
Greedy algorithm with a Queue or Monotonic Stack, focusing on the nearest available character that satisfies the activation rule. |
Magnetized Character Attraction. |
Characters are "activated" based on their distance. Instead of trying all, always pick the "cheapest" next step using a sliding window or a precomputed distance map. |
Draw the string. For the current active index, draw arrows to the nearest 'target' characters. Pick the shortest arrow, move there, and repeat. |
Linear Greedy Path. |
Draw a single arrow moving through the string. Even with some "lookback", the total movement is bounded. Write $O(N)$. |
A massive list of permutations of the string's indices. |
A few pointers and a Hash Map/Array of size 26 to store character positions. Space $O(N)$ or $O(1)$. |
| 3640 |
Trionic Array II (Hard) |
Same as Trionic Array I but with much larger constraints and a dynamic update component (queries that change array values). |
Repeated $O(N^2)$ Scans. |
Draw the N^2 scan from 3637. Now draw it again for every single query. Write $O(Q \cdot N^2)$. Instant failure. |
Segment Tree or Square Root Decomposition where each "node" or "bucket" stores partial Trionic counts. |
Partial Sum Blocks. |
Divide the array into blocks of size √N. When a value changes, only update the counts for its specific block. For queries, combine the precomputed results of all blocks. |
Draw the array. Group it into 4 large boxes. If an element in Box 1 changes, only redraw Box 1. To get the total, just sum the 4 boxes. |
Square Root Balancing. |
Write $O(Q \cdot √N)$. Draw the array as N, then draw the √N blocks. Show that we only visit a few blocks per query. |
Total recalculation of all triplet counts on every single update. |
1D array for the original data and a 2D or 3D structure for block-level summaries. Space $O(N)$. |
| 3641 |
Longest Semi-Repeating Subarray (Med) |
Generate every possible subarray (i, j), and for each, count how many pairs of adjacent characters are identical. $O(N^3)$. |
Subarray Nested Scan Grid. |
Draw an array. Draw a bracket for every possible start and end point. Inside each bracket, draw arrows checking every single adjacent pair. Write $O(N^3)$. |
Sliding Window with a single counter for "duplicate pairs". |
Expanding Window with a Violation Trigger. |
Move your `Right` pointer. If `arr[Right] == arr[Right-1]`, increment your "Double Count". If the count exceeds 1, move your `Left` pointer forward until the count drops back to 1. |
Draw an array. Use two fingers (L and R). Move R right. When you see two identical numbers together, write "Doubles: 1". Move R again. If you see another double, move L until one double is "pushed out" of the window. |
Amortized Linear Timeline. |
Draw a single line for the array. Show the L and R pointers only moving forward, never backward. Write $O(2N)$ ≈ $O(N)$. |
N^2 memory allocations if storing subarrays as separate strings. |
Two integer pointers and one "duplicate_counter" variable. Space $O(1)$. |
| 3642 |
Find Books with Polarized Opinions (Med) |
For every book, count 5-star reviews and 1-star reviews. If the difference or ratio exceeds a threshold, mark it. $O(\text{Books} \\text{cdot Reviews})$. |
Nested Loop Aggregation. |
Draw a list of Books. For each book, draw an arrow to a massive list of Reviews to filter by BookID. Repeat. Write $O(B \cdot R)$. |
Hash Map Aggregation / SQL Group By with HAVING clause. Compute statistics for all books in one pass. |
Review Sorting Funnel. |
Pour all reviews into a funnel. The funnel sorts them into bins based on `BookID`. Once the bin for "Book A" is full, calculate its polarization instantly. |
Draw a box for each Book. Read through the review list once. Drop a tally mark in the corresponding Book box for either "1-star" or "5-star". Calculate final ratios from the tallies. |
Linear Scan Pipeline. |
Draw one arrow for "Scan Reviews $O(R)$". Draw one arrow for "Filter Books $O(B)$". Total $O(R + B)$. |
Creating temporary filtered lists for every single book evaluation. |
A Hash Map where Keys are book_id and Values are [count1, count5]. Space $O(\text{Unique}_\text{Books})$. |
| 3643 |
Flip Square Submatrix Vertically (Easy) |
Creating a completely new matrix, copying the submatrix into it in reverse order, then copying it back into the original. |
Matrix Copy Overlay. |
Draw Matrix A. Draw an empty Matrix B. Draw arrows copying row 5 of A into row 1 of B. Then copy B back into A. Space $O(N^2)$. |
In-place row swapping within the specified submatrix boundaries. |
Mirror Image Reflection. |
Identify the top row and bottom row of the submatrix. Swap them. Move to the next inner pair of rows. Stop at the middle. |
Draw a 4x4 square inside a larger grid. Draw a horizontal "mirror line" in the center of that square. Draw arrows showing row 1 and row 4 of that square swapping places. |
Sub-area Scan Chart. |
Draw a square of size K by K. Show that only K/2 swaps are made. Write $O(K^2)$. |
Allocating an entirely new 2D array for the flip. |
Standard temp variable for in-place value swapping. Space $O(1)$. |
| 3644 |
Maximum K to Sort a Permutation (Med) |
Try every value of K from 1 to N. For each K, simulate the sorting process to see if it works. $O(N^2)$. |
Linear Search Simulation. |
Draw a number line for K. For K=1, run sort. For K=2, run sort. If N is 100,000, this takes 10 billion operations. Write "Time Limit Exceeded". |
Greatest Common Divisor (GCD) of the displacements. Find the distance each element needs to move and find the GCD of all those distances. |
Synchronization of Gears. |
Imagine elements are on gears of size K. For all elements to reach their home at once, K must be a divisor of the distance between `current_index` and `target_index` for every single element. |
Draw an array. Point to '5' at index 2. Its home is index 8. Distance = 6. Point to '3' at index 0. Its home is index 9. Distance = 9. Find GCD(6, 9) = 3. Final K = 3. |
GCD Reduction Line. |
Draw a linear scan (O(N)). At each step, update a single `current_gcd` variable. Write $O(N + \log(\text{Max}_\text{Distance})$). |
Large arrays storing the intermediate states of the simulation for every K. |
A single integer variable ans_gcd. Space $O(1)$. |
| 3645 |
Maximum Total from Optimal Activation Order (Med) |
Try every permutation of activation (N!) to find the one that yields the maximum sum. |
Factorial Decision Tree. |
Start with node 1. Branch to all others. The tree height is N. Total leaves are N!. Write "Impossible to compute". |
Greedy Algorithm with a Max-Priority Queue. At any step, activate the item that provides the highest immediate gain/value based on current state. |
Highest-Value-First Plucking. |
Treat items like fruit on a tree. Some fruit get riper over time; some rot. Always pluck the one that currently has the highest "Value/Cost" ratio. |
Draw a list of items with values. Put them in a "Priority Queue" (a funnel that always puts the largest on top). Pull the top item, update world state, repeat. |
Heap-Based Sorting. |
Draw a bar for "N insertions into Heap" (O(N log N)). Draw a bar for "N extractions" (O(N log N)). Total $O(N \log N)$. |
Storing all permutations in a giant list to compare them. |
A Max-Heap (Binary Tree) structure. Space $O(N)$. |
| 3646 |
Next Special Palindrome Number (Hard) |
Iterate through every integer starting from N+1, checking isPalindrome() and then checking "Special" digit rules one by one. $O(\text{Result} - N)$. |
Infinite Number Line Scan. |
Draw a number line. Start at N. Step by 1... step by 1... for every single number, check all rules. If the next palindrome is 10 million away, the program times out. |
Mirroring + Middle-Digit Increment. Construct the palindrome from the first half of N, then adjust based on "Special" digit constraints. |
Butterfly Fold Construction. |
Take the first half of the digits of N. Mirror them to create a palindrome. If this is smaller than N or violates special rules, increment the middle digit and re-mirror. |
Draw a number (e.g., 12345). Draw a vertical dashed line in the middle. "Fold" the left side (12) onto the right side to get 12321. Adjust the '3' if needed. |
Logarithmic Construction Map. |
Draw an arrow to the "Half-Length" of the number. Write $O(\log10 N)$. It takes constant time to construct the number regardless of distance. |
Millions of integer-to-string conversions filling the heap with temporary objects. |
A small array of digits (size ~10-20). Space $O(\log N)$. |
| 3647 |
Maximum Weight in Two Bags (Med) |
Try every possible way to partition N items into two bags (Bag A, Bag B, or Discard). $O(3^N)$. |
Trinary Decision Tree. |
Start at Item 1. Branch 3 ways: Bag A, Bag B, Trash. For each child, branch 3 times again. Total leaves: 3^N. Write "Exponential Failure". |
Dynamic Programming (Knapsack variant) or Meet-in-the-Middle if N is around 30-40. |
Two-Half Combination Matrix. |
Split the items into two halves (N/2). Find all possible weight sums for Half 1. Find all for Half 2. Use a two-pointer scan or Hash Map to pair them such that the total is maximized. |
Draw two lists of possible sums. Sort both. Use a finger on each list to find pairs that sum as close to the "Weight Limit" as possible without exceeding it. |
Polynomial Complexity Chart. |
Draw two blocks for $O(3^(N/2)$). Draw an arrow for the "Combine/Sort" step $O(M \log M)$. Write $O(3^(N/2)$) to show it’s much faster than 3^N. |
A recursion stack reaching depth N and millions of redundant state checks. |
A 2D DP table `dp[item_index][current_weight]` or two Hash Sets for Meet-in-the-Middle. Space $O(\text{Max}_\text{Weight})$. |
| 3648 |
Minimum Sensors to Cover Grid (Med) |
Exhaustive Search / Backtracking: Try placing a sensor in every possible cell combination to see if the whole grid is covered. $O(2^(R\cdot C)$). |
Grid Permutation Explosion. |
Draw a grid. Pick a few cells for sensors. Check coverage. Erase and try a different combination. There are billions of combinations for a 10x10 grid. |
Greedy with Set Cover or Bitmask DP (if dimensions are small). Focus on covering the "bottleneck" (uncovered cells with the fewest neighbors). |
Light-Bulb Illumination Map. |
Treat sensors like light bulbs with a specific radius. At each step, identify the "darkest" (uncovered) cell and place a sensor at the location that illuminates the most dark cells. |
Draw a grid. Shade cells that need coverage. Pick a sensor location, draw its "light" area. Subtract those from the "dark" total. Repeat until no shaded cells remain. |
State-Space Reduction Line. |
Write $O(R \cdot C \cdot (\text{Number of Sensors})$). Draw a grid where each sensor "removes" a chunk of work in one go. |
Massive recursive tree of grid states being stored in a list. |
A bitmask (integer) representing covered vs uncovered cells. Space $O(1)$ per state. |
| 3649 |
Number of Perfect Pairs (Med) |
Nested loops comparing every pair (arr[i], arr[j]) to check if they satisfy the "Perfect" math property (e.g., |a-b| <= min(a, b)). $O(N^2)$. |
Double Loop Intersection. |
Draw an array. For index 0, check every other index. For index 1, check every other index. Write $O(N^2)$. |
Algebraic Simplification + Binary Search / Fenwick Tree. Re-write the property as a range: arr[j] must be in [arr[i]/2, 2*arr[i]]. |
Sorted Range Sliding. |
Sort the array. For each number x, you now just need to find how many numbers in the sorted list fall between x/2 and 2x. This is two simple binary searches. |
Draw a sorted number line. Mark x. Draw a bracket from x/2 to 2x. Count the dots inside the bracket using bisect_right - bisect_left. |
Sorting + N Binary Searches. |
Draw a block for "Sort $O(N \log N)$". Draw a line with N dots, each with a small "Search $O(\log N)$" overhead. Total $O(N \log N)$. |
A massive list of all valid pairs found before counting them. |
In-place sorted array. Space $O(1)$ or $O(N)$. |
| 3650 |
Minimum Cost Path with Edge Reversals (Med) |
Standard BFS/Dijkstra that fails because it doesn't account for the cost of "flipping" an edge to go the wrong way. |
Disconnected Component Island. |
Draw a graph. If the destination isn't reachable via directed edges, BFS says "Cost: Infinity". This is the brute force failure. |
0-1 BFS or Dijkstra's Algorithm on a modified graph where every directed edge (u -> v) with weight 0 has a "ghost" edge (v -> u) with weight 1. |
Ghost Edge Overlay. |
Visualize the graph where every one-way street has a hidden "reverse" lane that costs 1 toll to enter. Now, just find the shortest path from start to end using Dijkstra. |
Draw a graph with solid arrows (cost 0). Draw dotted arrows in the reverse direction (cost 1). Use a Deque: push 0-cost edges to the front, 1-cost to the back. |
Weighted BFS Timeline. |
Write $O(V + E)$. Draw a queue where 0-cost nodes are processed instantly, and 1-cost nodes wait their turn. Total time is linear. |
Adjacency matrix (O(V^2)) taking up massive space for sparse graphs. |
Adjacency list with pairs (neighbor, weight). Space $O(V + E)$. |
| 3651 |
Minimum Cost Path with Teleportations (Hard) |
Standard Dijkstra's ignoring teleportation rules or treating every teleport as a standard edge (causing $O(V^2)$ edges if everyone can teleport to everyone). |
Dense Spaghetti Graph. |
Draw nodes. Draw lines from EVERY node to EVERY other node to represent teleport possibilities. The paper is solid black ink. $O(V^2)$. |
Dijkstra + Auxiliary "Teleport Hub" nodes. Instead of V \times V edges, connect all nodes to one "Hub" with specific entry/exit costs. |
Star-Network Hub/Spoke. |
Visualize a central "Warp Zone" node. Every city has a one-way road *into* the Warp Zone and a one-way road *out*. This reduces N^2 edges to 2N edges. |
Draw 5 nodes in a circle. Draw one big node in the center. Draw arrows from outer nodes to the center (Cost X) and from center to outer (Cost Y). Run Dijkstra. |
Linearized Edge Chart. |
Draw V nodes and E edges. Show that adding the hub node only adds V more edges. Total time $O((E+V)$ \log V). |
A massive adjacency matrix taking $O(V^2)$ space to store every possible jump. |
Adjacency list including the auxiliary hub node. Space $O(V+E)$. |
| 3652 |
Best Time to Buy and Sell Stock using Strategy (Med) |
Recursive backtracking: For every day, try "Buy", "Sell", or "Skip". $O(2^N)$. |
Binary Decision Tree. |
Day 1: Buy or Skip. Day 2: (if bought) Sell or Skip. The tree branches exponentially. Write "Stack Overflow" for N > 30. |
Dynamic Programming / State Machine. State = `(Day, HasStock)`. Use a simple greedy one-pass if unlimited trades are allowed. |
Mountain Range Valley-Peak. |
Visualize the stock prices as a mountain range. Every time the price goes up from yesterday to today, "capture" that slope. Ignore the dips. |
Draw a line graph. Whenever the line goes up, draw a vertical green arrow representing profit. Total profit = sum of all green arrows. |
Single Linear Pass. |
Draw one arrow sweeping across the price array from left to right. $O(N)$. |
Storing every possible profit path in a list to find the max. |
Two variables: `max_profit` and `min_price_so_far`. Space $O(1)$. |
| 3653 |
XOR After Range Multiplication Queries I (Med) |
For every query `(L, R, factor)`, loop from L to R, multiply each element, then loop again to calculate the total XOR. $O(Q \\text{times} N)$. |
Redundant Subarray Scans. |
Draw an array. Draw a bracket for each query. Inside, draw arrows hitting every element to multiply, then again to XOR. Write $O(10^5 \\text{times} 10^5)$ = 10^{10} ops. |
Segment Tree or Fenwick Tree with Lazy Propagation. Store XOR values in nodes and apply multiplications as "Lazy" updates. |
Segment Tree Node Splitting. |
Visualize a tree where the root covers the whole array. To multiply a range, find the largest "blocks" that fit and update them once. The change "trickles down" only when needed. |
Draw a binary tree over an array. Circle the nodes that cover range [L, R]. Write "\times K" next to them. If a node is XOR of its children, update it in $O(1)$. |
Tree Depth Bounding. |
Draw a height-balanced tree. Show that any range query only touches 2 \times \log N nodes. Total $O(Q \log N)$. |
Creating new modified copies of the array for every query. |
A 1D array of size 4N for the Segment Tree and another 4N for the Lazy array. Space $O(N)$. |
| 3654 |
Minimum Sum After Divisible Sum Deletions (Med) |
Try deleting every possible subset of the array, checking if the sum of deleted elements is divisible by K, then finding the min remaining sum. $O(2^N)$. |
Power Set Explosion. |
Draw the array. List every possible combination of removals. [1,2], [1,3], [1,2,3]... For N=100, this is 2^{100} combinations. Paper catches fire. |
Dynamic Programming (Remainder DP). State = `dp[i][remainder]`. Find the maximum sum we can delete that leaves a remainder of R. |
Modulo Bucket Filling. |
Imagine K buckets labeled 0 to K-1. For each number, decide: "Do I add this to a bucket's sum?" Update the buckets based on the new remainder. |
Draw a table with columns 0, 1, ..., K-1. As you process numbers, update the "Max Sum" for each column. Final answer = Total Sum - `dp[N][0]`. |
N \times K Grid Scan. |
Draw a grid of size N (items) by K (remainders). Each cell is visited once. Total $O(N \\text{times} K)$. |
Storing all valid subsets in a massive nested list. |
A 1D array of size K (storing max sums for each remainder). Space $O(K)$. |
| 3655 |
XOR After Range Multiplication Queries II (Hard) |
Same as Part I, but with a massive K or dynamic modulo properties that break standard Lazy Propagation. |
Segment Tree Overflow. |
Draw the Segment Tree from 3653. Now imagine the numbers are so large they exceed 64-bit integers, or the XOR property doesn't distribute over multiplication. |
Segment Tree where each node stores a "Bit Count" array (size 32 or 64). Multiplication by a power of 2 becomes a "Bit Shift" on the array. |
Bit-Plane Layers. |
Think of the array as 32 separate layers (one for each bit). Multiplication affects these layers in predictable ways (shifting or flipping). Treat each bit independently. |
Draw 32 Segment Trees stacked vertically. When a range is multiplied by 2, show bit 0 moving to bit 1, bit 1 to bit 2, etc. across the whole range. |
Bitwise-Multiplied Tree Depth. |
Write $O(32 \\text{times} Q \log N)$. Show that we are doing standard Segment Tree work, just repeated for each bit. |
Storing massive BigInts in every node of the tree. |
A 2D array or 1D array with bit-packing: `tree[node][bit_pos]`. Space $O(N \\text{times} 32)$. |
| 3656 |
Determine if a Simple Graph Exists (Med) |
Backtracking to try and draw every possible edge combination to see if you can satisfy the given degree sequence. $O(2^{V^2})$. |
Adjacency Matrix Permutations. |
Draw V dots. Try connecting them in every possible way while counting the lines attached to each dot. The combinations for just 10 dots are astronomical. |
Havel-Hakimi Algorithm. Sort the degree sequence, then repeatedly "consume" the highest degree by connecting it to the next highest degrees. |
The Greedy "Haircut" Technique. |
Take the highest number D from the list. Remove it, and subtract 1 from the next D numbers in the list. If any number becomes negative, the graph is impossible. |
List degrees: [3, 3, 2, 2]. Remove 3, subtract 1 from next 3: becomes [2, 1, 1]. Repeat until the list is all zeros (Success) or impossible (Fail). |
Sorting-Based Reduction Chart. |
Write $O(V^2 \log V)$ or $O(V^2)$ with bucket sort. Each step reduces the sum of degrees linearly. |
A massive recursion tree storing partial adjacency matrices. |
A single 1D array of integers representing the degree sequence. Space $O(V)$. |
| 3657 |
Find Loyal Customers (Med) |
Triple-nested loop: For every customer, for every transaction, check if there is a transaction in every single month of the year. $O(C \\text{times} T)$. |
Matrix Intersection Scan. |
Draw a table with Customers as rows and Months as columns. For every transaction, find the cell and put a checkmark. Scan every row to see if it has 12 checks. |
Hash Set Aggregation. For each customer, collect `transaction_month` into a Set. Filter customers where `Set.size == 12`. |
Monthly Bucket Check. |
Visualize 12 physical buckets for each customer. Every time they buy something, drop a token into that month's bucket. At the end, count how many customers have no empty buckets. |
Draw a customer ID. Next to it, draw 12 tiny boxes. As you read the logs, fill the boxes. If all are full, circle the ID. |
Linear Pass with Filtering. |
Draw one arrow scanning the Transaction table $O(T)$. Draw a second arrow scanning the Customer Summary $O(C)$. Total $O(T + C)$. |
Creating separate transaction lists for every single customer-month pair. |
A Hash Map where Keys are `customer_id` and Values are bitmasks (12 bits) representing months. Space $O(\text{Unique}\_\text{Customers})$. |
| 3658 |
GCD of Odd and Even Sums (Easy) |
Iterate through the array, calculate odd sum and even sum separately, then use a loop to find the GCD starting from the smaller sum downwards. |
Linear GCD Search. |
Calculate Sums (e.g., 20 and 30). Try dividing both by 20, then 19, then 18... until you hit 10. $O(\text{Sum})$. |
Euclidean Algorithm for GCD. `gcd(a, b)` where you repeatedly take the remainder until one reaches zero. |
The Rectangle Folding (Euclidean). |
Visualize a rectangle of A \times B. Cut out the largest possible square. Repeat with the remaining rectangle. The size of the final square is the GCD. |
Draw two bars (SumOdd, SumEven). Use the Euclidean subtraction: `while b: a, b = b, a % b`. Write the steps: `30 % 20 = 10`, `20 % 10 = 0`. GCD is 10. |
Logarithmic Reduction Line. |
Draw an arrow representing the values shrinking by half at each step. $O(N + \log(\\text{min}(\text{SumOdd}, \text{SumEven})$)). |
Converting sums to strings or large objects unnecessarily. |
Three integer variables: `sum_odd`, `sum_even`, and `temp`. Space $O(1)$. |
| 3659 |
Partition Array Into K-Distinct Groups (Med) |
Backtracking to try every possible way to group elements while maintaining the distinctness property. $O(K^N)$. |
Recursive Partition Tree. |
Draw the array. Try putting element 1 in Group A. Then element 2 in Group A or B. If A already has element 2, you must pick B. The branches explode. |
Greedy Frequency Distribution. Sort elements by frequency. Place the most frequent elements into different groups first. |
The "Card Dealing" Strategy. |
Imagine you have K hands. If you have four "7"s, you MUST deal them into four different hands. If any number's frequency > K, it's impossible. |
Draw K boxes. Count frequencies: `3: [7, 7, 7], 2: [5, 5]`. Put one '7' in Box 1, one in Box 2, one in Box 3. Put '5' in Box 1 and Box 2. |
Frequency Mapping Pass. |
Draw an arrow for counting frequencies $O(N)$. Draw a check for `max(freq) <= K. Write $O(N)$. |
Storing every failed grouping attempt in a list. |
A Hash Map of frequencies and K lists for groups. Space $O(N)$. |
| 3660 |
Jump Game IX (Med) |
For every index i, scan all j > i to find valid jumps, then run a standard BFS. $O(N^2)$. |
Oversaturated Jump Arcs. |
Draw an array. For index 0, draw arcs to every single index that is larger or smaller. The graph becomes too dense to process for large N. |
Monotonic Stack to find the next/previous greater/smaller elements in $O(N)$, then Dijkstra/DP on those specific edges. |
Specific Target Radar. |
Instead of looking everywhere, your "radar" only locks onto the very next element that is taller than you or the very next that is shorter. These are your only valid "efficient" jumps. |
Draw an array of heights. Use a stack to find the "Next Greater" index for each. Draw only ONE jump arrow from i to its Next Greater. Repeat for Next Smaller. |
Linear Edge Construction. |
Show that each node now has at most a constant number of outgoing edges (e.g., 2-4). Total time $O(N \log N)$ or $O(N)$ with DP. |
A full adjacency matrix for all possible jumps. |
A 1D DP array and two monotonic stacks. Space $O(N)$. |
| 3661 |
Maximum Walls Destroyed by Robots (Hard) |
Iterate through every possible path for every robot, checking every wall combination. $O(2^R x C x \text{Paths})$. |
Path-Wall Intersection Matrix. |
Draw a grid with robots. Draw lines representing paths. Try every single possible "toggle" for every robot (on/off) to see which combo breaks the most walls. $O(2^N)$ is too slow. |
Maximum Flow / Bipartite Matching. Model robots as one set of nodes, walls as another, and find the maximum matching/coverage. |
The "Power Grid" Flow Map. |
Imagine water flowing from a Source to Robots, through the Walls they can hit, into a Sink. The "capacity" of the pipes determines the maximum destruction. |
Draw a "Source" node. Connect it to Robots. Connect Robots to the Walls they can destroy. Connect Walls to a "Sink". The max flow value is your answer. |
Max-Flow Min-Cut Chart. |
Write the complexity of Dinic's algorithm or Edmonds-Karp: $O(V^2 E)$ or $O(\text{VE}^2)$. In a grid, V and E are proportional to R x C. |
A massive recursion stack for backtracking through every robot's decision tree. |
A flow network residual graph (Adjacency List with capacities). Space $O(V+E)$. |
| 3662 |
Filter Characters by Frequency (Easy) |
For every character in the string, loop through the entire string again to count its occurrences. $O(N^2)$. |
Nested Loop Scanning. |
Draw a string "APPLE". Point to 'P'. Scan the whole string to count 'P's (2). Point to 'L'. Scan the whole string to count 'L's (1). Repeat for all. |
Single-pass Hash Map / Frequency Array. Count all frequencies first, then perform a single pass to filter. |
The "Sorting Bin" Counter. |
Visualize 26 bins labeled A-Z. Walk through the string once, dropping a pebble in the corresponding bin for each letter. Then, check the bins. |
Draw 26 small boxes. As you read the string, put a tally mark in the box. Then, read the string again and only write characters whose box has a count > K. |
Two-Pass Linear Line. |
Draw one arrow for "Count $O(N)$" and a second for "Filter $O(N)$". Total $O(N)$. |
Creating new substrings or arrays inside the nested loop, leading to $O(N^2)$ space. |
A single fixed-size array of length 26 or 256. Space $O(1)$. |
| 3663 |
Find The Least Frequent Digit (Easy) |
Convert the number to a string, then perform nested loops to count each digit 0-9. |
Digit-by-Digit Comparator. |
Write the number. For digit '0', count how many appear. For digit '1', count how many. Compare the 10 totals to find the minimum. |
Modulo-based Frequency Array. Use `n % 10` to strip digits and an array of size 10 to store counts. |
The "10-Slot Tally Board". |
Visualize a board with slots 0 to 9. Strip the last digit of the number, put a tally in its slot, and discard it. Repeat until the number is gone. |
Draw 10 slots. Take `1223`. `3` goes to Slot 3. `2` to Slot 2. `2` to Slot 2. `1` to Slot 1. Slot 1 and 3 are tied for least frequent. |
Digit-Logarithmic Pass. |
Draw one arrow representing the number of digits. $O(\log_10 N)$. |
Allocating a large string object for a very large integer. |
An array of 10 integers. Space $O(1)$. |
| 3664 |
Two-Letter Card Game (Med) |
Simulate every possible turn and every possible card combination to find the winning strategy. $O(N^2)$. |
Game-State Decision Tree. |
Draw two hands of cards. Branch out: "If I play card A, what can they play?" "If I play card B..." The tree depth is the number of cards. |
Greedy Sorting / Hash Map counting. Pair cards based on their first and second letters to maximize your "counter-plays". |
Matching Letter Hubs. |
Think of cards as "connectors". A card 'AB' can only be played after a card ending in 'A'. Group cards by their starting and ending letters. |
Draw 26 nodes (letters). Draw an arrow for each card (e.g., 'AB' is an arrow from A to B). The game is about finding paths or cycles in this letter graph. |
Graph Traversal / Map Lookup. |
Write $O(N + 26^2)$. N to build the graph, then a constant time to check the 26x26 letter combinations. |
Storing every possible sequence of cards played in a list. |
A 2D array `counts[26][26]` representing all possible two-letter combinations. Space $O(1)$ relative to N. |
| 3665 |
Twisted Mirror Path Count (Med) |
Recursively trace every possible light beam path, branching at every mirror. $O(2^\text{Mirrors})$. |
Exponential Ray Tracing. |
Draw a grid with mirrors. One beam hits a mirror and splits/reflects. Each split beam hits another mirror and splits again. The number of active rays explodes. |
Dynamic Programming / BFS with State. State = `(row, col, direction)`. Since the path is "twisted", we track our entering vector. |
The "Room-and-Door" Navigator. |
Imagine entering a room. Depending on which door you used (direction) and the furniture (mirror), there is only one exit door. Map these transitions. |
Draw a grid. In each cell, draw 4 "ports" (N, S, E, W). Use a arrow to show how entering North reflects out East due to a '/' mirror. Mark cells as "visited" for that specific direction. |
Bounded State-Space Scan. |
Draw a grid of size R x C. Show that for each cell, there are only 4 directions. Total states = 4 x R x C. Write $O(R x C)$. |
Infinite recursion frames for circular light paths. |
A 3D boolean array `visited[R][C][4]`. Space $O(R x C)$. |
| 3666 |
Minimum Operations to Equalize Binary String (Hard) |
Trying every possible bit-flip combination using BFS/Recursion to reach a target string. $O(2^N)$. |
Exponential Bit-Flip Tree. |
Draw a binary string. Branch out by flipping index 0, then 1, etc. For a string of length 20, the tree has 1 million leaves. $O(2^N)$ is unusable. |
Greedy "Flip-and-Carry" or Difference Array. Start from the left; if the current bit doesn't match the target, flip the remainder of the string. |
The "Wavefront" Flip. |
Imagine a light switch. Flipping it affects everything to the right. Instead of actually flipping bits, keep a flip_count. Current state = (original + flip_count) % 2. |
Draw the string. Sweep left to right. When you hit a mismatch, increment a "Flip Counter" and move on. The counter tells you the "current" reality of the remaining bits. |
Linear Scan with State Variable. |
Draw one arrow scanning the string once. $O(N)$. |
Generating N new string copies, one for each flip operation. |
A single integer total_flips and current_bit_state. Space $O(1)$. |
| 3667 |
Sort Array By Absolute Value (Easy) |
Implementing a manual sorting algorithm like Selection Sort that compares absolute values. $O(N^2)$. |
Nested Comparison Grid. |
Draw an array. Compare abs(arr[0]) with everyone else. Repeat for abs(arr[1]). Write $O(N^2)$. |
Language-native sort with a Custom Key/Comparator. |
The "Magnetized" Number Line. |
Visualize a number line with a magnet at zero. All numbers (positive and negative) are pulled toward the center. Their distance from zero determines their order. |
Draw 0 in the center. Place -5 and 3. Since 3 is closer to 0 than -5 is, it comes first in the sorted absolute list. Order: [3, -5]. |
N log N Sorting Block. |
Draw a standard $O(N \log N)$ sorting flowchart with a custom key abs(x). |
Allocating a completely new array of absolute values just to sort them. |
In-place sorting using the original array. Space $O(1)$ (ignoring recursion stack). |
| 3668 |
Restore Finishing Order (Easy) |
Sorting the participants and then searching for their IDs one by one in the original messy logs. $O(N^2)$. |
Scan-and-Find Loops. |
Draw a list of results. For the 1st place finisher, scan the whole original log to find their entry. For the 2nd place, scan again. |
Hash Map (ID to Rank) or Tuple Sorting. Store (Time, ID) pairs and sort them directly. |
The "Leaderboard" Sort. |
Think of a race where everyone has a stopwatch. At the finish line, you just stack their stopwatches in order. The ID on the stopwatch tells you who won. |
Draw a table with two columns: Time and ID. Sort by the Time column. Read the ID column top to bottom. |
Linear Map + N log N Sort. |
Draw one arrow to build the tuples $O(N)$, then the sort $O(N \log N)$. Total $O(N \log N)$. |
Multiple nested loops or temporary filtered lists. |
An array of Tuples/Pairs. Space $O(N)$. |
| 3669 |
Balanced K-Factor Decomposition (Med) |
Trial division: Iterate from 1 to N to find all factors, then try all combinations of K factors to see if they are "balanced". $O(N)$. |
Linear Factor Search. |
Start at 1, divide N by 1, 2, 3... all the way to N. If N = 10^9, this is 1 billion operations. |
Square Root Factorization + Dynamic Programming. Only check up to √N to find all factors, then use DP to find balanced subsets. |
The "Factor Pairs" Mirror. |
If 2 is a factor of 100, then 100/2 = 50 is also a factor. Every factor has a partner on the other side of √N. |
Draw a line. Put √N in the middle. Find factors on the left. For each, draw an arc to its "partner" on the right. This finds all factors in $O(√N)$. |
Sub-linear Factorization. |
Draw an arrow that stops at the halfway point √N. Write $O(√N + \text{DP}_\text{time})$. |
Storing every single number from 1 to N to check if they are factors. |
A list of factors found. Since the number of factors is small (relative to N), space is $O(\text{factors})$. |
| 3670 |
Maximum Product of Two Integers With No Common Bits (Med) |
Nested loops comparing every pair (i, j) and using (arr[i] & arr[j]) == 0 to check for common bits. $O(N^2)$. |
Double-Pass Bitwise Grid. |
Draw an array of N numbers. For each number, bitwise AND it with every other number. If N=10^5, this is 10 billion checks. |
Hash Map of Bitmasks. For each unique bitmask, store the maximum integer found. Then compare all pairs of bitmasks. |
The "Bitmask Bucket" Compare. |
Group numbers by their "bit pattern" (e.g., all numbers that have bits 1 and 3 set). Since there are only 2^32 (or fewer in practice) possible masks, we only compare the best representative of each mask. |
Draw 32 bins. Drop numbers into bins based on their binary pattern. Compare Bin A and Bin B. If (BinA_mask & BinB_mask) == 0, multiply their max values. |
Mask-Space Interaction Chart. |
Write $O(N + M^2)$ where M is the number of *unique* bitmasks. Usually M ll N. |
A full N x N matrix of bitwise results. |
A Hash Map where Keys are bitmask and Values are max_val. Space $O(2^\text{bits})$. |
| 3671 |
Sum of Beautiful Subsequences (Hard) |
Generate every possible subsequence (2^N) and check if each one is "beautiful" by verifying every pair of elements. $O(N \cdot 2^N)$. |
Subsequence Branching Tree. |
Draw an array. At each element, branch "Include" or "Exclude". For N=30, you have 1 billion leaves. Paper is completely filled with failed paths. |
Dynamic Programming with Counting (Combinatorics). Group elements by their remainder when divided by the "beauty" difference K, then solve as a "House Robber" variant. |
Modulo-Grouped Independent Chains. |
If beauty depends on the difference K, a number X only affects X+K or X-K. Split the array into chains (e.g., if K=3: [1, 4, 7...], [2, 5, 8...]). Solve each chain independently and multiply. |
Draw circles for numbers. Draw lines between numbers that "conflict" (e.g., distance K). This creates several separate paths. Calculate valid subsets for each path using DP and multiply results. |
Multi-chain DP Chart. |
Write $O(N \log N)$ to sort, then $O(N)$ to process the chains. Total $O(N \log N)$. |
A massive recursive stack attempting to hold all 2^N combinations in memory. |
A small DP array `dp[2]` or `dp[i]` for the current chain being processed. Space $O(N)$. |
| 3672 |
Sum of Weighted Modes in Subarrays (Med) |
Nested loops to find every subarray (i, j), then another loop/map to find the mode (most frequent element) and its weight. $O(N^3)$. |
Subarray Mode Exhaustion. |
Draw the array. For every bracket [i, j], create a frequency map, find the highest count, and add it to the total. 10^15 operations for large N. |
Frequency Tracking with Contribution Counting. For each element, mathematically calculate how many subarrays it serves as the mode. |
Element Contribution Wavefront. |
Instead of looking at subarrays, look at an element X. When is it the king (mode)? It stays the mode until another element's frequency exceeds its own. Track its "reign" using a sliding window. |
Draw an array. Highlight all "5"s. Draw boundaries showing the largest area where "5" remains the most frequent (or tied). Use precomputed index lists for each number. |
Amortized Frequency Map Scan. |
Write $O(N √N)$ or $O(N)$ with advanced frequency buckets. Draw a timeline showing each index being processed a constant number of times. |
Creating millions of temporary frequency maps (HashMaps) in memory. |
A global frequency map and a "frequency of frequencies" counter. Space $O(N)$. |
| 3673 |
Find Zombie Sessions (Hard) |
Running a full BFS from every single node to find all connected components (zombie clusters) repeatedly for every session. $O(S \cdot (V+E)$). |
Repeated Graph Traversal. |
Draw a graph. Color a cluster. If a new edge appears, erase all colors and re-run BFS to find the new clusters. Repeat S times. |
Disjoint Set Union (DSU) with Path Compression. For every session connection, union the two nodes and decrement the total cluster count. |
The "Blob Merger" Animation. |
Start with N isolated dots. For every "zombie session" connection (A, B), draw a circle around them. If they are already in the same circle, do nothing. If not, merge their circles. |
Draw two 1D arrays: `parent` and `size`. When A and B connect, point A's root to B's root. Show the "Component Count" variable dropping by 1. |
Nearly-Linear DSU Chart. |
Write $O(S \\text{cdot alpha}(V)$) where alpha is the inverse Ackermann function (effectively a constant). This is vastly faster than BFS. |
Building new Adjacency Lists from scratch for every session. |
A single `parent` array of size N. Space $O(V)$. |
| 3674 |
Minimum Operations to Equalize Array (Easy) |
Trying to change every element to a specific target value, iterating through all possible target values (min to max). $O(N \\text{cdot Range})$. |
Target Value Brute Force. |
Draw an array: [1, 5, 10]. Try making them all 1. Calculate cost. Try making them all 2. Repeat until 10. If the range is 1 billion, it fails. |
Median-Based Greedy approach. The total cost is minimized when all elements are changed to the median of the array. |
The "Central Gravity" Point. |
Imagine the numbers as houses on a street. You want to build a post office. To minimize everyone's walking distance, you should put it exactly at the middle house (the median). |
Sort the array. Pick the middle element. Calculate `abs(arr[i] - median)` for every element and sum them up. |
Sorting-Bounded Line. |
Draw an $O(N \log N)$ sort block followed by a single $O(N)$ summation pass. Total $O(N \log N)$. |
Allocating a 2D matrix to store costs for every possible target value. |
A single sorted copy of the input array. Space $O(1)$ or $O(N)$ depending on sort. |
| 3675 |
Minimum Operations to Transform String (Med) |
Breadth-First Search (BFS) on all possible string transformations to find the shortest path from A to B. $O(2^N)$. |
State-Space String Tree. |
Start with String A. Draw arrows to every string you can reach in 1 move. From those, draw more arrows. The number of strings explodes. |
Two-Pointer Greedy Scan or Edit Distance variant. If only specific operations are allowed (like moving to front), focus on the "Longest Matching Suffix". |
The "Solid Foundation" Suffix. |
Look at the end of both strings. How many characters already match in order? These don't need to be moved. Everything else must be "plucked" and rearranged. |
Draw String A and String B. Place pointer `i` at the end of A and `j` at the end of B. If `A[i] == B[j]`, move both left. If not, only move `i` left. The remaining `j` count is the number of moves. |
Linear Reverse Scan. |
Draw one arrow scanning from Right to Left once. $O(N)$. |
A massive `visited` set in BFS storing every string permutation. |
Two pointers and a few character variables. Space $O(1)$. |
| 3676 |
Count Bowl Subarrays (Med) |
Generate every possible subarray (O(N^2)) and for each, check if the elements decrease then increase (the "bowl" shape) in $O(N)$. Total $O(N^3)$. |
Nested Array Scan. |
Draw an array. Draw a bracket for every possible [L, R]. Inside, check if numbers go down then up. With N=10,000, this is 100 billion checks. |
Precompute "Longest Decreasing" from left and "Longest Increasing" from right for every index. |
The "V-Shape" Intersection. |
Think of every index as the potential "bottom" of a bowl. A bowl at index i can extend left as far as numbers are increasing towards the left, and right as far as they increase towards the right. |
Draw an array. For each index, write two numbers: `L` (how many smaller items to the left) and `R` (how many smaller items to the right). Total bowls = sum of `L * R` for all i. |
Linear Precomputation Pass. |
Draw one arrow for Left-pass (O(N)), one for Right-pass (O(N)), and one for the final Sum (O(N)). Total $O(N)$. |
Allocating N^2 sub-arrays in memory for validation. |
Two 1D arrays of size N. Space $O(N)$. |
| 3677 |
Count Binary Palindromic Numbers (Hard) |
Iterate from 1 to N, convert each to a binary string, and check if it reads the same forwards and backwards. $O(N \log N)$. |
Binary String Brute Force. |
Draw a number line. For each number, write its binary form. 5 -> 101 (Yes), 6 -> 110 (No). For N=10^12, this takes centuries. |
Combinatorial Construction. Generate palindromes directly by mirroring the "first half" of the binary bits. |
The "Binary Mirror" Fold. |
A binary palindrome of length 5 is always 1_ _ _1. Since the first bit must be 1, you only have 2 free bits to choose (the middle). Total = 2^( (L-1)/2 ). |
Draw bit slots: [1][ ][ ][ ][1]. Note that the middle bits can be any combination. Use a loop to count combinations for each possible bit-length up to N. |
Logarithmic Length Summation. |
Draw an arrow representing the number of bits in N (e.g., 64). Write $O(\log N)$. You only calculate one formula per bit-length. |
Massive string objects created for every single integer up to N. |
A few integer variables for bit-math. Space $O(1)$. |
| 3678 |
Smallest Absent Positive Greater Than Average (Easy) |
Calculate average, then start from ceil(avg) + 1 and check if each number exists in the array using a linear scan. $O(N \\text{cdot Range})$. |
Average-to-Infinity Scan. |
Calculate avg = 5.5. Check if 6 is in array (scan N). Check if 7 is in array (scan N). If the array is empty, this works. If array has [6,7,8...1M], this is very slow. |
Calculate average, throw array into a Hash Set, and start checking from ceil(avg) + 1. |
The "Average Gate" Sieve. |
Visualize a gate at the "Average" value. Only numbers higher than this can pass. Throw all those "passing" numbers into a bucket (Set). The first number after the gate that *isn't* in the bucket wins. |
Draw a number line. Mark the 'Average'. Put all array numbers into a Hash Set. Start at the 'Average', take one step at a time. The first number not in the Set is the answer. |
Set Insertion + Linear Probe. |
Draw an $O(N)$ arrow to build the set, then a short $O(K)$ arrow to find the gap. Total $O(N)$. |
Nested loops scanning the original array repeatedly. |
A Hash Set containing the array elements. Space $O(N)$. |
| 3679 |
Minimum Discards to Balance Inventory (Med) |
Try discarding every possible subset of items (2^N) and check if the remaining inventory is "balanced". |
Sub-inventory Power Set. |
Draw a list of items. Branch: "Keep item 1" or "Discard item 1". For 40 items, you have 1 trillion combinations. |
Greedy with Frequency Maps or Dynamic Programming. Count the excess of each item type and discard only the necessary surplus. |
Surplus "Trimming". |
Imagine you need exactly 3 of every item. If you have 5 apples, you must discard 2. If you have 2 oranges, you must discard both (because you can't reach 3). |
Draw a frequency table. Write "Target Count = K". For each item, if `count > K`, subtract `count - K` from inventory. If `count < K`, subtract all. Sum the subtractions. |
Frequency Aggregation Pass. |
Draw one arrow scanning the inventory $O(N)$. Draw a second pass over the 26/K categories. Total $O(N)$. |
Massive recursion trees stored in memory. |
A Hash Map or Frequency Array. Space $O(\text{Unique}_\text{Items})$. |
| 3680 |
Generate Schedule (Med) |
Backtracking to try every possible task order (N!) to see which one fits the time constraints. |
Permutation Decision Tree. |
Start at Time 0. Try Task A, then Task B... Try Task B, then Task A... For 15 tasks, this is 1.3 trillion paths. |
Greedy Strategy: Earliest Deadline First (EDF) or Shortest Processing Time (SPT). |
The "Triage" Priority Queue. |
Visualize tasks as people in an ER. The person who will "die" (deadline) first gets treated first. If they take too long, you can't save everyone. |
Draw a timeline. Sort tasks by deadline. Place them on the timeline one by one. If any task's "End Time" exceeds its "Deadline", that schedule is invalid. |
Sorting-Bounded Timeline. |
Draw an $O(N \log N)$ sorting block. Draw a single $O(N)$ scan to verify the timeline. Total $O(N \log N)$. |
Storing every failed permutation in a giant list. |
A Min-Priority Queue or sorted list of tasks. Space $O(N)$. |
| 3681 |
Maximum XOR of Subsequences (Hard) |
Generating all 2^N subsequences and calculating the XOR sum for each. $O(N \cdot 2^N)$. |
Binary Subsequence Tree. |
Draw an array. Branch "Keep" or "Discard" for every number. For N=100, the number of leaves exceeds the atoms in the universe. 2^100 is mathematically impossible to brute force. |
Linear Basis (Gaussian Elimination for XOR). Find a set of basis vectors that can represent any possible XOR sum of the array. |
The "XOR Dimension" Filter. |
Visualize a set of slots (32 or 64). For each number, try to "insert" it. If it can be represented by existing numbers in the slots, it disappears. If not, it fills a slot. This reduces N numbers to at most 64 "Basis" numbers. |
Draw 31 slots. For each number, find its highest set bit B. If slot B is empty, put it there. If not, XOR it with slot B and repeat with the new number. Finally, greedily XOR from the top slot to 0 to get the max. |
Constant-Time Vector Scan. |
Draw an arrow through N items. For each, draw a loop of 32 iterations. Total $O(N \cdot 32)$. Write $O(N)$. |
Massive recursive memory frames trying to store every XOR result. |
An array of 64 integers (the Basis). Space $O(1)$. |
| 3682 |
Minimum Index Sum of Common Elements (Med) |
Nested loops comparing every element of List A with every element of List B. If they match, sum their indices. $O(A \cdot B)$. |
Cartesian Product Grid. |
Draw List A as rows and List B as columns. Put a check in the cell where values match. Calculate index sums for all checks. For N=10^5, this is 10 billion checks. |
Hash Map for List A (Value -> Index). Scan List B and look up values in the Map in $O(1)$. |
The "Value-to-Index" Lookup Table. |
Instead of searching the whole crowd for a specific person, you have a directory. Look up the person's name (Value) and get their seat number (Index) instantly. |
Draw a Map: {"Pizza": 0, "Burger": 1}. Read List B. When you see "Burger", get 1 from the map. Sum it with current index in B. Keep track of the minimum sum found. |
Two-Pass Linear Scan. |
Draw one arrow scanning List A to build the Map $O(A)$. Draw a second arrow scanning List B $O(B)$. Total $O(A + B)$. |
Building a full intersection matrix in memory. |
A Hash Map containing elements of List A. Space $O(A)$. |
| 3683 |
Earliest Time to Finish One Task (Easy) |
For every task, simulate the time it takes to finish given its requirements, then find the minimum. $O(N \\text{cdot Steps})$. |
Task-by-Task Simulation. |
Pick Task 1. Count minutes until finished. Pick Task 2. Repeat. If a task takes 1 million minutes, this is slow. |
Precompute dependencies and apply a Greedy "Earliest Start" calculation. |
The "Fastest Lane" Race. |
Imagine N sprinters. You only care about the one who crosses the line first. Calculate their "arrival time" based on their speed and starting position without running the whole race. |
Calculate StartTime + Duration for every task. Store them in an array and use a simple min() function. |
Single-Pass Comparison. |
Draw one arrow scanning all tasks once. $O(N)$. |
Allocating large timelines or simulation arrays for every task. |
Two or three integer variables. Space $O(1)$. |
| 3684 |
Maximize Sum of At Most K Distinct Elements (Easy) |
Generate all subsets with at most K distinct elements and find the one with the maximum sum. $O(2^N)$. |
Subset Combinatorial Search. |
Draw the array. Branch every which way. For N=50, this is trillions of branches. |
Greedy Sorting. Sort the array descending and pick the largest values until you hit the K distinct limit. |
The "High-Value" Buffet. |
You are at a buffet but can only try K different types of food. To maximize your "value", pick the most expensive food items first, even if you take multiple servings of the same kind. |
Sort the whole array largest to smallest. Walk down the list. Add to sum and keep a count of how many unique numbers you've seen. Stop when unique == K. |
Sorting-Bounded Pass. |
Draw an $O(N \log N)$ sorting block and an $O(N)$ scan. Total $O(N \log N)$. |
Storing all 2^N subsets in a nested list. |
In-place sorted array or a frequency map. Space $O(N)$. |
| 3685 |
Subsequence Sum After Capping Elements (Med) |
For every possible subsequence, apply the cap to each element, then sum them up. $O(2^N)$. |
Recursive Branching with Capping. |
Draw the array. For each number, if it's 10 and cap is 5, write 5. Branch "Include" or "Exclude". 2^N leaves. Total failure for N > 25. |
Dynamic Programming (Knapsack variant) or Combinatorial Math. Since capping is a uniform rule, use the frequency of elements to calculate contributions. |
The "Ceiling" Partition. |
Numbers larger than the cap all become the same value. Numbers smaller stay the same. Group them: [Small_Items] and [Large_Items rightarrow Cap]. Solve using 2^Count for the large group. |
Identify items > Cap. If there are M such items, any subsequence involving any of them contributes the Cap value. Use DP to find sums of the small items and combine with the 2^M combinations of the capped ones. |
Grouped DP Table. |
Write $O(N \\text{cdot MaxSum})$. Draw a grid where the capped items are handled as a single mathematical constant. |
A massive recursion stack with 2^N states. |
A 1D DP array of size `MaxSum`. Space $O(\text{MaxSum})$. |
| 3686 |
Number of Stable Subsequences (Hard) |
Generate all 2^N subsequences and check stability (e.g., frequency of all elements must be equal) for each. $O(N \cdot 2^N)$. |
Subsequence Combinatorial Explosion. |
Draw an array. Branch out into every subset. For each subset, build a frequency map. If all values in the map aren't the same, discard. 2^100 paths. |
Dynamic Programming with Frequency Maps or Combinatorics. Calculate combinations of each element frequency F independently and sum them. |
The "Frequency Pillar" Combinations. |
If a stable subsequence has frequency F=2, you need to pick exactly 2 of every number you include. Total ways = sum (Ways to pick F items of value X). |
Draw columns for each unique number. For a target frequency F, count how many ways to pick F items from each column using nCr. Multiply the (ways + 1 for excluding) across all numbers and subtract 1 (empty set). |
Frequency-Space Summation. |
Write $O(N \log N)$ to count frequencies, then $O(N)$ to iterate through possible frequencies F. Total $O(N \log N)$ or $O(N)$. |
Storing millions of frequency maps in a global list. |
A frequency map of the original array and a precomputed Pascal's Triangle (nCr) table. Space $O(N)$. |
| 3687 |
Library Late Fee Calculator (Easy) |
Manually counting days between two dates using a loop, then multiplying by the daily rate based on item type. $O(\text{Days})$. |
Day-by-Day Tick Counter. |
Start at Jan 1. Increment a counter 365 times to reach next year. If the book is 10 years late, this is thousands of iterations. |
Datetime library or Formula-based difference. `(Date2 - Date1).days * rate`. |
The "Date Stamp" Subtracter. |
Visualize two calendars. Instead of counting days, treat the dates as single points in time. The "distance" between the points is the delta. |
Convert both dates to "Days since Year 0". Day2 - Day1 = TotalDays. Multiplied by rate_map[item_type]. |
Constant-Time Calculation. |
Write $O(1)$. Draw two points on a line and a single arrow connecting them. |
Creating arrays or lists of every single day in the late period. |
Two or three integer variables. Space $O(1)$. |
| 3688 |
Bitwise OR of Even Numbers in an Array (Easy) |
Iterate through the array, if the number is even, add it to a list. Then loop through the list to calculate the OR. $O(N)$. |
Two-Pass Filter and Accumulate. |
Draw an array. Loop 1: Find evens and put in new array. Loop 2: XOR the new array. If N is large, the temporary array wastes space. |
Single-pass iteration with a running bitwise OR variable and a parity check. |
The "Even Filter" Funnel. |
Imagine the array falling through a screen. The screen only lets "Even" numbers pass (those with bit 0 as '0'). The numbers that pass fall into a single "OR Bucket". |
Initialize res = 0. Draw an arrow through the array. At each step, if num % 2 == 0, res |= num. |
Single Horizontal Timeline. |
Draw one arrow scanning the array once. $O(N)$. |
Creating a new list to store all even numbers found. |
A single integer variable res. Space $O(1)$. |
| 3689 |
Maximum Total Subarray Value I (Med) |
Nested loops to find every subarray (i, j) and a third loop to calculate its "Value" (e.g., sum * length). $O(N^3)$. |
Subarray Triple Loop. |
Draw an array. Draw brackets for every [L, R]. Calculate total value for each. With N=5000, this is 125 billion operations. |
Kadane's Algorithm or Sliding Window with Prefix Sums. If Value = Sum, it's strictly Kadane's. |
The "Rolling Snowball". |
As you move through the array, keep adding to your snowball (current sum). If the snowball becomes a "rock" (negative), throw it away and start a new one. |
Draw an array. Keep current_sum and max_sum. If current_sum < 0, reset it to 0. Always update max_sum with the current peak. |
Linear Cumulative Graph. |
Draw a single arrow moving left to right. $O(N)$. |
A 2D matrix storing values for every (i, j) pair. |
Two or three variables. Space $O(1)$. |
| 3690 |
Split and Merge Array Transformation (Med) |
Recursively simulating every possible split point and every merge result to find the target transformation. $O(2^N)$. |
Split-and-Merge Tree. |
Start with the array. Split at index 1, 2, 3... For each result, split again. The number of possible resulting configurations is exponential. |
Dynamic Programming (Interval DP). `dp[i][j]` stores whether the subarray from i to j can be transformed into the target. |
The "Puzzle Piece" Assembler. |
Instead of breaking it down, think of building it up. Can two smaller pieces (sub-transformations) be merged into this larger target piece? |
Draw a 2D grid. The cell (i, j) represents the range [i, j]. Build the grid diagonally, starting from length 1 up to N, checking if sub-ranges can merge. |
N^2 Grid Fill. |
Draw a square grid of size N x N. Shade the upper triangle. Write $O(N^3)$ (since each cell takes $O(N)$ to split). |
Massive recursive stack with duplicate sub-problem calculations. |
A 2D boolean array dp[N][N]. Space $O(N^2)$. |
| 3691 |
Maximum Total Subarray Value II (Hard) |
Exhaustively check every subarray and calculate value using a complex function (e.g., XORed sum * length). $O(N^3)$. |
Subarray Triple-Loop Chaos. |
Draw an array. Draw all N^2 brackets. For each, perform a bitwise XOR reduction. For N=10^5, the number of steps is 10^15. Total TLE. |
Divide and Conquer or Segment Tree with "Monotonic Property" optimization. Focus on boundaries where the XOR value changes (at most 32 times). |
The "Sparse Bit-Change" Window. |
A bitwise XOR/OR sum of a subarray only changes when a new bit is flipped. For any fixed start i, there are only approx 30 unique XOR values as you move j. Jump between these "change points." |
Draw an array. For index i, draw arrows pointing to the next indices where the XOR sum *actually* changes. Skip the redundant indices in between. |
Logarithmic Jump Scan. |
Write $O(N \cdot \log(\text{Max}_\text{Val})$). Draw a timeline where we only "stop" at bit-flip checkpoints. |
Storing full XOR results for every single possible index pair. |
A 2D sparse table or a list of "change-point" pairs. Space $O(N \log N)$. |
| 3692 |
Majority Frequency Characters (Easy) |
Double nested loop: For every character, count its frequency, then find the max frequency, then loop again to find characters matching it. $O(N^2)$. |
Multi-Pass Frequency Scan. |
Draw "AABBC". Loop 1: Find 'A' count (2). Loop 2: Find 'B' count (2). Loop 3: Find 'C' count (1). Find max is 2. Loop 4: Output A and B. |
Single-pass Frequency Array (size 26) + Max Frequency tracking. |
The "Alphabet Bucket" Race. |
Imagine 26 buckets. Toss characters in. Keep a "Leaderboard" variable for the highest bucket level. At the end, just announce everyone tied for first. |
Draw 26 small squares. As you scan, tally them. Keep max_freq updated. At the end, iterate the 26 squares and print those equal to max_freq. |
Two-Pass Linear Time. |
Draw one arrow for "Count $O(N)$" and one for "Identify $O(26)$". Total $O(N)$. |
Creating new lists or strings for every character's frequency count. |
An array of 26 integers. Space $O(1)$. |
| 3693 |
Climbing Stairs II (Med) |
Recursion without memoization: ways(n) = ways(n-1) + ways(n-2) + ways(n-3). $O(3^N)$. |
Tri-Branching Decision Tree. |
Start at N. Branch to N-1, N-2, N-3. Each of those branches 3 ways. The tree width triples at every level. 3^100 is impossible. |
Iterative Dynamic Programming (Bottom-Up). `dp[i] = dp[i-1] + dp[i-2] + dp[i-3]`. |
The "Three-Day Window" Slide. |
To know today's ways, you only need the totals from the last three steps. Like a sliding glass door that only covers three slots on a track. |
Draw a row of boxes. Fill boxes 1, 2, 3 with base cases. Box 4 is the sum of 1+2+3. Box 5 is the sum of 2+3+4. Keep sliding. |
Linear Step-by-Step Flow. |
Draw a straight arrow through N boxes. Write $O(N)$. |
A recursion stack reaching depth N with massive redundant subproblems. |
Three variables: a, b, c to store the last 3 steps. Space $O(1)$. |
| 3694 |
Distinct Points Reachable After Substring Removal (Med) |
Try removing every possible substring [i, j], calculate the final path from the remaining string, and store the endpoint in a Set. $O(N^3)$. |
Subsegment Deletion Exhaustion. |
Draw a string "URDL". Remove "U", path "RDL" -> (1, -1). Remove "UR", path "DL" -> (0, -2). With N=2000, this is 8 billion coordinates. |
Prefix Sums of Coordinates. Calculate (x, y) for all prefixes and suffixes. Endpoint = Prefix[i-1] + (Total - Prefix[j]). |
The "Vector Bridge" Calculation. |
Imagine a path as a chain. Removing a link doesn't require rebuilding the whole chain; just snap the two remaining ends together using simple vector addition. |
Precompute pref[i] as the (x, y) after i steps. For a removal of [i, j], the new endpoint is pref[i-1] + (pref[N] - pref[j]). Put these in a Set. |
N^2 Constant-Time Lookups. |
Draw an $O(N)$ pass to build prefixes. Then draw a nested $O(N^2)$ loop where each step is a simple subtraction. Total $O(N^2)$. |
Calculating the path from scratch for every single substring removal. |
A Hash Set of Coordinate pairs and a 1D array of prefix vectors. Space $O(N^2)$ for results. |
| 3695 |
Maximize Alternating Sum Using Swaps (Hard) |
Try every possible swap of two elements (i, j) and calculate the alternating sum for each configuration. $O(N^3)$. |
Permutation Swap Matrix. |
Draw an array. Swap index 0 and 1, calculate sum. Swap 0 and 2, calculate sum... For N=10^5, this is 10^10 calculations. |
Greedy Analysis of Parity. An alternating sum is (EvenSum - OddSum). Swapping only helps if you move a large number from an "Odd" (negative) position to an "Even" (positive) position. |
The "Valuable Trade" Market. |
Think of Even positions as "Profit" and Odd as "Loss." To maximize net worth, you want to find your biggest "Loss" (largest value at odd index) and swap it with your biggest "Potential Profit" (largest value at even index). |
Find min(arr[even_indices]) and max(arr[odd_indices]). If max_odd > min_even, swapping them increases the total sum by 2 * (max_odd - min_even). |
Two Linear Extremum Scans. |
Draw one arrow finding the min of even slots, one finding the max of odd slots. Total $O(N)$. |
Storing all possible swapped array versions in memory. |
Four variables: max_odd, min_even, max_even, min_odd. Space $O(1)$. |
| 3696 |
Maximum Distance Between Unequal Words I (Easy) |
Nested loops comparing every pair of words (i, j) and, if they are different, calculating j - i. $O(N^2)$. |
Word-Pair Index Comparison. |
Draw a list of words. Connect index 0 to 1, 0 to 2, 0 to 3... Repeat for index 1. Calculate distances for all unequal pairs. |
Single-pass: Find the first and last occurrence of different words. The max distance is either LastIndex - FirstIndex or LastIndex - SecondFirstIndex. |
The "First and Last" Goalposts. |
You only care about the extreme ends. If the word at index 0 is "Apple" and the word at index N-1 is "Banana", that's your max. If the word at index N-1 is also "Apple", then the answer is N-1 minus the first index that isn't "Apple". |
Draw an array. Point to arr[0] and arr[N-1]. If they differ, distance = N-1. If not, scan inward from both ends to find the first mismatch. |
Two-Pointer Boundary Scan. |
Draw two arrows starting at the ends and moving inward slightly. Total $O(N)$. |
Storing every distance value found in a list. |
Three or four integer variables to store indices. Space $O(1)$. |
| 3697 |
Compute Decimal Representation (Easy) |
Converting a large non-decimal string to a decimal using high-level language functions like parseInt or int() without handling precision. |
Black-Box Conversion. |
Write the number "1011". Feed it into a magic box labeled "Conversion". If the number is 1,000 digits long, the magic box crashes or loses precision. |
Horner's Method for Polynomial Evaluation. Process the string character by character, multiplying the current result by the base and adding the new digit. |
The "Rolling Multiplier" snowball. |
Think of it like building a number: ((FirstDigit x Base) + NextDigit) x Base... This keeps the math local and allows for BigInt handling. |
Start with res = 0. For each char c: res = res * base + digit(c). This handles any string length linearly. |
Linear Digit-by-Digit Pass. |
Draw one arrow scanning the string once. $O(N)$. |
Creating massive temporary strings or recursion for base conversion. |
A single BigInt or integer variable. Space $O(N)$ for the result storage. |
| 3698 |
Split Array With Minimum Difference (Med) |
Try every possible split point (O(N)) and for each, calculate the sums of both halves (O(N)). Total $O(N^2)$. |
Cut-and-Sum Simulation. |
Draw an array. Draw a vertical line at index 1. Sum left, sum right. Erase. Draw a line at index 2. Repeat. $O(N^2)$ is slow for N=10^6. |
Prefix Sums. Calculate all cumulative sums once. Sum of right half = TotalSum - PrefixSum[i]. |
The "Sliding Fulcrum". |
Imagine a balance scale. Instead of re-weighing everything, just move the center point. As you slide the point right, you subtract weight from the right side and add it to the left. |
Precompute total_sum. Draw an arrow through the array. At index i, left_sum += arr[i] and right_sum = total_sum - left_sum. Find the i where abs(left - right) is smallest. |
Single-Pass Prefix Summation. |
Draw one arrow for "Total Sum $O(N)$" and one for "Find Split $O(N)$". Total $O(N)$. |
Storing N separate sub-arrays in memory to calculate sums. |
Two long variables: left_sum and right_sum. Space $O(1)$. |
| 3699 |
Number of ZigZag Arrays I (Hard) |
Generate all 2^N subsequences and for each, check if the elements alternate between larger and smaller. $O(N \cdot 2^N)$. |
Subsequence Directional Tree. |
Draw an array. Branch "Include" or "Exclude". For included items, check: Up? Down? Up? Down? Most branches fail the "ZigZag" rule early. |
Dynamic Programming (DP). `dp[i][direction]` = number of zigzags ending at index i going "up" or "down". |
The "Mountain and Valley" Step. |
To be at the top of a peak at index i, you must have come from a valley at some previous index j. To be in a valley, you must have come from a peak. |
Draw a row of boxes. Each box has two slots: `Up` and `Down`. For arr[i], look at all arr[j] < arr[i] and add their `Down` counts to your `Up` slot. |
N^2 DP Grid. |
Draw a grid of size N x 2. Show that for each i, we scan all j < i. Total $O(N^2)$. |
Storing every valid zigzag path in a list of lists. |
A 2D DP array dp[N][2]. Space $O(N)$. |
| 3700 |
Number of ZigZag Arrays II (Hard) |
Same as part I, but with N=10^5, making the $O(N^2)$ DP solution far too slow. |
N^2 DP Time Limit Exceeded. |
Draw the N^2 grid from 3699. Imagine N is so large that filling the grid takes hours. Each cell requires a loop back over all previous cells. |
DP + Segment Tree or Fenwick Tree. Use a coordinate-compressed Segment Tree to query the sum of `Up/Down` counts for all values smaller/larger than the current element in $O(\log N)$. |
The "Rank-Based" Tree Query. |
Instead of scanning all previous j, "ask" a Segment Tree: "What is the sum of all 'Down' counts for elements with values between 0 and arr[i]-1?" The tree gives you the answer in logarithmic time. |
Draw a Segment Tree where the leaf nodes represent the sorted values of the array. As you process each arr[i], query the tree, update your current count, and then "insert" your new result back into the tree. |
N log N Data Structure Pass. |
Draw an arrow for the array scan $O(N)$. Above each step, draw a small $O(\log N)$ tree traversal. Total $O(N \log N)$. |
A full N x N matrix. |
A Segment Tree or Fenwick Tree structure. Space $O(N)$. |
| 3701 |
Compute Alternating Sum (Easy) |
Iterate through array, maintaining a boolean/multiplier flag that flips between +1 and -1, multiplying and accumulating. |
Linear step graph $O(N)$. |
Draw a horizontal line with N nodes. Below each node, write + or -, alternating. |
Single-Pass Accumulator / State Machine |
Accumulator Variable Box |
Point finger at index, update accumulator box, mentally flip sign, move finger right. |
Draw an array. Underneath, draw one box named "SUM". Cross out and update SUM as you move left to right. |
Flat horizontal line $O(N)$ time, dot for $O(1)$ space. |
Draw a 1D timeline axis to represent N ops. Write $O(1)$ in a tiny box. |
Single Variable Box (Sum) |
Single Variable Box + Sign Boolean Box |
| 3702 |
Longest Subsequence With Non-Zero Bitwise XOR (Med) |
Generate all 2^N subsequences, calculate XOR for each, find max length where XOR != 0. |
Exponential branching tree $O(2^N)$. |
Draw a binary decision tree. Left branch = "Include element", Right branch = "Exclude". |
Prefix XOR / Greedy Mathematical Observation |
Total XOR Bucket |
Calculate total array XOR. If != 0, answer is N. If 0, find first non-zero element to exclude. Answer is N-1. |
Draw whole array inside a bracket. Calculate total. If 0, cross out the first non-zero number and re-bracket. |
Single linear scan $O(N)$. |
Draw one straight line across the array blocks. $O(N)$ Time, $O(1)$ Space. |
Call Stack (Recursion) frames visualised as stacked boxes. |
Single Accumulator Box for Total XOR. |
| 3703 |
Remove K-Balanced Substrings (Med) |
Find all substrings. If one is K-balanced, remove it, concatenate the rest, and restart the process from index 0. |
String state transition graph $O(N^2)$ or worse. |
Write the string. Circle a substring, draw an arrow to a new string without it. Repeat until stuck. |
Stack / Amortized Sliding Window |
Vertical Stack Push/Pop |
Push chars to stack. Check top K elements. If they match the balance condition, pop them all. |
Draw a tall open box (Stack). Write letters from bottom up. When top elements form a match, erase/cross them out. |
Amortized $O(N)$ stair-step graph. |
Draw a graph where Y-axis is Stack Size. Line goes up, drops sharply on matches, ending at final size. |
New string arrays created constantly (Heap memory fragmentation). |
Contiguous Array/Stack memory layout. Pointers indicating "Top". |
| 3704 |
Count No-Zero Pairs That Sum to N (Hard) |
Nested loops iterating all possible (i, j) pairs up to N to check sum and string representation. |
2D Grid $O(N^2)$. |
Draw an N x N matrix. Shade the diagonal where i+j = N. Cross out rows/cols containing '0'. |
Two Pointers / Single-Pass String Check |
Symmetrical Number Line |
Start i at 1, j at N-1. Check if both strings lack '0'. Increment i, decrement j up to N/2. |
Draw a number line 1 to N. Draw arched lines connecting 1 & N-1, 2 & N-2. Cross out arcs with '0'. |
Linear scan $O(N)$. |
Draw a horizontal line segment from 1 to N/2. Write $O(N)$ above it. |
Massive 2D Grid allocation (if storing pairs). |
Two pointer variables in registers, small string buffer for digit checking. |
| 3705 |
Find Golden Hour Customers (Med) |
Compare every customer's timestamp with every other customer's timestamp. $O(N^2)$. |
Complete Graph (Nodes and Edges). |
Draw dots for customers. Draw lines connecting EVERY dot to EVERY other dot. |
Sorting + Sliding Window (Queue) |
Expanding/Shrinking Window on Timeline |
Sort by time. Move Right pointer to add customers. Move Left pointer if Right-Left time diff > 60 mins. |
Draw a horizontal timeline. Draw a bracket `[ ]` that expands to the right and drags its left tail when > 60. |
$O(N \log N)$ curve for sort + $O(N)$ flat line. |
Draw an upward curving line labeled $O(N \log N)$ (Sorting Phase), followed by a straight line $O(N)$ (Window Phase). |
Unordered Array memory layout. |
Sorted Array layout + Left/Right index pointer variables. |
| 3706 |
Maximum Distance Between Unequal Words in Array II (Med) |
Nested loops comparing every word with every other word to find max distance. |
N x N Grid (Upper Triangle). |
Draw an N-by-N grid. Shade cells where word[i] != word[j], circle the one furthest from diagonal. |
Two Pointers / Hash Map (First & Last Occurrence) |
Left/Right Pinching Pointers |
Point left index at start, right at end. If words differ, that's max. If same, check distance by moving left once, then right once. |
Draw the array. Draw a large bracket from first to last element. Shrink the bracket bounds if the endpoints are identical. |
Linear Scan Line $O(N)$. |
Draw one straight horizontal line with an $O(N)$ above it. $O(1)$ space dot. |
No extra memory, just index variables. |
Map or two simple pointer variables. |
| 3707 |
Equal Score Substrings (Easy) |
Generate all possible substrings and calculate the score for each to check for equality. |
Branching Substring Tree $O(N^2)$. |
Write the string. Below it, write all 1-letter parts. Below that, 2-letter parts. Calculate score for each block. |
Sliding Window / Prefix Sum Array |
Moving Window Box |
Maintain a running score. Expand window right. If score breaks rule, shrink from left until valid. |
Draw string. Draw a rectangle over valid chars. Tally score inside. Drag right edge, then drag left edge to keep score equal. |
Single pass $O(N)$. |
Draw a timeline. Put a box representing the window sliding right without resetting. |
Massive array of newly allocated string chunks. |
Integer variables for Left, Right, and Score. |
| 3708 |
Longest Fibonacci Subarray (Med) |
For every pair (i, j), scan forward to see how long the Fibonacci sequence continues. |
Triple nested loops $O(N^3)$. |
Draw array. Pick two numbers. Draw an arrow to their sum. Repeat until the chain breaks. Restart with new pair. |
Dynamic Programming / Hash Map |
2D DP State Matrix |
Map value to index. For each pair, look up the previous required number in map. DP[i][j] = DP[prev][i] + 1. |
Draw a 2D table where rows/cols are indices. Fill cells with sequence lengths, tracing back via map lookups. |
$O(N^2)$ Matrix fill. |
Draw a square grid and shade it in row by row to signify $O(N^2)$ time. |
Call stack frames for recursion. |
2D Array (DP Table) + Hash Map. |
| 3709 |
Design Exam Scores Tracker (Med) |
Store scores in an unsorted array. Search or sort the whole array for every query. |
Sorting Bar Chart $O(N \log N)$ per query. |
Draw unsorted bars. Every time a query comes, erase them and redraw them sorted by height. |
Segment Tree / Balanced BST (TreeMap) |
Binary Tree Traversal |
Insert score into tree to maintain order. Use tree properties to quickly find percentiles, max, or min. |
Draw a tree node. Left child is smaller score, right is larger. Keep counts in nodes. Trace path down for queries. |
$O(\log N)$ depth per query. |
Draw a triangle (Tree). Draw a single straight line from top to bottom representing $O(\log N)$ query time. |
Flat Array memory layout. |
Node-based memory scattered on heap with left/right pointers. |
| 3710 |
Maximum Partition Factor (Hard) |
Try cutting the array at every possible combination of indices (2^N partitions). |
Binary Partition Tree $O(2^N)$. |
Draw the array. Draw lines branching to "cut here" and "don't cut here" for every single gap. |
Dynamic Programming with Memoization |
State Transition Array |
Calculate max factor for subproblems (prefix arrays). Store result. Build up to full array. |
Draw an empty array DP. For each cell, look back at previous cells, apply factor math, and write the max value. |
$O(N^2)$ or $O(N)$ depending on math optimization. |
Draw a 1D array filling up left-to-right, with backward arrows showing lookups. |
Deep recursive call stack. |
1D DP Array memory block. |
| 3711 |
Maximum Transactions Without Negative Balance (Med) |
Try every subset of transactions using Backtracking to see which keeps balance >= 0. |
Decision Tree $O(2^N)$. |
Draw a tree. Branch left: "Take transaction". Branch right: "Skip". Cross out branches going below 0. |
Greedy + Priority Queue (Min-Heap of negative values) |
Heap Rebalancing / Time Travel Undo |
Add all to balance. If balance < 0, remove the most negative transaction seen so far (pop from Heap). |
Draw a running total. Draw a bucket (Heap) for negative numbers. When total < 0, cross out the biggest negative in the bucket and add it back to total. |
$O(N \log N)$ Heap insertions. |
Draw a straight line N with small sorting loops (log N) at each step. |
Call stack (recursion). |
Tree-shaped Array (Priority Queue). |
| 3712 |
Sum of Elements With Frequency Divisible by K (Easy) |
For each element, scan the whole array to count its frequency. If divisible, add it. $O(N^2)$. |
Overlapping Scan Lines $O(N^2)$. |
Draw the array. Pick an element, draw a line scanning the whole array to count it. Repeat for next. |
Hash Map Frequency Counting |
Two-Pass Map Reduction |
Pass 1: Tally frequencies in map. Pass 2: Iterate map keys, if value % K == 0, add (key * value) to sum. |
Draw two columns: "Number" and "Tally Marks". Scan array, add tallies. Then circle rows where tallies divide by K. |
$O(N)$ Time, $O(U)$ Space (U = unique elements). |
Draw two straight sequential lines (Two passes). |
No extra memory, N^2 time. |
Hash Table memory layout (Key-Value pairs). |
| 3713 |
Longest Balanced Substring I (Med) |
Generate all substrings, count balance of each to find the longest valid one. $O(N^2)$. |
Nested brackets $O(N^2)$. |
Write string. Draw a bracket for every possible substring and count 0s and 1s inside. |
Prefix Sum + Hash Map (First Occurrence) |
State Tracker Chart |
Treat '0' as -1, '1' as +1. Track running sum. If sum repeats, a balanced substring occurred between those indices! |
Draw string. Below it, write running sum (+1/-1). Circle duplicate sum numbers. The distance between them is the substring length. |
Linear Scan $O(N)$. |
Draw a wavy line (running sum). Draw a horizontal line connecting two peaks at the same height. |
String chunk allocations. |
Hash Map storing (RunningSum -> FirstIndex). |
| 3714 |
Longest Balanced Substring II (Med) |
Same as I, generating all substrings. (If it has more variables, $O(N^3)$). |
Nested brackets. |
Similar to 3713, exhaustive checking. |
Bitmasking + Hash Map / Advanced State Tracking |
Bitmask Toggle Box |
Track parity (even/odd) of character counts using bits. Store bitmask in map. Same bitmask means balanced difference! |
Write string. Keep a tally of even/odd (E/O). E.g., E,O -> O,O. Store the E/O state. Find matching past states. |
Linear Scan $O(N)$. |
Draw a timeline with state labels. Match identical labels. |
String generation. |
Hash Map storing (Bitmask Integer -> Index). |
| 3715 |
Sum of Perfect Square Ancestors (Hard) |
For every node, traverse back up to the root, checking if each ancestor is a perfect square. |
Upward Tree Tracing $O(N \\text{cdot Depth})$. |
Draw a tree. Pick a leaf, draw a line up to the root, circling perfect squares. Repeat for EVERY node. |
DFS with Running Sum/State |
Downward Passed State |
Do DFS. Maintain a running sum of perfect squares in the current path. Pass this sum down to children. |
Draw a tree. As you draw arrows DOWN to children, carry a "backpack" number (the sum). Update the backpack if current node is a square. |
$O(N)$ single tree traversal. |
Draw a single line tracing the contour of the whole tree (Euler tour). |
Parent pointer lookups or N^2 paths. |
Call stack containing current running sum integer. |
| 3716 |
Find Churn Risk Customers (Med) |
Cross-join style nested loops comparing every transaction of a user with every other transaction they made. |
Dense bipartite graph $O(N^2)$. |
Draw a list of transactions. Draw lines connecting every single transaction to every other transaction to check time gaps. |
Hash Map Aggregation / Sorting by User |
Bucketing System |
Group all transactions by Customer ID into buckets, sort timestamps inside each bucket, then linearly check adjacent times. |
Draw large squares (buckets) labeled with Customer IDs. Drop timestamps in, sort them, and draw small arcs between adjacent numbers to check differences. |
$O(N \log N)$ grouping and sorting. |
Draw a branching sort-tree (log N) next to a flat line of length N. |
Duplicated rows in a giant relational table memory layout. |
Hash Map pointing to dynamically sized arrays of integers (timestamps). |
| 3717 |
Minimum Operations to Make the Array Beautiful (Med) |
Iterate array. If an even index matches the next element, delete it and physically shift all remaining elements left. Restart. |
Block Shifting Cascade $O(N^2)$. |
Draw the array. Cross out a matching element, then draw arrows shifting every subsequent element one step to the left. |
Greedy Virtual Deletion (Two Pointers) |
Skipping Read Pointer |
Keep a "deletions" counter. Use it to calculate the *virtual* index. If a match occurs, increment counter instead of shifting array. |
Draw array. Move a finger (pointer) left to right. When pairs match on a virtual even index, tally a mark on a "Deletes" scoreboard and skip ahead. |
Single Linear Scan $O(N)$. |
Draw a single straight horizontal arrow passing over the array blocks. |
Constant memory reallocation or deep recursive array copies. |
Two simple integer variables (Index, DeletionCount). |
| 3718 |
Smallest Missing Multiple of K (Easy) |
Loop multiples `M = K, 2K, 3K...`. For each `M`, scan the entire array from index 0 to N to see if it exists. |
Multiple full-array scans $O(N \cdot (\text{Ans}/K)$). |
Draw array. Write `K`, draw a line scanning the whole array. Write `2K`, draw another full scanning line below it. |
Hash Set + While Loop |
Direct Lookup Table |
Put all array numbers into a Hash Set. Then loop `M = K, 2K...` and do $O(1)$ checks against the Set until one is missing. |
Draw a big circle (Set) with numbers scattered inside. Write a list `K, 2K, 3K`. Put a checkmark next to each if it's in the circle. Stop at the first X. |
$O(N)$ Set build + $O(1)$ lookups. |
Draw a thick line representing Set creation, followed by a few quick, detached dots representing instant lookups. |
$O(1)$ auxiliary space, purely in-place checks. |
Hash Set memory layout scattered in the heap. |
| 3719 |
Longest Balanced Subarray I (Med) |
Generate every possible subarray (O(N^2)), count elements in each to check balance condition. |
Overlapping Brackets $O(N^2)$. |
Draw sequence. Draw a bracket for every size-2 group, then size-4, etc. Count items inside each bracket. |
Prefix Sum Difference + Hash Map |
Running Balance Altitude Graph |
Treat categories as +1 and -1. Track running sum. If the sum reaches a value it has seen before, the items between are balanced. |
Draw sequence. Below it, plot a line graph going up (+1) and down (-1). Draw a horizontal line connecting two peaks at the exact same altitude. |
Linear Pass $O(N)$. |
Draw a single squiggly line progressing strictly rightward. |
$O(1)$ memory but very high CPU usage. |
Hash Map mapping (Running Sum Integer -> First Seen Index). |
| 3720 |
Lexicographically Smallest Permutation Greater Than Target (Med) |
Generate all N! possible permutations, sort them lexicographically, find the target, pick the one next to it. |
Massive Factorial Tree $O(N!)$. |
Draw a branching tree showing every single arrangement of the numbers. Circle the target sequence. |
Next Permutation Algorithm (Suffix Reversal) |
Pivot and Flip |
Scan right-to-left to find the first "dip" (pivot). Swap pivot with next largest on its right. Reverse everything right of the original pivot position. |
Draw array. Draw an arrow leftward from the end until the number drops (Pivot). Find smallest number bigger than Pivot on right. Swap. Bracket the right side and write "FLIP". |
Three linear passes $O(N)$. |
Draw three overlapping horizontal line segments on a 1D axis (Find pivot, Find swap, Reverse). |
Giant array holding all N! permutations. |
In-place array swaps $O(1)$ auxiliary space. |
| 3721 |
Longest Balanced Subarray II (Hard) |
Generate all possible subarrays, manually checking complex balance conditions for every single one. $O(N^3)$ or $O(N^2)$. |
Dense Overlapping Sub-segments. |
Draw the array. Bracket every possible subarray starting from index 0, then index 1, tallying internal counts for each. |
State Encoding (Bitmask) + Hash Map |
State-Transition Map |
Encode the "balance" as a single integer (e.g., bitmask of odd/even counts). If you hit a state you've seen before, the items between are perfectly balanced. |
Write the array. Below it, write the running "state code". When you write a code you've written before, draw a wide arc connecting them. |
Single linear scan $O(N)$. |
Draw a straight timeline left to right, placing dots for state checks. |
Constant space if counting in-place, but very slow execution. |
Hash Table storing (Encoded State Integer -> First Seen Index). |
| 3722 |
Lexicographically Smallest String After Reverse (Med) |
Generate all combinations by reversing every possible substring chunk, then compare all strings lexicographically. $O(N^3)$. |
Branching String Permutations. |
Write original string. Below it, write dozens of new strings, each with a different arbitrary chunk manually reversed. |
Greedy Traversal / Peak Finder |
Left-to-Right Anomaly Detection |
Scan left to right. Find the first character that breaks optimal order. Find the optimal suffix/prefix to reverse to fix it. |
Draw string. Move finger left to right. Stop at the first "suboptimal" character. Bracket it to the next target point, draw a swap arrow. |
Linear pass $O(N)$. |
Draw a single forward arrow, an $O(1)$ swap/reverse action curve, and done. |
Array of newly allocated strings in memory. |
In-place character array mutation (O(1) auxiliary space). |
| 3723 |
Maximize Sum of Squares of Digits (Med) |
Iterate all possible valid numbers or combinations within constraints, sum their squares, and find the maximum. |
Full Combinatorial Tree. |
Draw a branching tree of digit choices (0-9), calculating the square sum at every single leaf node. |
Greedy Digit Allocation |
Top-Heavy Buckets |
Larger numbers squared yield massively larger sums (e.g., 9² + 1² > 5² + 5²). Greedily assign 9s to as many positions as possible. |
Draw empty slots for digits. Fill them with '9's from left to right until your digit limit/sum limit is completely exhausted. |
Constant time $O(1)$ math or $O(D)$ digits. |
Draw a short, flat horizontal line representing a direct mathematical calculation. |
Recursion stack frames. |
A few simple integer variables. |
| 3724 |
Minimum Operations to Transform Array (Med) |
BFS exploring all possible forward operations (add, subtract, multiply) on all elements until the target is hit. |
Explosive State Space Graph $O(\text{Branch}^\text{Depth})$. |
Draw the array. Draw lines branching out for every possible operation applied to it, creating a massive expanding web. |
Backwards Traversal (Target to Start) |
Reverse Engineering Pathway |
Start from the Target array and work *backwards* to the Start array using inverse operations (e.g., divide by 2 if even, instead of trying to multiply up). |
Write Target on the right, Start on the left. Draw arrows pointing *leftward*, dividing or subtracting optimally until you hit start values. |
$O(N \log(\text{MaxVal})$) reduction. |
Draw a line representing array N, with small logarithmic spirals below each number showing its reduction path. |
Massive Queue holding thousands of array states. |
In-place array modifications, $O(1)$ extra space. |
| 3725 |
Count Ways to Choose Coprime Integers from Rows (Hard) |
Nested loops picking one element from each row, calculating the GCD for every single pair to ensure they are coprime. $O(M^N)$. |
Multi-dimensional Grid Selection. |
Draw rows. Draw lines connecting one number from row 1, to row 2, etc. Cross out paths where GCD != 1. |
DP + Prime Factor Bitmasking |
Bitmask State DP Table |
Map numbers to their prime factors. Use a bitmask to represent "primes used so far". Add a number to the path only if `(current_state & new_prime_mask) == 0`. |
Write available primes. Next to rows, write prime-masks for numbers. Draw a DP table mapping [RowIndex][PrimeMask]. Fill counts. |
$O(\text{Rows} \cdot 2^(\text{MaxPrimes})$). |
Draw a DP grid where Y is Rows, X is the fixed 2^10 possible prime states. Shade it top to bottom. |
Deep recursive call stack tracking full paths. |
2D DP Array Memory (Rows x 2^P). |
| 3726 |
Remove Zeros in Decimal Representation (Easy) |
Convert the integer to a string, iterate through to strip out '0' characters, then parse back to integer. |
String Array Shifting $O(D)$ where D is digits. |
Write the number. Cross out any '0'. Rewrite the remaining numbers squished together. |
Mathematical Digit Extraction (Modulo & Division) |
Digit Reconstruction Stack |
Loop while N > 0: Pop last digit using `N % 10`. If it's not 0, multiply it by a running power of 10 and add to result. Divide N by 10. |
Draw a number. Divide by 10 to drop the last digit into a bucket. If bucket has a non-zero, push it onto a new reconstructed pile. |
Fast loop $O(\log10(N)$). |
Draw a short, straight line with a few dots representing digit iterations. |
String allocations on the heap. |
Pure integer variables (O(1) space). |
| 3727 |
Maximum Alternating Sum of Squares (Med) |
Generate all possible subsequences, calculate their alternating sum of squares (+a² -b² +c²...), and find the maximum. $O(2^N)$. |
Binary Decision Tree. |
Draw a tree branching at every number: Include as positive square, Include as negative square, or Skip entirely. |
Dynamic Programming (State Machine) |
Parallel State Tracks |
Maintain two running maximums: one if the *next* operation is addition, one if the *next* operation is subtraction. Update them cross-wise. |
Draw two horizontal tracks (Top: Add, Bottom: Sub). Write numbers along the top. Draw zig-zag arrows between tracks updating the max possible sum at each step. |
Single pass $O(N)$. |
Draw a straight horizontal line spanning the array length. |
Deep recursive call stack. |
Two simple integer variables (O(1) space). |
| 3728 |
Stable Subarrays With Equal Boundary and Interior Sum (Med) |
Nested loops to generate all subarrays. For each, sum the interior elements and compare to the sum of the two boundary elements. $O(N^3)$. |
Overlapping loops with internal scans. |
Draw array. Pick L and R boundaries. Bracket the middle, sum it up manually, and check if it equals L+R. |
Prefix Sums + Hash Map |
Equation Rearrangement Mapping |
Interior sum is `Pref[R-1] - Pref[L]`. We need this to equal `arr[L] + arr[R]`. Rearrange to group L terms and R terms. Store L terms in a map to match with R terms. |
Draw array and Prefix Array below it. Draw a Hash Map bucket. Calculate the "target" math for L and drop it in the bucket. As R moves, check the bucket for matches. |
Linear Scan $O(N)$. |
Draw a straight timeline with dictionary lookups represented as fast instant drops. |
$O(1)$ auxiliary space, but terrible time complexity. |
Hash Map & Prefix Sum array (O(N) space). |
| 3729 |
Count Distinct Subarrays Divisible by K in Sorted Array (Hard) |
Generate all possible subarrays, sum them, check if sum % K == 0. Store valid ones in a Hash Set to ensure they are distinct. $O(N^3)$. |
Massive Bracket Overlaps. |
Draw every subarray combination. Sum them, check modulo. Write them in a "Seen" list, crossing out duplicates. |
Prefix Sum Modulo K + Trie/String Hashing |
Modulo Grouping + Sequence Deduplication |
Track running Prefix Sum % K. If we see a mod value we've seen before, the sum between is divisible by K. Use a Set/Trie to filter out identical sequences caused by duplicates in the sorted array. |
Draw array. Below it, write running sum % K. Connect identical modulo numbers with an arc. Feed the elements under the arc into a Set to check for uniqueness. |
$O(N^2)$ depending on distinct verification. |
Draw a quadratic curve indicating the cost of distinct subarray verification. |
Massive Hash Set of Arrays. |
Prefix Sum array + Trie or Hash Set for distinct sequences. |
| 3730 |
Maximum Calories Burnt from Jumps (Med) |
Recursively try every valid jump length from every position to find the path that yields the absolute highest calorie sum. $O(\text{Branch}^N)$. |
Exploding Pathing Tree. |
Draw a staircase. Draw lines jumping 1 step, 2 steps, etc. From each landing spot, branch out again until the end. |
1D Dynamic Programming |
Look-Back Max Array |
`dp[i]` represents max calories to reach index `i`. For each step, look back at all valid previous jump positions, pick the max `dp` value, and add current calories. |
Draw an empty array. Fill left to right. To fill a box, draw arrows looking back at allowed jump ranges. Pick the highest number, add current box's calories, write it down. |
$O(N \cdot J)$ where J is max jump range. |
Draw a linear sequence of boxes with short look-back arrows looping over previous items. |
Massive recursive call stack. |
1D DP Array memory block (O(N) space). |
| 3731 |
Find Missing Elements (Easy) |
Iterate through all numbers in the expected range. For each number, scan the entire array to see if it exists. $O(N^2)$. |
Multiple parallel scan lines. |
Draw the array. Write `1`, scan the whole array. Write `2`, scan the whole array below it. Cross out missing ones. |
Hash Set or Boolean Array Check |
Direct Lookup Bucket |
Throw all array numbers into a Set. Loop through the expected range (e.g., 1 to N). If a number is not in the Set, add it to the result list. |
Draw a big circle (Hash Set). Write array numbers inside it. Write a list 1 to N. Put a checkmark if the number is in the circle, X if it's missing. |
Two separate linear passes $O(N)$. |
Draw two horizontal timelines: one for "Building Set", one for "Checking Missing". |
$O(1)$ extra space, strictly in-place. |
Hash Set memory layout (scattered allocations). |
| 3732 |
Maximum Product of Three Elements After One Replacement (Med) |
Try replacing every single element with every other possible value, then check every possible triplet combination. $O(N^4)$. |
Massive Combinatorial Tree. |
Draw the array. Branch off to create N new arrays for each replacement. Then draw 3-pronged branches from each to find triplets. |
Sorting + Greedy Extremes |
Top/Bottom Extractor |
Sort the array. The maximum product comes from either the 3 largest numbers, or the 2 smallest (most negative) numbers times the largest. Calculate the best outcome if you replaced the "worst" number with a duplicate of the "best" multiplier. |
Draw sorted array. Put a bracket over the 3 rightmost elements. Put a bracket over the 2 leftmost and 1 rightmost. Compare their multiplied totals. |
$O(N \log N)$ Sorting. |
Draw a sweeping upward curve (Sort) followed by a short, flat $O(1)$ mathematical calculation. |
$O(1)$ simple variables. |
$O(\log N)$ sorting call stack space. |
| 3733 |
Minimum Time to Complete All Deliveries (Med) |
Generate all possible permutations of delivery orders and calculate the total time for every single sequence. $O(N!)$. |
Exploding Factorial Pathways. |
Draw map nodes. Trace every possible path connecting all nodes, tallying up the time for each route. |
Binary Search on Answer + Validation (Greedy/Bipartite) |
Shrinking Window on a Timeline |
Guess a maximum time `T`. Run a validation check to see if all deliveries can be completed within `T`. If yes, guess lower. If no, guess higher. |
Draw a number line of possible times. Pick the middle value. Do a quick test. Cross out the half of the line that is no longer possible. Repeat until narrowed to one point. |
$O(\log(\text{MaxTime})$ * Validation Time). |
Draw a horizontal line with brackets `[ | ]` continuously shrinking towards the center. |
Massive N! path tracking structures. |
$O(N)$ data structures for the validation step. |
| 3734 |
Lexicographically Smallest Palindromic Permutation Greater Than Target (Hard) |
Generate all string permutations, filter out the non-palindromes, sort them alphabetically, and find the one right after the target. $O(N!)$. |
Giant tree with heavy filtering branches. |
Write every scramble of the letters. Violently cross out any that don't read the same backwards. Order the survivors. |
Next Permutation on Half-String |
Mirror Flip Reflection |
Since it must be a palindrome, the right half is just a mirror of the left. Take the left half of the string, find its strictly "Next Permutation", and then mirror it to the right half. |
Write the string. Cut it in half. Ignore the right side. Run the "swap and reverse" permutation trick on the left half. Then copy the left half, flip it backward, and write it as the right half. |
Linear pass $O(N)$. |
Draw three quick horizontal segments: Find pivot, Reverse suffix, Mirror string. |
Huge arrays holding all valid permutations. |
In-place character array modification (O(1) extra space). |
| 3735 |
Lexicographically Smallest String After Reverse II (Hard) |
BFS/DFS exploring every valid sub-string reversal operation sequentially to see which paths lead to the smallest string. $O(N^\text{Depth})$. |
Branching web of full strings. |
Write the string. Draw branches to 5 new strings representing possible valid reversals. Branch again from each of those. |
Greedy Left-to-Right Minimization / Two Pointers |
Anomaly Targeting and Swapping |
Scan left to right. Find the earliest character that is suboptimal. Find the absolute smallest allowed character further right that can legally be reversed into that spot, and execute the flip. |
Move your finger left to right along the string. Stop at a "bad" letter. Scan ahead for the best replacement. Draw a sweeping arc connecting them and physically rewrite the reversed chunk. |
Linear Scan $O(N)$ or $O(N \log N)$. |
Draw a straight rightward arrow with one or two localized "flip" loops drawn above it. |
Massive queue of string states stored in memory. |
In-place string mutation, $O(1)$ or $O(N)$ space. |
| 3736 |
Minimum Moves to Equal Array Elements III (Easy) |
Try targeting every single number between the min and max of the array, calculate the absolute sum of differences for each. $O(N \\text{cdot Range})$. |
Multiple parallel distance checks. |
Draw a number line. Pick an arbitrary target dot. Draw lines from every array element to that dot. Sum the lengths. Repeat for next dot. |
Sorting & Median Finding |
Median Target Pull |
Sort the array. The optimal target to minimize absolute differences is ALWAYS the median element. Find the median, sum the distances from all other elements to it. |
Draw sorted array. Circle the exact middle number (the median). Draw arrows from all other numbers pointing inward to the circled median. Tally the distances. |
$O(N \log N)$ Sorting. |
Draw a sweeping upward curve representing the sort, followed by a flat horizontal line for the $O(N)$ summation pass. |
$O(1)$ extra space. |
$O(\log N)$ stack space for sorting algorithm. |
| 3737 |
Count Subarrays With Majority Element I (Med) |
Generate all $O(N^2)$ subarrays. For each, count frequencies of all elements to check if the max frequency is > length / 2. |
Overlapping brackets with internal tallies. |
Draw the array. Draw brackets for every subarray combination. Next to each bracket, draw a mini histogram of counts to check for a majority. |
Prefix Sums + Relative State Tracking (+1/-1) |
Balance Altitude Graph |
For a candidate majority element, treat it as +1 and all others as -1. Track the prefix sum. A valid subarray occurs when the current prefix sum is strictly greater than a previous prefix sum. |
Draw the array. Pick a target number. Write +1 under it, -1 under others. Plot a running sum on a line graph. Valid subarrays are paths between a lower dot and a higher dot. |
$O(N)$ per candidate or $O(N \log N)$ total. |
Draw a timeline moving right, with dots above it representing Hash Map/Tree lookups. |
$O(1)$ auxiliary space, purely computational. |
Hash Map or Fenwick Tree array layout (O(N) space). |
| 3738 |
Longest Non-Decreasing Subarray After Replacing at Most One Element (Med) |
Change every single element one by one to match its neighbor, then scan the array to find the longest non-decreasing streak. $O(N^2)$. |
N parallel array timelines. |
Draw the array N times. In each copy, cross out one number and rewrite it. Bracket the longest rising sequence in each. |
Dynamic Programming (Left & Right Prefix/Suffix Arrays) |
Left & Right Streak Merging |
Precompute the longest non-decreasing streak ending at `i` (Left array) and starting at `i` (Right array). For any gap `i`, if `arr[i-1] <= arr[i+1]`, the max length is `Left[i-1] + Right[i+1] + 1`. |
Draw the array. Above it, write streak counts moving left-to-right `[1,2,3...]`. Below it, write streak counts moving right-to-left `[...,3,2,1]`. Pick a number to "replace" and bridge the top and bottom streaks surrounding it. |
Three Linear Passes $O(N)$. |
Draw three straight, parallel horizontal lines indicating the Left pass, Right pass, and Merge pass. |
$O(1)$ extra space if done purely in loops. |
Two 1D DP arrays (Left and Right) taking $O(N)$ space. |
| 3739 |
Count Subarrays With Majority Element II (Hard) |
Same as part I, exhaustive sub-segment generation and frequency counting. Will result in Time Limit Exceeded due to tighter constraints. $O(N^2)$. |
Dense bracket overlays. |
Exhaustive listing of segments, crossing out invalid ones. |
Prefix Sum + Binary Indexed Tree (Fenwick) |
Accumulator Tree Query |
Treat target element as +1, others as -1. We need `Prefix[R] - Prefix[L-1] > 0`. This means we need to count how many previous `Prefix[L-1]` are strictly less than `Prefix[R]`. Use a Fenwick tree to count this efficiently. |
Draw array and Prefix sums. Next to it, draw a Fenwick Tree as an array of bins. To check a prefix sum, query the bins for values strictly smaller than it, add the count to total, then drop the current prefix into its respective bin. |
$O(N \log N)$ overall. |
Draw N segments on a line, with small tree-depth traversal loops (log N) occurring at every segment. |
$O(1)$ space, high time complexity. |
1D Array representing the Fenwick Tree (O(N) space). |
| 3740 |
Minimum Distance Between Three Equal Elements I (Easy) |
Triple nested loop (i, j, k) to find three identical elements. Calculate the distance `k - i` and keep the minimum. $O(N^3)$. |
3-Point Anchoring Loops. |
Pick an element. Scan forward for a second match. Scan forward for a third match. Measure the span from first to third. |
Hash Map with Index Lists / Sliding Window of Size 3 |
3-Element Queue / Index Memory |
Iterate through the array. Store indices of elements in a Hash Map. If a number's list of indices reaches size 3, calculate `index[last] - index[first]`. Keep a running minimum. |
Draw the array. Draw buckets for each unique number. Drop indices into their specific buckets. When a bucket gets 3 numbers, subtract the first from the last. Keep the smallest result. |
Single Linear Pass $O(N)$. |
Draw a straight, flat timeline left to right. $O(1)$ time per element. |
$O(1)$ space. |
Hash Map with dynamic arrays for indices (O(N) space). |
| 3741 |
Minimum Distance Between Three Equal Elements II (Med) |
Triple nested loops checking every combination of three identical numbers. Re-running entirely on updates. $O(N^3)$. |
3-Point Anchoring Loops. |
Pick element. Scan for 2nd match. Scan for 3rd match. Measure span. Repeat for all elements. |
Hash Map with Size-3 Deque (Sliding Window of Indices) |
3-Slot FIFO Queue |
Keep a map of numbers to a queue of length 3. When you see a number, push its index. If queue > 3, pop oldest. Calculate diff between newest and oldest. |
Draw small 3-box arrays for each unique number. Move left to right. Erase the oldest index in the box to write the newest one, then subtract the first from the third. |
Single Linear Pass $O(N)$. |
Draw a flat horizontal timeline moving right. |
$O(1)$ space. |
Hash Map pointing to tiny 3-element arrays. |
| 3742 |
Maximum Path Score in a Grid (Med) |
DFS exploring all possible paths moving right and down to calculate every possible score. $O(2^(R+C)$). |
Exploding binary tree of paths. |
Draw grid. Draw branching arrows down and right from every single cell. |
2D Dynamic Programming |
Matrix Accumulation |
`DP[r][c]` = cell value + `max(DP[r-1][c], DP[r][c-1])`. Build the max score iteratively from top-left to bottom-right. |
Draw blank grid. Fill top row and left col. For middle cells, point arrows from top and left neighbors, pick the bigger number, add current cell, and write it down. |
$O(R\cdot C)$ Matrix fill. |
Draw a square grid and shade it row by row, left to right. |
$O(R+C)$ Call stack. |
2D Array or optimized 1D row array $O(C)$. |
| 3743 |
Maximize Cyclic Partition Score (Hard) |
Try all N possible rotations of the array. For each, try all possible partition boundaries to find the max score. $O(N^3)$. |
Rotating Ring + Combinatorial Cuts. |
Draw a circle of numbers. Spin it 1 step. Draw lines cutting it into partitions. Sum them. Spin again. |
Double Array Concatenation + Monotonic Queue/DP |
Unrolled Circle Sliding Window |
Concatenate array to itself `(arr + arr)` to simulate rotation. Use a sliding window of size N with DP to find the optimal partition score within any N-length segment. |
Draw the array twice side-by-side. Slide a bracket of length N across it. Apply partitioning math only inside the bracket using looking-back arrows. |
$O(N)$ single pass on 2N array. |
Draw a line of length 2N with a sliding fixed-width box moving across it. |
$O(N)$ arrays generated repeatedly. |
Array of length 2N + 1D DP Array. |
| 3744 |
Find Kth Character in Expanded String (Med) |
Actually generate the massive string in memory by applying the expansion rules iteratively until it's larger than K, then return `str[K]`. |
Exponential string growth $O(2^\text{Steps})$. |
Write 'a', then 'ab', then 'abcd', expanding the string visually until it runs off the page. |
Reverse Recursive Math / Divide and Conquer |
Binary Tree Tracing Backwards |
Recognize string doubles each step. If K is in the right half, it is mapped from the left half with a character shift. Shrink K by subtracting half the length recursively until base case. |
Draw a long block. Cut in half. If K is on the right, draw an arrow to the exact mirrored spot on the left and write "+1 shift". Repeat halving until K is at index 0. |
$O(\log K)$ logarithmic halving. |
Draw a line halving repeatedly `[----] -> [--] -> [-]`. |
Gigabytes of string memory. |
$O(1)$ variables or $O(\log K)$ stack space. |
| 3745 |
Maximize Expression of Three Elements (Easy) |
Three nested loops picking 3 distinct indices (i < j < k). Calculate the expression for all triplets and track max. $O(N^3)$. |
Triple pointer scanning. |
Pin pointer 1. Pin pointer 2. Scan pointer 3 to the end. Move pointer 2. Repeat. |
Prefix Max / Suffix Max Arrays |
Peak Tracking Arrays |
Precalculate the best possible element for term 1 (prefix array, L to R) and term 3 (suffix array, R to L). Loop the middle element, lookup prefix and suffix, and compute. |
Draw array. Above it, write max-so-far moving L to R. Below it, write max-so-far moving R to L. Pick a middle element and add the top, middle, and bottom numbers together. |
3 Linear Passes $O(N)$. |
Draw three parallel horizontal lines (Prefix pass, Suffix pass, Evaluation pass). |
$O(1)$ space. |
Two 1D arrays of size N. |
| 3746 |
Minimum String Length After Balanced Removals (Med) |
Repeatedly scan the string, using `.replace()` to remove adjacent pairs (e.g., "AB" or "CD"). Start over from the beginning each time a removal happens until no more pairs exist. $O(N^2)$. |
Cascading String Replacements. |
Write the full string. Cross out a pair, rewrite the newly squished string on the line below. Repeat until stuck. |
Stack / Amortized Character Matching |
Vertical Push/Pop Cylinder |
Push characters onto a stack one by one. Before pushing, check if the incoming character and the top of the stack form a valid pair. If they do, pop the stack instead of pushing. |
Draw an open-top box (Stack). Write incoming letters top-down. If a new letter makes a pair with the top one, violently cross them both out. |
Linear Amortized $O(N)$. |
Draw a timeline with up-arrows (push) and immediate down-arrows (pop) that cancel out, scanning left to right once. |
Multiple immutable string allocations on the heap. |
A single contiguous character array or Stack structure. |
| 3747 |
Count Distinct Integers After Removing Zeros (Med) |
Convert every number to a string, manually iterate to strip out '0' characters, convert back to an integer, and append to a list. Finally, count distincts in the list. $O(N \\text{cdot Digits})$. |
Array of Shrinking Strings. |
Draw an array of numbers. Cross out '0's inside each cell. Rewrite the array, then draw connecting lines between duplicates to count uniques. |
Mathematical Digit Extraction + Hash Set |
Zero-Skipping Reconstruction |
Process each number mathematically: modulo 10 to extract digits. If digit != 0, add it to a new reconstructed number using powers of 10. Toss the result directly into a Hash Set. |
Draw a number. Drop its digits one by one into a sieve. Zeros fall through; other numbers build a new integer. Drop the new integer into a Set bucket. |
$O(N \cdot \log10(\text{MaxVal})$). |
Draw a flat horizontal timeline (array scan) with tiny, uniform loops at each step (digit processing). |
Heavy string creation and garbage collection. |
Hash Set in memory, purely $O(1)$ integer variables for math. |
| 3748 |
Count Stable Subarrays (Hard) |
Generate every possible subarray (O(N^2)). For each, do a full scan to verify if it meets the "stable" criteria (e.g., difference bounds). $O(N^3)$. |
Dense Subarray Bracket Web. |
Write the array. Draw a bracket for every conceivable chunk. Do math for every single bracketed chunk and tally the valid ones. |
Sliding Window + Monotonic Deques (Min/Max Tracking) |
Elastic Expanding Window |
Expand window Right. Track the min and max of the current window using two Deques. If the stability condition breaks, shrink the window from the Left until it's valid again. Add `Right - Left + 1` to total. |
Draw the array. Draw an expanding bracket `[ ]`. Below it, maintain a "Max" box and a "Min" box. When the difference breaks the rule, drag the left side of the bracket forward. |
Amortized $O(N)$. |
Draw a timeline moving right. Draw two simultaneous waves tracking the min/max bounds seamlessly. |
$O(1)$ extra space but massive repetitive computation. |
Two Double-Ended Queues (Deques) holding indices. |
| 3749 |
Evaluate Valid Expressions (Hard) |
Use recursive `eval()` functions or split the string repeatedly by operators, creating a massive tree of sub-expressions. $O(N^2)$ or worse if unbalanced. |
Fractal Expression Tree. |
Write the equation. Draw lines breaking it at every `+` or `-`, then break those at every `*` or `/`, solving from the bottom up. |
Shunting Yard Algorithm / Two Stacks (Operands & Operators) |
Dual-Stack Machine |
Read left to right. Push numbers to an Operand Stack. Push operators to an Operator Stack based on precedence. If precedence is lower, pop and calculate before pushing. |
Draw two boxes: "Numbers" and "Math Signs". Push items in. If a `*` is in the Math box and a `+` comes along, pop the `*`, pop two numbers, do the math, and push the result back. |
Single pass $O(N)$. |
Draw a straight line scanning right, with quick vertical loops symbolizing stack reductions. |
Deep recursive call stack frames parsing strings. |
Two array-backed Stacks (O(N) space). |
| 3750 |
Minimum Number of Flips to Reverse Binary String (Easy) |
Simulate the process. For every discrepancy, apply a full prefix/suffix flip operation to the string array and count steps. $O(N^2)$. |
Cascading String Mutations. |
Write the string. Find a wrong bit. Flip it and everything after it. Rewrite the entire new string. Repeat. |
State Transition Counting (Adjacent Differences) |
Bit Boundary Detection |
You don't need to physically flip anything! A flip is only required when the binary character *changes* from '0' to '1' or '1' to '0'. Just count the adjacent discrepancies. |
Write the binary string. Draw a vertical line `|` anywhere a '0' touches a '1'. Count the lines. Add 1 if the first character requires a flip to match the target state. |
Single pass $O(N)$. |
Draw a flat horizontal timeline moving right, with dots placed only when states flip. |
Repeated string cloning/modifications. |
$O(1)$ memory, just a counter variable. |
| 3751 |
Total Waviness of Numbers in Range I (Med) |
Iterate through every single integer from Low to High. Convert each to a string or digit list, check if it's "wavy" (alternating trends), and increment a counter. $O((\text{High}-\text{Low})$ * Digits). |
Linear enumeration with internal loops. |
Write every number in the range. Under each, draw a zig-zag line. If the line goes up-down-up or down-up-down consistently, circle the number. |
Digit DP (Dynamic Programming) |
Decision State Tree (Restricted) |
Construct the number digit by digit. Track: current digit, previous digit, and the required trend (up or down). Store results in a DP table to avoid re-calculating sub-problems. |
Draw a tree where each node is a digit (0-9). Cross out branches that don't satisfy the "wavy" trend. Use a "Memo" table [Position][LastDigit][Trend] to cache counts. |
$O(\text{Digits} \cdot 10 \cdot 2)$ complexity. |
Draw a small grid (DP table) and fill it. The width is the number of digits (log10(N)), which is very small. |
Minimal, but time is wasted on redundant checks. |
$O(\text{Digits} \cdot 10 \cdot 2)$ Memoization table in memory. |
| 3752 |
Lexicographically Smallest Negated Permutation that Sums to Target (Med) |
Generate all possible permutations of the numbers. For each, try all 2^N combinations of signs (+/-). Sort the results and pick the smallest that hits the Target sum. $O(N! \cdot 2^N)$. |
Explosive Permutation-Sign Forest. |
Draw every permutation. For each, draw a branching tree of +/- signs. Tally sums and look for the target. |
Greedy Selection with Math Constraints |
Range Bound Checking |
Sort input numbers ascending. At each step, decide whether to negate the number. Check if the remaining "best-case" sum can still hit the Target. Always pick the choice that results in the lexicographically smaller sequence. |
List the numbers. At each number, calculate: "If I pick '-', can the rest of the numbers still reach the Target?" If yes, pick '-' and move right. If no, pick '+'. |
$O(N \log N)$ Sort + $O(N)$ Greedy pass. |
Draw a straight timeline with a binary choice (High/Low) at each node, guided by a range check. |
Massive arrays of all possible combinations. |
Simple array of size N for the result. |
| 3753 |
Total Waviness of Numbers in Range II (Hard) |
Same as part I, iterating every number. Constraints are now massive (up to 10^18), making brute force impossible. |
$O(N)$ search on 10^18 elements. |
Visualise a timeline so long it disappears into infinity; marking wavy numbers is like finding needles in a haystack. |
Advanced Digit DP with Modulo/State constraints |
State-Space Compression |
Build the number from left to right. Maintain state: [Index][PrevDigit][Trend][IsLess][IsStarted]. Calculate counts using combinatorial math for each state. |
Draw the DP table on paper as a 5-dimensional coordinate system. Show how filling one cell uses the sum of 10 cells from the previous "Index" layer. |
$O(Log10(\text{Range})$ * 10 * 2) states. |
Draw a 1D timeline of length ~18 (digits), where each step involves a small 10x2 matrix multiplication. |
Massive CPU time; memory overflows if storing results. |
5D DP array [18][10][2][2][2] (very compact). |
| 3754 |
Concatenate Non-Zero Digits and Multiply by Sum I (Easy) |
Convert the number to a string. Loop to extract non-zero digits into a new string. Parse that string back to an integer. Calculate the sum of original digits and multiply. |
String manipulation pipeline. |
Write "1023". Cross "0" -> "123". Sum (1+0+2+3)=6. Calc 123 * 6. |
Single-Pass Mathematical Extraction |
Digit Hopper |
Iterate digits using `%10` and `/10`. Sum digits on the fly. Build the "concatenated" number by adding non-zero digits to a new integer (multiplied by power of 10). |
Draw a number box. As digits drop out of the bottom, if digit != 0, put it in the "New Number" box. Otherwise, just add it to the "Running Sum" bucket. |
$O(\log10(N)$) which is digit count. |
Draw a very short horizontal line with $O(\text{Digits})$ written above. |
String object allocations in the heap. |
Two or three integer variables in CPU registers. |
| 3755 |
Find Maximum Balanced XOR Subarray Length (Med) |
Generate all $O(N^2)$ subarrays. For each, calculate the bitwise XOR of all elements. If XOR == 0, check the length. Track the max length found. $O(N^3)$ or $O(N^2)$ with prefix XOR. |
Overlapping bracket scans. |
Draw array. Draw brackets for every possible length. Calculate XOR for each and circle the ones where result is zero. |
Prefix XOR + Hash Map (First Occurrence) |
XOR Anchor Points |
Calculate running prefix XOR. If `PrefXOR[i] == PrefXOR[j]`, then the subarray from `i+1` to `j` has a XOR of 0. Store the first time each XOR value is seen in a map. |
Draw array. Underneath, write running XOR (e.g., 5, 2, 7, 2...). Circle the two "2"s. Draw a bracket between them. That's a XOR-0 subarray. |
Single Linear Pass $O(N)$. |
Draw a flat timeline with dots representing $O(1)$ map lookups. |
Constant re-calculation of XORs. |
Hash Map [XOR_Value -> First_Index]. |
| 3756 |
Concatenate Non-Zero Digits and Multiply by Sum II (Med) |
Loop through range [1, N]. For each, convert to string, remove '0', parse to BigInt, sum digits, multiply. $O(N \cdot \log N)$. |
Linear enumeration with string manipulation. |
Draw a timeline. For every tick, draw a "process" box that turns "102" into "12" and "3", then multiplies them. |
Digit DP (Combinatorial Math) |
Digit-by-Digit Contribution Tree |
Instead of iterating N, count how many times each digit (1-9) appears in each position (units, tens, etc.) across all numbers up to N, excluding zeros. |
Draw a tree of height 10 (digits). Write "How many numbers have '5' in the hundreds place?". Multiply that count by the positional value and the sum component. |
$O(\log10(N)$) logarithmic time. |
Draw a very short timeline (length ~15-18) representing digits of N. |
Massive string object creation (GC pressure). |
$O(1)$ or $O(\log N)$ state variables. |
| 3757 |
Number of Effective Subsequences (Hard) |
Generate all 2^N subsequences. For each, check if the "effectiveness" condition is met. $O(2^N)$. |
Binary Decision Tree. |
Draw a tree branching at every element: "Take" or "Leave". Tally validity at the 2^N leaves. |
Sorting + Dynamic Programming / Two Pointers |
Subsequence Contribution States |
Sort the array. For each element, use DP to count how many subsequences ending at this element meet the condition, potentially using a Fenwick tree for range sums. |
Draw sorted array. For current element, draw arrows looking back to valid previous elements. Sum their DP values and write in the current box. |
$O(N \log N)$ or $O(N^2)$. |
Draw an upward curve for sorting, then a dense web of "look-back" arrows over the array. |
Stack frames for recursion. |
1D DP Array + Segment Tree/Fenwick Tree layout. |
| 3758 |
Convert Number Words to Digits (Med) |
Split string by spaces. Use a large switch-case or nested if-statements to handle "thousand", "million", etc., manually managing a current total. |
Conditional Branching Tree. |
Draw the sentence. Above each word, write its value. Draw circles around "million" to group previous words. |
Stack-Based Parsing / Grammar state machine |
Multiplier-Triggered Accumulation |
Maintain a `current` and `total` variable. Numbers add to `current`. Multipliers ("thousand") multiply `current` and add to `total`, then reset `current`. |
Draw two boxes: "Temp" and "Total". Write numbers in Temp. When "million" appears, multiply Temp by 1M, move to Total, clear Temp. |
$O(N)$ linear scan of words. |
Draw a flat timeline with dots representing word processing steps. |
Heavy string splitting and array creation. |
$O(1)$ integer variables + a small static Map for lookups. |
| 3759 |
Count Elements With at Least K Greater Values (Med) |
For every element in the array, run a second loop to count how many elements in the array are strictly greater than it. $O(N^2)$. |
Nested Loop Grid. |
Draw the array. Pick one element. Draw arrows to every larger number. Tally them. Move to next element. |
Sorting / Frequency Map + Suffix Sum |
Sorted Rank Reference |
Sort the array descending. For any element at index `i`, there are `i` elements greater than or equal to it. Adjust for duplicates using a frequency map or `bisect_right`. |
Draw sorted array. Write indices 0 to N-1 above. For any number, the index tells you how many are "to its left" (greater). |
$O(N \log N)$ for sorting. |
Draw a sorting curve followed by a single linear pass. |
N^2 comparisons. |
$O(1)$ extra space (in-place sort). |
| 3760 |
Maximum Substrings With Distinct Start (Med) |
Generate all possible substrings. For each, check if the first character is unique among all selected substrings. $O(N^2)$. |
Sub-segment set selection. |
List all substrings. Circle groups of them where no two circled strings start with the same character. Find the biggest group. |
Greedy Selection + Boolean Array/Set |
Character Slot Filling |
Each character 'a-z' can only be the "start" of ONE substring in our set. To maximize length/count, greedily pick the longest or most restricted first. |
Draw 26 boxes (A-Z). When you pick a substring starting with 'G', put a checkmark in box 'G'. You can't use box 'G' again. |
$O(N)$ or $O(26\cdot N)$. |
Draw a flat timeline with a small auxiliary 26-slot table below it. |
Massive set of strings. |
Fixed-size boolean array (size 26) or small Hash Set. |
| 3761 |
Minimum Absolute Distance Between Mirror Pairs (Med) |
Iterate through all possible swaps of elements to find a configuration where the sum of absolute differences between arr[i] and arr[n-1-i] is minimized. $O(N!)$. |
Permutation Tree. |
Draw the array. Draw lines connecting mirror positions (start and end). Swap two elements, redraw lines, and recalculate total distance. Repeat for all pairings. |
Greedy / Sorting Mirror Elements |
Bilateral Sorting |
To minimize |a - b|, a and b should be as close as possible. Treat each pair of mirror indices as a bucket. Collect all elements, sort them, and place the two closest remaining elements into mirror positions. |
Draw the array. Draw arrows connecting i and N-1-i. Sort the entire array. Take the two middle-most elements and place them in the first mirror pair, then the next two, and so on. |
$O(N \log N)$ for sorting. |
Draw a sorting curve followed by a single pass filling mirror slots. |
$O(N!)$ storage for permutations. |
$O(1)$ auxiliary space (if sorting in-place). |
| 3762 |
Minimum Operations to Equalize Subarrays (Hard) |
Try every possible target value (from min to max of array). For each target, calculate the operations needed for every possible subarray partition. $O(N^3)$. |
Brute force search over value range and partition space. |
Draw the array. Pick a target number. Draw different ways to cut the array into subarrays. Calculate "cost to reach target" for each slice. |
DP + Median Properties / Slopes |
Slope Trick / Cost Surface Visualization |
The cost to equalize elements to a value x is minimized when x is the median. Use DP where dp[i] is the min cost for prefix i. Optimize the transition using a sliding window median or slope trick. |
Draw dp array. For dp[i], look back at dp[j]. Draw a "median-finding" box for the range [j, i] and add that cost to dp[j]. |
$O(N^2)$ or $O(N \log N)$ with data structures. |
Draw a DP table being filled with a sliding "Median-Cost" window. |
Exponential state space. |
$O(N)$ for DP array + Heaps for median tracking. |
| 3763 |
Maximum Total Sum With Threshold Constraints |
Generate all possible subsets of elements, check if they meet the threshold constraints, and track the max sum. $O(2^N)$. |
Exponential Subset Tree |
Draw the array. Branch into "Include" or "Exclude" for every item, verifying complex math limits at the end. |
Greedy / Sorting |
The Threshold Cap Filler |
Sort the elements descending. Greedily pick the largest elements. Keep a running tally of constraints. If picking an element violates a threshold, skip it. |
Draw numbers sorted largest to smallest. Draw "buckets" representing thresholds. Drop the largest numbers into the buckets until they hit the "cap line." |
Sorting Bottleneck $O(N \log N)$ |
Draw a sorting tree, followed by a single linear pass to greedily select elements. |
Storing every subset combination. |
In-place sorting variables. $O(1)$ space. |
| 3764 |
Most Common Course Pairs (Hard) |
For every student, generate all pairs of courses they are taking. Count the frequency of every pair across all students using a nested loop. $O(S \cdot C^2)$. |
Pairwise Combination Grid. |
List students. For student A, draw lines between all their courses. Repeat for student B. Count which line (pair) appears most often. |
Hash Map with Tuple Keys / Bitsets |
Frequency Heatmap |
Map each course to a Bitset where the i-th bit is 1 if student i takes it. To find commonality between Course A and B, perform a bitwise AND and count set bits (Popcount). |
Draw a grid: Courses (Rows) vs Students (Cols). Fill with 1s and 0s. To compare two rows, look for columns where both have a "1". |
$O(C^2 \cdot (S/64)$) using bitset optimization. |
Draw a matrix multiplication-style visualization with fast bitwise AND operations. |
Massive list of all course pairs. |
$O(C \cdot S)$ Bitset matrix. |
| 3765 |
Complete Prime Number (Med) |
Check if the number is prime. Then, convert it to a string and check if every individual digit is also a prime number (2, 3, 5, 7). $O(\text{sqrt}(N)$ + log N). |
Sequential Boolean Logic. |
Write the number. Step 1: Divide by 2, 3, 5... to check primality. Step 2: Circle each digit and check against {2,3,5,7}. |
Sieve of Eratosthenes + Digit Mask |
Precomputed Prime Filter |
Precompute primes up to a limit using a Sieve. For the digit check, use a bitmask or a boolean array [F, F, T, T, F, T, F, T, F, F] for digits 0-9. |
Draw a Sieve grid (1-100). Cross out non-primes. For a target number, check the grid, then check each digit against the "Prime Digit" list. |
$O(1)$ after precomputation or $O(\text{sqrt}(N)$). |
Draw a short checklist with two boxes: "Is Prime?" and "Digits Prime?". |
No specific memory structure. |
Boolean array for digits; Sieve array for range queries. |
| 3766 |
Minimum Operations to Make Binary Palindrome (Med) |
Generate every possible palindrome of the same length and count the number of bit flips (Hamming distance) required to reach each. Pick the minimum. $O(2^(N/2)$). |
Exhaustive Palindrome Search. |
Write the binary string. Draw every possible palindrome. Count bit differences between the original and each candidate. Circle the smallest count. |
Two Pointers / Mirror Matching |
Centripetal Pointer Comparison |
Place pointers at index i and n-1-i. If str[i] != str[n-1-i], you MUST flip one of them. Count these mismatches to get the total operations. |
Draw the binary string. Draw arcs connecting mirror indices. If the bits at the end of an arc are different, put a tally mark in the "Flip" box. |
Single Pass $O(N)$. |
Draw a straight horizontal line with an $O(N)$ label. |
Recursive stack for string generation. |
$O(1)$ extra space (just a counter). |
| 3767 |
Maximize Points After Choosing K Tasks (Med) |
Generate all combinations of K tasks out of N, and for each combination, check the constraints and calculate the total points. $O(N \text{choose} K)$. |
Combinatorial Selection Tree. |
Draw N tasks. Draw branches showing every way to pick exactly K tasks. Calculate point totals at the end of each path. |
Greedy with Priority Queue (Max-Heap) |
Top-K Filtering |
If tasks are independent, simply sort by points and take the top K. If they have dependencies or time constraints, use a Max-Heap to always pick the highest available point task that satisfies current constraints. |
Draw a "Pool" of tasks. Draw a "Bucket" for your K choices. Pick the largest task from the pool, drop it in the bucket, and repeat K times. |
$O(N \log N)$ or $O(N \log K)$. |
Draw an N-length array being processed by a Log K depth Heap. |
Storage for all combinations in memory. |
Heap structure of size K. |
| 3768 |
Minimum Inversion Count in Subarrays of Fixed Length (Hard) |
For every subarray of length L, count inversions using a nested loop. $O((N-L)$ * L^2). |
Sliding window with internal quadratic scans. |
Draw the array. Slide a window of length L. For every window position, draw lines between all pairs (i, j) where i < j and arr[i] > arr[j]. |
Sliding Window + Fenwick Tree / Segment Tree |
Dynamic Inversion Counter |
As the window slides: 1) Subtract inversions caused by the exiting element using a Fenwick Tree. 2) Add inversions caused by the entering element. The Fenwick Tree tracks the frequency of values currently in the window. |
Draw a window moving across the array. Below it, draw a Fenwick Tree. When a number enters, "Ask" the tree how many numbers are larger. When it leaves, "Tell" the tree to remove it. |
$O(N \log L)$. |
Draw a horizontal line (sliding) with a small tree icon (log L) above each step. |
N subarrays stored as separate lists. |
Fenwick Tree array of size proportional to value range or L. |
| 3769 |
Sort Integers by Binary Reflection (Easy) |
For every integer, convert it to a binary string, reverse the string, convert it back to an integer, and then sort the array based on these new values. |
Transformation-Sort Pipeline. |
Write [1, 2, 3]. Step 1: Binary [01, 10, 11]. Step 2: Reverse [10, 01, 11]. Step 3: Back to decimal [2, 1, 3]. Step 4: Sort original by these keys. |
Custom Comparator with Bitwise Manipulation |
In-Place Bit-Reversal Logic |
Use a sorting function with a custom comparator. Inside the comparator, reflect the bits of the two numbers using bitwise operations (shift and mask) to compare their "reflected" values without string conversion. |
Draw two numbers. Show their bits swapping positions (Bit 0 with Bit N, etc.). Compare the results directly. |
$O(N \log N \cdot \log(\text{Value})$). |
Draw a sorting curve where each comparison has a small "Bit Swap" loop. |
Multiple string objects for every number. |
$O(1)$ auxiliary space (in-place sort). |
| 3770 |
Largest Prime from Consecutive Prime Sum (Med) |
Find all primes up to N. For every possible sequence of consecutive primes, calculate their sum and check if that sum is also prime. $O(P^3)$ where P is the number of primes. |
Nested Summation and Primality Checks. |
List primes [2, 3, 5, 7...]. Draw brackets for [2+3], [2+3+5], [3+5+7]... Check if each sum is in the prime list. |
Sieve of Eratosthenes + Sliding Window / Prefix Sums |
Prime-Only Timeline |
1) Sieve up to N to get all primes. 2) Use a Prefix Sum array of these primes. 3) Any consecutive sum is Prefix[j] - Prefix[i]. If this sum <=q N and is prime (use the Sieve for $O(1)$ check), update max. |
Draw a horizontal line of prime numbers. Below it, draw a Prefix Sum line. Draw an elastic bracket over the prime line; if the sum it covers is prime, mark it as a candidate. |
$O(N \log \log N)$ Sieve + $O(P^2)$ Sum checks. |
Draw a Sieve grid followed by a 2D scan of the Prefix Sum array. |
Deep recursion for sum checking. |
$O(N)$ Boolean array for the Sieve. |
| 3771 |
Total Score of Dungeon Runs (Med) |
Exhaustively explore every possible path from top-left to bottom-right in a grid using recursion/DFS, summing the scores for all paths. $O(2^(R+C)$). |
Exponential Path Web. |
Draw a grid. Draw arrows for every possible move (Right/Down). Follow every trail to the exit, writing the path sum at the end. Total them all. |
2D Dynamic Programming (Path Counting) |
Grid Score Accumulator |
Each cell dp[r][c] stores the sum of scores of all paths reaching it. dp[r][c] = (dp[r-1][c] + dp[r][c-1]) + (CurrentCellValue * NumPaths). |
Draw a grid. In each cell, write two numbers: "Ways to reach" and "Total Score so far". Use the top and left neighbors to update both numbers. |
$O(R \cdot C)$ Matrix fill. |
Draw a square grid and shade it row-by-row, showing values flowing into each cell from the top and left. |
Massive recursive call stack. |
Two 2D arrays (Score DP and Path Count DP) or optimized 1D rows. |
| 3772 |
Maximum Subgraph Score in a Tree (Hard) |
Try every possible subset of nodes. Check if they form a connected component (subgraph). If yes, calculate the sum and find the max. $O(2^N \cdot N)$. |
Connected Component Power Set. |
Draw a tree. Circle every possible connected group of nodes. Sum the values in each circle and find the highest number. |
Tree Dynamic Programming (Kadane's on Trees) |
Subtree Sum Propagation |
For each node, calculate the maximum score of a subtree rooted at that node that *must* include the node. dp[u] = val[u] + sum(max(0, dp[v])) for all children v. |
Draw a tree. Start at the leaves. If a leaf is positive, "send" its value up to its parent. If negative, send 0. The parent adds its own value to the incoming sums. |
$O(N)$ single DFS traversal. |
Draw a tree with upward-pointing arrows from children to parents, showing values aggregating at each node. |
$O(2^N)$ state storage. |
Recursive stack (Depth of tree) + 1D DP array. |
| 3773 |
Maximum Number of Equal Length Runs (Med) |
Generate all possible ways to partition the array into "runs" (consecutive equal elements). Count how many have the same length. $O(2^N)$. |
Recursive Partitioning. |
Write the array. Draw lines between numbers to create segments. Count segments of equal size. Repeat for every possible line placement. |
Hash Map + Grouping (Run-Length Encoding) |
Frequency of Frequencies |
Perform Run-Length Encoding (e.g., [1,1,2,2,2,3] becomes lengths: [2, 3, 1]). Put these lengths into a Hash Map to count their occurrences. Return the max value in the map. |
Draw the array. Bracket identical neighbors (e.g., "Two 1s", "Three 2s"). Write the lengths in a list. Tally how many times each length appears in a frequency table. |
Single Linear Pass $O(N)$. |
Draw a straight timeline with a "Bucket" for each run length found. |
$O(2^N)$ partition combinations. |
Hash Map of size proportional to number of unique run lengths. |
| 3774 |
Absolute Difference Between Maximum and Minimum K Elements (Easy) |
Try every possible subset of size K. For each, find the max and min, calculate the difference, and find the overall minimum/maximum difference. $O(N \text{choose} K)$. |
Combinatorial Selection. |
Draw N dots. Circle any K dots. Find the widest and narrowest range. Repeat for every single way to pick K dots. |
Sorting + Sliding Window (Fixed Size K) |
Sorted Distance Bracket |
Sort the array. The set of K elements with the smallest difference between max and min will always be contiguous. Use a window of size K and calculate arr[i + K - 1] - arr[i]. |
Draw the array and sort it. Draw a fixed-width bracket covering K elements. Slide it from left to right, measuring the distance between the two ends of the bracket. |
$O(N \log N)$ Sorting + $O(N)$ Scan. |
Draw a sorting curve followed by a single pass with a fixed sliding bracket. |
$O(N \text{choose} K)$ combinations in memory. |
$O(1)$ extra space (in-place sort). |
| 3775 |
Reverse Words With Same Vowel Count (Med) |
For every pair of words, count their vowels. If they match, swap them. Repeat this until no more swaps can be made or try all permutations. $O(N!)$. |
Permutation Word Scrambling. |
List words. Draw lines between words with the same vowel count. Try swapping them in different orders to see which ones are "allowed". |
Grouping by Vowel Count + Reverse Pointers |
Bucket-Based Reversal |
Group the *indices* of words by their vowel counts. For each group, reverse the words found at those indices while keeping other words in place. |
Draw the sentence. Above each word, write its vowel count. Circle all words with "2" vowels. Draw arrows swapping the first circled word with the last, second with second-to-last, etc. |
$O(N \\text{cdot WordLength})$. |
Draw a flat timeline with "Color-coded" buckets for vowel counts, then show reversal within each color. |
Massive string permutations. |
Hash Map [VowelCount -> List of Indices] + Array of Words. |
| 3776 |
Minimum Moves to Balance Circular Array (Med) |
Simulate every possible "shift" of elements in a circular fashion. For each shift, calculate the moves to reach a balanced state (e.g., all elements equal to average). $O(N^2)$. |
Circular Shift Matrix. |
Draw the array as a ring. Try moving "units" clockwise and counter-clockwise between all neighbors until equal. Repeat starting the process from every index. |
Prefix Sums on Doubled Array + Median of Differences |
Unrolled Ring Linearization |
Double the array to handle circularity. A balanced state requires moving values to eliminate the "debt" or "surplus" at each index. The optimal point to "break" the circle is found by the median of the prefix sums of differences. |
Draw the array twice side-by-side. Calculate prefix sums of (arr[i] - average). Find the median value of these prefix sums. The cost is the sum of absolute distances to this median. |
$O(N \log N)$ due to sorting for median. |
Draw a linear prefix sum graph and a horizontal "Median" line passing through it. |
$O(N^2)$ simulation states. |
$O(N)$ for doubled prefix sum array. |
| 3777 |
Minimum Deletions to Make Alternating Substring (Hard) |
Generate all 2^N subsequences, check if they are alternating (e.g., "0101" or "1010"), and find the longest one. Subtract its length from N. $O(2^N)$. |
Binary Subsequence Tree. |
Draw the string. Branch for every character: "Keep" or "Delete". At the leaves, check if the resulting string flickers between 0 and 1. |
Greedy Single Pass / State Machine |
Flicker Tracker |
Walk through the string. Keep a variable expected. If the current character matches expected, keep it and flip expected. If not, "delete" it (increment count). |
Write the string. Below it, write the pattern "0101...". Draw a line connecting the first '0' in the string to the '0' in the pattern, then the next '1', and so on. Any skipped characters are deletions. |
Single Linear Pass $O(N)$. |
Draw a flat timeline with a "Next Expected" toggle box. |
Recursive stack for all subsequences. |
$O(1)$ extra space (just 2-3 variables). |
| 3778 |
Minimum Distance Excluding One Maximum Weighted Edge (Med) |
For every edge in the graph, temporarily remove it and run Dijkstra's algorithm to find the shortest path between start and end. $O(E \cdot (E + V \log V)$). |
Edge-Removal Iteration. |
Draw a graph. Erase one line. Find the shortest path. Put the line back, erase the next one. Compare all results. |
Modified Dijkstra / BFS with State |
Layered Graph Traversal |
Run Dijkstra where the state is (node, has_excluded_edge). Alternatively, find the shortest path normally, then for every edge (u, v) in the graph, consider the path dist[u] + dist_from_end[v] (skipping the weight of (u, v)). |
Draw two versions of the graph: "Layer 0" (haven't used the skip) and "Layer 1" (have used the skip). Draw directed edges from Layer 0 to Layer 1 representing the "skipped" edge. |
$O(V \log V + E)$. |
Draw a Dijkstra priority queue progression on a 2-layered graph. |
E copies of the graph/distance array. |
$O(V)$ distance array and $O(E)$ graph storage. |
| 3779 |
Minimum Number of Operations to Have Distinct Elements (Med) |
Iteratively remove elements from the start of the array one by one until all remaining elements are unique. $O(N^2)$. |
Sequential Shifting and Set Checks. |
Draw the array. Check if unique. If not, erase the first element. Check again. Repeat until the "Seen" set doesn't have duplicates. |
Reverse Scan + Hash Set |
Suffix Uniqueness Boundary |
Scan the array from *right to left*. Keep track of elements in a Hash Set. The moment you hit an element already in the set, the boundary for "distinct elements" is just to the right of that position. |
Draw the array. Start at the end. Move left, adding numbers to a circle. Stop when you try to add a number that is already in the circle. Everything to the left of your finger must be removed. |
Single Linear Pass $O(N)$. |
Draw a timeline from Right to Left with $O(1)$ Set lookups. |
Repeated array slicing and set creation. |
$O(N)$ Hash Set. |
| 3780 |
Maximum Sum of Three Numbers Divisible by Three (Med) |
Generate all combinations of three numbers, calculate their sum, check if sum % 3 == 0, and track the maximum. $O(N^3)$. |
Triple Pointer Brute Force. |
Pick three numbers from the list. Add them. If the result is a multiple of 3, write it down. Check every possible triplet. |
Greedy / Bucketing by Remainder |
Remainder Pigeonhole Buckets |
Sort and group numbers into three buckets based on val % 3 (Remainders 0, 1, and 2). Valid triplets are (0,0,0), (1,1,1), (2,2,2), or (0,1,2). Pick the largest numbers from these buckets to maximize the sum. |
Draw three boxes labeled "Rem 0", "Rem 1", "Rem 2". Sort the numbers into them. Pick the top 3 from Rem 0; compare with picking the top 1 from each; compare with top 3 from Rem 1, etc. |
$O(N \log N)$ for sorting or $O(N)$ if only top-3 are kept. |
Draw a sorting pass followed by 4-5 constant-time comparisons. |
N^3 combinations in memory. |
$O(1)$ extra space (keeping only top-3 of each remainder). |
| 3781 |
Maximum Score After Binary Swaps (Med) |
Generate all possible strings reachable by any number of adjacent swaps of '0' and '1', then calculate the score for each. $O(2^N)$. |
State Space Reachability Graph. |
Draw the binary string. Draw branches for every possible swap. Follow the branches to see all unique string outcomes and calculate scores. |
Greedy Counting / Frequency Analysis |
Bit Re-distribution |
Adjacent swaps allow you to move any '1' to any position. To maximize a score (usually based on prefix/suffix or value), count the total number of '1's and '0's and place all '1's at the most "valuable" positions (e.g., the front). |
Write the string. Count the '1's. Draw a new string of the same length, filling the first N slots with '1's and the rest with '0's. This is your "perfect" swap result. |
Single Linear Pass $O(N)$. |
Draw a flat timeline with two counters (One for '0', one for '1'). |
Recursive state tree storage. |
$O(1)$ extra space (just bit counters). |
| 3782 |
Last Remaining Integer After Alternating Deletion Operations (Hard) |
Actually perform the deletions: remove every 2nd element from left to right, then every 2nd from right to left, until one remains. $O(N^2)$ or $O(N \log N)$ with list slicing. |
Step-by-Step List Shrinking. |
Write 1 to N. Cross out 2, 4, 6... Now go backwards and cross out every other remaining number. Repeat until only one is left. |
Mathematical Simulation (Step & Head Tracking) |
Arithmetic Progression Refinement |
Track the head of the remaining sequence, the step size (starts at 1), and the number of elements remaining. After each pass, double the step and update the head if the deletion removes the current head. |
Draw a line representing 1..N. Write "Head = 1, Step = 1". Show the "Head" jumping as numbers are deleted. Every round, the "Head" moves by the current "Step" size under specific conditions. |
Logarithmic Time $O(\log N)$. |
Draw a line halving repeatedly with a "Head" dot jumping larger and larger gaps. |
Multiple copies of the array during slicing. |
$O(1)$ extra space (just 3-4 integer variables). |
| 3783 |
Mirror Distance of an Integer (Easy) |
Convert the integer to a string, reverse the string, convert it back to an integer, and calculate the absolute difference. $O(\text{Digits})$. |
String Transformation Pipeline. |
Write "123". Write its reverse "321". Subtract the smaller from the larger: |123 - 321| = 198. |
Mathematical Remainder Reversal |
Digit Extraction and Reassembly |
Use % 10 to get the last digit and * 10 to shift the reversed result. No strings required. Subtract the original from this math-reversed result. |
Draw a "Number" box and a "Reverse" box. Use a loop to pop digits from the bottom of "Number" and push them into the top of "Reverse". |
$O(\log10(N)$) (Number of digits). |
Draw a very short horizontal line with $O(\log N)$ above it. |
Heap allocation for string objects. |
$O(1)$ extra space (pure integer arithmetic). |
| 3784 |
Minimum Deletion Cost to Make All Characters Equal (Med) |
Try making the string all 'a's, then all 'b's, etc. For each target character, sum the deletion costs of all characters that are NOT that character. $O(26 \cdot N)$. |
26-Target Comparison. |
List costs for "apple". Target 'p': Delete 'a', 'l', 'e'. Sum their costs. Target 'a': Delete 'p', 'p', 'l', 'e'. Sum their costs. Pick the minimum total. |
Total Cost - Max Character Frequency Cost |
Complementary Summation |
Calculate the total_cost of all characters. Then, for each character 'a-z', calculate the sum_of_costs for only that character. The answer is total_cost - max(sum_of_costs). |
Draw a bar chart where the X-axis is 'a-z' and the Y-axis is the total cost for that letter. Find the tallest bar. The "Minimum Deletion" is the sum of all other bars. |
Single Linear Pass $O(N)$. |
Draw a flat timeline with 26 "accumulators" (buckets) below it. |
$O(N)$ to store filtered strings for each case. |
$O(1)$ auxiliary space (Fixed 26-element array). |
| 3785 |
Minimum Swaps to Avoid Forbidden Values (Hard) |
Generate all N! permutations of the array and check each one to see if any element at index i is a forbidden value for that index. Pick the one with the fewest swaps from the original. $O(N! \cdot N)$. |
Permutation Validation Tree. |
Draw the array. Draw all ways to rearrange it. Cross out any arrangement where a "forbidden" number lands in a "forbidden" spot. Count swaps for the survivors. |
Min-Cost Flow / Hungarian Algorithm |
Bipartite Matching with Weights |
Model this as a Bipartite Graph: Left side is original values, Right side is indices. Edge weight is 0 if val == original_at_index, and 1 otherwise. Delete edges where val is forbidden for that index. Find the Minimum Weight Perfect Matching. |
Draw two columns of dots. Draw lines between them. Put an 'X' on forbidden lines. Give each line a cost (0 or 1). Find the set of lines that connects every dot with the lowest total cost. |
$O(N^3)$ or $O(E\cdot V)$. |
Draw a bipartite grid being resolved by augmenting paths. |
N! storage for permutations. |
$O(N^2)$ for the adjacency matrix or cost graph. |
| 3786 |
Total Sum of Interaction Cost in Tree Groups (Hard) |
Partition the tree into all possible group combinations. For each partition, calculate the distance between all pairs of nodes within the same group and sum them up. $O(\text{Partitions} \cdot N^2)$. |
Brute Force Partitioning and Pathfinding. |
Draw a tree. Cut it into two random groups. For every node in group A, measure the distance to every other node in group A. Repeat for group B. Tally all distances. |
Tree DP + Centroid Decomposition / Contribution of Edges |
Edge Contribution Multiplier |
Instead of summing pairs, count how many times each edge is crossed. An edge (u, v) with weight w is crossed by S_u x (Total - S_u) pairs, where S_u is the size of the subtree. Sum these contributions across the tree. |
Draw a tree. On each edge, write a number: (Nodes on the left) x (Nodes on the right). Multiply that by the edge weight. Sum all the results on the edges. |
$O(N)$ single DFS traversal. |
Draw a tree with "Weight" values assigned to edges based on subtree sizes. |
Massive list of all partitions and pairs. |
$O(N)$ for subtree size array and recursion stack. |
| 3787 |
Find Diameter Endpoints of a Tree (Med) |
For every node, run a BFS/DFS to find the distance to every other node. Record the two nodes that have the maximum possible distance between them. $O(N^2)$. |
All-Pairs Pathfinding. |
Draw a tree. Pick node 1, find furthest node. Pick node 2, find furthest node. Repeat for every node in the tree until you find the global maximum distance. |
Double BFS / DFS |
Furthest-Point Traversal |
1) Start BFS from an arbitrary node X to find the furthest node A. 2) Start a second BFS from A to find the furthest node B. A and B are the endpoints of the diameter. |
Draw a tree. Start at the root. Draw an arrow to the leaf furthest away (Node A). Now, starting from Node A, draw a long arrow to the leaf furthest from it (Node B). |
Two Linear Passes $O(N)$. |
Draw two sequential tree-contour scans. |
$O(N^2)$ distance matrix. |
$O(N)$ for adjacency list and BFS queue. |
| 3788 |
Maximum Score of a Split (Med) |
Try splitting the array/string at every possible index. Calculate the score of the left part and the right part independently. Find the index that maximizes the sum. $O(N^2)$. |
Exhaustive Split-Point Search. |
Write the array. Draw a vertical line at index 1, calculate score. Move the line to index 2, calculate score. Repeat until the end. |
Prefix and Suffix Accumulators |
Dual-Pass Balance |
Precalculate a prefix_score array (left-to-right) and a suffix_score array (right-to-left). The total score at any index i is simply prefix[i] + suffix[i+1]. |
Draw the array. Above it, write the "running score" from left to right. Below it, write the "running score" from right to left. Find the column where the top and bottom numbers add up to the highest total. |
Three Linear Passes $O(N)$. |
Draw three parallel horizontal lines (Prefix, Suffix, Comparison). |
Repeatedly calculating scores from scratch. |
Two 1D arrays of size N. |
| 3789 |
Minimum Cost to Acquire Required Items (Med) |
Try every subset of available items and check if the subset contains all "required" items. Calculate the total cost for each valid subset and pick the minimum. $O(2^N)$. |
Power Set Selection. |
List all items and their costs. Write every combination of items. Check if "Required Items" are inside each combo. Find the cheapest one. |
Bitmask Dynamic Programming (Knapsack Variant) |
State-Space Masking |
Represent the "Required Items" as bits in an integer (Bitmask). dp[mask] is the min cost to acquire the items represented by that mask. For each new item, update the DP table: dp[mask | item_mask] = min(dp[mask | item_mask], dp[mask] + item_cost). |
Draw a table where the header is bitmasks (001, 010, 011...). For each item, draw arrows showing how it "flips" the bits and updates the cost in the table. |
$O(N \cdot 2^K)$, where K is the number of required items. |
Draw a DP grid being filled row by row (Items) and column by column (Masks). |
Recursive stack for all 2^N combinations. |
1D DP array of size 2^K. |
| 3790 |
Smallest All-Ones Multiple (Med) |
Test numbers 1, 11, 111, 1111... one by one by dividing them by N until the remainder is zero. $O(N)$ or more depending on digit count. |
Sequential Modulo Testing. |
Write "1". Is 1/N remainder 0? No. Write "11". Is 11/N remainder 0? No. Repeat, adding a '1' each time until it works. |
Pigeonhole Principle + Iterative Modulo |
Modular Orbit Tracker |
Maintain a running remainder: rem = (rem * 10 + 1) % N. If you see the same remainder twice before hitting 0, it may cycle, but for coprime N and 10, you'll always hit 0 within N steps. |
Draw a "Remainder" bucket. Start with 1. Multiply by 10, add 1, then take the remainder of N and put it back in the bucket. Count how many times you do this until the bucket is 0. |
Linear Scan $O(N)$. |
Draw a loop that runs up to N times with a single modulo operation inside. |
Storing massive strings of "1"s in memory. |
$O(1)$ auxiliary space (just 2-3 integer variables). |
| 3791 |
Number of Balanced Integers in a Range (Hard) |
Iterate through every integer from low to high. For each, calculate the sum of digits at even positions and odd positions. Increment count if they match. $O((\text{High}-\text{Low})$ * log N). |
Linear Range Enumeration. |
Write out 100 to 200. For "121": Odd(1+1)=2, Even(2)=2. Match! Circle it. For "122": Odd(1+2)=3, Even(2)=2. No. Repeat for every number. |
Digit Dynamic Programming (Digit DP) |
Constraint-Based State Tree |
Build the number digit by digit. State: dp(index, diff, isLess, isStarted), where diff is the running difference between odd and even position sums. Result is count(high) - count(low-1). |
Draw a tree where each level is a digit position. The nodes store the current "balance" (OddSum - EvenSum). Only follow paths where the final balance can realistically reach 0. |
$O(\text{Digits} \\text{cdot MaxSum} \cdot 2)$ states. |
Draw a 1D timeline of length 18 (max digits), with a small 2D matrix (Sum x Diff) being filled at each step. |
Massive CPU time; time limit exceeded. |
Memoization table (4D/5D array) of small dimensions. |
| 3792 |
Sum of Increasing Product Blocks (Med) |
Generate all possible ways to partition the array into blocks. For each partition, check if the product of each block is strictly increasing. Sum the products of all valid partitions. $O(2^N)$. |
Partition Power Set. |
Draw the array. Draw lines to split it into chunks. Calculate products. If product sequence is 2, 10, 50, it's valid. Add 2+10+50 to total. Try every single split combination. |
Linear DP + Monotonic Optimization |
State Summation Flow |
dp[i][last_product] stores the sum of products of all valid partitions ending at index i with the last block's product being last_product. Use a Map to handle the large state space of products. |
Draw an array. For each index, draw arrows looking back. Each arrow carries a "Product" and a "Running Sum". Only arrows where new_product > old_product are allowed to contribute to the current cell. |
$O(N^2)$ or $O(N \\text{cdot unique}_\text{products})$. |
Draw a grid where rows are indices and columns are product values. Shade cells where the "increasing" rule is satisfied. |
Exponential recursive paths. |
1D or 2D DP array (often optimized with a Hash Map per index). |
| 3793 |
Find Users with High Token Usage (Easy) |
Iterate through all token usage logs. For each log, search for the user in a list, update their total, then iterate the list again to find users exceeding the threshold. $O(L \cdot U)$. |
Nested Search and Tally. |
Draw a log file with names and numbers. Take a highlighter. Find "Alice", add her numbers. Find "Bob", add his. Circle names that pass the "1000" mark. |
Hash Map Aggregation |
Key-Value Accumulator |
Use a Hash Map where keys are UserIDs and values are TotalTokens. Iterate the logs once to populate the map, then iterate the map to filter users. |
Draw a table with two columns: "User" and "Tokens". As you read the logs, update the token count next to the user's name. Finally, cross out anyone with tokens below the limit. |
Single Linear Pass $O(L)$. |
Draw a flat timeline with an $O(1)$ map "Drop-in" at every log entry. |
Multiple passes over large raw log files. |
Hash Map in memory (O(U) space where U is unique users). |
| 3794 |
Reverse String Prefix (Easy) |
Iterate through the string to find the first occurrence of character ch. Create a new string by manually copying the characters backward up to that index, then copy the rest. $O(N)$. |
Find and Slice. |
Write "abcdefd" and target "d". Find the first 'd'. Write the letters before it backwards: "dcba". Then write the rest: "efd". Result: "dcbaefd". |
Two Pointers (In-place Swap) |
Mirror Swap Segment |
Find the index i of the first ch. Use two pointers (start=0, end=i) to swap characters in the original array until they meet in the middle. |
Draw the string. Circle the first target character. Draw arcs between the start and that character, showing them swapping places. The tail of the string stays untouched. |
Single Pass $O(N)$. |
Draw a flat timeline with a single $O(N)$ search and a small $O(i/2)$ swap loop. |
Creating multiple substring objects. |
$O(1)$ extra space (if modifying character array in-place). |
| 3795 |
Minimum Subarray Length With Distinct Sum At Least K (Med) |
Generate all $O(N^2)$ subarrays. For each, count unique elements to see if the count is >=q K. Calculate length and find the minimum. $O(N^3)$. |
Exhaustive Sub-segment Scan. |
Draw the array. Bracket every possible chunk. Inside each bracket, count how many *different* numbers there are. If count >=q K, record length. Find the shortest bracket. |
Sliding Window + Frequency Map |
Elastic Contractive Window |
Expand the right pointer and update a frequency map until the number of distinct elements is >=q K. Then, shrink the left pointer as much as possible while maintaining the condition. |
Draw the array. Draw a bracket [ ]. Move the right side until you have K distinct numbers. Now drag the left side forward until you're about to lose a distinct number. The size of the bracket is your current "Best". |
Amortized Linear $O(N)$. |
Draw a timeline where two pointers move strictly rightward, never backtracking. |
Redundant counting for every subarray. |
Hash Map of current window frequencies (O(N) or $O(K)$ space). |
| 3796 |
Find Maximum Value in a Constrained Sequence (Med) |
Generate all possible sequences that satisfy the local constraints (e.g., |a_i - a_i-1| <=q K) and track the maximum value reached in any valid sequence. $O(\text{Branch}^N)$. |
Explosive Constraint Tree. |
Draw a starting number. Branch out to all numbers within distance K. From those, branch again. Follow all paths to length N and find the highest number in the entire tree. |
Dynamic Programming / Greedy Range Extremes |
Maximum Reachable Ceiling |
Calculate the maximum possible value at each index i by taking max_val[i] = min(upper_bound[i], max_val[i-1] + K). Then perform a backward pass to ensure the sequence can also satisfy constraints relative to future bounds. |
Draw the constraints as a set of "ceiling" bars. At each step, draw a point as high as possible, but no more than K units higher than the previous point and no higher than the current bar. |
Two Linear Passes $O(N)$. |
Draw two parallel horizontal lines (Forward and Backward constraint propagation). |
Deep recursive call stack. |
1D array of size N to store reachable maximums. |
| 3797 |
Count Routes to Climb a Rectangular Grid (Hard) |
Use recursion with DFS to count every path from the bottom row to the top row, moving only to adjacent higher cells. $O(3^N)$. |
Recursive Path Enumeration. |
Draw a grid. Start at a bottom cell. Draw arrows to the 3 cells above it (Left-Diag, Up, Right-Diag). Repeat until you hit the top. Count every single line. |
2D Dynamic Programming (Layered) |
Pascal's Triangle on a Grid |
The number of ways to reach cell (r, c) is the sum of ways to reach its three predecessors in the row below: (r+1, c-1), (r+1, c), (r+1, c+1). |
Draw a grid. Fill the bottom row with 1s. For the next row up, each cell's value is the sum of the three values directly below/diagonal to it. Continue to the top. |
$O(R \cdot C)$ Matrix fill. |
Draw a square grid and shade it row-by-row from bottom to top. |
Massive recursion tree. |
One or two 1D arrays of size C (current row and previous row). |
| 3798 |
Largest Even Number (Easy) |
Generate all permutations of the given digits, convert them to integers, and find the largest one that ends in an even digit. $O(D!)$. |
Permutation List Filtering. |
Write digits [1, 2, 3]. List: 123, 132, 213, 231, 312, 321. Filter evens: 132, 312. Largest: 312. |
Greedy Sorting + Last Digit Swap |
Sorted Digit Re-alignment |
Sort digits descending to get the largest possible number. If the last digit is odd, find the smallest even digit in the number and swap it to the last position to satisfy the "even" requirement. |
Draw the digits. Sort them: 9, 8, 5, 3, 1. Look for an even number. Found '8'. Move '8' to the very end: 9, 5, 3, 1, 8. |
$O(D \log D)$ for sorting digits. |
Draw a sorting pass followed by a single linear scan for the even digit. |
$O(D!)$ combinations in memory. |
$O(D)$ character array for digits. |
| 3799 |
Word Squares II (Med) |
Try every combination of words for the grid rows and check if grid[i][j] == grid[j][i] for all indices. $O(N^K)$. |
Brute Force Backtracking. |
Pick a word for Row 1. This forces Column 1. Pick a word for Row 2 that matches the 2nd letter of Column 1. Repeat until the square is full or invalid. |
Trie-Based Backtracking |
Prefix-Guided Search |
Build a Trie of all words. When picking the k-th word, you know its required prefix because it must match the characters already placed in the k-th column of previous rows. Use the Trie to quickly find all words starting with that prefix. |
Draw a grid. Fill Row 1. Now, Column 1 is fixed. Use the prefix formed by Row 1, Col 2 to search the Trie for valid Row 2 words. Draw the Trie path for each prefix. |
$O(N \cdot 26^L)$ where L is word length. |
Draw a backtracking tree where each node represents a Trie prefix lookup. |
Deep recursive search across all word combinations. |
Trie data structure (Prefix Tree) in memory. |
| 3800 |
Minimum Cost to Make Two Binary Strings Equal (Med) |
Try every combination of bit-flips and adjacent swaps to transform String A into String B, tracking the total cost. $O(2^N \cdot N!)$. |
State-Space Search (Dijkstra). |
Write String A. Draw arrows for "Flip" (Cost X) and "Swap" (Cost Y). Follow all paths until String B is reached. Pick the cheapest path. |
Dynamic Programming / Greedy Matching |
Mismatch Pairing |
Identify indices where A[i]
eq B[i]. To fix these, you can either flip them individually (Cost X x count) or "swap" a '0' and '1' from two different mismatch positions (Cost Y x distance). Use DP to find the cheapest way to pair up or flip mismatches. |
Draw two strings. Mark the "Mismatched" spots with 'X'. Draw lines connecting pairs of 'X's. Below each line, write min(2X, Y * distance). Sum the costs of the cheapest pairings. |
$O(N^2)$ or $O(N)$ depending on swap constraints. |
Draw a 1D DP array tracking the cost to resolve the first i mismatches. |
Massive reachability graph. |
$O(M)$ where M is the number of mismatches. |
| 3801 |
Minimum Cost to Merge Sorted Lists (Hard) |
Recursive Backtracking: Try merging all possible pairs (i, j) at every step and calculate the minimum cost path. |
Recursion Tree Diagram highlighting massive overlapping subproblems. |
Draw a root node representing N lists. Branch out for every NC2 pair. Below each, draw N-1 lists. Show the factorial $O(N!)$ explosion. |
Bitmask Dynamic Programming (DP on Subsets). |
State Space Directed Acyclic Graph (DAG) using bit strings. |
Represent array presence as bits (011 = lists 0 and 1 active). Track cost transitions from 111...1 down to 000...0. |
Draw binary states in circles (e.g., 111). Draw directed edges to states with one fewer '1'. Label edges with the merge cost formula. |
DAG Node/Edge count grid. |
Write DP states: 2^N. Next to it, write transition loops: $O(N^2)$. Draw a multiplication sign between them: $O(2^N \cdot N^2)$. |
Call Stack Frames stacked high, showing the deep recursion depth and cloned arrays. |
A 1D Array of size 2^N. Visualize the bitmask index converting to a memory slot storing the 'long long' minimum cost. |
| 3802 |
Number of Ways to Paint Sheets (Hard) |
Recursive assignment: Generate all valid color arrays segment by segment, checking adjacent constraints. |
N-ary Decision Tree where branches equal available colors. |
Draw nodes representing the sheet segments. Branch out with colored markers. Cross out invalid branches (pruning) to show wasted work. |
Matrix Exponentiation / 1D DP. |
Adjacency Matrix mapping valid color state transitions. |
Multiply the transition matrix by itself to jump K steps forward exponentially rather than linearly. |
Draw a small grid mapping Color A -> Color B valid transitions. Draw a square operation (Matrix^2) to show 2-step jumps. |
Logarithmic Exponentiation steps. |
Draw an M x M matrix. Write '^N'. Draw binary division branches of N to prove $O(M^3 \log N)$ time complexity. |
Deep recursion stack showing the current index and the previously used color. |
Two M x M matrices side-by-side swapping roles during multiplication, demonstrating $O(M^2)$ strict space limits. |
| 3803 |
Count Residue Prefixes (Easy) |
Nested Loops: Calculate the sum for each possible prefix and take the modulo remainder. |
Right-angled Triangle Grid showing redundant calculations. |
Draw an array. Underneath, draw brackets for [0..0], [0..1], [0..2], highlighting how earlier elements are re-added repeatedly. |
Prefix Sums + Frequency Counting (HashMap). |
Running pointer over the array + Hash Table state updates. |
Slide index i, update a running sum modulo M. Look up this remainder in the HashMap, add its frequency to the result, then increment the map. |
Draw the array. Below it, write the running sum % M. Next to it, draw a key-value table (HashMap) updating step-by-step. |
Linear timeline mapping $O(1)$ ops to array elements. |
Draw a straight line with N nodes. Under each node, write "O(1) Map Lookup". Bracket the whole line as $O(N)$. |
A single variable tracking count (O(1)). |
A Hash Table dynamically expanding its buckets to store up to M (modulo) different remainder keys. |
| 3804 |
Number of Centered Subarrays (Med.) |
Generate all $O(N^2)$ subarrays, sort them or find the center, and check the condition. |
Triangular matrix of subarray extractions. |
Draw two pointers (i, j). For each pair, draw a nested loop extracting elements to find the median/center. |
Prefix Sum Transformation + Fenwick Tree / Sliding Window. |
1D Line Plot mapping elements to +1 or -1 based on the target center. |
Convert elements > target to +1, < target to -1. Maintain running sum. Use a data structure to count valid previous prefix sums. |
Write original array. Below, map it to [-1, 0, 1]. Below that, write prefix sums. Use curved arrows to link valid prefix pairs. |
1D Sweep Line with logarithmic tree updates. |
Draw an array of size N. Below each element, draw a small binary tree representing the $O(\log N)$ Fenwick update. Sum to $O(N \log N)$. |
Subarray memory allocation showing $O(N)$ space created per $O(N^2)$ loops (if not done in-place). |
A Fenwick Tree array of size 2N, visualized as an array with step-wise index jumps storing frequency counts. |
| 3805 |
Count Caesar Cipher Pairs (Med.) |
Compare every pair. Shift string A 26 times and check if it matches string B. |
Dense Bipartite Graph mapping N strings to each other. |
Write two strings on paper. Draw 26 arrows between them representing the 26 rotational checks. |
Difference Array String Hashing + Frequency Map. |
Transformation pipeline (String -> Difference Array -> Hash). |
Convert "abc" to its adjacent difference [1, 1]. Hash this array. Look up [1, 1] in a map. Add frequency to total pairs. |
Write "abc". Draw arrows between a->b (1) and b->c (1). Write [1, 1]. Draw a bucket (HashMap) catching identical arrays from other words. |
Linear Scan Grouping. |
Draw N words flowing into a funnel (hashing algorithm), coming out as N keys. Show $O(N \cdot L)$ total time calculation. |
String copies generated during the 26 rotations, taking $O(N^2 \cdot L)$ space. |
A Trie (Prefix Tree) where each node represents an integer difference between characters, merging common prefixes. |
| 3806 |
Maximum Bitwise AND After Increment Operations (Hard) |
Recursively distribute K increments across N elements in all possible ways, calculating the AND result for every combination. |
Massive N-ary branching tree where each branch represents adding +1 to a specific array element. |
Draw an array. Draw N branches coming down for every single increment operation up to K. Write $O(N^K)$ to show the combinatorial explosion. |
Greedy Bitwise Construction (MSB to LSB). |
2D Grid mapping array elements to their binary representations (32 bits wide), scanning top-down. |
Start at MSB (bit 31). Calculate cost to turn this bit '1' for all elements. If total cost <= K, deduct cost from K and set bit to 1. Move to next bit. |
Write numbers in binary stacked vertically. Circle the leftmost column (MSB). Write "Cost to make all 1s". Subtract from K. |
Linear scan of 32 bits, with an inner loop of N elements. |
Draw a box labeled "32 (Bits)". Draw an arrow to another box "N (Array Size)". Write $O(32 \cdot N)$ = $O(N)$. |
Deep call stack and cloned arrays for every recursive increment step. |
$O(1)$ space block. Just a few integer variables (Cost, K, Answer) running in-place. |
| 3807 |
Minimum Cost to Repair Edges to Traverse a Graph (Med.) |
Generate all subsets of broken edges, check if graph is traversable (via BFS/DFS), and find the minimum cost among valid subsets. |
Power Set Tree of edges, with a full graph traversal calculated at every leaf node. |
Draw 2^E branches. At the bottom of each branch, draw a V+E graph traversal. Write $O(2^E \cdot (V+E)$). |
Modified Dijkstra's Algorithm (Shortest Path on weighted states). |
Graph with varying edge weights (0 for intact edges, cost C for broken edges). |
Start at node 0. Push neighbors to Min-Heap based on cumulative repair cost. Always expand the cheapest accumulated path until destination is reached. |
Draw nodes and edges. Label edges with 0 or Cost. Draw a "Priority Queue" bucket tracking the cheapest paths updating as you move node to node. |
Heap operations mapped to edges. |
Draw E edges. Beside them, draw a log(V) tree insertion diagram. Result: $O(E \log V)$. |
$O(2^E)$ massive memory overhead storing every possible edge configuration state. |
Adjacency list and a Min-Heap/Priority Queue taking $O(V + E)$ space. |
| 3808 |
Find Emotionally Consistent Users (Med.) |
SQL/Pandas: Self-joins for every day/interaction to check if sentiments match over a rolling chronological window. |
Cartesian product (NxN) table explosion showing overlapping date checks. |
Draw Table A, draw Table B. Draw lines connecting EVERY row to EVERY other row to filter dates. |
SQL Window Functions (LAG/LEAD) / Pandas `groupby().rolling()`. |
A sliding window overlay on a chronologically sorted table partitioned by User ID. |
Sort by User, Date. Add a column `prev_sentiment` using LAG(). Compare current to previous. If streak hits target, flag user. |
Draw a table (User, Date, Emotion). Add a new column next to it. Draw an arrow from row N-1 Emotion to row N New Column. |
Single pass sorting and scanning pipeline. |
Draw a funnel for "Sort $O(N \log N)$", then a straight pipe for "Window Scan $O(N)$". |
Temporary tempdb storage blowing up due to quadratic intermediate tables generated by self-joins. |
In-memory partition blocks holding only the current user's window frame $O(\text{Window Size})$. |
| 3809 |
Best Reachable Tower (Med.) |
From every empty cell, run a full BFS to find distances to all towers, then pick the best starting coordinate. |
N*M grids overlapping, showing redundant BFS spread from every single empty point. |
Draw a grid. Pick a cell. Draw ripples. Pick next cell. Draw ripples again. Total $O((N\cdot M)$^2). |
Multi-source Breadth-First Search (BFS). |
Simultaneous water-ripple effect starting from all towers at time T=0. |
Push all towers into queue with dist 0. Pop layer by layer. The first time a cell is reached, it gets the minimum distance. |
Draw grid. Mark towers 'T'. Draw expanding rings (1, 2, 3) outwards from all 'T's simultaneously until they collide. |
Single pass over the grid cells. |
Draw grid of size V. Write $O(V)$ = $O(N\cdot M)$ as each cell is enqueued and dequeued exactly once. |
Queue re-initialized N*M times, wasting massive memory cycles. |
A single Queue holding at most the perimeter of the expanding BFS fronts, plus a Visited matrix $O(N\cdot M)$. |
| 3810 |
Minimum Operations to Reach Target Array (Med.) |
Simulate every possible increment/decrement operation on subarrays until matching the target, using BFS on the array state. |
Massive state-space graph where nodes are entire array combinations. |
Draw array [0,0,0]. Draw arrows to [1,0,0], [1,1,0], [1,1,1]. Exponential branching factor. |
Difference Array + Greedy Peak Tracking. |
Bar chart showing the required differences, tracking height changes between adjacent elements. |
Compute diff array. If diff[i] > diff[i-1], we need diff[i] - diff[i-1] new operations. Accumulate these positive step-ups. |
Draw target array as a histogram. Draw the step-ups. Only the "upward steps" add to the total operation count. |
A single linear loop over the array. |
Draw array of length N. Draw a single arrow reading left to right. Write $O(N)$. |
Queue storing hundreds of intermediate array states. |
$O(1)$ extra space just tracking the previous element's difference integer. |
| 3811 |
Number of Alternating XOR Partitions (Med.) |
Backtracking: Recursively split the array into all possible partitions, calculating the XOR for each sub-segment to verify the alternating condition. |
Exponential recursion tree where every index has a "cut" or "no cut" decision branch. |
Draw an array. Draw scissors between elements. Branch down into 2^N paths representing all partition combos. |
Prefix XOR + Dynamic Programming with HashMap. |
1D Array moving forward while looking back via a HashMap to find valid previous partition boundaries. |
Calculate running prefix XOR. Look up the required XOR target in the HashMap to form a valid alternating partition. Add matching frequencies to DP state. |
Draw array. Below it, write the running Prefix XOR. Draw curved backward arrows linking current index to valid previous prefix values. |
Single pass timeline mapped to $O(1)$ lookups. |
Draw N nodes in a line. Under each, write "O(1) Map Lookup". Bracket the whole sequence as $O(N)$. |
Deep recursive call stack proportional to $O(N)$ depth, generating $O(2^N)$ branches. |
A HashMap and a 1D DP array of size N tracking the number of valid ways to partition up to index i. |
| 3812 |
Minimum Edge Toggles on a Tree (Hard) |
Try every possible node as the root. For each, run a full BFS/DFS to count how many directed edges need to be reversed to point away from the root. |
N separate tree traversals, where N nodes each trigger a full graph scan. |
Draw a tree. Pick node 1, draw a full DFS. Pick node 2, draw a full DFS. Write $O(N^2)$ to show the repeated work. |
Tree DP (Re-rooting Technique). |
Two-pass DFS: A bottom-up accumulation followed by a top-down transfer of state. |
Pass 1: Root at 0, count toggles for all subtrees. Pass 2: Move root to a child. If edge points child->parent, toggles -1. If parent->child, toggles +1. |
Draw tree. Pass 1: Draw arrows pointing UP to root 0, summing costs. Pass 2: Draw arrows shifting DOWN to children, adjusting the sum by +/- 1. |
Two sequential tree scans, independent of graph complexity. |
Draw tree. Write "DFS 1 = $O(N)$". Next to it, "DFS 2 = $O(N)$". Sum = $O(N)$. |
Call stack for N separate DFS runs, plus overhead for tracking visited nodes repeatedly. |
Two 1D arrays of size N: one for subtree toggle counts, one for the final answer after re-rooting. |
| 3813 |
Vowel-Consonant Score (Easy) |
Nested loops generating every possible substring to count vowels and consonants independently. |
Right-angled triangle grid representing all $O(N^2)$ substrings. |
Write a string. Draw brackets around [0,1], [0,2], [0,3]. Recount the vowels inside each bracket from scratch. |
Single Pass Linear Scan / Prefix Sums. |
Two counters moving left-to-right alongside the string index. |
Initialize V=0, C=0. Loop through characters. If vowel, V++. If consonant, C++. Apply score math at each step or at the end. |
Write the string. Below each letter, write a tuple (V, C) that increments as you read from left to right. |
Straight 1D vector timeline. |
Draw a string of N boxes. Draw one long arrow crossing all boxes. Write $O(N)$. |
Memory wasted if substrings are extracted as actual string copies (O(N^2) space). |
$O(1)$ space: Just a couple of integer variables maintaining the running counts. |
| 3814 |
Maximum Capacity Within Budget (Med.) |
Linear Search: Start capacity at 1, calculate total cost. Increment capacity by 1, recalculate cost. Stop when budget is exceeded. |
Long horizontal timeline checking every integer up to the maximum possible capacity. |
Draw a number line from 1 to 10,000. Under each tick mark, draw a loop representing the $O(N)$ cost check. Total $O(N \\text{cdot Max}_\text{Cap})$. |
Binary Search on Answer. |
A number line where half the possibilities are sliced off at every step. |
Set L=1, R=Max. Find Mid. Calculate cost for Mid capacity. If cost <= budget, record Mid as valid and search higher (L=Mid+1). Else, search lower (R=Mid-1). |
Draw number line. Mark L, R, Mid. Calculate cost. Cross out the right half with an X. Move R to Mid-1. Repeat. |
Logarithmic halving steps layered over a linear scan. |
Draw a binary search tree of ranges. At each node, write "O(N)". Height is log(Max). Total: $O(N \cdot \log(\text{Max})$). |
Variables running locally, $O(1)$. |
Variables running locally (L, R, Mid, Result), $O(1)$ space. |
| 3815 |
Design Auction System (Med.) |
Maintain a flat array of bids. Every time a bid is added or updated, sort the array to find the highest bid. |
Blocks of memory shifting left and right upon every new insertion. |
Draw an array. Add a number at the end. Draw arrows swapping it all the way to its sorted position. Write $O(N \log N)$ per operation. |
Hash Map + Max-Heap (Priority Queue) with Lazy Deletion. |
A tree structure (Heap) paired with a direct-lookup table (Map). |
Store active bids in Map. Push (Bid, UserID) to Max-Heap. For top bid, peek Heap. If Heap top doesn't match Map's current bid for that user, pop it (lazy delete). |
Draw a Binary Tree (Heap). Push a value to the bottom, draw an arrow bubbling it up to the root. Draw a Map beside it linking User->Bid. |
Logarithmic tree climbing. |
Draw a balanced tree. Write "Height = log N". Point to insertion path: $O(\log N)$. Point to Map: $O(1)$. |
A contiguous block of memory reallocating and sorting $O(N)$ data constantly. |
Parallel data structures: A dynamic Hash Map taking $O(N)$ space, and a Max-Heap array taking up to $O(M)$ space where M is total bids made. |
| 3816 |
Lexicographically Smallest String After Deleting Duplicate Characters (Hard) |
Backtracking: Generate all possible string combinations by keeping/deleting duplicates, sort the valid results alphabetically, and pick the first one. |
Massive binary decision tree (keep vs. delete) expanding out to 2^N leaves, followed by a sorting bottleneck. |
Write the string. Draw branching lines for every duplicate letter forming thousands of resulting words. Write $O(2^N \cdot N \log N)$. |
Monotonic Stack + Frequency Map + Visited Array. |
A vertical bucket (Stack) that actively ejects larger letters if a smaller one arrives and the larger one appears again later. |
Track char frequencies. Iterate string. If char is smaller than stack top AND stack top char has remaining count > 0, pop stack. Push new char. |
Draw a vertical open-top box. Push letters in. When a 'b' arrives and 'c' is on top, draw an arrow pulling 'c' out (if 'c' exists later). Push 'b'. |
Linear timeline with localized push/pop actions. |
Draw N characters on a line. Draw a small max 26-step loop below each. Write $O(N \cdot 26)$ = $O(N)$. |
Gigantic arrays of string permutations taking $O(2^N)$ memory space. |
A Frequency Array (size 26), Visited Boolean Array (size 26), and a Stack taking $O(N)$ space. |
| 3817 |
Good Indices in a Digit String (Med.) |
For every single index 'i', run two separate loops scanning left and right to check the "good" condition requirements. |
Overlapping horizontal arrows sweeping back and forth across the string repeatedly for every single index. |
Draw an array. Pick index 3, draw arrows left and right. Pick index 4, draw same arrows. Show $O(N^2)$ redundant scans. |
Prefix and Suffix Precomputation Arrays. |
Two separate shadow arrays, one building valid states left-to-right, the other right-to-left. |
Pass 1: Build left_valid[] array. Pass 2: Build right_valid[] array. Pass 3: If left_valid[i-1] AND right_valid[i+1] are true, index i is good. |
Draw string. Above it, draw right-pointing arrows computing prefix states. Below it, draw left-pointing arrows. Circle indices where both overlap validly. |
Three parallel 1D lines representing sequential passes. |
Draw 3 horizontal lines. Write "O(N) + $O(N)$ + $O(N)$ = $O(N)$". |
Memory is actually $O(1)$ but CPU stack handles $O(N^2)$ repetitive state variables. |
Two boolean/integer arrays of size N running parallel to the original string, taking $O(N)$ space. |
| 3818 |
Minimum Prefix Removal to Make Array Strictly Increasing (Med.) |
Iteratively remove prefixes of length 1, 2, 3... and loop through the remaining array to check if it is strictly increasing. |
A staircase-like sequence of smaller and smaller arrays being re-checked from scratch. |
Draw full array, cross out element 0, scan rest. Cross out 0, 1, scan rest. Write $O(N^2)$ to show the nested loop check. |
Suffix Array Traversal (Right-to-Left Scan). |
A single pointer moving backward from the end of the array until the strictly increasing rule breaks. |
Start at N-1. Move left as long as arr[i-1] < arr[i]. The moment arr[i-1] >= arr[i], the index 'i' is the length of the prefix that must be removed. |
Draw array. Start pencil at the rightmost number. Draw an arrow leftward, marking green until a number is bigger than the right one. Mark red and stop. |
A single backward timeline vector. |
Draw array. Draw one arrow starting at the end and stopping somewhere in the middle. Write $O(N)$. |
Re-allocating substring memory for every prefix deletion step, $O(N^2)$ space overhead. |
$O(1)$ Memory. A single integer pointer (`i`) moving backward in place. |
| 3819 |
Rotate Non Negative Elements (Med.) |
Extract all non-negative elements into a new array, rotate that separate array, and then place them back into their original positions. |
Memory cloning: Pulling elements out into a floating buffer, shifting them, and re-inserting them. |
Draw original array. Draw a separate smaller array. Copy positive numbers over. Shift them. Draw arrows putting them back. Time: $O(N)$, Space: $O(N)$. |
Two Pointers / Cyclic Replacement or Sub-segment Reversal Trick. |
In-place juggling of elements without using a secondary holding array. |
Identify positions of non-negatives. Use the 3-step string reversal trick on the active positions (Reverse all valid, reverse first K valid, reverse remaining). |
Draw array. Circle positive numbers. Draw curved swap lines reversing the whole positive sub-sequence, then swap lines for the sub-parts. |
Linear scan to find targets, followed by grouped in-place swaps. |
Draw an array line, point to specific indices, show them swapping. Write $O(N)$ swaps. |
A secondary dynamic array taking $O(K)$ space where K is the number of non-negative elements. |
$O(1)$ memory. Only variable pointers (left, right, temp) are used for the in-place swaps. |
| 3820 |
Pythagorean Distance Nodes in a Tree (Med.) |
Calculate the exact shortest path distance between every single pair of nodes (u, v) using N separate BFS traversals, then check if distance forms a valid Pythagorean triplet. |
Dense N x N distance matrix being fully populated by repeated graph traversals. |
Draw tree. Pick node A, BFS everywhere. Pick node B, BFS everywhere. Write $O(N^2)$ for distance generation. |
Tree DFS/BFS Depth Mapping + Frequency Hashing + Mathematical Convolution/Lookup. |
Convert the tree into a histogram of depths, then use algebra/hashing to find pairs that satisfy a^2 + b^2 = c^2. |
Run one BFS to get depth of all nodes from root. Count frequencies of distances. Loop through valid Pythagorean triples (a, b, c) within max depth, multiply frequencies. |
Draw tree. Next to it, draw a bar chart showing how many nodes are at distance 1, 2, 3. Draw a math formula matching the bar chart bins. |
Single graph traversal followed by an algebraic loop bounded by Max Depth. |
Draw tree -> $O(N)$. Draw Math Formula -> $O(\text{Max}_D^2)$. Total time $O(N + D^2)$. |
$O(N^2)$ matrix to store all-pairs shortest paths. |
A Frequency/Hash Map storing the count of nodes at specific distance intervals. Space $O(N)$ or $O(\text{Max Depth})$. |
| 3821 |
Find Nth Smallest Integer With K One Bits (Hard) |
Linear count: Start an integer at 1, increment indefinitely. Convert each to binary, count the 1s. Stop when you find the Nth match. |
Endless horizontal timeline checking every single integer up to infinity. |
Draw numbers 1, 2, 3, 4, 5. Under each, draw its binary form. Circle the ones with K bits. Write $O(\text{Answer})$ which could be billions. |
Combinatorics (nCr) + Bit-by-Bit Construction. |
A decision tree predicting the size of subtrees using combinations, bypassing thousands of numbers at once. |
Find the required bit length by checking nCr(length, K) >= N. Then, starting from MSB, if placing a '0' leaves fewer than N combinations, place a '1' and subtract combinations from N. |
Draw empty bit slots _ _ _ _. Write combinations (nCr) available if the first slot is 0. If N > combinations, write '1' and deduct. Otherwise, write '0'. |
Logarithmic descent. |
Draw ~60 binary slots. Under them, write "O(1) Math". Total time: $O(60)$ = $O(1)$ conceptually for 64-bit ints. |
$O(1)$ space, but high CPU cycles checking millions of numbers. |
$O(1)$ variables storing N, K, and current answer, alongside a precomputed Pascal's Triangle (Combinations matrix) up to 60x60. |
| 3822 |
Design Order Management System (Med.) |
Array simulation: Store all orders in a single list. For updates or deletes, scan the entire list from start to finish to find the Order ID. |
A long conveyor belt where you must inspect every item to find the one you want. |
Draw an array of boxes. Write an ID in each. Draw an arrow scanning left to right across all boxes to find "ID 42". Write $O(N)$ per query. |
Hash Map (Dictionary) for $O(1)$ CRUD. |
A post office with PO Boxes. You go directly to the box number without checking the others. |
Initialize a Hash Map tying OrderID to OrderDetails. Insert directly via key. Update/Delete directly via key in constant time. |
Draw a table with two columns: Key (ID) and Value (Details). Draw an arrow jumping directly from an external query straight to the correct row. |
Direct memory addressing timeline. |
Draw a box. Draw an arrow going straight in. Write "O(1) time". |
Dynamic array resizing constantly, taking up $O(N)$ space and shifting elements. |
Hash Map taking $O(N)$ space, structurally allocating buckets based on hash codes for rapid access. |
| 3823 |
Reverse Letters Then Special Characters in a String (Easy) |
Extract all letters to Array A, extract specials to Array B. Reverse both arrays independently. Loop through the original string and overwrite using the arrays. |
Three separate strings physically moving data back and forth. |
Draw string. Draw two buckets. Funnel letters into Bucket 1, specials into Bucket 2. Flip buckets. Funnel back. Time $O(N)$, Space $O(N)$. |
Multi-pass Two Pointers (In-Place). |
Two separate sets of pointers. One pair only "sees" letters, the other pair only "sees" specials. |
Pass 1: Pointers L (start) and R (end). Move until both hit a letter, swap. Pass 2: Reset L and R. Move until both hit a special character, swap. |
Draw string. Pass 1: Draw red pointers leaping over symbols to swap letters. Pass 2: Draw blue pointers leaping over letters to swap symbols. |
Two linear sweeps across the string. |
Draw a line. Write "Pass 1: $O(N)$". Draw second line. Write "Pass 2: $O(N)$". Total: $O(N)$. |
Two temporary arrays storing copies of the string's characters, $O(N)$ space. |
$O(1)$ memory. Just integer pointers (left, right) swapping characters directly in the original char array/string builder. |
| 3824 |
Minimum K to Reduce Array Within Limit (Med.) |
Try K=1, run a full simulation. Try K=2, run full simulation. Continue until the reduction limit is satisfied. |
A nested loop structure running a full $O(N)$ verification for every possible value of K. |
Draw an array. Try K=1, draw $O(N)$ operations. Try K=2, draw $O(N)$ operations. Write $O(\text{Max}_K \cdot N)$. |
Binary Search on Answer + Sliding Window / Greedy Check. |
A number line of K values being chopped in half, with a fast linear scanner checking validity. |
Set Low=1, High=Max_K. Mid = (Low+High)/2. Run $O(N)$ sliding window to see if Mid works. If yes, search lower half (High=Mid-1). If no, search upper (Low=Mid+1). |
Draw number line 1 to 100. Pick 50. Run a fast linear array check. It works. Cross out 51-100. Pick 25. Check again. |
Logarithmic guesses multiplied by a linear check. |
Draw a binary search tree. At each node, write "O(N)". Height is log(Max_K). Total: $O(N \log(\text{Max}_K)$). |
Call stacks and duplicated array states during simulation, $O(N)$. |
$O(1)$ space for pointers (L, R, Mid) and a single $O(N)$ sliding window or accumulator variable for the validity check. |
| 3825 |
Longest Strictly Increasing Subsequence With Non-Zero Bitwise AND (Med.) |
Generate all 2^N subsequences. Filter out those that aren't strictly increasing. For the remaining, calculate the total bitwise AND and check if > 0. Keep the longest. |
Explosive binary tree (include/exclude) generating every possible subset. |
Draw array. Draw branches splitting into 2^N paths. Write "O(2^N)" and draw a skull to show it will Time Out. |
1D DP + Bitmasking (State tracking per bit). |
Parallel timelines tracking the Longest Increasing Subsequence (LIS) specifically anchored to one of the 32 bit positions. |
Let dp[i] = length of LIS ending at index i. For each bit position (0-31), if current num has that bit set, look back at previous numbers with that bit set that are strictly smaller, and extend their DP sequence. |
Write numbers. Beside them, write their 32-bit binary. Draw vertical columns for Bits 0, 1, 2. Draw LIS chain arrows that only connect if the specific column has a '1'. |
Classic LIS double loop optimized by grouping. |
Draw array N. Inner loop checks previous elements. Write $O(N^2 \cdot 32)$. (Can be optimized to $O(N \log N)$ using segment trees if needed). |
Memory crashing from $O(2^N)$ subsequence combinations. |
A 1D DP array of size N. Optionally, an array of size 32 tracking the best tail for each bit position to optimize the inner loop. Space $O(N)$ or $O(32)$. |
| 3826 |
Minimum Partition Score (Hard) |
Backtracking: Try every possible way to partition the array into contiguous subarrays, calculate the score for each partition, and find the minimum. |
Exponential recursion tree showing every index deciding whether to split or continue the current subarray. |
Draw an array. Between every element, draw a dashed line representing a "cut" choice. Branch out 2^N paths. Write $O(2^N)$. |
Dynamic Programming + Monotonic Queue/Segment Tree. |
1D DP array updating sequentially, using a sliding window or tree structure to fetch the minimum previous valid state instantly. |
Calculate DP[i] by finding the best DP[j] where the subarray [j+1...i] is valid. Use a Monotonic Queue to keep only the most optimal DP[j] candidates as 'i' moves forward. |
Draw the array. Below it, draw a DP array. Draw a "window" sliding right. Inside the window, cross out larger DP values to show the Monotonic Queue filtering for the minimum. |
Linear or Logarithmic timeline scanning past states. |
Draw a line of N states. Under each, write an $O(\log N)$ tree lookup or $O(1)$ queue peek. Total: $O(N \log N)$ or $O(N)$. |
Deep call stack holding state for 2^N recursion branches. |
A 1D DP array of size N, plus a Deque (Double-Ended Queue) storing indices, taking $O(N)$ space. |
| 3827 |
Count Monobit Integers (Easy) |
Loop through the specified range [L, R], convert every number to a binary string, and count how many have exactly one '1'. |
A long iterative loop scanning thousands of numbers and counting their bits individually. |
Draw numbers from L to R. Under each, draw its binary. Circle the ones with a single '1'. Write $O(R - L)$. |
Bitwise Powers of 2 Math. |
Jumping directly between powers of 2 (1, 2, 4, 8, 16...) that fall within the given range. |
A "Monobit" integer is simply a power of 2. Start from the smallest power of 2 >= L, and count up by bit-shifting (val << 1) until exceeding R. |
Draw a number line. Mark L and R. Draw big jumping arcs landing exactly on 1, 2, 4, 8, 16. Count the dots inside the [L, R] window. |
Logarithmic scale timeline hopping across powers of 2. |
Draw 32 binary slots. Write a loop running max 32 times. Write $O(1)$ or $O(\log(\text{Max}_R)$). |
$O(1)$ memory, just taking excess CPU time. |
$O(1)$ Memory. Only a few integer variables (count, current_power) are needed. |
| 3828 |
Final Element After Subarray Deletions (Med.) |
Physically mutate the array: Find the target subarray, slice it out, shift all remaining elements left, and repeat until one element remains. |
Memory blocks constantly shrinking and shifting leftward. |
Draw an array. Cross out 3 elements. Draw arrows moving the entire right side leftward to fill the gap. Write $O(N^2)$ for repeated shifting. |
Two Pointers / Stack-based simulation. |
A logical stack where elements are pushed, and if a deletion pattern is matched at the top of the stack, they are popped (deleted) virtually. |
Iterate through the array pushing to a Stack. Check the top K elements against the deletion rule. If they match, pop them. The final element is the last one remaining. |
Draw an open-top bucket. Push numbers in one by one. If the top 3 numbers form the bad sequence, draw an eraser wiping them out. Continue pushing. |
Single pass linear scan with localized stack pops. |
Draw N numbers on a line. Draw an arrow entering the stack, and sometimes popping out. Write $O(N)$. |
Creating new array copies for every deletion step, $O(N^2)$ cumulative space. |
An Array used as a Stack, taking $O(N)$ space to store the non-deleted elements. |
| 3829 |
Design Ride Sharing System (Med.) |
Store all drivers in a flat list. For every ride request, iterate through the entire list to find the closest available driver. |
A linear scanner checking every single dot on a map to see if it's close to the target. |
Draw a map with dots. Draw a request. Draw lines connecting the request to EVERY single dot, calculating distance. Write $O(N \cdot Q)$. |
Spatial Hashing / Grid-based Priority Queues. |
A map divided into a grid. You only look in the grid cell where the request happened, or its immediate neighbors. |
Divide map into zones. Each zone has a Min-Heap of available drivers. Find request zone, pop closest driver from that zone's heap. |
Draw a Tic-Tac-Toe grid over the map. Put driver dots in cells. A request lands in cell 5. Draw a magnifying glass only looking inside cell 5's bucket. |
Direct grid coordinate math followed by a logarithmic heap pop. |
Draw an arrow to a grid box: $O(1)$. Inside box, draw a tree pop: $O(\log D)$. Total per query: $O(\log D)$. |
$O(N)$ contiguous array of drivers constantly being searched. |
A Hash Map of Priority Queues mapping `(X_grid, Y_grid) -> MinHeap(Drivers)`. Space $O(N)$ for drivers, grouped efficiently. |
| 3830 |
Longest Alternating Subarray After Removing At Most One Element (Hard) |
Try removing each element one by one. For each altered array, run a linear scan to find the longest alternating subarray. |
N separate array copies, each missing one element, being scanned sequentially. |
Draw the array. Put a finger over index 0, scan the rest. Move finger to index 1, scan the rest. Write $O(N^2)$. |
State Machine DP / Left-Right Precomputation. |
Three parallel timelines computing lengths: one moving left-to-right, one right-to-left, and a merge step bridging the gaps. |
Pass 1: Build `left[]` (longest alternating ending at i). Pass 2: Build `right[]` (longest starting at i). Pass 3: For each i, if `arr[i-1]` and `arr[i+1]` alternate correctly, potential length is `left[i-1] + right[i+1]`. |
Draw the array. Draw left-to-right growth arrows. Draw right-to-left growth arrows. For index 'i', draw an arch connecting index i-1 and i+1, skipping 'i'. |
Three sequential linear passes. |
Draw three horizontal lines representing the array passes. Write $O(N)$ + $O(N)$ + $O(N)$ = $O(N)$. |
$O(N^2)$ space if creating new arrays for every removal simulation. |
Two 1D arrays of size N (`left` and `right`) to store precomputed sequence lengths, taking $O(N)$ space. |
| 3831 |
Median of a Binary Search Tree Level (Med.) |
Level-order BFS pulling all nodes into arrays per level, then running a sorting algorithm on every level's array before finding the median. |
Trees dropping nodes chaotically into buckets, followed by expensive sorting cycles inside each bucket. |
Draw a tree. Draw buckets for levels 1, 2, 3. Draw nodes falling into buckets out of order. Write $O(L \log L)$ per bucket for sorting. |
In-Order DFS Traversal with Level Grouping. |
A left-to-right sweep of the tree that naturally drops elements into their respective level arrays in perfect sorted order. |
Run DFS(node, level). Because it's an In-Order traversal (Left, Node, Right) on a BST, as nodes are appended to `level_arrays[level]`, they are automatically sorted. Find median by index. |
Draw a BST. Draw a curved line weaving left-to-right through the nodes. Draw buckets below. Drop numbers into buckets; observe they magically land sorted. |
Single graph sweep with $O(1)$ mathematical lookups. |
Draw the tree. Write "O(N) Traversal". Next to buckets, write "O(1) Median Lookup". Total: $O(N)$. |
$O(N)$ memory for BFS Queue plus N array allocations that require shifting during sorts. |
A Hash Map of dynamic arrays `Map<Integer, List>` tracking levels, strictly taking $O(N)$ space, zero sorting memory overhead. |
| 3832 |
Find Users with Persistent Behavior Patterns (Hard) |
For every single user event, run a nested loop scanning all other events to see if they fall into consecutive chronological sequences. |
A massive N x N cross-join grid of user logs, with lines connecting matching dates. |
Draw a vertical list of dates. For the first date, draw arrows to all subsequent dates checking if they are Date+1, Date+2. Write $O(N^2)$. |
Gaps and Islands (SQL Window Functions) / Sequence Hashing. |
A mathematical subtraction timeline where consecutive days minus their row rank mathematically yield the exact same "Island ID". |
Sort by User, then Date. Create a ranking (1, 2, 3). Subtract rank from Date. Consecutive dates will yield the exact same base date (Island ID). Group by User + Island ID. |
Draw a table: Dates (Jan 1, Jan 2, Jan 4). Next column Rank (1, 2, 3). Subtract them: (Jan 0, Jan 0, Jan 1). Group identical results. |
Sorting pipeline followed by a linear grouping pass. |
Draw a funnel "Sort $O(N \log N)$". Draw a straight pipe "Group $O(N)$". Total: $O(N \log N)$. |
Database TempDB blowout from quadratic cross-joins. |
In-place pointer logic or window frames strictly bounded by $O(N)$ space. |
| 3833 |
Count Dominant Indices (Easy) |
Double nested loop: For every index 'i', loop through every other index 'j' to verify if `arr[i] >= 2 * arr[j]`. |
A dense spiderweb of comparison arrows bouncing between every pair of elements. |
Draw an array. Point finger at index 0. Draw arrows pointing from index 0 to every other number. Move to index 1, repeat. Write $O(N^2)$. |
Single-Pass Max & Second Max Tracking. |
Two podiums (Gold and Silver) holding the highest values as a conveyor belt of numbers moves past. |
Initialize Max = -1, SecondMax = -1. Loop once. If num > Max, demote Max to SecondMax, new Max = num. Finally, just check if Max >= 2 * SecondMax. |
Draw an array. Draw two boxes below: 'M1' and 'M2'. Update them as you read the array left to right. Final step: check if M1 >= M2 * 2. |
A straight horizontal line timeline. |
Draw a line. Write one arrow spanning left to right. Write $O(N)$. |
Call stack allocations if implemented recursively, or redundant tracking variables. |
$O(1)$ memory. Literally just two integer variables tracking the state. |
| 3834 |
Merge Adjacent Equal Elements (Med.) |
Scan array, find the first adjacent equal pair, merge them, shift everything down, and restart the entire scan from index 0. |
An array that constantly shrinks and shifts its blocks leftward over and over again. |
Draw array [2, 2, 4]. Cross out 2,2. Write 4. Rewrite whole array as [4, 4]. Cross out 4,4. Write 8. Write $O(N^2)$ for the shifting. |
Greedy Stack (Simulation). |
A vertical Tetris column where identical blocks falling on top of each other fuse together and double in value instantly. |
Iterate array. Push to Stack. If `stack.top() == current_element`, pop the top, double the value, and recursively check the new top. Else, push. |
Draw an open-top bucket. Push a '2'. Push another '2'. They touch, erase them, write '4'. The next number is '4'. Push it. They touch, write '8'. |
Linear push/pop sequence across the array. |
Draw N elements. Draw arrows going into the stack and sometimes bouncing back. Total operations is at most 2N. Write $O(N)$. |
Creating new array copies for every merge operation, $O(N^2)$ space. |
An Array used as a Stack taking up to $O(N)$ space in the worst case (no merges). |
| 3835 |
Count Subarrays With Cost Less Than or Equal to K (Med.) |
Generate all $O(N^2)$ possible subarrays. For each one, run a loop to calculate the cost. Keep a tally of those under K. |
A massive triangular matrix representing all subarray start/end combinations, with $O(N)$ work done inside each cell. |
Draw an array. Draw brackets for [0,0], [0,1], [0,2], [1,1], [1,2]. Calculate the sum for each bracket independently. Write $O(N^3)$ or $O(N^2)$. |
Variable-Size Sliding Window (Caterpillar Method). |
A stretchy window (caterpillar) moving right. It stretches until it eats too much (cost > K), then shrinks its tail until it's valid again. |
Pointer L=0, R=0. Expand R, adding to `current_cost`. While `current_cost > K`, subtract `arr[L]` and increment L. At each valid step, add `(R - L + 1)` to total subarrays. |
Draw array. Put L and R fingers on index 0. Move R right. When sum > K, move L right. For every valid stretch, draw a vertical line adding `R-L+1` to a total score box. |
Two pointers moving purely forward. |
Draw an array line. Draw L arrow and R arrow strictly moving left-to-right. Neither ever goes backward. Write $O(N)$. |
Memory exhaustion if subarrays are physically sliced out and stored. |
$O(1)$ memory. Only variable pointers (L, R, current_cost, total_count) are required. |
| 3836 |
Maximum Score Using Exactly K Pairs (Hard) |
Backtracking: Generate all possible combinations of choosing exactly K pairs from the array, sum their scores, and find the maximum. |
A massive branching tree picking 2 elements at every level until K pairs are formed. |
Draw an array. Draw branches for choosing pair (0,1), (0,2), etc. Write $O(N^(2K)$) to show the combinatorial explosion. |
Sorting + 2D Dynamic Programming (or Max-Heap Greedy). |
A 2D grid filling up systematically, balancing the cost of picking a pair vs. skipping an element. |
Sort the array. Let `dp[i][j]` be the max score using `j` pairs from the first `i` elements. Transition: `dp[i][j] = max(dp[i-1][j], dp[i-2][j-1] + score(i, i-1))`. |
Draw a 2D table (N rows, K columns). Fill cell (i, j) by drawing arrows from the cell directly above it (skip) and the cell diagonally up-left (pick pair). |
A steady sweep across a 2D grid. |
Draw a rectangle representing the DP table. Write dimensions N and K. Write $O(N \cdot K)$ or $O(N \log N)$ if using sorting + greedy. |
Call stack depths of K, with huge overhead for tracking used indices. |
A 2D DP array taking $O(N \cdot K)$ space, which can be optimized to two 1D rows taking $O(K)$ space. |
| 3837 |
Delayed Count of Equal Elements (Med.) |
For every single element in the array, run a nested loop looking backwards to count how many equal elements exist before the "delay" threshold. |
Horizontal arrows shooting backwards from every index, scanning overlapping sections repeatedly. |
Draw an array. Point to index 5. Draw an arrow pointing to indices 0, 1, 2 (assuming delay is 3) to count matches. Repeat for index 6. Write $O(N^2)$. |
Two Pointers (Sliding Window) + Frequency Map. |
Two pointers moving at a fixed distance (the delay). The trailing pointer adds to a bucket; the leading pointer checks the bucket. |
Set a trailing pointer at `i - delay`. As `i` moves forward, add `arr[i - delay]` to a HashMap. Then, check the HashMap for `arr[i]` and add to the total count. |
Draw an array. Draw pointer 'A' at index 0 and 'B' at index 3. 'A' drops a number into a bucket. 'B' looks into the bucket to see if it matches. Shift both right. |
Two parallel timelines moving perfectly in sync. |
Draw a line. Draw two arrows separated by a gap sliding left-to-right. Write $O(N)$. |
$O(1)$ memory space but $O(N^2)$ CPU time wasted. |
A HashMap tracking the frequencies of the "available" delayed elements, taking $O(N)$ space. |
| 3838 |
Weighted Word Mapping (Easy) |
For every character in the word, search through an array of key-value pairs or run a massive `if-else` block to find its numerical weight. |
A character bouncing down a long list of options trying to find its matching rule. |
Write a word. Under the first letter, write out 26 lines of check: "Is it a? Is it b?..." Write $O(N \cdot 26)$. |
Direct Hash Map / ASCII Array Indexing. |
A straight pipe where a letter goes in, and its weight instantly comes out without searching. |
Pre-fill an array of size 26 with the given weights. Iterate through the word. Convert the char to an index (e.g., `char - 'a'`), fetch the value instantly, and sum it. |
Draw a word. Below each letter, draw a single vertical arrow pointing directly to a number. Put plus signs between the numbers. |
A single, uninterrupted linear scan. |
Draw a box representing the string length N. Write a single arrow going through it. Write $O(N)$. |
$O(1)$ Memory. |
An array of 26 integers taking strictly $O(1)$ space regardless of the input word length. |
| 3839 |
Number of Prefix Connected Groups (Med.) |
For every prefix length (1 to N), build an adjacency list from scratch and run a full DFS/BFS to count the number of separate components. |
Building and tearing down a graph N times, traversing the entire thing from scratch every time. |
Draw 3 nodes, connect 1 edge, run DFS. Erase. Draw 3 nodes, connect 2 edges, run DFS. Write $O(N \cdot (V+E)$). |
Union-Find (Disjoint Set) with Dynamic Group Tracking. |
Droplets of water (nodes) merging together instantly when a pipe (edge) connects them. |
Start with V isolated groups. As you iterate through the edges of the prefix, use Union-Find. If two nodes have different parents, link them and decrement the total group count. Record the count. |
Draw isolated dots. Draw a line connecting two dots, circle them together into one blob. Note the total number of blobs left. Add next line, update blobs. |
Nearly constant time operations per edge added. |
Draw N edge additions. Write $O(N \cdot α(V)$) next to it, noting that the Inverse Ackermann function α makes it practically $O(N)$. |
Massive graph allocations, taking $O(V+E)$ space and re-allocating it N times. |
Two 1D arrays (`parent` and `rank`) taking exactly $O(V)$ space. |
| 3840 |
House Robber V (Med.) |
Recursive Backtracking: At every house, fork reality into two paths: "Rob this house" or "Skip this house," ensuring adjacent constraints are met. |
A binary decision tree that grows exponentially with every house evaluated. |
Draw an array of houses. From house 1, draw two branches: Rob (jump to house 3), Skip (jump to house 2). Branch again. Write $O(2^N)$. |
1D Dynamic Programming (State Machine). |
A single timeline accumulating optimal loot, looking back at the best possible past states. |
Maintain a DP array where `dp[i]` is the max loot up to house `i`. Formula: `dp[i] = max(dp[i-1], dp[i-step] + loot[i])`. (Adjust `step` based on problem's specific gap rules). |
Draw an array of house values. Below it, draw an empty array. Fill the first few cells. For cell 4, point back to cell 3 and cell 2 to visually pick the max. |
A single left-to-right sweep. |
Draw an array of N cells. Draw one continuous arrow scanning left-to-right. Write $O(N)$. |
Deep call stacks leading to Stack Overflow errors on large neighborhoods, $O(N)$ space overhead. |
A 1D DP array taking $O(N)$ space, which can often be optimized to just 2 or 3 rolling integer variables for $O(1)$ space. |
| 3841 |
Palindromic Path Queries in a Tree (Hard) |
For every query (u, v), perform a DFS to find the unique path, collect all character frequencies, and check if at most one character has an odd count. |
A spiderweb of DFS paths being traced over and over, traversing the same edges thousands of times for different queries. |
Draw a tree. Pick node A and B, trace path. Pick C and D, trace path. Write $O(Q \cdot N)$ to show the redundant path-finding. |
LCA (Lowest Common Ancestor) + Binary Lifting + Prefix Bitmasks. |
A "teleportation" technique using precomputed powers of 2 (2^0, 2^1...) to jump up the tree and aggregate character counts instantly. |
Precompute path-bitmask from root to every node (where bit 'i' is toggled for char 'i'). For query (u, v), path-mask = `Mask(u) XOR Mask(v) XOR CharBit(LCA(u,v))`. If `popcount(path-mask) <= 1`, it's a palindrome. |
Draw a tree. Draw a bitmask (0101) for each node. For two nodes, show the XOR operation canceling out common ancestors, leaving only the path between them. |
Logarithmic "jumps" per query after a linear setup. |
Draw a tree. Write "Setup: $O(N \log N)$". Draw a query arrow: "Jump $O(\log N)$". Total: $O((N+Q)$ log N). |
Memory overhead of thousands of character frequency arrays (size 26) created during DFS, $O(Q \cdot N \cdot 26)$. |
A 2D "jump table" of size N x log(N) and a 1D bitmask array of size N. Space $O(N \log N)$. |
| 3842 |
Toggle Light Bulbs (Easy) |
Simulation: For every round 'i', loop through all bulbs and flip the switch for every 'i-th' bulb. |
A grid where you walk across and flip switches repeatedly, with the number of flips decreasing per round. |
Draw 10 circles. Round 1: Flip all. Round 2: Flip 2, 4, 6... Write $O(N^2)$ for the nested loops. |
Mathematical Property (Perfect Squares). |
A simple number line where only the bulbs at "perfect square" positions remain ON. |
A bulb is toggled once for every factor it has. Only perfect squares have an odd number of factors (leaving them ON). Count how many `i*i <= N` exist. |
Draw numbers 1 to 10. List factors: 1(1), 2(1,2), 4(1,2,4). Circle 1, 4, 9. Show that only they have 3 factors (odd). Result is `floor(sqrt(N))`. |
Instant calculation. |
Draw a square root symbol over N. Write $O(1)$. |
$O(1)$ memory, but $O(N^2)$ time simulation wasted. |
$O(1)$ memory. Literally just one integer result from a square root function. |
| 3843 |
First Element with Unique Frequency (Med.) |
Nested loops: For every element, loop through the entire array to count its frequency. Then, check if that frequency is unique by looping through all other frequencies. |
A double-scan of the array followed by a comparison of every element's count against every other count. |
Draw an array. For element 1, count its occurrences. Do the same for all. Then compare count of '1' with count of '2'. Write $O(N^2)$. |
Two Hash Maps / Frequency-of-Frequency Tracking. |
A two-stage sorting/filtering pipeline that tallies elements and then tallies the tallies. |
Map 1: `Element -> Frequency`. Map 2: `Frequency -> Count`. Iterate array. Find first element where `Map2.get(Map1.get(element)) == 1`. |
Draw array. Map 1: {A:2, B:1, C:2}. Map 2: {2:2, 1:1}. Point to 'B' because its frequency (1) appears only once in Map 2. |
Two independent linear passes. |
Draw a line "Pass 1: $O(N)$". Draw second line "Pass 2: $O(N)$". Total: $O(N)$. |
$O(N^2)$ time-wasting loops; memory is $O(N)$ if storing frequencies in a list. |
Two Hash Maps taking $O(N)$ space to store unique elements and their frequency counts. |
| 3844 |
Longest Almost-Palindromic Substring (Med.) |
Generate all $O(N^2)$ substrings. For each, check if it can become a palindrome by changing at most K characters. |
A massive collection of substrings being manually verified character-by-character. |
Draw a string. Draw brackets for every possible substring. For each bracket, run a loop from start to end comparing letters. Write $O(N^3)$. |
Expand Around Center + Difference Count. |
A series of "mirrors" placed between letters that expand outwards, stopping only when the "error budget" K is exceeded. |
Pick a center (or between two letters). Expand left and right. Count mismatches. While `mismatches <= K`, keep expanding and track the max length. |
Draw a word. Put a pencil in the middle. Move left and right. Mark 'X' for a mismatch. If you hit more than K 'X's, stop. Repeat for all N centers. |
A centered-expansion sweep. |
Draw N center points. Below each, draw an arrow of max length N. Write $O(N^2)$. |
$O(N)$ memory to store substring copies during checks. |
$O(1)$ extra space (excluding output), just using pointers (L, R) and a mismatch counter. |
| 3845 |
Maximum Subarray XOR with Bounded Range (Hard) |
Generate all $O(N^2)$ subarrays, calculate the XOR for each, and check if it falls within [L, R]. Find the maximum among those that do. |
A grid of XOR calculations for every possible start/end point. |
Draw an array. Draw brackets for [0,1], [0,2], [0,3]. Recalculate XOR for each. Write $O(N^2)$. |
Prefix XOR + Binary Trie with Range Counting. |
A 0/1 decision tree (Trie) where you "search" for a path that maximizes XOR while staying within the [L, R] bounds. |
Store prefix XORs in a Binary Trie. For each new prefix XOR, search the Trie for the path that yields the highest XOR. Use sub-tree counts to prune paths that can't result in a value between L and R. |
Draw a tree where every left branch is 0 and right is 1. For a number 'X', show a path descending the tree to find its binary "opposite" to maximize XOR. |
Logarithmic bit-depth searches per element. |
Draw an array of length N. Under each, draw a tree search of depth 32. Total: $O(N \cdot 32)$ = $O(N)$. |
$O(1)$ memory, but $O(N^2)$ time complexity. |
A Binary Trie structure taking $O(N \cdot 32)$ space to store the bits of all prefix XORs. |
| 3846 |
Total Distance to Type a String Using One Finger (Med.) |
Recursive Backtracking: For every character in the string, calculate the distance from the previous character's coordinates on a 2D keyboard grid. |
A simple linear chain of distance calculations, but easily confused with multi-finger optimization. |
Draw a keyboard grid. Map 'A' to (0,0), 'B' to (0,1), etc. Trace a line from letter to letter. Write $O(N)$ for a single finger. |
Coordinate Geometry + Single Pass Accumulation. |
A "Manhattan Distance" calculation between 2D points (x1, y1) and (x2, y2). |
Pre-map all 26 letters to (row, col). Iterate string: `total += abs(x2-x1) + abs(y2-y1)`. Update `(x1, y1)` to current letter. |
Draw a 6x5 grid. Plot "H", then "E", then "L". Draw right-angle "stairs" connecting them to show Manhattan distance. Sum the lengths. |
Linear timeline of arithmetic operations. |
Draw a line of N characters. Under each, write "O(1) Math". Total: $O(N)$. |
$O(1)$ space, but potentially $O(N)$ if using recursion for simple summation. |
$O(1)$ memory. Just a 2D coordinate map of size 26 and one `total_distance` variable. |
| 3847 |
Find the Score Difference in a Game (Med.) |
Minimax Recursion: Simulate every possible move for Player A and Player B, exploring the entire game tree to find the final score difference. |
An exponential game tree where branches represent every valid move choice at each turn. |
Draw a root node. Branch out for every possible first move. Branch again for every second move. Write $O(2^N)$ or $O(N!)$. |
Dynamic Programming (Interval DP). |
A 2D "Score Table" where each cell represents the best relative score difference for a specific range of the array. |
Let `dp[i][j]` be the max score lead a player can get from subarray `[i...j]`. `dp[i][j] = max(arr[i] - dp[i+1][j], arr[j] - dp[i][j-1])`. |
Draw the array. Below it, draw a 2D grid. Fill the diagonal (single elements). Fill the rest by looking at the neighbors "below" and to the "left". |
A steady triangular sweep of a 2D matrix. |
Draw a square N x N. Shade in half (the triangle). Write $O(N^2)$. |
Massive recursion stack for the game tree, $O(N)$. |
A 2D DP table taking $O(N^2)$ space, which can be optimized to 1D (O(N)) by rolling rows. |
| 3848 |
Check Digitorial Permutation (Med.) |
Generate all N! permutations of the digit string and check if any of them satisfy the "Digitorial" (digit-factorial) property. |
A combinatorial explosion of strings being checked one by one. |
Draw a string "123". Draw branches for "132", "213", "231", "312", "321". Write $O(N! \cdot N)$. |
Frequency Counting + Permutation Invariance. |
Two "Frequency Buckets" that must match exactly, regardless of the order of digits. |
Count the frequency of digits 0-9 in String A. Count them in String B. If all 10 counts match, one is a permutation of the other. |
Draw two strings. Below each, draw 10 boxes (0-9). Put tally marks in the boxes. If the boxes look identical at the end, return True. |
Two independent linear scans. |
Draw two lines of length N. Write $O(N)$ + $O(N)$ = $O(N)$. |
$O(N!)$ space to store all generated strings. |
$O(1)$ memory. Two arrays of size 10 are constant space, regardless of string length. |
| 3849 |
Maximum Bitwise XOR After Rearrangement (Med.) |
Try every permutation of the input array. For each permutation, calculate the prefix XORs and find the maximum value encountered. |
N! array configurations being fully scanned for XOR peaks. |
Draw [A, B, C]. Draw [A, C, B], [B, A, C], etc. For each, calculate A, A oplus B, A oplus B oplus C. Write $O(N! \cdot N)$. |
Greedy Bit-Construction + Trie. |
Building the number bit-by-bit from MSB to LSB to ensure the largest possible value. |
Rearrangement usually implies we want the largest numbers to affect the highest bits. Sort or use a Trie to pick the best "next" number to XOR with the current prefix to keep it high. |
Draw binary numbers. Pick the one with the leftmost '1'. Then pick the next one that flips a '0' to a '1' in the highest possible position. |
Linear or Log-Linear sorting and scanning. |
Draw N elements. Write "Sort $O(N \log N)$". Write "Scan $O(N)$". Total: $O(N \log N)$. |
Massive memory used to store permutation copies. |
$O(1)$ or $O(N)$ depending on if you sort in-place or use a Trie. |
| 3850 |
Count Sequences to K (Hard) |
Recursive Backtracking: Generate all possible sequences that sum/multiply to K, checking every valid integer combination. |
A highly branched tree where the depth is the sequence length and branches are possible integers. |
Draw a root. Branch for 1, 2, 3... until the sum hits K. Write $O(2^K)$ or worse. |
Dynamic Programming (Partition DP) / Generating Functions. |
A "Staircase" DP where each step is built by looking back at all possible previous "jumps" that lead to the current sum. |
Let `dp[i]` be the number of ways to form sum `i`. `dp[i] = sum(dp[i - j])` for all valid `j`. Use a prefix sum to optimize the inner loop to $O(1)$. |
Draw a 1D array of size K. For cell 10, draw arrows from cells 1 through 9. Show how a "Running Total" variable avoids re-summing 1-9. |
Linear fill of a 1D state array. |
Draw a line of K units. Write "O(1) with Prefix Sum". Total: $O(K)$. |
Recursive stack overflow on large K. |
A 1D DP array of size K. Space $O(K)$. |
| 3851 |
Maximum Requests Without Violating the Limit (Med.) |
Bitmask Brute Force: Try every subset of requests (2^N combinations). For each subset, verify if the net change in every building is zero (in-flow equals out-flow). |
An exponential decision tree where each level represents a request being "Accepted" or "Rejected." |
Draw 2^N paths. For each path, draw a "Net Change" array. If all elements are 0, count the "Accepted" bits. Write $O(2^N \cdot B)$. |
Backtracking with Pruning / Network Flow. |
A recursive depth-first search that "undoes" changes (backtracks) to keep memory usage minimal while searching the state space. |
`dfs(index, count)`: Add current request (from, to), recurse, then subtract (from, to) to return to original state. Track the maximum `count` where all building balances are zero. |
Draw a circle of buildings. Draw arrows for requests. Show the "Balance" array (+1 for in, -1 for out). If the array is all 0s at a leaf, it's a valid max. |
Exponential but pruned search. |
Draw a tree. Cross out branches where the number of remaining requests + current count cannot beat the current max. Write $O(2^N)$. |
Storing all 2^N combination result arrays in memory. |
$O(B + N)$ space: one balance array for B buildings and the recursion stack of depth N. |
| 3852 |
Smallest Pair With Different Frequencies (Easy) |
Nested Loops: Generate all pairs (a, b) from the array. Calculate frequencies of all elements. Check if freq(a)
eq freq(b). Find the minimum sum a+b. |
A dense grid of comparisons (N x N) with a frequency calculation (O(N)) inside each comparison. |
Draw an array. Pair index 0 with 1, 2, 3... For each pair, scan the whole array to count how often those numbers appear. Write $O(N^3)$. |
Frequency Map + Sorted Unique Elements. |
A sorted list of unique values being checked against each other via a frequency lookup table. |
1. Build frequency map. 2. Get unique elements and sort them. 3. Use two pointers or nested loops on unique elements: if `map[u1] != map[u2]`, update min sum. |
Draw array. Map: {1:3, 2:1, 3:3}. Unique sorted: [1, 2, 3]. Check (1,2): freq 3!=1 (valid). Check (1,3): freq 3==3 (invalid). |
Linear map build followed by a small quadratic unique-element check. |
Draw a line for $O(N)$. Draw a small U x U grid for unique elements. Write $O(N + U^2)$. |
$O(1)$ if not counting frequency map; else $O(N)$. |
$O(U)$ space where U is the number of unique elements (max N). |
| 3853 |
Merge Close Characters (Med.) |
Iterative string mutation: Find two characters where |char1 - char2| <=q 1, merge them into a new character/symbol, and repeat until no more can be merged. |
A string that constantly shrinks, requiring a full re-scan after every single merge. |
Write "aacb". Merge "aa" -> "A". String is "Acb". Merge "cb" -> "B". Write $O(N^2)$ due to repeated string slicing. |
Frequency Array + Greedy Consolidation. |
A "Bucket Sort" style approach where we count the alphabet and resolve neighbors mathematically. |
Count frequencies in an array of size 26. Iterate from 'a' to 'z'. If `count[i]` and `count[i+1]` meet the merge criteria, combine them into the next bucket. |
Draw 26 buckets labeled A-Z. Put marbles in buckets. Pour marbles from bucket 'A' into 'B' if they are "close." |
A fixed-length scan of 26 characters. |
Draw 26 boxes. Draw one arrow passing through them. Write $O(N + 26)$ = $O(N)$. |
Creating new string objects for every merge operation (O(N^2) space). |
$O(1)$ extra space: just an array of size 26 to hold counts. |
| 3854 |
Minimum Operations to Make Array Parity Alternating (Med.) |
Try every possible value for even positions and every possible value for odd positions, counting how many changes are needed for each combination. |
An infinite search space (if values aren't bounded) or $O(\text{Max}_\text{Val}^2)$. |
Draw array. Try making all evens '1' and odds '2'. Count diffs. Try evens '1' and odds '3'. Count diffs. Write $O(V^2 \cdot N)$. |
Frequency Counting of Top 2 Elements (Even/Odd). |
A "Best vs. Second Best" strategy for two independent sets (Even indices and Odd indices). |
Count frequencies of numbers at even indices and odd indices separately. Find the top 2 most frequent numbers for both. If `TopEven != TopOdd`, answer is `N - FreqEven1 - FreqOdd1`. Else, try the two best cross-combinations. |
Draw two frequency tables. List "Most Common" for both. If they are different, keep them. If they are the same, pick the next best one from either table that minimizes total changes. |
Two linear passes to count and a constant time comparison. |
Draw two lines of length N/2. Under each, write "O(N)". Write "Compare Top 2: $O(1)$". Total: $O(N)$. |
$O(N)$ to store counts if many unique values exist. |
$O(N)$ space for the frequency maps, which can be optimized to $O(\text{Unique})$ elements. |
| 3855 |
Sum of K-Digit Numbers in a Range (Hard) |
Linear Summation: Iterate from L to R, check if the number has exactly K digits, and add it to the total sum. |
A massive loop that potentially visits billions of numbers. |
Draw number line. Check 1000, 1001... up to 99999. Write $O(R-L)$ and show it will time out for large ranges. |
Digit DP / Arithmetic Progression Formula. |
A "Block-Based" mathematical summation that treats numbers as strings to count and sum them by position. |
The sum of all K-digit numbers is the sum of an Arithmetic Progression: Sum = fracn2(first + last). Use `Sum(1 to R) - Sum(1 to L-1)` where only numbers with length K are considered. |
Draw a range [10^K-1, 10^K]. Identify the overlap of this "K-digit window" with your range [L, R]. Use the sum i = fracn(n+1)2 formula for that overlap. |
Constant time mathematical calculation. |
Draw a formula box. Write "Identify Overlap: $O(1)$". Write "AP Formula: $O(1)$". Total: $O(1)$. |
$O(1)$. |
$O(1)$ memory. Just a few `long long` variables for the range boundaries and the final sum. |
| 3856 |
Trim Trailing Vowels (Easy) |
Linear scan from the end of the string. Check if the last character is a vowel; if yes, remove it and repeat. Stop when the last character is a consonant. |
A string being repeatedly "sliced" or "resized," causing memory reallocations at every step. |
Draw the word "APPLEEE". Cross out 'E'. Rewrite "APPLE E". Cross out 'E'. Rewrite "APPLE". Write $O(N^2)$ if creating new strings repeatedly. |
Backward Pointer Scan. |
A single "Back-to-Front" pointer that identifies the first non-vowel index and truncates everything after it. |
Start pointer `i` at `N-1`. While `i >= 0` and `isVowel(s[i])`, decrement `i`. The final string is the substring from `0` to `i+1`. |
Draw the word "BANANA". Start at the last 'A'. Jump over it. Move to 'N'. Stop. Circle the part of the word from the start to 'N'. |
A single backward timeline vector. |
Draw a line of N characters. Draw one arrow starting at the right and moving left. Write $O(N)$. |
Generating multiple string objects in memory, $O(N^2)$. |
$O(1)$ extra space. Just one integer pointer to track the new end of the string. |
| 3857 |
Minimum Cost to Split into Ones (Med.) |
Recursive Backtracking: Try every possible split point for the array, calculating the cost of each split, and recursively find the minimum total cost until all segments are size 1. |
A binary tree representing all possible "Split Paths," with many overlapping subproblems. |
Draw an array [4]. Split into [1,3], [2,2], [3,1]. From [3], split again. Write $O(2^N)$ or $O(N!)$. |
Dynamic Programming (MCM - Matrix Chain Multiplication Style). |
A 2D triangular table where each cell represents the minimum cost to fully split a specific range `[i...j]`. |
Let `dp[i][j]` be the min cost for range `[i...j]`. `dp[i][j] = cost_of_current_split + min(dp[i][k] + dp[k+1][j])` for all `k` between `i` and `j`. |
Draw the array. Draw a 2D grid. Fill the diagonal with 0s. Fill the rest by "combining" results from smaller sub-ranges already calculated in the grid. |
A cubic $O(N^3)$ nested loop sweep. |
Draw a cube or a nested loop diagram: i (start), j (end), k (split point). Write $O(N^3)$. |
Extremely deep recursion stack, $O(N)$. |
A 2D DP table taking $O(N^2)$ space. |
| 3858 |
Minimum Bitwise OR From Grid (Med.) |
Exhaustive Pathfinding: Use DFS to find every possible path from top-left to bottom-right, calculating the cumulative bitwise OR for each. Find the minimum. |
An exponential branching tree of paths (2^N+M). |
Draw a 3x3 grid. Draw every possible path from (0,0) to (2,2). Write the OR result for each. Write $O(2^N+M)$. |
Dynamic Programming with Bitmasking / Dijkstra. |
A grid where each cell stores the minimum possible "state" (OR value) required to reach it. |
`dp[r][c] = min(dp[r-1][c] | grid[r][c], dp[r][c-1] | grid[r][c])`. Note: Since Bitwise OR is non-decreasing, standard DP works if there's no "back-tracking" required. |
Draw the grid. In each cell, write the binary OR of the cell above and the cell to the left. Pick the smaller binary value. |
A single $O(R x C)$ pass over the grid. |
Draw a grid N x M. Draw an arrow scanning row by row. Write $O(N \cdot M)$. |
Storing thousands of path strings in a list. |
A 2D DP table of size N x M storing integers. Space $O(N \cdot M)$. |
| 3859 |
Count Subarrays With K Distinct Integers (Hard) |
Nested Loops: Generate all $O(N^2)$ subarrays. For each, use a Set to count distinct integers. If the count equals K, increment the total. |
A massive triangular matrix of checks, with a Set operation (O(N)) inside each. |
Draw an array. Draw brackets for [0,0], [0,1], [0,2]... Inside each, write down the unique numbers. Write $O(N^3)$ or $O(N^2)$. |
Sliding Window (At Most K) Transformation. |
Two "stretchy" windows that calculate `AtMost(K) - AtMost(K-1)` to isolate subarrays with *exactly* K distinct elements. |
Define a function `atMost(K)`. Use a sliding window with a Frequency Map. If `map.size() > K`, shrink the tail. Total subarrays = sum of all `(right - left + 1)`. Result is `atMost(K) - atMost(K-1)`. |
Draw the array. Draw a window expanding. When distinct count > K, shrink. Note the length at each step. Repeat for K-1. Subtract the two final sums. |
Two independent linear sweeps. |
Draw two horizontal lines. Write $O(N)$ for each pass. Total: $O(N)$. |
Creating $O(N^2)$ sets or lists in memory. |
Two Frequency Maps taking $O(N)$ or $O(K)$ space. |
| 3860 |
Unique Email Groups (Med.) |
String Processing: For every email, apply the transformation rules (ignore dots, ignore everything after plus in the local name). Add the results to a list and count unique entries at the end. |
A list of strings that is sorted or checked for duplicates using nested loops. |
Draw "a.b+c@gmail.com". Manually erase '.' and "+c". Store "ab@gmail.com". Repeat for all. Compare every string to every other. Write $O(N^2 \cdot L)$. |
Hash Set + Pre-processing. |
A "Cleaning Station" followed by a "Direct Deposit" into a bucket that automatically ignores duplicates. |
1. Split email by '@'. 2. In local part, remove all '.'. 3. In local part, truncate after first '+'. 4. Join back with domain and add to a `HashSet`. Return `set.size()`. |
Draw a conveyor belt. A messy email enters. A "Cleaner" robot scrubs dots and pluses. The clean email lands in a "Set" box. Identical emails bounce off. |
Single pass over all characters in all emails. |
Draw N emails of length L. Write "Pass through cleaner: $O(N \cdot L)$". Write "Set lookup: $O(1)$ average". Total: $O(N \cdot L)$. |
Storing multiple temporary copies of the entire email list. |
A Hash Set storing cleaned strings, taking up to $O(N \cdot L)$ space. |
| 3861 |
Minimum Capacity Box (Easy) |
Simulation: Try boxes one by one in the order they are given, or try every combination of boxes to see which can fit the total items. |
A greedy or combinatorial search that might re-scan the item list for every box choice. |
Draw 5 items. Try Box A (size 2) - doesn't fit. Try Box B (size 6) - fits. Write $O(N)$ or $O(2^N)$. |
Sorting + Greedy Accumulation. |
A "Largest First" strategy where we fill the biggest containers first to minimize the number of containers used. |
1. Calculate total items S. 2. Sort box capacities in descending order. 3. Subtract box capacities from S until S <= 0. Count how many boxes were used. |
Draw a pile of items. Draw boxes from biggest to smallest. Throw items into the biggest box first. Keep track of the "Remaining Items" counter. |
Log-linear sorting followed by a linear count. |
Draw a funnel for "Sort $O(N \log N)$". Draw a line for "Scan $O(N)$". Total: $O(N \log N)$. |
$O(1)$ if sorting in-place, else $O(N)$. |
$O(1)$ extra space if the box array is sorted in-place. |
| 3862 |
Find the Smallest Balanced Index (Med.) |
Nested Loops: For every index i, run a loop to calculate the sum of elements to the left and another loop to calculate the sum to the right. |
A "Butterfly" scan where arrows extend from every point to both ends of the array. |
Draw an array. Point to index 3. Draw arrows to [0,1,2] and [4,5,6]. Sum them. Move to index 4, repeat. Write $O(N^2)$. |
Prefix Sums / Running Totals. |
A "Weight Scale" where you subtract from one side and add to the other in a single motion. |
1. Calculate total sum of array as `rightSum`. 2. Maintain `leftSum = 0`. 3. Iterate i: if `leftSum == rightSum - arr[i] - leftSum` (or appropriate balance logic), return i. Else, add `arr[i]` to `leftSum`. |
Draw a seesaw. All numbers are on the right. As you move the pointer, move one number at a time to the left. Stop when the seesaw is level. |
A single linear timeline. |
Draw a line of N nodes. Draw one arrow crossing from left to right. Write $O(N)$. |
$O(1)$ space but $O(N^2)$ time wasted. |
$O(1)$ memory. Only two or three `long long` variables for the sums. |
| 3863 |
Minimum Operations to Sort a String (Med.) |
BFS on States: Treat the string as a node in a graph. Each operation is an edge to a new string. Search for the shortest path to the sorted string. |
An massive state-space explosion (N! possible strings). |
Draw "CBA". Draw arrows to "BCA", "CAB", etc. Continue until you reach "ABC". Write $O(N!)$. |
Cycle Decomposition (Permutation Theory). |
A "Link-and-Swap" map where you count how many "closed loops" exist in the current arrangement versus the sorted one. |
1. Create a sorted version of the string. 2. Map current characters to their target positions. 3. Count cycles (e.g., A is where B should be, B is where A should be = 1 cycle). Min swaps = N - number of cycles. |
Draw the current string above the sorted string. Draw arrows from each top letter to its matching letter below. Count the independent "loops" formed by arrows. |
Linear mapping and cycle counting. |
Draw a line of N elements. Write "Map Positions: $O(N)$". Write "Count Cycles: $O(N)$". Total: $O(N)$. |
Storing all N! permutations in a Queue. |
$O(N)$ space for a visited array to track which elements have been processed in a cycle. |
| 3864 |
Minimum Cost to Partition a Binary String (Hard) |
Backtracking: Try every possible split point in the binary string. For each segment, check if it's a power of 5 (or other rule) and calculate cost recursively. |
An exponential recursion tree with overlapping sub-segments. |
Draw "1011". Split into "1"|"011", "10"|"11", etc. Write $O(2^N)$. |
Dynamic Programming (1D). |
A "Step-by-Step" build where each index i stores the minimum cost to partition the prefix S[0...i]. |
Let `dp[i]` be min cost for S[0...i]. `dp[i] = min(dp[j] + 1)` for all j < i where S[j+1...i] is a valid segment. Initialize `dp[0] = 0`, others as infty. |
Draw a string. Below it, draw a DP array. For each cell, look back at all previous cells. If the string between them is a power of 5, "jump" and add 1 to the cost. |
A nested loop $O(N^2)$ sweep. |
Draw a line of N. Under each, draw arrows looking back to all previous indices. Write $O(N^2)$. |
Deep recursion stack, $O(N)$. |
A 1D DP array of size N+1. Space $O(N)$. |
| 3865 |
Reverse K Subarrays (Med.) |
Simulation: For each of the K instructions, physically reverse the specified range in the array. |
An array being heavily modified K times, involving $O(N)$ work per reversal. |
Draw an array. Reverse [2,5]. Rewrite array. Reverse [1,3]. Rewrite array. Write $O(K \cdot N)$. |
Difference Array / Lazy Propagation (Segment Tree). |
A "Marking" strategy where you only record where reversals *start* and *stop*, and apply them all at once at the end. |
Note: For simple reversals, 2-pointers is often enough, but if K is huge and ranges overlap, use a Segment Tree or Splay Tree to perform "Lazy Reversals" in $O(\log N)$ time per operation. |
Draw a tree structure. For a range [L,R], mark the root of that range with a "Flip" tag. Only flip the children when you actually need to read them. |
Logarithmic operations per instruction. |
Draw K boxes. Under each, draw a tree traversal of height log N. Total: $O(K \log N)$. |
Creating new array copies for every reversal step. |
A tree-based data structure taking $O(N)$ space. |
| 3866 |
First Unique Even Element (Easy) |
Nested Loops: For every even element in the array, scan the rest of the array to count its occurrences. Return the first one with a count of 1. |
A repeating scan pattern where even numbers trigger a full array traversal. |
Draw an array. Point to '2'. Scan all other cells to see if '2' appears again. Repeat for '4'. Write $O(N^2)$. |
Hash Map (Frequency Counting). |
A "Tally Board" where you count everyone first, then check the board in the original order. |
1. Iterate once to fill a Frequency Map for all elements. 2. Iterate the original array a second time. 3. For each element, if it is even AND `map.get(element) == 1`, return it. |
Draw an array. Below it, draw a "Frequency Table". Fill the table. Then, move a finger across the array; when the finger hits an even number, look at the table to see if the count is 1. |
Two independent linear passes. |
Draw two horizontal lines. Write $O(N)$ + $O(N)$ = $O(N)$. |
$O(1)$ if counting in-place (impossible without sorting); otherwise $O(N^2)$ time waste. |
$O(N)$ space to store the frequency counts of unique elements in the map. |
| 3867 |
Sum of GCD of Formed Pairs (Med.) |
Backtracking: Generate every possible pairing of elements from the array, calculate the GCD of each pair, and sum them up. |
A combinatorial tree showing every possible way to group N elements into pairs. |
Draw [A, B, C, D]. Pairs: (A,B)(C,D), (A,C)(B,D), (A,D)(B,C). Write $O(N!)$ or $O((N-1)$!!). |
Bitmask Dynamic Programming. |
A state-space search where each "bit" in a binary string represents whether an element has been paired yet. |
Let `dp[mask]` be the max sum of GCDs for elements represented by the '1' bits in the mask. `dp[mask] = max(dp[mask ^ (1<
| Draw binary states like `1100` (elements 2 and 3 paired). Draw arrows to `1111` (all paired). Label arrows with the GCD of the new pair being added. |
Exponential state-space with quadratic transitions. |
Draw a column of 2^N states. Next to it, write "Transitions: $O(N^2)$". Total: $O(2^N \cdot N^2)$. |
Deep recursion stack storing all possible pairing combinations. |
A 1D DP array of size 2^N. Space $O(2^N)$. |
| 3868 |
Minimum Cost to Equalize Arrays Using Swaps (Med.) |
BFS on Permutations: Treat the array as a node in a graph. Each swap is an edge. Use BFS to find the shortest path to the target array state. |
A state explosion of N! nodes in a graph. |
Draw [3, 1, 2]. Draw edges for every possible swap. Hope you reach [1, 2, 3] quickly. Write $O(N!)$. |
Greedy / Cycle Counting with Costs. |
A "Distance-to-Target" calculation using the positions of elements. |
1. If all elements are the same, cost is 0. 2. If swaps are between any two indices, count how many elements are "out of place." If swaps have specific costs, use a Minimum Spanning Tree (MST) approach or greedy swaps if cost is uniform. |
Draw the current array and the goal array. Draw arrows from each number to its goal position. Count how many arrows cross. |
Linear scan of positions. |
Draw two lines of N. Write "Compare indices: $O(N)$". Total: $O(N)$. |
Queue storing N! array states. |
$O(1)$ extra space if only counting mismatches; $O(N)$ if tracking positions in a map. |
| 3869 |
Count Fancy Numbers in a Range (Hard) |
Linear Check: Iterate from L to R, check if each number is "Fancy" (e.g., has specific digit properties), and increment a counter. |
A massive loop that visits billions of numbers. |
Draw a number line. Check 1, 2, 3... up to 10^12. Write $O(R-L)$ and mark as "impossible." |
Digit Dynamic Programming. |
A "Digit-by-Digit" construction that counts valid numbers by filling slots from left to right. |
`dfs(index, isLess, isStarted, currentFancyState)`: Count how many ways to finish a number of length N given the current constraints. Use memoization to avoid redundant sub-problems. Result: `count(R) - count(L-1)`. |
Draw empty slots `_ _ _ _`. For the first slot, pick 0-9. If you pick a number equal to the range limit, the next slot is restricted. Show the recursion tree for filling these slots. |
Logarithmic time (based on the number of digits). |
Draw 12 slots for 10^12. Write "12 x States". Total: $O(\text{Digits} x \text{States})$. |
$O(1)$. |
A 3D or 4D memoization table, usually around $O(18 x 2 x 2 x 10)$, which is very small constant space. |
| 3870 |
Count Commas in Range (Easy) |
Iteration: For every number from 1 to N, convert it to a string, find how many commas it would have (every 3 digits), and sum them. |
A loop converting millions of integers to strings. |
Check 1 (0), 1000 (1), 1000000 (2). Sum them up one by one. Write $O(N \cdot \log N)$. |
Mathematical Range Summation. |
A "Block-Counting" approach that calculates how many numbers fall into 4-6 digits, 7-9 digits, etc. |
1. Numbers 1-999 have 0 commas. 2. Numbers 1,000-999,999 have 1 comma. 3. Count numbers in each power-of-1000 range: `total = sum(count_in_range * commas_for_range)`. |
Draw a number line with markers at 1,000, 1,000,000, and 1,000,000,000. Calculate the "width" of the segments between markers. Multiply width by the number of commas for that segment. |
Constant time or $O(\log N)$. |
Draw 5 power-of-10 boxes. Write "O(1) Math" for each. Total: $O(1)$. |
$O(N \cdot \log N)$ space for string conversions. |
$O(1)$ memory. Just a few `long long` variables. |
| 3871 |
Count Commas in Range II (Med.) |
Brute Force: Iterate from L to R, formatting each number as a string with commas and counting the total number of ',' characters. |
A massive loop performing string formatting millions of times. |
Draw a number line from L to R. For each number, write it out (e.g., "1,234,567") and count the commas. Write $O((R-L)$ log R). |
Mathematical Offset Calculation (f(R) - f(L-1)). |
A geometric summation of "comma-regions" using powers of 1000. |
Define f(X) as total commas from 1 to X. For each k > 0, the k-th comma appears in all numbers >= 10^3k. The number of times the k-th comma appears is max(0, X - 10^3k + 1). Total = sum f(k). Result = f(R) - f(L-1). |
Draw a number line. Mark 10^3, 10^6, 10^9. Shade the regions where 1, 2, or 3 commas exist. Calculate the area of these shaded blocks mathematically. |
Logarithmic time based on powers of 10. |
Draw 5-6 "Comma Threshold" boxes. Write "O(1) Math" per box. Total: $O(\log_1000 R)$. |
High memory overhead from string allocations. |
$O(1)$ memory. Only uses a few `long long` variables for the summation. |
| 3872 |
Longest Arithmetic Sequence After Changing At Most One Element (Med.) |
Brute Force: For every possible pair of indices (i, j) as the start of the sequence, and for every possible value change at every index k, check the length of the sequence. |
A massive nested search space involving (N^2) pairs and N possible changes. |
Draw an array. Pick two numbers to define the difference d. Try changing every other number one by one to see if it fits the a + n * d pattern. Write $O(N^3)$. |
Dynamic Programming with State (Changed vs. Unchanged). |
A 2D DP table where the second dimension tracks a "Boolean" state (Has an element been modified yet?). |
dp[i][diff][0] = longest seq ending at i with difference diff (no changes). dp[i][diff][1] = longest seq ending at i with diff (one change already used). |
Draw a grid: Rows = Indices, Cols = Differences. In each cell, store two numbers (Used-Change vs. Clean). When moving to a new cell, you can "spend" your change to connect two numbers that don't match the difference. |
Quadratic scan of pairs with constant state transitions. |
Draw a nested loop N x N. Inside, write "O(1) Map Update". Total: $O(N^2)$. |
Storing $O(N^3)$ sequence combinations. |
A Hash Map of Hash Maps: `Map>` to store differences per index. Space $O(N^2)$. |
| 3873 |
Maximum Points Activated with One Addition (Hard) |
Brute Force: For every empty coordinate on the grid, simulate adding a point and run a full clustering or "activation" algorithm (like BFS) to count the total points. |
A "What-If" simulation for every single empty cell in the grid. |
Draw a grid with points. Pick an empty cell, draw a circle/path to see what activates. Erase. Pick next cell. Write $O((\text{Grid}_\text{Size})$ * (V+E)). |
Union-Find with Component Size Tracking + Adjacency Map. |
A "Connector" strategy where you pre-calculate existing "islands" and find the one bridge that links the largest group. |
1. Group existing points into components using Union-Find. 2. For each empty cell, check its 4 neighbors. 3. Use a Set to find unique component IDs among neighbors. 4. Total points = 1 + sum (sizes of unique neighbor components). |
Draw "islands" of points. Label each island with its total size (e.g., Island A: 5, Island B: 3). Pick an empty spot between them. Draw arrows connecting to A and B. New size = 5+3+1 = 9. |
Linear scan of points followed by a linear scan of empty neighbors. |
Draw points N. Write "Union-Find: $O(N \text{alpha}(N)$)". Draw empty cells. Write "Neighbor Check: $O(1)$". Total: $O(N + \text{Grid})$. |
$O(\text{Grid})$ to store all simulation states. |
$O(N)$ space for Union-Find arrays (`parent` and `size`) and a Hash Map/Set for neighbor lookups. |