Minimum Adjacent Swaps to Reach the Kth Smallest Number — LeetCode 1850 Python Solution
- Problem
- #1850
- Pattern
- Two Pointers
- Reading time
- 6 min
- Source
- leetcode.com
The problem
You are given a string num, representing a large integer, and an integer k. We call some integer wonderful if it is a permutation of the digits in num and is greater in value than num.
Example
- Input
- num = "5489355142", k = 4
- Output
- 2
- Explanation
- The 4th smallest wonderful number is "5489355421". To get this number:
Python solution
class Solution:
def getMinSwaps(self, num: str, k: int) -> int:
def next_permutation(nums: List[str]) -> bool:
n = len(nums)
i = n - 2
while i >= 0 and nums[i] >= nums[i + 1]:
i -= 1
if i < 0:
return False
j = n - 1
while j >= 0 and nums[j] <= nums[i]:
j -= 1
nums[i], nums[j] = nums[j], nums[i]
nums[i + 1 : n] = nums[i + 1 : n][::-1]
return True
s = list(num)
for _ in range(k):
next_permutation(s)
d = [[] for _ in range(10)]
idx = [0] * 10
n = len(s)
for i, c in enumerate(num):
j = ord(c) - ord("0")
d[j].append(i)
arr = [0] * n
for i, c in enumerate(s):
j = ord(c) - ord("0")
arr[i] = d[j][idx[j]]
idx[j] += 1
return sum(arr[j] > arr[i] for i in range(n) for j in range(i))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n \times (k + n)) |
| Space | O(n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number is filed here because LeetCode tags it Two Pointers, which is the vocabulary this hub collects.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number?
- LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number?
- The Python solution on this page runs in O(n \times (k + n)).
- What is the space complexity of LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number cover?
- LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number is tagged Greedy, Two Pointers and String on LeetCode.