All problems
0864MediumString

Fewest Lifts to Order the Bead String

Tracked in this browser only
Write code

Trains the technique from

LeetCode 3863Minimum Operations to Sort a String

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A string of beads is given as s, each bead marked with a lowercase letter.

One lift takes a single bead off the string and threads it back on at any position, including either end. The other beads keep their order.

The string is ordered when its letters read in non-decreasing order from one end to the other. Return the fewest lifts that leave it ordered.

Examples

Example 1

Input
s = "cba"
Output
2

Leaving the bead marked "a" alone and lifting the other two, threading "b" after it and then "c" after that, orders the string in two lifts.

Example 2

Input
s = "abab"
Output
1

The beads reading "a", "a" and "b" can be left alone as a non-decreasing run, so only the remaining bead has to be lifted.

Example 3

Input
s = "aabbcc"
Output
0

The string already reads in non-decreasing order, so no bead has to move.

Constraints

  • 1 <= s.length <= 10^5
  • s consists of lowercase English letters only

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def fewest_lifts(s: str) -> int:
Java
public int fewestLifts(String s)
September 7
Apply