Beautiful Arrangement of Numbers in JavaScript

A beautiful arrangement is a permutation of numbers from 1 to num where each position satisfies specific divisibility rules. This problem involves finding all valid arrangements using backtracking.

Definition

For an array with num integers from 1 to num, a beautiful arrangement requires that for each position i (1-indexed):

  • The number at position i is divisible by i, OR

  • i is divisible by the number at position i

Problem Statement

Write a JavaScript function that takes a number and returns the count of all possible beautiful arrangements.

Example Input/Output

For input num = 2:

Input: 2
Output: 2

The two beautiful arrangements are [1,2] and [2,1]:

  • [1,2]: Position 1 has 1 (1%1=0), Position 2 has 2 (2%2=0) ?

  • [2,1]: Position 1 has 2 (1%2?0 but 2%1=0), Position 2 has 1 (2%1=0) ?

Solution Using Backtracking

const countArrangements = (num = 1) => {
    let ans = 0;
    
    const recur = (curr, vis) => {
        if (curr === 1) {
            ans++;
        } else {
            for (let i = num; i >= 1; i--) {
                let possible = (i % curr === 0 || curr % i === 0);
                let visited = vis & (1 

num = 2: 2
num = 3: 3
num = 4: 8

How the Algorithm Works

The solution uses backtracking with bit manipulation for efficient visited tracking:

  • curr: Current position being filled (counts down from num to 1)

  • vis: Bitmask representing which numbers are already used

  • Base case: When curr = 1, we've found a valid arrangement

  • Recursive case: Try each unused number that satisfies divisibility rules

Step-by-Step Example (num = 3)

const traceArrangements = (num) => {
    let count = 0;
    const arrangements = [];
    
    const backtrack = (position, used, current) => {
        if (position > num) {
            arrangements.push([...current]);
            count++;
            return;
        }
        
        for (let i = 1; i 

Total arrangements for num=3: 3
Valid arrangements: [ [ 1, 2, 3 ], [ 2, 1, 3 ], [ 3, 2, 1 ] ]

Conclusion

Beautiful arrangements use backtracking to explore all valid permutations efficiently. The bit manipulation approach optimizes space while the divisibility check ensures correctness.

Updated on: 2026-03-15T23:19:00+05:30

420 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements