FastPrepTarget-Sum Pair with Two Pointers

Target-Sum Pair with Two Pointers

Microsoft logoMicrosoft● EasyFULLTIMEPHONE SCREEN
Learn

Problem statement

Return true if two values at distinct array positions sum to target; otherwise return false. Input order is arbitrary and repeated values are allowed. An array with fewer than two entries returns false.

For the final approach, sort a copy and use two pointers moving inward from the smallest and largest values. The scan takes linear time after sorting.

Function

hasTargetSumPair(nums: int[], target: int) → boolean

Examples

Example 1

nums = [3,1,4,2]target = 6return = true

The values 4 and 2 occur at distinct positions and sum to 6.

Example 2

nums = [3,1]target = 6return = false

The single occurrence of 3 cannot be reused.

Example 3

nums = [-2,0,1,3]target = 1return = true

A negative value and a positive value can form a valid pair.

Constraints

  • 0 <= nums.length <= 5000.
  • -1000000000 <= nums[i], target <= 1000000000.

More Microsoft problems

See Microsoft hiring insights
public boolean hasTargetSumPair(int[] nums, int target) {
    return false;
}
nums[3,1,4,2]
target6
expectedtrue
Checking account…