LeetCode 2734: Lexicographically Smallest String After Substring Operation Solution

Master LeetCode problem 2734 (Lexicographically Smallest String After Substring Operation), a medium 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.

2734. Lexicographically Smallest String After Substring Operation

Problem Explanation

Explanation:

To solve this problem, we can iterate over the input string s from left to right. For each character, we can compute the distance to the character 'a' and the character 'z'. We then take the minimum of these distances and modify the character accordingly to get the lexicographically smallest string after the substring operation.

Algorithm:

  1. Initialize an empty string result to store the final modified string.
  2. Iterate over each character in the input string s.
  3. For each character, compute the distance to 'a' and 'z'.
  4. Modify the character based on the minimum distance.
  5. Append the modified character to the result string.
  6. Return the final result string.

Time Complexity:

The time complexity of this algorithm is O(n), where n is the length of the input string s.

Space Complexity:

The space complexity of this algorithm is O(n) to store the final modified string.


:

Solution Code

class Solution {
    public String findLexSmallestString(String s) {
        StringBuilder result = new StringBuilder();
        
        for (char c : s.toCharArray()) {
            int distToA = c - 'a';
            int distToZ = 'z' - c + 1;
            char modified = distToA <= distToZ ? (char)('a' + distToA) : (char)('a' + distToZ);
            result.append(modified);
        }
        
        return result.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2734 (Lexicographically Smallest String After Substring Operation)?

This page provides optimized solutions for LeetCode problem 2734 (Lexicographically Smallest String After Substring Operation) 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 2734 (Lexicographically Smallest String After Substring Operation)?

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

Can I run code for LeetCode 2734 on DevExCode?

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

Back to LeetCode Solutions