#526

Beautiful Arrangement

Medium
ArrayDynamic ProgrammingBacktrackingBit ManipulationBitmaskBacktrackingBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n * 2^n)
Space
O(n)
O(n)
💡

Intuition

Time O(n * 2^n)Space O(n)

The optimal solution uses backtracking with bit manipulation to efficiently track which numbers have been used in the arrangement. This reduces the overhead of generating all permutations explicitly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Use a backtracking function that takes the current position and a bitmask to track used numbers.
  2. 2Step 2: For each position, iterate through numbers from 1 to n, checking if they can be placed based on the beautiful arrangement conditions.
  3. 3Step 3: If valid, mark the number as used (update the bitmask) and proceed to the next position.
  4. 4Step 4: Count valid arrangements when reaching the end of the array.
solution.py10 lines
1def countArrangement(n):
2    def backtrack(pos, used):
3        if pos > n:
4            return 1
5        count = 0
6        for i in range(1, n + 1):
7            if not (used & (1 << i)) and (i % pos == 0 or pos % i == 0):
8                count += backtrack(pos + 1, used | (1 << i))
9        return count
10    return backtrack(1, 0)

Complexity note: The time complexity is O(n * 2^n) due to the backtracking with bitmasking, where we explore each number and the number of subsets of used numbers. The space complexity is O(n) for the recursion stack.

  • 1Backtracking is a powerful technique for generating permutations and combinations efficiently.
  • 2Using bit manipulation allows us to track used numbers without needing additional data structures.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.