DEV Community

Nishkarsh Pandey
Nishkarsh Pandey

Posted on

3 2 2 1 2

📅 Day 1/75 of LeetCode Practice – [Today’s Focus: Arrays / Strings / Sliding Window]::Part:1

Hey devs! 👋
I'm starting a daily challenge where I solve 2 LeetCode problems every day and share my solutions, explanations, and approach here on Dev.to.

Today’s problems:
🧮 Two Sum
Enter fullscreen mode Exit fullscreen mode

🔹 Problem 1: Two Sum
Problem Number:1
📝 Difficulty: Easy
✅ Problem Statement:
Given an array of integers nums and an integer target, return the indices of the two numbers such that they add up to target.

💡 Approach:
1.Using the basic approach (ie using two for loops)
Caution : This approach has a time complexity of O(n^2)

Python Code:

def twoSum(num,target):
     for i in range(len(nums)):
         for j in range(i+1,len(nums)):
                  if(nums[i]+nums[j]==target):
                          return [i,j]
Enter fullscreen mode Exit fullscreen mode

💡2.Approach:
We use a hash map to store previously seen numbers and their indices. For each number, we check if target - current number exists in the map.
Here we have use enumerate so first we have to understand what basically is enumerate in python.
enumerate() function adds a counter to each item in a list or other iterable.
Ex:
a = ["Geeks", "for", "Geeks"]

Iterating list using enumerate to get both index and element

for i, name in enumerate(a):
print(f"Index {i}: {name}")

Converting to a list of tuples

print(list(enumerate(a)))

Output:
Index 0: Geeks
Index 1: for
Index 2: Geeks
[(0, 'Geeks'), (1, 'for'), (2, 'Geeks')]

Python Code:

def twoSums(nums, target):
    dict1 = {}  # Empty dictionary
    # Iterating list using enumerate to get both index and element
    for i, num in enumerate(nums):
        diff = target - num  # Calculate the difference
        # Check if the required number is already in dictionary
        if diff in dict1:
            return [dict1[diff], i]
        # Store the current number with its index
        dict1[num] = i


Enter fullscreen mode Exit fullscreen mode

🧠 Explanation:
We use a dictionary to keep track of numbers we’ve seen so far along with their indices.
For each number num in nums, we compute target - num = diff.
If diff is already in the dictionary, it means we've seen the required number to complete the pair.
We return the stored index of that number and the current index.

Example:

nums = [2, 7, 11, 15]
target = 9
print(twoSums(nums, target))  # Output: [0, 1]

Enter fullscreen mode Exit fullscreen mode

🏁 Conclusion
The Two Sum problem is a great introduction to using hash maps (dictionaries) for efficient lookups. By storing previously seen values, we avoid nested loops and reduce the time complexity to O(n).
This pattern shows up in many other problems, so understanding this well is important for interviews.

ACI image

ACI.dev: The Only MCP Server Your AI Agents Need

ACI.dev’s open-source tool-use platform and Unified MCP Server turns 600+ functions into two simple MCP tools on one server—search and execute. Comes with multi-tenant auth and natural-language permission scopes. 100% open-source under Apache 2.0.

Star our GitHub!

Top comments (0)

Redis image

Short-term memory for faster
AI agents

AI agents struggle with latency and context switching. Redis fixes it with a fast, in-memory layer for short-term context—plus native support for vectors and semi-structured data to keep real-time workflows on track.

Start building

👋 Kindness is contagious

Discover this thought-provoking article in the thriving DEV Community. Developers of every background are encouraged to jump in, share expertise, and uplift our collective knowledge.

A simple "thank you" can make someone's day—drop your kudos in the comments!

On DEV, spreading insights lights the path forward and bonds us. If you appreciated this write-up, a brief note of appreciation to the author speaks volumes.

Get Started