Introduction
In this problem, we need to find two numbers that add up to a given target.
Since the array is already sorted, we can use a more efficient approach instead of checking all possible pairs.
Problem Explanation
You are given:
- A sorted array of integers (
numbers) - A target value
Find two numbers such that their sum equals the target and return their indices using 1-based indexing.
Example
Input: numbers = [2, 7, 11, 15], target = 9
Output: [1, 2]
Because 2 + 7 = 9
Approach Used β Two Pointer Technique
-
Use two pointers:
-
leftat the beginning -
rightat the end
-
Move the pointers based on the sum until the target is found.
Code (Python)
class Solution:
def twoSum(self, numbers: list[int], target: int) -> list[int]:
left = 0
right = len(numbers) - 1
while left < right:
current_sum = numbers[left] + numbers[right]
if current_sum == target:
return [left + 1, right + 1]
elif current_sum < target:
left += 1
else:
right -= 1
Code Explanation (Step by Step)
Line 1
class Solution:
Defines the class required by LeetCode.
Line 2
def twoSum(self, numbers: list[int], target: int) -> list[int]:
Defines the function:
-
numbersis the input array -
targetis the required sum - Returns a list of indices
Line 3
left = 0
Initializes the left pointer at the beginning of the array.
Line 4
right = len(numbers) - 1
Initializes the right pointer at the end of the array.
Line 5
while left < right:
Runs the loop until both pointers meet.
Ensures we do not use the same element twice.
Line 6
current_sum = numbers[left] + numbers[right]
Calculates the sum of elements at the current pointers.
Line 7β8
if current_sum == target:
return [left + 1, right + 1]
If the sum equals the target:
- Return indices
- Add 1 because the problem uses 1-based indexing
Line 9β10
elif current_sum < target:
left += 1
If the sum is smaller than the target:
- Move the left pointer forward
- This increases the sum
Line 11β12
else:
right -= 1
If the sum is greater than the target:
- Move the right pointer backward
- This decreases the sum
Complexity
- Time Complexity: O(n)
- Space Complexity: O(1)
Conclusion
The two pointer technique efficiently solves this problem by using the sorted nature of the array, reducing time complexity and avoiding extra space.
United States
NORTH AMERICA
Related News
Jeff Bezos Seeking $100 Billion to Buy Manufacturing Companies, 'Transform' Them With AI
9h ago
Firefox Announces Built-In VPN and Other New Features - and Introduces Its New Mascot
9h ago
Can Private Space Companies Replace the ISS Before 2030?
9h ago
Juicier Steaks Soon? The UK Approves Testing of Gene-Edited Cow Feed
9h ago
White House Unveils National AI Policy Framework To Limit State Power
9h ago