Post

POTD #6 - Two Sum - Pair with Given Sum | Geeks For Geeks

POTD #6 - Two Sum - Pair with Given Sum | Geeks For Geeks

{% raw %}

Problem Statement

Geeks For Geeks : https://www.geeksforgeeks.org/problems/key-pair5616/1

Given an array arr[] of positive integers and another integer target. Determine if there exists two distinct indices such that the sum of there elements is equals to target.

Examples

Input: arr[] = [1, 4, 45, 6, 10, 8], target = 16Output: trueExplanation: arr[3] + arr[4] = 6 + 10 = 16.

Input: arr[] = [1, 2, 4, 3, 6], target = 11Output: falseExplanation: None of the pair makes a sum of 11.

My Approach

  • Iterate through the array
  • For each element, check whether the remaining (target – element) is also present in the array using the supportive hashmap.
  • If the remaining is also present then return True.
  • Else, save the element in the hashmap and go to the next element.
#User function Template for python3class Solution:	def twoSum(self, arr, target):		# code here		maps = {}		for item in arr:		    rem = target - item		    if maps.get(rem):		        return True		    maps[item] = True		return False		

{% endraw %}

This post is licensed under CC BY 4.0 by the author.