Integers With Multiple Sum of Two Cubes Problem
#3890
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3890.
You are given an integer n.
An integer x is considered good if there exist at least two distinct pairs (a, b) such that:
aandbare positive integers.a <= bx = a^3 + b^3
Return an array containing all good integers less than or equal to n, sorted in ascending order.
Example 1:
Input: n = 4104
Output: [1729,4104]
Explanation:
Among integers less than or equal to 4104, the good integers are:
- 1729: 1^3 + 12^3 = 1729 and 9^3 + 10^3 = 1729.
- 4104: 2^3 + 16^3 = 4104 and 9^3 + 15^3 = 4104.
Thus, the answer is [1729, 4104].
Example 2:
Input: n = 578
Output: []
Explanation:
There are no good integers less than or equal to 578, so the answer is an empty array.
Constraints:
1 <= n <= 10^9
Solution
Approach: Preprocessing + Binary Search
If a or b exceeds 1000, then a^3 + b^3 > 10^9, so only 1 <= a <= b <= 1000 matters. Enumerate all such pairs once and count how often each sum a^3 + b^3 occurs. The sums that occur at least twice are the good integers; keep them in a sorted array GOOD.
For a query n, binary search GOOD for the first element greater than n at index idx, and return the first idx elements.
Complexity:
- Time complexity:
O(m^2 + k log k)for the preprocessing, wherem = 1000andkis the number of good integers, thenO(log k + answer size)per query. - Space complexity:
O(k).
from bisect import bisect_right
from collections import defaultdict
LIMIT = 10**9
cnt = defaultdict(int)
cubes = [i**3 for i in range(1001)]
for a in range(1, 1001):
for b in range(a, 1001):
x = cubes[a] + cubes[b]
if x > LIMIT:
break
cnt[x] += 1
GOOD = sorted(x for x, v in cnt.items() if v > 1)
class Solution:
def findGoodIntegers(self, n: int) -> List[int]:
idx = bisect_right(GOOD, n)
return GOOD[:idx]