Skip to content

1375. Number of Times Binary String Is Prefix-Aligned 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  int numTimesAllBlue(vector<int>& flips) {
    int ans = 0;
    int rightmost = 0;

    for (int i = 0; i < flips.size(); ++i) {
      rightmost = max(rightmost, flips[i]);
      // max(flips[0..i]) = rightmost = i + 1,
      // so flips[0..i] is a permutation of 1, 2, ..., i + 1.
      if (rightmost == i + 1)
        ++ans;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public int numTimesAllBlue(int[] flips) {
    int ans = 0;
    int rightmost = 0;

    for (int i = 0; i < flips.length; ++i) {
      rightmost = Math.max(rightmost, flips[i]);
      // Math.max(flips[0..i]) = rightmost = i + 1,
      // so flips[0..i] is a permutation of 1, 2, ..., i + 1.
      if (rightmost == i + 1)
        ++ans;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
  def numTimesAllBlue(self, flips: list[int]) -> int:
    ans = 0
    rightmost = 0

    for i, flip in enumerate(flips):
      rightmost = max(rightmost, flip)
      # max(flips[0..i]) = rightmost = i + 1,
      # so flips[0..i] is a permutation of 1, 2, ..., i + 1.
      if rightmost == i + 1:
        ans += 1

    return ans