Two sum interview question asked by Amazon|Google|Nagarro

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, and you may not use the same element twice.

You can return the answer in any order.

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

Constraints:

  • 2 <= nums.length <= 104
  • -109 <= nums[i] <= 109
  • -109 <= target <= 109
  • Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n2time complexity?

In simple words.

Interview will give us a array with integer number and one target number. We need to return the index of 2 elements those sum will be equal to target number.

Solution 1, if your array is sorted:

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        
        res = []
        for i in range(len(nums)):
            for c in range(i+1, len(nums)):
                result = nums[i] + nums[c]
                if result == target:
                    res.append(i)
                    res.append(c)
        return res

Solution 2, if your array is not sorted:

# Here am pring number itself, you can print index of those number as well.
def sum_of_two_numbers_with_hash_map(nums, target):
    #TODO: Working with sorted/unsorted array
    #TODO: O(n)
    map = {}
    for i, v in enumerate(nums):
        if (target - nums[i]) in map:
            print([(target - nums[i]), nums[i]])
            break
        else:
            map[v] = i

num = [2,3,5,7,11,6, 13]
sum_of_two_numbers_with_left_right_pointer(nums=num, target=12)
Two sum interview question asked by Amazon|Google|Nagarro
Show Buttons
Hide Buttons