RSS Amplifier

Harpreet's Newsletter · Jun 15, 2026

Two Sum

0
Sign in to vote or save

Harpreet Singh · Harpreet's Newsletter

Difficulty: Easy
LeetCode Pattern: Arrays & Hashing

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

Input:
· nums = [3,3]
· target = 6
Output:
· [0,1]
Input:
· nums = [2,7,11,15]
· target = 18
Output:
· [1,2]
  • Can the input array be empty?

    • Yes.

    • Return empty array.

  • Will it be sorted?

    • No.

1/ Nested Loop (Brute Force ⚠️)

  • Logic:

    • Start with value at index 0

    • Check its sum with all other values

    • If it adds up to target:

      • return the indices

    • Otherwise:

      • increment index and repeat

  • Big O:

    • Time Complexity: O(n²)

    • Space Complexity: O(1)

2/ Use a Map (Optimal ✅)

  • Logic:

    • Initialize an empty map

    • Iterate through the list

    • For each element:

      • Check if complement is in map

      • If it exists:

        • We found a solution

      • Otherwise:

        • Store in map and continue

    • Return empty array if no pair found

  • Big O:

    • Time Complexity: O(n)

    • Space Complexity: O(n)

  • What if the array is sorted?

    • Use two-pointer technique

    • No map is needed

  • How to return all valid pairs?

    • Store pairs in a list instead of returning immediately

    • Return the list after processing all elements

Read the original on singhz.substack.com

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.