Find Pair With Target Sum
Given an array of integers and a target integer, find two numbers in the array that add up to the target. This is a fundamental problem in computer science with applications in data searching and optimization algorithms.
Problem Description
You are tasked with writing a function that takes an array of integers nums and an integer target as input. Your goal is to find two distinct indices in the nums array such that the elements at those indices sum up to the target.
Requirements:
- The function should return a list or array containing the two indices.
- You can assume that each input will have exactly one solution.
- You must not use the same element twice.
Expected Behavior:
If nums = [2, 7, 11, 15] and target = 9, the function should return [0, 1] because nums[0] + nums[1] = 2 + 7 = 9.
Edge Cases:
- What if the array contains negative numbers?
- What if the array contains duplicate numbers? (Remember, you cannot use the same element twice, but you can use two occurrences of the same value if they are at different indices).
Examples
Example 1:
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Explanation: nums[0] + nums[1] = 2 + 7 = 9.
Example 2:
Input: nums = [3, 2, 4], target = 6
Output: [1, 2]
Explanation: nums[1] + nums[2] = 2 + 4 = 6.
Example 3:
Input: nums = [3, 3], target = 6
Output: [0, 1]
Explanation: nums[0] + nums[1] = 3 + 3 = 6.
Constraints
2 <= nums.length <= 10^4-10^9 <= nums[i] <= 10^9-10^9 <= target <= 10^9- Guaranteed: Exactly one solution exists.
Notes
Consider the trade-offs between different approaches in terms of time and space complexity. Think about how you can efficiently search for the "complement" of each number (i.e., target - current_number) within the array.