1. Nested Loops Pair Check (Brute Force)
Intuition
Iterate across all pairs i from 0 to n-1 and j from i+1 to n-1. If numbers[i] + numbers[j] == target, return [i + 1, j + 1].
When to apply: Use to verify 1-based index requirements.
Nested Loops (O(N^2) Time)
2 of 2 questions left todayFirst pair evaluated satisfies the target condition
First pair evaluated satisfies the target condition.
public class Main { public static class Solution { public int[] twoSum(int[] numbers, int target) { for (int i = 0; i < numbers.length; i++) { for (int j = i + 1; j < numbers.length; j++) { if (numbers[i] + numbers[j] == target) { return new int[]{i + 1, j + 1}; } } } return new int[]{-1, -1}; } } public static void main(String[] args) { Solution sol = new Solution(); int[] numbers = {2, 7, 11, 15}; int target = 9; int[] ans = sol.twoSum(numbers, target); System.out.println("Indices: [" + ans[0] + ", " + ans[1] + "]"); }}Time & Space Complexity
- Time complexity:
O(n^2)— Nested loops examine all n*(n-1)/2 pairs. - Space complexity:
O(1)— O(1) auxiliary space.
Why Brute Force Doesn't Scale:
For N = 30,000, N2 / 2 = 4.5 * 108 operations, exceeding typical 1-second CPU time limits.
The Two Pointer method checks at most N elements total, finishing in under 2ms with zero dynamic memory allocation.