FrontendInterviews.dev

Loading problem…

5. Two Sum - Product Recommendations

Easy•
Acceptance: 60.00%
•
🔓3/3 Pro unlocks today

You're building a product recommendation feature for an e-commerce app. Users have a budget, and you need to find two products whose prices sum exactly to their budget (for gift suggestions or bundle recommendations).

Given an array of product prices nums and a target budget target, return the indices of the two products whose prices add up to the target budget.

You may assume that each input has exactly one solution, and you may not use the same product twice.

Requirements

1. Basic Functionality

  • Find two numbers that sum to target
  • Return their indices (0-indexed)
  • Each number can only be used once
  • Exactly one solution exists

Example Usage

twoSum([2, 7, 11, 15], 9);  // [0, 1] - products at index 0 and 1 sum to 9
twoSum([3, 2, 4], 6);       // [1, 2] - products at index 1 and 2 sum to 6
twoSum([3, 3], 6);         // [0, 1] - two products with same price

Real-World Context

This problem models real e-commerce features:

  • Gift suggestions: Find two products that sum to a gift budget
  • Bundle recommendations: Suggest product pairs within budget
  • Price matching: Find products that match a target price when combined
  • Matching algorithm: Pair items based on combined value

Constraints

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9
  • Only one valid answer exists
  • Cannot use same element twice