System Design Prep 🔒 private, approval needed
Merge two strings by taking letters alternately; append any leftover letters.
Why? undefined
💡 Key idea undefined
Edge / failure case '','xyz' → 'xyz'
word1 is empty, so nothing alternates — the answer is just word2.
A string t 'divides' a string s if s is t repeated one or more times (t + t + … = s). Given two strings str1 and str2, return the longest string x that divides BOTH of them, or an empty string if there is none. Example: 'ABCABCABC' is 'ABC' three times and 'ABCABC' is 'ABC' twice, so the answer is 'ABC'.
Why? 'ABCABCABC' is ABC three times. 'ABCABC' is ABC two times. So ABC divides both.
💡 Key idea If str1+str2 ≠ str2+str1 there is no answer. Otherwise the answer's length is gcd(len1, len2).
Edge / failure case 'LEET','CODE' → ''
No string repeats to build both words, so the answer is the empty string.
candies[i] is how many candies kid i has, and you also have extraCandies to give. For each kid, imagine giving ALL the extra candies to just that kid. Return a list of true/false, one per kid: true if that kid would then have at least as many candies as the kid with the most candies (ties count as true). Example: candies=[2,3,5,1,3], extra=3 → the biggest pile is 5; kid with 1 candy gets 4 < 5, so false; everyone else reaches 5 or more.
Why? Most candies is 5, extra is 3. Kid with 2 → 5 ✓, 3 → 6 ✓, 5 → 8 ✓, 1 → 4 ✗, 3 → 6 ✓.
💡 Key idea Find the maximum once. Then check candies[i] + extra ≥ max.
Edge / failure case [4,2,1,1,2],1 → [True, False, False, False, False]
Only the kid who already has the most candies keeps up after +1.
flowerbed is a list where 0 means an empty plot and 1 means a plot with a flower. Flowers can't be planted in adjacent plots (two 1s may never sit side by side). Given an integer n, return true if you can plant n NEW flowers without breaking that rule, otherwise false. Existing flowers never move. Example: [1,0,0,0,1] with n=1 → only the middle plot is free of neighbours, so true.
Why? [1,0,0,0,1]: only the middle plot has empty plots on both sides. Plant there → one flower fits → True.
💡 Key idea Go left to right. Plant whenever a plot and both its neighbours are empty.
Edge / failure case [1,0,0,0,1],2 → False
Only the middle plot is free, so just 1 flower fits — we need 2.
Given a string s, reverse only its vowels (a, e, i, o, u — both lower and upper case) and return the result. All other characters stay exactly where they are. Example: 'IceCreAm' has vowels I, e, e, A (in that order); reversed they become A, e, e, I put back into the same vowel positions → 'AceCreIm'.
Why? IceCreAm: the vowels in order are I, e, e, A. Reversed they are A, e, e, I. Put them back → AceCreIm.
💡 Key idea Two pointers from both ends. Skip non-vowels. Swap vowels.
Edge / failure case 'bcd' → 'bcd'
There are no vowels, so nothing changes.
Given a string s that contains words separated by spaces (there may be extra spaces at the start, at the end, or several between words), return the words in REVERSE order, joined by exactly one space, with no leading or trailing spaces. Example: ' the sky is blue ' has words the, sky, is, blue → 'blue is sky the'.
Why? ' the sky is blue ' has the words the, sky, is, blue. Reversed → blue is sky the.
💡 Key idea split() already removes extra spaces. Reverse the word list and join with a space.
Edge / failure case 'a good example' → 'example good a'
Extra spaces between words collapse to a single space.
Given a list nums, return a list answer of the same length where answer[i] is the product of ALL numbers in nums except nums[i]. You may not use division. Aim for O(n) (time grows only in step with the input size) time. Example: [1,2,3,4] → answer[0]=2·3·4=24, answer[1]=1·3·4=12, answer[2]=1·2·4=8, answer[3]=1·2·3=6.
Why? [1,2,3,4]: position 0 → 2×3×4 = 24. Position 1 → 1×3×4 = 12. Position 2 → 1×2×4 = 8. Position 3 → 1×2×3 = 6.
💡 Key idea answer[i] = (product of everything left of i) × (product of everything right of i).
Edge / failure case [-1,1,0,-3,3] → [0, 0, 9, 0, 0]
A zero makes every product 0 except the one at the zero's own position.
Given a list nums, return true if there are three positions i < j < k such that nums[i] < nums[j] < nums[k] — three numbers in left-to-right order that strictly increase (they don't have to be next to each other). Otherwise return false. Example: [2,1,5,0,4,6] contains 2 < 5 < 6 (or 1 < 4 < 6), so true.
Why? [2,1,5,0,4,6]: 0, then 4, then 6 keep growing in order → True.
💡 Key idea Track the smallest value and the smallest 'middle' value so far. A number bigger than both proves a triplet.
Edge / failure case [5,4,3,2,1] → False
The numbers only go down, so no increasing triplet exists.
Compress runs in place: letter, then the count if it is greater than 1. Return new length.
Why? undefined
💡 Key idea undefined
Edge / failure case ['a'] → [1, ['a']]
A single letter has a run of 1, so no count is written.
Move all zeroes to the end in place, keeping the order of non-zero values.
Why? undefined
💡 Key idea undefined
Edge / failure case [0] → [0]
A lone zero has nowhere to move — the list stays the same.
Is s a subsequence of t (same order, gaps allowed)?
Why? undefined
💡 Key idea undefined
Edge / failure case 'axc','ahbgdc' → False
'x' never appears in 'ahbgdc', so 'axc' cannot be formed in order → False.
Pick two lines that, with the x-axis, hold the most water.
Why? undefined
💡 Key idea undefined
Edge / failure case [1,1] → 1
Only two walls of height 1, one unit apart → area 1.
Repeatedly remove two numbers that add to k. How many operations?
Why? undefined
💡 Key idea undefined
Edge / failure case [1,2,3,4],10 → 0
No two numbers add up to 10, so no operation is possible.
Find the contiguous subarray of length k with the largest average.
Why? undefined
💡 Key idea undefined
Edge / failure case [5],1 → 5
A single element is its own window.
Most vowels in any substring of length k?
Why? undefined
💡 Key idea undefined
Edge / failure case 'rhythm',3 → 0
'rhythm' contains no a, e, i, o or u, so every window has 0 vowels.
Longest run of 1s if you may flip at most k zeros.
Why? undefined
💡 Key idea undefined
Edge / failure case [0,0,0],0 → 0
No flips allowed and no 1s, so the longest run of 1s is 0.
Delete exactly one element; longest run of 1s left?
Why? undefined
💡 Key idea undefined
Edge / failure case [1,1,1] → 2
All 1s — you still must delete one, so the run shrinks to 2.
A biker starts at 0 and gains/loses altitude per leg. Highest point?
Why? undefined
💡 Key idea undefined
Edge / failure case [-4,-3,-2,-1,4,3,2] → 0
The biker never climbs above the starting altitude 0.
Find the index where the sum on the left equals the sum on the right.
Why? undefined
💡 Key idea undefined
Edge / failure case [1,2,3] → -1
No index has equal sums on both sides → -1.
Values only in nums1, and values only in nums2 (no duplicates).
Why? undefined
💡 Key idea undefined
Edge / failure case [1,2,3],[2,4,6] → [[1, 3], [4, 6]]
1,3 only in nums1; 4,6 only in nums2; 2 is in both.
Is every value's occurrence count different?
Why? undefined
💡 Key idea undefined
Edge / failure case [1,2] → False
Both numbers occur exactly once — the counts are not unique → False.
Can you turn one string into the other by swapping letters or swapping letter identities?
Why? undefined
💡 Key idea undefined
Edge / failure case 'a','aa' → False
Different lengths can never be made equal → False.
Count (row, column) pairs that contain the same sequence.
Why? undefined
💡 Key idea undefined
Edge / failure case [[1,2],[3,4]] → 0
No row matches any column → 0 pairs.
Each * deletes the closest non-star letter to its left. Return what remains.
Why? undefined
💡 Key idea undefined
Edge / failure case 'erase*****' → ''
Five stars delete all five letters, leaving an empty string.
Positive moves right, negative moves left. Smaller explodes; equal both explode. Final state?
Why? undefined
💡 Key idea undefined
Edge / failure case [8,-8] → []
Equal sizes meeting head-on: both explode → nothing left.
Expand k[encoded] patterns, possibly nested.
Why? undefined
💡 Key idea undefined
Edge / failure case '2[abc]3[cd]ef' → 'abcabccdcdcdef'
Several blocks in a row each expand separately.
ping(t) returns how many pings happened in the last 3000 ms (inclusive).
Why? undefined
💡 Key idea undefined
Edge / failure case ping(1), ping(5000) → [1, 1]
The second ping is far outside the 3000 ms window of the first, so the count resets to 1.
Senators ban opponents in turn. Which party wins?
Why? undefined
💡 Key idea undefined
Edge / failure case 'RD' → 'Radiant'
R acts first and bans D, so Radiant wins.
Delete the middle node (index ⌊n/2⌋) and return the head.
Why? undefined
💡 Key idea undefined
Edge / failure case [2,1] → 2
With 2 nodes the middle is index 1, so only the first node remains.
Group all odd-position nodes first, then even-position nodes, in place.
Why? undefined
💡 Key idea undefined
Edge / failure case [2,1,3,5,6,4,7] → 2 → 3 → 6 → 7 → 1 → 5 → 4
Odd positions (2,3,6,7) come first, then even positions (1,5,4).
Reverse a singly linked list.
Why? undefined
💡 Key idea undefined
Edge / failure case [] → None
An empty list has nothing to reverse → None.
Node i pairs with node n-1-i (its twin). Find the largest twin sum.
Why? undefined
💡 Key idea undefined
Edge / failure case [1,100000] → 100001
With only two nodes they are twins of each other.
How many levels does the tree have (longest root-to-leaf path)?
Why? undefined
💡 Key idea undefined
Edge / failure case [] → 0
An empty tree has depth 0.
Two trees are leaf-similar if their leaf values, read left to right, match.
Why? undefined
💡 Key idea undefined
Edge / failure case [1,2,3],[1,3,2] → False
Leaves read 2,3 in one tree and 3,2 in the other → not similar.
A node is good if no node on the path from the root is larger. Count them.
Why? undefined
💡 Key idea undefined
Edge / failure case [3,3,null,4,2] → 3
The node 2 is smaller than 3 and 4 above it, so it is not good.
Count downward paths whose values sum to target.
Why? undefined
💡 Key idea undefined
Edge / failure case [1,2],5 → 0
No downward path adds up to 5 → 0 paths.
Longest path that alternates left, right, left, right…
Why? undefined
💡 Key idea undefined
Edge / failure case [1] → 0
A single node has no steps to zigzag.
Find the lowest node that has both p and q as descendants.
Why? undefined
💡 Key idea undefined
Edge / failure case p = 5, q = 4 → [5, 6, 2, None, None, 7, 4]
Node 4 is below node 5, and a node counts as its own ancestor → 5.
What do you see standing on the right side of the tree?
Why? undefined
💡 Key idea undefined
Edge / failure case [1,null,3] → [1, 3]
The tree only has a right branch, so both nodes are visible.
Which level (1-indexed) has the largest sum?
Why? undefined
💡 Key idea undefined
Edge / failure case [-100,-200,-300] → 1
All sums are negative; the biggest (least negative) is the first level.
Return the subtree rooted at the node whose value equals val.
Why? undefined
💡 Key idea undefined
Edge / failure case [4,2,7,1,3],5 → None
5 is not in the tree → None.
Delete the node with the given key and keep it a valid BST.
Why? undefined
💡 Key idea undefined
Edge / failure case [5,3,6,2,4,null,7],0 → [5, 3, 6, 2, 4, None, 7]
The key 0 is not in the tree, so nothing is deleted.
Room 0 is open. Each room holds keys to other rooms. Can you visit them all?
Why? undefined
💡 Key idea undefined
Edge / failure case [[1],[2],[3],[]] → True
Every room's key opens the next one, so all rooms are reachable → True.
Cities are connected directly or indirectly. Count the groups.
Why? undefined
💡 Key idea undefined
Edge / failure case [[1,0,0],[0,1,0],[0,0,1]] → 3
Nobody is connected → 3 separate provinces.
Roads are one-way. Flip the fewest so every city can reach city 0.
Why? undefined
💡 Key idea undefined
Edge / failure case 5,[[1,0],[1,2],[3,2],[3,4]] → 2
Two roads point away from city 0 and must be flipped.
Given a/b = 2 and b/c = 3, answer queries like a/c and c/a.
Why? undefined
💡 Key idea undefined
Edge / failure case [['a','b']],[0.5],[['a','b'],['b','a'],['a','c'],['x','y']] → [0.5, 2, -1, -1]
Unknown variables (c, x, y) give -1.
Fewest steps from the entrance to any border exit ('.' cells on the edge).
Why? undefined
💡 Key idea undefined
Edge / failure case [['+','.','+'],['+','+','+']],[0,1] → -1
The entrance is the only open cell, so there is no exit → -1.
Each minute rotten oranges (2) rot adjacent fresh ones (1). Minutes until none are fresh?
Why? undefined
💡 Key idea undefined
Edge / failure case [[2,1,1],[0,1,1],[1,0,1]] → -1
The bottom-left orange is cut off by empty cells and never rots → -1.
Find the kth largest value (not kth distinct).
Why? undefined
💡 Key idea undefined
Edge / failure case [3,2,3,1,2,4,5,5,6],4 → 4
Duplicates count separately: sorted desc 6,5,5,4 → the 4th is 4.
An infinite set {1,2,3,…}. popSmallest removes and returns the smallest; addBack(x) restores x.
Why? undefined
💡 Key idea undefined
Edge / failure case addBack(5), popSmallest() → [None, 1]
5 was never removed, so adding it back changes nothing.
Pick k indices; score = (sum of nums1) × (min of nums2). Maximise it.
Why? undefined
💡 Key idea undefined
Edge / failure case [4,2,3,1,1],[7,5,10,9,6],1 → 30
With k = 1, pick the index with the best nums1 × nums2.
Hire k workers in rounds; each round take the cheapest among the first/last `candidates` (ties → lower index).
Why? undefined
💡 Key idea undefined
Edge / failure case [1,2,4,1],3,3 → 4
The two candidate windows overlap, so each worker is considered once.
Guess the number I picked from 1…n using an API that says higher or lower.
Why? undefined
💡 Key idea undefined
Edge / failure case n = 1, picked = 1 → 1
With n = 1 the only possible number is 1.
A pair succeeds if spell × potion ≥ success. For each spell, count the potions that work.
Why? undefined
💡 Key idea undefined
Edge / failure case [3,1,2],[8,5,8],16 → [2, 0, 2]
Only spell 3 and spell 2 reach 16 with a potion of 8.
Find any index whose value is greater than both neighbours, in O(log n).
Why? undefined
💡 Key idea undefined
Edge / failure case [1,2,3,4,5] → 4
The numbers only go up, so the peak is the last element.
Smallest eating speed k (bananas/hour) to finish all piles within h hours.
Why? undefined
💡 Key idea undefined
Edge / failure case [30,11,23,4,20],5 → 30
With h equal to the number of piles she must finish a whole pile each hour.
Return all letter combinations a digit string could represent on a phone keypad.
Why? undefined
💡 Key idea undefined
Edge / failure case '' → []
No digits → no combinations.
Choose k distinct numbers from 1–9 that add up to n.
Why? undefined
💡 Key idea undefined
Edge / failure case 4,1 → []
Four different numbers can't add up to 1 → empty list.
T0=0, T1=1, T2=1, Tn = Tn-1 + Tn-2 + Tn-3. Find Tn.
Why? undefined
💡 Key idea undefined
Edge / failure case 0 → 0
T0 is defined as 0.
Pay cost[i] to climb from step i by 1 or 2. Start at step 0 or 1; reach the top. Minimum cost?
Why? undefined
💡 Key idea undefined
Edge / failure case [10,15,20] → 15
Start on the 15 step and jump past the top.
Rob houses for maximum money without robbing two adjacent houses.
Why? undefined
💡 Key idea undefined
Edge / failure case [5] → 5
With a single house just rob it.
Count ways to tile a 2×n board with dominoes and L-trominoes (mod 10⁹+7).
Why? undefined
💡 Key idea undefined
Edge / failure case 1 → 1
A 2×1 board has exactly one tiling (a vertical domino).
A robot moves only right or down from top-left to bottom-right. How many paths?
Why? undefined
💡 Key idea undefined
Edge / failure case 3,2 → 3
A 3×2 grid has 3 paths.
Length of the longest subsequence common to both strings.
Why? undefined
💡 Key idea undefined
Edge / failure case 'abc','def' → 0
No letter is shared → length 0.
Unlimited trades, but pay a fee per sale. Maximum profit?
Why? undefined
💡 Key idea undefined
Edge / failure case [5,4,3,2],1 → 0
Prices only fall, so never trading (profit 0) is best.
Minimum insert / delete / replace operations to turn word1 into word2.
Why? undefined
💡 Key idea undefined
Edge / failure case 'intention','execution' → 5
A longer pair needs 5 edits.
For every i in 0…n, count the 1-bits in i's binary form.
Why? undefined
💡 Key idea undefined
Edge / failure case 0 → [0]
Only the number 0, which has no 1 bits.
Every number appears twice except one. Find it in O(1) space.
Why? undefined
💡 Key idea undefined
Edge / failure case [1] → 1
A single element is the answer.
Fewest bit flips in a and/or b so that (a OR b) == c.
Why? undefined
💡 Key idea undefined
Edge / failure case 1,2,3 → 0
1 OR 2 already equals 3 → 0 flips.
For each day, how many days until a warmer one? (0 if never.)
Why? undefined
💡 Key idea undefined
Edge / failure case [90,80,70] → [0, 0, 0]
It only gets colder, so every answer is 0.
For each price, count consecutive previous days (including today) with price ≤ today's.
Why? undefined
💡 Key idea undefined
Edge / failure case 5, 4, 3, 2 → [1, 1, 1, 1]
Prices keep falling, so every span is just 1.
Remove the fewest intervals so the rest don't overlap.
Why? undefined
💡 Key idea undefined
Edge / failure case [[1,2],[1,2],[1,2]] → 2
Three identical intervals overlap; keep one, remove two.
Balloons span [start, end] on the x-axis. An arrow at x bursts every balloon covering x. Fewest arrows?
Why? undefined
💡 Key idea undefined
Edge / failure case [[1,2],[3,4],[5,6],[7,8]] → 4
No balloons overlap, so each needs its own arrow.
Build a trie with insert, search (whole word) and startsWith (prefix).
Why? undefined
💡 Key idea undefined
Edge / failure case insert(hello), search(hell), startsWith(hell), search(help) → [None, False, True, False]
'hell' is only a prefix of 'hello', not a stored word; 'help' was never inserted.
After each typed letter, suggest up to 3 products with that prefix, in lexicographic order.
Why? undefined
💡 Key idea undefined
Edge / failure case ['havana'],'tatiana' → [[], [], [], [], [], [], []]
No product starts with 't', so every suggestion list is empty.
Two sorted lists. nums1 has empty room (zeros) at the end. Merge nums2 into nums1 so the whole thing is sorted, in place.
Why? nums1 = [1,2,3,_,_,_], nums2 = [2,5,6] → [1,2,2,3,5,6].
💡 Key idea Fill nums1 from the BACK with the biggest remaining value, so nothing gets overwritten.
Edge / failure case nums1=[1], m=1, nums2=[], n=0 → [1]
nums2 is empty, so nums1 stays as it is.
Remove every copy of val from the list in place. Return how many items remain; the first k slots must hold them.
Why? [3,2,2,3], val = 3 → keep 2,2 → return 2.
💡 Key idea One pointer reads, another writes: copy only the values you want to keep.
Edge / failure case [0,1,2,2,3,0,4,2], val=2 → [5, [0, 0, 1, 3, 4]]
Every 2 is removed; the other 5 numbers stay.
The list is sorted. Remove duplicates in place so each value appears once. Return how many unique values.
Why? [0,0,1,1,1,2,2,3,3,4] → 0,1,2,3,4 → return 5.
💡 Key idea Compare each number with the last kept one; keep it only if different.
Edge / failure case [1,2,3] → [3, [1, 2, 3]]
No duplicates, so nothing is removed.
Sorted list. Allow each value at most TWICE. Remove extras in place and return the new length.
Why? [1,1,1,2,2,3] → 1,1,2,2,3 → length 5.
💡 Key idea Keep x if fewer than 2 are kept, or if it differs from the value two places back.
Edge / failure case [0,0,1,1,1,1,2,3,3] → [7, [0, 0, 1, 1, 2, 3, 3]]
The extra 1s beyond two copies are dropped.
One number appears more than half the time. Find it.
Why? [2,2,1,1,1,2,2]: 2 appears 4 of 7 times → 2.
💡 Key idea Boyer–Moore voting: keep a candidate and a count. Equal numbers add, different ones cancel out.
Edge / failure case [3,2,3] → 3
3 appears 2 of 3 times — more than half.
Rotate the list to the right by k steps, in place.
Why? [1..7], k = 3: the last 3 numbers move to the front → [5,6,7,1,2,3,4].
💡 Key idea Reverse everything, then reverse the first k, then reverse the rest.
Edge / failure case [-1,-100,3,99], k=2 → [3, 99, -1, -100]
Rotating right by 2 moves the last two numbers to the front.
Prices per day. Buy once, sell once later. What's the biggest profit (0 if none)?
Why? [7,1,5,3,6,4]: buy at 1, sell at 6 → profit 5.
💡 Key idea Track the lowest price so far; profit today = price − lowest.
Edge / failure case [7,6,4,3,1] → 0
Prices only fall, so the best is not to trade → 0.
Prices per day. Buy and sell as many times as you like (hold one share at most). Maximum profit?
Why? [7,1,5,3,6,4]: buy 1 sell 5 (+4), buy 3 sell 6 (+3) → 7.
💡 Key idea Grab every upward step: add up each day's gain when the price rose.
Edge / failure case [1,2,3,4,5] → 4
Prices rise every day: buy at 1, sell at 5 (or add each day's gain).
Each number is the maximum jump length from that spot. Starting at the first spot, can you reach the last?
Why? [2,3,1,1,4]: from 0 you can reach 1 or 2; from 1 you can jump up to 4 → the end is reachable → True.
💡 Key idea Track the farthest spot you can reach. If you ever stand beyond it, you're stuck.
Edge / failure case [3,2,1,0,4] → False
Every path ends on the 0 at index 3 and gets stuck → False.
Same jump rules, and the end is always reachable. What's the fewest jumps to reach the last spot?
Why? [2,3,1,1,4]: jump 0→1 (1 jump), then 1→4 (2 jumps) → 2.
💡 Key idea Think in 'waves': when you reach the end of the current wave, take a jump to the farthest spot seen.
Edge / failure case [2,3,0,1,4] → 2
Jump to index 1 (value 3), then straight to the end → 2 jumps.
Citations per paper. The h-index is the biggest h where h papers have at least h citations each.
Why? [3,0,6,1,5] sorted high→low: 6,5,3,1,0. Three papers have ≥ 3 citations → h = 3.
💡 Key idea Sort descending, then count while the citation at position h is bigger than h.
Edge / failure case [1,3,1] → 1
Only one paper has at least 1 citation… h = 1.
Build a set where insert, remove and getRandom all run in O(1) time.
Why? insert 1, insert 2, remove 1, getRandom (only 2 is left).
💡 Key idea A list for random access + a dictionary of value → index. To remove, swap the last item into the hole.
Edge / failure case remove(1), insert(1), insert(1), getRandom() → [False, True, False, 1]
Removing a missing value and inserting a duplicate both return False.
Gas stations in a circle. gas[i] is fuel you get at station i, cost[i] is fuel to drive to the next one. Which station can you start from to complete a lap? (−1 if none)
Why? gas [1,2,3,4,5], cost [3,4,5,1,2] → start at station 3.
💡 Key idea If the tank goes negative, the start can't be anywhere before here — restart from the next station.
Edge / failure case [2,3,4],[3,4,3] → -1
Total gas (9) is less than total cost (10), so no start works → -1.
Children in a line with ratings. Everyone gets at least 1 candy, and a child with a higher rating than a neighbour gets more candy than that neighbour. Fewest candies?
Why? ratings [1,0,2] → candies [2,1,2] = 5.
💡 Key idea Two passes: left→right fixes 'higher than left neighbour', right→left fixes 'higher than right neighbour'.
Edge / failure case [1,2,2] → 4
Equal neighbours don't need extra candy → 1 + 2 + 1 = 4.
Bars of different heights. After rain, how much water is trapped between the bars?
Why? [0,1,0,2,1,0,1,3,2,1,2,1] traps 6 units.
💡 Key idea Water above a bar = (shorter of the tallest bar on each side) − its height. Use two pointers moving inward.
Edge / failure case [4,2,0,3,2,5] → 9
Deep valley between two tall walls traps 9 units.
Convert a Roman numeral to a number.
Why? MCMXCIV = 1000 + (1000−100) + (100−10) + (5−1) = 1994.
💡 Key idea If a symbol is smaller than the next one, subtract it; otherwise add it.
Edge / failure case 'LVIII' → 58
L + V + III = 50 + 5 + 3 = 58.
Convert a number to a Roman numeral.
Why? 1994 = M (1000) + CM (900) + XC (90) + IV (4) → MCMXCIV.
💡 Key idea Go through the values from biggest to smallest, taking each as many times as it fits.
Edge / failure case 58 → 'LVIII'
58 = L (50) + V (5) + III (3).
A sentence with spaces. How long is the last word?
Why? ' fly me to the moon ' → last word is 'moon' → 4.
💡 Key idea split() throws away extra spaces; take the last piece.
Edge / failure case 'luffy is still joyboy' → 6
The last word is 'joyboy'.
Find the longest beginning shared by all the words.
Why? flower, flow, flight all start with 'fl'.
💡 Key idea Start with the first word as the prefix and shorten it until each other word starts with it.
Edge / failure case ['dog','racecar','car'] → ''
The words share no starting letters → empty string.
Write the text in a zigzag down and up over numRows rows, then read it row by row.
Why? PAYPALISHIRING on 3 rows reads PAHNAPLSIIGYIR.
💡 Key idea Walk through the letters, moving the row down then up, bouncing at the top and bottom.
Edge / failure case 'PAYPALISHIRING',4 → 'PINALSIGYAHRPI'
With 4 rows the zigzag reads PINALSIGYAHRPI.
Find where the word needle first appears inside haystack. Return −1 if it doesn't.
Why? haystack 'hello', needle 'll' → starts at index 2.
💡 Key idea Slide a window the size of the needle along the haystack and compare.
Edge / failure case 'leetcode','leeto' → -1
'leeto' never appears in 'leetcode' → -1.
Pack words into lines of exactly maxWidth characters, spreading extra spaces evenly between words. The last line is left-aligned.
Why? Words This, is, an | example, of, text | justification. with width 16.
💡 Key idea Fit as many words as possible per line; then share leftover spaces across the gaps (extras go to the left gaps).
Edge / failure case ['What','must','be','acknowledgment','shall','be'],16 → ['What must be', 'acknowledgment ', 'shall be ']
A long word fills its own line; the last line is left-aligned.
Ignoring spaces, punctuation and capital letters, does the text read the same forwards and backwards?
Why? 'A man, a plan, a canal: Panama' becomes amanaplanacanalpanama, which is a palindrome → True.
💡 Key idea Two pointers from the ends moving inward; every pair must match.
Edge / failure case 'race a car' → False
'raceacar' does not read the same backwards → False.
The list is sorted. Find two numbers that add up to the target and return their positions (counting from 1).
Why? [2,7,11,15], target 9: 2 + 7 = 9 → positions 1 and 2.
💡 Key idea Pointers at both ends: sum too small → move left up; too big → move right down.
Edge / failure case [-1,0],-1 → [1, 2]
-1 + 0 = -1 at positions 1 and 2.
Find all unique triples in the list that add up to 0.
Why? [-1,0,1,2,-1,-4] → [-1,-1,2] and [-1,0,1].
💡 Key idea Sort. Fix one number, then use two pointers on the rest; skip duplicates.
Edge / failure case [0,1,1] → []
No three numbers add up to 0 → empty list.
Find the shortest run of numbers in a row whose sum is at least target.
Why? target 7 on [2,3,1,2,4,3]: the run [4,3] adds to 7 and has length 2.
💡 Key idea Grow the window on the right; while the sum is big enough, shrink from the left and record the length.
Edge / failure case 11,[1,1,1,1,1,1,1,1] → 0
The whole list sums to 8 < 11, so no subarray works → 0.
Find the longest piece of the text with no repeated letter.
Why? 'abcabcbb': 'abc' has no repeats and length 3 → 3.
💡 Key idea Slide a window; when a letter repeats, jump the left edge past its previous spot.
Edge / failure case 'bbbbb' → 1
Every letter repeats → the longest unique run is 1.
Find every start position where the text contains all the given words (same length), joined in any order with nothing in between.
Why? s = 'barfoothefoobarman', words foo + bar: 'barfoo' starts at 0, 'foobar' starts at 9 → [0, 9].
💡 Key idea Slice the text into word-sized chunks from each start and compare their counts with the word counts.
Edge / failure case 'wordgoodgoodgoodbestword',['word','good','best','word'] → []
The words can't be arranged to cover any 16-letter slice → empty.
Find the shortest piece of s that contains every letter of t (with repeats).
Why? s = ADOBECODEBANC, t = ABC → the shortest piece is BANC.
💡 Key idea Expand right until all needed letters are covered, then shrink left as far as possible; remember the smallest.
Edge / failure case 'a','aa' → ''
s has only one 'a' but t needs two → empty string.
Is a partly filled 9×9 Sudoku board valid so far? No repeated digit in any row, column or 3×3 box (empty cells ignored).
Why? The sample board has no repeats anywhere → True.
💡 Key idea Walk every cell and remember (row, digit), (column, digit), (box, digit) in a set; a repeat means invalid.
Edge / failure case the sample board with the top-left cell changed to 8 → False
Putting an 8 in the top-left makes two 8s in the first column → invalid.
Read a grid in spiral order: across the top, down the right side, back along the bottom, up the left side, then inward.
Why? [[1,2,3],[4,5,6],[7,8,9]] → 1,2,3,6,9,8,7,4,5.
💡 Key idea Peel off the top row, then rotate what's left so the next side becomes the top.
Edge / failure case [[1,2,3,4],[5,6,7,8],[9,10,11,12]] → [1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7]
A 3×4 grid spirals around and then inwards.
Rotate a square grid 90° clockwise, in place.
Why? [[1,2,3],[4,5,6],[7,8,9]] → [[7,4,1],[8,5,2],[9,6,3]].
💡 Key idea Transpose (swap rows and columns), then reverse each row.
Edge / failure case a 4×4 matrix → [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]]
A 4×4 grid rotated 90° clockwise.
If a cell is 0, turn its whole row and column to 0.
Why? [[1,1,1],[1,0,1],[1,1,1]] → the middle row and column become 0.
💡 Key idea First note which rows and columns have a 0, then zero them all.
Edge / failure case [[0,1,2,0],[3,4,5,2],[1,3,1,5]] → [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]
Two zeros zero out two rows and two columns.
Each cell is alive (1) or dead (0). All cells update at once: a live cell survives with 2–3 live neighbours; a dead cell comes alive with exactly 3; everything else dies or stays dead.
Why? The 4×3 sample board becomes the next generation shown on the right.
💡 Key idea Compute the next board from the old one (so updates don't affect each other), then copy it back.
Edge / failure case [[1,1],[1,0]] → [[1, 1], [1, 1]]
The dead cell has exactly 3 live neighbours → it comes alive.
Can you build the ransom note using letters cut from the magazine (each letter used once)?
Why? note 'aa', magazine 'aab' → the magazine has two a's → True.
💡 Key idea Count letters in both; the note's counts must fit inside the magazine's.
Edge / failure case 'a','b' → False
The magazine has no 'a' → False.
Can you swap letters in s to get t, with each letter always mapping to the same letter (and no two letters sharing a target)?
Why? egg → add: e→a, g→d works → True.
💡 Key idea Keep two maps (s→t and t→s); any conflict means False.
Edge / failure case 'foo','bar' → False
'o' would have to map to both 'a' and 'r' → False.
Does the text follow the pattern, with each pattern letter standing for exactly one word (and vice versa)?
Why? pattern abba and 'dog cat cat dog': a=dog, b=cat → True.
💡 Key idea Two maps again: letter→word and word→letter.
Edge / failure case 'abba','dog cat cat fish' → False
The last 'a' needs 'dog' but sees 'fish' → False.
Are the two words made of exactly the same letters (rearranged)?
Why? 'anagram' and 'nagaram' both have a×3, n×1, g×1, r×1, m×1 → True.
💡 Key idea Count the letters in each and compare.
Edge / failure case 'rat','car' → False
The letters differ → False.
Group together the words that are anagrams of each other.
Why? eat, tea, ate share letters a-e-t; tan, nat share a-n-t; bat is alone.
💡 Key idea Sort each word's letters to get a key; words with the same key go in the same group.
Edge / failure case [''] → [['']]
A single empty string forms one group.
Find two numbers in the list that add up to the target and return their positions.
Why? [2,7,11,15], target 9: 2 + 7 = 9 → positions 0 and 1.
💡 Key idea For each number, check if (target − number) was already seen, using a dictionary.
Edge / failure case [3,2,4],6 → [1, 2]
3 + 3 would reuse the same element; the answer is 2 + 4 at indexes 1 and 2.
Repeatedly replace a number by the sum of the squares of its digits. If it reaches 1 it's happy; if it loops forever it isn't.
Why? 19 → 82 → 68 → 100 → 1 → happy.
💡 Key idea Remember numbers you've seen; seeing one again means a loop.
Edge / failure case 2 → False
2 → 4 → 16 → 37 → 58 → 89 → 145 → 42 → 20 → 4 loops forever → False.
Are there two equal numbers whose positions differ by at most k?
Why? [1,2,3,1], k = 3: the two 1s are 3 apart → True.
💡 Key idea Remember each number's last position in a dictionary.
Edge / failure case [1,2,3,1,2,3],2 → False
Equal numbers are 3 apart, more than k = 2 → False.
Find the longest run of consecutive integers (like 1,2,3,4) in the unsorted list, in O(n).
Why? [100,4,200,1,3,2] contains 1,2,3,4 → length 4.
💡 Key idea Put numbers in a set. Only start counting from numbers with no smaller neighbour.
Edge / failure case [0,3,7,2,5,8,4,6,0,1] → 9
0 through 8 are all present → length 9.
Turn a sorted list of unique numbers into the shortest list of ranges.
Why? [0,1,2,4,5,7] → 0→2, 4→5, 7.
💡 Key idea Walk along; extend each run while the next number is exactly one bigger.
Edge / failure case [0,2,3,4,6,8,9] → ['0', '2->4', '6', '8->9']
Runs: 0, 2→4, 6, 8→9.
Merge all overlapping ranges.
Why? [1,3] and [2,6] overlap → [1,6]; [8,10] and [15,18] stand alone.
💡 Key idea Sort by start. If the next one starts before the last one ends, extend the last one.
Edge / failure case [[1,4],[4,5]] → [[1, 5]]
Intervals that touch at 4 are merged.
A sorted list of non-overlapping ranges plus one new range. Insert it and merge anything that overlaps.
Why? Insert [4,8] into [1,2],[3,5],[6,7],[8,10],[12,16] → it swallows [3,5],[6,7],[8,10] → [3,10].
💡 Key idea Three phases: copy ranges that end before the new one, merge the overlapping ones, copy the rest.
Edge / failure case [[1,3],[6,9]],[2,5] → [[1, 5], [6, 9]]
[2,5] overlaps [1,3] → [1,5]; [6,9] stays.
Is every bracket ( [ { closed by the matching bracket in the right order?
Why? '([{}])' is perfectly nested → True. '(]' would be False.
💡 Key idea Push opening brackets. On a closing bracket, the top of the stack must be its partner.
Edge / failure case '(]' → False
The ']' doesn't match the '(' → False.
Clean up a Unix file path: '.' means stay, '..' means go up one folder, and extra slashes collapse.
Why? '/a/./b/../../c/' → into a, stay, into b, up, up, into c → '/c'.
💡 Key idea Split on '/'; push folder names, pop on '..'.
Edge / failure case '/../' → '/'
Going up from the root stays at the root → '/'.
A stack that can also tell you its smallest value instantly.
Why? push -2, 0, -3 → getMin = -3 → pop → top = 0 → getMin = -2.
💡 Key idea Store each value together with the minimum so far.
Edge / failure case push(5), push(3), getMin(), pop(), getMin() → [None, None, 3, None, 5]
After popping 3, the minimum is 5 again.
Evaluate math written with the operator AFTER its numbers (e.g. 2 1 + means 2 + 1).
Why? ['2','1','+','3','*'] = (2 + 1) × 3 = 9.
💡 Key idea Push numbers; at an operator pop two, compute, push the result.
Edge / failure case ['4','13','5','/','+'] → 6
13 / 5 = 2 (truncated), then 4 + 2 = 6.
Evaluate an expression with + , − and parentheses (no multiplication).
Why? '1-(2+3)+4' = 1 − 5 + 4 = 0.
💡 Key idea Track a running total and the current sign. On '(' save them on a stack; on ')' combine.
Edge / failure case '(1+(4+5+2)-3)+(6+8)' → 23
Nested parentheses evaluate inside-out → 23.
Does the linked list loop back on itself?
Why? 3→2→0→−4 and −4 points back to 2 → there's a cycle → True.
💡 Key idea A slow pointer (1 step) and a fast pointer (2 steps): in a loop, fast catches slow.
Edge / failure case 1 → 2 → None → False
The list ends with None, so fast reaches the end → no cycle.
Two numbers are stored as linked lists with digits in REVERSE order. Add them and return the sum the same way.
Why? 2→4→3 is 342, 5→6→4 is 465 → 807, stored as 7→0→8.
💡 Key idea Add digit by digit like on paper, carrying over.
Edge / failure case [9,9,9,9,9,9,9],[9,9,9,9] → 8 → 9 → 9 → 9 → 0 → 0 → 0 → 1
Carries ripple through all digits and add a new leading 1.
Join two sorted linked lists into one sorted list.
Why? [1,2,4] and [1,3,4] → 1,1,2,3,4,4.
💡 Key idea Keep a tail pointer; repeatedly attach the smaller front node.
Edge / failure case [],[0] → 0
One list is empty, so the answer is the other list.
Each node has a 'next' and also a 'random' pointer to any node. Make a deep copy of the whole list.
Why? List A→B→C with random pointers; the copy has new nodes A'→B'→C' with matching pointers.
💡 Key idea Pass 1: make a copy of every node and remember old→new in a dictionary. Pass 2: wire up next and random using the dictionary.
Edge / failure case one node, random → itself → Node('A')
A single node whose random pointer points to itself.
Reverse only the part of the list from position left to position right.
Why? 1→2→3→4→5, left 2, right 4 → 1→4→3→2→5.
💡 Key idea Walk to the node before the section, then repeatedly move the next node to the front of the section.
Edge / failure case [5],1,1 → 5
left = right → nothing to reverse.
Reverse the list k nodes at a time. If fewer than k nodes remain, leave them as they are.
Why? 1→2→3→4→5 with k = 2 → 2→1→4→3→5.
💡 Key idea Check that k nodes exist, reverse them, and attach to the result of handling the rest.
Edge / failure case [1,2,3,4,5],3 → 3 → 2 → 1 → 4 → 5
Only the first 3 nodes form a full group; 4 and 5 stay.
Remove the nth node counting from the END of the list.
Why? 1→2→3→4→5, n = 2 → remove 4 → 1→2→3→5.
💡 Key idea Send fast n steps ahead, then move both until fast is at the end; slow is just before the target.
Edge / failure case [1],1 → None
Removing the only node leaves an empty list.
In a sorted linked list, delete EVERY value that appears more than once (not just the extras).
Why? 1→2→3→3→4→4→5 → 1→2→5.
💡 Key idea Use a previous pointer; when a value repeats, skip all its copies.
Edge / failure case [1,1,1,2,3] → 2 → 3
Every 1 is a duplicate and is removed entirely.
Rotate the linked list to the right by k places.
Why? 1→2→3→4→5, k = 2 → 4→5→1→2→3.
💡 Key idea Make the list a circle, then cut it at the right spot.
Edge / failure case [0,1,2],4 → 2 → 0 → 1
k = 4 wraps around (4 mod 3 = 1) → rotate by 1.
Rearrange so all nodes smaller than x come first, then the rest, keeping the original order within each group.
Why? 1→4→3→2→5→2 with x = 3 → 1→2→2→4→3→5.
💡 Key idea Build two lists (small and big) and join them.
Edge / failure case [2,1],2 → 1 → 2
1 < 2 goes first, then 2.
A cache with a fixed size. When it's full, throw out the Least Recently Used item. get and put both count as 'using' an item.
Why? Capacity 2: put 1, put 2, get 1, put 3 → evicts 2 (1 was used more recently), get 2 → −1.
💡 Key idea Keep items in usage order (an ordered dictionary): move to the end when used, drop from the front when full.
Edge / failure case capacity 2: put(1), put(2), put(3), get(1), get(3) → [None, None, None, -1, 3]
1 is the least recently used and gets evicted by put(3), so get(1) is -1.
Are two binary trees identical — same shape and same values?
Why? Both trees are 1 with children 2 and 3 → True.
💡 Key idea Compare the roots, then compare the left subtrees and the right subtrees the same way.
Edge / failure case [1,2],[1,null,2] → False
Same values but 2 is on a different side → False.
Flip the tree like a mirror: swap every node's left and right children.
Why? [4,2,7,1,3,6,9] becomes [4,7,2,9,6,3,1].
💡 Key idea Swap the two children, then do the same inside each child.
Edge / failure case [2,1,3] → [2, 3, 1]
Swap the two children.
Is the tree a mirror image of itself around its center?
Why? [1,2,2,3,4,4,3]: the left half is the mirror of the right half → True.
💡 Key idea Compare the left subtree with the right subtree, crossing over: outer with outer, inner with inner.
Edge / failure case [1,2,2,null,3,null,3] → False
Both 3s are on the same side, not mirrored → False.
Rebuild a tree from its preorder list (root first) and inorder list (left, root, right).
Why? preorder [3,9,20,15,7], inorder [9,3,15,20,7] → root 3, left 9, right 20 with children 15 and 7.
💡 Key idea The next preorder value is always a root. Find it in the inorder list: everything to its left is the left subtree.
Edge / failure case [-1],[-1] → [-1]
A single node.
Rebuild a tree from its inorder list and postorder list (left, right, root).
Why? inorder [9,3,15,20,7], postorder [9,15,7,20,3] → the same tree as before.
💡 Key idea The LAST postorder value is the root. Build the right subtree first, then the left.
Edge / failure case [-1],[-1] → [-1]
A single node.
Connect each node's 'next' pointer to the node on its right on the same level (or nothing if it's the last).
Why? Tree [1,2,3,4,5,null,7]: 2→3, 4→5→7, others end.
💡 Key idea Go level by level; link neighbours in each level.
Edge / failure case [1,2,3,4,null,null,5] → [[[1, None]], [[2, 3], [3, None]], [[4, 5], [5, None]]]
Level 3 links 4 → 5 even though they have different parents.
Turn the tree into a straight 'linked list' using only right pointers, in preorder order.
Why? [1,2,5,3,4,null,6] → 1→2→3→4→5→6.
💡 Key idea For each node with a left child: attach its right subtree to the end of the left subtree, then move the left subtree to the right.
Edge / failure case [0] → [0]
A single node is already flat.
Is there a root-to-leaf path whose values add up to the target?
Why? Target 22: 5 → 4 → 11 → 2 = 22 → True.
💡 Key idea Subtract each node's value from the target as you go down; at a leaf the remainder must be 0.
Edge / failure case [1,2,3],5 → False
Paths sum to 3 and 4 only → False.
Each root-to-leaf path spells a number (digits top to bottom). Add up all those numbers.
Why? Paths 4→9→5 = 495, 4→9→1 = 491, 4→0 = 40 → 1026.
💡 Key idea Carry the number so far down the tree: cur = cur × 10 + node value.
Edge / failure case [1,2,3] → 25
12 + 13 = 25.
A path can start and end at any node and moves along edges (it may turn once at a top node). What's the biggest sum of values on a path?
Why? [-10,9,20,null,null,15,7]: the path 15 → 20 → 7 sums to 42.
💡 Key idea For each node, find the best downward 'arm' from each child (ignore negatives). The best path through the node = value + left arm + right arm.
Edge / failure case [-3] → -3
A path must contain at least one node, so the answer is -3.
Build an iterator that returns a BST's values in sorted order, one at a time, without storing them all.
Why? BST [7,3,15,null,null,9,20] → next() returns 3, 7, 9, 15, 20.
💡 Key idea Keep a stack of the 'left spine'. Pop = next smallest; then push the left spine of its right child.
Edge / failure case BST [2,1,3]: next ×3, hasNext() → [1, 2, 3, False]
After three next() calls there is nothing left.
Count the nodes of a complete binary tree (all levels full except possibly the last, filled left to right) faster than visiting every node.
Why? [1,2,3,4,5,6] has 6 nodes.
💡 Key idea If the left depth equals the right depth the subtree is perfect: it has 2^depth − 1 nodes. Otherwise recurse.
Edge / failure case [] → 0
An empty tree has 0 nodes.
What is the average of the values on each level of the tree?
Why? [3,9,20,null,null,15,7]: level averages 3, (9+20)/2 = 14.5, (15+7)/2 = 11.
💡 Key idea BFS level by level; average = sum ÷ count.
Edge / failure case [5] → [5]
Just one level, one value.
List the tree's values level by level, left to right.
Why? [3,9,20,null,null,15,7] → [[3],[9,20],[15,7]].
💡 Key idea BFS with a queue; handle one level's worth of nodes at a time.
Edge / failure case [1] → [[1]]
A single node is a single level.
Level order again, but alternate direction: left→right, then right→left, then left→right…
Why? [3,9,20,null,null,15,7] → [[3],[20,9],[15,7]].
💡 Key idea Do normal BFS, and reverse every other level.
Edge / failure case [1,2,3,4,5,6,7] → [[1], [3, 2], [4, 5, 6, 7]]
Levels alternate direction: →, ←, →.
Find the smallest difference between any two values in a BST.
Why? [4,2,6,1,3]: in sorted order 1,2,3,4,6 the closest neighbours differ by 1.
💡 Key idea An inorder walk of a BST gives sorted values; only neighbours in that order need comparing.
Edge / failure case [1,0,48,null,null,12,49] → 1
Sorted values 0,1,12,48,49 — the closest pair (0,1) and (48,49) differ by 1.
Find the kth smallest value in a BST.
Why? Tree [5,3,6,2,4,null,null,1], k = 3 → inorder is 1,2,3,4,5,6 → the 3rd is 3.
💡 Key idea Inorder gives sorted order; stop at the kth node visited.
Edge / failure case [3,1,4,null,2],1 → 1
The smallest value is 1.
Is the tree a valid BST — every node bigger than everything in its left subtree and smaller than everything in its right?
Why? [5,1,6,null,null,3,7]: 3 sits in 5's right subtree but 3 < 5 → False.
💡 Key idea Pass down an allowed range (low, high) for each node.
Edge / failure case [2,1,3] → True
Left < root < right everywhere → valid.
A grid of land (1) and water (0). An island is land connected up/down/left/right. How many islands?
Why? The sample grid has three separate groups of 1s → 3.
💡 Key idea Scan the grid; when you hit unvisited land, count an island and 'sink' all connected land with DFS.
Edge / failure case [['0','0'],['0','0']] → 0
All water → no islands.
Capture every group of 'O's that is completely surrounded by 'X'. 'O's connected to the border stay.
Why? The big O group is enclosed → becomes X. The bottom O touches the border → stays.
💡 Key idea Start from border 'O's and mark everything connected to them as safe. Flip the rest.
Edge / failure case [['X']] → [['X']]
A single X has no O to capture.
Make a deep copy of a connected graph (new nodes with the same connections).
Why? A square graph 1–2–3–4–1 → a new square with its own nodes.
💡 Key idea Walk the graph; create each copy once (remember old→new in a dictionary) and connect copies to copies.
Edge / failure case one node, no neighbours → Node(1)
A graph with one node and no neighbours.
Some courses require others first. Can you finish all courses (is there an order with no circular requirement)?
Why? 4 courses: 1 and 2 need 0; 3 needs 1 and 2 → take 0, then 1, 2, then 3 → True.
💡 Key idea Keep taking courses that have no remaining requirements (topological sort). If you finish them all, True.
Edge / failure case 2,[[1,0],[0,1]] → False
Course 1 needs 0 and course 0 needs 1 — a cycle → False.
Same as Course Schedule, but return an order in which you can take all courses (or an empty list if impossible).
Why? 4 courses: one valid order is 0, 1, 2, 3.
💡 Key idea Topological sort: record each course as you take it.
Edge / failure case 2,[[1,0],[0,1]] → []
A cycle means no valid order → empty list.
Play snakes and ladders on an n×n board (squares numbered in a zigzag). Each move you roll 1–6; ladders/snakes move you. Fewest moves to reach the last square?
Why? 3×3 board with a ladder from 2 to 8: roll 1 (→2 → ladder to 8), then roll 1 → 9. That's 2 moves.
💡 Key idea BFS over squares: each square connects to the next 6 squares; the first time you reach the end is the minimum.
Edge / failure case [[-1,-1],[-1,3]] → 1
From square 1 one roll of 3 lands exactly on the last square (4) → 1 move.
A gene is an 8-letter string of A, C, G, T. A mutation changes ONE letter and the result must be in the bank. Fewest mutations from start to end?
Why? AAAAACCC → AAAACCCC → AAACCCCC → AACCCCCC takes 3 mutations.
💡 Key idea BFS: try every single-letter change; keep the ones that are in the bank and unseen.
Edge / failure case 'AACCGGTT','AACCGGTA',[] → -1
The bank is empty, so no mutation is allowed → -1.
Change one letter at a time to turn beginWord into endWord. Every step must be a word in the list. How many words are in the shortest sequence?
Why? hit → hot → dot → dog → cog is 5 words.
💡 Key idea BFS: from each word, try replacing each letter with a–z and keep words from the list.
Edge / failure case 'hit','cog',['hot','dot','dog','lot','log'] → 0
'cog' isn't in the word list, so the ladder can't finish → 0.
Store words, then search them where '.' can stand for any single letter.
Why? After adding bad, dad, mad: search('pad') → False, search('bad') → True, search('.ad') → True, search('b..') → True.
💡 Key idea A trie. For a '.', try every child branch.
Edge / failure case addWord(a), search(a), search(.), search(aa), search(b) → [None, True, True, False, False]
'.' matches any single letter; 'aa' is too long; 'b' was never added.
Find all words from a list that can be traced on a letter grid by moving up/down/left/right (no cell used twice in a word).
Why? On the sample board, 'oath' and 'eat' can be traced; 'pea' and 'rain' can't.
💡 Key idea Put the words in a trie, then DFS from every cell, following the trie so dead-end paths stop early.
Edge / failure case [['a','b'],['c','d']],['abcb'] → []
'abcb' would need to reuse the b cell → not found.
List every way to choose k numbers from 1 to n (order doesn't matter).
Why? n = 4, k = 2 → [1,2],[1,3],[1,4],[2,3],[2,4],[3,4].
💡 Key idea Backtracking: pick numbers in increasing order so you never repeat a set.
Edge / failure case 1,1 → [[1]]
Choose 1 number from 1 → just [1].
List every possible ordering of the given distinct numbers.
Why? [1,2,3] has 3 × 2 × 1 = 6 orderings.
💡 Key idea Backtracking: pick an unused number for each position, then undo and try the next.
Edge / failure case [0,1] → [[0, 1], [1, 0]]
Two items have 2 orderings.
Choose numbers from the list (each can be used any number of times) that add up to the target. List all unique combinations.
Why? candidates [2,3,6,7], target 7 → [2,2,3] and [7].
💡 Key idea Backtracking: add a number, recurse (it can repeat), and stop when the sum is too big.
Edge / failure case [2],1 → []
2 can't make 1 → no combination.
Place n queens on an n×n chessboard so none attack each other (no shared row, column or diagonal). How many ways?
Why? On a 4×4 board there are 2 solutions.
💡 Key idea Place one queen per row; skip columns and diagonals already used; undo when stuck.
Edge / failure case 2 → 0
On a 2×2 board every placement attacks → 0 solutions.
List every valid way to write n pairs of parentheses.
Why? n = 2 → (()) and ()().
💡 Key idea Build the string: you may add '(' while you have some left, and ')' only if there is an unmatched '('.
Edge / failure case 1 → ['()']
One pair has exactly one form: ()
Can you spell the word by moving through neighbouring cells (up/down/left/right) without reusing a cell?
Why? On the sample grid, ABCCED can be traced: A→B→C→C→E→D.
💡 Key idea DFS from every cell; mark the cell used while exploring, unmark when backing out.
Edge / failure case [['A','B','C','E'],['S','F','C','S'],['A','D','E','E']],'ABCB' → False
The path would reuse the same 'B' cell → False.
Turn a sorted list into a height-balanced binary search tree.
Why? [-10,-3,0,5,9] → a tree with 0 at the top.
💡 Key idea Pick the middle element as the root; build the left half and right half the same way.
Edge / failure case [1,3] → [1, None, 3]
Two items: one becomes the root, the other its child.
Sort a linked list in O(n log n).
Why? 4→2→1→3 becomes 1→2→3→4.
💡 Key idea Merge sort: split the list in half, sort each half, merge the two sorted halves.
Edge / failure case [-1,5,3,4,0] → -1 → 0 → 3 → 4 → 5
Merge sort handles negatives and unsorted input.
Compress a square grid of 0s and 1s into a quad tree: if a block is all the same value it's a leaf; otherwise split it into 4 quadrants.
Why? The sample 4×4 grid isn't uniform, so it splits into four 2×2 quadrants — each of which is uniform (1, 0, 1, 1).
💡 Key idea Check if the block is uniform. If not, split into 4 and recurse.
Edge / failure case [[1,1],[1,1]] → Node(True)
A uniform grid is one leaf.
Merge k sorted linked lists into one sorted list.
Why? [1,4,5], [1,3,4], [2,6] → 1,1,2,3,4,4,5,6.
💡 Key idea Keep a min-heap of the front node of each list; always take the smallest.
Edge / failure case [] → None
No lists to merge → None.
Find the contiguous run of numbers with the biggest sum.
Why? [-2,1,-3,4,-1,2,1,-5,4]: the run [4,-1,2,1] sums to 6.
💡 Key idea Kadane: at each number, either extend the current run or start fresh from this number.
Edge / failure case [-3,-2,-1] → -1
All negative: the best subarray is the single number -1.
The list is circular (the end connects to the start). Find the biggest sum of a contiguous run that may wrap around.
Why? [5,-3,5]: wrapping around, 5 + 5 = 10.
💡 Key idea The best run either doesn't wrap (normal Kadane) or wraps — then it equals total − (smallest run in the middle).
Edge / failure case [-3,-2,-3] → -2
All negative → best is the single largest element -2.
In a sorted list, find the index of the target, or the index where it would be inserted to keep the list sorted.
Why? [1,3,5,6], target 2 → it belongs at index 1.
💡 Key idea Binary search for the first position whose value is ≥ target.
Edge / failure case [1,3,5,6],7 → 4
7 is bigger than everything → insert at the end (index 4).
A grid where each row is sorted and each row starts bigger than the previous row ends. Is the target in it?
Why? Target 3 is in the first row → True.
💡 Key idea Pretend the grid is one long sorted list and binary search it (index → row = i ÷ n, column = i mod n).
Edge / failure case [[1,3,5,7],[10,11,16,20],[23,30,34,60]],13 → False
13 is not in the matrix → False.
A sorted list was rotated (e.g. [0,1,2,4,5,6,7] became [4,5,6,7,0,1,2]). Find the target's index in O(log n).
Why? target 0 in [4,5,6,7,0,1,2] → index 4.
💡 Key idea One half is always sorted. Check whether the target lies in the sorted half; if yes search there, else the other half.
Edge / failure case [4,5,6,7,0,1,2],3 → -1
3 is not in the array → -1.
In a sorted list, find the first and last index of the target (−1, −1 if missing).
Why? [5,7,7,8,8,10], target 8 → first at 3, last at 4.
💡 Key idea Binary search for the left edge (bisect_left) and the right edge (bisect_right − 1).
Edge / failure case [5,7,7,8,8,10],6 → [-1, -1]
6 isn't present → [-1, -1].
A sorted list was rotated. Find the smallest value in O(log n).
Why? [3,4,5,1,2] → the minimum is 1.
💡 Key idea Compare the middle with the right end: if the middle is bigger, the minimum is to the right; otherwise it's at mid or to the left.
Edge / failure case [11,13,15,17] → 11
Not actually rotated (or rotated n times) — the minimum is the first element.
Find the median of two sorted lists combined, in O(log(m+n)).
Why? [1,3] and [2]: merged is 1,2,3 → median 2.
💡 Key idea Binary search how many items to take from the smaller list so the left half and right half are balanced.
Edge / failure case [1,2],[3,4] → 2.5
Even total: average of the two middle values 2 and 3.
You start with capital w and can do at most k projects. Each project needs some minimum capital and gives a profit (added to your capital). Maximise final capital.
Why? k=2, w=0, profits [1,2,3], capital [0,1,1] → do project 0 (+1 → w=1), then project 2 (+3 → w=4).
💡 Key idea Each round, among projects you can afford, take the most profitable one (max-heap).
Edge / failure case 2,0,[1,2],[1,1] → 0
Every project needs capital 1 but we have 0 → we can't start any.
Two sorted lists. Pick one number from each to make a pair. List the k pairs with the smallest sums.
Why? [1,7,11] and [2,4,6], k = 3 → (1,2), (1,4), (1,6).
💡 Key idea A min-heap of candidate pairs; after taking (i, j), push the next pair (i, j+1).
Edge / failure case [1,1,2],[1,2,3],2 → [[1, 1], [1, 1]]
Duplicate values give two equal smallest pairs.
Numbers arrive one at a time. After each, report the median so far.
Why? Add 1, add 2 → median 1.5. Add 3 → median 2.
💡 Key idea Keep the smaller half in a max-heap and the larger half in a min-heap; the median is at the tops.
Edge / failure case addNum(-1), addNum(-2), findMedian(), addNum(-3), findMedian() → [None, None, -1.5, None, -2]
Negative numbers work the same way.
Add two binary numbers given as strings.
Why? '11' + '1' = 3 + 1 = 4 = '100'.
💡 Key idea Add from the right with a carry, like adding on paper.
Edge / failure case '1010','1011' → '10101'
10 + 11 = 21 = 10101.
Reverse the 32 bits of a number.
Why? (Shown with 8 bits.) 00001011 reversed is 11010000.
💡 Key idea Repeat: take the last bit of n and push it onto the end of the result.
Edge / failure case 0 → 0
Zero reversed is still zero.
Count the 1s in the binary form of a number.
Why? 11 is 1011 → three 1s.
💡 Key idea n & (n−1) removes the lowest 1 bit. Count how many times you can do it.
Edge / failure case 0 → 0
0 has no 1 bits.
Every number appears THREE times except one, which appears once. Find it.
Why? [2,2,3,2] → 3.
💡 Key idea Track which bits have been seen once ('ones') and twice ('twos'). A bit seen three times resets.
Edge / failure case [0,1,0,1,0,1,99] → 99
Everything repeats three times except 99.
What is the bitwise AND of every number from left to right?
Why? 5 AND 6 AND 7 = 4.
💡 Key idea The result is the common binary prefix of left and right. Shift both right until they match.
Edge / failure case 0,1 → 0
0 AND 1 = 0.
Is the integer the same when its digits are reversed?
Why? 121 reads the same both ways → True. −121 isn't (the minus sign) → False.
💡 Key idea Reverse only the second half of the digits and compare it with the first half.
Edge / failure case -121 → False
The minus sign makes it '-121' vs '121-' → False.
A number is stored as a list of digits. Add one to it.
Why? [1,2,9] means 129 → 130 → [1,3,0].
💡 Key idea From the right: a 9 becomes 0 and carries; the first non-9 digit gets +1.
Edge / failure case [9,9] → [1, 0, 0]
99 + 1 = 100 — a new leading digit appears.
How many zeros are at the end of n! (n factorial)?
Why? 25! ends in 6 zeros.
💡 Key idea Each zero comes from a factor 10 = 2 × 5, and 5s are rarer than 2s. Count the 5s: n/5 + n/25 + …
Edge / failure case 3 → 0
3! = 6 has no trailing zero.
Compute the square root of x, rounded down to a whole number (no built-in sqrt).
Why? sqrt(8) = 2.82… → 2.
💡 Key idea Binary search for the biggest number whose square is ≤ x.
Edge / failure case 0 → 0
The square root of 0 is 0.
Compute x raised to the power n quickly.
Why? 2^10 = 1024.
💡 Key idea Repeated squaring: look at the bits of n; multiply the result by x when the bit is 1, and square x each step.
Edge / failure case 2,-2 → 0.25
Negative exponent: 2⁻² = 1/4 = 0.25.
Given points on a plane, what's the most points that lie on one straight line?
Why? Points (1,1), (2,2), (3,3), (1,4): the first three are on a line → 3.
💡 Key idea From each point, count other points by their slope; the biggest group + the point itself is a line.
Edge / failure case [[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]] → 4
The best line passes through 4 of the 6 points.
You climb a staircase taking 1 or 2 steps at a time. How many different ways to reach step n?
Why? n = 5 → 8 ways.
💡 Key idea Ways(n) = Ways(n−1) + Ways(n−2) — it's the Fibonacci sequence.
Edge / failure case 2 → 2
Two ways: 1+1 or 2.
Can the text be split into words from the dictionary?
Why? 'leetcode' = 'leet' + 'code' → True.
💡 Key idea dp[i] = True if some earlier dp[j] is True and s[j:i] is a word.
Edge / failure case 'catsandog',['cats','dog','sand','and','cat'] → False
'og' at the end can't be formed from the dictionary → False.
With unlimited coins of given values, what's the fewest coins that make the amount? (−1 if impossible)
Why? coins [1,2,5], amount 11 → 5 + 5 + 1 = 3 coins.
💡 Key idea dp[a] = 1 + the best of dp[a − coin] over all coins.
Edge / failure case [2],3 → -1
Only 2-coins can't make an odd amount → -1.
Find the length of the longest strictly increasing subsequence (numbers in order, not necessarily next to each other).
Why? [10,9,2,5,3,7,101,18] → 2,3,7,101 → length 4.
💡 Key idea Keep a list 'tails' where tails[k] is the smallest possible end of an increasing subsequence of length k+1. Replace using binary search.
Edge / failure case [7,7,7,7] → 1
The sequence must be strictly increasing, so equal numbers give length 1.
Walk from the top of a number triangle to the bottom, moving to an adjacent number each row. What's the smallest path sum?
Why? [[2],[3,4],[6,5,7],[4,1,8,3]] → 2 + 3 + 5 + 1 = 11.
💡 Key idea Work from the bottom up: each cell = its value + the smaller of the two cells below it.
Edge / failure case [[-10]] → -10
A one-row triangle is just its only number.
Move from the top-left to the bottom-right of a grid, only right or down. What's the smallest sum of the numbers you pass?
Why? [[1,3,1],[1,5,1],[4,2,1]] → 1 → 3 → 1 → 1 → 1 = 7.
💡 Key idea Each cell = its value + the smaller of (cell above, cell to the left).
Edge / failure case [[1,2,3],[4,5,6]] → 12
Cheapest path is 1 → 2 → 3 → 6 = 12.
Like Unique Paths, but some cells are obstacles (1) you can't step on. How many paths from top-left to bottom-right?
Why? With one obstacle in the middle of a 3×3 grid there are 2 paths.
💡 Key idea Paths into a cell = paths from above + paths from the left; obstacle cells have 0.
Edge / failure case [[1,0]] → 0
The start itself is an obstacle → 0 paths.
Find the longest piece of the text that reads the same backwards.
Why? 'babad' → 'bab' (or 'aba') → length 3.
💡 Key idea Treat every position (and every gap) as a center and expand outwards while the letters match.
Edge / failure case 'cbbd' → 'bb'
The longest palindrome is the even-length 'bb'.
Can s3 be made by weaving letters of s1 and s2 together, keeping each string's own order?
Why? 'ab' and 'cd' can make 'acbd' (a from s1, c from s2, b from s1, d from s2) → True.
💡 Key idea dp[i][j] = can the first i letters of s1 and first j of s2 make the first i+j letters of s3?
Edge / failure case 'aabcc','dbbca','aadbbbaccc' → False
No way to weave the letters in order → False.
You may complete at most TWO buy-sell trades. What's the maximum profit?
Why? [3,3,5,0,0,3,1,4]: buy 0 sell 3 (+3), buy 1 sell 4 (+3) → 6.
💡 Key idea Track four numbers: best after buy 1, after sell 1, after buy 2, after sell 2.
Edge / failure case [7,6,4,3,1] → 0
Prices only fall → profit 0.
You may complete at most k buy-sell trades. What's the maximum profit?
Why? k = 2, prices [3,2,6,5,0,3]: buy 2 sell 6 (+4), buy 0 sell 3 (+3) → 7.
💡 Key idea Like the two-trade version, but keep buy[t] and sell[t] for every trade count t up to k.
Edge / failure case 2,[7,6,4,3,1] → 0
Prices only fall → profit 0.
In a grid of 0s and 1s, find the largest square made only of 1s and return its AREA.
Why? The largest all-1 square in the sample is 2×2 → area 4.
💡 Key idea dp[i][j] = side of the biggest square ending at that cell = 1 + min(up, left, up-left).
Edge / failure case [['0']] → 0
No 1s → area 0.
Why? Turn text like ' -42abc' into the number -42: skip spaces, read a sign, read digits, stop at anything else.
💡 Key idea Walk left to right once with an index: spaces → optional sign → digits. Clamp to the 32-bit range at the end.
Edge / failure case 'words and 987' → 0
The text starts with a letter, not a digit, so no number is read at all and the answer is 0.
Why? Where in the text does a rearrangement of the word p appear? 'cbaebabacd' with p='abc' → starts at 0 ('cba') and 6 ('bac').
💡 Key idea Slide a window the same length as p. Keep letter counts for the window and for p; when they match, record the start. Each step adds one letter and drops one.
Edge / failure case s="abab", p="ab" → [0, 1, 2]
Windows overlap: 'ab' at 0, 'ba' at 1 and 'ab' at 2 are all rearrangements of 'ab'.
Why? Does the text contain some rearrangement of s1 as a continuous piece? s1='ab', s2='eidbaooo' → 'ba' is there → True.
💡 Key idea Slide a window the same length as s1 over s2 and compare letter counts; a match means a rearrangement is hiding there.
Edge / failure case s1="ab", s2="eidboaoo" → False
'b' and 'a' are never next to each other, so no window of length 2 is a rearrangement of 'ab'.
Why? Join some of the given 2-letter words (each at most once) into the longest palindrome. 'lc' and 'cl' pair up; 'gg' can sit in the middle.
💡 Key idea A word pairs with its reverse (each pair adds 4 letters). A word like 'gg' pairs with another 'gg', and one leftover 'gg' can be the centre (+2).
Edge / failure case ["cc", "ll", "xx"] → 2
No word has a partner, but each is its own reverse; only one can sit in the middle, so the length is 2.
Why? Starting at the node with value k, which leaf (a node with no children) is the fewest steps away — going up, down, any direction?
💡 Key idea A tree only lets you walk down, but the answer may be up and over. Turn the tree into an undirected graph (add parent links) and run a BFS from k until you hit a leaf.
Edge / failure case tree [1,3,2], k=3 → 3
Node 3 is itself a leaf, so the answer is 3 without moving.
Why? Give directions from node A to node B using U (up), L (left), R (right). Climb to the meeting point, then walk down.
💡 Key idea Find the path from the root to each node as letters L/R. The shared beginning of both paths is the common route — cut it off. Each leftover letter of A's path becomes a U; B's leftover letters stay as they are.
Edge / failure case start=5, dest=4 → 'RR'
The start is already the top node (an ancestor of the destination), so no climbing is needed: just R, R.
Why? A grid of 0 (open) and 1 (blocked). Walk from the top-left to the bottom-right, moving in 8 directions through 0s. How many squares is the shortest path?
💡 Key idea Shortest path with equal step cost = BFS. Explore all 8 neighbours, mark squares as used the moment you queue them, and carry the path length with each square.
Edge / failure case [[1,0],[0,0]] → -1
The start square itself is blocked (1), so no path exists: -1.
Why? A chess knight starts at (0,0) on an endless board. How many moves to reach (x, y)?
💡 Key idea BFS over board squares, 8 knight moves each. By symmetry we may use |x| and |y|, and never need to stray more than 2 squares beyond the target.
Edge / failure case x=2, y=1 → 1
The target is exactly one knight move away.
Why? Walk from top-left to bottom-right; you may smash through at most k walls (1s). What is the fewest steps?
💡 Key idea A square is not enough to describe where you are — you also need how many wall-breaks you have left. BFS over (row, col, breaks left); the first time you reach the corner is the shortest.
Edge / failure case [[0,1],[1,0]], k=0 → -1
Both neighbours of the start are walls and you may not break any (k=0), so you are stuck: -1.
Why? Roads take time, cities charge a passing fee each time you are in them. Cheapest trip from city 0 to the last city within maxTime?
💡 Key idea Make time part of the state: dp[t][city] = cheapest cost to be in that city at exactly time t. Roads move you from t−w to t.
Edge / failure case maxTime=8, same roads → 10
The direct road takes 9 > 8, so you must take the slower-looking but quicker two-road route and pay the extra fee.
Why? Walk from the start square to the end square stepping on EVERY empty square exactly once. Count how many such walks exist.
💡 Key idea Try all four moves from each square, marking it used and un-marking on the way back (backtracking). Count a path only if it reaches the end with no empty squares left.
Edge / failure case [[0,1],[2,0]] → 0
Start and end are diagonal neighbours; any walk that covers both empty squares would have to end before reaching the exit, so there are 0 paths.
Why? Houses stand in a circle, so the first and last are neighbours. [2,3,2] → you can't take both 2s, best is 3.
💡 Key idea A circle means you can't use both ends. So solve the straight-line version twice — once without the first house, once without the last — and take the better.
Edge / failure case [1,2,3,1] → 4
The first and last houses are neighbours in the circle, so you cannot take both 1s; the best is 1 + 3 = 4.
Why? Cover exactly n consecutive IP addresses with as few 'CIDR blocks' as possible. A block starting at an address can only be as big as that address's lowest set bit allows.
💡 Key idea Treat the IP as a 32-bit number. At each start, take the biggest block that is both aligned (lowest set bit) and not larger than what is left (n). Write it as ip/(32−log2 size).
Edge / failure case ip="0.0.0.0", n=1 → ['0.0.0.0/32']
A single address needs one block of size 1, written /32.
Why? After every move, say if that move just won the game. You don't want to rescan the whole board each time.
💡 Key idea Keep a running score per row, column and both diagonals (+1 for player 1, −1 for player 2). A line is won when its score reaches ±n.
Edge / failure case n=3: (0,0,1) (0,2,2) (0,1,1) (1,1,2) (1,0,1) (2,0,2) → [0, 0, 0, 0, 0, 2]
Player 2 wins along the anti-diagonal (0,2), (1,1), (2,0) on the sixth move; before that nobody has three in a line.
Why? Count how many hits happened in the last 5 minutes (300 seconds). Old hits must stop counting.
💡 Key idea Keep hit times in a queue. When asked, drop everything older than 300 seconds from the front, then the queue length is the answer.
Edge / failure case hit(1), getHits(400) → [None, 0]
The only hit is 399 seconds old, which is outside the 300-second window, so it no longer counts.
Why? A long list is stored compressed as pairs: [3,8] means three 8s. next(n) skips n items and returns the last one skipped, or −1 if there aren't enough.
💡 Key idea Never expand the list. Keep a pointer to the current pair and spend the requested n against that pair's remaining count, moving on when a pair is used up.
Edge / failure case RLEIterator([2,4]); next(1), next(3), next(1) → [4, -1, -1]
Only two 4s exist. Asking for 3 more runs past the end, so it returns -1, and everything is used up.
Why? A key can hold different values at different times. get(key, t) returns the value stored at the latest time that is ≤ t.
💡 Key idea Per key, timestamps arrive in increasing order, so store them in a sorted list and binary-search for the last one ≤ t.
Edge / failure case set(a,x,5), get(a,2) → [None, '']
The only value was stored at time 5, and we ask about time 2, before it existed, so the answer is an empty string.
Why? An array you can 'snapshot' and later read as it was at that snapshot. Copying the whole array every time would be wasteful.
💡 Key idea Store only changes: for each index keep a list of (snapshot id, value). A read at snapshot s binary-searches for the last change made at or before s.
Edge / failure case snap(), get(2,0) → [0, 0]
Index 2 was never set, so it still has its default value 0 in the snapshot.
Why? Keep adding ranges like [2,3] and [7,10]; at any time say how many different integers are covered in total.
💡 Key idea Store covered ranges as sorted, non-overlapping intervals. A new range swallows every interval it overlaps; update the running total by removing their sizes and adding the merged size.
Edge / failure case add(1,10), add(3,4), count() → [None, None, 10]
The second range lies entirely inside the first, so nothing new is covered: count stays 10.
Why? What is the smallest positive whole number NOT in the list? [3,4,-1,1] → 1 and 3,4 are there, 2 is not → 2.
💡 Key idea The answer is between 1 and n+1. Swap every number x (1 ≤ x ≤ n) into position x−1 using the list itself as a table; the first slot holding the wrong number reveals the missing one.
Edge / failure case [7, 8, 9, 11, 12] → 1
No number from 1 to 5 is present at all, so the answer is simply 1.
Why? Which software version is newer? '1.2' vs '1.10' → 10 is bigger than 2, so 1.10 is newer. Missing parts count as 0 ('1.0' = '1.0.0').
💡 Key idea Split both on '.', turn each part into a number (so '01' = 1), and compare part by part, treating a missing part as 0.
Edge / failure case "1.0", "1.0.0" → 0
A missing part counts as 0, so '1.0' and '1.0.0' are the same version.
Why? Write a number in words: 1234567 → 'One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven'.
💡 Key idea Split the number into chunks of three digits (billions, millions, thousands, rest). Spell each chunk with a small recursive helper (hundreds, tens, ones) and add the unit name after it.
Edge / failure case 1000010 → 'One Million Ten'
The thousands group is zero and must be skipped, not spelled out: 'One Million Ten'.
Why? Find the third largest DIFFERENT value; if there are fewer than three different values, return the largest. [2,2,3,1] → 1.
💡 Key idea Keep three slots (1st, 2nd, 3rd largest). For each number skip repeats and slide it into the right slot, pushing smaller ones down.
Edge / failure case [1, 2] → 2
There are only two different values, so there is no third maximum; the answer falls back to the largest value, 2.
Why? A 'special' string has equally many 1s and 0s and every start of it has at least as many 1s as 0s. You may swap two neighbouring special pieces. Make the string as large as possible.
💡 Key idea Split the string into its top-level special pieces (the balance returns to zero). Make each piece's inside as large as possible (recursion), then sort the pieces from largest to smallest and join.
Edge / failure case "101100" → '110010'
The pieces '10' and '1100' can be swapped; putting the larger '1100' first gives '110010'.
Why? Write letters with given pixel widths on lines that are 100 pixels wide, never splitting a letter. How many lines, and how wide is the last one?
💡 Key idea Add letters to the current line; if the next letter would overflow 100, start a new line with it.
Edge / failure case every letter 10 wide, ten a's → [1, 100]
Ten letters of width 10 fill the line exactly (100 is allowed), so one line of width 100.
Why? Make the list as large as possible but still SMALLER than it is now, using exactly one swap. [1,9,4,6,7] → [1,7,4,6,9].
💡 Key idea Scan from the right for the first position i that is bigger than its right neighbour — that is where the list can get smaller. Swap it with the largest smaller value to its right (the leftmost one if equal).
Edge / failure case [1, 1, 5] → [1, 1, 5]
The list is already the smallest arrangement (never decreasing from the left), so no swap can make it smaller: it is returned unchanged.
Why? Find every set of four numbers that add up to the target, without listing the same set twice.
💡 Key idea Sort first. Fix the first two numbers with two loops (skipping repeats), then close in on the last two with a left and a right pointer.
Edge / failure case nums=[2,2,2,2,2], target=8 → [[2, 2, 2, 2]]
Five equal numbers: only ONE distinct set of four 2s exists, so duplicates must not be listed five times.
Why? A list of n+1 numbers uses only the values 1..n, so one value repeats. Find it without changing the list or using extra memory. [1,3,4,2,2] → 2.
💡 Key idea Treat each value as a pointer to the next position: the repeat creates a loop. A slow and a fast pointer meet inside the loop; restarting one from the start and moving both one step at a time makes them meet at the loop entrance — the duplicate.
Edge / failure case [3, 1, 3, 4, 2] → 3
The repeated value 3 appears at the very start and in the middle; the loop-finding steps still land on it.
Why? Reverse a list of characters in place: h,e,l,l,o → o,l,l,e,h.
💡 Key idea Keep one pointer at each end, swap, and walk inward until they meet.
Edge / failure case ["a"] → 'a'
A single character is its own reverse; the two pointers never even swap.
Why? For every window of k numbers, report the largest. [1,3,-1,-3,5,3,6,7], k=3 → 3,3,5,5,6,7.
💡 Key idea Keep a deque of indexes whose values are in decreasing order. The front is always the window's maximum; drop smaller values from the back when a bigger one arrives and drop the front when it leaves the window.
Edge / failure case [4, 2, 12], k=1 → [4, 2, 12]
With windows of size 1 every number is its own maximum.
Why? Longest stretch of the text that uses at most k different letters. 'eceba', k=2 → 'ece' → 3.
💡 Key idea Grow the window to the right adding letters to a count map; when it has more than k different letters, shrink from the left until it is back to k.
Edge / failure case s="a", k=0 → 0
With k = 0 no letter is allowed, so the longest piece has length 0.
Why? You stand at a spot and can see a slice of angle degrees. Turn to see as many points as possible. Points exactly where you stand are always visible.
💡 Key idea Turn each point into an angle (atan2), sort them, and duplicate the list shifted by 360° so the circle wraps. Then slide a window whose width is at most `angle`.
Edge / failure case points (-1,1) and (-1,-1), angle 90, location (0,0) → 2
One point is at 135° and the other at 225° (-135°): they are 90° apart ACROSS the 180° line, so a window that wraps around the circle sees both.
Why? Does any value appear at least twice? [1,2,3,1] → yes.
💡 Key idea Remember what you have seen in a set; the first number already in the set is a duplicate.
Edge / failure case [1, 2, 3, 4] → False
Every number is different, so there is no duplicate.
Why? Which k numbers appear most often? [1,1,1,2,2,3], k=2 → 1 and 2.
💡 Key idea Count each number, then drop numbers into buckets indexed by how often they occur. Read buckets from the highest count down until you have k numbers — no sorting needed.
Edge / failure case [1], k=1 → [1]
Only one number exists, so it is trivially the most frequent.
Why? Find the first letter that appears only once and return its position. 'leetcode' → 'l' at 0.
💡 Key idea Count every letter once, then scan left to right and return the first position whose letter has count 1.
Edge / failure case "aabb" → -1
Every letter repeats, so no unique letter exists: -1.
Why? Replace each word of a sentence by its shortest 'root' from a dictionary, if any root is its beginning. 'cattle' with root 'cat' → 'cat'.
💡 Key idea For each word try its prefixes from shortest to longest and stop at the first one found in the root set.
Edge / failure case roots [a], "hello world" → 'hello world'
No word starts with 'a', so the sentence is unchanged.
Why? Return the k most frequent words, most frequent first; words with the same count go in alphabetical order.
💡 Key idea Count the words, then sort by two keys: highest count first, then alphabetical. Take the first k.
Edge / failure case [a, b, c, c], k=2 → ['c', 'a']
'c' appears twice; 'a' and 'b' tie at once, and ties are broken alphabetically, so 'a' comes second.
Why? Two folders (with their whole contents) that look identical must all be deleted. Return the folders that remain.
💡 Key idea Build the folder tree. Give every non-empty folder a text 'signature' of its whole subtree. If a signature occurs more than once, every folder with it is duplicated and removed (along with everything inside).
Edge / failure case [[a],[a,x],[b]] → [['a'], ['a', 'x'], ['b']]
No two folders have the same contents ('b' is empty, and empty folders are never counted as duplicates), so nothing is deleted.
Why? Find two numbers whose digits add up to the same total, with the largest possible sum of the two numbers. [18,43,36,13,7] → 36 + 18 = 54 (digit sum 9).
💡 Key idea For each digit-sum remember the largest number seen. A new number with the same digit sum forms a candidate pair with that largest one.
Edge / failure case [10, 12, 19, 14] → -1
The digit sums are 1, 3, 10 and 5: all different, so no pair qualifies and the answer is -1.
Why? Do tasks in order, one per day. After a task of some type, the next task of that SAME type must wait at least `space` days. Skipping (idling) is allowed. How many days in total?
💡 Key idea Keep the last day each task type ran. If the new task of that type is too soon, jump the day counter to last + space + 1.
Edge / failure case tasks [5,5,5], space=2 → 7
The same task must wait 2 full days between runs: days 1, 4 and 7.
Why? Count the runs of consecutive numbers that add up to k. [1,2,3], k=3 → [1,2] and [3] → 2.
💡 Key idea A run from i to j sums to k exactly when (prefix sum up to j) − (prefix sum before i) = k. Keep a map of how many times each prefix sum has occurred and look up prefix − k.
Edge / failure case [1, -1, 0], k=0 → 3
With negatives and zeros several runs can sum to 0: [1,-1], [0] and [1,-1,0] → 3.
Why? Count the runs of a 0/1 list whose total equals goal. [1,0,1,0,1], goal=2 → 4.
💡 Key idea Same trick as 'subarray sum equals k': count how often each running total has occurred and add the count of (running total − goal).
Edge / failure case [0, 0, 0, 0, 0], goal=0 → 15
Every run of zeros sums to 0, so all 5·6/2 = 15 runs count.
Why? Cut the list into a non-empty left part and non-empty right part so that the left sum is at least the right sum. How many cuts work?
💡 Key idea Know the total once. Walking left to right, the right sum is total − left sum, so each cut is checked in O(1).
Edge / failure case [1, 2] → 0
The only cut gives left = 1 and right = 2; 1 is not ≥ 2, so there are 0 valid splits.
Why? A list contains only 0s, 1s and 2s. Sort it in place in a single pass: [2,0,2,1,1,0] → [0,0,1,1,2,2].
💡 Key idea Keep three zones: 0s on the left (lo), 2s on the right (hi), and an unknown middle. Look at the middle element: send 0s left, 2s right, leave 1s.
Edge / failure case [1, 1, 1] → [1, 1, 1]
Every value is already 1, so nothing needs to move.
Why? Arrange the numbers so that, glued together, they make the biggest possible number. [3,30,34,5,9] → 9534330.
💡 Key idea Number a goes before b if the text a+b is bigger than b+a ('3'+'30' = 330 beats '30'+'3' = 303). Sort with that rule and join.
Edge / failure case [0, 0] → '0'
All zeros would glue into '00'; the answer must be written as a single '0'.
Why? Pick three numbers with the biggest product. Two big negatives multiply to a positive, so [-10,-10,5,2] → 500.
💡 Key idea After sorting, the best triple is either the three largest numbers, or the two smallest (possibly very negative) times the largest.
Edge / failure case [-4, -3, -2, -1] → -6
With all negatives the best product comes from the three numbers closest to zero: −3 × −2 × −1 = −6.
Why? Find every pair of numbers whose difference is the smallest possible. [4,2,1,3] → (1,2), (2,3), (3,4).
💡 Key idea The closest numbers are neighbours once the list is sorted, so only adjacent pairs need to be checked.
Edge / failure case [1, 3, 6, 10, 15] → [[1, 3]]
Only the pair (1,3) has the smallest gap of 2.
Why? For each number find the next bigger one, looking right and wrapping around to the start (the list is circular). [1,2,1] → 2, −1, 2.
💡 Key idea Walk the list twice (indexes 0..2n−1). Keep a stack of positions still waiting for a bigger number; a new number answers every smaller waiting position.
Edge / failure case [5, 4, 3, 2, 1] → [-1, 5, 5, 5, 5]
5 is the biggest, so nothing is greater even after wrapping (−1); every other number sees 5 after wrapping around.
Why? People stand in a line looking right. A person sees someone if everyone between them is shorter than both. How many people does each person see?
💡 Key idea Go right to left with a stack of heights. Everyone shorter that you pop is someone you see; the first taller-or-equal person left on the stack is one more you see.
Edge / failure case [1, 2, 3] → [1, 1, 0]
Each person can only see the next person, who blocks the rest, and the last person sees nobody.
Why? Does the list read the same forwards and backwards? 1→2→2→1 → yes.
💡 Key idea Find the middle with a slow and a fast pointer, reverse the second half in place, then walk both halves together comparing values.
Edge / failure case 1 → 2 → False
1 and 2 are different, so reading backwards gives 2→1, not the same list.
Why? Pick a random node's value from a linked list of unknown length, each equally likely, without storing the list.
💡 Key idea Walk the list once. At the i-th node, replace the current pick with this node's value with probability 1/i. Every node ends up chosen with probability 1/n.
Edge / failure case single node 7, ask 3 times → [7, 7, 7]
With a single node every pick must be that node's value.
Why? Return the middle node of a linked list (the second of the two middles if the length is even).
💡 Key idea Move one pointer one step and another two steps at a time; when the fast one reaches the end, the slow one is in the middle.
Edge / failure case 1 → 2 → 3 → 4 → 5 → 6 → [4, 5, 6]
Six nodes have two middles (3 and 4); the answer is the second one, 4.
Why? Cut nodes a through b out of list1 and put all of list2 in their place.
💡 Key idea Walk to the node just before position a and the node just after b, point the first at list2's head, and point list2's tail at the second.
Edge / failure case list1 = 0→1→2, a=1, b=1, list2 = 9 → [0, 9, 2]
Only the single node at position 1 is replaced by the inserted list: 0 → 9 → 2.
Why? Turn a tree into a string you can save, then rebuild exactly the same tree from that string.
💡 Key idea Write nodes in preorder (node, left, right) and write '#' for every missing child. Reading the same order back, each value or '#' tells you exactly where to attach the next node.
Edge / failure case tree [1,null,2,null,3] → [1, None, 2, None, 3]
A tree that only goes down the right side: missing left children are stored as '#' so the shape comes back exactly.
Why? Turn a tree where a node can have ANY number of children into a string and back into the same tree.
💡 Key idea Write each node as its value followed by how many children it has, then its children in order. When reading, the count tells you exactly how many subtrees to read next.
Edge / failure case a tree with only the root 7 → [7, []]
A single node with no children: its child count is 0, so it reads back as just that node.
Why? The diameter is the longest path (counted in edges) between any two nodes; it may not pass through the root.
💡 Key idea At every node, the longest path THROUGH it is (height of left) + (height of right). One post-order pass computes heights and keeps the best sum seen.
Edge / failure case [1] → 0
A single node has no edges, so the longest path has length 0.
Why? List every node exactly k steps away from the target node, going up or down the tree.
💡 Key idea Trees only point down, so first record each node's parent. Then BFS outward from the target (children and parent), stopping at distance k.
Edge / failure case same tree, target 5, k=0 → [5]
Distance 0 is the target itself.
Why? A full binary tree has nodes with 0 or 2 children. List every different full tree with exactly n nodes (n must be odd).
💡 Key idea Pick how many nodes go to the left subtree (odd numbers) — the rest go right. Combine every left tree with every right tree. Cache results per size.
Edge / failure case n = 2 → 0
Every node must have 0 or 2 children, which forces an odd node count; n = 2 is impossible.
Why? At a party a celebrity is known by everybody but knows nobody. You can only ask 'does A know B?'. Find the celebrity with as few questions as you can.
💡 Key idea Each question removes one person: if the candidate knows i, the candidate cannot be the celebrity (i is the new candidate); otherwise i cannot be. After one pass check the single survivor against everyone.
Edge / failure case 3 people in a ring of 'knows' → -1
Everyone knows someone, so nobody is known-by-all and knows-nobody: there is no celebrity (-1).
Why? A ball rolls in a direction until it hits a wall. Can it STOP exactly on the destination?
💡 Key idea The ball's decisions only happen where it stops. Treat each stopping square as a graph node; from it, roll in 4 directions to find the next stopping squares, and search (BFS) for the destination.
Edge / failure case same maze, destination (3,2) → False
The ball can roll THROUGH (3,2) but cannot stop there (it keeps rolling until a wall), so the destination is never a stopping point: False.
Why? A signal starts at node k and travels along one-way links, each with a travel time. How long until EVERY node has it (or −1 if some never do)?
💡 Key idea Dijkstra: always settle the unvisited node with the smallest arrival time using a min-heap. The answer is the largest arrival time, if all n nodes were reached.
Edge / failure case times [[2,1,1]], n=2, k=1 → -1
Node 1 has no outgoing link, so the signal never reaches node 2: -1.
Why? A 2×3 puzzle with tiles 1–5 and one empty square. Slide tiles into the gap to reach [[1,2,3],[4,5,0]]. Fewest moves?
💡 Key idea Every arrangement of the board is a state; one slide gets you to a neighbouring state. BFS from the start state finds the fewest moves; if the goal is never reached, it is unsolvable (−1).
Edge / failure case [[1,2,3],[5,4,0]] → -1
Swapping only the 4 and 5 can never be reached by sliding tiles, so the puzzle is unsolvable: -1.
Why? Every node points to at most one other node. What is the length of the longest cycle (−1 if none)?
💡 Key idea Follow pointers from each unvisited node, stamping each node with a step number. If you reach a node stamped during THIS walk, the difference of stamps is the cycle length.
Edge / failure case [2, -1, 3, 1] → -1
The pointers lead to the dead end (-1) and never loop, so there is no cycle: -1.
Why? Repeatedly smash the two heaviest stones: equal stones vanish, otherwise the lighter one vanishes and the heavier loses that much weight. What remains?
💡 Key idea You always need the two largest stones, which is exactly what a max-heap gives (Python's heapq is a min-heap, so store negatives).
Edge / failure case [1, 1] → 0
Two equal stones destroy each other, leaving nothing: 0.
Why? k times: pick a pile and remove half of it (rounded down). Make the total as small as possible.
💡 Key idea Removing half of the BIGGEST pile always saves the most, so keep the piles in a max-heap and halve the top k times.
Edge / failure case piles [1], k=5 → 1
Halving a pile of 1 removes 0 stones (rounded down), so no operation changes anything.
Why? Put 3 dots into a string of digits to make a valid IP address (4 numbers 0–255, no leading zeros). '25525511135' → 255.255.11.135 or 255.255.111.35.
💡 Key idea Choose the first segment (1, 2 or 3 digits), then the next, and so on; stop a branch when a segment is above 255 or has a leading zero. A path is valid if it uses exactly 4 segments and all the digits.
Edge / failure case "0000" → ['0.0.0.0']
Leading zeros are not allowed in a segment, so each 0 must be its own segment: only 0.0.0.0 works.
Why? F(0)=0, F(1)=1 and every next number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8 … F(6) = 8.
💡 Key idea You only ever need the last two values, so keep two variables and step forward n times.
Edge / failure case n = 0 → 0
The sequence starts F(0) = 0, so asking for 0 returns 0 without any adding.
Why? Change exactly one letter so the word is no longer a palindrome, and make the result alphabetically smallest. 'abccba' → 'aaccba'.
💡 Key idea To be smallest, change the earliest possible letter to 'a'. Look only at the first half (the middle letter doesn't matter); if it is all 'a's, change the last letter to 'b'.
Edge / failure case "a" → ''
A single letter is always a palindrome and any change keeps it one, so it is impossible: empty string.
Why? Each event runs over a range of days but you can only attend one event per day (on any one day of its range). Attend as many events as possible.
💡 Key idea Go day by day. Among the events already started and not yet expired, attend the one that ends earliest (a min-heap of end days); drop events whose last day has passed.
Edge / failure case [[1,1],[1,1],[1,1]] → 1
All three events can only be attended on day 1, and only one event per day is allowed.
Why? Rearrange the list into a new list perm. 'Greatness' is the number of positions where perm[i] > nums[i]. Make it as big as possible.
💡 Key idea Sort. Walk through the values in order and give each position the next strictly larger value, using a second pointer that only moves when it finds one.
Edge / failure case [1, 1, 1] → 0
Equal values can never be strictly greater than each other: greatness 0.
Why? How many prime numbers are smaller than n? n=10 → 2, 3, 5, 7 → 4.
💡 Key idea Cross out the multiples of every prime, starting from its square. Whatever is never crossed out is prime.
Edge / failure case n = 2 → 0
Primes must be LESS than n; there is no prime below 2.
Why? Two rectangles may overlap. What total area do they cover together? Count the shared part only once.
💡 Key idea Total = area A + area B − overlap. The overlap is a rectangle too: its width is min of right edges − max of left edges (same for height); if either is not positive, there is no overlap.
Edge / failure case A=(0,0)–(1,1), B=(5,5)–(7,7) → 5
The rectangles do not touch, so the overlap is 0 and the areas simply add: 1 + 4.
Why? Is the number 1, 2, 4, 8, 16 …? 16 → yes, 6 → no.
💡 Key idea A power of two has exactly one 1-bit in binary (10000). Subtracting 1 flips that bit and everything below it, so n & (n−1) is 0 only for powers of two.
Edge / failure case n = -16 → False
Negative numbers (and 0) are never powers of two.
Why? The list holds 0..n with one number missing. [3,0,1] → 2 is missing.
💡 Key idea XOR cancels equal pairs. XOR every index 0..n with every value; everything cancels except the missing number.
Edge / failure case [0, 1] → 2
Numbers 0 and 1 are present, so the missing one is n = 2, the top of the range.
Why? For 1..n write 'Fizz' if the number divides by 3, 'Buzz' if by 5, 'FizzBuzz' if by both, otherwise the number itself.
💡 Key idea Test the 'both' case (divisible by 15) first, otherwise the Fizz and Buzz checks would swallow it.
Edge / failure case n = 1 → ['1']
For n = 1 no number is divisible by 3 or 5, so the only entry is the plain number '1'.
Why? You are given pref where pref[i] = arr[0] ^ arr[1] ^ … ^ arr[i]. Recover arr.
💡 Key idea XOR undoes itself: pref[i] ^ pref[i−1] cancels everything except arr[i].
Edge / failure case [13] → [13]
A single prefix is just the first element itself.
Why? A subsequence is 'good' if every letter in it appears the same number of times. Count the good subsequences (answer mod 1,000,000,007).
💡 Key idea Fix a frequency f. For each letter you either skip it or choose f of its c copies (C(c, f) ways): multiply (1 + C(c, f)) over all letters, subtract the empty choice, and add up over every f.
Edge / failure case "aaa" → 7
With one distinct letter, every non-empty selection of positions is good: 2³ − 1 = 7.
Why? In one operation you add or subtract a power of 2. Fewest operations to reach 0? 39 → 3.
💡 Key idea Look at the lowest bits. A single 1 is removed with one subtraction; a run of 1s (…11) is cheaper to fix by adding 1 to carry it away. Shift right as you go.
Edge / failure case n = 1 → 1
1 is itself a power of two: a single subtraction reaches 0.
Why? You can only read a file 4 characters at a time (read4). Build read(buf, n) that can be called again and again, never losing characters it read but didn't hand out.
💡 Key idea read4 may fetch more than you need. Keep the extra characters in a small queue and serve the next read() from the queue first.
Edge / failure case empty file, read(5) → [0, '']
The file is empty: read4 returns 0 at once, so read returns 0 characters.
Why? A queue of fixed size that reuses freed space at the front by wrapping around the end of its array.
💡 Key idea Store items in an array. The front is at index head; the next free slot is (head + size) % capacity. Use modulo to wrap.
Edge / failure case capacity 1: Front, deQueue, isEmpty → [-1, False, True]
Nothing was added: Front reports -1, deQueue has nothing to remove (False) and the queue is empty (True).
Why? Four threads each print a different kind of line (Fizz, Buzz, FizzBuzz, or the number). Together they must print 1..n in the right order.
💡 Key idea Share a counter i. Each thread waits until i is a number it is responsible for, prints, increases i and wakes the others. A condition variable (wait / notify_all) coordinates the turns.
Edge / failure case n = 3 → [1, 2, 'fizz']
With n = 3 only the first three numbers are produced: 1, 2, fizz. All four threads still stop cleanly.
Why? Two long lists are mostly zeros. Their dot product (multiply matching positions, then add) only needs the positions where both are non-zero.
💡 Key idea Keep each vector as {position: value} for non-zero entries only. For the dot product loop over the smaller dictionary and look each position up in the other.
Edge / failure case [0, 0] · [0, 0] → 0
Both vectors have no non-zero entries, so there is nothing to multiply: 0.
Why? A strip of n memory cells. allocate(size, id) reserves the LEFTMOST run of `size` free cells for that id; freeMemory(id) releases all cells held by that id.
💡 Key idea Keep the cells in an array (0 = free, otherwise the owner's id). Allocate by scanning for the first run of free cells long enough; free by clearing every cell with that id.
Edge / failure case Allocator(2): allocate(3,1), freeMemory(1) → [-1, 0]
3 cells will not fit in a memory of size 2, so allocate returns -1 and freeing finds nothing (0).
Why? Rearrange the list into the next bigger arrangement (like the next word in a dictionary); if it is already the biggest, make it the smallest. [1,2,3] → [1,3,2].
💡 Key idea From the right, find the first number smaller than its right neighbour (the dip). Swap it with the next-larger number to its right, then reverse everything after the dip so the tail is as small as possible.
Edge / failure case [3, 2, 1] → [1, 2, 3]
[3,2,1] is already the largest arrangement, so the next one wraps around to the smallest: [1,2,3].
Why? You may change at most k letters. How long a stretch of identical letters can you make? 'AABABBA', k=1 → 4.
💡 Key idea A window is fixable if (window length − count of its most common letter) ≤ k. Slide a window, keep the largest letter count seen, and shrink by one when the window needs too many changes.
Edge / failure case s="ABCD", k=0 → 1
No changes are allowed and all letters differ, so the longest run of one letter is 1.
Why? Pick fruit from consecutive trees but only two kinds fit in your baskets. What is the longest run you can pick?
💡 Key idea This is 'longest stretch with at most 2 different values'. Grow the window, count kinds, and shrink from the left when a third kind appears.
Edge / failure case [1, 1] → 2
Only one kind of fruit exists, so every tree can be picked.
Why? Count the runs of the list that contain exactly k different numbers.
💡 Key idea 'Exactly k' is hard for a sliding window, but 'at most k' is easy. Exactly k = (runs with at most k different) − (runs with at most k−1 different).
Edge / failure case [1, 2, 1, 3, 4], k=3 → 3
Exactly three runs contain 3 different numbers: [1,2,1,3], [2,1,3] and [1,3,4].
Why? An infection starts at one node and spreads to each neighbour (children and parent) every minute. How many minutes until the whole tree is infected?
💡 Key idea Turn the tree into an undirected graph by adding parent links, then BFS from the start node; the number of BFS levels (minus one) is the time.
Edge / failure case tree [1], start 1 → 0
Only one node, already infected at minute 0.
Why? Water flows from a cell to neighbours that are the same height or lower. Which cells can send water to BOTH the Pacific (top/left edges) and the Atlantic (bottom/right edges)?
💡 Key idea Reverse the question: start at each ocean's edge cells and flood uphill (to neighbours that are the same height or higher). The cells reached from both oceans are the answer.
Edge / failure case [[1]] → [[0, 0]]
A single cell touches both oceans.
Why? Count islands, but two islands with the same shape (just moved) count as one.
💡 Key idea DFS each island from its first cell and record every cell as an offset from that start. Identical shapes give identical offset lists; store them in a set.
Edge / failure case two identical 2×2 islands → 1
Two islands exist but both are the same 2×2 square, so only 1 distinct shape.
Why? Which cables, if cut, would split the network into two parts (the 'bridges')?
💡 Key idea DFS and number nodes in visit order (disc). low[u] is the earliest visited node reachable from u's subtree without using the edge to its parent. An edge u–v is a bridge when low[v] > disc[u] — v's side cannot get back around.
Edge / failure case a triangle of 3 servers → []
The three cables form a triangle: cutting any one still leaves the others connected, so there are no critical connections.
Why? Connect one node of tree 1 to one node of tree 2 with a new edge. Choose the nodes to make the longest path in the merged tree as short as possible.
💡 Key idea Join the middle (centre) of each tree. The result's diameter is max(d1, d2, ⌈d1/2⌉ + ⌈d2/2⌉ + 1), where d1 and d2 are the two diameters (found with two BFS passes each).
Edge / failure case edges1 = [], edges2 = [] → 1
Two single-node trees joined by one edge give a path of length 1.
Why? Every number appears twice (neighbours) except one. Find it in O(log n).
💡 Key idea Before the lonely number, pairs start at even positions; after it, pairs start at odd positions. Binary search on whether the pair at an even position is still 'in sync'.
Edge / failure case [7] → 7
A single-element list: that element is the answer.
Why? List every way to cut a string into dictionary words. 'catsanddog' → 'cats and dog' and 'cat sand dog'.
💡 Key idea From a start position try every word that fits, then solve the rest. Remember the answers per start position so the same suffix is never solved twice.
Edge / failure case s="catsandog" → []
No way of cutting 'catsandog' uses only dictionary words ('og' is left over), so the answer is an empty list.
Why? Put a + or − in front of every number so the total equals the target. How many sign choices work? [1,1,1,1,1] and target 3 → 5.
💡 Key idea Process numbers one by one, keeping a map: 'running total → number of ways to reach it'. Each number splits every total into total+x and total−x.
Edge / failure case [1], target=2 → 0
With only the number 1 you can reach +1 or −1, never 2.
Why? Build a playlist of `goal` songs using all n songs at least once, where a song can only repeat after k other songs have played. Count the playlists.
💡 Key idea dp[i][j] = playlists of length i using exactly j different songs. The last song is either new ((n−j+1) choices) or a repeat of one of the j songs whose gap is satisfied ((j−k) choices).
Edge / failure case n=2, goal=3, k=1 → 2
With 2 songs and a gap of 1 the playlists must alternate: A B A and B A B → 2.
Why? Buy some stocks today at present[i] and sell them next year at future[i]; you have a fixed budget and can buy each stock at most once. Maximise profit.
💡 Key idea Each stock is an item: weight = price now, value = future − present (skip losers). Classic 0/1 knapsack over the budget.
Edge / failure case present [5,4], future [3,2] → 0
Both stocks would lose money next year, so buy nothing: profit 0.
Why? Roll a die n times. Neighbouring rolls must be co-prime (gcd 1) and the same value must not repeat within a gap of 2. How many sequences are possible?
💡 Key idea The rules only look at the last two rolls, so the state is (second-last, last). Extend each state by every legal next roll and add up the counts.
Edge / failure case n = 1 → 6
One roll has no neighbours to compare, so all 6 faces are allowed.
Why? A string of [ and ] with the same number of each. Swap any two characters, as few times as possible, to make the brackets balanced.
💡 Key idea Scan and match every ']' to an earlier '['. The leftover unmatched ']' are the problem; each swap fixes two of them, so the answer is ⌈unmatched / 2⌉.
Edge / failure case "[]" → 0
The brackets are already balanced: 0 swaps.
Why? Some brackets are locked and some can be changed to '(' or ')'. Can you make the whole string a valid bracket string?
💡 Key idea Odd length is impossible. Scan left→right treating every unlocked bracket as '(' — the balance must never drop below 0. Then scan right→left treating them as ')' with the same check.
Edge / failure case s=")(", locked="11" → False
Both brackets are locked and in the wrong order, so it can never be valid.
Why? You may change letters (the alphabet wraps: z is next to a) with a total 'distance' budget k. Make the string alphabetically smallest.
💡 Key idea Go left to right. If the letter can be turned into 'a' within the remaining budget, do it and pay the (wrap-around) distance. Otherwise move it down as far as the budget allows and stop spending.
Edge / failure case s="xaxcd", k=4 → 'aawcd'
Spend 3 turning x into a (wrapping x→y→z→a), then the next x can only use the last 1 step: x → w.
Why? With special bit-flip rules, how many flips turn n into 0? n=3 (11) → 2, n=6 (110) → 4.
💡 Key idea The allowed flips walk through a Gray-code sequence, so the answer is the position of n in that sequence: the XOR of n with all its right-shifts (n ^ n>>1 ^ n>>2 ^ …).
Edge / failure case n = 0 → 0
The number is already 0, so no operations are needed.
Why? Pick one element and make it co-prime with all others. You may change values (each change costs 1) to anything up to maxVal. Score = chosen value − total cost.
💡 Key idea For every candidate final value v count how many numbers are NOT co-prime with it (inclusion–exclusion with the Möbius function over multiples). Those must each be changed (to 1); one extra change may turn some element into v. Take the best v − cost.
Edge / failure case nums [2, 4], maxVal=4 → 3
2 and 4 share a factor; the best is to keep one of them and change the other to 1.
Why? Each row is sorted left→right and each column top→bottom. Find a value fast.
💡 Key idea Start at the top-right corner. If the value is too big, move left; if too small, move down. Each move discards a whole row or column.
Edge / failure case same matrix, target 20 → False
20 is not in the matrix: the staircase walk runs off the edge and returns False.
Why? Build a first-in-first-out queue using only stacks (last-in-first-out piles).
💡 Key idea Push onto an 'in' stack. When you need the front, pour the 'in' stack into an 'out' stack — reversing it — and pop from there. Only pour when 'out' is empty.
Edge / failure case empty, push 5, pop, empty → [True, None, 5, True]
Starting empty: empty() is True; after pushing 5 and popping it, the queue is empty again.
Why? A cache with a fixed size. When full, throw out the Least Frequently Used key; if tied, the one used longest ago.
💡 Key idea Keep each key's use-count, group keys into buckets by count (each bucket remembers order), and track the smallest count. Evict from the front of the smallest bucket; a use moves a key to the next bucket.
Edge / failure case capacity 0: put(1,1), get(1) → [None, -1]
Capacity 0 means nothing can ever be stored, so get returns -1.
Why? Given a list of words, how close (in positions) do two particular different words come to each other?
💡 Key idea Walk the list once, remembering the latest position of each target word. Each time you see one, the distance to the other's latest position is a candidate.
Edge / failure case makes, coding → 1
'makes' at position 4 is right next to 'coding' at position 3: distance 1.
Why? For every position, how far is the nearest copy of letter c? 'loveleetcode', 'e' → 3,2,1,0,1,0,0,1,2,2,1,0.
💡 Key idea Go left→right remembering the last c (distance back), then right→left remembering the next c, keeping the smaller distance at each position.
Edge / failure case s="aaab", c='b' → [3, 2, 1, 0]
Only the last letter is 'b'; the distance grows by 1 for each position to its left.
Why? Pick an empty seat to be as far as possible from the nearest person. [1,0,0,0,1,0,1] → the middle of the big gap → 2.
💡 Key idea The best seat is either at an end (distance = empty seats before the first person / after the last) or in the middle of a gap (gap length ÷ 2). Check all three kinds.
Edge / failure case [0, 1] → 1
The only free seat is next to the person: distance 1.
Why? Remove every folder that sits inside another listed folder. '/a' and '/a/b' → keep only '/a'.
💡 Key idea Sorted alphabetically, a folder's sub-folders come right after it. Keep a folder unless it starts with the last kept folder followed by '/' (so '/a/b/ca' is not inside '/a/b/c').
Edge / failure case [/a/b/c, /a/b/ca, /a/b/d] → ['/a/b/c', '/a/b/ca', '/a/b/d']
'/a/b/ca' merely STARTS with the text '/a/b/c' but is not inside that folder, so all three stay.
Why? Count the pieces of the word made ONLY of vowels that contain all five vowels (a, e, i, o, u).
💡 Key idea From each start position extend to the right while letters are vowels, tracking the set of vowels seen; every time the set reaches 5 vowels count one piece.
Edge / failure case "unicornarihan" → 0
The word never has a stretch containing all five vowels (consonants break every run), so the count is 0.
Why? Income is taxed in slices: the first slice at one percent, the next slice at another, and so on. How much tax in total?
💡 Key idea For each bracket, the taxable part is min(income, upper limit) − previous limit; multiply by the rate and add. Stop once income is used up.
Edge / failure case income 0 → 0
No income means no tax.
Why? The list holds only 0, 1 and 2. Find the smallest distance (difference of positions) between a 1 and a 2.
💡 Key idea Walk once, remembering the latest position of a 1 and of a 2. Each new 1 is compared with the latest 2 and vice versa.
Edge / failure case [1, 0, 1, 0] → -1
There is no 2 in the list, so no valid pair exists: -1.
Why? Digits in an abbreviation mean 'skip this many letters'. 'i12iz4n' stands for 'internationalization'. Is the abbreviation valid for the word? (No leading zeros in a number.)
💡 Key idea Walk two pointers. A letter in the abbreviation must equal the word's letter; a number moves the word pointer ahead by that many. Both must end exactly at the end.
Edge / failure case word "apple", abbr "a2e" → False
'a2e' means a, skip two letters, then e — but the 4th letter of 'apple' is 'l', so it does not match.
Why? Each boat carries at most 2 people and a weight limit. Fewest boats for everyone? [3,2,2,1], limit 3 → 3.
💡 Key idea Sort. The heaviest person must take a boat; if the lightest can share it, pair them, otherwise the heaviest goes alone. Two pointers do it in one pass.
Edge / failure case [3, 5, 3, 4], limit=5 → 4
No two people fit together within the limit of 5, so each needs their own boat: 4.
Why? Reverse only the letters of a string; every other character stays put. 'a-bC-dEf-ghIj' → 'j-Ih-gfE-dCba'.
💡 Key idea Move a left and right pointer inward, skipping non-letters, and swap when both point at letters.
Edge / failure case "7_28]" → '7_28]'
There are no letters, so nothing is reversed.
Why? Who used their key-card 3 or more times within 60 minutes? Return those names alphabetically.
💡 Key idea Group the times (as minutes since midnight) by person and sort them. Three uses fit in an hour exactly when some time and the time two positions later differ by at most 60.
Edge / failure case two people, only one triggers → ['bob']
Alice's uses are 12:00, 12:01 and 18:00 (not all within an hour); Bob's three uses at 21:00, 21:20 and 21:30 are.
Why? Evaluate '3+2*2' = 7 (multiplication first) using only + − × ÷ and whole numbers.
💡 Key idea Read numbers with the operator that came BEFORE them. '+' and '−' push the number (signed) on a stack; '×' and '÷' combine it with the top of the stack right away. Finally add up the stack.
Edge / failure case " 3/2 " → 1
Spaces are skipped and 3/2 is whole-number division: 1.
Why? Delete k digits from a number (written as text) to make the number as small as possible. '1432219', k=3 → '1219'.
💡 Key idea Whenever a digit is smaller than the one before it, the earlier bigger digit should go. A stack that stays in non-decreasing order does exactly that; leftover deletions come off the end.
Edge / failure case "10200", k=1 → '200'
Removing the 1 leaves '0200'; leading zeros are dropped, giving '200'.
Why? In a perfect binary tree, make every node's next pointer point to the node on its right on the same level (the last one points to nothing).
💡 Key idea Once a level is linked, you can walk along it and use it to link the level below: left.next = right, and right.next = the next node's left child. No queue needed.
Edge / failure case tree [1] → [[[1, None]]]
A single node has no neighbours; its next stays empty.
Why? List the nodes on the outline of a binary tree going anti-clockwise: root, the left edge down, all leaves left to right, then the right edge back up.
💡 Key idea Walk the left boundary top-down (skipping leaves), collect all leaves with a DFS, walk the right boundary top-down, and reverse it when appending.
Edge / failure case tree [1] → [1]
A single node is both the root and a leaf, listed once.
Why? Find the longest path in a binary tree where every node has the SAME value (counted in edges).
💡 Key idea At each node, extend the chain from a child only if the child has the same value. The best path through a node = left chain + right chain; return the longer single chain to the parent.
Edge / failure case tree [1] → 0
A single node has no edges, so the path length is 0.
Why? For each node, is its value equal to the (rounded-down) average of all values in its subtree? Count such nodes.
💡 Key idea Post-order: each node gets the sum and the number of nodes of its subtree from its children, then compares sum // count with its own value.
Edge / failure case tree [1] → 1
A single node's average is its own value, so it counts.
Why? For each query, imagine cutting off one subtree and report the height (in edges) of the remaining tree. Queries are independent.
💡 Key idea Precompute every node's depth and height. Removing a node at depth d only matters for that level: the new tree height is d + (the best height among the OTHER nodes at depth d), or d − 1 if it was the only node there. Keep the top two heights per level.
Edge / failure case tree [1,2,null,3], query 3 → [1]
The tree is a chain 1→2→3. Removing the only node at depth 2 leaves a tree of height 1.
Why? Do these edges connect all n nodes into a tree (connected, no loops)?
💡 Key idea A tree on n nodes has exactly n−1 edges. If the count is right, joining nodes with union-find must never join two nodes that are already together (that would be a cycle).
Edge / failure case a graph with a cycle → False
Nodes 1, 2 and 3 form a loop (1-2-3-1), and there are 5 edges for 5 nodes: not a tree.
Why? Find the size of the biggest island of 1s (connected up/down/left/right).
💡 Key idea Whenever you meet a 1, flood it with DFS, turning each visited cell to 0 and counting them. The biggest count is the answer.
Edge / failure case [[0, 0]] → 0
There is no land at all, so the largest island has size 0.
Why? Cheapest trip from src to dst using at most k stops (k+1 flights).
💡 Key idea Relax every flight once per allowed flight, always reading the previous round's prices (copy them first) so a round adds exactly one more flight.
Edge / failure case k = 0 → -1
With 0 stops only a direct flight is allowed, and there is no direct flight from 0 to 3.
Why? You may turn ONE water cell into land. How big can the largest island become?
💡 Key idea First label every island and record its size. For each water cell, add 1 + the sizes of the DIFFERENT islands touching it; the best is the answer.
Edge / failure case [[1,1],[1,1]] → 4
There is no water to turn into land, so the answer is the whole grid: 4.
Why? Split n people into two groups so that nobody is in the same group as someone they dislike.
💡 Key idea Draw dislike lines between people and try to colour everyone with two colours so connected people differ (BFS). If two people who dislike each other end up the same colour, it is impossible.
Edge / failure case n=3, all pairs dislike → False
Everyone dislikes everyone else: three people cannot be split into two groups without a clash.
Why? A grid has exactly two islands. What is the fewest water cells to flip so they become one island?
💡 Key idea DFS to find all cells of the first island and put them in a queue; then BFS outward through water, layer by layer. The layer where you first touch the second island is the answer.
Edge / failure case [[0,1],[1,0]] → 1
The two islands touch diagonally; flipping either corner water cell joins them: 1.
Why? A stone can be removed if another stone shares its row or column. How many stones can be removed in total?
💡 Key idea Stones linked by a shared row or column form groups; in each group all but one stone can be removed. Answer = stones − number of groups. Union-find over 'row ids' and 'column ids' counts groups.
Edge / failure case [[0,0],[1,1]] → 0
The stones share no row or column, so none can be removed.
Why? Courses have prerequisites; you can take any number of available courses per semester. Fewest semesters to finish all (−1 if there is a loop)?
💡 Key idea Repeatedly take every course with no remaining prerequisites (one semester per round) using a queue of zero-indegree courses. If not all courses get taken, there is a cycle.
Edge / failure case n=3, a circular set of prerequisites → -1
Course 1 needs 3, 3 needs 2 and 2 needs 1: a circle of prerequisites, so no course can ever be started: -1.
Why? Start at a web page and follow its links, but only to pages on the SAME website (hostname). Return every page reached.
💡 Key idea A graph search: a queue of pages to visit, a set of pages already seen, and for each page ask HtmlParser.getUrls for its links, keeping only those on the same host.
Edge / failure case start at news.google.com → ['http://news.google.com']
The start page has no links, so only the page itself is returned.
Why? Crawl a website like the single-threaded crawler, but fetch many pages at the same time because each fetch is slow.
💡 Key idea Visit the site level by level. For each level, ask a thread pool to fetch all of its pages' links in parallel, then collect the new same-host links as the next level. Only the main thread touches the 'seen' set.
Edge / failure case start at news.google.com → ['http://news.google.com']
The start page links nowhere, so only the page itself is returned.
Why? Walk from the top-left to the bottom-right of a height map. The 'effort' of a route is its biggest height jump between neighbouring cells. Find the route with the smallest effort.
💡 Key idea Like Dijkstra, but the cost of a route is the MAXIMUM jump so far, not the sum. Always expand the cell reachable with the smallest effort.
Edge / failure case [[1]] → 0
One cell: the start is also the goal, so no jump is needed.
Why? Each course takes some months; you can take any number in parallel but only after their prerequisites finish. Minimum months to finish everything?
💡 Key idea Process courses in topological order. A course finishes at (latest finish among its prerequisites) + its own duration. The answer is the largest finish time.
Edge / failure case n=2, no relations, time [4,7] → 7
No dependencies: both courses run in parallel, so the total time is the longer one, 7.
Why? Alice walks from the root to a leaf, Bob walks from his node up to the root, both one step per second. Each node's gate gives/costs money: if both arrive together they split it. Maximise Alice's money.
💡 Key idea First compute when Bob reaches each node on his way to the root. Then DFS Alice's walk: at a node, she takes all of it if she is earlier than Bob, half if at the same time, nothing if Bob was first. Keep the best leaf total.
Edge / failure case edges [[0,1]], bob=1, amount [5,-6] → 5
Alice takes the 5 at node 0 first (Bob is still at node 1 and has already taken the −6 gate there when she arrives), so she ends with 5.
Why? Given meeting times, how many rooms are needed so no two overlapping meetings share a room?
💡 Key idea Sort by start time. Keep a min-heap of the end times of rooms in use. If the earliest room is free by the next start, reuse it (pop); otherwise a new room is needed. The heap size is the answer.
Edge / failure case [[7,10],[2,4]] → 1
The two meetings do not overlap, so one room is enough.
Why? IDs are added or removed in bulk step by step. After each step, how many times does the MOST common ID appear?
💡 Key idea Keep counts per ID and push (−count, id) onto a max-heap after every change. Before reading the top, discard entries whose count is out of date.
Edge / failure case nums [5,5], freq [2,-2] → [2, 0]
After the second step ID 5 has been removed completely, so nothing is left: 0.
Why? Does the pattern match the WHOLE text? '.' matches any one letter; 'x*' matches zero or more x. 'aa' matches 'a*'.
💡 Key idea dp[i][j] = does the first i letters of the text match the first j pattern characters. A '*' can either vanish (zero copies: look two columns back) or eat one more matching letter (look one row up).
Edge / failure case s="ab", p=".*c" → False
'.*' can swallow 'ab' but the pattern still needs a final 'c' that the text does not have, so there is no match.
Why? Paint n fence posts with k colours so that no THREE posts in a row have the same colour. How many ways?
💡 Key idea Track two counts for the last post: it has the same colour as the post before (only allowed if the two before differed), or a different colour (k−1 choices from any earlier state).
Edge / failure case n=1, k=5 → 5
With one post any of the 5 colours works.
Why? Pick non-overlapping jobs (a job may start exactly when another ends) to maximise total profit.
💡 Key idea Sort jobs by end time and keep 'best profit so far at each end time'. For a job, binary-search the latest finished job that ends by its start and add its profit; keep it if it beats the current best.
Edge / failure case start [1,1,1], end [2,3,4], profit [5,6,4] → 6
All three jobs overlap (they all start at 1), so only one can be chosen: the best is the job paying 6.
Why? Like Parallel Courses, but you can take at most k courses per semester. Fewest semesters?
💡 Key idea A set of finished courses is a bitmask. From a mask, the courses whose prerequisites are done are 'available'; try every subset of at most k of them as the next semester.
Edge / failure case n=3, no relations, k=2 → 2
No prerequisites but at most 2 courses per semester: 3 courses need 2 semesters.
Why? Build the target letter by letter, taking each letter from a column of the dictionary words; columns must go left to right and once you use column j you can't go back.
💡 Key idea Count, for each column, how many words have each letter. dp[t] = ways to build the first t target letters using columns so far; each column adds dp[t−1] × (count of target[t−1] in that column).
Edge / failure case words [abc], target "abcd" → 0
The target (4 letters) is longer than the words (3 columns), so it cannot be built at all.
Why? Each event has a start, an end and a value. Attend at most k non-overlapping events to maximise the total value.
💡 Key idea Sort by start. For event i you either skip it or take it and jump to the first event starting after it ends (binary search), with one fewer event allowed. Cache by (i, left).
Edge / failure case k = 1 → 4
Only one event may be attended, so pick the most valuable: 4.
Why? A paid painter paints wall i in time[i] and costs cost[i]; a free painter paints one wall per time unit but only while the paid painter is busy. Cheapest way to paint all walls?
💡 Key idea Hiring the paid painter for wall i effectively paints 1 + time[i] walls. So choose walls to pay for such that their (1 + time) sum covers n walls at minimum total cost — a knapsack.
Edge / failure case cost [2,3,4,2], time [1,1,1,1] → 4
Paying for two cheap walls (cost 2 + 2) lets the free painter cover the other two: total 4.
Why? A subsequence is 'good' if at most k neighbouring pairs in it are different. Find the longest good subsequence.
💡 Key idea dp[i][j] = longest good subsequence ending at index i with j 'changes' (neighbouring pairs that differ). Extend from any earlier index p: same value costs no change, a different value costs one.
Edge / failure case nums [1,2,3,4,5,1], k=0 → 2
With no changes allowed all chosen numbers must be equal: the best is the two 1s.
Why? Same as part I, but the list is much longer, so the O(n²) approach is too slow.
💡 Key idea For each value x and number of changes j keep the best length ending with x, and for each j the best over ALL values. A new element either continues a run of the same value (no change) or extends the best subsequence with j−1 changes.
Edge / failure case nums [1,2,3,4,5,1], k=0 → 2
With no changes allowed all chosen numbers must be equal: the best is the two 1s.
Why? Add the fewest numbers to a sorted list so that every value from 1 to n can be made as a sum of some of its numbers.
💡 Key idea Keep 'reach' = every value up to it is already buildable. If the next list number is ≤ reach+1 it extends reach for free; otherwise patch in reach+1, which doubles the range.
Edge / failure case nums [], n=7 → 3
Nothing to start with: patch 1, 2 and 4 to reach every value up to 7.
Why? Run tasks (A–Z), one per time unit; the same task needs n units of cool-down between runs. Fewest time units to finish (idle allowed)?
💡 Key idea The most frequent task decides the frame: (maxCount−1) blocks of length n+1, plus the last row of all tasks tied at maxCount. If tasks exceed that, no idle is needed: the answer is at least len(tasks).
Edge / failure case n = 0 → 6
No cool-down is needed, so every task simply runs in its own time unit: 6.
Why? Assign each worker a different bike: always take the (worker, bike) pair with the smallest walking distance; break ties by smaller worker, then smaller bike.
💡 Key idea List every worker–bike pair as (distance, worker, bike), sort them, and walk through: if both the worker and the bike are still free, make the assignment.
Edge / failure case three workers, three bikes with tied distances → [0, 2, 1]
Several pairs have equal distance; ties go to the smaller worker index, then the smaller bike index.
Why? In a sorted list, repeatedly delete two numbers where the left one is strictly smaller than the right one. How short can the list get?
💡 Key idea If one value takes more than half of the list, it can only be paired with other values, leaving 2·maxCount − n of it behind. Otherwise everything pairs off and 0 or 1 remains (n odd).
Edge / failure case [1000000000, 1000000000] → 2
Both numbers are equal, so neither is smaller than the other: nothing can be removed.
Why? In one operation you move a suffix of s to the front (a rotation). In how many ways can you turn s into t using exactly k operations?
💡 Key idea Each operation rotates by 1..n−1 positions. Track the net rotation: from 'rotation 0' there are n−1 ways to leave; from any other rotation, one way returns to 0 and n−2 ways stay non-zero. A 2×2 matrix raised to the power k counts this fast; multiply by how many rotations of s equal t.
Edge / failure case s=t="ababab", k=1 → 2
The word equals itself after rotating by 2 or by 4 positions, so one operation can give the same word in 2 ways.
Why? At each data centre you may sell some servers to pay for upgrading others. How many servers can you upgrade? (Each server is either sold, upgraded or untouched.)
💡 Key idea If you upgrade x servers, you must be able to pay: x·upgradeCost ≤ money + (count − x)·sellPrice. Solving for x gives x ≤ (money + count·sell) / (upgrade + sell), and x cannot exceed count.
Edge / failure case count [2], upgrade [1], sell [1], money [100] → [2]
There is so much money that every server can be upgraded: capped by the number of servers (2).
Why? Turn a list of strings into ONE string and back, even if the strings contain any characters (including '#' or commas).
💡 Key idea Write each string as its length, a '#', then the string itself. When decoding, read the length up to '#', then take exactly that many characters — no separator inside a string can confuse it.
Edge / failure case [""] → ['']
One empty string is NOT the same as an empty list: the encoding must remember there was one (empty) item.
Why? Build a tiny file system: list a folder, make folders, write to a file (appending) and read it back.
💡 Key idea Represent a folder as a dictionary of names → (folder dictionary or file text). Every operation just walks the path one name at a time.
Edge / failure case write '/f', then ls('/f') → [None, ['f']]
Listing a FILE path returns just that file's name.
Why? Store logs with timestamps like '2017:01:01:23:59:59' and fetch the ids between two times at a chosen precision (Year, Month, Day, Hour, Minute, Second).
💡 Key idea The precision decides how many leading characters of the timestamp matter. Cut start, end and each log's timestamp to that length and compare as text.
Edge / failure case retrieve at Second precision → [None, [1]]
At Second precision the whole timestamp must match exactly, and it does.
Why? A fixed-size queue you can add to and remove from at BOTH ends, wrapping around its array.
💡 Key idea Keep a head index and a size. Inserting at the front moves head back by one (mod capacity); inserting at the back writes at (head + size) mod capacity.
Edge / failure case empty deque: getFront, getRear, deleteFront → [-1, -1, False]
Nothing has been inserted: both ends report -1 and there is nothing to delete.
Why? Build a dictionary (put, get, remove) without using a built-in hash table.
💡 Key idea Spread keys over a fixed number of buckets with key % size. Keys that land in the same bucket sit together in a small list that you scan.
Edge / failure case keys 1 and 8 collide → [None, None, 10, 80, None, 80]
Keys 1 and 8 land in the same bucket (1 % 7 = 8 % 7); both must be found independently, and removing one keeps the other.
Why? Create paths like '/a/b' with a value — only if the parent path already exists and the path is new. get(path) returns the value or −1.
💡 Key idea Store each full path in a dictionary. To create, check the path is new and its parent (everything before the last '/') is already stored.
Edge / failure case create /a twice, get /b → [True, False, -1]
'/a' already exists so creating it again fails, and '/b' was never created so get returns -1.
Why? A browser with visit, back and forward. Visiting a new page erases the 'forward' pages.
💡 Key idea Keep a list of pages and an index for the current page. visit cuts the list after the current page and appends; back/forward just move the index (clamped to the list).
Edge / failure case back(5), forward(5) → ['home.com', 'home.com']
With no history, going back or forward any number of steps stays on the homepage.
Why? People are born into a royal family tree; the succession order is the preorder walk of that tree, skipping anyone who has died.
💡 Key idea Store each person's children in birth order. getInheritanceOrder walks the tree depth-first (person, then each child's whole line) and prints everyone who is still alive.
Edge / failure case king dies, child 'a' remains → [None, None, ['a']]
The king has died, so he is skipped in the order, but his child still inherits.
Why? Add two big numbers given as text, without converting them to integers. '11' + '123' = '134'.
💡 Key idea Do school addition: start at the right ends, add the two digits plus the carry, write the last digit and keep the carry.
Edge / failure case "999" + "1" → '1000'
The carry ripples through all digits and creates a new leading digit: 1000.
Why? Given clock times like '23:59', find the smallest gap in minutes between any two of them (the clock wraps around midnight).
💡 Key idea Convert each time to minutes since midnight and sort. The answer is the smallest gap between neighbours, and also the gap from the last time round midnight to the first.
Edge / failure case [00:00, 23:59, 00:00] → 0
'00:00' appears twice, so two times are identical: difference 0.
Why? Count the pieces of a string that read the same backwards (each position counts separately). 'aaa' has 6.
💡 Key idea Every palindrome has a centre (a letter, or the gap between two). From each of the 2n−1 centres expand outwards while the letters match, counting each step.
Edge / failure case "aaa" → 6
Every single letter (3), every adjacent pair (2) and the whole word (1) is a palindrome: 6.
Why? A robot follows moves U, D, L, R. Does it end up where it started?
💡 Key idea Keep x and y: up/down change y, left/right change x. It is back at the origin exactly when both are 0.
Edge / failure case "LL" → False
Two steps left and none right: the robot ends 2 steps from the origin.
Why? Is the list always going up (or flat), or always going down (or flat)?
💡 Key idea Assume both 'increasing' and 'decreasing' are possible; every step that goes the other way rules one of them out. If either survives, the list is monotonic.
Edge / failure case [1, 3, 2] → False
The list goes up and then down, so it is not monotonic.
Why? An expression 'a+b' (digits). Put one pair of brackets so that the '+' is inside, evaluate the result (anything outside the brackets is multiplied) and make it as small as possible. '247+38' → '2(47+38)' = 170.
💡 Key idea Only two choices: where the '(' goes in the left number and where the ')' goes in the right number. Try every combination, treat missing outside parts as 1, and keep the smallest value.
Edge / failure case "12+34" → '1(2+3)4'
Putting the brackets so that 1 and 4 stay outside makes the result 1 × (2 + 3) × 4 = 20, the smallest option.
Why? Cut a digit string into groups of k, replace each group by the sum of its digits, glue the results together, and repeat until the string has at most k characters.
💡 Key idea Simulate it: a loop that slices every k characters, sums each slice, and rebuilds the string, until the length is ≤ k.
Edge / failure case "00000000", k=3 → '000'
Every group sums to 0, so the string becomes '000' and stops (its length is 3 = k).
Why? A row of n cells starts uncoloured (0). Colour cells one query at a time; after each query report how many neighbouring cells have the same non-zero colour.
💡 Key idea A recolour can only change the pairs touching that cell. Before recolouring subtract any matching neighbour pairs, after recolouring add the new matching pairs — O(1) per query.
Edge / failure case n=2, paint cell 0 with 1 twice → [0, 0]
Painting a cell the colour it already has changes nothing, and its neighbour is still uncoloured: no matching pairs.
Why? Find two numbers at least x positions apart whose values are as close as possible.
💡 Key idea Walk through the list; for position i, all elements at positions ≤ i − x are allowed partners. Keep them in a sorted list and use binary search to find the closest value to nums[i].
Edge / failure case [1, 2, 3, 4], x=3 → 3
With a gap of at least 3 positions only the first and last numbers can be paired: |1 − 4| = 3.
Why? Typing a string: a 'key change' happens when the next key is a different letter (capital and small letters are the same key). Count the changes.
💡 Key idea Lowercase every letter and count neighbouring pairs that differ.
Edge / failure case "AaAaAaaA" → 0
Capital and small letters are the same key, so no key is ever changed.
Why? The pattern is a list of 1 (goes up), 0 (stays equal), −1 (goes down). Count runs of the list whose consecutive steps follow the pattern exactly.
💡 Key idea A window of length m+1 matches if for every k the step from nums[i+k] to nums[i+k+1] has the sign pattern[k]. Check each window.
Edge / failure case nums [1,4,4,1,3,5,5,3], pattern [1,0,-1] → 2
Two windows rise, stay equal, then fall: (1,4,4,1) and (3,5,5,3).
Why? Count pairs of words (i < j) where words[i] is both the start AND the end of words[j].
💡 Key idea With few, short words just test every pair with startswith and endswith.
Edge / failure case ["abab", "ab"] → 0
The earlier word 'abab' is longer than 'ab', so it cannot be a prefix of it: no pairs.
Why? A 0/1 list. Count the runs of neighbouring numbers in which no two neighbours are equal.
💡 Key idea For each position, the number of alternating runs ENDING there equals the length of the alternating stretch ending there. Add those lengths up.
Edge / failure case [1, 0, 1, 0] → 10
The whole list alternates, so every run of neighbouring numbers counts: 4 + 3 + 2 + 1 = 10.
Why? A shop owner is sometimes grumpy and customers leave unsatisfied. He has a secret technique to stay calm for `minutes` in a row, once. How many customers can be satisfied at most?
💡 Key idea Customers in calm minutes are always satisfied. The technique should cover the stretch of `minutes` where the most grumpy-minute customers are — a sliding window sum of the grumpy-minute customers.
Edge / failure case customers [4,5], grumpy [0,0], minutes 1 → 9
The owner is never grumpy, so everyone is satisfied and the technique adds nothing: 9.
Why? Longest stretch of the list in which the biggest and smallest numbers differ by at most `limit`.
💡 Key idea Slide a window. Keep two deques that always know the window's maximum and minimum in O(1). While max − min > limit, shrink from the left.
Edge / failure case [10,1,2,4,7,2], limit 5 → 4
The window [2,4,7,2] has max 7 and min 2, a difference of 5 — still allowed, length 4.
Why? Tiles in a circle are red (0) or blue (1). A 'group' is k tiles in a row whose colours alternate. Count the groups (the circle wraps around).
💡 Key idea Append the first k−1 tiles to the end to handle the wrap-around. Walk along keeping the length of the current alternating run; every position where that run is at least k ends one group.
Edge / failure case colors [0,1,0,0,1,0,1], k=6 → 2
Looking round the circle, only two stretches of 6 tiles alternate.
Why? A pair (i, j) is 'nice' if nums[i] + rev(nums[j]) = nums[j] + rev(nums[i]), where rev reverses the digits. Count nice pairs.
💡 Key idea Rearrange the equation: nums[i] − rev(nums[i]) = nums[j] − rev(nums[j]). Count how many earlier numbers share the same 'x − rev(x)' value using a dictionary.
Edge / failure case [13, 10, 35, 24, 76] → 4
Numbers whose 'x − reverse(x)' match form pairs: 4 such pairs exist.
Why? Count ordered pairs (i, j), i ≠ j, whose strings glued together spell the target.
💡 Key idea Split the target at every position into (prefix, suffix) and count how many list items equal each. Multiply the counts; if prefix = suffix use cnt × (cnt − 1) so an item is not paired with itself.
Edge / failure case ["1","1","1"], target "11" → 6
The same string can pair with a DIFFERENT copy of itself in either order: 3 × 2 = 6 ordered pairs.
Why? Take one number from each list; their longest common prefix is the longest shared start of their digits. What is the longest one over all pairs?
💡 Key idea Put every digit-prefix of every number in the first list into a set. For each number in the second list, find its longest prefix that is in the set.
Edge / failure case [1,2,3] and [4,4,4] → 0
No number in the first list shares even its first digit with the numbers in the second list.
Why? Bars of different heights stand side by side (each width 1). What is the area of the largest rectangle that fits inside them?
💡 Key idea Keep a stack of bars with increasing heights. When a lower bar arrives, pop taller bars: each popped bar is the shortest bar of a rectangle that stretches from the bar below it on the stack to the current position.
Edge / failure case [2, 4] → 4
Two options tie: both bars at height 2 (2 × 2 = 4) or the single bar of height 4 (4 × 1 = 4), so the answer is 4.
Why? List every root-to-leaf path of a binary tree as text like '1->2->5'.
💡 Key idea Walk down with DFS, adding each node to the path string. When you reach a leaf (no children), the path is complete — save it.
Edge / failure case tree [1] → ['1']
A single node is itself a leaf: the only path is '1'.
Why? Use every flight ticket exactly once, starting from JFK, to build one trip; if several trips work, choose the alphabetically smallest.
💡 Key idea This is an Eulerian path. DFS from JFK always taking the smallest unused destination; when a city has no more flights, add it to the route. The route built this way, reversed, is the answer.
Edge / failure case five tickets with a choice at JFK → ['JFK', 'ATL', 'JFK', 'SFO', 'ATL', 'SFO']
From JFK both ATL and SFO are possible; the alphabetically smaller ATL is tried first, and the trip still uses every ticket.
Why? Paint-bucket tool: recolour the clicked pixel and every connected pixel (up, down, left, right) that has the same original colour.
💡 Key idea Remember the original colour and DFS from the start pixel, repainting neighbours that still have it. If the new colour equals the old one, return immediately (otherwise it would loop forever).
Edge / failure case new colour = old colour → [[0, 0, 0], [0, 0, 0]]
The new colour equals the old colour, so nothing needs to change (and a careless version would loop forever).
Why? You get all neighbouring pairs of a hidden array (in any order). Rebuild the array (either direction is fine).
💡 Key idea Treat pairs as edges of a path. The two ends of the path are the only values that appear once; start at one end and keep stepping to the neighbour you did not come from.
Edge / failure case pairs with negative values → [-3, 1, 4, -2]
Negative numbers work too; starting from the smaller end gives -3, 1, 4, -2 (the reverse -2, 4, 1, -3 is also correct).
Why? You have n computers and a pile of batteries (each with some minutes). Batteries can be swapped any time. For how many minutes can all n computers run at once?
💡 Key idea Guess a time T. A battery can give at most T minutes (a computer can't use more than T), so we need Σ min(battery, T) ≥ n·T. This is true for small T and false for large T — binary-search the largest T that works.
Edge / failure case n=2, batteries [1,1,1,1] → 2
Four batteries of 1 minute give 4 computer-minutes in total, shared by 2 computers: 2 minutes.
Why? For each number with exactly four divisors, add up its divisors; return the total. 21 has 1, 3, 7, 21 → 32.
💡 Key idea Divisors come in pairs d and x/d, so test d only up to √x. Stop early as soon as more than 4 divisors are found.
Edge / failure case [1, 2, 3] → 0
1, 2 and 3 have 1, 2 and 2 divisors, never exactly four: 0.
Why? Repeatedly subtract the smaller number from the larger until one is 0. How many subtractions? (2, 3) → 3.
💡 Key idea Just simulate: each step, whichever number is larger loses the smaller one. (Euclid's algorithm in slow motion.)
Edge / failure case 10 and 10 → 1
The numbers are equal, so one subtraction makes one of them 0.
Why? Add the digits of a number but alternate signs, the first (leftmost) digit being positive. 521 → 5 − 2 + 1 = 4.
💡 Key idea Turn the number into text and go left to right, adding each digit with a sign that flips every step.
Edge / failure case n = 111 → 1
1 − 1 + 1 = 1.
Why? Each employee has busy time intervals. When is EVERYONE free (between the earliest and latest busy times)?
💡 Key idea Throw all intervals together, sort by start, and sweep keeping the latest end seen. A gap appears when the next interval starts after that end.
Edge / failure case [[[1,5]],[[2,8]]] → []
The two employees' busy times overlap and cover everything from 1 to 8: no free time.
Why? Street lamps light a stretch of the street around them. Find the position lit by the MOST lamps (the leftmost if tied).
💡 Key idea Each lamp is an interval [pos − range, pos + range]. Record +1 where it starts and −1 just after it ends, sort these events and sweep left to right keeping a running count.
Edge / failure case lights [[5,0]] → 5
A single lamp that lights only its own position: the brightest position is 5.
Why? A street has positions 0..n−1, each needing some brightness (how many lamps must light it). How many positions get enough light?
💡 Key idea Add +1 where each lamp's lit range starts and −1 just after it ends (a difference array). A running sum then gives every position's brightness; compare with the requirement.
Edge / failure case n=2, no lights, requirement [0,0] → 2
There are no lamps but nothing is required either, so both positions are fine.
Why? Same question as part I, but with very many long words — testing every pair is far too slow.
💡 Key idea Build a trie whose steps are PAIRS (letter from the front, letter from the back). A previous word that is both a prefix and a suffix of the current word is exactly a path of those pairs that ends at a word marker. Count markers while walking.
Edge / failure case ["abab", "ab"] → 0
The earlier word 'abab' is longer than 'ab', so it cannot be a prefix of it: no pairs.
Why? Simulate a candy game: any 3+ equal candies in a row or column vanish at the same time, the rest fall down, and this repeats until nothing more can vanish.
💡 Key idea Each round: find all candies that belong to a line of three or more (don't remove yet), set them to 0, then let each column's remaining candies fall to the bottom. Stop when a round finds nothing.
Edge / failure case [[1,2],[3,4]] → [[1, 2], [3, 4]]
No candy has two equal neighbours in line, so nothing is crushed and the board is returned as it was.
Why? A box of stones (#), obstacles (*) and empty cells (.) is rotated 90° clockwise; stones fall down (towards the new bottom) until they hit something.
💡 Key idea Before rotating, a stone falls to the RIGHT. So in each row, scan from the right and move every stone to the rightmost free cell before the next obstacle. Then rotate the grid clockwise.
Edge / failure case a box with an obstacle → [['#', '.'], ['#', '#'], ['*', '*'], ['.', '.']]
Stones stop at the obstacle '*' (they cannot pass through it) before the box is rotated.
Why? On an m×n grid some cells are black. How many 2×2 blocks contain 0, 1, 2, 3 and 4 black cells?
💡 Key idea The grid is huge but black cells are few. Each black cell touches up to four 2×2 blocks; count how many black cells each touched block has. Blocks never touched have 0 (total blocks minus the rest).
Edge / failure case a 2×2 cluster of black cells in a 3×3 grid → [0, 1, 2, 0, 1]
The four black cells fill the top-left 2×2 block completely (4) and touch the other three blocks partly.
Why? A grid of 0/1/2. Make the cells that form the letter Y all the same value, and every other cell one DIFFERENT same value. Each cell change costs 1.
💡 Key idea Count how many Y cells and non-Y cells hold each value. For every choice of (value for Y, value for the rest) with the two different, the cost is the cells that don't already match; take the minimum.
Edge / failure case a grid of all 1s → 4
All cells are 1, but the Y and the rest must differ: the cheapest is to change the 4 cells of the Y.
Why? Two lists. add(index, val) changes an entry of the second list; count(tot) says how many pairs (one number from each list) add up to tot.
💡 Key idea Keep a counter of the second list's values, updated on every add. To count pairs, go through the (short) first list and look up tot − x in the counter.
Edge / failure case count(100) with one pair possible → [0]
No pair adds up to 100, so the count is 0.
Why? A bank with numbered accounts: transfer, deposit and withdraw. Each action succeeds only if the account numbers are valid and there is enough money.
💡 Key idea Keep balances in a list. Before each action check the account number is in range and (for money leaving an account) that the balance is enough; only then change the balances.
Edge / failure case deposit(0,5), transfer(1,9,1) → [False, False]
Account numbers run from 1 to n, so account 0 and account 9 do not exist: both actions fail.
Why? Deal numbers into two lists: the first to list 1, the second to list 2, then each next number goes to the list in which MORE elements are greater than it (ties: the shorter list, then list 1).
💡 Key idea You need 'how many elements already in a list are greater than x' fast. Compress the values to ranks and keep a Fenwick tree (binary indexed tree) per list that counts values; a prefix query gives the number ≤ x.
Edge / failure case [5, 14, 3, 1, 2] → [5, 3, 1, 2, 14]
The first two numbers start the lists; then each new number goes to the list with more elements greater than it, or the shorter list on a tie.
Why? A number line gets obstacles one at a time. Between them you are asked: can a block of length sz fit somewhere in the part from 0 to x without touching an obstacle?
💡 Key idea Store for each obstacle the gap to the obstacle before it, in a segment tree for 'maximum over a range'. Adding an obstacle splits one gap into two (two point updates). A query takes the maximum gap among obstacles ≤ x, also considering the open stretch from the last obstacle to x.
Edge / failure case a single query, no obstacles → [True]
There are no obstacles at all, so a block of length 5 fits into [0, 5].
Why? Make a smaller grid where each cell is the largest value in the matching 3×3 block of the original.
💡 Key idea For each top-left corner of a 3×3 window take the maximum of its nine cells.
Edge / failure case 3×3 grid → [[2]]
A 3×3 grid has just one 3×3 window; its maximum is 2.
Why? Each directory line lists files with their contents. Report groups of files that have identical content.
💡 Key idea Parse each line into directory + (name, content) pairs and put the full path in a dictionary keyed by content. Groups with two or more paths are duplicates.
Edge / failure case two files, different contents → []
No two files have the same content, so there are no duplicate groups.
Why? A list can contain integers and further lists to any depth. Build an iterator that returns the integers one by one in order.
💡 Key idea Keep a stack with the items still to visit (in reverse). hasNext() keeps unpacking the top item while it is a list; when the top is an integer it is ready for next().
Edge / failure case [[], [[]], 3] → [3]
Empty nested lists contain no integers; only the 3 is returned.
Why? A spreadsheet where a cell can hold a plain number or a SUM formula over other cells/ranges, and updates automatically when those change.
💡 Key idea Store plain values and, for formula cells, the list of cells they add up. get() computes a formula cell by recursively summing the cells it depends on, so changes show up automatically.
Edge / failure case a formula cell overwritten by set → [0, None, None, 9]
Writing a plain number into a formula cell replaces the formula: the cell now shows 9, whatever A1 holds.
Why? Login tokens expire timeToLive seconds after they are created or renewed. Support generate, renew (only if not yet expired) and counting the unexpired tokens.
💡 Key idea Store each token's expiry time. Renew only if its expiry is still in the future; counting means counting expiries greater than the current time.
Edge / failure case renew after expiry → [None, None, 0]
The token expired at time 6, so renewing at time 10 does nothing and no token is active at 11.
Why? A tiny database: insert rows (with auto-increment ids), remove rows, read a cell and export a table as text.
💡 Key idea Keep for each table a dictionary id → row and a counter for the next id (ids are never reused). Every operation first checks the table exists and the sizes fit.
Edge / failure case invalid table, bad row, bad id → [False, False, '<null>']
Unknown table, wrong number of cells and a row that does not exist all fail ('<null>' for the read).
Why? A spreadsheet with cells like A1…Z999; set, reset and evaluate a simple formula '=X+Y' where X and Y are cells or plain numbers.
💡 Key idea Store only the cells that were set (dictionary); an unset cell is 0. To evaluate a formula, split it on '+' and add each part (a number, or the cell's value).
Edge / failure case getValue(=C3+4) → [4]
Cell C3 was never set, so it counts as 0.
Why? From start/end log lines of function calls, how much time did each function spend running itself (not counting the functions it called)?
💡 Key idea Keep a stack of running functions. When something starts, charge the time since the last event to the function that was running; when something ends, charge it the time since the last event (+1 because the end second counts).
Edge / failure case n=1, recursive calls → [7]
A function that calls itself: all 7 time units (0 to 6) count towards function 0.
Why? Are two strings exactly one edit apart (insert, delete or replace ONE character)?
💡 Key idea Make s the shorter one. At the first position where they differ, the rest must match after replacing (same length) or after skipping one character of the longer string.
Edge / failure case "ab", "ab" → False
The strings are identical: that is ZERO edits, not one.
Why? A transaction is suspicious if it is over $1000, or if the same name made a transaction in a DIFFERENT city within 60 minutes. List all suspicious ones.
💡 Key idea Parse each 'name,time,amount,city'. For every transaction check the amount and scan the others by the same name for a different city within 60 minutes.
Edge / failure case one big transaction → ['alice,20,1500,mtv']
The amount is over 1000, so the transaction is invalid by itself.
Why? A shop's log says for each hour whether customers came (Y) or not (N). Closing at hour h costs 1 per open hour with no customers plus 1 per closed hour with customers. Which hour is best (earliest)?
💡 Key idea Start with 'closed all day' (penalty = number of Y). Moving the closing hour past an hour changes the penalty by +1 for an N and −1 for a Y. Track the minimum.
Edge / failure case "NNNNN" → 0
Nobody ever comes, so closing at hour 0 costs nothing.
Why? '{a,b}c{d,e}f' stands for all words choosing one letter from each {…}: acdf, acef, bcdf, bcef. List them alphabetically.
💡 Key idea Split the pattern into groups (a plain letter is a group of one). Sort each group and take every combination of one choice per group (cartesian product).
Edge / failure case "abcd" → ['abcd']
No braces: only one word.
Why? Are there two numbers at most k positions apart whose values differ by at most t?
💡 Key idea Group values into buckets of width t+1: two numbers in the same bucket always differ by ≤ t, and only the two neighbouring buckets need a check. Keep buckets only for the last k numbers.
Edge / failure case nums [1,5,9,1,5,9], k=2, t=3 → False
Equal values are 3 positions apart (more than 2) and nearby values differ by 4 (more than 3): no valid pair.
Why? In a directed graph without cycles, list every path from node 0 to the last node.
💡 Key idea DFS from node 0, adding nodes to a current path; when you reach the last node save a copy; remove the node when you step back.
Edge / failure case [[1], []] → [[0, 1]]
Only one path exists: 0 → 1.
Why? Longest run of numbers (consecutive) that appears in BOTH lists.
💡 Key idea dp[i][j] = length of the longest common run starting at i in the first list and j in the second: if the numbers match it is 1 + dp[i+1][j+1], else 0. The answer is the largest cell.
Edge / failure case [0,0,0], [1,1] → 0
The lists share no number, so no common run exists: 0.
Why? A message may be printed only if the same message was not printed in the last 10 seconds.
💡 Key idea Keep a dictionary message → time it was last printed. Print (and update) only when there is no entry or at least 10 seconds have passed.
Edge / failure case 'a' at 1 and at 11 → [True, True]
Exactly 10 seconds later the same message may be printed again.
Why? As you type letters, suggest the 3 most used past sentences that start with what you typed (ties alphabetical). Typing '#' saves the sentence.
💡 Key idea Keep a count per sentence and the text typed so far. After each letter, filter sentences by the prefix and sort by (−count, text). '#' adds the finished sentence with count +1 and resets.
Edge / failure case type b, #, b → [[], [], ['b']]
No stored sentence starts with 'b', so nothing is suggested; after '#' the sentence 'b' is saved and then suggested.
Why? From (x, y) you may go to (x+y, y) or (x, x+y). Can (sx, sy) become (tx, ty)?
💡 Key idea Go BACKWARDS: the bigger coordinate must have come from subtracting the smaller. Subtract in bulk with the remainder (%) until you reach the start or can't continue.
Edge / failure case (1,1) → (2,2) → False
(2,2) would have to come from (2,0) or (0,2), which are not allowed: False.
Why? A stack with a size limit that also supports 'add val to the bottom k items'.
💡 Key idea Don't touch the k items; just note the increment at position k−1. When an item is popped, add its note to it and pass the note down to the item below.
Edge / failure case capacity 1 → [None, None, 5, -1]
The stack holds at most 1 item, so the second push is ignored; the second pop finds it empty (-1).
Why? A list should hold 1..n once each, but one number appears twice and another is missing. Find both.
💡 Key idea The duplicate = (sum of list) − (sum of distinct values); the missing number = (1+…+n) − (sum of distinct values).
Edge / failure case [1, 1] → [1, 2]
1 is repeated and 2 is missing.
Why? Run-length encode a string ('aaabcc' → 'a3bc2'). You may delete at most k characters first. Shortest possible encoded length?
💡 Key idea At each start position decide: delete this character, or keep it and merge all later copies of the same letter (deleting the different letters in between, within the budget). Memoise by (position, deletions left).
Edge / failure case "aabbaa", k=2 → 2
Deleting both b's merges the a's into 'a4' (length 2).
Why? Is the number made only from the prime factors 2, 3 and 5? 6 yes, 14 no.
💡 Key idea Keep dividing by 2, then 3, then 5 while possible. If you end at 1 the number is 'ugly'.
Edge / failure case n = 14 → False
14 = 2 × 7: the factor 7 is not allowed.
Why? You must move to one of the 8 neighbouring cells every second. Can you be at the target cell after EXACTLY t seconds?
💡 Key idea With 8-direction moves the shortest time is max(|dx|, |dy|). Any t at least that works (you can wiggle), except when you start on the target and t = 1 (you can't stay still).
Edge / failure case start = target, t = 1 → False
You start on the target but must move every second, so after exactly 1 second you can't be back there.
Why? A robot starts at (0,0) facing north and follows commands (turn left/right or walk k steps), stopping early if an obstacle is in front. Largest squared distance from the origin ever reached?
💡 Key idea Track position and a direction vector (dx, dy); turning rotates the vector. Move one step at a time, checking an obstacle set.
Edge / failure case an obstacle on the route → 65
The obstacle at (2,4) blocks the robot on its last leg, so it stops one step short.
Why? Paint a row of houses red, blue or green with given prices, never painting neighbours the same colour. Cheapest total?
💡 Key idea For each house keep the cheapest total if it is red, blue or green: each is its own price plus the cheaper of the other two colours from the previous house.
Edge / failure case [[3,1,2]] → 1
One house: just pick its cheapest colour.
Why? Turn a long URL into a short one and be able to turn it back.
💡 Key idea Hand out increasing numbers as short codes and store code → long URL in a dictionary; decode just looks the code up.
Edge / failure case two different URLs → [True, True, True]
Different long URLs must get different short ones and each must decode back correctly.
Why? Which numbers appear in both lists (each reported once)?
💡 Key idea Put the first list in a set; scan the second list and collect numbers found in it, removing them from the set so they are reported only once.
Edge / failure case [4,9,5], [9,4,9,8,4] → [9, 4]
9 and 4 are common (each reported once); 5 and 8 are not.
Why? Lay one tree on top of another: where both have a node, add their values; otherwise keep whichever exists.
💡 Key idea Recursively: if one node is missing return the other; otherwise add the values and merge the left and right children the same way.
Edge / failure case [] merged with [1] → [1]
The first tree is empty, so the second tree is the result.
Why? Each tree node knows its parent. Find the lowest common ancestor of two nodes.
💡 Key idea Walk two pointers up the parent links; when one reaches the top, restart it at the other node. They meet exactly at the common ancestor after equal total steps.
Edge / failure case p=5, q=4 → 5
Node 4 is below node 5, so 5 is itself the lowest common ancestor.
Why? Rain falls on a lake (a number) or the day is dry (0). A lake that is full and rains again floods the city. On dry days you may dry ONE lake. Return a plan that avoids all floods.
💡 Key idea Remember dry days (sorted) and when each lake was last filled. When a full lake rains again, use the earliest dry day AFTER it was filled to dry exactly that lake; if no such day exists, the flood is unavoidable.
Edge / failure case [1, 1, 0] → []
Lake 1 is full and rains again before any dry day: a flood cannot be avoided, so no plan exists.
Why? Give money to children: everyone gets at least $1, nobody gets exactly $4, all money is used. Maximise the children who get exactly $8.
💡 Key idea Give each child $1 first, then upgrade as many as possible to $8 (7 more each). Fix the traps: leftover money with no child left to take it, or the last child ending up with exactly $4.
Edge / failure case money 16, children 2 → 2
Both children can get exactly $8.
Why? A stream of (timestamp, price) records where an old record can be CORRECTED. Report the latest price, the highest and the lowest current price.
💡 Key idea Keep a dictionary timestamp → current price, plus a max-heap and a min-heap of (price, timestamp). When reading the top, pop entries whose price no longer matches the dictionary (lazy deletion).
Edge / failure case one update → [None, 7, 7, 7]
With a single record all three answers are that price.
Why? 2n people sit in a row; couples are (0,1), (2,3) … Fewest swaps (of any two people) so every couple sits side by side?
💡 Key idea Go through the seats two at a time. If the person next to you is not your partner, swap your partner into that seat (one swap fixes one couple permanently).
Edge / failure case [3, 2, 0, 1] → 0
Both couples (2,3) and (0,1) already sit together (in either order): 0 swaps.
Why? Hens and grains sit on a line. Each second a hen moves 1 step. Fewest seconds until all grains are eaten?
💡 Key idea Binary-search the time T. To check T, sort hens and grains and let each hen (left to right) eat the leftmost uneaten grains it can reach: going left first then right, or right first then left, whichever reaches farther.
Edge / failure case hens near each grain → 1
Every grain is right next to a hen, so one second is enough.
Why? Fill the empty cells of a Sudoku so every row, column and 3×3 box contains 1–9 exactly once.
💡 Key idea Remember which digits each row, column and box already uses. For each empty cell try the digits that fit, move on, and undo the choice if you get stuck (backtracking).
Edge / failure case the classic starting board → ['534678912', '672195348', '198342567', '859761423', '426853791', '713924856', '961537284', '287419635', '345286179']
A much emptier board needs many more guesses and take-backs (backtracking); the trace is cut off after the first 900 steps.
Why? Find every number that appears MORE than a third of the time.
💡 Key idea At most two numbers can do that. Keep two candidate numbers with counters (Boyer–Moore): a different number cancels one vote from each. Then verify the survivors with a real count.
Edge / failure case [1] → [1]
With one number it appears more than a third of the time.
Why? Given points, find the smallest rectangle (sides parallel to the axes) whose four corners are all in the list.
💡 Key idea Put the points in a set. For every pair of points that could be opposite corners (different x and y), check whether the other two corners exist.
Edge / failure case [[1,1],[2,2]] → 0
Two points cannot form a rectangle: 0.
Why? After sorting, what is the biggest difference between neighbouring numbers? Do it without a full sort.
💡 Key idea With n numbers the biggest gap is at least (max−min)/(n−1). Drop numbers into buckets of that width, keeping only each bucket's min and max; the answer is the largest gap between one bucket's max and the next non-empty bucket's min.
Edge / failure case [10] → 0
A single number has no neighbours, so the gap is 0.
Why? Cars drive toward the same target and cannot overtake; a faster car behind a slower one just joins it as a fleet. How many fleets arrive?
💡 Key idea Sort cars from the one closest to the target. Compute each car's time to arrive alone; if it is longer than the fleet ahead's time it forms a new fleet, otherwise it is caught by that fleet.
Edge / failure case one car → 1
A single car is a single fleet.
Why? Words are sorted in an alien language. Work out the order of its letters.
💡 Key idea Compare each pair of neighbouring words: the first differing letters give a rule 'x comes before y'. Those rules form a graph; a topological order is the alphabet. A cycle (or a word followed by its own prefix) means it is impossible.
Edge / failure case [z, x, z] → ''
z < x and x < z contradict each other (a cycle), so no valid alphabet exists: empty string.
Why? Build a house on an empty spot so the total walking distance to ALL buildings is smallest (obstacles block the way).
💡 Key idea BFS from each building across empty cells, adding the distance into a 'total' grid and counting how many buildings reached each cell. The answer is the smallest total among cells every building reached.
Edge / failure case [[1,2,0]] → -1
The only empty cell is behind an obstacle, so the building cannot reach it: -1.
Why? A car must travel `target` miles with limited fuel and fuel stations on the way. Fewest refuelling stops?
💡 Key idea Drive as far as the fuel allows, remembering the fuel amount at every station you passed in a max-heap. When you can't go on, retroactively refuel at the biggest passed station.
Edge / failure case start fuel 1 → -1
The car cannot even reach the first station (1 unit of fuel, station at 10): -1.
Why? Pick an index at random where index i is chosen with probability proportional to w[i].
💡 Key idea Build running totals of the weights. Pick a random number from 1 to the total and binary-search the first running total that is ≥ it.
Edge / failure case weights [5] → [0]
One weight means only index 0 can ever be picked.
Why? A robot in an unknown room can only move forward, turn and clean. Make it clean every reachable cell.
💡 Key idea DFS using coordinates you invent (start = (0,0)): clean, then try all four directions; if a move works and the cell is new, recurse, then turn around, step back and turn back so the robot is in the right place and direction.
Edge / failure case a room with a single open cell → [1, 1]
A one-cell room: clean it and nothing else to do.
Why? A taxi drives from 1 to n picking up passengers (start, end, tip). A ride earns (end − start + tip). Carry one passenger at a time; maximise earnings.
💡 Key idea dp[x] = best earnings once you reach position x: either carry on from x−1 or finish a ride that ends at x and add its earnings to dp[start].
Edge / failure case two separate rides → 13
The two rides do not overlap, so both can be taken: (1+5) + (1+6) = 13.
Why? Can the numbers be split into groups of k consecutive values (like 3,4,5,6 for k=4)?
💡 Key idea Count the numbers. Take the smallest remaining value x: it must start a run x, x+1, …, x+k−1, so remove one of each (and as many runs as x's remain). If any needed number is missing, it fails.
Edge / failure case [1,2,3,4], k=3 → False
4 numbers cannot be split into groups of 3.
Why? Answer many 'sum of this rectangle of the grid' questions quickly.
💡 Key idea Precompute p[i][j] = sum of the rectangle from the top-left corner to (i, j). Any rectangle sum is then four lookups: big − left − top + overlap.
Edge / failure case [[7]] → [7]
A rectangle of one cell is just that cell.
Why? Land appears one cell at a time on a map. After each addition, how many islands are there?
💡 Key idea Each new land cell starts as its own island (+1). For each land neighbour, union them; every successful union merges two islands (−1). Union-find makes each step almost O(1).
Edge / failure case same cell twice → [1, 1]
The same cell is added twice; the second time nothing changes, so the count stays 1.
Why? Make a 0/1 string alternate (0101… or 1010…) with the fewest flips.
💡 Key idea Count how many characters differ from the pattern 0101…. The other pattern 1010… differs in all the remaining positions, so the answer is min(diff, n − diff).
Edge / failure case "10" → 0
'10' already alternates: 0 changes.
Why? Like Word Ladder, but list EVERY shortest sequence from beginWord to endWord (one changed letter per step, all words from the list).
💡 Key idea BFS level by level, remembering for each word which words at the previous level reach it (its parents). When the end word is found, walk the parents backwards to rebuild every shortest path.
Edge / failure case endWord missing from the list → []
'cog' is not in the word list, so no sequence can end there: empty list.
Why? Recipes need ingredients, which may be supplies or other recipes. Which recipes can be made?
💡 Key idea Treat 'ingredient → recipe' as edges. Start with the supplies; each time a recipe has all its ingredients available it becomes available too (like Kahn's algorithm).
Edge / failure case a circular recipe → []
Recipe a needs b and b needs a, and there are no supplies: neither can ever be made.
Why? Rearrange the letters so no two neighbouring letters are equal, or say it is impossible.
💡 Key idea Repeatedly take the two most frequent remaining letters and place them next to each other (max-heap). If a single letter is left over more than once, it is impossible.
Edge / failure case "aaab" → ''
Three a's cannot be kept apart with only one other letter: impossible, empty string.
Why? Is a list of bytes a valid UTF-8 text? A character takes 1–4 bytes: the first byte tells how many, the rest must start with bits 10.
💡 Key idea Read the leading bits of the first byte (0… = 1 byte, 110… = 2, 1110… = 3, 11110… = 4) to know how many continuation bytes follow; each must start with 10.
Edge / failure case [235, 140, 4] → False
The first byte announces 3 bytes, but the third byte does not start with the required bits 10: invalid.
Why? Hydrogen and oxygen threads arrive in any order; they must leave in groups of 2 hydrogens + 1 oxygen (one water molecule at a time).
💡 Key idea Allow at most 2 hydrogen and 1 oxygen threads into the 'room' (semaphores), and make the three wait for each other at a barrier. They release together, print, and only then let the next molecule's atoms in.
Edge / failure case H, H, O → ['HHO']
A single water molecule: the three atoms form exactly one group of 2 H + 1 O.
Why? A car park with a fixed number of big, medium and small spots. addCar says whether a car of that size can park.
💡 Key idea Keep the number of free spots per size; a car parks if its size still has a free spot.
Edge / failure case ParkingSystem(0,0,0) → [False, False, False]
There are no spots at all.
Why? A secret key's letters, in order of first appearance, stand for a, b, c, … Decode a message with it.
💡 Key idea Walk the key and give each new letter the next alphabet letter in a dictionary; then replace every message letter (spaces stay).
Edge / failure case a key with all 26 letters → 'the five boxing wizards jump quickly'
A key that lists every letter once gives a full substitution table.
Why? Walk two lists alternately: one from the first, one from the second, and so on; when one runs out keep taking from the other.
💡 Key idea Keep a queue of the lists that still have items (with their position). next() takes the front list, returns its current item and puts the list back at the end if it has more.
Edge / failure case [] and [7, 8] → [7, 8]
The first list is empty, so everything comes from the second list.
Why? Water drops fall one at a time at a position of a terrain; each drop flows left if it can go down that way, otherwise right, otherwise stays. Where does the water end up?
💡 Key idea For each drop: scan left while the ground does not rise, remembering the lowest (nearest) spot reached; if one lower than the start exists drop there. Otherwise do the same to the right. Otherwise stay at the start.
Edge / failure case heights [1,1], drop at 0 → [2, 1]
The neighbour is not lower, so the water cannot flow anywhere and stays at the drop position.
Why? Count the runs of neighbouring numbers whose product is less than k.
💡 Key idea Grow the window to the right multiplying; while the product is ≥ k, divide out the left number and shrink. Every window ending here contributes (window length) runs.
Edge / failure case k = 0 → 0
Every product is at least 1, never below 0: no valid runs.
Why? Find the shortest piece of s1 that contains all of s2 as a subsequence (in order, gaps allowed).
💡 Key idea From a start, move forward matching s2's letters in order to find an end; then walk backwards from that end matching s2 reversed to find the tightest start. Record it and restart just after that start.
Edge / failure case s1="abc", s2="d" → ''
The letter d never appears, so no window exists: empty string.
Why? Find all pairs of words (i, j) whose concatenation words[i] + words[j] is a palindrome.
💡 Key idea For each word, split it at every position. If the left part is a palindrome, the reverse of the right part (if it is a word) can go in front; if the right part is a palindrome, the reverse of the left part can go behind. A dictionary makes each lookup O(1).
Edge / failure case ["a", ""] → [[0, 1], [1, 0]]
The empty word can be glued before or after 'a' and the result is still a palindrome: both orders count.
Why? Regions contain smaller regions (like Earth ⊃ North America ⊃ Canada). Find the smallest region that contains both of two given regions.
💡 Key idea Record each region's parent. Collect all ancestors of the first region (including itself), then climb from the second until you hit one of them.
Edge / failure case Canada and Quebec → 'Canada'
Quebec is inside Canada, so the smallest region containing both is Canada itself.
Why? Do two strings in the list differ at exactly one position?
💡 Key idea For each string and each position, replace that letter by '*' to make a key ('abcd' → '*bcd', 'a*cd', …). Two strings that differ in one position share a key.
Edge / failure case [ab, cd, yz] → False
Every pair differs in both positions, so none differ by exactly one.
Why? For each string, find the shortest piece (substring) of it that appears in NO other string; among equally short ones the alphabetically smallest; empty if none.
💡 Key idea Collect every substring of every string in a set. For a string, check its substrings from shortest (alphabetical) and take the first that is not in any OTHER string's set.
Edge / failure case [abc, bcd, abcd] → ['', '', 'abcd']
Every piece of 'abc' and 'bcd' also appears in 'abcd', so they have none; 'abcd' itself appears nowhere else.
Why? Turn a text like '[123,[456,[789]]]' into a nested structure of integers and lists.
💡 Key idea Scan the characters. '[' starts a new list (push the current one on a stack), digits build a number, ',' or ']' finish the number and add it to the current list, and ']' pops back to the parent list.
Edge / failure case "324" → 324
A plain number (no brackets) becomes a single integer.
Why? Two linked lists merge into one tail at some node. Find the first shared node (or none).
💡 Key idea Walk one pointer along list A then list B, the other along B then A. Both walk the same total length, so they arrive at the shared node at the same moment (or both end at nothing).
Edge / failure case two separate lists → None
The lists never meet, so there is no intersection: nothing.
Why? A grid has walls, locks (A, B…) and keys (a, b…). Fewest steps from the start to collect all keys?
💡 Key idea Where you stand is not the whole state — which keys you hold matters. BFS over (row, column, set of keys as a bitmask); a lock cell is passable only if you hold its key.
Edge / failure case ["@Aa"] → -1
The key 'a' is behind the lock 'A', and the only key opens that lock from the other side: impossible, -1.
Why? Flipping a cell also flips its 4 neighbours. Fewest flips to make the whole 0/1 board zeros?
💡 Key idea The board fits in an integer bitmask (at most 9 cells). Each flip is an XOR with a precomputed mask; BFS from the start board finds the fewest flips to reach 0.
Edge / failure case [[1,0,0],[1,0,0]] → -1
No sequence of flips can clear this board (a parity argument), so the answer is -1.
Why? Boxes may be locked, contain candies, keys to other boxes and other boxes. Starting from some boxes, how many candies can you collect?
💡 Key idea Keep the boxes you hold and which are unlocked. Repeatedly open any held box that is unlocked: take its candies, unlock the boxes its keys open, and add the boxes inside. Stop when nothing new can be opened.
Edge / failure case a locked starting box → 0
Box 0 is locked and no key for it exists, so nothing inside can be reached: 0 candies.
Why? In a directed acyclic graph, find the smallest set of nodes from which every node can be reached.
💡 Key idea A node with no incoming edge can't be reached from anywhere else, so it must be in the set; and those nodes together reach everything.
Edge / failure case n=3, no edges → [0, 1, 2]
With no edges every node is its own starting point.
Why? Each bomb has a position and blast radius; detonating one sets off every bomb inside its radius, and so on. Starting from the best bomb, how many explode?
💡 Key idea Make a directed graph: i → j if bomb j is within i's radius. DFS from every bomb and take the largest number of bombs reached.
Edge / failure case two far-apart bombs → 1
The bombs are far apart: each only sets off itself.
Why? Return the k points nearest to (0,0).
💡 Key idea Keep the k best in a max-heap keyed by distance; when it grows beyond k, drop the farthest.
Edge / failure case k = 2 → [[-2, 4], [3, 3]]
The two nearest points by squared distance (18 and 20) are (3,3) and (-2,4).
Why? Stack blocks in a pyramid: each block rests on two blocks below and the three colours must form an allowed triple. Can the pyramid be completed from the bottom row?
💡 Key idea Build the next row one block at a time using the allowed triples (a dictionary from the pair below to the possible tops); recurse on the finished row. Memoise rows that already failed.
Edge / failure case bottom "AAAA" → False
The first level can be built (B or C on top of AA) but neither combination can be continued to a single top block.
Why? Buy exactly the items you need; special offers bundle several items at one price. Cheapest total?
💡 Key idea The state is the list of items still needed. Either buy everything at normal prices, or apply one offer (if it doesn't overshoot) and solve the rest. Cache by the needs.
Edge / failure case price [2,3], offer costs 10 → 5
The bundle costs 10 but buying the two items separately costs only 5, so no offer is used.
Why? Pick the fewest people so that every required skill is covered by someone on the team.
💡 Key idea A set of covered skills is a bitmask. For each person, update the best (smallest) team known for every skill set reachable by adding them.
Edge / failure case skills a, b → [2]
One person who knows both skills (index 2) is enough.
Why? Build a house of cards from exactly n cards: each row of k triangles uses 3k − 1 cards and the row above must have fewer triangles. How many different houses?
💡 Key idea A house is a strictly decreasing list of row sizes k1 > k2 > … whose card costs 3k − 1 add up to n. Count them with recursion: choose the next (smaller) row size and recurse on the leftover cards.
Edge / failure case n = 4 → 0
No combination of row costs (2, 5, 8, …) adds up to exactly 4.
Why? Round each price up or down so the rounded prices add up to the target, with the smallest total rounding error.
💡 Key idea Floor every price first; the target tells how many must be rounded UP. Round up the ones with the biggest fractional parts (cheapest in error). If the target is outside the possible range, answer −1.
Edge / failure case target 10 → '-1'
The prices can only sum to between 6 and 9 after rounding, so a total of 10 is impossible.
Why? Write 1, 2, 3, … 10, 11 … as one long string of digits. What is the n-th digit? n=11 → 0 (the '0' of 10).
💡 Key idea There are 9 one-digit numbers, 90 two-digit numbers, 900 three-digit… Subtract whole groups until n falls inside one, then compute which number and which digit of it.
Edge / failure case n = 3 → 3
The sequence starts 1 2 3 …, so the 3rd digit is 3.
Why? In how many ways can n be written as a sum of consecutive positive whole numbers? 5 = 5 = 2 + 3 → 2 ways.
💡 Key idea A run of k numbers starting at a sums to k·a + k(k−1)/2. For each k, check whether n − k(k−1)/2 is divisible by k (and the start is positive). k only goes up to about √(2n).
Edge / failure case n = 1 → 1
Only '1' itself.
Why? Write a whole number in base −2 (digits 0/1). 2 → '110' because 1·4 + 1·(−2) + 0·1 = 2.
💡 Key idea Repeatedly divide by −2. If the remainder comes out negative, add 2 to it and add 1 to the quotient. The remainders, read backwards, are the digits.
Edge / failure case n = 0 → '0'
Zero is just '0'.
Why? A robot repeats a list of commands (G go, L/R turn) forever. Does it stay inside some circle?
💡 Key idea After one pass: if it is back at the start it is bounded; if it is NOT facing north any more, repeating will rotate it around and bring it back within 4 passes. Only 'moved away and still facing north' is unbounded.
Edge / failure case "GG" → False
The robot walks straight north forever and gets further and further away: not bounded.
Why? An iterator over a list of lists that returns all numbers in order, skipping empty inner lists.
💡 Key idea Keep a row index and a column index. Before reading or checking, move forward past rows that are used up (or empty).
Edge / failure case [[], [1], [], [2]] → [1, 2]
Empty rows are skipped, so only the two real numbers come out.
Why? Accounts (name + emails) belong to the same person if they share an email. Merge them.
💡 Key idea Treat every email as a node; join all emails of one account. Emails in the same set belong to one person; output the owner's name with the sorted emails of each set.
Edge / failure case one account → [['Ann', 'a@x.com']]
A single account stays as it is.
Why? Letters a–z are laid out in rows of 5 ('z' alone on the last row). Give the moves (U, D, L, R and '!' to select) that type a word starting from 'a'.
💡 Key idea Each letter has a row and column (index // 5, index % 5). Move to the next letter's cell and press '!'. Do LEFT and UP moves before DOWN and RIGHT so you never step off the board when leaving 'z'.
Edge / failure case "zb" → 'DDDDD!UUUUUR!'
From 'z' (alone on the last row) go UP first, then right — going right first would leave the board.
Why? The width of a column is the number of characters of its longest number (a minus sign counts). Report each column's width.
💡 Key idea For each column compute the length of every number written as text and keep the maximum.
Edge / failure case a grid with negatives → [3, 1, 2]
The minus sign counts as a character: '-15' has width 3.
Why? Count pairs of songs whose lengths add up to a multiple of 60 seconds.
💡 Key idea Only the remainder mod 60 matters. For each song, add the number of earlier songs whose remainder is (60 − r) mod 60, then record this song's remainder.
Edge / failure case [60, 60, 60] → 3
Every pair sums to 120, a multiple of 60: three pairs.
Why? You may add or subtract `value` from any element any number of times. What is the largest MEX (smallest missing non-negative integer) you can reach?
💡 Key idea Adding/subtracting value keeps a number's remainder mod value. So each number can become any non-negative number with the same remainder. Count numbers per remainder and use them up while counting 0, 1, 2, … (number m needs a spare number with remainder m mod value).
Edge / failure case [3,0,3,2,4,2,1,1,0,4], value 5 → 10
There are enough numbers in every remainder class to build 0 through 9: the MEX is 10.
Why? Who badged in three or more times within a single hour (strictly less than 60 minutes between the first and third)?
💡 Key idea Convert each time (like '0829') to minutes, group by employee and sort. Three accesses fit when entry i and entry i+2 are less than 60 minutes apart.
Edge / failure case three accesses exactly an hour apart → []
The first and third access are exactly 60 minutes apart, which is not 'within an hour' (it must be less than 60).
Why? For each query range [l, r] count the words that both start and end with a vowel.
💡 Key idea Mark each word 1 or 0 and take a running total. A range answer is the difference of two running totals.
Edge / failure case ["b"] → [0]
'b' does not start with a vowel, so the count is 0.
Why? A run is 'good' if its first and last numbers differ by exactly k. Largest sum of a good run?
💡 Key idea For the run ending at x, the first number must be x−k or x+k. Keep, for each value, the smallest prefix sum before an occurrence of it; the best run ending here is (prefix through x) − (that smallest prefix).
Edge / failure case [-1, -2, -3, -4], k=2 → -6
The best good run is [-1,-2,-3] (first and last differ by 2) with sum −6.
Why? Voters rank all teams. The team with more first-place votes wins; ties are broken by second-place votes, and so on; a complete tie is broken alphabetically.
💡 Key idea Count, for every team, how many votes it got in each position. Sort teams by those counts (more is better, position by position), then alphabetically.
Edge / failure case [WXYZ, XYZW] → 'XWYZ'
W and X each have one first-place vote; X has the better second place, so X comes before W; then Y and Z.
Why? You may swap two elements whenever their values differ by at most `limit`. Make the list alphabetically smallest.
💡 Key idea Elements whose values chain together (neighbours in sorted order within the limit) can be rearranged freely. Sort values into such groups; put each group's sorted values back into that group's sorted positions.
Edge / failure case [1,7,28,19,10], limit 3 → [1, 7, 28, 19, 10]
No two values are within 3 of each other, so nothing can be swapped.
Why? A pair (a, b) is 'perfect' if min(|a−b|, |a+b|) ≤ min(|a|,|b|) and max(|a−b|, |a+b|) ≥ max(|a|,|b|). Count perfect pairs.
💡 Key idea The condition simplifies to: after taking absolute values, the larger one is at most twice the smaller. Sort the absolute values and use a moving left pointer so that every partner is at least half the current value.
Edge / failure case [-3, 2, -1, 4] → 4
After taking absolute values (3,2,1,4) pairs need the larger to be at most twice the smaller: four pairs qualify.
Why? In a binary search tree (smaller on the left, bigger on the right), find the lowest node that is an ancestor of both p and q.
💡 Key idea Start at the root. If both values are smaller go left, if both are bigger go right; otherwise this node splits them (or is one of them) and is the answer.
Edge / failure case p=2, q=4 → 2
Node 4 is inside node 2's subtree, so 2 is the lowest common ancestor.
Why? Find the lowest common ancestor of p and q, but they might not both be in the tree (then return nothing).
💡 Key idea Do the usual DFS but visit BOTH children before deciding, and count how many of p and q were actually met. If fewer than two were found, there is no answer.
Edge / failure case q not in the tree → None
The node 10 is not in the tree, so there is no common ancestor: nothing.
Why? Find the lowest node that has ALL of the given nodes in its subtree (the nodes are guaranteed to be in the tree).
💡 Key idea DFS: return a node if it is one of the targets; otherwise combine the children's answers — if both sides found something, this node is the answer; otherwise pass along whichever side found one.
Edge / failure case one target node → 6
With a single target node, that node is its own lowest common ancestor.
Why? Servers send a message to the master server (0) and wait for the reply, resending every `patience` seconds if no reply has come. When does the network finally go quiet?
💡 Key idea BFS gives each server's distance d to the master; the round trip is 2d. A server resends at multiples of patience while < 2d, so its last message is sent at ((2d − 1) // patience) · patience and the reply arrives 2d later. The network is idle one second after the latest reply.
Edge / failure case patience 10 → 3
Both servers are 1 step from the master with huge patience, so there are no resends: the last reply arrives at 2, idle at 3.
Why? grid[i][j] is the earliest second you may enter that cell; you must move every second but can bounce back and forth. Earliest time to reach the bottom-right corner?
💡 Key idea Dijkstra on arrival time. Moving to a neighbour takes max(t+1, its opening time); if you have to wait, you can only wait an even number of seconds by bouncing, so add 1 when the parity is wrong. If both first moves are blocked, return −1.
Edge / failure case a blocked start → -1
Both cells next to the start open too late (time 2 and 3) so you can never step forward and wait: -1.
Why? A company has n branches joined by roads. In how many ways can you close some branches (maybe none) so that every remaining pair is within maxDistance of each other (travelling only through remaining branches)?
💡 Key idea n is at most 10, so try all 2ⁿ subsets of branches to keep. For each, compute all shortest distances among the kept branches (Floyd–Warshall) and check they are all ≤ maxDistance.
Edge / failure case n=1 → 2
One branch: keeping it or closing it are both fine (no pairs to check): 2 sets.
Why? Letters can be changed into other letters at given costs (and chains of changes are allowed). Cheapest way to turn source into target letter by letter?
💡 Key idea Build a 26×26 table of cheapest direct changes, run Floyd–Warshall to get the cheapest chain between any two letters, then add up the cost for each position (−1 if some change is impossible).
Edge / failure case an impossible conversion → -1
There is no way to turn 'a' into 'b' (only a → c exists): -1.
Why? Meetings start at fixed times; each uses the lowest-numbered free room, or waits for the earliest room to free up (keeping its length). Which room hosts the most meetings (lowest number on ties)?
💡 Key idea Sort meetings by start. Keep a min-heap of free room numbers and a min-heap of (end time, room) for busy rooms. Free rooms whose meeting ended; if none is free, take the room that frees first and delay the meeting by the wait.
Edge / failure case n=3, five meetings → 1
Rooms 1 and 2 each end up hosting two meetings (more than room 0), and on a tie the lower room number, 1, wins.
Why? An envelope fits inside another only if BOTH width and height are strictly smaller. How many can be nested?
💡 Key idea Sort by width ascending (and height DESCENDING for equal widths, so equal widths can't chain). Then the answer is the longest strictly increasing subsequence of heights, found with binary search in O(n log n).
Edge / failure case three equal envelopes → 1
Equal envelopes cannot be nested: the best chain is a single envelope.
Why? Each day one more cell floods. What is the last day you can still walk from the top row to the bottom row over land?
💡 Key idea If you can cross on day d you could on any earlier day: binary-search d. To test a day, flood the first d cells and run BFS from all top land cells to see whether the bottom row is reached.
Edge / failure case a 3×3 grid → 3
The crossing becomes impossible only after the third cell floods, so day 3 is the last day.
Why? Letters stand for different digits so that the words add up to the result (like SEND + MORE = MONEY); no word may start with 0. Is there an assignment?
💡 Key idea Give every letter a weight: +10^position in each summed word, −10^position in the result. A valid assignment makes the weighted sum zero. Backtrack over letters trying unused digits (not 0 for leading letters).
Edge / failure case AB + AB = AC → False
2 × AB = AC would need 10A + 2B = C ≤ 9, forcing A = 0 — not allowed for a leading letter: impossible.
Why? A chain grows a word by inserting ONE letter each step (a → ba → bda → bdca). Longest chain in the list?
💡 Key idea Process words from shortest to longest. For each word try deleting each letter; if the shorter word has a chain of length L, this word has L + 1. Keep the maximum.
Edge / failure case [abcd, dbqca] → 1
Neither word can be built from the other by adding one letter: chains have length 1.
Why? Jobs must be done in order over exactly d days (at least one per day). A day's difficulty is its hardest job; minimise the sum over all days.
💡 Key idea go(i, days) = best total for jobs from i on using `days` days: choose how many jobs to do today (the day's cost is the maximum so far), then solve the rest. Cache by (i, days).
Edge / failure case 3 jobs, 4 days → -1
More days than jobs: each day needs at least one job, so it is impossible.
Why? Count the subsequences of length 5 of a digit string that read the same backwards (answer modulo 1,000,000,007).
💡 Key idea A length-5 palindrome is ab·x·ba. For every middle position, count how many 'ab' pairs exist before it (prefix table) and how many 'ba' pairs after it (suffix table), and multiply for all 100 pairs.
Edge / failure case "0000000" → 21
Every choice of 5 of the 7 zeros is a palindrome: C(7,5) = 21.
Why? Like part I, but you change whole SUBSTRINGS (of various lengths) at once with given costs. Cheapest conversion of source into target?
💡 Key idea Treat each distinct substring in the rules as a node and run Floyd–Warshall for chain costs. Then dp[i] = cheapest cost to fix the first i characters: either they already match, or a substring starting at i is converted by a rule chain.
Edge / failure case overlapping rules → -1
The rules only change the pieces 'bcd' and 'defgh', which overlap; they cannot be applied together: -1.
Why? Match a pattern against the whole text; '?' matches any one character and '*' matches any sequence (including none).
💡 Key idea Walk both strings. On '*' remember its position and how much text it covers; if a later mismatch happens, go back to the last star and let it swallow one more character of the text.
Edge / failure case "cb", "?a" → False
'?' matches 'c' but 'a' does not match 'b': no match.
Why? Swap fruits between two baskets (swap costs the smaller of the two values) so both baskets hold the same multiset. Cheapest total cost, or −1 if impossible.
💡 Key idea Every value must appear an even number of times overall. Work out the surplus values that must move; pair the smallest half of them with the largest half. Each swap costs min(value, 2 × the smallest value overall), because a cheap value can act as a 'go-between' using two swaps.
Edge / failure case [2,3,4,1], [3,2,5,1] → -1
4 and 5 appear an odd number of times in total, so the baskets can never be made equal: -1.
Why? Pick x below 2ⁿ to maximise (a XOR x) · (b XOR x). Give the answer modulo 1,000,000,007.
💡 Key idea Where a and b have the same bit, choose x so both become 1. Where they differ, exactly one of the two gets a 1: give it to the SMALLER number so the two stay as balanced as possible (a fixed sum gives the biggest product when balanced).
Edge / failure case a=1, b=6, n=3 → 12
x = 5 turns a = 1 into 4 and b = 6 into 3: 4 × 3 = 12, the best possible.
Why? Simulate the Snake game: the snake moves one cell per step, grows when it eats food, and the game ends if it hits a wall or itself. Report the score after every move (−1 when the game is over).
💡 Key idea Keep the body cells in a deque (head at the right) and in a set for quick collision checks. Each move: compute the new head; if no food is eaten drop the tail first; then check for walls and self-collision; add the new head.
Edge / failure case a move into the wall → [-1]
Moving up from the top-left corner leaves the board: game over (−1).
Why? Keep word counts with inc and dec, and get a most-counted and a least-counted word, all in O(1).
💡 Key idea Keep buckets (one per count) in a doubly linked list ordered by count; each bucket holds the words with that count. inc/dec move a word to the neighbouring bucket (creating or removing buckets as needed); the ends of the list give min and max.
Edge / failure case inc a, dec a → [None, None, '', '']
The only word was decremented to zero and removed, so both max and min are empty.
Why? Foods belong to cuisines and have ratings that can change. Ask for the highest-rated food of a cuisine (ties: alphabetically smaller name).
💡 Key idea Keep each food's current rating in a dictionary and a max-heap per cuisine of (−rating, name). When a rating changes push a new entry; when reading the top, drop entries whose rating is out of date.
Edge / failure case one-food cuisine → ['moussaka', None, 'moussaka']
With a single food in a cuisine it stays the best even after its rating drops.
Why? Can you make two strings equal by swapping two letters of ONE of them (at most once)?
💡 Key idea List the positions where the strings differ. Either there are none, or there are exactly two and they are mirror images of each other (a, b vs b, a).
Edge / failure case equal strings → True
The strings are already equal, so zero swaps are fine.
Why? Can you make s equal to goal by swapping exactly two letters of s?
💡 Key idea If s already equals goal you need a repeated letter to swap with itself. Otherwise there must be exactly two differing positions and they must cross-match.
Edge / failure case equal strings without a repeated letter → False
The strings are equal, but a swap needs two equal letters to keep them equal; 'a' and 'b' differ, so False.
Why? A point is 'valid' if it shares the x or the y coordinate with you. Which valid point is closest (Manhattan distance; smallest index on ties)?
💡 Key idea Loop through the points, skip invalid ones, and remember the one with the smallest |dx| + |dy|.
Edge / failure case no valid point → -1
The only point shares neither x nor y, so no point is valid: −1.
Why? Delete a block of consecutive letters from t so that what remains is a subsequence of s. The score is the length of the deleted block (from its first to its last position). Minimise it.
💡 Key idea Precompute where the suffix t[k:] can start in s (matching from the right). Then match prefixes of t greedily from the left; for each prefix choose the smallest k whose suffix starts after it. The deleted block is t[p:k].
Edge / failure case t already a subsequence → 0
t is already a subsequence of s, so nothing needs to be removed: score 0.
Why? The median of every window of k numbers.
💡 Key idea Keep the current window in a sorted list. Slide: remove the number leaving (binary search for its place) and insert the new one (insort); the median is read from the middle.
Edge / failure case huge numbers → [2.14748e+09]
Adding the two middle numbers could overflow in other languages; Python is fine: 2147483647.0.
Why? In one step you replace any character of t. Fewest steps to make t an anagram of s (same letters, any order)?
💡 Key idea Count letters in both. Every letter t has more of than s must be replaced: sum those surpluses.
Edge / failure case already anagrams → 0
The strings are already anagrams of each other: 0 changes.
Why? Remove one number; the rest shift left. In how many cases is the sum of the numbers at even positions equal to the sum at odd positions?
💡 Key idea After removing index i, everything to its right swaps parity. Track the running sums of even/odd positions on the left and the totals still on the right (with swapped roles) to test equality in O(1).
Edge / failure case all ones → 3
Removing any one leaves [1,1], whose even and odd sums are equal, so all 3 ways work.
Why? Evaluate an expression with + − × ÷ and parentheses (non-negative numbers). '2*(5+5*2)/3+(6/2+8)' = 21.
💡 Key idea Evaluate left to right with a stack of terms, remembering the previous operator: × and ÷ combine with the top of the stack at once, + and − push. A '(' makes a recursive call that returns the value of the bracket.
Edge / failure case division of a negative number → -1
−3 / 2 is truncated toward zero, giving −1 (not −2).
Why? Is there a triple (i<j<k) with nums[i] < nums[k] < nums[j]? [3,1,4,2] → 1, 4, 2 yes.
💡 Key idea Scan from the right with a decreasing stack, remembering the largest value ever popped (the '2'). If a number smaller than that '2' shows up on the left (the '1'), a pattern exists.
Edge / failure case increasing numbers → False
The numbers only go up, so there is no small–big–medium pattern.
Why? Remove a node from a tree: the tree falls apart into its children's subtrees and the rest. The node's score is the product of the sizes of those pieces. How many nodes share the highest score?
💡 Key idea Compute every subtree size. For a node, multiply its children's sizes and the size of the remaining part (n − own size, if not zero). Count how many nodes reach the maximum.
Edge / failure case two nodes → 2
Removing either node leaves a single piece of size 1, so both nodes tie with score 1.
Why? Give each node coordinates (row, column); list the values column by column from left to right, top to bottom within a column (equal positions sorted by value).
💡 Key idea Traverse the tree recording (column, row, value) — column −1 for a left child, +1 for a right child, row +1 per level. Sort all triples and group by column.
Edge / failure case two nodes in the same spot → [[4], [2], [1, 5, 6], [3], [7]]
5 and 6 share the same row and column, so the smaller value 5 comes first.
Why? List a tree's values column by column from left to right; inside a column go top to bottom, and left to right on the same row.
💡 Key idea BFS with each node's column (−1 for a left child, +1 for a right child) and append values to a dictionary by column; then output columns in order.
Edge / failure case a full tree → [[4], [9], [3, 0, 1], [8], [7]]
Within a column nodes are listed top to bottom, then left to right: column 0 is [3,0,1].
Why? A grid has walls (−1), gates (0) and empty rooms (a huge number). Fill every empty room with its distance to the nearest gate (unchanged if no gate can be reached).
💡 Key idea Start a BFS from ALL gates at once. Each time you reach an empty room for the first time, its distance is the current step count.
Edge / failure case a room walled off from the gate → [[2147483647, -1, 0]]
The room is cut off from the gate by a wall, so it keeps its huge 'unreachable' value.
Why? For every cell of a 0/1 grid, find the distance to the nearest 0.
💡 Key idea Put all 0 cells in a queue at distance 0 and expand outwards (BFS); each cell gets its distance the first time it is reached.
Edge / failure case one row → [[0, 1, 2, 3]]
A single row: the distance grows by 1 for each step away from the 0.
Why? The water level rises with time; you can swim to a neighbouring cell once the level reaches that cell's height. Earliest time to get from the top-left to the bottom-right?
💡 Key idea The cost of a route is the HIGHEST cell on it. Run Dijkstra with a min-heap keyed by 'highest cell so far'; the first time the goal is popped, that is the answer.
Edge / failure case 1×1 grid → 0
Start and end are the same cell: wait time 0.
Why? From '*' find the fewest steps to any food cell '#' (X is a wall, O is free).
💡 Key idea Plain BFS from the start; stop at the first food cell reached.
Edge / failure case food walled off → -1
A wall blocks the only way to the food: −1.
Why? For every road, say whether it lies on at least one shortest route from node 0 to node n−1.
💡 Key idea Compute shortest distances from node 0 and from node n−1. A road (u, v, w) is on a shortest route if dist0[u] + w + distEnd[v] equals the shortest total (in either direction).
Edge / failure case edges listed in either direction → [True, False, False, True]
Only the roads 0–2 and 2–3 form the shortest route (cost 3).
Why? A CPU runs one task at a time. Tasks arrive at given times with given running times; whenever it is free it picks the shortest available task (lowest index on ties). In what order do tasks run?
💡 Key idea Sort tasks by arrival. Keep a min-heap of (running time, index) of tasks that have arrived. When the heap is empty, jump the clock to the next arrival.
Edge / failure case a late task listed first → [1, 0]
The CPU is idle until time 1, runs task 1, and task 0 only appears at time 100.
Why? In a sorted list, return the k numbers closest to x (ties → smaller number), in sorted order.
💡 Key idea The answer is a window of k neighbours. Binary-search its start: compare x − arr[mid] with arr[mid+k] − x to decide whether the window should move right.
Edge / failure case x larger than everything → [4, 5]
x is beyond the right end, so the k largest numbers are the closest.
Why? Walk from node 0 and back to node 0 within maxTime; a path's quality is the sum of the values of the DIFFERENT nodes visited. Maximise it.
💡 Key idea Few nodes have a large degree, so depth-first search over all walks that fit in the time budget is fine. Count a node's value only the first time it is visited (a counter of visits per node).
Edge / failure case no time to move → 1
There is no time to leave node 0, so only its value counts.
Why? Move up/down/left/right to a strictly bigger number each step. How long can the path be?
💡 Key idea The longest path starting at a cell is 1 + the best among bigger neighbours. Cache it per cell, so every cell is solved once.
Edge / failure case all cells equal → 1
Equal numbers do not count as increasing, so no step is possible: length 1.
Why? Each worker can do jobs up to their ability and does exactly one job (several workers may do the same job). Maximise total profit.
💡 Key idea Sort jobs by difficulty and workers by ability. As abilities grow, keep the best profit among jobs the worker can do; every worker takes that best job.
Edge / failure case workers too weak → 0
No worker can do any job, so the total profit is 0.
Why? Two mice eat different pieces of cheese with different rewards. Mouse 1 must eat exactly k pieces, mouse 2 the rest. Maximise the total reward.
💡 Key idea Start with everything going to mouse 2. Switching a piece to mouse 1 changes the total by reward1 − reward2; do the k switches with the largest gain.
Edge / failure case k=0 → 2
The first mouse takes no cheese, so the second eats both: 1 + 1 = 2.
Why? Find the smallest number that uses exactly the same digits and is bigger than n (or −1; also −1 if it does not fit in 32 bits). 12 → 21.
💡 Key idea It is the 'next permutation' of the digits: find the rightmost digit smaller than its right neighbour, swap it with the next-larger digit on its right, and reverse the tail.
Edge / failure case an answer that overflows → -1
The next bigger arrangement, 9199999999, does not fit in a 32-bit integer, so the answer is −1.
Why? n orders each have a pickup and a delivery; a delivery must come after its own pickup. How many valid sequences of all 2n events exist (modulo 1,000,000,007)?
💡 Key idea Add orders one by one. With 2(i−1) events already placed, the new pickup and delivery can be placed in (2i−1)·(2i)/2 = i(2i−1) ways; multiply them all together.
Edge / failure case n=1 → 1
One order: pickup first, then delivery.
Why? Friends live at the 1s of a grid. Choose a meeting cell that minimises their total walking distance (Manhattan: |dx| + |dy|).
💡 Key idea Rows and columns are independent. The sum of absolute distances along one axis is smallest at the MEDIAN, so take the median row and the median column.
Edge / failure case two adjacent friends → 1
Meeting at either friend's house gives total distance 1.
Why? Two sorted lists of non-overlapping intervals. Return where they overlap.
💡 Key idea Compare the current interval of each list: the overlap (if any) is [max of starts, min of ends]. Then advance the list whose interval ends first.
Edge / failure case no overlap → []
The two intervals do not overlap: no intersections.
Why? Some computers are infected and the infection spreads along connections. You may remove ONE infected computer from the start list; which removal leaves the fewest infected in the end (smallest index on ties)?
💡 Key idea Group computers into connected components. Removing an infected node only helps if it is the ONLY infected node in its component — then the whole component is saved. Pick the one saving the biggest component.
Edge / failure case a tie → 0
Removing either infects the other alone; ties go to the smaller index: 0.
Why? Two strings are 'similar' if equal or if swapping two letters of one gives the other. Similarity chains form groups. How many groups?
💡 Key idea Compare every pair (they are all anagrams, so being similar means differing in 0 or 2 places) and union the similar ones. Count the components.
Edge / failure case duplicates → 1
Identical strings are similar (0 differences), so they form one group.
Why? Decide whether a string is a valid decimal number: optional sign, digits with at most one dot, optionally followed by e/E, an optional sign and digits.
💡 Key idea Scan once and remember: have I seen a digit, a dot, an 'e', and (after an 'e') a digit again? A sign is only allowed at the start or right after 'e'.
Edge / failure case dot after e → False
A dot is not allowed after the exponent: False.
Why? Find the smallest gap between an occurrence of word1 and an occurrence of word2 in a list (the two words may be the same word, then two different occurrences are needed).
💡 Key idea Scan once and remember the last position of each word. When both words are the same, compare with the previous occurrence of that word instead.
Edge / failure case same word twice → 3
Two different occurrences of the same word: positions 1 and 4, gap 3.
Why? Add up the sums of all subarrays whose length is odd.
💡 Key idea Number i starts in (i+1) ways and ends in (n−i) ways, so it lies in (i+1)(n−i) subarrays; about half of them (rounded up) have odd length.
Edge / failure case 3 numbers → 66
[10]+[11]+[12]+[10,11,12] = 66.
Why? Apply f(x) = a·x² + b·x + c to every number of a sorted list and return the results sorted.
💡 Key idea f is a parabola. If it opens upward (a ≥ 0) the biggest results are at the two ends of the sorted input, if it opens downward the smallest are. Fill the answer from the end (or start) taking the extreme end each time.
Edge / failure case a < 0 → [-23, -5, 1, 7]
The parabola opens downward, so the extreme numbers give the smallest results.
Why? Can the number c be written as a² + b² with whole numbers a and b?
💡 Key idea Put one pointer at 0 and one at √c. If the sum of squares is too small move the left up, if too big move the right down.
Edge / failure case c=0 → True
0 = 0² + 0².
Why? Count the triples of numbers in the list that can be the three sides of a triangle.
💡 Key idea Sort. Fix the longest side nums[k]; with pointers i < j below it, if nums[i] + nums[j] > nums[k] then every i' between i and j works too, so add j − i and move j down; otherwise move i up.
Edge / failure case no triangle → 0
Every triple has a long side at least as long as the other two together: 0.
Why? Typing a name, a key may have been held down so a letter repeats. Could the typed text have come from the name?
💡 Key idea Walk through the typed text with a pointer into the name: a matching letter advances both; otherwise it must be a repeat of the previous typed letter.
Edge / failure case missing letter → False
The typed text has only one 'e' where the name needs two.
Why? Count the windows of k consecutive numbers whose average is at least the threshold.
💡 Key idea Average ≥ threshold is the same as sum ≥ k·threshold. Slide the window by adding the new number and subtracting the old one.
Edge / failure case mixed numbers → 6
Six windows have an average of at least 5.
Why? Among substrings with at most maxLetters distinct letters and length between minSize and maxSize, find the maximum number of times any one substring occurs.
💡 Key idea If a longer substring occurs t times, its first minSize letters occur at least t times. So only substrings of length exactly minSize need to be counted.
Edge / failure case overlapping occurrences → 2
'aaa' occurs twice, overlapping.
Why? List every 10-letter piece of the DNA string that occurs more than once.
💡 Key idea Slide a 10-letter window; remember the pieces seen. When a piece appears a second time, report it (only once).
Edge / failure case 11 equal letters → ['AAAAAAAAAA']
The window 'AAAAAAAAAA' appears twice but is reported once.
Why? Count the triples of positions i < j < k whose three numbers add up to a multiple of d.
💡 Key idea Sweep k from left to right. Keep a count of the remainders (mod d) of all pair sums (i, j) with j < k. The triples ending at k are those pairs whose remainder is (−nums[k]) mod d. Then add the pairs (i, k) to the map.
Edge / failure case no triple → 0
1 + 1 + 1 = 3 is odd: no divisible triple.
Why? Numbers are pushed onto a stack in the order 'pushed' and popped in some moments. Could the pops have happened in exactly the order 'popped'?
💡 Key idea Push the numbers one by one; whenever the top equals the next number that must be popped, pop it. At the end the stack must be empty.
Edge / failure case impossible order → False
After 4, 3, 5 are popped the top is 2 but 1 must come next.
Why? Find the length of the longest stretch of a bracket string that is correctly balanced.
💡 Key idea Keep a stack of indices, starting with −1 as a base. On '(' push its index; on ')' pop — if the stack becomes empty push the current index as the new base, otherwise the stretch from the new top to here is balanced.
Edge / failure case empty string → 0
Empty string: no pair.
Why? Count the subarrays whose first and last numbers both equal the biggest number in the subarray.
💡 Key idea Keep a stack of (value, how many times it appears) that is decreasing. For a new number pop every smaller value; if the top equals it, increase its count. Each subarray ending here and starting at one of those equal numbers is valid, so add the top's count.
Edge / failure case equal numbers → 6
All 6 subarrays (3 singles, 2 pairs, 1 triple) start and end with the maximum.
Why? Reorder a linked list L0→L1→…→Ln into L0→Ln→L1→Ln−1→… in place.
💡 Key idea Find the middle, reverse the second half, then weave the two halves together one node at a time.
Edge / failure case five nodes → [1, 5, 2, 4, 3]
With an odd length the middle node ends up last.
Why? Repeatedly remove all the leaves of a tree and list the removed values round by round, until the tree is gone.
💡 Key idea A node is removed in round (its height + 1), where a leaf has height 0 and a node's height is 1 + the bigger height of its children. Compute heights bottom-up and put every node in its group.
Edge / failure case one node → [[1]]
A single node is a leaf and is removed in the first round.
Why? Flip the tree: the leftmost node becomes the root, its parent becomes its right child, and the parent's old right child becomes its left child. Return the new root.
💡 Key idea Walk down the left spine. For each node, point its left at the previous node's old right child and its right at the previous node, remembering what you overwrite.
Edge / failure case one node → [1]
A single node stays as it is.
Why? In this special tree every node has 0 or 2 children and equals the smaller of its two children. Return the second smallest distinct value in the tree, or −1.
💡 Key idea The root is the minimum. The answer is the smallest value bigger than the root. Going below a node whose value is already bigger than the root is pointless (children are even bigger), so stop there.
Edge / failure case all equal → -1
Every value is 2: there is no second distinct value.
Why? In a binary search tree return the k values closest to a target number.
💡 Key idea An in-order walk visits values in ascending order. Keep a window of the k best so far; when the next value is closer than the window's smallest, slide the window, otherwise every later value is even farther, so stop.
Edge / failure case target beyond the tree → [3, 4, 5]
The target is above everything, so the k largest values win.
Why? Return the largest value on each level of a binary tree.
💡 Key idea Process the tree one level at a time and take the max of each level.
Edge / failure case empty tree → []
Empty tree: no rows.
Why? Each description [parent, child, isLeft] says that child hangs on the left (1) or right (0) of parent. Build the tree and return its root.
💡 Key idea Create each node once in a dictionary and link it. The root is the only node that is never a child.
Edge / failure case one edge → [1, 2]
One description: a root with a left child.
Why? Insert a new value into a binary search tree and return the tree.
💡 Key idea Go left if the value is smaller, right otherwise, until you reach an empty spot — attach the new node there.
Edge / failure case empty tree → [5]
Inserting into an empty tree creates the root.
Why? A list contains numbers and further lists. A number's weight is (maxDepth − its depth + 1): the DEEPEST numbers weigh 1. Return the weighted sum.
💡 Key idea Go level by level. Keep a running sum of all numbers seen so far and add it to the total after each level: shallow numbers get added once per extra level, which is exactly their weight.
Edge / failure case [1,[4,[6]]] → 17
6 is the deepest (weight 1), 4 has weight 2, 1 has weight 3: 6 + 8 + 3 = 17.
Why? A list contains numbers and further lists. Each number counts (number × how deep it is), the outer level having depth 1. Return the total.
💡 Key idea Recurse into every inner list with depth + 1 and multiply each number by the current depth.
Edge / failure case [1,[4,[6]]] → 27
1·1 + 4·2 + 6·3 = 27.
Why? A 4-wheel lock starts at 0000; one move turns one wheel by one digit (9↔0 wraps). Some states are dead ends. Find the fewest moves to reach the target, or −1.
💡 Key idea Every state has 8 neighbours. Breadth-first search from '0000', skipping dead ends and visited states, finds the shortest path.
Edge / failure case start is a dead end → -1
The start is itself a dead end: −1.
Why? Can the nodes of an undirected graph be split into two groups so that every edge joins the two groups?
💡 Key idea Colour a start node 0, its neighbours 1, their neighbours 0, … If an edge ever joins two nodes of the same colour, it is impossible. Do this for every component.
Edge / failure case disconnected graph → True
Isolated nodes and one edge: easily split in two groups.
Why? Each node has a colour letter. The value of a path is the count of its most frequent colour. Find the largest path value in the directed graph, or −1 if it has a cycle.
💡 Key idea Process nodes in topological order (Kahn's algorithm). For each node keep, per colour, the best count of that colour on a path ending there; push these counts to its successors. If fewer than n nodes are processed, there is a cycle.
Edge / failure case cycle → -1
A self-loop is a cycle: −1.
Why? k workers must move n boxes over a one-lane bridge, each with their own times (cross left→right, pick up a box, cross right→left, put it down). Rules: workers waiting on the right cross first; among waiting workers the LEAST efficient (bigger left+right time, then bigger index) goes first. Return when the last box arrives on the left.
💡 Key idea Simulate time. Keep heaps for waiting-left, waiting-right, busy-left and busy-right workers. At each step release the workers whose work has finished, let one cross by the rules, and if nobody can move, jump the clock to the next finishing time.
Edge / failure case two workers, three boxes → 50
The fast worker does most of the work but must wait for his own box and put-down times.
Why? k sorted lists are given. Find the smallest range [a, b] that contains at least one number from every list.
💡 Key idea Keep the current smallest element of each list in a min-heap and remember the current maximum. The range is [heap min, max]. Then advance the list that owns the minimum — any better range needs that list to move on.
Edge / failure case one number per list → [1, 3]
Each list has a single number so the range must cover 1 to 3.
Why? Servers have weights; task j arrives at second j and needs tasks[j] seconds. Each task goes to the free server with the smallest weight (smaller index on ties); if none is free, it waits and takes the first server that frees up. Return the server used by each task.
💡 Key idea Keep two heaps: free servers (by weight, index) and busy servers (by finishing time). Move finished servers back to free before assigning each task, and jump the clock to the earliest finishing time when nobody is free.
Edge / failure case servers busy → [1, 4, 1, 4, 1, 3, 2]
The lightest free server is used; when all are busy the task waits for the first one to finish.
Why? Given sorted letters and a target letter, return the smallest letter that is strictly bigger; if none, wrap around to the first letter.
💡 Key idea bisect_right gives the position of the first letter bigger than the target. Using index % length handles the wrap-around.
Edge / failure case target at the end → 'c'
Nothing is bigger than 'j', so wrap around to the first letter.
Why? Two sorted lists (negatives and zeros allowed). Look at all products a·b with a from the first list and b from the second; return the k-th smallest.
💡 Key idea Guess a value v and count how many products are ≤ v: for each a, the matching b's form a prefix or suffix of the second list (found with bisect, flipping the direction for negative a). Binary search the smallest v whose count reaches k.
Edge / failure case negatives and zero → 0
The 8 products sort to −16,−8,−8,−4,0,0,6,12; the 6th is 0.
Why? Decide whether a positive integer is a perfect square, without using a square-root function.
💡 Key idea Binary search a number r in [1, n] with r·r compared to n.
Edge / failure case not a square → False
14 lies between 3² and 4².
Why? A sorted list (duplicates allowed) was rotated. Is the target in it?
💡 Key idea At each step one half is sorted: check whether the target lies inside it. If the left, middle and right values are equal we cannot tell which half is sorted, so shrink both ends by one.
Edge / failure case rotated with duplicates → True
With many equal values the sorted half cannot be determined, so the search shrinks by one on both sides.
Why? Can the numbers be split into k groups that all have the same sum?
💡 Key idea Each group must sum to total/k. Place the numbers (biggest first) one by one into buckets, skipping buckets that would overflow and buckets whose current sum was already tried.
Edge / failure case total not divisible by k → False
The total 10 is not divisible by 3.
Why? List all ways to write n as a product of numbers between 2 and n−1 (order inside a product does not matter).
💡 Key idea Pick a smallest factor f ≥ the previous one, with f ≤ √(remaining). Record [path, f, remaining/f] and then keep factoring the remainder with factors ≥ f.
Edge / failure case a prime → []
37 is prime: no factorisation.
Why? List all distinct orderings of a list that may contain repeated numbers.
💡 Key idea Sort the numbers. When choosing the next number, skip a value equal to the previous one if that previous copy is not currently in use — otherwise the same ordering appears twice.
Edge / failure case all equal → [[2, 2]]
Two equal numbers give only one ordering.
Why? From a list with duplicates, find all unique combinations (each element used at most once) that add up to the target.
💡 Key idea Sort the list. At each level try the candidates from the current position onward, skipping a value equal to the previous one at the same level (it would repeat a combination), and stop when the remainder goes negative.
Edge / failure case repeated 2s → [[1, 2, 2], [5]]
{1,2,2} and {5}; the three 2s do not create duplicate answers.
Why? Insert +, − or × (or nothing) between the digits of a number string so the expression equals the target; list all such expressions.
💡 Key idea Build the expression left to right, remembering its value and the last term. For '×' replace the last term: value − last + last·n. Numbers with a leading zero (other than 0 itself) are not allowed.
Edge / failure case a zero digit → ['1*0+5', '10-5']
'1*0+5' and '10-5'; '05' is not allowed because of the leading zero.
Why? Find the contiguous part of the list with the largest product.
💡 Key idea A negative number can turn the smallest product into the biggest. So keep both the max and the min product of subarrays ending at the current number.
Edge / failure case a zero in the middle → 0
The zero resets the product; the best is 0 (not −1 or −2).
Why? Find the length of the longest palindrome that can be read from the string by deleting letters (without reordering).
💡 Key idea dp[i][j] = answer for s[i..j]. If the end letters match, they wrap the answer for the inside (+2); otherwise drop one end and take the better.
Edge / failure case one letter → 1
A single letter is a palindrome of length 1.
Why? Two players take turns choosing a number from 1..m without reuse and add it to a shared total; whoever reaches the target first wins. Can the first player force a win?
💡 Key idea State = which numbers are used (a bitmask); the total is determined by it. A player wins if some choice reaches the target or leaves the opponent in a losing state.
Edge / failure case target 0 → True
The target is already reached: the first player wins immediately.
Why? Count the DIFFERENT non-empty palindromes that can be read from a string over a, b, c, d (modulo 1,000,000,007).
💡 Key idea dp[i][j] for s[i..j]. If the end letters differ it is inclusion–exclusion. If they match letter x, look for the next and last x inside: none → the inside doubled plus 'x' and 'xx'; one → doubled plus 'xx'; several → doubled minus the ones counted twice.
Edge / failure case all the same letter → 3
'a', 'aa' and 'aaa' — equal palindromes are counted once.
Why? Each fruit has a price and a tastiness; you may buy each at most once, with a budget, and you have a few coupons that halve a fruit's price (rounded down), at most one coupon per fruit. Maximise the total tastiness.
💡 Key idea A 0/1 knapsack with an extra dimension: dp[amount][coupons] = best tastiness. For every fruit try 'skip', 'buy at full price' and 'buy with a coupon'.
Edge / failure case two coupons → 28
Coupons make 15 cost 7 and 7 cost 3: both fit in 10, tastiness 8 + 20.
Why? Start with val = 1. For each number choose: multiply val by it, divide val by it (exactly, as a fraction), or leave val. Count the choice sequences that end with val = k.
💡 Key idea Keep a dictionary {value: number of ways} of every fraction reachable so far; each number sends every entry to three new values. The answer is the count stored for k.
Edge / failure case a single 1 → 3
Multiplying by 1, dividing by 1 or leaving it all keep val = 1: 3 sequences.
Why? Paint a row of houses with one of k colours (a different cost for each house and colour); neighbouring houses must differ. Find the minimum total cost.
💡 Key idea For each house you only need the cheapest and second cheapest total from the previous house: use the cheapest unless it has the same colour, then use the second.
Edge / failure case one house → 8
One house and one colour: just its cost.
Why? A tree with weighted edges: remove edges so every node keeps at most k edges, and the total weight of the kept edges is as big as possible.
💡 Key idea For each node return two values: the best total in its subtree if the edge to the parent is NOT kept (it may keep k child edges), and if it IS kept (only k−1 child edges left). For each child, keeping the edge gains (child's 'kept' value + weight − child's 'not kept' value); take the largest positive gains.
Edge / failure case star with k=1 → 3
The centre may keep only one edge: the heaviest one (3).
Why? How many structurally different binary search trees store the values 1..n?
💡 Key idea Pick a root j. The j−1 smaller values form its left subtree and the n−j larger ones its right: count[n] = Σ count[j−1]·count[n−j].
Edge / failure case n=1 → 1
One value: one tree.
Why? Some houses are already painted. Paint the rest (each colour has its own cost per house) so that exactly 'target' groups of equal-coloured neighbouring houses exist. Minimise the cost, or return −1.
💡 Key idea State = (house index, colour of the previous house, neighbourhoods so far). A new neighbourhood starts whenever the colour changes. Try every allowed colour for the current house.
Edge / failure case impossible target → -1
The painted houses already form 4 neighbourhoods: target 3 is impossible.
Why? Numbers 1..n sit in order. Some pairs [a, b] are 'conflicting': a subarray may not contain both. You must delete exactly one pair; count the subarrays that contain no remaining pair, as large as possible.
💡 Key idea For a right end r, the valid left ends are those after the biggest 'left number' of any pair that already fits inside [.., r]. Track the top two such left numbers. Deleting the pair that owns the top one lifts every such r from top1 to top2 — add up those gains per pair and take the best.
Edge / failure case three pairs → 12
Removing the best pair leaves 12 valid subarrays.
Why? Pick as many non-overlapping substrings as possible, each a palindrome of length at least k.
💡 Key idea Any palindrome longer than k+1 contains a palindrome of length k or k+1 in its middle that ends earlier. So only lengths k and k+1 matter: scan left to right and take a palindrome of those lengths as soon as one ends (and starts after the last pick).
Edge / failure case no palindromes → 0
No palindrome of length 2 or more exists in the string: 0.
Why? An inside position is 'special' if its number is bigger than both neighbours. You may add 1 to any number any number of times. First make as many positions special as possible, then use as few additions as possible. Return that number of additions.
💡 Key idea At most (n−1)/2 positions can be special since two neighbours cannot both be peaks. Making position i a peak costs max(0, max(left, right) + 1 − nums[i]) (raise only i). For odd n the peaks are forced at 1,3,5,…; for even n they are 1,3,…,2j−1 then 2j+2,…,n−2 — try every split j with prefix/suffix sums.
Edge / failure case one valley → 5
The middle 1 has to be raised to 6 to beat both 5s: 5 additions.
Why? A string of '(', ')' and '*' where each '*' may be '(', ')' or nothing. Can it be a balanced bracket string?
💡 Key idea Track the smallest and largest possible number of unclosed '(' (lo and hi). '(' raises both, ')' lowers both, '*' lowers lo and raises hi. If hi ever goes below 0 it fails; lo never goes below 0; at the end lo must be 0.
Edge / failure case closes first → False
A ')' first can never be matched.
Why? Cut a string into as many pieces as possible so that every letter appears in at most one piece. Return the piece lengths.
💡 Key idea Record the last position of each letter. Walk through; a piece ends when the walk reaches the farthest last position of all letters seen in the piece.
Edge / failure case one big piece → [10]
'e' appears at both ends, so the whole string is one piece.
Why? n bulbs start off. In round r you toggle every r-th bulb. How many are on after n rounds?
💡 Key idea Bulb i is toggled once for each divisor of i. Only perfect squares have an odd number of divisors, so the answer is the number of squares ≤ n = ⌊√n⌋.
Edge / failure case n=0 → 0
No bulbs at all: 0 are on.
Why? Delete as few numbers from nums as possible so that the smallest remaining number divides every number of numsDivide.
💡 Key idea A number divides all of numsDivide exactly when it divides their gcd. Find the smallest such number in nums; everything smaller than it must be deleted.
Edge / failure case impossible → -1
The gcd of the second list is 2 and no number of the first list divides it: −1.
Why? A cinema has n rows of 10 seats. A family of four needs four adjacent seats in one row; an aisle splits seats 3|4 and 7|8, so only seats 2–5, 4–7 and 6–9 work. Given the reserved seats, how many families fit?
💡 Key idea Rows without reservations hold 2 families. For each reserved row use a bitmask and check the three blocks: left+right free → 2 families, any single block free → 1.
Edge / failure case partly blocked rows → 4
Rows 2 and 3 are empty (2 families each); rows 1 and 4 are partly blocked but each still fits one family in the middle block... in total 4.
Why? You only have rand7() (uniform 1..7). Build rand10() that returns uniform 1..10.
💡 Key idea Two calls give a uniform number 1..49: (a−1)·7 + b. Keep it if it is ≤ 40 (an exact multiple of 10 outcomes), mapping to 1 + (x−1) mod 10; otherwise try again.
Edge / failure case 30 calls → True
Every returned value lies between 1 and 10.
Why? Reverse the digits of an integer (keeping the sign). If the result does not fit in a signed 32-bit integer, return 0.
💡 Key idea Reverse the absolute value's digits and put the sign back; compare against −2³¹ and 2³¹−1.
Edge / failure case overflow → 0
The reversed number 9646324351 does not fit in 32 bits: 0.
Why? Multiply two matrices that contain mostly zeros.
💡 Key idea For every non-zero mat1[i][k], add it times row k of mat2 into row i of the answer — and skip the whole inner loop for zeros.
Edge / failure case 1×1 with a zero → [[0]]
Zero times anything is zero.
Why? Build a stack that can also report the biggest value (peekMax) and remove the top-most biggest value (popMax).
💡 Key idea Store with every pushed value the maximum of everything below it. popMax digs down to that maximum, removes it and pushes the dug-up values back.
Edge / failure case max below the top → [2, 1, 1]
The biggest value (2) is not on top: popMax digs it out and the 1 stays.
Why? Store a list of words once, then answer many queries: the smallest gap between a position of word1 and a position of word2.
💡 Key idea Remember each word's sorted positions. A query walks both lists with two pointers, always advancing the smaller position.
Edge / failure case two words → [1]
Neighbouring words are 1 apart.
Why? A bag of numbers (duplicates allowed) with insert, remove one copy, and getRandom (each stored copy equally likely), all in O(1) on average.
💡 Key idea Keep the values in an array (for random picks) and, for every value, the set of its positions. To remove, move the LAST array element into the freed slot and fix both position sets.
Edge / failure case remove from empty → [False, True, False, 5]
Removing from an empty bag fails; adding a duplicate returns False; the only value is 5.
Why? A thread-safe queue with a maximum size: enqueue waits while it is full, dequeue waits while it is empty.
💡 Key idea One lock with a condition variable. Wait in a loop until there is room (or an item), do the operation, then wake everyone up.
Edge / failure case capacity 1 → [None, 1, 7, 0]
Capacity 1: after enqueue the queue is full, after dequeue it is empty again.
Why? A structure with add(number) and find(value): is there a pair of stored numbers adding up to value?
💡 Key idea Keep a count of every number. For find, for each stored x look for value − x (if it equals x itself, we need at least two copies).
Edge / failure case duplicate needed → [None, False, None, True]
One 3 cannot be used twice; with a second 3 it works.
Why? Design a class that returns the original array on reset() and a uniformly random shuffle on shuffle().
💡 Key idea Fisher–Yates: go from the end to the start and swap each position with a random position at or before it. Every permutation is equally likely.
Edge / failure case one number → [[7], [7]]
One number has only one arrangement.
Why? There are n nodes and some undirected edges. How many separate groups of connected nodes are there?
💡 Key idea Start with n groups. Every edge that joins two different groups merges them and lowers the count by one.
Edge / failure case a chain → 1
The three edges chain all four nodes into one group.
Why? Follow a program: 'add' adds a value to the score and moves on to the next instruction, 'jump' moves by a value. Stop when you leave the program or would run an instruction a second time. Return the score.
💡 Key idea Just simulate, remembering which instructions already ran.
Edge / failure case a loop → 0
The program jumps back to the instruction 1 and 2, then reaches 3 again: stop.
Why? Return the first numRows rows of Pascal's triangle (each number is the sum of the two above it).
💡 Key idea Each new row starts and ends with 1; the inside numbers are sums of neighbouring numbers of the previous row.
Edge / failure case one row → [[1]]
Only the first row.
Why? nums is a permutation of 0..n−1. Starting at index i, repeatedly jump to nums[i]; the set of visited numbers stops when a value repeats. Find the longest such set.
💡 Key idea A permutation splits into disjoint cycles. Walk each cycle once, marking visited numbers, and keep the largest length.
Edge / failure case all fixed points → 1
Every index points to itself: cycles of length 1.
Why? Return 'IPv4', 'IPv6' or 'Neither' for a text.
💡 Key idea IPv4: four numbers 0–255 separated by dots, written without leading zeros. IPv6: eight groups of 1–4 hexadecimal digits separated by colons.
Edge / failure case bad IPv6 → 'Neither'
An empty group and the letter 'j' make it invalid: Neither.
Why? A file can only be read 4 characters at a time with read4(buf4). Implement read(buf, n) that reads up to n characters into buf and returns how many were read.
💡 Key idea Call read4 repeatedly, copy only as many characters as are still needed, and stop at n or at the end of the file.
Edge / failure case 5 characters → [5, 'abcde']
The file is read in chunks of 4 then 1.
Why? Compress a string: replace each run of the same letter by (count)(letter), with counts at most 9 (longer runs are split).
💡 Key idea Walk through the string; for each run take up to 9 equal letters at a time and write count + letter.
Edge / failure case no repeats → '1a1b1c'
Every run has length 1.
Why? A secret word is among a list of words. master.guess(word) tells how many letters match in position. Find the secret in at most 10 guesses.
💡 Key idea Keep the list of candidates consistent with all answers so far. Guess the word whose worst-case group of equal match counts is smallest (minimax); then keep only candidates with the same match count against that guess.
Edge / failure case two words → [True, True]
Two candidates: found within a couple of guesses.
Why? Players A and B alternate placing marks on a 3×3 board (A first). Given the moves, report 'A' or 'B' if someone has three in a row, otherwise 'Draw' (board full) or 'Pending'.
💡 Key idea Keep a counter per row, column and diagonal: +1 for A, −1 for B. A line is won when its counter reaches ±3.
Edge / failure case a draw → 'Draw'
The board is full and nobody has a line: Draw.
Why? Find the longest non-empty proper prefix of a string that is also a suffix (it may overlap).
💡 Key idea The KMP failure array lps[i] gives, for each position, the length of the longest proper prefix of s[:i+1] that is also a suffix; the last value is the answer.
Edge / failure case no happy prefix → ''
No prefix is also a suffix: empty string.
Why? People are alive from birth up to (not including) death. Which year (the earliest on ties) has the highest population?
💡 Key idea Add +1 at each birth year and −1 at each death year in a difference array; the running sum is the population. Take the first maximum.
Edge / failure case overlapping lives → 1960
In 1960 two people are alive (the first one dies in 1961); the earliest year with the maximum.
Why? Split every word by a separator character and return all the non-empty pieces in order.
💡 Key idea Use the built-in split on each word and keep only the non-empty parts.
Edge / failure case empty pieces → []
Only empty pieces: nothing is returned.
Why? Count the non-empty subarrays that can be removed so that the numbers left over are strictly increasing.
💡 Key idea Let the increasing prefix end at i. Removing a part that starts at or before i+1 keeps a prefix of length 0..i+1. For each increasing suffix start j, shrink the prefix pointer until it is smaller than nums[j] and count the choices.
Edge / failure case a falling array → 3
Only removing a long enough part works: 3 ways.
Why? The same question for long arrays: count the non-empty subarrays whose removal leaves a strictly increasing array.
💡 Key idea Same two-pointer idea in O(n): the increasing prefix ends at i; walk the increasing suffix from the right, pulling i back while nums[i] ≥ nums[j], and add i + 2 choices each time.
Edge / failure case already increasing → 10
The array is already increasing, so any non-empty subarray can go: 4·5/2 = 10.
Why? Can the string become a palindrome after deleting at most one character?
💡 Key idea Compare from both ends. At the first mismatch you may skip either the left or the right letter; check whether the rest is a palindrome.
Edge / failure case not fixable → False
One deletion cannot fix both mismatches.
Why? A number is lonely if it appears exactly once and neither x−1 nor x+1 appears. List all lonely numbers.
💡 Key idea Count everything once; then check each number's count and its two neighbours.
Edge / failure case a repeated number → [1, 5]
3 appears twice, so only 1 and 5 are lonely.
Why? Is there a subarray of length at least 2 whose sum is a multiple of k?
💡 Key idea Two prefix sums with the same remainder mod k enclose a subarray whose sum is a multiple of k. Remember the first index of each remainder and check the gap is at least 2.
Edge / failure case no multiple → False
No stretch of two or more numbers adds up to a multiple of 13.
Why? Words are written one after another, each followed by '#'. A word may share its letters with a longer word that ends the same way. Find the shortest total length.
💡 Key idea A word that is a suffix of another word is free. Put all words in a set, delete every proper suffix of every word, and add up (length + 1) of what remains.
Edge / failure case single word → 2
One word: 't#' has length 2.
Why? In an alien language the letters have a different alphabetical order. Are the given words sorted in that order?
💡 Key idea Map each letter to its rank. Compare each word with the next by their rank lists (lists compare like dictionary order; a longer word loses to its own prefix).
Edge / failure case prefix order → False
'app' is a prefix of 'apple' and must come first.
Why? Given 5 cards (ranks and suits) return the best hand: 'Flush' (all one suit), 'Three of a Kind' (three of one rank), 'Pair' (two of one rank) or 'High Card'.
💡 Key idea One suit → Flush. Otherwise count the ranks and look at the biggest count.
Edge / failure case four of a kind → 'Three of a Kind'
Four equal ranks include three of a kind.
Why? Return the first letter whose second occurrence appears before the second occurrence of any other letter.
💡 Key idea Scan left to right with a set; the first letter already in the set is the answer.
Edge / failure case end repeats → 'd'
Only 'd' repeats.
Why? Repeatedly delete two equal neighbouring letters until none are left. Return the final string.
💡 Key idea Use a stack: if the new letter equals the top, pop; otherwise push.
Edge / failure case everything cancels → ''
Eight equal letters cancel in pairs completely.
Why? For each number of nums1 (a subset of nums2), find the first bigger number to its right in nums2, or −1.
💡 Key idea Scan nums2 once with a decreasing stack: when a bigger number arrives, it is the answer for every smaller number popped. Store answers in a dictionary.
Edge / failure case second example → [3, -1]
3 is the next bigger after 2; nothing is bigger than 4.
Why? Evaluate a Lisp-like expression with (add a b), (mult a b) and (let v1 e1 v2 e2 … expr), where let creates variables visible only inside it (inner definitions shadow outer ones).
💡 Key idea Tokenise, then evaluate recursively. Keep a stack of scopes: let pushes a new scope that is popped when the let ends; variable lookup searches from the innermost scope outwards.
Edge / failure case variables used later → 4
b2 is defined from a1, then returned as the last expression: 4.
Why? Remove the fewest brackets from a string so that its brackets are balanced; return the result.
💡 Key idea Scan with a stack of '(' positions. A ')' with an empty stack is unmatched (remove it); at the end the '(' still on the stack are unmatched (remove them).
Edge / failure case all unmatched → ''
None of the brackets can be matched.
Why? You get only a pointer to a node (not the last) in a singly linked list and must delete that node.
💡 Key idea You cannot reach the previous node, so overwrite this node's value with the next node's value and skip the next node.
Edge / failure case delete the 1 → [4, 5, 9]
Deleting a node near the end.
Why? Turn a sorted linked list into a height-balanced binary search tree.
💡 Key idea The middle node is the root; the part before it builds the left subtree and the part after builds the right. Find the middle with slow/fast pointers and cut the list there.
Edge / failure case two nodes → [2, 1]
Two nodes: the second becomes the root with the first as its left child.
Why? Remove every node with a given value from a linked list.
💡 Key idea Put a dummy node before the head so deleting the first node is no special case; skip nodes that match.
Edge / failure case all removed → []
Every node is removed.
Why? Return the number of edges on the path between the nodes with values p and q in a binary tree.
💡 Key idea Find their lowest common ancestor; the distance is the depth of p plus the depth of q measured from that ancestor.
Edge / failure case p equals q → 0
A node is at distance 0 from itself.
Why? Is a binary tree height-balanced (the two subtrees of every node differ in height by at most 1)?
💡 Key idea Compute heights bottom-up; return −1 as soon as any subtree is unbalanced so the answer propagates upwards.
Edge / failure case a lopsided tree → False
The left branch is two levels deeper than the right branch.
Why? Rebuild a binary tree (distinct values) from its preorder and postorder lists.
💡 Key idea The first preorder value is the root; the second is the root of the left subtree. Find that value in postorder to learn how many nodes the left subtree has, then split both lists and recurse.
Edge / failure case one node → [1]
A single node.
Why? Change every value of a binary search tree to (its value + the sum of all bigger values).
💡 Key idea A reverse in-order walk (right, node, left) visits values from biggest to smallest. Keep a running total and add it to each node as you pass.
Edge / failure case two nodes → [1, None, 1]
0 + 1 = 1 and 1 stays 1.
Why? Units are connected as a tree: one unit of A equals some number of units of B. Answer queries 'how many units of B equal one unit of A' as a fraction modulo 10⁹+7.
💡 Key idea Pick unit 0 as the root and compute for every unit how many of it equal one root unit (multiply by the factor going down an edge, by its modular inverse going up). A query is ratio[b] / ratio[a] — a division done with a modular inverse.
Edge / failure case a chain → [6, 166666668]
0 → 2 is 2·3 = 6, and back is 1/6 modulo 10⁹+7.
Why? Hire exactly k workers. Each worker has a quality and a minimum wage. Everyone is paid in proportion to quality (the same rate for all), and nobody earns less than their minimum. Minimise the total pay.
💡 Key idea The rate must be at least wage/quality for everyone hired, so the group's rate is the largest wage/quality ratio in it. Sort by ratio; going through workers, the current ratio is the group's rate, and we want the k smallest qualities seen so far (a max-heap drops the largest).
Edge / failure case five workers → 30.6667
The best group has total pay about 30.67.
Why? k servers. Request i arrives at time arrival[i], takes load[i], and goes to server i mod k if free, otherwise to the next free server (wrapping around); if none is free it is dropped. Return the servers that handled the most requests.
💡 Key idea Keep a sorted list of free server ids and a heap of busy servers by finish time. Release finished servers, then use bisect to find the first free id ≥ i mod k (wrapping to the smallest).
Edge / failure case no overlaps → [0, 1, 2]
Each of the three requests goes to its own server.
Why? Buildings are rectangles [left, right, height]. Return the outline of their skyline as the key points where the height changes.
💡 Key idea Sweep over the x positions: at a building's left edge add it to a max-heap, at its right edge it becomes stale. The skyline height at x is the top of the heap after removing expired buildings; report a point whenever the height changes.
Edge / failure case touching buildings → [[0, 3], [5, 0]]
Two touching buildings of the same height form one block.
Why? Every row and every column of an n×n matrix is sorted ascending. Find the k-th smallest number.
💡 Key idea Guess a value v and count the numbers ≤ v by walking from the bottom-left corner (move up when too big, right otherwise). Binary search the smallest v whose count is at least k.
Edge / failure case 1×1 matrix → -5
The only element is the first smallest.
Why? Packages must be shipped in the given order, a ship carrying up to some capacity per day. What is the smallest capacity that ships everything within D days?
💡 Key idea Guess a capacity and simulate (greedily fill each day). The capacity is at least the heaviest package and at most the total; binary search the smallest that fits the days.
Edge / failure case uneven packages → 6
Capacity 6: [3,2], [2,4], [1,4].
Why? Versions 1..n: once a version is bad, all later ones are bad. Using isBadVersion(v), find the first bad one with as few calls as possible.
💡 Key idea Binary search: if the middle version is bad the answer is at or before it, otherwise after it.
Edge / failure case n=1 → 1
Only one version and it is bad.
Why? Split a list into k non-empty consecutive parts so that the largest part-sum is as small as possible.
💡 Key idea Guess the limit L for a part-sum and greedily cut whenever adding the next number would exceed L. If at most k parts are needed, L is feasible; binary search the smallest feasible L.
Edge / failure case five numbers → 9
[1,2,3,4] and [5] gives 10; [1,2,3] and [4,5] gives 9.
Why? Find a target in a sorted list and return its index, or −1.
💡 Key idea Look at the middle element and discard the half that cannot contain the target.
Edge / failure case target missing → -1
2 is not in the list.
Why? You ride n trains in order; each leaves at the next whole hour after you arrive (except the first and the last arrival). Find the smallest whole speed that gets you there within 'hour' hours, or −1.
💡 Key idea For a speed s the time is Σ ceil(d/s) for all but the last train, plus last/s. It decreases as s grows, so binary search the smallest s that fits. If hour ≤ n − 1 it is impossible.
Edge / failure case impossible → -1
Two trains must wait for whole hours so at least 2 hours are needed.
Why? Count the different orderings of the numbers in which every two neighbours add up to a perfect square.
💡 Key idea Group equal numbers with a counter so duplicates never create duplicate orderings. Precompute which values can follow which (sum is a square) and extend the ordering one value at a time.
Edge / failure case all equal → 1
2+2=4 is a square, so the only ordering [2,2,2] works.
Why? Return all possible subsets of a list of distinct numbers.
💡 Key idea Build subsets in a path; at each step record the current path, then try adding each later number.
Edge / failure case one number → [[], [0]]
The empty subset and [0].
Why? Repeatedly smash two stones: equal ones vanish, otherwise the heavier loses the lighter's weight. What is the smallest possible weight of the last stone (or 0)?
💡 Key idea The final stone is the difference of two groups of stones (those with + and those with −). So split the stones into two subsets with sums as close as possible: find the reachable subset sum closest to half of the total (bitset knapsack).
Edge / failure case five stones → 5
The best split of the stones leaves a difference of 5.
Why? Buy and sell a stock as often as you like (one share at a time), but after selling you must wait one day before buying again. Maximise the profit.
💡 Key idea Track three values each day: best profit while holding a share, just sold today, and resting (not holding, free to buy).
Edge / failure case one day → 0
Nothing can be sold.
Why? Fall from the top row to the bottom, moving to the cell below, below-left or below-right each step. Find the smallest total.
💡 Key idea For each cell, the best path ending there is its value plus the smallest of the up-to-three cells above it.
Edge / failure case negative numbers → -59
−19 then −40 gives −59.
Why? Walk from the top-left to the bottom-right of a grid moving only right or down. Count the paths whose sum of cell values is divisible by k (modulo 10⁹+7).
💡 Key idea For every cell keep an array ways[r] = number of paths reaching it with sum ≡ r (mod k). Each cell merges the arrays from above and from the left, shifted by its own value.
Edge / failure case one row → 1
A single path of sum 0, divisible by 5.
Why? Can the numbers be split into two groups with equal sums?
💡 Key idea The total must be even; then ask if some subset sums to half. Keep all reachable sums as bits of one big integer and shift-or for each number.
Edge / failure case odd total → False
The total 11 is odd.
Why? Count the different combinations of coins (unlimited supply of each kind) that add up to an amount.
💡 Key idea dp[a] = number of ways to make a. Process one coin kind at a time (outer loop) and add dp[a − coin] for amounts from the coin upwards — that counts combinations, not orderings.
Edge / failure case impossible → 0
Only 2s are available, but 3 is odd.
Why? A knight on an n×n board makes k random moves (each of the 8 moves equally likely, even off the board). What is the probability it is still on the board after k moves?
💡 Key idea Keep a grid of probabilities of being on each cell. For each move, send 1/8 of every cell's probability to each of its 8 target cells that are on the board. The answer is the total left.
Edge / failure case k=0 → 1
With zero moves the knight is certainly still on the board.
Why? You may swap two digits of a number at most once. Return the largest number you can make.
💡 Key idea Record the last position of every digit. Scan from the left; at the first digit for which a bigger digit exists later, swap it with the LAST occurrence of the biggest such digit.
Edge / failure case already maximal → 9973
The digits are already in decreasing order: no useful swap.
Why? Several packs of apples must be re-packed into boxes of given capacities (apples from a pack can be split among boxes). Use as few boxes as possible.
💡 Key idea Total apples is all that matters. Sort capacities from big to small and take boxes until the total fits.
Edge / failure case all boxes needed → 4
15 apples: 7 + 4 + 2 + 2 needs all four boxes.
Why? arr is a permutation of 0..n−1. Cut it into as many chunks as possible so that sorting each chunk separately and gluing them gives the sorted array.
💡 Key idea A cut after index i works exactly when the biggest number so far is i (then the first i+1 numbers are exactly 0..i). Count those positions.
Edge / failure case reversed → 1
The 4 at the front forces one big chunk.
Why? A grid of 0/1. Choose numSelect columns. A row is 'covered' if every 1 in it lies in a chosen column (a row of only zeros is always covered). Maximise the covered rows.
💡 Key idea Turn each row into a bitmask of its 1s. For every choice of numSelect columns (also a mask) a row is covered when rowMask & ~chosen == 0.
Edge / failure case one column → 2
A row of zeros is always covered, and the chosen column covers the other.
Why? The Hamming distance of two numbers is the number of bit positions where they differ. Return the sum over all pairs.
💡 Key idea Handle each bit position separately: if c numbers have a 1 there and n−c have a 0, that bit contributes c·(n−c) differing pairs.
Edge / failure case two numbers → 1
1 = 01 and 3 = 11 differ in one bit.
Why? You have two jugs of capacities x and y and unlimited water. Can you measure exactly 'target' litres in the jugs together?
💡 Key idea You can measure any multiple of gcd(x, y) up to x + y. So the answer is target ≤ x + y and target is divisible by gcd(x, y).
Edge / failure case impossible → False
Everything measurable is a multiple of 2, and 5 is odd.
Why? Can one person attend all the meetings (no two overlap)?
💡 Key idea Sort by start time; any meeting that starts before the previous one ends is an overlap.
Edge / failure case unsorted input → True
The meetings do not overlap once sorted.
Why? Two people list their free time slots. Find the earliest time slot of the given duration that fits both.
💡 Key idea Sort both lists. For the current pair of slots the common part is [max(starts), min(ends)]; if it is long enough, answer. Otherwise advance the slot that ends first.
Edge / failure case no fit → []
The only overlap, 60–70, is too short for 12.
Why? A grayscale image. A 'region' is a 3×3 block in which every two neighbouring pixels differ by at most the threshold. Each pixel becomes the average of the (rounded-down) averages of all regions it belongs to, or stays unchanged if it is in none.
💡 Key idea Test every 3×3 block's neighbour differences; for good blocks add the block average (floor of sum/9) to the nine pixels' totals and counts. Finally divide totals by counts.
Edge / failure case overlapping regions → [[25, 25, 25], [27, 27, 27], [27, 27, 27], [30, 30, 30]]
Pixels lying in two overlapping regions get the average of the two region averages.
Why? Fill an n×n matrix with 1…n² in spiral order.
💡 Key idea Keep four boundaries (top, bottom, left, right). Fill the top row, right column, bottom row and left column in turn, shrinking the boundary after each side.
Edge / failure case n=1 → [[1]]
A single cell holds 1.
Why? A grid with a single island (1 = land). Return the length of its perimeter.
💡 Key idea Each land cell contributes 4 sides, minus 2 for every pair of land cells that touch (each shared edge hides two sides).
Edge / failure case one cell → 4
A single land cell has four sides.
Why? Replace every pixel by the average (rounded down) of itself and its up to 8 neighbours.
💡 Key idea For each cell collect the values in the 3×3 window that lie inside the grid and divide the sum by their count.
Edge / failure case different neighbourhood sizes → [[137, 141, 137], [141, 138, 141], [137, 141, 137]]
Corners average 4 pixels, edges 6 and the centre 9, each rounded down.
Why? Wrap an iterator (next, hasNext) so it also supports peek(): look at the next value without consuming it.
💡 Key idea Always keep the upcoming value in a variable. peek returns it; next returns it and loads the following one.
Edge / failure case empty iterator → [False]
An empty iterator has nothing to peek at.
Why? Students enter one at a time and sit at the seat that maximises the distance to the closest person (the lowest seat on ties); students may also leave. Implement seat() and leave(p).
💡 Key idea Keep the occupied seats sorted. The candidate seats are: the first seat 0, the last seat n−1, and the middle of every gap between two people. Compare their distances.
Edge / failure case one seat → [0, None, 0]
The only seat is 0 each time.
Why? A stack whose pop removes the most frequent element (the most recently pushed one among ties).
💡 Key idea Keep the frequency of every value and, for each frequency level f, a stack of the values that reached frequency f. Pop takes from the highest level.
Edge / failure case single value → [None, 1]
One value pushed and popped.
Why? Accept a new booking [start, end) unless it would make a third booking cover some moment (double booking is allowed).
💡 Key idea Store all accepted bookings and a list of the double-booked stretches. A new booking is rejected if it hits any double-booked stretch; otherwise record its overlaps with the earlier bookings.
Edge / failure case a triple booking → [True, True, False]
A third booking inside the double-booked stretch 2–5 is refused.
Why? A task manager with add, edit (change priority), rmv (remove) and execTop (run the highest-priority task, ties → bigger task id, and return its user).
💡 Key idea Keep a dictionary of the current tasks and a max-heap of (priority, taskId). Edits push a new heap entry; stale entries (removed or changed tasks) are skipped when popped.
Edge / failure case ties and empty → [2, 1, -1]
Equal priority: the bigger task id (9, user 2) runs first; then nothing is left (−1).
Why? Build a last-in-first-out stack using only queue operations.
💡 Key idea After pushing a new element at the back, rotate all older elements behind it, so the newest is at the front.
Edge / failure case empty stack → [True, None, 1, True]
A new stack is empty; after push and pop it is empty again.
Why? Users post tweets, follow/unfollow others, and see a news feed of the 10 most recent tweets from themselves and the people they follow.
💡 Key idea Store each user's tweets with a global timestamp. For a feed, merge the newest tweets of all followees with a max-heap, pulling the next older tweet of whoever was just used, until 10 are found.
Edge / failure case more than 10 tweets → [11, 10, 9, 8, 7, 6, 5, 4, 3, 2]
Only the 10 most recent of 11 tweets are shown, newest first.
Why? Implement a linked list with get(index), addAtHead, addAtTail, addAtIndex and deleteAtIndex.
💡 Key idea A dummy node in front removes the special cases. To change position i, walk to the node just before it.
Edge / failure case invalid positions → [-1, None, -1, None, 5]
Inserting beyond the end is ignored; get on an empty list gives −1.
Why? Accept a booking [start, end) only if it does not overlap any earlier booking.
💡 Key idea Keep the bookings sorted. A new booking only has to be compared with its two neighbours: the one before must end by start, the one after must start at or after end.
Edge / failure case touching intervals → [True, True, True, False]
Touching intervals are fine; 7–8 lies inside 5–10.
Why? Two sentences are similar if they have the same length and each word pair is equal or 'similar'. Similarity is transitive (a~b and b~c means a~c). Pairs of similar words are given.
💡 Key idea Union the words of every pair; two words are similar when they have the same representative.
Edge / failure case different lengths → False
Different lengths: never similar.
Why? Every house needs water: either dig its own well (a cost per house) or connect it by pipe to a house that has water (pipe costs given). Minimise the total cost.
💡 Key idea Add a virtual node 0 and an edge 0–i with the well cost of house i. Now we need the cheapest way to connect all nodes: a minimum spanning tree (Kruskal with union-find).
Edge / failure case two houses → 2
A well at house 1 (1) and a pipe to house 2 (1) costs 2.
Why? A connected weighted graph; delete edges so that at most k components remain. The cost of a component is its heaviest edge (0 if none). Minimise the largest component cost.
💡 Key idea Keep the cheapest edges that merge components (Kruskal). Add edges in increasing weight order; stop when only k components are left — the last weight added is the answer.
Edge / failure case k=1 → 9
One component must keep a path from end to end; the heaviest edge on it is 9.
Why? Is the string formed by the first letters of the words, in order?
💡 Key idea Build the acronym and compare.
Edge / failure case length mismatch → False
The acronym 'aa' differs from 'a'.
Why? Is the string equal to the concatenation of the first k words of the list, for some k?
💡 Key idea Append the words one at a time; return True when the built text equals s, False once it gets longer.
Edge / failure case wrong order → False
The first word 'apples' does not match.
Why? How many of the patterns occur inside the word?
💡 Key idea Count patterns p with p in word.
Edge / failure case some missing → 2
'a' and 'b' occur, 'c' does not.
Why? Split a message into parts that each end with a suffix '<i/b>' (part number i of b parts) and have exactly 'limit' characters in total (the last part may be shorter). Use the fewest parts; return [] if impossible.
💡 Key idea Try b = 1, 2, 3, …: with b parts the room for message text in part i is limit − len('<i/b>'). The first b where the total room reaches the message length is the answer; then cut the message greedily.
Edge / failure case many parts → ['thi<1/14>', 's i<2/14>', 's r<3/14>', 'eal<4/14>', 'ly <5/14>', 'a v<6/14>', 'ery<7/14>', ' aw<8/14>', 'eso<9/14>', 'me<10/14>', ' m<11/14>', 'es<12/14>', 'sa<13/14>', 'ge<14/14>']
Fourteen parts are needed.
Why? Add characters only in front of a string to make it a palindrome; return the shortest result.
💡 Key idea Find the longest palindromic PREFIX of s: it is the longest prefix that equals a suffix of reverse(s), found with the KMP failure function on s + '#' + reverse(s). Put the reversed remainder in front.
Edge / failure case nothing to reuse → 'dcbabcd'
No prefix longer than 'a' is a palindrome.
Why? Source code lines may contain // line comments and /* … */ block comments (which can span lines). Return the code with all comments removed (empty lines are dropped).
💡 Key idea Scan character by character with a flag 'inside a block comment'. Outside a block: '/*' starts one, '//' ends the line, otherwise keep the character. Emit a line when the scan of a line ends outside a block and the line is not empty.
Edge / failure case block over lines → ['ab']
The block comment spans lines, so 'a' and 'b' join into one line.
Why? Binary search with a random pivot is run for every value of an unsorted array of distinct numbers. How many values are always found?
💡 Key idea A value is always found iff everything to its left is smaller and everything to its right is bigger. Check with a prefix maximum and a suffix minimum.
Edge / failure case one number → 1
A single element is always found.
Why? How many times must string a be repeated so that b is a substring of the result? (−1 if never)
💡 Key idea b needs at least ceil(len(b)/len(a)) copies; one more copy may be needed because b can start in the middle of a. If neither works, no number works.
Edge / failure case no match → -1
The letters of b never appear in a: −1.
Why? '00110011': the runs are 2,2,2,2. Neighbouring runs of lengths a and b give min(a,b) valid pieces: 2+2+2 = 6.
💡 Key idea Group the string into runs of equal characters. Two touching runs of lengths a and b contain exactly min(a, b) substrings with equal 0s and 1s, so add that for every neighbouring pair.
Edge / failure case alternating → 4
Every neighbouring pair of runs gives one piece: 10, 01, 10, 01.
Why? 'I speak': 'I' starts with a vowel → 'Imaa'; 'speak' → move 's' to the end → 'peaksmaaa'.
💡 Key idea Split into words. If a word starts with a consonant, move its first letter to the end. Then add 'ma' and as many 'a's as the word's position (1, 2, 3 …).
Edge / failure case single vowel word → 'amaa'
'a' is a vowel: it only gets 'ma' and one 'a'.
Why? Square every number of a sorted list (it may contain negatives) and return the squares sorted.
💡 Key idea The biggest square is at one of the two ends. Compare the ends and fill the answer from the back.
Edge / failure case negatives and positives → [4, 9, 9, 49, 121]
The two ends (−7 and 11) give the biggest squares.
Why? A sentence is given as a list of characters. Reverse the order of the words in place.
💡 Key idea Reverse the whole list; every word is now backwards, so reverse each word back to normal.
Edge / failure case one word → 'a'
A single word stays as it is.
Why? Count the subarrays whose largest element is between left and right (inclusive).
💡 Key idea Scan once keeping the last position of a number > right (breaks everything) and the last position of a number in [left, right]. The subarrays ending here with a valid maximum start after the break and at or before that last valid number.
Edge / failure case a too-big number → 7
The 9 breaks the array: 7 valid subarrays.
Why? One operation replaces any element with any integer. The array is 'continuous' if its numbers are all different and max − min = n − 1. Find the minimum operations.
💡 Key idea Keep as many original (distinct) numbers as possible: those that already fit inside some value window of width n−1. Sort the distinct values and slide a window; the answer is n minus the biggest count.
Edge / failure case far apart numbers → 3
Only one value fits in any window of width 3: three changes.
Why? Prizes lie on a line (sorted positions). Choose two segments of length k (ends included, may overlap); you win every prize inside either. Maximise the number of prizes.
💡 Key idea Slide a window of length k; for every window ending at i add the best window that lies entirely before its start (kept as a running maximum).
Edge / failure case k=0 → 2
Segments of length 0 hold one position each: two segments win 2 prizes.
Why? strategy[i] is −1 (buy), 0 (hold) or 1 (sell) on day i; profit = Σ strategy[i]·prices[i]. You may once choose k consecutive days and set the first half to hold (0) and the second half to sell (1). Maximise the profit.
💡 Key idea Compute the base profit. For a window the change is −(old profit of the window) + (sum of prices in its second half). Slide the window with prefix sums and take the best change (or none).
Edge / failure case choose a window → 9
Setting the last two days to hold and sell gives 9.
Why? Count the subarrays whose smallest value is exactly minK and largest value is exactly maxK.
💡 Key idea Scan once remembering the last index of minK, the last index of maxK and the last 'bad' index (a value outside [minK, maxK]). Subarrays ending here start between the bad index and the smaller of the two last indices.
Edge / failure case all equal → 10
Every subarray works: 10.
Why? Take exactly k cards, each from either end of the row. Maximise the total points.
💡 Key idea The cards you do NOT take form one block of n − k consecutive cards in the middle. Minimise the sum of that block with a sliding window and subtract it from the total.
Edge / failure case equal cards → 4
Any two cards give 4.
Why? In one operation add 1 to any element; at most k operations. What is the highest frequency of one value you can reach?
💡 Key idea Sort. Raise a window of numbers up to the window's last (largest) value: cost = largest × length − sum. Grow the window to the right and shrink from the left while the cost exceeds k.
Edge / failure case limited operations → 1
Only 1 element can be reached.
Why? A tree's edges carry letters. Count the pairs of nodes (u, v) whose path's letters can be rearranged into a palindrome.
💡 Key idea A word can be rearranged into a palindrome when at most one letter has an odd count. Give every node a 26-bit mask of letter parities on its root path; the path mask of (u, v) is mask[u] XOR mask[v]. Count earlier nodes whose mask equals it or differs by one bit.
Edge / failure case all the same letter → 10
Every path has only 'a's, so all 10 pairs work.
Why? Two strings are in the same group if shifting every letter of one by the same amount (z wraps to a) gives the other. Group the strings.
💡 Key idea Strings in a group share the same differences between neighbouring letters (mod 26). Use that tuple as the dictionary key.
Edge / failure case single string → [['a']]
One string, one group.
Why? Can the letters of a string be rearranged into a palindrome?
💡 Key idea A palindrome has at most one letter with an odd count.
Edge / failure case no palindrome → False
Four different letters: four odd counts.
Why? Return the numbers that appear in every list, sorted ascending.
💡 Key idea Count in how many lists each number appears (each list has distinct numbers); keep the numbers whose count equals the number of lists.
Edge / failure case disjoint lists → []
No number is in both lists.
Why? Count the distinct non-empty subarrays containing at most k numbers divisible by p.
💡 Key idea For each start extend to the right while the divisible-count stays ≤ k, adding every prefix (as a tuple) to a set; the set removes duplicates.
Edge / failure case everything allowed → 10
Every number is divisible by 1, k=4 allows all: all 10 subarrays.
Why? How many of the words are subsequences of s?
💡 Key idea Put every word in a bucket under the letter it is waiting for. Walk through s once: for each letter move that bucket's words forward one letter (words that finish are counted).
Edge / failure case longer text → 2
Only 'ahjpjau' and 'ja' are subsequences.
Why? Count the subarrays whose sum is divisible by k.
💡 Key idea Two prefix sums with the same remainder (mod k) enclose a subarray divisible by k. Count how many earlier prefixes have each remainder.
Edge / failure case no divisible subarray → 0
5 is not a multiple of 9.
Why? Each record says a user visited a website at a time. A pattern is an ordered triple of sites a user visited (in time order, not necessarily consecutively). Find the pattern visited by the most DIFFERENT users (lexicographically smallest on ties).
💡 Key idea Group each user's visits by time, list every 3-combination of their visited sites in order, collect them in a set per user, and count in how many users' sets each pattern appears.
Edge / failure case same pattern → ['a', 'b', 'a']
Both users visited a → b → a.
Why? 'aba': the wonderful substrings are 'a', 'b', 'a' and 'aba' (only 'b' has an odd count) → 4.
💡 Key idea Keep a 10-bit mask of which letters have an odd count so far. A substring is wonderful if the two prefix masks are equal or differ in exactly one bit. Count earlier prefixes with those masks.
Edge / failure case two different letters → 2
'h' and 'e' alone are wonderful, 'he' has two odd letters.
Why? Rearrange distinct numbers so that no element equals the average of its two neighbours.
💡 Key idea Sort, then alternate the smaller half and the larger half: every inner element is then either bigger than both neighbours or smaller than both, so it cannot be their average.
Edge / failure case another input → [True, True]
Valid arrangement of different numbers.
Why? Find i < j < k with nums[i] < nums[j] < nums[k] maximising nums[i] − nums[j] + nums[k].
💡 Key idea For each middle j the best k is the biggest number to its right (suffix maximum, it must exceed nums[j]); the best i is the largest earlier number below nums[j] (bisect in a sorted list of earlier numbers).
Edge / failure case choose the middle → 4
Triplet 1, 3, 6 gives 1 − 3 + 6 = 4, better than 1, 5, 6 (2).
Why? Split a row of marbles into k bags of consecutive marbles; a bag costs (first weight + last weight). Return the difference between the maximum and minimum total cost.
💡 Key idea Each cut between positions i and i+1 adds weights[i] + weights[i+1]. Choosing which k−1 cuts to make: max total = sum of the k−1 largest pair sums, min = sum of the k−1 smallest; the difference is what we want.
Edge / failure case two marbles → 0
Only one way to split: difference 0.
Why? Sorted [1,2,4,5] has prefix sums 1,3,7,12. A budget of 3 fits two numbers, 10 fits three, 21 fits all four.
💡 Key idea The cheapest way to pick many numbers is to take the smallest ones. Sort, build prefix sums, and for each query find how many prefix sums stay within it.
Edge / failure case budget too small → [0]
Even the smallest number 2 is above 1.
Why? Item i gets a discount equal to the first later price that is ≤ prices[i] (none → no discount). Return the final prices.
💡 Key idea A decreasing-stack pass: when a price arrives that is ≤ the price on top of the stack, it is that item's discount.
Edge / failure case increasing prices → [1, 2, 3, 4, 5]
No later price is ever smaller or equal: no discounts.
Why? The min-product of a subarray is (its smallest number) × (its sum). Find the maximum over all subarrays (modulo 10⁹+7 at the end).
💡 Key idea For each number as the minimum, find how far it can extend left and right while staying the minimum (monotonic stack); the best sum is then a prefix-sum difference.
Edge / failure case a hill → 60
Subarray [5,6,4] has min 4 and sum 15: 60.
Why? People stand in a grid with heights. A person sees someone to the right (same row) or below (same column) if everybody in between is shorter than both. Count, for every person, the people they can see.
💡 Key idea Along each row (and each column) scan from the far end with a stack of heights: pop everybody shorter than the current person (each popped one is seen), then if the stack is not empty, the person on top is seen too.
Edge / failure case a column → [[3, 1], [2, 1], [1, 0]]
In the first column the 5 sees the 3 and the 4; the 3 sees the 4.
Why? While two neighbouring numbers share a factor greater than 1 (gcd > 1), replace them by their least common multiple. Return the final array.
💡 Key idea Push numbers on a stack; while the new number and the top are not coprime, pop the top and replace the new number by their lcm; then push it. The result does not depend on the merge order.
Edge / failure case equal neighbours → [2, 1, 1, 3]
2, 2 merge into 2; the 1s stay; 3,3,3 merge into 3.
Why? Swap every two adjacent nodes of a linked list (by changing links, not values).
💡 Key idea Keep a pointer to the node before each pair and rewire three links.
Edge / failure case odd length → [2, 1, 3]
The last node stays when the length is odd.
Why? Repeatedly delete consecutive nodes of a linked list that sum to 0, until none are left; return the resulting list.
💡 Key idea Two equal prefix sums mean the nodes between them sum to zero. First pass: remember the last node for each prefix sum. Second pass: from each prefix point, jump straight to that last node's next.
Edge / failure case nested cancellation → [1]
3 and −3 cancel, then 2 and −2 cancel: only 1 is left.
Why? A tree (parent array) has a letter on each node. Find the longest path (number of nodes) in which no two adjacent nodes share a letter.
💡 Key idea For each node compute the longest downward chain. The best path through a node joins its two longest child chains whose first letters differ from the node's letter.
Edge / failure case star → 3
A path b–a–c uses nodes of different letters: 3 nodes.
Why? In a binary search tree find the value closest to a target (the smaller on ties).
💡 Key idea At every node record it if it is closer, then go left if the target is smaller, right otherwise — the closest value lies on that path.
Edge / failure case one node → 1
Only one value.
Why? Find the longest path in a binary tree whose values are consecutive (…+1 each step or −1 each step); the path may go up to a parent and down again.
💡 Key idea For every node compute the longest increasing and decreasing chain going down from it. A path through the node joins an increasing chain on one side with a decreasing chain on the other: length = inc + dec − 1.
Edge / failure case path through the root → 3
The path 1 → 2 → 3 goes up through the root.
Why? Return one root node for every kind of subtree (same structure and values) that appears more than once in the tree.
💡 Key idea Give each subtree a text serialisation like 'left,node,right' built bottom-up. Count them in a dictionary; the moment a serialisation is seen for the second time, report that subtree.
Edge / failure case two equal leaves → [[1]]
The two leaves 1 are the same subtree.
Why? [0,0,null,0,0]: one camera on the left child watches itself, its parent and its two children. The right side is empty, so 1 camera is enough.
💡 Key idea Go bottom-up and give each node a state: 0 = not watched, 1 = has a camera, 2 = watched. If a child is not watched, this node needs a camera. If a child has a camera, this node is watched. Otherwise it is not watched yet and waits for its parent.
Edge / failure case a chain → 2
A long zig-zag chain needs 2 cameras.
Why? Each bus loops forever along its list of stops. Starting at a stop, find the fewest buses to take to reach the target stop (you may change buses at shared stops).
💡 Key idea Think of buses as graph nodes: from a route you can board any route that shares a stop. Map each stop to the routes serving it and run a BFS over routes, counting buses.
Edge / failure case unreachable → -1
No chain of buses connects stop 15 to stop 12.
Why? A tree has directed edges. For each node as the start, how few edges must be reversed so that every node can be reached from it?
💡 Key idea Treat every edge as two-way: going along it costs 0, against its direction costs 1. Compute the cost for root 0, then move the root across an edge: the cost goes up by 1 if the edge pointed away from the old root, otherwise down by 1.
Edge / failure case a chain → [2, 0, 1]
Node 1 reaches 2 and 0 along the arrows; others need reversals.
Why? A grid of rooms; moveTime[i][j] is the earliest second you may start entering room (i, j). A move to a neighbouring room takes 1 second. Find the earliest arrival at the bottom-right room.
💡 Key idea Dijkstra over rooms: the arrival time in a neighbour is max(current time, its moveTime) + 1.
Edge / failure case no waiting → 3
No waiting: three moves take 3 seconds.
Why? A fire spreads each minute to neighbouring grass cells (walls block it). You start at the top-left, move one cell per minute and want to reach the bottom-right. What is the longest you can wait before leaving and still survive? (−1 if impossible; 10⁹ if you can always escape.)
💡 Key idea Compute when the fire reaches every cell with a BFS. Then binary search the waiting time: for a given delay, BFS yourself and require reaching each cell strictly before the fire (the last cell may be reached at the same moment).
Edge / failure case escape is always possible → 1000000000
The fire can never catch you on the way, so you may wait without limit: 10⁹.
Why? A ball in a maze rolls in one direction until it hits a wall. Find the shortest distance (number of cells travelled) from the start to the destination where the ball stops there, or −1.
💡 Key idea Each node is a stopping position. From it, roll in each of four directions counting cells until the wall; run Dijkstra on these roll lengths.
Edge / failure case unreachable stop → -1
The ball can never stop exactly at [3,2]: −1.
Why? Start with 1.0 of a currency. Day 1 allows conversions with one set of rates (and their inverses), day 2 with another. Maximise the amount of the starting currency at the end.
💡 Key idea The rates are consistent, so the value of any currency c in start-units is one fixed number per day. Find day-1 rate r1[c] from start to c and day-2 rate r2[c] from start to c (graph walk); converting start→c on day 1 and c→start on day 2 gives r1[c]/r2[c]. Take the best c reachable in both.
Edge / failure case two days, one pair → 1.5
Convert to EUR on day 1 (×9) and back on day 2 (÷6): 1.5.
Why? Like the previous room problem, but moves alternate in cost: the first move takes 1 second, the second 2 seconds, then 1, 2, …
💡 Key idea After k moves you are on a cell with (row + col) ≡ k (mod 2), so the cost of leaving cell (i, j) is 1 if i + j is even and 2 if odd. Dijkstra again, with arrival = max(time, moveTime) + cost.
Edge / failure case alternating costs → 4
Moves cost 1 then 2: total 4.
Why? Each employee has an importance value and a list of direct subordinates. Return the total importance of one employee and all their (indirect) subordinates.
💡 Key idea Put the employees in a dictionary by id and add up importance with a DFS through the subordinate lists.
Edge / failure case negative importance → -3
Employee 5 has no subordinates: importance −3.
Why? Cities joined by weighted roads. For each city count the cities reachable within a distance threshold; return the city with the fewest (the largest number on ties).
💡 Key idea Compute all shortest distances with Floyd–Warshall, count neighbours within the threshold for each city, and choose the best.
Edge / failure case five cities → 0
City 0 has the fewest neighbours within 2.
Why? Prerequisites form a directed graph. Answer queries 'is course u a (direct or indirect) prerequisite of course v?'
💡 Key idea Compute reachability between all pairs once (Floyd–Warshall on booleans) and answer each query by lookup.
Edge / failure case indirect prerequisite → [True, True]
1 → 2 → 0: both queries are True.
Why? A tree's nodes carry letters. For every node count the nodes in its subtree (itself included) with the same letter.
💡 Key idea A DFS returns, for each node, an array of 26 letter counts for its subtree: the sum of its children's arrays plus itself. The answer for the node is the count of its own letter.
Edge / failure case all the same label → [4, 2, 1, 1]
All letters are 'b', so each count is the size of the subtree.
Why? A set of pairs says 'x is an ancestor of y or the other way round'. Count the rooted trees consistent with exactly these pairs: 0, 1 or 2 (meaning multiple).
💡 Key idea The root must be paired with every node. For every other node its parent is the neighbour with the smallest degree that is still ≥ its own; its neighbours must all be that parent's neighbours too, otherwise no tree exists. If a parent has exactly the same degree as the child, either could be on top: multiple ways.
Edge / failure case impossible → 0
No node is paired with all others in the right way: 0.
Why? Every cell has an arrow (1 right, 2 left, 3 down, 4 up). Following arrows is free; changing one cell's arrow costs 1. Find the cheapest way to make a path from the top-left to the bottom-right.
💡 Key idea A graph where every move costs 0 (along the arrow) or 1 (against it). Use a deque: push 0-cost moves to the front and 1-cost moves to the back (0-1 BFS).
Edge / failure case valid path → 0
Following the arrows reaches the corner: cost 0.
Why? A tree with coins on some nodes. Start anywhere; from a node you can collect all coins within distance 2. You must return to the start. Minimise the number of edges walked.
💡 Key idea First strip off leaves without coins (repeatedly). Then peel off two more layers of leaves: a coin there can be picked up from two steps away. The remaining tree must be walked fully, each edge twice.
Edge / failure case longer path → 6
A longer path: pick coins within distance 2.
Why? A grid contains thieves (1). The safeness of a cell is its Manhattan distance to the nearest thief; the safeness of a path is its smallest cell safeness. Find the safest path from the top-left to the bottom-right.
💡 Key idea First compute every cell's distance to the nearest thief with a multi-source BFS. Then run Dijkstra that always extends the path with the biggest safeness so far (max-heap), tracking the minimum along the path.
Edge / failure case thief on the path → 0
A thief sits at the start: safeness 0.
Why? Split the nodes of a graph into numbered groups so that each edge joins nodes in groups whose numbers differ by exactly 1. Maximise the number of groups (−1 if impossible).
💡 Key idea It is only possible if every component is bipartite. In a component the best number of groups is the largest BFS depth (+1) over all starting nodes; add these up over components.
Edge / failure case odd cycle → -1
A triangle cannot be split into groups: −1.
Why? In a directed graph a node is safe if every path from it ends at a terminal node (no outgoing edges). Return all safe nodes, ascending.
💡 Key idea Terminal nodes are safe; a node becomes safe when all its successors are safe. Reverse the edges and peel nodes whose out-degree reaches 0 (Kahn's algorithm).
Edge / failure case cycles → [4]
Only node 4 is safe: everything else reaches a cycle.
Why? From index i you may step to i ± 1; and if nums[i] is a prime p you may teleport to any index whose value is a multiple of p. Find the fewest jumps from index 0 to the last index.
💡 Key idea BFS. Group indices by each prime factor of their value. When you stand on a prime p, jump to everything in p's group once and then empty the group (each index only needs to be reached once).
Edge / failure case walking needed → 3
Teleport from 5 (prime) to any multiple of 5: here the end is reached in 3 jumps.
Why? Person 0 tells person 1 at time 0. Meetings at time 5 spread it to 2, time 8 to 3, and time 10 to 5.
💡 Key idea Handle meetings in time order. Inside one time, build a small graph of that time's meetings and spread the secret by BFS from everyone who already knows it. People who met but never touched a secret-holder learn nothing.
Edge / failure case meetings out of order → [0, 1, 3]
0 and 3 know it from the start. 1 and 2 meet at time 2 when nobody knows; at time 3 person 3 tells 1, and 2 never hears.
Why? Going 0→1→4 costs 4 + 11 = 15. Use the one discount on the 11 toll (now 5): 4 + 5 = 9, the best.
💡 Key idea Run Dijkstra where a state is (city, discounts used so far). From each road you may pay the full toll or, if discounts remain, half of it (rounded down) and move to the next discount level.
Edge / failure case unreachable city → -1
City 3 cannot be reached: −1.
Why? Three cities hang directly off the capital 0. Each needs its own car (5 seats is plenty), one litre per road → 3.
💡 Key idea Root the tree at the capital. Every edge from a city up to its parent carries all the people of that city's subtree, and each car holds `seats` people, so that edge costs ceil(people / seats). Add this for every non-capital node.
Edge / failure case a bigger tree → 7
Cars fill up on the way: 7 litres.
Why? Every node must reach node 0. With edges of weight 1 only (1→0, 3→0, 4→3, 2→1) all nodes reach 0, so the largest weight needed is 1.
💡 Key idea Each node needs only one outgoing edge towards 0, so the limit on edges per node never blocks us. Reverse the edges and run a Dijkstra from 0 where a path's cost is its largest edge; the answer is the worst node, or −1 if some node is unreachable.
Edge / failure case node 0 unreachable → -1
Nothing points into node 0: −1.
Why? On day i the tree gives apples[i] apples that rot after days[i] days. You eat at most one apple per day. How many can you eat?
💡 Key idea Every day add the new batch to a min-heap keyed by its rotting day, discard rotten batches, and eat one apple from the batch that rots soonest.
Edge / failure case gaps without apples → 5
Apples from day 0 last 3 days, those from day 5 last 2: 5 eaten.
Why? For each query q start at the top-left: if the cell's value is < q you score a point and may move to its neighbours; otherwise you stop. Return the points for each query.
💡 Key idea Sort the queries. Grow one reachable region with a min-heap of frontier cells: for each query, keep absorbing the smallest frontier cell while it is smaller than the query; the region size is the answer.
Edge / failure case blocked corner → [0]
The corner value 5 is not below 3: no points.
Why? Walk over buildings left to right; going up costs the height difference in bricks, or one ladder (any height). Going down is free. How far can you get?
💡 Key idea Ladders belong on the biggest climbs. Keep a min-heap of the climbs that hold a ladder; when there are more climbs than ladders, the smallest one is paid with bricks. Stop when the bricks run out.
Edge / failure case ladders → 7
Use the ladders on the two big climbs.
Why? [7,9,5,8,1,3], n=2: remove 9 and 1 → [7,5,8,3]; (7+5) − (8+3) = 1, the smallest possible.
💡 Key idea Remove n numbers, keep 2n, split them in half: first n sum minus last n sum. Make the left sum as small and the right sum as large as possible. For every split point, a max-heap tracks the smallest n of the prefix and a min-heap the largest n of the suffix.
Edge / failure case n = 1 → -1
Remove 3 → (1) − (2) = −1.
Why? Bus i needs time[i] per trip; buses run independently. Find the smallest time by which the buses have made at least totalTrips trips together.
💡 Key idea In time t bus i completes t // time[i] trips. That total grows with t, so binary search the smallest t reaching totalTrips.
Edge / failure case one bus → 2
One trip of the single bus takes 2.
Why? Given a sorted array of distinct integers, find the smallest index i with arr[i] == i, or −1.
💡 Key idea arr[i] − i never decreases (the array is strictly increasing). Binary search the first place where it reaches 0.
Edge / failure case no fixed point → -1
arr[i] − i is negative then positive but never 0: −1.
Why? Count the numbers a in arr1 for which no number b of arr2 satisfies |a − b| ≤ d.
💡 Key idea Sort arr2. For each a, the nearest numbers of arr2 are found with bisect; a counts only if both neighbours are farther than d.
Edge / failure case a larger distance → 2
Two numbers of arr1 stay farther than 3 from everything in arr2.
Why? The absolute sum difference of two lists is Σ|nums1[i] − nums2[i]|. You may replace ONE element of nums1 by any other element of nums1. Return the minimum possible sum (mod 10⁹+7).
💡 Key idea For each position find, in a sorted copy of nums1, the value closest to nums2[i] (bisect); the gain is the old difference minus the new one. Subtract the best gain from the total.
Edge / failure case choose the best replacement → 20
Replacing the 10 by a 3 or 4 saves the most.
Why? Each machine makes one alloy from fixed amounts of several metals. You have stock and a budget to buy missing metal at given prices. Use ONE machine; maximise the alloys.
💡 Key idea For one machine, binary search the number of alloys a: the cost is Σ max(0, a·need − stock)·price; it must fit the budget. Take the best machine.
Edge / failure case bigger budget → 33
Machine 1 makes 5 alloys within the budget.
Why? [1,3,1], k=1: the pair distances are 2, 0, 2. Sorted: 0, 2, 2, so the 1st smallest is 0.
💡 Key idea Sort the numbers. For a guessed distance d, count the pairs with distance ≤ d using two pointers. The answer is the smallest d whose count reaches k, found by binary search on d.
Edge / failure case a big gap → 5
Distances are 5, 0, 5 sorted: 0, 5, 5 — the 3rd is 5.
Why? 30 in the middle is bigger than its neighbours 21, 14 and 16 (and 20 above it), so [1,1] is a peak. Any valid peak is accepted.
💡 Key idea Look at the middle row and take its maximum. If the cell below is bigger, a peak must exist in the lower half; otherwise it exists in this row or above. Halve the rows each time.
Edge / failure case small grid → True
Either 4 or 3 is a valid peak.
Why? Piles [5,8,6] and 3 children: with 5 candies each, the piles give 1 + 1 + 1 = 3 children. With 6 they only give 0 + 1 + 1 = 2. So the answer is 5.
💡 Key idea If each child gets x candies, pile c serves c // x children. The number of children served drops as x grows, so binary search the largest x that still serves at least k children.
Edge / failure case too many children → 0
Not enough candies for 11 children: 0.
Why? At time 3: flowers [1,6] and [3,7] are open, and [9,12] and [4,13] are not yet → 2.
💡 Key idea Flowers in bloom at time p = flowers already started (start ≤ p) minus flowers already ended (end < p). Sort the starts and the ends once and use two binary searches per person.
Edge / failure case overlapping flowers → [2, 2, 1]
At time 3 both flowers bloom; at time 2 only the first.
Why? nums [2,0,2]: after the first 2 queries every cell can lose up to 2, which covers the two 2s. So 2 queries are enough.
💡 Key idea Checking whether the first k queries are enough is easy with a difference array: each query adds capacity v on [l, r] and every cell needs capacity ≥ its value. More queries never hurt, so binary search the smallest k.
Edge / failure case impossible → -1
Index 0 needs 4 but only gets 1: −1.
Why? Does the string split into words that match the pattern letter by letter (each pattern letter always the same word, different letters different words)?
💡 Key idea Try to assign the next pattern letter to every possible prefix of the remaining string; remember the mapping and the words already used; backtrack on a clash.
Edge / failure case no match → False
No consistent split exists.
Why? Transactions [from, to, amount] say who paid whom. Find the minimum number of money transfers that settle all debts.
💡 Key idea Only each person's net balance matters. Take the first non-zero balance and try to settle it with every later balance of opposite sign (skipping duplicates), recursing on the rest.
Edge / failure case one transfer → 1
The balances cancel in a single transfer.
Why? Four cards with numbers 1–9: can +, −, ×, ÷ and parentheses make 24?
💡 Key idea Pick any two numbers, replace them by the result of one operation, and recurse until one number remains. Compare with 24 allowing a tiny error for fractions.
Edge / failure case impossible → False
No arrangement of the four numbers gives 24.
Why? Walk from the top-left to the bottom-right (right/down), then back to the top-left (left/up), picking cherries (each can be taken once) and avoiding thorns (−1). Maximise cherries.
💡 Key idea Going back is the same as a second walker going down. Move both walkers one step at a time: state = (step, row of walker 1, row of walker 2). Count a shared cell once.
Edge / failure case no path → 0
Thorns block every route to the bottom-right: 0.
Why? Mario drives on a two-lane road with coins (or tolls) every mile. He enters on lane 1 anywhere, leaves any time after at least one mile, and may switch lanes at most twice. Maximise the coins.
💡 Key idea Track the best total for a stretch ending at this mile in three situations: lane 1 with 0 switches, lane 2 after 1 switch, lane 1 after 2 switches. A new stretch may start at any mile.
Edge / failure case one switch → 8
Start in lane 1 (+1), switch to lane 2 for the 3 and 4: total 8.
Why? Houses form a binary tree; robbing two directly linked houses triggers the alarm. What is the most you can rob?
💡 Key idea For each node return two numbers: the best total if it IS robbed (its children must be skipped) and if it is NOT robbed (children free to choose).
Edge / failure case bigger children → 9
Rob the 4, 5 and the leaves 1 and 3: not the root.
Why? 'A'=1 … 'Z'=26. In how many ways can a digit string be decoded into letters?
💡 Key idea ways[i] = (ways[i−1] if the last digit is 1–9) + (ways[i−2] if the last two digits form 10–26).
Edge / failure case leading zero → 0
A leading zero cannot be decoded.
Why? A convex polygon has values at its corners. Cut it into triangles; each triangle's score is the product of its three corner values. Minimise the total score.
💡 Key idea For the edge between corners i and j, pick the corner k between them that forms the triangle (i, k, j) over that edge; the two remaining parts are smaller polygons: dp[i][j] = min over k of dp[i][k] + dp[k][j] + v[i]·v[k]·v[j].
Edge / failure case a triangle → 6
A triangle is already one triangle: 1·2·3 = 6.
Why? On an n×m grid you move to any other cell in your row or column. Count the ways to go from the source to the destination in exactly k moves (modulo 10⁹+7).
💡 Key idea Only four kinds of cell matter relative to the destination: the destination itself, same row, same column, and others. Keep how many ways end in each kind and update them k times with the move counts between kinds.
Edge / failure case 3 moves → 9
Three moves from (1,2) to (2,3): 9 ways.
Why? A knight crosses a grid from the top-left to the bottom-right moving right or down; each room adds or subtracts health. His health must stay at least 1 at all times. Find the smallest starting health.
💡 Key idea Work backwards: need[i][j] = the health required when entering the cell = max(1, min(need of the two next cells) − value).
Edge / failure case one cell → 1
Health must be at least 1.
Why? Bursting balloon i gives nums[i−1]·nums[i]·nums[i+1] coins (missing neighbours count as 1). Burst them all for the maximum coins.
💡 Key idea Think in reverse: choose the LAST balloon k to burst in a range; then its neighbours are the range borders and the two sides are independent: dp[l][r] = max over k of dp[l][k] + dp[k][r] + nums[l]·nums[k]·nums[r].
Edge / failure case two balloons → 10
Burst 1 first (1·1·5 = 5) and then 5 (1·5·1 = 5): 10.
Why? Find the biggest square subgrid whose whole border (outer ring) consists of 1s; return its area.
💡 Key idea Precompute, for every cell, the number of consecutive 1s going left and going up. A square of side s with bottom-right corner (i, j) is valid if the bottom and right edges have ≥ s ones and the top-left corner's edges do too.
Edge / failure case a single row → 1
Only a 1×1 square fits.
Why? Choose the biggest subset of binary strings that uses at most m zeros and n ones in total.
💡 Key idea A knapsack with two capacities: dp[z][o] = most strings using at most z zeros and o ones; go through the strings and update the table downwards.
Edge / failure case small limits → 2
Take '0' and '1' (or just '10'): 2 strings.
Why? Days [1,4,6,7,8,20], costs [2,7,15]: a 1-day ticket on day 1 (2), a 7-day ticket covering days 4–10 (7), a 1-day ticket on day 20 (2) → 11.
💡 Key idea dp[d] is the cheapest cost to cover all travel days up to day d. On a non-travel day it equals dp[d−1]. On a travel day take the best of: 1-day ticket from d−1, 7-day ticket from d−7, 30-day ticket from d−30.
Edge / failure case a mix of tickets → 17
One 7-day or 30-day pass plus cheap single days gives 17.
Why? A 2×2 grid with 3 colours and no two touching cells equal: 18 ways.
💡 Key idea Because m ≤ 5, list every valid colouring of one column (no equal neighbours inside it). Two columns can sit side by side if no row matches. Then count column by column.
Edge / failure case a single row → 6
One row of two cells: 3 × 2 = 6.
Why? [1,2,3,4,5], k=2: every neighbouring pair sums to an odd number, i.e. the same residue 1 mod 2. The whole array is valid → 5.
💡 Key idea A subsequence is valid when all neighbouring sums have the same remainder mod k. Try each possible remainder s. Then dp[r] = longest valid subsequence ending in a number with remainder r; the number before it must have remainder (s − r) mod k.
Edge / failure case mod 3 → 4
The subsequence [1,4,1,4] has equal neighbour sums mod 3: length 4.
Why? Two arrays of the same length. Swapping two elements inside one array is free; swapping nums1[i] with nums2[i] costs 1. Make the two arrays identical at minimum cost (−1 if impossible).
💡 Key idea Free swaps mean only the multiset of each array matters. Every value must appear an even number of times in total. The arrays are equal when each value has the same count in both; each paid swap fixes one surplus value in nums1 against one in nums2, so the cost is the total surplus of nums1.
Edge / failure case odd counts → -1
Values 1 and 3 each occur once: impossible.
Why? Can all the letters of a string be used to make exactly k non-empty palindromes?
💡 Key idea Each odd-count letter must be the centre of a different palindrome, so odd letters ≤ k; and k ≤ the number of letters (each palindrome needs at least one).
Edge / failure case too few palindromes → False
Odd letters l, t, c, o, d need 5 palindromes: impossible with 3.
Why? Two lists. You may change elements by ±1 up to k1 times in the first and k2 times in the second. Minimise Σ(nums1[i] − nums2[i])².
💡 Key idea Only the absolute differences matter and every operation can reduce one difference by 1; reduce the LARGEST differences first. Lower the whole top group to the next level while operations last, then spread the remainder inside the group.
Edge / failure case operations available → 43
Two operations spread over the biggest differences: 43.
Why? In one operation flip three consecutive bits. Make all bits 1 with the fewest operations, or return −1.
💡 Key idea The leftmost 0 can only be fixed by flipping the window that starts there. Go left to right flipping whenever you see a 0; at the end the last two bits must be 1.
Edge / failure case impossible → -1
The first flip leaves a 0 in the last positions: −1.
Why? In one operation pick an index and flip every bit from it to the end. Make all bits 1 with the fewest operations.
💡 Key idea Go left to right keeping the number of flips done so far; the current bit's real value is its value XOR (flips mod 2). Whenever it is 0, flip from here.
Edge / failure case one flip → 1
Flip from index 1 once.
Why? A garden spans 0…n. Tap i at position i waters [i − ranges[i], i + ranges[i]]. Open the fewest taps to water the whole garden, or −1.
💡 Key idea Turn every tap into an interval and cover [0, n] greedily: for each left end keep the farthest right end reachable, then jump like in the minimum-jumps problem.
Edge / failure case gaps → -1
No tap reaches beyond its own position: −1.
Why? Reduce n to 1: if n is even replace it by n/2; if odd by n + 1 or n − 1. Fewest steps?
💡 Key idea For an odd n choose the neighbour with more trailing zero bits: n + 1 unless n ends in binary '01' (or n is 3). That removes the most 1-bits.
Edge / failure case largest int → 32
n+1 wins over and over: 32 steps.
Why? [4,2,3], k=1: flip the smallest (2 → −2) gives 4 − 2 + 3 = 5.
💡 Key idea Each step, negate the smallest number: if it is negative this gains the most, and if every number is positive it loses the least. A min-heap hands out the smallest each time.
Edge / failure case flip negatives → 13
Flip −4 and −3 → 2 + 3 − 1 + 5 + 4 = 13.
Why? 'NWSE' with 1 change: after N, W, S we stand 1 away from the start; changing S to the opposite way adds 2, so 3 is reachable.
💡 Key idea At every prefix of length i, each change can turn a step that goes 'back' into a step that goes 'forward', adding 2 to the distance. The best distance there is min(current distance + 2k, i). Keep the maximum over all prefixes.
Edge / failure case more changes → 4
After N S W W the distance is 2; one change gives 4.
Why? Given a number (as text), return the closest palindromic number that is not the number itself (the smaller one if two are equally close).
💡 Key idea The answer is one of only five candidates: the mirrored first half, the mirrored first half ± 1, and the edge cases 10^(L−1) − 1 (like 999) and 10^L + 1 (like 1001). Pick the closest.
Edge / failure case a tie → '0'
0 and 2 are equally close; the smaller, 0, wins.
Why? Convert a spreadsheet column title (A, B, …, Z, AA, AB, …) to its number.
💡 Key idea It is a base-26 number with digits A=1 … Z=26: result = result × 26 + digit.
Edge / failure case ZY → 701
26·26 + 25 = 701.
Why? For maximumBit = m, repeatedly: choose k < 2^m maximising (XOR of all numbers) XOR k, record k, then remove the last number. Return all the k's.
💡 Key idea To maximise XOR with k, k should be the complement of the current XOR within m bits: k = xor ^ (2^m − 1). Maintain the XOR as numbers are removed (XOR again).
Edge / failure case 3 bits → [5, 2, 6, 5]
Complement of the running XOR in 3 bits, as numbers are removed from the end.
Why? Add the digits of a number repeatedly until a single digit remains.
💡 Key idea The result is the digital root: 0 for 0, otherwise 1 + (n − 1) mod 9.
Edge / failure case zero → 0
0 stays 0.
Why? Rotate each digit by 180° (0,1,8 stay; 2↔5; 6↔9; 3, 4, 7 become invalid). A number is 'good' if it stays valid and changes. Count the good numbers in 1..n.
💡 Key idea A number is good if it has no 3, 4 or 7 and contains at least one of 2, 5, 6, 9.
Edge / failure case n=1 → 0
1 rotates to itself, so it is not good.
Why? People stand in a line; some are already sick. Each second one healthy person next to a sick one gets infected. Count the possible infection orders (modulo 10⁹+7).
💡 Key idea The healthy people form gaps between the sick ones. Orders inside different gaps can be interleaved freely (a multinomial coefficient). Inside a gap bounded by sick people on both sides there are 2^(g−1) orders (infection can start at either end each time); for a gap at the border only one order.
Edge / failure case one sick person → 3
Three healthy people on one side or the other: 3 orders.
Why? A notepad holds one 'A'. Each step is Copy All or Paste. Fewest steps to have exactly n 'A's?
💡 Key idea To multiply the count by p you need 1 copy + (p−1) pastes = p steps. So the answer is the sum of the prime factors of n (with multiplicity).
Edge / failure case n=1 → 0
Already one 'A'.
Why? Cars park on a number line occupying [start, end]. How many integer points are covered by at least one car?
💡 Key idea Add +1 at each start and −1 after each end; the running sum is the number of cars on each point.
Edge / failure case gap between cars → 7
3 points + 4 points, no overlap: 7.
Why? Squares fall one at a time onto a number line (given left position and side length) and stick on whatever is below. After each drop report the height of the tallest stack so far.
💡 Key idea A new square lands on top of the highest earlier square that overlaps it horizontally. Keep each square's top height; the new top is that maximum plus its side.
Edge / failure case touching squares → [100, 100]
The squares only touch, so each lands on the ground.
Why? Day 1 paints cells 1–3 (3 new). Day 2 paints 4–6 (3 new). Day 3 asks for 5–7: 5 and 6 are already painted, so only 7 is new (1).
💡 Key idea Treat each unit cell as an item. Once a cell is painted, remember a pointer to the next unpainted cell (like Union Find). Then every day we jump straight over painted cells and only touch new ones.
Edge / failure case fully covered → [4, 0]
Everything on day 2 was already painted.
Why? 'aabbaba' has 28 substrings in total, but 7 of them are repeats, leaving 21 different ones.
💡 Key idea Every substring is a prefix of some suffix. Insert all suffixes into a trie: each NEW node created is one new distinct substring.
Edge / failure case all the same letter → 4
Only 'a', 'aa', 'aaa', 'aaaa'.
Why? A matrix of 0s and 1s whose rows are sorted. You can only read it through get(row, col) and dimensions(). Find the leftmost column that contains a 1.
💡 Key idea Start at the top-right. If the cell is 1, step left (a 1 may exist further left); if 0, step down. The last column where you saw a 1 is the answer.
Edge / failure case all zeros → -1
There is no 1 at all: −1.
Why? A pattern grid contains digits and letters; each letter stands for one digit (different letters, different digits; a letter's digit differs from the pattern's own digits). Find the first position in the board where a submatrix matches.
💡 Key idea Try every top-left corner (row by row). For each cell compare: a pattern digit must equal the board digit; a letter gets (or must keep) one digit. Finally the digits assigned to letters must all be different and not appear as pattern digits.
Edge / failure case no match → [-1, -1]
A letter must stand for one digit: no match.
Why? Only the cells that cannot walk off the grid count. The 3 land cells in the middle are surrounded by water, so the answer is 3.
💡 Key idea Start from every land cell on the border and sink everything reachable from it (BFS). Whatever land is left cannot reach the edge, so count it.
Edge / failure case no enclave → 0
Every land cell connects to the border: 0.
Why? Design a class over a stream of numbers: add(value), and showFirstUnique() returns the first number that appears exactly once (or −1).
💡 Key idea Keep every number's count and a queue in arrival order. When asked, pop from the front while the front number is no longer unique.
Edge / failure case empty start → [-1, None, 1]
An empty stream has no unique number; after adding 1 it is unique.
Why? Pick a random integer in [0, n) that is NOT in the blacklist, each allowed number equally likely, with few random calls.
💡 Key idea There are k = n − len(blacklist) allowed numbers. Pick uniformly from [0, k); if the pick is blacklisted, replace it by an allowed number from [k, n) that was assigned to it in advance.
Edge / failure case n=1 → [0]
The only allowed number is 0.
Why? Pick a uniformly random integer point from the union of non-overlapping rectangles (borders included).
💡 Key idea A rectangle with more integer points must be chosen more often: build prefix sums of point counts, pick a random number in [0, total) and locate its rectangle with bisect; then pick x and y uniformly inside it.
Edge / failure case one point → [[1, 1]]
A single point rectangle has only one choice.
Why? A leaderboard with addScore(player, score) (adds to the player's total), top(K) (sum of the K best totals) and reset(player).
💡 Key idea Keep totals in a dictionary. top sorts the totals (or uses a heap) and sums the K largest.
Edge / failure case adding twice → [None, None, 10, None, 0]
Scores add up per player; reset sets the total to 0.
Why? After 'leetcode' → delete 4 → 'leet' → add 'practice' → 'leetpractice'. Moving right does nothing (the cursor is at the end), and the last 10 characters left of it are 'etpractice'.
💡 Key idea Keep the text left of the cursor in one stack and the text right of it in another. Moving the cursor just moves characters between the two stacks; adding and deleting only touch the left stack.
Edge / failure case cursor at the start → [None, '', 0, 'a']
The cursor stops at the start, so nothing can be deleted; moving right once shows 'a'.
Why? Logs say that at a time two people became friends (friendship is transitive). Find the earliest time at which everybody is connected, or −1.
💡 Key idea Sort the logs by time and union the pairs; the moment the number of groups drops to 1 is the answer.
Edge / failure case never everyone → -1
Persons 2 and 3 never get connected: −1.
Why? A grid whose cells contain '/', '\' or a space cuts a square into regions. Count the regions.
💡 Key idea Split every cell into 4 triangles (top, right, bottom, left). A slash joins two pairs of triangles, a space joins all four; neighbouring cells join across shared sides. Count union-find groups.
Edge / failure case a diamond → 5
A diamond: four corner regions and the centre.
Why? Edges of type 1 can be used only by Alice, type 2 only by Bob, type 3 by both. Remove as many edges as possible so that both can still reach every node (−1 if impossible).
💡 Key idea Use type-3 edges first (they help both). Keep a union-find for Alice and one for Bob; keep an edge only if it joins two groups for somebody. Everything else is removable. Both must end connected.
Edge / failure case not traversable → -1
Alice cannot reach node 4: −1.
Why? Each equation says a / b = value. Is there a contradiction (two equations that cannot both hold)? Compare with precision 10⁻⁵.
💡 Key idea Weighted union-find: store for each variable its ratio to its group's root. A new equation between variables in the same group must agree with the stored ratios; otherwise merge the groups with the ratio that makes the equation true.
Edge / failure case contradiction → True
le/et = 2 but (le/code)·(code/et) = 5·0.5 = 2.5.
Why? Connect all points on a plane with the least total Manhattan length of cables (every pair may be joined).
💡 Key idea A minimum spanning tree: sort all pairs by distance and add a cable whenever it joins two separate groups (union-find).
Edge / failure case three points → 18
Join −4,1 to −2,5 (6) and −2,5 to 3,12 (12): 18.
Why? In a weighted graph, an edge is 'critical' if removing it makes the minimum spanning tree (MST) heavier (or impossible); 'pseudo-critical' if it appears in some MST but not all. List both kinds (by edge index).
💡 Key idea Compute the MST weight W. For each edge: Kruskal without it — if the weight rises (or the graph disconnects) it is critical. Otherwise Kruskal with it forced in — if the weight is still W it is pseudo-critical.
Edge / failure case a square → [[], [0, 1, 2, 3]]
All edges have equal weight: none is critical, all are pseudo-critical.
Why? Cities 1…n; two cities are directly connected if they share a divisor larger than the threshold. Answer queries: are cities a and b connected (directly or through other cities)?
💡 Key idea Instead of testing pairs, for every number z > threshold union all its multiples (z, 2z, 3z, …): they all share the divisor z. Then answer each query by comparing roots.
Edge / failure case threshold 0 → [True, True, True, True, True]
Threshold 0: any two numbers sharing a divisor (≥1) are connected, so all are.
Why? Query (0,1,limit 2): the only 0–1 edge has length 2, which is not below 2 → false. Query (0,2,limit 5): 0–1 (2) and 1–2 (4) are both below 5 → true.
💡 Key idea Sort edges by length and queries by limit. Walk the queries in increasing limit order and union every edge shorter than that limit before answering — then 'is there a path' is just 'are they in the same group'.
Edge / failure case strict limit → [True, False]
With limit 14 all edges work; with limit 13 the edge of length 13 is too long.
Why? Request 0–2 is fine. Request 2–1 would put 0 and 1 in the same friend group, which is forbidden, so it is rejected.
💡 Key idea Keep friend groups with Union Find. For a request, look at the two groups; if any restricted pair would end up with one person in each group, reject it. Otherwise merge.
Edge / failure case several restrictions → [True, False, True, False]
1–2 is itself a restricted pair → rejected; 3–1 is fine; 3–4 would put 0 and 1 in one group → rejected.
Why? Between 0 and 1 nothing is missing; between 1 and 3 the number 2; between 3 and 50 the numbers 4–49; and so on up to 99.
💡 Key idea Keep the previous number (start with lower − 1) and look at each next number (finally upper + 1). If the gap is at least 2 the numbers in between form one missing range.
Edge / failure case empty array → [[1, 1]]
Empty input: the whole range 1–1 is missing.
Why? 123 × 456 = 56088, built digit by digit as on paper.
💡 Key idea Digit i of the first number times digit j of the second lands at positions i + j and i + j + 1 of the result. Add into those cells and carry.
Edge / failure case single digits → '6'
A single-digit product.
Why? [1,1,0,1,1,1]: the longest run of 1s has length 3.
💡 Key idea Count the current run of 1s, reset it at every 0, and remember the largest run.
Edge / failure case all zeros → 0
No 1s at all.
Why? [1,2,1] followed by [1,2,1] is [1,2,1,1,2,1].
💡 Key idea The answer is the array joined with itself.
Edge / failure case four numbers → [1, 3, 2, 1, 1, 3, 2, 1]
The array twice.
Why? 1 → '11' (one 1) → '21' (two 1s) → '1211' (one 2, one 1).
💡 Key idea Start from '1'. To get the next term read the previous one in groups of equal digits and write 'count then digit' for each group.
Edge / failure case n = 1 → '1'
The first term is '1'.
Why? [3,4,5,1,2] is [1,2,3,4,5] rotated by 3 — the order drops only once (5 → 1).
💡 Key idea Looking at the array as a circle, a sorted-then-rotated array has at most one place where a number is bigger than the next one.
Edge / failure case not rotated sorted → False
The order drops twice (2→1 and 4→2 around the circle).
Why? 'abcde' shifted left twice becomes 'cdeab' → true.
💡 Key idea Every rotation of s is a substring of s + s. So goal is a rotation of s exactly when the lengths match and goal appears inside s + s.
Edge / failure case not a rotation → False
No rotation gives 'abced'.
Why? '1.1.1.1' becomes '1[.]1[.]1[.]1'.
💡 Key idea Replace every '.' by '[.]'.
Edge / failure case bigger numbers → '255[.]100[.]50[.]0'
Every dot is replaced.
Why? ['ab','c'] and ['a','bc'] both spell 'abc' → true.
💡 Key idea Join each array into one string and compare.
Edge / failure case different letters → False
'acb' is not 'abc'.
Why? [4,3,2,7,8,2,3,1]: 2 and 3 appear twice.
💡 Key idea All numbers are between 1 and n, so each number can use its own position as a flag: negate nums[value − 1]. If that cell is already negative, the value was seen before.
Edge / failure case small array → [1]
Only 1 repeats.
Why? 'abcdefg', k=2: reverse 'ab' → 'ba', skip 'cd', reverse 'ef' → 'fe', keep 'g' → 'bacdfeg'.
💡 Key idea Jump through the string in steps of 2k and reverse the first k characters of each block (the slice just clips at the end of the string).
Edge / failure case k = length → 'dcba'
k equals the whole length: reverse all.
Why? [1,3,5,4,7]: the longest strictly rising run is 1,3,5 (length 3).
💡 Key idea Extend the current run while each number is bigger than the previous one; reset to 1 otherwise. Keep the longest.
Edge / failure case no increase → 1
Equal numbers do not count as increasing.
Why? [2,4,1,1,6,5]: 4 is a hill, the run 1,1 is a valley, 6 is a hill → 3.
💡 Key idea Equal neighbours count as one position. For each element compare with the previous different value and the next different value: both smaller = hill, both bigger = valley. Skip an element equal to the next, and only update 'previous' after a real move.
Edge / failure case only descending → 0
The array only goes down: no hill, no valley.
Why? For each i the answer is nums[nums[i]]: nums[nums[0]] = nums[0] = 0, nums[nums[1]] = nums[2] = 1 …
💡 Key idea Build the new array with ans[i] = nums[nums[i]].
Edge / failure case another permutation → [4, 5, 0, 1, 2, 3]
Looks up each value as an index.
Why? '52': the last digit 2 is even, so cut it off → '5'.
💡 Key idea A number is odd iff its last digit is odd. The largest odd substring is the longest prefix that ends in an odd digit: look for the last odd digit and cut right after it.
Edge / failure case no odd digit → ''
No odd digit at all.
Why? 12 (2 digits) and 7896 (4 digits) have an even number of digits → 2.
💡 Key idea Turn each number into text, take its length and count the even lengths.
Edge / failure case mixed lengths → 1
Only 1771 has 4 digits.
Why? [1,2,2,6,6,6,6,7,10]: 6 appears 4 times out of 9 (more than a quarter).
💡 Key idea The array is sorted, so equal numbers sit together. A value covering more than 25% of the array must also be at distance n/4 from itself: check arr[i] == arr[i + n//4].
Edge / failure case one value → 1
The only value is 100%.
Why? Items are [type, color, name]. With ruleKey 'color' and value 'silver' only the computer matches → 1.
💡 Key idea Turn the rule key into a column index (type = 0, color = 1, name = 2) and count the items whose entry in that column equals the value.
Edge / failure case match on type → 2
Two phones.
Why? [13,25,83,77] → 1,3, 2,5, 8,3, 7,7.
💡 Key idea Write every number as text and append its digits one by one, keeping the original order.
Edge / failure case single digits → [7, 1, 3, 9]
Single-digit numbers stay as they are.
Why? 'aabcb': the substrings with beauty > 0 are aab, aabc, aabcb, abcb, bcb (1 each) → 5.
💡 Key idea The beauty of a substring is (highest letter count) − (lowest non-zero letter count). Fix the start, extend the end one letter at a time with a 26-slot count array, and add the beauty each time.
Edge / failure case a longer string → 17
More repeated letters give more beautiful substrings: 17.
Why? 'word' differs from 'wood' in one letter, 'note' from 'joke' in two, 'wood' equals 'wood' → those three are kept; 'ants' is too far from everything.
💡 Key idea Words have the same length, so an edit is a changed letter. For every query check whether some dictionary word differs in at most 2 positions.
Edge / failure case no close word → []
'yes' and 'not' differ in 3 letters.
Why? [2,5,1,3,4,7] with n = 3: take 2, 3 then 5, 4 then 1, 7 → [2,3,5,4,1,7].
💡 Key idea The array is [x1…xn, y1…yn]; the answer is x1, y1, x2, y2 … so alternate the first and the second half.
Edge / failure case four numbers → [1, 2, 1, 2]
1,2,1,2.
Why? With the digits 2, 1, 3, 0 you can make 102, 120, 130, 132, 210, 230, 302, 310, 312, 320.
💡 Key idea Count the available digits. Test every even number from 100 to 998: count its digits and check that the pool has enough of each.
Edge / failure case repeated digits → [222, 228, 282, 288, 822, 828, 882]
Only the digits 2 and 8 exist, with at most three 2s and two 8s.
Why? Both customers have 1 + 2 + 3 = 6 → 6.
💡 Key idea A customer's wealth is the sum of their row. Return the largest row sum.
Edge / failure case a 3 × 3 table → 17
The richest customer has 2 + 8 + 7 = 17.
Why? Fruits [4,2,5], baskets [3,5,4]: 4 → basket 5, 2 → basket 3, 5 finds no free basket of size ≥ 5 → 1 fruit type stays unplaced.
💡 Key idea Simulate it: for every fruit scan the baskets from the left and take the first unused one that is big enough; otherwise count the fruit as unplaced.
Edge / failure case all placed → 0
Every fruit finds a basket.
Why? [4,3,2,7,8,2,3,1]: 5 and 6 never appear.
💡 Key idea Values are between 1 and n, so a value can mark its own position: make nums[value − 1] negative. In the end the positions that are still positive belong to missing numbers.
Edge / failure case tiny array → [2]
Only 2 is missing.
Why? [5,2,3,1]: merge the cheapest pair 3+1 → [5,2,4]; merge 2+4 → [5,6]. Two operations, and the array is non-decreasing.
💡 Key idea Do exactly what the statement says: while the array is not sorted, find the leftmost adjacent pair with the smallest sum, replace it by that sum and count one operation.
Edge / failure case already sorted → 0
Already non-decreasing: 0 operations.
Why? [-1,2,1,-4], target 1: the triple −1 + 2 + 1 = 2 is the closest sum to 1.
💡 Key idea Sort the numbers. Fix one number and move two pointers inward from both ends: if the sum is too small move the left one up, if too big move the right one down. Remember the sum closest to the target.
Edge / failure case single triple → 0
Only one triple exists: 0.
Why? '69' turned upside down becomes '69' again (6 → 9 and 9 → 6) → true. '962' is not.
💡 Key idea Rotating the number by 180° swaps its two ends. Use two pointers from both ends: the left digit must rotate into the right digit (0→0, 1→1, 8→8, 6→9, 9→6).
Edge / failure case invalid digit → False
2 cannot be rotated into a digit: false.
Why? [1,1,1,2,2,2] × [6,6,6,3,3,3] = [6,6,6,6,6,6] → one run [6,6].
💡 Key idea Walk both run lists with two pointers. Take the shorter remaining run length, multiply the two values, and add that many copies to the result (merging with the last run if the product is equal). Then advance whichever run was used up.
Edge / failure case runs that split → [[2, 3], [6, 1], [9, 2]]
Products 2,2,2,6,9,9: runs [2,3],[6,1],[9,2].
Why? [3,1,2,4] → move the even numbers to the front: [4,2,1,3] (any order inside each group is fine).
💡 Key idea Keep one pointer at the left and one at the right. Skip an even on the left and an odd on the right; when the left is odd and the right is even, swap them.
Edge / failure case single number → [0]
One number is trivially fine.
Why? [3,1,-2,-5,2,-4]: positives go to positions 0, 2, 4 in order (3,1,2) and negatives to 1, 3, 5 (−2,−5,−4) → [3,−2,1,−5,2,−4].
💡 Key idea Equal numbers of positives and negatives must alternate, starting with a positive. Keep two write positions (even slots for positives, odd slots for negatives) and drop each number into its slot.
Edge / failure case negative first in input → [1, -1]
The positive number must come first.
Why? 1 and 5 appear in all three arrays → [1, 5].
💡 Key idea Keep one pointer per array. If the three current numbers are equal, record it and move all pointers; otherwise move the pointer(s) holding the smallest number.
Edge / failure case no common number → []
Nothing in common.
Why? [3,5,6,7], target 9: valid subsequences are [3], [3,5], [3,6], [3,5,6] → 4.
💡 Key idea The order of picks does not matter, so sort. With min = nums[l] and max = nums[r] and min + max ≤ target, every subset of the numbers strictly between them (2^(r−l) choices) works together with those two ends. Move the pointers: if the sum fits count 2^(r−l) and advance l, else shrink r.
Edge / failure case duplicates → 6
Six subsequences have min + max ≤ 10.
Why? [-1,1,2,3,1], target 2: the pairs (−1,1), (−1,2) and (−1,1) → 3.
💡 Key idea Sort. If nums[l] + nums[r] < target then all of nums[l+1…r] also pair with nums[l]: add r − l and move l. Otherwise move r down.
Edge / failure case negative target → 10
Ten pairs have a sum below −2.
Why? 'ab#c' and 'ad#c' both end up as 'ac' → true.
💡 Key idea Walk both strings from the right. A '#' means skip one more letter. Jump each pointer to its next real letter and compare; no extra memory is needed.
Edge / failure case different results → False
'a#c' is 'c' but the other is 'b'.
Why? [2,3,4,5] vs [2,1,3,4]: the first difference is at index 1. Sensor 1's tail [3,4] equals sensor 2's shifted tail [3,4], so sensor 1 dropped a value → 1.
💡 Key idea A defective sensor drops one reading and shifts all later readings one step left. Find the first index i where they differ, then check whether sensor 1's readings from i equal sensor 2's readings from i+1 (sensor 1 defective) or the other way round. If both or neither fit, answer −1.
Edge / failure case the other sensor → 2
From index 3 sensor 2's readings are sensor 1's shifted by one → 2.
Why? 'eceba': the longest piece with at most 2 different letters is 'ece' (length 3).
💡 Key idea Grow the window to the right and count its letters. If it holds more than 2 different letters, move the left edge forward until it is back to 2. Track the longest window.
Edge / failure case a long run → 5
'aabbb' has two different letters.
Why? 'abcabc': there are 10 substrings containing a, b and c.
💡 Key idea Walk through the string and remember the last position of 'a', 'b' and 'c'. For a substring ending at i to contain all three, it must start at or before the smallest of the three last positions — that is min(last) + 1 choices.
Edge / failure case letters at the end → 3
Only substrings reaching 'cb' work.
Why? Stones at 4, 7, 9: the minimum is 1 move (4 → 8 gives 7, 8, 9), the maximum is 2.
💡 Key idea Maximum: skip the first or the last gap — max(last − second − (n−2), second-last − first − (n−2)). Minimum: slide a window of n positions over the sorted stones; the stones outside must move, so the cost is n − (stones inside). Special case: if n−1 stones already sit next to each other (span n−2) and one stone is far away, that needs 2 moves, not 1.
Edge / failure case a far stone → [2, 3]
Minimum 2 (the far stone needs two moves), maximum 3.
Why? k = 3: every number is replaced by the sum of the next 3 (circularly): 5 → 7+1+4 = 12, 7 → 1+4+5 = 10 …
💡 Key idea For k > 0 sum the next k numbers, for k < 0 the previous |k| numbers, for k = 0 all zeros. Instead of re-adding k numbers for each position, slide a window: subtract the number that leaves and add the one that enters (indices modulo n).
Edge / failure case negative k → [12, 5, 6, 13]
k is negative: sum the previous 2 numbers.
Why? 'bcbbbcba': the longest piece in which no letter appears more than twice has length 4 (for example 'bcbb').
💡 Key idea Grow the window to the right. If the new letter now appears three times, move the left edge forward until it appears at most twice again. Track the longest window.
Edge / failure case all the same → 2
Only two a's may be in a window.
Why? order 'cba': c comes first, then b, then a. s = 'abcd' → 'cba' and the letter d, which is not in the order, goes at the end.
💡 Key idea Count the letters of s. Write each letter of `order` as many times as it was counted, in that order, then append whatever letters are left over.
Edge / failure case letter not in order → 'bcad'
b, c, a first; d is not in the order and goes last.
Why? Ages 16, 17, 18: 17 may ask 16 (16 > 15.5), 18 may ask 17 (17 > 16), but 18 may not ask 16 (16 ≤ 16) → 2 requests.
💡 Key idea Ages are at most 120, so count people per age and test every age pair once. A sends to B unless B ≤ 0.5·A + 7 or B > A. Multiply the counts, and remove self-requests when the ages are equal.
Edge / failure case large ages → 3
Only 110 → 100, 120 → 110 and 120 → 100 qualify.
Why? [0,1] has one 0 and one 1 → length 2.
💡 Key idea Count 1 as +1 and 0 as −1. A subarray has equal 0s and 1s exactly when the running balance is the same at both ends. Remember the first index of each balance and measure the distance when it repeats.
Edge / failure case an unbalanced array → 6
The last six numbers have three 1s and three 0s.
Why? 'tree': e appears twice, so it goes first: 'ee' then 't' and 'r' → 'eetr' ('eert' is also accepted).
💡 Key idea Count the characters and write each one repeated by its count, from the most frequent to the least.
Edge / failure case case-sensitive letters → 'bbAa'
b appears twice; 'A' and 'a' are different letters.
Why? [2,3,5,10]: if 5 is the sum of the specials 2 and 3, the outlier is 10. The total is 20 = 2·5 + 10.
💡 Key idea If s is the sum element and o the outlier, the total of the array is (special numbers) + s + o = 2s + o. So for every candidate s the outlier must be total − 2s. Check that this number exists (at a different position) and keep the biggest.
Edge / failure case equal values → 5
Special numbers 1,1,1,1,1, sum 5, outlier 5 (same value, different position).
Why? [1,2,3,2]: 1 and 3 appear once → 4.
💡 Key idea Count each number and add up the numbers whose count is exactly 1.
Edge / failure case all the same → 0
No number appears exactly once: 0.
Why? [[1,3],[2,2]]: 2 appears twice, 4 never appears → [2, 4].
💡 Key idea The grid holds the numbers 1…n² once each, except one repeated and one missing. Count them and report the value with count 2 and the one with count 0.
Edge / failure case a 3 × 3 grid → [9, 5]
9 appears twice, 5 is missing.
Why? 'good' appears on 3 different days, 'ok' and 'bad' on 2 → 'good'. If there is a tie the alphabetically smaller response wins.
💡 Key idea Turn every day's list into a set (duplicates within a day count once), count the responses over all days, and take the highest count, breaking ties by the smaller string.
Edge / failure case a tie → 'bad'
good, ok and bad each appear on 2 days; 'bad' is the smallest alphabetically.
Why? The best vertical line passes through 4 joints (at x = 4), so it crosses 6 − 4 = 2 bricks.
💡 Key idea A vertical line that crosses the fewest bricks goes through the most joints. Count how many rows have a joint at each x position (ignoring the right edge of the wall); the answer is the number of rows minus the best count.
Edge / failure case no inner joints → 3
Single-brick rows have no inner joint: the line crosses 3 bricks.
Why? 'abccccdd' has letters c×4, d×2, a×1, b×1: pairs give 4 + 2 = 6 letters, and one single letter can sit in the middle → 7 (e.g. 'dccaccd').
💡 Key idea Count the letters. Every pair of equal letters can go on both sides of the palindrome. If any letter is left over, one of them can be the centre.
Edge / failure case single letter → 1
One letter: itself.
Why? 'abcd' and 'cdab' can be turned into each other by swapping letters at even positions and at odd positions, so they are in one group; the words fall into 3 groups.
💡 Key idea A swap of two letters at positions of the same parity keeps the multiset of even-position letters and of odd-position letters. So two words are equivalent exactly when these two sorted lists are equal — count the distinct signatures.
Edge / failure case permutations → 3
Letters can only swap within even or odd positions: 3 groups.
Why? Reversals can sort any array, so [1,2,3,4] and [2,4,1,3] can be made equal: they hold the same numbers.
💡 Key idea Reversing sub-arrays can reorder the array in any way (adjacent swaps are reversals of length 2). So the two arrays can be made equal exactly when they contain the same numbers.
Edge / failure case different numbers → False
11 is not in the target.
Why? 'thequickbrownfoxjumpsoverthelazydog' uses every letter a–z.
💡 Key idea The sentence has only lower-case letters, so it is a pangram exactly when it has 26 different letters.
Edge / failure case not a pangram → False
Most letters are missing.
Why? [2,2,3,4]: 2 appears twice, so 2 is lucky (value = frequency). 3 and 4 appear once → the answer is 2.
💡 Key idea Count how often each number appears; a number is lucky if its value equals its count. Return the largest lucky number, or −1.
Edge / failure case no lucky number → -1
5 appears once: no lucky number.
Why? [1,2,2,1] and [2,2]: 2 appears twice in both → [2,2].
💡 Key idea Count the numbers of the first array. Walk through the second array; when a number still has a positive count, add it to the answer and decrease the count — so each number is used as often as it appears in both.
Edge / failure case different counts → [9, 4]
9 and 4 are in both; each is used as often as it appears in both (once).
Why? Jewels 'aA': the stones 'aAAbbbb' contain a, A, A → 3 jewels.
💡 Key idea Put the jewel types in a set and count the stones that are in it.
Edge / failure case case matters → 0
Upper and lower case are different.
Why? A = [1,3,2,4], B = [3,1,2,4]: after 2 numbers both prefixes hold {1,3} → 2 common; after 3 → 3; after 4 → 4.
💡 Key idea Count how often each number has appeared in either prefix. When a number's count reaches 2 it is present in both prefixes, so the running common total goes up. Record the total after each position.
Edge / failure case late match → [0, 1, 3]
Only after the third number are both prefixes equal.
Why? [1,3,2,2,5,2,3,7]: the numbers 2 (×3) and 3 (×2) differ by exactly 1 → 5.
💡 Key idea A harmonious subsequence uses just two values that differ by 1, and the order does not matter. Count the numbers; for every x add count[x] + count[x + 1] when both exist and keep the largest.
Edge / failure case all equal → 0
There is no pair with a difference of 1.
Why? [1,1,2]: two rabbits say '1' (they are a pair of the same colour) and one says '2' (needs two more of its colour) → at least 2 + 3 = 5 rabbits.
💡 Key idea A rabbit answering a belongs to a colour group of size a + 1. All rabbits answering a can share groups of that size, so with c such rabbits we need ceil(c / (a + 1)) groups, i.e. ceil(c / (a + 1)) · (a + 1) rabbits. Add this over all answers.
Edge / failure case one big group → 11
Three rabbits say 10 others share the colour: a group of 11.
Why? [-2,0,3,-5,2,-1]: the sum of positions 0–2 is −2 + 0 + 3 = 1.
💡 Key idea Precompute pre[i] = sum of the first i numbers. The sum of positions left…right is then pre[right + 1] − pre[left], answered in O(1).
Edge / failure case one element → [5]
A single element.
Why? [1,-1,5,-2,3] and k=3: the subarray [1,-1,5,-2] adds to 3 and has length 4 (the longest).
💡 Key idea A subarray sums to k when two prefix sums differ by k. Store the first index of every prefix sum; at each position look up (prefix − k) and measure the distance.
Edge / failure case negative numbers → 2
The subarray [-1,2] sums to 1.
Why? [1,2,3,4] → 1, 1+2, 1+2+3, 1+2+3+4 = [1,3,6,10].
💡 Key idea Entry i of the answer is the sum of the first i + 1 numbers: keep a running total.
Edge / failure case mixed numbers → [3, 4, 6, 16, 17]
3, 4, 6, 16, 17.
Why? [1,1,2,1,1] with k = 3: the subarrays [1,1,2,1] and [1,2,1,1] contain exactly three odd numbers → 2.
💡 Key idea Keep a running count of odd numbers and how many times each count was seen as a prefix. A subarray ending here has exactly k odds if an earlier prefix had (odd − k) odd numbers.
Edge / failure case no odd numbers → 0
No odd numbers at all.
Why? [2,1,2]: at index 1 the left sum is 2 and the product of the right side is 2 → balanced, and it is the smallest such index.
💡 Key idea Precompute the product of every suffix. The left sum is at most the total sum, so a suffix product larger than that can never match; cap it to keep the numbers small. Sweep from the left with a running sum and return the first index where the sum equals the product of what remains.
Edge / failure case no balanced index → -1
Left sum 0 and right product 1 differ: −1.
Why? Boxes '110': moving all balls to box 0 costs 1, to box 1 costs 1, to box 2 costs 2 + 1 = 3.
💡 Key idea Sweep left to right keeping the number of balls seen (cnt) and the cost to move them to the current box (ops): each step every ball needs one more move, so ops += cnt. Do the same from the right and add both sweeps for every box.
Edge / failure case balls on the right → [11, 8, 5, 4, 3, 4]
Balls in boxes 2, 4 and 5.
Why? [1,3,2,3,1]: the pairs (3,1) and (3,1) have 3 > 2·1 → 2 reverse pairs.
💡 Key idea Merge sort the array. While merging two sorted halves, for every number x on the left count the numbers y on the right with x > 2y (a moving pointer, since both halves are sorted). Then merge normally.
Edge / failure case three pairs → 3
(4,1), (3,1), (5,1) are the reverse pairs.
Why? [5,2,3,1] → split into [5,2] and [3,1], sort each, merge: [1,2,3,5].
💡 Key idea Split the array in halves, sort each half recursively and merge the two sorted halves by always taking the smaller front element.
Edge / failure case duplicates → [0, 0, 1, 1, 2, 5]
Equal numbers stay together.
Why? [40,10,20,30]: sorted that is 10,20,30,40 → ranks 1,2,3,4 → [4,1,2,3].
💡 Key idea Sort the distinct values, give each its rank (1, 2, 3 …) in a dictionary, then replace every number by its rank.
Edge / failure case duplicates → [5, 3, 4, 2, 8, 6, 7, 1, 3]
Equal numbers share a rank.
Why? [2,1,3,3], k=2: the two largest numbers are the 3s → [3,3].
💡 Key idea The k numbers with the largest values give the largest sum. Find their indices and read the numbers in index order so the subsequence keeps the original order.
Edge / failure case negative numbers → [-1, 3, 4]
The three largest are -1, 3, 4 (kept in their original order).
Why? [3,5,1] sorted is 1,3,5 — every gap is 2 → true.
💡 Key idea Sort the numbers and check that all neighbouring differences are equal.
Edge / failure case not an AP → False
Gaps 1 and 2.
Why? The ocean is on the right. Building 3 (height 1) sees it; building 2 (height 3) is taller than everything right of it; building 1 (height 2) is blocked by the 3; building 0 (height 4) sees over everything.
💡 Key idea Walk from the right (the ocean) towards the left, remembering the tallest building seen so far. A building has an ocean view only if it is strictly taller than that.
Edge / failure case one ocean view → [3]
Only the last building is taller than everything on its right.
Why? '())': the last ')' has no '(' to match, so we must add one '(' → 1.
💡 Key idea Count the currently open '('. A ')' closes one if possible; otherwise it is unmatched and needs one added '('. In the end every still-open '(' needs a ')'.
Edge / failure case only open brackets → 3
Three '(' stay open: add three ')'.
Why? 'deeedbbcccbdaa', k=3: remove eee → 'ddbbcccbdaa'; remove ccc → 'ddbbbdaa'; remove bbb → 'dddaa'; remove ddd → 'aa'.
💡 Key idea Keep a stack of [letter, count]. A letter equal to the top increases its count; when the count reaches k the whole run is popped. Whatever stays is the answer.
Edge / failure case nothing to remove → 'abcd'
No two equal neighbours: nothing is removed.
Why? The biggest all-1s rectangle in the grid has area 6 (2 rows × 3 columns).
💡 Key idea Treat each row as the bottom of a histogram where each column's height is the number of consecutive 1s above it. The largest rectangle in each histogram (Largest Rectangle in Histogram, solved with a monotonic stack) is a candidate.
Edge / failure case no ones → 0
No 1s: area 0.
Why? '(()())(())' has two primitive pieces; removing each one's outer pair gives '()()' + '()' = '()()()'.
💡 Key idea Track the depth. A '(' that starts at depth 0 and a ')' that returns to depth 0 are outer brackets — skip those, keep the others.
Edge / failure case only outer brackets → ''
Each primitive is just '()': everything is removed.
Why? ['5','2','C','D','+']: 5, 2, then C removes the 2, D doubles 5 → 10, + adds the last two (5 + 10) = 15. Scores 5 + 10 + 15 = 30.
💡 Key idea Keep a stack of valid scores. A number is pushed; 'C' pops the last score; 'D' pushes double the last; '+' pushes the sum of the last two. The answer is the sum of the stack.
Edge / failure case negative score → 27
Negative scores work the same way: total 27.
Why? [3,1,2,4]: the minimums of all subarrays are 3,1,1,1,1,2,2,4,… adding to 17.
💡 Key idea For each element count the subarrays in which it is the minimum: it can extend left until a smaller element and right until a smaller-or-equal one. Two monotonic-stack passes give these distances; the contribution is value × left × right.
Edge / failure case a small value at the end → 444
Every subarray containing the 3 has minimum 3.
Why? In '(1+(2*3)+((8)/4))+1' the deepest place is the 8, inside three open brackets → 3.
💡 Key idea Walk the string and keep the number of currently open brackets; the answer is the largest value it reaches.
Edge / failure case no nesting → 1
Only one level of brackets at a time.
Why? 'cbacdcbc' → 'acdb': every letter once, and it is the smallest possible order.
💡 Key idea Build the answer on a stack. When a smaller letter comes and the letter on top will appear again later, pop the top (it can be re-added later). A letter already in the stack is skipped.
Edge / failure case a small string → 'abc'
'abc' is the smallest result.
Why? [5,3,4,4,7,3,6,11,8,5,11]: in each step every number smaller than its left neighbour is removed; after 3 steps the array is non-decreasing.
💡 Key idea A number is removed after (1 + the longest time among the numbers it swallows) steps. Keep a decreasing stack of (value, steps). For a new number pop smaller-or-equal entries and take the maximum of their steps; if a bigger number remains on the stack the new one dies after max + 1 steps, otherwise it never dies (0).
Edge / failure case already sorted → 0
Already non-decreasing: 0 steps.
Why? '(()(()))': () = 1, (()) = 2, (A) = 2·A. The inner part scores 1 + 2 = 3, doubled = 6.
💡 Key idea Keep a stack of partial scores, starting with 0. On '(' push 0. On ')' pop v and add max(2·v, 1) to the new top: an empty pair '()' (v = 0) is worth 1, a wrapped group is doubled.
Edge / failure case a single pair → 1
One pair: 1.
Why? [2,-1,2] with k=3: the whole array adds up to 3 → length 3.
💡 Key idea With prefix sums, a subarray (i, j] has sum pre[j] − pre[i]. Keep a deque of candidate start indices with INCREASING prefix sums. For each j pop from the front while the sum is at least k (record the length), and pop from the back every start whose prefix sum is not smaller than pre[j] (it can never be a better start).
Edge / failure case impossible → -1
Even the whole array adds to only 3: −1.
Why? '(()))': the first '(' needs '))', the second '(' needs '))' — we have '))' and one more ')'. One more ')' for the first '(' is missing → 1 insertion.
💡 Key idea Every '(' needs TWO ')'. Track how many ')' are still owed (need). A '(' adds 2; if need is odd when a '(' arrives, insert one ')' first. A ')' reduces need; if need would go negative insert a '(' (count 1, and now one more ')' is owed). At the end the owed ')' must be inserted.
Edge / failure case only closing brackets → 5
Seven ')' with no '(' need four '(' and one more ')' → 5.
Why? List 3→4→1→(back to 3) is sorted ascending with the wrap between 4 and 1. Inserting 2 goes after 1: 3→4→1→2.
💡 Key idea Walk around the circle looking for a spot where prev ≤ value ≤ next, or the wrap point (the biggest then the smallest) where the value is ≥ the biggest or ≤ the smallest. If we come back to the start, all values are equal: insert anywhere.
Edge / failure case empty list → [1, True]
An empty list becomes one node pointing to itself.
Why? 1 → 1 → 2 becomes 1 → 2.
💡 Key idea Because the list is sorted, duplicates are neighbours. If the next node has the same value, unlink it; otherwise move on.
Edge / failure case two repeated values → [1, 2, 3]
Both repeated values are reduced to one.
Why? The list 3→2→0→−4 loops back to the node 2, so the cycle starts at the node with value 2.
💡 Key idea Move a slow (1 step) and a fast (2 steps) pointer. If they meet there is a cycle. Put one pointer back to the head and move both one step at a time: they meet exactly at the start of the cycle.
Edge / failure case no cycle → None
No cycle: None.
Why? Values between 7 and 15 are 7, 10 and 15 → 32.
💡 Key idea In a binary search tree, if a node is smaller than low then its whole left side is too small; if it is bigger than high its whole right side is too big. Skip those and add the matching nodes.
Edge / failure case a deeper tree → 23
Only 6, 7 and 10 are in range: 23.
Why? The in-order walk of [4,2,5,1,3] is 1,2,3,4,5. We link each node to the previous one (left = previous, right = next) and close the ring.
💡 Key idea An in-order traversal visits a BST in sorted order. Remember the previous visited node: link prev.right = node and node.left = prev. At the end connect the first and the last node to make it circular.
Edge / failure case three nodes → [[1, 2, 3], 3]
In-order 1,2,3; 3 links back to 1.
Why? [1,2,3,4,5,6] fills every level left to right → complete. In [1,2,3,4,5,null,7] the missing node comes before 7 → not complete.
💡 Key idea Do a level-order walk and also queue the missing children as None. After the first None, every remaining entry must be None too; a real node after a gap means the tree is not complete.
Edge / failure case gap in the last level → False
The gap before 7 breaks the left-to-right filling.
Why? '4(2(3)(1))(6(5))': 4 is the root, (2(3)(1)) is its left subtree, (6(5)) its right subtree.
💡 Key idea Read a number to make a node. If a '(' follows, parse the left child and skip its ')'; if another '(' follows, parse the right child the same way. A shared index moves through the string.
Edge / failure case negative number → [-4, 2, 6, 3, 1, 5, 7]
A negative root and a node with two children on the right.
Why? Tree 1 → right child 2 → left child 3. In-order visits left, node, right: 1, 3, 2.
💡 Key idea Go as far left as possible, pushing nodes on a stack. Pop one, record it, then continue with its right child.
Edge / failure case empty tree → []
An empty tree gives an empty list.
Why? The deepest nodes are 7 and 4 (both below node 2), so the smallest subtree containing them is rooted at 2.
💡 Key idea For each node compute the depth of its subtree and its best answer. If one side is deeper, the answer comes from that side; if both sides are equally deep, this node is the answer.
Edge / failure case single node → [1]
A single node is its own answer.
Why? The deepest leaves 7 and 4 hang under node 2, so their lowest common ancestor is 2.
💡 Key idea The LCA of the deepest leaves is the node whose two sides are equally deep. Return (depth, node) up the tree: pick the deeper side's answer, or this node when the depths are equal.
Edge / failure case one deepest leaf → [2]
The only deepest leaf is 2, so it is the answer.
Why? The tree [3,4,5,1,2] contains the subtree [4,1,2] at its left child → true.
💡 Key idea For every node of the big tree test whether the tree starting there is identical to subRoot (same shape and values).
Edge / failure case almost the same subtree → False
The node 4 has an extra child 0 below it, so it is not identical.
Why? In the tree [5,3,6,2,4,null,7] the values 2 and 7 add up to 9 → true.
💡 Key idea Visit every node; before adding its value to a set, check whether (k − value) is already there.
Edge / failure case no pair → False
No two values add up to 28.
Why? For n = 3 there are 5 different BSTs that use the values 1, 2, 3.
💡 Key idea For the range lo…hi try each value i as the root. Every tree built from lo…i−1 can be the left subtree and every tree from i+1…hi the right subtree — combine all pairs.
Edge / failure case n = 1 → [[1]]
One value: a single node.
Why? Left leaves are 9 and 15 → 24.
💡 Key idea Walk the tree and remember whether we came from a left child. A node with no children that was reached as a left child is a left leaf.
Edge / failure case single node → 0
A lone root is not a left leaf.
Why? Two root-to-leaf paths add up to 22: 5→4→11→2 and 5→8→4→5.
💡 Key idea Walk down from the root, keeping the path and the remaining sum. At a leaf with remaining sum 0, copy the path into the answer. Remove the node when going back up.
Edge / failure case no path → []
The paths sum to 3 and 4, not 5.
Why? The target is the node 3 in the original; walking the clone along the same path leads to its twin.
💡 Key idea Traverse the original and the clone at the same time. When the original node is the target (same object), return the clone node at that position.
Edge / failure case target is the root → [1, True]
The target is the root itself.
Why? Deleting 3 and 5 from [1,2,3,4,5,6,7] leaves the trees [1,2,null,4], [6] and [7].
💡 Key idea DFS with a flag telling whether the node is a root of a new tree (its parent was deleted, or it is the real root). A node that is not deleted and is a root joins the answer. Children of a deleted node get the flag; deleted nodes are cut off by returning None.
Edge / failure case delete a leaf → [[1, 2, 4]]
Deleting the leaf 3 leaves a single tree.
Why? The closest leaf is 9, two nodes from the root → depth 2.
💡 Key idea Level-order search: the first leaf we meet is the closest one, so its level is the minimum depth.
Edge / failure case a chain → 5
A chain: the only leaf is 5 levels down.
Why? The widest level is the third one: positions 0 and 3 (counting the empty slot between) → width 4.
💡 Key idea Number the nodes like a heap (children of i are 2i and 2i+1), as if the tree were complete. The width of a level is last index − first index + 1. Subtract the first index of the level to keep numbers small.
Edge / failure case a skewed last level → 7
The last level spans 7 positions.
Why? A BST that is a straight line 1→2→3→4 becomes a balanced tree rooted at the middle value.
💡 Key idea The in-order walk of a BST is sorted. Collect it, then build a new tree: the middle value becomes the root and the left and right halves become the subtrees (recursively).
Edge / failure case single node → [1]
One node is already balanced.
Why? Tree 1 → right child 2 → left child 3. Preorder visits node, left, right: 1, 2, 3.
💡 Key idea Pop a node from the stack, record it, then push its right child first and its left child second so the left one is processed next.
Edge / failure case empty tree → []
An empty tree.
Why? In the tree 2 with children 1 and 3, the successor of 1 is 2.
💡 Key idea The successor of p is the smallest value larger than p. Walk down from the root: if p is smaller than the current node, this node is a candidate and we go left; otherwise go right.
Edge / failure case no successor → None
3 is the largest value: no successor.
Why? Adding 5 to the max tree [4,1,3,null,null,2] makes 5 the new root with the old tree as its left child.
💡 Key idea The new value was appended at the END of the original list. So it can only go on the right spine: go right while the node is bigger than the value; at the first node that is smaller (or at the end) make the new value take its place with that subtree as its left child.
Edge / failure case a smaller value → [5, 2, 4, None, 1, None, 3]
3 is smaller than 4, so it goes below it.
Why? In [10,3,4,2,1] the node 10 equals 3 + 4 + 2 + 1 and the node 3 equals 2 + 1 → 2 nodes.
💡 Key idea Compute every subtree sum bottom-up (post-order). A node counts when its value equals the sum of its left and right subtree sums.
Edge / failure case a zero leaf → 1
A leaf with 0 equals the empty sum 0.
Why? In the tree 2 with children 1 and 3, the successor of the node 1 is its parent 2.
💡 Key idea If the node has a right child, the successor is the leftmost node of that subtree. Otherwise climb up while we are a right child; the first ancestor reached from a left child is the successor (none if we reach the root).
Edge / failure case no successor → None
3 is the largest: no successor.
Why? Preorder 8, 5, 1, 7, 10, 12: 8 is the root; 5, 1, 7 are smaller (left), 10, 12 larger (right).
💡 Key idea Read the preorder list once with a shared index. build(bound) makes the next number the root as long as it is below the bound; its left child uses the root's value as bound, the right child uses the parent's bound.
Edge / failure case two nodes → [1, None, 3]
3 is bigger than 1, so it is the right child.
Why? The right-most 0 has no 1 below it, so it is removed; the other branches contain a 1 and stay.
💡 Key idea Prune the children first. Then a node is removed (return None) if it is 0 and has no children left; otherwise it stays.
Edge / failure case no ones → []
No 1 anywhere: the whole tree is removed.
Why? Apples at 2, 4 and 5. Every edge that leads to an apple is walked down and back (2 seconds): 0–1, 1–4, 1–5, 0–2 → 4 edges × 2 = 8.
💡 Key idea An edge is worth walking only if its lower side contains an apple. DFS from the root: a child's subtree costs (its own cost + 2) when it has an apple anywhere inside it.
Edge / failure case one apple → 4
Only the path 0 → 1 → 2 and back: 4.
Why? A robot walks in an unknown 3×3 maze; after exploring we know the free cells and the target at the far corner, and the shortest path has 4 moves.
💡 Key idea You can only call master.canMove(d), master.move(d) and master.isTarget(). First explore with DFS (Depth-First Search): from each cell try the four directions, move into new free cells, record their coordinates (relative to the start) and move back afterwards. Then run a BFS (Breadth-First Search) on the recorded cells from the start to the target; return −1 if the target was never found.
Edge / failure case unreachable → -1
The target is walled off: −1.
Why? The longest path is 5 → 3 → 1 → 2 (or 4): 3 edges.
💡 Key idea For every node take the two deepest child subtrees. The longest path through the node is top1 + top2 edges. Return top1 + 1 to the parent, and keep the best path seen.
Edge / failure case two nodes → 1
A single edge.
Why? Node 0 has the children 1 (left) and 2 (right); node 2 has the child 3 (left). One root, every other node has exactly one parent, and all 4 nodes are reachable → true.
💡 Key idea A valid binary tree has exactly one node with no parent (the root), no node with two parents, and every node reachable from the root. Compute in-degrees, find the root, then BFS and make sure each node is met once and all n are visited.
Edge / failure case a cycle → False
Nodes 0 and 1 point at each other: a cycle, no root.
Why? There are 4 different shortest routes (7 minutes) from 0 to 6 in the example graph.
💡 Key idea Run Dijkstra and keep for every node the number of shortest paths found so far. When a strictly shorter way to a node appears, copy the count of its predecessor; when an equally short way appears, add the counts (modulo 10⁹+7).
Edge / failure case a single node → 1
Already at the destination: one (empty) way.
Why? 0→1 costs 3. At node 1 the edge 3→1 can be reversed to 1→3 for twice its weight (2): total 5.
💡 Key idea Using a switch to reverse an incoming edge is the same as being allowed to walk any edge backwards at double cost. So add, for every edge u→v of weight w, an extra edge v→u of weight 2w and run Dijkstra from 0 to n − 1.
Edge / failure case unreachable → -1
Node 2 has no edge at all: −1.
Why? k=3 with [4,5,8,2]: the 3rd largest is 4. Add 3 → still 4; add 5 → 5; add 10 → 5; add 9 → 8; add 4 → 8.
💡 Key idea Keep only the k largest numbers in a min-heap. Its top is the k-th largest overall. A new number is pushed, and if the heap grows beyond k the smallest is dropped.
Edge / failure case empty start → [-3, -2, -2]
With k = 1 it is the maximum so far.
Why? Pick one number from each row: with rows [1,3,11] and [2,4,6] the sums sorted are 3, 5, 5, 7, 7, 9 … the 5th is 7.
💡 Key idea Combine the rows one at a time. After merging the first i rows keep only the k smallest sums — a larger sum can never be among the k smallest overall. Adding the next row to those k sums gives at most k·n candidates; sort and cut again.
Edge / failure case three rows → 9
Three rows: the 7th smallest sum is 9.
Why? The terrain holds 4 units of water in its low spots.
💡 Key idea Water can only escape over the border. Put all border cells in a min-heap and always process the lowest one. Each unvisited neighbour holds max(0, current wall − its height) water, and then joins the heap with height max(wall, own height).
Edge / failure case a basin → 10
A pit of 2s with a 1 inside holds 10 units.
Why? [2,3,4,7,11]: the missing numbers are 1, 5, 6, 8, 9, 10 …; the 5th missing is 9.
💡 Key idea At index i the number of missing positives before arr[i] is arr[i] − (i + 1), which only grows. Binary search the first index where that is at least k; the answer is then lo + k.
Edge / failure case k beyond the array → 6
Everything up to 4 is present; the missing ones are 5, 6.
Why? [0,2,1,0] rises to 2 at index 1, then falls.
💡 Key idea If arr[mid] < arr[mid+1] we are still climbing, so the peak is to the right; otherwise mid could be the peak or the peak is to the left. Halve until one index remains.
Edge / failure case peak near the end → 2
The array rises to 5 at index 2.
Why? [4,7,9,10]: the missing numbers after 4 are 5, 6, 8, 11 …; the 1st missing is 5.
💡 Key idea At index i the numbers missing before nums[i] are nums[i] − nums[0] − i, which only grows. Binary search the first index where that reaches k, then count back from there.
Edge / failure case k beyond the last number → 6
The missing numbers are 3, 5, 6 → the 3rd is 6.
Why? Ribbons [9,7,5], k=3: cutting length 5 gives 1 + 1 + 1 = 3 pieces; length 6 would give only 1 + 1 + 0 = 2.
💡 Key idea For a length L, ribbon r gives r // L pieces. The count of pieces drops as L grows, so binary search the largest L that still gives at least k pieces (0 if none).
Edge / failure case k pieces → 4
Length 4 gives 1 + 1 + 2 = 4 pieces.
Why? Flowers bloom on days [1,10,3,10,2]; we need 3 bouquets of 1 flower. On day 3 the flowers 1, 3, 2 are open → 3 bouquets.
💡 Key idea If it works on day d it works on any later day, so binary search d. To test a day, scan the garden and count groups of k adjacent flowers that are all in bloom.
Edge / failure case not enough flowers → -1
3 bouquets of 2 flowers need 6 flowers but there are only 5: −1.
Why? 5 coins: rows of 1, 2, 2 → 2 full rows (the 3rd row would need 3).
💡 Key idea k full rows need k(k+1)/2 coins. That grows with k, so binary search the largest k with k(k+1)/2 ≤ n.
Edge / failure case n = 8 → 3
Rows 1, 2, 3 use 6 coins; 2 are left.
Why? Citations [0,1,3,5,6]: 3 papers (3, 5, 6) have at least 3 citations → h = 3.
💡 Key idea With the citations sorted ascending, the paper at index i has n − i papers at or above it. Find the first i where citations[i] ≥ n − i; then h = n − i. Binary search does it in O(log n).
Edge / failure case one huge paper → 2
Two papers have at least 2 citations.
Why? [1,2,5,9], threshold 6: divisor 5 gives 1 + 1 + 1 + 2 = 5 ≤ 6, divisor 4 gives 1 + 1 + 2 + 3 = 7 > 6 → 5.
💡 Key idea A bigger divisor makes the sum of rounded-up quotients smaller (or equal). Binary search the smallest divisor whose sum is at most the threshold.
Edge / failure case tight threshold → 44
Each number must give 1 → the divisor must be at least 44.
Why? '()())()': removing one ')' gives '(())()' or '()()()' — both valid with the minimum of 1 removal.
💡 Key idea Try removing 0 characters, then 1, then 2 … level by level. The first level that contains a valid string is the minimum, and every valid string on that level is an answer (a set removes duplicates).
Edge / failure case all brackets invalid → ['']
Both brackets must go: an empty string.
Why? On a 4×4 board there are exactly 2 ways to place 4 queens that never attack each other.
💡 Key idea Place one queen per row. A square is safe if its column, its ↘ diagonal (row − col) and its ↙ diagonal (row + col) are all unused. Place, recurse to the next row, and undo.
Edge / failure case n = 1 → [['Q']]
One queen on a 1×1 board.
Why? 'aab' can be cut as a | a | b or aa | b — every piece is a palindrome.
💡 Key idea From the current start, try every end; if s[start:end] is a palindrome add it, recurse on the rest, and remove it again. When the start reaches the end of the string record the partition.
Edge / failure case single letter → [['a']]
One letter: a single partition.
Why? [1,2,2] has 6 different subsets: [], [1], [1,2], [1,2,2], [2], [2,2].
💡 Key idea Sort the numbers so equal ones sit together. While choosing the next element at one depth, skip it if it equals the previous choice at the same depth — that would produce a duplicate subset.
Edge / failure case single number → [[], [0]]
One number: the empty subset and [0].
Why? 'a1b2': each letter can be lower or upper case, digits stay → 2 × 2 = 4 strings.
💡 Key idea Build the strings character by character. A digit is appended to every string; a letter doubles the list: one copy with the lower-case letter, one with the upper-case letter.
Edge / failure case digits around a letter → ['3z4', '3Z4']
Only the letter z has two cases.
Why? Length 2: wrap the empty middle with a pair — 11, 69, 88, 96 (no leading 0).
💡 Key idea A strobogrammatic number of length n is a strobogrammatic number of length n−2 wrapped in a pair (0…0, 1…1, 6…9, 8…8, 9…6). The middle is empty (n even) or one of 0, 1, 8 (n odd). The outermost pair must not be 0.
Edge / failure case n = 1 → ['0', '1', '8']
A single digit must look the same upside down: 0, 1, 8.
Why? 'un' + 'iq' = 'uniq' (4 unique letters); 'ue' clashes with 'un' (u twice) → best is 4.
💡 Key idea Turn each word into a 26-bit mask (skip words with a repeated letter). Keep all masks reachable so far with their lengths; a word can be added to a combination only if the masks do not overlap.
Edge / failure case choose the right pair → 6
'cha' + 'ers' has 6 different letters.
Why? n = 3 → [3,1,2,3,2]: 1 appears once, 2 twice with two positions between them, 3 twice with three positions between them.
💡 Key idea Fill the sequence left to right. At the first empty slot try the numbers from n down to 1: a number v > 1 also takes slot i + v, number 1 takes only one slot. Trying big numbers first makes the first complete sequence the largest one.
Edge / failure case n = 1 → [1]
Only the number 1.
Why? The best pairing of 3 students with 3 mentors adds up to 3 + 2 + 3 = 8 matching answers.
💡 Key idea There are at most 8 students, so try every way to assign mentors (permutations). Precompute how many answers match for every student/mentor pair and take the best total.
Edge / failure case nothing matches → 0
No answer ever matches: 0.
Why? 'letsleetcode', k=2: the subsequence 'let' repeated twice ('letlet') is a subsequence of the string, and it is the longest/largest such.
💡 Key idea Only letters that occur at least k times can be used, and the answer has at most n / k letters. Grow candidates letter by letter (BFS), keep those whose k-fold repetition is still a subsequence of s, and remember the longest (largest alphabetically on ties).
Edge / failure case tiny string → 'b'
'b' twice is 'bb'.
Why? 'abcdeca': the longest palindromic subsequence is 'acdca' (length 5), so only 7 − 5 = 2 letters must go (b and e); 2 ≤ k = 2 → true.
💡 Key idea The fewest characters to delete to get a palindrome is length − (longest palindromic subsequence). Compute that subsequence with an interval DP and compare with k.
Edge / failure case too many removals → False
Six different letters need five deletions: false.
Why? With windows of length 2 the best three non-overlapping ones start at 0 (sum 3), 3 (sum 8) and 5 (sum 12): total 23.
💡 Key idea Compute the sum w[i] of every window of length k. For each possible middle window j, take the best window to its left (start ≤ j − k) and the best to its right (start ≥ j + k), precomputed in two passes. Keep the best total, preferring the earliest starts.
Edge / failure case ties → [0, 2, 4]
Many ties: the earliest starts win.
Why? 'rabbbit' contains 'rabbit' as a subsequence in 3 different ways (choose which two of the three b's to use).
💡 Key idea dp[j] is the number of ways to form the first j letters of t from the part of s read so far. For each letter of s that equals t[j−1], we can use it: dp[j] += dp[j−1]. Update j from high to low so each letter is used once.
Edge / failure case many matches → 5
There are 5 ways to pick b, a, g in order.
Why? [3,4,16,8]: sorted 3, 4, 8, 16 — 4 divides 8 and 8 divides 16, so [4,8,16] is the largest group where every pair divides.
💡 Key idea Sort the numbers. If a divides b and b divides c then a divides c, so we only need chains. dp[i] is the longest chain ending at nums[i]; remember the previous index to rebuild it.
Edge / failure case a tie → [1, 2]
[1,2] or [1,3] are both valid answers; [1,2] is returned.
Why? [1,2,3], target 4 has 7 ordered ways: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1, 2+2, 1+3, 3+1.
💡 Key idea dp[t] is the number of ordered ways to reach t. The last number can be any x ≤ t, so dp[t] = Σ dp[t − x]. dp[0] = 1.
Edge / failure case no way → 0
9 is larger than the target: 0 ways.
Why? '1*': the star can be 1–9. As two letters: 11–19 (9 ways); as single letters 1, then * = 1…9 (9 ways) → 18.
💡 Key idea dp[i] is the number of ways to decode the first i characters. Add the single-character ways (a digit 1–9 counts once, '*' counts 9 times) times dp[i−1], and the two-character ways (like 1* = 9 values, 2* = 6 values, ** = 15 values) times dp[i−2]. Everything modulo 10⁹+7.
Edge / failure case star after a 2 → 15
2 then 1–9 as single letters (9) plus 21–26 as pairs (6) → 15.
Why? [1,3,5,4,7]: the longest increasing subsequences have length 4: 1,3,5,7 and 1,3,4,7 → 2.
💡 Key idea For each i keep the length of the longest increasing subsequence ending there and how many such subsequences exist. A previous smaller number j extends it: if it gives a longer length replace the count, if it ties add the counts.
Edge / failure case all equal → 5
Strictly increasing: each single 2 is a subsequence of length 1 → 5.
Why? A 5×5 grid with one hole at (4,2): the biggest plus has order 2 (arm length 1 on each side).
💡 Key idea The plus around a cell is limited by the shortest of its four arms. For every cell compute how many consecutive non-hole cells end there from the left, right, top and bottom; the order is the minimum of the four. Take the maximum.
Edge / failure case no plus → 0
The only cell is a hole: no plus sign.
Why? [1,15,7,9,2,5,10], k=3: blocks [1,15,7] → 15×3 = 45, [9] → 9, [2,5,10] → 10×3 = 30: total 84.
💡 Key idea Cut the array into blocks of length at most k; every block turns into its maximum repeated. dp[i] is the best sum for the first i numbers: try every last block length j ≤ k and take dp[i−j] + j × (max of that block).
Edge / failure case more numbers → 83
Blocks of up to 4 give 83.
Why? [1,3,5,4] and [1,2,3,7]: swapping position 3 gives [1,3,5,7] and [1,2,3,4] — both increasing with 1 swap.
💡 Key idea At each index we either keep or swap the pair. keep / swap hold the fewest swaps so far for each choice at the previous index. A choice is allowed if both rows still increase (same decision as before) or cross-increase (opposite decision).
Edge / failure case swap in the middle → 1
Swapping index 1 makes both rows increasing.
Why? 'aab' → 'aa' | 'b': one cut.
💡 Key idea cut[i] is the minimum number of cuts for the first i letters (initially i − 1). Every palindrome found by expanding around a centre s[l..r] lets the prefix ending at r be cut at l: cut[r+1] = min(cut[r+1], cut[l] + 1).
Edge / failure case no palindrome longer than 1 → 1
Two different letters need one cut.
Why? Piles [5,3,4,5]: Alice takes the first 5, Bob takes 5 or 4 … Alice can always end ahead → true.
💡 Key idea dp[i][j] is the best score difference (current player minus the other) for the piles i…j. The current player takes the left pile or the right pile and then faces the opponent's best difference on the rest: dp[i][j] = max(piles[i] − dp[i+1][j], piles[j] − dp[i][j−1]). Alice wins if dp[0][n−1] > 0.
Edge / failure case another game → True
Alice can also win here.
Why? n = 2: Alice picks 1, Bob has n = 1 and cannot move → Alice wins.
💡 Key idea dp[i] is true if the player to move wins with the number i. They win if some divisor x (0 < x < i) leaves the opponent in a losing position: not dp[i − x]. dp[1] is false. (It turns out Alice wins exactly for even n.)
Edge / failure case odd n → False
Alice has to subtract 1, then Bob wins at 2.
Why? g = [1,2,3], cookies [1,1]: the cookie 1 satisfies the child with greed 1; the other 1 is too small for greed 2 → 1 child.
💡 Key idea Sort both lists. Walk through the cookies from the smallest; each cookie goes to the least greedy child still waiting if it is big enough.
Edge / failure case more cookies than children → 2
Every child gets a cookie.
Why? Customers pay 5, 5, 5, 10, 20: the 10 gets a 5 back; the 20 gets 10 + 5 back. Everyone gets the right change → true.
💡 Key idea Only 5s and 10s are useful as change. For a 10 give one 5. For a 20 give 10 + 5 if possible (keeps the more flexible 5s), otherwise three 5s.
Edge / failure case not enough fives → False
For the 20 we only have 10 + 10: no 5 left → false.
Why? 'abc' with k = 2: three different letters, only two allowed → delete one whole letter (they all appear once) → 1 deletion.
💡 Key idea To lower the number of distinct letters you must delete ALL copies of some letters. It is cheapest to remove the letters with the smallest counts, so sort the counts and add up the smallest (distinct − k) of them.
Edge / failure case nothing to delete → 0
Already only 2 distinct letters.
Why? period 8, greens [2,3]: use the light with 3 green seconds for everyone. A car at r = 2 or 0 waits 0; r = 5 waits 8 − 5 = 3; r = 3 waits 8 − 3 = 5 → the worst wait is 5.
💡 Key idea Cars may share a light, and a longer green phase never hurts. So every car uses the light with the longest green time g. A car arriving at r = t % period waits 0 if r < g, otherwise period − r. The answer is the largest wait.
Edge / failure case always green → 0
The green phase is the whole period: nobody waits.
Why? 11891: map 1 → 9 gives 99899 (biggest); map 1 → 0 gives 00890 = 890 (smallest); the difference is 99009.
💡 Key idea For the largest value replace every copy of the first digit that is not 9 by 9. For the smallest value replace every copy of the first digit by 0. Subtract.
Edge / failure case two digits → 99
Max 99, min 00 = 0.
Why? 12 + 5 = 17.
💡 Key idea Return num1 + num2.
Edge / failure case negative number → -6
Negative numbers work the same.
Why? 10 ÷ 3: subtract 3·2 = 6 (adds 2), then 3 (adds 1) → 3, with 1 left over.
💡 Key idea Divide positives and fix the sign at the end. Repeatedly double the divisor (by shifting) as long as it still fits into what is left, subtract the biggest such multiple and add its multiplier to the answer. Watch the 32-bit overflow case.
Edge / failure case negative divisor → -2
7 ÷ −3 = −2.33 → truncated towards zero: −2.
Why? 1200 + 34 = 1234.
💡 Key idea Add from the last digit like on paper: take a digit of the array (if any), the last digit of k, plus the carry; write the last digit of the total and carry the rest.
Edge / failure case long carry → [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
The carry runs through every digit and adds a new digit.
Why? (1,1) → (3,4): 2 diagonal steps and 1 straight step = 3 seconds. (3,4) → (−1,0): 4 seconds. Total 7.
💡 Key idea In one second you can move one step in x, in y, or diagonally. Going from one point to the next therefore takes max(|dx|, |dy|) seconds. Sum over consecutive points.
Edge / failure case a straight line → 5
Only a straight move of 5.
Why? Length 4: even positions (0 and 2) take an even digit (5 choices), odd positions (1 and 3) take a prime digit 2, 3, 5, 7 (4 choices) → 5·4·5·4 = 400.
💡 Key idea Positions 0, 2, 4 … (there are ceil(n/2) of them) each have 5 choices, and the odd positions (floor(n/2) of them) each have 4. The answer is 5^ceil(n/2) · 4^floor(n/2) modulo 1,000,000,007 — use fast power.
Edge / failure case n = 1 → 5
One even position: 5 digits.
Why? 701 = 26·26 + 25: that is Z then Y → 'ZY'.
💡 Key idea It is base 26 where the digits are A…Z = 1…26 (no zero). Subtract 1 before taking the remainder so A…Z map to 0…25, write the letter and divide by 26.
Edge / failure case two letters → 'AB'
26 = Z, 27 = AA, 28 = AB.
Why? 10 = 3 + 3 + 4 → 3 · 3 · 4 = 36, the biggest product.
💡 Key idea Splitting into 3s gives the best product (a 4 is as good as 2 + 2). So peel off 3s while the rest is more than 4, then multiply by what is left. Small n (2 and 3) must be split in at least two parts.
Edge / failure case smallest n → 1
2 = 1 + 1 → 1.
Why? 4 ÷ 333 = 0.012012012… → '0.(012)'.
💡 Key idea Do long division by hand. The digits repeat as soon as a remainder appears for the second time. Store the position where each remainder first appeared and put the brackets around the repeating part.
Edge / failure case repeat after a digit → '0.1(6)'
1/6 = 0.1666…: only the 6 repeats.
Why? 26 = 0x1a: the lowest 4 bits are 1010 (a) and the next 4 bits are 0001 (1).
💡 Key idea Negative numbers use 32-bit two's complement, so mask them with 0xFFFFFFFF first. Then repeatedly take the lowest 4 bits as a hex digit and shift right by 4.
Edge / failure case negative number → 'ffffffff'
−1 is all ones in 32 bits: ffffffff.
Why? 27 = 3³ → true.
💡 Key idea 3 is prime, so n is a power of 3 exactly when it divides the largest power of 3 that fits in 32 bits (3¹⁹ = 1,162,261,467).
Edge / failure case not a power → False
45 = 3² · 5: false.
Why? 1 = 0001 and 4 = 0100 differ in 2 bit positions.
💡 Key idea x XOR y has a 1 exactly where the bits differ. Count the 1s.
Edge / failure case one different bit → 1
3 = 11 and 1 = 01 differ in one bit.
Why? Stones at 1, 2, 5: at least 1 move (5 → 3), at most 2 moves (5 → 4 → 3).
💡 Key idea Sort the three positions x < y < z. Maximum: move one stone one step at a time → z − x − 2. Minimum: 0 if already consecutive, 1 if one gap is at most 1 (a stone can jump into it), otherwise 2.
Edge / failure case already consecutive → [0, 0]
Already consecutive.
Why? At 12:30 the hour hand is halfway to 1 (15°) and the minute hand points at 6 (180°): the difference is 165°.
💡 Key idea The minute hand moves 6° per minute. The hour hand moves 30° per hour plus 0.5° per minute. Take the difference and the smaller of it and 360 − it.
Edge / failure case hands close together → 7.5
Hour hand at 97.5°, minute hand at 90°.
Why? Four darts lie on a circle of radius 2 around the origin, so one board of radius 2 covers all of them → 4.
💡 Key idea An optimal board can be moved until two darts lie on its edge. So for every pair of darts at most 2r apart compute the two circle centres of radius r through both and count the darts inside each circle (with a tiny tolerance). The best count is the answer (at least 1).
Edge / failure case darts spread out → 5
One board covers 5 of the 6 darts.
Why? S1 = 0, S2 = 011, S3 = 0111001, S4 = 011100110110001. The 11th bit of S4 is 1.
💡 Key idea S_n = S_(n−1) + '1' + reverse(invert(S_(n−1))). The middle bit (position 2^(n−1)) is 1. A bit in the left half is the same bit of S_(n−1). A bit in the right half is the inverted bit at the mirrored position 2·mid − k of S_(n−1).
Edge / failure case first bit → '0'
The first bit is always 0.
Why? Start 'a'; every round append the word with each letter moved one step forward: a → ab → abbc → abbcbccd. The 5th letter is 'b'.
💡 Key idea Do what the game says: repeat 'append the next-letter version of the whole word' until the word has at least k letters, then read position k.
Edge / failure case a later position → 'c'
The 10th letter is 'c'.
Why? The even numbers are 2, 4 and 6: 2 | 4 | 6 = 6.
💡 Key idea Start from 0 and OR in every even number.
Edge / failure case no even number → 0
No even number: 0.
Why? Between 100 and 300 the numbers whose digits go up by one are 123 and 234.
💡 Key idea Sequential-digit numbers are slices of '123456789'. For every length between the lengths of low and high take every slice of that length and keep those inside the range — they come out in increasing order.
Edge / failure case bigger range → [1234, 2345, 3456, 4567, 5678, 6789, 12345]
Four- and five-digit numbers.
Why? Capacity 4: 2 people ride from 1 to 5 and 3 more from 3 to 7. Between 3 and 5 there are 5 people → more than 4 → false.
💡 Key idea Mark +people at every pick-up point and −people at every drop-off point. Sweep the points in order with a running total; if it ever exceeds the capacity the trip is impossible.
Edge / failure case bigger car → True
5 people at most at the same time: fits.
Why? WordFilter(['apple']).f('a','e') → 0: the word 'apple' starts with 'a' and ends with 'e'.
💡 Key idea Words are short, so precompute every (suffix, prefix) pair of every word as the key 'suffix#prefix' and store the largest word index. A query is then one dictionary lookup of 'suff#pref'.
Edge / failure case two matches → [1, 1]
Both words match 'a…e'; the later index 1 wins.
Why? Diagonal 1 is just [1]; the next goes down-left: 2, 4; the next goes up-right: 7, 5, 3; then 6, 8; then 9.
💡 Key idea All cells on one diagonal share the same i + j. Collect each diagonal top-to-bottom; for even i + j the walk goes up-right, so reverse that diagonal.
Edge / failure case 2 × 2 matrix → [1, 2, 3, 4]
1, then 2, 3 on the next diagonal, then 4.
Why? Every diagonal from top-left to bottom-right holds one value: 1-1-1, 2-2-2, 3-3, and so on → true.
💡 Key idea A matrix is Toeplitz when every cell equals its up-left neighbour. Check that for all cells that have one.
Edge / failure case not Toeplitz → False
The diagonal 1,2 changes value.
Why? The board has one horizontal ship (the top-left X plus its neighbour is 1 ship) and one vertical ship on the right → 2.
💡 Key idea Ships never touch, so every ship has exactly one cell with no 'X' above it and none to its left. Count those cells.
Edge / failure case no ships → 0
An empty board has no ships.
Why? Clicking the bottom-left empty cell has no mine around it, so it opens ('B') and the opening spreads to its neighbours until cells next to the mine show numbers.
💡 Key idea Clicking a mine ends the game ('X'). Otherwise count the mines around the clicked cell. If there are some, show the number; if none, mark it 'B' and reveal all its unrevealed neighbours the same way.
Edge / failure case click on a mine → [['X', 'E'], ['E', 'E']]
Clicking a mine turns it into 'X' and the game ends.
Why? Diagonal 1 holds 2 and 4; going bottom-left to top-right gives 4 then 2. The result is 1, 4, 2, 7, 5, 3, 8, 6, 9.
💡 Key idea Cells on a diagonal share i + j. Walk the rows from the bottom up and append each value to its diagonal's list; then each diagonal is already ordered bottom-left to top-right. Join the diagonals in order (works for ragged rows too).
Edge / failure case ragged rows → [1, 6, 2, 8, 7, 3, 9, 4, 12, 10, 5, 13, 11, 14, 15, 16]
Rows of different length make diagonals of different length.
Why? Only one rectangle has four 1s in its corners: rows 1 and 3 share the columns 2 and 4.
💡 Key idea A rectangle is defined by two rows and two columns that are 1 in both rows. For each pair of rows count the columns where both are 1 (c); they form c·(c−1)/2 rectangles.
Edge / failure case a single row → 0
Only one row: no rectangle.
Why? The grid has 8 negative numbers.
💡 Key idea Rows and columns are sorted in decreasing order. Start at the top-right corner: if the cell is negative, the whole column below it is negative (add that many) and move left; otherwise move down.
Edge / failure case no negatives → 0
No negative numbers.
Why? The cell numbers 0, 1, 2 … must start in the top-left corner and every next cell must be a knight's jump away.
💡 Key idea Record the position of every number. The tour starts at 0 in the top-left corner; for k = 1 … n²−1 the cells k−1 and k must differ by (1,2) or (2,1) rows/columns.
Edge / failure case not a knight's tour → False
From 0 there is no knight jump to 1.
Why? The first column 1,4,7 becomes the first row.
💡 Key idea zip(*matrix) pairs up the i-th entries of all rows — exactly the columns.
Edge / failure case not square → [[1, 4], [2, 5], [3, 6]]
A 2 × 3 matrix becomes 3 × 2.
Why? Window size 3: [1] → 1.0, [1,10] → 5.5, [1,10,3] → 4.67, then 1 drops out: [10,3,5] → 6.0.
💡 Key idea Keep the last `size` numbers in a queue and their running total. A new number adds to the total; if the queue is too long the oldest number leaves and is subtracted.
Edge / failure case window of one → [4, 2]
Window size 1 always returns the latest number.
Why? [1,2,3,3,3]: pick(3) must return 2, 3 or 4 with equal chance (1/3 each).
💡 Key idea Scan the array. For the c-th occurrence of the target, replace the current answer with its index with probability 1/c. After the scan every occurrence is equally likely, and no extra memory is needed.
Edge / failure case one element → [0]
A single element is always picked.
Why? Every 3rd customer gets a 50% discount: the 1st bill 100 + 2·200 = 500 has no discount, the 3rd customer's bill is halved.
💡 Key idea Keep a dictionary product → price and a customer counter. A bill is the sum of price × amount; if the counter is a multiple of n apply the percentage discount.
Edge / failure case every second customer → [10, 30]
The 2nd customer gets 25% off 40.
Why? next() walks the sorted values 3, 7, 9, 15, 20; prev() steps back to the previous one.
💡 Key idea The in-order walk of a BST is sorted. Store it in a list with a pointer: next moves forward, prev moves back, and hasNext / hasPrev only check the pointer.
Edge / failure case one node → [False, True, 1, False, False]
A single node: nothing before, one next.
Why? After 3, 0, 2, 5, 4 the last two numbers multiply to 20, the last three to 40, and the last four include the 0 → 0.
💡 Key idea Keep prefix products. A product of the last k numbers is prefix[−1] / prefix[−1−k]. A 0 destroys everything before it, so on 0 restart the list; if k reaches back past the restart the answer is 0.
Edge / failure case a zero at the end → [None, 1, None, 0]
After a 0 the last number is 0.
Why? Rider 3 and driver 2 are first in line, so the first match is [2,3]. Rider 1 then cancels, so the next match finds nobody: [-1,-1].
💡 Key idea Keep one queue of waiting riders and one of available drivers. A match takes the front of both. For a cancel, remember the id in a set and skip cancelled riders when they reach the front.
Edge / failure case driver waits → [None, [-1, -1], None, [5, 7]]
No rider yet gives [-1,-1]; once rider 7 arrives driver 5 is matched.
Why? Edges 1–2 and 1–3 connect all three nodes; the edge 2–3 closes a cycle, so it is the redundant one.
💡 Key idea Add the edges one by one with Union Find. The first edge whose two ends are already in the same group closes the cycle — return it.
Edge / failure case bigger cycle → [1, 4]
1–4 closes the cycle 1-2-3-4.
Why? [1,1,2,2,1,1], range 0-5 needs frequency ≥ 4: 1 appears 4 times → 1; range 0-3 needs ≥ 3: none → −1.
💡 Key idea Each query asks for the range's mode (highest frequency, smallest value on ties) and checks it reaches the threshold. Split the array into blocks and precompute the mode of every block range. For a query, candidates are the mode of the full middle blocks plus every value in the two partial ends; count each candidate with binary search on its position list.
Edge / failure case tie and threshold → [2, -1]
Only 2 is frequent enough in the full range.
Why? The computers 0, 1, 2 are already wired (with one spare cable), computer 3 is alone: move the spare cable → 1 operation.
💡 Key idea To connect n computers you need at least n − 1 cables, otherwise the answer is −1. With enough cables each extra component needs exactly one move, so the answer is (number of connected components − 1). Count the components with Union Find.
Edge / failure case not enough cables → -1
4 cables cannot connect 6 computers (needs 5).
Why? '0110101': every second all '01' pairs swap to '10'. After 4 seconds all 1s are in front → 4.
💡 Key idea A 1 can only move left one step per second, and it cannot overtake another 1. Scan left to right keeping the number of zeros seen so far and the time t when the previous 1 finished: a new 1 that has zeros in front needs max(t + 1, zeros) seconds.
Edge / failure case already sorted → 0
No '01' exists, already finished.
Why? '10#11#12' → '10#' = j, '11#' = k, '1' = a, '2' = b → 'jkab'.
💡 Key idea Digits 1-9 are single letters a-i; two digits followed by '#' are 10-26 (j-z). Scan from the right: a '#' means the previous two digits form one letter, otherwise a single digit does.
Edge / failure case single digits then # → 'acz'
'1','3','26#' = a c z.
Why? [[1,2],[2,5],[4,3]]: waits 2, 5, 8 → average 15 / 3 = 5.
💡 Key idea One chef serves customers in arrival order. Keep the time the chef becomes free: a customer starts at max(free, arrival), finishes after their cooking time, and waited finish − arrival. Average the waits.
Edge / failure case same arrival → 3
Second customer waits for the first: 2 and 4.
Why? ['hello','i','am','leetcode','hello'], target hello, start 1: index 0 is one step left → 1.
💡 Key idea For each index holding target, the walking distance is the smaller of the direct gap and the way around the circle (n − gap). Return the minimum, or −1 if the target is absent.
Edge / failure case wrap-around → 1
Going left wraps around: one step.
Why? arrival [0,1,1,2,4], state [0,1,0,0,1]: crossing times come out as [0,3,1,2,4].
💡 Key idea Simulate second by second with one queue for people who want to enter and one to exit (first come, first served). If both queues are non-empty, the door's previous use decides: same direction as last second wins, and if the door was idle exit goes first. Remember the last direction (or idle) and the current time.
Edge / failure case idle door → [0, 2, 1]
Exit person 0 goes first; the door was just used to exit, so exit person 2 follows, then the enter.
Why? [0,1,7,4,4,5], 3..6: pairs (0,4)(0,4)(0,5)(1,4)(1,4)(1,5) → 6.
💡 Key idea Order does not matter for pair sums, so sort. Count pairs with sum ≤ v using two pointers (when nums[i] + nums[j] ≤ v every index between i and j also works with j). The answer is count(upper) − count(lower − 1).
Edge / failure case single target sum → 1
Only 2+9 = 11.
Why? [2,1,5], k=2: keep [1,2] (2 ≤ 2·1) and remove 5 → 1 removal.
💡 Key idea An array is balanced when max ≤ k × min. After sorting, a balanced set to keep is a window whose last value is at most k times its first. Slide a window with two pointers, find the longest, and remove everything else.
Edge / failure case two kept → 2
Keep [1,2] (or [6,9]): remove 2.
Why? …'aeiaaioaaaaeiiiiouuuooaauuaeiu' → the best beautiful block is 'aaaaeiiiiouuu' of length 13.
💡 Key idea A beautiful substring is a run of a's, then e's, then i's, o's, u's (each at least once). Compress the word into runs of equal letters; any five consecutive runs spelling 'aeiou' form a beautiful substring, and its length is the sum of the five run lengths.
Edge / failure case too short → 0
No beautiful substring.
Why? [1,3,1,4,1,3,2]: query index 0 (value 1): the closest other 1 is at index 2 → 2. Index 3 (value 4) is alone → −1.
💡 Key idea The array is circular. Group the indices of each value in order; the closest equal element to an index is one of its two neighbours in that group (wrapping around). Compute the circular distance to both and keep the smaller.
Edge / failure case no duplicates → [-1, -1]
All values are different, so every answer is -1.
Why? 'aaaa' vs 'bccb': 'a' appears 4 times in one and 0 in the other, difference 4 > 3 → false.
💡 Key idea Two words are almost equivalent when, for every letter, the counts differ by at most 3. Count letters of one word up and the other down; no letter may end beyond ±3.
Edge / failure case within the limit → True
Differences are at most 3 for every letter.
Why? [3,1,4,1,5], k=2: pairs (1,3) and (3,5) → 2 (the repeated 1 counts once).
💡 Key idea Count each value. For k > 0 a pair is (x, x + k), so count the distinct x where x + k is also present. For k = 0 a pair needs a value that appears at least twice.
Edge / failure case k = 0 → 1
Only the value 1 appears twice.
Why? ['hello','world','leetcode'] with banned ['world','hello']: two words match → true.
💡 Key idea Put the banned words in a set. A message is spam when at least two of its words are in that set (repeated words count each time).
Edge / failure case just one → False
Only one banned word.
Why? ['adc','wzy','abc']: differences are [3,−1], [3,−1], [1,1] → 'abc' is the odd one.
💡 Key idea Turn each word into the list of differences between neighbouring letters. All words but one share the same list; group words by that list and return the one that is alone.
Edge / failure case odd in the middle → 'bob'
'bob' has a different pattern.
Why? Three houses in a circle: 0→1 forward costs 1, 1→2 costs 4 (or 5 backward), 2→0 costs 3 backward, 0→2 costs 4 backward → 12.
💡 Key idea Houses sit on a circle; from a to b you can go forward or backward. Build prefix sums over the forward and backward costs (doubled so they wrap around) and take the cheaper direction for every consecutive pair of the visit order, starting at house 0.
Edge / failure case query = start house → 2
Staying at house 0 costs nothing, then 0→1 costs 2.
Why? [3,2,1,4,5], k=4: subarrays [4], [4,5], [1,4,5] have median 4 → 3.
💡 Key idea Replace each number by +1 (bigger than k), −1 (smaller) or 0 (k itself). A subarray containing k has median k exactly when its balance is 0 (odd length) or 1 (even length, the left middle is k). Count balances going left from k in a hash map, then for every balance going right add the matches for −bal and 1 − bal.
Edge / failure case k in the middle → 1
Only [3] works: [2,3] and [3,1] have left-middle 2 and 1.
Why? [1,1,4,2,1,3] sorted is [1,1,1,2,3,4]: positions 2, 4, 5 differ → 3.
💡 Key idea The expected order is simply the sorted heights. Count the positions where the current height differs from the sorted one.
Edge / failure case already sorted → 0
Already in order.
Why? 1234: odds {1,3} and evens {2,4} → put the larger odd first, then the larger even … → 3412.
💡 Key idea Only digits of the same parity can swap, so they can be arranged in any order within their own positions. Put the biggest odd digits in the odd-digit positions and the biggest even digits in the even-digit positions.
Edge / failure case five digits → 87655
Odd: 7,5,5 even: 6,8 → 87655.
Why? [5,3,4,1,1]: peak at index 0 → heights [5,3,3,1,1] → sum 13.
💡 Key idea Choose the peak i. To its left heights must not decrease toward i and stay ≤ maxHeights, so each tower is capped by the minimum since it. A monotonic stack gives left[i] = best sum of 0..i when i is the right end of a non-decreasing run: reuse left of the previous smaller tower. Do the same from the right and answer max(left[i] + right[i] − h[i]).
Edge / failure case plateau peak → 18
Peak at index 2 or 3: [2,2,5,5,2,2] = 18.
Why? [5,3,4,1,1]: peak at index 0 → heights [5,3,3,1,1] → sum 13.
💡 Key idea Pick a peak i; going outwards each tower is the smaller of its own cap and the tower before it. Sum both sides and keep the best peak. With n up to 1000 the O(n²) scan is fine (the monotonic-stack version of part II makes it O(n)).
Edge / failure case peak in the middle → 22
Best peak is 9: [3,3,3,9,2,2] = 22.
Why? 'bac': push b, push a, pop a (nothing smaller remains), pop b, push c, pop c → 'abc'.
💡 Key idea The robot's string t is a stack. Write the top character to paper only when it is no larger than every character still unread (the smallest remaining letter, tracked with counts). Otherwise keep pushing.
Edge / failure case keep b for later → 'addb'
Output 'addb'.
Why? [2,1,3,4,4]: chunks [2,1], [3], [4], [4] → 4.
💡 Key idea Keep a stack with the maximum of each chunk so far (increasing). A new number smaller than the top must merge with those chunks: pop them and push their overall maximum. The stack size at the end is the number of chunks.
Edge / failure case reverse order → 1
The whole array is one chunk.
Why? [5,2,1,3,6] is a valid preorder; [5,2,6,1,3] is not, because 1 comes after 6 (right side) yet is smaller than 5.
💡 Key idea In preorder, once a value is larger than something on the stack we have moved into a right subtree; every later value must exceed the last popped value (the lower bound). Keep a decreasing stack and a lower bound; fail if a value is below the bound.
Edge / failure case invalid → False
1 after 6 breaks the lower bound 5.
Why? Path 0-1-2-3: starting at 0 the last marked node is 3; starting at 2 it is 0.
💡 Key idea Marking spreads one edge per second, so the last node marked is the farthest node from the start. In a tree the farthest node from any vertex is one of the two endpoints of the diameter. Find the endpoints A and B with two BFS (Breadth-First Search) runs, then for every node answer A if it is at least as far from A as from B, otherwise B.
Edge / failure case two nodes → [1, 0]
Two nodes: each one's last marked node is the other.
Why? Star with centre 0 and leaves 1, 2: the longest path 1-0-2 has 2 edges.
💡 Key idea BFS (Breadth-First Search) from any node reaches the farthest node A; that A is one end of a longest path. BFS from A: the largest distance found is the diameter.
Edge / failure case branching tree → 4
Longest path 0-1-4-5 or 3-2-1-4-5: 4 edges.
Why? Cycle 1-2-4-3 with branches 0 (off 1) and 5-6 (off 2): distances [1,0,0,0,0,1,2].
💡 Key idea The graph is connected with exactly one cycle. Repeatedly remove nodes of degree 1 (like topological sort); the nodes that never get removed are the cycle. Then run a multi-source BFS (Breadth-First Search) from all cycle nodes to get every node's distance.
Edge / failure case two branches → [0, 0, 0, 1, 2, 2, 1, 2, 2]
Triangle 0-1-2 with branches.
Why? Courses [100,200],[200,1300],[1000,1250],[2000,3200] → take the first three, the 2000-day course cannot fit → 3.
💡 Key idea Process courses by deadline. Add each course to the schedule (and a max-heap of durations). If the total time now passes this deadline, drop the longest course taken so far — that frees the most time while losing just one course.
Edge / failure case nothing fits → 0
Both are too long for their deadlines.
Why? 'aaba*': the star removes the smallest letter to its left; remove the last 'a' (index 3) → 'aab'.
💡 Key idea Each '*' deletes the smallest character on its left. To keep the final string smallest, among equal smallest letters delete the RIGHTMOST one. Use a min-heap of (letter, −index); pop on '*', mark that index removed, and rebuild the string from the remaining letters.
Edge / failure case all removed → ''
Everything is deleted.
Why? '000001', 1 flip: flipping the middle zero breaks 00000 into runs of at most 2 → 2.
💡 Key idea Guess the answer L (the longest run we allow) and count the flips needed. For L = 1 the string must alternate: flips = min(mismatches with 0101…, with 1010…). For L ≥ 2 a run of length r needs r // (L + 1) flips (flip every (L+1)-th character). A bigger L never needs more flips, so binary search the smallest L that fits in numOps.
Edge / failure case alternate fully → 1
Flip the 2nd and 4th zero to get 0101.
Why? '000001', 1 flip: one flip in the middle cuts the run of five 0s into pieces of at most 2 → 2.
💡 Key idea Same idea as part I with a much longer string: binary search the longest allowed run L. L = 1 means a fully alternating string; for L ≥ 2 a run of length r costs r // (L + 1) flips. Each check is linear, so the total is O(n log n).
Edge / failure case no flips needed → 1
Already alternating, longest run is 1.
Why? [2,4,5,5,5,5,5,6,6], target 5 appears 5 times out of 9 (> 4.5) → true.
💡 Key idea In a sorted array equal values sit together. Binary search the first and the last position of target; if that block is longer than n / 2 it is the majority element.
Edge / failure case exactly half → False
101 appears 2 of 4 = not more than half.
Why? Baskets at [1,2,3,4,7], 3 balls: put them at 1, 4, 7 → smallest gap 3.
💡 Key idea Guess the minimum gap d and place balls greedily from the left, each at the first basket at least d away from the last one. If m balls fit, d works; larger d is harder, so binary search the largest d that works.
Edge / failure case huge gap → 999999999
First and last basket.
Why? [[0,6,0],[5,8,7],[0,9,0]]: path 9 → 8 → 7 collects 24.
💡 Key idea Start a DFS (Depth-First Search) from every cell with gold. Collect the gold, mark the cell as 0 so it is not reused, try the four neighbours that still have gold, then restore the cell (backtrack). The answer is the best total over all starts.
Edge / failure case winding path → 28
The best route collects 28.
Why? [3,9,7,3] → split into [3,9] and [7,3]? sums 12 and 10 → difference 2.
💡 Key idea 2n numbers split into two groups of n. Split the array into halves of n and list every subset of each half with its size and sum. A group of n is k elements from the left half plus n − k from the right. For each k, sort the right sums for size n − k and binary search the one that makes the group sum closest to half the total.
Edge / failure case negative numbers → 72
Groups of one: |-36-36| = 72.
Why? n=3, prefix of 3 must have 2 inversions and the first element 0 inversions: [2,0,1] and [1,2,0] → 2.
💡 Key idea Build the permutation by inserting the next element's rank: the i-th element (0-based) adds anywhere from 0 to i new inversions. dp[j] = ways with j inversions so far; the next step is a sliding-window sum of the previous dp over the last i+1 values. When a requirement ends at i, keep only the required inversion count.
Edge / failure case extra requirement → 1
The first 2 have 1 inversion and the whole has 2: only [2,0,1] fits.
Why? [3,4,2]: take 4 (earn 4), which deletes 3; then take 2 → 6.
💡 Key idea Taking value v earns v × count(v) but forbids v−1 and v+1. Sum the points per value and run house robber over the values 1 … max: best[v] = max(best[v−1], best[v−2] + points[v]).
Edge / failure case choose a middle value → 9
Taking all 3s (9) beats 2s and 4s (4+4=8).
Why? n=3: the valid permutations of 1,2,3 where gcd(value, position)=1 everywhere are [3,1,2], [2,3,1], [1,3,2] → 3.
💡 Key idea A permutation of 1…n is self-divisible if gcd(a_i, i) = 1 for every position i. Fill positions 1, 2, 3… in order; the mask of used numbers tells how many positions are filled, so dp[mask] = ways to reach it, trying each unused value that is coprime with the next position.
Edge / failure case n = 1 → 1
Only [1].
Why? 'abcde' → 'cdef': keep the common block 'cde' (3 chars): remove 'ab' (2) and add 'f' (1) → 3.
💡 Key idea Characters can only be added or removed at the two ends, so what stays in the middle is a contiguous block common to both strings. Keep the longest common substring: everything else of the first string is removed and everything else of the target is added.
Edge / failure case no common block → 6
Nothing in common: remove 3, add 3.
Why? 2×3 grid, 1 introvert, 2 extroverts: best placement gives happiness 240.
💡 Key idea Process cells in row-major order. A cell only interacts with the cell above and the cell to its left, so the state is the last n cells (0 empty, 1 introvert, 2 extrovert) as a base-3 number plus the people left. Placing a person adds its own base happiness plus the interaction with the up/left neighbours (a pair adds both people's changes).
Edge / failure case single column → 260
Three cells in a column.
Why? 'aba': print 'aaa', then print 'b' over the middle → 2 turns.
💡 Key idea Squeeze runs of equal letters first. dp[i][j] = turns for s[i..j]. Print s[i] alone and solve the rest (1 + dp[i+1][j]), or, if some s[k] equals s[i], let the same print stroke cover i and k: dp[i+1][k−1] + dp[k][j].
Edge / failure case two blocks → 2
Two strokes.
Why? [2,8,3,19,3], k=3, one halving and one subtraction: apply both to 19 → 10 − 3 = 7 → sum 23.
💡 Key idea Each element can get nothing, op1 (halve, rounding up), op2 (subtract k, only if ≥ k), or both (in the better of the two orders). dp(i, a, b) = best sum of the suffix with a halvings and b subtractions left. Try every option per element.
Edge / failure case second sample → 3
Halve 2 and 4 and subtract 3 from one of them: total 3.
Why? ['abbb','ba','aa']: letters can be swapped between words; pairs available = 4, enough to make all three words palindromes → 3.
💡 Key idea Swapping lets you move any character anywhere, so only the total number of PAIRS of equal letters matters (odd lengths get their middle from any leftover letter). A word of length L needs L // 2 pairs. Serve the shortest words first while pairs last.
Edge / failure case no pairs → 1
No letter has a partner, only the single-letter word works.
Why? 'aaaaa': change the 2nd and 4th letters to something far away → 2 changes.
💡 Key idea Two neighbours are 'almost equal' if they are the same or adjacent in the alphabet. When a pair is bad, change the second letter of the pair to something far from both neighbours; that also fixes the next pair, so skip one position.
Edge / failure case alphabet neighbours → 2
'ab' and 'dd' are bad pairs.
Why? 'RLRRLLRLRL': cut after RL, RRLL, RL, RL → 4 balanced pieces.
💡 Key idea Walk through the string with a balance (+1 for R, −1 for L). Every time the balance returns to 0, the piece so far is balanced, so cut there. Cutting as early as possible gives the most pieces.
Edge / failure case smallest → 1
Just one pair.
Why? [3,9,3]: split 9 into 3+3+3 (2 operations) → [3,3,3,3,3] sorted → 2.
💡 Key idea Walk from the right keeping the limit prev (the smallest value allowed). If the number is ≤ prev just lower the limit to it. Otherwise it must be split into k = ceil(x / prev) parts; splitting as evenly as possible makes the smallest part x // k as large as possible, so the new limit is x // k. That costs k − 1 operations.
Edge / failure case already sorted → 0
Already sorted.
Why? [[1,3],[2,2],[3,1]], truck holds 4 boxes: take 1 box of 3 units, 2 of 2 units, 1 of 1 unit = 8.
💡 Key idea Every box takes one slot, so use the slots for boxes with the most units. Sort box types by units per box, descending, and take as many as fit.
Edge / failure case truck fills mid-way → 91
Take 5x10, 3x9, 2x7.
Why? [5,5,4], k=1: removing the single 4 leaves just the value 5 → 1 unique integer.
💡 Key idea To minimise how many distinct values remain, delete values completely, starting with those that appear least often. Sort the frequencies ascending and spend k removals on whole groups while you can.
Edge / failure case partial group → 2
Remove 4, 2 and one 1.
Why? [3,2,0,1,0] → 3+2+1+1+1 = 8 and [6,5,0] → 12: the first has zeros to grow, so both become 12.
💡 Key idea Every zero must become at least 1, so the smallest possible sums are a = sum1 + zeros1 and b = sum2 + zeros2. The answer is max(a, b) — unless the smaller side has no zeros to grow, then it is impossible (−1).
Edge / failure case impossible → -1
nums2 has no zeros and is smaller.
Why? n=7 (111): AND of 7,6,5,4 is still 4, but adding 3 (011) clears the top bit → largest x is 3.
💡 Key idea The AND of n, n−1, …, x only becomes 0 once the highest set bit of n has been cleared, i.e. when the sequence reaches the number just below that power of two. So the answer is 2^(bit_length−1) − 1.
Edge / failure case n = 1 → 0
1 & 0 = 0, so x = 0.
Why? [1,2,4,5], k=3: the subarray [1,2] has OR 3 → difference 0.
💡 Key idea OR only ever adds bits, so the subarrays ending at a position have at most ~30 distinct OR values. Keep that set, update it with each new number (OR every old value, add the number itself) and track the smallest |value − k|.
Edge / failure case k not reachable → 1
OR of [1,3] is 3 and no subarray gives 2: difference 1.
Why? n=13: 1,10,11,12,13 contain 1s → 1+1+2+1+1 = 6.
💡 Key idea Count how many times a 1 appears in each decimal place separately. For place p (1, 10, 100…) split n into high = n // (10p), cur = digit at p, low = n % p. If cur = 0 the place is a 1 high·p times; if cur = 1, high·p + low + 1 times; if cur > 1, (high + 1)·p times.
Edge / failure case zero → 0
No numbers contain 1.
Why? [1,4],[2,5],[3,6]: interval [1,4] touches both others → team of 3.
💡 Key idea A team is valid if one member (the hub) overlaps every other. So the best team for a hub is the hub plus everything overlapping it. The number overlapping interval [s, e] is n minus the intervals that end before s minus those that start after e (no interval can be both). Use sorted starts/ends and binary search; answer the maximum over hubs.
Edge / failure case disjoint → 1
No interval overlaps another.
Why? [[2,2],[6,3],[5,4]]: mountain [6,3] lies inside [5,4]'s base → hidden, so 2 are visible.
💡 Key idea A mountain with peak (x, y) covers the base interval [x−y, x+y]; it is hidden exactly when another interval contains it. Identical mountains hide each other. Sort the distinct intervals by left end (right end descending), sweep keeping the largest right end seen, and count intervals that extend past it and are not duplicated.
Edge / failure case duplicates → 0
Identical mountains hide each other.
Why? [[1,2,3],[4,5,6],[7,8,9]], k=4: shifting by 4 ≡ 1 place changes the row [1,2,3] → false.
💡 Key idea Even rows shift left and odd rows shift right, but a row equals its shifted self in either direction exactly when row[j] == row[(j + k) mod n] for every j. Check that for every row.
Edge / failure case all equal → True
Identical values in every row stay the same.
Why? [[1,0,1],[1,1,1]]: one rectangle for the left column (area 2), one for the middle 1 (area 1), one for the right column (area 2) → 5.
💡 Key idea Three non-overlapping rectangles can always be separated by straight cuts. There are only six shapes: three vertical strips, three horizontal strips, or one cut with the other side split once the other way (four variants). For each region the best rectangle is the bounding box of its 1s.
Edge / failure case full grid → 9
Three row strips of area 3 each.
Why? [[0,1,0],[1,0,1]]: ones span rows 0-1 and columns 0-2 → 2 × 3 = 6.
💡 Key idea The smallest rectangle covering every 1 is the bounding box: from the smallest to the largest row and column that contain a 1.
Edge / failure case single 1 → 1
A single cell.
Why? red=2, blue=4: start with blue (1), red (2), blue (3) → 3 rows, using 4 blue and 2 red.
💡 Key idea Row r needs r balls, all of one colour, and colours alternate. Rows alternate between the two colours, so try starting with red and starting with blue; keep adding rows while the colour in turn has enough balls. Take the better height.
Edge / failure case too few balls → 1
Row 1 uses one ball, row 2 needs 2: height 1.
Why? n=3 with queries row0=1, col2=2, row2=3, col0=4 → final matrix sums to 23.
💡 Key idea A later query overwrites an earlier one on the same row or column, so go backwards: the first time a row (or column) is seen it is final. A row set to v contributes v for every cell not already covered by a final column, i.e. v × (n − columns already fixed); a column symmetrically.
Edge / failure case mixed order → 17
Total 17.
Why? Stations 1-5 in a line; station 3 asks → itself. Station 1 goes offline; asking 1 returns the smallest online in its grid → 2.
💡 Key idea Connected stations form a grid: union them once. Keep each grid's stations in a min-heap. For a query on an offline station, pop offline stations from the top of its grid's heap (lazy deletion) and answer with the top, or −1 if the heap empties.
Edge / failure case isolated stations → [1, -1, 2]
No cables: station 1 offline has no online partner.
Why? [1,3,7,15] → 1|3=3, 3|7=7, 7|15=15 → [3,7,15].
💡 Key idea The answer has n−1 entries: entry i is nums[i] OR nums[i+1].
Edge / failure case two elements → [2]
One pair.
Why? '20th Oct 2052' → '2052-10-20'.
💡 Key idea Split into day, month name and year. Strip the two-letter suffix from the day, look the month up in a list, and zero-pad both to two digits.
Edge / failure case one-digit day → '1933-06-06'
Day is padded to 06.
Why? [4,3,2,1,2,3,1]: merge 3+1 on the right, then 1+2 → [4,3,3,4]-style palindrome after 2 merges.
💡 Key idea Compare both ends. If equal, move inward. If the left value is smaller, merge it with its right neighbour (cost 1); otherwise merge the right end with its left neighbour. Merging the smaller side is always the only way to ever make the ends equal.
Edge / failure case increasing → 3
Merge everything into 10: 3 operations.
Why? [1,3,2,3,3], k=2: subarrays with at least two 3s: 6.
💡 Key idea Let M be the array's maximum. Move the right end; once the window holds k copies of M, move the left end forward until it holds only k−1. Every start before the new left gives a valid subarray ending here, so add l.
Edge / failure case not enough maxima → 0
The maximum 4 occurs once only.
Why? ['aba','aabb','abcd','bac','aabc']: 'aba' & 'aabb' share {a,b}; 'bac' & 'aabc' share {a,b,c} → 2.
💡 Key idea Two words are similar when they use the same set of letters. Turn each word into a bitmask of its letters, count equal masks, and add c·(c−1)/2 for each group.
Edge / failure case no pairs → 0
All different letter sets.
Why? [1,1,2,2,3,4] can be split into [1,2,3] and [1,2,4] → true.
💡 Key idea Both halves need distinct values, so each value can appear at most twice (once in each half). With an even length, that condition is also enough.
Edge / failure case too many repeats → False
1 appears four times.
Why? '**|**|***|', query [2,5]: candles at 2 and 5 enclose 2 plates → 2.
💡 Key idea A plate counts only if a candle is on both sides inside the query range. For each position store the nearest candle to its right and to its left. Shrink [l, r] to [next candle ≥ l, previous candle ≤ r] and count plates with a prefix sum.
Edge / failure case several ranges → [9, 0, 0, 0, 0]
A mix of closed and open ranges.
Why? [1,3,6], k=3: 1→4, 3→6, 6→3 gives [4,6,3], range 3 (the original range is 5).
💡 Key idea Sort the numbers. Small numbers should go up (+k) and large numbers down (−k); the switch happens at some split i: nums[0..i] get +k, the rest get −k. For each split the max is max(nums[i]+k, nums[-1]−k) and the min is min(nums[0]+k, nums[i+1]−k). Take the smallest range, starting from the no-split value nums[-1] − nums[0].
Edge / failure case two numbers → 6
Both ends move toward each other: 2 and 8.
Why? [1,1,2,2,2,3]: 3 once, 1 twice, 2 three times → [3,1,1,2,2,2].
💡 Key idea Sort with a key of (frequency ascending, value descending) so equal-frequency values come out biggest first.
Edge / failure case ties → [1, 3, 3, 2, 2]
1 once, then 3,3 and 2,2 (larger first).
Why? '(u(love)i)': inner 'love' → 'evol', then 'uevoli' reversed → 'iloveu'.
💡 Key idea Keep a stack of lists. '(' starts a new list; letters go on the current list; ')' pops the list, reverses it and appends it to the list below.
Edge / failure case nested → 'apmnolkjihgfedcbq'
Nested reversal.
Why? 1-2-3-4 with child list 7-8 under 3: result 1-2-3-7-8-4.
💡 Key idea Walk the list. When a node has a child, push its next onto a stack, splice the child list in as its next (fix prev, clear child). When the end of a list is reached, pop the saved node and link it after the tail.
Edge / failure case one child → [1, 3, 2]
The child list goes between 1 and 2.
Why? prevRoom [-1,0,0,1,2]: room 1 and 2 after 0, 3 after 1, 4 after 2 → 6 valid orders.
💡 Key idea The rooms form a tree rooted at 0 and a valid build order is a topological order. The number of orders of a rooted tree is n! / ∏(size of each subtree). Compute subtree sizes bottom-up and use modular inverses.
Edge / failure case chain → 1
A chain has exactly one order.
Why? [1,2,3,4]: 4's parent is 2, 3's parent is 1 and both are not at the same depth → false.
💡 Key idea Cousins have the same depth but different parents. Walk the tree (BFS (Breadth-First Search) or DFS (Depth-First Search)) recording depth and parent of x and y, then compare.
Edge / failure case true case → True
Same depth, different parents.
Why? [1,0,2], keep 1..2: node 0 is too small, drop it and keep its right side → [1,null,2].
💡 Key idea If a node is below low, its whole left subtree is too small too, so the answer is the trimmed right subtree. If it is above high, take the trimmed left subtree. Otherwise keep the node and trim both children.
Edge / failure case needs re-attaching → [3, 2, None, 1]
Drop 0, keep its right subtree.
Why? 1 unit0 = 2 unit1 and 1 unit1 = 3 unit2 → unit counts [1, 2, 6].
💡 Key idea The conversions form a tree rooted at unit 0. Walk it from 0 and multiply the factors along the path (modulo 1e9+7): base[target] = base[source] × factor.
Edge / failure case star → [1, 2, 3]
Two children of unit 0.
Why? k=5: no factorial has exactly 5 trailing zeros (24! has 4, 25! has 6) → 0.
💡 Key idea f(x) = number of trailing zeros of x! = x//5 + x//25 + … and it never decreases. Binary search the smallest x with f(x) ≥ k. The answer is 5 if f(x) == k (x … x+4 all share it) and 0 otherwise.
Edge / failure case k = 0 → 5
0! to 4! all have 0 trailing zeros.
Why? houses [1,2,3], heater at 2: the farthest house is 1 away → radius 1.
💡 Key idea Each house needs the nearest heater within the radius, and the radius must cover the worst house. Sort the heaters and binary search the closest one on either side of each house; the answer is the largest of these distances.
Edge / failure case far house → 3
House 5 is 3 away.
Why? [[1,1],[3,4]]: single cells 4, plus 1→3, 1→4, 3→4, 1→3→4 → 8.
💡 Key idea Let paths(i,j) be the number of strictly increasing paths that start at cell (i,j): 1 (the cell alone) plus paths(neighbour) for each neighbour with a larger value. Values only increase, so there are no cycles and memoisation makes it linear. Sum over all cells.
Edge / failure case single column → 3
Two cells and the path between them: 3.
Why? nums1=[1,2,5], nums2=[2,6,3]: three balanced ways exist → 3.
💡 Key idea Track the balance (sum of picks from nums1 minus sum of picks from nums2) for a range ending at i. Each range either starts at i or extends one ending at i−1, and at i it adds +nums1[i] or −nums2[i]. Keep a dictionary balance → ways; every way with balance 0 is a valid balanced choice.
Edge / failure case zeros → 2
Choosing either side gives balanced sums: 2 ways.
Why? [2,3,3,7,3,5], k=20: [2·3·3=18],[7·3=21 too big → 7],[3·5=15] → 3 groups.
💡 Key idea A zero makes everything collapse to one number. Otherwise scan left to right keeping the running product; extend it while the product stays ≤ k, else start a new group. Merging as early as possible never hurts.
Edge / failure case zero present → 1
A zero absorbs everything.
Why? n=4: whatever you take (1-3), your friend takes the rest → you lose → false.
💡 Key idea Taking 1–3 stones each turn, if n is a multiple of 4 the opponent can always answer so that 4 stones disappear per round, and you take the last-but-never. Otherwise take n mod 4 first and keep that up. So you win iff n % 4 != 0.
Edge / failure case tiny heap → True
Take the only stone.
Why? [0,10], k=2: raise 0 by 2 and lower 10 by 2 → [2,8], range 6.
💡 Key idea Every number can move by up to k either way, so the max and the min can approach each other by 2k in total. The answer is max(0, max − min − 2k).
Edge / failure case single element → 0
One number: range 0.
Why? num1=1 (0001), num2=12 (1100 has two 1s): x needs two set bits; 0011 = 3 gives XOR (exclusive OR) 2, the smallest.
💡 Key idea x must have as many set bits as num2. To make x XOR num1 small, match the highest set bits of num1 first; if bits are left over, set the lowest unset bits of x.
Edge / failure case same bit count → 3
x = 3 has the same number of set bits as 5.
Why? [2,1,3] → raise 2 by 1 and 1 by 2 → 3 moves.
💡 Key idea Each move adds 1 to one element, so the common value is at least the maximum, and raising everything to the maximum is optimal. Moves = n × max − sum.
Edge / failure case decreasing → 6
6 moves.
Why? [5,1,6]: OR = 7, 7 × 2² = 28.
💡 Key idea Look at one bit: if some number has it set, exactly half of the 2ⁿ subsets have it set in their XOR (2ⁿ⁻¹ of them). So the total is (OR of all numbers) × 2ⁿ⁻¹.
Edge / failure case six numbers → 480
Total 480.
Why? n=10 boxes: a 3-level stair pyramid uses 1 + 3 + 6 = 10 boxes and touches the floor with 6 → 6.
💡 Key idea The best shape is a staircase pyramid in a corner. Complete layers need 1, 1+3, 1+3+6 … boxes and touch the floor with 1, 3, 6 … boxes. Add the largest complete pyramid that fits, then add floor boxes one by one: the j-th extra floor box allows j more boxes on top.
Edge / failure case tiny → 3
Three boxes on the floor.
Why? [16,17,71,62,12,24,14]: four of them have bit 2 set, and their AND is > 0 → 4.
💡 Key idea The AND of a group is non-zero exactly when all of them share at least one set bit. So count, for each bit position, how many numbers have it, and take the largest count.
Edge / failure case same numbers → 2
Both share one bit.
Why? n=5, k=2: friends leave in order 2, 4, 1, 5 → friend 3 wins.
💡 Key idea With i friends the survivor's index f(i) satisfies f(i) = (f(i−1) + k) mod i, starting from f(1) = 0. The answer is f(n) + 1.
Edge / failure case k near n → 1
Winner 1.
Why? [[5,10],[6,8],[1,5],[2,3],[1,10]]: three intervals overlap at time 5 or 6 → 3 groups.
💡 Key idea Intervals that share a point must be in different groups, so the answer is the maximum overlap. Sort by start and keep a min-heap of group end times: if the earliest-ending group ended before this start, reuse it, otherwise open a new group.
Edge / failure case disjoint → 1
No two intervals overlap.
Why? n=3 with two rectangle additions gives [[1,1,0],[1,2,1],[0,1,1]].
💡 Key idea Instead of touching every cell of each rectangle, mark only its four corners in a difference grid (+1 top-left, −1 just right, −1 just below, +1 diagonal). A final 2D prefix sum turns the marks into the real counts.
Edge / failure case single cell → [[1]]
A 1x1 matrix.
Why? [1,3,5]: sum(0,2)=9; set index 1 to 2; sum(0,2)=8.
💡 Key idea A Fenwick tree stores partial sums so both a point update and a prefix-sum query touch only O(log n) cells (jump by the lowest set bit). Range sum = prefix(right) − prefix(left−1).
Edge / failure case one element → [5, None, 7]
A single element.
Why? '& is an HTML entity but &ambassador; is not.' → '& is an HTML entity but &ambassador; is not.'
💡 Key idea Replace each known entity (" ' > < ⁄) by its character. Replace & last, otherwise text like &gt; would wrongly turn into > instead of >.
Edge / failure case several entities → 'x > y && y < z'
Entities in the middle of text.
Why? 'cat and dog' → 3 valid words; '!this 1-s b8d!' → 0 (leading punctuation, digits).
💡 Key idea Split on spaces. A token is valid if it has no digits, at most one hyphen that sits between two letters, and punctuation (!.,) at most once and only as the last character.
Edge / failure case all invalid → 0
Every token breaks a rule.
Why? [2,1,4,7,3,2,5]: the mountain 1,4,7,3,2 has length 5.
💡 Key idea Scan left to right. From a start index climb while values increase; if you climbed and then can descend, you have a mountain whose length is the climb plus the descent. Continue scanning from the end of the descent.
Edge / failure case flat → 0
No mountain.
Why? [-2,0,1,3], target 2: triples (-2,0,1) and (-2,0,3) are below 2 → 2.
💡 Key idea Sort the array. Fix the first number, then use two pointers: if nums[i] + nums[l] + nums[r] < target, then every index between l and r also works with l, so add r − l and move l; otherwise move r.
Edge / failure case unsorted input → 3
Three triples.
Why? '2523533': 2 appears 2 times and 3 appears 3 times, so the first valid neighbour pair is '23'.
💡 Key idea A pair is valid when its two digits differ and each digit appears in the whole string exactly as many times as its value. Count the digits once, then scan adjacent pairs left to right and return the first valid one.
Edge / failure case no valid pair → ''
1 appears twice but needs to appear once; the digits are equal anyway.
Why? [1,2,2,3,1]: degree 2 (both 1 and 2); the shortest span is [2,2] → 2.
💡 Key idea The degree is the highest frequency. For each value remember its count, first index and last index. Among values whose count equals the degree, the answer is the shortest last − first + 1.
Edge / failure case longer span → 6
Degree 3 (value 2), span 6.
Why? nums [1,3,5,2], cost [2,3,1,14]: the weighted median is 2 → cost 1·2 + 1·3 + 3·1 + 0 = 8.
💡 Key idea Changing nums[i] to t costs cost[i] × |nums[i] − t|. The sum of such absolute values is minimised at the weighted median. Sort by value and pick the first value where the running cost reaches half of the total cost, then add up the cost.
Edge / failure case all equal → 0
Already equal.
Why? nums1=[3,4,6,5], nums2=[9,1,2,5,8,3], k=5 → [9,8,6,5,3].
💡 Key idea Try every split: i digits from nums1 and k−i from nums2. The best i digits of an array (keeping order) come from a monotonic stack that can drop smaller digits while it still has enough left. Merge two sequences into the largest by always taking from the one that is lexicographically larger from the current position. Keep the best result over all splits.
Edge / failure case k = total → [6, 7, 6, 0, 4]
Use everything.
Why? 1 → 0 → 1 reads as binary 101 = 5.
💡 Key idea Walk the list from the most significant bit. For every node, shift the value left by one and add the node's bit.
Edge / failure case single zero → 0
Zero.
Why? 0→3→1→0→4→5→2→0 becomes 4 → 11.
💡 Key idea The list starts and ends with 0 and has no neighbouring zeros. Walk it, adding values into a running sum; at every 0 (after the first) emit a node with the sum and reset it.
Edge / failure case single block → [1]
One block.
Why? 7243 + 564 = 7807 → list 7→8→0→7.
💡 Key idea The lists store the most significant digit first, so push both onto stacks to read digits from the end. Pop, add with carry, and put each new digit in front of the result list.
Edge / failure case zeros → [0]
Zero plus zero.
Why? [3,9,20,null,null,15,7] → levels [3],[9,20],[15,7] listed bottom-up: [[15,7],[9,20],[3]].
💡 Key idea Do an ordinary level-order BFS (Breadth-First Search) and reverse the list of levels at the end.
Edge / failure case single node → [[1]]
Single node.
Why? receiver [2,0,1], k=4 starting at player 2: 2 → 1 → 0 → 2 → 1, ids add up to 6.
💡 Key idea f(x) = x plus the ids of the next k receivers. k can be huge, so use binary lifting: up[j][i] is the player reached after 2^j passes and total[j][i] is the sum of ids of those 2^j receivers. Decompose k into powers of two and combine the jumps for every start.
Edge / failure case second sample → 10
Starting at 4 gives the best total.
Why? n=5, shortcut 2–4: 10 ordered pairs at distance 1, 8 at distance 2, 2 at distance 3 → [10,8,2,0,0].
💡 Key idea Houses 1..n lie on a line plus one extra street between x and y. The distance between i < j is the smaller of the direct walk j − i and the two routes using the shortcut (i → x, cross, y → j or i → y, cross, x → j). Count each unordered pair twice.
Edge / failure case x = y → [6, 4, 2, 0]
The shortcut is a loop on one house; it changes nothing.
Why? n=5, shortcut 2–4: the cycle is 2-3-4, tails 1 and 5 → [10,8,2,0,0].
💡 Key idea With the shortcut x–y the graph is a ring of m = y−x+1 houses with a tail of a = x−1 houses on one side and b = n−y on the other. Count pairs by distance in groups: ring–ring, tail–ring (a tail node at depth s is s + ring distance away), tail–tail on opposite sides (s + t + 1) and same-side tail pairs. Each group adds a range of counts, which a difference array handles in O(1) per node.
Edge / failure case full cycle → [6, 0, 0]
A triangle: every pair is at distance 1.
Why? Edges 0→3, 1→3, 3→5: node 5's ancestors are 0, 1, 3 → [0,1,3].
💡 Key idea Process nodes in topological order (Kahn). When u is processed, every child v inherits u and all of u's ancestors. Sort each node's set at the end.
Edge / failure case complete DAG → [[], [0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
Every earlier node is an ancestor.
Why? Land (0) groups not touching the edge count; the sample grid has 2 such islands.
💡 Key idea An island is closed if none of its land cells touches the border. First flood-fill (turn into water) every land cell reachable from the border. Then each remaining land region is closed: count them with another flood fill.
Edge / failure case nested islands → 2
A ring island and a single cell inside it.
Why? pid [1,3,10,5], ppid [3,0,5,3], kill 5 → killing 5 also kills its child 10 → [5,10].
💡 Key idea ppid tells each process's parent. Build a map parent → children, then walk down from the killed process, collecting everything under it.
Edge / failure case no children → [1]
Only one process.
Why? [1,2,3,4,5,3,1], target 3 → the smallest index holding 3 is 2.
💡 Key idea The array rises to a peak and then falls. Binary search the peak (compare get(mid) with get(mid+1)). Then binary search the ascending side for the target; only if it is missing, binary search the descending side. This uses O(log n) calls to get().
Edge / failure case missing → -1
3 is not in the array.
Why? ['able','area','echo','also']: top 'able', left 'area', right 'echo', bottom 'also' share all four corner letters.
💡 Key idea A square is four distinct words top, left, right, bottom where top[0]=left[0], top[3]=right[0], bottom[0]=left[3] and bottom[3]=right[3]. With at most 15 words, trying every ordered choice of four distinct words is cheap. Collect the valid ones and sort them.
Edge / failure case no square → []
No corner letters match.
Why? 'AAB': A, B, AA, AB, BA, AAB, ABA, BAA → 8 sequences.
💡 Key idea Keep a count of each available letter. Every time you can place a letter you get a new sequence: add 1 and continue building from the remaining counts. Using counts (not positions) avoids counting equal sequences twice.
Edge / failure case single tile → 1
One tile.
Why? low=high=3, zero=one=1: every binary string of length 3 works → 8.
💡 Key idea dp[len] is the number of strings of exactly that length: you reach len by appending a block of `zero` zeros to length len−zero or a block of `one` ones to length len−one. Add up dp[low..high].
Edge / failure case mixed block sizes → 5
Five strings of length 2 or 3.
Why? Stones [0,1,3,5,6,8,12,17]: jumps 1,2,2,1,2,4,5 reach the last stone → true.
💡 Key idea For every stone keep the set of jump sizes with which the frog can arrive. From a stone reached with jump k, the next jump is k−1, k or k+1 (positive); if there is a stone there, record that jump for it. The frog can cross if the last stone has any arrival jump.
Edge / failure case unreachable → False
The gap before 8 is too wide.
Why? obstacles [0,1,2,3,0]: the frog needs 2 sideways jumps to dodge the obstacles → 2.
💡 Key idea dp[l] is the fewest side jumps to be in lane l at the current point. An obstacle in a lane makes that lane unreachable. At each point you can jump into any free lane from another lane for +1, so dp[l] = min(dp[l], min(dp) + 1) for the free lanes.
Edge / failure case no jumps → 0
No jump needed.
Why? 'mbadm' → keep 'mam' (3) and insert the 2 others → 2 insertions.
💡 Key idea Characters of a longest palindromic subsequence already pair up; every other character needs a partner inserted. So the answer is n − LPS (Longest Palindromic Subsequence), and LPS is the longest common subsequence of s and its reverse.
Edge / failure case already palindrome → 0
Already a palindrome.
Why? [3,7,1,6]: prefix averages 3, 5, 3.67→4, 4.25→5 → answer 5.
💡 Key idea An operation moves one unit from nums[i] to the element on its left, so the values can only be pushed toward the front. The best possible maximum is therefore the largest ceiling of any prefix average.
Edge / failure case decreasing → 10
Nothing can be pushed to the right.
Why? [1,2,3,2,1]: one operation per rise: 1 + 1 + 1 = 3.
💡 Key idea Each operation adds 1 to a contiguous range. Whenever the target rises from the previous element, the rise cannot be covered by operations already running, so it needs new operations. The answer is the first element plus all positive differences.
Edge / failure case up and down → 7
3 + 4 = 7.
Why? n=5 gives a 20-day schedule such as [0,1],[2,3],[0,4],[1,2],… with no team playing two days in a row; n ≤ 4 is impossible.
💡 Key idea There are n(n−1) matches (every ordered pair). For n ≤ 4 no schedule exists. Otherwise build the days one by one: among the remaining matches that use neither team from the previous day, play the one whose two teams still have the most matches left (ties: smallest ids). This keeps busy teams from getting stuck at the end.
Edge / failure case impossible → []
No schedule exists for 3 teams.
Why? n=5: day 1 adds 2 and 4 (5 % x = 1), later days add 3 → numbers 2..5 → 4.
💡 Key idea For any x > 2 on the board, x % (x−1) = 1, so x−1 is added; repeating, every number down to 2 ends up on the board. For n > 1 the answer is n − 1; for n = 1 it is 1.
Edge / failure case small n → 2
2 and 3.
Why? [5,5,5,10,5]: the minimum 5 divides everything and appears 4 times → 4 / 2 = 2.
💡 Key idea Let m be the minimum. If some element is not a multiple of m, taking its remainder produces something smaller than m, which then wipes out the rest: answer 1. Otherwise only copies of m can ever be paired with each other (m % m = 0) so they vanish two at a time: answer ceil(count(m) / 2).
Edge / failure case non-multiple → 1
3 % 2 = 1 starts a collapse to length 1.
Why? [1,2,1,3,2,5]: pairs cancel, leaving 3 XOR (exclusive OR) 5 = 6; the lowest set bit separates them → [3,5].
💡 Key idea XOR of all numbers cancels the pairs and leaves a XOR b of the two singles. Any set bit of that value differs between a and b. Use the lowest set bit to split all numbers into two groups; XOR each group to get a and b.
Edge / failure case two elements → [-1, 0]
Two singles.
Why? [[6,10],[5,15]] overlap → one component → 2 ways (all in group 1 or all in group 2).
💡 Key idea Ranges that overlap must share a group, so they form connected blocks. Sort the ranges and merge overlapping ones to count the blocks c; each block independently picks one of two groups, giving 2^c ways.
Edge / failure case interleaved → 4
Blocks 1-8 and 10-20 give 2 groups, each in two ways.
Why? [[3,7,8],[9,11,13],[15,16,17]]: 15 is the minimum of its row and the maximum of its column → [15].
💡 Key idea A lucky number is the minimum of its row and the maximum of its column. Compute every row minimum and every column maximum and keep the numbers that are both.
Edge / failure case bottom right → [12]
12 is the minimum of the last row and the maximum of its column.
Why? [1,3,2,4,5]: (1,3,2,4) and (1,3,2,5) fit nums[i] < nums[k] < nums[j] < nums[l] → 2.
💡 Key idea We need i<j<k<l with nums[i] < nums[k] < nums[j] < nums[l]. For each pair j<k with nums[j] > nums[k], the count is (how many i<j are smaller than nums[k]) × (how many l>k are larger than nums[j]). Keep less[k] = number of earlier elements below nums[k] updated as j moves right, and count larger elements to the right of k while scanning k from the end.
Edge / failure case sorted → 0
No decreasing step in the middle.
Why? A 3×6 room with broken seats: placing students so none sees a neighbour's paper fits at most 4.
💡 Key idea A student sees left, right, upper-left and upper-right. Go row by row; the state is the bitmask of occupied seats in the previous row. A mask for this row is valid if it only uses working seats, has no two neighbours, and shares no diagonal with the previous mask. dp[mask] = best total after this row.
Edge / failure case full room → 2
Two students sit in the same column in different rows; diagonals stay empty.
Why? skills [4,2,6,3,9], k=2: 4 beats 2, loses to 6; 6 beats 3 (2 wins in a row) → player 2.
💡 Key idea The front player plays the next in line; the winner stays and the loser goes to the back. That is the same as keeping a champion index and a win streak while scanning the others. If nobody reaches k wins, the strongest player ends up as champion.
Edge / failure case huge k → 1
k is larger than needed: the strongest wins.
Why? prices [10,2,3,4], profits [100,2,7,10]: pick 2,3,4 → 2 + 7 + 10 = 19.
💡 Key idea Fix the middle index j. On its left take the most profitable item with a lower price; on its right the most profitable item with a higher price. If both exist, that triple's profit is a candidate. Check all j (n is at most 2000, so O(n²) is fine).
Edge / failure case no triple → -1
Prices only decrease.
Why? [1,3,6,10,12,15]: 6 and 12 qualify → (6 + 12) / 2 = 9.
💡 Key idea Even and divisible by 3 means divisible by 6. Average those with integer division, or 0 if none.
Edge / failure case none → 0
No multiple of 6.
Why? logs [[0,3],[2,5],[0,9],[1,15]]: durations 3, 2, 4, 6 → employee 1.
💡 Key idea A task starts when the previous one ended (the first starts at 0), so its duration is leave − previous leave. Keep the longest duration and, on a tie, the smaller id.
Edge / failure case unique max → 3
Durations 1, 6, 5, 5.
Why? '0110111': runs of 2 and 3 ones → 3 + 6 = 9.
💡 Key idea Every substring of all 1s lies inside one run of consecutive 1s. A run of length L contains L(L+1)/2 substrings. Count them with a running length (each new 1 adds 'current run length' new substrings).
Edge / failure case separate ones → 2
Two single 1s.
Why? [7,52,2,4]: 74 + 522 = 596.
💡 Key idea Take the first and last numbers, glue their digits (first then last) and add the result; then move both ends inwards. A middle leftover is added as is.
Edge / failure case odd length → 673
Odd length leaves a middle value.
Why? 'abab': the largest suffix starting with the biggest letter is 'bab'.
💡 Key idea The answer is always a suffix. Keep two candidate starts i < j and compare s[i+k] with s[j+k] as k grows. When one candidate loses at k, skip every start that lies inside the matched part (jump past k positions). The survivor i is the answer start.
Edge / failure case unique → 'tcode'
'tcode' is the largest suffix.
Why? [3,5,2,3]: pairs (2,5) and (3,3) → max pair sum 7.
💡 Key idea To keep the biggest pair sum low, pair the smallest number with the largest, the second smallest with the second largest and so on. Return the maximum of those sums.
Edge / failure case six numbers → 8
Pairs (2,6), (3,5), (4,4).
Why? [0,3,2,1] is a mountain; [3,5,5] is not (flat step).
💡 Key idea Walk up while values strictly increase, then walk down while they strictly decrease. It is a mountain if the peak is neither the first nor the last position and the walk reached the end.
Edge / failure case plateau → False
A plateau.
Why? 'egcfe': pair (e,e) ok, pair (g,f) → both f → 'efcfe'.
💡 Key idea Changing letters is the only operation and we want the fewest changes and then the smallest string. For every mirrored pair keep the smaller letter on both sides.
Edge / failure case even length → 'abba'
abba.
Why? '111000' rotated to '110001'… best alternating target needs 2 flips.
💡 Key idea Moving the first character to the end (type 1) is free, so any rotation can be used; type 2 flips a bit. Look at s+s with a window of length n and compare it to the two alternating patterns 0101… and 1010…, tracking mismatches incrementally as the window slides. The answer is the smallest mismatch count seen.
Edge / failure case no flips → 0
Already alternating.
Why? 'abcd' → 'bcdf' costs 1,1,1,2; with budget 3 the longest affordable window is 3.
💡 Key idea Turning s[i] into t[i] costs |s[i] − t[i]|. Find the longest window whose total cost ≤ maxCost: expand the right end, shrink from the left while the cost is too high.
Edge / failure case tight budget → 1
Each change costs 2: only one fits.
Why? [0,1,0,1,1,0,0]: three ones; the best circular window of length 3 holds 2 ones → 1 swap.
💡 Key idea Let w be the number of 1s. The ones must end up in some window of length w on the circular array; the swaps needed equal the zeros inside that window. Slide a window over nums + nums and take the minimum zero count.
Edge / failure case wraps around → 0
Circular array already grouped.
Why? 'abacaba': 'ab' has length 2 and no longer run exists → 2.
💡 Key idea A continuous substring has each letter exactly one after the previous (abc, not ace). Scan and extend the current run when the code is previous + 1, else restart at 1.
Edge / failure case full run → 5
Whole string.
Why? nums [1,3,1,7], x=1: positions are [0,2]; the 1st → 0, 3rd → −1.
💡 Key idea Store the indices where x occurs. The k-th occurrence is positions[k−1] if it exists, otherwise −1.
Edge / failure case absent → [-1]
x does not appear at all.
Why? 'abaacbcbb': a×3 → 1, b×4 → 2, c×2 → 2 → 5.
💡 Key idea An operation deletes the nearest equal letters on both sides of a chosen letter, removing 2 of that letter at a time while at least 3 remain. So a letter with count c shrinks to 1 if c is odd, or to 2 if c is even (c ≥ 2). Sum over the letters.
Edge / failure case nothing removable → 2
No letter has a partner on both sides.
Why? ['abba','baba','bbaa','cd','cd'] → 'baba' and 'bbaa' are anagrams of the previous kept word, the second 'cd' too → ['abba','cd'].
💡 Key idea Whenever a word is an anagram of the word before it, remove it; comparing against the last kept word is enough. Anagrams have equal sorted letters.
Edge / failure case none removed → ['a', 'b', 'c', 'd', 'e']
No neighbours are anagrams.
Why? possible [1,0,1,0]: Alice plays level 0 (+1), Bob plays 1,0,1... Alice 1 > Bob −1 → 1 level.
💡 Key idea A playable level gives +1 and an impossible one gives −1. Alice plays the first i levels, Bob the rest (each must play at least one). Using the total score, Alice's prefix p beats Bob when p > total − p. Return the smallest i that works.
Edge / failure case all clearable → 3
Alice needs 3 levels.
Why? nums [3,1,6,8], query 5: |3−5|+|1−5|+|6−5|+|8−5| = 10.
💡 Key idea For each query q the cost is Σ|nums[i] − q|. Sort the numbers and build prefix sums. Binary search how many numbers are below q; those cost q·count − their sum, the rest cost their sum − q·count.
Edge / failure case one query → [20]
A single query.
Why? [2,3,5]: for 3: |3−2| + |3−5| = 3; the answers are [4,3,5].
💡 Key idea The array is sorted, so for index i every earlier element is ≤ nums[i] and every later one is ≥. The sum is nums[i]·i − prefix_left + suffix_right − nums[i]·(n−i−1).
Edge / failure case five values → [24, 15, 13, 15, 21]
Five values.
Why? [-3,2,-3,4,2]: prefix sums −3,−1,−4,0,2; lowest is −4 so the start must be 5.
💡 Key idea With start value v the running sum after i steps is v + prefix[i]; it must stay ≥ 1. The worst case is the lowest prefix, so v = 1 − min prefix (at least 1).
Edge / failure case all positive → 1
Start at 1.
Why? Sorting by column 2: scores 11, 9, 3 → rows come out [7,5,11,2], [10,6,9,1], [4,8,3,15].
💡 Key idea Each row is a student. Sort the rows by the value in column k, largest first.
Edge / failure case k = 0 → [[5, 6], [3, 4]]
Sort by the first exam.
Why? [2,5,6,8,5], k=4: sorted [2,5,5,6,8]; the median 5 → 4 costs 1, and the left 5 must also drop to 4 (1 more) → 2.
💡 Key idea After sorting, the median is the element at index n // 2 (the larger middle). Move it to k, then every element left of it must be ≤ k and every element right of it must be ≥ k, fixing only the violators.
Edge / failure case even length → 0
The median is already 4.
Why? [1,5,1,1,6,4] → [1,6,1,5,1,4] has nums[0] < nums[1] > nums[2] < nums[3] > …
💡 Key idea Sort the array. Put the smaller half, in reverse order, into the even positions and the larger half, in reverse order, into the odd positions. Reversing keeps equal middle values apart so strict inequalities hold.
Edge / failure case duplicates → [2, 3, 1, 3, 1, 2]
Sorted halves placed alternately.
Why? 'daabcbaabcbc' removing 'abc' repeatedly → 'dab'.
💡 Key idea Push characters one by one; whenever the top of the stack spells part, pop those characters. Removing as soon as a match completes is the same as removing the leftmost occurrence repeatedly.
Edge / failure case nested → 'ab'
Nested removals.
Why? Star with centre 0 and targets 1, 2, 3: node 1 sees distances (0, 2, 2) and 0² + 2² = 2² → special; same for 2 and 3 → 3.
💡 Key idea Run a BFS (Breadth-First Search) from each of the three target nodes to get the distance of every node to x, y and z. For a node sort its three distances (a ≤ b ≤ c) and check a² + b² = c².
Edge / failure case second sample → 1
Only node 3 forms a triple.
Why? [2,4,3]: join 2+3 (cost 5), then 5+4 (cost 9) → 14.
💡 Key idea Joining two sticks costs their sum, and sticks joined early get re-counted in later joins. So join the two shortest sticks every time (Huffman style) using a min-heap.
Edge / failure case four sticks → 30
Total 30.
Why? n=4, index 2, maxSum 6: [1,2,2,1] gives 2 at index 2 → 2.
💡 Key idea Positions are positive and neighbours differ by at most 1, so the best shape is a pyramid peaking at index. Binary search the peak v and compute the minimum sum: each side is an arithmetic descent from v down to 1, then 1s. Accept v if the sum fits in maxSum.
Edge / failure case edge index → 3
Peak near the left edge.
Why? [5,2,−10,−5,1], k=3: start at 0 → 5 + (−5) = 0; start at 1 → 2 + 1 = 3 → best 3.
💡 Key idea From a start you jump k places until you fall off the end, collecting energy. Define total[i] = energy[i] + total[i+k]; compute from the right and return the maximum total.
Edge / failure case all negative → -1
Start at index 2: -1.
Why? [1,2,3,4]: slices [1,2,3], [2,3,4], [1,2,3,4] → 3.
💡 Key idea Let cur be the number of arithmetic slices ending at i. If nums[i] continues the same difference as the previous pair, cur = cur + 1 (every earlier slice extends, plus one new slice of length 3); otherwise cur = 0. Add cur each step.
Edge / failure case single element → 0
Too short.
Why? inventory [2,5], 4 orders: sell 5,4,3 and then a 2 → 14.
💡 Key idea Each sale takes the ball with the largest current value, which drops by 1 after the sale. Sort the stocks descending and lower the top group of w colours together, level by level, with arithmetic-series sums; when the orders run out in the middle of a level, handle the partial level.
Edge / failure case partial level → 19
Sell 5,4,3,3,2,2.
Why? [2,1,3,2,1,3] sorted [1,1,2,2,3,3]: medians 3 and 2 → 5.
💡 Key idea Each step removes three numbers and scores their median. The best step takes the two largest numbers plus the smallest: the median is the second largest. Sort, then repeatedly take the second largest of what remains, jumping two positions each time, for n/3 steps.
Edge / failure case big values → 20
Medians 10 and 10.
Why? 'abacaba': ab | ac | ab | a → 4 pieces.
💡 Key idea Each piece must have all-distinct letters. Extend the current piece while letters are new; when a letter repeats, start a new piece with it. Greedy is optimal.
Edge / failure case all same → 6
Every letter starts a piece.
Why? 'aabb': the last b's partner is at index 2; two adjacent swaps → 'abba' → 2.
💡 Key idea Look at the last character. Find the first occurrence of the same letter: bringing it to the front costs that index in swaps. Remove both and repeat on the inside. If the last letter is unique (the odd-length middle), move it to the centre at the cost of len // 2 and remove it.
Edge / failure case odd leftovers → 2
Two swaps.
Why? 'b' needs an 'a' before and a 'c' after → 2 insertions.
💡 Key idea A valid string is a concatenation of 'abc'. Scan the word: a new group starts whenever a letter is not greater than the previous one. With g groups the final length is 3g, so the additions are 3g − len(word).
Edge / failure case repeated a → 6
Each a needs b and c after it.
Why? tasks [[1,2],[2,4],[4,8]] (actual, minimum): start with 8 energy.
💡 Key idea A task needs at least `minimum` energy to start and uses `actual`. Order tasks by (minimum − actual) descending — the ones that leave the most 'slack' unused go first. Simulate: whenever current energy is below a task's minimum, top it up and count what you added.
Edge / failure case five tasks → 32
Answer 32.
Why? '1001': pairs '10' and '01' both differ → 2 changes.
💡 Key idea A beautiful string can be cut into even-length blocks of equal bits; every block splits into aligned pairs of equal letters, and pairs are enough. So count aligned pairs (positions 2i, 2i+1) whose letters differ.
Edge / failure case two chars → 1
One flip.
Why? [3,4,5] → all sides different → scalene; [8,4,4] → 4 + 4 is not more than 8 → none.
💡 Key idea Sort the sides; a triangle exists only if the two smaller add up to more than the largest. Then 1 distinct length means equilateral, 2 isosceles, 3 scalene.
Edge / failure case not a triangle → 'none'
4 + 4 is not more than 8.
Why? big_nums starts 1,2,1,2,4,1,4,2,4,1,… so the product of positions 1…3 is 2·1·2 = 4.
💡 Key idea big_nums is the concatenation, for i = 1, 2, 3 …, of the powers of two in i's binary expansion. Every element is a power of two, so a product is 2^(sum of exponents). Let pre(k) be the sum of exponents of the first k elements: binary search the largest number m whose total set-bit count up to m is ≤ k, add the exponent sum of 1…m (counted bit by bit) and the lowest remaining set bits of m+1. The answer is 2^(pre(to+1) − pre(from)) mod m.
Edge / failure case two queries → [2, 2]
Two queries.
Why? target 2: 1+2 = 3 overshoots by 1 (odd), 1+2+3 = 6 overshoots by 4 (even) → flip −2: 1−2+3 = 2 → 3 moves.
💡 Key idea On move i you step i left or right. Work with |target|. Take the smallest k with 1+…+k ≥ target. The overshoot (sum − target) can be fixed by flipping a step of size overshoot/2 to the other direction, which needs the overshoot to be even; otherwise keep increasing k until it is.
Edge / failure case target 3 → 2
1 + 2.
Why? 9 full bottles, 3 empties per new one: drink 9, exchange 9 → 3 new, drink, exchange → 1 more → 13.
💡 Key idea Keep drinking everything you have, then trade numExchange empties for one full bottle. Repeat while you have enough empties, adding every new bottle to the total.
Edge / failure case uneven → 19
Five exchanges in total.
Why? [1,2,3] → 3 moves: [2,3,3] → [3,4,3] → [4,4,4].
💡 Key idea Adding 1 to n−1 elements changes the gaps exactly like subtracting 1 from the remaining one. So the answer is how far every element is above the minimum: sum − n × min.
Edge / failure case equal → 0
Already equal.
Why? n=2 → 00, 01, 11, 10 → [0,1,3,2].
💡 Key idea The i-th Gray code is i ^ (i >> 1): consecutive values differ in exactly one bit. Generate it for i = 0 … 2ⁿ − 1.
Edge / failure case n = 1 → [0, 1]
0 then 1.
Why? 1 + 2: xor 3, carry 0 → 3. Python needs a 32-bit mask to behave like fixed-width ints.
💡 Key idea a XOR (exclusive OR) b adds without carrying; (a AND b) << 1 is the carry. Repeat until the carry is 0. Python integers are unbounded, so mask to 32 bits and convert back to a negative number if the sign bit is set.
Edge / failure case negative → 0
Negative plus positive.
Why? Column [3,1,3,0] becomes [3,4,5,6]: 0 + 3 + 2 + 6 = 11 operations for that column.
💡 Key idea Handle each column independently, top to bottom. A cell must be at least (value above) + 1; if it is smaller, raise it by the difference and count those increments.
Edge / failure case no operations → 0
Already increasing.
Why? Same as part I with much larger input: left/right best profits are found with Fenwick trees → 19 for the sample.
💡 Key idea Same idea as part I, but n is up to 50 000. Compress the prices, then use a Fenwick tree that stores the maximum profit seen for each price rank: scanning left to right it answers 'best profit among cheaper items' as a prefix maximum; scanning right to left with reversed ranks it answers 'best profit among pricier items'.
Edge / failure case increasing → 21
6 + 7 + 8 = 21.
Why? 'abc' with [0,1] (left 1) and [1,2] (right 2): net right 1 → 'cab'.
💡 Key idea Left shifts and right shifts cancel. Sum them into one net amount (left positive), reduce modulo the length, and rotate once.
Edge / failure case mixed shifts → 'efgabcd'
Net right shift of 3.
Why? 'ELELEEL': the room holds at most 2 people at the same time → 2 chairs.
💡 Key idea E means a person enters (+1) and L means a person leaves (−1). The chairs needed equal the largest running total.
Edge / failure case all enter → 7
Nobody leaves.
Why? 'leetcode' → 'ee' is the longest run → 2.
💡 Key idea Walk the string with a run counter that resets when the letter changes; keep the maximum.
Edge / failure case longest in the middle → 5
Longest run is five e's.
Why? [2,5,3,4,1]: teams (2,3,4), (5,4,1), (5,3,1) → 3.
💡 Key idea A team is an increasing or decreasing triple i<j<k. Fix the middle j: the increasing teams are (smaller on the left) × (larger on the right), the decreasing teams are (larger on the left) × (smaller on the right).
Edge / failure case no team → 0
No monotone triple.
Why? [2,1,3,5,4,6,7], k=2: 5 beats 3 and then 4: two wins in a row → 5.
💡 Key idea The larger of the first two stays, the smaller goes to the back. Scan once keeping the current champion and its win streak; if the streak reaches k return the champion. If it never does, the champion at the end is the maximum.
Edge / failure case huge k → 3
3 wins every game.
Why? 'aabccabba': strip the a's from both ends, then the b's, leaving 'cca' → 3.
💡 Key idea While the first and last characters are equal (and the pointers have not met), remove the whole run of that character from both ends. Stop when the ends differ; the answer is what is left.
Edge / failure case empty → 0
Everything can be removed.
Why? [2,-1,1,2,2]: 0 → 2 → 3 → 0 is a cycle of length 3 where every jump is forward → true.
💡 Key idea Each element tells how far to jump (mod n). A valid cycle has length > 1 and all jumps in the same direction. From every start follow the jumps while the direction stays the same and the jump is not a self-loop; revisiting a node on this walk means a cycle. Otherwise mark the visited nodes as 0 (dead) so they are never explored again.
Edge / failure case no cycle → False
Directions differ.
Why? [1,2,3,10,4,2,3,5]: keep [1,2,3] and [3,5] → remove 3 elements.
💡 Key idea Find the longest non-decreasing prefix and the longest non-decreasing suffix. Remove everything between, or keep part of both: with two pointers, for every prefix element find the first suffix element that is ≥ it; the removed middle shrinks as the prefix grows.
Edge / failure case reverse sorted → 4
Keep one element.
Why? Student 1 has scores 91, 92, 60, 65, 87, 100 → top five 100, 92, 91, 87, 65 → average 87.
💡 Key idea Group scores by student id, sort each group descending, average the top five (integer division), and output students in increasing id order.
Edge / failure case five scores → [[1, 30]]
Exactly five scores.
Why? [5,3,6,1,12], original 3 → 3, 6, 12, 24 → 24.
💡 Key idea Put the numbers in a set. While the current value is in the set, double it. Return the first value not found.
Edge / failure case absent → 4
4 is not present.
Why? 'a3c9b2c1' → a:3, b:2, c:9+1=10 → 'a3b2c10'.
💡 Key idea The compressed string is pairs of a letter and a (possibly multi-digit) count. Parse the pairs, add counts per letter, and write the letters alphabetically with their totals.
Edge / failure case already unique → 'a1b3c2'
Reorder alphabetically.
Why? [[1,2,10],[2,3,20],[2,5,25]], n=5 → seats per flight [10,55,45,25,25].
💡 Key idea A booking adds seats to a range of flights. Add the seats at the first flight and subtract them just after the last; a prefix sum then gives every flight's total.
Edge / failure case two flights → [10, 25]
Overlap on flight 2.
Why? n=15 = 1+2+4+8: queries [0,1]→2, [2,2]→4, [0,3]→64.
💡 Key idea powers is the sorted list of powers of two in n's binary form. For each query multiply the powers from l to r modulo 1e9+7 (at most ~30 numbers).
Edge / failure case single power → [2]
Only the power 2.
Why? [2,1,1,1,3,4,1], k=2: index 2 and 3 have two non-increasing before and two non-decreasing after → [2,3].
💡 Key idea Index i is good if the k elements before it are non-increasing and the k after it are non-decreasing. Precompute for every position the length of the non-increasing run ending there and of the non-decreasing run starting there; i is good if both are at least k (looking one step away from i).
Edge / failure case none → []
No index has two on each side that fit.
Why? mapping [8,9,4,0,2,1,3,5,7,6]: 991→669, 338→007, 38→07 → sorted order 338, 38, 991.
💡 Key idea Each digit d is replaced by mapping[d] to get the number's mapped value. Sort the original numbers by their mapped value; Python's sort is stable, so equal mapped values keep their original order.
Edge / failure case identity → [123, 456, 789]
Identity mapping.
Why? [1,3,4,2,6,8] = original [1,3,4] plus doubles [2,6,8] → [1,3,4].
💡 Key idea The array holds each original value x and also 2x. Sort and count. For the smallest remaining value x it must be an original, so consume one x and one 2x; if there is no 2x left the array is not doubled.
Edge / failure case invalid → []
Odd length.
Why? 'IIIDIDDD' → 123549876.
💡 Key idea Write digits 1, 2, 3 … in order, but for every group of consecutive D's reverse the matching digits. A stack does this: push each digit, and pop everything whenever you reach an I (or the end).
Edge / failure case all D → '4321'
Strictly decreasing.
Why? '|(f,f,f,t)' → OR of false, false, false, true → true.
💡 Key idea Scan left to right. Push every character except commas and ')'. On ')' pop the values back to the operator ('!', '&', '|'), combine them (not / all / any) and push the result as 't' or 'f'.
Edge / failure case nested → True
AND is false, NOT makes it true.
Why? [3,0,0]: move one coin to each child → 2 moves.
💡 Key idea Postorder: a subtree with n nodes and c coins must send c − n coins to its parent (negative means it needs coins). Every such coin crosses the edge to the parent once, so add |c − n| for each node.
Edge / failure case coins in the middle → 3
Three moves.
Why? Pairs [5,1],[4,5],[11,9],[9,4] chain as 11→9→4→5→1.
💡 Key idea Treat each pair as a directed edge start → end. A valid arrangement uses every edge once: an Eulerian path. Its start is the node with out − in = 1 (or any node if all balanced). Run Hierholzer's algorithm with a stack, appending edges when a node is exhausted, then reverse.
Edge / failure case cycle → [[1, 3], [3, 2], [2, 1]]
A closed loop: start anywhere.
Why? Path 1 → 0 → 2 → 3 with the 4-edge and the 6-edge hopped (cost 0) leaves just the 2-edge → 2.
💡 Key idea A hop makes one edge cost 0, at most k times. Run Dijkstra on states (node, hops used): from a state you can pay the edge weight, or if hops remain use a hop and pay 0. The answer is the cheapest distance to the destination over all hop counts.
Edge / failure case second sample → 6
Hop over two heavy edges.
Why? 'banana' → 'ana' occurs twice (overlapping) → 'ana'.
💡 Key idea If a duplicate of length L exists, one of every shorter length exists too, so binary search L. Check a length by hashing all substrings of that length with a rolling (prefix) hash and looking for a repeat, confirming equality to rule out collisions.
Edge / failure case repeat → 'abc'
'abc' repeats.
Why? [2,2,2,0,1] → minimum 0.
💡 Key idea Compare nums[mid] with nums[hi]. If mid is bigger, the minimum is to the right. If smaller, it is at mid or to the left. If equal we cannot tell, so drop one element from the right end.
Edge / failure case sorted → 1
Not rotated.
Why? n=3: 1,2,3 and 3,2,1 alternate odd/even → [[1,2,3],[3,2,1]].
💡 Key idea Build permutations of 1…n by backtracking, trying numbers in increasing order so results come out sorted, and only allowing a number whose parity differs from the previous one.
Edge / failure case n = 2 → [[1, 2], [2, 1]]
Both orders alternate.
Why? skill [1,5,2,4], mana [5,1,4,2] → the last potion is done at time 110.
💡 Key idea Potions pass through wizards without waiting, so for each potion only its start time matters. Keep done[i], the time wizard i finishes the previous potion. For the next potion compute forward the earliest finish at the last wizard (each wizard starts when both it is free and the potion arrives), then walk backwards subtracting work times to get the new done[] values.
Edge / failure case all ones → 5
Every wizard takes 1 for every potion.
Why? houses [1,4,8,10,20], 3 mailboxes → groups (1,4),(8,10),(20): 3 + 2 + 0 = 5.
💡 Key idea Sort the houses and split them into k contiguous groups, each with one mailbox at the group's median (the cheapest spot). cost(i, j) is the total distance to the median of houses i..j. dp[g][j] = min over split points of dp[g−1][i] + cost(i, j−1).
Edge / failure case two mailboxes → 9
Groups (2,3,5) and (12,18).
Why? '22233' → 222 → {aaa, ab, ba, c} (4), 33 → {ee, f} (2) → 8.
💡 Key idea Texts are phone-key presses; a run of the same digit can be split into groups of up to 3 presses (4 for keys 7 and 9). dp[i] = number of ways to decode the first i presses = sum of dp[i−1], dp[i−2], dp[i−3] (and dp[i−4] for 7/9) while the previous presses are the same key.
Edge / failure case long run → 82876089
A long run of 2s.
Why? 'cacb' and 'cbba': the best palindrome using letters from both words has length 5.
💡 Key idea Concatenate the words and compute the longest palindromic subsequence dp[i][j]. A candidate only counts if its outer letters come from different words: when s[i] == s[j] with i in word1 and j in word2, record dp[i][j] as an answer.
Edge / failure case small → 3
'aba' with letters from both words.
Why? [3,6,5,1,8] → 3+6+1+8 = 18.
💡 Key idea Keep dp[r], the largest sum seen so far with remainder r when divided by 3. For each number, try adding it to every existing remainder class and update the class of the new remainder.
Edge / failure case single number → 0
No multiple of 3 can be built.
Why? [1,2,3,4,5,6,7,8] → 1,2,3,5,8 has length 5.
💡 Key idea dp[(j,k)] is the length of the longest Fibonacci-like subsequence ending in arr[j], arr[k]. For a pair, look for the previous term arr[k] − arr[j] (must be smaller than arr[j] and present) and extend its chain by one. Answer is the best length ≥ 3, else 0.
Edge / failure case length three → 3
1,11,12 or 3,11,14 or 7,11,18.
Why? The sample 3×4 matrix contains 10 + 4 + 1 = 15 all-ones squares.
💡 Key idea dp[i][j] is the side of the largest all-ones square whose bottom-right corner is (i, j): 1 + min(up, left, up-left) if the cell is 1. That number is also how many squares end at this cell, so the answer is the sum of dp.
Edge / failure case small grid → 7
Seven squares.
Why? Numbers 1…12 with digit sum between 1 and 8: only 9 (sum 9) is excluded → 11.
💡 Key idea Count numbers in [0, N] whose digit sum lies in [min_sum, max_sum] with a digit DP (Dynamic Programming): state (position, sum so far, still tight to N). Answer = f(num2) − f(num1) + (1 if num1 itself qualifies), modulo 1e9+7.
Edge / failure case small range → 5
All of 1-5.
Why? From (1,0) to (2,3): enter row 2 (3) and columns 1,2,3 (2 + 6 + 7) → 18.
💡 Key idea Every path that moves only toward home enters the same rows and columns, and the cost of a move depends only on the row or column entered. So the minimum is the sum of rowCosts of every row passed (excluding the start row) plus colCosts of every column passed.
Edge / failure case already home → 0
Already home.
Why? [3,2,1,2,1,7]: sorted 1,1,2,2,3,7 become 1,2,3,4,5,7 → 6 increments.
💡 Key idea Sort the numbers. Walk left to right; each number must be at least previous + 1. If it is smaller, raise it to that value and count the increments.
Edge / failure case small → 1
One increment.
Why? 'cbabc' → decrement 'cb' to 'ba' → 'baabc'.
💡 Key idea The operation replaces every letter of one chosen substring by its previous letter ('a' becomes 'z'). To make the string smallest, start at the first letter that is not 'a' and decrement until the next 'a'. If the string is all 'a', change only the last letter to 'z'.
Edge / failure case all a → 'az'
All a: change the last letter to z.
Why? s1='xy', s2='yx': one x/y mismatch and one y/x mismatch → 2 swaps.
💡 Key idea Look only at positions where the strings differ: count (x,y) mismatches and (y,x) mismatches. Two of the same kind are fixed with one swap. If one of each kind is left over, it takes two swaps. If the total number of mismatches is odd, it is impossible (−1).
Edge / failure case same type → 1
One swap fixes both.
Why? n=3 monkeys: 8 direction choices, only all-clockwise and all-counter-clockwise avoid collisions → 6 collide.
💡 Key idea Each monkey picks one of 2 directions: 2ⁿ ways. Only the two ways where everyone goes the same direction have no collision, so the answer is 2ⁿ − 2 modulo 1e9+7.
Edge / failure case n = 4 → 14
16 − 2.
Why? Row 2 is 01: the 1st symbol is 0, the 2nd is 1.
💡 Key idea Each row is the previous one with 0 → 01 and 1 → 10. The k-th symbol is the parity of the number of 1 bits in k − 1 (the Thue–Morse sequence).
Edge / failure case row 4 → 1
Row 4 is 01101001.
Why? ['01:15','02:00'] and ['02:00','03:00'] share the instant 02:00 → conflict.
💡 Key idea Convert each 'HH:MM' to minutes. Two closed intervals overlap when each starts no later than the other ends.
Edge / failure case disjoint → False
Different parts of the day.
Why? Rook (5,3), bishop (3,4), queen (5,2): the rook sees the queen straight up the column → 1.
💡 Key idea On an 8×8 board a rook and a bishop try to capture the queen. The answer is 1 if the rook shares a row or column with the queen without the bishop between them, or the bishop shares a diagonal with the queen without the rook between them; otherwise 2 moves always suffice.
Edge / failure case two moves → 2
Neither piece sees the queen in one move.
Why? Events (5,7),(2,7),(9,4): poll → 2 (tie on priority 7, smaller id); update 9 to 7; poll → 5; poll → 9.
💡 Key idea Keep a heap ordered by (priority descending, id ascending). Updating an event pushes a new entry and records the current priority in a dict; stale heap entries are ignored when popped. pollHighest pops until it finds an entry that matches the dict, removes the event and returns its id.
Edge / failure case empty queue → [1, -1]
After the only event is gone, poll returns -1.
Why? Tree parents [-1,0,0,1,1,2,2]: the 1st ancestor of 3 is 1; the 2nd of 5 is 0; the 3rd of 6 does not exist → −1.
💡 Key idea Precompute up[j][v], the 2^j-th ancestor of v, from the parent array. To jump k levels, combine the jumps for each set bit of k; if any jump lands on −1 the answer is −1.
Edge / failure case single node → [-1, 0]
The root has no ancestor.
Why? 'dcab' with pairs [0,3],[1,2]: positions {0,3} sort to 'b','d'; {1,2} to 'a','c' → 'bacd'.
💡 Key idea Indices connected by swap pairs (directly or through others) can be permuted freely. Union the pairs; for each group sort its letters and put them back into the group's sorted index positions.
Edge / failure case one group → 'abcd'
All positions connect.
Why? nums [0,1,2,3,4], index [0,1,2,2,1] → [0,4,1,3,2].
💡 Key idea Start with an empty list and for each position i insert nums[i] at position index[i] (this shifts later elements right).
Edge / failure case single → [1]
One element.
Why? [1,1,1,6,1,1,1]: the 6 and the first or last 1 → farthest distance 3.
💡 Key idea For the farthest pair with different colours, one house can be moved to an end of the row. So compare the first house with the last different one, and the last house with the first different one; the larger distance wins.
Edge / failure case ends differ → 4
Colour 1 at the left end and 3 at index 4.
Why? Users 0,1: message mentions both, user 0 goes offline for a minute, then HERE at time 71 reaches both → [2,2].
💡 Key idea Sort events by time; at the same time OFFLINE events come before MESSAGE events. Remember the time each user comes back online (offline time + 60). A message with 'id…' tokens increases each mentioned id (duplicates count), 'ALL' increases everyone, 'HERE' increases only users who are online at that time.
Edge / failure case offline user → [0, 1]
User 0 is offline.
Why? [2,1,3]: arr1=[2], arr2=[1], then 2 > 1 so 3 goes to arr1 → [2,3,1].
💡 Key idea The first element goes to arr1 and the second to arr2. For each later element, put it into arr1 if the last element of arr1 is larger than the last of arr2, else into arr2. The answer is arr1 followed by arr2.
Edge / failure case four numbers → [5, 3, 4, 8]
5 > 4 sends 3 to arr1; then 3 < 4 sends 8 to arr2.
Why? 'xyzzaz': 'xyz' is good, 'yzz' no, 'zza' no, 'zaz' no → 1.
💡 Key idea Look at every window of three consecutive letters and count those with three different letters.
Edge / failure case longer text → 4
Four windows.
Why? [3,1,4,3,2,2,4], k=2: four subarrays contain at least 2 equal pairs → 4.
💡 Key idea A subarray is good if it has at least k pairs (i<j) with equal values. Maintain the pair count of the window with a frequency map (adding x adds freq[x] pairs; removing x removes freq[x]−1). When the window has ≥ k pairs, every extension to the right is good, so add n − r and shrink from the left.
Edge / failure case all equal → 1
Only the whole array has 10 pairs.
Why? 'aabca': 'aba', 'aca', 'aaa' → 3.
💡 Key idea A length-3 palindrome is x y x. For every letter x take its first and last positions; every distinct letter strictly between them is a valid middle y. Add up the number of distinct letters in each such interval.
Edge / failure case none → 0
No repeated letter.
Why? [[1,2,3],[4,5,6],[7,8,9]], k=1: the centre cell sums the whole grid, 45.
💡 Key idea answer[i][j] is the sum of the block from (i−k, j−k) to (i+k, j+k), clamped to the matrix. A 2D prefix-sum table gives any rectangle sum in O(1) by inclusion–exclusion.
Edge / failure case small matrix → [[10, 10], [10, 10]]
Every block covers the whole matrix.
Why? nums [-5,-2,3]: 0→1 costs 1 (closest), 1→2 costs 5 → query [0,2] = 6.
💡 Key idea nums is strictly increasing, so a jump equals the sum of single steps and walking step by step is never worse. A right step from i costs 1 if i's closest neighbour is i+1, otherwise the gap; a left step from i costs 1 if the closest is i−1, otherwise the gap. Build prefix sums for right steps and for left steps and answer each query in O(1).
Edge / failure case both directions → [5, 5]
Mixes closest moves and gaps.
Why? [3,2,5,1,3,4] → pairs (1,5), (2,4), (3,3) all sum to 6 → 3·... chemistry 5 + 8 + 9 = 22.
💡 Key idea All teams of two must have the same total skill. After sorting, the only way is to pair the smallest with the largest, the second smallest with the second largest, and so on, and every pair must have the same sum. Add up the products; return −1 if a pair differs.
Edge / failure case one team → 12
One team.
Why? [5,8,9,2,1,3,7,4,6] has level sums 5, 17, 13, 10; the 2nd largest is 13.
💡 Key idea Do a BFS (Breadth-First Search) and compute the sum of each level. If there are fewer than k levels return −1, otherwise sort the sums in descending order and take the k-th.
Edge / failure case too few levels → -1
Only three levels.
Why? ['A..','.A.','...']: step onto an A, jump free to the other A and walk the rest → 2 moves.
💡 Key idea Moves cost 1 and teleports cost 0, so use a 0-1 BFS (Breadth-First Search) with a deque. The first time any cell of letter c is reached, that is the cheapest moment to use portal c: push all other cells of c at the same distance to the front of the queue and mark c as used. Walk the four directions otherwise.
Edge / failure case teleport to the goal → 0
Step onto A and teleport straight to the goal A.
Why? graph [[1,1,0],[1,1,0],[0,0,1]], initial [0,1]: removing node 0 leaves 1 infected; removing 1 leaves 1 → pick the smaller index 0.
💡 Key idea Removing a node deletes it and its edges. For each node in initial, delete it, spread the infection from the other initial nodes through the remaining graph with BFS (Breadth-First Search) and count infected nodes. Choose the removal with the fewest infected nodes (smallest index on ties). n ≤ 300 keeps this fast enough.
Edge / failure case triangle → 1
Removing node 1 leaves 2 infected nodes.
Why? [1,10,3,3,3], k=3: take 10 (→4), then 4 (→2), then 3 → 17.
💡 Key idea Each operation adds nums[i] to the score and replaces it with ceil(nums[i] / 3). Greedy: always operate on the current maximum. Use a max-heap.
Edge / failure case all equal → 50
Take each once.
Why? n=2: [1,2] and [2,1] both satisfy 'divisible one way' at every position → 2.
💡 Key idea A permutation of 1…n is beautiful if for each position i, perm[i] is divisible by i or i is divisible by perm[i]. Fill positions 1, 2, 3… with unused numbers that satisfy the rule (a bitmask records used numbers) and count complete arrangements.
Edge / failure case n = 4 → 8
Eight valid permutations.
Why? [[1,3,3],[2,5,4],[4,3,5]], k=2: walk down, right (cost 7), then teleport to the bottom-right (value 5 ≤ 5) → 7.
💡 Key idea Layer t = best cost to reach each cell using at most t teleports. Layer 0 is the usual right/down DP (cost = destination value). For the next layer, a cell can be entered for free from any cell with a value ≥ its own, so keep the cheapest previous-layer cost among cells with value ≥ v (a suffix minimum over values), then rerun the right/down DP (Dynamic Programming) seeded with those teleport costs.
Edge / failure case one teleport → 9
Teleport from the larger cell to the goal.
Why? The first 10 ugly numbers are 1,2,3,4,5,6,8,9,10,12 → the 10th is 12.
💡 Key idea Ugly numbers have only the prime factors 2, 3 and 5. Each is an earlier ugly number times 2, 3 or 5. Keep three pointers into the list built so far; the next ugly number is the smallest of the three candidates, and every pointer whose candidate equals it advances.
Edge / failure case n = 1 → 1
1 is the first.
Why? [1,-1,-2,4,-7,3], k=2 → path 1, -1, 4, 3 gives 7.
💡 Key idea dp[i] = nums[i] + max(dp[i−k..i−1]). The sliding-window maximum is kept with a decreasing deque of indices: drop indices that left the window and any with values ≤ the new dp.
Edge / failure case wide jumps → 17
Jump 0 → 3 → 5.
Why? nums1 [2,3,1], nums2 [1,2,1]: choose 2,3,... → best subarray length 2.
💡 Key idea At each index build nums3[i] from nums1 or nums2. Keep a1 = longest non-decreasing subarray ending here if we pick nums1[i], and a2 for nums2[i]. Each extends the previous a1 or a2 when the earlier value is ≤ the current one; otherwise restart at 1.
Edge / failure case mix arrays → 4
Take 1,2,3,4.
Why? plant [1,4,3], grow [2,3,1] → plant the 3-day grower first, then the 2-day grower, then the 1-day one → day 9.
💡 Key idea Planting takes your own time one seed after another, but growing runs in the background. To finish soonest, plant seeds with the longest grow time first. Then the finish day is the maximum over seeds of (planting finished + grow time).
Edge / failure case one seed → 2
Plant 1 day, grow 1 day.
Why? [1,2,3,6,2,3,4,7,8], groupSize 3 → [1,2,3], [2,3,4], [6,7,8] → true.
💡 Key idea Count the cards. The smallest remaining card must start a group of consecutive numbers: remove one of each of value, value+1, …, value+groupSize−1. If any is missing, return false.
Edge / failure case bad size → False
5 cards cannot form groups of 4.
Why? '10111' changes at 0→1, 1→0, 0→1 → 3 flips.
💡 Key idea A flip inverts everything from index i to the end, so only the places where the target changes from the previous bit need a flip (starting from an all-0 string). Count the positions where the bit differs from the one before it (with an initial 0).
Edge / failure case alternating → 3
Three changes.
Why? [12,9], k=1: double 9 → 18, OR with 12 = 30.
💡 Key idea Doubling shifts a number left, so it is best to put all k shifts on one element to make its high bits count. Try each element with prefix OR and suffix OR of the others: prefix[i] | (nums[i] << k) | suffix[i+1].
Edge / failure case three numbers → 35
Shift the 8: 32 | 1 | 2 = 35.
Why? In the sample grid the segment 1 → 2 → 0 → 2 → 0 along a diagonal with one clockwise turn has length 5.
💡 Key idea A segment starts at a 1 and then follows 2, 0, 2, 0 … along a diagonal, and may turn clockwise once. State = (cell, direction, turned yet?). From a cell with value v the next required value is 2 (after 1 or 0) or 0 (after 2). Continue straight, or turn to the next clockwise diagonal if no turn has been used; take the longer result. Memoise and try every 1 with every direction.
Edge / failure case single cell → 1
A lone 1.
Why? [3,5,4,2,4], k=1: 3 < 5 > 2 < 4 uses indices 0,1,3,4 → 14.
💡 Key idea Let peak[i] be the best sum of a valid subsequence ending at i where nums[i] is higher than the previous chosen value, and valley[i] the same with nums[i] lower. peak[i] = nums[i] + max(0, best valley[j]) over j ≤ i − k with nums[j] < nums[i]; valley[i] is symmetric. Two Fenwick trees (prefix maximum over compressed values) answer those queries; insert index j only once i − j reaches k.
Edge / failure case k = 1 → 14
3 < 5 > 2 < 4 uses indices 0,1,3,4.
Why? Two infected columns in a 4×8 grid: quarantining each costs 5 walls, total 10.
💡 Key idea Simulate night by night. Find every connected infected region (4-directional) and, for each, the set of uninfected cells it could spread to (its frontier) and the number of walls needed (region cell – uninfected neighbour pairs). Wall off the region with the biggest frontier (mark it quarantined and add its walls); every other region spreads into its frontier. Stop when no region threatens any cell.
Edge / failure case ring → 4
A ring around one healthy cell needs 4 walls.
Why? Rectangles overlapping in a 1×1 region → largest square has area 1.
💡 Key idea A square inside the overlap of two rectangles is limited by the overlap's width and height. For each pair compute width = min(right) − max(left) and height = min(top) − max(bottom); if both are positive the biggest square has side min(width, height). Take the largest side over all pairs and return its square.
Edge / failure case bigger square → 1
The overlap is 2 wide but only 1 tall, so the square has side 1.
Why? '1001' has two segments of ones → false; '110' has one → true.
💡 Key idea The string starts with '1'. A second segment of ones exists exactly when the pattern '01' appears (a zero followed by a one).
Edge / failure case single segment → True
One segment.
Why? [7,1,5,4]: buy at 1, sell at 5 → 4.
💡 Key idea For each j find the smallest earlier value; if it is smaller than nums[j], nums[j] − that min is a candidate. Return the largest candidate, or −1 if no pair has nums[i] < nums[j].
Edge / failure case no pair → -1
Strictly decreasing.
Why? 'aaabcbbcc', count=3: three substrings (e.g. 'aaa') have every present letter exactly 3 times → 3.
💡 Key idea A substring where every letter that occurs does so exactly `count` times and which has d distinct letters has length d × count. For each d from 1 to 26 slide a window of that length while tracking how many letters currently occur exactly count times; when that number equals d the window is valid.
Edge / failure case none → 0
No letter appears twice.
Why? [1,5,2]: player 1 takes 1 and loses to 5+...; best difference is −2 → false.
💡 Key idea dp[i][j] is the best (current player − opponent) score difference on nums[i..j]. The player takes the left end or the right end and then faces the opponent's best difference: dp[i][j] = max(nums[i] − dp[i+1][j], nums[j] − dp[i][j−1]). Player 1 wins if dp[0][n−1] ≥ 0.
Edge / failure case player 1 wins → True
Player 1 takes 1 then 233.
Why? [[1,2],[2,3],[3,4]]: take [1,2] then [3,4] → chain of 2.
💡 Key idea A pair (c,d) can follow (a,b) if b < c. This is activity selection: sort pairs by their right end and greedily take each pair that starts after the end of the last chosen one.
Edge / failure case unsorted → 3
All three can be chained.
Why? k=2, n=5: the smallest numbers that are palindromes in base 10 and base 2 are 1, 3, 5, 7, 9 → 25.
💡 Key idea Instead of testing every integer, generate base-10 palindromes in increasing order (by length, then by their first half mirrored). For each, check whether its base-k digits form a palindrome, collect the first n that do, and add them up.
Edge / failure case base 3 → 499
The seven smallest sum to 499.
Why? 5×5 with k=1: each sensor covers a 3×3 block → 2 × 2 = 4 sensors.
💡 Key idea A sensor covers every cell within Chebyshev distance k: a (2k+1)×(2k+1) square. Tiling the n×m grid with these squares needs ceil(n/(2k+1)) rows and ceil(m/(2k+1)) columns of sensors.
Edge / failure case big k → 1
One sensor covers all.
Why? Router with capacity 3: adding a 4th packet evicts the oldest; getCount(5,100,110) counts packets for destination 5 in that time range.
💡 Key idea Keep packets in a FIFO (First In, First Out) deque (oldest first) with a set for duplicate detection. For getCount, store each destination's timestamps in a list (they arrive in non-decreasing order) plus how many of its oldest entries have been removed; binary search the live part of the list. Evicting or forwarding a packet pops the deque front and advances that destination's removed counter.
Edge / failure case forward from empty → [True, [7, 4, 90], []]
Forward returns the only packet, then an empty list.
Why? Bids 5 and 6 on item 7: the highest bidder is user 2; user 1 raises to 8 and becomes the highest.
💡 Key idea Keep a dictionary (user, item) → current bid, and for each item a max-heap of (amount, userId). add and update push a new heap entry and overwrite the dictionary; remove deletes the dictionary entry. When asked for the highest bidder, discard heap tops that no longer match the dictionary (stale), then return the top's user (highest user id on ties) or −1.
Edge / failure case tie on amount → [None, None, 5, -1]
Equal bids: the larger user id wins; an item with no bids gives -1.
Why? DataStream(4, 3): after 4, 4, 4 the last three are all 4 → true; a 3 breaks the run.
💡 Key idea Keep a counter of how many equal-to-value integers have just arrived in a row: increase it when num == value, reset it to 0 otherwise. consec returns true when the counter is at least k.
Edge / failure case k = 1 → [False, True]
With k = 1 the latest number decides.
Why? ['are','amy','u'], indices 0-2: 'are' and 'u' start and end with a vowel → 2.
💡 Key idea In the index range, count words whose first and last letters are both vowels.
Edge / failure case inner range → 3
Three words qualify.
Why? [1,1,1,2,1,2], k=3: the window [2,1,2] scores 2² + 1 = 5; [1,1,1] scores 1.
💡 Key idea The score of a window is Σ value^frequency over its distinct values, taken modulo 1e9+7, and we maximise that modded value. Slide a window of size k keeping the frequency map and the score: adding x changes its term from x^f to x^(f+1); removing x changes it from x^f to x^(f−1).
Edge / failure case all ones → 1
1 to any power is 1.
Why? words ['cat','bt','hat','tree'], chars 'atach': 'cat' and 'hat' can be formed → 3 + 3 = 6.
💡 Key idea A word is good if every letter appears in chars at least as many times as in the word. Count the letters of chars once, test each word with a Counter, and add the lengths of the good words.
Edge / failure case two words → 10
'hello' and 'world' can be formed.
Why? nums [1,2,3,4,5], requests [1,3] and [0,1]: slot 1 is asked twice, slots 0,2,3 once → best sum 19.
💡 Key idea A permutation changes where each number goes, not how often each slot is requested. Count how many requests cover each index with a difference array, then pair the largest request counts with the largest numbers (sort both) and sum the products.
Edge / failure case single request → 11
Put 6 and 5 in the two requested slots.
Why? richer pairs [1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3] with the quiet values: person 0's answer is 5 (the quietest among everyone at least as rich).
💡 Key idea richer[a] = [x, y] means x has more money than y. For each person, the answer is the quietest person among those who have at least as much money, i.e. themselves and everyone reachable by walking up the 'richer' edges. DFS (Depth-First Search) with memoisation from each person.
Edge / failure case no edges → [0]
One person alone.
Why? banned [1,6,5], n=5, maxSum=6 → pick 2 and 3 → 2 (n and maxSum can be huge).
💡 Key idea Same greedy as part I (take the smallest available numbers), but n and maxSum are huge so we cannot loop. Sort the distinct banned numbers ≤ n. Between consecutive banned numbers the available values form a run; binary search how many numbers of that run fit in the remaining sum using the arithmetic-series formula. Stop as soon as a run cannot be taken completely.
Edge / failure case gap before n → 3
Take 1, 2 and 7.
Why? k=2 with digits 0 and 2: 2, 20, 22 … the first number > 2 divisible by 2 is 20.
💡 Key idea Generate numbers that use only the two digits in increasing order with a queue: start from the non-zero digits and append the digits in ascending order. The first generated number that is greater than k and divisible by k is the answer; stop with −1 once the numbers exceed the 32-bit limit.
Edge / failure case digits 4 and 2 → 24
24 is the smallest.
Why? One rook at (1,1) can end on 15 squares (14 moves along its row and column plus staying) → 15.
💡 Key idea Each piece chooses a direction and a distance (or stays). Describe every move by the square it occupies at times 0 … 7 (it waits at the destination). Backtrack over the pieces choosing one move each and reject a combination as soon as two pieces share a square at the same time. Count the complete combinations.
Edge / failure case queen → 22
A queen in the corner reaches 22 squares.
Why? banned [1,6,5], n=5, maxSum=6: take 2 and 3 (sum 5); adding 4 would reach 9 → 2.
💡 Key idea To pick as many numbers as possible with a limited sum, pick the smallest ones. Walk 1 … n, skip banned numbers, and stop when the next number would push the sum over maxSum.
Edge / failure case everything fits → 7
Take all of 1-7.
Why? p=3: numbers 1…7; best arrangement leaves 7 and three pairs (1, 6) → 7 · 6³ = 1512.
💡 Key idea Swapping bits between two numbers keeps their sum, so to make the product small make one of them tiny. The best is to turn every pair (x, 2^p−1−x) into (1, 2^p−2). That leaves the maximum 2^p−1 alone and 2^(p−1)−1 pairs worth 2^p−2 each: (2^p−1) · (2^p−2)^(2^(p−1)−1) mod 1e9+7.
Edge / failure case p = 2 → 6
3 × 2 = 6.
Why? [1,2,3,4,5], k=2: pairs containing an even number work: 7 of them.
💡 Key idea nums[i]·nums[j] is divisible by k exactly when gcd(nums[i], k) · gcd(nums[j], k) is divisible by k. k has few divisors, so count the earlier numbers by their gcd with k and, for each new number, add the counts of the gcd classes that pair with it.
Edge / failure case none → 0
No product is divisible by 5.
Why? [3,7,8,1,1,5], space=2: seed 1 destroys every odd value (3,7,1,1,5) → seed 1.
💡 Key idea A seed destroys all targets equal to seed + c·space, i.e. with the same remainder mod space. Count targets per remainder, pick the remainder with the most targets, and return the smallest number having that remainder.
Edge / failure case tie → 1
Odd remainder and even remainder tie; the smaller seed wins.
Why? [2,5,4,3]: distinct evens {2,4} and distinct odds {5,3} are equal in number → length 4.
💡 Key idea A subarray is balanced when the number of distinct even values equals the number of distinct odd values. For each start index extend to the right, keeping two sets (distinct evens and distinct odds); whenever the sizes match, update the best length.
Edge / failure case repeated values → 5
Whole array: evens {2,4}, odds {3,5}.
Why? '0110011', ratio 1:2: four substrings have exactly one 0 per two 1s → 4.
💡 Key idea A substring has zeros:ones = num1:num2 exactly when zeros·num2 = ones·num1. Let key(i) = zeros·num2 − ones·num1 over the prefix of length i. A substring qualifies when the keys at its ends are equal. Count equal key pairs with a hash map (substrings with only zeros or only ones never match because num1, num2 > 0).
Edge / failure case no match → 0
No substring has three 0s per 1.
Why? 'e + 8 - a + 5' with e = 1 simplifies to '-1*a' and '14'.
💡 Key idea Treat every expression as a polynomial: a dictionary from a sorted tuple of variable names (a monomial) to its integer coefficient. Parse with recursive descent (expression → term → factor), substituting the known variables. Addition and subtraction merge dictionaries; multiplication multiplies every pair of monomials. Finally output the terms ordered by degree (high first) then alphabetically.
Edge / failure case product → ['1*e*e', '-64']
e² − 64.
Why? The sample grid has four islands; two have totals divisible by 5 → 2.
💡 Key idea Cells with positive values are land; neighbours (4 directions) belong to one island. Flood-fill each unvisited land cell, summing the values, and count the islands whose sum is divisible by k.
Edge / failure case separate cells → 8
Eight single-cell islands each worth 3.
Why? [9] with 2 splits: 9 → 3+3+3 → penalty 3.
💡 Key idea Guess the maximum bag size p. A bag of x balls needs ceil(x / p) − 1 splits. If the total splits needed is ≤ maxOperations, p works. Binary search the smallest p.
Edge / failure case several bags → 2
Penalty 2.
Why? Grid [[9,5,7,3],[8,9,6,1],[6,7,14,3],[2,5,3,1]]: go from 2 to 14 and on → total score 9.
💡 Key idea Moving from a cell to any cell to its right or below scores (destination − source), and a path's total telescopes to (last − first). So for each cell the best path ending there starts at the smallest cell reachable going up/left. Keep the running minimum of each prefix rectangle and take the best of cell − min(top, left).
Edge / failure case negative answer → -1
Every move loses points; the best loses 1.
Why? [1,2,3,4,5], target 9: {2,3,4} or {1,3,5} or {4,5}… the longest has 3 elements → 3.
💡 Key idea dp[s] is the longest subsequence that adds up to exactly s (−∞ if impossible). Process each number once, updating sums from high to low so each number is used at most once: dp[s] = max(dp[s], dp[s − x] + 1).
Edge / failure case impossible → -1
No subset adds to 3.
Why? n=1 has 12 colourings (6 of type ABC, 6 of type ABA); n=2 has 54.
💡 Key idea A row with 3 cells and 3 colours is either three different colours (ABC type, 6 ways) or the outer two equal (ABA type, 6 ways). From an ABC row the next row can be 2 ABC and 2 ABA patterns; from an ABA row it can be 2 ABC and 3 ABA. Iterate: abc' = 2·abc + 2·aba, aba' = 2·abc + 3·aba.
Edge / failure case large n → 30228214
A large n.
Why? [1,3,2,2,2,3,4,3,1] → clear 2,2,2 (9 points), then 4, then merge the 3s... best score 23.
💡 Key idea Removing k same-coloured contiguous boxes scores k². dp(l, r, k) = best score for boxes[l..r] when k extra boxes equal to boxes[r] are stuck to its right. Either remove boxes[r] with its k attachments now ((k+1)² + dp(l, r−1, 0)), or find an earlier box i of the same colour and first clear the stuff between them so they join: dp(l, i, k+1) + dp(i+1, r−1, 0).
Edge / failure case one colour → 9
All three at once: 9.
Why? flowers [1,3,1,1], 7 new flowers, target 6, full 12, partial 1: complete one garden (cost 3), raise the rest to 2 → 14.
💡 Key idea A garden with at least target flowers is complete (full points each); the rest score min flowers × partial. Cap every garden at target and sort. Try every number k of complete gardens, completing the k largest (cheapest). With the remaining flowers, binary search the highest value v < target that the other gardens can all be raised to, and score k·full + v·partial. Take the best k.
Edge / failure case second sample → 30
Complete three gardens and level the last.
Why? 'abca' → sorted 'aabc' already has s[0]≠s[3] and s[1]≠s[2] → 'aabc'; 'cccd' can't be fixed → '-1'.
💡 Key idea An anti-palindrome has s[i] ≠ s[n−1−i] for every i. Start from the sorted string (smallest). Walk the second half: if s[i] equals its mirror, swap it with the first later character that differs (the smallest bigger letter); if there is none the answer is '-1'.
Edge / failure case impossible → '-1'
Three c's cannot all avoid each other.
Why? 'aaabbbcc' has frequencies 3, 3, 2: lower the second 3 to 2, then the clashing 2 to 1 → 2 deletions.
💡 Key idea Count each letter's frequency. Process frequencies from largest to smallest, remembering the highest frequency still allowed: if a frequency is not below that cap, delete characters until it is (or until 0), counting the deletions.
Edge / failure case mixed letters → 2
Two deletions.
Why? source 'abc', target 'abcbc': 'abc' then 'bc' (a subsequence of 'abc') → 2.
💡 Key idea Each piece is a subsequence of source. Walk through the target with a pointer; scan source from the start, matching as many target characters as possible in one pass, then start a new pass. If a pass matches nothing, some target letter is missing from source: return −1.
Edge / failure case impossible → -1
'd' is not in the source.
Why? [2,1,4,3,5], k=10: subarrays with sum·length < 10 number 6.
💡 Key idea The score of a window is sum × length, which only grows as the window grows. For each right end move the left end forward until the score is below k; then all windows ending at right and starting between left and right are valid: add right − left + 1.
Edge / failure case all ones → 5
Only windows of length 1 and 2 fit.
Why? jobs [1,2,4,7,8] on 2 workers: {8,2,1} and {7,4} → max 11.
💡 Key idea Assign every job to one of k workers to minimise the heaviest worker's total. Backtrack: sort jobs largest first (fail early), try each worker, but skip a worker whose current load equals one already tried (symmetry) and skip assignments that already exceed the best answer found.
Edge / failure case one per worker → 3
One job each.
Why? boxes [1,2,2,3,4], rooms [3,4,1,2]: room capacities 3, 3, 1, 2 → 4 boxes fit.
💡 Key idea Boxes are pushed in from either end and a box stops at a room only if all rooms before it are tall enough. So room i can hold a box up to max(min of rooms from the left up to i, min of rooms from the right up to i). Sort capacities and boxes, then match greedily from the smallest.
Edge / failure case five rooms → 3
Boxes from both ends.
Why? boxes [4,3,4,1], rooms [5,3,3,4,1] → capacities 5,3,3,3,1 → 3 boxes fit.
💡 Key idea Boxes enter from the left only, so room i can hold a box no taller than the lowest room up to i (a prefix minimum). Sort the boxes and the capacities and match the smallest boxes to the smallest rooms that fit.
Edge / failure case left only → 3
Only 3 can pass the low room.
Why? ['a','banana','app','appl','ap','apply','apple'] → 'apple' (a, ap, app, appl, apple are all present).
💡 Key idea A buildable word has every prefix in the list. Sort the words (shorter and alphabetical first). Keep a set of buildable words: a word is buildable if its prefix without the last letter is buildable (or it has length 1). Track the longest, preferring the lexicographically smaller on ties — sorted order gives that for free.
Edge / failure case single chain → 'world'
Every prefix exists.
Why? [[0,1,0],[1,1,1],[0,1,0]], target 0: the four single zero cells are the only submatrices → 4.
💡 Key idea Choose a pair of rows (top, bottom) and collapse the columns between them into one array of column sums. The submatrices with those rows are now subarrays of this array, counted with a prefix-sum hash map (count earlier prefixes equal to current − target).
Edge / failure case negatives → 5
Five submatrices sum to 0.
Why? 'F?1:T?4:5' → F picks the right part 'T?4:5' → T picks 4 → '4'.
💡 Key idea A ternary expression is right-associative, so scan from the right and push characters on a stack. When the character on top of the stack is '?', the current character is a condition: pop '?', the 'true' value, ':' and the 'false' value, and push whichever the condition selects. The stack ends with the answer.
Edge / failure case nested → 'F'
Nested true branch.
Why? m=1, n=1: any single dot → 9 patterns; m=1, n=2 → 9 + 56 = 65.
💡 Key idea Count paths over the 3×3 keypad with length between m and n, never reusing a key. Moving between two keys that have a key exactly between them is allowed only if that middle key was already used (the 'skip' table). Use symmetry: patterns from corners are all equal, as are those from edges, so count from keys 1, 2 and 5 and multiply by 4, 4 and 1.
Edge / failure case up to length 2 → 65
9 + 56 = 65.
Why? x=3, target=19: 3*3 + 3*3 + 3/3 → 5 operators.
💡 Key idea Write target in base x. The digit at position k is built either from cur copies of x^k (cur·x^k) or from (x − cur) subtracted from the next higher power, and a carry decides which is cheaper. Keep two running costs: pos (no borrow) and neg (borrowed from the next digit) and update them digit by digit; each x^k costs k operators for k ≥ 2 (x^0 = x/x costs 2).
Edge / failure case x = 5 → 8
8 operators.
Why? 'cabaa' and 'bcaaa' → 'cbcabaaaaa'.
💡 Key idea To build the largest string, always take the first letter of the word whose remaining suffix is lexicographically larger (comparing whole suffixes, not just the first letters, breaks ties between equal letters correctly).
Edge / failure case equal starts → 'abdcabcabcaba'
Equal starts need whole-suffix compares.
Why? 'abcde' has five distinct letters: all on separate keys (8 keys), 1 push each → 5.
💡 Key idea Keys 2–9 give 8 first-position slots (1 push), then 8 second-position slots (2 pushes) and so on. Assign the most frequent letters to the cheapest slots: sort letter frequencies descending and letter number r (from 0) costs (r // 8 + 1) pushes per occurrence.
Edge / failure case repeats → 12
Three letters on separate keys.
Why? 'internal' vs 'interval': same start 'inter', so they keep their full spelling; 'face' → 'f2e'.
💡 Key idea An abbreviation is a prefix + count + last letter, used only if shorter than the word, and it must be unique. Only words with the same length and last letter can clash. Within such a group sort the words: the prefix needed for a word is one longer than its longest common prefix with either sorted neighbour.
Edge / failure case shared prefixes → ['abcd2g', 'abccefg', 'abcckkg']
Common prefixes force longer ones.
Why? grid [[1,0,0,0],[1,1,1,0]], hit (1,0): two bricks (the rest of the bottom row) lose their only support → 2.
💡 Key idea Deleting is hard, adding is easy: process the hits in reverse. First remove all hit bricks and union the remaining bricks, with a virtual 'roof' node connected to row 0. Then add the hits back in reverse order; when a brick is restored, the number of bricks attached to the roof grows by (new roof size − old roof size − 1), which is how many bricks that hit made fall.
Edge / failure case no falls → [0, 0]
Nothing falls.
Why? 7 nodes split into components of sizes 3, 2, 2 → pairs across components = 14.
💡 Key idea Two nodes are unreachable from each other when they are in different components. With component sizes s₁, s₂ …, the number of such pairs is the sum over components of s × (nodes not in earlier components). Find components with Union-Find.
Edge / failure case all connected → 0
One component.
Why? 'crcoakroak' mixes two frogs: one at 'c','o','a','k' while another starts → 2 frogs.
💡 Key idea Keep a count of frogs currently at each letter of 'croak'. A letter 'c' starts a frog (or reuses a finished one); any other letter moves a frog from the previous stage to this one — if none is waiting there the string is invalid. A 'k' finishes a frog. The answer is the maximum number of frogs croaking at the same time, or −1 if the string is invalid or some frog is left unfinished.
Edge / failure case one frog → 1
One frog croaks twice.
Why? [3,3,3,3,3,1,3] → groups [0,1,2], [5] and [3,4,6].
💡 Key idea Person i must be in a group of exactly groupSizes[i] people. Keep one open group per size; add each person to the open group of their size, and when it reaches that size close it and start a new one.
Edge / failure case mixed sizes → [[1], [2, 3, 4], [0, 5]]
Three groups.
Why? '9001 discuss.leetcode.com' counts 9001 for discuss.leetcode.com, leetcode.com and com.
💡 Key idea For each entry split the count and the domain. Every suffix after a dot (and the full domain) gets the count added in a dictionary. Format the results as 'count domain'.
Edge / failure case several domains → ['1 intel.mail.com', '5 org', '5 wiki.org', '50 yahoo.com', '900 google.mail.com', '901 mail.com', '951 com']
Counts add up on shared parents.
Why? hats [[3,4],[4,5],[5]]: person 0 takes 3, person 1 takes 4, person 2 takes 5 → the only way → 1.
💡 Key idea There are at most 10 people but up to 40 hats, so use a bitmask of people who already have a hat and process hats one by one. For each hat, for each mask, try giving that hat to any person who likes it and is not yet in the mask. Go through masks from high to low so a hat is used at most once.
Edge / failure case overlapping hats → 4
Four ways.
Why? The sample grid's three biggest distinct rhombus-border sums are 228, 216, 211.
💡 Key idea A rhombus is defined by a centre and a radius k (k = 0 is a single cell). Its border is the four diagonal edges. For every centre and every radius that stays inside the grid, add up the 4k border cells (the corners belong to two edges, so walk each edge excluding its far end) and collect distinct sums; return the three largest.
Edge / failure case single value → [7]
Only one distinct sum.
Why? [1,2,3,1,2,3,1,2], k=2: the window [2,3,1,2,3,1] has every value at most twice → 6.
💡 Key idea Slide a window and count each value. When adding the right element makes its count exceed k, move the left end forward until that count is back to k. Track the longest window.
Edge / failure case one value → 4
At most four 5s.
Why? Orders [[10,5,0],[15,2,1],[25,1,1],[30,4,0]]: after matching, 6 orders remain in the backlog.
💡 Key idea Keep a max-heap of buy orders and a min-heap of sell orders. A new buy order matches the cheapest sells priced at or below it; a new sell order matches the highest buys priced at or above it. Match amounts until one side is exhausted; leftovers go into the backlog heap. Answer = total remaining amount mod 1e9+7.
Edge / failure case big amounts → 1991
A big sell order absorbs the smaller buy orders.
Why? Four customers at (0,1), (1,0), (1,2), (2,1): the centre (1,1) gives total distance 4.
💡 Key idea The sum of Euclidean distances to the customers is a convex function of the centre (x, y). Convex functions can be minimised by ternary search: search x in the coordinate range, and for each x search y the same way. A hundred iterations give far more precision than needed; round the answer to 5 decimals.
Edge / failure case two points → 2.82843
Any point on the segment: 2.82843.
Why? regular [1,6,9,5], express [5,2,3,10], expressCost 8 → costs to stops 1…4: [1,7,14,19].
💡 Key idea Track two numbers while moving stop by stop: the cheapest cost to be at the stop on the regular route, and on the express route. Staying on a route adds that route's segment cost; switching to the express route costs expressCost extra, switching back to regular is free. The answer for each stop is the smaller of the two.
Edge / failure case second sample → [10, 15, 24]
Express pays off after the first stop.
Why? [1,1,3,4]: cast both 1s and the 4 → 6 (3 is too close to both 1 and 4).
💡 Key idea Casting a spell with damage p blocks any spell with damage p−2 … p+2, but spells with the same damage can all be cast. Group by value: taking value v earns v × count(v) and excludes the previous two smaller values. Over the sorted distinct values: best[i] = max(best[i−1], best[j] + v × count) where j counts the values at least 3 below v.
Edge / failure case repeated value → 13
Cast 1, 6, 6 = 13.
Why? prices [1,5,3] with a holding fee that grows with days: the best single trade buys on day 0 and sells on day 1.
💡 Key idea A trade buys on day i and sells on day j for prices[j] − prices[i] − costs[j−i]; after selling on day j the next buy is allowed from day j + cooldown + 1. Let best[d] be the best total profit using days up to d. Then best[j] = max(best[j−1], max over buy days i < j of best[i − cooldown − 1] + trade profit(i, j)) with best of a negative index = 0.
Edge / failure case fees → 0
Buy-sell pairs are limited by the fees.
Why? 2 dice with 6 faces, target 7 → 6 ways.
💡 Key idea ways[d][s] = number of ways to reach sum s with d dice = sum of ways[d−1][s−f] over faces f = 1…k. Build up the table die by die; answer ways[n][target] modulo 1e9+7.
Edge / failure case one way → 1
5 + 5 is the only way.
Why? n=2: from each of the 10 keys the knight has some moves; total 20 numbers.
💡 Key idea On a phone keypad a knight moves from each digit to a fixed list of digits (e.g. 1 → 6, 8). Let ways[d] be the number of numbers of the current length ending on digit d; for the next length each digit's ways are the sum over the digits that can jump to it. Repeat n − 1 times and add everything up modulo 1e9+7.
Edge / failure case large n → 136006598
Large n.
Why? arr [1,3,4,2], mat [[1,4],[2,3]]: after painting 1, 3, 4 the first row (1,4) is complete at index 2.
💡 Key idea Record where each number sits in the matrix. Paint numbers in the order of arr, counting how many cells of each row and each column are painted. The first index where some row or column reaches its full size is the answer.
Edge / failure case 3×3 → 3
Column 1 completes at index 3.
Why? [[1,2],[3,4]] → ranks [[1,2],[2,3]].
💡 Key idea The rank of a cell is one more than the largest rank among smaller cells in its row and column. Process distinct values from small to large. Cells with the same value that share a row or column must get the same rank, so union them (rows and columns as nodes). For each connected group the rank is 1 + the largest current rank in any of its rows or columns; then update the row/column maxima.
Edge / failure case all equal → [[1, 1], [1, 1]]
All equal → all rank 1.
Why? [1,1,1] → [1,2,3] costs 0 + 1 + 2 = 3.
💡 Key idea Walk left to right. If nums[i] is not larger than the previous (already adjusted) value, raise it to previous + 1 and add the difference to the count.
Edge / failure case mixed → 14
14 operations.
Why? 'My name is Haley' vs 'My Haley': 'My' matches in front and 'Haley' at the back; 'name is' is the inserted middle → true.
💡 Key idea Two sentences are similar if one can be made from the other by inserting a sentence in the middle (possibly at the ends). Split into words, count how many words match from the start and how many from the end; if the two counts together cover the shorter sentence it is similar.
Edge / failure case not similar → False
Different words.
Why? [1,3,1,2,2] has 3 distinct values; subarrays containing 1, 2 and 3 number 4.
💡 Key idea A subarray is complete if it has as many distinct values as the whole array. For each right end, shrink the window from the left while it is still complete; the number of valid starts is then left (all earlier starts are also complete). Add up.
Edge / failure case one value → 10
Every subarray is complete.
Why? 'ababbc', k=2: 'c' appears once, so split there → 'ababb' of length 5.
💡 Key idea Any letter with total count < k can never be in a valid substring, so split the string at every such letter and solve the pieces recursively. A piece in which all letters appear at least k times is itself the answer for that piece.
Edge / failure case split at b → 3
'aaa' is the best.
Why? [1,0,1,0,1] has three 1s; the best window of length 3 has one 0 → 1 swap.
💡 Key idea All 1s must end in a window whose length equals the total number of ones. Slide such a window across the array; the swaps needed equal the zeros inside it. Return the minimum.
Edge / failure case single one → 0
A single 1.
Why? alice has videos with 5 and 5 views (total 10), bob has one with 10 → both tie at 10; alice's best id is 'one' (smaller id).
💡 Key idea For each creator keep their total views and their best video (most views, smallest id on ties). The most popular creators are those with the maximum total; return each with their best video id.
Edge / failure case tie → [['alice', 'b']]
Tie on views: smaller id b.
Why? differences [1,-3,4], lower 1, upper 6: the first value can be 3 or 4 → 2 sequences.
💡 Key idea The hidden sequence is the first value x plus the running sum of differences. Track the lowest and highest running sums. All values stay within [lower, upper] when lower ≤ x + low and x + high ≤ upper, so the number of valid x is (upper − lower) − (high − low) + 1, or 0 if negative.
Edge / failure case wide range → 4
Four starting values.
Why? [2,3,7,5,10]: conversion values 4, 10, 24, 12→ (5 + max 7 = 12), 20; prefix scores 4, 10, 24, 36, 56.
💡 Key idea The conversion value of an element is itself plus the largest value seen so far (including itself). The score of a prefix is the sum of conversion values, so keep a running maximum and a running total.
Edge / failure case powers → [2, 4, 8, 16, 32, 64]
Doubling pattern.
Why? [2,6,4,8,10,9,15]: sorting positions 1…5 puts everything in order → 5.
💡 Key idea Sort a copy. The first and last positions where the arrays differ bound the subarray that must be sorted. Return the length between them (0 if equal).
Edge / failure case sorted → 0
Already sorted.
Why? [3,5,2,1,6,4] → [3,5,1,6,2,4] satisfies nums[0] ≤ nums[1] ≥ nums[2] ≤ nums[3] ≥ …
💡 Key idea For every index i ≥ 1: if i is odd we need nums[i−1] ≤ nums[i], if i is even we need nums[i−1] ≥ nums[i]. When the pair is out of order swap them; swapping never breaks the earlier pairs.
Edge / failure case duplicates → [6, 6, 5, 6, 3, 8]
Equal neighbours are fine.
Why? [6,0,8,2,1,5]: ramp from index 1 (value 0) to index 5 (value 5) has width 4.
💡 Key idea A ramp is i < j with nums[i] ≤ nums[j]. Candidate left ends are the positions of strictly new prefix minimums (a decreasing stack). Scan j from the right and pop every candidate i with nums[i] ≤ nums[j], recording j − i; the earliest valid i gives the widest ramp for that j.
Edge / failure case long ramp → 7
Width 7.
Why? [1,null,3,2,4,null,null,null,5]: 3 → 4 → 5 is a run of 3.
💡 Key idea Walk down from the root passing the run length ending at the parent. A child extends the run when its value is the parent's value + 1, otherwise a new run of length 1 starts. Track the maximum over all nodes.
Edge / failure case short run → 2
Run 2 → 3.
Why? n=7, cost [1,5,2,2,3,3,1]: raise 1→... total 6 increments equalise all root-to-leaf paths.
💡 Key idea The tree is perfect with nodes numbered like a heap (children of i are 2i and 2i+1, 1-indexed). Go bottom-up: at a node, the two child paths must be equal, so add the difference to the smaller one (count it as increments) and pass the larger path cost up by adding it to the node's cost.
Edge / failure case already equal → 0
Already equal.
Why? [1,2,3,null,4], distance 3: leaves 3 and 4 are 3 edges apart → 1 pair.
💡 Key idea For each node compute how many leaves lie at each depth below it in the left and right subtrees. A leaf pair whose lowest common ancestor is this node is good if depth_left + depth_right ≤ distance, so multiply the counts for every compatible pair of depths. Return the combined (depth+1) counts upwards.
Edge / failure case deeper tree → 1
One close pair.
Why? [1,2,3,4,5,null,6,7,null,null,null,null,8]: the deepest level holds 7 and 8 → 15.
💡 Key idea Do a level-order traversal and keep the sum of the level you just finished; the last level's sum is the answer.
Edge / failure case uneven depth → 19
Deepest leaves 9, 1, 4, 5.
Why? [1,3,null,null,2] has 3 and 1 swapped → fixed tree [3,1,null,null,2].
💡 Key idea An in-order traversal of a BST (Binary Search Tree) is increasing. Two swapped nodes show up as one or two places where the order goes down. The first violation's larger node and the last violation's smaller node are the swapped pair — swap their values.
Edge / failure case non-adjacent swap → [2, 1, 4, None, None, 3]
Swap 3 and 2.
Why? The 3×3 grid with land in the corners: the centre water cell is 2 steps from the nearest land → 2.
💡 Key idea Start a BFS (Breadth-First Search) from all land cells at once. Each wave moves one step into water; the number of waves needed to reach the last water cell is the largest distance to land. If the grid is all land or all water, return −1.
Edge / failure case corner land → 4
Opposite corner is 4 away.
Why? [100,-23,-23,404,100,23,23,23,3,404]: 0 → 4 → 3 → 9 takes 3 jumps.
💡 Key idea From index i you can step to i±1 or to any index with the same value. BFS (Breadth-First Search) from index 0. Group indices by value; the first time a value is used, jump to all its indices at once and clear that list so each value is expanded only once.
Edge / failure case single → 0
Already at the end.
Why? a=1, b=1, c=7: 'ccaccbcc' uses every letter without ever writing three equal letters in a row.
💡 Key idea Always append the letter with the most remaining copies, but if the last two letters are already that letter take the next most common one instead. Use a max-heap of (count, letter) and stop when no letter can be added.
Edge / failure case one big pile → 'aabaa'
aabaa
Why? speeds [2,10,3,1,5,8], efficiency [5,4,3,9,7,2], k=2: pick engineers 2 and 5 → (10+5)·4... best performance 60.
💡 Key idea Performance = (sum of speeds) × (minimum efficiency). Sort engineers by efficiency descending and treat each as the minimum efficiency of the team: everyone processed before has efficiency ≥ it. Keep a min-heap of the k largest speeds seen so far and their sum; the candidate is sum × current efficiency.
Edge / failure case three engineers → 56
Pick the fastest two efficient engineers.
Why? The 3×3 sample has one cell with 2 stones and one empty cell: moving a stone there costs the distance → total 3.
💡 Key idea There are exactly nine stones. List the cells with extra stones (one entry per extra stone) and the empty cells; both lists have the same length. Every extra stone must go to a distinct empty cell at cost = Manhattan distance, so try all assignments (permutations) and take the cheapest.
Edge / failure case stacked stones → 4
Four moves.
Why? [1,1,2,2,2]: sides {2}, {2}, {2}, {1,1} → every side is 2... total 8 = 4×2 → true.
💡 Key idea The total length must be divisible by 4. Sort sticks descending and try to place each into one of four sides without exceeding the target side length, skipping sides with the same current length (symmetry). Success if all sticks are placed.
Edge / failure case bad total → False
Total not divisible by 4.
Why? 'aaabc': change one 'a' to 'b' and insert a 'c' so every letter appears twice → 2.
💡 Key idea Pick the common frequency f (1 … n). Walk the letters a…z. A letter can end with f copies or with 0. Extra copies cost 1 each whether deleted or turned into the next letter, but turning them into the next letter can fill that letter's deficit for free later. Keep a small DP (Dynamic Programming) over the 'carry' of extra copies passed to the next letter (carry 0 or exactly what the next letter needs); a deficit costs one insertion per missing copy. Take the best over all f.
Edge / failure case one deletion → 1
Delete one 'a'.
Why? 'cdcd' → 'cccc' (two operations) is the cheapest, smallest good caption.
💡 Key idea A good caption has every letter in runs of at least 3. Each change costs the alphabet distance. Compute from the right h[i][c][k] = cheapest way to finish positions after i when position i holds letter c at the end of a run of length k (1, 2 or 3+). A run can be continued with the same letter, or — once it has length 3+ — switched to any other letter. The minimum starts at position 0; rebuild left to right choosing the smallest letter that keeps the optimal total (that makes the answer lexicographically smallest). Captions shorter than 3 are impossible.
Edge / failure case short caption → 'aaa'
Change the middle letter.
Why? 2 eggs, 6 floors: 3 moves are enough (and 2 are not) → 3.
💡 Key idea Flip the question: with m moves and k eggs, how many floors can we distinguish? f(m, k) = f(m−1, k−1) + f(m−1, k) + 1 (drop from a floor: if the egg breaks we continue with one egg fewer, otherwise with the same eggs above). Increase m until f(m, k) ≥ n.
Edge / failure case three eggs → 4
Four drops.
Why? 2 cups poured: the top cup holds 1, the overflow of 1 splits into two cups at 0.5 each → query (1,1) is 0.5.
💡 Key idea Pour into the top glass. Any amount above 1 overflows and splits equally into the two glasses below it. Simulate row by row up to the query row and return min(1, amount) for the queried glass.
Edge / failure case huge pour → 1
Full glass.
Why? stickers ['with','example','science'], target 'thehat' → 3 stickers.
💡 Key idea State = bitmask of target letters already covered. From a state take the first uncovered letter and try every sticker that contains it, covering as many remaining target letters as it can. dp[mask] = fewest stickers to reach the mask; the answer is dp[full] or −1.
Edge / failure case impossible → -1
Missing letters.
Why? [4,3,2,6]: replace [3,2] by 5 → [4,5,6] length 3.
💡 Key idea Replacing a subarray by its sum means splitting the array into blocks whose sums are non-decreasing; maximise the number of blocks. dp[i] is the best block count for the prefix i, with last[i] the smallest possible sum of the last block. A cut at j is allowed when pre[i] − pre[j] ≥ last[j], i.e. pre[j] + last[j] ≤ pre[i]. Keep candidates j in a deque ordered by pre[j] + last[j] so the best (latest) allowed j is found at the front.
Edge / failure case decreasing → 1
Merge everything.
Why? str1 'TFTF', str2 'ab' → 'ababa'.
💡 Key idea The word has length n + m − 1. Every 'T' position i forces word[i…i+m−1] = str2 (a conflict means impossible). Fill every unforced slot with 'a' (smallest). Then check each 'F' window: if it accidentally equals str2, change the rightmost unforced slot in that window to 'b' (the smallest change that breaks the match with the least lexicographic damage); if no slot is free the answer is empty.
Edge / failure case impossible → ''
Conflicting windows.
Why? nums [1,1,0,0,0,1,1,0,0,1], k=3, maxChanges=1 → pick the neighbouring ones for free/1 move and one created one for 2 moves → 3.
💡 Key idea Standing at index i: its own one is free, an adjacent one costs 1 move, a created one (set a nearby zero, then swap it in) costs 2 moves, and a one at distance d costs d moves. Case A: use the ones around the best index and changes for the rest: cost = (adjacent ones used) + 2 × (k − picked) if enough changes. Case B: use all maxChanges (2 moves each) and fetch k − maxChanges real ones from the best window of ones, whose cost is the sum of distances to the window's median. The answer is the cheaper case.
Edge / failure case no ones → 4
Two created ones cost 2 each.
Why? values [[8,5,2],[6,4,1],[9,7,3]]: buying all items in increasing order over 9 days spends 285.
💡 Key idea Each shop's items are sorted non-increasing; every day you may buy the rightmost (cheapest remaining) item of one shop, paying value × day. To spend as much as possible you want the large values to be bought late, so overall buy the items in globally increasing price order: sort all values ascending and multiply the i-th by (i+1).
Edge / failure case single shop → 110
2·1 + 4·2 + 6·3 + 8·4 + 10·5.
Why? costs [[10,20],[30,200],[400,50],[30,20]]: send the first two to A and the last two to B → 110.
💡 Key idea Half the people go to each city. Start by sending everyone to A; switching person i to B changes the cost by costB − costA. Sort by that difference and send the n people with the smallest difference (biggest saving) to B.
Edge / failure case six people → 1859
1859.
Why? Between 10 and 19 the primes are 11, 13, 17, 19; the closest pair is 11 and 13.
💡 Key idea List the primes in [left, right] with a sieve. The closest pair must be consecutive primes, so scan neighbours and keep the pair with the smallest gap (the earliest on ties). Return [−1, −1] if there are fewer than two primes.
Edge / failure case no pair → [-1, -1]
Only one prime (5).
Why? memory1=2, memory2=2: second 1 takes 1 from the first stick, second 2 takes 2 from the second → crash at second 3 with [1, 0].
💡 Key idea At second i the program needs i bits and takes them from the stick with more free memory (the first on ties). Keep subtracting until the next demand does not fit in either stick. The loop runs about √(memory) times.
Edge / failure case uneven sticks → [6, 0, 4]
Crashes at 6.
Why? digits {1,3,5,7}, n=100: 4 one-digit + 16 two-digit numbers = 20.
💡 Key idea Numbers shorter than N's length can use any digit at each place: Σ d^len. For numbers with the same length as N walk its digits left to right: for each position add (number of allowed digits smaller than N's digit) × d^(remaining positions); continue only if N's digit itself is allowed; if every digit is allowed, N itself counts +1.
Edge / failure case large n → 29523
Large n.
Why? (0,0), (1,1), (1,0), (0,1) form a unit square → true.
💡 Key idea Compute the six squared distances between the four points. In a square four of them are equal and positive (the sides) and the two largest are equal (the diagonals, twice the side squared). So sort them: the first four equal, the last two equal and bigger, and the smallest is non-zero.
Edge / failure case invalid → False
Repeated point.
Why? s 'abcxyz123' with words ['abc','123'] → '<b>abc</b>xyz<b>123</b>'.
💡 Key idea Mark every character covered by an occurrence of any word. Maximal runs of marked characters (which automatically merges overlapping and touching matches) are wrapped in <b>…</b>.
Edge / failure case overlapping → '<b>aaabbc</b>c'
Overlaps merge.
Why? n=13: order is 1, 10, 11, 12, 13, 2, 3 … so the 2nd is 10.
💡 Key idea Think of the numbers as a 10-ary trie. Start at prefix 1 with k−1 steps left. For the current prefix count how many numbers ≤ n lie in its subtree; if that count is ≤ the steps left, skip the entire subtree (move to prefix+1), otherwise go one level down (prefix × 10, one step used).
Edge / failure case n = 1 → 1
Only 1.
Why? Four friends paired (0,1) and (2,3) — friend 1 prefers 3 to 0 and 3 prefers 1 to 2 → both are unhappy → 2.
💡 Key idea Build rank[x][y] = how much x likes y. Friend x paired with y is unhappy if there is some u that x prefers over y, where u is paired with v and u also prefers x over v. Check every friend against all friends they prefer more than their partner.
Edge / failure case two friends → 0
Nobody is unhappy.
Why? 'Hello how are you Contestant', k=4 → 'Hello how are you'.
💡 Key idea Split on spaces, keep the first k words and join them again.
Edge / failure case k = all → 'chopper is not a tanuki'
Whole sentence.
Why? [9,12,5,10,14,3,10], pivot 10 → [9,5,3,10,10,12,14].
💡 Key idea Collect the numbers smaller than the pivot, equal to it and larger, each in original order, and concatenate.
Edge / failure case single pivot → [-3, 2, 4, 3]
Equal elements sit in the middle.
Why? 'abab' = 'ab' twice → true.
💡 Key idea A string is a repetition of a block exactly when it appears inside (s + s) with the first and last character removed.
Edge / failure case no pattern → False
Not a repetition.
Why? '234Adas' is valid: ≥ 3 chars, letters/digits, has a vowel (A) and a consonant (d).
💡 Key idea A valid word has at least 3 characters, consists only of letters and digits, and contains at least one vowel and one consonant (letters only).
Edge / failure case bad char → False
Contains '$'.
Why? [1,4,3,3,2]: longest run is 1,4 (2) or 4,3 (2) → 2.
💡 Key idea Walk through the array keeping the length of the current strictly increasing run and the current strictly decreasing run; reset the one that breaks. The answer is the longest run seen.
Edge / failure case all equal → 1
No strict step.
Why? 'USA' ✓, 'leetcode' ✓, 'Google' ✓, 'FlaG' ✗.
💡 Key idea The usage is right if the word is all uppercase, all lowercase, or only the first letter is uppercase — exactly what isupper, islower and istitle check.
Edge / failure case bad usage → False
Mixed capitals.
Why? [3,4,9,1,3,9,5], key 9, k=1 → indices 1–6.
💡 Key idea For each position j where nums[j] == key mark all i with |i − j| ≤ k. Collect the marked indices in increasing order.
Edge / failure case all keys → [0, 1, 2, 3, 4]
Every index is within 2.
Why? 'hello' → |h−e| + |e−l| + |l−l| + |l−o| = 13.
💡 Key idea Add up the absolute difference of the ASCII (American Standard Code for Information Interchange) codes of every two neighbouring characters.
Edge / failure case wrap → 50
25 + 25 = 50.
Why? ['mass','as','hero','superhero'] → 'as' is in 'mass' and 'hero' is in 'superhero'.
💡 Key idea For every word check whether it occurs inside any other word.
Edge / failure case inside → ['et', 'code']
'et' and 'code'.
Why? '6777133339' → '777' and '333': the largest is '777'.
💡 Key idea Check each window of three characters; if they are equal it is a candidate. Return the largest candidate (or an empty string).
Edge / failure case none → ''
No triple.
Why? [1,2,34,3,4,5,7,23,12] has 5, 7, 23 in a row → true.
💡 Key idea Walk through the array counting consecutive odd numbers; return true when the run reaches three.
Edge / failure case false → False
No.
Why? n=5 → [-4,-2,0,2,4].
💡 Key idea Use the values 2i − (n − 1) for i = 0 … n−1: they are distinct, symmetric around 0, and sum to zero.
Edge / failure case n = 1 → [0]
[0].
Why? [-4,-2,1,4,8] → 1; [2,-1,1] → 1.
💡 Key idea Pick the number with the smallest absolute value; on ties the larger value wins, so use (|x|, −x) as the sort key.
Edge / failure case tie → 1
Tie: larger wins.
Why? [3,4,5,2] → (5−1)(4−1) = 12.
💡 Key idea The product (nums[i]−1)(nums[j]−1) is largest for the two largest numbers.
Edge / failure case duplicates → 16
16.
Why? 'abcdefghij', k=3, fill 'x' → ['abc','def','ghi','jxx'].
💡 Key idea Cut the string into pieces of length k; pad the last piece with the fill character.
Edge / failure case exact fit → ['abc', 'def', 'ghi']
No padding needed.
Why? 'abbcccc': the typing could have been the word itself or one run shortened (b, c×3) → 5.
💡 Key idea Alice may have held a key too long at most once, so exactly one run could have lost extra letters. Count the original word plus, for each pair of equal neighbouring letters, one possibility.
Edge / failure case no repeats → 1
No repeated keys.
Why? [2,1,4] alternates even/odd → true; [4,3,1,6] has 3,1 both odd → false.
💡 Key idea An array is special if every two adjacent elements have different parity.
Edge / failure case not special → False
3 and 1 are both odd.
Why? sequence 'ababc', word 'ab' → 'abab' fits twice → 2.
💡 Key idea Find the largest k such that word repeated k times is a substring of the sequence. Keep multiplying the word and testing with `in`.
Edge / failure case absent → 0
Not present.
Why? 'a#b%*' → a, aa, aab, baa, ba.
💡 Key idea Keep the result in a list: a letter appends, '*' removes the last letter if any, '#' doubles the list, '%' reverses it.
Edge / failure case empty result → ''
Everything removed.
Why? n=31 → 3 × 1 = 3.
💡 Key idea The product of two digits is largest for the two largest digits of the number (the same digit may be used twice if it occurs twice). Sort the digits and multiply the last two.
Edge / failure case equal digits → 81
The two largest digits are the same digit twice.
Why? 'abc' → 26·1 + 25·2 + 24·3 = 148.
💡 Key idea The reverse position of a letter is 26 for 'a' down to 1 for 'z'. Multiply it by the 1-based index of the letter in the string and add everything.
Edge / failure case zaza → 160
'z' weighs 1, 'a' weighs 26.
Why? [1,2,3,4] (n=4): indices 1, 2, 4 divide 4 → 1 + 4 + 16 = 21.
💡 Key idea With 1-based indexing, element i is special if i divides n. Add the squares of those elements.
Edge / failure case n=6 → 63
n=6, indices 1,2,3,6 divide 6.
Why? ['--X','X++','X++'] → 1.
💡 Key idea Each operation contains either '++' (adds 1) or '--' (subtracts 1). Check the middle character: '+' adds, '-' subtracts.
Edge / failure case all plus → 3
Only increments.
Why? arr [3,0,1,1,9,7], a=7, b=2, c=3 → 4 good triplets.
💡 Key idea A triplet i<j<k is good if |arr[i]−arr[j]| ≤ a, |arr[j]−arr[k]| ≤ b and |arr[i]−arr[k]| ≤ c. With n ≤ 100 just test all triples.
Edge / failure case tight limits → 0
Tight limits: only equal neighbours.
Why? ['pay','attention','practice','attend'] with prefix 'at' → 2.
💡 Key idea Count the words that start with the prefix.
Edge / failure case no match → 0
No word starts with the prefix.
Why? [3,6,1,0] → 6 ≥ 2·3 → index 1.
💡 Key idea Find the largest and second largest values. The largest is dominant if it is at least twice the second largest; return its index, else −1.
Edge / failure case not dominant → -1
4 is not twice 3.
Why? [3,1,2,2,2,1,3], k=2 → 4 pairs.
💡 Key idea Count pairs i<j with nums[i] == nums[j] and i·j divisible by k. n ≤ 100, so test all pairs.
Edge / failure case no equal → 0
No equal values.
Why? 'dbca' with 2 friends → splits give 'd','bca' / 'db','ca' / 'dbc','a' → largest is 'dbc'.
💡 Key idea With f friends, a piece can have at most n − f + 1 letters. Any piece is a substring starting at some index, so try every start and take the longest allowed piece from it; the answer is the maximum of those. For one friend the whole word is the only split.
Edge / failure case single letters → 'g'
Four friends and four letters: the pieces are single letters.
Why? 'abcdefd', ch 'd' → 'dcbaefd'.
💡 Key idea Find the first index of ch. If there is none return the word; otherwise reverse the slice up to and including that index.
Edge / failure case mid prefix → 'zxyxxe'
The first z is at index 3.
Why? [1,2,4] → |1−2|, |2−4|, |4−1| → 3.
💡 Key idea In a circular array the last element is next to the first. Take the maximum of |nums[i] − nums[(i+1) % n]| over all i.
Edge / failure case negatives → 5
Negative numbers and the wrap-around pair.
Why? 'Leetcode daily streak achieved' → '#leetcodeDailyStreakAchieved'.
💡 Key idea Split on spaces. The first word is all lowercase, each later word has a capital first letter and lowercase rest. Drop every character that is not a letter, prefix '#', and keep at most 100 characters.
Edge / failure case extra spaces → '#helloWorld'
Extra spaces are ignored.
Why? 'PPALLP' → true; 'PPALLL' → false.
💡 Key idea The student is eligible when the string has fewer than two 'A's and does not contain three 'L's in a row.
Edge / failure case three lates → False
Three lates in a row.
Why? s 'cba', k=1 → rotations: 'cba','bac','acb' → 'acb'.
💡 Key idea With k = 1 you can only rotate the string, so try all rotations and take the smallest. With k ≥ 2 you can reorder arbitrarily (adjacent swaps are possible), so the answer is the sorted string.
Edge / failure case k = 3 → 'aaabc'
k ≥ 2: sort.
Why? [1,15,6,3]: element sum 25, digit sum 1+1+5+6+3 = 16 → 9.
💡 Key idea Compute the sum of the elements and the sum of all digits of all elements; return the absolute difference.
Edge / failure case single digits → 0
Single digits: no difference.
Why? [2,5,7,8,9,2,3,4,3,1], k=3 → [7,8,9] and [2,3,4] are adjacent increasing → true.
💡 Key idea Compute inc[i] = length of the strictly increasing run starting at i. Two adjacent increasing subarrays of length k start at a and a+k, so we need inc[a] ≥ k and inc[a+k] ≥ k.
Edge / failure case no pair → False
No pair of adjacent increasing runs of length 5.
Why? [1,0,0,0,1,0,0,1], k=2 → gaps of 3 → true.
💡 Key idea Walk the array remembering the index of the previous 1. A new 1 is too close if i − prev − 1 < k.
Edge / failure case too close → False
Only one zero between the 1s.
Why? [1,0,0] → '10' then '0' → true.
💡 Key idea A 1 starts a two-bit character, a 0 is a one-bit character. Walk from the start skipping 2 on a 1 and 1 on a 0; the last character is one-bit if we land exactly on the last index.
Edge / failure case ends in two-bit → False
The last 0 is part of a two-bit character.
Why? 'aaabbb' → true; 'abab' → false.
💡 Key idea All a's come before all b's exactly when the string never has a 'b' directly followed (at any distance) by an 'a'; checking for the substring 'ba' is enough.
Edge / failure case b before a → False
A 'b' is followed by an 'a'.
Why? s 'abcd', index 0 'a'→'eee', index 2 'cd'→'ffff' → 'eeebffff'.
💡 Key idea All replacements are checked against the original string. Order them by index, copy the untouched parts, and when s really has sources[i] at indices[i] write targets[i] instead and skip over the replaced characters.
Edge / failure case mismatch → 'eeecd'
The second source does not match.
Why? [2,1,1,2] → the path crosses itself → true.
💡 Key idea You move north, west, south, east, … by distance[i]. A crossing can only involve the previous 3, 4 or 5 segments: segment i crosses the one 3 back (i−3) when it is long enough and the previous one short; it touches segment i−4 when the two parallel segments overlap exactly; or it crosses segment i−5 after a spiral turn. Check these three patterns for every i.
Edge / failure case spiral out → False
An expanding spiral never crosses.
Why? [1,2,3,4,5], target 5, start 3 → index 4 → 1.
💡 Key idea Look at every index where nums[i] == target and take the smallest |i − start|.
Edge / failure case single → 0
One element.
Why? [2,1,3] → [2,2,3].
💡 Key idea Jump right to a smaller value or left to a larger one. A boundary between i and i+1 can be crossed in the right direction exactly when the largest value on the left is greater than the smallest value on the right. Scan from the right: ans[i] = ans[i+1] if prefix max of 0…i exceeds the suffix min of i+1…, otherwise the prefix max itself.
Edge / failure case all reach → [3, 3, 3]
Every index reaches the 3.
Why? 'Let's take LeetCode contest' → "s'teL ekat edoCteeL tsetnoc".
💡 Key idea Split on spaces, reverse every word and join with spaces again.
Edge / failure case two words → 'rM gniD'
Two words.
Why? 'abcd' weighs 5+3+12+14 = 34 → 34 % 26 = 8 → 'r'.
💡 Key idea The weight of a word is the sum of its letters' weights. Take it modulo 26 and map 0 → 'z', 1 → 'y', …, 25 → 'a' (the character with code 122 − r). Join the mapped letters.
Edge / failure case single letters → 'yyy'
Every letter weighs 1, so each word maps to 'y'.
Why? '0100' → turn the 1 into 0 and the whole 0000 into 1111 → 4.
💡 Key idea A trade turns a block of 1s (with zeros on both sides) into zeros, which merges the two neighbouring zero blocks into one block surrounded by 1s (the augmented ends), and then flips that block to 1s. The gain is the two neighbouring zero blocks' lengths. Return the current ones plus the largest such gain.
Edge / failure case one trade → 7
One block of ones between zero blocks.
Why? ' this is a sentence ' → 'this is a sentence'.
💡 Key idea Count the spaces and the words. Put spaces // (words − 1) between words and the remainder at the end (for a single word all spaces go to the end).
Edge / failure case single word → 'hello '
A single word: all spaces go to the end.
Why? [10,20,30,5,10,50] → 5+10+50 = 65.
💡 Key idea Keep the sum of the current strictly ascending run; reset to the current element when the order breaks. Track the largest sum seen.
Edge / failure case runs → 33
The best run is 12, 17.
Why? [1,10,11] → index 1 (digit sum 1) → 1.
💡 Key idea Compute the digit sum of each number and return the first index where it equals the index, or −1.
Edge / failure case none → -1
No digit sum matches its index.
Why? n=3, k=2 → [1,3,2] (differences 2, 1).
💡 Key idea Alternate between the smallest and largest unused values of 1…k+1: 1, k+1, 2, k, … This produces differences k, k−1, …, 1 (k distinct values). Then append k+2, …, n in increasing order, which only adds the difference 1.
Edge / failure case n = 5 → [1, 4, 2, 3, 5]
Four distinct differences needed.
Why? [1,0,2,3,0,4,5,0] → [1,0,0,2,3,0,0,4].
💡 Key idea Count how many zeros will be duplicated so we know how far elements shift. Walk from the end writing each element to its final position (and a second 0 for zeros), skipping writes beyond the array.
Edge / failure case no zeros → [1, 2, 3]
No zeros.
Why? 'IDID' → [0,4,1,3,2].
💡 Key idea Keep the smallest and largest unused numbers. For an 'I' place the smallest (so the next is larger), for a 'D' place the largest; the last position gets the remaining number.
Edge / failure case all I → [0, 1, 2, 3]
0, 1, 2, 3.
Why? '.L.R...LR..L..' → 'LL.RR.LLRRLL..'.
💡 Key idea For each upright domino the force comes from the nearest 'R' to its left and the nearest 'L' to its right. Compute the distance to the nearest pushing domino from each side (an 'L' blocks an earlier 'R' and vice versa); the nearer push wins, equal distances cancel.
Edge / failure case balanced → 'RR.L'
RR.L stays.
Why? [1,2,2,1,1,0] → merge → [1,4,0,2,0,0] → shift zeros → [1,4,2,0,0,0].
💡 Key idea For i from 0: if nums[i] == nums[i+1], double nums[i] and set nums[i+1] = 0. Afterwards move all zeros to the end keeping the order of non-zero numbers.
Edge / failure case zero start → [1, 0]
Zero first.
Why? '_L__R__R_' → 'L______RR': L moves left, R moves right: true.
💡 Key idea 'L' can only move left and 'R' only right, and pieces never pass each other. Skip blanks with two pointers; the next piece must be the same letter in both strings, and an L must not end up to the right of where it started, an R not to the left.
Edge / failure case crossing → False
The pieces would have to cross: impossible.
Why? nums1 [1,2,3], nums2 [2,4] → 2.
💡 Key idea Both arrays are sorted. Advance the pointer at the smaller value; when the two values are equal that is the smallest common value.
Edge / failure case two common → 2
Two common values: the smaller one.
Why? s 'isawsquirrelnearmysquirrelhouseohmy', a 'my', b 'squirrel', k 15 → [16, 33].
💡 Key idea Collect every start index of a and of b. An a-index i is beautiful if some b-index j has |i − j| ≤ k. With both lists sorted, binary search the closest b-index to i.
Edge / failure case same word → [0]
An a-index is its own neighbour.
Why? [4,2,5,7] → [4,5,2,7].
💡 Key idea Keep a pointer on the even indices and one on the odd indices. Advance the even pointer to an index holding an odd number and the odd pointer to an index holding an even number; swap them. Repeat until the even pointer runs out.
Edge / failure case already ok → [2, 3]
Already sorted.
Why? 'RXXLRXRXL' → 'XRLXXRRLX' is reachable → true.
💡 Key idea A swap 'XL' → 'LX' moves an L left, and 'RX' → 'XR' moves an R right. Ignoring X, both strings must show the same sequence of L and R; and each L may only be at the same or an earlier position in the result, each R at the same or a later one.
Edge / failure case different → False
Different letters.
Why? [1,4,3,7,4,5], k=3 → subarray [1..5], min 3, length 5 → 15.
💡 Key idea The subarray must contain index k. Start with the window [k, k] and expand one step at a time toward the side whose next value is larger (this keeps the minimum as large as possible). After each step score = window minimum × window length; keep the best.
Edge / failure case k = 0 → 20
Starts at the left end.
Why? [1,5,4,2,9,9,9], k=3: [5,4,2], [4,2,9] and [1,5,4] are distinct; best sum 15.
💡 Key idea Slide a window of size k, keeping a frequency map and the window sum. The window counts when it holds k distinct values (map size equals k).
Edge / failure case none → 0
No distinct window.
Why? nums [1,1,4,2,3], x=5 → remove 2 and 3 from the right (2 operations).
💡 Key idea Removing from both ends leaves a contiguous middle that sums to total − x. Find the longest such window with a sliding window (all numbers are positive); the answer is n − its length, or −1.
Edge / failure case impossible → -1
Impossible.
Why? [1,3,8,48,10]: 3, 8, 48 have pairwise AND 0 → length 3.
💡 Key idea A nice subarray has pairwise AND = 0, i.e. no bit appears in two elements. Keep the OR of the window; when the new number overlaps with it, remove elements from the left (XOR (exclusive OR) them out) until it does not.
Edge / failure case none longer → 1
1.
Why? s='011010', jumps of 2–3: 0 → 2 → 5 → reaches the end → true.
💡 Key idea Index j is reachable if s[j] == '0' and some reachable i has j − maxJump ≤ i ≤ j − minJump. Keep a running count of reachable indices inside that window (add the new left edge, remove the one that left).
Edge / failure case blocked → False
The last index cannot be reached.
Why? [1,2,3,4,3,2,5], k=3 → [3,4,-1,-1,-1].
💡 Key idea A window's power is its maximum if its elements are consecutive and ascending (each = previous + 1), otherwise −1. Keep the length of the current run of +1 steps; a window ending at i is good when the run is at least k.
Edge / failure case equal → [-1, -1]
No consecutive run.
Why? [5,4,2,4] has 8 continuous subarrays.
💡 Key idea A subarray is continuous when every two elements differ by at most 2, i.e. max − min ≤ 2. For each right end keep the leftmost start such that the window satisfies this (maintain the window's max and min with monotonic deques) and add the window length.
Edge / failure case increasing → 6
6.
Why? [1,1,2,2,3,4,2,3], k=6, x=2: keep the two most frequent values (ties: larger value) and sum their occurrences.
💡 Key idea For every window of size k count frequencies, sort the values by (frequency, value) descending, keep the top x values, and add up value × frequency over them.
Edge / failure case second sample → [11, 15, 15, 15, 12]
Another sample input.
Why? 'YazaAay' → 'aAa'.
💡 Key idea A string is nice if every letter that appears also appears in the other case. If a letter's counterpart is missing, no nice substring can contain it: split there and solve both sides recursively. Return the longest nice piece (earliest on ties).
Edge / failure case already nice → 'Bb'
The whole string is nice.
Why? 'aeioqq', k=1: the only window with all five vowels is 'aeio' + 'q', but it needs exactly one consonant, and no vowel set completes within one; the answer is 0.
💡 Key idea Count the substrings with all five vowels and at least k consonants, then subtract those with at least k+1. For a fixed right end the valid starts form a prefix of positions, so a sliding window (move left while the window still satisfies the 'at least' condition) gives the count in O(n).
Edge / failure case k = 2 → 3
Two consonants, all vowels.
Why? eventTime 5, k=1, meetings [1,2],[3,5] → move [1,2] to [2,3] → free time 2.
💡 Key idea Free time sits in the n+1 gaps between meetings (including before the first and after the last). Moving k meetings merges k+1 consecutive gaps into one. So the answer is the largest sum of k+1 consecutive gaps.
Edge / failure case k = 1 → 6
Meetings at the start and end of the event.
Why? [4,2,4,5,6] → best window 2,4,5,6 → 17.
💡 Key idea Keep a window with no repeated values and its running sum. When the new value is already inside, shrink from the left until it is gone. Track the best sum.
Edge / failure case repeats → 8
Repeated values force the window to restart.
Why? '00011' → the dominant substrings (ones ≥ zeros²) number 5.
💡 Key idea A substring is dominant when ones ≥ zeros², so it has at most √n zeros. For each start i, look at the first zero, second zero and so on (at most √n of them). With exactly z zeros the end lies between the z-th zero and just before the next zero, and the length must be at least z² + z (z zeros plus z² ones). Count those ends by arithmetic. z = 0 counts the all-ones substrings.
Edge / failure case mixed → 16
Several dominant substrings.
Why? 'aabaaaacaabc', k=2 → take 8 from the ends.
💡 Key idea Taking from both ends leaves a contiguous middle window untouched. The remaining characters (outside the window) must contain at least k of each of a, b, c. So find the longest window whose removal still leaves ≥ k of each letter: slide it, shrinking from the left when some letter drops below k. Answer = n − longest window (−1 if the total counts are below k).
Edge / failure case missing letters → -1
Not all three letters are present: −1.
Why? [1,0,1,1,0] → flip the first 0: 1,1,1,1 → 4.
💡 Key idea Keep a window containing at most one zero. Move the right end; when a second zero appears, move the left end past the first zero. The longest window is the answer.
Edge / failure case flip middle → 4
Flip the middle zero.
Why? [9,4,1,7], k=2 → sorted 1,4,7,9 → 4 − 1... best window (7,9)? → 2.
💡 Key idea After sorting, the best k scores are consecutive. Slide a window of size k and take the smallest difference between its last and first element.
Edge / failure case one score → 0
A single score.
Why? 'TTFF', k=2 → change both F to T → 4.
💡 Key idea Make a run of the same answer by flipping at most k others. Slide a window that contains at most k 'T's (to turn into F) and separately at most k 'F's; the longest window over both is the answer.
Edge / failure case k = 1 → 3
Flip one letter.
Why? 'abcc': removing one 'c' leaves a, b, c once each → true.
💡 Key idea For each distinct letter remove one occurrence and check whether all remaining letters have the same count.
Edge / failure case false → False
Removing any letter breaks it.
Why? [1,2,3,1,1,3] → three 1s give 3 pairs, two 3s give 1 → 4.
💡 Key idea A value that appears c times forms c(c−1)/2 good pairs. Add them up.
Edge / failure case all equal → 6
Six pairs.
Why? [10,2,5,3]: 5 and 10 → true.
💡 Key idea For each number check whether its double or (when even) its half has been seen, then record it.
Edge / failure case no pair → False
No pair.
Why? 'abacbc' → a,b,c each 2 times → true.
💡 Key idea Count the letters and check that the set of counts has exactly one value.
Edge / failure case unequal → False
3 versus 2.
Why? [1,2,2,3,1,4]: 1 and 2 both appear twice → 4 elements.
💡 Key idea Count each value; the answer is (max frequency) × (how many values have that frequency).
Edge / failure case all unique → 5
All appear once.
Why? [8,2,3,4,6], k=2: 2, 4, 6, 8 are present; 10 is missing → 10.
💡 Key idea Put nums in a set and test k, 2k, 3k … in order; the first multiple not present is the answer.
Edge / failure case first multiple → 5
5 is missing.
Why? ['bella','label','roller'] share e, l, l → ['e','l','l'].
💡 Key idea Intersect the Counters of all words (minimum count per letter) and expand the result.
Edge / failure case second sample → ['c', 'o']
c and o.
Why? [2,3,4,6]: 2·6 = 3·4 = 12 → 8 tuples.
💡 Key idea Count how many pairs (a, b) give each product. A product that arises from c pairs gives c(c−1)/2 ways to choose two pairs, and each choice yields 8 tuples (orderings).
Edge / failure case second sample → 16
16.
Why? [1,1,2,2,3,3]: 3 kinds, may eat 3 candies → 3.
💡 Key idea Alice can eat n/2 candies. She gets the most types by eating different ones: min(number of distinct types, n/2).
Edge / failure case limited by n/2 → 2
2.
Why? [0,1,2,2,4,4,1] → 2 and 4 both appear twice → smaller is 2.
💡 Key idea Count only the even numbers and pick the one with the highest count (smallest value on ties); return −1 if there is no even number.
Edge / failure case none → -1
No even.
Why? 'KiTe' matches 'kite' case-insensitively and 'keti' matches 'KiTe' when vowels are ignored.
💡 Key idea Answer each query by priority: exact match; else the first word equal ignoring case; else the first word equal after lowercasing and replacing every vowel by '*'. Build the three tables once, keeping the first word for each key.
Edge / failure case case only → ['yellow']
Case-insensitive match.
Why? [6,3,6]: i=0, j=1, k=2 with 6 = 2·3 on both sides → 1 triplet.
💡 Key idea A special triplet has i<j<k with nums[i] = nums[k] = 2·nums[j]. For every middle j multiply the number of earlier elements equal to 2·nums[j] by the number of later ones. Keep a counter of the left part and a counter of the right part while sweeping. Modulo 1e9+7.
Edge / failure case second sample → 2
Two triplets.
Why? [3,9,2,1,7], k=3: 7 appears in exactly one window of size 3 and is the largest such value → 7.
💡 Key idea For each window of size k add 1 to the counter of every distinct value in it. Values whose counter is exactly 1 are almost missing; return the largest or −1.
Edge / failure case k = 4 → 3
3.
Why? Alice [1,1], Bob [2,2]: swap 1 for 2 so both have 3 → [1,2].
💡 Key idea If Alice gives x and takes y then sumA − x + y = sumB − y + x, so y = x + (sumB − sumA) / 2. Put Bob's boxes in a set and look for the first x in Alice's list with x + delta in the set.
Edge / failure case second sample → [1, 2]
[1, 2].
Why? limit 4, queries [[1,4],[2,5],[1,3],[3,4]] → [1,2,2,3].
💡 Key idea Keep a dictionary ball → colour and a counter of how many balls have each colour. For each query remove the ball's old colour (decrease its count and drop the colour at zero), set the new colour, and report the number of colours with a positive count.
Edge / failure case second sample → [1, 2, 2, 3, 4]
[1,2,2,3,4].
Why? [1,2,3,4,2,3,3,5,7]: remove the first 6 elements (2 operations) to leave the distinct suffix [3,5,7].
💡 Key idea Each operation removes up to 3 elements from the front. The remaining suffix must have distinct elements. Find the longest distinct suffix by scanning from the right until a repeated value; if the first bad index is p (0-based), you need ceil((p + 1) / 3) operations.
Edge / failure case second sample → 2
2.
Why? n=13: digit sums group {1,10},{2,11},{3,12},{4,13},{5},… → four groups of size 2.
💡 Key idea Group the numbers 1…n by the sum of their digits and count how many groups have the largest size.
Edge / failure case tiny → 2
2.
Why? allowed 'ab', words ['ad','bd','aaab','baa','badab'] → 'aaab' and 'baa' → 2.
💡 Key idea A word is consistent when all its letters are in allowed. Convert allowed to a set and test each word.
Edge / failure case all consistent → 7
7.
Why? 'abbac' → 'abba' has a and b twice each → 4.
💡 Key idea A substring is balanced when all distinct letters in it occur equally often. For each start extend to the right keeping a Counter; the substring is balanced when the set of counts has size 1. Keep the longest.
Edge / failure case mixed letters → 4
Another sample input.
Why? m=4, n=3, hFences [2,3], vFences [2]: a 2×2 square is possible → 4.
💡 Key idea After removing fences you can pick any two horizontal fences (including the borders 1 and m) and any two vertical ones. A square needs equal distances, so compute all pairwise distances of the horizontal lines and of the vertical lines, intersect the two sets, and square the largest common distance. Modulo 1e9+7; −1 if none.
Edge / failure case impossible → -1
No square.
Why? [1,4,2,5] → 3 is missing.
💡 Key idea The range is from the smallest to the largest element of nums; return the integers in that range that are not in the array (ascending).
Edge / failure case consecutive → []
Nothing missing.
Why? [1,2,3,3] → 3.
💡 Key idea The array has n+1 distinct values and one of them appears n times, every other once. The first value you see twice is the repeated one.
Edge / failure case second sample → 5
Another sample input.
Why? 'abbac' → 'abba' (a and b twice each) → 4.
💡 Key idea A balanced substring has 1, 2 or 3 distinct letters, all with equal counts. One letter: the longest run. Two letters (x,y): split the string at the third letter and find the longest piece where count(x) − count(y) returns to the same prefix value (hash map of first occurrence). Three letters: prefix pairs (a − b, b − c) repeating. Take the maximum.
Edge / failure case three letters → 3
Another sample input.
Why? Points (0,0), (1,0), (2,0): from (1,0) the other two are equidistant → 2 boomerangs.
💡 Key idea A boomerang is (i, j, k) with dist(i, j) = dist(i, k). For each point i count the other points by squared distance; for a distance with c points there are c(c−1) ordered pairs (j, k).
Edge / failure case single → 0
A single point.
Why? secret 1807, guess 7810: one bull (8) and three cows (1, 7, 0) → '1A3B'.
💡 Key idea Bulls are positions with the same digit. For the remaining digits count how many of each digit occur in secret and guess; the cows are the sum over digits of the smaller count.
Edge / failure case repeats → '1A1B'
Another sample input.
Why? [5,4,1,2,2]: the subset [2,4,2] has the pattern x, x², x → 3.
💡 Key idea A valid subset looks like x, x², x⁴, …, x^k, …, x⁴, x², x. For each value x ≠ 1 follow the chain x → x² → x⁴ … while at least two copies exist (each adds 2 elements); at the end add 1 if a single copy of the next power exists, otherwise drop the last pair's top (−1). Value 1 is special because 1² = 1: use the largest odd count of 1s.
Edge / failure case no chain → 1
Another sample input.
Why? [1,2,3,2,5]: the sequential prefix 1,2,3 sums to 6; 6 is missing → 6.
💡 Key idea A sequential prefix has each element equal to the previous plus 1. Take the longest one from the start and its sum s; the answer is the smallest integer ≥ s that is not in nums.
Edge / failure case sum present → 15
Prefix 3,4,5 sums to 12 which is present; search upwards to 15.
Why? nums1 [4,3,2,3,1], nums2 [2,2,5,2,3,6] → [3, 4].
💡 Key idea answer1 is the number of indices in nums1 whose value occurs in nums2; answer2 likewise for nums2 in nums1. Use sets for membership.
Edge / failure case nothing shared → [0, 0]
No value is shared.
Why? words2 ['e','o'] needs one 'e' and one 'o' → 'facebook', 'google', 'leetcode' are universal.
💡 Key idea A word is universal if it contains every word of words2 as a subset (with multiplicity). Combine words2 into a single table: for each letter the maximum count needed by any word. Then check each word of words1 against the table.
Edge / failure case two letters → ['apple', 'google', 'leetcode']
Needs an l and an e.
Why? [3,2,3,2,2,2] → 3 appears twice, 2 four times → true.
💡 Key idea The array can be split into pairs of equal numbers exactly when every value occurs an even number of times.
Edge / failure case all different → False
All different: impossible.
Why? [[1,2],[2,1],[3,4],[5,6]] → [1,2] and [2,1] are equivalent → 1.
💡 Key idea Two dominoes are equivalent when one is a rotation of the other. Normalise each to (min, max) and count; a group of c equal dominoes gives c·(c−1)/2 pairs.
Edge / failure case three equal → 3
Three equal dominoes make 3 pairs.
Why? [3,1,3,2,4,3]: even positions hold 3,3,4 and odd ones 1,2,3; keeping 3 and 1 changes 3 elements → 3.
💡 Key idea Alternating means all even positions share one value a, all odd positions share another value b ≠ a. For each parity find the most and second most frequent value. If the two best differ take both; if they coincide take the best of the pair (best + second of the other parity). The cost is n minus the kept count.
Edge / failure case same value → 2
The same value dominates both parities, so one side must change.
Why? 2 languages, 3 users: teach language 1 to user 2 → 1.
💡 Key idea Find the friendships whose two people share no language. Only the people in those pairs need teaching. Pick one language to teach to all of them: the best choice is the one already known by the most of these people; the answer is their count minus that maximum.
Edge / failure case four people → 2
Two people have to be taught one language.
Why? [4,1,3,3]: 6 pairs in total, 1 good pair (indices 1 and 3) → 5 bad pairs.
💡 Key idea A pair i<j is good when j − i == nums[j] − nums[i], i.e. nums[i] − i == nums[j] − j. Count good pairs by grouping equal nums[i] − i values, and subtract from n(n−1)/2.
Edge / failure case all good → 0
Every pair is good.
Why? [-1,2,-3,3] → 3 (and −3 both exist) → 3.
💡 Key idea Put all numbers in a set. For each positive number whose negative is also in the set keep the maximum; return −1 if there is none.
Edge / failure case no match → -1
No number has its negative.
Why? 'aaabc' → 'abc' → 3.
💡 Key idea Repeatedly deleting the nearest equal characters around a letter leaves one copy of each distinct letter, so the answer is the number of distinct characters.
Edge / failure case cbbd → 3
Duplicate b is removed.
Why? [1,2,3,4,5,10,6,7,8,9], k=5 → true.
💡 Key idea Pairs add up to a multiple of k when remainders r and k − r match up. Count the remainders: the count of remainder r must equal the count of k − r; remainder 0 (and k/2 for even k) must appear an even number of times.
Edge / failure case k = 7 → True
Remainders pair up to 7.
Why? 'nlaebolko' → 1 balloon.
💡 Key idea 'balloon' needs b, a, n once and l, o twice. Count the letters; the number of words is the minimum of count[b], count[a], count[n], count[l] // 2, count[o] // 2.
Edge / failure case two → 2
Two balloons.
Why? ['coffee','donuts','time','toffee'] → 6 valid names.
💡 Key idea Swapping the first letters of two ideas gives a valid name when both new words are not in the original list. Group the suffixes by first letter. For two letters a and b, let c = number of suffixes they share; the valid pairs are (|A| − c)·(|B| − c), counted twice for the two orders. Sum over all letter pairs.
Edge / failure case no valid pair → 0
Swapping gives the same words.
Why? 'Bob hit a ball, the hit BALL flew far after it was hit.', banned ['hit'] → 'ball'.
💡 Key idea Lowercase the paragraph, replace punctuation by spaces, split into words, count those not in the banned set, and return the most frequent.
Edge / failure case single → 'a'
A single word with punctuation.
Why? [[4,8],[3,6],[10,20],[15,30]] → all have ratio 1:2 → 6 pairs.
💡 Key idea Two rectangles are interchangeable when width/height is the same. Reduce each (w, h) by their gcd to get a canonical ratio and count; a group of c rectangles gives c(c−1)/2 pairs.
Edge / failure case no pairs → 0
Different ratios.
Why? [1,2,1] → distinct counts 1,1,1,2,2,2 → 1+1+1+4+4+4 = 15.
💡 Key idea For every start index extend the end one element at a time while keeping a set of the values; after each extension add (size of the set)² to the total.
Edge / failure case equal → 3
Equal elements.
Why? nums [1,0,1], query [0,2] can reduce every index by 1 → all zero → true.
💡 Key idea Each query lets you subtract 1 (or nothing) from every index in its range. So index i can be reduced at most as many times as there are queries covering it. Count the coverage with a difference array and check coverage[i] ≥ nums[i] for all i.
Edge / failure case not enough → False
Index 3 can only be reduced once.
Why? [10,4,8,3] → [15,1,11,22].
💡 Key idea Keep a running left sum; the right sum is total − left − nums[i]. The answer at i is their absolute difference.
Edge / failure case single → [0]
0.
Why? [1,2], k=1 → the whole array (length 2 divisible by 1) sums to 3.
💡 Key idea A subarray (i, j] has length divisible by k exactly when i ≡ j (mod k). Keep, for each remainder, the smallest prefix sum seen so far; at each j the best subarray ending there is prefix[j] − min prefix with the same remainder.
Edge / failure case negatives → -10
-10.
Why? [1,-3,2,3,-4]: best subarray [2,3] = 5 → 5.
💡 Key idea A subarray sum is prefix[j] − prefix[i]. The largest absolute value is therefore (max prefix − min prefix), including the empty prefix 0.
Edge / failure case negative → 8
8.
Why? [12,6,1,2,7]: (12 − 1) · 7 = 77.
💡 Key idea Maximise (nums[i] − nums[j]) · nums[k] for i<j<k. Scan k from left to right keeping the maximum prefix value and the maximum difference (max prefix − current) seen so far; the candidate is best_diff × nums[k]. The answer is at least 0.
Edge / failure case second sample → 133
133.
Why? [1,0,2,0,3]: start at index 3 going left, or index 1 going right → 2 valid selections.
💡 Key idea The process bounces between the two sides, decrementing numbers, and ends with all zeros only when the left sum and right sum of the start (a zero) are equal (2 directions work) or differ by exactly 1 (one direction works).
Edge / failure case no valid → 0
0.
Why? [2,3,-1,8,4]: index 3 has left sum 4 and right sum 4 → 3.
💡 Key idea Keep the total and a running left sum; index i is the middle if left == total − left − nums[i].
Edge / failure case single → 0
Single element.
Why? [1,3,1,1,2] → arr[0] = |0−2| + |0−3| = 5, arr[2] = 2 + 1 = 3, … → [5,0,3,4,0].
💡 Key idea Group the indices of equal values. For the sorted positions p of one value, the distance sum for p[j] is (p[j]·j − sum of earlier positions) + (sum of later positions − p[j]·(count − j − 1)). Prefix sums of the positions give this in O(1) per index.
Edge / failure case all different → [0, 0, 0]
All values are different so every sum is 0.
Why? [3,1,4,2], p=6: remove [4] → remaining sum 6 → 1.
💡 Key idea Let r = total % p. We need to remove a subarray whose sum has remainder r, as short as possible (but not the whole array). Walk prefix remainders and store the latest index of each; at prefix remainder cur look for the earlier prefix with remainder (cur − r) mod p.
Edge / failure case remove suffix → 2
Remove the last two elements.
Why? [4,3,1,6], query [2,3] → 1 and 6 have different parity → true.
💡 Key idea A subarray is special if no two neighbours share the same parity. Prefix-sum the positions i where nums[i] and nums[i−1] have the same parity; a query [l, r] is true when there is no such position in (l, r].
Edge / failure case single element → [True]
A one-element subarray is special.
Why? 'abc' with shifts [3,5,9] → letter 0 shifts 17, letter 1 shifts 14, letter 2 shifts 9 → 'rpl'.
💡 Key idea Shifts[i] applies to the first i+1 letters, so letter j moves by the sum of shifts[j:]. Compute suffix sums (mod 26) from the right.
Edge / failure case aaa → 'gfd'
Shifts accumulate from the right.
Why? [3,2,4], modulo 2, k 1: the subarrays with an odd number of odd-remainder elements.
💡 Key idea Mark an element 1 if nums[i] % modulo == k. A subarray is interesting if its number of marked elements c satisfies c % modulo == k. With prefix counts p, we need p[r] − p[l] ≡ k (mod modulo), i.e. p[l] ≡ p[r] − k. Keep a Counter of earlier prefix remainders.
Edge / failure case modulo 3 → 2
Count subarrays with a multiple of 3 marked elements.
Why? '1122211', k=3: the window '11222' has 2 three times and 1 twice → 3 − 2 = 1.
💡 Key idea The digits are 0–4, so try every ordered pair (a, b). With prefix counts ca, cb, a window (l, r] needs ca odd, cb even and non-zero, and length ≥ k. Keep the minimum of ca[l] − cb[l] for each parity pair (ca%2, cb%2) over left ends that are far enough (r − l ≥ k) and leave at least two b's; the best window at r pairs with the state that flips ca's parity.
Edge / failure case impossible → -1
No window has an odd and a non-zero even frequency.
Why? [7,4,3,9,1,8,5,2,6], k=3 → [-1,-1,-1,5,4,4,-1,-1,-1].
💡 Key idea For an index i with k elements on each side the average is the sum of nums[i−k…i+k] divided by 2k+1 (integer division). Use prefix sums; indices without full radius give −1.
Edge / failure case radius 0 → [100000]
Radius 0: each element is its own average.
Why? [[1,2],[3,4]] → each cell = product of all others mod 12345 → [[24,12],[8,6]].
💡 Key idea Flatten the grid in row-major order. The product of all other cells is (product of everything before) × (product of everything after), modulo 12345 (not prime, so no division). Compute running prefix and suffix products.
Edge / failure case multiple of 12345 → [[2], [0], [0]]
A multiple of the modulus makes other cells zero.
Why? [[1,4],[2,3]] → cut between the rows: 5 and 5 → true.
💡 Key idea Compute the row sums and the column sums. A horizontal cut after row r splits the grid into two halves of sums prefix(r) and total − prefix(r); equal when prefix(r) · 2 == total. Same for vertical cuts with the column sums.
Edge / failure case no split → False
No equal split.
Why? [1,2,2,3], target 2 → 5 subarrays.
💡 Key idea Map each element to +1 if it equals target and −1 otherwise. A subarray has target as majority exactly when its sum is positive, i.e. prefix[j+1] − prefix[i] > 0. With n ≤ 1000, compare all pairs of prefix sums.
Edge / failure case all → 10
Every subarray.
Why? s '10203004', query [0,7] → x = 1234, digit sum 10 → 12340.
💡 Key idea For each prefix keep: the number formed by its non-zero digits mod p, their digit sum, and how many non-zero digits there are. For a range [l, r] the number x is (P[r+1] − P[l] · 10^(c)) where c is the count of non-zero digits inside the range. Multiply by the digit sum difference, modulo 1e9+7.
Edge / failure case all zeros → [0]
No non-zero digits: the answer is 0.
Why? '3242415' → '24241' can be rearranged into a palindrome → 5.
💡 Key idea A substring can be rearranged into a palindrome if at most one digit occurs an odd number of times. Keep the parity mask of the prefix (bit d flips when digit d appears) and the earliest index of each mask. A substring ending here is awesome if an earlier prefix has the same mask or a mask differing in exactly one bit.
Edge / failure case no repeats → 1
Only single digits are palindromes.
Why? [5,0,1,4], k=3 → index 3: max 5, min 4 → 1 ≤ 3 → 3.
💡 Key idea The instability of index i is max(nums[0..i]) − min(nums[i..]). Precompute the suffix minimum, sweep with a running prefix maximum, and return the first index with instability ≤ k.
Edge / failure case none → -1
No index is stable.
Why? [1,2,4,3], limit 4 → make every pair sum to 5 → 1 move.
💡 Key idea The pairs (a, b) = (nums[i], nums[n−1−i]) must all sum to one target T. For a pair, T = a + b costs 0, T in [min+1, max+limit] costs 1, otherwise 2. Record these ranges for every pair with a difference array over T ∈ [2, 2·limit] and take the minimum total.
Edge / failure case already → 2
Two replacements are needed.
Why? Range 12–15, k=2: powers 9, 10, 17, 9 → sorted 12, 13, 15, 14 … the 2nd is 13.
💡 Key idea The power of x is the number of Collatz steps (x even → x/2, odd → 3x+1) to reach 1. Compute it with memoisation, sort the numbers in [lo, hi] by (power, value) and return the k-th.
Edge / failure case second sample → 7
Sorted order 8, 10, 11, 7, 9: the 4th is 7.
Why? [8,1,2,2,3] → [4,0,1,1,3].
💡 Key idea For each value the count of smaller numbers is the index of its first occurrence in the sorted array.
Edge / failure case all equal → [0, 0, 0, 0]
All equal.
Why? [1,4,3,2] sorted [1,2,3,4]: pairs (1,2),(3,4) → 1 + 3 = 4.
💡 Key idea To maximise the sum of the minimums of the pairs, pair neighbours in sorted order; the minimum of each pair is the element at an even position.
Edge / failure case duplicates → 9
9.
Why? [1,2,3,12]: split [1],[2],[3,12] → 1 + 2 + 3 = 6.
💡 Key idea The cost of a subarray is its first element. Three subarrays always include nums[0] as a first element; the other two first elements can be any two later elements, so take the two smallest of nums[1:].
Edge / failure case small tail → 12
12.
Why? [5,4,3,2,1] → ['Gold Medal','Silver Medal','Bronze Medal','4','5'].
💡 Key idea Sort the scores in descending order and give the first three medals and the rest their place number. Map every score back to its label.
Edge / failure case unordered → ['Gold Medal', '5', 'Bronze Medal', 'Silver Medal', '4']
Medals for 10, 9, 8.
Why? [3,5]: exactly 2 numbers are ≥ 2 → x = 2.
💡 Key idea Sort descending. If the i-th number (0-based) is ≥ i+1 and the next one is < i+1, then exactly i+1 numbers are ≥ i+1. Check each candidate x directly: count the numbers ≥ x for x = 1…n.
Edge / failure case no x → -1
-1.
Why? [2,1,3,4,5,2]: take 1 (marks its neighbours), then the last 2, then 4 → 1 + 2 + 4 = 7.
💡 Key idea Sort indices by (value, index). Take the smallest unmarked element, add its value to the score and mark it together with its two neighbours. Continue until all are marked.
Edge / failure case second sample → 5
5.
Why? [5,4,2,3] → sorted [2,3,4,5] → arr [3,2,5,4].
💡 Key idea Alice removes the smallest, Bob the next smallest, but Bob appends first. After sorting, swap each neighbouring pair.
Edge / failure case two numbers → [5, 2]
[5, 2].
Why? [1,3,4,8,7,9,3,5,1], k=2 → [[1,1,3],[3,4,5],[7,8,9]].
💡 Key idea Sort the array and cut it into consecutive groups of three; each group must have max − min ≤ k, otherwise no valid division exists (return []).
Edge / failure case impossible → []
No valid division.
Why? arr1 [2,3,1,3,2,4,6,7,9,2,19], arr2 [2,1,4,3,9,6] → [2,2,2,1,4,3,3,9,6,7,19].
💡 Key idea Elements in arr2 come first in arr2's order; the rest follow in ascending order. Use the key (index in arr2 if present else a large number, value).
Edge / failure case leftovers → [22, 28, 8, 6, 17, 44]
Leftovers 44 and 17 go last, ascending.
Why? names ['Mary','John','Emma'], heights [180,165,170] → ['Mary','Emma','John'].
💡 Key idea Pair each name with its height and sort by height descending.
Edge / failure case duplicate names → ['Bob', 'Alice', 'Bob']
Duplicated names with different heights.
Why? rows with 2,4,1,2,5 soldiers, k=3 → rows [2, 0, 3].
💡 Key idea Soldiers (1s) come before civilians (0s) in each row, so the count of soldiers is the row's sum. Sort the row indices by (sum, index) and take the first k.
Edge / failure case ties → [1, 0]
Equal rows are ordered by index.
Why? 'cb34' → '' (digit 3 removes b, digit 4 removes c).
💡 Key idea Scan the string; push letters on a stack and let each digit pop the closest letter to its left.
Edge / failure case no digits → 'abc'
No digits.
Why? 2 → 1 → 5: the next greater values are [5, 5, 0].
💡 Key idea Copy the values into an array and use a decreasing stack of indices: when a value is bigger than the one at the top of the stack, it is the next greater value of that index. Indices left on the stack get 0.
Edge / failure case mixed → [7, 0, 5, 5, 0]
Classic example.
Why? 'leEeetcode' → 'leetcode'.
💡 Key idea Push characters on a stack; if the new character is the same letter in the other case as the top, pop instead.
Edge / failure case all cancel → ''
Everything cancels.
Why? [3,1,2,1]: clear 1s across (1 op), then 2 (1 op), then 3 (1 op) → 3.
💡 Key idea An operation picks a subarray and zeroes all its minimum non-zero values. Scan with a stack that keeps increasing values: pop larger values when a smaller one arrives (those levels are finished); a zero clears the stack; push a value and count one operation whenever it is not already on top of the stack.
Edge / failure case leading zero → 1
One operation.
Why? 'cdbcbbaaabab', ab=4, ba=5: take 'ba' first, then 'ab' → 19.
💡 Key idea Removing 'ab' scores x and 'ba' scores y. Do the more valuable pair first with a stack scan (push letters, pop when the top and the new letter form the pair), then remove the other pair from what is left.
Edge / failure case x larger → 20
20.
Why? [1,2,3]: ranges 0,0,0,1,1,2 → 4.
💡 Key idea The range of a subarray is max − min, so the answer is (sum of all subarray maxima) − (sum of all subarray minima). Each is computed in O(n) with a monotonic stack: an element is the maximum of (left span × right span) subarrays.
Edge / failure case mixed → 59
59.
Why? '((()))()()()' with k=3 → the first six characters cancel → '()()()'.
💡 Key idea Keep a stack of runs (character, length). When a run of ')' reaches length k directly above a run of '(' of length ≥ k, remove k from both. Merge equal neighbouring runs when pushing. The stack contents are the final string.
Edge / failure case k = 1 → ''
Everything cancels.
Why? 'cbacdcbc' → 'acdb'.
💡 Key idea Same as 'remove duplicate letters': keep a stack of chosen letters. For each letter not yet on the stack, pop larger letters from the top as long as they occur again later (last-occurrence index), then push it.
Edge / failure case second sample → 'abc'
Another sample input.
Why? '{a,b}{c,{d,e}}' → {ac, ad, ae, bc, bd, be}.
💡 Key idea Grammar: an expression is a union (comma separated) of terms; a term is a concatenation (product) of factors; a factor is a letter or a braced expression. Parse with recursive descent: a union collects sets, a product combines sets by concatenating every pair of strings, and the result is returned sorted.
Edge / failure case letters and sets → ['abdfg', 'abdfh', 'abefg', 'abefh', 'acdfg', 'acdfh', 'acefg', 'acefh']
Letters outside braces multiply with the sets.
Why? 'leet2code3', k=10 → 'o'.
💡 Key idea Never build the huge string. First compute the decoded length by scanning. Then go backwards: for a digit d divide the length by d and reduce k mod the length; for a letter, if k is 0 (or equals the length) it is the answer, else shrink the length by 1.
Edge / failure case ha22 → 'h'
'hahahaha' has 'h' at position 5.
Why? target [1,3], n=3 → Push, Push, Pop, Push.
💡 Key idea Read the numbers 1, 2, 3, … in order. Always Push; if the number is not the next target value, Pop it again. Stop after the last target value.
Edge / failure case no pops → ['Push', 'Push', 'Push']
Nothing to pop.
Why? [3,2,1,6,0,5] → root 6, left [3,2,1], right [0,5].
💡 Key idea The root is the maximum; the left subtree is built from the elements before it and the right from those after it. Scan left to right with a stack of decreasing values: a new value pops smaller ones (the last popped becomes its left child), and then becomes the right child of the new stack top.
Edge / failure case descending → [3, None, 2, None, 1]
A descending array leans to the right.
Why? students [1,1,0,0], sandwiches [0,1,0,1] → everyone eats → 0.
💡 Key idea Students rotate until someone takes the top sandwich. Only the counts matter: while the top sandwich has a remaining student who wants that type, serve it; when none do, the rest of the students are stuck.
Edge / failure case stuck → 3
Three students are stuck.
Why? [17,13,11,2,3,5,7] → [2,13,3,11,5,17,7].
💡 Key idea Simulate the reveal on indices: take the first index (it gets the smallest card), move the next index to the end, repeat. Assign the sorted cards to the revealed indices in order.
Edge / failure case two cards → [1, 1000]
Two cards.
Why? tickets [2,3,2], k=2: 2 + 2 + 2 → the last person finishes after 6 seconds.
💡 Key idea People in front of k (and k) buy at most tickets[k] tickets before k finishes; people behind k buy at most tickets[k] − 1. Sum min(tickets[i], limit).
Edge / failure case first person → 8
8.
Why? nums {1,2,3}, list 1→2→3→4→5 → 4→5.
💡 Key idea Put nums in a set and walk the list with a dummy head, linking only nodes whose value is not in the set.
Edge / failure case repeated removals → [2, 2, 2]
Only the 2s stay.
Why? 5→2→6→3→9→1→7→3→8→4: groups of 1,2,3,4 → the even groups are reversed.
💡 Key idea The list is split into groups of sizes 1, 2, 3 … (the last group may be shorter). Collect each group's nodes' values; if the group's real length is even reverse the values, then write them back in place.
Edge / failure case short → [1, 0, 1, 6]
The group of two is reversed.
Why? 1→2→3→4→5, k=2: swap the 2nd node from each end → 1→4→3→2→5.
💡 Key idea Walk to the k-th node from the front. A second pointer started at the head then advances together with a pointer that continues to the end; when the lead reaches the end the second pointer is the k-th from the back. Swap the two values.
Edge / failure case middle swap → [7, 9, 6, 6, 8, 7, 3, 0, 9, 5]
Another sample input.
Why? [1,2,3] into 5 parts → [1],[2],[3],[],[].
💡 Key idea With length n and k parts, every part has n // k nodes and the first n % k parts get one extra. Walk the list and cut after each part's size.
Edge / failure case uneven parts → [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
10 nodes in 3 parts: sizes 4, 3, 3.
Why? [5,3,1,2,5,1,2] has critical points at positions 2, 4 and 5 → [1, 3].
💡 Key idea A critical point is an inner node that is a local maximum or minimum. Record their positions. The minimum distance is the smallest gap between consecutive positions and the maximum is last − first; with fewer than two critical points return [−1, −1].
Edge / failure case plateau → [3, 3]
Critical points at 2 and 4 only.
Why? [18,6,10,3] → [18,6,6,2,10,1,3].
💡 Key idea For each adjacent pair (a, b) insert a node holding gcd(a, b) between them. Walk with one pointer, create the node, link it, and jump past it.
Edge / failure case single node → [7]
A single node has no neighbour pair.
Why? head [0,1,2,3], nums [0,1,3] → components {0,1} and {3} → 2.
💡 Key idea Put nums in a set. Walk the list; a component starts at a node whose value is in the set while the previous node's value is not (or there is no previous node).
Edge / failure case two runs → 2
Two components {0,1} and {3,4}.
Why? [4,2,1,3] → [1,2,3,4].
💡 Key idea Keep a dummy head for the sorted list. Take the nodes one by one; walk the sorted part to the first node larger than the current value and splice the node in before it.
Edge / failure case negatives → [-1, 0, 3, 4, 5]
Negative numbers.
Why? Ships at (1,1), (2,2), (3,3), (5,5): in the rectangle (0,0)–(4,4) there are 3 of them.
💡 Key idea You may only ask 'is there at least one ship in this rectangle?'. If the answer is no, return 0. If the rectangle is a single point return 1. Otherwise split it into four quarters and add the counts. Since there are at most 10 ships only a few rectangles are ever refined.
Edge / failure case big rectangle → 3
Three ships in a big sea.
Why? [1,10,4,3,null,7,9,12,8,6,null,null,2] is an even-odd tree → true.
💡 Key idea Level 0 (even) must hold odd values in strictly increasing order; level 1 must hold even values in strictly decreasing order; and so on. Check each level during a BFS (Breadth-First Search).
Edge / failure case invalid → False
Level 1 is not strictly decreasing even values.
Why? label 14 in the zigzag tree: path 1 → 3 → 4 → 14.
💡 Key idea In a normal heap numbering the parent of x is x // 2. In the zigzag tree odd rows are reversed, so the real parent is found by mirroring x inside its level (level min + level max − x) before halving. Climb to the root and reverse.
Edge / failure case label 26 → [1, 2, 6, 10, 26]
1, 2, 6, 10, 26.
Why? Nodes given in random order [5,4,3,1,2]... the one never listed as a child is the root.
💡 Key idea Add every node's value to a running total and subtract every child's value. What remains is the root's value (it is the only node never counted as a child); then pick that node from the list.
Edge / failure case two nodes → 1
Two nodes in reverse order.
Why? [1,0,1,0,1,0,1]: paths 100, 101, 110, 111 = 4+5+6+7 = 22.
💡 Key idea Carry the binary value of the path to each node (value × 2 + node bit). At a leaf add the value to the total.
Edge / failure case single node → 0
Zero.
Why? [2,1,3] → the bottom row's leftmost value is 1.
💡 Key idea Do a level-order traversal pushing the right child before the left child. The last node taken from the queue is the leftmost node of the last level.
Edge / failure case deep → 7
7.
Why? [1,null,2,3] → postorder [3,2,1].
💡 Key idea Postorder (left, right, root) is the reverse of a traversal that visits root, then right, then left. Do that with a stack and reverse the output.
Edge / failure case bigger → [4, 5, 2, 6, 3, 1]
Bigger tree.
Why? [1,2,3,4,5,6]: cutting off the subtree rooted at 2 (sum 11) gives 11 × 10 = 110.
💡 Key idea Removing one edge splits the tree into a subtree with sum s and the rest with total − s. Compute every subtree sum (post-order) and maximise s × (total − s). Take the result modulo 1e9+7 at the end.
Edge / failure case second sample → 90
Another sample input.
Why? Path with 2 edges: the weights must sum to an odd number → 2 ways (1,2 or 2,1).
💡 Key idea Every edge has weight 1 or 2; a path of d edges has an odd sum for exactly half of the 2^d assignments, i.e. 2^(d−1) (and 0 if d = 0). For each query find d = depth[u] + depth[v] − 2·depth[lca(u, v)] with binary lifting (a table of 2^j-th ancestors).
Edge / failure case two nodes → [0, 1]
Another sample input.
Why? [1,null,2,2] → 2 appears most often → [2].
💡 Key idea An in-order walk of a BST (Binary Search Tree) visits values in sorted order so equal values are adjacent. Count the current run, track the maximum run length and collect the values reaching it.
Edge / failure case one node → [0]
A single node is its own mode.
Why? root 1 with children 3, 2, 4 and 3's children 5, 6 → [5,6,3,2,4,1].
💡 Key idea Visit all children (left to right) recursively, then the node itself. An iterative version reverses a root-then-children-reversed traversal.
Edge / failure case one node → [7]
A tree with one node.
Why? [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]: the BST (Binary Search Tree) rooted at 3 has sum 20.
💡 Key idea For every node compute from its children whether the subtree is a BST (left max < node < right min), its minimum, its maximum and its sum. Update the answer with the sum of every BST subtree (never negative: an empty tree counts 0).
Edge / failure case invalid root → 2
The 2 is larger than its parent 3 on the left side of 4, so the whole tree is no BST; the best BST is the single leaf 2.
Why? '1-2--3--4-5--6--7' rebuilds the full binary tree [1,2,5,3,4,6,7].
💡 Key idea Each node is written as dashes (its depth) followed by its value. Scan the string: read the dashes and the number; pop the stack until its size equals the depth; the node is the left child of the stack top if that has no left child, otherwise its right child. Push the node.
Edge / failure case multi-digit values → [1, 401, None, 349, 88, 90]
A left spine with a right child.
Why? [4,2,6,3,1,5], val 1, depth 2 → a new row of 1s under the root.
💡 Key idea At depth 1 make a new root whose left child is the old tree. Otherwise find the nodes at depth − 1 with BFS (Breadth-First Search); for each, insert val-nodes as its new left and right children and hang the old children below them.
Edge / failure case deeper row → [4, 2, None, 1, 1, 3, None, None, 1]
Add the row at depth 3.
Why? [10,4,6] → 10 == 4 + 6 → true.
💡 Key idea The tree has exactly three nodes. Compare the root value with the sum of the left and right child values.
Edge / failure case not equal → False
3 + 1 is not 5.
Why? [8,3,10,1,6,null,14,null,null,4,7,13] → |8 − 1| = 7.
💡 Key idea For every node the best ancestor to compare with is the smallest or largest value on the path from the root. DFS (Depth-First Search) down carrying the path's min and max; at each node update the answer with |val − min| and |val − max|.
Edge / failure case chain → 3
A chain: the root 1 against the leaf 3.
Why? n=6, edges [[0,1],[0,2],[2,3],[2,4],[2,5]] → [8,12,6,10,10,10].
💡 Key idea Compute, for the root 0, the subtree sizes and the sum of distances from the root. Moving the root from a parent p to its child c brings the c-subtree one step closer (size[c] nodes) and everything else one step farther (n − size[c] nodes): ans[c] = ans[p] − size[c] + (n − size[c]).
Edge / failure case single node → [0]
A single node.
Why? edges [[1,2],[1,3],[3,4],[3,5]] → the deepest path has 2 edges → 2 ways.
💡 Key idea Take a deepest node; its path from the root has d edges, each weighing 1 or 2. The total is odd exactly when the number of weight-1 edges is odd, which is half of all 2^d assignments: 2^(d−1). Find d with a BFS (Breadth-First Search) from node 1.
Edge / failure case one edge → 1
One edge: weight 1 gives an odd cost.
Why? [2,1,3] → [2,3,1] gives the same BST (Binary Search Tree) → 1.
💡 Key idea The first element is the root; elements smaller than it form the left subtree's insertion order, larger ones the right's. Any interleaving of the two orders (keeping each internally ordered) gives the same BST: C(len − 1, len(left)) ways times the ways of each side. Answer = ways − 1 (excluding the original order), modulo 1e9+7.
Edge / failure case five values → 5
A longer array.
Why? grid [[1,1,1],[1,0,1],[0,0,1]]: every boy can get a different girl → 3 invitations.
💡 Key idea This is maximum bipartite matching between boys (rows) and girls (columns). For each boy try to find an augmenting path with DFS (Depth-First Search): take a free girl, or re-route the boy who currently holds her to another girl.
Edge / failure case second sample → 3
Three accepted.
Why? n=2, trust [[1,2]] → person 2 is trusted by 1 and trusts nobody → 2.
💡 Key idea The judge is trusted by everyone else (n−1) and trusts nobody. Keep a score per person: +1 when trusted, −1 when trusting someone. The judge's score is n−1.
Edge / failure case no judge → -1
The judge would trust someone.
Why? A star with centre 1 and leaves 0, 2, 3: the centre is the only minimum-height root → [1].
💡 Key idea The roots of minimum height trees are the centre(s) of the tree. Repeatedly remove all current leaves (degree 1) like peeling an onion; when at most two nodes remain, they are the answer.
Edge / failure case two roots → [3, 4]
Two centres: 3 and 4.
Why? Edges [1,2],[2,3],[4,2]: node 2 is in both of the first two edges → 2.
💡 Key idea The centre of a star appears in every edge. Look at the first two edges: the one node they share is the centre.
Edge / failure case centre 1 → 1
1.
Why? n=5, k=0, invocations [[1,2],[0,2],[0,1],[3,4]]: 0, 1, 2 are suspicious and not called from outside → remove them → [3, 4].
💡 Key idea Methods reachable from k (by following invocations) are suspicious. They can be removed only if no non-suspicious method invokes a suspicious one. If such a call exists, nothing may be removed and all methods remain; otherwise return the non-suspicious methods.
Edge / failure case outside caller → [0, 1, 2, 3]
All remain.
Why? A 2×2 room 'S.' / 'XL' with energy 2: right then down collects the litter in 2 moves.
💡 Key idea Number the litter cells (at most 10) and search with BFS (Breadth-First Search) over states (row, column, bitmask of collected litter, current energy). A move costs 1 energy, stepping on 'R' refills to the maximum, stepping on 'L' sets its bit. The first state with all bits set gives the minimum moves; a move with 0 energy left is not allowed.
Edge / failure case with a reset area → 3
Another sample input.
Why? isWater [[0,1],[0,0]] → heights [[1,0],[2,1]].
💡 Key idea Water cells have height 0 and neighbouring cells differ by at most 1, so the best height of a land cell is its distance to the nearest water. Start a BFS (Breadth-First Search) from all water cells at once.
Edge / failure case second sample → [[1, 1, 0], [0, 1, 1], [1, 2, 2]]
Another sample input.
Why? 3 gardens in a triangle: 1, 2, 3.
💡 Key idea Each garden has at most 3 neighbours and there are 4 flower types, so a free type always exists. Go through the gardens in order and give each the smallest type not used by an already-coloured neighbour.
Edge / failure case two components → [1, 2, 1, 2]
Two separate pairs of gardens.
Why? A grid with unsafe cells (1) that each cost 1 health: reach the bottom-right keeping health ≥ 1.
💡 Key idea Moving into an unsafe cell costs 1 health. Find the path that loses the least health with 0-1 BFS (Breadth-First Search with a deque: cost-0 moves to the front, cost-1 moves to the back). Return true if health − minimum loss is at least 1.
Edge / failure case unsafe ring → True
A ring of unsafe cells around the centre.
Why? edges [2,2,3,-1], node1 0, node2 1 → both reach node 2 → 2.
💡 Key idea Each node has at most one outgoing edge, so from a node you just follow the chain. Record the distance from node1 and node2 to every node they reach; among nodes reached by both, pick the one with the smallest larger distance (smallest index on ties).
Edge / failure case chain → 2
Node 2 is reached by both: the chain is 0 → 1 → 2.
Why? 8 items, 2 groups: items of one group stay together and obey beforeItems.
💡 Key idea Give every item without a group its own new group. Build two dependency graphs: between groups (item a before b in different groups gives group[a] → group[b]) and between items of the same group. Topologically sort the groups (smallest id first), then each group's items (smallest first) and concatenate. If either graph has a cycle return [].
Edge / failure case mixed groups → [1, 2, 0, 3]
Item 0 must come after item 2; item 2 belongs to group 0.
Why? a=3, b=15, x=9: three jumps forward (3, 6, 9) reach home → 3.
💡 Key idea From position p you jump forward a, or backward b (never two backward jumps in a row, never to a forbidden spot, never below 0). Search states (position, last move was backward). Bound the positions by max(x, forbidden) + a + b.
Edge / failure case back jump → -1
No sequence of jumps reaches 11: −1.
Why? A tree where the frog starts at 1; after t seconds it is at the target with probability 1/3.
💡 Key idea The frog starts at node 1 and each second jumps to a random unvisited neighbour; it never goes back. DFS (Depth-First Search) from 1 carrying the probability: at a node, split the probability equally among its unvisited children. At the target the frog must either have exactly t seconds left or have no unvisited children left (it stays there forever); otherwise the probability is 0.
Edge / failure case can still move → 1
The frog is at node 2 after one second but can still move.
Why? A graph game where the mouse wins at the hole 0... the answer is 1 (mouse), 2 (cat) or 0 (draw).
💡 Key idea State = (mouse node, cat node, whose turn). Terminal states are known: the mouse at 0 wins, the cat on the mouse's node wins. Run a BFS (Breadth-First Search) backwards from them: a state is a win for the player to move if some move leads to a state they already won; it is a loss if every move leads to a state they lose (tracked by a degree counter). States never decided are draws.
Edge / failure case mouse wins → 1
The mouse can reach the hole.
Why? [[0,1,1],[1,1,0],[1,1,0]] → remove 2 obstacles.
💡 Key idea Moving into an empty cell costs 0, into an obstacle costs 1. That is a shortest path with 0/1 weights: use a deque, pushing cost-0 moves at the front and cost-1 moves at the back.
Edge / failure case free path → 0
A clear path exists.
Why? n=5, queries [[2,4],[0,2],[0,4]] → [3,2,1].
💡 Key idea Roads never cross, so the shortest path is the chain of the 'outermost' roads. Keep next[i] = where city i's best road goes (initially i + 1) and the current path length. For a new road (u, v) with u still on the path and next[u] < v, walk from next[u] to v removing every city jumped over (each removal shortens the path by 1) and set next[u] = v.
Edge / failure case full road → [1, 1]
A road covering the whole line.
Why? nums [2,0,2], queries [[0,2],[0,2],[1,1]]: two queries are enough, so one can be removed → 1.
💡 Key idea Sweep i from left to right. Queries starting at i go into a max-heap keyed by end. If the number of active (applied) queries covering i is less than nums[i], apply more queries from the heap choosing those that reach farthest (largest end ≥ i); if the heap runs dry return −1. Unused queries can be removed: answer = total − used.
Edge / failure case second sample → 2
2.
Why? classes [[1,2],[3,5],[2,2]], 2 extra students → average pass ratio 0.78333.
💡 Key idea Adding a passing student to a class with p of t passing changes its ratio by (p+1)/(t+1) − p/t. Greedily give each extra student to the class with the largest gain, using a max-heap keyed by the gain. The answer is the average ratio afterwards.
Edge / failure case second sample → 0.53485
0.53485.
Why? nums [1,2,3,4], left=1, right=5 → sorted sums 1,2,3,3,4 → 13.
💡 Key idea Compute the sums of all n(n+1)/2 non-empty subarrays, sort them and add the elements from position left to right (1-based) modulo 1e9+7.
Edge / failure case narrow range → 6
Positions 3 and 4 of the sorted sums.
Why? intervals [[1,4],[2,4],[3,6],[4,4]], query 2 → smallest interval containing 2 is [2,4] (size 3).
💡 Key idea Answer the queries in increasing order. Push every interval that starts at or before the query into a min-heap keyed by size (with its right end); pop intervals whose right end is before the query. The top of the heap is the smallest interval covering the query, or −1 if the heap is empty.
Edge / failure case uncovered → [2, -1, 4, 6]
A query outside every interval gives −1.
Why? nums1 [4,2,1,5,3], nums2 [10,20,30,40,50], k=2 → [80,30,0,80,50].
💡 Key idea Sort the indices by nums1. Sweep upwards keeping a min-heap of the k largest nums2 values among strictly smaller nums1 entries (and their sum). Equal nums1 values share one answer, so add a group's values to the heap only after answering the whole group.
Edge / failure case all equal → [0, 0, 0, 0]
Equal nums1 values: nobody has a smaller one, so all answers are 0.
Why? nums [1,1,2,2,3,4,2,3], k=6, x=2 → [6,10,12].
💡 Key idea The x-sum counts only the x most frequent values (ties: bigger value wins). Keep each value's frequency and two ordered collections of (frequency, value) pairs: top (size ≤ x) and rest. When a value's frequency changes, remove its old pair, insert the new pair, then rebalance: move the best of rest into top, or the worst of top out. Maintain the sum of freq·value in top.
Edge / failure case k = 2 → [11, 15, 15, 15, 12]
Windows of two numbers.
Why? [1,2,3,4] → [2,2,3,4]... best deviation 1.
💡 Key idea Odd numbers can be doubled and even numbers halved. First double every odd number once (they can then only shrink). Now all numbers are even and can only be halved: repeatedly take the maximum from a max-heap, record the deviation (max − min), and halve it while it is even; stop when the maximum is odd.
Edge / failure case mixed → 3
Mixed even and odd values.
Why? nums [2,3,5,9], k=2: rob 2 and 5 → capability 5.
💡 Key idea Guess the capability c (the largest amount you may take from one house). Greedily rob every house with money ≤ c that is not adjacent to the last robbed one and count; if the count reaches k, c is enough. Binary search the smallest c.
Edge / failure case second sample → 2
Rob the houses worth 2 and 1: capability 2.
Why? arr [4,9,3], target 10: capping values at 3 gives 3 + 3 + 3 = 9 and at 4 gives 4 + 4 + 3 = 11; both are 1 away, pick the smaller value 3.
💡 Key idea Replace every number larger than value by value. The sum increases with value, so binary search the value in [0, max(arr)]; compare the two values around the target and pick the one with the smaller difference (smaller value on ties).
Edge / failure case no cap needed → 5
5.
Why? Two unit squares at y=0 and y=2: a line at y=1 puts half the area on each side → 1.0.
💡 Key idea The area below a horizontal line y = h grows continuously with h. Binary search h in [min y, max top] until the area below equals half the total (area of each square below the line is side × clamp(h − y, 0, side)). Round to 5 decimals.
Edge / failure case overlap → 1.16667
1.16667.
Why? [[1,0,1],[0,-2,3]], k=2: the rectangle [[0,1],[-2,3]] sums to 2 → 2.
💡 Key idea Fix a top and a bottom row and collapse the columns between them into one array of column sums. We now want the subarray of that array with the largest sum ≤ k: keep a sorted list of prefix sums; for each prefix p find the smallest earlier prefix ≥ p − k with bisect — the difference is the best sum ending here.
Edge / failure case single row → 3
Another sample input.
Why? prices [13,5,1,8,21,2], k=3 → pick 13, 5, 2? best tastiness is 8.
💡 Key idea Tastiness is the smallest price difference between two chosen candies. Guess a gap g; after sorting, greedily pick the cheapest candy and then each next candy whose price is at least g more than the last picked; if k are picked the gap works. Binary search the largest g.
Edge / failure case equal prices → 0
Equal prices.
Why? coins [3,6,9], k=3: the amounts are multiples of 3, so the third is 9.
💡 Key idea Binary search the amount x. The number of amounts ≤ x is the size of a union of multiple-sets, counted with inclusion–exclusion: for every non-empty subset of coins add or subtract floor(x / lcm(subset)) depending on the subset's parity. The answer is the smallest x with count ≥ k (at most min(coin)·k).
Edge / failure case two coins → 12
Multiples of 2 and 5 merge: the 7th is 12.
Why? [-2,-1,-1,1,2,3] → 3 negatives and 3 positives → 3.
💡 Key idea The array is sorted. The number of negatives is the index of the first non-negative; the number of positives is n minus the index of the first positive. Return the larger.
Edge / failure case all zeros → 0
Zeros are neither positive nor negative.
Why? [[3,4],[2,3],[1,2]] → right intervals: [−1, 0, 1].
💡 Key idea For each interval find the interval with the smallest start ≥ its end. Sort the starts with their original indices and binary search each end.
Edge / failure case single → [-1]
A single interval: its own start 1 is below its end 4, so there is no right interval.
Why? tasks [3,2,1], workers [0,3,3], pills 1, strength 1 → 3.
💡 Key idea If k tasks can be done, so can fewer: binary search k. To check k, take the k easiest tasks and k strongest workers. Go through the workers from weakest to strongest keeping a deque of tasks they could do with a pill: if the easiest task fits without a pill take it, otherwise spend a pill on the hardest task the worker can reach.
Edge / failure case single pill → 1
One pill lets one worker do one task.
Why? [5,11,20,20], k=5, 1 operation: the two 20s are already equal → frequency 2.
💡 Key idea Choose a target value t. Elements already equal to t cost nothing; each other element within distance k of t can be moved onto it, but only numOperations of them may be. So the frequency is same(t) + min(numOperations, near(t) − same(t)). The best target is an element value, or a value x±k (where a window starts or ends), so test those candidates, counting with binary search on the sorted array.
Edge / failure case k = 0 → 1
With k = 0 nothing can change.
Why? [1,4,5], k=1, 2 operations: 5 becomes 4 → two 4s (1 is too far to join) → 2.
💡 Key idea Pick a target t. Elements already equal to t are free; each other element within k of t can be moved onto it, but only numOperations elements may be changed. So frequency = same(t) + min(numOperations, near(t) − same(t)). Candidate targets are the element values and value ± k; count with binary search on the sorted array.
Edge / failure case second sample → 2
The two 20s.
Why? side 2, points [[0,2],[2,0],[2,2],[0,0]], k=4 → all four corners, minimum distance 2.
💡 Key idea Binary search the answer d. Lay the points out in order around the boundary of the square. To test d, try each point as the first chosen one: greedily walk forward choosing the next point at Manhattan distance ≥ d from the last chosen, and finally check the last chosen is ≥ d from the first. If k points are reached the distance d is possible.
Edge / failure case five points → 1
Five points, four chosen.
Why? edges [[0,1,5],[1,3,10],[0,2,3],[2,3,4]], k=10 → the path 0→2→3 costs 7 with minimum 3 → 3.
💡 Key idea The score of a path is its cheapest edge, and we want the largest score whose path stays within total cost k. Binary search the score s: use only edges with cost ≥ s and find the cheapest path from 0 to n−1 through online intermediate nodes (a DAG (Directed Acyclic Graph), so process in topological order). If that cost is ≤ k then s is achievable.
Edge / failure case offline node → 5
Node 3 is offline, so the path through it is not allowed.
Why? stations [1,2,4,5,0], r=1, k=2 → minimum power can be raised to 5.
💡 Key idea The power of a city is the number of stations within distance r. Binary search the target minimum power T. Sweep the cities left to right; if a city is below T, place the missing stations as far right as possible (at city i + r), which helps the most following cities; track their effect with a difference array. T is possible if the stations used are ≤ k.
Edge / failure case r = 0 → 4
Radius zero: each station powers its own city.
Why? n=13 → [1,10,11,12,13,2,3,4,5,6,7,8,9].
💡 Key idea Start at 1. Next number: if cur × 10 ≤ n go deeper; otherwise move to cur + 1, first stepping up (cur //= 10) while cur is n or ends in 9. Repeat n times.
Edge / failure case tiny → [1, 2]
Just 1, 2.
Why? words ['dog','cat','dad','good'] with the given letters: choose 'dad' and 'good' → score 23.
💡 Key idea Each letter can be used only as many times as it appears in letters. Try every subset of words with DFS (take or skip each word), subtracting the letter counts when taking it and abandoning the branch if a letter runs out. Score = sum of letter scores of the chosen words; keep the best.
Edge / failure case shared letters → 27
Choose the words that share the x's best.
Why? n=10: 1, 9 (9² = 81 → 8+1) and 10 (100 → 10+0) qualify → 1 + 81 + 100 = 182.
💡 Key idea For each i from 1 to n test whether the decimal digits of i² can be cut into contiguous pieces whose values add up to i (backtracking over cut positions). Add i² for each i that works.
Edge / failure case n = 37 → 1478
1182.
Why? n=3: the happy strings in order start 'aba', 'abc', 'aca' … the 3rd is 'aca'.
💡 Key idea A happy string uses a, b, c with no two equal neighbours. For length n there are 3·2^(n−1) of them: after choosing the first letter each remaining position has 2 choices. Pick each letter greedily: the number of strings beginning with a given prefix is 2^(remaining), so subtract blocks until k falls into one.
Edge / failure case too large k → ''
Only a, b, c exist.
Why? digits [1,2,3,4]: all 3-digit numbers from distinct positions that end in 2 or 4 → 12.
💡 Key idea Take every ordered choice of three positions (so each digit card is used at most once), form the number, keep it if the first digit is not 0 and the last digit is even, and count distinct values.
Edge / failure case with zero → 2
Only 202 and 220.
Why? [3,1] → maximum OR 3 reached by {3} and {3,1} → 2.
💡 Key idea The largest possible OR is the OR of all numbers. Count the subsets whose OR reaches it with a DFS (Depth-First Search) that either includes or skips each number.
Edge / failure case all equal → 7
Every non-empty subset reaches the maximum.
Why? [2,4,6], k=2 → beautiful subsets: {2},{4},{6},{2,6} → 4.
💡 Key idea A subset is beautiful if no two of its numbers differ by exactly k. Backtrack over elements: include nums[i] only if neither nums[i]−k nor nums[i]+k is already chosen (tracked in a Counter). Count every non-empty subset reached.
Edge / failure case one number → 1
A single number.
Why? n=3 → '010','011','101','110','111'.
💡 Key idea Build the string left to right. After a '0' only '1' may follow; after a '1' either digit. Collect the strings of length n and return them sorted.
Edge / failure case n = 1 → ['0', '1']
Both single digits are valid.
Why? 2 × 3 rectangle → 3 squares (a 2×2 and two 1×1).
💡 Key idea Keep the filled heights of each column (the skyline). Always fill the lowest-leftmost gap: try every square size that fits there, from large to small, recurse, and prune when the count already exceeds the best.
Edge / failure case 5 × 8 → 5
A 5 × 8 rectangle needs 5 squares.
Why? n=3, k=7 → 181, 292, 707, 818, 929.
💡 Key idea The first digit is 1–9. Each next digit differs from the previous by exactly k, so it is prev + k or prev − k (once if k = 0), staying within 0–9. Build all numbers of n digits and return them sorted.
Edge / failure case k = 0 → [11, 22, 33, 44, 55, 66, 77, 88, 99]
Difference zero repeats the digit.
Why? n=12 = 4 + 4 + 4 → 3 squares.
💡 Key idea dp[i] = fewest perfect squares summing to i: min over squares s ≤ i of dp[i − s] + 1. Build up to n.
Edge / failure case 13 → 2
4 + 9.
Why? rowIndex=3 → [1,3,3,1].
💡 Key idea Start with [1]. For each next row update the values from right to left so each number becomes the sum of the two above it, then append a 1.
Edge / failure case row zero → [1]
Just 1.
Why? '2-1-1' → ((2−1)−1) = 0 and (2−(1−1)) = 2 → [0,2].
💡 Key idea For every operator split the expression into left and right parts, compute all results of each part recursively and combine them with the operator. A pure number returns itself. Memoise the sub-expressions.
Edge / failure case mixed operators → [10, -10, -10, -14, -34]
Five ways.
Why? [8,1,5,2,6]: 8 + 5 + 0 − 2 = 11.
💡 Key idea Score of a pair i<j is (values[i] + i) + (values[j] − j). Scan j from left to right, keeping the best values[i] + i seen before.
Edge / failure case two spots → 2
1 + 2 + 0 − 1 = 2.
Why? n=10, x=2: 1² + 3² = 10 is the only way → 1.
💡 Key idea Use each positive integer at most once, contributing i^x. dp[s] = number of ways to reach sum s; process each i with i^x ≤ n and update sums from high to low. Modulo 1e9+7.
Edge / failure case x = 1 → 2
4 and 1+3.
Why? n=6, k=1, maxPts=10: Alice draws once; the chance of ending ≤ 6 is 0.6.
💡 Key idea dp[s] = probability of ever having s points. Alice stops once she has ≥ k points. dp[s] = (sum of dp[s − j] for j = 1…maxPts over states < k) / maxPts, kept with a sliding window sum. The answer is the sum of dp[s] for k ≤ s ≤ n.
Edge / failure case certain → 1
One draw always ≤ 10.
Why? n=6, delay=2, forget=4 → 5 people know the secret on day 6.
💡 Key idea Let new[d] be the people who learn the secret on day d. A person starts sharing delay days later and stops forget days after learning. new[d] = sum of new[d − forget + 1 … d − delay] (those currently allowed to share). The answer is the sum of new over the last `forget` days. Modulo 1e9+7.
Edge / failure case short → 6
6.
Why? 'aababbab' → delete two characters to get 'aaabbb'-style order → 2.
💡 Key idea A string is balanced when no 'b' comes before an 'a'. Scan left to right keeping the number of 'b's seen and the best deletion count: at an 'a' either delete it (cost+1) or delete all earlier 'b's (cost = count of b); keep the smaller.
Edge / failure case second sample → 2
2.
Why? Range 120–130: 120, 121 and 130 each have one peak (the middle digit) → 3.
💡 Key idea Let F(N) = total waviness of all numbers 0…N; the answer is F(num2) − F(num1−1). Build F with a digit DP (Dynamic Programming) over the digits of N with state (position, previous two digits, still tight to N, number started). Each state returns (how many completions, sum of waviness of those completions); when adding a digit d, the previous digit becomes a peak/valley if it is strictly above/below both neighbours, which contributes 1 to every completion.
Edge / failure case across 200 → 3
Three peaks.
Why? n=3, values 4…5: [4,5,4] and [5,4,5] → 2.
💡 Key idea State = (last value, did the last step go up or down). From an 'up' ending the next step must go down to a smaller value and vice versa, so the counts for length t+1 are linear in those for length t. The values range over at most 75 numbers, so build the 2m×2m transition matrix and raise it to the power n − 2 by repeated squaring, starting from the counts for length 2. Modulo 1e9+7.
Edge / failure case range 1–3 → 10
Ten arrays.
Why? n=4: Alice removes 4 stones and wins → true; n=2: only 1 can be removed, Bob then wins → false.
💡 Key idea win[i] is true if the player to move with i stones can remove a square number s ≤ i leaving i − s stones where the opponent loses. win[0] = false.
Edge / failure case n = 2 → False
Alice loses.
Why? 'sea' and 'eat' share 'ea' → 3 + 3 − 2·2 = 2 deletions.
💡 Key idea The characters that remain must form a common subsequence. Keeping the longest one (LCS (Longest Common Subsequence)) minimises deletions: len1 + len2 − 2·LCS (Longest Common Subsequence).
Edge / failure case subsequence → 4
4 deletions.
Why? 'abc' has 7 distinct non-empty subsequences; 'aaa' has 3.
💡 Key idea Let end[c] be the number of distinct subsequences ending with letter c. When a letter c arrives, every existing subsequence (and the empty one) can be extended by c, so end[c] = 1 + sum of all end[·] — this replaces the old count for c instead of adding to it, which removes duplicates. Answer = sum of end, modulo 1e9+7.
Edge / failure case repeats → 3
3.
Why? [2,1,1,5,6,2,3,1]: the longest mountain keeps 1,5,6,2,1 or similar (5 elements) → remove 3.
💡 Key idea Compute for every index the length of the longest increasing subsequence ending there (left[i]) and the longest decreasing subsequence starting there (right[i]) using LIS (Longest Increasing Subsequence) DP (Dynamic Programming). A mountain peaking at i keeps left[i] + right[i] − 1 elements (only if both sides have at least 2). Remove the rest.
Edge / failure case second sample → 4
4.
Why? [1,1,2,1]: splits ([1],[1],[2,1]) and ([1],[1,2],[1]) are beautiful → 2.
💡 Key idea Split nums into three non-empty parts A, B, C. It is beautiful if A is a prefix of B, or B is a prefix of C. Precompute lcp[i][j] = longest common prefix of the suffixes starting at i and j (LCP (Longest Common Prefix) table built from the end). Then A = nums[0:i] is a prefix of B = nums[i:j] when len(B) ≥ i and lcp[0][i] ≥ i; B is a prefix of C when len(C) ≥ len(B) and lcp[i][j] ≥ j − i.
Edge / failure case none → 0
0.
Why? The 4×4 sample: the diagonal gives 34 and the other two children add 66 → 100.
💡 Key idea Three children cross an n×n grid and each reaches (n−1, n−1) in n−1 moves. The child from (0,0) must follow the main diagonal. The child from (0, n−1) stays above the diagonal and the child from (n−1, 0) below it, so they never collide. Each triangle is a simple DP (Dynamic Programming) over rows; the third child is handled by transposing the grid. Total = diagonal + both triangles.
Edge / failure case 2×2 → 4
Another sample input.
Why? n=50: the probability that A empties first (plus half that both empty together) is 0.625.
💡 Key idea Four equally likely servings take (100,0), (75,25), (50,50), (25,75) ml from (A, B). Work in units of 25 ml: p(a, b) = ¼ Σ p(a − x, b − y). A is empty first → 1, both empty → 0.5, B empty first → 0. For large n the answer is within 1e-5 of 1, so return 1 when n ≥ 4800.
Edge / failure case n = 100 → 0.71875
Another sample input.
Why? [[0,1,-1],[1,-2,3],[2,-3,4]] → neutralise two robbers, end with 8.
💡 Key idea The robot moves right or down. A negative cell is a robber that steals that amount unless the robot neutralises it, which can be done at most twice. dp[i][j][t] = best total at (i, j) having neutralised t robbers: from the top or left cell add coins (or, for a robber with t > 0 left, skip the loss and use one neutralisation).
Edge / failure case no robbers → 40
No robbers.
Why? n=4 → [2,1,4,3].
💡 Key idea An array with no i<k<j where 2·nums[k] = nums[i] + nums[j] stays beautiful under x → 2x−1 and x → 2x. So build beautiful(n) from beautiful of the odd count mapped to odd numbers followed by beautiful of the even count mapped to even numbers.
Edge / failure case n = 5 → [1, 5, 3, 2, 4]
Another sample input.
Why? n=10: a smart strategy guarantees winning with at most 16 dollars.
💡 Key idea cost(l, r) = the money needed to guarantee a win in [l, r]. Guessing x costs x plus the worse of the left part and right part: x + max(cost(l, x−1), cost(x+1, r)). Pick the x that minimises it; an empty or one-number range costs 0.
Edge / failure case n = 1 → 0
No guess needed.
Why? ['E23','2X2','12S'] → maximum score 7 reached in 1 way.
💡 Key idea Starting at the bottom-right 'S' you move up, left or diagonally up-left to the top-left 'E', collecting digits ('X' blocks). dp[i][j] = (best score, number of ways) from S: take the maximum over the three predecessor cells (those reachable) and add the cell's digit; ways add up when scores tie. Ways are modulo 1e9+7; answer [0, 0] if E is unreachable.
Edge / failure case two paths → [4, 2]
Another sample input.
Why? [1,2,3,4] → 10 pairs of disjoint non-empty subsequences with equal GCD (Greatest Common Divisor).
💡 Key idea Go through the numbers once; every number is put in seq 1, in seq 2 or in neither. State = (g1, g2), the gcd of each sequence so far (0 for empty). Adding x to seq 1 changes g1 to gcd(g1, x), likewise for seq 2. Count the states; the answer sums the counts of all states (g, g) with g > 0. Modulo 1e9+7.
Edge / failure case multiples → 2
Another sample input.
Why? The first sample: indices [2, 3] (weights 5 and 3) give the best score 8.
💡 Key idea Sort the interval indices by start. f(p, k) = the best (score, index list) using intervals from position p onward with at most k picks left: either skip interval p, or take it and continue at the first interval whose start is after its end (binary search) with k−1 picks. Prefer the higher score and, on equal scores, the lexicographically smaller sorted index list.
Edge / failure case ties → [1, 3]
Several intervals tie; the index list must be smallest.
Why? [9,4,7,2,10] → 4,7,10 with difference 3 → length 3.
💡 Key idea For each pair j < i with difference d = nums[i] − nums[j], dp[i][d] = dp[j][d] + 1 (a sequence of two elements has length 2). Keep a dictionary of differences per index and track the maximum.
Edge / failure case difference −5 → 4
Pick a subsequence with the difference -5.
Why? [[1,2,3],[4,5,6],[7,8,9]] → 1 + 5 + 7 = 13.
💡 Key idea A falling path takes one element per row with no two in the same column as neighbours. For each cell the best previous cell is the smallest value in the previous row from a different column: keep the smallest and second smallest (with the column of the smallest) of the previous row.
Edge / failure case one cell → 7
A single cell.
Why? n=7, cuts [1,3,4,5] → total cost 16.
💡 Key idea A cut costs the current stick length. Sort the cuts and add the ends 0 and n. dp[i][j] = cheapest way to make all cuts strictly between positions i and j: choose the first cut k and pay (pos[j] − pos[i]) + dp[i][k] + dp[k][j].
Edge / failure case five cuts → 22
Five cuts on a stick of length 9.
Why? robots [0,4,6], factories [[2,2],[6,2]] → robots 0 and 4 to factory 2, robot 6 to factory 6 → total 4.
💡 Key idea Sort robots and factories by position. dp[i][j] = minimum distance for the first i robots using the first j factories. For factory j with capacity c, let it take the last t robots (0 ≤ t ≤ c) of the first i: dp[i][j] = min over t of dp[i−t][j−1] + sum of |robot − factory| for those t robots.
Edge / failure case one each → 2
Each factory repairs one robot: the nearer robot goes to each.
Why? n=4 houses with costs for 3 colours: pair (0,3) and (1,2) get different colours inside each pair and neighbours differ.
💡 Key idea n is even; house i and n−1−i must have different colours, and neighbouring houses differ. Process the pairs from the outside to the middle: state = (colour of the left house, colour of the right house) of the current pair. A pair (c1, c2) can follow a pair (p1, p2) if c1 ≠ c2, c1 ≠ p1 and c2 ≠ p2. Minimise the total cost.
Edge / failure case one pair → 2
A single pair of houses.
Why? 'abcdeafdef' → 'abcdea' and 'fdef' → 2.
💡 Key idea dp[i] = the most substrings in the first i letters. Either skip letter i−1 (dp[i−1]) or end a substring there: it must start at an earlier equal letter at distance ≥ 3. Since dp never decreases, the latest such start is best: dp[start] + 1.
Edge / failure case overlap → 1
Two overlapping candidates: only one fits.
Why? s1 'great', s2 'rgeat' → true.
💡 Key idea s2 is a scramble of s1 if some split point i gives either (s1[:i] ~ s2[:i] and s1[i:] ~ s2[i:]) or the swapped version (s1[:i] ~ s2[-i:] and s1[i:] ~ s2[:-i]). Strings with different letter counts can never match, which prunes the search. Memoise on (s1, s2).
Edge / failure case not a scramble → False
No split of the two strings works.
Why? 'aabbccdd', k=7 → 5 originals of length ≥ 7.
💡 Key idea Group equal consecutive letters; each group of length g can come from 1…g typed letters, so there are the product of g's originals in total. Subtract those shorter than k: if there are at least k groups, none are shorter. Otherwise count length-<k originals with a DP (Dynamic Programming) over groups using prefix sums, modulo 1e9+7.
Edge / failure case three groups → 5
Groups of 1, 2 and 3 letters.
Why? n=11, first 2, second 4 → they can meet as early as round 3 and as late as round 4.
💡 Key idea Only the positions of the two special players matter. If they are mirror images (positions add to n+1) they meet this round. Otherwise reflect so the pair is in the left part, then try every way the other players can win: how many survivors land before the first, and between the two. Recurse on the halved row.
Edge / failure case meet at once → [1, 1]
The first and last player meet in round 1.
Why? n=2 → 8 of the 9 two-day records are rewarded (only 'AA' fails).
💡 Key idea A record is rewarded if it has fewer than 2 'A's and no 'LLL'. Track the number of valid records by state (absences used 0/1, trailing late days 0/1/2) and extend one day at a time with 'P', 'A' or 'L'. Sum the six states after n days modulo 1e9+7.
Edge / failure case n = 3 → 19
Longer records.
Why? [6,2,8,4] → remove 6 and 8 (cost 8), then 2 and 4 (cost 4) → 12.
💡 Key idea Each step removes two of the first three elements, so at most one older element survives at the front (the 'carry'). State: the index of the carry and the next unread index. Remove the next two (carry stays), or the carry with one of the next two (the other becomes the new carry). When fewer than three elements remain, pay the maximum of them.
Edge / failure case four elements → 5
Four elements.
Why? [2,1,-2,5], [3,0,-6] → pick (2,-2) with (3,-6): 6 + 12 = 18.
💡 Key idea Choose non-empty subsequences of equal length. dp[i][j] is the best result using the first i of nums1 and j of nums2: skip nums1[i−1], skip nums2[j−1], take the pair alone, or take the pair and add dp[i−1][j−1] if that is positive. Start from −infinity.
Edge / failure case negative → -1
All products are negative: take the least bad pair.
Why? [2,4,6,8,10] → 7 arithmetic subsequences of length ≥ 3.
💡 Key idea For each pair j < i with difference d, every arithmetic subsequence (of length ≥ 2) ending at j with difference d can be extended by nums[i]. Keep cnt[i][d] = number of such subsequences of length ≥ 2 ending at i; the extensions of length ≥ 3 are cnt[j][d], which are added to the answer.
Edge / failure case all equal → 16
Equal numbers form many sequences.
Why? [1,4,2,7] → 1,4 up; 4,2 down; 2,7 up → sum 14.
💡 Key idea A trionic subarray is increasing, then decreasing, then increasing. Keep the best sum of a subarray ending at i in each phase: inc1[i] (first rise, ≥ 2 elements), dec[i], inc2[i]. When nums[i−1] < nums[i] extend a rise: inc1[i] = max(inc1[i−1], nums[i−1]) + nums[i], inc2[i] = max(inc2[i−1], dec[i−1]) + nums[i]; when nums[i−1] > nums[i], dec[i] = max(dec[i−1], inc1[i−1]) + nums[i]. The answer is the best inc2.
Edge / failure case negatives → -4
Negative numbers.
Why? 'abac' and 'cab' → 'cabac' (length 5).
💡 Key idea dp[i][j] = length of the shortest string having both str1[i:] and str2[j:] as subsequences. If the letters match they share one character; otherwise take the better of using str1's or str2's letter. Walk the table from (0,0) writing characters, preferring str1's letter on a tie.
Edge / failure case equal strings → 'aaaaaaaa'
Equal strings.
Why? n=3, range [4,5] → [4,5,4] and [5,4,5] → 2.
💡 Key idea A zigzag alternates up and down. Let up[v] / down[v] be the number of valid arrays so far ending in value v after an up-step / down-step. A new up-step to v comes from any earlier down-ending smaller value; a down-step to v from an earlier up-ending larger value. Prefix sums make each layer O(range). Start with both directions allowed for length 2 and sum at the end, modulo 1e9+7.
Edge / failure case range 3 → 10
Three values.
Why? n=3, k=1 → 2 permutations of 1,2,3 have exactly one inverse pair.
💡 Key idea dp[n][k] = number of permutations of 1…n with k inverse pairs. Placing the largest element n at position i (counting from the right) creates i inverse pairs, i from 0 to n−1, so dp[n][k] = dp[n−1][k] + … + dp[n−1][k−n+1]. Keep that window sum while sweeping k, modulo 1e9+7.
Edge / failure case k = 0 → 1
Only the sorted permutation.
Why? [1,2,3,7] → Bob wins.
💡 Key idea Let dp[i] be the best (current player − other player) score difference using stones from i onwards. Taking j = 1…3 stones gives the sum of those stones minus dp[i + j]. Alice wins if dp[0] > 0, Bob if < 0, otherwise a tie.
Edge / failure case negative → 'Tie'
All negative values.
Why? [1,2,3,4,5], k=3 → [9, 2, 4].
💡 Key idea The operation removes a prefix and a suffix, so what is left is any non-empty subarray. For each end index keep how many subarrays ending there have product ≡ r (mod k): extend every earlier subarray by multiplying its remainder by the new number, and add the new single-element subarray. Add these counts into the result.
Edge / failure case k = 4 → [18, 1, 2, 0]
Powers of two modulo 4.
Why? 'L_RL__R': 3 L's and 2 R's net −1, plus 2 underscores → 3.
💡 Key idea Each '_' can go either way, so send all of them in the direction of the majority. The answer is |#L − #R| + #_.
Edge / failure case all underscores → 7
All free moves.
Why? positions [2,2,2,3,3]: move the two chips on 3 to 2 (cost 1 each) → 2.
💡 Key idea Moving a chip by 2 is free and by 1 costs 1. So every chip can reach any position with the same parity for free; the answer is the smaller of the count of chips on even positions and on odd positions.
Edge / failure case three chips → 1
One move of cost 1.
Why? '1001010', k=5: take all zeros and the low-order ones that keep the value ≤ 5 → length 5.
💡 Key idea Leading zeros are free, so keep every 0. Scan from the right: add a 1 only while the value built so far (the bit's weight 2^position) still keeps the number ≤ k.
Edge / failure case k = 1 → 6
Keep all zeros and one 1.
Why? word1 'vbcca', word2 'abc': indices [0,1,2] (v differs once, the rest match) is the smallest valid sequence.
💡 Key idea We need indices i₀<i₁<… so that word1 at those indices equals word2 with at most one mismatch, lexicographically smallest. Precompute suf[j]: the latest start in word1 from which word2[j:] can still be matched exactly as a subsequence. Greedily take the earliest matching index for each letter; if it mismatches, spend the single skip only when the rest can still be matched exactly after that index.
Edge / failure case late skip → [1, 2, 3, 4]
Skip the first mismatch.
Why? [[0,0,1],[1,1,0],[1,0,0]] → 3 adjacent row swaps make all cells above the diagonal zero.
💡 Key idea The grid is valid when all cells above the main diagonal are 0, i.e. row i ends with at least n−1−i zeros. Compute trailing zeros per row. For i = 0, 1, … find the first row at or below i with enough trailing zeros and bubble it up with adjacent swaps (count the distance). If none exists the answer is −1.
Edge / failure case impossible → -1
Impossible.
Why? n=5, restrictions [[2,1],[4,1]]: heights 0,1,2,1,2 → the maximum is 2.
💡 Key idea Building 1 has height 0 and neighbours differ by at most 1. Sort the restrictions, add (1, 0) and (n, ∞). Sweep left to right then right to left so every limit is consistent with its neighbours (limit ≤ neighbour's limit + distance). Between two consecutive limited buildings at distance d with limits a and b the highest possible peak is (a + b + d) // 2.
Edge / failure case no restrictions → 5
No restrictions: the last building reaches 5.
Why? 'babab' → counts a:2, b:3 → left half 'ab', middle 'b' → 'abbba'.
💡 Key idea The input is a palindrome, so every letter appears an even number of times except possibly one. Put half of each letter in sorted order on the left, the odd letter in the middle, and mirror the left half on the right.
Edge / failure case single → 'z'
Single letter.
Why? num=555: biggest 999, smallest 111 → 888.
💡 Key idea To get the largest number replace every copy of the first digit that is not 9 by 9. To get the smallest replace the first digit by 1 (if it is not 1), otherwise replace the first digit after it that is not 0 or 1 by 0 (never creating a leading zero). Return the difference.
Edge / failure case single digit → 8
9 and 1.
Why? 'aabcaba', k=0: keep a, b with equal frequency 3 → delete 1 c... answer 3.
💡 Key idea A string is k-special if any two letter frequencies differ by at most k. Try each existing frequency f as the lowest kept frequency: letters with frequency below f are deleted entirely, letters above f + k are reduced to f + k. Take the cheapest total deletions.
Edge / failure case k = 2 → 1
Delete the b.
Why? [1,1,0,1,1] → keep one 1 → 1.
💡 Key idea After deleting arbitrary elements you want a subarray with distinct values and the largest sum. Because you may delete anything, take each distinct positive value once; if no positive value exists the best is the largest element.
Edge / failure case all negative → -100
Only a negative.
Why? [2,1,2] → 2 + 1 + 2 = 5.
💡 Key idea Sort descending. The first three consecutive sides a ≥ b ≥ c with b + c > a form the triangle with the largest perimeter. If none exists the answer is 0.
Edge / failure case none → 0
No triangle.
Why? [[1,-1],[-1,1]] → flip a pair to make everything positive → 4.
💡 Key idea One operation flips the signs of two neighbouring cells. So the parity of the number of negatives is invariant. Take the sum of absolute values; if the count of negatives is odd, one cell must stay negative — subtract twice the smallest absolute value.
Edge / failure case second sample → 16
Another sample input.
Why? [6,5,7,9,2,2] → pay 9 + 7 + 5 + 2? → every third from the top is free: total 23.
💡 Key idea When you buy two candies you get the cheapest of the next ones free (not more expensive than either). Sort the costs descending and skip every third.
Edge / failure case two candies → 10
No free candy.
Why? Land ride 2+4=6 then water ride starting at 6 for 3 → finishes at 9.
💡 Key idea You must take one land ride and one water ride, in either order; a ride can only start at or after its opening time and after the previous ride ended. Try every pair in both orders and keep the earliest finish.
Edge / failure case second sample → 14
Another sample input.
Why? [2,10,7,5,4,1,8,6]: min at index 5, max at index 1: removing from both ends costs 5.
💡 Key idea Let i<j be the positions of the min and max in either order. Options: remove from the front until j (j+1 deletions), from the back until i (n−i), or the front to i and the back from j (i+1 + n−j). Take the cheapest.
Edge / failure case single element → 1
One element is both min and max.
Why? '(()())' → [0,1,1,1,1,0].
💡 Key idea Split the parentheses into two groups so the larger nesting depth of the two is minimal: give each parenthesis to group (depth mod 2). The depth of a '(' is the nesting level after it opens; its matching ')' gets the same group.
Edge / failure case mixed depth → [0, 0, 0, 1, 1, 0, 0, 0]
Depth parity alternates in nested parentheses.
Why? colors 'abaac', times [1,2,3,4,5]: in 'aa' remove the cheaper one (3) → 3.
💡 Key idea Neighbouring balloons of the same colour are a problem. In every run of equal colours keep the balloon with the largest removal time and remove all the others; the cost is the run's sum minus its maximum.
Edge / failure case already colourful → 0
No neighbours share a colour: cost 0.
Why? [[1,2,3],[4,5],[1,2,3]] → 5 − 1 = 4.
💡 Key idea The best pair uses the minimum of one array and the maximum of another. Scan the arrays keeping the smallest first element and the largest last element seen so far (from earlier arrays) and test each array against them.
Edge / failure case equal → 0
Equal values give distance 0.
Why? number '123', digit '3' → '12'.
💡 Key idea The digit appears at a few positions. Remove each in turn and keep the largest resulting string (all candidates have the same length, so string comparison works).
Edge / failure case equal choices → '51'
Removing the second 5 gives 51, the first gives 51: ties are fine.
Why? n=4 path 0-1-2-3 → values 1,3,4,2 → 3 + 12 + 8 = 23.
💡 Key idea Every node has degree ≤ 2, so the connected graph is a path or a cycle. To maximise the sum of products, big numbers must be neighbours: line the values up with n in the middle, n−1 to its right, n−2 to its left, n−3 on the right … The arrangement is the same for a path; a cycle also joins the two ends (the values 1 and 2).
Edge / failure case cycle → 48
A cycle of five nodes.
Why? start 2, target 3: reverse 3 → 4 (add 1) → 2 (halve) = 2 steps.
💡 Key idea Going forward you can double or subtract 1. Reversed: from the target either halve (if even) or add 1 (if odd), until the target is at most the start; then the remaining gap is closed by decrements (start − target steps).
Edge / failure case 5 → 8 → 2
Halve, then fall back by decrements.
Why? [1,2,2,3,3,4], k=2 → 6 distinct values.
💡 Key idea Every element may change by at most k, i.e. take any value in [x−k, x+k]. Sort the numbers. Keep the last value used (cur); for the next number pick max(cur+1, x−k); if that is within x+k count it as a new distinct value.
Edge / failure case crowded → 3
Three values 3, 4, 5 are available for four numbers.
Why? (1,2) → (1,4) → (5,4) takes 2 moves.
💡 Key idea A move adds m = max(x, y) to one coordinate. Reverse it: from (X, Y) with X > Y, if X ≥ 2Y the last move doubled X (needs X even, previous x = X/2); otherwise the previous point was (X − Y, Y). Symmetric for Y > X. At X == Y the previous point was (0, Y) or (X, 0), only possible if the start has a zero. Stop on reaching the start, or return −1 when a coordinate drops below the start's.
Edge / failure case from the axis → 3
Start next to the axis.
Why? [5,1,-4] → three units from person 0 (distance 1) and one from person 1 (distance 1) = 4 moves.
💡 Key idea At most one person is negative. If the total is negative nothing works (−1). Otherwise the deficit must be covered by other people; a unit travelling d positions costs d moves. Take units from the nearest neighbours first: at distance d look at the two people d steps away on either side, take what they can give, add d per unit.
Edge / failure case both sides → 6
The deficit is covered from both sides.
Why? ['ca','bb','ac'] → delete column 0: 'a','b','c' sorted → 1.
💡 Key idea Go through the columns left to right, remembering which neighbouring pairs of strings are already strictly ordered by earlier kept columns. A column is kept if it never decreases for any still-tied pair; otherwise delete it. Kept columns that strictly order a pair mark it done.
Edge / failure case all columns → 0
Both columns must go.
Why? [[6,2],[4,4],[2,6]]: (2,6)–(4,4) and (4,4)–(6,2) work; (2,6)–(6,2) is blocked by (4,4) → 2.
💡 Key idea A pair (A, B) works if A is on the upper-left of B (x_A ≤ x_B and y_A ≥ y_B) and no other point lies in the rectangle they span. Sort points by x ascending then y descending. For each A, scan the points after it: B is valid only if its y is at most A's y and strictly above every y seen so far among valid candidates (otherwise an earlier point blocks it).
Edge / failure case diagonal → 0
The points rise to the right: nobody is upper-left of another.
Why? coins [1,4,10], target 19 → add 2 and 8 → 2.
💡 Key idea Keep reach = the largest amount such that every value 1…reach can be formed. Sort the coins. If the next coin is ≤ reach + 1 it extends the reach by its value; otherwise add a coin of value reach + 1 (doubling the reach). Continue until reach ≥ target.
Edge / failure case more coins → 1
Several coins.
Why? costs [1,3,2,4,1], 7 coins → 1,1,2,3 = 7 → 4 bars.
💡 Key idea To buy as many as possible, buy the cheapest first. Sort the costs and keep buying while the coins last.
Edge / failure case none → 0
No bar is affordable.
Why? [100,1,1000] → sorted [1,100,1000] → 1, 2, 3 → 3.
💡 Key idea The first element must be 1 and neighbours may differ by at most 1. Sort, set the first to 1 and cap every next element at previous + 1. The last element is the maximum possible.
Edge / failure case duplicates → 2
Sorted and capped: 1,1,2,2,... .
Why? rolls [4,2,1,2,3,3,2,4,1], k=4 → the first full set ends at index 3, the second at 6 → every length-2 sequence exists, a length-3 one does not → 3.
💡 Key idea Scan the rolls collecting distinct faces. Each time all k faces have been seen, one 'round' is complete (every sequence of that many rolls can be formed) and the set resets. If c rounds are complete, every sequence of length c exists, and some sequence of length c + 1 does not. Return c + 1.
Edge / failure case two rounds → 2
Two complete rounds: length 3 is impossible.
Why? 'xyzxyzxyzxyz' → 3 letters on 3 keys, each 1 push → 12.
💡 Key idea There are 8 keys. Each key can hold several letters; the j-th letter on a key costs j pushes. Sort letter frequencies in descending order: the first 8 letters cost 1 push each, the next 8 cost 2, and so on.
Edge / failure case twelve letters → 16
Twelve different letters: 8 cost 1, 4 cost 2.
Why? 'aA1' → needs 3 more characters → 3.
💡 Key idea A password is strong if it has 6–20 characters, a lowercase, an uppercase and a digit, and no three equal characters in a row. Count the missing character types and the runs of ≥ 3 equal characters. If length < 6: max(6 − n, missing). If length ≤ 20: max(missing, sum of run//3). If longer than 20: deleting characters can shorten runs cheaply (runs of length 3k need 1 deletion to save a replacement, 3k+1 need 2, …); the answer is the excess length plus the remaining replacements, at least the missing types.
Edge / failure case too long → 5
Too long with long runs.
Why? players [4,7,9], trainers [8,2,5,8] → 4↔5, 7↔8, 9 has none → 2.
💡 Key idea A player can use a trainer whose capacity is at least their ability. Sort both lists and go through the trainers: whenever the weakest unmatched player fits the trainer, match them. This keeps the strongest trainers for the hardest players.
Edge / failure case one trainer → 1
One trainer, many players.
Why? '?3295???' → Bob wins... the answer is true or false.
💡 Key idea The string has even length; the first half is Alice's side and the second half Bob's. Alice moves first and wants the halves to be unequal. If the total number of '?' is odd Alice wins (she makes the last choice). Otherwise Bob wins exactly when the difference of the known sums equals 9 · (question marks in the right half − in the left half) / 2.
Edge / failure case marks → False
Question marks on both sides.
Why? tokens [100,200,300,400], power 200 → play 100 (score 1), then... best score 2.
💡 Key idea Face-up a token to gain score for its cost in power; face-down a token to gain power for 1 score. Sort; use two pointers: while you can, buy the cheapest token (score +1); otherwise, if score > 0, sell the most expensive token for power (score −1). Track the best score.
Edge / failure case one token → 1
Only the cheaper token is affordable.
Why? dist [1,3,4], speed [1,1,1] → arrival times 1, 3, 4 → all 3 can be shot.
💡 Key idea Monster i reaches the city at time ceil(dist/speed). You shoot once per minute starting at minute 0, so the k-th shot (k = 0, 1, …) must happen before the k-th earliest arrival. Sort arrival times and count how many shots fit.
Edge / failure case too fast → 1
The first monster is too fast.
Why? [1,2,3] → squares 9, 4, 1: 2 plus slots, 1 minus → 9 + 4 − 1 = 12.
💡 Key idea Only the squares matter. In the alternating sum, ceil(n/2) values are added and floor(n/2) subtracted. Put the largest squares on the plus positions: sort the squares in descending order and add the first ceil(n/2), subtract the rest.
Edge / failure case signs → 16
Signs do not matter.
Why? n=46 can be rearranged to 64 = 2⁶ → true.
💡 Key idea Two numbers are rearrangements of each other if their sorted digits are equal. Precompute the sorted digit strings of 2⁰ … 2³⁰ and check whether n's sorted digits appear among them.
Edge / failure case false → False
Cannot make 01 or any power of two.
Why? n=3, k=3 → permutations 123, 132, 213, ... the 3rd is '213'.
💡 Key idea Each leading digit accounts for (n−1)! permutations. Convert k−1 to the factorial number system: at each position divide by (remaining−1)! to pick which unused digit comes next, and take the remainder.
Edge / failure case n = 4 → '2314'
2314.
Why? s='abcd', t='abcde' → the extra letter is 'e'.
💡 Key idea XOR (exclusive OR) all characters of both strings: every letter that appears in both cancels, leaving the added one.
Edge / failure case empty → 'y'
Empty s.
Why? 5 = 101 → complement 010 = 2.
💡 Key idea Build a mask of ones as long as n's binary form and XOR (exclusive OR) n with it. Zero is a special case (its complement is 1).
Edge / failure case zero → 1
Special case.
Why? 28 = 1 + 2 + 4 + 7 + 14 → true.
💡 Key idea A perfect number equals the sum of its positive divisors excluding itself. Find divisor pairs (d, n/d) up to √n.
Edge / failure case prime → False
Not perfect.
Why? n=9: left pass, right pass, left pass leaves 6.
💡 Key idea Each pass halves the list. Keep the first element of the remaining arithmetic progression, its step and the remaining count. Passing left always moves the head; passing right moves it only if the count is odd.
Edge / failure case n = 1 → 1
Only 1.
Why? Points (0,0),(0,1),(1,0),(0,2),(2,0): the largest triangle has area 2.
💡 Key idea Try every triple of points and compute the area with the cross-product (shoelace) formula |x1(y2−y3) + x2(y3−y1) + x3(y1−y2)| / 2.
Edge / failure case three points → 0.5
Half a unit square.
Why? n=1 → the next balanced number is 22.
💡 Key idea A number is numerically balanced if each digit d appears exactly d times. Starting at n + 1 test each number until one is balanced (balanced numbers are dense enough for n ≤ 10⁶).
Edge / failure case 1000 → 1333
1333.
Why? num=4, t=1 → x can be 6.
💡 Key idea Each operation moves x and num towards each other by 1 each, closing a gap of 2 per operation. So the largest achievable x is num + 2t.
Edge / failure case t = 2 → 7
7.
Why? n=3, m=2, k=1 → arrays like [1,1,2], [2,1,1] … 4.
💡 Key idea An array has k positions where a neighbour equals the previous one, so there are n−1−k positions where the value changes. Choose which of the n−1 neighbour pairs are equal: C(n−1, k). The first value has m choices and each change has m−1 choices: m · (m−1)^(n−1−k). Multiply modulo 1e9+7.
Edge / failure case n = 4 → 18
18.
Why? [2,5,6,9,10]: gcd(2, 10) = 2.
💡 Key idea The common divisors of the smallest and largest numbers are the common divisors of all of them for this problem's definition; return gcd(min, max).
Edge / failure case equal → 3
Equal numbers.
Why? [1,1,2] → ORs 1, 1, 2, 1, 3, 3 → distinct {1,2,3} → 3.
💡 Key idea For subarrays ending at i keep the set of their OR values; it has at most ~30 elements because OR only adds bits. Extend each by arr[i] and add arr[i] itself. Collect all values in a global set.
Edge / failure case distinct bits → 6
1, 2, 3, 4, 6, 7.
Why? [4,3,2,6]: F(0)=25, F(1)=16, F(2)=23, F(3)=26 → 26.
💡 Key idea F(k) = Σ i · arr_k[i] for the array rotated k times. Going from F(k−1) to F(k): F(k) = F(k−1) + sum(nums) − n · nums[n − k]. Compute F(0), update n−1 times and keep the maximum.
Edge / failure case single → 0
A single value.
Why? [0,0,2,2] and [1,1,3,3] overlap in a 1×1 square → true; touching edges do not count.
💡 Key idea Two axis-aligned rectangles overlap with positive area exactly when their x-intervals overlap and their y-intervals overlap (strictly): min(x2) > max(x1) and min(y2) > max(y1).
Edge / failure case touching → False
They only touch.
Why? Between 1 and 100 the symmetric integers are 11, 22, …, 99 → 9.
💡 Key idea An integer with an even number of digits is symmetric if the sum of the first half equals the sum of the second half. Check every number in the range.
Edge / failure case four digits → 4
4.
Why? [1,0,2,1,3] → [3,3,2,2,1].
💡 Key idea For each start i the maximum OR over subarrays starting at i equals the OR of nums[i:]. The shortest subarray achieving it must reach the latest 'first occurrence' of every bit: keep last[b] = nearest index ≥ i containing bit b (scanning from the right) and take max(last) − i + 1.
Edge / failure case two numbers → [2, 1]
[2, 1].
Why? 16 = 4² → true; 8 is a power of two but not four → false.
💡 Key idea A power of four has exactly one set bit, and that bit is at an even position. So n > 0, n & (n−1) == 0 and n & 0x55555555 != 0.
Edge / failure case false → False
Power of two only.
Why? 9669 → change the first 6: 9969.
💡 Key idea Changing a digit from 6 to 9 gains the most when done at the highest position. Replace the first '6' in the number by '9' (nothing changes if there is none).
Edge / failure case all nines → 9999
Already max.
Why? num1=3, num2=−2: three operations (each subtracts 2^i − 2) reach 0.
💡 Key idea After k operations num1 − k·num2 must be written as a sum of exactly k powers of two. That is possible iff x = num1 − k·num2 ≥ k and the number of set bits of x is ≤ k. Try k = 1 … 60.
Edge / failure case no way → -1
Impossible.
Why? turnedOn=1: 0:01, 0:02, 0:04, 0:08, 0:16, 0:32, 1:00, 2:00, 4:00, 8:00.
💡 Key idea The watch has 4 hour LEDs and 6 minute LEDs. Loop over all hours 0–11 and minutes 0–59 and keep the times where the number of set bits in the hour plus in the minute equals turnedOn.
Edge / failure case too many LEDs → []
No valid time.
Why? n=25 → reverse 52 → distance 27.
💡 Key idea Reverse the digits of n and return the absolute difference with n.
Edge / failure case trailing zero → 9
10 − 1 = 9.
Why? n=15, t=3: 15 → product 5 no; 16 → 6 divisible by 3 → 16.
💡 Key idea Test n, n+1, … until the product of the digits is divisible by t. A zero digit makes the product 0 (divisible by everything), so the loop ends within a few steps.
Edge / failure case already works → 10
10 already works.
Why? [1,2,3,4] → 1, 2 and 4 are one step from a multiple of 3 → 3.
💡 Key idea Adding or subtracting 1 turns any number that is not a multiple of 3 into one, so the answer is the number of elements with a non-zero remainder.
Edge / failure case none → 0
Already divisible.
Why? n=3, x=4: the sequence 4, 5, 6 has AND 4; the last element is 6.
💡 Key idea Every element must contain all bits of x, so only the zero bits of x can vary. The i-th smallest valid number fills the zero bits of x with the binary digits of i (i = 0 is x itself). The last element corresponds to i = n − 1: deposit its bits into the free positions, lowest first.
Edge / failure case x = 7 → 15
15.
Why? 5 → 10; 6 → 6.
💡 Key idea The smallest positive number divisible by both 2 and n is n when n is even and 2n otherwise.
Edge / failure case already even → 6
6.
Why? n=3 → 13 cells (a diamond).
💡 Key idea After n minutes the coloured area is a diamond made of two nested squares: n² + (n−1)² cells.
Edge / failure case n = 1 → 1
1.
Why? n=10, m=3: non-multiples sum 37, multiples (3+6+9) sum 18 → 19.
💡 Key idea Sum the numbers 1…n that are not divisible by m and subtract the sum of those that are.
Edge / failure case m > n → 15
15.
Why? 14 → 7 → 6 → 3 → 2 → 1 → 0: 6 steps.
💡 Key idea Each 1 bit costs one subtraction and each shift costs one division. The answer is bit_length − 1 + popcount (for n > 0), 0 for n = 0.
Edge / failure case power of two → 4
Another sample input.
Why? queries [[1,2],[2,4]]: totals of steps 2 and 4 → 1 + 2 = 3 operations.
💡 Key idea One operation divides two numbers by 4, so each number needs d(x) = number of base-4 digits of x steps. The minimum operations for a range is ceil(sum of d(x) / 2). Sum d(x) over [l, r] by splitting the range into blocks [4^k, 4^(k+1) − 1] where d = k + 1.
Edge / failure case one query → 4
Another sample input.
Why? 234: product 24 − sum 9 = 15.
💡 Key idea Walk the digits, multiplying and adding; return product − sum.
Edge / failure case second sample → 21
Another sample input.
Why? n=4: odd sum 16, even sum 20 → gcd 4.
💡 Key idea The sum of the first n odd numbers is n² and of the first n even numbers is n(n+1). Their gcd is n · gcd(n, n+1) = n.
Edge / failure case n = 5 → 5
Another sample input.
Why? n=3 → '1' '10' '11' = 11011 = 27.
💡 Key idea Build the number left to right: result = (result << bit_length(i)) | i for i = 1 … n, modulo 1e9+7.
Edge / failure case n = 12 → 505379714
Large value modulo 1e9+7.
Why? n=4 has divisors 1, 2, 4 → true.
💡 Key idea A number has exactly three divisors only if it is the square of a prime. Count its divisors up to √n.
Edge / failure case prime → False
Only two divisors.
Why? n=1002: 1,000, 1,001, 1,002 → 3 commas.
💡 Key idea With n up to 10⁵ every number from 1000 to n has exactly one comma and smaller numbers have none, so the answer is max(0, n − 999).
Edge / failure case no commas → 0
No number reaches 1000.
Why? n=2 (numbers below 100): 91 numbers have no repeated digit.
💡 Key idea Numbers with exactly k digits (k ≥ 2) and no repeated digit: 9 choices for the first digit, then 9, 8, 7 … for the rest. Sum these over lengths 1…n plus 1 for the number 0.
Edge / failure case n = 0 → 1
Only the number 0.
Why? [1,2,3,3,2,2] → the maximum 3 appears twice in a row → 2.
💡 Key idea The AND of a subarray is at most its minimum, and the largest possible AND equals the array maximum (achieved by subarrays of maximum values). So the answer is the longest run of consecutive copies of the maximum.
Edge / failure case all equal → 4
Every element is the maximum.
Why? ['01','10'] → flip the diagonal bits to get '11', which differs from both.
💡 Key idea Build a string whose i-th character is the opposite of the i-th character of the i-th given string. It differs from each given string in at least one position.
Edge / failure case length three → '000'
Three strings of length three.
Why? 12 = 3 + 9 → true; 21 has a base-3 digit 2 → false.
💡 Key idea Each power of three can be used at most once, so n is such a sum exactly when its base-3 representation has only 0s and 1s.
Edge / failure case 91 → True
91 = 81 + 9 + 1.
Why? k=5, ops [0,0,0] → word becomes 'aaaaaaaa' → 'a'.
💡 Key idea After each operation the word doubles; the second half is a copy of the first (shifted by one letter for an operation of type 1). Work backwards: if k lies in the second half, move it to the first half and add the shift of that operation. The count of shifts mod 26 gives the letter.
Edge / failure case no shift → 'a'
Only doubling operations: the letter stays 'a'.
Why? 'a1' and 'c3' are both dark → true.
💡 Key idea A square's colour is decided by the parity of (column index + row number). Compare the two parities.
Edge / failure case different colours → False
Different colours.
Why? n=4, time=5 → 1,2,3,4,3,2 → person 2.
💡 Key idea The pillow goes from 1 to n and back, a full cycle of 2(n−1) seconds. Reduce time modulo the cycle length t; if t ≤ n−1 the holder is 1 + t, otherwise n − (t − (n−1)).
Edge / failure case reaches the end → 3
The pillow reaches the last person.
Why? n=3, m=2 → the pairs with odd sum: (1,2),(2,1),(3,2) → 3.
💡 Key idea Alice wins exactly when the total number of flowers x + y is odd. Count the pairs with x in 1…n and y in 1…m and odd sum: (odd x, even y) plus (even x, odd y) = (n+1)//2·(m//2) + (n//2)·((m+1)//2), which equals n·m // 2.
Edge / failure case 1 × 1 → 0
x + y = 2 is even: Alice cannot win.
Why? x=2, y=7, z=4 → |2−4| = 2, |7−4| = 3 → person 1 arrives first.
💡 Key idea Person 1 needs |x − z| steps and person 2 needs |y − z|. Return 1, 2 or 0 (tie).
Edge / failure case person 1 → 1
Person 1 is closer than person 2.
Why? 526 → 625 → 526: true; 1800 → 81 → 18: false.
💡 Key idea Reversing drops trailing zeros (they become leading zeros). So the number comes back unchanged exactly when it is 0 or does not end in 0.
Edge / failure case trailing zeros → False
The trailing zeros are lost.
Why? K=3 → 111 is divisible by 3 → length 3.
💡 Key idea We only need the remainder of the repunit (1, 11, 111, …) modulo K: next = (rem·10 + 1) % K. If K is even or a multiple of 5 the answer is −1; otherwise a remainder of 0 appears within K steps (pigeonhole), and that step count is the length.
Edge / failure case even K → -1
An even K can never divide a number ending in 1.
Why? [10,10,3,7,6] → total 36 is even → all 4 cut positions work.
💡 Key idea left − right = 2·left − total, so its parity equals the parity of the total sum. If the total is even every cut works (n − 1 cuts), otherwise none does.
Edge / failure case odd total → 0
The total is odd: no cut works.
Why? [[1,0],[2,0],[3,0],[2,2],[3,2]] → 3 trapezoids.
💡 Key idea A horizontal trapezoid has two horizontal sides on two different heights. For a height with c points there are c(c−1)/2 possible horizontal segments. Choose two segments from two different heights: sum over height pairs of seg(a)·seg(b), computed with a running sum, modulo 1e9+7.
Edge / failure case two rows → 1
Two rows with one segment each.
Why? 'SSPPSPS' → 3 ways.
💡 Key idea Each section needs exactly two seats. If the seat count is 0 or odd the answer is 0. Otherwise seats pair up (1–2, 3–4, …); a divider can go in any gap between the second seat of a pair and the first of the next, so multiply (plants + 1) for each such gap, modulo 1e9+7.
Edge / failure case plants outside → 1
Plants outside the seats do not matter.
Why? n=5 → (3,4,5) and (4,3,5) → 2.
💡 Key idea Count ordered (a, b, c) with a² + b² = c² and everything ≤ n. Loop over a and b, compute the sum and check that it is a perfect square not above n².
Edge / failure case n = 10 → 4
(3,4,5) and (6,8,10) in both orders.
Why? [2,3,5,7] → [-1,1,4,3].
💡 Key idea We need the smallest a with a | (a + 1) == x. Adding 1 to a turns its trailing run of 1s into 0s and sets the next 0, so x must end in a run of at least one 1 (x odd). The minimum a is x with the top bit of that trailing run of 1s cleared: x − 2^(t−1), where t is the length of the run. Even x has no answer: −1.
Edge / failure case trailing runs → [9, 12, 15]
Odd numbers with different trailing runs.
Why? 22 = 10110 → 1s at positions 4, 2, 1 → largest gap 2.
💡 Key idea Scan the bits of n from the lowest. Remember the position of the last 1 seen; each new 1 gives a gap of (position − last). Track the maximum.
Edge / failure case single 1 → 0
A single 1 bit has no gap.
Why? 145 → 1! + 4! + 5! = 145 → true.
💡 Key idea A digitorial number equals the sum of the factorials of its digits. Only four exist: 1, 2, 145 and 40585. A permutation of n (not starting with 0) is one of these exactly when n has the same multiset of digits as one of them.
Edge / failure case no → False
No permutation of 10 is digitorial.
Why? 100 → 202 (2·49 + 0·7 + 2).
💡 Key idea Divide by 7 repeatedly, collecting remainders; they are the digits from the least significant. Handle zero and negative numbers separately.
Edge / failure case negative → '-10'
A negative number.
Why? [2,3,4] → pair gcds sorted [1,1,2] → queries 0, 2, 2 → [1,2,2].
💡 Key idea For each g, count the numbers divisible by g, c, and the pairs among them c(c−1)/2; subtract the pairs whose gcd is a larger multiple of g (go from large g to small). That gives exact[g] = number of pairs with gcd exactly g. Prefix-sum exact[1…max]; a query q is answered by the first g whose prefix exceeds q (binary search).
Edge / failure case repeated → [4, 2, 1, 1]
Repeated values.
Why? [1,3] → XORs of triplets (i ≤ j ≤ k): 1, 3, 1^1^3 = 3, 1^3^3 = 1 ... → 2 distinct values.
💡 Key idea A triplet i ≤ j ≤ k can repeat indices, so the set of all XORs of two numbers (including a with itself, which gives 0) combined with any third number covers every triplet. Build the set of pair XORs, then XOR (exclusive OR) each with each number; the answer is the size of the resulting set.
Edge / failure case five values → 8
Several values.
Why? [2,6,4] → prefixGcd [2,6,2] → sorted [2,2,6] → gcd(2,6) = 2.
💡 Key idea prefixGcd[i] = gcd(nums[i], maximum of nums[0..i]). Sort it, pair the smallest with the largest, the second smallest with the second largest, and so on (the middle element of an odd list is ignored); add up the gcd of every pair.
Edge / failure case pair of two → 4
Two numbers.
Why? [1,2,3] → total XOR (exclusive OR) is 0, so drop one element → 2.
💡 Key idea If the XOR of the whole array is non-zero, take everything. If it is zero, removing any one non-zero element makes the XOR non-zero (it becomes that element), giving n − 1. If every element is zero no subsequence works: 0.
Edge / failure case all zeros → 0
All zeros.
Why? arr [1,4,1,3], k=2 → positions 0,2 must match and 1,3 must match → 1.
💡 Key idea In the circular array every window of k elements must have the same sum, which forces arr[i] = arr[i + k] (indices modulo n). Elements split into gcd(n, k) cycles, and each cycle must become constant. The cheapest way to equalise a cycle is to move all its values to their median; add the costs.
Edge / failure case k = 3 → 5
k = 3 with n = 4.
Why? main 5, additional 10 → 5 L → 50 km, +1 L → 10 km → 60.
💡 Key idea The truck does 10 km per litre. Each time 5 litres are used and the additional tank has fuel, 1 litre moves into the main tank. Simulate in chunks of 5 litres (or with the closed form min((main − 1) // 4, additional)).
Edge / failure case short → 10
Less than 5 litres in the main tank.
Why? low 3, high 7 → 3, 5, 7 → 3.
💡 Key idea The number of odd numbers in [1, x] is (x + 1) // 2, so the count in [low, high] is (high + 1) // 2 − low // 2.
Edge / failure case even start → 1
The range starts on an even number.
Why? ranges [[1,2],[3,4],[5,6]] cover 2..5 → true.
💡 Key idea Put every number covered by any range into a set (the limits are small) and test that every integer in [left, right] is in it.
Edge / failure case not covered → False
21 is not covered.
Why? Four rectangles that separate cleanly into three groups by two horizontal cuts → true.
💡 Key idea Two parallel cuts (both horizontal or both vertical) must split the rectangles into three non-empty groups with none crossing a cut. Project the rectangles on one axis, sort and merge overlapping intervals; if at least three merged groups remain you can cut between them. Try both axes.
Edge / failure case impossible → False
false.
Why? Alice 08-15…08-18, Bob 08-16…08-19: they overlap on 16, 17, 18 → 3.
💡 Key idea Convert each 'MM-DD' to a day number in the year (non-leap). The shared days are between max of the arrivals and min of the departures; if that interval is empty the answer is 0.
Edge / failure case disjoint → 0
No overlap.
Why? eventTime 5, meetings [1,2] and [3,5]: moving [1,2] to the end leaves a free stretch of 2 → 2.
💡 Key idea Compute the n+1 gaps between meetings (and the event edges). Removing meeting i merges the two gaps around it. Its duration can be put back either inside the merged hole (then the free time is both gaps) or, if some other gap is at least its duration long, anywhere else (then the free time is both gaps plus the duration). Use prefix/suffix maxima of the gaps to know the largest other gap.
Edge / failure case second sample → 7
Another sample input.
Why? [[1,4],[3,6],[2,8]]: [1,4] and [3,6] are covered by [2,8]? only [3,6] → 2 remain.
💡 Key idea Sort by start ascending and end descending. Sweep keeping the largest end seen; an interval whose end is not beyond that is covered by an earlier one. Count the intervals that extend the reach.
Edge / failure case nested → 1
Another sample input.
Why? days 10, meetings [5,7],[1,3],[9,10] → busy days 1–3, 5–7, 9–10 → 2 free days.
💡 Key idea Sort the meetings by start, merge overlapping ones while counting the busy days, and subtract from the total number of days.
Edge / failure case overlap → 1
Overlapping meetings.
Why? [3,10,5,25,2,8] → 5 XOR (exclusive OR) 25 = 28.
💡 Key idea Build the answer from the highest bit down. At each bit take the set of all prefixes (numbers shifted right) and test whether the candidate answer with this bit set is achievable: there are prefixes a, b with a XOR (exclusive OR) b = candidate (check candidate XOR a in the set).
Edge / failure case larger sample → 127
127.
Why? A 1×4 grid starting at (0,0): the spiral visits (0,0),(0,1),(0,2),(0,3).
💡 Key idea Walk a spiral outward from the start: segments of length 1,1,2,2,3,3,… turning right each time (east, south, west, north). Record every visited cell that lies in the grid until all rows × cols cells are collected.
Edge / failure case mid start → [[1, 4], [1, 5], [2, 5], [2, 4], [2, 3], [1, 3], [0, 3], [0, 4], [0, 5], [3, 5], [3, 4], [3, 3], [3, 2], [2, 2], [1, 2], [0, 2], [4, 5], [4, 4], [4, 3], [4, 2], [4, 1], [3, 1], [2, 1], [1, 1], [0, 1], [4, 0], [3, 0], [2, 0], [1, 0], [0, 0]]
Starts mid-grid.
Why? [[1,0,1],[1,1,0],[1,1,0]] contains 13 all-ones submatrices.
💡 Key idea Let h[j] be the number of consecutive ones above (and including) the current row in column j. For each row and each column j count the rectangles whose bottom-right corner is (row, j): extend leftwards keeping the minimum height and add it up.
Edge / failure case second sample → 24
24.
Why? [[0,1],[1,0]] → both rows have one 1 → [0, 1].
💡 Key idea Count the ones in each row and return [row index, count] for the row with the most ones (the smallest index on ties).
Edge / failure case second row → [1, 2]
[1, 2].
Why? The sample 3×4 grid contains one 3×3 magic square (1–9 each once, all lines sum to 15).
💡 Key idea A 3×3 magic square of the numbers 1–9 must have 5 in the centre, hold each of 1–9 exactly once, and all rows, columns and both diagonals sum to 15. Test each window.
Edge / failure case tiny → 0
Too small.
Why? [[0,0,1],[1,1,1],[1,0,1]] → rearrange columns to get a 2×2 block of ones → 4.
💡 Key idea Columns can be reordered freely. For each row compute the heights of consecutive ones ending there, sort the heights descending, and the best rectangle in this row has area max over j of height[j] × (j + 1).
Edge / failure case single row → 3
Another sample input.
Why? [[1,2,3],[4,5,6],[7,8,9]], k=1 → [[9,1,2],[3,4,5],[6,7,8]].
💡 Key idea Shifting k times moves every cell k places forward in row-major order (wrapping). Flatten the grid, rotate the list right by k mod (m·n), and cut it back into rows.
Edge / failure case single column → [[3], [1], [2]]
Shifts bigger than the grid wrap around.
Why? Sliding the first image one step right and one down overlaps three 1s → 3.
💡 Key idea Slide one image over the other by every possible shift. For two 1-cells (one from each image) the shift that aligns them is their coordinate difference; count how many pairs give each shift and take the largest count.
Edge / failure case one cell → 1
A single pixel overlaps itself.
Why? [[1,2,3],[4,5,6],[7,8,9]] → 1 + 5 + 9 + 3 + 7 = 25.
💡 Key idea Add mat[i][i] and mat[i][n−1−i] for every row; for odd n the centre cell is counted twice, so subtract it once.
Edge / failure case single cell → 5
The only cell is the centre.
Why? [[1,1,0],[1,0,1],[0,0,0]] → flip rows → [[0,1,1],[1,0,1],[0,0,0]] → invert → [[1,0,0],[0,1,0],[1,1,1]].
💡 Key idea Flipping a row reverses it, inverting turns 0 into 1 and 1 into 0. Doing both: output cell j of a row is 1 − input cell (n−1−j).
Edge / failure case 4 × 4 → [[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0]]
A 4×4 image.
Why? A guard sees along its row and column until a wall or another guard; free cells nobody sees are unguarded.
💡 Key idea Create a grid with the guards and walls marked. From each guard walk in the four directions, marking free cells as guarded, and stop at a wall or another guard. The unguarded cells are the free cells never marked.
Edge / failure case one guard → 4
One guard in the middle.
Why? 3 × 3, ops [[2,2],[3,3]] → the cell block 2 × 2 is added to most → 4.
💡 Key idea Each operation adds 1 to the top-left a × b block. The cells incremented by every operation form the overlap, a rectangle of size min(a) × min(b); its area is the count of maximum values (the whole matrix if there are no operations).
Edge / failure case no ops → 9
No operations: every cell is maximal.
Why? mat [[0,1],[1,0]], target [[1,0],[0,1]] → rotate once → true.
💡 Key idea Rotate the matrix by 90° up to four times and compare with the target after each (zip the reversed rows).
Edge / failure case three turns → True
Rotate by 270°.
Why? [[1,2],[3,4]], rowShift [1,0], colShift [0,1] → [[2,4],[3,1]].
💡 Key idea Row i is rotated left by rowShift[i] (element at column j moves to (j − k) mod n). Then column j is rotated up by colShift[j]. Do the two steps in order.
Edge / failure case columns only → [[7, 8], [5, 6]]
Only columns shift.
Why? Customer 45 checks in at Leyton at t=3 and out at Waterloo at t=15: that trip takes 12.
💡 Key idea Store each customer's check-in (station, time). On check-out compute the trip time and add it to the total and count of the route (start, end). The average is total / count.
Edge / failure case two trips → [None, None, None, None, 5.5]
Two trips of 5 and 6.
Why? insert(3,'c') → [], insert(1,'a') → ['a'], insert(2,'b') → ['b','c'].
💡 Key idea Keep an array of n slots and a pointer to the next id expected. insert stores the value, then returns the longest run of filled slots starting at the pointer and advances the pointer.
Edge / failure case n = 1 → [['a']]
Single element.
Why? Dictionary ['hello','leetcode']: 'hhllo' is one letter away from 'hello' → true; 'hello' itself is not (needs exactly one change).
💡 Key idea For every word and every position store the word with that position replaced by '*' together with the original letter. A search word matches if some wildcard form of it was stored from a word with a different letter at that position.
Edge / failure case single letters → [None, True, True]
'c' is one change from 'a' or 'b'; 'a' needs exactly one change.
Why? A 5×5 grid: sumRegion(2,1,4,3) = 8; after update(3,2,2) it is 10.
💡 Key idea A 2D binary indexed tree stores partial rectangle sums. Update adds the delta at (r, c) along both index chains; a prefix query sums along the chains. A region sum is inclusion–exclusion of four prefix queries.
Edge / failure case single cell → [1, None, 5]
A single cell.
Why? Add tasks, ask for pending ones sorted by due date, filter by tag, complete some.
💡 Key idea Keep tasks by id (description, due date, tags, done flag, owner) and for each user the list of their task ids. The getters filter the user's pending tasks (optionally by tag) and sort by due date; completeTask marks the task done only if it belongs to that user.
Edge / failure case complete → [1, None, []]
The task is completed.
Why? votes at times [0,5,10,15,20] for persons [0,1,1,0,0]: at t=3 the leader is 0, at t=12 it is 1.
💡 Key idea Process the votes once in time order, tracking counts and the current leader (ties go to the most recent voter). Store the leader after each vote. A query q(t) binary searches the last vote time ≤ t and returns the stored leader.
Edge / failure case single vote → [0, 0]
A single vote.
Why? add(1), add(2), contains(1) → true, contains(3) → false, remove(2), contains(2) → false.
💡 Key idea Use a fixed number of buckets (lists); an element goes to the bucket of key % size. add checks for presence first, remove deletes it, contains scans the bucket.
Edge / failure case same bucket → [None, None, None, True, False]
Two keys share a bucket.
Why? append 2, addAll 3, append 7, multAll 2, getIndex(0) → 10.
💡 Key idea Every element ends up as value·mul + add after all addAll / multAll calls. Keep the global (mul, add) and, for each appended value, store the value that will give the right result after the current global transform: x' = (x − add) · mul⁻¹ (modular inverse via pow). getIndex(i) returns stored[i]·mul + add, modulo 1e9+7.
Edge / failure case past the end → [None, None, None, None, 8, 7, -1]
An index past the end returns −1.
Why? add (3,10), (11,2), (3,2); count (11,10) → 1 square.
💡 Key idea Store how many times each point was added. To count squares with the query point (x, y) as one corner, look at every stored point (px, py) that could be the opposite corner: |px − x| == |py − y| > 0. The other two corners are (x, py) and (px, y); multiply the three counts.
Edge / failure case unit square → [None, None, None, None, 1, 0]
One unit square.
Why? add 1, 3, 7, 2, 6 → intervals [1,3], [6,7].
💡 Key idea Keep the disjoint intervals sorted by start. Adding a value: binary search its position, and either it is already inside an interval, extends a neighbour by one, joins two neighbours, or becomes a new single-value interval.
Edge / failure case merge → [None, None, None, [[4, 6]], None, [[4, 6]]]
Adding next to existing intervals merges them.
Why? Triangle 0-1-2: 0 reaches 2 → true.
💡 Key idea Union the endpoints of every edge; source and destination are connected exactly when they have the same root.
Edge / failure case disconnected → False
Two separate groups.
Why? [5,2,6,1] → [2,1,1,0].
💡 Key idea Scan from the right. Keep a Fenwick tree (counts per compressed value). For each number ask how many already-inserted values are smaller, then insert it.
Edge / failure case equal → [0, 0]
Equal values do not count.
Why? Roads (1-2:9, 2-3:6, 2-4:5, 1-4:7): the cheapest road reachable from city 1 weighs 5.
💡 Key idea A path may revisit cities and edges, so the best score is the smallest road weight in the connected component that contains both city 1 and city n (they are guaranteed connected). Union the endpoints and take the minimum weight among roads in city 1's component.
Edge / failure case shortcut → 2
The cheapest road is 2.
Why? fruits [4,2,5], baskets [3,5,4]: 4→5, 2→3, 5 has no basket → 1 unplaced.
💡 Key idea For each fruit in order take the leftmost unused basket whose capacity is at least the fruit size. A segment tree storing the maximum capacity per range lets us descend to the leftmost sufficient basket in O(log n), then set that leaf to 0.
Edge / failure case all placed → 0
All placed.
Why? source [1,2,3,4], target [2,1,4,5], swaps (0,1),(2,3) → hamming distance 1.
💡 Key idea Indices connected by allowed swaps can be permuted arbitrarily. Group them with Union-Find; within a group count how many source values can match target values (multiset intersection). The distance is n minus the total matches.
Edge / failure case all fixable → 0
Another sample input.
Why? nums [2,5,6,8], maxDiff 2: components {0}, {1,2,3} → query (1,3) true.
💡 Key idea Nodes i and j are adjacent if |nums[i] − nums[j]| ≤ maxDiff and nums is sorted, so connected components are contiguous index ranges: start a new component whenever two consecutive values differ by more than maxDiff. A query is true when both nodes share a component id.
Edge / failure case tiny → [True, False]
Another sample input.
Why? nums1 [2,0,1,3], nums2 [0,1,2,3] → the only good triplet is (0,1,3) → 1.
💡 Key idea A triplet of values (x, y, z) is good if they appear in the same order in both arrays. Map each value to its position in nums2. Scan nums1: for value v at nums2-position p, the number of earlier values with a smaller position is a Fenwick-tree prefix count (left), and the values still to come with a larger position = (n − 1 − p) − (earlier values with a larger position). The middle element contributes left × right.
Edge / failure case five values → 4
A longer pair of orderings.
Why? s1 'parker', s2 'morris', base 'parser' → 'makkek'.
💡 Key idea Letters s1[i] and s2[i] are equivalent. Merge them with union-find, always making the smaller letter the root. Replace every letter of baseStr with the root of its group.
Edge / failure case chains → 'hdld'
Chains of equivalent letters.
Why? vals [1,3,2,1,3], a tree → 6 good paths.
💡 Key idea A good path starts and ends at equal values and never passes a larger value. Process the edges ordered by the larger endpoint value. Union two components when joined; whenever two components with the same maximum value merge, the pairs of equal-maximum nodes become good paths: add count_a · count_b and keep the merged count. Add one path per node for single-node paths.
Edge / failure case blocked → 7
Equal values joined through a larger node do not count.
Why? nums [1,8,3,4,2], maxDiff 3: nodes 0 and 3 are directly linked → distance 1.
💡 Key idea Nodes i and j are linked if their values differ by at most maxDiff. Sort the nodes by value: from sorted position p you can reach every position up to reach[p]. The shortest path between two positions is a sequence of greedy jumps to the farthest reachable position. Precompute reach, then build binary-lifting tables (jump 2^k greedy steps) and answer each query by taking the largest jumps that stay short of the target.
Edge / failure case chain → [-1, -1, 2, 1]
A chain of nodes.
Why? s '0100', queries [[0,3],[0,2],[1,3]] → [4,3,1].
💡 Key idea Split s into blocks of equal characters. For each block of 1s with two zero neighbours, value = sum of the neighbour lengths. For a query only the first and last blocks are clipped by the range; the blocks in between are whole. Take the best of (a) the 1-blocks next to the clipped ends, computed with clipped lengths, and (b) the whole interior blocks, via a sparse table range maximum.
Edge / failure case no trade → [1]
No 1-block has zeros on both sides.
Why? s 'babacc', updates 'b'→1, 'a'→3, 'a'→... after each, the longest run length.
💡 Key idea Each segment tree node keeps its left character, right character, the length of the run touching its left end (prefix), touching its right end (suffix), the best run inside, and its size. Merging two children joins the right suffix of the left child with the left prefix of the right child when those characters are equal. A point update recomputes O(log n) nodes; the root's best is the answer.
Edge / failure case two updates → [2, 3]
Updates change the longest run.