Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. I've tried a few modified versions of the solution below.
function twoSum($nums, $target) {
$arr = array();
for($i = 0; $i < count($nums); $i++){
if($nums[$i] + $nums[$i+1] == $target){
array_push($arr, array_search($nums[$i], $nums), array_search($nums[++$i], $nums));
break;
}
}
return $arr;
}
When passed three test cases the first two return the correct outcome the last case returns the first correct index but the last index is (technically) incorrect.
Test cases used:
nums = [2,7,11,15], target = 9
expected output: [0,1]
actual output: [0,1]
nums = [3,2,4], target = 6
expected output: [1,2]
actual output: [1,2]
nums = [3,3], target = 6
expected output: [0,1]
actual output: [0,0]
Your approach is incorrect because you assume 2 consecutive indices can lead to a target value in this line, which is incorrect. The pair could be any combination.
$nums[$i] + $nums[$i+1] == $target
It is also not considering index out of bounds exception for $i + 1
. Rest of the code would surely go in incorrect direction anyway.
The steps to solve this is pretty straightforward.
Use a simple associative array, say $set
which will store key as the array element and value as the index of that element in the array.
Now, when looping over the array, if target - current_element
key(the other number) exists in the $set
, you got the pair.
Snippet:
<?php
function twoSum($nums, $target) {
$set = [];
foreach($nums as $index => $curr_element){
$cousin_value = $target - $curr_element;
if(isset( $set[ $cousin_value ] )){
return [ $set[ $cousin_value ], $index ];
}
$set[ $curr_element ] = $index;
}
return -1;
}
print_r(twoSum([3,3],6));