LeetCode Python Problem #1 – Solving “Two Sum”

Welcome back to the blog! In this post, I’m kicking off my Python coding challenge series by solving an easy yet essential problem from LeetCode: “Two Sum”. Whether you’re a beginner learning Python or someone preparing for coding interviews, this problem is a perfect place to start.

If you missed the introduction post for this Python challenge series, check it out here: [Leveling Up with LeetCode Python].

Let’s break it down step by step and solve it together.

Problem Statement: Two Sum

You are given an array of integers nums and an integer target. Return the indices of the two numbers such that they add up to the target.

Example:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9.
Constraints:
  1. Each input has exactly one solution.
  2. You cannot use the same element twice.
  3. You can return the answer in any order.

Thought Process

To solve this problem, we need to:

  1. Loop through the array nums.
  2. For each number, check if its complement (target – number) already exists in a dictionary.
  3. If the complement is found, return the indices of both numbers.
  4. Otherwise, store the current number and its index in the dictionary.

The use of a dictionary allows us to efficiently check for complements while iterating through the array in a single pass.

Python Solution

def two_sum(nums, target):
    seen = {}  # Dictionary to store number and its index
    
    for index, num in enumerate(nums):
        complement = target - num  # Calculate the complement
        
        if complement in seen:  # Check if complement exists
            return [seen[complement], index]
        
        seen[num] = index  # Store the number and its index in dictionary
    
    return []  # Fallback (though problem guarantees a solution)

# Example Usage
nums = [2, 7, 11, 15]
target = 9
result = two_sum(nums, target)
print("Indices of Two Sum:", result)

Explanation of Code

  1. Initialization: A dictionary seen is created to store numbers and their indices.
  2. Loop through the Array:
    • For each number, calculate the complement (target - num).
    • Check if the complement exists in the seen dictionary.
    • If yes, return the indices of the current number and the complement.
    • Otherwise, add the current number and its index to the dictionary.
  3. Efficiency: This approach runs in O(n) time complexity because we loop through the array once and lookups in the dictionary are O(1).

Key Takeaways

  1. Hash Maps are Powerful: Using a dictionary allows us to solve this problem efficiently in a single pass.
  2. Python Enumerate: enumerate is a handy function that gives us both the index and the value while iterating through a list.
  3. Practice Problem-Solving: Problems like “Two Sum” teach us fundamental concepts that are building blocks for more complex challenges.

What’s Next?

This was just the beginning! In the next post, we’ll tackle another easy Python problem, building on the concepts we learned today. Stay consistent, and your coding skills will improve with every challenge.

If you enjoyed this post and want to follow along, stay tuned for the next problem!

Let’s code, learn, and grow—one Python problem at a time.

,
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.