DSA Arena helps you master data structures and algorithms through real-time coding contests, instant AI feedback, and detailed performance tracking.
15 min
30 min
1 Hour
500+
Problems
Instant
AI Feedback
All
Levels
Problem: Two Sum
Difficulty: Easy 🔰
Tags: Array, HashMap
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
class Solution {
  public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
      int diff = target - nums[i];
      if (map.containsKey(diff))
        return new int[] { map.get(diff), i };
      map.put(nums[i], i);
    }
    return new int[0];
  }
}