LeetCode 1: Two Sum Solution

Master LeetCode problem 1 (Two Sum), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1. Two Sum

Problem Explanation

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.

Solution Code

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");
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1 (Two Sum)?

This page provides optimized solutions for LeetCode problem 1 (Two Sum) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1 (Two Sum)?

The time complexity for LeetCode 1 (Two Sum) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1 in Java, C++, or Python.

Back to LeetCode Solutions