employer cover photo
employer logo
employer logo

Hvantage Technologies

Is this your company?

Hvantage Technologies interview question

Two-sum problem - find two numbers from an array whose sum will be a given target number

Interview Answer

Anonymous

Jul 17, 2024

import java.util.HashMap; import java.util.Map; public class TwoSum { public static void main(String[] args) { int[] numbers = {2, 7, 11, 15}; int target = 9; int[] result = findTwoSum(numbers, target); if (result != null) { System.out.println("Numbers found at indices: " + result[0] + " and " + result[1]); System.out.println("Numbers are: " + numbers[result[0]] + " and " + numbers[result[1]]); } else { System.out.println("No two numbers found that sum to the target."); } } public static int[] findTwoSum(int[] nums, int target) { Map map = new HashMap(); for (int i = 0; i < nums.length; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { return new int[] { map.get(complement), i }; } map.put(nums[i], i); } return null; // No solution found } }