Two Sum

Easy

10 min read

April 5, 2025

Problem Statement

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Understanding the Problem

The goal here is simple: given an array of numbers and a target sum, I need to find two different indices where the numbers at those positions add up to the target.

For example, if I have nums = [2, 7, 11, 15] and target = 9, I should return [0, 1] because 2 + 7 = 9.

Solution Approach

For this version, I kept it simple and went with a brute-force approach.

Here’s what I did:

  1. I loop through the array using two pointers — one starting at i, the other at j = i + 1.
  2. For each pair of numbers, I check if their sum equals the target.
  3. If it does, I push their indices into a result array.
  4. Once the loops are done, I return that array.

This method is easy to understand and works fine for small inputs. But because it checks every possible pair, it ends up being O(n²) in terms of time complexity — which isn’t ideal for bigger arrays.

Code Implementation

function twoSum(nums: number[], target: number): number[] {
let arr: number[] = []
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] + nums[j] === target) arr.push(i, j)
}
}

return arr
};

Time and Space Complexity

O(N2)

Testing

Result of valid parenthesis
Valid Parenthesis — Result

Takeaways

I like starting with the straightforward solution first — just get it working, make sure I understand the problem. This brute-force method does exactly that.

But in a real-world or professional setting, performance matters. I’d definitely go for a more optimized approach, like using a hash map to get it down to O(n).

Still, there’s nothing wrong with starting simple — as long as I remember to level it up when it counts.