Saurabh Mishra
Saurabh Mishra's Blog

Saurabh Mishra's Blog

2 number sum problem

Photo by Glenn Carstens-Peters on Unsplash

2 number sum problem

Easy

Saurabh Mishra's photo
Saurabh Mishra
·Aug 1, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Problem Statement

LeetCode link

Screenshot 2022-08-01 at 5.13.40 PM.png

Approach

Random thought/BruteForce

Initially looking at the problem there might be multiple solution came into your mind. My initial thought was kind of linear search for finding the result/appropriate number from array.

But that will not be the best solution as you will keep iterating to find an element from array , and this is the thing where we can optimise our solution i.e Searching. So if somehow we can directly get to know that certain element is there in array or not our job will be very easy and code also looks good at the same time.

To solve that we need to somehow use Hashmap or Dictionary. So lets see the solution now.

class Solution {
    func twoSum(_ nums: [Int], _ target: Int) -> [Int] {
        var dict = [Int: Int]()
        for (index, item) in nums.enumerated() {
            let value = target - item 
            //this piece of code is storing and searching element at the same time
            // previousIndex != index -> important condition to check
            if let previousIndex = dict[value], previousIndex != index {
                return [previousIndex, index]
            } else {
                dict[item] = index
            }
        }
        return []
    }
}

Twist

What if problem changed a little bit and now inspite of printing index , output should contains those numbers.

Let's see the solution for that , very minor change and job done.

class Solution {
  func twoSum(_ array: inout [Int], _ targetSum: Int) -> [Int] {
    var dict = [Int: Int]()
    for (index, item) in array.enumerated() {
      let numberToFind = targetSum - item
      if let previousIndex = dict[numberToFind], previousIndex != index {
        // we got the number
        return [numberToFind, item]
      } else {
        dict[item] = index
      }
    }
    return []
  }
}

Tip

Do not try to use inbuilt functions of Swift like isContains, that will be little problematic and also not a optimise solution.

 
Share this