DEV Community

WhereIsLijah
WhereIsLijah

Posted on

1. Two Sum

Topic: Array & Hashing

Soln 1 (dictonary solution):
After learning how to use dictionaries in the previous leetcode questions, i decided to see how many more solutions i can provide for using it.

  1. Create an empty dictionary to store the key-value pairs (this will be where the values and it's respective indiced will be stored)
  2. loop through the list nums with both the indices and the values:
  3. Initialize a variable (complement); its value will be the result of the target minus the current number [Major logic of the solution] - for every number in the list
  4. if the complement exists in the dictionary, then we return the index of the complement in the dictionary and the current index from the loop we are iterating with.
  5. else we add this complement into our dictionary (both key and value) which means
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        num_index = {}

        for i, num in enumerate(nums):
            complement = target - num

            if complement in num_index:
                return [num_index[complement], i]
            else:
                num_index[nums[i]] = i

Enter fullscreen mode Exit fullscreen mode

Soln 2 (Bruteforce):

  1. iterate through the list using index i (outer loop)
  2. iterate through the list using index j starting from (i + j) to avoid duplicates (inner loop)
  3. compare the sum of both elements at indices i and j to the target
  4. if the sum is equal to the target then return the indices [i, j]
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

Note: Hashmaps use key-value pairs, try to solve questions with methods you know before trying to improve them.

Top comments (0)