educative.io

How is "Find any 3 values in an array that sum up to 825" solved by the 2 pointers pattern?

The course material spends a lot of time specifying this works when you have only TWO elements of the input data - " * We are only considering the two elements in the input data that are pointed to by the two pointers rather than the whole set of elements located between the two pointers."

How do 3 elements, and not 2 elements, play into it?


Course: Grokking Coding Interview Patterns in Java - Learn Interactively
Lesson: Two Pointers: Introduction - Grokking Coding Interview Patterns in Java

Hi Pedro!

That’s a great question and I’m glad you asked.

The point of using better problem-solving techniques is that they lead to more efficient solutions compared to the naive approach. If you think about it, to find 3 elements that sum up to a given target, we would, somewhere inside our solution (whether using two pointers or not), actually be checking if v1 + v2 = (target - v3), where v1, v2 and v3 are the three values we happen to be examining at any given point in time.

With this insight in mind, I think you can probably enhance the standard two-pointers technique for the two-sum problem to make it work for the three-sum problem.

Having said that, we’ll definitely review the statement you’ve cited from the pattern introduction lesson.

Hope this helps – and happy learning!

1 Like