Candy [Hard/Medium] — Two-Pass Greedy
Distribute minimum candies so each child with higher rating than neighbors gets more, using left-to-right then right-to-left passes.
webcoderspeed.com
120 articles
Distribute minimum candies so each child with higher rating than neighbors gets more, using left-to-right then right-to-left passes.
Calculate trapped rain water using inward two pointers that track left-max and right-max, replacing the classic O(n) space approach.
Find the maximum in every sliding window of size k in O(n) using a monotonic decreasing deque.
Find the smallest missing positive integer in O(n) time O(1) space using in-place cyclic sort to place each number at its correct index.
Find the largest rectangle in a histogram in O(n) using a monotonic increasing stack that computes area when a shorter bar is encountered.
Find the minimum window in s that contains all characters of t using a shrinkable sliding window with a character frequency counter.
Count elements smaller than each element to its right using a modified merge sort that counts inversions during the merge step.
Find the median of two sorted arrays in O(log(min(m,n))) by binary searching for the correct partition point.
Find the largest rectangle of 1s in a binary matrix by treating each row as a histogram and applying the Largest Rectangle in Histogram algorithm.
Count pairs (i,j) where i<j and nums[i]>2*nums[j] using modified merge sort to count cross-half pairs before merging.
Minimize the largest sum among m subarrays by binary searching on the answer and greedy checking feasibility.
Find the shortest subarray with sum >= K using a monotonic deque on prefix sums, handling negative numbers correctly.
Count the number of range sums that lie in [lower, upper] using a merge sort approach on prefix sums.
Find three non-overlapping subarrays of length k with maximum sum using sliding window sums and left/right best index arrays.
Find the minimum refueling stops to reach target by greedily picking the largest fuel station passed so far whenever we run out.
Find the maximum number of points on the same line using a slope-as-fraction HashMap for each anchor point.
Find the longest valid parentheses substring using a stack that tracks the last unmatched index as a base.
Count subarrays with exactly K distinct integers using the formula: atMost(K) - atMost(K-1).
Reconstruct the stamp sequence in reverse by greedily finding where the stamp can overwrite current characters in the target string.
Find the longest substring that appears at least twice using binary search on length and Rabin-Karp rolling hash for O(n log n) average time.
Design a stack that pops the most frequent element (breaking ties by recency) using frequency and group-stacks mapping.
Find the minimum in a rotated array with duplicates by shrinking hi-- when nums[mid]==nums[hi].
Find the median of two sorted arrays in O(log(min(m,n))) by binary searching for the correct partition point.
Count smaller elements to the right of each element using merge sort with position tracking in O(n log n).
Find the maximum number of nested envelopes by sorting by width ascending then height descending, then applying LIS.
Find the maximum length to cut k ribbons from given ribbons using binary search on the ribbon length.
Place c cows in stalls to maximize the minimum distance between any two cows using binary search on the answer.
Count subarrays with sum in [lower, upper] using merge sort on prefix sums for O(n log n) complexity.
Find the kth smallest prime fraction from an array using binary search on the fraction value with a counting function.
Find the kth smallest element from two sorted arrays in O(log(m+n)) using binary elimination of k/2 elements per step.
Assign each element of nums1 to exactly one element of nums2 to minimize XOR sum. Classic assignment bitmask DP: dp[mask] = min XOR sum.
Count words that contain puzzle[0] and only letters from puzzle. Encode words as bitmasks, for each puzzle enumerate its subsets containing puzzle[0].
Maximum envelopes you can nest. Sort by width ascending and height descending, then LIS on heights. Descending heights prevents using same-width twice.
Minimum operations (insert, delete, replace) to transform word1 to word2. Classic Wagner-Fischer 2D DP with O(n) space optimization.
Find shortest string containing both strings as subsequences. Length = len(s1)+len(s2)-LCS. Reconstruct by tracing DP table.
Maximize coins by bursting balloons. Key insight: think of last balloon burst in interval [i,j]. dp[i][j] = max coins from interval with k as last balloon.
Maximize profit with at most 2 transactions. Track 4 states: buy1, sell1, buy2, sell2. State machine DP.
At most k transactions. dp[t][i] = max profit using t transactions up to day i. If k >= n/2, unlimited transactions.
Match string s against pattern p with . and *. dp[i][j] = does s[:i] match p[:j]. Handle * by matching zero or more of preceding char.
Match string with wildcard pattern: ? matches any char, * matches any sequence. Similar to regex but * matches any sequence (not zero/more of preceding).
Find minimum initial health to reach bottom-right dungeon cell. Solve backwards: dp[i][j] = min health needed at (i,j) to survive.
Minimum turns to print string where each turn prints a contiguous run of same char. Interval DP: dp[i][j] = min turns for s[i..j].
Find the largest island after flipping exactly one 0 to 1. Color each island with DFS, store sizes, then check each 0 cell's unique neighbour islands.
Find minimum flips to connect two islands. DFS to find and color first island, then BFS outward until reaching second island.
Find path from top-left to bottom-right minimizing maximum absolute difference between consecutive cells. Use Dijkstra or binary search + BFS.
Count islands after each addLand operation. Online version requires Union-Find: add each land cell and union with adjacent land cells.
Find ALL shortest transformation sequences. BFS builds layer map, DFS reconstructs all paths backwards from endWord to beginWord.
Find minimum buses to get from source to target stop. BFS where nodes are routes (buses), not stops. Jump to all stops of a route, then to all routes passing through each stop.
Count total reachable nodes in a subdivided graph within M moves. Dijkstra from node 0 gives max remaining moves at each node; use those to count subdivisions.
Distribute minimum candies with higher-rated children getting more than neighbors. Two-pass: left-to-right for ascending, right-to-left for descending.
Find the area of the largest rectangle in a histogram. Monotonic increasing stack: when a shorter bar is found, pop and compute rectangle area using popped height and current width.
Calculate water trapped between bars. Two-pointer approach: maintain max_left and max_right; water at each position = min(max_left, max_right) - height.
Find the largest rectangle in a binary matrix. Build histogram row by row (reset to 0 on '0'), apply Largest Rectangle in Histogram each row.
Implement an LFU cache with O(1) get/put using three hash maps: key→val, key→freq, freq→OrderedDict.
Design a data structure supporting inc/dec and getMaxKey/getMinKey in O(1) using a doubly linked list of frequency buckets.
Design Twitter with follow/unfollow and getNewsFeed using per-user tweet lists and a min-heap merge.
Find all index pairs forming palindromes by checking prefix/suffix splits against a reverse-word map.
Maintain a dynamic median using two heaps: a max-heap for the lower half and a min-heap for the upper half.
Compute medians of all sliding windows using two heaps with lazy deletion for element removal.
Merge K sorted linked lists into one sorted list using a min-heap to always extract the globally smallest node.
Maximize courses taken within deadlines by greedily scheduling and swapping out the longest past course.
Maximize capital after k IPO investments by greedily picking the highest profit project among affordable ones.
Calculate trapped water in a 3D height map using BFS with a min-heap to process cells from shortest boundary inward.
Find minimum time to swim from top-left to bottom-right in a grid where time = max elevation on the path.
Find the smallest range that contains at least one element from each of K sorted lists using a sliding K-way merge.
Find minimum fuel stops to reach the target by greedily selecting the largest available fuel stations when running low.
Maximize team performance (sum of speeds * min efficiency) by sorting by efficiency and using a min-heap on speeds.
Design a stack that pops the most frequent element, breaking ties by most recently pushed, using frequency-bucket stacks.
Minimize max-min of an array by doubling odd numbers and repeatedly halving the max using a max-heap.
Extended practice: compute median for each window in a stream using two-heap with lazy deletion pattern.
For each query point, find the smallest interval containing it by sorting both intervals and queries, using a min-heap.
Reverse every k nodes of a linked list recursively: check k nodes exist, reverse them, recurse on the rest.
Merge k sorted linked lists into one sorted list using a min-heap for O(n log k) time complexity.
Sort a linked list in O(n log n) time and O(1) space using bottom-up merge sort with doubling sublist sizes.
Build a balanced BST from a sorted list in O(n) by counting nodes, building in-order, and consuming list nodes.
Implement LRU Cache from scratch using a doubly linked list with sentinel nodes and a hash map for O(1) operations.
Design a browser history with visit, back, and forward operations using a doubly linked list for O(1) navigation.
Count smaller elements to the right of each element. Process from right to left; BIT tracks seen elements. Coordinate compress values to BIT indices.
Count pairs (i,j) where i<j and nums[i] > 2*nums[j]. Modified merge sort: during merge, count pairs across left/right halves.
Track coverage of half-open intervals. addRange, removeRange, queryRange. Sorted dictionary of disjoint intervals with merge/split logic.
Simulate falling squares, track tallest stack height. Coordinate compress x-coordinates, use segment tree with lazy propagation for range max.
Count subarray sums within [lower, upper]. Use prefix sums and merge sort: during merge count pairs of prefix sums with difference in range.
Track maximum booking overlaps at any time. Difference array: +1 at start, -1 at end; running max of prefix sum. Lazy segment tree for dynamic range.
Find max rectangle sum <= k in 2D matrix. Fix row boundaries, compress to 1D array, use prefix sums + BIT/sorted set to find best subarray sum <= k.
Find the shortest subarray with sum >= k using a monotonic deque on prefix sums for O(n) time.
Design a hit counter that returns hits in the past 5 minutes using a queue to expire old timestamps.
Find the largest rectangle in a histogram by computing left and right boundaries using a monotonic increasing stack.
Find the maximal rectangle in a binary matrix by building histogram heights row by row and applying largest rectangle.
Evaluate a basic expression with +, -, and parentheses using a stack to save and restore sign context.
Design a frequency stack with O(1) push and pop-max-frequency using a map of frequency to stack of elements.
Find the median dynamically as numbers are added using two heaps: a max-heap for the lower half and min-heap for upper.
Serialize a binary tree to a string using BFS level-order and deserialize back using a queue for reconstruction.
Calculate trapped rainwater volume using a monotonic stack that computes water in horizontal layers as bars are processed.
Find minimum cameras to monitor all nodes using greedy bottom-up: prefer placing cameras at parents of uncovered leaves.
Find the maximum path sum in a binary tree where the path can start and end at any node.
Serialize a binary tree to string and back using BFS level-order or DFS preorder with null markers.
Find the maximum sum of any BST subtree within a binary tree using post-order DFS returning subtree metadata.
Compute sum of distances from every node to all others in O(n) using two DFS passes with rerooting technique.
Sum all root-to-leaf path sums in a tree encoded as 3-digit integers using a hashmap to decode tree structure.
Find k values closest to target in a BST using two in-order iterators (forward and reverse) with a two-pointer merge.
Find all words from a list in a grid. Build trie from words, DFS on grid while traversing trie simultaneously to prune early.
Find pairs (i,j) where words[i]+words[j] is a palindrome. Insert reversed words into trie, for each word check palindromic suffix/prefix conditions.
Query if any word ends at the current stream position. Insert reversed words into trie; maintain suffix deque to match from current position backwards.
Find word with given prefix AND suffix. Insert 'suffix#word' for each suffix of each word into trie; query combines prefix+suffix search.
For each word, sum up how many other words share each of its prefixes. Trie with prefix count at each node; query each word's prefix sum.
Find all words that can be formed by concatenating two or more words from the same list. Build trie, then run word break DP on each word.
For each query (xi, mi), find max xi XOR with element ≤ mi. Offline: sort queries and elements by value, add elements up to mi, query trie.
Count subarrays with exactly K distinct integers using the mathematical trick: exactly(K) = atMost(K) - atMost(K-1).
Count subarrays where min=minK and max=maxK using a single pass tracking the last invalid position and last positions of minK and maxK.
Find the minimum window in s that contains t as a subsequence by using a forward pass to find a valid window then backward pass to minimize it.
Count subarrays where the median is exactly k by converting the problem to counting balanced prefix sequences around k.
Find the median of each sliding window of size k using two heaps (max-heap for lower half, min-heap for upper half) with lazy deletion.
Find all starting indices of substrings that are concatenations of all given words using a sliding window for each possible word-aligned start.
Count subarrays where score = sum × length is less than k using a shrinkable sliding window with running sum.
Find the smallest window in s containing all characters of t using a have/need counter to track when the window is valid.
Find the maximum in every sliding window of size k in O(n) using a monotonic decreasing deque of indices.
Find the shortest subarray with sum >= k, handling negative numbers correctly using a monotonic deque on prefix sums.
Find the longest substring containing at most 2 distinct characters using a variable sliding window with a character count map.
Calculate trapped rainwater using optimal two-pointer approach that tracks left and right maximums without extra space.
Week 3 mock focuses on hard problems. Strategy: get a working solution in 35 minutes, optimize in remaining 15. Includes triage framework for when you're stuck on a hard problem.