LeetCode 3216: Lexicographically Smallest String After a Swap Solution

Master LeetCode problem 3216 (Lexicographically Smallest String After a Swap), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

3216. Lexicographically Smallest String After a Swap

Problem Explanation

Explanation

To solve this problem, we can follow these steps:

  1. Iterate through the string and identify pairs of adjacent digits with the same parity.
  2. For each identified pair, swap the digits to get the lexicographically smallest string.
  3. If there are multiple pairs with the same parity, prioritize swapping the leftmost pair.

Time Complexity: O(n) where n is the length of the input string s.
Space Complexity: O(n) for storing the intermediate results.

Solution Code

class Solution {
    public String findLexSmallestString(String s) {
        char[] arr = s.toCharArray();
        int n = arr.length;
        
        for (int i = 0; i < n - 1; i++) {
            if (arr[i] > arr[i + 1]) {
                for (int j = i + 1; j < n; j++) {
                    if (arr[j] >= arr[i] && (arr[j] - '0') % 2 == (arr[i] - '0') % 2) {
                        char temp = arr[i];
                        arr[i] = arr[j];
                        arr[j] = temp;
                        break;
                    }
                }
                break;
            }
        }
        
        return new String(arr);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 3216 (Lexicographically Smallest String After a Swap)?

This page provides optimized solutions for LeetCode problem 3216 (Lexicographically Smallest String After a Swap) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 3216 (Lexicographically Smallest String After a Swap)?

The time complexity for LeetCode 3216 (Lexicographically Smallest String After a Swap) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 3216 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 3216 in Java, C++, or Python.

Back to LeetCode Solutions