Java Easy Solution for Beginners
Approach\n1. Define a method minAddToMakeValid that takes a string s representing parentheses.\n2. Initialize a stack (Stack<Character> st) to keep track of ope
# Approach\n1. Define a method `minAddToMakeValid` that takes a string `s` representing parentheses.\n2. Initialize a stack (`Stack<Character> st`) to keep track of opening parentheses.\n3. Initialize a counter (`count`) to count the number of additional parentheses needed.\n4. Iterate through each character in the string.\n5. If the current character is an opening parenthesis \'(\', push it onto the stack.\n6. If the current character is a closing parenthesis \')\':\n   - If the stack is empty, increment the `count` to indicate a missing opening parenthesis.\n   - If the stack is not empty, pop an opening parenthesis from the stack, matching it with the current closing parenthesis.\n7. After iterating through all characters, add the remaining unmatched opening parentheses in the stack to the `count`.\n8. Return the total count, which represents the minimum number of parentheses needed to make the string valid.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n    public int minAddToMakeValid(String s) {\n        Stack<Character> st=new Stack<>();\n        int count=0;\n        for(int i=0; i<s.length(); i++){\n            if(s.charAt(i) == \'(\') st.push(s.charAt(i));\n            else{\n                if(st.empty()) count++;\n                else st.pop();\n            }\n        }\n        return count+st.size();\n    }\n}\n```\n\n![193730892e8675ebafc11519f6174bee5c4a5ab0.jpeg](https://assets.leetcode.com/users/images/773afcec-9e69-4c04-b526-20fd5465f173_1718521422.314726.jpeg)\n
['Java']