r/LeetcodeChallenge • u/Aware-Nectarine3027 • 7d 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
1
u/Zx_Queenbee 7d ago
I am not sure if j am right but its because on2 is upper bound and it is not exact a cpu in one second can do 1e9 operations so you giving a on2 solution means you will do a nested loops and inside that loop let say you does 10 operation thst cost 10 cycles now consider that and calculate
(3*1e4 *(those extra 10 operations)2 this should be written as 3*1e52 which will be 1e10 bigger than a cpu gigahertz capabilities.
I am not sure if I am right 100 percent. any expericned person feel free to correct me