Prepin
Log in

G

Desired Total

Approach / Explanation

The Target Sum problem is a frequently encountered interview question that evaluates your knowledge of data structures and algorithms. In this challenge, you receive an array of integers along with a target sum, and your objective is to identify two numbers within the array that total the target sum. Here are some important points to help you tackle this question: Clarify the inputs: You are provided with an array of integers and a target sum. Clarify the objective: Your goal is to find two numbers in the array that together equal the target sum. Devise your strategy: This problem suggests utilizing a hash table (JavaScript object) to keep the numbers from the array as keys and their respective indices as values. You can iterate through the array, and for each number, compute the difference between the target sum and that number. If this difference is already a key in the hash table, you have found the pair that sums to the target. Account for edge cases: If there are no two numbers that add up to the target, your function should reflect this, potentially by returning None or an empty list. Enhance your solution: By employing a hash table, you can resolve this problem with a time complexity of O(n), as a single pass through the array is sufficient.

Suggested Answer

For example, given the array [1, 2, 3, 4, 5] with a target sum of 7, we can approach the problem as follows: We start by creating an empty hash table named numHash . Next, we iterate through the array. For each element, we determine if targetSum - number is a key in numHash . If it is not present, we insert the current number into numHash with its index as the associated value. If it is present, we have identified our pair: the current number and targetSum - number . In this situation, the numbers that add up to 7 are 2 and 5. Here’s a Python code example illustrating this solution: def twoSum ( array , targetSum ) : numHash = { } for i in range ( len ( array ) ) : num = array [ i ] complement = targetSum - num if complement in numHash : return [ complement , num ] else : numHash [ num ] = i return None

Alternative Answer

For the input array of [-2, -1, 1, 2] with a target sum of 0, the procedure remains the same, but the pair that sums to 0 would be -2 and 2. Below is a JavaScript code snippet to implement this solution: function twoSum ( array , targetSum ) { let numHash = { } ; for ( let i = 0 ; i < array . length ; ++ i ) { let num = array [ i ] ; let complement = targetSum - num ; if ( complement in numHash ) return [ complement , num ] ; else numHash [ num ] = i ; } return null ; }

Question Details

Difficulty & Category

Medium
algorithms

Companies

Meta (Facebook)
Google

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.