Developer Learning Wiki
  • About
  • DSA
    • Overview
    • Data Structures
    • Algorithms
    • Problems
  • System Design
    • Overview
  • Technical Blogs
    • Overview
  1. Data Structures & Algorithms
  2. Practice Problems
  3. Two Sum
  • Data Structures & Algorithms
    • Practice Problems
      • Binary Search in Reversed Sorted Array
      • Two Sum
      • Valid Parentheses
      • Climbing Stairs
      • Longest Substring Without Repeating Characters
    • Data Structures
      • Queue
    • Algorithms
      • Binary Search
      • Kadane’s Algorithm

On this page

  • Two Sum
    • Solution
    • Analysis
    • Approach
    • Edge Cases
    • Variations
  1. Data Structures & Algorithms
  2. Practice Problems
  3. Two Sum

Two Sum

Two Sum

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

Solution

def two_sum(nums, target):
    seen = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return []

# Example
nums = [2, 7, 11, 15]
target = 9
print(two_sum(nums, target))  # [0, 1]

Analysis

Time Complexity: O(n)
Space Complexity: O(n)

Approach

  1. Hash Map Approach: Use a hash map to store numbers we’ve seen
  2. One Pass: For each number, check if its complement exists in the map
  3. Return Indices: Return the indices when complement is found

Edge Cases

  • Empty array
  • No solution exists
  • Duplicate numbers
  • Array with single element

Variations

  • Two Sum II (Sorted Array): Use two pointers approach
  • Three Sum: Extend to find three numbers
  • Four Sum: Extend to find four numbers

© 2024 • Developer Learning Wiki • About •

Found an error? Please leave a comment here or submit a PR in this repository, thanks!

The best way to predict the future is to invent it.

Alan Kay

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Martin Fowler

First, solve the problem. Then, write the code.

John Johnson

×

🚀 Happy Coding!