C++ 0526.cpp
class Solution {
struct hasher
{
template <typename T, typename U>
size_t operator()(const std::pair<T, U> &x) const
{
return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
}
};
unordered_map<pair<int, int>, int, hasher> cache;
bool beauty[16][16];
int dp(int pos, int maxPos, int mask)
{
if (pos == maxPos + 1)
return 1;
auto key = make_pair(pos, mask);
auto lookup = cache.find(key);
if (lookup != cache.end())
return lookup->second;
int result = 0;
for (int bit = 1; bit <= maxPos; bit++)
{
int compare = 1 << (bit - 1);
if ((mask & compare) == 0)
continue;
if (!beauty[bit][pos])
continue;
result += dp(pos+1, maxPos, mask & ~compare);
}
cache[key] = result;
return result;
}
public:
int countArrangement(int n) {
cache.reserve(20000);
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
beauty[i][j] = (i % j == 0) || (j % i == 0);
auto mask = (1 << n) - 1;
auto result = dp(1, n, mask);
return result;
}
};
Difficulty
and has an acceptance rate of about 65% (300k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
- Bitmask
- Dynamic Programming
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The presented solution computes the number of valid arrangements of the integers 1 through n where each position i must be paired with a number j that satisfies a “beauty” relation: either i divides j or j divides i. The algorithm employs depth-first recursion with memoization, representing the set of still-available numbers as a bitmask. A custom hash enables efficient storage of intermediate results in an unordered_map.
Key Components
Custom Pair Hasher
struct hasher
{
template <typename T, typename U>
size_t operator()(const std::pair<T, U> &x) const
{
return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
}
};
A lightweight XOR-based combination of the standard hash values for the two components of a pair. This allows the pair (pos, mask) to be used directly as a key in the memoization table.
Memoization Table
unordered_map<pair<int, int>, int, hasher> cache;
The map stores the number of ways to complete the arrangement from a given position with a particular remaining-number mask. By reusing previously computed results, the exponential search space is dramatically reduced.
Beauty Matrix Construction
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
beauty[i][j] = (i % j == 0) || (j % i == 0);
A pre-computed boolean matrix records whether two indices satisfy the required divisibility condition. This enables constant-time checks during recursion.
Recursive DP Function
int dp(int pos, int maxPos, int mask)
{
if (pos == maxPos + 1)
return 1;
auto key = make_pair(pos, mask);
auto lookup = cache.find(key);
if (lookup != cache.end())
return lookup->second;
int result = 0;
for (int bit = 1; bit <= maxPos; bit++)
{
int compare = 1 << (bit - 1);
if ((mask & compare) == 0)
continue;
if (!beauty[bit][pos])
continue;
result += dp(pos+1, maxPos, mask & ~compare);
}
cache[key] = result;
return result;
}
The function advances position by position. The base case triggers when all positions have been filled, returning a single valid arrangement. For each candidate number (bit) still present in the mask, the algorithm checks the beauty condition and recurses with the number removed from the mask. The accumulated sum of recursive calls yields the total count for the current state.
Entry Point
int countArrangement(int n) {
cache.reserve(20000);
// beauty matrix filled as shown earlier
auto mask = (1 << n) - 1;
auto result = dp(1, n, mask);
return result;
}
The initial mask has the lowest n bits set, indicating that all numbers are available. Reserving space in the cache anticipates the number of distinct states, reducing rehashing overhead.
Edge Cases Handled
When the recursion reaches a state where the mask contains no set bits, the position index will have advanced to maxPos + 1, satisfying the base case and returning 1. This correctly counts the scenario where the last remaining number fits the beauty requirement.
If a particular bit does not satisfy the beauty relation with the current pos, the inner loop skips the recursive call, ensuring that only admissible pairings contribute to the total.
The bitmask operations (mask & compare and mask & ~compare) safely handle any n up to the width of the integer type, and the loop bounds (bit <= maxPos) guarantee that only defined bits are examined.
Performance Optimizations
The custom hasher eliminates the need for a more heavyweight pair hashing strategy, keeping key lookups fast.
Pre-computing the beauty matrix avoids repeated modulus operations inside the deep recursion, turning a potentially costly arithmetic check into a simple array lookup.
Reserving capacity for the unordered_map prevents frequent reallocation and rehashing as new states are stored, which is especially beneficial given the large number of distinct (pos, mask) combinations encountered for moderate values of n.
Bitmask representation compresses the set of remaining numbers into a single integer, enabling constant-time inclusion tests and updates via bitwise AND and NOT operations. This compact representation reduces both memory footprint and the cost of state transitions.
The early continue statements in the loop prune the search space aggressively: numbers not present in the mask or failing the beauty test are discarded before any recursive call, minimizing unnecessary function invocations.
ELI5 - Simplified Explanation
Imagine you have a row of empty boxes that need toys. Each toy has a number, and each box has a number. A toy can only go into a box if the numbers are friends, which means one number divides evenly into the other.
The code starts by making a giant list of every pair of numbers to see which ones are friends. Think of it like making a treasure map showing which toys fit into which boxes.
Next, it tries to fill the boxes one by one. It keeps track of which toys are already used by hiding them in a little pretend container called a mask. If a toy is in the mask, it is still waiting to be played with.
To make sure things stay fast, the code uses a notebook called a cache. Every time it finds a way to finish a row using a certain set of available toys, it writes the answer down in the notebook. If it ever encounters the same situation again, it just checks the notebook instead of doing all the hard work over again.
The code keeps testing different toys for each spot. It only moves forward to the next spot if the toy it picked is a friend to the box it is currently filling. It keeps trying every single combination until it adds up all the different ways to successfully fill every box.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||||
| WalkCCC | C++ | Java | ||||||||
| leetcode.ca | C++ | Python | Rust | Java | Go | TS | ||||
| LeetcodeHelp | C++ | Python | Java | |||||||
| Progiez | C++ | Python | Java | |||||||
| github | black-shadows | C++ | ||||||||
| charles-wangkai | Java | |||||||||
| everthis | JS | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JS | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| yuanliu666 | Kotlin | |||||||||
| YuriSpiridonov | Python | |||||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||||
| WalkCCC | C++, Java | |||||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||||
| LeetcodeHelp | C++, Java, Python | |||||||||
| Progiez | C++, Java, Python | |||||||||
| black-shadows | C++, C++ | |||||||||
| charles-wangkai | Java | |||||||||
| everthis | JavaScript | |||||||||
| fsq | C++ | |||||||||
| halfrost | Go | |||||||||
| JoshCrozier | JavaScript | |||||||||
| keineahnung2345 | C++ | |||||||||
| linouk23 | C++ | |||||||||
| lkwq007 | Python | |||||||||
| MacJim | C++ | |||||||||
| ruoru | Rust | |||||||||
| suxrobGM | C# | |||||||||
| yuanliu666 | Kotlin | |||||||||
| YuriSpiridonov | Python |
Videos
Similar Problems
- problem 667: Beautiful Arrangement II
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 190: Reverse Bits
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality