Skip to main content

1. Two Sum

easyAsked at Baidu

Find two indices in an array whose values sum to a target.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

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

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • Exactly one valid answer exists

Examples

Example 1

Input
nums = [2,7,11,15], target = 9
Output
[0,1]

Example 2

Input
nums = [3,2,4], target = 6
Output
[1,2]

Approaches

1. Brute force

Check every pair of indices.

Time
O(n^2)
Space
O(1)
for (let i=0;i<nums.length;i++)
  for (let j=i+1;j<nums.length;j++)
    if (nums[i]+nums[j]===target) return [i,j];

Tradeoff:

2. Hash map

Store complements in a map so each element is checked in O(1). One pass suffices.

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

Tradeoff:

Baidu-specific tips

Baidu interviewers expect you to reach the hash-map solution quickly and explain how it would scale to a sharded search-index lookup of billions of keys.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Two Sum and other Baidu interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →