Skip to content
Learn Netverks
Company prep Rivian
Junior (1–3 years) Coding / DSA Easy

Given an array and a target, find two indices that sum to the target

Reported in Rivian USA engineering loops. Classic array + hash map problem testing optimal time–space trade-offs.

Role
SDE
Location
Los Angeles, CA
Study track
JavaScript

Context for Rivian candidates:

Return the indices of the two numbers. Exactly one solution exists; you may not use the same element twice. Aim for better than O(n²).

Try answering aloud first

Cover trade-offs, structure, and a concrete example before revealing the baseline response.

Spoiler-free prep mode

How to frame this at Rivian: Connect your answer to measurable impact, clarity of thought, and trade-offs the team cares about. Below is a strong baseline response you can adapt with your own project examples.

Use a hash map storing value → index for elements already seen. For each nums[i], compute complement = target - nums[i]. If complement exists in the map, return [map[complement], i]; otherwise store nums[i] → i.

function twoSum(nums, target) {
  const seen = new Map();
  for (let i = 0; i < nums.length; i++) {
    const need = target - nums[i];
    if (seen.has(need)) return [seen.get(need), i];
    seen.set(nums[i], i);
  }
}

Complexity: O(n) time, O(n) space. Sorting + two pointers achieves O(n log n) time and O(1) extra space if indices are not required.

Discuss handling duplicates, integer overflow in other languages, and how hash maps give O(1) average lookup versus linear scan.

Comments (0)

Share how this question came up in your loop, or add tips for others preparing.

Log in to comment on this question.