How to Solve the Two Sum Challenge on LeetCode

NatureNature
4 min read

๐Ÿงฉ Two Sum โ€“ Explained simply

๐Ÿš€ Difficulty: Easy | ๐Ÿ’ผ Asked in Many Interviews


๐Ÿ“˜ The Problem (from LeetCode)

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 must:

  • Return exactly one solution (you can assume there is always one)

  • Not use the same element twice

  • Return the indexes (positions) of the numbers, not the numbers themselves

  • The order of the result doesnโ€™t matter


๐Ÿ’ก Letโ€™s Understand With an Example:

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

We need to find two numbers from the array whose sum is 9.

Letโ€™s try:

  • 2 + 7 = โœ… 9 โ†’ Found at index 0 and 1

Answer: [0, 1]


๐ŸŽ“ Real-Life Analogy:

Imagine you're shopping. Your friend gives you โ‚น9 and a list of item prices. You need to pick 2 items that exactly total โ‚น9.

Item prices = [2, 7, 11, 15]
You pick โ‚น2 (item at index 0) and โ‚น7 (index 1). Thatโ€™s the answer โ†’ [0, 1].


โ— Common Misunderstanding

Some people only check each element and the next one (i and i+1). But what if the answer is in some other pair (like index 1 and 3)? That logic will miss some valid answers.

We need to try every pair, not just adjacent ones.


๐Ÿง Solution 1: Brute Force (Beginner Friendly)

Try every possible pair of numbers. If their sum is the target, return their indexes.

๐Ÿงฎ Logic:

  • Loop over each number with index i

  • Inside that loop, loop over every number after i (index j)

  • Check if nums[i] + nums[j] == target

  • If yes, return [i, j]

๐Ÿ• Time Complexity:

  • O(n^2) (nested loops)

  • ๐Ÿง  Pseudocode:

      Loop i from 0 to length-1
          Loop j from i+1 to length
              if nums[i] + nums[j] == target
                  return [i, j]
    

๐Ÿ’ป PHP Code

class Solution {
    function twoSum($nums, $target) {
        $n = count($nums); // Get the size of the array
        for ($i = 0; $i < $n; $i++) {
            for ($j = $i + 1; $j < $n; $j++) {
                // Check if this pair sums up to the target
                if ($nums[$i] + $nums[$j] == $target) {
                    return [$i, $j]; // Return their positions
                }
            }
        }
        return []; // Return empty if no pair found
    }
}

โ˜• Java Code

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[] { i, j };
                }
            }
        }
        return new int[] {};
    }
}

๐Ÿ Python Code

class Solution:
    def twoSum(self, nums, target):
        n = len(nums)
        for i in range(n):
            for j in range(i + 1, n):
                if nums[i] + nums[j] == target:
                    return [i, j]
        return []

๐ŸŒ JavaScript Code

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 [];
}

๐Ÿ’ก Solution 2: Optimized Using Hash Map (For Faster Performance)

Instead of checking every pair, we can:

  • Use a hash map to remember numbers weโ€™ve already seen

  • For each number, check if target - current number already exists in the map

โœ… Time: O(n), Space: O(n)

Python (Optimized):

class Solution:
    def twoSum(self, nums, target):
        seen = {}
        for i, num in enumerate(nums):
            complement = target - num
            if complement in seen:
                return [seen[complement], i]
            seen[num] = i

โœ… Summary

ApproachTime ComplexitySpaceEasy to Understand
Brute ForceO(nยฒ)O(1)โœ…
Hash MapO(n)O(n)โŒ (slightly tricky)

๐Ÿ“’ Final Tips

  • Master brute force first โ†’ it's simple and helps understand the problem.

  • Later, try to learn the hash map method โ€” it's fast and often asked in interviews.

  • Practice writing in multiple languages (like we just did!) โ€” great for polyglot devs.


0
Subscribe to my newsletter

Read articles from Nature directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Nature
Nature