#3470

Permutations IV

Hard
ArrayMathCombinatoricsEnumerationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(n!)
O(n)
💡

Intuition

Time O(n)Space O(n)

Use combinatorial properties to generate the k-th permutation directly without generating all permutations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Determine the number of odd and even integers based on n.
  2. 2Step 2: Use combinatorial counting to find the k-th valid permutation directly.
  3. 3Step 3: Construct the permutation by selecting elements based on the calculated positions.
solution.py25 lines
1from math import comb
2
3def kth_alternating_permutation(n, k):
4    odds = (n + 1) // 2
5    evens = n // 2
6    result = []
7    if k > comb(odds + evens, odds): return []
8    for i in range(n):
9        if i % 2 == 0:
10            for j in range(1, odds + 1):
11                count = comb(odds - j + evens, odds - j)
12                if k <= count:
13                    result.append(2 * j - 1)
14                    odds -= 1
15                    break
16                k -= count
17        else:
18            for j in range(1, evens + 1):
19                count = comb(odds + evens - j, odds)
20                if k <= count:
21                    result.append(2 * j)
22                    evens -= 1
23                    break
24                k -= count
25    return result

Complexity note: The optimal solution uses combinatorial counting, leading to linear time complexity for generating the k-th permutation.

  • 1Understanding permutations and their properties is crucial.
  • 2Combinatorial counting can significantly reduce complexity.

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