Skip to content

Bug Report for two-integer-sum #5846

@prem-savla

Description

@prem-savla

Bug Report for https://neetcode.io/problems/two-integer-sum

Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.

The following consists of output from the solution code for the given test case.
public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> prevMap = new HashMap<>();

    for (int i = 0; i < nums.length; i++) {
        int num = nums[i];
        int diff = target - num;

        if (prevMap.containsKey(diff)) {
            return new int[] { prevMap.get(diff), i };
        }

        prevMap.put(num, i);
    }

    return new int[] {};
}

}

TestCase:
nums=[5,5,5,5,2]
target=7

Your Output:
[3,4]
Expected output:
[3,4]

But the correct answer for this should be the smallest index of integer 5
i.e. [0,4] should be the correct output

Hence adding a - !prevMap.containsKey(num) check before adding num to the prevMap will ensure correctness.

Thank You.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions