Skip to main content

Posts

Showing posts from December, 2022

Valid parentheses leet code

  class Solution :     def isValid ( self , s : str ) -> bool :         d={ "(" : ")" , "{" : "}" , "[" : "]" }         stack=[]         for p in s:             if p in d: #check each paremnthasis if it is opening one                 stack.append(d[p]) # append closing of that to stack             elif stack and stack[- 1 ]==p: #if p is closing parethasis and                 stack.pop() #it is last ele in stack pop that ele             else :                 return False         return True if not stack else False             #time complexity O(n) # memeory complexity O(n)

Merge sorted Array

  class Solution :     def merge ( self , nums1 : List[ int ], m : int , nums2 : List[ int ], n : int ) -> None :         last=m+n- 1         while m> 0 and n> 0 :             if nums1[m- 1 ]>nums2[n- 1 ]:                 nums1[last]=nums1[m- 1 ]                 m=m- 1             else :                 nums1[last]=nums2[n- 1 ]                 n=n- 1             last=last- 1         while n> 0 :             nums1[last]=nums2[n- 1 ]             n=n- 1             last=last- 1         """         Do not return anything, ...

Reverse integer leetcode solution

  class Solution :     def reverse ( self , x : int ) -> int :         if x< 0 :             sign=- 1         else :             sign= 1         s= str (x)                   if s[ 0 ]== "-" :             ss=sign* int (s[:- len (s):- 1 ])                         elif s[- 1 ]== "0" :             ss= int (s[:- len (s)- 1 :- 1 ])                         else :             ss= int (s[::- 1 ])         if ss>- 2 ** 31 and ss<( 2 ** 31 )- 1 :             return ss         else :             re...

Roman to integer Leetcode Solution

  class Solution :     def romanToInt ( self , s : str ) -> int :         roman={ "I" : 1 , "V" : 5 , "X" : 10 , "L" : 50 , "C" : 100 , "D" : 500 , "M" : 1000 }         total= 0         for i in range ( len (s)):             if i+ 1 < len (s) and roman[s[i]]<roman[s[i+ 1 ]]:                 total=total-(roman[s[i]])             else :                 total=total+(roman[s[i]])         return total

add two numbers || linked list python leetcode solution

  # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution : def addTwoNumbers ( self , l1 : Optional [ ListNode ] , l2 : Optional [ ListNode ] ) - > Optional [ ListNode ] : dummy = ListNode ( None ) tail = dummy carry = 0 while l1 or l2 or carry : v1 = l1 . val if l1 else 0 # there might be a case where 2 digit v2 = l2 . val if l2 else 0 # number is add with 3 so we add 0 """1-->2-->9 2-->3-->2-->1 in above we place 0 """ val = v1 + v2 + carry carry = val // 10 # it stores 10th place in carry val = val % 10 tail . next = ListNode ( val ) l1 = l1 . next if l1 else None l2 = l2 . next if l2 else None tail = tail . next return dummy . next ...