top of page

Two Sum Problem

  • Shreyas Naphad
  • Jun 4, 2024
  • 1 min read

Updated: Jun 6, 2024

In this article, we will be solving a commonly asked question on the array which is the 2 sum problem. So in this problem, we are given an array of N integers and a target integer. We aim to find two elements in the array whose sum is equal to the target.

Example:

N = 5

Arr = [2,1,8,0,4]

Target = 12

Output: Yes

8 + 4 = 12 where both 8 and 4 are present in the array.

 

Solution:


Explanation:

·       We aim to search for two numbers in the array that give a sum up to the given target.

·       We use an unordered map to store each number's index as we iterate through the array.

·       For every number in the array, we chec whethr the difference between the target and the current number is present in the map or not.

·        If the difference is found in the map, it means the pair of numbers sum up to the target, and we return true.

·       If no such pair is found after iterating through the entire array, we return false.

 

Time Complexity: O(n)

Space Complexity: O(n)

Comments


©2025 by DevSparks.

bottom of page