Skip to content

2380. Time Needed to Rearrange a Binary String 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int secondsToRemoveOccurrences(string s) {
    int ans = 0;
    int zeros = 0;

    for (const char c : s)
      if (c == '0')
        ++zeros;
      else if (zeros > 0)  // c == '1'
        ans = max(ans + 1, zeros);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int secondsToRemoveOccurrences(String s) {
    int ans = 0;
    int zeros = 0;

    for (final char c : s.toCharArray())
      if (c == '0')
        ++zeros;
      else if (zeros > 0) // c == '1'
        ans = Math.max(ans + 1, zeros);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def secondsToRemoveOccurrences(self, s: str) -> int:
    ans = 0
    zeros = 0

    for c in s:
      if c == '0':
        zeros += 1
      elif zeros > 0:  # c == '1'
        ans = max(ans + 1, zeros)

    return ans