Problem #62 medium
Cubic Permutations
The cube, (), can be permuted to produce two other cubes: () and (). In fact, 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.
Implementations
#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_MODEint 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