From 36271425d3050bdb3b8e68e9e53b868857a60c9f Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 2 Aug 2021 12:42:50 +0530 Subject: [PATCH 01/78] Create Day-1_Making A Large Island.py --- .../Day-1_Making A Large Island.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-1_Making A Large Island.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-1_Making A Large Island.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-1_Making A Large Island.py new file mode 100644 index 0000000..6b37dc0 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-1_Making A Large Island.py @@ -0,0 +1,21 @@ +class Solution: + def largestIsland(self, g: List[List[int]]) -> int: + R,C=len(g),len(g[0]) + def get(i, j): + return 0 if i < 0 or j < 0 or i >= R or j >= C else g[i][j] + def paint(i, j, clr): + if get(i, j) != 1: return 0 + g[i][j] = clr + return 1 + paint(i + 1, j, clr) + paint(i - 1, j, clr) + paint(i, j + 1, clr) + paint(i, j - 1, clr) + sizes = [ 0, 0 ] # sentinel values; colors start from 2. + for i in range(R): + for j in range(C): + if g[i][j] == 1: sizes.append(paint(i, j, len(sizes))) + res=0 + for i in range(R): + for j in range(C): + if not g[i][j]: + # need to use set to remove duplicate as there could be some valid flip position + # which is closed to the same area multiple times. + res = max(res, 1 + sum(sizes[c] for c in {get(i + 1, j), get(i - 1, j), get(i, j + 1), get(i, j - 1)})) + return R*C if not res else res From cb9cd9b7c964ecf5ce1913a16bafc991b062aa8c Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 2 Aug 2021 13:00:56 +0530 Subject: [PATCH 02/78] Create Day-2_Two_Sum.py --- .../August_Challenge_2021/Day-2_Two_Sum.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py new file mode 100644 index 0000000..dca4066 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py @@ -0,0 +1,32 @@ +''' Brute Force solution - O(N^2) ''' +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + for i,v in enumerate(nums): + for j,vs in enumerate(nums[i+1:], i+1): + if v + vs == target: + return [i, j] + + +''' Optimized O(N) Time and O(N) Space. ''' +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + # Keys are the value of nums, Values is a list = [frequency, Indices....] + d = {} + for i,v in enumerate(nums): + if v not in d: + d[v] = [1, i] + else: + d[v][0] += 1 + d[v].append(i) + + for i in nums: + value = target - i + if value == i and d[value][0] > 1: + return d[value][1:3] + elif value in d and value != i: + return [d[i][1], d[value][1]] + + + + + From 9e35d9872c81b6ba0d6b6a5f6ce9e563773b4898 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 2 Aug 2021 13:12:43 +0530 Subject: [PATCH 03/78] Update Day-2_Two_Sum.py --- .../August_Challenge_2021/Day-2_Two_Sum.py | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py index dca4066..6ed2bf9 100644 --- a/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py @@ -8,6 +8,8 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: ''' Optimized O(N) Time and O(N) Space. ''' + +# Two pass Solution class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: # Keys are the value of nums, Values is a list = [frequency, Indices....] @@ -28,5 +30,15 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: - +# One Pass Solution +'''While inserting the element in dictionary itself, we check if (target - i) is already present in dict. If present return the indices there itself.''' +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + d = {} + for i,v in enumerate(nums): + value = target - v + if value in d: + return [d[value], i] + else: + d[v] = i From 4dbc735e09ce651f96d7603b6588fcf558cc02aa Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 2 Aug 2021 13:32:39 +0530 Subject: [PATCH 04/78] Update Day-2_Two_Sum.py --- .../August_Challenge_2021/Day-2_Two_Sum.py | 25 ++++++++----------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py index 6ed2bf9..ac51055 100644 --- a/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-2_Two_Sum.py @@ -9,32 +9,27 @@ def twoSum(self, nums: List[int], target: int) -> List[int]: ''' Optimized O(N) Time and O(N) Space. ''' -# Two pass Solution +# Iterating Twice - O(2*N) class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: - # Keys are the value of nums, Values is a list = [frequency, Indices....] d = {} + # O(N) for i,v in enumerate(nums): - if v not in d: - d[v] = [1, i] - else: - d[v][0] += 1 - d[v].append(i) + d[v] = i + # O(N) + for i,v in enumerate(nums): + value = target - v + if value in d and d[value] != i: + return [i, d[value]] - for i in nums: - value = target - i - if value == i and d[value][0] > 1: - return d[value][1:3] - elif value in d and value != i: - return [d[i][1], d[value][1]] - -# One Pass Solution +# Iterating Once - O(N) '''While inserting the element in dictionary itself, we check if (target - i) is already present in dict. If present return the indices there itself.''' class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: d = {} + # O(N) for i,v in enumerate(nums): value = target - v if value in d: From fa90e65208ba9813556c146dbbbf2c88682e6913 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 3 Aug 2021 16:38:50 +0530 Subject: [PATCH 05/78] Create Day-3_Subsets_ll.py --- .../August_Challenge_2021/Day-3_Subsets_ll.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-3_Subsets_ll.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-3_Subsets_ll.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-3_Subsets_ll.py new file mode 100644 index 0000000..cc68daf --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-3_Subsets_ll.py @@ -0,0 +1,20 @@ +class Solution: + def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: + def generate(arr, idx, subarr, res): + if idx == len(arr): + if len(subarr) > 0: + # To avoid adding duplicates + res.add(tuple(sorted(subarr))) + return + # Not including the element at current index - idx + generate(arr, idx + 1, subarr, res) + # Including the element at current index - idx + generate(arr, idx + 1, subarr + [arr[idx]], res) + + res = set() + generate(nums, 0, [], res) + l = [list(x) for x in res] + [[]] + + return l + + From 8ddc1d76c03fb869df188df6f82e8273bea9435e Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 4 Aug 2021 16:51:36 +0530 Subject: [PATCH 06/78] Create Day-4_Path_Sum_ll.py --- .../Day-4_Path_Sum_ll.py | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-4_Path_Sum_ll.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-4_Path_Sum_ll.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-4_Path_Sum_ll.py new file mode 100644 index 0000000..3acbf77 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-4_Path_Sum_ll.py @@ -0,0 +1,41 @@ +""" +Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum. + +Solution: O(N) Time and O(Height) Space. +""" + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: + def get_sum(root, ans, target, res): + if root is None: + return res + + # Appending the root value to arr + ans.append(root.val) + + # If root is leaf node, print the path + if root.left is None and root.right is None: + if sum(ans) == target: + #print(ans, target) + res.append(list(ans)) + + + # Recur on the LST + get_sum(root.left, ans, target, res) + # Recur on the RST + get_sum(root.right, ans, target, res) + + # Pop off the last element, as we are changing the subtrees + ans.pop() + + + res = [] + get_sum(root, [], targetSum, res) + return res + From ebd284278accd2cdff420e73e3210a702cb57dec Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 4 Aug 2021 17:11:43 +0530 Subject: [PATCH 07/78] Update Day-4_Path_Sum_ll.py --- .../Day-4_Path_Sum_ll.py | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-4_Path_Sum_ll.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-4_Path_Sum_ll.py index 3acbf77..3e6d8a2 100644 --- a/Leetcode_30day_challenge/August_Challenge_2021/Day-4_Path_Sum_ll.py +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-4_Path_Sum_ll.py @@ -1,7 +1,8 @@ """ Given the root of a binary tree and an integer targetSum, return all root-to-leaf paths where each path's sum equals targetSum. -Solution: O(N) Time and O(Height) Space. +Solution - 1: O(N) Time and O(Height) Space. +Find the path, sum the path and check if pathsum equals targetSum """ # Definition for a binary tree node. @@ -39,3 +40,33 @@ def get_sum(root, ans, target, res): get_sum(root, [], targetSum, res) return res +""" +Solution-2: O(N) Time and O(Height) Space +Calculate the Sum on the go while traversing the path from root to leaf +""" +class Solution: + def pathSum(self, root: TreeNode, targetSum: int) -> List[List[int]]: + def get_sum(root, ans, sums, res): + if root is None: + return res + + # Appending the root value to arr + ans.append(root.val) + + # If root is leaf node and sums == root.val (i.e we have found a path whose sum equals targetSum), print the path + if root.left is None and root.right is None and sums == root.val: + res.append(list(ans)) + + sums -= root.val + # Recur on the LST + get_sum(root.left, ans, sums, res) + # Recur on the RST + get_sum(root.right, ans, sums, res) + + # Pop off the last element, as we are moving from LST to RST and viceversa + ans.pop() + + + res = [] + get_sum(root, [], targetSum, res) + return res From 081a296adb40f289a512e41273a7f7082e26c1b6 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 4 Aug 2021 17:15:03 +0530 Subject: [PATCH 08/78] Create Path_Sum.py --- Leetcode_30day_challenge/Path_Sum.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Leetcode_30day_challenge/Path_Sum.py diff --git a/Leetcode_30day_challenge/Path_Sum.py b/Leetcode_30day_challenge/Path_Sum.py new file mode 100644 index 0000000..8dbd305 --- /dev/null +++ b/Leetcode_30day_challenge/Path_Sum.py @@ -0,0 +1,20 @@ +# https://leetcode.com/problems/path-sum/ +''' +Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum. +Solution: O(N) Time and O(Height) Space +''' + +class Solution: + def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: + def solve(root, sums): + if root is None: + return False + + if root.left is None and root.right is None and root.val == sums: + return True + sums -= root.val + return solve(root.left, sums) or solve(root.right, sums) + + + res = solve(root, targetSum) + return res From 2c9034ffd5e431c20fbce767e0f3a228d969e99a Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 6 Aug 2021 17:20:24 +0530 Subject: [PATCH 09/78] Create Day-6_N-ary Tree Level Order Traversal.py --- .../Day-6_N-ary Tree Level Order Traversal.py | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py new file mode 100644 index 0000000..c836f44 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py @@ -0,0 +1,60 @@ +""" +Given an n-ary tree, return the level order traversal of its nodes' values. + +Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). +""" + +from collections import deque +""" +# Definition for a Node. +class Node: + def __init__(self, val=None, children=None): + self.val = val + self.children = children +""" +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + # Base Condition + if root is None: + return [] + + q = deque() + # Append the trees root + q.append(root) + # Separator - Separates Levels of the Tree + sep = '$' + # Append the separator - means end of root level + q.append(sep) + + # Appending root.val to answer + ans = [[root.val]] + + # Previous to check if all nodes are visited. Used to break while loop below + prev = -1 + # A temporary list to store all nodes of each level + temp = [] + while q: + # Pop the first element of the deque + curr = q.popleft() + # If curr is not $, the we add it's children(the next level) one by one to the deque and temp list as well. + if curr and curr != sep: + for i in curr.children: + q.append(i) + temp.append(i.val) + elif curr == sep: + # if curr == $, that means we have reached the end of a level, so append temp list to answer. + q.append(sep) + if temp: + ans.append(list(temp)) + temp = [] + + # Exit conditon. If curr == prev and they are both $,means we have completed traversing all levels + if prev == curr and curr == sep: + break + + # Updating the prev with curr + prev = curr + + + return ans + From 086204825b4214f65fc963097007692107280ff9 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 6 Aug 2021 17:49:49 +0530 Subject: [PATCH 10/78] Update Day-6_N-ary Tree Level Order Traversal.py --- .../Day-6_N-ary Tree Level Order Traversal.py | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py index c836f44..766cd84 100644 --- a/Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-6_N-ary Tree Level Order Traversal.py @@ -4,14 +4,8 @@ Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples). """ +# Solution - 1 from collections import deque -""" -# Definition for a Node. -class Node: - def __init__(self, val=None, children=None): - self.val = val - self.children = children -""" class Solution: def levelOrder(self, root: 'Node') -> List[List[int]]: # Base Condition @@ -58,3 +52,22 @@ def levelOrder(self, root: 'Node') -> List[List[int]]: return ans + + +# Solution - 2 Pythonic Way +from collections import deque +class Solution: + def levelOrder(self, root: 'Node') -> List[List[int]]: + # Base Condition + if root is None: + return [] + # Append the root to deque + q = deque([root]) + ans = [] + while q: + # Append the list of nodes present in the deque + ans.append([node.val for node in q]) + # Update/Append the Deque with the list of nodes from the next level. + q = [node for nodes in q for node in nodes.children if node] + + return ans From 5c3fbb15d09f20e0b7716367865ffc74a35c73fd Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 9 Aug 2021 14:58:11 +0530 Subject: [PATCH 11/78] Create Day-9_Add_Strings.py --- .../Day-9_Add_Strings.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-9_Add_Strings.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-9_Add_Strings.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-9_Add_Strings.py new file mode 100644 index 0000000..20b6b3c --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-9_Add_Strings.py @@ -0,0 +1,23 @@ +""" +Time Complexity - O(max(len(num1), len(num2))) +Space Complexity - O(abs(len(num1) - len(num2))) +""" +class Solution: + def addStrings(self, num1: str, num2: str) -> str: + n = max(len(num1), len(num2)) + num1 = num1.rjust(n, '0') + num2 = num2.rjust(n, '0') + ans = '' + carry = 0 + for i in range(len(num1)-1,-1,-1): + temp = int(num1[i]) + int(num2[i]) + carry + if temp > 9: + carry = 1 + else: + carry = 0 + + ans = str(temp)[-1] + ans + if carry > 0: + ans = str(carry) + ans + + return ans From 6ec6dc2a467041c410405e9e820f2ecc308fab7e Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 9 Aug 2021 15:14:55 +0530 Subject: [PATCH 12/78] Update Day-9_Add_Strings.py --- .../Day-9_Add_Strings.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-9_Add_Strings.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-9_Add_Strings.py index 20b6b3c..01be7d8 100644 --- a/Leetcode_30day_challenge/August_Challenge_2021/Day-9_Add_Strings.py +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-9_Add_Strings.py @@ -21,3 +21,29 @@ def addStrings(self, num1: str, num2: str) -> str: ans = str(carry) + ans return ans + + +# Using Dictionary - Not using int() anywhere in the code. +class Solution: + def addStrings(self, num1: str, num2: str) -> str: + d = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9} + n = max(len(num1), len(num2)) + num1 = num1.rjust(n, '0') + num2 = num2.rjust(n, '0') + ans = '' + carry = 0 + for i in range(len(num1)-1,-1,-1): + temp = d[num1[i]] + d[num2[i]] + carry + #print(temp) + if temp > 9: + carry = 1 + + else: + carry = 0 + + ans = str(temp)[-1] + ans + if carry > 0: + ans = str(carry) + ans + + return ans + From 9b9fa7d02db173ab95c61611c3cf1b127ed7dbda Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 10 Aug 2021 19:01:10 +0530 Subject: [PATCH 13/78] Create Day-10_Flip String to Monotone Increasing.py --- .../Day-10_Flip String to Monotone Increasing.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-10_Flip String to Monotone Increasing.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-10_Flip String to Monotone Increasing.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-10_Flip String to Monotone Increasing.py new file mode 100644 index 0000000..28f9288 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-10_Flip String to Monotone Increasing.py @@ -0,0 +1,12 @@ +class Solution: + def minFlipsMonoIncr(self, s: str) -> int: + ones, flips = 0, 0 + for i in s: + if i == '1': + ones += 1 + else: + flips += 1 + flips = min(flips, ones) + + return flips + From b9a9f467360585bbd76f3e12f15b8a1001c82c56 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 11 Aug 2021 16:59:49 +0530 Subject: [PATCH 14/78] Create Day-11_Array of Doubled Pairs.py --- .../Day-11_Array of Doubled Pairs.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-11_Array of Doubled Pairs.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-11_Array of Doubled Pairs.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-11_Array of Doubled Pairs.py new file mode 100644 index 0000000..d9dce47 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-11_Array of Doubled Pairs.py @@ -0,0 +1,16 @@ +from collections import Counter +class Solution: + def canReorderDoubled(self, arr: List[int]) -> bool: + d = Counter(arr) + arr.sort(key=abs) + + for i in arr: + double = 2*i + if d[i] == 0: + continue + if d[double] == 0: + return False + d[double] -= 1 + d[i] -= 1 + + return True From f7388daa50cf9d95a6b572224765ae30a1ab10de Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 11 Aug 2021 17:03:32 +0530 Subject: [PATCH 15/78] Update Day-11_Array of Doubled Pairs.py --- .../August_Challenge_2021/Day-11_Array of Doubled Pairs.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-11_Array of Doubled Pairs.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-11_Array of Doubled Pairs.py index d9dce47..3117ea9 100644 --- a/Leetcode_30day_challenge/August_Challenge_2021/Day-11_Array of Doubled Pairs.py +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-11_Array of Doubled Pairs.py @@ -6,10 +6,13 @@ def canReorderDoubled(self, arr: List[int]) -> bool: for i in arr: double = 2*i + # Since we have sorted the array, we'll first iterate over the small values and if small values frequency is zero, we just continue if d[i] == 0: continue + # If double values frequency is Zero, that means there is no double value for i. So we return False if d[double] == 0: return False + # Decrement both i and double d[double] -= 1 d[i] -= 1 From 5c0e9ecd48c72c823121c992fc63d24bf96df962 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Thu, 12 Aug 2021 16:41:38 +0530 Subject: [PATCH 16/78] Create Day-12_Group_Anagrams.py --- .../August_Challenge_2021/Day-12_Group_Anagrams.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-12_Group_Anagrams.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-12_Group_Anagrams.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-12_Group_Anagrams.py new file mode 100644 index 0000000..856eea9 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-12_Group_Anagrams.py @@ -0,0 +1,13 @@ +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + d = {} + sor = [''.join(sorted(list(x))) for x in strs] + + for i,v in enumerate(sor): + if v not in d: + d[v] = [strs[i]] + else: + d[v].append(strs[i]) + + + return (list(d.values())) From 98a80fc3a4185dc7d6df18289b4c372ec1a69544 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 13 Aug 2021 14:29:17 +0530 Subject: [PATCH 17/78] Create Day-13_Set_Matrix_Zeroes.py --- .../Day-13_Set_Matrix_Zeroes.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-13_Set_Matrix_Zeroes.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-13_Set_Matrix_Zeroes.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-13_Set_Matrix_Zeroes.py new file mode 100644 index 0000000..ae85409 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-13_Set_Matrix_Zeroes.py @@ -0,0 +1,23 @@ +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + """ + rows = len(matrix) + cols = len(matrix[0]) + cr = set() + cs = set() + for i in range(rows): + for j in range(cols): + if matrix[i][j] == 0: + #matrix[i][0], matrix[0][j] = 0,0 + cs.add(j) + cr.add(i) + + for i in cr: + matrix[i] = [0] * cols + #print(matrix) + for j in cs: + for i in range(rows): + matrix[i][j] = 0 + From e7c085cd66974b03f38a58ff9483b6bf521431df Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 16 Aug 2021 14:29:36 +0530 Subject: [PATCH 18/78] Create Day-16_Range_Sum_Query.py --- .../Day-16_Range_Sum_Query.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-16_Range_Sum_Query.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-16_Range_Sum_Query.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-16_Range_Sum_Query.py new file mode 100644 index 0000000..7a44c2a --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-16_Range_Sum_Query.py @@ -0,0 +1,21 @@ +class NumArray: + + def __init__(self, nums: List[int]): + self.nums = nums + self.pre = [] + prev = 0 + for i in self.nums: + self.pre.append(prev + i) + prev = self.pre[-1] + + + def sumRange(self, left: int, right: int) -> int: + if left != 0: + return self.pre[right] - self.pre[left-1] + return self.pre[right] + + + +# Your NumArray object will be instantiated and called as such: +# obj = NumArray(nums) +# param_1 = obj.sumRange(left,right) From b0e950712806e1920cbab344f622bdc1c95ab03c Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 17 Aug 2021 15:07:53 +0530 Subject: [PATCH 19/78] Create Day-17_Count_Good_Nodes_in_Binary_Tree.py --- .../Day-17_Count_Good_Nodes_in_Binary_Tree.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-17_Count_Good_Nodes_in_Binary_Tree.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-17_Count_Good_Nodes_in_Binary_Tree.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-17_Count_Good_Nodes_in_Binary_Tree.py new file mode 100644 index 0000000..0210551 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-17_Count_Good_Nodes_in_Binary_Tree.py @@ -0,0 +1,17 @@ +# O(N) Time and Space. +class Solution: + def goodNodes(self, root: TreeNode) -> int: + + def dfs(root: TreeNode, ans: list, maxm: float) -> int: + if root is None: + return + maxm = max(root.val, maxm) + if root.val >= maxm: + ans.append(root.val) + + dfs(root.left, ans, maxm) + dfs(root.right, ans, maxm) + + ans = [] + dfs(root, ans, float('-inf')) + return len(ans) From 8c5860d882d7de795af0f6cea7210bd1891fe052 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 17 Aug 2021 15:15:16 +0530 Subject: [PATCH 20/78] Update Day-17_Count_Good_Nodes_in_Binary_Tree.py --- .../Day-17_Count_Good_Nodes_in_Binary_Tree.py | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-17_Count_Good_Nodes_in_Binary_Tree.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-17_Count_Good_Nodes_in_Binary_Tree.py index 0210551..06876ee 100644 --- a/Leetcode_30day_challenge/August_Challenge_2021/Day-17_Count_Good_Nodes_in_Binary_Tree.py +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-17_Count_Good_Nodes_in_Binary_Tree.py @@ -1,4 +1,4 @@ -# O(N) Time and Space. +# O(N) Time and Space - Storing the Good Nodes and count them at last. class Solution: def goodNodes(self, root: TreeNode) -> int: @@ -15,3 +15,16 @@ def dfs(root: TreeNode, ans: list, maxm: float) -> int: ans = [] dfs(root, ans, float('-inf')) return len(ans) + +# O(N) Time and O(H) Space. - No list used +class Solution: + def goodNodes(self, root: TreeNode) -> int: + + def dfs(root: TreeNode, ans: list, maxm: float) -> int: + if root is None: + return 0 + maxm = max(root.val, maxm) + return int(root.val >= maxm) + dfs(root.left, ans, maxm) + dfs(root.right, ans, maxm) + + ans = 0 + return dfs(root, ans, root.val) From fbcc20d6832eca6ade24551c880ea56b1198776d Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 18 Aug 2021 22:29:11 +0530 Subject: [PATCH 21/78] Create Day-18_Decode_Strings.py --- .../Day-18_Decode_Strings.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-18_Decode_Strings.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-18_Decode_Strings.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-18_Decode_Strings.py new file mode 100644 index 0000000..4761c4d --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-18_Decode_Strings.py @@ -0,0 +1,18 @@ +class Solution: + def numDecodings(self, s: str) -> int: + + n = len(s) + dp = [0] * (n + 1) + dp[0] = 1 + dp[1] = 0 if s[0] == '0' else 1 + + + for i in range(2,n+1): + if int(s[i-1:i]) in range(1,10): + dp[i] += dp[i-1] + if int(s[i-2:i]) in range(10,27): + dp[i] += dp[i-2] + + + return dp[n] + From c40f1f669a32d7a6727536b36f732c91d11cf93b Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Thu, 19 Aug 2021 15:10:15 +0530 Subject: [PATCH 22/78] Create Day-19_Maximum Product of Splitted Binary Tree.py --- ...Maximum Product of Splitted Binary Tree.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-19_Maximum Product of Splitted Binary Tree.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-19_Maximum Product of Splitted Binary Tree.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-19_Maximum Product of Splitted Binary Tree.py new file mode 100644 index 0000000..64072ad --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-19_Maximum Product of Splitted Binary Tree.py @@ -0,0 +1,25 @@ +""" +Python Solution +Time Complexity: O(N) +Space Complexity: O(N) +""" + +class Solution: + def maxProduct(self, root: Optional[TreeNode]) -> int: + def sum_at_node(root: Optional[TreeNode], d: dict) -> int: + if root is None: + return 0 + val = root.val + sum_at_node(root.left, d) + sum_at_node(root.right, d) + d[root] = val + return val + + # Dictionary to store the sum of subtree with current node as root + # {Node: Sum of subtree with Node as root} + d = {} + sum_at_node(root, d) + ans = 0 + root_val = d[root] + for i,v in d.items(): + ans = max(ans, (root_val - v) * v) + + return ans % int(1e9+7) From c69dc21a4e594915e6495ba70edf6bd5399a685a Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 20 Aug 2021 18:05:00 +0530 Subject: [PATCH 23/78] Create Day-20_Valid_Sudoku.py --- .../Day-20_Valid_Sudoku.py | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-20_Valid_Sudoku.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-20_Valid_Sudoku.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-20_Valid_Sudoku.py new file mode 100644 index 0000000..8fa0791 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-20_Valid_Sudoku.py @@ -0,0 +1,52 @@ +# My Solution - O(N^2) +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + rows, cols = 9, 9 + # Check the Rows + for i in range(rows): + s = set() + for j in range(cols): + if board[i][j] in s and board[i][j] != '.': + return False + s.add(board[i][j]) + + # Check the Cols + for i in range(cols): + s = set() + for j in range(rows): + if board[j][i] in s and board[j][i] != '.': + return False + s.add(board[j][i]) + + # Check the Submatrices + for i in range(0,9,3): + for j in range(9): + if j%3 == 0: + ss = set() + for el in board[j][i:i+3]: + if el != '.' and el in ss: + return False + else: + ss.add(el) + return True + + +# A Better approach +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + seen = {} + for row in range(9): + for col in range(9): + val = board[row][col] + if val == '.': + continue + if (val,'r',row) in seen: + return False + if (val,'c',col) in seen: + return False + if (val,row//3,col//3) in seen: + return False + seen[(val,'r',row)] =True + seen[(val,'c',col)]=True + seen[(val,row//3,col//3)]=True + return True From 6e3e4275509d054d208c9bca1a6d53f5ed35424e Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 23 Aug 2021 13:47:35 +0530 Subject: [PATCH 24/78] Create Day-23_Two Sum IV - Input is a BST.py --- .../Day-23_Two Sum IV - Input is a BST.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-23_Two Sum IV - Input is a BST.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-23_Two Sum IV - Input is a BST.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-23_Two Sum IV - Input is a BST.py new file mode 100644 index 0000000..d063eae --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-23_Two Sum IV - Input is a BST.py @@ -0,0 +1,24 @@ +# TC: O(N) | SC: O(N) + +from collections import defaultdict +class Solution: + def findTarget(self, root: Optional[TreeNode], k: int) -> bool: + d = defaultdict(int) + if root.left is None and root.right is None: + return False + def inorder(root, d): + if root is None: + return + inorder(root.left, d) + d[root.val] += 1 + inorder(root.right, d) + + inorder(root, d) + + for i in d.keys(): + val = k - i + if val in d and val != i: + return True + + return False + From 1b951c473790e1d3abeeb1dac384c46e29f773cf Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 23 Aug 2021 13:54:29 +0530 Subject: [PATCH 25/78] Update Day-23_Two Sum IV - Input is a BST.py --- .../Day-23_Two Sum IV - Input is a BST.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-23_Two Sum IV - Input is a BST.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-23_Two Sum IV - Input is a BST.py index d063eae..5a0622c 100644 --- a/Leetcode_30day_challenge/August_Challenge_2021/Day-23_Two Sum IV - Input is a BST.py +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-23_Two Sum IV - Input is a BST.py @@ -1,5 +1,5 @@ # TC: O(N) | SC: O(N) - +# Method - 1: Traverse the BST, store the nodes values in a Dictionary. Then find the sum of two numbers equals target. from collections import defaultdict class Solution: def findTarget(self, root: Optional[TreeNode], k: int) -> bool: @@ -22,3 +22,5 @@ def inorder(root, d): return False +# Method - 2: Since it is a BST, for every element we can search for the element b (b = target - node.val) in O(H) Time. +# TC: O(N) and space will now be O(H) [Best: logN and Worst: N] From 71740f03403a3771d0f9c0f2a2154abf3f7830ba Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 24 Aug 2021 14:07:07 +0530 Subject: [PATCH 26/78] Create Day-24_Complex_Numbers_Multiplication.py --- .../Day-24_Complex_Numbers_Multiplication.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-24_Complex_Numbers_Multiplication.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-24_Complex_Numbers_Multiplication.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-24_Complex_Numbers_Multiplication.py new file mode 100644 index 0000000..c12b101 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-24_Complex_Numbers_Multiplication.py @@ -0,0 +1,11 @@ +class Solution: + def complexNumberMultiply(self, num1: str, num2: str) -> str: + a,b = num1.split('+') + c,d = num2.split('+') + a,c = int(a), int(c) + b,d = int(b.strip('i')), int(d.strip('i')) + + ans = str(a*c - d*b) + '+' + str(a*d+b*c) + 'i' + + return (ans) + From 559b6bab0b12ea8c9ec9f3ee7de43383e666490f Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 25 Aug 2021 16:06:59 +0530 Subject: [PATCH 27/78] Create Day-25_Sum_of_Squares.py --- .../Day-25_Sum_of_Squares.py | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-25_Sum_of_Squares.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-25_Sum_of_Squares.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-25_Sum_of_Squares.py new file mode 100644 index 0000000..5c9c284 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-25_Sum_of_Squares.py @@ -0,0 +1,34 @@ +# Solution - 1: PreComputation +class Solution: + def judgeSquareSum(self, c: int) -> bool: + threshold = (1<<31) - 1 + pre = set() + i = 0 + while True: + temp = i*i + if temp > threshold: + break + else: + pre.add(temp) + i += 1 + + for i in pre: + val = c - i + if val in pre: + return True + + return False + + + +# Solution - 2 +import math +class Solution: + + def judgeSquareSum(self, c: int) -> bool: + for a in range(int(math.sqrt(c))+1): + b = math.sqrt(c - a*a) + if b == int(b): + return True + + return False From 1cfa73a165ffa7a5ac1bd4014cf7efec1a4e123e Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Thu, 26 Aug 2021 17:46:35 +0530 Subject: [PATCH 28/78] Create Day-26_Verify Preorder Serialization of a Binary Tree.py --- ...Preorder Serialization of a Binary Tree.py | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-26_Verify Preorder Serialization of a Binary Tree.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-26_Verify Preorder Serialization of a Binary Tree.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-26_Verify Preorder Serialization of a Binary Tree.py new file mode 100644 index 0000000..a7cea3d --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-26_Verify Preorder Serialization of a Binary Tree.py @@ -0,0 +1,30 @@ +class Solution(object): + def isValidSerialization(self, preorder): + """ + :type preorder: str + :rtype: bool + """ + # remember how many empty slots we have + # non-null nodes occupy one slot but create two new slots + # null nodes occupy one slot + + p = preorder.split(',') + + #initially we have one empty slot to put the root in it + slot = 1 + for node in p: + + # no empty slot to put the current node + if slot == 0: + return False + + # a null node? + if node == '#': + # ocuppy slot + slot -= 1 + else: + # create new slot + slot += 1 + + #we don't allow empty slots at the end + return slot==0 From 7dbb70998184a5a5f11f5e134173efdc36548226 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 27 Aug 2021 15:47:13 +0530 Subject: [PATCH 29/78] Create Day-27_Longest_Uncommon_Subsequence.py --- .../Day-27_Longest_Uncommon_Subsequence.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-27_Longest_Uncommon_Subsequence.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-27_Longest_Uncommon_Subsequence.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-27_Longest_Uncommon_Subsequence.py new file mode 100644 index 0000000..520aa4b --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-27_Longest_Uncommon_Subsequence.py @@ -0,0 +1,22 @@ +####################### +1. Sort the words in order of decreasing length of strings and count the number of each word in a hashmap and do +####################### + + +class Solution(object): + def findLUSlength(self, strs): + def isSub(w1, w2, count): + for i in w2: + if i == w1[count]: + count += 1 + if count == len(w1): + return True + return count == len(w2) + + d = collections.Counter(strs) + strs.sort(key = len, reverse = True) + for i in range(len(strs)): + if d[strs[i]] == 1: + res = any(isSub(strs[i], strs[j], 0) for j in range(i)) + if res == False: return len(strs[i]) + return -1 From e825772fac9a2bbd259d742b9ffae43f048a95a3 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 30 Aug 2021 14:40:06 +0530 Subject: [PATCH 30/78] Create Day-30_Range_Addition_II.py --- .../Day-30_Range_Addition_II.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-30_Range_Addition_II.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-30_Range_Addition_II.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-30_Range_Addition_II.py new file mode 100644 index 0000000..8e81edf --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-30_Range_Addition_II.py @@ -0,0 +1,16 @@ +######### +# The maximum value is present in between [0, min(a)] and [0, min(b)]. So return min(a) * min(b) for all the items in "ops" list. +# Special Case: When ops is empty, then the answer is 0 and the number of 0's is nothing but m * n +######### + +class Solution: + def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int: + # Case when ops = [] + if not ops: + return m * n + min_a, min_b = float('inf'),float('inf') + for i in ops: + min_a = min(i[0], min_a) + min_b = min(i[1], min_b) + + return min_a * min_b From 67556556d9dcce9cf892a17c9d7d7fd0a9e7627d Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 31 Aug 2021 14:55:23 +0530 Subject: [PATCH 31/78] Create Day-31_Find_minimum_in_rotated_sorted_array.py --- ...31_Find_minimum_in_rotated_sorted_array.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Leetcode_30day_challenge/August_Challenge_2021/Day-31_Find_minimum_in_rotated_sorted_array.py diff --git a/Leetcode_30day_challenge/August_Challenge_2021/Day-31_Find_minimum_in_rotated_sorted_array.py b/Leetcode_30day_challenge/August_Challenge_2021/Day-31_Find_minimum_in_rotated_sorted_array.py new file mode 100644 index 0000000..dc0d715 --- /dev/null +++ b/Leetcode_30day_challenge/August_Challenge_2021/Day-31_Find_minimum_in_rotated_sorted_array.py @@ -0,0 +1,27 @@ +# Linear Search - O(N) +# Binary Search - O(logN) + +class Solution: + def findMin(self, nums: List[int]) -> int: + # Special cases + # If only one element + if len(nums) == 1: + return nums[0] + # If not rotated. How do we know ? If nums[0] < nums[n-1] + if nums[0] < nums[-1]: + return nums[0] + + # Binary Search + low, high = 0, len(nums) - 1 + while low <= high: + mid = (low + high)//2 + if nums[mid] < nums[low]: + # Check for inflection point on the left side + high = mid - 1 + else: + # Check for inflection point on the right side + low = mid + 1 + if nums[mid] > nums[mid+1]: + return nums[mid+1] + if nums[mid] < nums[mid - 1]: + return nums[mid] From bb98b5cf83818ba8e0615cc4b598748ff0176a5c Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 31 Aug 2021 14:56:07 +0530 Subject: [PATCH 32/78] Create Day-1.py --- Leetcode_30day_challenge/September_Challenge_2021/Day-1.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 Leetcode_30day_challenge/September_Challenge_2021/Day-1.py diff --git a/Leetcode_30day_challenge/September_Challenge_2021/Day-1.py b/Leetcode_30day_challenge/September_Challenge_2021/Day-1.py new file mode 100644 index 0000000..5b223b2 --- /dev/null +++ b/Leetcode_30day_challenge/September_Challenge_2021/Day-1.py @@ -0,0 +1 @@ +# Will be updated... From 5b7ccc0b1b3031078dbb52d562e3419d80d8459f Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 4 Sep 2021 16:39:41 +0530 Subject: [PATCH 33/78] Create Single_Number_III.py --- Single_Number_III.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 Single_Number_III.py diff --git a/Single_Number_III.py b/Single_Number_III.py new file mode 100644 index 0000000..737ecb1 --- /dev/null +++ b/Single_Number_III.py @@ -0,0 +1,33 @@ +""" +Time: O(N) and Space: O(1) + +1. First pass: Find the XOR of those two numbers. let it be 'ans' +2. Find any position in ans where a bit is set.let it be 'pos' +3. Second pass: Divide the numbers into two groups(g1 and g2) based on - if that position 'pos' is set or not. This will make the two numbers fall in different groups. +4. Now again find the XOR of the individual groups and the result of the XOR will be the answer (those two digits) +""" +class Solution: + def singleNumber(self, nums: List[int]) -> List[int]: + #First pass - Do XOR and find the XOR of those two elements - will be stored in ans + ans = 0 + for i in nums: + ans ^= i + + # Find any random set bit position in ans + def find_set_pos(n): + for i in range(32): + if n & (1 << i): + return i + + def check_bit_set_at_pos(m, k): + return (m >> k) & 1 + + pos = find_set_pos(ans) + res = [0, 0] + for i in nums: + if check_bit_set_at_pos(i, pos): + res[0] ^= i + else: + res[1] ^= i + + return res From 5409ce4762bd42dfb2c9350fbc2febd11529eda6 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 6 Sep 2021 14:25:22 +0530 Subject: [PATCH 34/78] Create day-6_Slowest_Key.py --- .../September_Challenge_2021/day-6_Slowest_Key.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Leetcode_30day_challenge/September_Challenge_2021/day-6_Slowest_Key.py diff --git a/Leetcode_30day_challenge/September_Challenge_2021/day-6_Slowest_Key.py b/Leetcode_30day_challenge/September_Challenge_2021/day-6_Slowest_Key.py new file mode 100644 index 0000000..985f574 --- /dev/null +++ b/Leetcode_30day_challenge/September_Challenge_2021/day-6_Slowest_Key.py @@ -0,0 +1,13 @@ +class Solution: + def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str: + ans, max_val = keysPressed[0], releaseTimes[0] + for i in range(1, len(keysPressed)): + rtime = releaseTimes[i] - releaseTimes[i-1] + + if rtime > max_val: + ans, max_val = keysPressed[i], max(max_val, rtime) + elif rtime == max_val: + ans = max(ans, keysPressed[i]) + + return ans + From f2a8792bc5580c6970ac08dbdf871fd0bd740377 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 7 Sep 2021 14:25:18 +0530 Subject: [PATCH 35/78] Create Day-7_Reverse_a_SLL.py --- .../September_Challenge_2021/Day-7_Reverse_a_SLL.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 Leetcode_30day_challenge/September_Challenge_2021/Day-7_Reverse_a_SLL.py diff --git a/Leetcode_30day_challenge/September_Challenge_2021/Day-7_Reverse_a_SLL.py b/Leetcode_30day_challenge/September_Challenge_2021/Day-7_Reverse_a_SLL.py new file mode 100644 index 0000000..c43df02 --- /dev/null +++ b/Leetcode_30day_challenge/September_Challenge_2021/Day-7_Reverse_a_SLL.py @@ -0,0 +1,10 @@ +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + prev = None + while head: + x = head.next + head.next = prev + prev = head + head = x + + return prev From 031ea615bd926f5075350d2841ee9c40c2dbc39e Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 7 Sep 2021 14:25:31 +0530 Subject: [PATCH 36/78] Rename day-6_Slowest_Key.py to Day-6_Slowest_Key.py --- .../{day-6_Slowest_Key.py => Day-6_Slowest_Key.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Leetcode_30day_challenge/September_Challenge_2021/{day-6_Slowest_Key.py => Day-6_Slowest_Key.py} (100%) diff --git a/Leetcode_30day_challenge/September_Challenge_2021/day-6_Slowest_Key.py b/Leetcode_30day_challenge/September_Challenge_2021/Day-6_Slowest_Key.py similarity index 100% rename from Leetcode_30day_challenge/September_Challenge_2021/day-6_Slowest_Key.py rename to Leetcode_30day_challenge/September_Challenge_2021/Day-6_Slowest_Key.py From d9010055ec23bdbcbf7375efb9b6215279d0239e Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 8 Sep 2021 14:48:31 +0530 Subject: [PATCH 37/78] Create Day-8_Shifting_Letters.py --- .../Day-8_Shifting_Letters.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Leetcode_30day_challenge/September_Challenge_2021/Day-8_Shifting_Letters.py diff --git a/Leetcode_30day_challenge/September_Challenge_2021/Day-8_Shifting_Letters.py b/Leetcode_30day_challenge/September_Challenge_2021/Day-8_Shifting_Letters.py new file mode 100644 index 0000000..bfe7be0 --- /dev/null +++ b/Leetcode_30day_challenge/September_Challenge_2021/Day-8_Shifting_Letters.py @@ -0,0 +1,15 @@ +# Time: O(N) and Space: O(1) + +class Solution: + def shiftingLetters(self, s: str, shifts: List[int]) -> str: + a = ord('a') + d = {chr(c): c - a for c in range(a, a+26)} + rd = {c - a: chr(c) for c in range(a, a+26)} + for i in range(len(shifts)-2,-1,-1): + shifts[i] += shifts[i+1] + + ans = '' + for i in range(len(s)): + ans += rd[(d[(s[i])] + shifts[i]) % 26] + + return ans From a8565d761f2363068064d6bf558c7183d69ff8d3 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 13 Sep 2021 14:56:55 +0530 Subject: [PATCH 38/78] Create Day-13_Maximum_number_of_balloons.py --- .../Day-13_Maximum_number_of_balloons.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Leetcode_30day_challenge/September_Challenge_2021/Day-13_Maximum_number_of_balloons.py diff --git a/Leetcode_30day_challenge/September_Challenge_2021/Day-13_Maximum_number_of_balloons.py b/Leetcode_30day_challenge/September_Challenge_2021/Day-13_Maximum_number_of_balloons.py new file mode 100644 index 0000000..6cd38f9 --- /dev/null +++ b/Leetcode_30day_challenge/September_Challenge_2021/Day-13_Maximum_number_of_balloons.py @@ -0,0 +1,20 @@ +class Solution: + def maxNumberOfBalloons(self, text: str) -> int: + s = set('balloon') + d = {} + + for i in text: + d[i] = d.get(i,0) + 1 + + #print(d) + ans = 0 + while True: + for i in 'balloon': + if i not in d or d[i] < 1: + return ans + else: + d[i] -= 1 + ans += 1 + + + return ans From 670a63a97f3551af3cf925f47d04ddb557cdbdce Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 14 Sep 2021 13:35:36 +0530 Subject: [PATCH 39/78] Create Day-14_Reverse_only_Letters.py --- .../Day-14_Reverse_only_Letters.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Leetcode_30day_challenge/September_Challenge_2021/Day-14_Reverse_only_Letters.py diff --git a/Leetcode_30day_challenge/September_Challenge_2021/Day-14_Reverse_only_Letters.py b/Leetcode_30day_challenge/September_Challenge_2021/Day-14_Reverse_only_Letters.py new file mode 100644 index 0000000..5bd7a8e --- /dev/null +++ b/Leetcode_30day_challenge/September_Challenge_2021/Day-14_Reverse_only_Letters.py @@ -0,0 +1,23 @@ +# Time: O(N) | Space: O(N) +class Solution: + def reverseOnlyLetters(self, s: str) -> str: + s = list(s) + d = set() + p1, p2 = 0, len(s)-1 + + for i in range(97, 123): + x = chr(i) + d.add(x) + d.add(x.upper()) + + while p1 < p2: + if s[p1] not in d: + p1 += 1 + if s[p2] not in d: + p2 -= 1 + if s[p1] in d and s[p2] in d: + s[p1], s[p2] = s[p2], s[p1] + p1 += 1 + p2 -= 1 + + return ''.join(s) From 9e3f52d6dd14b84219d707ff1e9ab0de0cbb7eae Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Thu, 16 Sep 2021 19:53:37 +0530 Subject: [PATCH 40/78] Create Bubble_Sorting.py --- Sorting_Algorithms/Bubble_Sorting.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 Sorting_Algorithms/Bubble_Sorting.py diff --git a/Sorting_Algorithms/Bubble_Sorting.py b/Sorting_Algorithms/Bubble_Sorting.py new file mode 100644 index 0000000..658924c --- /dev/null +++ b/Sorting_Algorithms/Bubble_Sorting.py @@ -0,0 +1,21 @@ +# Bubble Sorting Algorithm - Inplace and Stable sorting algorithm + +arr = [6,1,5,-9,2,12,4,0] +#arr = [1,2,3,4,5,6] +n = len(arr) +isSwapped = 0 +for i in range(1,n): + # This loop will move the max element of the left unsorted part to it's + # correct position. + for j in range(n-1): + if arr[j] > arr[j+1]: + # Swapping + arr[j+1], arr[j] = arr[j], arr[j+1] + isSwapped = 1 + print(f'After Iteration - {i}: {arr}') + # If not swapped, then the array is already sorted + if not isSwapped: + break + + +print(f'\nAfter Sorting: {arr}') From 43ef6ef0200e43b249b1dc83a2d57dfe7de49f09 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Thu, 16 Sep 2021 19:54:13 +0530 Subject: [PATCH 41/78] Add files via upload --- Sorting_Algorithms/Insertion_Sort.py | 16 ++++++++++++++++ Sorting_Algorithms/Selection_Sort.py | 14 ++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 Sorting_Algorithms/Insertion_Sort.py create mode 100644 Sorting_Algorithms/Selection_Sort.py diff --git a/Sorting_Algorithms/Insertion_Sort.py b/Sorting_Algorithms/Insertion_Sort.py new file mode 100644 index 0000000..bb23a3f --- /dev/null +++ b/Sorting_Algorithms/Insertion_Sort.py @@ -0,0 +1,16 @@ +# Insertion Sort - Inplace and Stable +arr = [2,4,1,5,0,65,-9] +n = len(arr) +print(f'Before Sorting: {arr}') +for i in range(1,n): + val, curr_idx = arr[i], i + # Moving all the elements of sorted part to their appropriate position + while curr_idx > 0 and arr[curr_idx - 1] > val: + arr[curr_idx] = arr[curr_idx-1] + curr_idx -= 1 + + arr[curr_idx] = val + + + +print(f'After Sorting: {arr}') diff --git a/Sorting_Algorithms/Selection_Sort.py b/Sorting_Algorithms/Selection_Sort.py new file mode 100644 index 0000000..69c1873 --- /dev/null +++ b/Sorting_Algorithms/Selection_Sort.py @@ -0,0 +1,14 @@ +# Selection Sort Algorithm - Inplace and Unstable +arr = [2,4,1,6,7,9] +n = len(arr) +print(f'Before Sorting: {arr}') +for i in range(n): + idx = i + for j in range(i+1, n): + if arr[j] < arr[idx]: + idx = j + # Swapping the numbers + arr[i], arr[idx] = arr[idx], arr[i] + +print(f'After Sorting: {arr}') + From d193a15f552cca5b9388d7e1be17173e0d91da27 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 18 Oct 2021 13:03:23 +0530 Subject: [PATCH 42/78] Create Remove_Linked_List_Elements.py --- Remove_Linked_List_Elements.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Remove_Linked_List_Elements.py diff --git a/Remove_Linked_List_Elements.py b/Remove_Linked_List_Elements.py new file mode 100644 index 0000000..5838ddb --- /dev/null +++ b/Remove_Linked_List_Elements.py @@ -0,0 +1,17 @@ +# URL: https://leetcode.com/problems/remove-linked-list-elements/ +# This method handles all the edge cases - All values are same, starting node value is val etc., + +class Solution: + def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: + dummy = ListNode(-1) + dummy.next = head + + t_head = dummy + while t_head.next: + if t_head.next.val == val: + t_head.next = t_head.next.next + else: + t_head = t_head.next + + return dummy.next + From b6266ba8bb43a5f1a5b23cc48fe98f187b9683a4 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 18 Oct 2021 13:04:15 +0530 Subject: [PATCH 43/78] Rename Remove_Linked_List_Elements.py to Linked_Lists/Remove_Linked_List_Elements.py --- .../Remove_Linked_List_Elements.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Remove_Linked_List_Elements.py => Linked_Lists/Remove_Linked_List_Elements.py (100%) diff --git a/Remove_Linked_List_Elements.py b/Linked_Lists/Remove_Linked_List_Elements.py similarity index 100% rename from Remove_Linked_List_Elements.py rename to Linked_Lists/Remove_Linked_List_Elements.py From c5918989549754d51b1842f9d5c8dd110cb84f94 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 18 Oct 2021 13:04:50 +0530 Subject: [PATCH 44/78] Update Remove_Linked_List_Elements.py --- Linked_Lists/Remove_Linked_List_Elements.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Linked_Lists/Remove_Linked_List_Elements.py b/Linked_Lists/Remove_Linked_List_Elements.py index 5838ddb..6c3b7a1 100644 --- a/Linked_Lists/Remove_Linked_List_Elements.py +++ b/Linked_Lists/Remove_Linked_List_Elements.py @@ -1,5 +1,6 @@ # URL: https://leetcode.com/problems/remove-linked-list-elements/ # This method handles all the edge cases - All values are same, starting node value is val etc., +# Time: O(N); Space: O(1) class Solution: def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: From 28b2a11c9916d43e87e19c10f99fce64f8f5d9d9 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 18 Oct 2021 13:29:25 +0530 Subject: [PATCH 45/78] Create Reverse_Linked_List.py --- Linked_Lists/Reverse_Linked_List.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Linked_Lists/Reverse_Linked_List.py diff --git a/Linked_Lists/Reverse_Linked_List.py b/Linked_Lists/Reverse_Linked_List.py new file mode 100644 index 0000000..ac223d5 --- /dev/null +++ b/Linked_Lists/Reverse_Linked_List.py @@ -0,0 +1,12 @@ +# Iterative | Time: O(N) & Space: O(1) + +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + prev = None + while head: + x = head.next + head.next = prev + prev = head + head = x + + return prev From c57efdbbd6fc39b16fffc780ac7a7e419cedb791 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 19 Oct 2021 14:02:01 +0530 Subject: [PATCH 46/78] Create Permutations.py --- Linked_Lists/Permutations.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Linked_Lists/Permutations.py diff --git a/Linked_Lists/Permutations.py b/Linked_Lists/Permutations.py new file mode 100644 index 0000000..2c99dd3 --- /dev/null +++ b/Linked_Lists/Permutations.py @@ -0,0 +1,17 @@ +class Solution: + def permute(self, arr: List[int]) -> List[List[int]]: + if len(arr) == 0: + return [] + elif len(arr) == 1: + return [arr] + else: + ans = [] + for i in range(len(arr)): + curr_elem = arr[i] + # Remaining elements before and after curr_elem as list + rem = arr[:i] + arr[i+1:] + # Generate permutations of the remaining + for el in self.permute(rem): + ans.append([curr_elem] + el) + + return ans From 1a07c65247d98d4fea9b2415b120d739cf153547 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 19 Oct 2021 15:10:21 +0530 Subject: [PATCH 47/78] Delete Array and transpose.py --- Array and transpose.py | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 Array and transpose.py diff --git a/Array and transpose.py b/Array and transpose.py deleted file mode 100644 index 3bc684a..0000000 --- a/Array and transpose.py +++ /dev/null @@ -1,10 +0,0 @@ -#Creating an array using Numpy - -n,m = input().split(' ') -n = int(n) -m = int(m) - -l = [] -for i in range(n): - for j in range(m): - From 47975cf3ad823b0d327a432b2b12dc42fc1aff3d Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 22 Oct 2021 14:35:53 +0530 Subject: [PATCH 48/78] Create Max_Area_of_Island.py --- .../Max_Area_of_Island.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Leetcode_30day_challenge/Max_Area_of_Island.py diff --git a/Leetcode_30day_challenge/Max_Area_of_Island.py b/Leetcode_30day_challenge/Max_Area_of_Island.py new file mode 100644 index 0000000..94c89dd --- /dev/null +++ b/Leetcode_30day_challenge/Max_Area_of_Island.py @@ -0,0 +1,32 @@ +# DFS Solution - O(M*N) Time and O(1) Space + +class Solution: + def maxAreaOfIsland(self, grid: List[List[int]]) -> int: + rows, cols = len(grid), len(grid[0]) + ans = 0 + def DFS(i, j, m): + # Exit condition + if i < 0 or j < 0 or i > rows-1 or j > cols-1 or m[i][j] == 0: + return 0 + # Mark the current node as visited + if m[i][j] == 1: + m[i][j] = 0 + + # N-4 Connectivity. Calling DFS on four neighbours + x = DFS(i-1,j,m) + y = DFS(i,j-1,m) + z = DFS(i+1,j,m) + t = DFS(i,j+1,m) + + sums = 1+x+y+z+t + + return sums + + # Calling DFS for every set Node + for i in range(rows): + for j in range(cols): + if grid[i][j] == 1: + curr = DFS(i,j,grid) + ans = max(ans, curr) + + return ans From bc1c0fe19f6cd46745fede847f7f69a9c396e356 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 22 Oct 2021 15:08:51 +0530 Subject: [PATCH 49/78] Create Binary_Tree_Level_Order_Traversal.py --- .../Binary_Tree_Level_Order_Traversal.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Leetcode_30day_challenge/Binary_Tree_Level_Order_Traversal.py diff --git a/Leetcode_30day_challenge/Binary_Tree_Level_Order_Traversal.py b/Leetcode_30day_challenge/Binary_Tree_Level_Order_Traversal.py new file mode 100644 index 0000000..78a3262 --- /dev/null +++ b/Leetcode_30day_challenge/Binary_Tree_Level_Order_Traversal.py @@ -0,0 +1,27 @@ +class Solution: + def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: + if not root: + return None + q = [root] + sep = '$' + ans = [] + q.append(sep) + res = [] + prev = -1 + while q: + temp = q.pop(0) + if prev == temp: + break + if temp != sep: + res.append(temp.val) + if temp.left: + q.append(temp.left) + if temp.right: + q.append(temp.right) + else: + ans.append(list(res)) + res = [] + q.append(sep) + prev = temp + + return ans From ae6abaa0de00fa5cba822a5c0034716dc48eda7d Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 23 Oct 2021 16:46:37 +0530 Subject: [PATCH 50/78] Create Print_paths_in_Binary_Tree.py --- .../Print_paths_in_Binary_Tree.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Leetcode_30day_challenge/Print_paths_in_Binary_Tree.py diff --git a/Leetcode_30day_challenge/Print_paths_in_Binary_Tree.py b/Leetcode_30day_challenge/Print_paths_in_Binary_Tree.py new file mode 100644 index 0000000..8301bc1 --- /dev/null +++ b/Leetcode_30day_challenge/Print_paths_in_Binary_Tree.py @@ -0,0 +1,19 @@ +# Function to print all the paths of a Binary Tree | O(N) Time & Space + +def get_paths(root, path, paths): + if root is None: + return + path.append(root.val) + get_paths(root.left, path, paths) + get_paths(root.right, path, paths) + + + if root.left is None and root.right is None: + paths.append(list(path)) + + # Pop here because, we're changing direction here. + if path: + path.pop() + + paths = [] + get_paths(root, [], paths) From 2836002f704cf1b3d01c3c1b4306e8e199803f9a Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 23 Oct 2021 17:00:10 +0530 Subject: [PATCH 51/78] Create Invert_Binary_Tree.py --- Leetcode_30day_challenge/Invert_Binary_Tree.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Leetcode_30day_challenge/Invert_Binary_Tree.py diff --git a/Leetcode_30day_challenge/Invert_Binary_Tree.py b/Leetcode_30day_challenge/Invert_Binary_Tree.py new file mode 100644 index 0000000..1372b4a --- /dev/null +++ b/Leetcode_30day_challenge/Invert_Binary_Tree.py @@ -0,0 +1,16 @@ +# Given the root of a binary tree, invert the tree, and return its root. + +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + def solve(root): + if root is None: + return + # Swapping the left and right nodes + root.left, root.right = root.right, root.left + + # Recur on both sides + solve(root.left) + solve(root.right) + + solve(root) + return root From e88eb19a79bab1aaf1ca3c6f3bf33f70b8f82940 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sun, 24 Oct 2021 15:15:21 +0530 Subject: [PATCH 52/78] Create Insert_into_Binary_Search_Tree.py --- .../Insert_into_Binary_Search_Tree.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py diff --git a/Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py b/Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py new file mode 100644 index 0000000..81a00b8 --- /dev/null +++ b/Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py @@ -0,0 +1,24 @@ +# Time: O(N) and Space: O(1) + +class Solution: + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if root is None: + root = TreeNode(val) + else: + t_root = root + while True: + if t_root.val < val: + if t_root.right: + t_root = t_root.right + else: + t_root.right = TreeNode(val) + break + else: + if t_root.left: + t_root = t_root.left + else: + t_root.left = TreeNode(val) + break + + return root + From 04b285ebe86d5bddd6e98ece1ba007f85e6eb164 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sun, 24 Oct 2021 15:23:39 +0530 Subject: [PATCH 53/78] Update Insert_into_Binary_Search_Tree.py --- .../Insert_into_Binary_Search_Tree.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py b/Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py index 81a00b8..7ba59ca 100644 --- a/Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py +++ b/Leetcode_30day_challenge/Insert_into_Binary_Search_Tree.py @@ -1,5 +1,5 @@ -# Time: O(N) and Space: O(1) - +""" Time: O(N) and Space: O(1) """ +# Iterative Solution class Solution: def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: if root is None: @@ -22,3 +22,14 @@ def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode return root + +# Recursive Solution +class Solution: + def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: + if root is None: + root = TreeNode(val) + elif root.val < val: + root.right = self.insertIntoBST(root.right, val) + else: + root.left = self.insertIntoBST(root.left, val) + return root From 53bca8d10e53277686a010035f8be01265512246 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 25 Oct 2021 10:38:25 +0530 Subject: [PATCH 54/78] Create Lowest_Common_Ancestor.py --- Leetcode_30day_challenge/Lowest_Common_Ancestor.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Leetcode_30day_challenge/Lowest_Common_Ancestor.py diff --git a/Leetcode_30day_challenge/Lowest_Common_Ancestor.py b/Leetcode_30day_challenge/Lowest_Common_Ancestor.py new file mode 100644 index 0000000..fcb2bbf --- /dev/null +++ b/Leetcode_30day_challenge/Lowest_Common_Ancestor.py @@ -0,0 +1,12 @@ +# Time: O(N) +class Solution: + def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': + def find_LCA(root, p, q): + if root.val < p.val and root.val < q.val: + return find_LCA(root.right, p, q) + elif root.val > p.val and root.val > q.val: + return find_LCA(root.left, p, q) + else: + return root + + return find_LCA(root, p, q) From 60dffdef425e89786d3a6941ecd925190c949a87 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 25 Oct 2021 11:26:23 +0530 Subject: [PATCH 55/78] Create Validate_BST.py --- Leetcode_30day_challenge/Validate_BST.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 Leetcode_30day_challenge/Validate_BST.py diff --git a/Leetcode_30day_challenge/Validate_BST.py b/Leetcode_30day_challenge/Validate_BST.py new file mode 100644 index 0000000..255788f --- /dev/null +++ b/Leetcode_30day_challenge/Validate_BST.py @@ -0,0 +1,11 @@ +class Solution: + def isValidBST(self, root: Optional[TreeNode]) -> bool: + MIN = float('-inf') + MAX = float('inf') + def solve(root, MIN, MAX): + if root is None: + return True + if root.val <= MIN or root.val >= MAX: + return False + return solve(root.left, MIN, root.val) and solve(root.right,root.val, MAX) + return solve(root, MIN, MAX) From 10ad1b5a65d96d7368a32eb282f0c8bbd8984148 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Tue, 16 Nov 2021 18:32:15 +0530 Subject: [PATCH 56/78] Create 3Sum.py --- 3Sum.py | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 3Sum.py diff --git a/3Sum.py b/3Sum.py new file mode 100644 index 0000000..14d0e4d --- /dev/null +++ b/3Sum.py @@ -0,0 +1,63 @@ +# Solution - 1 | O(N**2) Time and O(N) Space +class Solution: + def threeSum(self, nums): + nums.sort() + result = [] + for left in range(len(nums) - 2): # renamed this to left because this will always be the leftmost pointer in the triplet + if left > 0 and nums[left] == nums[left - 1]: # this step makes sure that we do not have any duplicates in our result output + continue + mid = left + 1 # renamed this to mid because this is the pointer that is between the left and right pointers + right = len(nums) - 1 + while mid < right: + curr_sum = nums[left] + nums[mid] + nums[right] + if curr_sum < 0: + mid += 1 + elif curr_sum > 0: + right -= 1 + else: + result.append([nums[left], nums[mid], nums[right]]) + while mid < right and nums[mid] == nums[mid + 1]: # Another conditional for not calculating duplicates + mid += 1 + while mid < right and nums[right] == nums[right - 1]: # Avoiding duplicates check + right -= 1 + mid += 1 + right -= 1 + return result + + + + + +# Solution - 2 | O(N**2) Time and O(N) Space +from collections import Counter +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + visited = set() + ans, n = set(), len(nums) + def two_sum(arr, target): + c = Counter(arr) + res = set() + for i in arr: + x = target - i + if x in c: + if x == i and c[x] > 1: + if (i,x) not in res and (x,i) not in res: + res.add((i, x)) + elif x != i: + if (i,x) not in res and (x,i) not in res: + res.add((i, x)) + return res + + + for i,v in enumerate(nums): + if v not in visited: + t_arr = nums[:i] + nums[i+1:] + ts = two_sum(t_arr, -v) + if ts: + for item in ts: + t = [v] + list(item) + t.sort() + ans.add(tuple(t)) + visited.add(v) + + return ans From 64d3e3c230b1c3cae0abb83788b4c567bfd696e2 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Thu, 18 Nov 2021 15:19:39 +0530 Subject: [PATCH 57/78] Create Spiral_Matrix_II.py --- Leetcode_30day_challenge/Spiral_Matrix_II.py | 38 ++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Leetcode_30day_challenge/Spiral_Matrix_II.py diff --git a/Leetcode_30day_challenge/Spiral_Matrix_II.py b/Leetcode_30day_challenge/Spiral_Matrix_II.py new file mode 100644 index 0000000..678e5ae --- /dev/null +++ b/Leetcode_30day_challenge/Spiral_Matrix_II.py @@ -0,0 +1,38 @@ +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + mat = [[0 for _ in range(n)] for _ in range(n)] + key = 1 + top, down, right, left = 0, n, n, 0 + + # Directions - 0 -> left to right; 1 -> top to down; + # 2 -> right to left; 3 -> down to top + d = 0 + while left <= right and top <= down: + if d == 0: # Move from Left to right + for i in range(left, right): + mat[top][i] = key + key += 1 + top += 1 + d = 1 + elif d == 1: # Move from Top to Down + for i in range(top, down): + mat[i][right-1] = key + key += 1 + right -= 1 + d = 2 + elif d == 2: # Move from right to left + for i in range(right-1, left-1,-1): + mat[down-1][i] = key + key += 1 + down -= 1 + d = 3 + elif d == 3: # Move from down to top + for i in range(down-1, top-1, -1): + mat[i][left] = key + key += 1 + left += 1 + d = 0 + + return mat + + From 9590fd9208520ba3935a0e5877b42341e33d0389 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 19 Nov 2021 14:54:43 +0530 Subject: [PATCH 58/78] Create Search_a_2D_Matrix_II.py --- .../Search_a_2D_Matrix_II.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Leetcode_30day_challenge/Search_a_2D_Matrix_II.py diff --git a/Leetcode_30day_challenge/Search_a_2D_Matrix_II.py b/Leetcode_30day_challenge/Search_a_2D_Matrix_II.py new file mode 100644 index 0000000..4ff79b7 --- /dev/null +++ b/Leetcode_30day_challenge/Search_a_2D_Matrix_II.py @@ -0,0 +1,35 @@ +# Solution - 1: For every row, apply Binary Search - Time: O(rows * log(cols)) +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + rows, cols = len(matrix), len(matrix[0]) + r,c = 0,0 + while r < rows and c < cols: + start, end = matrix[r][0], matrix[r][-1] + if target in range(start, end+1): + low, high = 0, cols-1 + while low <= high: + mid = (low + high) // 2 + if target == matrix[r][mid]: + return True + elif target < matrix[r][mid]: + high = mid-1 + else: + low = mid+1 + r += 1 + return False + + +# Solution - 2: Start from the Top-right element and move the row and col pointer appropriately - Time: O(rows + cols) +class Solution: + def searchMatrix(self, matrix: List[List[int]], target: int) -> bool: + rows, cols = len(matrix), len(matrix[0]) + r,c = 0, cols-1 + """Idea: Start from top right element and keep applying Binary Search.""" + while r < rows and c >= 0: + if target == matrix[r][c]: + return True + elif target < matrix[r][c]: + c -= 1 + else: + r += 1 + return False From 60e621f29cc38cf88a9b5a2db2c3ac6ab3c0c0d6 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 19 Nov 2021 15:14:14 +0530 Subject: [PATCH 59/78] Create Non_Overlapping_Intervals.py --- .../Non_Overlapping_Intervals.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Leetcode_30day_challenge/Non_Overlapping_Intervals.py diff --git a/Leetcode_30day_challenge/Non_Overlapping_Intervals.py b/Leetcode_30day_challenge/Non_Overlapping_Intervals.py new file mode 100644 index 0000000..70c0e40 --- /dev/null +++ b/Leetcode_30day_challenge/Non_Overlapping_Intervals.py @@ -0,0 +1,16 @@ +# Time: O(N) +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + # Sort the intervals by the second value + intervals.sort(key=lambda x: x[1]) + st = [intervals[0]] + ans = 0 + for i in intervals[1:]: + top = st[-1] + if i[0] < top[1]: # If there is an overlap, then that should't be considered + ans += 1 + else: + # If there is no overlap, then that item should be considered. Add it to the stack + st.append(i) + + return ans From 5176d0117742d1746930926e7d0f93fb62fb96b7 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 20 Nov 2021 16:53:20 +0530 Subject: [PATCH 60/78] Create Product_of_Array_Except_Self.py --- .../Product_of_Array_Except_Self.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Leetcode_30day_challenge/Product_of_Array_Except_Self.py diff --git a/Leetcode_30day_challenge/Product_of_Array_Except_Self.py b/Leetcode_30day_challenge/Product_of_Array_Except_Self.py new file mode 100644 index 0000000..b0dda88 --- /dev/null +++ b/Leetcode_30day_challenge/Product_of_Array_Except_Self.py @@ -0,0 +1,22 @@ +# Solution - 1: Time: O(N) and Space: O(N) +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + pre, suff = [nums[0]], [nums[-1]] + n = len(nums) + # Calculating the Prefix Product + for i in range(1, n): + pre.append(pre[-1] * nums[i]) + + # Calculating the Suffix Product + for j in range(n-2,-1,-1): + suff.append(suff[-1] * nums[j]) + suff.reverse() + + ans = [0] * n + ans[0] = suff[1] + for i in range(1, n-1): + ans[i] = pre[i-1] * suff[i+1] + + ans[n-1] = pre[n-2] + + return ans From 6f4e50857ab8793630b068b2f4103911cc82fbe3 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 20 Nov 2021 17:03:50 +0530 Subject: [PATCH 61/78] Update Product_of_Array_Except_Self.py --- .../Product_of_Array_Except_Self.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/Leetcode_30day_challenge/Product_of_Array_Except_Self.py b/Leetcode_30day_challenge/Product_of_Array_Except_Self.py index b0dda88..c721e5d 100644 --- a/Leetcode_30day_challenge/Product_of_Array_Except_Self.py +++ b/Leetcode_30day_challenge/Product_of_Array_Except_Self.py @@ -20,3 +20,28 @@ def productExceptSelf(self, nums: List[int]) -> List[int]: ans[n-1] = pre[n-2] return ans + +# Solution - 2: Time: O(N) Time and O(1) Space +class Solution: + def productExceptSelf(self, nums: List[int]) -> List[int]: + n = len(nums) + c = nums.count(0) + prod = 1 + ans = [0]*n + zero_idx = None + # Calculating the Product + for i,v in enumerate(nums): + if v != 0: + prod *= v + else: + zero_idx = i + + if c > 1: + return ans + elif c == 0: + for i in range(n): + ans[i] = prod//nums[i] + else: + ans[zero_idx] = prod + + return ans From 6dbb29eb68838847486d8c3e3915208ef52e2d12 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 20 Nov 2021 18:35:03 +0530 Subject: [PATCH 62/78] Create Subarray_Sum_Equals_K.py --- .../Subarray_Sum_Equals_K.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 Leetcode_30day_challenge/Subarray_Sum_Equals_K.py diff --git a/Leetcode_30day_challenge/Subarray_Sum_Equals_K.py b/Leetcode_30day_challenge/Subarray_Sum_Equals_K.py new file mode 100644 index 0000000..bd53c57 --- /dev/null +++ b/Leetcode_30day_challenge/Subarray_Sum_Equals_K.py @@ -0,0 +1,20 @@ +class Solution: + def subarraySum(self, nums: List[int], k: int) -> int: + ans, pre = 0, 0 + d = {} + for i in nums: + pre += i + + if pre == k: + ans += 1 + + if pre - k in d: + ans += d[pre-k] + + if pre not in d: + d[pre] = 1 + else: + d[pre] += 1 + + + return ans From c4eef3745fff0b1da7a9cc6b47cfe465bb8680a7 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 20 Nov 2021 19:16:12 +0530 Subject: [PATCH 63/78] Create Increasing_Triplet_Subsequence.py --- .../Increasing_Triplet_Subsequence.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py diff --git a/Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py b/Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py new file mode 100644 index 0000000..a2037fa --- /dev/null +++ b/Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py @@ -0,0 +1,15 @@ +# Solution - 1: Time: O(N) +class Solution: + def increasingTriplet(self, nums: List[int]) -> bool: + # Set both the first and the second values as MAX value + first = second = float('inf') + + for i in nums: + if i <= first: # This will ensure that we always store the minimum value in first + first = i + elif i <= second: # This will ensure that we always store a value greater than first + second = i + else: # If we have reached here, we have seen a value greater than first and second. So return True + return True + + return False From 0b9d38fe9377aeaaae3a5ba00b12f13ce5c4f476 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 20 Nov 2021 19:18:06 +0530 Subject: [PATCH 64/78] Update Increasing_Triplet_Subsequence.py --- Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py b/Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py index a2037fa..81ed89e 100644 --- a/Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py +++ b/Leetcode_30day_challenge/Increasing_Triplet_Subsequence.py @@ -1,4 +1,5 @@ # Solution - 1: Time: O(N) +# This will only check for existence of a Valid Triplet. THIS WILL NOT GIVE WHAT THAT TRIPLET IS. class Solution: def increasingTriplet(self, nums: List[int]) -> bool: # Set both the first and the second values as MAX value From bbead9b4790aae4a8455ad342231f880b5e275c0 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sun, 21 Nov 2021 13:19:52 +0530 Subject: [PATCH 65/78] Create Longest_Palindrome.py --- Leetcode_30day_challenge/Longest_Palindrome.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Leetcode_30day_challenge/Longest_Palindrome.py diff --git a/Leetcode_30day_challenge/Longest_Palindrome.py b/Leetcode_30day_challenge/Longest_Palindrome.py new file mode 100644 index 0000000..3f18d2c --- /dev/null +++ b/Leetcode_30day_challenge/Longest_Palindrome.py @@ -0,0 +1,16 @@ +# Solution - 1 | Time: O(N) and Space: O(N) +from collections import Counter +class Solution: + def longestPalindrome(self, s: str) -> int: + c = Counter(s) + ans = 0 + + for i in c.values(): + if ans % 2 == 1: # If odd + if i % 2 == 0: # If i is even, then it can be added + ans += i + else: # If i is odd, then (odd-1) which is even should be added + ans += i-1 + else: #If even, either odd or even can be added. + ans += i + return ans From 1855074a5634ea977997f347ff9e3f465c0d3949 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 22 Nov 2021 13:56:00 +0530 Subject: [PATCH 66/78] Create Partition_Labels.py --- Leetcode_30day_challenge/Partition_Labels.py | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 Leetcode_30day_challenge/Partition_Labels.py diff --git a/Leetcode_30day_challenge/Partition_Labels.py b/Leetcode_30day_challenge/Partition_Labels.py new file mode 100644 index 0000000..7fd10ff --- /dev/null +++ b/Leetcode_30day_challenge/Partition_Labels.py @@ -0,0 +1,28 @@ +# Time: O(N) and Space: O(N) + +class Solution: + def partitionLabels(self, s: str) -> List[int]: + d = {} + # Store the first and last index of each character. + for i,v in enumerate(s): + if v not in d: + d[v] = [i,i] + else: + d[v][1] = i + + + + # Now the problem is same as merge intervals. + temp = list(d.values()) + st = [temp[0]] + for item in temp[1:]: + top = st[-1] + if item[0] <= top[1]: + top[1] = max(top[1], item[1]) + + else: + st.append(item) + + # Calculating the answer + ans = [x[1]-x[0]+1 for x in st] + return ans From 6a8e3fa554db4ea5378fe83ebe30042a0b6ac0fa Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 26 Nov 2021 12:53:27 +0530 Subject: [PATCH 67/78] Create Intersection of Two Linked Lists.py --- .../Intersection of Two Linked Lists.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Linked_Lists/Intersection of Two Linked Lists.py diff --git a/Linked_Lists/Intersection of Two Linked Lists.py b/Linked_Lists/Intersection of Two Linked Lists.py new file mode 100644 index 0000000..e8ab85b --- /dev/null +++ b/Linked_Lists/Intersection of Two Linked Lists.py @@ -0,0 +1,17 @@ +# Solution - 1: O(N) Space using a Set + +# Solution - 2: O(1) Space +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: + p1,p2 = headA, headB + while p1 != p2: + if p1: + p1 = p1.next + else: + p1 = headB + if p2: + p2 = p2.next + else: + p2 = headA + + return p1 From 5469431b1810de3bfcea2dc4cebf4ac1f166873b Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 26 Nov 2021 12:54:22 +0530 Subject: [PATCH 68/78] Create Remove Duplicates from Sorted List II.py --- .../Remove Duplicates from Sorted List II.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 Linked_Lists/Remove Duplicates from Sorted List II.py diff --git a/Linked_Lists/Remove Duplicates from Sorted List II.py b/Linked_Lists/Remove Duplicates from Sorted List II.py new file mode 100644 index 0000000..da8364f --- /dev/null +++ b/Linked_Lists/Remove Duplicates from Sorted List II.py @@ -0,0 +1,18 @@ +# https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ +class Solution: + def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]: + dummy = ListNode(0) + prev = dummy + dummy.next = head + + while head and head.next: + if head.val == head.next.val: + while head and head.next and head.val == head.next.val: + head.next = head.next.next + head = head.next + prev.next = head + else: + head = head.next + prev = prev.next + + return dummy.next From 8613f074d267e85e79909c22c89f123f29f47a91 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 26 Nov 2021 12:55:44 +0530 Subject: [PATCH 69/78] Create Add_Two_Numbers.py --- Linked_Lists/Add_Two_Numbers.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Linked_Lists/Add_Two_Numbers.py diff --git a/Linked_Lists/Add_Two_Numbers.py b/Linked_Lists/Add_Two_Numbers.py new file mode 100644 index 0000000..85b408d --- /dev/null +++ b/Linked_Lists/Add_Two_Numbers.py @@ -0,0 +1,19 @@ +# Solution - 1: O(N + M) Time and O(1) Space +class Solution: + def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]: + carry = 0 + dummy = ListNode(0) + t_head = dummy + while l1 or l2 or carry: + if l1: + carry += l1.val + l1 = l1.next + if l2: + carry += l2.val + l2 = l2.next + t_head.next = ListNode(carry % 10) + carry = carry//10 + t_head = t_head.next + + return dummy.next + From 6801df71d0d99d2f50c917430fc9aadc8089aea3 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 27 Nov 2021 13:24:27 +0530 Subject: [PATCH 70/78] Create Swap_Nodes_in_Pairs.py --- Linked_Lists/Swap_Nodes_in_Pairs.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Linked_Lists/Swap_Nodes_in_Pairs.py diff --git a/Linked_Lists/Swap_Nodes_in_Pairs.py b/Linked_Lists/Swap_Nodes_in_Pairs.py new file mode 100644 index 0000000..e646e41 --- /dev/null +++ b/Linked_Lists/Swap_Nodes_in_Pairs.py @@ -0,0 +1,23 @@ +# Solution - 1: Time: O(N) and Space: O(1) +class Solution: + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: + # Base condition + if not head or not head.next: + return head + t_head = head.next + p1, p2 = head, head.next + prev_p1 = None + while p1 and p2: + temp = p2 + p1.next = temp.next + temp.next = p1 + + if prev_p1: + prev_p1.next = p2 + prev_p1 = p1 + + p1 = p1.next + if p1: + p2 = p1.next + + return t_head From 8dfbf1f844b387eaa712d8545e797a0dcf5fd149 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 27 Nov 2021 13:26:12 +0530 Subject: [PATCH 71/78] Update Swap_Nodes_in_Pairs.py --- Linked_Lists/Swap_Nodes_in_Pairs.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/Linked_Lists/Swap_Nodes_in_Pairs.py b/Linked_Lists/Swap_Nodes_in_Pairs.py index e646e41..3ace99f 100644 --- a/Linked_Lists/Swap_Nodes_in_Pairs.py +++ b/Linked_Lists/Swap_Nodes_in_Pairs.py @@ -1,4 +1,4 @@ -# Solution - 1: Time: O(N) and Space: O(1) +# Solution - 1: Swapping the Nodes | Time: O(N) and Space: O(1) class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: # Base condition @@ -21,3 +21,25 @@ def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: p2 = p1.next return t_head + + +# Solution - 2: Swapping the Values | Time: O(N) and Space: O(1) +class Solution: + def swapPairs(self, head: ListNode) -> ListNode: + if not head or not head.next: + return head + p1, p2 = head, head.next + t_head = head + + while p1 and p2: + temp = p2.val + p2.val = p1.val + p1.val = temp + + if p2.next and p2.next.next: + p1 = p2.next + p2 = p1.next + else: + break + + return head From ec908ad0f819706de2441ac047efcc2c6ea71c2a Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sat, 27 Nov 2021 13:34:24 +0530 Subject: [PATCH 72/78] Update Swap_Nodes_in_Pairs.py --- Linked_Lists/Swap_Nodes_in_Pairs.py | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Linked_Lists/Swap_Nodes_in_Pairs.py b/Linked_Lists/Swap_Nodes_in_Pairs.py index 3ace99f..6e4355c 100644 --- a/Linked_Lists/Swap_Nodes_in_Pairs.py +++ b/Linked_Lists/Swap_Nodes_in_Pairs.py @@ -1,4 +1,4 @@ -# Solution - 1: Swapping the Nodes | Time: O(N) and Space: O(1) +# Solution - 1: Swapping the Nodes (Iterative) | Time: O(N) and Space: O(1) class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: # Base condition @@ -22,8 +22,19 @@ def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: return t_head +# Solution - 1 Swapping the Nodes (Recursive) | Time: O(N) and Space: O(N) +class Solution: + def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: + if head and head.next: + temp = head.next + head.next = self.swapPairs(temp.next) + temp.next = head + return temp + + return head -# Solution - 2: Swapping the Values | Time: O(N) and Space: O(1) + + # Solution - 2: Swapping the Values | Time: O(N) and Space: O(1) class Solution: def swapPairs(self, head: ListNode) -> ListNode: if not head or not head.next: From acbf861c9cc4676fbd59bea6da6db3b6a034a793 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Sun, 28 Nov 2021 12:06:11 +0530 Subject: [PATCH 73/78] Create Reverse_Nodes_in_K_group.py --- Linked_Lists/Reverse_Nodes_in_K_group.py | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Linked_Lists/Reverse_Nodes_in_K_group.py diff --git a/Linked_Lists/Reverse_Nodes_in_K_group.py b/Linked_Lists/Reverse_Nodes_in_K_group.py new file mode 100644 index 0000000..af37a9d --- /dev/null +++ b/Linked_Lists/Reverse_Nodes_in_K_group.py @@ -0,0 +1,35 @@ +""" +Use a dummy head, and + +l, r : define reversing range + +pre, cur : used in reversing, standard reverse linked linked list method + +jump : used to connect last node in previous k-group to first node in following k-group +""" +class Solution: + def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: + # Dummy node initialization + dummy = jump = ListNode(-1) + dummy.next = l = r = head + + while True: + count = 0 + # Moving k positions + while r and count < k: + count += 1 + r = r.next + # If count == k, then reverse the segment [l, r] + if count == k: + pre, cur = r, l + for _ in range(k): + temp = cur.next + cur.next = pre + pre = cur + cur = temp + # Joining the current k-group with the previous k-group + jump.next = pre + jump = l + l = r + else: + return dummy.next From 915d4cfd29cc94e7de80104631e7f442537bbee0 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Mon, 6 Dec 2021 14:31:28 +0530 Subject: [PATCH 74/78] Create Kth_largest_element_in_array.py --- Heaps/Kth_largest_element_in_array.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Heaps/Kth_largest_element_in_array.py diff --git a/Heaps/Kth_largest_element_in_array.py b/Heaps/Kth_largest_element_in_array.py new file mode 100644 index 0000000..cb4c5eb --- /dev/null +++ b/Heaps/Kth_largest_element_in_array.py @@ -0,0 +1,24 @@ +# Solution - 1: Using List & Sort | Time: O(NlogN) +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + nums.sort(reverse=True) + return nums[k-1] + + +# Solution - 2: Using Heap | Time: O(N) to build heap + O(KlogN) to find the Kth largest item +import heapq +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + # To put into Max Heap + nums = [-x for x in nums] + heapq.heapify(nums) + while k: + ans = heapq.heappop(nums) + k -= 1 + + return -ans + + + + + From 1f25193bfffb182463ad4daffad9039ee3445465 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Fri, 17 Dec 2021 19:24:20 +0530 Subject: [PATCH 75/78] Create Merge_Sort.py --- Sorting_Algorithms/Merge_Sort.py | 44 ++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Sorting_Algorithms/Merge_Sort.py diff --git a/Sorting_Algorithms/Merge_Sort.py b/Sorting_Algorithms/Merge_Sort.py new file mode 100644 index 0000000..c868b9d --- /dev/null +++ b/Sorting_Algorithms/Merge_Sort.py @@ -0,0 +1,44 @@ +# Merge Sorting Algorithm +arr = [2,4,1,-9,5,32,-55] + +def merge(l: list, r: list, arr: list) -> None: + i,j,k= 0,0,0 + while i Date: Fri, 17 Dec 2021 19:54:26 +0530 Subject: [PATCH 76/78] Create Quick_Sort.py --- Sorting_Algorithms/Quick_Sort.py | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 Sorting_Algorithms/Quick_Sort.py diff --git a/Sorting_Algorithms/Quick_Sort.py b/Sorting_Algorithms/Quick_Sort.py new file mode 100644 index 0000000..4d46d2d --- /dev/null +++ b/Sorting_Algorithms/Quick_Sort.py @@ -0,0 +1,41 @@ +# QuickSort - Pythonic +def quicksort(arr): + if len(arr) <= 1: + return arr + pivot = arr[len(arr) // 2] + left = [x for x in arr if x < pivot] + middle = [x for x in arr if x == pivot] + right = [x for x in arr if x > pivot] + return quicksort(left) + middle + quicksort(right) + +#print(quicksort([3,6,8,10,1,2,1])) + + +# QuickSort - Normal +def partition(start, end, arr): + """Returns the partition index.""" + # Last element chosen as Pivot + pivot = arr[end] + p_index = start + for i in range(start, end): #Places pivot in correct position + if arr[i] <= pivot: + # Swap arr[i] with arr[p_index] + arr[i], arr[p_index] = arr[p_index], arr[i] + p_index += 1 + + # Swapping the pivot element with element at p_index + arr[p_index], arr[end] = arr[end], arr[p_index] + return p_index + + +def quicksort(start, end, arr): + if start < end: + p_index = partition(start, end, arr) + quicksort(start, p_index-1, arr) + quicksort(p_index+1, end, arr) + + +arr = [1,5,-9,6,-66,-70,2,45] +quicksort(0,len(arr)-1,arr) +print(arr) + From 64c2ac1fc7cb3db916245a7e4cdb957fb2446875 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Thu, 15 May 2025 23:18:03 +0530 Subject: [PATCH 77/78] Update Day16_Validate_IP_Addresses.py --- .../June_Challenge_2020/Day16_Validate_IP_Addresses.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Leetcode_30day_challenge/June_Challenge_2020/Day16_Validate_IP_Addresses.py b/Leetcode_30day_challenge/June_Challenge_2020/Day16_Validate_IP_Addresses.py index 2922570..b7b41e0 100644 --- a/Leetcode_30day_challenge/June_Challenge_2020/Day16_Validate_IP_Addresses.py +++ b/Leetcode_30day_challenge/June_Challenge_2020/Day16_Validate_IP_Addresses.py @@ -8,7 +8,7 @@ def isIPv4(s): def isIPv6(s): if len(s) > 4: - return Fase + return False try: return int(s, 16) >= 0 and s[0] != '-' except: From 5339fccade2ffd3a8e0240e5158e347813656bb3 Mon Sep 17 00:00:00 2001 From: Ram Babu Date: Wed, 28 May 2025 14:36:24 +0530 Subject: [PATCH 78/78] inital commit --- Get_max_presentations.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Get_max_presentations.py diff --git a/Get_max_presentations.py b/Get_max_presentations.py new file mode 100644 index 0000000..0839280 --- /dev/null +++ b/Get_max_presentations.py @@ -0,0 +1,38 @@ +""" +This is an Activity Selection problem where we want to find the maximum number of non-overlapping presentations that can be attended. +Use Greedy approach to solve this problem. + - Sort the timings in the increasing order of their end times. + - Iterate through the sorted list and select presentations that start after or at the end of the last selected presentation. + - Count the number of such presentations. + - Return the count as the result. +""" + +def get_max_presentations(start_times, end_times): + """ + Calculates the maximum number of non-overlapping presentations that can be attended. + + Args: + start_times (list of int): List of start times for each presentation. + end_times (list of int): List of end times for each presentation. + + Returns: + int: The maximum number of non-overlapping presentations. + """ + # Sort the presentations by their end times (greedy approach) + intervals = sorted(zip(start_times, end_times), key=lambda x: x[1]) + count = 0 + prev_end = 0 + + # Iterate through each presentation + for start, end in intervals: + # If the current presentation starts after or at the end of the last selected one + if prev_end <= start: + count += 1 + prev_end = end # Update the end time to the current presentation's end + + return count + +# Example usage +start = [1, 1, 2, 3] +end = [2, 3, 3, 4] +print(get_max_presentations(start, end)) \ No newline at end of file