🧠
Sorting + Two Pointers (Not Applicable Here)
💡 Sorting and two pointers is a common approach for sum problems but not suitable here because we must return original indices.
Intuition
Sort the array and use two pointers from start and end to find the sum, but sorting changes indices.
Algorithm
- Copy and sort the array while keeping track of original indices.
- Use two pointers at start and end to find two numbers summing to target.
- Return the original indices of these two numbers.
💡 This approach requires extra bookkeeping and is less efficient due to sorting.
from typing import List
def two_sum(nums: List[int], target: int) -> List[int]:
nums_with_index = list(enumerate(nums))
nums_with_index.sort(key=lambda x: x[1])
left, right = 0, len(nums) - 1
while left < right:
current_sum = nums_with_index[left][1] + nums_with_index[right][1]
if current_sum == target:
return [nums_with_index[left][0], nums_with_index[right][0]]
elif current_sum < target:
left += 1
else:
right -= 1
# Driver code
if __name__ == '__main__':
print(two_sum([2,7,11,15], 9)) # Output: [0, 1]
Line Notes
nums_with_index = list(enumerate(nums))Pair each number with its original index
nums_with_index.sort(key=lambda x: x[1])Sort pairs by number value
while left < right:Two pointers to find sum
return [nums_with_index[left][0], nums_with_index[right][0]]Return original indices when sum found
import java.util.*;
public class TwoSum {
public static int[] twoSum(int[] nums, int target) {
int n = nums.length;
int[][] numsWithIndex = new int[n][2];
for (int i = 0; i < n; i++) {
numsWithIndex[i][0] = i;
numsWithIndex[i][1] = nums[i];
}
Arrays.sort(numsWithIndex, Comparator.comparingInt(a -> a[1]));
int left = 0, right = n - 1;
while (left < right) {
int sum = numsWithIndex[left][1] + numsWithIndex[right][1];
if (sum == target) {
return new int[]{numsWithIndex[left][0], numsWithIndex[right][0]};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[0];
}
public static void main(String[] args) {
int[] result = twoSum(new int[]{2,7,11,15}, 9);
System.out.println(Arrays.toString(result)); // [0, 1]
}
}
Line Notes
int[][] numsWithIndex = new int[n][2];Store pairs of index and value
Arrays.sort(numsWithIndex, Comparator.comparingInt(a -> a[1]));Sort by value
while (left < right) {Two pointers to find sum
return new int[]{numsWithIndex[left][0], numsWithIndex[right][0]};Return original indices
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> twoSum(vector<int>& nums, int target) {
int n = nums.size();
vector<pair<int,int>> numsWithIndex;
for (int i = 0; i < n; i++) {
numsWithIndex.push_back({i, nums[i]});
}
sort(numsWithIndex.begin(), numsWithIndex.end(), [](const pair<int,int>& a, const pair<int,int>& b) {
return a.second < b.second;
});
int left = 0, right = n - 1;
while (left < right) {
int sum = numsWithIndex[left].second + numsWithIndex[right].second;
if (sum == target) {
return {numsWithIndex[left].first, numsWithIndex[right].first};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return {};
}
int main() {
vector<int> nums = {2,7,11,15};
vector<int> res = twoSum(nums, 9);
cout << "[" << res[0] << ", " << res[1] << "]" << endl; // [0, 1]
return 0;
}
Line Notes
vector<pair<int,int>> numsWithIndex;Store pairs of original index and value
sort(numsWithIndex.begin(), numsWithIndex.end(), [](const pair<int,int>& a, const pair<int,int>& b) {Sort pairs by value using custom comparator
while (left < right) {Two pointers to find sum
return {numsWithIndex[left].first, numsWithIndex[right].first};Return original indices
function twoSum(nums, target) {
const numsWithIndex = nums.map((num, idx) => [num, idx]);
numsWithIndex.sort((a, b) => a[0] - b[0]);
let left = 0, right = nums.length - 1;
while (left < right) {
const sum = numsWithIndex[left][0] + numsWithIndex[right][0];
if (sum === target) {
return [numsWithIndex[left][1], numsWithIndex[right][1]];
} else if (sum < target) {
left++;
} else {
right--;
}
}
return [];
}
// Test
console.log(twoSum([2,7,11,15], 9)); // [0, 1]
Line Notes
const numsWithIndex = nums.map((num, idx) => [num, idx]);Pair each number with original index
numsWithIndex.sort((a, b) => a[0] - b[0]);Sort pairs by number value
while (left < right) {Two pointers to find sum
return [numsWithIndex[left][1], numsWithIndex[right][1]];Return original indices when sum found
Sorting takes O(n log n), two pointers scan in O(n), total O(n log n)
💡 For n=100000, sorting is slower than hash map approach but still acceptable.
Interview Verdict: Accepted but not preferred due to sorting overhead and complexity
Good to mention to show knowledge but hash map is better here.