Integers With Multiple Sum of Two Cubes solution and explanation
7 more videos on this problem
LeetCode Problem 3890 | Integers With Multiple Sum of Two CubesRepovive TV · 7:59 · 182 views
Integers with multiple sum of two cubes (Problem number 3890) | Leetcode weekly contest 496.Prince Gupta Study · 17:28 · 117 views
Integers With Multiple Sum of Two Cubes|leetcode 3890|Leetcode contest 496|solution contest 496Code Thoughts · 4:09 · 114 views
Integers With Multiple Sum of Two Cubes | Leetcode 3890 | Explanation With Code | Javacodewithsitaram · 17:31 · 104 views
Leetcode 3890. Integers With Multiple Sum of Two Cubes | Math | Map | Set | MediumLeet's Code · 19:09 · 80 views
3890.Integers With Multiple Sum of Two Cubes | Telugu | #leetcode #dsa #programming #lecturecodewarriortelugu · 4:17 · 27 views
3890. Integers With Multiple Sum of Two Cubes Leetcode Weekly 496 Greedy SolutionBEASTCODES · 8:39 · 22 views
The Math Trick Behind LeetCode 3890! Integers With Multiple Sum of Two Cubes (Java)CodingHelp · 7:36 · 12 views
The problem
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 = a3 + b3
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:
13 + 123 = 1729and93 + 103 = 1729. - 4104:
23 + 163 = 4104and93 + 153 = 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 <= 109
Approach overview
Problem Overview: Given a bound on integers, identify numbers that can be written as a^3 + b^3 in more than one distinct way. Different pairs (a, b) may produce the same cube sum, and the task is to detect sums that appear multiple times.
Approach 1: Brute Force Pair Enumeration (O(n^2) time, O(1) extra space)
Enumerate every pair (a, b) where 1 ≤ a ≤ b ≤ n. For each pair compute a^3 + b^3 and compare it against previously generated sums by scanning stored results. This approach relies purely on enumeration and repeated comparisons, which makes it simple but inefficient. Time complexity grows to O(n^3) if comparisons require scanning previous results, and even optimized versions still need O(n^2) enumeration. Use this only to demonstrate the mathematical property of cube sums.
Approach 2: Hash Table Counting (O(n^2) time, O(n^2) space)
Enumerate all cube pairs but store the computed sum in a hash table. Each key represents a value of a^3 + b^3, and the value stores how many pairs generate it. When the same sum appears again, increment the counter. After enumeration, every key with count ≥ 2 represents an integer that has multiple cube representations. Hash lookup is O(1), so the algorithm remains dominated by the n^2 pair enumeration. This approach is straightforward and commonly used in interview solutions.
Approach 3: Sort Cube Sums and Count Duplicates (O(n^2 log n) time, O(n^2) space)
Instead of hashing, store all cube sums in an array while enumerating pairs. Sort the array using a standard sorting algorithm. Identical sums become adjacent after sorting, allowing a single pass to count duplicates and detect numbers that appear multiple times. Sorting introduces a log n factor but can be useful when deterministic ordering or offline processing is preferred over hashing.
Approach 4: Ordered Pair Enumeration with Min Heap (O(n^2 log n) time, O(n) space)
A more memory‑efficient technique generates sums in sorted order using a min heap. Start with pairs (a, a) for each a. Push their cube sums into a heap. Each time you pop the smallest sum, push the next pair for that a (i.e., (a, b+1)). This technique resembles merging sorted sequences and is common in enumeration problems. Duplicate sums appear consecutively, making it easy to detect integers with multiple representations. The approach relies on priority queue operations and controlled enumeration rather than storing every pair.
Recommended for interviews: The hash table counting approach is the most practical. It clearly shows you understand pair enumeration and how hash tables eliminate repeated searches. Mentioning brute force first demonstrates reasoning about the search space, while the optimized hash-based solution shows the ability to reduce lookup cost and handle duplicate detection efficiently.
Solution
We observe that when a or b is greater than 1000, the expression a^3 + b^3 > 10^9. Therefore, we only need to enumerate 1 leq a leq b leq 1000 and count the occurrences of each integer x = a^3 + b^3. Finally, we filter out the integers that appear more than once and sort them in ascending order to obtain all good integers.
We preprocess all good integers and store them in an array GOOD. For each query, we use binary search to find the index idx of the first integer in GOOD that is greater than n, then return the first idx integers in GOOD.
The time complexity is O(m^2 + k log k), where m = 1000 is the enumeration range and k is the number of good integers. The space complexity is O(k).
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]class Solution {
private static final int LIMIT = (int) 1e9;
private static final List<Integer> GOOD = new ArrayList<>();
static {
Map<Integer, Integer> cnt = new HashMap<>();
int[] cubes = new int[1001];
for (int i = 0; i <= 1000; i++) {
cubes[i] = i * i * i;
}
for (int a = 1; a <= 1000; a++) {
for (int b = a; b <= 1000; b++) {
int x = cubes[a] + cubes[b];
if (x > LIMIT) {
break;
}
cnt.merge(x, 1, Integer::sum);
}
}
for (Map.Entry<Integer, Integer> e : cnt.entrySet()) {
if (e.getValue() > 1) {
GOOD.add(e.getKey());
}
}
Collections.sort(GOOD);
}
public List<Integer> findGoodIntegers(int n) {
int idx = Collections.binarySearch(GOOD, n + 1);
if (idx < 0) {
idx = -idx - 1;
}
return GOOD.subList(0, idx);
}
}vector<int> GOOD;
auto init = [] {
const int LIMIT = 1e9;
unordered_map<int, int> cnt;
vector<int> cubes(1001);
for (int i = 0; i <= 1000; ++i) {
cubes[i] = i * i * i;
}
for (int a = 1; a <= 1000; ++a) {
for (int b = a; b <= 1000; ++b) {
int x = cubes[a] + cubes[b];
if (x > LIMIT) break;
cnt[x]++;
}
}
for (auto& [x, v] : cnt) {
if (v > 1) {
GOOD.push_back(x);
}
}
sort(GOOD.begin(), GOOD.end());
return 0;
}();
class Solution {
public:
vector<int> findGoodIntegers(int n) {
int idx = upper_bound(GOOD.begin(), GOOD.end(), n) - GOOD.begin();
return vector<int>(GOOD.begin(), GOOD.begin() + idx);
}
};const LIMIT = 1e9;
const GOOD: number[] = (() => {
const cnt = new Map<number, number>();
const cubes: number[] = Array.from({ length: 1001 }, (_, i) => i * i * i);
for (let a = 1; a <= 1000; a++) {
for (let b = a; b <= 1000; b++) {
const x = cubes[a] + cubes[b];
if (x > LIMIT) break;
cnt.set(x, (cnt.get(x) ?? 0) + 1);
}
}
const res: number[] = [];
for (const [x, v] of cnt.entries()) {
if (v > 1) res.push(x);
}
res.sort((a, b) => a - b);
return res;
})();
function findGoodIntegers(n: number): number[] {
const idx = _.sortedLastIndex(GOOD, n);
return GOOD.slice(0, idx);
}var GOOD []int
func init() {
const LIMIT = 1e9
cnt := make(map[int]int)
cubes := make([]int, 1001)
for i := 0; i <= 1000; i++ {
cubes[i] = i * i * i
}
for a := 1; a <= 1000; a++ {
for b := a; b <= 1000; b++ {
x := cubes[a] + cubes[b]
if x > LIMIT {
break
}
cnt[x]++
}
}
for x, v := range cnt {
if v > 1 {
GOOD = append(GOOD, x)
}
}
sort.Ints(GOOD)
}
func findGoodIntegers(n int) []int {
idx := sort.Search(len(GOOD), func(i int) bool {
return GOOD[i] > n
})
return GOOD[:idx]
}Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force Pair Enumeration | O(n^2) to O(n^3) | O(1) | Conceptual baseline or very small constraints |
| Hash Table Counting | O(n^2) | O(n^2) | General solution; fastest lookup for duplicate cube sums |
| Sort Cube Sums | O(n^2 log n) | O(n^2) | When deterministic ordering or post‑processing of sums is required |
| Min Heap Enumeration | O(n^2 log n) | O(n) | When memory is constrained but sorted enumeration is needed |
Frequently asked questions
Is Integers With Multiple Sum of Two Cubes easy or hard?
The problem is usually classified as medium difficulty. The enumeration idea is simple, but recognizing that duplicate sums must be tracked efficiently pushes the solution toward hash tables or sorted pair generation techniques.
Integers With Multiple Sum of Two Cubes Python/Java solution
Python typically uses a dictionary to store cube sums: iterate over all pairs, compute a**3 + b**3, and increment the count in the map. Java implementations follow the same pattern using HashMap<Integer, Integer>. After processing pairs, iterate through the map to collect sums with frequency greater than one.
How to solve Integers With Multiple Sum of Two Cubes in O(n^2)?
Iterate through all integer pairs where a ≤ b and compute a^3 + b^3. Store the result in a hash map that tracks how many times each sum appears. Whenever a sum appears more than once, it means different cube pairs generate the same integer. The algorithm finishes after processing all pairs, giving O(n^2) time and O(n^2) space.
What is the best approach for Integers With Multiple Sum of Two Cubes?
The most practical approach uses a hash table to store counts of values generated by a^3 + b^3. Iterate through all pairs (a, b), compute the cube sum, and increment its frequency in a map. Any sum with a frequency of at least two has multiple representations. This runs in O(n^2) time with O(n^2) space.
Is Integers With Multiple Sum of Two Cubes asked at Google/Amazon/Meta?
Problems involving cube sums and duplicate pair detection appear in interview variations related to hash tables and pair enumeration. Companies like Google, Amazon, and Meta often ask similar problems where you must detect multiple representations or repeated pair sums efficiently.
What data structure is used in Integers With Multiple Sum of Two Cubes?
A hash table (or dictionary) is the primary data structure. It maps each computed value of a^3 + b^3 to the number of pairs that produce it. Sorting arrays or using a min heap are alternative strategies depending on whether ordered processing or memory optimization is needed.
What is the time complexity of Integers With Multiple Sum of Two Cubes?
The dominant cost is enumerating all pairs (a, b), which requires O(n^2) iterations. Hash table insertion and lookup are O(1) on average, so the overall complexity remains O(n^2). Sorting-based solutions increase complexity to O(n^2 log n).
