Taro Logo

Minimum Possible Integer After at Most K Adjacent Swaps On Digits

Hard
Asked by:
HashedIn
0 views
Topics:
ArraysStringsGreedy Algorithms

You are given a string num representing the digits of a very large integer and an integer k. You are allowed to swap any two adjacent digits of the integer at most k times.

Return the minimum integer you can obtain also as a string.

Example 1:

Input: num = "4321", k = 4
Output: "1342"
Explanation: The steps to obtain the minimum integer from 4321 with 4 adjacent swaps are shown.

Example 2:

Input: num = "100", k = 1
Output: "010"
Explanation: It's ok for the output to have leading zeros, but the input is guaranteed not to have any leading zeros.

Example 3:

Input: num = "36789", k = 1000
Output: "36789"
Explanation: We can keep the number without any swaps.

Constraints:

  • 1 <= num.length <= 3 * 104
  • num consists of only digits and does not contain leading zeros.
  • 1 <= k <= 109

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum length of the string representing the numeric integer, and can $K$ be larger than the number of possible swaps needed to fully sort the string?
  2. Does the input string represent a standard positive integer without leading zeros, or could it contain leading zeros that need to be preserved?
  3. How should we handle identical digits in the string (e.g., if there are multiple '0's or '5's), and do we prioritize the leftmost occurrence when making swaps?
  4. Can $K$ be extremely large (e.g., $10^{15}$), meaning we need to optimize our approach beyond a naive $O(N dot K)$ simulation?
  5. Is the input guaranteed to contain only numeric characters, or do we need to validate against empty strings or non-digit characters?

Brute Force Solution

Approach

Imagine you have a string of digits and you want to make the smallest possible number by swapping neighboring digits, but you are only allowed to do this a limited number of times. The brute force approach involves trying every single possible sequence of swaps to see all the different numbers you can possibly create.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first position of your number.
  2. Look at all the nearby digits that you can reach by making a set number of swaps or fewer, and pretend to move each of them to the front one by one.
  3. For each of those choices, spend some of your allowed swaps to bring that chosen digit to the front, which leaves you with a smaller number of allowed swaps and a slightly shorter remaining sequence.
  4. Repeat this exact same trial process for the next position, trying every possible digit you can reach with your remaining swaps.
  5. Keep going until you run out of allowed swaps or you have successfully examined the entire number.
  6. Because you are trying every conceivable path, you will generate a huge collection of different final numbers.
  7. Finally, compare every single number you generated and pick the absolute smallest one to be your winner.

Code Implementation

def min_integer(num_string, max_swaps):
    # We convert the string to a list of digits to simulate the swapping process and explore paths
    digit_list = [int(digit) for digit in num_string]
    best_result = num_string

    def explore_swaps(current_digits, remaining_swaps, current_index):
        nonlocal best_result
        if remaining_swaps == 0 or current_index == len(current_digits):
            candidate_string = ''.join(map(str, current_digits))
            if candidate_string < best_result:
                best_result = candidate_string
            return

        limit = min(current_index + remaining_swaps + 1, len(current_digits))
        # We iterate through reachable positions to try bringing each valid candidate digit to the front
        for target_index in range(current_index, limit):
            swaps_needed = target_index - current_index
            temp_digits = list(current_digits)
            digit_to_move = temp_digits.pop(target_index)
            temp_digits.insert(current_index, digit_to_move)
            explore_swaps(temp_digits, remaining_swaps - swaps_needed, current_index + 1)

    explore_swaps(digit_list, max_swaps, 0)

    # Finally we return the absolute smallest number discovered across all valid swap sequences
    return best_result

Big(O) Analysis

Time Complexity
O(n * K) – For each of the n positions in the string, the algorithm scans up to K reachable adjacent digits to find the smallest candidate to move to the front. Bringing that chosen digit to the front via adjacent swaps requires up to K operations and reduces our remaining budget. This process repeats across the string, meaning we perform roughly n steps where each step evaluates up to K choices. The total operations therefore approximate n * K, which simplifies to Big O of n times K.
Space Complexity
O(N^2) – The brute force approach generates and stores a massive collection of different final number permutations derived from trying every conceivable path of adjacent swaps. Storing all these intermediate and final string representations requires auxiliary storage that grows quadratically with the input length N due to the exponentially expanding search tree of paths. Additionally, the recursive trial process consumes call stack frames up to a maximum depth of N as it processes each position of the number one by one. Consequently, the total auxiliary memory required to hold the generated numbers and manage the recursion scales proportionally to N squared.

