Skip to content

1419. Minimum Number of Frogs Croaking

Description

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 <= 105
  • croakOfFrogs is either 'c', 'r', 'o', 'a', or 'k'.

 

Solutions

Solution: Counting

  • Time complexity: O(n)
  • Space complexity: O(5)

 

JavaScript

js
/**
 * @param {string} croakOfFrogs
 * @return {number}
 */
const minNumberOfFrogs = function (croakOfFrogs) {
  const croakMap = new Map();
  const indexMap = { c: 0, r: 1, o: 2, a: 3, k: 4 };
  const croak = ['c', 'r', 'o', 'a', 'k'];
  let result = (frog = 0);

  for (const char of croakOfFrogs) {
    const count = croakMap.get(char) ?? 0;

    char === 'k' ? (frog -= 1) : croakMap.set(char, count + 1);
    if (char === 'c') {
      frog += 1;
      result = Math.max(frog, result);
      continue;
    }
    const index = indexMap[char];
    const preChar = croak[index - 1];
    const preCharCount = croakMap.get(preChar) ?? 0;

    if (preCharCount < 1) return -1;
    croakMap.set(preChar, preCharCount - 1);
  }
  return frog ? -1 : result;
};

Released under the MIT license