658. Longest Valid Parentheses (O(1) Space)

HardStackStackTwo PointersString

Given a string s of '(' and ')', return the length of the longest valid balanced substring using only O(1) extra space (two directional passes counting brackets). The input is JSON {s}.

Input: JSON {s}.

Output: Integer — the longest valid substring length.

Examples

Example 1
Input: {"s":")()())"}
Output: 4
Explanation: '()()' has length 4.
Example 2
Input: {"s":"(()"}
Output: 2
Explanation: '()' has length 2.
Example 3
Input: {"s":""}
Output: 0
Explanation: Empty string.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →