Talentd
FleetCode
Make and follow sheets.Sign in

Minimum Adjacent Swaps to Reach the Kth Smallest Number solution and explanation

MediumGreedyStringTwo Pointers7 min read72.0% acceptanceUpdated 9 Apr 2026
Minimum Adjacent Swaps to Reach the Kth Smallest Number | LeetCode 1850 | Coders CampCoders Camp · 13:32 · 3K viewsWatch on YouTube
9 more videos on this problem
  1. Minimum Adjacent Swaps to Reach the Kth Smallest Number | LeetCode 1850 | Coders CampCoders Camp · 13:32 · 3K views
  2. LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest NumberHappy Coding · 18:45 · 2K views
  3. LeetCode Contest 239 Qusetion 3: Minimum Adjacent Swaps to Reach the Kth Smallest NumberCoding Ninjas Webinars and Contest Editorials · 8:51 · 1K views
  4. 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number (Leetcode Medium)Programming Live with Larry · 17:44 · 649 views
  5. LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number 中文 | Weekly Contest 239宰相小甘罗 · 3:15 · 634 views
  6. Leetcode 1850: Minimum Adjacent Swaps to Reach the Kth Smallest Number | Intuition and approachCode Concepts with Animesh · 31:13 · 529 views
  7. 【每日一题】1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number, 5/7/2021Huifeng Guan · 18:18 · 477 views
  8. LeetCode Contest 239 Question 3: Minimum Adjacent Swaps to Reach the Kth Smallest NumberCoding Ninjas Webinars and Contest Editorials · 12:41 · 422 views
  9. LeetCode 1850. Minimum Adjacent Swaps to Reach the Kth Smallest Number | Weekly Contest 239宰相小甘罗 · 3:18 · 344 views
  10. LeetCode 1850: Minimum Adjacent Swaps to Reach the Kth Smallest Number | Medium | String | GreedyThe Compass · 27:59 · 235 views

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. There can be many wonderful integers. However, we only care about the smallest-valued ones.

  • For example, when num = "5489355142":
    • The 1st smallest wonderful integer is "5489355214".
    • The 2nd smallest wonderful integer is "5489355241".
    • The 3rd smallest wonderful integer is "5489355412".
    • The 4th smallest wonderful integer is "5489355421".

Return the minimum number of adjacent digit swaps that needs to be applied to num to reach the kth smallest wonderful integer.

The tests are generated in such a way that kth smallest wonderful integer exists.

Example 1:

Input: num = "5489355142", k = 4
Output: 2
Explanation: The 4th smallest wonderful number is "5489355421". To get this number:
- Swap index 7 with index 8: "5489355142" -> "5489355412"
- Swap index 8 with index 9: "5489355412" -> "5489355421"

Example 2:

Input: num = "11112", k = 4
Output: 4
Explanation: The 4th smallest wonderful number is "21111". To get this number:
- Swap index 3 with index 4: "11112" -> "11121"
- Swap index 2 with index 3: "11121" -> "11211"
- Swap index 1 with index 2: "11211" -> "12111"
- Swap index 0 with index 1: "12111" -> "21111"

Example 3:

Input: num = "00123", k = 1
Output: 1
Explanation: The 1st smallest wonderful number is "00132". To get this number:
- Swap index 3 with index 4: "00123" -> "00132"

Constraints:

  • 2 <= num.length <= 1000
  • 1 <= k <= 1000
  • num only consists of digits.

Approach overview

Problem Overview: Given a numeric string num and an integer k, find the minimum number of adjacent swaps required to transform num into its kth next lexicographically smallest permutation. You first determine what the kth permutation looks like, then compute how many adjacent swaps are needed to reach it.

Approach 1: Using Next Permutation (O(k·n + n²) time, O(n) space)

Generate the target number by applying the next_permutation operation k times on the original string. This algorithm scans from right to left to find the first decreasing pair, swaps with the next larger digit, then reverses the suffix. Once the kth permutation is obtained, compute the minimum adjacent swaps needed to convert the original string into this target. Iterate through each position; when digits differ, search forward in the target and repeatedly swap left until the correct digit reaches the position. This simulates the minimum adjacent swaps required. The approach relies on string manipulation and a greedy bubble-style swap process.

Approach 2: Optimized Swap Calculation (O(k·n + n²) time, O(1) extra space)

