⌘K
Flycodx

Two Sum

Two Sum

EasyArrays27% accepted

Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one solution, and you may not use the same element twice. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=4, nums=[2 7 11 15], target=9 → "0 1" (because nums[0]+nums[1]=9)

Input format — only if your code reads from stdin

Input format (stdin): - First line: integer n (array size) - Second line: n space-separated integers - Third line: integer target Output: two space-separated 0-based indices.

Approach

Use a hash map: for each element at index i, check if (target - nums[i]) is already in the map. If yes, return both indices. If no, store nums[i] → i in the map. This runs in O(n) time and O(n) space.

Input

4 2 7 11 15 9

Output

0 1
  • •2 ≤ n ≤ 10^4, -10^9 ≤ nums[i], target ≤ 10^9
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3