LeetCode: Two Sum (Solution in Python & Explanation)

In this article, I will be explaining how to solve the Two Sum problem on LeetCode. This is an Easy-level question for Arrays.

The Problem

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.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

The Solution

The most straightforward way to solve this problem is to check every combination of two values in the array and see if they can sum up to the target value. To do this, we would iterate through the entire array and for each item we would iterate through the array a second time to check the sums of the current array item with every other item in the array and see if they are the target. The (worst-case) runtime for this solution method is not very efficient: O(n2).

There is a better solution that only requires us to loop through the array once. Basically, if we could loop through the array and, for each array item, check if the number that adds with that value to get the target exists in the array using an operation that doesn’t have O(n) time complexity, then we could make our program much faster. We can do this by using a hash map.

We create a hash map that will store array items as keys and their indexes in the array as values ({array_value: array_index})

We use the enumerate function to get the index of the current item as we loop through the array. For each array item, we compute the difference diff between the target value and the item’s value. Since target - n = diff, that means diff + n = target. If this difference diff is in the hash map, then that means that the value has already been seen in the array. Thus, we’ve found the . If the difference is not in the array, then we add the current array item and its index to the hash map then move to the next array item.

def twoSum(self, nums: List[int], target: int) -> List[int]:
        hm = {} 
        for i, n in enumerate(nums): 
            diff = target - n 
            if diff in hm:
                    return [hm[diff], i]
            hm[n] = i

This solution has a time complexity of O(n) because we only have to loop through the nums array once and the lookup and insert operations into the hash map have a runtime of O(1). Although, we do have to use extra memory to create the hash map. The memory complexity is O(n) because we could potentially add every value to the hash map.

Complete Guide to JavaScript ES6 Destructuring

Destructuring assignment is a JavaScript technique in which you take the values from an array or the properties from an object and assign them to local variables.

Using destructuring allows you to write code that is cleaner, more concise, and more readable.

We will first look at destructuring rules for arrays then for objects.

Arrays

Let’s say we have an array of emojis:

const emojis = ['🐶', '🐱', '🐭'];

We want to pull out the values and assign them to local variables. We have two options of doing this:

 Option 1: One-by-One

const dog = emojis[0]; 
const cat = emojis[1];
const mouse = emojis[2];

By using destructuring assignment, you can accomplish the same thing with just one simple line.

 Option 2: Destructuring

const [dog, cat, mouse] = emojis;

Syntax for Destructuring an Array

Follow the const with a set of brackets []. Inside the brackets, you can assign a variable name for each index in the array. The variable’s value will coincide with the index at which it matches in the array.

Omit values from destructuring

If there is an array value that you don’t want to assign to a variable, you can omit it from the destructuring by adding a comma without a variable name to skip that index. In the example below, we are omitting cat:

const [dog, , mouse] = emojis;

Put remaining values in separate array

If you only want to name the first couple values and accumulate the rest into a smaller array, use the spread syntax (...)

In the example below, we are creating a variable for the first element then putting the rest in a shortened array:

const [dog, ...rest] = emojis;
console.log(rest) // outputs ['🐱', '🐭']

Provide a default value

You can set a default value for the element at an index in case the value in the array is undefined. Think of it like a “fallback” value.

const emojis = [undefined, '🐱', '🐭'];
const [dog = '🐕', cat, mouse] = emojis;
console.log(dog) // outputs '🐕'

Objects

Let’s say we have an object describing a person:

const person = {
name: 'Alex',
age: 23,
inSchool: true
}

We want to pull out the properties of the object and assign them to local variables. We have two options of doing this:

 Option 1: One-by-One

const name = person.name;
const age = person.age;
const inSchool = person.inSchool;

 Option 2: Destructuring

const { name, age, inSchool } = person;

Syntax for Destructuring an Object

Follow the const with a set of braces {}. Inside the braces, put the names of object properties that you want.

The variable names in the destructured object (on the left of the equals) must match the property names exactly.

Use custom variable name for property

To use a different name for the variable than what’s provided on the object itself, put the property name then a colon followed by the new variable name.

const { name: personName, age, inSchool } = person;
console.log(personName) // outputs 'Alex'

Defining a new name is useful when dealing with name collisions or when destructuring with JSON objects whose property names are not valid variable names because they’re strings.

Nested property destructuring

You can also access the properties of objects within objects through destructuring.

const people = {
   person = {
      name = 'Bob'
   }
}

const { person: { name } } = people;
console.log(name) // outputs 'Bob'

Provide a default value

You can provide a default value for a property in case the object does not have that property.

Since the person object we defined above doesn’t have a job property, it will be set to the default value ( ‘Unemployed’):

const { name, age, inSchool, job = 'Unemployed' } = person;

Challenge

We have an array of dogs:

const dogs = [
{ name: "Sally", age: 6, children: { name: "Blue", age: 1 }},
{ name: "Fido", age: 4 },
{ name: "Sissy", age: 3},
]

How would you use destructuring to assign a variable for Sally’s child’s name with just two lines?


Answer:

const [sallyInfo,] = dogs;
const { children: { blueName } } = sallyInfo;
console.log(blueName)   // outputs 'Blue'

I hope you enjoyed this lesson. Thanks for reading! Comment any questions.