After generating the kth permutation, compute swaps more efficiently using a greedy shifting strategy. Traverse both strings from left to right. If characters match, move forward. When they differ, locate the matching digit in the target suffix, then shift it left using adjacent swaps while counting operations. Each shift reduces the distance between the digit's current index and its desired position. This guarantees the minimal number of swaps because adjacent swaps preserve relative ordering. The logic combines ideas from greedy algorithms with pointer scanning similar to two pointers.

Recommended for interviews: Interviewers typically expect the next permutation approach combined with a greedy adjacent swap count. Showing the next_permutation logic demonstrates understanding of permutation generation, while the swap simulation shows how to compute minimal adjacent operations. The optimized swap counting variant is cleaner in implementation and easier to reason about during interviews.

Approach 1: Approach 1: Using Next Permutation

This approach involves finding the next permutation of the given number sequentially k times. Once we have the kth permutation, we compare it with the original number and calculate the minimum swaps needed to transform the original number into this new permutation.

def next_permutation(perm):
    i = len(perm) - 2
    while i >= 0 and perm[i] >= perm[i + 1]:
        i -= 1
    if i == -1:
        return False
    j = len(perm) - 1
    while perm[j] <= perm[i]:
        j -= 1
    perm[i], perm[j] = perm[j], perm[i]
    perm[i + 1:] = perm[i + 1:][::-1]
    return True

def min_adjacent_swaps(num, k):
    num_list = list(num)
    b_list = num_list[:]
    for _ in range(k):
        next_permutation(num_list)

    def count_swaps(a, b):
        a = list(a)
        swaps = 0
        for i in range(len(a)):
            if a[i] != b[i]:
                j = a.index(b[i], i)
                while j > i:
                    a[j], a[j - 1] = a[j - 1], a[j]
                    swaps += 1
                    j -= 1
        return swaps

    return count_swaps(b_list, num_list)

num = "5489355142"
k = 4
print(min_adjacent_swaps(num, k))
function nextPermutation(perm) {
    let i = perm.length - 2;
    while (i >= 0 && perm[i] >= perm[i + 1]) i--;
    if (i === -1) return false;
    let j = perm.length - 1;
    while (perm[j] <= perm[i]) j--;
    [perm[i], perm[j]] = [perm[j], perm[i]];
    perm = [...perm.slice(0, i + 1), ...perm.slice(i + 1).reverse()];
    return perm;
}

function minAdjacentSwaps(num, k) {
    const numArr = num.split('');
    let bArr = numArr.slice();
    for (let count = 0; count < k; count++) {
        numArr = nextPermutation(numArr);
    }

    const countSwaps = (a, b) => {
        let swaps = 0;
        a = a.slice();
        for (let i = 0; i < a.length; i++) {
            if (a[i] !== b[i]) {
                let j = a.indexOf(b[i], i);
                while (j > i) {
                    [a[j], a[j - 1]] = [a[j - 1], a[j]];
                    swaps++;
                    j--;
                }
            }
        }
        return swaps;
    };

    return countSwaps(bArr, numArr);
}

const num = "5489355142";
const k = 4;
console.log(minAdjacentSwaps(num, k));

This Python function first computes the kth permutation by finding the next permutation k times. The next_permutation function rearranges the list into the next lexicographically greater permutation. After obtaining the kth permutation, we calculate the minimum swaps needed to transform the original permutation into the kth one. This is achieved by finding the index of the element in the current list that matches the desired permutation and swapping it into the correct place.

Complexity

Time Complexity: O(n * k), where n is the length of the string and k is the number of permutations to find.
Space Complexity: O(n), for storing the list representation of the numbers.

Try this approach in the editor

Approach 2: Approach 2: Optimized Swap Calculation

This approach involves computing the kth permutation more efficiently using an algorithm to apply the minimum adjacent swaps directly based on the differences between current and target permutations. Instead of finding all permutations, this focuses on achieving the next permutations and dynamically swaps to approach the target.

import java.util.*;

public class MinSwaps {
    public static int getNextPermutation(String num, int k) {
        char[] numArr = num.toCharArray();
        char[] original = num.toCharArray();
        while (k-- > 0) {
            nextPermutation(numArr);
        }
        return countSwaps(original, numArr);
    }

    private static void nextPermutation(char[] num) {
        int i = num.length - 2;
        while (i >= 0 && num[i] >= num[i + 1]) i--;
        if (i >= 0) {
            int j = num.length - 1;
            while (num[j] <= num[i]) j--;
            swap(num, i, j);
        }
        reverse(num, i + 1);
    }

