Two Sum
Easy About 10 min Free, no account needed
Find the indices of the two numbers that add up to a target.
The brief
Given an array of integers nums and an integer target, return the indices
of the two numbers such that they add up to target.
- Return the two indices in ascending order.
- Exactly one valid answer exists.
The obvious approach is a double loop over every pair, O(n²). It gives the right answer, but the hidden test runs on 200,000 elements with the pair deep in the array, so it's too slow. Aim for O(n).
Starter code
using System;
public class Solution
{
// TODO: return the indices (ascending) of the two numbers that add up to target.
public int[] TwoSum(int[] nums, int target)
{
throw new NotImplementedException();
}
}How it is graded
Visible examples help you iterate. Hidden tests then cover edge cases and larger inputs, and every test reports server-measured time and allocated bytes.
Related guides
What it practices
- Hash maps and sets
- Trade memory for constant-time lookups, membership tests and frequency counts.
Related katas
- Contains Duplicate Easy Free Decide whether an array contains any repeated value.
- Count Distinct Letters Easy Free How many different letters appear? A 26-slot array already knows.
- Count Pairs With Difference K Easy Free Count the pairs of indices whose values differ by exactly k.
- Isomorphic Strings Easy Free Can one string be turned into the other by a consistent character substitution?