LeetCode Solutions

921. Minimum Add to Make Parentheses Valid

Time: $O(n)$

Space: $O(1)$

			

class Solution {
 public:
  int minAddToMakeValid(string s) {
    int l = 0;
    int r = 0;

    for (const char c : s)
      if (c == '(') {
        ++l;
      } else {
        if (l == 0)
          ++r;
        else
          --l;
      }

    return l + r;
  }
};
			

class Solution {
  public int minAddToMakeValid(String s) {
    int l = 0;
    int r = 0;

    for (final char c : s.toCharArray())
      if (c == '(') {
        ++l;
      } else {
        if (l == 0)
          ++r;
        else
          --l;
      }

    return l + r;
  }
}
			

class Solution:
  def minAddToMakeValid(self, s: str) -> int:
    l = 0
    r = 0

    for c in s:
      if c == '(':
        l += 1
      else:
        if l == 0:
          r += 1
        else:
          l -= 1

    return l + r