LeetCodechevron_righttwo pointer invariant

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. 1. Define the active state/window.
  2. 2. Update state while preserving invariants.
  3. 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

#TitleDifficulty
11

Container With Most Water

Find two vertical lines that can form a container with the most water in a given array of heights.

Medium
15

3Sum

Given an integer array, return all unique triplets where the sum is zero using two-pointer scanning with careful duplica…

Medium
16

3Sum Closest

Find the sum of three integers in an array that is closest to a given target using two-pointer scanning.

Medium
18

4Sum

The 4Sum problem requires finding all unique quadruplets in an array that sum to a specific target value.

Medium
26

Remove Duplicates from Sorted Array

Learn how to remove duplicates from a sorted array in-place using two-pointer scanning while preserving element order.

Easy
27

Remove Element

Remove Element challenges you to remove a value from an array in-place using efficient two-pointer scanning and tracking…

Easy
28

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 …

Easy
31

Next Permutation

Next Permutation is a medium-difficulty problem focusing on generating the next lexicographically greater permutation of…

Medium
75

Sort Colors

Sort Colors requires in-place reordering of an array using a two-pointer scanning strategy to group 0s, 1s, and 2s effic…

Medium
80

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…

Medium
88

Merge Sorted Array

Merge two sorted arrays into the first array in non-decreasing order, using a two-pointer approach.

Easy
125

Valid Palindrome

Check if a given string is a valid palindrome by using two-pointer scanning and invariant tracking techniques.

Easy
151

Reverse Words in a String

Reverse Words in a String requires reordering words using precise two-pointer scanning with careful space handling for e…

Medium
165

Compare Version Numbers

Compare two version numbers by checking their individual revisions, considering missing revisions as zero, using a two-p…

Medium
189

Rotate Array

Rotate Array challenges you to shift elements right by k steps using precise two-pointer scanning and invariant tracking…

Medium
202

Happy Number

Determine if a number is happy by repeatedly summing squares of digits using two-pointer scanning to detect cycles effic…

Easy
283

Move Zeroes

Move all zeros in an array to the end while preserving the order of non-zero elements using efficient in-place operation…

Easy
295

Find Median from Data Stream

Implement a MedianFinder class that supports adding numbers and finding the median from a data stream.

Hard
321

Create Maximum Number

Create Maximum Number involves merging digits from two arrays while preserving order, maximizing the resulting number.

Hard
344

Reverse String

Reverse a character array in-place using a two-pointer scanning technique, ensuring minimal memory and correct index swa…

Easy
345

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…

Easy
443

String Compression

Compress a character array in-place by converting consecutive repeated characters into counts using two-pointer scanning…

Medium
455

Assign Cookies

Maximize content children by assigning at most one cookie per child using two-pointer scanning and greedy sorting techni…

Easy
481

Magical String

Count the number of '1's in the first n characters of a magical string using two-pointer scanning and invariant tracking…

Medium
524

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…

Medium
541

Reverse String II

Reverse String II requires reversing segments of a string using two-pointer scanning while tracking invariants carefully…

Easy
556

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…

Medium
557

Reverse Words in a String III

Reverse Words in a String III involves reversing each word in a sentence using the two-pointer technique.

Easy
567

Permutation in String

Check if a string contains a permutation of another string using two-pointer scanning and hash table techniques.

Medium
581

Shortest Unsorted Continuous Subarray

Find the shortest unsorted continuous subarray that, if sorted, would sort the entire array.

Medium
680

Valid Palindrome II

Check if a string can become a palindrome by deleting at most one character using two-pointer scanning and invariant tra…

Easy
696

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…

Easy
763

Partition Labels

Partition a string into maximal parts so that each letter appears in only one segment, using two-pointer scanning.

Medium
777

Swap Adjacent in LR String

Transform one string into another by swapping adjacent 'L' and 'R' characters in a sequence of moves.

Medium
795

Number of Subarrays with Bounded Maximum

Count the number of contiguous subarrays with a bounded maximum value using a two-pointer approach.

Medium
809

Expressive Words

Expressive Words challenges you to determine if a word can be transformed into a given string by extending groups of rep…

Medium
821

Shortest Distance to a Character

Compute the minimum distance from each character in a string to a target character using efficient scanning techniques.

Easy
832

Flipping an Image

Flip each row of a binary matrix horizontally and invert its values efficiently using a two-pointer scanning approach.

Easy
844

Backspace String Compare

Compare two strings after processing backspaces using efficient two-pointer scanning and careful invariant tracking to e…

Easy
870

Advantage Shuffle

Maximize the advantage of nums1 over nums2 using a two-pointer greedy strategy, carefully tracking which elements beat o…

Medium
881

Boats to Save People

Find the minimum number of boats required to save all people, using a two-pointer approach for efficient pairing.

Medium
905

Sort Array By Parity

Reorder an integer array so all even numbers come before odd numbers using a precise two-pointer scanning method.

Easy
917