    private static void swap(char[] num, int i, int j) {
        char temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }

    private static void reverse(char[] num, int start) {
        int end = num.length - 1;
        while (start < end) {
            swap(num, start, end);
            start++; end--;
        }
    }

    private static int countSwaps(char[] original, char[] target) {
        int swaps = 0;
        List<Character> listO = new ArrayList<>();
        for (char c : original) listO.add(c);
        for (int i = 0; i < target.length; i++) {
            if (listO.get(i) != target[i]) {
                int index = listO.lastIndexOf(target[i]);
                for (int j = index; j > i; j--) {
                    Collections.swap(listO, j, j - 1);
                    swaps++;
                }
            }
        }
        return swaps;
    }

    public static void main(String[] args) {
        String num = "5489355142";
        int k = 4;
        System.out.println(getNextPermutation(num, k));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int getNextPermutation(string& num, int k) {
    string original = num;
    vector<int> swaps;
    while (k--) {
        next_permutation(num.begin(), num.end());
    }
    for (int i = 0; i < num.size(); ++i) {
        if (original[i] != num[i]) {
            int j = i;
            while (original[j] != num[i]) {
                j++;
            }
            while (j > i) {
                swap(original[j], original[j - 1]);
                swaps.push_back(j - 1);
                j--;
            }
        }
    }
    return swaps.size();
}

int main() {
    string num = "5489355142";
    int k = 4;
    cout << getNextPermutation(num, k);
    return 0;
}

Java code follows a similar logic where it uses character arrays to manage permutations. The nextPermutation function generates the kth permutation, while the countSwaps calculates the number of swaps needed. It employs ArrayList operations for swapping that are tightly aligned with indices to efficiently determine and execute minimum adjacent swaps.

Complexity

Time Complexity: O(n * k) due to sequential operations.
Space Complexity: O(n) for the storage of arrays and intermediate lists.

Try this approach in the editor

Approach 3: Find Next Permutation + Inversion Pairs

We can call the next_permutation function k times to get the kth smallest permutation s.

Next, we just need to calculate how many swaps are needed for num to become s.

Let's first consider a simple situation where all the digits in num are different. In this case, we can directly map the digit characters in num to indices. For example, if num is "54893" and s is "98345". We map each digit in num to an index, that is:

$ \begin{aligned} num[0] &= 5 &\rightarrow& \quad 0 \ num[1] &= 4 &\rightarrow& \quad 1 \ num[2] &= 8 &\rightarrow& \quad 2 \ num[3] &= 9 &\rightarrow& \quad 3 \ num[4] &= 3 &\rightarrow& \quad 4 \ \end{aligned}

Then, mapping each digit in s to an index results in "32410". In this way, the number of swaps needed to change num to s is equal to the number of inversion pairs in the index array after s is mapped.

If there are identical digits in num, we can use an array d to record the indices where each digit appears, where d[i] represents the list of indices where the digit i appears. To minimize the number of swaps, when mapping s to an index array, we only need to greedily select the index of the corresponding digit in d in order.

Finally, we can directly use a double loop to calculate the number of inversion pairs, or we can optimize it with a Binary Indexed Tree.

The time complexity is O(n times (k + n)), and the space complexity is O(n). Where n is the length of num$.

function getMinSwaps(num: string, k: number): number {
    const n = num.length;
    const s = num.split('');
    for (let i = 0; i < k; ++i) {
        nextPermutation(s);
    }
    const d: number[][] = Array.from({ length: 10 }, () => []);
    for (let i = 0; i < n; ++i) {
        d[+num[i]].push(i);
    }
    const idx: number[] = Array(10).fill(0);
    const arr: number[] = [];
    for (let i = 0; i < n; ++i) {
        arr.push(d[+s[i]][idx[+s[i]]++]);
    }
    let ans = 0;
    for (let i = 0; i < n; ++i) {
        for (let j = 0; j < i; ++j) {
            if (arr[j] > arr[i]) {
                ans++;
            }
        }
    }
    return ans;
}

function nextPermutation(nums: string[]): boolean {
    const n = nums.length;
    let i = n - 2;
    while (i >= 0 && nums[i] >= nums[i + 1]) {
        i--;
    }
    if (i < 0) {
        return false;
    }
    let j = n - 1;
    while (j >= 0 && nums[i] >= nums[j]) {
        j--;
    }
    [nums[i], nums[j]] = [nums[j], nums[i]];
    for (i = i + 1, j = n - 1; i < j; ++i, --j) {
        [nums[i], nums[j]] = [nums[j], nums[i]];
    }
    return true;
}
func getMinSwaps(num string, k int) (ans int) {
	s := []byte(num)
	for ; k > 0; k-- {
		nextPermutation(s)
	}
	d := [10][]int{}
	for i, c := range num {
		j := int(c - '0')
		d[j] = append(d[j], i)
	}
	idx := [10]int{}
	n := len(s)
	arr := make([]int, n)
	for i, c := range s {
		j := int(c - '0')
		arr[i] = d[j][idx[j]]
		idx[j]++
	}
	for i := 0; i < n; i++ {
		for j := 0; j < i; j++ {
			if arr[j] > arr[i] {
				ans++
			}
		}
	}
	return
}

func nextPermutation(nums []byte) bool {
	n := len(nums)
	i := n - 2
	for i >= 0 && nums[i] >= nums[i+1] {
		i--
	}
	if i < 0 {
		return false
	}
	j := n - 1
	for j >= 0 && nums[j] <= nums[i] {
		j--
	}
	nums[i], nums[j] = nums[j], nums[i]
	for i, j = i+1, n-1; i < j; i, j = i+1, j-1 {
		nums[i], nums[j] = nums[j], nums[i]
	}
	return true
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Approach 1: Using Next Permutation

Time Complexity: O(n * k), where n is the length of the string and k is the number of permutations to find.
Space Complexity: O(n), for storing the list representation of the numbers.

Approach 2: Optimized Swap Calculation

Time Complexity: O(n * k) due to sequential operations.
Space Complexity: O(n) for the storage of arrays and intermediate lists.

Find Next Permutation + Inversion Pairs–

Complexity analysis

ApproachTimeSpaceWhen to Use
Next Permutation + Swap SimulationO(k·n + n²)O(n)Most common solution; easy to implement and explain in interviews
Optimized Greedy Swap CalculationO(k·n + n²)O(1)When minimizing extra memory and implementing cleaner swap counting

Frequently asked questions

Is Minimum Adjacent Swaps to Reach the Kth Smallest Number easy or hard?

The problem is classified as Medium because it combines two concepts: generating permutations and calculating minimal adjacent swaps. Each component is manageable individually, but implementing both correctly requires careful index handling and string manipulation.

Minimum Adjacent Swaps to Reach the Kth Smallest Number Python/Java solution

Python and Java implementations usually follow the same structure: compute the kth permutation using next permutation logic, then simulate adjacent swaps to transform the original number into that permutation. The algorithm works identically across languages including Python, Java, C++, and JavaScript.

How to solve Minimum Adjacent Swaps to Reach the Kth Smallest Number in O(n)?

A strict O(n) solution is not possible because generating the kth permutation itself requires repeated permutation operations. The practical optimal approach performs next permutation k times and then computes swap distance greedily. This results in O(k·n + n²) time, which is efficient for the constraints of the problem.

What is the best approach for Minimum Adjacent Swaps to Reach the Kth Smallest Number?

The most reliable method generates the kth smallest permutation using the next permutation algorithm, then counts the minimum adjacent swaps needed to convert the original string into that permutation. This combines permutation generation with a greedy swap simulation. Time complexity is O(k·n + n²) and space complexity is O(n).

Is Minimum Adjacent Swaps to Reach the Kth Smallest Number asked at Google/Amazon/Meta?

Permutation manipulation and minimum swap problems frequently appear in interviews at companies like Google, Amazon, and Meta. Variants involving next permutation, greedy swaps, and string transformations are common because they test algorithmic thinking and careful implementation.

What data structure is used in Minimum Adjacent Swaps to Reach the Kth Smallest Number?

The solution mainly uses arrays or strings to represent digits. Two-pointer scanning and greedy swapping are used to compute the minimal number of adjacent swaps. No advanced data structures are required beyond basic string or array manipulation.

What is the time complexity of Minimum Adjacent Swaps to Reach the Kth Smallest Number?

Generating the kth permutation requires applying the next permutation operation k times, which costs O(k·n). Counting the minimum adjacent swaps between the original and target permutation takes O(n²) in the worst case. Overall complexity is O(k·n + n²) with O(n) auxiliary space.

Comments

Now write it yourselfClose this page and solve Minimum Adjacent Swaps to Reach the Kth Smallest Number in the editor, without looking.
Practise Minimum Adjacent Swaps to Reach the Kth Smallest Number