Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find out the k-th largest product of elements of two arrays in Python
Given two lists containing integer numbers, we need to find the k-th largest product by multiplying each element from the first list with each element from the second list. This problem can be efficiently solved using a min-heap to track the k largest products.
So, if the input is like p = [2, 5], q = [6, 8], k = 2, then the output will be 16.
The multiplication results are: 2 × 6 = 12, 2 × 8 = 16, 5 × 6 = 30, 5 × 8 = 40. When sorted in descending order: [40, 30, 16, 12]. The 2nd largest element is 16.
Algorithm Overview
To solve this efficiently, we follow these steps ?
- Sort both lists to optimize the search process
- Use a min-heap to maintain the k largest products
- For positive elements in q, iterate through p in reverse order (largest first)
- For negative elements in q, iterate through p in normal order
- Use early termination when products become too small
Implementation
from heapq import heappush, heappop
def solve(p, q, k):
p = sorted(p)
q = sorted(q)
k += 1 # Adjust for 0-based indexing
heap = []
for elem in q:
if elem >= 0:
# For non-negative elements, start with largest values in p
for i in range(len(p) - 1, -1, -1):
cd = elem * p[i]
if heap and len(heap) == k and cd <= heap[0]:
break # Early termination
heappush(heap, cd)
if len(heap) > k:
heappop(heap)
else:
# For negative elements, start with smallest values in p
for i in range(len(p)):
cd = elem * p[i]
if heap and len(heap) == k and cd <= heap[0]:
break # Early termination
heappush(heap, cd)
if len(heap) > k:
heappop(heap)
return heap[0]
# Test the function
result = solve([2, 5], [6, 8], 2)
print(f"The 2nd largest product is: {result}")
The 2nd largest product is: 16
Step-by-Step Execution
Let's trace through the example with p = [2, 5], q = [6, 8], k = 2 ?
def solve_with_trace(p, q, k):
print(f"Original arrays: p = {p}, q = {q}, k = {k}")
p = sorted(p)
q = sorted(q)
k += 1
heap = []
print(f"Sorted arrays: p = {p}, q = {q}")
print(f"Adjusted k = {k}")
for elem in q:
print(f"\nProcessing element {elem} from q:")
if elem >= 0:
for i in range(len(p) - 1, -1, -1):
cd = elem * p[i]
print(f" Product: {elem} × {p[i]} = {cd}")
if heap and len(heap) == k and cd <= heap[0]:
print(f" Early termination: {cd} <= {heap[0]}")
break
heappush(heap, cd)
print(f" Heap after push: {sorted(heap)}")
if len(heap) > k:
removed = heappop(heap)
print(f" Removed smallest: {removed}, heap: {sorted(heap)}")
print(f"\nFinal heap: {sorted(heap)}")
return heap[0]
result = solve_with_trace([2, 5], [6, 8], 2)
print(f"\nResult: {result}")
Original arrays: p = [2, 5], q = [6, 8], k = 2 Sorted arrays: p = [2, 5], q = [6, 8] Adjusted k = 3 Processing element 6 from q: Product: 6 × 5 = 30 Heap after push: [30] Product: 6 × 2 = 12 Heap after push: [12, 30] Processing element 8 from q: Product: 8 × 5 = 40 Heap after push: [12, 30, 40] Product: 8 × 2 = 16 Heap after push: [12, 30, 40, 16] Removed smallest: 12, heap: [16, 30, 40] Final heap: [16, 30, 40] Result: 16
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(m×n×log k) | m×n products, each heap operation is O(log k) |
| Space | O(k) | Heap stores at most k elements |
Conclusion
This algorithm efficiently finds the k-th largest product using a min-heap approach with early termination optimization. The sorting step and careful iteration order help minimize unnecessary computations, making it suitable for large datasets.
