educative.io

Triplet Sum Close to Target (medium)

Why did we run the iteration till i < arr.length - 2 in Triplet Sum Close to Target (medium) question? Could someone please explain?

for (let i = 0; i < arr.length - 2; i++) { … }


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Triplet Sum Close to Target (medium) - Grokking the Coding Interview: Patterns for Coding Questions

Hi @Bilal_Rana

My name is Shahrukh Naeem. I hope everything is going well with you. Thank you for reaching out about this. I will try my best to answer your query!

If we won’t set the for loop condition to i < arr.length() - 2 It can cause an overflow error (An overflow error occurs when one attempts to access the array using an index value greater than its actual size). As we are performing calculations on 3 values of arrays So it can go till the 3rd last value of the array. I would suggest you to do some dry run on the given example so that you can have a better understanding.

I hope that this guide is helpful. Remember that I am always available via message to help you with any difficulty you might encounter.

Regards,

Happy Learning :slight_smile:

1 Like

Hi @Shahrukh_Naeem

Thanks for acknowledging, really appreciate that.

However I tried to do it with for (let i = 0; i < arr.length; i++) { … }, and it worked fine, also in question Triple Sum to zero we did not run the loop i < arr.length - 2, in which we are also running calculation on 3 values. How come in that question we did not do i < arr.length - 2 and in this Triplet Sum close to Target we are doing it.

Reagrds,
Bilal


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Triplet Sum to Zero (medium) - Grokking the Coding Interview: Patterns for Coding Questions

Hi @Bilal_Rana
Any problem can be solved in various ways, so, the given solution is just for the implementation purpose. It can be the same or different from other solutions.
The loop for (let i = 0; i < arr.length - 2; i++) is used to fix the smallest number among the three integers. Secondly, removing -2 won’t affect the output. So, you can use i < arr.length or i < arr.length - 2 according to your choice.

Hope this helps.
Thanks!

1 Like

Thanks @Muntha_Amjad for the clarification. Appreciate it.


Course: Grokking the Coding Interview: Patterns for Coding Questions - Learn Interactively
Lesson: Merge Intervals (medium) - Grokking the Coding Interview: Patterns for Coding Questions

@Bilal_Rana
You are most welcome. I’m happy I could help you.
Happy Learning :slight_smile: