Skip to content

1419. Minimum Number of Frogs Croaking 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int minNumberOfFrogs(string croakOfFrogs) {
    const string kCroak = "croak";
    int ans = 0;
    int frogs = 0;
    vector<int> count(5);

    for (const char c : croakOfFrogs) {
      ++count[kCroak.find(c)];
      for (int i = 1; i < 5; ++i)
        if (count[i] > count[i - 1])
          return -1;
      if (c == 'c')
        ++frogs;
      else if (c == 'k')
        --frogs;
      ans = max(ans, frogs);
    }

    return frogs == 0 ? ans : -1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int minNumberOfFrogs(String croakOfFrogs) {
    final String CROAK = "croak";
    int ans = 0;
    int frogs = 0;
    int[] count = new int[5];

    for (final char c : croakOfFrogs.toCharArray()) {
      ++count[CROAK.indexOf(c)];
      for (int i = 1; i < 5; ++i)
        if (count[i] > count[i - 1])
          return -1;
      if (c == 'c')
        ++frogs;
      else if (c == 'k')
        --frogs;
      ans = Math.max(ans, frogs);
    }

    return frogs == 0 ? ans : -1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def minNumberOfFrogs(self, croakOfFrogs: str) -> int:
    CROAK = 'croak'
    ans = 0
    frogs = 0
    count = [0] * 5

    for c in croakOfFrogs:
      count[CROAK.index(c)] += 1
      if any(count[i] > count[i - 1] for i in range(1, 5)):
        return -1
      if c == 'c':
        frogs += 1
      elif c == 'k':
        frogs -= 1
      ans = max(ans, frogs)

    return ans if frogs == 0 else -1