Brute Force
Intuition
The most straightforward approach is to check every possible pair of numbers in the array. For each element, we look at every other element that comes after it to see if their sum equals the target. While this is inefficient, it requires no extra space and is easy to understand. This approach works because we exhaustively search all pairs, guaranteeing we find the answer if it exists.
Algorithm
- Iterate through each element nums[i] using an outer loop from index 0 to n-2.
- For each nums[i], iterate through every subsequent element nums[j] using an inner loop from index i+1 to n-1.
- Check if nums[i] + nums[j] equals the target.
- If a match is found, return the pair of indices [i, j].
O(n^2)SpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
for (int i = 0; i < nums.size(); i++) {
for (int j = i + 1; j < nums.size(); j++) {
if (nums[i] + nums[j] == target) {
return {i, j};
}
}
}
return {};
}
};class Solution {
public int[] twoSum(int[] nums, int target) {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[] { i, j };
}
}
}
return new int[] {};
}
}def twoSum(nums: list[int], target: int) -> list[int]:
for i in range(len(nums)):
for j in range(i + 1, len(nums)):
if nums[i] + nums[j] == target:
return [i, j]
return []func twoSum(nums []int, target int) []int {
for i := 0; i < len(nums); i++ {
for j := i + 1; j < len(nums); j++ {
if nums[i]+nums[j] == target {
return []int{i, j}
}
}
}
return []int{}
}