MediumNo. 0526
Beautiful Arrangement — LeetCode 526 Python Solution
- Pattern
- Backtracking
- Topics
- Bit Manipulation, Array, Dynamic Programming, Backtracking, Bitmask
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Suppose you have n integers labeled 1 through n. A permutation of those n integers perm (1-indexed) is considered a beautiful arrangement if for every i (1 <= i <= n), either of the following is true: perm[i] is divisible by i.
Example
- Input
- n = 2
- Output
- 2
- Explanation
- The first beautiful arrangement is [1,2]:
Python solution
class Solution:
def countArrangement(self, n: int) -> int:
def dfs(i):
nonlocal ans, n
if i == n + 1:
ans += 1
return
for j in match[i]:
if not vis[j]:
vis[j] = True
dfs(i + 1)
vis[j] = False
ans = 0
vis = [False] * (n + 1)
match = defaultdict(list)
for i in range(1, n + 1):
for j in range(1, n + 1):
if j % i == 0 or i % j == 0:
match[i].append(j)
dfs(1)
return ansComplexity
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
Pattern: Backtracking
Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 526. Beautiful Arrangement is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.
The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0667 | Beautiful Arrangement II | Medium |
| 0473 | Matchsticks to Square | Medium |
| 0638 | Shopping Offers | Medium |
| 0698 | Partition to K Equal Sum Subsets | Medium |
| 1655 | Distribute Repeating Integers | Hard |
| 1723 | Find Minimum Time to Finish All Jobs | Hard |
Frequently asked questions
- How hard is LeetCode 526. Beautiful Arrangement?
LeetCode 526. Beautiful Arrangement is rated Medium on LeetCode.
- What topics does LeetCode 526. Beautiful Arrangement cover?
LeetCode 526. Beautiful Arrangement is tagged Bit Manipulation, Array, Dynamic Programming, Backtracking and Bitmask on LeetCode.