Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
LeetCode two sum not working as expected with a hash graph

I am trying to come up with an efficient solution to the two sum function on leetCode. From what I understand this code SHOULD work, but it keeps on returning undefined

    var twoSum = function(nums, target) {
    let hashGraph = {}
    let slow = 0
    let fast = nums.length - 1
    
    while(slow < Math.abs(nums.length / 2)) {
        if(nums[slow] + nums[fast] == target) {
            return [slow, fast]
        } else if(!hashGraph[target - nums[slow]] === undefined) {
            let answer = [slow, hashGraph[target - nums[slow]]].sort()
            return answer
        } else if(!hashGraph[target - nums[fast]] === undefined) {
            return [hashGraph[target - nums[fast]], fast].sort()
        } else {
            hashGraph[nums[slow]] = slow
            hashGraph[nums[fast]] = fast
            slow++
            fast--
        }
    }
};

essentially I am storing the values at each index inside of a hash graph and assigning the values at that location to the index that the number was found. When I iterate through I am checking if the complement for the number at the current index exists in the hash table. If it does I return the current index and the value of the found index (which is the value in the array that the number was discovered on)

For the first test case I am given the array [2,7,11,15] and a target of 9 what SHOULD happen here is that the while loop's else case is hit and the graph is populated as follows: { 2: 0, 15: 3 }

Then on the second iteration the second condition is hit where it checks if hashGraph[target - nums[slow]] is valid. Given the target of 9 and the input of 7 I am essentially asking it if hashGraph[9-2] or hashGraph[2] exists. Indeed it does, however when visualizing the execution with python tutor's Javascript execution visualizer it fails this check and reaches the else clause.

This is what is stumping me. hashGraph[2] does exist. I can replicate the same thing and get the correct result if I use the following:

let hash = {
  2: 0,
  15: 3
}

let arr = [7]

console.log(hash[9 - arr[0]])

If that code gets me the correct result then why does my if condition fail?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!