Two Sum Less Than K — LeetCode 1099 Python Solution

EasyLeetCode PremiumArrayTwo PointersBinary SearchSorting
Problem
#1099
Reading time
2 min

The problem

Given an array nums of integers and integer k, return the maximum sum such that there exists i < j with nums[i] + nums[j] = sum and sum < k. If no i, j exist satisfying this equation, return -1.

Example

Input
nums = [34,23,1,24,75,33,54,8], k = 60
Output
58
Explanation
We can use 34 and 24 to sum 58 which is less than 60.

Python solution

Python
class Solution:
    def twoSumLessThanK(self, nums: List[int], k: int) -> int:
        nums.sort()
        ans = -1
        for i, x in enumerate(nums):
            j = bisect_left(nums, k - x, lo=i + 1) - 1
            if i < j:
                ans = max(ans, x + nums[j])
        return ans

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(\log n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 1099. Two Sum Less Than K is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1099. Two Sum Less Than K?
LeetCode 1099. Two Sum Less Than K is rated Easy on LeetCode.
What is the time complexity of LeetCode 1099. Two Sum Less Than K?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1099. Two Sum Less Than K?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1099. Two Sum Less Than K cover?
LeetCode 1099. Two Sum Less Than K is tagged Array, Two Pointers, Binary Search and Sorting on LeetCode.
Is LeetCode 1099. Two Sum Less Than K a premium problem?
Yes. LeetCode 1099. Two Sum Less Than K is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview