Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Find two indices with target sum

Find two distinct indices whose elements sum to a target using a hash map for O(n) time.

Python practice15 minArrays – Fundamentals & PatternsIntermediateLast updated March 25, 2026

Problem statement

Given an array of integers nums and an integer target, return a list [i, j] of two distinct 0-based indices such that nums[i] + nums[j] == target. If multiple pairs exist, returning any valid pair is acceptable. If no such pair exists, return [-1, -1]. Use an algorithm with O(n) time and O(n) extra space.

Task

Return indices of two numbers that add up to the target. If none exist, return [-1, -1].

Examples

Basic two-sum

Input

nums = [2,7,11,15], target = 9

Output

[0, 1]

nums[0] + nums[1] = 9.

Input format

Function call: two_sum_indices(nums, target) where nums is a list of integers and target is an integer.

Output format

A list of two integers [i, j] representing indices. If no pair exists, return [-1, -1].

Constraints

2 <= len(nums) <= 10^5. Elements may be negative. Do not use the same element twice (indices must be distinct). Time: O(n), Space: O(n).

Samples

Sample 1

Input

two_sum_indices([3,2,4], 6)

Output

[1, 2]

nums[1] + nums[2] = 6.