Problem 526

Abstract / Summary

Count how many ways to place numbers so that each number at position i is divisible by i or i is divisible by the number.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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;
    }
};
54 lines | 1325 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 65% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Backtracking
  • Bit Manipulation
  • Bitmask
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.93 | σ = 1.30

Complexity Analysis

Time: exponential
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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
32 links | 19 authors | 9 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

19 easy 42 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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