Longest Sub{string,array}
Longest Consecutive x with k impurities (1-pass)
while shrink
1004. Max Consecutive Ones III
The challenge is to find the maximum number of consecutive 1's in the array nums after flipping at most k zeros to 1's. This is solved using a variable-size sliding window that dynamically adjusts to include as many 1's as possible while allowing up to k zeros within the window.
Expansion:
- Increment the
rightpointer to expand the window, increasing thezeroscounter if the current element is a zero.
Shrinking:
- If the
zeroscount exceedsk, increment theleftpointer to shrink the window from the left, decrementing thezeroscounter if a zero leaves the window.
Logic:
- After each adjustment, calculate the current window's length (
right - left). Updatemaxito keep track of the maximum length found.
- Time
- O(N)
- The algorithm iterates through each element of
numsonce, with each element being considered for inclusion in the window exactly once. - Space
- O(1)
- Constant extra space is utilized, with variables to track the window boundaries (
leftandright), the count of zeros within the window (zeros), and the maximum window length found (maxi).
487. Max Consecutive Ones II
This problem extends "Max Consecutive Ones" by allowing for at most one zero to be flipped to one. It can be directly solved by applying the generic longestAllowed approach with allowed = 1 and k = 1.
- Time
- O(N)
- A single pass through the array with efficient sliding window adjustments.
- Space
- O(1)
- Constant extra space is utilized.
485. Max Consecutive Ones
The problem seeks to identify the longest sequence of consecutive 1's in the given binary array nums. This is the simplest case where no impurities (0's) are permitted in the sequence (k = 0).
- Time
- O(N)
- A single traversal through the array.
- Space
- O(1)
- Constant space for a fixed number of variables.
1493. Longest Subarray of 1's After Deleting One Element
This problem seeks the longest subarray of 1's achievable by removing exactly one element from a binary array nums. The window allows at most one zero (k = 1). The length of the subarray after deletion equates to right - left - 1, accounting for the removal of one element.
If nums consists entirely of 1's, removing one element (a 1) results in a subarray one element shorter than the original array (n - 1).
- Time
- O(N)
- A single traversal through
nums. - Space
- O(1)
- Constant space.
Longest Consecutive x with k impurities (>1-pass)
while shrink
1869. Longer Contiguous Segments of Ones than Zeros
Determine if the longest contiguous segment of 1's is longer than the longest contiguous segment of 0's. Solved by finding the longest consecutive sequence of each value with k = 0, then comparing.
- Time
- O(2n)
n = len(s).checkZeroOnescallslongestAllowedtwice, once for"0"and once for"1"; each call'sleft/righttwo-pointer scan visits every index once - two separateO(n)passes overs, giving2n.- Space
- O(1)
- Only scalar counters (
left,right,count,maxi) are tracked; nothing scales withn.
2024. Maximize the Confusion of an Exam
Find the maximum number of consecutive same answers achievable by flipping at most k answers. Run longestAllowed once targeting 'T' and once targeting 'F', then take the maximum.
- Time
- O(2N)
longestAllowedis a linear two-pointer sweep,O(N), run once targeting'T'and once targeting'F'- two separateO(N)passes overanswerKey.- Space
- O(1)
- Only scalars (
count,maxi,left,right) are tracked; no structure grows withN.
424. Longest Repeating Character Replacement
This one-pass solution uses a sliding window and a counter to track character frequencies within the window. The number of replacements needed equals window_length - max_frequency. The window shrinks whenever this exceeds k.
- Time
- O(26N)
characterReplacementcallslongestAllowedonce per uppercase letter, and each call runs its ownO(N)sliding window over the string - 26 passes total.- Space
- O(1)
- Only
count,maxi, and the pointers are tracked - no structure grows withN.
2831. Find the Longest Equal Subarray
After deleting at most k elements, the longest equal subarray is the longest window whose impurity (elements that are not the most frequent value) is at most k. A counter tracks frequencies in the window and max_freq is the count of the dominant value. The impurity equals window_length - max_freq; whenever it exceeds k, the window shrinks. The answer is the largest max_freq seen.
- Time
- O(N)
- Each element is added and removed from the window at most once.
- Space
- O(N)
- The counter holds at most one entry per distinct value.
Hashmap - Unique Elements
while shrink
3. Longest Substring Without Repeating Characters
Find the length of the longest substring without any repeating characters. A sliding window with a counter tracks character frequencies. The window shrinks whenever a duplicate is detected (when the number of unique keys in the counter is less than the window length).
- Time
- O(n)
- Single pass through the string of length
n, with each character considered exactly once. - Space
- O(26)
- The counter tracks character frequencies; at worst case,
scan contain all lowercase alphabets.
1695. Maximum Erasure Value
Can be restated as "Find the maximum sum of subarray with unique elements". A sliding window with a counter tracks element uniqueness while maintaining a running total. The window shrinks whenever a duplicate is found.
- Time
- O(n)
- Single pass through
nums(lengthn);leftandrighteach advance at mostnsteps. - Space
- O(n)
countercan hold up tonunique elements.
Hashmap - K Distinct Elements
while shrink
340. Longest Substring with At Most K Distinct Characters
Find the length of the longest substring that contains at most k distinct characters. A sliding window with a counter tracks character frequencies. The window shrinks whenever the distinct character count exceeds k.
- Time
- O(N)
- Single pass through the string with constant-time adjustments.
- Space
- O(k)
- The counter holds at most
kdistinct characters.
Longest Substring with K Uniques
Find the length of the longest substring that contains exactly k distinct characters. A sliding window with a counter tracks character frequencies and shrinks whenever the distinct count exceeds k. The answer is only recorded when the window holds exactly k distinct characters, and stays -1 if no such substring exists.
- Time
- O(N)
- Single pass through the string;
leftandrighteach move at most N steps. - Space
- O(k)
- The counter holds at most
kdistinct characters.
159. Longest Substring with At Most Two Distinct Characters
A specific instance of "Longest Substring with At Most K Distinct Characters" where k = 2.
- Time
- O(N)
- Single pass through the string.
- Space
- O(1)
- The counter is limited to at most
k = 2distinct characters, a fixed constant regardless ofN.
904. Fruit Into Baskets
A special case of "Longest Substring with At Most K Distinct Characters" where k = 2, but with an array of integers instead of a string.
- Time
- O(n)
- Single pass through the array.
- Space
- O(1)
- The basket counter holds at most
k = 2distinct fruit types, a fixed bound independent ofn.
1446. Consecutive Characters
Find the maximum power of a string, defined as the maximum length of a non-empty substring that contains only one unique character. This is "Longest Substring with At Most K Distinct Characters" where k = 1.
- Time
- O(N)
- Single traversal through the string.
- Space
- O(1)
- Constant space.
395. Longest Substring with At Least K Repeating Characters
The "at least k" constraint is not monotonic, so a single window cannot slide directly. Instead, fix the number of distinct characters allowed (maxUnique, from 1 up to the total distinct count) and, for each value, find the longest window holding at most that many distinct characters. A window is the answer when every distinct character in it appears at least k times - detected by comparing uniqueChars against countAtLeastK.
- Time
- O(N + N * M)
maxUniqueChars = len(set(s))is oneO(N)pass overs.Mis the number of distinct characters ins(at most 26). The outerforloop callsatMostKUniqueCharsonce per value from1toM, and each call is anO(N)two-pointer scan -N * M.- Space
- O(1)
counterand theset(s)used to computemaxUniqueCharshold at most 26 distinct characters.
Depends on prev
674. Longest Continuous Increasing Subsequence
Find the length of the longest continuous increasing subsequence (LCIS). The window expands as long as each element is greater than the previous one. When the increasing sequence breaks, the window rapidly shrinks to start from the current position.
Expansion:
- The window expands by moving the
rightpointer forward as long as the current element is greater than the previous one.
Logic:
- After each expansion, update
maxiwith the current window length.
Shrinking:
- When the increasing sequence breaks, set
lefttorightand restart.
- Time
- O(N)
- Single pass through the array.
- Space
- O(1)
- Constant space for a few variables.
1839. Longest Substring Of All Vowels in Order
Find the length of the longest "beautiful" substring that contains all five vowels ('a', 'e', 'i', 'o', 'u') in order. The window expands as long as characters remain in non-decreasing order. A seen set tracks which vowels have been encountered. When the order breaks, the window resets.
- Time
- O(n)
nis the length ofword-leftandrighteach advance at mostntimes across the run, so every character is visited once.- Space
- O(1)
counteronly ever tracks the 5 vowels, a fixed-size bound independent ofn.
978. Longest Turbulent Subarray
A turbulent subarray alternates between elements being strictly greater and then less than (or vice versa) adjacent elements. The window expands as long as the turbulent pattern holds. When the pattern breaks, the window rapidly shrinks.
- Time
- O(N)
- Single pass through the array with each element evaluated once.
- Space
- O(1)
- A minimal number of variables.
2419. Longest Subarray With Maximum Bitwise AND
ANDing two numbers can only clear bits, never set them, so the AND of any subarray is at most max(subarray) - and it equals that max only when every element in the subarray already equals the array's overall maximum. The problem reduces to: find the longest run of consecutive elements equal to max(nums).
Compute max_element once, then make a single pass counting the current run (consec), resetting to 0 on any mismatch and tracking the best run seen (maxi).
- Time
- O(2N)
- One
O(N)pass to findmax(nums), then a secondO(N)pass to count the longest run -2N. - Space
- O(1)
- A few counters, no extra structures.
Miscellaneous
1208. Get Equal Substrings Within Budget
Find the maximum length of a substring of s that can be made equal to the corresponding substring of t, where the total cost does not exceed maxCost. The cost is the absolute difference in ASCII values between corresponding characters. The window expands by accumulating costs and shrinks when the budget is exceeded.
- Time
- O(N)
rightadvances across alln = len(s)positions exactly once, andleftnever moves pastright, so the innerwhileshrink loop can advanceleftat mostntimes total across the whole run.- Space
- O(1)
- Only
left,right,maxi, andcostare tracked; no structure scales withn.
1658. Minimum Operations to Reduce X to Zero
To find the shortest operations that sum up to x from both ends is to find the longest subarray that sums up to total - x.
Instead of directly finding elements to remove from both ends, identify the largest contiguous subarray with sum equal to sum(nums) - x. The answer is n - length_of_that_subarray.

