This page looks best with JavaScript enabled

Leetcode practice - Problem 1 Two Sum

 ·  ☕ 2 min read  ·  ✍️ Wei-Hsiang

Description:

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.

1
2
3
4
5
6
7
8
9

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        d = {}
        for ii in range(len(nums)):
            x = nums[ii]
            if target - x in d:
                return (d[target - x],ii)
            d[x] = ii
  1. The method initializes an empty dictionary d. This dictionary is used to map the value of each element in nums to its index. This mapping will later help in finding the required pair of indices efficiently.

  2. It then enters a loop that iterates over all indices (ii) of the list nums. For each iteration, the current element x is obtained by nums[ii].

  3. Inside the loop, the method checks if target - x is present in the dictionary d. If it is, it means there exists a pair (nums[ii], nums[d[target - x]]) that adds up to the target value. The method then immediately returns a tuple containing the indices of these two elements (d[target - x] and ii).

  4. The reason this check is performed before adding x to the dictionary is to ensure that each potential pair is only considered once and to avoid using the same element twice. If target - x is not found in the dictionary, the current element x along with its index ii is added to the dictionary. The key is the element value x, and the value is its index ii. This is done so that in future iterations, if a complement to x (which, when added to x, equals target) is encountered, the index of x can be retrieved.

  5. The loop continues until either a pair is found and returned, or all elements have been iterated over without finding such a pair. It’s worth noting that the given implementation assumes that a valid pair exists and will return the indices of the first pair that satisfies the condition.