#2386
Find the K-Sum of an Array
HardArraySortingHeap (Priority Queue)Heap (Priority Queue)Dynamic Programming (for subsequence problems)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(k * n log k) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(k * n log k)Space O(n)
The optimal approach uses a max-heap to efficiently find the k-th largest subsequence sum without generating all sums. By starting from the largest sum and exploring the next largest sums, we can efficiently track the k largest sums.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a max-heap and add the total sum of the array.
- 2Step 2: While the heap has elements and we haven't found k sums yet, extract the largest sum.
- 3Step 3: For each extracted sum, generate new sums by adding each element of the array (considering duplicates) and push them back into the heap.
- 4Step 4: Use a set to avoid duplicate sums in the heap.
- 5Step 5: Repeat until we extract the k-th largest sum.
solution.py16 lines
1import heapq
2
3def k_sum(nums, k):
4 max_heap = []
5 total_sum = sum(nums)
6 heapq.heappush(max_heap, -total_sum)
7 seen = set([-total_sum])
8 current_sum = 0
9 for _ in range(k):
10 current_sum = -heapq.heappop(max_heap)
11 for num in nums:
12 new_sum = current_sum - num
13 if new_sum not in seen:
14 seen.add(new_sum)
15 heapq.heappush(max_heap, -new_sum)
16 return current_sumℹ
Complexity note: The time complexity is O(k * n log k) because we are pushing new sums into the heap, which takes O(log k) time. The space complexity is O(n) due to the storage of unique sums in the set and the heap.
- 1Using a max-heap allows us to efficiently track the largest sums without generating all possible sums.
- 2The uniqueness of sums is crucial to avoid unnecessary computations and memory usage.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.