Minimum Number of Frogs Croaking - Problem

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.

Input & Output

Example 1 — Basic Overlapping
$ Input: croakOfFrogs = "croakcroak"
Output: 1
💡 Note: One frog can say the entire sequence: first "croak" then second "croak". Only 1 frog needed.
Example 2 — Simultaneous Frogs
$ Input: croakOfFrogs = "crcoakroak"
Output: 2
💡 Note: Need 2 frogs: Frog1 says "c-r-o-a-k" and Frog2 says "c-r-o-a-k" with interleaved timing.
Example 3 — Invalid Sequence
$ Input: croakOfFrogs = "croakcrook"
Output: -1
💡 Note: Contains invalid character 'o' after 'o' - not following proper croak sequence.

Constraints

  • 1 ≤ croakOfFrogs.length ≤ 105
  • croakOfFrogs[i] is either 'c', 'r', 'o', 'a', or 'k'

Visualization

Tap to expand
Minimum Number of Frogs Croaking INPUT croakOfFrogs = "croakcroak" First sequence: c r o a k Second sequence: c r o a k Sequential croaks (no overlap) Length: 10 chars ALGORITHM STEPS 1 Track counters c, r, o, a, k counts 2 Process each char Increment current counter 3 Validate order c >= r >= o >= a >= k 4 Track max frogs max(c - k) at any time Counter State After Processing: c r o a k frogs 1 1 1 1 1 0 2 2 2 2 2 0 Max concurrent frogs: 1 Time: O(n) | Space: O(1) FINAL RESULT Minimum frogs needed: 1 croak! One frog can croak twice sequentially! Validation: OK All counters equal: 2 Valid croak sequence Key Insight: Track how many frogs are actively croaking at any moment. A frog starts at 'c' and finishes at 'k'. The max value of (count_c - count_k) during processing equals minimum frogs needed. When a frog finishes 'k', it becomes available to start a new 'c'. In "croakcroak", no overlap means 1 frog suffices. TutorialsPoint - Minimum Number of Frogs Croaking | Optimal Solution
Asked in
Google 12 Facebook 8 Amazon 6
28.0K Views
Medium Frequency
~25 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen