Files
framework_note/leetcode/note/easy/1_two_sum.md
T
2026-05-30 16:02:33 -04:00

2.6 KiB

id, title, difficulty, tags, status, date_solved, leetcode_url, review_needed
id title difficulty tags status date_solved leetcode_url review_needed
1 Two Sum Easy
array
hash-table
Solved 2026-05-26 https://leetcode.com/problems/two-sum/ false

1. Two Sum

[!info] Problem Link: LeetCode - Two Sum

📝 Problem Description

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.


📥 Example 1

Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

📥 Example 2

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

📥 Example 3

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


💡 Approaches & Explanations

Approach 1: Hash Map (One-Pass) — Optimal

The optimal approach is to use a hash map to keep track of the numbers we have seen so far and their indices. As we iterate through the array, we check if the complement (target - nums[i]) already exists in our hash map.

  • If it does, we found the pair and return their indices.
  • If it doesn't, we add the current number and its index to the hash map.

📊 Complexity Analysis

  • Time Complexity: \mathcal{O}(N) where N is the number of elements in the array. We traverse the list containing N elements only once, and lookup in the hash table takes \mathcal{O}(1) time.
  • Space Complexity: \mathcal{O}(N) since we store at most N elements in the hash map.

Approach 2: Brute Force

Compare every pair of numbers to see if their sum equals the target.

  • Time Complexity: \mathcal{O}(N^2)
  • Space Complexity: \mathcal{O}(1)

💻 Code Implementations

Python3

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        seen = {}  # val -> index
        for i, num in enumerate(nums):
            complement = target - num
            if complement in seen:
                return [seen[complement], i]
            seen[num] = i
        return []

🧠 Key Takeaways & Lessons

  • The Complement Trick: When looking for a pair that sums to a target, rephrase the search: instead of looking for A + B = \text{target}, look for \text{complement} = \text{target} - A that is already stored.
  • Hash Map for \mathcal{O}(1) Lookups: Trading memory (space complexity) for time complexity is a common pattern in array search problems.