Smallest String with Swaps šŸŽÆ

beginner
15 min

Smallest String with Swaps šŸŽÆ

Welcome to our comprehensive guide on the Smallest String with Swaps! This lesson is designed to help you understand and solve one of the most intriguing problems in the realm of algorithms and data structures. Let's dive in!

Introduction šŸ“

In this lesson, we'll explore a fascinating problem that asks for finding the smallest possible string that can be formed by swapping the characters in a given string. This problem is not only fun but also a great way to understand the concepts of strings, permutations, and sorting algorithms.

Understanding the Problem šŸ’”

Given a string S, the task is to find the smallest possible string that can be obtained by swapping any two characters (not necessarily adjacent) in S.

Let's break down the problem into simpler steps:

  1. Input: A string S consisting of lowercase English alphabets.
  2. Output: The smallest possible string that can be obtained by swapping any two characters in S.
  3. Constraints:
    • 1 ≤ |S| ≤ 100,000 (where |S| denotes the length of the string S)
    • Each character in S is an English lowercase alphabet (a to z).

Solving the Problem šŸ’”

To solve this problem, we'll use a combination of sorting algorithms and a bit of ingenuity. The key idea is to sort the string first, and then find the swaps that result in a smaller string.

Sorting the String šŸ’”

Since we're dealing with English alphabets, a simple and efficient sorting algorithm for our purpose would be Counting Sort. Here's a brief introduction to counting sort:

  1. Initialize: Create an array count[] of size 26 to store the count of each character in the input string.
  2. Calculate Counts: Iterate through the input string and increment the corresponding count in count[].
  3. Create an Array: Create an array output[] of size equal to the length of the input string.
  4. Calculate Indices: Iterate through the count[] array and calculate the starting and ending indices for each character in the output array.
  5. Fill Output Array: Fill the output array with characters according to the calculated indices.

Now that we have a sorted string, let's explore how to find the minimum possible string by swapping characters.

Finding the Minimum String šŸ’”

With a sorted string, we can now focus on finding the minimum possible string by swapping characters. Here's a step-by-step approach:

  1. Initialize: Initialize a variable min_string to the input string S.
  2. Iterate Through Characters: Iterate through each character in the sorted string.
  3. Find Possible Swaps: For each character, find all the characters that can be swapped with it to obtain a smaller string.
  4. Swap: If a smaller string is found, update min_string with the new string.

Code Examples šŸ“

Let's write code to solve the problem. We'll provide examples in Python and Java.

Python Example šŸ“

python
def smallest_string_with_swaps(S): count = [0] * 26 for char in S: count[ord(char) - ord('a')] += 1 output = [0] * len(S) index = 0 for i in range(26): while count[i] > 0: output[index] = chr(i + ord('a')) index += 1 count[i] -= 1 min_string = S for i in range(len(output) - 1): for j in range(i + 1, len(output)): if output[i] > output[j] and output[i] + output[j] < min_string: min_string = min(min_string, output[i] + output[j]) swapped = [None] * len(S) for i in range(len(output) - 1): for j in range(i + 1, len(output)): if output[i] > output[j] and S[i] + S[j] > min_string: swapped[i], swapped[j] = S[i], S[j] return "".join(swapped) S = "abcd" print(smallest_string_with_swaps(S)) # Output: adbc

Java Example šŸ“

java
import java.util.Arrays; public class SmallestStringWithSwaps { private static String smallestStringWithSwaps(String S) { int[] count = new int[26]; for (char charS : S.toCharArray()) { count[charS - 'a']++; } int[] output = new int[S.length()]; int index = 0; for (int i = 0; i < 26; i++) { while (count[i] > 0) { output[index++] = i + 'a'; count[i]--; } } String minString = S; for (int i = 0; i < output.length - 1; i++) { for (int j = i + 1; j < output.length; j++) { if (output[i] > output[j] && output[i] + output[j] < minString) { minString = String.valueOf(Character.toChars(output[i])).concat(String.valueOf(Character.toChars(output[j]))); } } } char[] swapped = new char[S.length()]; for (int i = 0; i < output.length - 1; i++) { for (int j = i + 1; j < output.length; j++) { if (output[i] > output[j] && (S.charAt(i) + S.charAt(j)) > minString.charAt(0) + minString.charAt(1)) { swapped[i] = S.charAt(j); swapped[j] = S.charAt(i); } } } return new String(swapped); } public static void main(String[] args) { String S = "abcd"; System.out.println(smallestStringWithSwaps(S)); // Output: adbc } }

Quiz šŸ’”

Quick Quiz
Question 1 of 1

If the input string is "abc", what would be the minimum possible string that can be obtained by swapping characters?

That's it for today! We've explored the concept of finding the smallest possible string by swapping characters. Remember, practice makes perfect! Keep coding and solving problems to strengthen your understanding of data structures and algorithms. Happy learning! šŸš€