Minimum Number of Frogs Croaking Problem
Description
LeetCode Problem 1419.
You are given the string croakOfFrogs, which represents a combination of the string "croak" from different frogs, that is, multiple frogs can croak at the same time, so multiple "croak" are mixed.
Return the minimum number of different frogs to finish all the croaks in the given string.
A valid "croak" means a frog is printing five letters 'c', 'r', 'o', 'a', and 'k' sequentially. The frogs have to print all five letters to finish a croak. If the given string is not a combination of a valid "croak" return -1.
Example 1:
Input: croakOfFrogs = "croakcroak"
Output: 1
Explanation: One frog yelling "croak" twice.
Example 2:
Input: croakOfFrogs = "crcoakroak"
Output: 2
Explanation: The minimum number of frogs is two.
The first frog could yell "crcoakroak".
The second frog could yell later "crcoakroak".
Example 3:
Input: croakOfFrogs = "croakcrook"
Output: -1
Explanation: The given string is an invalid combination of "croak" from different frogs.
Constraints:
1 <= croakOfFrogs.length <= 10^5croakOfFrogsis either'c','r','o','a', or'k'.
Solution
Approach: Track Frogs by Their Last Letter
Think of each frog as moving through the stages c → r → o → a → k. Keep cnt[i], the number of frogs whose last letter was "croak"[i] and that are waiting for the next one, and active, the number of frogs in the middle of a croak.
For each letter of the string:
'c'starts a croak: one more active frog, and it now waits for'r'.- Any other letter must be said by a frog that just said the letter before it. If
cnt[i − 1]is0, no frog can say it, so the string is invalid and we return-1. Otherwise one frog moves from stagei − 1to stagei. - When a frog says
'k', its croak is done and it stops being active. It can start another croak later, which is why one frog is enough for"croakcroak".
The number of frogs we need is the largest value active ever reaches, since those croaks overlap in time and need different frogs. At the end, every croak must be finished: if active is not 0 (e.g. "croakcroa"), return -1.
Complexity: O(n) time and O(1) space.
class Solution:
def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
stage = {c: i for i, c in enumerate("croak")}
cnt = [0] * 5 # cnt[i] = frogs whose last letter was "croak"[i]
active = ans = 0 # frogs in the middle of a croak, and the most at once
for ch in croakOfFrogs:
i = stage[ch]
if i == 0:
active += 1
ans = max(ans, active)
else:
if cnt[i - 1] == 0:
return -1 # no frog is waiting to say this letter
cnt[i - 1] -= 1
if i == 4:
active -= 1 # this frog finished and can start again
continue
cnt[i] += 1
return -1 if active else ans