two pointer invariant Pattern
99 problems
Pattern pages help build reusable solving frames. Identify signals first, then explain state, transition, and edge handling.
Recognition Signals
- Do you understand the two-pointer technique and how it helps reduce the time complexity of this problem?
- Can you explain why we always move the pointer pointing to the shorter line in the two-pointer approach?
- Do you see how sorting simplifies duplicate management in two-pointer scanning?
Solve Flow
- 1. Define the active state/window.
- 2. Update state while preserving invariants.
- 3. Validate with edge-heavy examples.
Common Misses
- Failing to optimize the solution and instead using a brute-force approach that simulates all pairs, leading to O(n^2) time complexity.
- Failing to skip duplicate fixed elements leads to repeated triplets in output.
- Forgetting to sort the array first, which can lead to inefficient solutions or missed results.
Recommended Ladder
Container With Most Water
Find two vertical lines that can form a container with the most water in a given array of heights.
3Sum
Given an integer array, return all unique triplets where the sum is zero using two-pointer scanning with careful duplica…
3Sum Closest
Find the sum of three integers in an array that is closest to a given target using two-pointer scanning.
4Sum
The 4Sum problem requires finding all unique quadruplets in an array that sum to a specific target value.
Remove Duplicates from Sorted Array
Learn how to remove duplicates from a sorted array in-place using two-pointer scanning while preserving element order.
Remove Element
Remove Element challenges you to remove a value from an array in-place using efficient two-pointer scanning and tracking…
Find the Index of the First Occurrence in a String
Locate the first occurrence of a substring within a string using a two-pointer scanning strategy and invariant tracking …
Next Permutation
Next Permutation is a medium-difficulty problem focusing on generating the next lexicographically greater permutation of…
Sort Colors
Sort Colors requires in-place reordering of an array using a two-pointer scanning strategy to group 0s, 1s, and 2s effic…
Remove Duplicates from Sorted Array II
Solve the problem of removing duplicates from a sorted array in-place, ensuring each element appears at most twice, usin…
Merge Sorted Array
Merge two sorted arrays into the first array in non-decreasing order, using a two-pointer approach.
Valid Palindrome
Check if a given string is a valid palindrome by using two-pointer scanning and invariant tracking techniques.
Reverse Words in a String
Reverse Words in a String requires reordering words using precise two-pointer scanning with careful space handling for e…
Compare Version Numbers
Compare two version numbers by checking their individual revisions, considering missing revisions as zero, using a two-p…
Rotate Array
Rotate Array challenges you to shift elements right by k steps using precise two-pointer scanning and invariant tracking…
Happy Number
Determine if a number is happy by repeatedly summing squares of digits using two-pointer scanning to detect cycles effic…
Move Zeroes
Move all zeros in an array to the end while preserving the order of non-zero elements using efficient in-place operation…
Find Median from Data Stream
Implement a MedianFinder class that supports adding numbers and finding the median from a data stream.
Create Maximum Number
Create Maximum Number involves merging digits from two arrays while preserving order, maximizing the resulting number.
Reverse String
Reverse a character array in-place using a two-pointer scanning technique, ensuring minimal memory and correct index swa…
Reverse Vowels of a String
Reverse Vowels of a String uses a two-pointer approach to reverse the vowels in a string while leaving the consonants in…
String Compression
Compress a character array in-place by converting consecutive repeated characters into counts using two-pointer scanning…
Assign Cookies
Maximize content children by assigning at most one cookie per child using two-pointer scanning and greedy sorting techni…
Magical String
Count the number of '1's in the first n characters of a magical string using two-pointer scanning and invariant tracking…
Longest Word in Dictionary through Deleting
Find the longest word in the dictionary that can be formed by deleting characters from a string, using two-pointer scann…
Reverse String II
Reverse String II requires reversing segments of a string using two-pointer scanning while tracking invariants carefully…
Next Greater Element III
Find the next greater integer using the same digits as a given number with precise two-pointer scanning and invariant tr…
Reverse Words in a String III
Reverse Words in a String III involves reversing each word in a sentence using the two-pointer technique.
Permutation in String
Check if a string contains a permutation of another string using two-pointer scanning and hash table techniques.
Shortest Unsorted Continuous Subarray
Find the shortest unsorted continuous subarray that, if sorted, would sort the entire array.
Valid Palindrome II
Check if a string can become a palindrome by deleting at most one character using two-pointer scanning and invariant tra…
Count Binary Substrings
Count Binary Substrings solves for the number of valid substrings with equal 0's and 1's, grouped consecutively in a bin…
Partition Labels
Partition a string into maximal parts so that each letter appears in only one segment, using two-pointer scanning.
Swap Adjacent in LR String
Transform one string into another by swapping adjacent 'L' and 'R' characters in a sequence of moves.
Number of Subarrays with Bounded Maximum
Count the number of contiguous subarrays with a bounded maximum value using a two-pointer approach.
Expressive Words
Expressive Words challenges you to determine if a word can be transformed into a given string by extending groups of rep…
Shortest Distance to a Character
Compute the minimum distance from each character in a string to a target character using efficient scanning techniques.
Flipping an Image
Flip each row of a binary matrix horizontally and invert its values efficiently using a two-pointer scanning approach.
Backspace String Compare
Compare two strings after processing backspaces using efficient two-pointer scanning and careful invariant tracking to e…
Advantage Shuffle
Maximize the advantage of nums1 over nums2 using a two-pointer greedy strategy, carefully tracking which elements beat o…
Boats to Save People
Find the minimum number of boats required to save all people, using a two-pointer approach for efficient pairing.
Sort Array By Parity
Reorder an integer array so all even numbers come before odd numbers using a precise two-pointer scanning method.
Reverse Only Letters
Reverse the characters of a string while skipping non-letter characters using a two-pointer technique.
Sort Array By Parity II
Sort an array where even numbers appear at even indices and odd numbers appear at odd indices using two-pointer scanning…
Long Pressed Name
Check if a typed string could result from long pressing characters while typing a given name using a two-pointer scan.
DI String Match
Reconstruct a permutation from a DI string using two-pointer scanning, carefully tracking the increasing and decreasing …
Bag of Tokens
Maximize your score in the Bag of Tokens problem by strategically playing tokens with two-pointer scanning and greedy te…
Maximum Width Ramp
Find the maximum width of a ramp where nums[i] <= nums[j] for i < j using a two-pointer approach.
Pancake Sorting
Sort an array using pancake flips, leveraging two-pointer scanning and invariant tracking to iteratively position the la…
Squares of a Sorted Array
The problem involves squaring elements of a sorted array and returning the squares in non-decreasing order.
Interval List Intersections
This problem requires finding the intersection of two lists of intervals using a two-pointer technique with invariant tr…
Camelcase Matching
Camelcase Matching is a medium difficulty problem where you match queries to a given pattern by inserting lowercase lett…
Duplicate Zeros
Duplicate each zero in a fixed-length array in place, shifting elements right using a two-pointer scanning approach effi…
Last Substring in Lexicographical Order
Identify the lexicographically last substring in a string using two-pointer scanning with invariant tracking efficiently…
Remove Palindromic Subsequences
This problem challenges you to remove palindromic subsequences from a string with a minimum number of steps using two-po…
Check If a Word Occurs As a Prefix of Any Word in a Sentence
Determine the first word in a sentence where a given searchWord is a prefix using two-pointer scanning with string match…
The k Strongest Values in an Array
Identify the k strongest values in an array using two-pointer scanning and careful tracking of the array's centre value.
Split Two Strings to Make Palindrome
Determine if splitting two equal-length strings at a common index can form a palindrome using two-pointer scanning techn…
Checking Existence of Edge Length Limited Paths
Solve the problem of checking if there exists a path between two nodes under edge length constraints using efficient tec…
Minimum Length of String After Deleting Similar Ends
Minimize string length by deleting similar characters from both ends repeatedly using a two-pointer technique.
Largest Merge Of Two Strings
Construct the lexicographically largest merge from two strings using a two-pointer greedy scanning approach efficiently.
Form Array by Concatenating Subarrays of Another Array
Determine if you can sequentially select disjoint subarrays from nums matching each group in order using two-pointer sca…
Merge Strings Alternately
Merge two strings alternately, starting with the first string, and append extra characters when one string is longer.
Sentence Similarity III
Sentence Similarity III asks if one sentence can be transformed into another by inserting a sentence inside it.
Minimum Adjacent Swaps to Reach the Kth Smallest Number
Find the minimum number of adjacent swaps to reach the kth smallest wonderful integer from a given number string.
Rotating the Box
Rotate a box represented by a character matrix, letting stones fall under gravity using precise two-pointer scanning and…
Minimize Maximum Pair Sum in Array
Minimize the maximum pair sum in an array by optimally pairing its elements.
Check If String Is a Prefix of Array
Determine if a string is a prefix of an array by concatenating initial elements, using two-pointer scanning efficiently.
Minimum Number of Swaps to Make the String Balanced
Determine the minimum swaps to balance a bracket string using two-pointer scanning with invariant tracking efficiently.
Reverse Prefix of Word
Reverse the prefix of a string starting from index 0 to the first occurrence of a given character.
Watering Plants II
Simulate watering a row of plants with Alice and Bob using two-pointer scanning, tracking refills precisely for each ste…
Find First Palindromic String in the Array
Return the first palindromic string from an array of words or an empty string if none exists.
Adding Spaces to a String
Learn to efficiently insert spaces in a string using two-pointer scanning with invariant tracking in linear time.
Rearrange Array Elements by Sign
Rearrange an array by alternating positive and negative integers using a two-pointer approach with invariant tracking.
Partition Array According to Given Pivot
Rearrange an array around a pivot while maintaining relative order using a two-pointer scanning approach efficiently.
Minimum Number of Moves to Make Palindrome
The problem challenges you to find the minimum number of adjacent swaps to make a string a palindrome.
Find All K-Distant Indices in an Array
Identify all indices in an array that are within k distance of elements equal to the given key using two-pointer scannin…
Move Pieces to Obtain a String
Determine if the pieces in start can be moved to form target using two-pointer scanning and strict left-right movement r…
Strictly Palindromic Number
Determine if a number is strictly palindromic in all bases from 2 to n minus 2 using two-pointer scanning and invariant …
Divide Intervals Into Minimum Number of Groups
Determine the minimum number of non-overlapping groups for a set of intervals using precise two-pointer scanning logic.
Maximum Matching of Players With Trainers
Maximize the number of valid player-trainer matchings using two-pointer scanning and careful sorting strategy.
Apply Operations to an Array
Transform an array by applying adjacent doubling operations and shifting zeros efficiently using two-pointer scanning te…
Total Cost to Hire K Workers
Optimize the total cost of hiring exactly k workers using a two-pointer approach with invariant tracking and priority qu…
Append Characters to String to Make Subsequence
Determine the minimum characters to append to s so t becomes a subsequence using efficient two-pointer scanning techniqu…
Maximum Number of Points From Grid Queries
Solve the Maximum Number of Points From Grid Queries problem using two-pointer scanning and invariant tracking.
Maximum Enemy Forts That Can Be Captured
Find the maximum number of enemy forts that can be captured by moving your army using two-pointer scanning with invarian…
Find the Array Concatenation Value
Compute the array concatenation value efficiently using two-pointer scanning while maintaining a running total of concat…
Maximize Greatness of an Array
Maximize Greatness of an Array requires permuting numbers to exceed original values at most indices efficiently.
Lexicographically Smallest Palindrome
Given a string, make it a palindrome with the fewest operations, prioritizing lexicographically smallest result.
Make String a Subsequence Using Cyclic Increments
Determine if str2 can be made a subsequence of str1 by incrementing characters cyclically using at most one operation.
Find Indices With Index and Value Difference I
Find two indices in an array where their difference in both index and value meets specified thresholds.
Find Indices With Index and Value Difference II
Locate two indices in an array where both index and value differences meet specified thresholds using precise scanning t…
Separate Black and White Balls
Solve the "Separate Black and White Balls" problem by swapping adjacent balls to group all black balls to the right with…
Find the Integer Added to Array II
Given two arrays nums1 and nums2, determine the integer added to nums1 to make it equal to nums2 after removing two elem…
Minimum Average of Smallest and Largest Elements
Solve the Minimum Average of Smallest and Largest Elements problem using two-pointer scanning to track averages effectiv…
Minimum Number of Flips to Make Binary Grid Palindromic I
Find the minimum flips to make a binary grid palindromic by scanning with two pointers and tracking symmetry efficiently…
Minimum Number of Flips to Make Binary Grid Palindromic II
The problem asks to flip cells in a binary grid to make its rows and columns palindromic using the minimum number of fli…
Find the Lexicographically Largest String From the Box I
This problem involves finding the lexicographically largest string from a given word using a two-pointer approach.
Maximum Product of First and Last Elements of a Subsequence
Maximize the product of the first and last elements of any subsequence of size m in an integer array.