Practice
Resources
Contests
Online IDE
New
Free Mock
Scaler
Practice
Improve your coding skills with our resources
Contests
Compete in popular contests with top coders
Scaler
Explore Offerings by SCALER

Two Pointers

Go to Problems

Level 1

Jump to Level 2

Level 2

Jump to Level 3

Level 3

Jump to Level 4

Level 4

Jump to Level 5

Level 5

Jump to Level 6

Level 6

Jump to Level 7

Level 7

Jump to Level 8

Level 8

Be a Code Ninja!

TWO POINTERS

This topic in itself is not particularly broad. However, a lot of interviews tend to be a little biased to questions using this technique which prompted us to separate it out as another topic.

So, two pointer ( or N pointer for that matter ) is usually a really clever optimization on some bruteforce approches in certain condition.

Let us start looking at this with the help of a question. Then we will generalize our approach.

Example:
Given a sorted array A ( sorted in ascending order ),
find if there exists 2 integers A[i] and A[j] such that A[i] + A[j] = 0, i != j

Now the naive solution would be,

        for (int i = 0; i < A.size(); i++) 
            for (int j = 0; j < A.size(); j++) {
                if (i != j && A[i] + A[j] == 0) return true; // solution found. 
                if (A[i] + A[j] > 0) break; // Clearly A[i] + A[j] would increase as j increases
            }

This solution is O(n^2).

However, let us now analyze how ‘i’ and ‘j’ move with iterations.
Clearly, ‘i’ moves forward with every iteration.
Now let us analyze the ‘j’ loop.
As i is increasing, A[i] is also increasing.
That means the point where the loop breaks is decreasing.
Let us rewrite the 2 loops slightly differently.

        for (int i = 0; i < A.size(); i++) 
            for (int j = A.size() - 1; j >= 0; j--) {
                if (i != j && A[i] + A[j] == 0) return true; // solution found. 
                if (A[i] + A[j] < 0) break; // Clearly A[i] + A[j] would decrease as j decreases.
            }

Still O(n^2).

Now, with the same analysis, as ‘i’ increases, A[i] also increases.
And the number of iterations after which ‘j’ breaks also increases.
But note what changes when ‘i’ moves to i + 1:

  • If A[i] + A[J] > 0,
  • Then A[i + 1] + A[J] is also greater than 0, as A[i + 1] > A[i].
    This means if we have tried J for ‘i’, then when moving to i + 1, we should only try values of j < J.
    This concludes that our ‘j’ should be monotonically decreasing and we could re-write the above solution as :
        int j = A.size() - 1;    
        for (int i = 0; i < A.size(); i++) 
            for (; j > i; j--) {
                if (i != j && A[i] + A[j] == 0) return true; // solution found. 
                if (A[i] + A[j] < 0) break; // Clearly A[i] + A[j] would decrease as j decreases.
            }

Let us analyze the time complexity of the above solution.
Let us say A.size() = n.

  • ‘i’ moves in total of n steps.
  • ‘j’ also moves in total of n steps
    ( j– is executed atmost n times. Note that we are never increasing the value of j. Neither are we resetting it ).

That means we take in total of n + n steps = O(n).

In general, all two pointer approach work similarly. You look at the naive solution involving multiple loops and then you start analyzing the pattern on each loop.
Try to look for monotonicity in one of the loops as other loops move forward. If you find that, you have found your optimization.

Happy 2 pointer-ing :-)

 

Serious about Learning Programming ?

Learn this and a lot more with Scaler Academy's industry vetted curriculum which covers Data Structures & Algorithms in depth.

Two Pointers Problems

Sorting
Problem Score Companies Time Status
Pair With Given Difference 200 38:21
Counting Triangles 225
65:12
Diffk 300
29:31
Multiple arrays
Problem Score Companies Time Status
Merge Two Sorted Lists II 200 25:38
Intersection Of Sorted Arrays 225
18:20

Additional Practice

Problem Score Companies Time Status
Palindrome Numbers 200
LTI
34:32
Free Mock Assessment
Fill up the details for personalised experience.
All fields are mandatory
Current Employer *
Enter company name *
Graduation Year *
Select an option *
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Phone Number *
OTP will be sent to this number for verification
+1 *
+1
Change Number
Graduation Year *
Graduation Year *
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
*Enter the expected year of graduation if you're student
Current Employer *
Company Name *
Please verify your phone number
Edit
Resend OTP
By clicking on Start Test, I agree to be contacted by Scaler in the future.
Already have an account? Log in
Free Mock Assessment
Instructions from Interviewbit
Start Test