[EXPLAINED] Runtime beats 95.59%
Intuition\nThe intuition is that by ensuring the counts of \'(\' and \')\' are balanced in both directions, we can identify the longest valid parentheses substr
# Intuition\nThe intuition is that by ensuring the counts of \'(\' and \')\' are balanced in both directions, we can identify the longest valid parentheses substring.\n\n# Approach\nThe approach involves two passes over the string: one left-to-right and one right-to-left, keeping track of the balance between opening and closing parentheses.\n\n# Complexity\n- Time complexity:\nO(n) - The string is scanned twice, once from left-to-right and once from right-to-left.\n\n- Space complexity:\nO(1) - Only a few extra variables are used, regardless of the input size.\n\n# Code\n```typescript []\nfunction longestValidParentheses(s: string): number {\n    let maxLen = 0;\n    let left = 0;\n    let right = 0;\n\n    // Left to right scan\n    for (let i = 0; i < s.length; i++) {\n        if (s[i] === \'(\') {\n            left++;\n        } else {\n            right++;\n        }\n        if (left === right) {\n            maxLen = Math.max(maxLen, 2 * right);\n        } else if (right > left) {\n            left = right = 0;\n        }\n    }\n\n    left = right = 0;\n\n    // Right to left scan\n    for (let i = s.length - 1; i >= 0; i--) {\n        if (s[i] === \'(\') {\n            left++;\n        } else {\n            right++;\n        }\n        if (left === right) {\n            maxLen = Math.max(maxLen, 2 * left);\n        } else if (left > right) {\n            left = right = 0;\n        }\n    }\n\n    return maxLen;\n}\n\n```
['TypeScript']