Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Two Sum (Sorted Array)

Arrays & Two-Pointerseasy

Course · Section 11: Working With Arrays · Lecture 149: Simple Array Methods

Given a **sorted** array `nums` and a `target`, return the 0-based indices `[i, j]` of the two numbers that add up to `target`. Exactly one solution exists. Example: `twoSum([1, 2, 4, 7], 6)` → `[1, 2]`.

Sample tests

Input: twoSum([1,2,4,7], 6)
Output: [1,2]
Input: twoSum([2,7,11,15], 9)
Output: [0,1]

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • A nested loop is O(n^2); the sorted order is what lets you avoid it.

Learning resources

  • MDN: Arrays
Approach & explanation (try first)

Two pointers start at the ends and move inward based on the sum versus target. O(n) time, O(1) space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.