Google Coding Problem- #001

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:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

CODE

def twoSum(arr1, sum1):
    dict1= {}
    for i, v in enumerate(arr1):
        remaining = sum1 - v
        if remaining in dict1:
            return [dict1[remaining], i]
        dict1[v] = i
    return []
arr = [2, 7, 11, 15]
sum1 = 9
twoSum(arr, sum1)

Output:          [0, 1]

Time Complexity: O(n)

Space Complexity: O(n)

Given a list of numbers, return whether any two sums to k.
For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17.

CODE

def twoSum(arr, sum1):
    num_set = set()
    for num in arr:
        if (sum1-num) in num_set:
            return True
        else:
            return False
        num_set.add(num)
arr = [2, 7, 11, 15]
sum1 = 9
twoSum(arr, sum1)

Output:          True

Time Complexity: O(n)

Space Complexity: O(n)

Leave a comment