1. Two Sum

ArrayHash Table

Explanation

To solve this problem efficiently, we can use a hashmap to store the difference between the target value and the current element in the array. As we iterate through the array, we check if the current element exists in the hashmap. If it does, we have found a pair of elements that add up to the target value. If not, we store the difference in the hashmap for future reference.

  • Time complexity: O(n) - We iterate through the array once.
  • Space complexity: O(n) - We store up to n elements in the hashmap.
import java.util.HashMap;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<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);
        }
        
        throw new IllegalArgumentException("No two sum solution");
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.