1166. Overtaking Line

Medium3.5 points estimatedSimulationGreedyStringBrainteaser

Walkers queue on a narrow boardwalk, described by the string line whose index 0 is the front. A character S is a slow walker and F a fast one. Every second, all at once, each fast walker standing directly behind a slow walker swaps places with it. After enough seconds nobody can overtake any more.

Return the number of seconds until the first second in which no swap happens, that is, the time of the last swap (0 if nothing ever swaps). The swaps in one second are simultaneous, and the pairs involved never overlap, so the order is well defined. Here 1 <= line.length <= 2 * 10^5 and line contains only S and F.

Simulating second by second is too slow. Process the fast walkers left to right in one pass, in O(n) time and O(1) space.

Example 1

Input:
line = "SF"
Output:
1
Explanation:

The fast walker steps past the slow one in one second.

Example 2

Input:
line = "SSFF"
Output:
3
Explanation:

SSFF becomes SFSF after one second, FSFS after two and FFSS after three, and then nothing can swap.

Example 3

Input:
line = "FFSS"
Output:
0
Explanation:

Every fast walker is already ahead of every slow one, so no swap ever happens.

Constraints

1 ≤ line.length ≤ 2 * 105

line contains only 'S' and 'F'

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…