💡
Seb's Whiteboard
  • 👨‍💻Welcome, I'm Sebastien St Vil
  • Extras
    • Gradient Descent
    • How I learned Java
    • Machine Learning by Andrew Ng
  • Projects
    • 📉Backtest Equity Trading with SMA Strategy
    • Wellington GA Lab
    • Stock analysis
    • 📈Time Series Regression-based Trading Strategy
  • Arrays & Strings
    • Best Time to Buy and Sell Stock II
    • Online Stock Span
    • Implement strStr()
    • 2Sum
    • 3Sum
    • 3Sum Closest
    • 4Sum II
    • Set Matrix Zeroes
    • Group Anagrams
    • Longest Substring Without Repeating Characters
    • Remove Duplicates from Sorted Array
    • Move Zeroes
    • Valid Sudoku
    • Rotate Image
    • First Unique Character in a String
    • Design a Circular Queue
    • Longest Common Prefix
  • Binary Tree
  • Second Minimum Node In a Binary Tree (671)
  • Design
  • LRU Cache
  • Min Stack (155)
  • Sorting & Searching
    • Merge Sorted Array (88)
    • First Bad Version
  • Math
    • Power of Three (326)
    • Power of Two (231)
    • Count Prime (204)
    • Roman to Integer (13)
    • Fizz Buzz (412)
    • Count-and-Say
  • Dynamic Programming
    • Pascal's Triangle (118)
  • Linked List
    • Copy List with Random Pointer
    • Remove Nth Node From End of List
    • Remove Duplicated from Sorted List II
  • Tips
    • Finding dups
  • Sliding Window
    • Subarray Product Less Than K
Powered by GitBook
On this page
  • Approach1: Dictionnary or Map
  • Approach: Java Version

Was this helpful?

  1. Arrays & Strings

2Sum

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.

Example 1:

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

Approach1: Dictionnary or Map

The general key to this problem is to be aware that there will always be one pair of numbers that will satisfy the target value. If we assume that the list contains element (x1, x2, x3, xn), there will inevitably be a pair that exists such that xa + xb = target.

  • We first create a Dictionnary d that will map all elements of the list to their respective index.

  • We then notice that we're able to solve the problem in one pass as we change the equation above to xa = target - xb. Since we already know the target, as long as we maintain all previous numbers to our records as we iterate, we will be able to verify whether xa = target - xb or xb = target - xa. Either way, we will find a corresponding pair.

  • We iterate over the elements of list num, we verify whehther the dictionnary contains the complement pair. If it does not contain it, we add the element as well as it's index to the dictionary otherwise if it does, we have found a pair of element which equals the target.

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

Time: O(n) Space: O(n)

Approach: Java Version

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(target - nums[i])){
                return new int[] {map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        return new int[]{-1, -1};
    }
}
PreviousImplement strStr()Next3Sum

Last updated 4 years ago

Was this helpful?