Max Consecutive Ones III — Sliding Window with K Flips [Google, Meta Medium]
Find maximum consecutive ones if you can flip at most k zeros to one. Variable sliding window O(n) solution.
webcoderspeed.com
348 articles
Find maximum consecutive ones if you can flip at most k zeros to one. Variable sliding window O(n) solution.
Find all unique triplets summing to zero. Sort array then fix one element and use two pointers. Full O(n²) solution in C, C++, Java, JavaScript and Python.
Find two lines that together with the x-axis form a container holding the most water. Greedy two-pointer O(n) — never check a pair that can't be optimal.
Compute product of all elements except self without division. O(n) two-pass prefix/suffix approach with O(1) extra space.
Merge all overlapping intervals. Sort by start, then merge greedily in one pass. O(n log n) time.
Return all elements of an m×n matrix in spiral order. Use boundary shrinking or direction array. O(m*n) time O(1) space.
Group strings that are anagrams of each other. Use sorted string as HashMap key. O(n*k*log k) time. Full solutions in 5 languages.
Find length of longest substring without repeating characters. Optimal O(n) sliding window with HashMap tracking last seen positions.
Count subarrays summing to k. Classic prefix sum + HashMap trick: if prefix[j]-prefix[i]=k then prefix[i]=prefix[j]-k. O(n) time.
Search a target in a rotated sorted array with no duplicates. Modified binary search identifies which half is sorted, then checks the target range. O(log n) time.
Determine if you can reach the last index. Greedy: track maximum reachable index. If current position exceeds max reach, return false. O(n) O(1).
Rotate array right by k steps. Triple reverse trick: reverse whole, reverse first k, reverse rest. O(n) time O(1) space.
Find the minimum element in a rotated sorted array with no duplicates. Binary search: the minimum is in the unsorted half. O(log n) time O(1) space.
Find k most frequent elements. Approach 1: min-heap O(n log k). Approach 2: bucket sort O(n). Full 5-language solutions.
Find the maximum product of a contiguous subarray. Track both min and max at each position (negative * negative = positive). O(n) time O(1) space.
Rotate an n×n matrix 90 degrees clockwise in-place. Trick: transpose (swap i,j with j,i) then reverse each row. O(n²) time O(1) space.
Find the lexicographically next permutation in-place using a two-pass scan from the right.
Find the one duplicate in [1..n] without modifying the array using Floyd's tortoise-and-hare cycle detection.
Sort an array of 0s, 1s, and 2s in-place in one pass using Dijkstra's Dutch National Flag algorithm.
Insert a new interval into a sorted non-overlapping list and merge any overlaps in a single sweep.
Find the minimum number of intervals to remove so the rest are non-overlapping, using a greedy earliest-end-time strategy.
Find all unique combinations that sum to a target, using backtracking with candidate reuse allowed.
Generate all permutations of distinct integers using in-place swap backtracking.
Generate the power set of distinct integers using backtracking or bitmask enumeration.
Find the smallest contiguous subarray with sum >= target using the shrinkable sliding window technique.
Find all integers that appear twice using index-sign-marking trick in O(n) time and O(1) extra space.
Decode a run-length-encoded string like "3[a2[bc]]" = "abcbcabcbcabcbc" using a stack for nested brackets.
Find all unique combinations that sum to target where each number may be used once, skipping duplicates at each recursion level.
Search for a word in a 2D grid using DFS backtracking with in-place visited marking.
Determine if there exists an increasing subsequence of length 3 using two greedy variables in O(n) time O(1) space.
Find all unique quadruplets summing to target by extending the 3Sum pattern with an outer loop and duplicate skipping.
Find minimum number of jumps to reach the last index using greedy BFS-style level tracking.
Determine the unique starting gas station for a circular route using a greedy one-pass algorithm.
Find how many days until a warmer temperature for each day using a monotonic decreasing stack.
Find the longest consecutive integer sequence in O(n) using a HashSet and only extending sequences from their start.
Partition a string into the maximum number of parts where each letter appears in at most one part, using last occurrence mapping.
Calculate minimum CPU intervals for tasks with cooldown using a greedy formula based on the most frequent task count.
Find the minimum arrows needed to burst all balloons arranged as intervals using a greedy sort-by-end approach.
Maximize a number by making at most one swap, using a last-occurrence map to find the optimal swap greedily.
Find a peak element in O(log n) by binary searching on the slope direction — always move toward the higher neighbor.
Find the missing number in [0..n] using the Gauss sum formula or XOR in O(n) time O(1) space.
Find all elements appearing more than n/3 times using Extended Boyer-Moore Voting with two candidate trackers.
Rearrange an array so nums[0] < nums[1] > nums[2] < nums[3]... using virtual index mapping and nth_element for O(n) time.
Find the minimum total moves to make all array elements equal by targeting the median value.
Find the longest nested set S(k) in a permutation array by tracing cycles with visited marking in O(n) time.
Rearrange nums to maximize advantage over B using a greedy strategy: assign the smallest winning card, else discard the smallest.
Generate all unique subsets from an array with duplicates by sorting and skipping repeated elements at each recursion level.
Find the minimum times A must repeat so that B is a substring, using a tight bound on the number of repeats needed.
Find the longest subarray of 1s after deleting exactly one element using a sliding window that tracks the count of zeros.
Find the shortest subarray that when sorted makes the whole array sorted, using a single linear scan tracking violated boundaries.
Count subarrays where max element is in [L,R] using a clever counting formula with two linear scans.
Find the minimum rotations to make all tops or bottoms equal by checking if a target value (from first domino) can unify the entire row.
Find the starting and ending positions of a target in a sorted array using two separate binary searches.
Search in a rotated sorted array by identifying which half is sorted and narrowing accordingly.
Find the minimum element in a rotated sorted array by comparing mid with right boundary to locate the rotation point.
Search a row-column sorted 2D matrix in O(log(m*n)) by treating it as a virtual 1D sorted array.
Find the minimum eating speed for Koko to finish all bananas in h hours using binary search on the answer space.
Find the minimum ship capacity to ship all packages within d days using binary search on capacity.
Find any peak element in O(log n) by always moving toward the uphill neighbor, which guarantees finding a peak.
Find the k closest elements to x in a sorted array by binary searching for the optimal left window boundary.
Find the single non-duplicate element in O(log n) by observing that pairs shift the parity of indices after the singleton.
Find the length of LIS in O(n log n) using patience sorting: binary search to maintain a sorted tails array.
Minimize the largest subarray sum when splitting into k parts using binary search on the possible answer range.
Search in a rotated sorted array that may contain duplicates by skipping lo++ when mid equals both boundaries.
Find the minimum day to make m bouquets of k adjacent flowers using binary search on the day value.
Find h-index from a sorted citations array in O(log n) using left-boundary binary search.
Count spell-potion pairs with product >= success by sorting potions and binary searching for each spell's threshold.
Find the kth smallest element in a row-column sorted matrix by binary searching on the value range.
Maximize the minimum distance between m balls in baskets using binary search on the answer (minimum distance).
Minimize the maximum value after performing k operations (average adjacent elements) using binary search on the answer.
Maximize nums[index] given array length n, sum constraint maxSum, and each element >= 1 using binary search on the peak value.
Find the kth missing number in a sorted array by binary searching on the number of missing elements up to each index.
Search a row-column sorted 2D matrix in O(m+n) using the staircase technique from top-right corner.
Find the smallest letter in a circular sorted list that is greater than the target using left-boundary binary search.
Answer election queries for who is leading at time t by precomputing the leader at each vote and binary searching.
Find the duplicate in array of n+1 integers in [1,n] using binary search on value with count-of-smaller logic.
Implement get(key, timestamp) using binary search on stored sorted timestamps for O(log n) retrieval.
Maximize events attended by greedily attending the event with the earliest end date each day using binary search.
Find the minimum train speed to arrive on time given n rides (last ride doesn't wait) using binary search on speed.
Every element appears 3 times except one. Track bit counts mod 3: ones and twos bitmasks, or count each bit position.
Two numbers appear once, rest appear twice. XOR all to get a^b, then use any set bit to partition numbers into two groups.
Add two integers without + or - operators. Simulate: sum = a XOR b (no carry), carry = (a AND b) << 1. Repeat until carry = 0.
Generate all subsets of an array. Each subset corresponds to a bitmask of n bits where bit i = 1 means element i is included.
Can array be partitioned into k equal-sum subsets? Bitmask DP: dp[mask] = sum filled so far. O(2^n * n) instead of O(k^n) DFS.
Sum of Hamming distances between all pairs. For each bit position, count 0s and 1s: contribution = count_0 * count_1.
AND of all numbers in [left, right]. Result is the common prefix of left and right: keep shifting right until equal, then shift back.
Generate n-bit Gray code sequence where adjacent codes differ by exactly 1 bit. Formula: gray(i) = i ^ (i >> 1).
Find all 10-letter DNA sequences that appear more than once. Use rolling hash (4-bit per char) or set of seen substrings.
Find max product of lengths of two words with no common letters. Encode each word as bitmask; two words share letters if AND != 0.
Maximize amount robbed without robbing adjacent houses. Classic skip-one DP: dp[i] = max(dp[i-1], dp[i-2] + nums[i]).
Houses arranged in a circle: first and last are adjacent. Run linear House Robber twice: once excluding last house, once excluding first.
Picking value k deletes all k-1 and k+1 elements. Map to House Robber: earn[k] = k * count(k), then max non-adjacent sum.
Find maximum product of a contiguous subarray. Track both min and max at each position because a negative * negative becomes positive.
Find minimum coins to make amount. Unbounded knapsack DP: dp[amount] = min(dp[amount-coin]+1) over all coins. Bottom-up from 0 to amount.
Count number of combinations making up amount. Process each coin denomination completely (outer loop = coin) to avoid counting permutations.
Minimum perfect squares summing to n. Isomorphic to Coin Change where coins = all perfect squares ≤ n.
Check if you can reach the last index. Greedy: track furthest reachable index. If current position > reach, stuck.
Find minimum jumps to reach the last index. Greedy: at each jump boundary, extend to the farthest reachable position.
Count ways to decode a digit string as letters (A=1,...,Z=26). DP: single digit + valid double digit transitions.
Check if string can be segmented into dictionary words. DP: dp[i]=true if some dp[j] is true and s[j:i] is in wordDict.
Find the length of the longest strictly increasing subsequence. O(n²) DP or O(n log n) patience sorting with binary search.
Count palindromic substrings. Expand around each center (n odd-length + n-1 even-length centers), count valid expansions.
Find longest palindromic subsequence length. 2D DP: if s[i]==s[j], dp[i][j] = dp[i+1][j-1]+2, else max of neighbors. Fill diagonally.
Can array be partitioned into two equal-sum subsets? 0/1 knapsack: can we pick some numbers summing to total/2? Bitset or DP boolean array.
Assign + or - to each number to reach target sum. DP counts ways to reach each sum. Reduces to 0/1 knapsack subset sum count.
LCS of two strings: dp[i][j] = LCS of first i chars of s1 and first j chars of s2. Full 2D DP treatment in the 2D DP section.
Count paths from top-left to bottom-right moving only right or down. dp[i][j] = dp[i-1][j] + dp[i][j-1]. Math formula O(1) also works.
Count paths avoiding obstacle cells. Same DP but obstacles block cell (dp[i][j]=0) and obstacle at start/end returns 0.
Find minimum cost path from top-left to bottom-right moving right or down. dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]).
Minimum path sum from top to bottom of triangle. Bottom-up DP: dp[j] = triangle[i][j] + min(dp[j], dp[j+1]).
Classic LCS: dp[i][j] = LCS length of s1[:i] and s2[:j]. If chars match add 1 to diagonal; else take max of skip either string.
Maximize profit with unlimited buy-sell transactions (but hold at most 1 share). Greedy: collect every upward slope.
Unlimited transactions with 1-day cooldown after selling. 3-state DP: hold, sold (cooldown), rest.
Unlimited transactions with transaction fee per sell. 2-state DP: cash (not holding) and hold (holding stock).
Check if s3 is formed by interleaving s1 and s2. dp[i][j] = can s3[:i+j] be formed from s1[:i] and s2[:j].
Find maximum strings using at most m zeros and n ones. 2D 0/1 knapsack: dp[i][j] = max strings using i zeros and j ones.
Find minimum sum falling path from top row to bottom row, moving to adjacent diagonal cells. DP row by row.
Minimum removals to make intervals non-overlapping. Sort by end time; greedily keep earliest-ending intervals, count conflicts.
Find minimum arrows to burst all balloons (intervals). Sort by end; one arrow can burst all overlapping intervals. Count arrows needed.
Find starting gas station index to complete circular route. If total gas >= total cost, a solution exists. Track running balance; reset start when negative.
For each day find how many days until a warmer temperature. Monotonic decreasing stack of indices; pop when warmer temperature found.
Remove duplicates to get smallest lexicographic subsequence with all chars. Greedy: use monotonic stack, only pop if char appears later.
Remove k digits to get smallest number. Monotonic increasing stack: pop larger digits when they appear before a smaller one. Remove remaining from end.
Sum of minimums of all subarrays. For each element, count how many subarrays have it as minimum using previous/next smaller element positions.
Find max j-i where i<j and nums[i]<=nums[j]. Build decreasing monotonic stack for left candidates, then scan from right to match.
Find i<j<k where nums[i]<nums[k]<nums[j]. Scan right-to-left with decreasing stack; track max popped element as potential 'nums[k]' candidate.
Next greater element in circular array. Iterate twice (2n) but use index mod n. Same decreasing stack pattern.
Minimum cost to connect all sticks. Always connect the two cheapest (Huffman coding variant). Min-heap greedy: cost = sum of merged sticks each round.
Partition string so each letter appears in at most one part. Track last occurrence of each char; greedily extend current partition end.
Reconstruct queue where [h,k] means person of height h has k taller/equal people in front. Sort by height desc (then k asc), insert at index k.
Maximum score to reach end where each jump is 1..k steps. Monotonic deque (sliding window maximum) of DP values for O(n) solution.
Find max chunks of array that when sorted individually give fully sorted array. A chunk boundary exists when max(chunk so far) == current index.
Find all groups of duplicate files by parsing path strings and grouping files by their content using a HashMap.
Group strings that are anagrams together by using their sorted form as a HashMap key.
Find the k most frequent elements in O(n) using bucket sort by frequency instead of a heap.
Design a Least Recently Used cache with O(1) get and put operations using a HashMap combined with a doubly linked list.
Count subarrays with sum exactly k using prefix sums stored in a HashMap to find valid starting positions in O(n).
Check if a continuous subarray of length >= 2 sums to a multiple of k using prefix sum modulo k with a HashMap.
Find the longest consecutive integer sequence in O(n) by using a HashSet and only starting sequences from their minimum element.
Design a set with O(1) insert, delete, and getRandom using a dynamic array combined with a HashMap for index tracking.
Find all starting indices of anagram substrings by using a fixed window with character frequency comparison.
Implement weighted random selection by building a prefix sum array and using binary search to find the sampled index.
Find the vertical line that crosses the fewest bricks by counting the most frequent gap position using a HashMap.
Count substrings with at most one odd-frequency letter using bitmask prefix XOR and a hash map.
Count (row, col) pairs that are equal by hashing each row tuple and each column tuple.
Find if a BST contains two nodes summing to target using a hash set during DFS traversal.
Find the longest arithmetic subsequence using dp[i][diff] = length ending at index i with given difference.
Count pairs (i,j) where j-i != nums[j]-nums[i] by counting good pairs via frequency map of nums[i]-i.
Find the smallest subarray to remove so the remaining sum is divisible by p using prefix modular arithmetic.
Count tuples (a,b,c,d) where a*b=c*d by counting pairs with each product using a frequency map.
Design a URL shortener using two hash maps for O(1) encode and decode operations.
Convert a fraction to decimal string with recurring part detected via remainder position tracking.
Find all duplicate subtrees by serializing each subtree and tracking serialization counts in a hash map.
Implement a hash map from scratch using an array of buckets with chaining for collision resolution.
Implement a hash set from scratch supporting add, remove, and contains in O(1) average time.
Pick a random index of a target value with equal probability using reservoir sampling over the array.
Find the most common word not in a banned list by normalizing input and using a frequency counter.
Determine if cards can be rearranged into consecutive groups of size groupSize using a sorted frequency map.
Count subarrays with sum divisible by k using prefix mod frequencies and the complement map pattern.
Count pairs summing to a power of 2 by checking all 22 powers-of-2 against a running frequency map.
Design a time-stamped key-value store supporting set and get(key, timestamp) using binary search on sorted timestamps.
Count 4-tuples summing to zero by splitting into two pairs and using a frequency map of pair sums.
Find K closest elements to x in a sorted array using binary search to find the optimal left boundary.
Find the Kth largest element using quickselect O(n) average or a min-heap of size K in O(n log k).
Return the K most frequent elements using a frequency map plus min-heap, or bucket sort for O(n) solution.
Sort characters in a string by decreasing frequency using a frequency counter and max-heap or bucket sort.
Find K points closest to the origin using a max-heap of size K or quickselect for O(n) average.
Find minimum CPU intervals to schedule tasks with cooldown using a greedy max-heap simulation.
Rearrange a string so no two adjacent characters are the same using a greedy max-heap approach.
Find the Kth smallest element in an n×n row-and-column sorted matrix using binary search on value range or heap.
Find K pairs (u, v) with smallest sums from two sorted arrays using a min-heap initialized with first row candidates.
Find the nth ugly number (only prime factors 2, 3, 5) using three pointers for the 2x, 3x, 5x merge streams.
Find minimum conference rooms required by tracking room end times with a min-heap of ongoing meeting endings.
Find minimum cost to connect all sticks by greedily always merging the two shortest sticks first.
Check if a car can pick up all passengers by processing start/end events with a sorted timeline or heap.
Greedily use ladders for the largest climbs and bricks for smaller gaps, managed with a min-heap of ladder sizes.
Assign tasks to available servers using two heaps: one for free servers and one for busy servers sorted by free time.
Find the nth super ugly number with prime factors only from a given list using K-pointer dynamic programming.
Design a simplified Twitter with follow/unfollow and a news feed showing the 10 most recent tweets from followed users.
Find the nth number divisible by a, b, or c using binary search with inclusion-exclusion counting formula.
Build the longest string with at most 2 consecutive identical characters by always using the most frequent available character.
For each interval find the interval with the smallest start point >= the end point using sorted starts and binary search.
Find the kth largest level sum in a binary tree using BFS to compute level sums then sorting or using a heap.
Minimize total hiring cost by always choosing the cheapest candidate from the first or last p candidates using two min-heaps.
Design a seat manager that reserves the lowest numbered available seat and unreserves seats using a min-heap.
Track stock prices with corrections by maintaining a sorted multiset and a timestamp-to-price map.
Find the minimum number of elements to remove to reduce array size by half by greedily removing most frequent elements.
Remove the nth node from the end in one pass using two pointers offset by n steps and a dummy head.
Swap every two adjacent nodes in a linked list without modifying node values using pointer rewiring.
Group all odd-indexed nodes before even-indexed nodes in O(n) time and O(1) space using two pointer chains.
Rotate a linked list to the right by k places by finding length, computing effective rotation, and rewiring.
Reorder a linked list into L0→Ln→L1→Ln-1 pattern by splitting at middle, reversing second half, then merging.
Add two numbers represented as reversed linked lists by simulating digit addition with carry propagation.
Add two numbers given in forward order by pushing digits to stacks, then building the result list in reverse.
Partition a linked list around value x into less-than and greater-than-or-equal chains, then join them.
Sort a linked list in O(n log n) time and O(log n) space using top-down merge sort with fast/slow split.
Remove all nodes that have duplicate numbers from a sorted linked list using a dummy head and skip logic.
Deep copy a linked list with random pointers using either a hash map or the O(1) space interleave technique.
Flatten a multilevel doubly linked list by inserting child sub-lists inline using DFS or an explicit stack.
Find the node where a cycle begins using Floyd's algorithm: detect meeting point, then reset one pointer to head.
Find the duplicate in an array of n+1 integers in O(1) space by treating indices as a linked list with Floyd's cycle detection.
Find the next greater value for each node in a linked list using a monotonic decreasing stack of indices.
Implement a doubly linked list with sentinel head and tail nodes for clean O(1) insertions and deletions.
Swap the kth node from the front with the kth node from the end by finding both with two pointers.
Remove consecutive nodes that sum to zero by tracking prefix sums in a map and relinking past zero-sum runs.
Split a linked list into k consecutive parts as evenly as possible, front parts get the extra nodes.
Reverse the portion of a linked list between positions left and right in one pass using careful pointer manipulation.
Find the maximum sum of twin nodes (node i + node n-1-i) by reversing the second half and comparing pairs.
Merge all nodes between 0s into a single node with their sum, modifying the list in-place.
Delete the middle node of a linked list using a prev-pointer variant of the fast/slow technique.
Reverse nodes in each even-length group of a linked list by counting group sizes and selectively reversing.
Insert a value into a sorted circular linked list by finding the correct position with careful edge case handling.
Count the number of connected components of a linked list that consist of nodes in a given set.
Flatten a binary tree in-place into a linked list following pre-order using the Morris traversal approach.
Convert a sorted linked list to a height-balanced BST by repeatedly finding the middle node as root.
Support point updates and range sum queries. BIT (Fenwick Tree) gives O(log n) both operations with elegant implementation.
Book events without double-booking. Use sorted dictionary to find previous and next events; check overlap with both.
Count all LIS of maximum length. DP: track length and count. Segment tree on values enables O(n log n) solution.
Apply range shift operations to letters. Difference array: mark +1 at start and -1 at end+1, prefix sum gives net shift at each position.
Sum of rectangle region. Precompute 2D prefix sums: prefix[i][j] = sum of all cells from (0,0) to (i-1,j-1). Inclusion-exclusion for query.
Find longest subarray with sum <= k. Build prefix sums, use monotonic deque for decreasing prefix sums to efficiently find left boundaries.
For each element compute product of all other elements. Two-pass: left prefix products then multiply with right suffix products.
Find how many days until a warmer temperature using a monotonic decreasing stack of unresolved day indices.
Find the next greater element for each query in O(n+m) using a monotonic stack on nums2 and a lookup map.
Find the next greater element in a circular array by iterating twice (0 to 2n) and using a monotonic stack.
Calculate the stock price span (consecutive days <= today) using a monotonic stack that accumulates spans.
Remove k digits to form the smallest number by maintaining a monotonic increasing stack and greedy removal.
Decode a string with nested encodings like 3[a2[bc]] using two stacks: one for counts and one for partial strings.
Evaluate an RPN expression by pushing numbers and applying operators to the top two stack elements.
Find the maximum in each sliding window of size k using a monotonic decreasing deque storing indices.
Simulate asteroid collisions using a stack where right-moving asteroids wait and left-moving ones destroy smaller ones.
Sum the minimums of all subarrays by computing each element's contribution as the minimum using previous and next smaller element spans.
Calculate the score of balanced parentheses where () = 1 and AB = A+B and (A) = 2*A using a stack depth trick.
Find the minimum intervals to execute all tasks with cooldown n by greedily scheduling the most frequent task first.
Find minutes until all oranges rot using multi-source BFS starting from all initially rotten oranges simultaneously.
Count islands in a 2D grid using BFS or DFS to flood-fill connected land cells, marking them visited.
Detect if all courses can be finished (no cycle) using Kahn's algorithm: BFS on in-degree zero nodes.
Return a valid course order using Kahn's BFS topological sort, or empty array if a cycle exists.
Find the shortest word transformation sequence using BFS where each step changes exactly one character.
Evaluate a string expression with +, -, *, / using a stack that handles operator precedence without parentheses.
Detect a 132 pattern (i < j < k, nums[i] < nums[k] < nums[j]) using a monotonic stack scanning right to left.
Count visible people in a queue for each person using a monotonic decreasing stack scanning right to left.
Implement a circular queue using a fixed-size array with head and tail pointers and a size counter.
Find cells that can flow to both oceans by doing reverse BFS from each ocean's borders and finding the intersection.
Maximize score jumping through an array with window k by combining DP with a monotonic decreasing deque.
Fill each empty room with its distance to nearest gate using simultaneous multi-source BFS from all gates.
Implement an iterator for a nested list using a stack that lazily expands nested lists as elements are consumed.
Remove k adjacent identical characters repeatedly using a stack that tracks (character, count) pairs.
Return values grouped by level using BFS with a queue, processing each level in a batch loop.
Traverse a binary tree in zigzag level order by toggling insertion direction at each level.
Find the rightmost node at each level using BFS and taking the last element seen at each depth.
Collect all root-to-leaf paths with a given sum using DFS backtracking, appending and removing the current node.
Find the diameter (longest path between any two nodes) using a depth function that tracks the maximum path through each node.
Validate a BST by passing down min and max bounds through DFS, ensuring every node falls strictly within its valid range.
Find the kth smallest element in a BST using inorder traversal (left-root-right) which visits nodes in sorted order.
Find the LCA of two nodes using post-order DFS: return root when found, propagate upward and split at the ancestor.
Find the LCA in a BST in O(h) by navigating left or right based on whether both nodes are in the same subtree.
Build a binary tree from preorder and inorder traversals by using the preorder root and inorder index to split left/right subtrees.
Count paths in a binary tree summing to target (not necessarily root-to-leaf) using a prefix sum frequency map.
Find and delete a node from a BST while maintaining BST properties using in-order successor.
Flatten a binary tree to a linked list in-place using pre-order traversal order.
Connect each node to its next right node using BFS level order or O(1) space pointer manipulation.
Find all nodes at distance K from a target node by building parent pointers then doing BFS.
Compute the total sum of all root-to-leaf numbers formed by concatenating digits along each path.
Find the maximum width of a binary tree where width is measured from leftmost to rightmost non-null node per level.
Count nodes where no node on the root-to-node path has a value greater than the node itself.
Replace each node value with the sum of all values greater than or equal to it using reverse in-order traversal.
Find all duplicate subtrees by serializing each subtree and using a hash map to detect duplicates.
Generate all structurally unique BSTs with values 1 to n using divide and conquer with memoization.
Trim a BST so all values lie within [low, high] by recursively pruning out-of-range subtrees.
Serialize a BST to a compact preorder string and reconstruct it using the min-max BST property.
Group tree nodes by vertical column then row, sorting by value within same position using BFS with coordinates.
Find path directions between two tree nodes by finding LCA then building paths from LCA to each target.
Verify a binary tree is complete using BFS: once a null child is seen, no more non-null nodes should follow.
Find and swap the two misplaced nodes in a BST using in-order traversal to detect the violations.
Maximize robbery from a tree-structured neighborhood where adjacent (parent-child) nodes cannot both be robbed.
Count minimum moves to distribute coins evenly by tracking excess/deficit coins flowing through each edge.
Find the Kth ancestor of any tree node in O(log k) per query using binary lifting (sparse table DP).
Reconstruct a BST from its preorder traversal in O(n) using min-max bounds to place each node.
Collect leaves by height (distance from leaf) repeatedly, returning all leaves at each height level.
Count nodes in a complete binary tree in O(log^2 n) by comparing left and right heights to identify full subtrees.
Find minimum seconds to collect all apples in a tree by DFS: include a subtree path only if it contains apples.
Find the maximum |a - b| for any ancestor-descendant pair by tracking min and max values along each root-to-leaf path.
Find the longest zigzag path in a binary tree where you alternate left-right directions at each step.
Count the number of structurally unique BSTs with n nodes using Catalan numbers and DP.
Perform level-order traversal of an N-ary tree using BFS, collecting all children at each level.
Remove all subtrees that do not contain a 1 by recursively returning null for subtrees with only zeros.
Find the level with the maximum sum using BFS level-order traversal to compute each level's total.
Find lexicographically smallest string from any leaf to root by collecting and comparing reversed paths.
Find time for infection to spread through entire tree from a start node by converting to graph then doing BFS.
Find minimum swaps to sort each level of a binary tree using BFS and cycle-detection in permutation sorting.
Implement an in-order BST iterator with O(h) space using a stack to simulate recursive in-order traversal.
Transform a binary tree so every right child becomes a sibling and left child becomes parent using iterative rotation.
Find the inorder successor of a node in a BST when you have access to parent pointers.
Insert a new row of nodes at a given depth in a binary tree using BFS to reach the target depth level.
Sum all nodes at the deepest level of a binary tree using BFS to process level by level.
Count nodes in complete binary tree in O(log^2 n) by comparing left vs right subtree heights recursively.
Insert a value into a BST by traversing left/right based on comparisons until reaching a null position.
Build a quad tree from a 2D grid by recursively checking if a region is uniform and splitting into four quadrants.
Count nodes where node value equals the average of all values in its subtree using post-order DFS returning sum and count.
Implement a Trie with insert, search, and startsWith operations. Core data structure for all prefix-based problems.
Trie that supports wildcard '.' matching any character. DFS through trie when '.' encountered, trying all children.
Replace each word in sentence with its shortest root from dictionary. Insert roots into trie; for each sentence word find shortest matching prefix.
Find maximum XOR of any two numbers in array. Binary trie (bit by bit from MSB): for each number greedily choose opposite bit to maximize XOR.
After each character typed, return up to 3 lexicographically smallest matching products. Sort products, insert into trie, store sorted lists at each node.
Find longest word where all prefixes exist in dictionary. Trie: only follow nodes where is_end=True, track max depth.
Encode word list as shortest string where each word is a suffix. Words that are suffixes of others need not be separately encoded. Use trie of reversed words.
Implement insert(key, val) and sum(prefix) returning sum of values for all keys with given prefix. Trie with value at end node.
Find the longest common prefix length between any number in arr1 and any number in arr2. Build trie from arr1 digits, query with arr2.
Count distinct substrings. Naive: insert all suffixes into trie and count nodes. Optimal: suffix automaton or rolling hash.
Find the maximum number of consecutive 1s achievable by flipping at most k zeros, using a variable sliding window.
Find the longest substring without duplicate characters using a HashSet-backed shrinkable sliding window.
Find the longest substring with at most k character replacements by tracking the maximum frequency char in the window.
Check if any permutation of s1 is a substring of s2 using a fixed-size sliding window with character frequency comparison.
Find the maximum fruits you can collect starting from any tree with two baskets (at most 2 distinct fruit types) using a sliding window.
Find the maximum sum of a subarray with all unique elements using a sliding window backed by a HashSet.
Find the smallest subarray with sum >= target using a variable sliding window that shrinks from the left when the condition is met.
Count tuples (i,j,k,l) where nums1[i]+nums2[j]+nums3[k]+nums4[l]=0 by hashing all pairs from first two arrays.
Maximize water trapped between two vertical lines using inward two pointers that always move the shorter line inward.
Find minimum boats to save everyone where each boat carries at most 2 people with total weight <= limit, using sort + greedy two pointers.
Find all unique triplets summing to zero by sorting and using two pointers for each fixed element with careful duplicate skipping.
Find two numbers summing to target in a 1-indexed sorted array using inward two pointers in O(n) time O(1) space.
Count contiguous subarrays with product < k using a sliding window that divides from the left when product exceeds the limit.
Maximize card points taken from both ends of an array by finding the minimum-sum subarray of size n-k in the middle.
Count subarrays with exactly k odd numbers using the at-most(k) minus at-most(k-1) sliding window formula.
Count binary subarrays with exactly the given sum using prefix sum with HashMap or the atMost(k)-atMost(k-1) trick.
Find the maximum frequency of any element after at most k increments by sorting and using a sliding window with a running sum.
Find minimum operations to reduce X to zero from either end by finding the longest middle subarray with sum = total-X.
Find the longest mountain subarray (strictly increasing then decreasing) using two separate forward scans for up and down slopes.
Find the longest turbulent subarray where comparisons alternate between > and < using two-pointer direction tracking.
Find the minimum length substring to replace so that a string of QWER has equal frequencies, using a shrinkable two-pointer approach.
Find minimum character flips to make a binary string alternating by applying a fixed circular sliding window of size n.
Find the maximum number of vowels in any substring of length k using a fixed sliding window with vowel count.
Find minimum swaps to group all 1s together in a circular binary array using a fixed-size sliding window equal to the count of 1s.
Find minimum minutes to collect at least k of each character from ends by finding the longest middle window that can be excluded.
Maximize customer satisfaction by finding the best k-minute window for the bookstore owner to stay non-grumpy.
Find the maximum length substring you can transform from s to t within a given cost budget using a sliding window on character change costs.
Count substrings containing at least one a, b, and c using the last-seen indices shortcut for O(n) time.
Count subarrays with sum divisible by k using prefix sum modulo k and a frequency map of remainders.
Find k closest integers to x in a sorted array using binary search to locate the optimal left boundary of the window.
Find the maximum consecutive ones in a binary array when you can flip at most k zeros, identical to the Max Consecutive Ones III pattern.
Sort only the vowels in a string while keeping consonants in place by extracting vowels, sorting, then reinserting.
Find the minimum number of consecutive cards that contain a matching pair using a HashMap tracking last seen positions.
Find the longest contiguous subarray of 1s after deleting exactly one element using a sliding window allowing at most one zero.
Sort an array of 0s, 1s, and 2s in one pass using the Dutch National Flag 3-pointer algorithm.
Check if a string can become a palindrome by deleting at most one character using recursive two-pointer palindrome checking.
Week 1 mock session: two carefully chosen easy/medium problems designed to build communication habits. Full problem walkthrough with example think-aloud scripts.
Week 2 mock: solve medium problems then optimize. Practice the full interview loop of brute force → optimal → follow-up questions. Includes common interviewer follow-up prompts.