JavaScriptMediumHashing20 min

Find two indices with a target sum

Return indices [i,j] with i < j whose values sum to target, or [] if none exist. Choose the smallest possible j, then the smallest i. All input is valid JSON satisfying the constraints; do not mutate the meaning of values through type coercion. Interviewers use this problem to assess look up each needed complement in a Map.

Input

A JSON object {"array": [...], "target": integer}.

Output

Print one compact JSON value: two zero-based indices or [].

Constraints

0 <= array length <= 10000; values and target between -1000000 and 1000000.

Example

Input

{"array":[2,7,11,15],"target":9}

Output

[0,1]

Example 2 input

{"array":[1,1,2],"target":3}

Output

[0,2]

Boundary case: Scan j in increasing order to enforce the tie rule

Public test cases (2)

  • Input

    {"array":[2,7,11,15],"target":9}

    Expected output

    [0,1]
  • Input

    {"array":[3,3],"target":6}

    Expected output

    [0,1]
Hints (2)
  1. Store only the first index for each value
  2. Scan j in increasing order to enforce the tie rule

Target complexity: time O(n) · space O(n)

Your solution

Checking runner availability…

Reference solution

Sign in for solution
All JavaScript programs