The Permutations III problem asks for permutations of 1..n with the additional constraint that adjacent elements must not be consecutive integers (|perm[i] - perm[i+1]| != 1). This coding problem uses backtracking with an additional adjacency constraint check. The array and backtracking interview pattern is demonstrated with pruning.
Goldman Sachs asks this to test backtracking with custom constraints. Adding the "no consecutive integers adjacent" rule requires checking the last placed element before each placement, enabling significant pruning of the search space.
Backtracking with adjacency pruning. Standard permutation backtracking with an extra check: before placing nums[i] at position j > 0, verify |nums[i] - current[-1]| > 1. If the constraint fails, skip this choice. This prunes many invalid branches early.
n=3, nums=[1,2,3]. Standard permutations=6. With constraint |a-b|!=1:
n=4: some valid permutations exist (e.g., [2,4,1,3]).
Constraint-based backtracking always prunes as early as possible. Check the constraint before recursing, not after. The adjacency constraint here is checked immediately when adding to the path. Practice adding various constraints to standard permutation backtracking: "no two same elements adjacent," "alternating odd/even," "no two consecutive." Each requires only a minor modification to the base template.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Combination Sum II | Medium | Solve | |
| Permutations | Medium | Solve | |
| Combination Sum | Medium | Solve | |
| Combination Sum III | Medium | Solve | |
| Construct the Lexicographically Largest Valid Sequence | Medium | Solve |