Max Number of K-Sum Pairs — LeetCode 1679 Python Solution

MediumArrayHash TableTwo PointersSorting
Problem
#1679
Reading time
3 min

The problem

You are given an integer array nums and an integer k. In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.

Example

Input
nums = [1,2,3,4], k = 5
Output
2
Explanation
Starting with nums = [1,2,3,4]:

Python solution

Python
class Solution:
    def maxOperations(self, nums: List[int], k: int) -> int:
        nums.sort()
        l, r, ans = 0, len(nums) - 1, 0
        while l < r:
            s = nums[l] + nums[r]
            if s == k:
                ans += 1
                l, r = l + 1, r - 1
            elif s > k:
                r -= 1
            else:
                l += 1
        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 1679. Max Number of K-Sum Pairs is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.

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

Related problems

On a study list

This problem is on LeetCode 75.

Frequently asked questions

How hard is LeetCode 1679. Max Number of K-Sum Pairs?
LeetCode 1679. Max Number of K-Sum Pairs is rated Medium on LeetCode.
What is the time complexity of LeetCode 1679. Max Number of K-Sum Pairs?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1679. Max Number of K-Sum Pairs?
The Python solution on this page uses O(\log n) auxiliary space.
What topics does LeetCode 1679. Max Number of K-Sum Pairs cover?
LeetCode 1679. Max Number of K-Sum Pairs is tagged Array, Hash Table, Two Pointers and Sorting on LeetCode.

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