#C14643. Two Sum Challenge
Two Sum Challenge
Two Sum Challenge
Given an array of integers and a target integer, your task is to find two distinct indices such that the numbers at these indices add up to the target value.
If such a pair exists, output the two indices (0-indexed) separated by a space. In case there are multiple valid answers, output the first found pair (i.e., the pair corresponding to the smallest second index). If no such pair exists, output []
.
Note: The solution must run in linear time using an appropriate data structure.
The underlying algorithm can be expressed by the equation:
\(a_i + a_j = target\), where \(i \neq j\) and \(0 \leq i,j < n\).
inputFormat
The input consists of two lines:
- The first line contains two integers
n
andtarget
, wheren
is the number of elements in the array. - The second line contains
n
space-separated integers representing the elements of the array.
outputFormat
If a valid pair exists, output the two 0-indexed positions separated by a space. If no such pair exists, output []
.
4 9
2 7 11 15
0 1