educative.io

Sum of three values improvement

why is low being initialized to nums[i+1]. Should not low be always 0 other than for nums[0].

So my logic was
low = 0
high = nums[nums.size()-1]
if ( i == 0) {low = 1;}
if (high == nums[nums.size() - 1] {high = nums[num.size() -2];}

Hello @Naveen1,

In your approach, you’re initializing low to 0 first and then adding an additional check to assign low to the 1st index. This can be done in a single line as done in the solution lesson.

The reason for initializing the low pointer to i + 1 is that we have slightly enhanced the traditional two-pointers approach. With this initialization, we can keep i' fixed to the 0th index, lowinitially pointing toi + 1(1st) index, andhighpointing to the last index of the array. We have three values right now,i’, low, and high, and we can sum up the values at these indexes to check whether this addition matches the target value we are looking for.

Furthermore, if you run your solution on the provided test cases in the challenge lesson, it will fail on a test case where nums = [-1, 2, 1, -4, 5, -3] and target = 0. The issue with your code lies in the initialization of the high pointer. In the line int high = nums[nums.size()-1];, you are assigning the value of the last element in the nums vector to high. However, you should be assigning the index of the last element, not the value itself.

To fix this, you can change the line to int high = nums.size() - 1;. This will correctly initialize the high pointer to the index of the last element in the vector. Additionally, the lines if (i == 0) and if (high == nums[nums.size() - 1]) are unnecessary and can be removed. They don’t affect the logic of the algorithm.

After making these changes, your code should work correctly for the test case. Hope this clears your confusion. Feel free to share more suggestions and feedback.

Regards,

Dian Us Suqlain
Developer Advocate @Educative.io