U

120. Two Sum — Indices with Target Sum

Easy

Problem Description

Given an array of NN integers and a target TT, find the two distinct 0-based indices whose values sum to TT. Output the indices in ascending order separated by space. If no pair exists, print -1 -1.

Input Format

  • •Line 1: Two space-separated integers NN and TT.
  • •Line 2: NN space-separated integers A0,…,AN−1A_0, \dots, A_{N-1}.

Output Format

Print the two 0-based indices separated by space, or -1 -1.

Example 1:
Input:
4 9
2 7 11 15
Output:
0 1
Explanation: A[0] + A[1] = 2 + 7 = 9.
Example 2:
Input:
3 6
3 2 4
Output:
1 2
Explanation: A[1] + A[2] = 2 + 4 = 6.
Example 3:
Input:
2 6
3 3
Output:
0 1
Explanation: A[0] + A[1] = 3 + 3 = 6.
Constraints:
  • Standard integer bounds: 32-bit signed integer or input range [1, 10^5].
  • Time complexity target: O(N) or O(N log N) where applicable.
  • Auxiliary space target: O(1) or minimal auxiliary memory.
Follow up:Can this algorithm be adapted to an online streaming setting where the entire input cannot be held in memory simultaneously?
1,180 Online