Skip to main content

Minimum Operations to Sort a String - Solution & Explanation

MediumString10 min readAsked at: Amazon
Practice this problem

Problem Statement

You are given a string s consisting of lowercase English letters.

In one operation, you can select any substring of s that is not the entire string and sort it in non-descending alphabetical order.

Return the minimum number of operations required to make s sorted in non-descending order. If it is not possible, return -1.

 

Example 1:

Input: s = "dog"

Output: 1

Explanation:​​​​​​​

  • Sort substring "og" to "go".
  • Now, s = "dgo", which is sorted in ascending order. Thus, the answer is 1.

Example 2:

Input: s = "card"

Output: 2

Explanation:

  • Sort substring "car" to "acr", so s = "acrd".
  • Sort substring "rd" to "dr", making s = "acdr", which is sorted in ascending order. Thus, the answer is 2.

Example 3:

Input: s = "gf"

Output: -1

Explanation:

  • It is impossible to sort s under the given constraints. Thus, the answer is -1.

 

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Approach Overview

Problem Overview: You are given a string and need to determine the minimum number of operations required to transform it into its lexicographically sorted version. The challenge is identifying where characters violate sorted order and determining the smallest set of operations needed to fix those positions efficiently.

Approach 1: Brute Force Simulation (O(n^2) time, O(n) space)

The most direct idea is to simulate how the string becomes sorted. First generate the sorted target string. Then repeatedly scan the current string and move or adjust characters that are out of place until it matches the target. Each operation fixes one misplaced region, but finding the correct character and shifting elements may require scanning the string repeatedly. Because each correction can take O(n) time and you may perform up to O(n) corrections, the total time complexity grows to O(n^2) with O(n) space for temporary strings. This approach helps build intuition but becomes slow for large inputs.

Approach 2: Case Analysis with Target Comparison (O(n log n) time, O(n) space)

A more efficient strategy compares the original string with its sorted version and analyzes where characters diverge. Start by creating a sorted copy of the string using a standard sorting routine. Then iterate through both strings simultaneously. Whenever the current character already matches the sorted position, no operation is needed. When it doesn't, you analyze the mismatch segment and determine how many operations are required to realign those characters with the sorted order.

The key insight: sorting defines the exact final arrangement. Instead of performing actual modifications, you only count structural mismatches between the original and sorted strings. This turns the problem into a counting and case analysis task. A single pass through the string identifies contiguous mismatched regions and increments the operation counter accordingly.

This approach uses basic string traversal combined with reasoning about sorted order. Sorting the string costs O(n log n), while the comparison scan runs in O(n). Space complexity is O(n) because the sorted copy must be stored.

Recommended for interviews: The case analysis approach is what interviewers typically expect. Brute force simulation demonstrates understanding of the transformation process, but comparing the string against its sorted version shows stronger algorithmic reasoning. It also highlights your ability to reduce a modification problem into a simpler counting problem using properties of strings and ordering logic often seen in greedy-style reasoning.

Solution

We first check whether the string is already sorted in ascending order; if so, return 0.

Otherwise, if the string has length 2, since we cannot choose the entire string to sort, it is impossible to sort the string, so we return -1.

Next, we find the minimum character mn and the maximum character mx in the string. If the first character of the string equals mn, or the last character equals mx, then one operation on the remaining substring is sufficient to sort the entire string, so we return 1.

Otherwise, if some character in the middle of the string equals mn or mx, we need one operation to move that character to the beginning or the end of the string, and then one more operation to sort the rest, so we return 2.

Finally, if none of the above cases apply, we need one operation on the substring containing both mn and mx, followed by one more operation on the remaining substring, so we return 3.

The time complexity is O(n), where n is the length of the string s. The space complexity is O(1).

Code

Python

Java

C++

Go

TypeScript

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force SimulationO(n^2)O(n)Useful for understanding the transformation process or when constraints are very small
Case Analysis with Sorted TargetO(n log n)O(n)General case solution; efficient and straightforward for interview settings

Video Solution

3863. Minimum Operations to Sort a String (Leetcode Medium) • Programming Live with Larry • 680 views views

Watch 7 more video solutions →

Frequently Asked Questions

Is Minimum Operations to Sort a String easy or hard?
Minimum Operations to Sort a String is generally considered a medium difficulty problem. The core logic is simple once you compare the string with its sorted version, but identifying the correct counting logic for operations requires careful reasoning.
Minimum Operations to Sort a String Python/Java solution
Python, Java, C++, Go, and TypeScript implementations typically follow the same structure: create a sorted version of the string, iterate through both strings, and count the positions or segments that require operations. Built-in sorting functions simplify implementation.
How to solve Minimum Operations to Sort a String in O(n)?
Pure O(n) solutions are only possible if the character range is limited and counting sort can replace comparison sorting. In that case you compute the sorted order using frequency counts, then scan the string once to detect mismatches and count required operations.
What is the best approach for Minimum Operations to Sort a String?
The most practical approach compares the original string with its sorted version and performs case analysis on mismatched positions. Sorting takes O(n log n) time and a single linear scan counts the operations needed to align characters with the sorted order. This method avoids expensive simulations and is easy to implement.
Is Minimum Operations to Sort a String asked at Google/Amazon/Meta?
String transformation and minimum operation problems are common interview patterns at companies like Google, Amazon, and Meta. Variants that involve sorting constraints, mismatch counting, or greedy corrections frequently appear in technical interviews.
What data structure is used in Minimum Operations to Sort a String?
The solution primarily uses strings or character arrays along with a sorted copy of the string. Some implementations also use frequency arrays or counters when optimizing sorting for limited character sets.
What is the time complexity of Minimum Operations to Sort a String?
The optimal solution typically runs in O(n log n) time due to sorting the string. After sorting, a single pass comparison with the original string determines where operations are needed, which costs O(n). Space complexity is O(n) for storing the sorted copy.

Ready to solve this problem?

Practice Minimum Operations to Sort a String with our built-in code editor and test cases.

Practice on FleetCode