Grokking the Coding Interview: Patterns for Coding Questions
Ask Author
Back to course home

0% completed

Vote For New Content
Hi, could I get some clarification please for why we increment count by the diff...

Micky M

Apr 26, 2022

Hi, could I get some clarification please for why we increment count by the difference between the right and left index?

count += right - left;

My expectation would be that we could increment count by 1 as we have found a new triplet and the goal is to count the number of triplets that are less than the target.

0

0

Comments
Comments
Design Gurus
Design Gurus4 years ago

Your understanding is correct.

We are using an optimization here. Since arr[right] >= arr[left], therefore, we can replace arr[right] by any number between left and right to get a sum less than the target sum; therefore, all numbers from left to right will give us the...

N
Nirbhay Lourembam2 years ago

I think I understand why this was done.

Since the array is sorted Arrays.sort(arr), all the elements between left and right (inclusive) will also form a valid triplet with the current pair and arr[first]. This is because all these elements are smaller than arr[right]...