#1EasyHash Map

Two Sum

The most asked interview problem — find two indices that add to a target.

AmazonGoogleMicrosoftMetaApple

Problem Statement

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

Examples

Example 1

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

Explanation: nums[0] + nums[1] = 2 + 7 = 9

Example 2

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

Explanation: nums[1] + nums[2] = 2 + 4 = 6

Constraints

  • 2 ≤ nums.length ≤ 10⁴
  • -10⁹ ≤ nums[i] ≤ 10⁹
  • -10⁹ ≤ target ≤ 10⁹
  • Only one valid answer exists.

Solutions

1
Brute Force — Nested Loops
TimeO(n²)SpaceO(1)

Try every pair of elements. For each element at index i, scan every element at index j > i and check if their sum equals the target. Simple but slow — O(n²) for large arrays.

Visual Animation
def twoSum(nums: list[int], target: int) -> list[int]:
    n = len(nums)
    for i in range(n):
        for j in range(i + 1, n):
            if nums[i] + nums[j] == target:
                return [i, j]
    return []  @@0@@

Related Concepts

Deepen your understanding with these related topics from our AI Glossary:

Deepen your understanding

Want to master the core concepts?

Our free AI Glossary covers 190+ topics — from Hash Map to Dynamic Programming, Machine Learning, SQL, and more. Structured learning tracks for every level.

Browse AI Glossary All Problems
39+
AI Models
₹69
Per day used
4
Languages

Stuck? Ask AI to explain it step by step.

Ask Claude, GPT-4o, or Gemini to debug your code, generate test cases, or walk through the intuition. 39+ models. Pay only on days you use it — no subscription required.

Free to start · No credit card required to explore

Get Started Free
Back to all problems