Two Sum
The most asked interview problem — find two indices that add to a target.
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
Explanation: nums[0] + nums[1] = 2 + 7 = 9
Example 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
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.
Related Concepts
Deepen your understanding with these related topics from our AI Glossary:
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.
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