TWO POINTERS

WHAT IS THE TWO POINTER TECHNIQUE?

WHAT IS THE TWO POINTER TECHNIQUE?

The two pointers technique is an algorithmic strategy where two pointers are used to traverse a data structure (usually an array or a list) in order to solve problems more efficiently.

Chat GPT

WHAT IS THE TWO POINTER TECHNIQUE?

Imagine you have a long row of textbooks lined up on the floor, and you want to find two textbooks that together are the heaviest. Instead of picking up every textbook and checking with every other textbook (which takes a long time, Nested loop), you and your friend start from opposite ends of the line. You move toward the middle, each picking up a textbook as you go, and checking if their combined weight is what you want.

 

WHAT IS THE TWO POINTER TECHNIQUE?

THE TWO POINTER TECHNIQUE IS NOT ONLY FOR SORTED ARRAYS !!!!!

Though sorted arrays would be the best use case, it is not limited to it

UNSORTED ARRAYS

LINKED LISTS

STRINGS

AND OTHERS...

The key idea behind the two-pointer technique is to maintain two pointers that move through the data structure, often in opposite directions, to solve a specific problem.

COMMON PATTERNS:

Opposite End Pointers

Same Direction Pointers 

Fixed distance Pointers 

Opposite End Pointers

One pointer starts at one end, and the second pointer on the other end

Same Direction Pointers 

Both pointers start on the same direction with one delayed or lagging behind

Fixed distance Pointers 

Referring to sliding window (we would look deeply later on)

TIME COMPLEXITY

 O(n)

SPACE COMPLEXITY

 O(1)

The two pointers themselves are typically stored in variables, which occupy a constant amount of memory regardless of the input size.

WHEN DO WE USE THIS TECHNIQUE

PAIR SEARCHING

OPPOSITE END PROCESSING

REARRANGING OR PARTITIONING

Many More...

Further Reading and Relevant Links

Team Algo Daily (Video)

Team Algo Daily (Website)

You know the drill, Let's go solve those Leetcode challenges 

Thank you !!!!

S.I.T: DSA - Two Pointers

By Chineletam Ugwuadu (Letam)

S.I.T: DSA - Two Pointers

  • 211