Two Sum
LeetCode - 0001 Two Sum (Easy)
https://leetcode.com/problems/two-sum/
Problem Description
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
1 | Given nums = [2, 7, 11, 15], target = 9, |
Solutions
Brute Force
The easiest way of solving the problem is by using two loops to go through all the numbers in an array, and see if the result matches the target number. However, the time complexity will not be good for this method.
1 | class Solution { |
- Time complexity is O(n^2) due to two loops
- Space complexity is O(1)
Two-pass Hash Table
In order to improve run time complexity, a more efficient way to check if the complement exists in the array is needed. By using hash map, we are able to do lookup in a constant time.
1 | class Solution { |
- Time complexity: O(n)
- Space complexity: O(n)
One-pass Hash Table
It turns out that we can do it in one-pass. By iterating and inserting elements into the table, we can also look back and check if current element’s complement already exists in the table. If so, we have found the solution and return immediately.
1 | class Solution { |
- Time complexity: O(n)
- Space complexity: O(n)
1 | class Solution: |