Two Sum
Solve the famous Two Sum coding problem often asked in interviews.
π§© Problem Statement
Given an array of integers, return the indices of the two numbers that add up to a specific target.
You may assume that each input has exactly one solution, and you may not use the same element twice.
βοΈ Function Signature
public int[] twoSum(int[] nums, int target)
π Approach
This solution uses a hash map to store the numbers weβve seen so far and their indices. For each element, we check if the complement (target - current element) exists in the map. If it does, we return its index and the current index.
β Time Complexity
- O(n) β where
n
is the number of elements in the array.
π‘ Java Implementation
import java.util.*;
public class TwoSumSolver {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> 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 new int[] {}; // Return empty array if no solution
}
}
π§ͺ Test Cases
public class TwoSumTest {
public static void main(String[] args) {
TwoSumSolver solver = new TwoSumSolver();
// Test Case 1
int[] result1 = solver.twoSum(new int[] {2, 7, 11, 15}, 9);
System.out.println(Arrays.toString(result1)); // Output: [0, 1]
// Test Case 2
int[] result2 = solver.twoSum(new int[] {3, 2, 4}, 6);
System.out.println(Arrays.toString(result2)); // Output: [1, 2]
// Test Case 3
int[] result3 = solver.twoSum(new int[] {1, 5, 3, 7}, 8);
System.out.println(Arrays.toString(result3)); // Output: [0, 3]
// Test Case 4
int[] result4 = solver.twoSum(new int[] {0, -1, 2, -3, 1}, -2);
System.out.println(Arrays.toString(result4)); // Output: [1, 3]
// Test Case 5
int[] result5 = solver.twoSum(new int[] {1, 2, 3, 4, 5}, 10);
System.out.println(Arrays.toString(result5)); // Output: [] (No solution)
}
}
π Notes
- Input constraints and assumptions should be clearly specified during interviews.
- Itβs a good idea to discuss edge cases, like arrays with duplicates or negative numbers.
Happy coding! π―
Related Posts
Java Interview Guide - Part 3: Advanced Java Concepts (Q21βQ30)
A comprehensive list of essential Java interview questions covering OOP, memory management, exceptions, collections, and Streams
Java Interview Guide - Part 5: Advanced Java Concepts (Q41βQ50)
A comprehensive list of essential Java interview questions covering OOP, memory management, exceptions, collections, and Streams
Java Interview Guide - Part 1: Core Questions (1β10)
A comprehensive list of essential Java interview questions covering OOP, memory management, exceptions, collections