Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Two Sum (Unsorted)

Hash Mapsmedium

Course · Section 9: Data Structures, Modern Operators and Strings · Lecture 124: Maps: Fundamentals

Given an **unsorted** array `nums` and a `target`, return the 0-based indices `[i, j]` (i < j) of the two numbers that add up to `target`. Exactly one solution exists. Example: `twoSumUnsorted([2, 7, 11, 15], 9)` → `[0, 1]`.

Sample tests

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

+ 2 hidden tests run on Submit.

Hints

Common pitfalls
  • The brute-force pair check is O(n^2).
  • Look up the complement before inserting the current value to avoid using an element twice.

Learning resources

  • MDN: Map
Approach & explanation (try first)

Store each value-to-index as you scan and look up the complement. O(n) time and space.

Loading...
⌘/Ctrl + Enter

Run your code to see results.