Two Sum Indices

Two Sum Indices

Medium PHP PHP Arrays 32 views
Explanation Complexity

Problem Statement

Find indices i and j such that a[i]+a[j]=target. Print first pair found, else -1 -1.

Input Format

Line1 n target. Line2 n integers.

Output Format

Two integers indices.

Example

5 9
2 7 11 15 1
0 1

Constraints

n

Input / Output Format

Input Format
Line1 n target. Line2 n integers.
Output Format
Two integers indices.
Constraints
n

Examples

Input:
5 9 2 7 11 15 1
Output:
0 1

Example Solution (Public)

PHP
<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0; $n=intval($tokens[$i++] ?? 0);
$target=intval($tokens[$i++] ?? 0);
$seen=[];
$ansI=-1; $ansJ=-1;
for($idx=0;$idx<$n;$idx++){
  $v=intval($tokens[$i++] ?? 0);
  $need=$target-$v;
  if($ansI===-1 && array_key_exists(strval($need),$seen)){
    $ansI=$seen[strval($need)];
    $ansJ=$idx;
  }
  if(!array_key_exists(strval($v),$seen)) $seen[strval($v)]=$idx;
}
echo $ansI.' '.$ansJ;
?>

Official Solution Code

<?php
$inputText=trim(stream_get_contents(STDIN));
if($inputText==='') exit;
$tokens=preg_split('/\\s+/', $inputText);
$i=0; $n=intval($tokens[$i++] ?? 0);
$target=intval($tokens[$i++] ?? 0);
$seen=[];
$ansI=-1; $ansJ=-1;
for($idx=0;$idx<$n;$idx++){
  $v=intval($tokens[$i++] ?? 0);
  $need=$target-$v;
  if($ansI===-1 && array_key_exists(strval($need),$seen)){
    $ansI=$seen[strval($need)];
    $ansJ=$idx;
  }
  if(!array_key_exists(strval($v),$seen)) $seen[strval($v)]=$idx;
}
echo $ansI.' '.$ansJ;
?>
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.