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 * 104num consists of only digits and does not contain leading zeros.1 <= k <= 109When 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:
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:
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
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:
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)
| Case | How to Handle |
|---|---|
| String with a single digit or empty string | Return the input string directly as no swaps can or need to be performed. |
| K is large enough to allow fully sorting the string | Greedy selection will naturally sort the string into the absolute lexicographically smallest arrangement. |
| K is zero, meaning no swaps are allowed | The algorithm returns the original string unmodified since the budget is exhausted. |
| Multiple identical digits competing for the optimal position | 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 | 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 | 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 | 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 | Since all digits are identical, the swap cost is zero and the original string is returned instantly. |