- Time
- O(2N)
k = sum(nums) - xis oneO(N)pass, then the sliding window makes a secondO(N)pass, adding and removing each element exactly once - two distinctO(N)passes,2N.- Space
- O(1)
- Only a fixed number of variables are used regardless of
N.
1438. Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit
The window is valid only while max(window) - min(window) <= limit. To check that in a sliding window we keep two heaps over (value, index) pairs: a min-heap for the window minimum and a max-heap for the window maximum.
Expansion:
- Push
nums[right]into both heaps and advanceright.
Shrinking:
- While the window is invalid (
abs(min_heap[0][0] - max_heap[0][0]) > limit), advanceleft, lazily popping any heap tops whose stored index has fallen out of the window (index <= left).
Logic:
- After each adjustment, update
maxiwith the current window lengthright - left.
Indices are stored alongside values so stale extremes can be discarded lazily - a heap entry is only removed once left passes its index, so each element is pushed and popped at most once.
- Time
- O(N log N)
- Each element is pushed and popped from each heap at most once; every heap operation is
O(log N). - Space
- O(N)
- In the worst case both heaps hold all
Nelements.
2779. Maximum Beauty of an Array After Applying Operation
Two elements can be turned into the same value exactly when their [i-k, i+k] ranges overlap, which is when they differ by at most 2*k. Sorting nums turns that into a locality property: a group can all become one value iff its smallest and largest differ by at most 2*k, and the extremes of any group are its first and last element once sorted. So slide a window over the sorted array - grow right, then shrink left while nums[right-1] - nums[left] > 2*k. Every window that survives the shrink is a valid group, so maxi just tracks the widest one.
- Time
- O(2n + n log n)
nums.sort()isO(n log n).rightadvancesntimes andleftadvances at mostntimes across the whole run - neither pointer ever moves backwards - so the two-pointer scan is2n.- Space
- O(sort)
- Only the scalars
n,left,right,maxiare allocated, so the sort's own working memory is the entire cost. - Sorting algorithms are typically
O(log n)space (in-place, recursion stack only), but Python'slist.sort()is Timsort, which allocates up toO(n)auxiliary space in the worst case - that's whatsortstands for here.
1156. Swap For Longest Repeated Character Substring
A single swap can extend a run of one character. Slide a window that stays valid while it contains at most one character different from the rest ((right - left) - max_frequency <= 1). The candidate length is capped by min(window_size, total_count_of_that_char) - you can only swap in another copy of the character if one exists somewhere else in the string.
- Time
- O(N)
- Single pass with the sliding window;
leftandrighteach advance at mostNtimes. - Space
- O(1)
- The frequency maps hold at most 26 distinct characters.
Bitwise
2401. Longest Nice Subarray
A subarray is "nice" if the bitwise AND of every pair of elements equals 0 (no two elements share a set bit). The key insight: if all elements in a window have no overlapping bits, their sum equals their XOR (XOR = addition without carries; any carry means a bit collision). The window shrinks from the left whenever sum ≠ XOR. Both operations are losslessly reversible: shrinking subtracts the left element and XORs it out.
- Time
- O(n)
rightadvances throughnumsonce in the outerwhile right < nloop, andleft(in the inner shrink loop) only ever moves forward, so each index enters and leaves the window at most once:O(n), wherenislen(nums).- Space
- O(1)
- Only scalars (
left,right,maxi,window_sum,window_xor) are tracked, no structure grows withn.