beats 99% | 45.45% | JAVA SOLUTION
Intuition\n Describe your first thoughts on how to solve this problem. \nusing Stack\n\n# Approach\n Describe your approach to solving the problem. \nYou can ma
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nusing Stack\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nYou can maintain two counters, left and right, to keep track of the number of open and close parentheses encountered so far. By iterating through the string twice (once from left to right and once from right to left), you can find the longest valid parentheses substring without using a stack.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\nclass Solution {\n    public int longestValidParentheses(String s) {\n        int maxLen = 0;\n        int left = 0;\n        int right = 0;\n\n        // Left to right pass\n        for (int i = 0; i < s.length(); i++) {\n            if (s.charAt(i) == \'(\') {\n                left++;\n            } else {\n                right++;\n            }\n\n            if (left == right) {\n                maxLen = Math.max(maxLen, 2 * right);\n            } else if (right > left) {\n                left = 0;\n                right = 0;\n            }\n        }\n\n        left = 0;\n        right = 0;\n\n        // Right to left pass\n        for (int i = s.length() - 1; i >= 0; i--) {\n            if (s.charAt(i) == \')\') {\n                right++;\n            } else {\n                left++;\n            }\n\n            if (left == right) {\n                maxLen = Math.max(maxLen, 2 * left);\n            } else if (left > right) {\n                left = 0;\n                right = 0;\n            }\n        }\n\n        return maxLen;\n    }\n}\n\n```
['Java']