Arrays & Hashing

Two sum

Estimated reading: 1 minute 32 views

Given an array of integers nums and an integer target, return the indices i and j such that nums[i] + nums[j] == target and i != j.

  • You may assume that every input has exactly one valid pair of indices that satisfy the condition.
  • Return the answer with the smaller index first.

Examples:

Example 1:

  • Input: nums = [3, 4, 5, 6], target = 7
  • Output: [0, 1]
  • Explanation: nums[0] + nums[1] == 7, so the output is [0, 1].

Example 2:

  • Input: nums = [4, 5, 6], target = 10
  • Output: [0, 2]

Example 3:

  • Input: nums = [5, 5], target = 10
  • Output: [0, 1]

Constraints:

  • 2 <= nums.length <= 1000
  • -10^7 <= nums[i] <= 10^7
  • -10^7 <= target <= 10^7
				
					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[] {};
    }
				
			
Share this Doc

Two sum

Or copy link

CONTENTS