0% completed
Pair with Target Sum (easy)
On This Page
Problem Statement
Try it yourself
Problem Statement
Given an array of numbers sorted in ascending order and a target sum, find a pair in the array whose sum is equal to the given target.
Write a function to return the indices of the two numbers (i.e. the pair) such that they add up to the given target. If no such pair exists return [-1, -1].
Example 1:
Input: [1, 2, 3, 4, 6], target=6
Output: [1, 3]
Explanation: The numbers at index 1 and 3 add up to 6: 2+4=6
Example 2:
Input: [2, 5, 9, 11], target=11
Output: [0, 2]
Explanation: The numbers at index 0 and 2 add up to 11: 2+9=11
Constraints:
- 2 <= arr.length <= 10<sup>4</sup>
- -10<sup>9</sup> <= arr[i] <= 10<sup>9</sup>
- -10<sup>9</sup> <= target <= 10<sup>9</sup>
- Only
onevalid answer exists.
Try it yourself
Try solving this question here:
Anonymous
· 3 years ago
There's a test case in the problem that violates the assumption that only a single valid answer exists.
Example:
arr = [2,30,33,64,67,98]
target_sum = 100
This scenario has two valid answers: [0, 5] and [2, 4].
Anonymous
· 3 years ago
class Solution: def search(self, arr, target_sum): # TODO: Write your code here l, r = 0, len(arr) - 1 while l<r: curr= arr[l] + arr[r] if curr>target_sum: r-=1 elif curr<target_sum: l+=1 else: return [l,r] return [-1, -1]
Anonymous
· 3 years ago
Question text should say to return -1,-1 when no result exists.
Anonymous
· 4 years ago
FYI if anyone else thinks they're going crazy two-pointer and sliding window have switched spots. I think it's a correct move as sliding window feels like a more specialized version of two-pointer so you get the benefit of general to specifics.
Anonymous
· 4 years ago
I think it's important to mention that the solution with a HashMap works even when the array is unsorted.
Anonymous
· 4 years ago
I keep getting [-1,-1]as the result even though its clear that there is a correct answer from the output
Anonymous
· 5 years ago
This one is NOT working on LeetCode. Can someone help me with this please?
Anonymous
· 5 years ago
Anyone can explain why the return is [-1,-1] here?
function pair_with_target_sum(arr, targetSum) { const nums = {}; // to store numbers and their indices for (let i = 0; i < arr.length; i++) { const num = arr[i]; if (targetSum - num in nums) { return [nums[targetSum - num], i]; } nums[arr[i]] = i; } return [-1, -1]; }
Anonymous
· 5 years ago
The first solution for "Pair with Target Sum. I guess it is not working for the inputs. [3,2,4] and target as 6;
pair_with_target([3,2,4], 6)
Reading Progress
0%
On This Page
Problem Statement
Try it yourself