Leet Code

#1 Two Sum Leetcode Problem

brian | Published: March 7, 2024, 7:27 p.m. | Updated: July 9, 2025, 9:33 p.m.

Profile Picture




'''
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.
NOTE:!!! I added the prints so we can visually see 
whats happening and how it worked


'''



class Solution(object):
    def twoSum(self, nums, target):
        
        curr_dict = {}

        for index, num in enumerate(nums):
            print(curr_dict)
            answer = target - num  #   --> 1, 3 index  would give us the target 8

            
            if answer in curr_dict:
                curr_dict[num] = index
                print(curr_dict)
                print(curr_dict[answer], index)
                return
            else:
                curr_dict[num] = index


#       0  1  2  3  4
nums = [3, 2, 4, 6, 8]
target = 8


solve = Solution()

solve.twoSum(nums, target)

---output---
{}
{3: 0}
{3: 0, 2: 1}
{3: 0, 2: 1, 4: 2}      
{3: 0, 2: 1, 4: 2, 6: 3}
1 3  # these are the indices that will give us the target of 8 when added