Skip to main content

Two Pointers

MikeAbout 1 minleetcodetwo pointers

Two Pointers

The two pointers technique is a technique used to iterate through a data set, typically an array or a list, in a controlled way. It involves using two pointers, one pointing to the beginning of the data set and the other pointing to the end, and moving them towards each other based on specific conditions. This technique is commonly used to solve problems that involve searching for a specific condition or pattern within a data set, or that require a comparison between different elements in the data set.

The two pointers technique is mainly used for solving problems that have a linear time complexity, it can lead to substantial performance improvements over a brute-force approach. Some common examples of problems that can be solved using this technique include:

  • Finding the maximum / minimum value in a set of data.
  • Counting the number of occurrences of a specific element.
  • Finding the longest substring without repeating characters.
  • Finding the maximum sum of a sub-array of size k.

Overall, the two pointers technique is a useful approach for solving specific types of problems that involve iterating through a data set in a controlled way, such as in pattern matching, data analysis, and statistics. It allows for an efficient and controlled iteration of a data set, which can lead to improved performance and more accurate results.

two pointers
two pointers

Exercise

Remove Element

27: Remove Element
26: Remove Duplicates from Sorted Array
283: Move Zeroes
844: Backspace String Compare
977: Squares of a Sorted Array

Reverse String

344: Reverse String

Replace Numbers

KamaCoder 54: Replace Numbers

Reverse Words in s String

151: Reverse words in a String

Reverse Linked List

206: Reverse Linked List

Remove Nth Node From End of List

19: Remove Nth Node From End of List

Intersection of Two Linked Lists

160: Intersection of Two Linked Lists

Linked List Cycle

141: Linked List Cycle
142: Linked List Cycle II

Three Sum

15: Three Sum
16: Three Sum Closest

Four Sum

18: Four Sum

Summary