Tim Varley Logo
Tim Varley Principal AI Engineer and Tech Leader
Problem #62 medium

Cubic Permutations

The cube, 4106362541063625 (3453345^3), can be permuted to produce two other cubes: 5662310456623104 (3843384^3) and 6643012566430125 (4053405^3). In fact, 4106362541063625 is the smallest cube which has exactly three permutations of its digits which are also cube.

Find the smallest cube for which exactly five permutations of its digits are cube.

View on Project Euler

Implementations

cpp
#include <iostream>
#include <climits>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <string>
long long cubic_permutations() {
std::unordered_map<std::string, std::vector<long long>> groups;
for (long long n = 1; ; ++n) {
long long cube = n * n * n;
std::string s = std::to_string(cube);
if (s.length() > 12) break;
std::string key = s;
std::sort(key.begin(), key.end());
groups[key].push_back(cube);
}
long long min_cube = LLONG_MAX;
for (const auto& pair : groups) {
if (pair.second.size() == 5) {
for (long long c : pair.second) {
if (c < min_cube) min_cube = c;
}
}
}
return min_cube;
}
#if ! defined UNITTEST_MODE
int main(int argc, char const *argv[]) {
std::cout << cubic_permutations() << std::endl;
}
#endif
View on GitHub
O(n) time complexity

Solution Notes

Mathematical Background

This problem involves finding the smallest cube whose digits can be rearranged to form exactly four other cubes.

Algorithm Analysis

Generate cubes and group them by their sorted digit strings to find permutations that are also cubes.

Performance Analysis

  • Time Complexity: O(n log n) due to string sorting
  • Space Complexity: O(n) for storing groups
  • Execution Time: Very fast for reasonable limits
  • Scalability: Linear with cube root of limit

Key Insights

  • Digit sorting creates canonical representation for permutations
  • Grouping enables efficient lookup of cube permutations
  • The solution has 12 digits

Educational Value

This problem teaches:

  • String manipulation and sorting
  • Hash maps for grouping
  • Permutation concepts
  • Cube number generation