Skip to content

Instantly share code, notes, and snippets.

@masmerino13
Created May 1, 2025 01:34
Show Gist options
  • Save masmerino13/b2b0d4194153c31ec02750928b2cd464 to your computer and use it in GitHub Desktop.
Save masmerino13/b2b0d4194153c31ec02750928b2cd464 to your computer and use it in GitHub Desktop.
get the smallest binary string
package main
import (
"fmt"
)
func smallestBinaryStringWithSwaps(s string, maxSwaps int) string {
runes := []rune(s)
n := len(runes)
for i := 0; i < n-1 && maxSwaps > 0; {
if runes[i] > runes[i+1] {
runes[i], runes[i+1] = runes[i+1], runes[i]
maxSwaps--
if i > 0 {
i--
}
} else {
i++
}
}
return string(runes)
}
func main() {
s := "1101101"
maxSwaps := 5
result := smallestBinaryStringWithSwaps(s, maxSwaps)
fmt.Println("smallest bynary string:", result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment