2 Sum

From InterviewBit:

Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 < index2. Please note that your returned answers (both index1 and index2 ) are not zero-based. 
Put both these numbers in order in an array and return the array from your function ( Looking at the function signature will make things clearer ). Note that, if no pair exists, return empty list.
If multiple solutions exist, output the one where index2 is minimum. If there are multiple solutions with the minimum index2, choose the one with minimum index1 out of them.

Solution / Approach

Naive solution will be iterating through all element and compare it through other element ( O(n2)).

It’s a good idea to track value that you already evaluated in a set, then search through it when you stumble upon a new value. Check if the diff between target with currentValue exists in the set.

def twoSum(self, A, B):
        d = {}
        for i, a in enumerate(A):
            r = B-a
            if r in d:
                return [d[r]+1, i+1]
            if a not in d:
                d[a] = i
                
        return [] 

Next question: with this idea, can you solve if the target supposed to be from 4 numbers? And it’s possible for a list to have many combinations of the solution. Return all the solutions!

Diterbitkan oleh muzavan

A software engineer from Indonesia. I like puzzle, code, comedy, and wrestling, so, probably will write stuff about those.

Tinggalkan komentar