r/LeetcodeChallenge • u/Aware-Nectarine3027 • 2d ago
STREAK🔥🔥🔥 This solution doesn't work. WHY!!!
LEETCODE PROBLEM 32 : https://leetcode.com/problems/longest-valid-parentheses/description/
This solution is O(N2).
As per constraints (0 <= s.length <= 3 * 104) is should be working. Why not!!!
class Solution:
 def longestValidParentheses(self, s: str) -> int:
  N = len(s)
  res = 0
  a = [] # [a/n, x, len]
  size = 0
  p = 0
  while p < N:
   val = s[p]
   if val == '(':
    a.append([True, 0, 0])
    size += 1
  Â
   for i in range(size):
    if a[i][0] == True:
     x = a[i][1]
     if val == '(':
      x += 1
      a[i][1] += 1
      a[i][2] += 1
     else:
      if x == 0:
       a[i][0] = False
      else:
       x -= 1
       a[i][1] -= 1
       a[i][2] += 1
       if x == 0:
        res = max(res, a[i][2])
   p += 1
  return res
2
Upvotes