VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-number-possible-by-doing-at-most-k-swaps/

⇱ Maximum number possible by doing at-most K swaps - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum number possible by doing at-most K swaps

Last Updated : 12 May, 2025

Given a string s and an integer k, the task is to find the maximum possible number by performing swap operations on the digits of s at most k times.

Examples:

Input: s = "7599", k = 2
Output: 9975
Explanation: Two Swaps can make input 7599 to 9975. First swap 9 with 5 so number becomes 7995, then swap 9 with 7 so number becomes 9975

Input: s = "1234567", k = 4
Output: 7654321
Explanation: Three swaps can make the input 1234567 to 7654321. First swap 1 with 7, then swap 2 with 6 and finally swap 3 with 5.

Input: s = "76543", k = 1 
Output: 76543
Explanation: No swap is required.

[Approach 1] Using Recursion - O((n^2)^k) Time and O(k) Space

The idea is to generate the maximum possible number by performing at most k swaps on the given string. We iterate through all pairs of characters and swap them if it results in a larger number. After each swap, we recursively call the function with one fewer swap left. The algorithm backtracks after each swap to explore all possible combinations, and the largest number found is returned as the result.


Output
9975

Time Complexity: O((n^2)^k), where n is the length of the string and k is the maximum number of swaps. For each recursion, O(n^2) operations are performed, and there are k levels of recursion).
Auxiliary Space: O(k), for the recursion stack.

[Approach 2] Swap the Max Digit - O((n^2)^k) Time and O(k) Space

The idea is to recursively iterate through the string, finding the maximum digit for the current position, and swapping it with a larger digit later in the string. The algorithm uses a backtracking technique, meaning after each swap, it recurses to explore further swaps and then undoes the swap (backtracks). This process continues until no swaps are left or the maximum number is achieved.

Output
9975

Time Complexity: O(n^2 ^ k), where n is the length of the string and k is the maximum number of swaps. In the worst case, the recursion can go as deep as k. Therefore, the total time complexity can be approximated as O(n^2 ^ k)
Auxiliary Space: O(k), due to recursion stack.

Comment