Reverse Only Letters

Reverse the characters of a string while skipping non-letter characters using a two-pointer technique.

Easy
922

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…

Easy
925

Long Pressed Name

Check if a typed string could result from long pressing characters while typing a given name using a two-pointer scan.

Easy
942

DI String Match

Reconstruct a permutation from a DI string using two-pointer scanning, carefully tracking the increasing and decreasing …

Easy
948

Bag of Tokens

Maximize your score in the Bag of Tokens problem by strategically playing tokens with two-pointer scanning and greedy te…

Medium
962

Maximum Width Ramp

Find the maximum width of a ramp where nums[i] <= nums[j] for i < j using a two-pointer approach.

Medium
969

Pancake Sorting

Sort an array using pancake flips, leveraging two-pointer scanning and invariant tracking to iteratively position the la…

Medium
977

Squares of a Sorted Array

The problem involves squaring elements of a sorted array and returning the squares in non-decreasing order.

Easy
986

Interval List Intersections

This problem requires finding the intersection of two lists of intervals using a two-pointer technique with invariant tr…

Medium
1023

Camelcase Matching

Camelcase Matching is a medium difficulty problem where you match queries to a given pattern by inserting lowercase lett…

Medium
1089

Duplicate Zeros

Duplicate each zero in a fixed-length array in place, shifting elements right using a two-pointer scanning approach effi…

Easy
1163

Last Substring in Lexicographical Order

Identify the lexicographically last substring in a string using two-pointer scanning with invariant tracking efficiently…

Hard
1332

Remove Palindromic Subsequences

This problem challenges you to remove palindromic subsequences from a string with a minimum number of steps using two-po…

Easy
1455

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…

Easy
1471

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.

Medium
1616

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…

Medium
1697

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…

Hard
1750

Minimum Length of String After Deleting Similar Ends

Minimize string length by deleting similar characters from both ends repeatedly using a two-pointer technique.

Medium
1754

Largest Merge Of Two Strings

Construct the lexicographically largest merge from two strings using a two-pointer greedy scanning approach efficiently.

Medium
1764

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…

Medium
1768

Merge Strings Alternately

Merge two strings alternately, starting with the first string, and append extra characters when one string is longer.

Easy
1813

Sentence Similarity III

Sentence Similarity III asks if one sentence can be transformed into another by inserting a sentence inside it.

Medium
1850

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.

Medium
1861

Rotating the Box

Rotate a box represented by a character matrix, letting stones fall under gravity using precise two-pointer scanning and…

Medium
1877

Minimize Maximum Pair Sum in Array

Minimize the maximum pair sum in an array by optimally pairing its elements.

Medium
1961

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.

Easy
1963

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.

Medium
2000

Reverse Prefix of Word

Reverse the prefix of a string starting from index 0 to the first occurrence of a given character.

Easy
2105

Watering Plants II

Simulate watering a row of plants with Alice and Bob using two-pointer scanning, tracking refills precisely for each ste…

Medium
2108

Find First Palindromic String in the Array

Return the first palindromic string from an array of words or an empty string if none exists.

Easy
2109

Adding Spaces to a String

Learn to efficiently insert spaces in a string using two-pointer scanning with invariant tracking in linear time.

Medium
2149

Rearrange Array Elements by Sign

Rearrange an array by alternating positive and negative integers using a two-pointer approach with invariant tracking.

Medium
2161

Partition Array According to Given Pivot

Rearrange an array around a pivot while maintaining relative order using a two-pointer scanning approach efficiently.

Medium
2193

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.

Hard
2200

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…

Easy
2337

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…

Medium
2396

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 …

Medium
2406

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.

Medium
2410

Maximum Matching of Players With Trainers

Maximize the number of valid player-trainer matchings using two-pointer scanning and careful sorting strategy.

Medium
2460

Apply Operations to an Array

Transform an array by applying adjacent doubling operations and shifting zeros efficiently using two-pointer scanning te…

Easy
2462

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…

Medium
2486

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…

Medium
2503

Maximum Number of Points From Grid Queries

Solve the Maximum Number of Points From Grid Queries problem using two-pointer scanning and invariant tracking.

Hard
2511

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…

Easy
2562

Find the Array Concatenation Value

Compute the array concatenation value efficiently using two-pointer scanning while maintaining a running total of concat…

Easy
2592

Maximize Greatness of an Array

Maximize Greatness of an Array requires permuting numbers to exceed original values at most indices efficiently.

Medium
2697

Lexicographically Smallest Palindrome

Given a string, make it a palindrome with the fewest operations, prioritizing lexicographically smallest result.

Easy
2825

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.

Medium
2903

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.

Easy
2905

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…

Medium
2938

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…

Medium
3132

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…

Medium
3194

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…

Easy
3239

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…

Medium
3240

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…

Medium
3403

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.

Medium
3584

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.

Medium

Related Topics

Two-pointer scanning with invariant tracking LeetCode Pattern: 99 Solutions