FastPrepApply Operations to Make a String Empty

Apply Operations to Make a String Empty

Flexport logoFlexport● MediumFULLTIMEPHONE SCREEN

Problem statement

You are given a string s of lowercase letters. One operation works like this: for every letter from 'a' to 'z', if that letter still appears in s, remove its first copy.

Keep applying operations until s is empty. Return the string as it was right before the last operation, that is, the last non-empty string.

Function

lastNonEmptyString(s: String) → String

Examples

Example 1

s = "bccab"return = "cb"

The first operation removes the first a, the first b and the first c, which leaves "cb". The next operation removes both remaining letters and leaves an empty string, so the answer is "cb".

Example 2

s = "zyx"return = "zyx"

Every letter appears once, so the first operation already empties the string. The string right before it is the whole input, "zyx".

Example 3

s = "aabbbcb"return = "b"

The letter b appears four times, more than any other letter. The operations leave "abbb", then "bb", then "b", then the empty string, so the answer is "b".

Constraints

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

More Flexport problems

See Flexport hiring insights
Saved
public String lastNonEmptyString(String s) {
    // Write your code here.
}
Checking account…