Skip to problem
←

Largest Number After at Most K Swaps

Hard 0 attempts

Given a digit string num and a nonnegative integer k, return the largest number you can form using at most k swaps. Each swap exchanges digits at any two positions; the positions need not be adjacent.

Return a string of the same length, without converting it to a JavaScript number. Digits may repeat, and leading zeros are allowed in the input. You may use fewer than k swaps, including none when the arrangement is already optimal.

Function contract

num is a string of decimal digits; k is the maximum number of swaps between any two positions.

Output: Return the largest obtainable digit string. Preserve its length, including leading zeros when no larger arrangement is possible.

Example 1

Input
num = "1234567"
k = 4
Output
"7654321"

Example 2

Input
num = "1234"
k = 1
Output
"4231"

Example 3

Input
num = "1234"
k = 0
Output
"1234"
Constraints
  • 0 <= k <= 10
  • 1 <= num.length <= 30
  • num contains decimal digits.

Backtracking with Pruning

Fix digits from left to right. If the current digit is already the largest in its suffix, keep it without spending a swap. Otherwise, place that largest digit here. When it appears more than once, try every occurrence: the displaced digit can change the best suffix.

Track the best complete string. Stop as soon as it equals all digits sorted in descending order, the global upper bound. Memoize each arrangement and prefix position with the largest remaining swap budget already explored; a revisit with no more swaps cannot improve the result.

javascript
function findMaximumNum(num, k) {
  const digits = [...num];
  const target = [...num].sort().reverse().join('');
  const seen = new Map();
  let best = num;

  function search(index, remaining) {
    const current = digits.join('');
    if (current > best) best = current;
    if (best === target || remaining === 0 || index === digits.length) return;

    const key = index + ':' + current;
    if ((seen.get(key) ?? -1) >= remaining) return;
    seen.set(key, remaining);

    let largest = digits[index];
    for (let i = index + 1; i < digits.length; i++) {
      if (digits[i] > largest) largest = digits[i];
    }
    if (largest === digits[index]) {
      search(index + 1, remaining);
      return;
    }

    for (let i = digits.length - 1; i > index; i--) {
      if (digits[i] !== largest) continue;
      [digits[index], digits[i]] = [digits[i], digits[index]];
      search(index + 1, remaining - 1);
      [digits[index], digits[i]] = [digits[i], digits[index]];
      if (best === target) return;
    }
  }

  search(0, k);
  return best;
}

Time: Exponential in the worst case. If C recursive calls are made, scanning, string construction, and map-key work cost O(nC), plus O(n log n) to form the target. Memoization and the upper bound prune repeated or already optimal searches; they do not make the problem polynomial.

Space: O(nS + n), where S is the number of memoized states. Each stored key contains the full arrangement, and recursion depth is at most n.

Loading discussion…

Saved in this browser only. Private to you.

JavaScript