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!

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 October 2026 (Oct 4–15)Sponsored by FLXBL

Contest runs October 4 - 15. Complete challenges to climb the leaderboard!

Prizes 1 & 2: Salesforce certification exam voucher — won by random drawing, where every point is a ticket. see all prizes

Only the 12 daily challenges shown during this contest count toward points. Earlier dailies don't carry over.

Wally can't hear you

Please sign in to access the AI Assistant

Sign In