#3890

Integers With Multiple Sum of Two Cubes

Medium
Hash TableSortingCountingEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n)
O(n)
💡

Intuition

Time O(n)Space O(n)

Instead of checking all pairs, we can compute sums directly and count occurrences using a hash map, which reduces unnecessary computations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a hash map to count sums of cubes.
  2. 2Step 2: Loop through possible values of a and b, calculating their cubes and storing sums in the map.
  3. 3Step 3: Collect keys from the map that have counts greater than 1 and return them sorted.
solution.py11 lines
1def findGoodIntegers(n):
2    from collections import defaultdict
3    count = defaultdict(int)
4    limit = int(n**(1/3))
5    for a in range(1, limit + 1):
6        for b in range(a, limit + 1):
7            s = a**3 + b**3
8            if s > n:
9                break
10            count[s] += 1
11    return sorted(k for k, v in count.items() if v > 1)

Complexity note: The complexity is reduced by limiting the range of a and b to the cube root of n, leading to a more efficient solution.

  • 1Good integers can be expressed as sums of cubes in multiple ways.
  • 2Using a hash map allows efficient counting of occurrences.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.