Skip to content

2844. Minimum Operations to Make a Special Number 👍

  • Time: $O(|\texttt{num}|)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int minimumOperations(string num) {
    const int n = num.length();
    bool seenFive = false;
    bool seenZero = false;

    for (int i = n - 1; i >= 0; --i) {
      if (seenZero && num[i] == '0')  // '00'
        return n - i - 2;
      if (seenZero && num[i] == '5')  // '50'
        return n - i - 2;
      if (seenFive && num[i] == '2')  // '25'
        return n - i - 2;
      if (seenFive && num[i] == '7')  // '75'
        return n - i - 2;
      seenZero = seenZero || num[i] == '0';
      seenFive = seenFive || num[i] == '5';
    }

    return seenZero ? n - 1 : n;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int minimumOperations(String num) {
    final int n = num.length();
    boolean seenFive = false;
    boolean seenZero = false;

    for (int i = n - 1; i >= 0; --i) {
      if (seenZero && num.charAt(i) == '0') // '00'
        return n - i - 2;
      if (seenZero && num.charAt(i) == '5') // '50'
        return n - i - 2;
      if (seenFive && num.charAt(i) == '2') // '25'
        return n - i - 2;
      if (seenFive && num.charAt(i) == '7') // '75'
        return n - i - 2;
      seenZero = seenZero || num.charAt(i) == '0';
      seenFive = seenFive || num.charAt(i) == '5';
    }

    return seenZero ? n - 1 : n;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def minimumOperations(self, num: str) -> int:
    n = len(num)
    seenFive = False
    seenZero = False

    for i in range(n - 1, -1, -1):
      if seenZero and num[i] == '0':  # '00'
        return n - i - 2
      if seenZero and num[i] == '5':  # '50'
        return n - i - 2
      if seenFive and num[i] == '2':  # '25'
        return n - i - 2
      if seenFive and num[i] == '7':  # '75'
        return n - i - 2
      seenZero = seenZero or num[i] == '0'
      seenFive = seenFive or num[i] == '5'

    return n - 1 if seenZero else n