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.
- Create an empty dictionary to store the key-value pairs (this will be where the values and it's respective indiced will be stored)
- loop through the list nums with both the indices and the values:
- 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
- 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.
- 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
Soln 2 (Bruteforce):
- iterate through the list using index i (outer loop)
- iterate through the list using index j starting from (i + j) to avoid duplicates (inner loop)
- compare the sum of both elements at indices i and j to the target
- 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])
Note: Hashmaps use key-value pairs, try to solve questions with methods you know before trying to improve them.
Top comments (0)