File: two-sum-less-than-k/solution.py

Date: 2026-06-06

Time: 19:34

two-sum-less-than-k/solution.py

Purpose

This file solves LeetCode 1099 — Two Sum Less Than K. Given an array of positive integers and a threshold k, it finds the maximum sum of any two distinct-index elements that is strictly less than k. It returns -1 if no valid pair exists.

This is the canonical solution file for this problem in the leetcode-implementations repo — one of hundreds of problem directories that each contain a solution.py, test_solution.py, and optionally plan.md/review.md.

Key Components

maxsumunder_k(nums, k) — The single exported function. Contract:

Patterns

Sort + two-pointer squeeze — the classic O(n log n) approach for optimizing over pairs with a sum constraint. After sorting, the left pointer starts at the smallest element and the right at the largest. The two pointers converge based on whether the current pair sum is under or over the threshold. This avoids the O(n^2) brute-force scan.

The pattern is the same one used in the original Two Sum II (sorted input) problem, adapted to maximize a sum below a ceiling rather than find an exact target.

Dependencies

Imports: None — pure stdlib Python, no external or internal imports.

Imported by: The testsolution.py files listed in the "Imported By" section are an artifact of the test runner's shared infrastructure — they don't actually import this specific solution. Only two-sum-less-than-k/testsolution.py directly imports and tests maxsumunder_k.

Flow

1. Sort nums in-place (ascending). This is the precondition for the two-pointer technique.

2. Initialize left = 0, right = len(nums) - 1, result = -1.

3. Loop while left < right:

4. Return result — either the best valid sum found, or -1 if no pair qualified.

Invariants

Error Handling

None. The function assumes valid input per the LeetCode contract (at least 2 elements, positive integers). For edge cases like len(nums) < 2, the while loop simply never executes and -1 is returned, which happens to be the correct answer. No exceptions are raised or caught.

Complexity

Topics to Explore

Beliefs