Using greedy without proof
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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 <= 109Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Greedy · Segment Tree
"4321" 4
"100" 1
"36789" 1000
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1505: Minimum Possible Integer After at Most K Adjacent Swaps On Digits
class Solution {
public String minInteger(String num, int k) {
Queue<Integer>[] pos = new Queue[10];
for (int i = 0; i < 10; ++i) {
pos[i] = new ArrayDeque<>();
}
int n = num.length();
for (int i = 0; i < n; ++i) {
pos[num.charAt(i) - '0'].offer(i + 1);
}
StringBuilder ans = new StringBuilder();
BinaryIndexedTree tree = new BinaryIndexedTree(n);
for (int i = 1; i <= n; ++i) {
for (int v = 0; v < 10; ++v) {
if (!pos[v].isEmpty()) {
Queue<Integer> q = pos[v];
int j = q.peek();
int dist = tree.query(n) - tree.query(j) + j - i;
if (dist <= k) {
k -= dist;
q.poll();
ans.append(v);
tree.update(j, 1);
break;
}
}
}
}
return ans.toString();
}
}
class BinaryIndexedTree {
private int n;
private int[] c;
public BinaryIndexedTree(int n) {
this.n = n;
c = new int[n + 1];
}
public void update(int x, int delta) {
while (x <= n) {
c[x] += delta;
x += lowbit(x);
}
}
public int query(int x) {
int s = 0;
while (x > 0) {
s += c[x];
x -= lowbit(x);
}
return s;
}
public static int lowbit(int x) {
return x & -x;
}
}
// Accepted solution for LeetCode #1505: Minimum Possible Integer After at Most K Adjacent Swaps On Digits
type BinaryIndexedTree struct {
n int
c []int
}
func newBinaryIndexedTree(n int) *BinaryIndexedTree {
c := make([]int, n+1)
return &BinaryIndexedTree{n, c}
}
func (this *BinaryIndexedTree) lowbit(x int) int {
return x & -x
}
func (this *BinaryIndexedTree) update(x, delta int) {
for x <= this.n {
this.c[x] += delta
x += this.lowbit(x)
}
}
func (this *BinaryIndexedTree) query(x int) int {
s := 0
for x > 0 {
s += this.c[x]
x -= this.lowbit(x)
}
return s
}
func minInteger(num string, k int) string {
pos := make([][]int, 10)
for i, c := range num {
pos[c-'0'] = append(pos[c-'0'], i+1)
}
n := len(num)
tree := newBinaryIndexedTree(n)
var ans strings.Builder
for i := 1; i <= n; i++ {
for v := 0; v < 10; v++ {
if len(pos[v]) > 0 {
j := pos[v][0]
dist := tree.query(n) - tree.query(j) + j - i
if dist <= k {
k -= dist
pos[v] = pos[v][1:]
ans.WriteByte(byte(v + '0'))
tree.update(j, 1)
break
}
}
}
}
return ans.String()
}
# Accepted solution for LeetCode #1505: Minimum Possible Integer After at Most K Adjacent Swaps On Digits
class BinaryIndexedTree:
def __init__(self, n):
self.n = n
self.c = [0] * (n + 1)
@staticmethod
def lowbit(x):
return x & -x
def update(self, x, delta):
while x <= self.n:
self.c[x] += delta
x += BinaryIndexedTree.lowbit(x)
def query(self, x):
s = 0
while x:
s += self.c[x]
x -= BinaryIndexedTree.lowbit(x)
return s
class Solution:
def minInteger(self, num: str, k: int) -> str:
pos = defaultdict(deque)
for i, v in enumerate(num, 1):
pos[int(v)].append(i)
ans = []
n = len(num)
tree = BinaryIndexedTree(n)
for i in range(1, n + 1):
for v in range(10):
q = pos[v]
if q:
j = q[0]
dist = tree.query(n) - tree.query(j) + j - i
if dist <= k:
k -= dist
q.popleft()
ans.append(str(v))
tree.update(j, 1)
break
return ''.join(ans)
// Accepted solution for LeetCode #1505: Minimum Possible Integer After at Most K Adjacent Swaps On Digits
/**
* [1505] Minimum Possible Integer After at Most K Adjacent Swaps On Digits
*
* 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:
* <img alt="" src="https://assets.leetcode.com/uploads/2020/06/17/q4_1.jpg" style="width: 500px; height: 40px;" />
* 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 * 10^4
* num consists of only digits and does not contain leading zeros.
* 1 <= k <= 10^9
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/
// discuss: https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
// Credit: https://leetcode.com/problems/minimum-possible-integer-after-at-most-k-adjacent-swaps-on-digits/solutions/3162681/just-a-runnable-solution/
pub fn min_integer(num: String, k: i32) -> String {
let mut k = k as usize;
let num = num.into_bytes();
let n = num.len();
let mut result = Vec::with_capacity(n);
let mut q = vec![n; 10];
for (i, &item) in num.iter().enumerate() {
let d = (item - b'0') as usize;
if q[d] == n {
q[d] = i;
}
}
let mut used = vec![false; n];
let mut q_used = vec![0; 10];
for _ in 0..n {
for d in 0..10_usize {
if q[d] == n {
continue;
}
let c = q[d] - q_used[d];
if c <= k {
k -= c;
result.push(b'0' + d as u8);
used[q[d]] = true;
for d1 in 0..10_usize {
if q[d1] > q[d] {
q_used[d1] += 1;
}
}
while q[d] < n {
if used[q[d]] {
q_used[d] += 1;
}
q[d] += 1;
let &c = num.get(q[d]).unwrap_or(&0_u8);
if c == b'0' + d as u8 {
break;
}
}
break;
}
}
}
String::from_utf8(result).unwrap()
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_1505_example_1() {
let num = "4321".to_string();
let k = 4;
let result = "1342".to_string();
assert_eq!(Solution::min_integer(num, k), result);
}
#[test]
fn test_1505_example_2() {
let num = "36789".to_string();
let k = 1000;
let result = "36789".to_string();
assert_eq!(Solution::min_integer(num, k), result);
}
#[test]
fn test_1505_example_3() {
let num = "100".to_string();
let k = 1;
let result = "010".to_string();
assert_eq!(Solution::min_integer(num, k), result);
}
}
// Accepted solution for LeetCode #1505: Minimum Possible Integer After at Most K Adjacent Swaps On Digits
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1505: Minimum Possible Integer After at Most K Adjacent Swaps On Digits
// class Solution {
// public String minInteger(String num, int k) {
// Queue<Integer>[] pos = new Queue[10];
// for (int i = 0; i < 10; ++i) {
// pos[i] = new ArrayDeque<>();
// }
// int n = num.length();
// for (int i = 0; i < n; ++i) {
// pos[num.charAt(i) - '0'].offer(i + 1);
// }
// StringBuilder ans = new StringBuilder();
// BinaryIndexedTree tree = new BinaryIndexedTree(n);
// for (int i = 1; i <= n; ++i) {
// for (int v = 0; v < 10; ++v) {
// if (!pos[v].isEmpty()) {
// Queue<Integer> q = pos[v];
// int j = q.peek();
// int dist = tree.query(n) - tree.query(j) + j - i;
// if (dist <= k) {
// k -= dist;
// q.poll();
// ans.append(v);
// tree.update(j, 1);
// break;
// }
// }
// }
// }
// return ans.toString();
// }
// }
//
// class BinaryIndexedTree {
// private int n;
// private int[] c;
//
// public BinaryIndexedTree(int n) {
// this.n = n;
// c = new int[n + 1];
// }
//
// public void update(int x, int delta) {
// while (x <= n) {
// c[x] += delta;
// x += lowbit(x);
// }
// }
//
// public int query(int x) {
// int s = 0;
// while (x > 0) {
// s += c[x];
// x -= lowbit(x);
// }
// return s;
// }
//
// public static int lowbit(int x) {
// return x & -x;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Try every possible combination of choices. With n items each having two states (include/exclude), the search space is 2ⁿ. Evaluating each combination takes O(n), giving O(n × 2ⁿ). The recursion stack or subset storage uses O(n) space.
Greedy algorithms typically sort the input (O(n log n)) then make a single pass (O(n)). The sort dominates. If the input is already sorted or the greedy choice can be computed without sorting, time drops to O(n). Proving greedy correctness (exchange argument) is harder than the implementation.
Review these before coding to avoid predictable interview regressions.
Wrong move: Locally optimal choices may fail globally.
Usually fails on: Counterexamples appear on crafted input orderings.
Fix: Verify with exchange argument or monotonic objective before committing.