Leetcode 1: Two Sum

grid47
grid47
Exploring patterns and algorithms
Nov 6, 2024 5 min read

A pair of floating, glowing puzzle pieces coming together in a soft light.
Solution to LeetCode 1: Two Sum Problem

Given an array of integers nums and a target integer target, find and return the indices of two distinct numbers in the array that sum up to the given target. The solution is guaranteed to exist for the given input. You can return the indices in any order.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of integers and a target integer.
Example: nums = [1, 5, 7, 3], target = 8
Constraints:
• 2 <= nums.length <= 10^4
• -10^9 <= nums[i] <= 10^9
• -10^9 <= target <= 10^9
Output: Return the indices of two numbers that add up to the target as an array of integers.
Example: [0, 2]
Constraints:
• The indices returned should be valid for the given input array.
• The two numbers must be distinct elements of the array.
Goal: Identify the indices of two numbers that sum up to the given target.
Steps:
• Iterate through the array while maintaining a mapping of the difference between the target and each number to its index.
• For each number, check if it exists in the map. If it does, return its index and the current index.
• If no pair is found during the iteration, return an error (though the problem guarantees a solution).
Goal: Conditions that the input will always meet.
Steps:
• Each input will have exactly one solution.
• You may not use the same element twice.
Assumptions:
• All inputs are valid.
• There will always be exactly one solution.
Input: nums = [1, 5, 7, 3], target = 8
Explanation: The numbers at indices 0 and 2 (1 and 7) sum to 8, so the output is [0, 2].

Input: nums = [4, 6, 10], target = 16
Explanation: The numbers at indices 1 and 2 (6 and 10) sum to 16, so the output is [1, 2].

Input: nums = [2, 8, 12], target = 10
Explanation: The numbers at indices 0 and 1 (2 and 8) sum to 10, so the output is [0, 1].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus