WorkspaceProblem lab
ALGORITHM VISUALIZER

Two Sum

Opening the interactive workspace…

Understanding Two Sum

Given an integer array nums and an integer target, return the indices of two distinct elements whose sum equals target. Return an empty array if no pair exists. Any valid pair is accepted.

How it works

Instead of searching for two values at once, ask whether the complement of the current value has already appeared.

Store each previously seen value with its index. Check for target minus the current value before inserting, so an element cannot match itself.

Try an example

Input: nums = [2, 7, 11, 15], target = 9

Output: [0, 1]

2 + 7 = 9.

Input: nums = [3, 3], target = 6

Output: [0, 1]

Equal values at different indices form a valid pair.

Constraints

  • Use each index at most once.
  • Negative numbers and duplicate values are allowed.
  • Visualization limit: 64 integers between −1,000,000 and 1,000,000.

Use the simulator

Change the input, then choose Visualize input. Use Next and Previous to inspect each decision, or Play to advance automatically. Compare approaches and their complexity. Choose Try yourself to write JavaScript, select My code and Visualize code to inspect its execution, or Run Tests to check results.

Execution happens in your browser. Drafts are saved locally; avoid entering secrets or sensitive information.

Related concepts and complexity