Given a slice of integers and a nonzero target, return the indices of the two
numbers whose product equals the target. As with Pair Sum, scan left to right and
return [i, j] for the earliest earlier index i that completes the pair at j,
in increasing order. Assume exactly one valid answer exists.
pairProduct(nums, target)
Input format: nums | target. Output the two indices separated by a space.
pairProduct([]int{3, 2, 5, 4}, 8) // → [1, 3] (2 * 4)
pairProduct([]int{2, 7, 3}, 21) // → [1, 2] (7 * 3)
pairProduct([]int{6, 4}, 24) // → [0, 1]
This is the same shape as finding a pair that sums to a target, just with multiplication instead of addition. If you already know how to solve the sum version, you can carry the same reasoning over almost unchanged — just swap the operation and its inverse.
For a sum target, the value you need to have already seen is target minus current. For a product target, it's target divided by current — division undoes multiplication the same way subtraction undoes addition. So the core idea carries over: scan left to right and ask "have I already seen the partner this number needs?", where "partner" is defined by the inverse operation.
Checking every pair of indices is O(n²) — the same waste as before. By the time you reach a given index, you already know every value before it; you just need a fast way to check if a specific value was among them. A hash map from value to its first index gives you that O(1) lookup, turning the nested loop into a single pass.
Division introduces two wrinkles addition never had:
target / current might not be a whole number. Since you're working with integers, only compute and look up the quotient when the current value evenly divides the target.Many "two elements that combine to a target" problems reduce to the same pattern: find the inverse of the combining operation, use it to compute the partner you need, and check for that partner with a hash map instead of rescanning. The one extra step here is respecting division's edge cases — when it's undefined, or when it can't produce a valid integer answer.
def pair_product(nums, target):
idx = {}
for j, v in enumerate(nums):
if v != 0 and target % v == 0:
need = target // v
if need in idx:
return [idx[need], j]
if v not in idx:
idx[v] = j
return []
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.