codeintuition-logo

Understanding the two pointer pattern


The inorder and reverse inorder traversal on a binary search tree results in traversal in the sorted and reverse sorted order. And so, a binary search tree can be used to store values in sorted or reverse-sorted order, which would otherwise have to be stored in an array. Unlike arrays, a binary search tree can be dynamically updated to add more values and searching for the node with a given value is also very efficient. This makes a binary search tree the ideal choice for storing values that need to be accessed in sorted order. 

However, some problems require us to traverse the stored values in both sorted and reverse-sorted order simultaneously. For certain problems, we can use the two-pointer traversal technique to traverse the nodes of a binary search tree simultaneously in sorted and reverse-sorted order. It allows us to solve problems in linear time and single-pass, which would otherwise require inefficient nested loops or complicated recursive functions.

The two-pointer pattern is a classification of problems that can be solved using the two-pointer traversal technique.

Liking the course? Check our discounted plans to continue learning.