Two Sum Less Than K — LeetCode 1099 Python Solution
- Problem
- #1099
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(\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.