Skip to main content

Practice ยท 2 of 2

Two-sum in one pass

Implement std::vector<int> two_sum(const std::vector<int>& nums, int target) returning the indices [i, j] (i < j) of the two numbers adding to target, or an empty vector when no pair exists. The one-pass hash-map approach is O(n): before inserting nums[i], check whether target - nums[i] was already seen.

Difficulty: intermediate

Back to lesson: Practice: Algorithm practice