Leetcode: Two Sum Problem Explained (For Beginners)

shinoX3N9

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

Example:
  • nums = [2, 7, 11, 15], target = 9
  • Output: [0, 1]
  • Explanation: 2 + 7 = 9 (indices 0 and 1)

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

# Example usage:
nums = [2, 7, 11, 15]
target = 9
print(twoSum(nums, target))  # Output: [0, 1]

Explanation for Dummies:
  • Look at each number in the list.
  • For every number, check every other number after it to find a pair that adds up to your target number.
  • If you find them, return their positions (indices) in the list.

Feel free to comment with your questions or share other solutions!
 

About this Thread

  • 1
    Replies
  • 255
    Views
  • 2
    Participants
Last reply from:
jisoo69

Trending Topics

Online now

Members online
670
Guests online
1,896
Total visitors
2,566

Forum statistics

Threads
2,268,250
Posts
28,921,166
Members
1,243,882
Latest member
kurt3434
Back
Top