Problem · Greedy

Minimum Boys Next to Girls

Learn this problem
MediumGuidewireFULLTIMEOA

Problem statement

You are given a row of seats represented by a string s.

  • 'G' means the seat is already occupied by a girl.
  • '-' means the seat is empty, and you may place a boy there.

Place the minimum number of boys so that every girl has at least one adjacent boy immediately to her left or right. Boys can only be placed in empty seats.

Return the minimum number of boys required. If it is impossible to satisfy every girl, return -1.

Function

minBoysNextToGirls(s: String) → int

Examples

Example 1

s = "-G-GG--"return = 2

One optimal placement is -GBGGB- with boys at indices 2 and 5.

Example 2

s = "G-G"return = 1

Placing one boy in the middle seat covers both girls.

Example 3

s = "G"return = -1

Constraints

  • 1 <= s.length <= 2 * 10^5
  • s[i] is either 'G' or '-'.
  • Adjacency only means immediate left or immediate right.
drafts saved locally
public int minBoysNextToGirls(String s) {
    // write your code here
}
s"-G-GG--"
expected2
checking account