Given a list of integers and a target sum, return the indices of the two numbers that add up to the target.

You may assume that each input has exactly one solution, and you cannot use the same element twice. Return the indices as a list of two integers [index1, index2] where index1 < index2.

Method Signature:

public static List<Integer> twoSum(List<Integer> nums, Integer target)

Examples:

Example 1:

  • Input: nums = [2, 7, 11, 15], target = 9
  • Output: [0, 1]
  • Explanation: nums[0] + nums[1] = 2 + 7 = 9, so return [0, 1]

Example 2:

  • Input: nums = [3, 2, 4], target = 6
  • Output: [1, 2]
  • Explanation: nums[1] + nums[2] = 2 + 4 = 6, so return [1, 2]

Example 3:

  • Input: nums = [3, 3], target = 6
  • Output: [0, 1]
  • Explanation: Both elements at index 0 and 1 add up to 6

Example 4:

  • Input: nums = null, target = 9
  • Output: null
  • Explanation: Return null for null input
Apex Code Editor

Welcome to Lightning Challenge!

Create an Account

Sign up to track your progress, earn points, and compete with others. Your solutions will be saved automatically.

Create account

How It Works

  • • Write your solution in the code editor
  • • Connect your Salesforce org to test
  • • Submit to check if your solution passes
  • • Use hints if you get stuck

Contest Alert

🏆 #CodeEveryDay Feb 2026

Contest runs February 1 - 28. Complete challenges to climb the leaderboard!

Points are calculated for challenges completed during the contest period.