#1419
Medium Algorithms Minimum number of frogs croaking
String Counting
51.1% acceptance
Feb 25, 2026
1123
95
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn min_number_of_frogs(croak_of_frogs: String) -> i32 {
let mut stages = [0i32; 4]; // stages[i]: frogs waiting for next char
let mut max_frogs = 0;
for c in croak_of_frogs.chars() {
let pos = match c { 'c'=>0, 'r'=>1, 'o'=>2, 'a'=>3, 'k'=>4, _ => return -1 };
if pos == 0 {
stages[0] += 1;
} else if pos < 4 {
if stages[pos-1] == 0 { return -1; }
stages[pos-1] -= 1;
stages[pos] += 1;
} else {
if stages[3] == 0 { return -1; }
stages[3] -= 1;
}
let active: i32 = stages.iter().sum();
max_frogs = max_frogs.max(active);
}
if stages.iter().any(|&x| x != 0) { return -1; }
max_frogs
}
}