Quick Overview

Determine whether two integers at distinct indices sum to a target, including the case where equal values occur twice. Validate all inputs, avoid mutation, and scan once with a set of previously seen complements for expected O(n) time.

Determine Whether Two Integers Sum to a Target

Company: Hudson

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Technical Screen

# Determine Whether Two Integers Sum to a Target Given a list of integers and a target integer, return whether two elements at distinct indices add up to the target. ```python def has_two_sum(values: list[int], target: int) -> bool: ... ``` The same value may be used twice only when it occurs at two different indices. ## Examples ```text Input: values = [4, 7, 1, -2], target = 5 Output: true ``` The values `7` and `-2` form a valid pair. ```text Input: values = [3], target = 6 Output: false Input: values = [3, 3], target = 6 Output: true ``` ## Constraints and Errors - `0 <= len(values) <= 500_000` - `-10**18 <= values[i], target <= 10**18` - Every input number must be a Python integer; Boolean values do not count as integers. - An invalid value or target raises `ValueError`. - Validate the full input before returning a result. - Do not mutate `values`. ## Hints - While scanning a value `x`, ask whether `target - x` has appeared at an earlier index. - Insert the current value only after performing that lookup. - Expected linear time can be achieved with linear auxiliary space.

Quick Answer: Determine whether two integers at distinct indices sum to a target, including the case where equal values occur twice. Validate all inputs, avoid mutation, and scan once with a set of previously seen complements for expected O(n) time.

Return whether two elements at distinct indices in the input list sum to the target.

Constraints

  • 0 <= len(values) <= 500000
  • Inputs are signed integers, not booleans
  • Do not mutate values

Examples

Input: {'values': [4, 7, 1, -2], 'target': 5}

Expected Output: True

Explanation: Seven and negative two form the target.

Input: {'values': [3], 'target': 6}

Expected Output: False

Explanation: One occurrence cannot be reused.

Hints

  1. For each value, look for its complement among earlier values.
  2. Insert the current value only after the lookup.

Loading coding console...