DSA-VerseLearn by watching code run
DashboardData StructuresAlgorithmsVisualizerCORECoding PlaygroundInterview QuestionsComplexity AnalyzerLearning NotesBookmarksLearning ProgressSettings
All interview questions

Interview preparation

Two Sum

EasyArraysHashing
AmazonGoogleMicrosoftAppleMetaAdobe Community-reported practice tags — not verified company questions.

1Problem statement

Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one solution, and you may not use the same element twice. Return the answer in any order.

2Examples

Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]

3Constraints

  • 2 ≤ nums.length ≤ 10⁴
  • −10⁹ ≤ nums[i], target ≤ 10⁹
  • Exactly one valid answer exists.

4Approaches

Approach 1

Brute Force

Check every pair (i, j) with i < j and return the first pair whose sum equals target.

Time O(n²)Space O(1)

Approach 2

Better: Sort + Two Pointers

Sort (value, index) pairs, then move a left and right pointer inward depending on whether the sum is too small or too large.

Time O(n log n)Space O(n)

Approach 3

Optimal: One-pass Hash Map

For each number, look up complement = target − number in a map of previously seen values. If present, return both indices; otherwise store number → index.

Time O(n)Space O(n)

5Code (optimal approach)

Complete programs that print the example outputs — verified in JavaScript, Python, Java and Go.

function twoSum(nums, target) {
  const seen = new Map();
  for (let i = 0; i < nums.length; i++) {
    const complement = target - nums[i];
    if (seen.has(complement)) return [seen.get(complement), i];
    seen.set(nums[i], i);
  }
  return [];
}

console.log(twoSum([2, 7, 11, 15], 9));
console.log(twoSum([3, 2, 4], 6));

6Complexity

Time

O(n)

Space

O(n)

7Visual walkthrough

Step through this exact algorithm:

Two Suminteractive Open full visualizer
3
8
11
2
7
15
0
1
2
3
4
5
Hash map · seen
key (value)→ index
empty
ComparingSwapping / movingCurrentSorted / finalFound / placed

Finds two indexes whose values add up to a target in one pass, storing each value's index in a hash map and looking up the complement (target − value).

1 / 22

8Related questions

Valid AnagramMove Zeroes

On this page

  1. 01Problem statement
  2. 02Examples
  3. 03Constraints
  4. 04Approaches
  5. 05Code (4 languages)
  6. 06Complexity
  7. 07Visual walkthrough
  8. 08Related questions