Problem: Given an array of integers and a target number, return indices of the two numbers that add up to the target.
๐ข Input:
let arr = [1, 2, 6, 9, 3, 2, 8, 7];
let resultNumber = 10;
  ๐ง Brute Force Approach:
This solution checks all possible pairs (i, j) in the array.
let indexes = [];
for(let i = 0; i < arr.length; i++) {
  for(let j = i + 1; j < arr.length; j++) {
    if(arr[i] + arr[j] === resultNumber) {
      indexes.push([i, j]);
    }
  }
}
console.log(indexes);
  ๐ Time Complexity:
O(n²) – because we check each pair of elements once.
๐งฉ Sample Output:
[ [ 0, 3 ], [ 1, 6 ], [ 4, 7 ], [ 5, 6 ] ]
  ๐ก Optimization Tip:
We can reduce time complexity to O(n) using a hash map. Stay tuned for the optimized version in my next post!
✅ Summary:
- Clear understanding of nested loops
 - Simple yet effective for small input sizes
 - Ideal for beginners practicing DSA
 
If you liked this post, follow my blog or connect with me on LinkedIn!
Comments
Post a Comment