Optimal Solution

Approach

To construct the lexicographically smallest number, we greedily select the smallest available digit that can be shifted to the current front position within the remaining swap budget. A Binary Indexed Tree tracks how many elements have already been removed to accurately compute the effective shift distance for any element. We repeat this selection until all positions in the result string are filled.

Here's how the algorithm would work step-by-step:

  1. Store the initial indices of each digit from zero to nine in separate queues.
  2. Initialize a Binary Indexed Tree to track active and removed positions across the string.
  3. Iterate through each position of the output number to pick the next digit greedily.
  4. For digits from zero to nine, check if the first available occurrence can reach the current front within the remaining swap budget.
  5. Select the first valid digit found, deduct the required swaps from the budget, and mark its original index as used in the tree.
  6. Append the chosen digit to the result list and repeat until all characters are placed.
  7. Join and return the collected characters as the final smallest integer string.

Code Implementation

from collections import deque

def min_integer(num: str, k: int) -> str:
    total_length = len(num)
    digit_indices = [deque() for _ in range(10)]
    for original_index, char_digit in enumerate(num):
        digit_indices[int(char_digit)].append(original_index)
    
    bit_tree = [0] * (total_length + 1)
    
    def update(index: int, value: int) -> None:
        while index <= total_length:
            bit_tree[index] += value
            index += index & (-index)
            
    def query(index: int) -> int:
        total_sum = 0
        while index > 0:
            total_sum += bit_tree[index]
            index -= index & (-index)
        return total_sum
    
    # Initialize the binary indexed tree with 1 at each position
    for index in range(1, total_length + 1):
        update(index, 1)
        
    result_digits = []
    remaining_swaps = k
    
    # Process digits greedily from most significant to least significant
    for _ in range(total_length):
        for target_digit in range(10):
            if digit_indices[target_digit]:
                current_original_pos = digit_indices[target_digit][0]
                shift_cost = query(current_original_pos)
                if shift_cost <= remaining_swaps:
                    # Append the chosen digit and update remaining swaps
                    result_digits.append(str(target_digit))
                    remaining_swaps -= shift_cost
                    update(current_original_pos + 1, -1)
                    digit_indices[target_digit].popleft()
                    break
                    
    return "".join(result_digits)

Big(O) Analysis

Time Complexity
O(N * D * log N) – For each of the N positions, we check up to 10 possible digits (D = 10) and perform a Binary Indexed Tree query which takes O(log N) time.
Space Complexity
O(N) – The queues storing digit indices and the Binary Indexed Tree array each require memory proportional to the length of the string, which is O(N).

Edge Cases

String with a single digit or empty string
How to Handle:
Return the input string directly as no swaps can or need to be performed.
K is large enough to allow fully sorting the string
How to Handle:
Greedy selection will naturally sort the string into the absolute lexicographically smallest arrangement.
K is zero, meaning no swaps are allowed
How to Handle:
The algorithm returns the original string unmodified since the budget is exhausted.
Multiple identical digits competing for the optimal position
How to Handle:
Greedy selection always targets the leftmost occurrence of the smallest available digit to minimize swap distance.
Maximum length strings with up to thirty thousand digits
How to Handle:
Use a Fenwick tree or Segment tree to manage index shifts efficiently in O(N log N) time complexity instead of O(N squared).
Insufficient K to move the absolute smallest digit to the front
How to Handle:
Consume the entire K budget on the best possible prefix rearrangement and leave remaining digits relative order intact.
Leading zeros created by moving a zero to the front
How to Handle:
The problem statement specifies the input represents a valid numeric integer, so zero cannot be moved past the first non-zero digit unless the string is just zero.
Inputs containing only duplicate digits like nine nine nine nine
How to Handle:
Since all digits are identical, the swap cost is zero and the original string is returned instantly.