#K52627. Two Sum Problem
Two Sum Problem
Two Sum Problem
Given an array of integers and a target integer \(T\), find two distinct indices \(i\) and \(j\) such that the sum of the numbers at these indices equals \(T\), i.e., \(nums[i] + nums[j] = T\). If such a pair exists, output the two indices separated by a space. Otherwise, output []
.
The input is read from standard input and the output should be written to standard output. The problem guarantees that if a solution exists, the returned indices are unique. Note that the order of the indices should correspond to the order of discovery in a single pass using a hash map.
Examples:
- For the input array [2, 7, 11, 15] and target 9, the correct output is
0 1
because 2 + 7 = 9. - For the input array [1, 2, 3, 4, 5] and target 10, no such pair exists and the correct output is
[]
.
inputFormat
The input consists of three lines:
- The first line contains an integer \(n\), which is the number of elements in the array.
- The second line contains \(n\) space-separated integers representing the array elements.
- The third line contains an integer representing the target sum \(T\).
outputFormat
If a valid pair exists, output the two indices separated by a space. If no such pair exists, output []
(without quotes).
4
2 7 11 15
9
0 1