#1419

Minimum Number of Frogs Croaking

Medium
StringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach uses a single pass through the string while maintaining counts of each character in 'croak'. This allows us to determine how many frogs are croaking simultaneously without needing to check combinations.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a count array for 'c', 'r', 'o', 'a', 'k' and a variable for the maximum number of frogs needed.
  2. 2Step 2: Iterate through each character in the string and update the count based on the character.
  3. 3Step 3: For each character, ensure that the previous character's count is not greater than the current character's count.
  4. 4Step 4: Update the maximum number of frogs needed when encountering 'c'.
  5. 5Step 5: At the end, check if the counts are balanced and return the maximum number of frogs or -1 if invalid.
solution.py17 lines
1def minNumberOfFrogs(croakOfFrogs):
2    croak_count = [0] * 5
3    frogs = 0
4    max_frogs = 0
5    croak = 'croak'
6    for char in croakOfFrogs:
7        if char not in croak:
8            return -1
9        croak_count[croak.index(char)] += 1
10        if char == 'c':
11            frogs += 1
12            max_frogs = max(max_frogs, frogs)
13        if char == 'k':
14            frogs -= 1
15        if any(crook_count[i] < croak_count[i-1] for i in range(1, 5)):
16            return -1
17    return max_frogs if all(count == 0 for count in croak_count) else -1

Complexity note: The time complexity is O(n) since we only make a single pass through the string, updating counts as we go. The space complexity is O(1) because we only use a fixed amount of space for the counts.

  • 1Each character in 'croak' must appear in a specific order; if not, the sequence is invalid.
  • 2The maximum number of frogs at any point corresponds to the number of 'c's encountered minus the number of 'k's.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.