Two sum problem

Published: (April 3, 2026 at 10:53 PM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Cover image for Two sum problem

Hello! Today I will explain how to solve the Two Sum problem. I believe most developers have seen this problem before—either when they first started practicing coding or when preparing for job interviews.

For those in the software industry who haven’t solved this problem yet, I’ll show you how to approach it step by step.

Let’s get started.

Question

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

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

You can return the answer in any order.

Example

Input: nums = [2,11,15,7], target = 9
Output: [0,3]
Explanation: Because nums[0] + nums[3] == 9, we return [0, 3].

Solution

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

const nums = [2, 11, 15, 7];
const target = 9;

console.log(twoSum(nums, target)); // Answer: [0, 3]

Explain the solution

  • Create a function that takes two parameters: nums and target.
  • Use two loops to find two numbers in the array whose sum equals the target:
    • The outer loop iterates through each element in the array.
    • The inner loop checks the elements after the current outer loop index.
  • For example, with [2, 11, 15, 7]:
    • When the outer loop is at 2, the inner loop checks 11, 15, and 7.
  • Inside the inner loop, check whether the sum of the two numbers equals the target.
  • If it does, return their indices.
  • If no pair is found after checking all possibilities, return an empty array.
  • That’s it!

Performance consideration

This solution is easy to understand and works correctly, but it is not efficient. It uses a time complexity of O(n²) because it checks every possible pair.

In the next article, I will show you a more efficient solution that reduces the time complexity—this will be useful for interviews and real‑world applications.

Thanks for reading, and keep learning!

Reference

https://leetcode.com/problems/two-sum/description/

0 views
Back to Blog

Related posts

Read more »

PWC 367 Overlapping Oddities

Task 1 – Maximum Odd Binary It’s the week of the Artemis 2 mission to the moon, and we have a problem about odd numbers. I’d call that a Space Oddity. You are...

Weekly Challenge: Maximum conflict

markdown !Simon Greenhttps://media2.dev.to/dynamic/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fu...

Destructuring in JavaScript

Have you ever written code like this? js // repetitive extraction const numbers = 10, 20, 30; const first = numbers0; const second = numbers1; It works—but it’s...