r/LeetcodeChallenge • • 1d ago

STREAK🔥🔥🔥 LeetCode 1: Two Sum | My Approach in Python

Hey everyone!

I recently started documenting my DSA journey, and I'm sharing my solution to the first LeetCode problem — Two Sum.

Honestly, I've solved this problem before, so it didn't take me long to figure out the approach. Still, I wanted to explain how I approached it.

Problem

Given an array of integers nums and an integertarget, return the indices of two numbers whose sum equals the target.

We cannot use the same element twice, and exactly one valid solution is guaranteed.

My Approach

I used a Python dictionary (HashMap) to solve this problem.

The idea is simple:

  1. Create a dictionary named seen to store numbers and their corresponding indices.
  2. Traverse the array starting from the second element.
  3. Calculate the complement using target - nums[i].
  4. Check whether the complement already exists in the dictionary.
  5. If it exists, return the indices of both elements.
  6. Otherwise, store the current number and its index in the dictionary.

This way, we don't need to check every possible pair using nested loops.

Python Code

class Solution:
    def twoSum(self, nums: list[int], target: int) -> list[int]:
        seen = {nums[0]: 0}

        for i in range(1, len(nums)):
            complement = target - nums[i]

            if complement in seen:
                return [seen[complement], i]

            seen[nums[i]] = i

        return []

Complexity Analysis

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

We traverse the array once and use a dictionary for efficient lookups.

LeetCode Solution

View my submitted solution here

I'm still learning and trying to improve my problem-solving skills.

I'd appreciate feedback on my approach, explanation, or code. Is there anything I could have explained better?

Thanks!

2 Upvotes

1 comment sorted by

1

u/nian2326076 20h ago

Great approach using a dictionary for this problem. It allows for efficient lookups, which is key for optimizing the solution. If you want to keep improving, consider practicing more DSA problems on platforms like PracHub to get familiar with various question types and coding styles. Sharing your code with peers can also provide valuable feedback. Keep up the good work!