/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function (nums, target) {
/**
* remain value is the final value of target and array's individual element subtraction.
* If remain Value is present in the given nums array that means we have our answer
* start and current represents the index value of subtracted number and current number against which comparision is happening in loop;
* result is to store final result and retuen it ;
*/
let start = 0;
let remain = target - nums[start];
let current = 1;
let result = [];
/**
* WHY NOT FOR LOOP?
* For loop will only run for limited number of time based on the emenent size in the array, but here i need to loop against every index to compare it with remain value
* and update remain value till the last element , while is more suitable for such problems where we don't have any predefined iteration count. while loop totally depends
* on base condition
*/
/**
* This condition will make sure we consider all the array elements as substration value.
*/
while (start <= nums.length - 1) {
// O(n) - NOt sure here!!!
if (remain === nums[current]) {
if (start !== current) {
result = [start, current];
console.log(result);
break;
}
}
if (current === nums.length - 1) {
/**
* I increment current value on every iteration and start value once in loop single phase.
* after one loop cycle assign current to 0 index again ;
*/
current = 0;
start++;
remain = target - nums[start];
}
current++;
}
return result;
};
twoSum([3, 2, 4], 6);