test_reference_editorial

Two Sum

Given an array of integers numsnums and an integer targettarget, find two indices ii and jj such that nums[i]+nums[j]=targetnums[i] + nums[j] = target. You may assume that each input has exactly one solution, and you may not use the same element twice.

Input / Output

Input: An array numsnums of nn integers and an integer targettarget.

Output: Two indices i,ji, j with iji \neq j such that nums[i]+nums[j]=targetnums[i] + nums[j] = target.

Constraints

2n104,109nums[i]1092 \leq n \leq 10^4, \quad -10^9 \leq nums[i] \leq 10^9
207111215314
numsnums
Step 1 / 10

Complexity Analysis

The brute-force algorithm uses two nested loops over the array:

T(n)=i=0n2j=i+1n1O(1)=n(n1)2=O(n2)T(n) = \sum_{i=0}^{n-2} \sum_{j=i+1}^{n-1} O(1) = \frac{n(n-1)}{2} = O(n^2)

Time complexity: O(n2)O(n^2) — we examine every pair exactly once.

Space complexity: O(1)O(1) — no additional data structures are used.

A hash-map approach improves time to O(n)O(n) at the cost of O(n)O(n) space:

Thash(n)=i=0n1O(1)=O(n)T_{hash}(n) = \sum_{i=0}^{n-1} O(1) = O(n)