Find Maximum number possible by doing at-most K swaps

Pattern: Permutations

medium

Go left to right. At each position, find the biggest digit to its right. If it is already here, move on for free. Otherwise try swapping in each copy of that digit (not just one), spend a swap, and recurse. Keep the largest number seen.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Given a number as a string of digits and k, return the largest number you can get with at most k swaps of two digits. For example, "1234567" with k = 4 gives "7654321", and "3435335" with k = 3 gives "5543333".

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name findMaximumNum is this guide's own.

Think first

  • Which position matters most for the size of the number?
  • Should a swap ever be spent on a position that already holds its best digit?
  • If the best digit appears twice to the right, does it matter which copy you swap in?

Hints

    Brute force, and why it fails

    Breadth-first search over all numbers reachable within k swaps: up to (n²)^k states, which this guide uses on small tests. Swapping in only the best digit at each place cuts the branching to the number of its copies.

    The key insight

    The greedy rule "put the biggest digit first" is right, but which copy to take is not obvious, as in 3435335. Trying every copy of the best digit, and nothing else, covers exactly the choices that matter.

    Dry run

    10 
    01 
    32 
    43 

    str = 1034 and k = 2. At position 0, the biggest digit to the right is 4.

    Step 1 of 4

    The plan

    best = str
    function search(start, k):
        if k == 0 or start == n: return
        mx = biggest digit in d[start ..]
        if d[start] == mx: search(start + 1, k); return
        for each j > start with d[j] == mx:
            swap d[start], d[j]; best = max(best, d)
            search(start + 1, k - 1)
            swap back
    search(0, k)
    

    Complexity

    Time
    O(n^k) worst
    Space
    O(n)

    Each swap level can branch over several copies of the best digit. In practice the branching is small. The recursion is at most n deep.

    Edge cases

    • Already in decreasing order: unchanged.
    • k larger than needed: the extra swaps are not used.
    • Repeated best digits, as in 3435335: trying every copy matters.
    I've built my logic, show the code

    Java

    class Solution {
        private String best;
    
        public String findMaximumNum(String str, int k) {
            best = str;
            search(str.toCharArray(), 0, k);
            return best;
        }
    
        private void search(char[] d, int start, int k) {
            if (k == 0 || start == d.length) return;
            char max = d[start];
            for (int j = start + 1; j < d.length; j++) if (d[j] > max) max = d[j];   // the best digit for this place
            if (max == d[start]) { search(d, start + 1, k); return; }              // already there: no swap used
            for (int j = d.length - 1; j > start; j--) {
                if (d[j] != max) continue;                  // try every copy of the best digit
                char t = d[start]; d[start] = d[j]; d[j] = t;
                String now = new String(d);
                if (now.compareTo(best) > 0) best = now;
                search(d, start + 1, k - 1);
                t = d[start]; d[start] = d[j]; d[j] = t;    // undo
            }
        }
    }

    C++

    class Solution {
    public:
        string best;
    
        string findMaximumNum(string str, int k) {
            best = str;
            search(str, 0, k);
            return best;
        }
    
        void search(string& d, size_t start, int k) {
            if (k == 0 || start == d.size()) return;
            char mx = *max_element(d.begin() + start, d.end());   // the best digit for this place
            if (mx == d[start]) { search(d, start + 1, k); return; }   // already there: no swap used
            for (size_t j = d.size() - 1; j > start; j--) {
                if (d[j] != mx) continue;                   // try every copy of the best digit
                swap(d[start], d[j]);
                if (d > best) best = d;
                search(d, start + 1, k - 1);
                swap(d[start], d[j]);                       // undo
            }
        }
    };

    Python

    class Solution:
        def findMaximumNum(self, s: str, k: int) -> str:
            d = list(s)
            best = s
    
            def search(start: int, k: int) -> None:
                nonlocal best
                if k == 0 or start == len(d):
                    return
                mx = max(d[start:])                 # the best digit for this place
                if mx == d[start]:
                    search(start + 1, k)            # already there: no swap used
                    return
                for j in range(len(d) - 1, start, -1):
                    if d[j] != mx:
                        continue                    # try every copy of the best digit
                    d[start], d[j] = d[j], d[start]
                    best = max(best, "".join(d))
                    search(start + 1, k - 1)
                    d[start], d[j] = d[j], d[start] # undo
    
            search(0, k)
            return best

    Common mistakes

    • Swapping with the first copy of the best digit only.
    • Spending a swap on a position that already holds its best digit.
    • Comparing numbers as integers, which overflows for long strings.

    Similar problems