easyArrays & Matrix (Must-Do)

Two Sum

Find two distinct positions whose values add up to the target. Exactly one pair exists. Return the smaller index first; indices start at zero.

Work through the cases

3 examples

Input notation

Space-separated integers on line 1. The target is on line 2. There are at least two values.

Expected result

The two indices separated by a space.
Case 1

Input

4 7 1 9
8

Expected output

1 2
Case 2

Input

3 3
6

Expected output

0 1
Case 3

Input

-3 4 3 90
0

Expected output

0 2

These notes use simplified input/output notation. The linked platform defines the method signature and judge format.

FROM IDEA TO IMPLEMENTATION

Understand the approach.

Compare the documented approaches below. Brute force, better, and optimal versions appear where available; a direct exercise may need only one approach.

Try every pair of distinct indices. Return the pair whose values sum to the target. Time: O(n²). Extra space: O(1). This is easy to reason about, but repeats the search for a matching value.

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++)
            for (int j = i + 1; j < nums.length; j++)
                if (nums[i] + nums[j] == target) return new int[]{i, j};
        return new int[0];
    }
}

Reference code. Platform solutions may use supplied node types, imports, or collection libraries; foundational examples are complete programs.

Solutions adapted from Doocs / LeetCode contributors, licensed under CC BY-SA 4.0. Formatting changed; TypeScript versions converted to JavaScript. Supplemental implementations and approach notes added. Adapted solution material is available under the same license.