From 040a48f814347d9e1aeb04f27a2fd51a877c1119 Mon Sep 17 00:00:00 2001 From: 27Anurag <56363215+27Anurag@users.noreply.github.com> Date: Mon, 14 Sep 2020 04:03:37 +0530 Subject: [PATCH 001/204] Added the solution for gray code problem Look into this pr, this is my first pr, please guide me accordingly. --- .DS_Store | Bin 0 -> 8196 bytes LeetCode/0089_Gray_code.py | 11 +++++++++++ 2 files changed, 11 insertions(+) create mode 100644 .DS_Store create mode 100644 LeetCode/0089_Gray_code.py diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..4ddc034a1a008d47dd805c4bb29823601395dd57 GIT binary patch literal 8196 zcmeHMPfrs;6n|3?wji+lZ`4C0G0{Lw2?}0}rPL_VgoY&u0fgOlC>yssb$1H_Vj3@g z1C8E{U%E*_M_Cj*W>k&CYN7{>*#x+stg=763@9lp6(z z0f2%RN3|WhLmJofE7T%^qzjRtKUn!uEz1hUkfjtz1|$QL0m*=5Kr-;JFo4f&-jpMr z`$8*w$$(_wzhr=)4{^LWCIc)B^p6hg{1O1M8O46XvC0RC@c@$nmIa~)8xgLE!j%Li z1`+Nkj|Xg)H% zowd3GOQ#Ks87Nb}eR}!JeDYzkUY|QwU)-p9H$YyaE3{VP!UmMUsE;1`61J$z;b}F8 z1M?JEO(sWL)#W1&8wG9y#g7M5z#s?I*m8@(nm-yv%XGa&;wy_ue#`pH3%HX-ttJ7q&FN&?WMe9=4RH{UFt3H2w8_&R))EzXEJ-SM!UG|NB3x9+FoZEk!LVdfpZrWX18J@u_cnk00GyH(x@P~Ae0dkfMlM!;6Opqj* zBva%jnI^NsJ5sr&XDXotk|o5@Ev?^8Ef)^6sohUY@2dMLG*|78I?k?sPbGMIp}96S z$F`WAM;%{}eExHmWRnauo`EJ2GREuw>qo!;Z+v1hqGUia&@cu_b6QKMFkIya#=*$E z){f(~h8J(#t}M`Z!Okzo5&d!;vHFK0j^k*`eUbr|1)>C-d=cQ&AUnxGLmBuBYmPGn literal 0 HcmV?d00001 diff --git a/LeetCode/0089_Gray_code.py b/LeetCode/0089_Gray_code.py new file mode 100644 index 0000000..ac696d1 --- /dev/null +++ b/LeetCode/0089_Gray_code.py @@ -0,0 +1,11 @@ +def gray(a): + return ((a)^(a>>1)) + +class Solution: + def grayCode(self, n: int) -> List[int]: + ans=[] + for i in range(pow(2,n)): + ans.append(gray(i)) + return ans + + From 1865b3a65e126b253f78a746e04cdb2a3fc5c96f Mon Sep 17 00:00:00 2001 From: devanshi-katyal <60283765+devanshi-katyal@users.noreply.github.com> Date: Fri, 2 Oct 2020 01:19:52 +0530 Subject: [PATCH 002/204] Create 0041_findingLeastPositiveNumber.py Description of the Problem Given an unsorted integer array, find the smallest missing positive integer. Link To The LeetCode Problem [LeetCode](https://leetcode.com/problems/first-missing-positive/) --- LeetCode/0041_findingLeastPositiveNumber.py | 26 +++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 LeetCode/0041_findingLeastPositiveNumber.py diff --git a/LeetCode/0041_findingLeastPositiveNumber.py b/LeetCode/0041_findingLeastPositiveNumber.py new file mode 100644 index 0000000..699b76c --- /dev/null +++ b/LeetCode/0041_findingLeastPositiveNumber.py @@ -0,0 +1,26 @@ +# finding least positive number +# Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, +# find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. +# code contributed by devanshi katyal +# space complexity:O(1) +# time complexity:O(n) + + +def MainFunction(arr, size): + for i in range(size): + if (abs(arr[i]) - 1 < size and arr[abs(arr[i]) - 1] > 0): + arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1] + for i in range(size): + if (arr[i] > 0): + return i + 1 + return size + 1 + +def findpositive(arr, size): + j= 0 + for i in range(size): + if (arr[i] <= 0): + arr[i], arr[j] = arr[j], arr[i] + j += 1 + return MainFunction(arr[j:], size - j) +arr = list(map(int, input().split(" "))) +print("the smallest missing number", findpositive(arr, len(arr))) From 9e6a1fad978c88a8aa15b2a443465d2e6320eda7 Mon Sep 17 00:00:00 2001 From: Austin Ewens Date: Thu, 1 Oct 2020 19:53:59 +0000 Subject: [PATCH 003/204] First proposed solution to problem 0032 --- LeetCode/0032_Longest_Valid_Parentheses.py | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 LeetCode/0032_Longest_Valid_Parentheses.py diff --git a/LeetCode/0032_Longest_Valid_Parentheses.py b/LeetCode/0032_Longest_Valid_Parentheses.py new file mode 100644 index 0000000..3ba791b --- /dev/null +++ b/LeetCode/0032_Longest_Valid_Parentheses.py @@ -0,0 +1,56 @@ +class Solution: + def longestValidParentheses(self, s: str) -> int: + state = 0 + tokens = list() + for paren in s: + if paren == "(": + state = state - 1 + tokens.append(-1) + + elif paren == ")" and state < 0: + state = state + 1 + tokens.append(1) + + else: + tokens.append(0) + + token_sets = [list()] + for token in tokens: + if token == 0: + token_sets.append(list()) + continue + + token_sets[-1].append(token) + + valid_sets = [0] + for token_set in token_sets: + for offset in range(len(token_set)-1): + for nudge in range(offset+1): + offset_front = offset - nudge + offset_back = len(token_set) - nudge + offset_tokens = token_set[:][offset_front:offset_back] + + invalid = True + while invalid: + check = 0 + front = offset_tokens[0] + if front in [1, 0]: + offset_tokens = offset_tokens[1:] + check = check + 1 + + back = offset_tokens[-1] + if back in [-1, 0]: + offset_tokens = offset_tokens[:-1] + check = check + 1 + + if check == 0: + invalid = False + + if len(offset_tokens) < 2: + break + + if not invalid and sum(offset_tokens) == 0: + valid_sets.append(len(offset_tokens)) + continue + + return max(valid_sets) From 7e4ffd5b2f4c750d0fb2c17a484da55186625baf Mon Sep 17 00:00:00 2001 From: DAIIVIIK Date: Fri, 2 Oct 2020 17:16:50 +0530 Subject: [PATCH 004/204] added_0933 --- LeetCode/0933_Number_of_recent_calls.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/0933_Number_of_recent_calls.py diff --git a/LeetCode/0933_Number_of_recent_calls.py b/LeetCode/0933_Number_of_recent_calls.py new file mode 100644 index 0000000..9d3ef76 --- /dev/null +++ b/LeetCode/0933_Number_of_recent_calls.py @@ -0,0 +1,11 @@ +#python3 +class RecentCounter: + + def __init__(self): + self.q = collections.deque() + + def ping(self, t: int) -> int: + self.q.append(t) + while self.q[0] < t - 3000: + self.q.popleft() + return len(self.q) From 3a36b2a17db1fc78c669b6eb8dfa09883090d6ab Mon Sep 17 00:00:00 2001 From: tanaykulkarni Date: Fri, 2 Oct 2020 04:48:43 -0700 Subject: [PATCH 005/204] added solution for issue 0777 --- LeetCode/0777_Swap_Adjacent_in_LR String.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/0777_Swap_Adjacent_in_LR String.py diff --git a/LeetCode/0777_Swap_Adjacent_in_LR String.py b/LeetCode/0777_Swap_Adjacent_in_LR String.py new file mode 100644 index 0000000..b638c56 --- /dev/null +++ b/LeetCode/0777_Swap_Adjacent_in_LR String.py @@ -0,0 +1,10 @@ +if start.replace('X', '') != end.replace('X', ''): + return False + + ctr = collections.Counter() + for s, e in zip(start, end): + ctr[s] += 1 + ctr[e] -= 1 + if ctr['L'] > 0 or ctr['R'] < 0: + return False + return True \ No newline at end of file From 4eecdaae5f4841e59932a483ed2fe17081b866bb Mon Sep 17 00:00:00 2001 From: tanaykulkarni Date: Fri, 2 Oct 2020 04:49:30 -0700 Subject: [PATCH 006/204] deleted 0777 --- LeetCode/0777_Swap_Adjacent_in_LR String.py | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 LeetCode/0777_Swap_Adjacent_in_LR String.py diff --git a/LeetCode/0777_Swap_Adjacent_in_LR String.py b/LeetCode/0777_Swap_Adjacent_in_LR String.py deleted file mode 100644 index b638c56..0000000 --- a/LeetCode/0777_Swap_Adjacent_in_LR String.py +++ /dev/null @@ -1,10 +0,0 @@ -if start.replace('X', '') != end.replace('X', ''): - return False - - ctr = collections.Counter() - for s, e in zip(start, end): - ctr[s] += 1 - ctr[e] -= 1 - if ctr['L'] > 0 or ctr['R'] < 0: - return False - return True \ No newline at end of file From 7634a1af4ef998b70a35e82a43a26747979e92d5 Mon Sep 17 00:00:00 2001 From: tanaykulkarni Date: Fri, 2 Oct 2020 04:53:27 -0700 Subject: [PATCH 007/204] added solution for issue 0777 --- LeetCode/0777_Swap_Adjacent_in_LR String.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0777_Swap_Adjacent_in_LR String.py diff --git a/LeetCode/0777_Swap_Adjacent_in_LR String.py b/LeetCode/0777_Swap_Adjacent_in_LR String.py new file mode 100644 index 0000000..628bc38 --- /dev/null +++ b/LeetCode/0777_Swap_Adjacent_in_LR String.py @@ -0,0 +1,15 @@ +# L can move left util L meets R. And R can move right util R meets L !! X is something that does not really need attention + +class Solution: + def canTransform(self, start: str, end: str) -> bool: + + if start.replace('X', '') != end.replace('X', ''): + return False + + m = collections.Counter() + for s, e in zip(start, end): + m[s] += 1 + m[e] -= 1 + if m['L'] > 0 or m['R'] < 0: + return False + return True \ No newline at end of file From 70177b34673aebc955632287a907f958d6be9b66 Mon Sep 17 00:00:00 2001 From: tanaykulkarni Date: Fri, 2 Oct 2020 05:03:45 -0700 Subject: [PATCH 008/204] added solution for issue 0933 --- LeetCode/0933_Number_of_Recent_Calls.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/0933_Number_of_Recent_Calls.py diff --git a/LeetCode/0933_Number_of_Recent_Calls.py b/LeetCode/0933_Number_of_Recent_Calls.py new file mode 100644 index 0000000..fe0ac67 --- /dev/null +++ b/LeetCode/0933_Number_of_Recent_Calls.py @@ -0,0 +1,10 @@ +class RecentCounter: + + def __init__(self): + self.p = [] + + def ping(self, t: int) -> int: + self.p.append(t) + while self.p[0] < t - 3000: + self.p.pop(0) + return len(self.p) \ No newline at end of file From e28f262bbd7c504f3855f204cef0d59b650e179a Mon Sep 17 00:00:00 2001 From: tanaykulkarni Date: Fri, 2 Oct 2020 05:18:30 -0700 Subject: [PATCH 009/204] added solution for issue 1227 --- LeetCode/1227_Airplane_Seat_Assignment_Probability.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 LeetCode/1227_Airplane_Seat_Assignment_Probability.py diff --git a/LeetCode/1227_Airplane_Seat_Assignment_Probability.py b/LeetCode/1227_Airplane_Seat_Assignment_Probability.py new file mode 100644 index 0000000..b0164c4 --- /dev/null +++ b/LeetCode/1227_Airplane_Seat_Assignment_Probability.py @@ -0,0 +1,6 @@ +class Solution: + def nthPersonGetsNthSeat(self, n: int) -> float: + if n == 1: + return 1.0 + else: + return 0.5 \ No newline at end of file From f00b40c20e8a9f50e5f1d98f77237dd17498f9b9 Mon Sep 17 00:00:00 2001 From: tanaykulkarni Date: Fri, 2 Oct 2020 05:23:03 -0700 Subject: [PATCH 010/204] added solution for issue 0111 --- LeetCode/0111_Minimum_Depth_of_Binary_Tree.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0111_Minimum_Depth_of_Binary_Tree.py diff --git a/LeetCode/0111_Minimum_Depth_of_Binary_Tree.py b/LeetCode/0111_Minimum_Depth_of_Binary_Tree.py new file mode 100644 index 0000000..680208c --- /dev/null +++ b/LeetCode/0111_Minimum_Depth_of_Binary_Tree.py @@ -0,0 +1,15 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Solution: + def minDepth(self, root: TreeNode) -> int: + if not root: + return 0 + if not root.left or not root.right: + return max(self.minDepth(root.left), self.minDepth(root.right)) + 1 + else: + return min(self.minDepth(root.left), self.minDepth(root.right)) + 1 From 8a199f89d71494eb3f768d3e217e502c3a81a7ee Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 2 Oct 2020 17:56:54 +0530 Subject: [PATCH 011/204] 0233 - Number of Digit One - Leet Code Problem --- LeetCode/0233_Number_of_Digit_One.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LeetCode/0233_Number_of_Digit_One.py diff --git a/LeetCode/0233_Number_of_Digit_One.py b/LeetCode/0233_Number_of_Digit_One.py new file mode 100644 index 0000000..7dbcec4 --- /dev/null +++ b/LeetCode/0233_Number_of_Digit_One.py @@ -0,0 +1,18 @@ +# Denote the number of 1 less than or equal to a given number +# Eg) +# Input: 13 +# Output: 6 +# Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13. + +class Solution(object): + def countDigitOne(self, n): + number = 0 + i = 1 + while(i <= n): + divider = i * 10 + number += (int(n / divider) * i + + min(max(n % divider -i + + 1, 0), i)) + i *= 10 + + return number \ No newline at end of file From c9759c9590bb6457ade95e771b3debc7299b2145 Mon Sep 17 00:00:00 2001 From: Divy Shah <38474504+divyhshah@users.noreply.github.com> Date: Fri, 2 Oct 2020 18:57:20 +0530 Subject: [PATCH 012/204] Solution to 0054 Spiral Matrix --- LeetCode/0054_Spiral_Matrix.py | 35 ++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 LeetCode/0054_Spiral_Matrix.py diff --git a/LeetCode/0054_Spiral_Matrix.py b/LeetCode/0054_Spiral_Matrix.py new file mode 100644 index 0000000..db75a62 --- /dev/null +++ b/LeetCode/0054_Spiral_Matrix.py @@ -0,0 +1,35 @@ +class Solution: + def spiralOrder(self, matrix): + if len(matrix)>0: + k, l = 0, 0 + m = len(matrix) + n = len(matrix[0]) + + l1 = [] + while (k < m and l < n): + + for i in range(l, n): + l1.append(matrix[k][i]) + + k += 1 + + for i in range(k, m): + l1.append(matrix[i][n - 1]) + n -= 1 + + if (k < m): + + for i in range(n - 1, (l - 1), -1): + l1.append(matrix[m - 1][i]) + + m -= 1 + + if (l < n): + for i in range(m - 1, k - 1, -1): + l1.append(matrix[i][l]) + + l += 1 + return l1 + + + \ No newline at end of file From e3cef1d782cef2c0beb898f3a192acd950a210fa Mon Sep 17 00:00:00 2001 From: sarthak55k Date: Fri, 2 Oct 2020 19:10:50 +0530 Subject: [PATCH 013/204] class Solution: --- .../0537_Complex_Number_Multiplication.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LeetCode/0537_Complex_Number_Multiplication.py diff --git a/LeetCode/0537_Complex_Number_Multiplication.py b/LeetCode/0537_Complex_Number_Multiplication.py new file mode 100644 index 0000000..77e0871 --- /dev/null +++ b/LeetCode/0537_Complex_Number_Multiplication.py @@ -0,0 +1,21 @@ + +class Solution: + def complexNumberMultiply(self, a: str, b: str) -> str: + x = a.split('+') + x[1] = x[1][:-1] + + y = b.split("+") + y[1] = y[1][:-1] + + a_real = int(x[0]) + + a_img = int(x[1]) + + + b_real = int(y[0]) + + + b_img = int(y[1]) + return str(a_real * b_real - a_img * b_img) + "+" + str(a_real * b_img + a_img * b_real) + "i"; + + From 5c8fb09543a38c620352f3816562ee328eccedde Mon Sep 17 00:00:00 2001 From: sarthak55k Date: Fri, 2 Oct 2020 19:17:58 +0530 Subject: [PATCH 014/204] Complex Numbers --- LeetCode/0537_Complex_Number_Multiplication.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/LeetCode/0537_Complex_Number_Multiplication.py b/LeetCode/0537_Complex_Number_Multiplication.py index 77e0871..33aebbd 100644 --- a/LeetCode/0537_Complex_Number_Multiplication.py +++ b/LeetCode/0537_Complex_Number_Multiplication.py @@ -8,13 +8,10 @@ def complexNumberMultiply(self, a: str, b: str) -> str: y[1] = y[1][:-1] a_real = int(x[0]) - a_img = int(x[1]) - b_real = int(y[0]) - - + b_real = int(y[0]) b_img = int(y[1]) return str(a_real * b_real - a_img * b_img) + "+" + str(a_real * b_img + a_img * b_real) + "i"; From 6acc7a662030b63c607939439ac01f2e65c17416 Mon Sep 17 00:00:00 2001 From: Tobias Christiansen Date: Fri, 2 Oct 2020 15:48:45 +0200 Subject: [PATCH 015/204] Create 0070_Climbing_stairs --- LeetCode/0070_Climbing_Stairs.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 LeetCode/0070_Climbing_Stairs.py diff --git a/LeetCode/0070_Climbing_Stairs.py b/LeetCode/0070_Climbing_Stairs.py new file mode 100644 index 0000000..72da524 --- /dev/null +++ b/LeetCode/0070_Climbing_Stairs.py @@ -0,0 +1,27 @@ +''' +Problem: +You are climbing a stair case. It takes n steps to reach to the top. +Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? + +Solution: +Let k be the number of 2-steps taken +Then there are (n-2*k) 1-steps and k 2-steps to reach the top. +In total there are n/2 different k's for a given n, because then there are 0 1-steps and n/2 2-steps. +Using the binomial coeficcient the permutations of 1-steps and 2-steps for a given k can be calculated as +(n-(2*k)+k) choose k = (n-k) choose k +The total number of ways is thus +sum (n-k) choose k where k=0..n/2 +The solution of this sum equals the (n+1)th fibonacci number as seen here: https://www.wolframalpha.com/input/?i=sum+%28n-k%29+choose+k+for+k%3D0..n%2F2 +That way the problem becomes rather easy. +''' +class Solution: + def climbStairs(self, n: int) -> int: + return self.fib(n + 1) + + def fib(self, n: int) -> int: + if n <= 2: + return 1 + return self.fib(n - 1) + self.fib(n - 2) + + +print(Solution().climbStairs(3)) From 0f6f574814afc168c0624a7f8cedb62d10ce9b53 Mon Sep 17 00:00:00 2001 From: Vishesh Ruparelia Date: Fri, 2 Oct 2020 19:19:59 +0530 Subject: [PATCH 016/204] 0059 Spiral Matrix II fixes #163 --- LeetCode/0059_Spiral_Matrix_II.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 LeetCode/0059_Spiral_Matrix_II.py diff --git a/LeetCode/0059_Spiral_Matrix_II.py b/LeetCode/0059_Spiral_Matrix_II.py new file mode 100644 index 0000000..a1e5e80 --- /dev/null +++ b/LeetCode/0059_Spiral_Matrix_II.py @@ -0,0 +1,8 @@ +class Solution: + def generateMatrix(self, n: int) -> List[List[int]]: + res, lo = [[n*n]], n*n + while lo > 1: + lo, hi = lo - len(res), lo + #print('res:', res) + res = [[i for i in range(lo, hi)]] + [list(j) for j in zip(*res[::-1])] + return res From 100601b90ef40ceda45523c6cb4d2aa9a730223e Mon Sep 17 00:00:00 2001 From: Shreeraksha Date: Fri, 2 Oct 2020 19:21:41 +0530 Subject: [PATCH 017/204] Added 0066_Plus_One.py --- LeetCode/0066_Plus_One.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0066_Plus_One.py diff --git a/LeetCode/0066_Plus_One.py b/LeetCode/0066_Plus_One.py new file mode 100644 index 0000000..22d1575 --- /dev/null +++ b/LeetCode/0066_Plus_One.py @@ -0,0 +1,19 @@ +# Problem name : Plus One +# Problem link : https://leetcode.com/problems/plus-one/ +# Contributor : Shreeraksha R Aithal + +class Solution: + def plusOne(self, digits: List[int]) -> List[int]: + n = len(digits) + i = -1 + carry = 1 + while i>=-n: + digits[i] = digits[i] + carry + carry = digits[i]//10 + digits[i] = digits[i]%10 + i = i-1 + + if carry > 0: + digits = [carry] + digits + + return digits \ No newline at end of file From 584cb6adb9bbdaaadd8e5c3ef2ea2f7e80b3e4bf Mon Sep 17 00:00:00 2001 From: patel kamil <38882087+kamil200@users.noreply.github.com> Date: Fri, 2 Oct 2020 19:22:49 +0530 Subject: [PATCH 018/204] 0077_Combinations solution of 0077._Combinations fixes #176 --- 0077_Combinations.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 0077_Combinations.py diff --git a/0077_Combinations.py b/0077_Combinations.py new file mode 100644 index 0000000..387a6d2 --- /dev/null +++ b/0077_Combinations.py @@ -0,0 +1,38 @@ +class Solution: + def combine(self, n: int, k: int) -> List[List[int]]: + # Pretty much same as combination sums II, use index at most once per combo + + # create list from 1 to n + # for each i-th element, call helper function from [i+1:] + # from the helper function, if length of arr passed in == k + # append and return + # otherwise, keep going for i+1 in a for loop in the helper + # ^ after done, delete the last index(backtrack process) + + nums = [_ for _ in range(1,n+1)] + result = [] + combo = [] + n = len(nums) + + for i in range(n): + combo.append(nums[i]) + self.backtrack(nums[i+1:],combo, result, k) + combo = [] + + return result + + def backtrack(self, nums: List[int], combo: List[int], result: List[List[int]], k: int) -> None: + + if len(combo) == k: + result.append([_ for _ in combo]) + return + + n = len(nums) + + for i in range(n): + combo.append(nums[i]) + self.backtrack(nums[i+1:],combo,result,k) + # This is the backtrack process + del combo[-1] + + return \ No newline at end of file From 277553211ba34d2508c92126c97013a0935eefb0 Mon Sep 17 00:00:00 2001 From: Vishesh Ruparelia Date: Fri, 2 Oct 2020 19:27:25 +0530 Subject: [PATCH 019/204] 0057 Insert Interval - fixes #162 --- LeetCode/0057_Insert_Interval.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0057_Insert_Interval.py diff --git a/LeetCode/0057_Insert_Interval.py b/LeetCode/0057_Insert_Interval.py new file mode 100644 index 0000000..325acb6 --- /dev/null +++ b/LeetCode/0057_Insert_Interval.py @@ -0,0 +1,20 @@ +class Solution: + def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: + result = [] + + for interval in intervals: + # the new interval is after the range of other interval, so we can leave the current interval baecause the new one does not overlap with it + if interval[1] < newInterval[0]: + result.append(interval) + # the new interval's range is before the other, so we can add the new interval and update it to the current one + elif interval[0] > newInterval[1]: + result.append(newInterval) + newInterval = interval + # the new interval is in the range of the other interval, we have an overlap, so we must choose the min for start and max for end of interval + elif interval[1] >= newInterval[0] or interval[0] <= newInterval[1]: + newInterval[0] = min(interval[0], newInterval[0]) + newInterval[1] = max(newInterval[1], interval[1]) + + + result.append(newInterval); + return result From 53bf83af38ae66fdf5d02afd9fe11316c76484c2 Mon Sep 17 00:00:00 2001 From: sathiyajith Date: Fri, 2 Oct 2020 19:28:30 +0530 Subject: [PATCH 020/204] Solution for Container With most water --- LeetCode/0011 - Container With Most Water.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 LeetCode/0011 - Container With Most Water.py diff --git a/LeetCode/0011 - Container With Most Water.py b/LeetCode/0011 - Container With Most Water.py new file mode 100644 index 0000000..e432773 --- /dev/null +++ b/LeetCode/0011 - Container With Most Water.py @@ -0,0 +1,16 @@ +class Solution(object): + def maxArea(self, height): + i=0 + j=len(height)-1 + a=0 + b=0 + while ia: + a=b + return a \ No newline at end of file From 8d552a54a8bb41797ac155215d339eadbe1c724f Mon Sep 17 00:00:00 2001 From: Tobias Christiansen Date: Fri, 2 Oct 2020 15:59:14 +0200 Subject: [PATCH 021/204] Added memoization to not calculate a value twice. --- LeetCode/0070_Climbing_Stairs.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/LeetCode/0070_Climbing_Stairs.py b/LeetCode/0070_Climbing_Stairs.py index 72da524..09bd58b 100644 --- a/LeetCode/0070_Climbing_Stairs.py +++ b/LeetCode/0070_Climbing_Stairs.py @@ -18,10 +18,17 @@ class Solution: def climbStairs(self, n: int) -> int: return self.fib(n + 1) + fibStore = {} def fib(self, n: int) -> int: + if n in self.fibStore: + return self.fibStore[n] + if n <= 2: return 1 - return self.fib(n - 1) + self.fib(n - 2) + + value = self.fib(n - 1) + self.fib(n - 2) + self.fibStore[n] = value + return value -print(Solution().climbStairs(3)) +print(Solution().climbStairs(30)) From 8a9d827012e6ce882f62661dc599b79cec37d7df Mon Sep 17 00:00:00 2001 From: Mohitbalwani26 Date: Fri, 2 Oct 2020 19:30:02 +0530 Subject: [PATCH 022/204] added sudoku solver solution --- 0037_Sudoku_Solver.py | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 0037_Sudoku_Solver.py diff --git a/0037_Sudoku_Solver.py b/0037_Sudoku_Solver.py new file mode 100644 index 0000000..a4f7956 --- /dev/null +++ b/0037_Sudoku_Solver.py @@ -0,0 +1,42 @@ +from collections import defaultdict, deque + + +class Solution: + def solveSudoku(self, board: List[List[str]]) -> None: + rows = defaultdict(set) + cols = defaultdict(set) + subgrids = defaultdict(set) + empty_cells = deque() + for i in range(9): + for j in range(9): + if board[i][j] != '.': + rows[i].add(board[i][j]) + cols[j].add(board[i][j]) + subgrids[(i//3, j//3)].add(board[i][j]) + else: + empty_cells.append((i, j)) + + def dfs(): + if not empty_cells: + return True + + row, col = empty_cells[0] + subgrid = (row//3, col//3) + for digit in {"1", '2', '3', '4', '5', '6', '7', '8', '9'}: + if digit not in rows[row] and digit not in cols[col] and digit not in subgrids[subgrid]: + board[row][col] = digit + rows[row].add(digit) + cols[col].add(digit) + subgrids[subgrid].add(digit) + empty_cells.popleft() + if dfs(): + return True + + board[row][col] = '.' + rows[row].remove(digit) + cols[col].remove(digit) + subgrids[subgrid].remove(digit) + empty_cells.appendleft((row, col)) + return False + dfs() + return board From 294fbd4faaf21b835966ad18d24395e91a826634 Mon Sep 17 00:00:00 2001 From: Divy Shah <38474504+divyhshah@users.noreply.github.com> Date: Fri, 2 Oct 2020 19:55:51 +0530 Subject: [PATCH 023/204] Solved 0042 Trapping Rain Water --- LeetCode/0042_Trapping_Rain_Water.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 LeetCode/0042_Trapping_Rain_Water.py diff --git a/LeetCode/0042_Trapping_Rain_Water.py b/LeetCode/0042_Trapping_Rain_Water.py new file mode 100644 index 0000000..df2cc51 --- /dev/null +++ b/LeetCode/0042_Trapping_Rain_Water.py @@ -0,0 +1,24 @@ +class Solution: + def trap(self, height: List[int]) -> int: + n = len(height) + if n>0: + left = [0]*n + right = [0]*n + result = 0 + + # Fill left array + left[0] = height[0] + for i in range( 1, n): + left[i] = max(left[i-1], height[i]) + + # Fill right array + right[n-1] = height[n-1] + for i in range(n-2, -1, -1): + right[i] = max(right[i + 1], height[i]); + + for i in range(0, n): + result += min(left[i], right[i]) - height[i] + + return result + else: + return 0 \ No newline at end of file From b5c71456218b1ed37f08e68e672fdba05416cd0e Mon Sep 17 00:00:00 2001 From: Divy Shah <38474504+divyhshah@users.noreply.github.com> Date: Fri, 2 Oct 2020 20:06:43 +0530 Subject: [PATCH 024/204] Delete 0042_Trapping_Rain_Water.py --- LeetCode/0042_Trapping_Rain_Water.py | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 LeetCode/0042_Trapping_Rain_Water.py diff --git a/LeetCode/0042_Trapping_Rain_Water.py b/LeetCode/0042_Trapping_Rain_Water.py deleted file mode 100644 index df2cc51..0000000 --- a/LeetCode/0042_Trapping_Rain_Water.py +++ /dev/null @@ -1,24 +0,0 @@ -class Solution: - def trap(self, height: List[int]) -> int: - n = len(height) - if n>0: - left = [0]*n - right = [0]*n - result = 0 - - # Fill left array - left[0] = height[0] - for i in range( 1, n): - left[i] = max(left[i-1], height[i]) - - # Fill right array - right[n-1] = height[n-1] - for i in range(n-2, -1, -1): - right[i] = max(right[i + 1], height[i]); - - for i in range(0, n): - result += min(left[i], right[i]) - height[i] - - return result - else: - return 0 \ No newline at end of file From 207ea37a39f8acf84ae048d3ea0d02d3ce764884 Mon Sep 17 00:00:00 2001 From: Suparna Nandkumar Raut Date: Fri, 2 Oct 2020 20:09:32 +0530 Subject: [PATCH 025/204] Create 0076_Minimum_Window_Substring.py --- LeetCode/0076_Minimum_Window_Substring.py | 31 +++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 LeetCode/0076_Minimum_Window_Substring.py diff --git a/LeetCode/0076_Minimum_Window_Substring.py b/LeetCode/0076_Minimum_Window_Substring.py new file mode 100644 index 0000000..06a33d3 --- /dev/null +++ b/LeetCode/0076_Minimum_Window_Substring.py @@ -0,0 +1,31 @@ +from collections import defaultdict + +class Solution: + def minWindow(self, s: str, t: str) -> str: + char_frequency = defaultdict(lambda: 0) + for c in pattern: + char_frequency[c] += 1 + chars_matched = 0 + + start = 0 + res = "" + + for end in range(len(string)): + right_char = string[end] + if right_char in pattern: + char_frequency[right_char] -= 1 + if char_frequency[right_char] == 0: + chars_matched += 1 + + while start <= end and chars_matched == len(char_frequency): + if res == "" or end-start+1 < len(res): + res = string[start:end+1] + + left_char = string[start] + if left_char in pattern: + if char_frequency[left_char] == 0: + chars_matched -= 1 + char_frequency[left_char] += 1 + start += 1 + + return res From bce5ba779bee402cb7e36cc2467069127725f302 Mon Sep 17 00:00:00 2001 From: Pranjal Kumar Date: Fri, 2 Oct 2020 20:47:14 +0530 Subject: [PATCH 026/204] Added solution to 0069_sqrt(x) --- LeetCode/0069 _ Sqrt(x).py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 LeetCode/0069 _ Sqrt(x).py diff --git a/LeetCode/0069 _ Sqrt(x).py b/LeetCode/0069 _ Sqrt(x).py new file mode 100644 index 0000000..f71cd35 --- /dev/null +++ b/LeetCode/0069 _ Sqrt(x).py @@ -0,0 +1,17 @@ +class Solution(object): + def mySqrt(self, x): + if x<2: + return x + low = 0 + high = x + result=0 + while(low<=high): + mid = (low+high)//2 + if(mid*mid==x): + return mid + elif(mid*mid Date: Fri, 2 Oct 2020 20:48:53 +0530 Subject: [PATCH 027/204] Added 0075_Sort_Colors.py --- LeetCode/0075_Sort_Colors.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 LeetCode/0075_Sort_Colors.py diff --git a/LeetCode/0075_Sort_Colors.py b/LeetCode/0075_Sort_Colors.py new file mode 100644 index 0000000..0192268 --- /dev/null +++ b/LeetCode/0075_Sort_Colors.py @@ -0,0 +1,29 @@ +# Problem name : Sort Colors +# Problem link : https://leetcode.com/problems/sort-colors/ +# Contributor : Shreeraksha R Aithal + +class Solution: + def sortColors(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + + i = k = 0 + n = len(nums) + j = n-1 + while k < n and i < j: + if nums[k] == 0: + if k > i: + nums[i], nums[k] = nums[k], nums[i] + i += 1 + else: + k += 1 + elif nums[k] == 2: + if k < j: + nums[j], nums[k] = nums[k], nums[j] + j -= 1 + else: + k += 1 + else: + k += 1 + From e45e82532f6c5b18ad0b1852d71025dc52f65ac5 Mon Sep 17 00:00:00 2001 From: Yunus Bulut Date: Fri, 2 Oct 2020 18:30:05 +0300 Subject: [PATCH 028/204] Create 0053_Maximum_Subarray.py #114 --- LeetCode/0053_Maximum_Subarray.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 LeetCode/0053_Maximum_Subarray.py diff --git a/LeetCode/0053_Maximum_Subarray.py b/LeetCode/0053_Maximum_Subarray.py new file mode 100644 index 0000000..960a895 --- /dev/null +++ b/LeetCode/0053_Maximum_Subarray.py @@ -0,0 +1,9 @@ +class Solution(object): + def maxSubArray(self, nums: List[int]) -> int: + dp = [0]*len(nums) + dp[0] = nums[0] + max_num = nums[0] + for i in range(1, len(nums)): + dp[i] = max(dp[i-1]+nums[i], nums[i]) + if dp[i]>max_num: max_num = dp[i] + return max_num From 6962e731f24eb0c62bad186ba26cdc1a54eae950 Mon Sep 17 00:00:00 2001 From: Yunus Bulut Date: Fri, 2 Oct 2020 18:49:56 +0300 Subject: [PATCH 029/204] Create 0064_Minimum_Path_Sum.py #140 --- LeetCode/0064_Minimum_Path_Sum.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0064_Minimum_Path_Sum.py diff --git a/LeetCode/0064_Minimum_Path_Sum.py b/LeetCode/0064_Minimum_Path_Sum.py new file mode 100644 index 0000000..917b1ff --- /dev/null +++ b/LeetCode/0064_Minimum_Path_Sum.py @@ -0,0 +1,12 @@ +class Solution: + def minPathSum(self, grid: List[List[int]]) -> int: + rows=len(grid) + columns=len(grid[0]) + for i in range(1,columns): + grid[0][i]+=grid[0][i-1] + for j in range(1,rows): + grid[j][0]+=grid[j-1][0] + for k in range(1,rows): + for l in range(1,columns): + grid[k][l]+=min(grid[k][l-1],grid[k-1][l]) + return grid[-1][-1] From a375851a7c97ed0701c211b34c450fdb3a0cc473 Mon Sep 17 00:00:00 2001 From: Yunus Bulut Date: Fri, 2 Oct 2020 19:23:45 +0300 Subject: [PATCH 030/204] Create 0374_Guess_Number_Higher_or_Lower #113 --- LeetCode/0374_Guess_Number_Higher_or_Lower | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/0374_Guess_Number_Higher_or_Lower diff --git a/LeetCode/0374_Guess_Number_Higher_or_Lower b/LeetCode/0374_Guess_Number_Higher_or_Lower new file mode 100644 index 0000000..5d6917d --- /dev/null +++ b/LeetCode/0374_Guess_Number_Higher_or_Lower @@ -0,0 +1,11 @@ +class Solution: + def guessNumber(self, n: int) -> int: + l, r = 0, n + while l <= r: + m = (l + r)//2 + if guess(m) == 0: return m + elif guess(m) == -1: + r = m - 1 + else: + l = m + 1 + return l From 71f7a1b4b2de9e15ceebe8dab4ade6c5aa13e36e Mon Sep 17 00:00:00 2001 From: Divy Shah <38474504+divyhshah@users.noreply.github.com> Date: Fri, 2 Oct 2020 21:56:16 +0530 Subject: [PATCH 031/204] Solved 0042 Trapping Rain Water --- LeetCode/0042_Trapping_Rain_Water.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 LeetCode/0042_Trapping_Rain_Water.py diff --git a/LeetCode/0042_Trapping_Rain_Water.py b/LeetCode/0042_Trapping_Rain_Water.py new file mode 100644 index 0000000..df2cc51 --- /dev/null +++ b/LeetCode/0042_Trapping_Rain_Water.py @@ -0,0 +1,24 @@ +class Solution: + def trap(self, height: List[int]) -> int: + n = len(height) + if n>0: + left = [0]*n + right = [0]*n + result = 0 + + # Fill left array + left[0] = height[0] + for i in range( 1, n): + left[i] = max(left[i-1], height[i]) + + # Fill right array + right[n-1] = height[n-1] + for i in range(n-2, -1, -1): + right[i] = max(right[i + 1], height[i]); + + for i in range(0, n): + result += min(left[i], right[i]) - height[i] + + return result + else: + return 0 \ No newline at end of file From b99d6348bf99ed1f36a4813b285fe1b180a61e7d Mon Sep 17 00:00:00 2001 From: Divy Shah <38474504+divyhshah@users.noreply.github.com> Date: Fri, 2 Oct 2020 22:01:02 +0530 Subject: [PATCH 032/204] deleted 0042 --- .../0042_Trapping_Rain_Water.py => 0042_Trapping_Rain_Water.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/0042_Trapping_Rain_Water.py => 0042_Trapping_Rain_Water.py (100%) diff --git a/LeetCode/0042_Trapping_Rain_Water.py b/0042_Trapping_Rain_Water.py similarity index 100% rename from LeetCode/0042_Trapping_Rain_Water.py rename to 0042_Trapping_Rain_Water.py From f919c59f06f2dae237288a1df10fc0a775ba0049 Mon Sep 17 00:00:00 2001 From: Divy Shah <38474504+divyhshah@users.noreply.github.com> Date: Fri, 2 Oct 2020 22:02:55 +0530 Subject: [PATCH 033/204] Solved 0042 Trapping Rain Water --- LeetCode/0042_Trapping_Rain_Water.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 LeetCode/0042_Trapping_Rain_Water.py diff --git a/LeetCode/0042_Trapping_Rain_Water.py b/LeetCode/0042_Trapping_Rain_Water.py new file mode 100644 index 0000000..df2cc51 --- /dev/null +++ b/LeetCode/0042_Trapping_Rain_Water.py @@ -0,0 +1,24 @@ +class Solution: + def trap(self, height: List[int]) -> int: + n = len(height) + if n>0: + left = [0]*n + right = [0]*n + result = 0 + + # Fill left array + left[0] = height[0] + for i in range( 1, n): + left[i] = max(left[i-1], height[i]) + + # Fill right array + right[n-1] = height[n-1] + for i in range(n-2, -1, -1): + right[i] = max(right[i + 1], height[i]); + + for i in range(0, n): + result += min(left[i], right[i]) - height[i] + + return result + else: + return 0 \ No newline at end of file From e53f704d654b815953f4b07b6cf5ddd8ea2ac363 Mon Sep 17 00:00:00 2001 From: Divy Shah <38474504+divyhshah@users.noreply.github.com> Date: Fri, 2 Oct 2020 22:03:36 +0530 Subject: [PATCH 034/204] deleted unused file --- 0042_Trapping_Rain_Water.py | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 0042_Trapping_Rain_Water.py diff --git a/0042_Trapping_Rain_Water.py b/0042_Trapping_Rain_Water.py deleted file mode 100644 index df2cc51..0000000 --- a/0042_Trapping_Rain_Water.py +++ /dev/null @@ -1,24 +0,0 @@ -class Solution: - def trap(self, height: List[int]) -> int: - n = len(height) - if n>0: - left = [0]*n - right = [0]*n - result = 0 - - # Fill left array - left[0] = height[0] - for i in range( 1, n): - left[i] = max(left[i-1], height[i]) - - # Fill right array - right[n-1] = height[n-1] - for i in range(n-2, -1, -1): - right[i] = max(right[i + 1], height[i]); - - for i in range(0, n): - result += min(left[i], right[i]) - height[i] - - return result - else: - return 0 \ No newline at end of file From 0045fe3657aa6420aefcc5308027375321865d99 Mon Sep 17 00:00:00 2001 From: Austin Ewens Date: Fri, 2 Oct 2020 16:54:21 +0000 Subject: [PATCH 035/204] Second proposed solution to problem 0032 --- LeetCode/0032_Longest_Valid_Parentheses.py | 88 ++++++++++------------ 1 file changed, 38 insertions(+), 50 deletions(-) diff --git a/LeetCode/0032_Longest_Valid_Parentheses.py b/LeetCode/0032_Longest_Valid_Parentheses.py index 3ba791b..4ac1147 100644 --- a/LeetCode/0032_Longest_Valid_Parentheses.py +++ b/LeetCode/0032_Longest_Valid_Parentheses.py @@ -1,56 +1,44 @@ +from typing import List, Dict + class Solution: + def _score(self, position: List[int], state: Dict[int,bool]) -> List[int]: + score = 0 + scores = list() + for pos in position: + matched = state.get(pos) + if not matched: + scores.append(score) + score = 0 + + else: + score = score + 2 + + scores.append(score) + + return scores + def longestValidParentheses(self, s: str) -> int: - state = 0 - tokens = list() - for paren in s: + scores = [0] + state = dict() + position = list() + opened = list() + closed = list() + for p, paren in enumerate(s): if paren == "(": - state = state - 1 - tokens.append(-1) + opened.append(p) + position.append(p) + state[p] = False - elif paren == ")" and state < 0: - state = state + 1 - tokens.append(1) + elif paren == ")" and len(opened) > 0: + op = opened.pop() + state[op] = True else: - tokens.append(0) - - token_sets = [list()] - for token in tokens: - if token == 0: - token_sets.append(list()) - continue - - token_sets[-1].append(token) - - valid_sets = [0] - for token_set in token_sets: - for offset in range(len(token_set)-1): - for nudge in range(offset+1): - offset_front = offset - nudge - offset_back = len(token_set) - nudge - offset_tokens = token_set[:][offset_front:offset_back] - - invalid = True - while invalid: - check = 0 - front = offset_tokens[0] - if front in [1, 0]: - offset_tokens = offset_tokens[1:] - check = check + 1 - - back = offset_tokens[-1] - if back in [-1, 0]: - offset_tokens = offset_tokens[:-1] - check = check + 1 - - if check == 0: - invalid = False - - if len(offset_tokens) < 2: - break - - if not invalid and sum(offset_tokens) == 0: - valid_sets.append(len(offset_tokens)) - continue - - return max(valid_sets) + scores.extend(self._score(position, state)) + state = dict() + position = list() + opened = list() + closed = list() + + scores.extend(self._score(position, state)) + return max(scores) From 4c1a4c3597d83e664a93023e67cb1ea7030506ba Mon Sep 17 00:00:00 2001 From: Leonardo Anjos Date: Fri, 2 Oct 2020 14:21:26 -0300 Subject: [PATCH 036/204] Added solution for LeetCode's 0278 - First Bad Version --- LeetCode/0278_First_Bad_Version.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 LeetCode/0278_First_Bad_Version.py diff --git a/LeetCode/0278_First_Bad_Version.py b/LeetCode/0278_First_Bad_Version.py new file mode 100644 index 0000000..08c2ef1 --- /dev/null +++ b/LeetCode/0278_First_Bad_Version.py @@ -0,0 +1,22 @@ +# The isBadVersion API is already defined for you. +# @param version, an integer +# @return an integer +# def isBadVersion(version): + +class Solution: + def firstBadVersion(self, n): + """ + :type n: int + :rtype: int + """ + l, r, ans = 1, n, -1 + while l <= r: + mid = (l + r) // 2 + if isBadVersion(mid): + ans = mid + r = mid - 1 + else: + l = mid + 1 + + return ans + \ No newline at end of file From cfc34262b8954b6e320a713ff7d3b6488f7f9ee0 Mon Sep 17 00:00:00 2001 From: PushpikaWan Date: Sat, 3 Oct 2020 01:01:04 +0530 Subject: [PATCH 037/204] feat: 0044-wildcard-Matching solution added --- LeetCode/0044_Wildcard_Matching.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0044_Wildcard_Matching.py diff --git a/LeetCode/0044_Wildcard_Matching.py b/LeetCode/0044_Wildcard_Matching.py new file mode 100644 index 0000000..38e466a --- /dev/null +++ b/LeetCode/0044_Wildcard_Matching.py @@ -0,0 +1,19 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + #this is a dynamic programming solution fot this + matrix = [[False for x in range(len(p) + 1)] for x in range(len(s) + 1)] + matrix[0][0] = True + + for i in range(1,len(matrix[0])): + if p[i-1] == '*': + matrix[0][i] = matrix[0][i-1] + + for i in range(1, len(matrix)): + for j in range(1, len(matrix[0])): + if s[i - 1] == p[j - 1] or p[j - 1] == '?': + matrix[i][j] = matrix[i-1][j-1] + elif p[j-1] == '*': + matrix[i][j] = matrix[i][j-1] or matrix[i-1][j] + else: + matrix[i][j] = False + return matrix[len(s)][len(p)] From 8ccb4c9bec6467d51fda935f55e1fa4386647f20 Mon Sep 17 00:00:00 2001 From: Hruday007 Date: Sat, 3 Oct 2020 01:59:41 +0530 Subject: [PATCH 038/204] Adding 0741_Cherry Pickup --- LeetCode/0741_CherryPickup.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/0741_CherryPickup.py diff --git a/LeetCode/0741_CherryPickup.py b/LeetCode/0741_CherryPickup.py new file mode 100644 index 0000000..79cca13 --- /dev/null +++ b/LeetCode/0741_CherryPickup.py @@ -0,0 +1,14 @@ +class Solution: + def cherryPickup(self, grid: List[List[int]]) -> int: + n = len(grid) + + @lru_cache(None) + def fn(t, i, ii): + """Return maximum cherries collected at kth step when two robots are at ith and iith row""" + j, jj = t - i, t - ii #columns + if not (0 <= i < n and 0 <= j < n) or t < i or grid[ i][ j] == -1: return -inf #robot 1 not at proper location + if not (0 <= ii < n and 0 <= jj < n) or t < ii or grid[ii][jj] == -1: return -inf #robot 2 not at proper location + if t == 0: return grid[0][0] #starting from 0,0 + return grid[i][j] + (i != ii)*grid[ii][jj] + max(fn(t-1, x, y) for x in (i-1, i) for y in (ii-1, ii)) + + return max(0, fn(2*n-2, n-1, n-1)) \ No newline at end of file From 9f5253b0556854d2549432d260a9089607727ade Mon Sep 17 00:00:00 2001 From: ajeers <54639791+sus5pect@users.noreply.github.com> Date: Sat, 3 Oct 2020 02:25:43 +0530 Subject: [PATCH 039/204] Create 0072_Edit_Distance.py --- LeetCode/0072_Edit_Distance.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 LeetCode/0072_Edit_Distance.py diff --git a/LeetCode/0072_Edit_Distance.py b/LeetCode/0072_Edit_Distance.py new file mode 100644 index 0000000..0a779cf --- /dev/null +++ b/LeetCode/0072_Edit_Distance.py @@ -0,0 +1,22 @@ +class Solution: + # @return an integer + def minDistance(self, word1, word2): + m=len(word1) + n=len(word2) + dp=[[0 for i in range(n+1)] for j in range(m+1)] + for i in range(m+1): + dp[i][0]=i + for j in range(n+1): + dp[0][j]=j + for i in range(1,m+1): + for j in range(1,n+1): + if word1[i-1]==word2[j-1]: + dp[i][j]=dp[i-1][j-1] + else: + dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+1) + return dp[m][n] + +test=Solution() +input1=str(input(“Enter a string1”)) +input2=str(input(“Enter a string2”)) +print(test.minDistance(input1,input2)) From d7a7bbf42b27fa79a5e87fa745bea058dd879864 Mon Sep 17 00:00:00 2001 From: tanaykulkarni Date: Sat, 3 Oct 2020 01:03:41 -0700 Subject: [PATCH 040/204] added solution for issue 0061 --- LeetCode/0061_Rotate_List.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 LeetCode/0061_Rotate_List.py diff --git a/LeetCode/0061_Rotate_List.py b/LeetCode/0061_Rotate_List.py new file mode 100644 index 0000000..c752eaf --- /dev/null +++ b/LeetCode/0061_Rotate_List.py @@ -0,0 +1,29 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def rotateRight(self, head: ListNode, k: int) -> ListNode: + + + if head == None or head.next == None: + return head + count = 1 + p = head + while p.next: + count+=1 + p=p.next + + rot = k%count + temp = head + p.next = head + for i in range(count-rot-1): + temp = temp.next + answer = temp.next + temp.next = None + + return answer + + \ No newline at end of file From bfd7d38a64d2c0973a67b8e20147278f80d1abc9 Mon Sep 17 00:00:00 2001 From: SOURAB-BAPPA <62734958+SOURAB-BAPPA@users.noreply.github.com> Date: Sat, 3 Oct 2020 16:19:46 +0530 Subject: [PATCH 041/204] permutation sequence added --- LeetCode/0060 - Permutation_Sequence.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 LeetCode/0060 - Permutation_Sequence.py diff --git a/LeetCode/0060 - Permutation_Sequence.py b/LeetCode/0060 - Permutation_Sequence.py new file mode 100644 index 0000000..06f45ba --- /dev/null +++ b/LeetCode/0060 - Permutation_Sequence.py @@ -0,0 +1,23 @@ +class Solution: + data = [] + + def getPermutation(self, n: int, k: int) -> str: + string = [] + for i in range(1, n+1): + string.append(str(i)) + self.permutations(string, 0, len(string)) + return self.data[k-1] + + def permutations(self, string, val, length): + if val == length - 1: + self.data.append("".join(string)) + else: + for i in range(val, length): + string[val], string[i] = string[i], string[val] + self.permutations(string, val + 1, length) + string[val], string[i] = string[i], string[val] + + +user = Solution() +output = user.getPermutation(int(input("Input: n=")), int(input("k="))) +print("\nOutput: {}".format(output)) From 3144a2e17e483e281804c7a033e4e6967bae65e8 Mon Sep 17 00:00:00 2001 From: bislara Date: Sat, 3 Oct 2020 17:13:24 +0530 Subject: [PATCH 042/204] added the solution for combination sum 2 --- LeetCode/0040_Combination_Sum_2.py | 33 ++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 LeetCode/0040_Combination_Sum_2.py diff --git a/LeetCode/0040_Combination_Sum_2.py b/LeetCode/0040_Combination_Sum_2.py new file mode 100644 index 0000000..757b547 --- /dev/null +++ b/LeetCode/0040_Combination_Sum_2.py @@ -0,0 +1,33 @@ +''' +Problem :- + +Given a collection of candidate numbers (candidates) and a target number (target), +find all unique combinations in candidates where the candidate numbers sums to target. + +- Each number in candidates may only be used once in the combination. + +Example:- + +Input: candidates = [10,1,2,7,6,1,5], target = 8, +A solution set is: +[ + [1, 7], + [1, 2, 5], + [2, 6], + [1, 1, 6] +] + +''' +class Solution: + def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: + candidates.sort() + table = [None] + [set() for i in range(target)] + for i in candidates: + if i > target: + break + for j in range(target - i, 0, -1): + table[i + j] |= {elt + (i,) for elt in table[j]} + table[i].add((i,)) + return map(list, table[target]) + + From 4d24827f60caa18f8ddc2f358d73ec0d7f99f7d5 Mon Sep 17 00:00:00 2001 From: bislara Date: Sat, 3 Oct 2020 17:35:51 +0530 Subject: [PATCH 043/204] added swap notes in pair solution --- LeetCode/0024_ Swap_Nodes_in_Pairs.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 LeetCode/0024_ Swap_Nodes_in_Pairs.py diff --git a/LeetCode/0024_ Swap_Nodes_in_Pairs.py b/LeetCode/0024_ Swap_Nodes_in_Pairs.py new file mode 100644 index 0000000..e91712e --- /dev/null +++ b/LeetCode/0024_ Swap_Nodes_in_Pairs.py @@ -0,0 +1,27 @@ +''' +Problem:- + +Given a linked list, swap every two adjacent nodes and return its head. +You may not modify the values in the list's nodes, only nodes itself may be changed. + +Example: +- Given 1->2->3->4, you should return the list as 2->1->4->3. + +''' + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def swapPairs(self, head: ListNode) -> ListNode: + pre, pre.next = self, head + while pre.next and pre.next.next: + a = pre.next + b = a.next + pre.next, b.next, a.next = b, a, b.next + pre = a + return self.next + + From a3dbe49a9b7f8717bde7cfcf212ae3a93921c3e5 Mon Sep 17 00:00:00 2001 From: bislara Date: Sat, 3 Oct 2020 17:54:41 +0530 Subject: [PATCH 044/204] Added the Longest Palindromic Substring Solution --- .../0005_Longest_Palindromic_Substring.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 LeetCode/0005_Longest_Palindromic_Substring.py diff --git a/LeetCode/0005_Longest_Palindromic_Substring.py b/LeetCode/0005_Longest_Palindromic_Substring.py new file mode 100644 index 0000000..62982d8 --- /dev/null +++ b/LeetCode/0005_Longest_Palindromic_Substring.py @@ -0,0 +1,38 @@ +''' +Problem:- + +Given a string s, find the longest palindromic substring in s. +You may assume that the maximum length of s is 1000. + +Example 1: + Input: "babad" + Output: "bab" + Note: "aba" is also a valid answer. + +''' + +class Solution: + def longestPalindrome(self, s: str) -> str: + res = "" + resLen = 0 + + for i in range(len(s)): + # odd length + l, r = i, i + while l >= 0 and r < len(s) and s[l] == s[r]: + if (r - l + 1) > resLen: + res = s[l:r + 1] + resLen = r - l + 1 + l -= 1 + r += 1 + + # even length + l, r = i, i + 1 + while l >= 0 and r < len(s) and s[l] == s[r]: + if (r - l + 1) > resLen: + res = s[l:r + 1] + resLen = r - l + 1 + l -= 1 + r += 1 + + return res \ No newline at end of file From 938e52b08f8d29a539e6b090e6efef737b2bc7ec Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sat, 3 Oct 2020 22:12:30 +0200 Subject: [PATCH 045/204] moved files to correct directory --- 0037_Sudoku_Solver.py => LeetCode/0037_Sudoku_Solver.py | 0 0077_Combinations.py => LeetCode/0077_Combinations.py | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename 0037_Sudoku_Solver.py => LeetCode/0037_Sudoku_Solver.py (100%) rename 0077_Combinations.py => LeetCode/0077_Combinations.py (100%) diff --git a/0037_Sudoku_Solver.py b/LeetCode/0037_Sudoku_Solver.py similarity index 100% rename from 0037_Sudoku_Solver.py rename to LeetCode/0037_Sudoku_Solver.py diff --git a/0077_Combinations.py b/LeetCode/0077_Combinations.py similarity index 100% rename from 0077_Combinations.py rename to LeetCode/0077_Combinations.py From a438545c9c0ee88e4413af3142027e24ddde8bff Mon Sep 17 00:00:00 2001 From: Suparna Nandkumar Raut Date: Sun, 4 Oct 2020 12:24:05 +0530 Subject: [PATCH 046/204] Updated as per requested changes --- LeetCode/0076_Minimum_Window_Substring.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/LeetCode/0076_Minimum_Window_Substring.py b/LeetCode/0076_Minimum_Window_Substring.py index 06a33d3..86cdf44 100644 --- a/LeetCode/0076_Minimum_Window_Substring.py +++ b/LeetCode/0076_Minimum_Window_Substring.py @@ -3,26 +3,26 @@ class Solution: def minWindow(self, s: str, t: str) -> str: char_frequency = defaultdict(lambda: 0) - for c in pattern: + for c in t: char_frequency[c] += 1 chars_matched = 0 start = 0 res = "" - for end in range(len(string)): - right_char = string[end] - if right_char in pattern: + for end in range(len(s)): + right_char = s[end] + if right_char in t: char_frequency[right_char] -= 1 if char_frequency[right_char] == 0: chars_matched += 1 while start <= end and chars_matched == len(char_frequency): if res == "" or end-start+1 < len(res): - res = string[start:end+1] + res = s[start:end+1] - left_char = string[start] - if left_char in pattern: + left_char = s[start] + if left_char in t: if char_frequency[left_char] == 0: chars_matched -= 1 char_frequency[left_char] += 1 From a2beb067f2cd2daac223944be1deda87e59e14d5 Mon Sep 17 00:00:00 2001 From: Hiroshii8 Date: Sun, 4 Oct 2020 19:29:39 +0700 Subject: [PATCH 047/204] feature(palindrome-number): add new answer for leetcode 0009 problem --- LeetCode/0009_Palindrom_Number.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0009_Palindrom_Number.py diff --git a/LeetCode/0009_Palindrom_Number.py b/LeetCode/0009_Palindrom_Number.py new file mode 100644 index 0000000..7bf7938 --- /dev/null +++ b/LeetCode/0009_Palindrom_Number.py @@ -0,0 +1,12 @@ +class Solution: + def isPalindrome(self, x: int) -> bool: + if x > 0 and x < 10: + return True + + copyNumber = x + newNumber = 0 + while copyNumber > 0: + newNumber = int(newNumber * 10 + (copyNumber % 10)) + copyNumber = int(copyNumber / 10) + + return newNumber == x \ No newline at end of file From 05f529553b8fe7db56990c4cb18108423986576b Mon Sep 17 00:00:00 2001 From: tanmoyee04 <61410535+tanmoyee04@users.noreply.github.com> Date: Sun, 4 Oct 2020 18:43:58 +0530 Subject: [PATCH 048/204] uploaded Problem no. 62 i.e. Unique Paths --- LeetCode/0062_Unique_Paths.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 LeetCode/0062_Unique_Paths.py diff --git a/LeetCode/0062_Unique_Paths.py b/LeetCode/0062_Unique_Paths.py new file mode 100644 index 0000000..0b5dfff --- /dev/null +++ b/LeetCode/0062_Unique_Paths.py @@ -0,0 +1,3 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + return math.factorial(n+m-2)//(math.factorial(m-1)*math.factorial(n-1)) \ No newline at end of file From 72191daa9d8bae211829afe1bd80633c8fc742a5 Mon Sep 17 00:00:00 2001 From: tanmoyee04 <61410535+tanmoyee04@users.noreply.github.com> Date: Sun, 4 Oct 2020 19:09:21 +0530 Subject: [PATCH 049/204] Uploaded solution for problem number 83 --- ...0083_Remove_Dupticates_from_Sorted_List.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0083_Remove_Dupticates_from_Sorted_List.py diff --git a/LeetCode/0083_Remove_Dupticates_from_Sorted_List.py b/LeetCode/0083_Remove_Dupticates_from_Sorted_List.py new file mode 100644 index 0000000..890fd10 --- /dev/null +++ b/LeetCode/0083_Remove_Dupticates_from_Sorted_List.py @@ -0,0 +1,19 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + if head==None: + return head + current= head.next + prev=head + while current!=None: + if current.val==prev.val: + prev.next=current.next + current=current.next + else: + current=current.next + prev=prev.next + return head \ No newline at end of file From c0bd850f617129ff40ef40e9edee79312d058b44 Mon Sep 17 00:00:00 2001 From: Yash Chaudhary Date: Sun, 4 Oct 2020 21:07:17 +0530 Subject: [PATCH 050/204] added new problem with solution --- LeetCode/0073_Set Matrix Zeroes.py | 65 ++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 LeetCode/0073_Set Matrix Zeroes.py diff --git a/LeetCode/0073_Set Matrix Zeroes.py b/LeetCode/0073_Set Matrix Zeroes.py new file mode 100644 index 0000000..70cecee --- /dev/null +++ b/LeetCode/0073_Set Matrix Zeroes.py @@ -0,0 +1,65 @@ +# SOLUTIONS 1 + +class Solution(object): + def setZeroes(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: void Do not return anything, modify matrix in-place instead. + """ + R = len(matrix) + C = len(matrix[0]) + rows, cols = set(), set() + + # Essentially, we mark the rows and columns that are to be made zero + for i in range(R): + for j in range(C): + if matrix[i][j] == 0: + rows.add(i) + cols.add(j) + + # Iterate over the array once again and using the rows and cols sets, update the elements + for i in range(R): + for j in range(C): + if i in rows or j in cols: + matrix[i][j] = 0 + + +#SOLUTIONS 2 + +class Solution(object): + def setZeroes(self, matrix): + """ + :type matrix: List[List[int]] + :rtype: void Do not return anything, modify matrix in-place instead. + """ + is_col = False + R = len(matrix) + C = len(matrix[0]) + for i in range(R): + # Since first cell for both first row and first column is the same i.e. matrix[0][0] + # We can use an additional variable for either the first row/column. + # For this solution we are using an additional variable for the first column + # and using matrix[0][0] for the first row. + if matrix[i][0] == 0: + is_col = True + for j in range(1, C): + # If an element is zero, we set the first element of the corresponding row and column to 0 + if matrix[i][j] == 0: + matrix[0][j] = 0 + matrix[i][0] = 0 + + # Iterate over the array once again and using the first row and first column, update the elements. + for i in range(1, R): + for j in range(1, C): + if not matrix[i][0] or not matrix[0][j]: + matrix[i][j] = 0 + + # See if the first row needs to be set to zero as well + if matrix[0][0] == 0: + for j in range(C): + matrix[0][j] = 0 + + # See if the first column needs to be set to zero as well + if is_col: + for i in range(R): + matrix[i][0] = 0 \ No newline at end of file From d360c4b8f3c81e9663a97236fb29a968d91a170d Mon Sep 17 00:00:00 2001 From: David Banda Date: Sun, 4 Oct 2020 10:35:45 -0600 Subject: [PATCH 051/204] Add the solution to the 0189_Rotate_Array.py file --- LeetCode/0189_Rotate_Array.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 LeetCode/0189_Rotate_Array.py diff --git a/LeetCode/0189_Rotate_Array.py b/LeetCode/0189_Rotate_Array.py new file mode 100644 index 0000000..b72eef1 --- /dev/null +++ b/LeetCode/0189_Rotate_Array.py @@ -0,0 +1,6 @@ +class Solution: + def rotate(self, nums: List[int], k: int) -> None: + for i in range(k): + lastValue = nums.pop() + nums.insert(0, lastValue) + return nums \ No newline at end of file From 3b9a7bd1e2b650f6509634e63ee94639578f8405 Mon Sep 17 00:00:00 2001 From: matheusphalves Date: Sun, 4 Oct 2020 14:28:37 -0300 Subject: [PATCH 052/204] Added 0206_Reverse_Linked_List.py --- LeetCode/0206_Reverse_Linked_List.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0206_Reverse_Linked_List.py diff --git a/LeetCode/0206_Reverse_Linked_List.py b/LeetCode/0206_Reverse_Linked_List.py new file mode 100644 index 0000000..a659b0c --- /dev/null +++ b/LeetCode/0206_Reverse_Linked_List.py @@ -0,0 +1,15 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution(object): + def reverseList(self, head, auxNode=None): #recursive mode + if(head==None): + return auxNode + else: + return self.reverseList(head.next, ListNode(head.val, auxNode)) + """ + :type head: ListNode + :rtype: ListNode + """ \ No newline at end of file From 429d3641a5dd97a26d4b332c567ff86308a2ce54 Mon Sep 17 00:00:00 2001 From: "J.M. Dana" Date: Sun, 4 Oct 2020 20:14:22 +0200 Subject: [PATCH 053/204] Solution to 0003_Longest_Substring_Without_Repeating_Characters --- ...ngest_Substring_Without_Repeating_Characters.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/0003_Longest_Substring_Without_Repeating_Characters.py diff --git a/LeetCode/0003_Longest_Substring_Without_Repeating_Characters.py b/LeetCode/0003_Longest_Substring_Without_Repeating_Characters.py new file mode 100644 index 0000000..2a8162f --- /dev/null +++ b/LeetCode/0003_Longest_Substring_Without_Repeating_Characters.py @@ -0,0 +1,14 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + map_chars = {} + longest = 0 + j = 0 + + for i in range(0, len(s)): + if s[i] in map_chars.keys(): + j = max(j, map_chars[s[i]] + 1) + + longest = max(longest, i - j + 1) + map_chars[s[i]] = i + + return longest \ No newline at end of file From b194104b8e5a2e15bdf9cdebf03f4eb1dd0ef0b7 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sun, 4 Oct 2020 20:50:51 +0200 Subject: [PATCH 054/204] Delete .DS_Store --- .DS_Store | Bin 8196 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 4ddc034a1a008d47dd805c4bb29823601395dd57..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMPfrs;6n|3?wji+lZ`4C0G0{Lw2?}0}rPL_VgoY&u0fgOlC>yssb$1H_Vj3@g z1C8E{U%E*_M_Cj*W>k&CYN7{>*#x+stg=763@9lp6(z z0f2%RN3|WhLmJofE7T%^qzjRtKUn!uEz1hUkfjtz1|$QL0m*=5Kr-;JFo4f&-jpMr z`$8*w$$(_wzhr=)4{^LWCIc)B^p6hg{1O1M8O46XvC0RC@c@$nmIa~)8xgLE!j%Li z1`+Nkj|Xg)H% zowd3GOQ#Ks87Nb}eR}!JeDYzkUY|QwU)-p9H$YyaE3{VP!UmMUsE;1`61J$z;b}F8 z1M?JEO(sWL)#W1&8wG9y#g7M5z#s?I*m8@(nm-yv%XGa&;wy_ue#`pH3%HX-ttJ7q&FN&?WMe9=4RH{UFt3H2w8_&R))EzXEJ-SM!UG|NB3x9+FoZEk!LVdfpZrWX18J@u_cnk00GyH(x@P~Ae0dkfMlM!;6Opqj* zBva%jnI^NsJ5sr&XDXotk|o5@Ev?^8Ef)^6sohUY@2dMLG*|78I?k?sPbGMIp}96S z$F`WAM;%{}eExHmWRnauo`EJ2GREuw>qo!;Z+v1hqGUia&@cu_b6QKMFkIya#=*$E z){f(~h8J(#t}M`Z!Okzo5&d!;vHFK0j^k*`eUbr|1)>C-d=cQ&AUnxGLmBuBYmPGn From b91b1b996f894a38d9345e663b9941034fe802ab Mon Sep 17 00:00:00 2001 From: ayush_manglani <61349816+Ayushmanglani@users.noreply.github.com> Date: Mon, 5 Oct 2020 00:28:38 +0530 Subject: [PATCH 055/204] #0046_Permutations.py --- LeetCode/Permutations.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/Permutations.py diff --git a/LeetCode/Permutations.py b/LeetCode/Permutations.py new file mode 100644 index 0000000..4456739 --- /dev/null +++ b/LeetCode/Permutations.py @@ -0,0 +1,12 @@ +class Solution: + def permutations(self, nums: List[int]): + if not nums: + yield [] + for num in nums: + remaining = list(nums) + remaining.remove(num) + for perm in self.permutations(remaining): + yield [num] + list(perm) + + def permute(self, nums: List[int]) -> List[List[int]]: + return list(self.permutations(nums)) From 50b0ab07dbe3d5ef8e827135bf9fed9e6970b874 Mon Sep 17 00:00:00 2001 From: ayush_manglani <61349816+Ayushmanglani@users.noreply.github.com> Date: Mon, 5 Oct 2020 00:29:53 +0530 Subject: [PATCH 056/204] Created 0046_Permutations.py --- LeetCode/{Permutations.py => 0046_Permutations.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{Permutations.py => 0046_Permutations.py} (100%) diff --git a/LeetCode/Permutations.py b/LeetCode/0046_Permutations.py similarity index 100% rename from LeetCode/Permutations.py rename to LeetCode/0046_Permutations.py From b61fea700aafca89cd76d8b891fba0b6eed46a85 Mon Sep 17 00:00:00 2001 From: Harsh Vartak <50980498+Harshvartak@users.noreply.github.com> Date: Mon, 5 Oct 2020 00:57:27 +0530 Subject: [PATCH 057/204] Create 0412_Fizz Buzz.py --- LeetCode/0412_Fizz Buzz.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 LeetCode/0412_Fizz Buzz.py diff --git a/LeetCode/0412_Fizz Buzz.py b/LeetCode/0412_Fizz Buzz.py new file mode 100644 index 0000000..fe6d00b --- /dev/null +++ b/LeetCode/0412_Fizz Buzz.py @@ -0,0 +1,4 @@ +class Solution(object): + def fizzBuzz(self, n): + return [str(i) * (i % 3 != 0 and i % 5 != 0) + "Fizz" * (i % 3 == 0) + "Buzz" * (i % 5 == 0) + for i in range(1, n + 1)] From 32676f8dd6565a12e27c600749206c1b8f2ed9fa Mon Sep 17 00:00:00 2001 From: "J.M. Dana" Date: Sun, 4 Oct 2020 21:28:58 +0200 Subject: [PATCH 058/204] Solution for 0008_String_to_Integer --- LeetCode/0008_String_to_Integer.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 LeetCode/0008_String_to_Integer.py diff --git a/LeetCode/0008_String_to_Integer.py b/LeetCode/0008_String_to_Integer.py new file mode 100644 index 0000000..8364817 --- /dev/null +++ b/LeetCode/0008_String_to_Integer.py @@ -0,0 +1,26 @@ +class Solution: + def myAtoi(self, s: str) -> int: + INT_MAX = (1 << 31) - 1 + INT_MIN = -(1 << 31) + + ret = 0 + s = s.strip() + + if s == "": + return ret + + negate = -1 if s[0] == '-' else 1 + + if s[0] in ('+', '-'): + s = s[1::] + + for c in s: + if not '0' <= c <= '9': + break + + ret = ret * 10 + ord(c) - ord('0') + + ret *= negate + ret = min(max(ret, INT_MIN), INT_MAX) + + return ret \ No newline at end of file From 6223ea7fe800e82c587bdbc29d1f3cf531e05f8c Mon Sep 17 00:00:00 2001 From: anuranjanpandey Date: Mon, 5 Oct 2020 01:03:04 +0530 Subject: [PATCH 059/204] Solution to 0532 - K-diff Pairs in an Array --- LeetCode/0523_K_diff_Pairs_in_an_Array.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/0523_K_diff_Pairs_in_an_Array.py diff --git a/LeetCode/0523_K_diff_Pairs_in_an_Array.py b/LeetCode/0523_K_diff_Pairs_in_an_Array.py new file mode 100644 index 0000000..ae814ec --- /dev/null +++ b/LeetCode/0523_K_diff_Pairs_in_an_Array.py @@ -0,0 +1,14 @@ +from collections import Counter +class Solution: + def findPairs(self, nums: List[int], k: int) -> int: + ans = 0 + c = Counter(nums) + if k == 0: + for val in c.values(): + if val > 1: + ans += 1 + return ans + for i in c.keys(): + if i + k in c.keys(): + ans += 1 + return ans \ No newline at end of file From a14d962bf9502e22a58985248229e6af554aedf5 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sun, 4 Oct 2020 21:33:32 +0200 Subject: [PATCH 060/204] Update README.md --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 73f586e..b724687 100644 --- a/README.md +++ b/README.md @@ -33,10 +33,16 @@ To contribute make sure the Algorithm isn't commited yet! Make sure to add the n Please make sure your file is in the `LeetCode`-Folder and Named like this: `0001_TwoSum.py` -> 4-digit Number of the LeetCode Issue, Underscore, LeetCodeName +### Opening Issues +When you open an issue, please make sure the Problem is not already implemented (Look at Code/Leetcode for the Problemnumber). +Opened Issues by existing Problem will be closed & PR made to this Issue marked as **spam** +The Contributer who opened an issue will be assigned prefered to the issue. If there is no PR within about 7 Days the issue will be assigned to another Contributer. + ### Pull Requests Only Pull Requests **joined with an Issue** and matching the **naming-conventions** (See Folders and Files) will be merged! If there is no Issue joined in the PR your PR will be labeld as **spam** and closed. If your code don't passes the Check on LeetCode.com your PR will be labeld as **"invalid"** and the Issue stays open for the next PR! +If your PR doesn' follow the Contributing Guidelines of this Repository it will be also marked as **spam** and closed! ## Getting Started * Fork this repository (Click the Form button, top right of this page) From 92113ae0e2f2f4756fb8ab6226fe1f757abff3d3 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sun, 4 Oct 2020 21:34:25 +0200 Subject: [PATCH 061/204] Update CONTRIBUTING.md --- CONTRIBUTING.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c0b781c..a64b946 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -4,10 +4,16 @@ Please make sure your file is in the `LeetCode`-Folder and Named like this: `0001_TwoSum.py` -> 4-digit Number of the LeetCode Issue, Underscore, LeetCodeName -## Pull Requests +### Opening Issues +When you open an issue, please make sure the Problem is not already implemented (Look at Code/Leetcode for the Problemnumber). +Opened Issues by existing Problem will be closed & PR made to this Issue marked as **spam** +The Contributer who opened an issue will be assigned prefered to the issue. If there is no PR within about 7 Days the issue will be assigned to another Contributer. + +### Pull Requests Only Pull Requests **joined with an Issue** and matching the **naming-conventions** (See Folders and Files) will be merged! If there is no Issue joined in the PR your PR will be labeld as **spam** and closed. If your code don't passes the Check on LeetCode.com your PR will be labeld as **"invalid"** and the Issue stays open for the next PR! +If your PR doesn' follow the Contributing Guidelines of this Repository it will be also marked as **spam** and closed! ## Which PR will be accepted? * Ones you are assigned to From 701c0b1fbc8208baa04e248623f6b521b697ab6a Mon Sep 17 00:00:00 2001 From: Giorgi Beriashvili Date: Sun, 4 Oct 2020 23:27:45 +0400 Subject: [PATCH 062/204] Add the solution for "0383 - Ransom Note" problem Resolves #264 --- LeetCode/0383_RansomNote.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/0383_RansomNote.py diff --git a/LeetCode/0383_RansomNote.py b/LeetCode/0383_RansomNote.py new file mode 100644 index 0000000..ee10ec7 --- /dev/null +++ b/LeetCode/0383_RansomNote.py @@ -0,0 +1,13 @@ +class Solution: + def canConstruct(self, ransomNote: str, magazine: str) -> bool: + length = len(magazine) + + for index in range(len(ransomNote)): + if ransomNote[index] in magazine: + match = magazine.find(ransomNote[index]) + + magazine = magazine[:match] + magazine[match + 1 :] + else: + return False + if length - len(magazine) == len(ransomNote): + return True From af51600b29288fac516d2b66786c0a67697f79af Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sun, 4 Oct 2020 21:54:31 +0200 Subject: [PATCH 063/204] Delete pyhtonalgorithms-issues.md --- .../ISSUE_TEMPLATE/pyhtonalgorithms-issues.md | 25 ------------------- 1 file changed, 25 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/pyhtonalgorithms-issues.md diff --git a/.github/ISSUE_TEMPLATE/pyhtonalgorithms-issues.md b/.github/ISSUE_TEMPLATE/pyhtonalgorithms-issues.md deleted file mode 100644 index 2b5a20a..0000000 --- a/.github/ISSUE_TEMPLATE/pyhtonalgorithms-issues.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -name: PyhtonAlgorithms Issues -about: Template to commit an Issue -title: '' -labels: '' -assignees: '' - ---- - -### Subject of the issue -Describe your issue here. - -### Your environment -* version of angular-translate -* version of angular -* which browser and its version - -### Steps to reproduce -Tell us how to reproduce this issue. - -### Expected behaviour -Tell us what should happen - -### Actual behaviour -Tell us what happens instead From bf4dcd0124e6dd196d9dde871c23c2c9660e4401 Mon Sep 17 00:00:00 2001 From: "J.M. Dana" Date: Sun, 4 Oct 2020 21:55:24 +0200 Subject: [PATCH 064/204] Solution for 0020_Valid_Parentheses --- LeetCode/0020_Valid_Parentheses.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 LeetCode/0020_Valid_Parentheses.py diff --git a/LeetCode/0020_Valid_Parentheses.py b/LeetCode/0020_Valid_Parentheses.py new file mode 100644 index 0000000..e2e41c5 --- /dev/null +++ b/LeetCode/0020_Valid_Parentheses.py @@ -0,0 +1,16 @@ +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + openbrackets = ('(', '[', '{') + matches = ('()', '[]', '{}') + + for c in s: + if c in openbrackets: + stack.append(c) + else: + if len(stack) < 1 or stack[-1] + c not in matches: + return False + + stack.pop() + + return len(stack) == 0 \ No newline at end of file From 555fa8bb5f8475e30d9dcda60277bee6bb2c7096 Mon Sep 17 00:00:00 2001 From: "J.M. Dana" Date: Sun, 4 Oct 2020 22:11:05 +0200 Subject: [PATCH 065/204] Solution for 0017_Letter_Combinations_of_a_Phone_Number --- ...7_Letter_Combinations_of_a_Phone_Number.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0017_Letter_Combinations_of_a_Phone_Number.py diff --git a/LeetCode/0017_Letter_Combinations_of_a_Phone_Number.py b/LeetCode/0017_Letter_Combinations_of_a_Phone_Number.py new file mode 100644 index 0000000..e44ffe4 --- /dev/null +++ b/LeetCode/0017_Letter_Combinations_of_a_Phone_Number.py @@ -0,0 +1,19 @@ +import itertools +from typing import List + +class Solution: + def letterCombinations(self, digits: str) -> List[str]: + keyboard = { + '2': "abc", + '3': "def", + '4': "ghi", + '5': "jkl", + '6': "mno", + '7': "pqrs", + '8': "tuv", + '9': "wxyz", + } + + pressed = [keyboard[c] for c in digits] + + return [''.join(p) for p in itertools.product(*pressed) if p != ()] \ No newline at end of file From 8b129b534af884a44d0ed5275c27f1a1755a10f7 Mon Sep 17 00:00:00 2001 From: Giorgi Beriashvili Date: Mon, 5 Oct 2020 00:22:56 +0400 Subject: [PATCH 066/204] Fix the solution for "0383 - Ransom Note" problem Resolves #264 --- LeetCode/0383_RansomNote.py | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/LeetCode/0383_RansomNote.py b/LeetCode/0383_RansomNote.py index ee10ec7..4eb197b 100644 --- a/LeetCode/0383_RansomNote.py +++ b/LeetCode/0383_RansomNote.py @@ -1,13 +1,6 @@ class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: - length = len(magazine) - - for index in range(len(ransomNote)): - if ransomNote[index] in magazine: - match = magazine.find(ransomNote[index]) - - magazine = magazine[:match] + magazine[match + 1 :] - else: - return False - if length - len(magazine) == len(ransomNote): - return True + return all( + ransomNote.count(letter) <= magazine.count(letter) + for letter in set(ransomNote) + ) From c91fa1e909c04f809c60c2272a738a9ca7723d89 Mon Sep 17 00:00:00 2001 From: Arihant416 Date: Mon, 5 Oct 2020 06:19:18 +0530 Subject: [PATCH 067/204] Added Range Sum of BST --- LeetCode/0938_Range_Sum_of_BST.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0938_Range_Sum_of_BST.py diff --git a/LeetCode/0938_Range_Sum_of_BST.py b/LeetCode/0938_Range_Sum_of_BST.py new file mode 100644 index 0000000..3db83d4 --- /dev/null +++ b/LeetCode/0938_Range_Sum_of_BST.py @@ -0,0 +1,15 @@ +class Solution: + def __init__(self): + self.ans = 0 + + def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int: + def dfs(node): + if node: + if L <= node.val <= R: + self.ans += node.val + if L < node.val: + dfs(node.left) + if node.val < R: + dfs(node.right) + dfs(root) + return self.ans From b223c01ce5efe39e19da41c4c8abafece559a273 Mon Sep 17 00:00:00 2001 From: ChillOutFlim <72233142+ChillOutFlim@users.noreply.github.com> Date: Sun, 4 Oct 2020 20:46:31 -0500 Subject: [PATCH 068/204] just a few readability improvements --- CONTRIBUTING.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a64b946..04b4a9a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,10 +12,10 @@ The Contributer who opened an issue will be assigned prefered to the issue. If t ### Pull Requests Only Pull Requests **joined with an Issue** and matching the **naming-conventions** (See Folders and Files) will be merged! If there is no Issue joined in the PR your PR will be labeld as **spam** and closed. -If your code don't passes the Check on LeetCode.com your PR will be labeld as **"invalid"** and the Issue stays open for the next PR! +If your code don't passes the Check on LeetCode.com your PR will be labled as **"invalid"** and the Issue stays open for the next PR! If your PR doesn' follow the Contributing Guidelines of this Repository it will be also marked as **spam** and closed! -## Which PR will be accepted? +## Which PR's will be accepted? * Ones you are assigned to * Your PR has to link the Issue * Your Solution must be correct - you can check ist on LeetCode (submit) if it works on different test-cases From 4f2f6aebf8fbf8dab1b3db86469ee46e673d6919 Mon Sep 17 00:00:00 2001 From: ANURANJAN PANDEY Date: Mon, 5 Oct 2020 08:37:16 +0530 Subject: [PATCH 069/204] Added newline at end of file --- LeetCode/0523_K_diff_Pairs_in_an_Array.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LeetCode/0523_K_diff_Pairs_in_an_Array.py b/LeetCode/0523_K_diff_Pairs_in_an_Array.py index ae814ec..1e96cc0 100644 --- a/LeetCode/0523_K_diff_Pairs_in_an_Array.py +++ b/LeetCode/0523_K_diff_Pairs_in_an_Array.py @@ -11,4 +11,4 @@ def findPairs(self, nums: List[int], k: int) -> int: for i in c.keys(): if i + k in c.keys(): ans += 1 - return ans \ No newline at end of file + return ans From 069354d31461ea41766cb40c02b71ab13641ebf3 Mon Sep 17 00:00:00 2001 From: Sourab Maity <62734958+SOURAB-BAPPA@users.noreply.github.com> Date: Mon, 5 Oct 2020 08:51:26 +0530 Subject: [PATCH 070/204] Update 0060 - Permutation_Sequence.py after LeetCode success --- LeetCode/0060 - Permutation_Sequence.py | 23 ++++++++--------------- 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/LeetCode/0060 - Permutation_Sequence.py b/LeetCode/0060 - Permutation_Sequence.py index 06f45ba..d28e294 100644 --- a/LeetCode/0060 - Permutation_Sequence.py +++ b/LeetCode/0060 - Permutation_Sequence.py @@ -1,23 +1,16 @@ +from itertools import permutations class Solution: data = [] def getPermutation(self, n: int, k: int) -> str: + self.data = [] string = [] for i in range(1, n+1): string.append(str(i)) - self.permutations(string, 0, len(string)) - return self.data[k-1] - - def permutations(self, string, val, length): - if val == length - 1: - self.data.append("".join(string)) - else: - for i in range(val, length): - string[val], string[i] = string[i], string[val] - self.permutations(string, val + 1, length) - string[val], string[i] = string[i], string[val] - + string = list(permutations(string)) + temp = string[k-1] + string = [] + string.append("".join(temp)) + return string[0] -user = Solution() -output = user.getPermutation(int(input("Input: n=")), int(input("k="))) -print("\nOutput: {}".format(output)) + From 8aa0cae4e7ccc6cdb4985d948ad168de5900f035 Mon Sep 17 00:00:00 2001 From: ANURANJAN PANDEY Date: Mon, 5 Oct 2020 09:06:14 +0530 Subject: [PATCH 071/204] 1288 - Remove Covered Intervals --- LeetCode/1288_Remove_Covered_Intervals.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/1288_Remove_Covered_Intervals.py diff --git a/LeetCode/1288_Remove_Covered_Intervals.py b/LeetCode/1288_Remove_Covered_Intervals.py new file mode 100644 index 0000000..143dc05 --- /dev/null +++ b/LeetCode/1288_Remove_Covered_Intervals.py @@ -0,0 +1,11 @@ +class Solution: + def removeCoveredIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort(key=lambda x: (x[0], -x[1])) + inside = 0 + right = -1 + for i, j in intervals: + if j <= right: + inside += 1 + else: + right = j + return len(intervals) - inside From 6ac893b4d2961137271f0e369204e9cc93749605 Mon Sep 17 00:00:00 2001 From: Yash Chaudhary Date: Mon, 5 Oct 2020 10:28:05 +0530 Subject: [PATCH 072/204] 0078_Subsets.py --- LeetCode/0078_Subsets.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LeetCode/0078_Subsets.py diff --git a/LeetCode/0078_Subsets.py b/LeetCode/0078_Subsets.py new file mode 100644 index 0000000..23fccc3 --- /dev/null +++ b/LeetCode/0078_Subsets.py @@ -0,0 +1,21 @@ +#using backtracking approach + +class Solution: + def subsets(self, nums: List[int]) -> List[List[int]]: + def backtrack(first = 0, curr = []): + # if the combination is done + if len(curr) == k: + output.append(curr[:]) + for i in range(first, n): + # add nums[i] into the current combination + curr.append(nums[i]) + # use next integers to complete the combination + backtrack(i + 1, curr) + # backtrack + curr.pop() + + output = [] + n = len(nums) + for k in range(n + 1): + backtrack() + return output From 267223782c0f08f167971c53184e6de6a7090b88 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 5 Oct 2020 13:25:20 +0800 Subject: [PATCH 073/204] Added the solution for "0058 - Length of Last Word" problem --- LeetCode/0058_Length_of_Last_Word.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 LeetCode/0058_Length_of_Last_Word.py diff --git a/LeetCode/0058_Length_of_Last_Word.py b/LeetCode/0058_Length_of_Last_Word.py new file mode 100644 index 0000000..db53f9f --- /dev/null +++ b/LeetCode/0058_Length_of_Last_Word.py @@ -0,0 +1,6 @@ +class Solution: + def lengthOfLastWord(self, s: str) -> int: + try: + return len(s.split()[-1]) + except IndexError: + return 0 From 37655bda8286c19887bbb4e4213763da87b32c04 Mon Sep 17 00:00:00 2001 From: Yash Nagare Date: Mon, 5 Oct 2020 11:15:47 +0530 Subject: [PATCH 074/204] Added solution for 0728-Self Dividing Numbers --- LeetCode/0728_Self_Dividing_Numbers.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/0728_Self_Dividing_Numbers.py diff --git a/LeetCode/0728_Self_Dividing_Numbers.py b/LeetCode/0728_Self_Dividing_Numbers.py new file mode 100644 index 0000000..af5a2f0 --- /dev/null +++ b/LeetCode/0728_Self_Dividing_Numbers.py @@ -0,0 +1,10 @@ +class Solution: + def selfDividingNumbers(self, left: int, right: int) -> List[int]: + result = [] + for i in range(left, right+1): + for char in str(i): + if int(char)==0 or i % int(char)!=0: + break + else: + result.append(i) + return result \ No newline at end of file From bb1d6afba1e2c4f3a3c26df11ef3c90547e92af4 Mon Sep 17 00:00:00 2001 From: Calm-23 Date: Mon, 5 Oct 2020 11:22:17 +0530 Subject: [PATCH 075/204] 0567_Permutations_in_String.py added --- LeetCode/0567_Permutation_in_String.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0567_Permutation_in_String.py diff --git a/LeetCode/0567_Permutation_in_String.py b/LeetCode/0567_Permutation_in_String.py new file mode 100644 index 0000000..c8c03fb --- /dev/null +++ b/LeetCode/0567_Permutation_in_String.py @@ -0,0 +1,12 @@ +#Sliding Window Approach +from collections import Counter +class Solution: + def checkInclusion(self, s1, s2): + d1, d2 = Counter(s1), Counter(s2[:len(s1)]) + for start in range(len(s1), len(s2)): + if d1 == d2: return True + d2[s2[start]] += 1 + d2[s2[start-len(s1)]] -= 1 + if d2[s2[start-len(s1)]] == 0: + del d2[s2[start-len(s1)]] + return d1 == d2 \ No newline at end of file From c4a99213de4bf57aa58f4dc623fc087889f0181f Mon Sep 17 00:00:00 2001 From: Fergus Yip Date: Mon, 5 Oct 2020 16:53:54 +1100 Subject: [PATCH 076/204] Add solutions to Linked List Cycle --- LeetCode/0141_Linked_List_Cycle.py | 39 ++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 LeetCode/0141_Linked_List_Cycle.py diff --git a/LeetCode/0141_Linked_List_Cycle.py b/LeetCode/0141_Linked_List_Cycle.py new file mode 100644 index 0000000..c26485b --- /dev/null +++ b/LeetCode/0141_Linked_List_Cycle.py @@ -0,0 +1,39 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + ''' + Solution using Floyd's cycle-finding algorithm (tortoise and hare) + ''' + + def hasCycle(self, head: ListNode) -> bool: + if not head or not head.next: + return False + + fast = slow = head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + # If there is a cycle, fast will inevitably be on the same node as + # slow. + if fast is slow: + return True + return False + + +class SolutionO1: + ''' + Solution to follow up. Disregards contents of each ListNode. + ''' + + def hasCycle(self, head: ListNode) -> bool: + while head: + if head.val is None: + return True + head.val = None + head = head.next + return False From e021362ef8199e0b4b164581a5403042225a9051 Mon Sep 17 00:00:00 2001 From: Calm-23 Date: Mon, 5 Oct 2020 11:24:44 +0530 Subject: [PATCH 077/204] 0567_Permutations_in_String.py added --- ...67_Permutation_in_String.py => 0567_Permutations_in_String.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{0567_Permutation_in_String.py => 0567_Permutations_in_String.py} (100%) diff --git a/LeetCode/0567_Permutation_in_String.py b/LeetCode/0567_Permutations_in_String.py similarity index 100% rename from LeetCode/0567_Permutation_in_String.py rename to LeetCode/0567_Permutations_in_String.py From acda2abda81bcc45e362812873af5b97c583d71c Mon Sep 17 00:00:00 2001 From: Amogh Rajesh Desai Date: Mon, 5 Oct 2020 14:55:45 +0530 Subject: [PATCH 078/204] Solution to 0121_Best_Time_to_Buy_and_Sell_Stock solves issue #291 --- LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py diff --git a/LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py b/LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py new file mode 100644 index 0000000..bd751d4 --- /dev/null +++ b/LeetCode/0121_Best_Time_to_Buy_and_Sell_Stock.py @@ -0,0 +1,11 @@ +class Solution: + def maxProfit(self, prices: List[int]) -> int: + if len(prices) == 0: + return 0 + profit = 0 + mincost = prices[0] + + for i in range(1, len(prices)): + profit = max(profit, prices[i] - mincost) + mincost = min(mincost, prices[i]) + return profit \ No newline at end of file From 41adc2f3b54f458745116f15ed268d3a5fe917ec Mon Sep 17 00:00:00 2001 From: tejasbirsingh Date: Mon, 5 Oct 2020 14:57:46 +0530 Subject: [PATCH 079/204] Add Gas Station Problem --- LeetCode/0134_Gas_Station.py | 41 ++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 LeetCode/0134_Gas_Station.py diff --git a/LeetCode/0134_Gas_Station.py b/LeetCode/0134_Gas_Station.py new file mode 100644 index 0000000..161388d --- /dev/null +++ b/LeetCode/0134_Gas_Station.py @@ -0,0 +1,41 @@ +""" +134. Gas Station Problem + +Problem:- +There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. +You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). +You begin the journey with an empty tank at one of the gas stations. +Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. + +Input:- gas = [1,2,3,4,5], gas is the array consisting of the gas can get at i th stop + cost= [3,4,5,1,2], cost is the array consisting of the cost to travel from i to i+1 index + +Output:- 3, we have to return the index from where we can start journey and traverse all stops in clockwise manner + +Time complexity :- O(N) where N is the number is the size of array(stops) +Space complexity:- O(1) + +""" + +class Solution: + def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int: + # total_fuel variable is maintained to check if path is possible or not if sum(gas) < sum(cost) return -1 + n = len(gas) + curr_fuel = 0 + total_fuel = 0 + start_idx = 0 + + for i in range(n): + curr_fuel += gas[i]-cost[i] + total_fuel += gas[i]-cost[i] + # at any index if fuel becomes less than 0 then we have to choose new starting index + if curr_fuel < 0: + # start_idx will be i+1 because at i th index out curr_fuel became < 0 + # so we start from any index between start_idx and i there will be no valid start_idx + start_idx = i+1 + # reset the curr_fuel to 0 as we have chose new start_idx + curr_fuel = 0 + # at last check if start_idx is less than n and total_fuel is not less than 0 return start_idx else -1 + return start_idx if start_idx < n and total_fuel>=0 else -1 + + From ab9e85dcb677298a17292a97a5117baa642b6d6b Mon Sep 17 00:00:00 2001 From: PrachiSinghal86 <36899384+PrachiSinghal86@users.noreply.github.com> Date: Mon, 5 Oct 2020 15:42:07 +0530 Subject: [PATCH 080/204] Add files via upload Solution to problem 1046 --- LeetCode/1046_Last Stone Weight.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 LeetCode/1046_Last Stone Weight.py diff --git a/LeetCode/1046_Last Stone Weight.py b/LeetCode/1046_Last Stone Weight.py new file mode 100644 index 0000000..9a955e4 --- /dev/null +++ b/LeetCode/1046_Last Stone Weight.py @@ -0,0 +1,26 @@ +import bisect +class Solution: + def lastStoneWeight(self, stones: List[int]) -> int: + stones.sort() + + l=len(stones) + while l>1: + + if stones[l-1]==stones[l-2]: + stones.pop() + stones.pop() + l=l-2 + else: + x=stones[l-1]-stones[l-2] + + stones.pop() + stones.pop() + bisect.insort(stones,x) + l-=1 + try: + return stones[0] + except: + return 0 + + + \ No newline at end of file From 0a11682bb0730924aeea39a62745aa1f9a78912a Mon Sep 17 00:00:00 2001 From: PrachiSinghal86 <36899384+PrachiSinghal86@users.noreply.github.com> Date: Mon, 5 Oct 2020 17:16:40 +0530 Subject: [PATCH 081/204] Solution of 0746 --- LeetCode/0746_Min_Cost_Climbing_Stairs.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 LeetCode/0746_Min_Cost_Climbing_Stairs.py diff --git a/LeetCode/0746_Min_Cost_Climbing_Stairs.py b/LeetCode/0746_Min_Cost_Climbing_Stairs.py new file mode 100644 index 0000000..30ffd1b --- /dev/null +++ b/LeetCode/0746_Min_Cost_Climbing_Stairs.py @@ -0,0 +1,16 @@ +class Solution: + def minCostClimbingStairs(self, cost: List[int]) -> int: + l=len(cost) + + if l<=2: + return 0 + a=[0]*l + a[0]=cost[0] + a[1]=cost[1] + for i in range(2,l): + a[i]=min(a[i-1],a[i-2])+cost[i] + return min(a[l-1],a[l-2]) + + + + \ No newline at end of file From 420f6304e3c1997fe7e293064b93ce11ffc429c7 Mon Sep 17 00:00:00 2001 From: Yash Chaudhary Date: Mon, 5 Oct 2020 19:37:03 +0530 Subject: [PATCH 082/204] 0347_Top K Frequent Elements.py --- LeetCode/0347_Top K Frequent Elements.py | 57 ++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 LeetCode/0347_Top K Frequent Elements.py diff --git a/LeetCode/0347_Top K Frequent Elements.py b/LeetCode/0347_Top K Frequent Elements.py new file mode 100644 index 0000000..9a828d1 --- /dev/null +++ b/LeetCode/0347_Top K Frequent Elements.py @@ -0,0 +1,57 @@ +from collections import Counter +class Solution: + def topKFrequent(self, nums: List[int], k: int) -> List[int]: + count = Counter(nums) + unique = list(count.keys()) + + def partition(left, right, pivot_index) -> int: + pivot_frequency = count[unique[pivot_index]] + # 1. move pivot to end + unique[pivot_index], unique[right] = unique[right], unique[pivot_index] + + # 2. move all less frequent elements to the left + store_index = left + for i in range(left, right): + if count[unique[i]] < pivot_frequency: + unique[store_index], unique[i] = unique[i], unique[store_index] + store_index += 1 + + # 3. move pivot to its final place + unique[right], unique[store_index] = unique[store_index], unique[right] + + return store_index + + def quickselect(left, right, k_smallest) -> None: + """ + Sort a list within left..right till kth less frequent element + takes its place. + """ + # base case: the list contains only one element + if left == right: + return + + # select a random pivot_index + pivot_index = random.randint(left, right) + + # find the pivot position in a sorted list + pivot_index = partition(left, right, pivot_index) + + # if the pivot is in its final sorted position + if k_smallest == pivot_index: + return + # go left + elif k_smallest < pivot_index: + quickselect(left, pivot_index - 1, k_smallest) + # go right + else: + quickselect(pivot_index + 1, right, k_smallest) + + n = len(unique) + # kth top frequent element is (n - k)th less frequent. + # Do a partial sort: from less frequent to the most frequent, till + # (n - k)th less frequent element takes its place (n - k) in a sorted array. + # All element on the left are less frequent. + # All the elements on the right are more frequent. + quickselect(0, n - 1, n - k) + # Return top k frequent elements + return unique[n - k:] From 86b8cb3be34f8517df9c1f0cef4941bae44831d1 Mon Sep 17 00:00:00 2001 From: Yash Chaudhary Date: Mon, 5 Oct 2020 19:37:48 +0530 Subject: [PATCH 083/204] Rename 0347_Top K Frequent Elements.py to 0347_Top_K_Frequent_Elements.py --- ...Top K Frequent Elements.py => 0347_Top_K_Frequent_Elements.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{0347_Top K Frequent Elements.py => 0347_Top_K_Frequent_Elements.py} (100%) diff --git a/LeetCode/0347_Top K Frequent Elements.py b/LeetCode/0347_Top_K_Frequent_Elements.py similarity index 100% rename from LeetCode/0347_Top K Frequent Elements.py rename to LeetCode/0347_Top_K_Frequent_Elements.py From 069984199742fc5bac1d3bf2b79d7b648bbde057 Mon Sep 17 00:00:00 2001 From: Yash Chaudhary Date: Mon, 5 Oct 2020 20:32:47 +0530 Subject: [PATCH 084/204] Create 0086_Partition_List.py --- LeetCode/0086_Partition_List.py | 36 +++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 LeetCode/0086_Partition_List.py diff --git a/LeetCode/0086_Partition_List.py b/LeetCode/0086_Partition_List.py new file mode 100644 index 0000000..6248e3e --- /dev/null +++ b/LeetCode/0086_Partition_List.py @@ -0,0 +1,36 @@ +class Solution(object): + def partition(self, head, x): + """ + :type head: ListNode + :type x: int + :rtype: ListNode + """ + + # before and after are the two pointers used to create two list + # before_head and after_head are used to save the heads of the two lists. + # All of these are initialized with the dummy nodes created. + before = before_head = ListNode(0) + after = after_head = ListNode(0) + + while head: + # If the original list node is lesser than the given x, + # assign it to the before list. + if head.val < x: + before.next = head + before = before.next + else: + # If the original list node is greater or equal to the given x, + # assign it to the after list. + after.next = head + after = after.next + + # move ahead in the original list + head = head.next + + # Last node of "after" list would also be ending node of the reformed list + after.next = None + # Once all the nodes are correctly assigned to the two lists, + # combine them to form a single list which would be returned. + before.next = after_head.next + + return before_head.next From 49ff5dab012411288b3babe13db79936627b028a Mon Sep 17 00:00:00 2001 From: Lenart Bucar Date: Mon, 5 Oct 2020 17:22:31 +0200 Subject: [PATCH 085/204] Create 0098_Validate_Binary_Search_Tree.py --- LeetCode/0098_Validate_Binary_Search_Tree.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 LeetCode/0098_Validate_Binary_Search_Tree.py diff --git a/LeetCode/0098_Validate_Binary_Search_Tree.py b/LeetCode/0098_Validate_Binary_Search_Tree.py new file mode 100644 index 0000000..35253cc --- /dev/null +++ b/LeetCode/0098_Validate_Binary_Search_Tree.py @@ -0,0 +1,16 @@ +# 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 isValidBST(self, root: TreeNode, sm=[], gt=[]) -> bool: + if root is None: + return True + + if any([root.val <= x for x in sm]) or any([root.val >= x for x in gt]): + return False + + return (root.left is None or self.isValidBST(root.left, sm, gt + [root.val])) and (root.right is None or self.isValidBST(root.right, sm + [root.val], gt)) From f612c41a4eef4c095ba4df0ebe28fccecaf04ae8 Mon Sep 17 00:00:00 2001 From: gustavoortega Date: Mon, 5 Oct 2020 10:33:27 -0500 Subject: [PATCH 086/204] solution.py --- LeetCode/0118_pascal_triangle.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 LeetCode/0118_pascal_triangle.py diff --git a/LeetCode/0118_pascal_triangle.py b/LeetCode/0118_pascal_triangle.py new file mode 100644 index 0000000..ccd4440 --- /dev/null +++ b/LeetCode/0118_pascal_triangle.py @@ -0,0 +1,9 @@ +class Solution: + def generate(self, numRows: int) -> List[List[int]]: + if numRows==0: + return [] + triangle=[[1]] + for row in range(numRows-1): + triangle.append([1]+[triangle[-1][i]+triangle[-1][i+1] for i in range(row)]+[1]) + return triangle + \ No newline at end of file From b552f00522ebd904f75d3976e286249b217acbf6 Mon Sep 17 00:00:00 2001 From: Dhawal Khapre Date: Tue, 6 Oct 2020 01:07:46 +0530 Subject: [PATCH 087/204] closes #342 --- .../1464_Maximum Product of Two Elements in an Array.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LeetCode/1464_Maximum Product of Two Elements in an Array.py diff --git a/LeetCode/1464_Maximum Product of Two Elements in an Array.py b/LeetCode/1464_Maximum Product of Two Elements in an Array.py new file mode 100644 index 0000000..83bc2db --- /dev/null +++ b/LeetCode/1464_Maximum Product of Two Elements in an Array.py @@ -0,0 +1,7 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + List.sort() + + max_product = (List[-1]-1) * (List[-2]-1) + + return max_product \ No newline at end of file From b844f3a4da4d21bdfabdf9f4895fb0181488389a Mon Sep 17 00:00:00 2001 From: Richard Wi Date: Mon, 5 Oct 2020 22:51:46 +0200 Subject: [PATCH 088/204] Solve Leet Code problem 0414 * Name: Third Maximum Number * Link: https://leetcode.com/problems/third-maximum-number/ --- LeetCode/0414_Third_Maximum_Number.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LeetCode/0414_Third_Maximum_Number.py diff --git a/LeetCode/0414_Third_Maximum_Number.py b/LeetCode/0414_Third_Maximum_Number.py new file mode 100644 index 0000000..fdf1d00 --- /dev/null +++ b/LeetCode/0414_Third_Maximum_Number.py @@ -0,0 +1,7 @@ +class Solution: + def thirdMax(self, nums: List[int]) -> int: + nums_set = sorted(set(nums), reverse=True) + if len(nums_set) >= 3: + return nums_set[2] + else: + return nums_set[0] From 8b5605ae3b815920a8100c1586752d03ace12a29 Mon Sep 17 00:00:00 2001 From: Randy Consuegra Date: Mon, 5 Oct 2020 16:11:44 -0500 Subject: [PATCH 089/204] added problem 0231 --- LeetCode/0231_Power_Of_Two.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 LeetCode/0231_Power_Of_Two.py diff --git a/LeetCode/0231_Power_Of_Two.py b/LeetCode/0231_Power_Of_Two.py new file mode 100644 index 0000000..e9304e4 --- /dev/null +++ b/LeetCode/0231_Power_Of_Two.py @@ -0,0 +1,3 @@ +class Solution: + def isPowerOfTwo(self, x: int) -> bool: + return (x != 0) and ((x & (x - 1)) == 0); \ No newline at end of file From 417e55646e963b6bf280948d9d613ebe3fe374da Mon Sep 17 00:00:00 2001 From: Patrick Ofili Date: Tue, 6 Oct 2020 01:37:29 +0100 Subject: [PATCH 090/204] Added 0079_Word_Search.py --- LeetCode/0079_Word_Search.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 LeetCode/0079_Word_Search.py diff --git a/LeetCode/0079_Word_Search.py b/LeetCode/0079_Word_Search.py new file mode 100644 index 0000000..82f56be --- /dev/null +++ b/LeetCode/0079_Word_Search.py @@ -0,0 +1,35 @@ +def exist(self, grid: List[List[str]], word: str) -> bool: + + seen = set() + + # Boundary checking + def inBound(row, col, grid): + return 0 <= row < len(grid) and 0 <= col < len(grid[0]) + + def dfs(grid, word, curr_i, row, col): + + if curr_i == len(word): + return True + + if not inBound(row, col,grid) or grid[row][col] != word[curr_i]: + return False + + seen.add((row, col)) + + # Explore possible paths + pos_paths = [(row, col + 1), (row, col - 1), (row + 1, col), (row - 1, col)] + for row_n, col_n in pos_paths: + if (row_n,col_n) not in seen: + if dfs(grid, word, curr_i + 1, row_n, col_n): + return True + + seen.remove((row,col)) + return False + + for row in range(len(grid)): + for col in range(len(grid[0])): + if grid[row][col] == word[0]: + if dfs(grid, word, 0, row, col): + return True + + return False \ No newline at end of file From 17c264f9a2a2615bd93025ae66e442462e091c53 Mon Sep 17 00:00:00 2001 From: Wanda Juan Date: Tue, 6 Oct 2020 11:20:05 +0800 Subject: [PATCH 091/204] added codes for problem 1592 --- .../1592_Rearrange_Spaces_Between_Words.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 LeetCode/1592_Rearrange_Spaces_Between_Words.py diff --git a/LeetCode/1592_Rearrange_Spaces_Between_Words.py b/LeetCode/1592_Rearrange_Spaces_Between_Words.py new file mode 100644 index 0000000..e072724 --- /dev/null +++ b/LeetCode/1592_Rearrange_Spaces_Between_Words.py @@ -0,0 +1,22 @@ +class Solution: + def reorderSpaces(self, text: str) -> str: + + if ' ' not in text: + return text + + words, new_word, space_cnt = [], '', 0 + for l in text: + if l == ' ': + if new_word != '': + words.append(new_word) + space_cnt += 1 + new_word = '' + else: + new_word = ''.join([new_word, l]) + if text[-1] != ' ': + words.append(new_word) + + if len(words) > 1: + return (' '* (space_cnt // (len(words)-1))).join(words)+ ' ' * (space_cnt % (len(words)-1)) + else: + return words[0] + ' '* space_cnt \ No newline at end of file From ee72d7917c589c4299585c434378c7a5da129b5a Mon Sep 17 00:00:00 2001 From: Wanda Juan Date: Tue, 6 Oct 2020 11:26:29 +0800 Subject: [PATCH 092/204] improved runtime efficiency --- .../1592_Rearrange_Spaces_Between_Words.py | 23 ++++--------------- 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/LeetCode/1592_Rearrange_Spaces_Between_Words.py b/LeetCode/1592_Rearrange_Spaces_Between_Words.py index e072724..cca6c53 100644 --- a/LeetCode/1592_Rearrange_Spaces_Between_Words.py +++ b/LeetCode/1592_Rearrange_Spaces_Between_Words.py @@ -1,22 +1,9 @@ class Solution: def reorderSpaces(self, text: str) -> str: + words = text.split() + space_cnt = text.count(' ') - if ' ' not in text: - return text - - words, new_word, space_cnt = [], '', 0 - for l in text: - if l == ' ': - if new_word != '': - words.append(new_word) - space_cnt += 1 - new_word = '' - else: - new_word = ''.join([new_word, l]) - if text[-1] != ' ': - words.append(new_word) - - if len(words) > 1: - return (' '* (space_cnt // (len(words)-1))).join(words)+ ' ' * (space_cnt % (len(words)-1)) + if len(words) == 1: + return words[0] + ' ' * space_cnt else: - return words[0] + ' '* space_cnt \ No newline at end of file + return (' '* (space_cnt // (len(words)-1))).join(words)+ ' ' * (space_cnt % (len(words)-1)) \ No newline at end of file From 1eea50b20459f27d1ba4078772ee64cf0b0af93e Mon Sep 17 00:00:00 2001 From: Wanda Juan Date: Tue, 6 Oct 2020 11:49:07 +0800 Subject: [PATCH 093/204] added codes for problem 1494 --- LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py diff --git a/LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py b/LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py new file mode 100644 index 0000000..c1fcb8f --- /dev/null +++ b/LeetCode/1464_Maximum_Product_Of_Two_Elements_In_An_Array.py @@ -0,0 +1,4 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + nums.sort() + return (nums[-1]-1) * (nums[-2]-1) \ No newline at end of file From dfcbe9daac5d5cbe1ee428a4d4817b45b7bd6515 Mon Sep 17 00:00:00 2001 From: Bauri <52131226@acsind.com> Date: Tue, 6 Oct 2020 10:38:51 +0530 Subject: [PATCH 094/204] Added Solution to Problem 13 Roman to Integer --- LeetCode/0013_Roman to Integer.py | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 LeetCode/0013_Roman to Integer.py diff --git a/LeetCode/0013_Roman to Integer.py b/LeetCode/0013_Roman to Integer.py new file mode 100644 index 0000000..7ec9c38 --- /dev/null +++ b/LeetCode/0013_Roman to Integer.py @@ -0,0 +1,32 @@ +class Solution: + def romanToInt(self, s: str) -> int: + + symbolValDict = { + 'I':1, + 'V':5, + 'X':10, + 'L':50, + 'C':100, + 'D':500, + 'M':1000 + } + + + i = 0 + finalDigit = 0 + while(i= nextDigit: + finalDigit += firstDigit + i+=1 + else: + finalDigit += nextDigit - firstDigit + i+=2 + else: + finalDigit += firstDigit + i+=1 + + + return finalDigit \ No newline at end of file From 82672ad3948bbf21c2c1aa02ff5d620529f00f55 Mon Sep 17 00:00:00 2001 From: Amogh Rajesh Desai Date: Tue, 6 Oct 2020 14:11:13 +0530 Subject: [PATCH 095/204] Solution to 0299_Bulls_and_Cows solves issue #334 --- LeetCode/0299_Bulls_and_Cows.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LeetCode/0299_Bulls_and_Cows.py diff --git a/LeetCode/0299_Bulls_and_Cows.py b/LeetCode/0299_Bulls_and_Cows.py new file mode 100644 index 0000000..f1253ad --- /dev/null +++ b/LeetCode/0299_Bulls_and_Cows.py @@ -0,0 +1,18 @@ +from collections import Counter +class Solution: + def getHint(self, secret: str, guess: str) -> str: + n = len(secret) + matched = [] + bulls = cows = 0 + for i in range(n): + if secret[i] == guess[i]: + bulls += 1 + + a = Counter(secret) + b = Counter(guess) + + for i in set(secret): + cows += min(a[i], b[i]) + + ans = str(bulls) + "A" + str(cows - bulls) + "B" + return ans \ No newline at end of file From 3796ffd3f8b966ecb5797b23ac8d93d14352d9b2 Mon Sep 17 00:00:00 2001 From: ANURANJAN PANDEY Date: Tue, 6 Oct 2020 14:21:37 +0530 Subject: [PATCH 096/204] Added 1009_Complement_of_base_10_integer.py --- LeetCode/1009_Complement_of_base_10_integer.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/1009_Complement_of_base_10_integer.py diff --git a/LeetCode/1009_Complement_of_base_10_integer.py b/LeetCode/1009_Complement_of_base_10_integer.py new file mode 100644 index 0000000..6ec5c64 --- /dev/null +++ b/LeetCode/1009_Complement_of_base_10_integer.py @@ -0,0 +1,11 @@ +class Solution: + def bitwiseComplement(self, N: int) -> int: + binary = bin(N)[2:] + ans = ['0'] * len(binary) + for i in range(len(binary)): + if binary[i] == '0': + ans[i] = '1' + else: + ans[i] = '0' + return int(''.join(ans), 2) + From d45257ec6ced691de4d9b46dde9214fc4f7b4eb4 Mon Sep 17 00:00:00 2001 From: adi0311 <2018308@iiitdmj.ac.in> Date: Tue, 6 Oct 2020 14:29:02 +0530 Subject: [PATCH 097/204] Merge pull request #329 from adi0311/master --- ...611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LeetCode/1611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py diff --git a/LeetCode/1611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py b/LeetCode/1611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py new file mode 100644 index 0000000..e8fd5d5 --- /dev/null +++ b/LeetCode/1611_Minimum_One_Bit_Operations_to_Make_Integers_Zero.py @@ -0,0 +1,7 @@ +class Solution: + def minimumOneBitOperations(self, n: int) -> int: + b = list(bin(n)[2:]) + temp = len(b) + for i in range(1, temp): + b[i] = str(int(b[i]) ^ int(b[i-1])) + return int(''.join(b), 2) From 3b287ebd13005b518553ac550aecc3f00989008c Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Tue, 6 Oct 2020 11:11:50 +0200 Subject: [PATCH 098/204] Update README.md --- README.md | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index b724687..46f4b1a 100644 --- a/README.md +++ b/README.md @@ -44,6 +44,9 @@ If there is no Issue joined in the PR your PR will be labeld as **spam** and clo If your code don't passes the Check on LeetCode.com your PR will be labeld as **"invalid"** and the Issue stays open for the next PR! If your PR doesn' follow the Contributing Guidelines of this Repository it will be also marked as **spam** and closed! +### Spam Users +Users who spam this Repo with PRs/Issues that does not align the Contribution Guidelines will be **blocked**. + ## Getting Started * Fork this repository (Click the Form button, top right of this page) * Clone your fork down to your local machine @@ -73,6 +76,17 @@ git push origin branch-name ## Which PR will be accepted? * Ones you are assigned to * Your PR has to link the Issue -* Your Solution must be correct - you can check ist on LeetCode (submit) if it works on different test-cases +* Your Solution must be correct - you can check first on LeetCode (submit) if it works on different test-cases + +## Which PRs will be NOT accepted? +* Ones you are NOT assigned to +* Your PR is NOT linked to the Issue you are linked to +* Your Solution is not correct +* Your PR contains more than the .py file +* PRs that "correct" Typos or spam files with comments +* PRs that "correct" Coding Styles - Please accept that everybody has a different style + +## Hacktoberfest +During October there come pretty much PRs and Issues - Please be patient because of my fulltime job I cannot be online 24/7 - I do my best to work through your PRs as soon as possible. __Thank You!__ From a86bce280bf04a6c7662af66aa26d838e0954853 Mon Sep 17 00:00:00 2001 From: Soroosh Date: Tue, 6 Oct 2020 11:20:34 +0200 Subject: [PATCH 099/204] Added the solution with time complexity of O(len(a) + len(b)) --- LeetCode/0888_Fair_Candy_Swap.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 LeetCode/0888_Fair_Candy_Swap.py diff --git a/LeetCode/0888_Fair_Candy_Swap.py b/LeetCode/0888_Fair_Candy_Swap.py new file mode 100644 index 0000000..b165ac3 --- /dev/null +++ b/LeetCode/0888_Fair_Candy_Swap.py @@ -0,0 +1,9 @@ +class Solution: + def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]: + total_a = sum(A) + total_b = sum(B) + set_b = set(B) + for candy in A: + swap_item = candy + (total_b - total_a) / 2 + if swap_item in set_b: + return [candy, candy + (total_b - total_a) / 2] \ No newline at end of file From 44a82041605cfe643a66e46f3748773041e74de6 Mon Sep 17 00:00:00 2001 From: Bauri <52131226@acsind.com> Date: Tue, 6 Oct 2020 15:49:14 +0530 Subject: [PATCH 100/204] Added Solution to Problem 88 Merge Sorted Array --- LeetCode/0088_Merge Sorted Array.py | 31 +++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 LeetCode/0088_Merge Sorted Array.py diff --git a/LeetCode/0088_Merge Sorted Array.py b/LeetCode/0088_Merge Sorted Array.py new file mode 100644 index 0000000..c70f721 --- /dev/null +++ b/LeetCode/0088_Merge Sorted Array.py @@ -0,0 +1,31 @@ +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + + ##Method1 + i=0 + while(ik): +# pos = j +# break +# j+=1 +# nums1.insert (pos,k) +# m+=1 +# for x in range(0,len(nums1)-totalLen): +# del nums1[-1] +# # print(nums1) + + \ No newline at end of file From 58a23bd99726b54edd8f29ecfc4a336462c69c47 Mon Sep 17 00:00:00 2001 From: tejasbirsingh Date: Tue, 6 Oct 2020 16:17:48 +0530 Subject: [PATCH 101/204] Add House Robber 2 --- LeetCode/0213_House_robber.py | 55 +++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 LeetCode/0213_House_robber.py diff --git a/LeetCode/0213_House_robber.py b/LeetCode/0213_House_robber.py new file mode 100644 index 0000000..c5a93f9 --- /dev/null +++ b/LeetCode/0213_House_robber.py @@ -0,0 +1,55 @@ +""" +213. House Robber II +You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically contact the police if two adjacent houses were broken into on the same night. +Given a list of non-negative integers nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police. +Input: nums = [2,3,2] +Output: 3 +Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. + +This problem is solved using Dynamic Programming +Time Complexity:- O(N) +Space Complexity: O(N) , we need to make 2 DP arrays so it takes O(2N) space + +""" +class Solution: + def rob(self, nums: List[int]) -> int: + n = len( nums ) + # base conditions + # if there is no element in array + if n==0: + return 0 + # if there is only one element in array return the element + if n==1: + return nums[0] + # if there are 2 elements then return the max value out of both as we can't choose adjacent values together + if n==2: + return max(nums[0],nums[1]) + + + def max_profit(dp): + """ + This function finds the max profit by robbing the adjacent houses using DP + Input:- DP array of size n-1 + Output:- Max profit from that DP array + """ + len_dp = len( dp ) + dp[1] = max( dp[0], dp[1] ) + for k in range( 2, len_dp ): + dp[k] = max( dp[k - 1], dp[k] + dp[k - 2] ) + + return dp[-1] + + """ + We exclude the last element in first case then find max profit + we exculde the first element in second case then find max profit + we can't take both first and last element as they are adjacent + as last house is connected to first house + """ + # find the profit excluding the last house + dp_excludingLastElement = nums[:n - 1] + profit1 = max_profit(dp_excludingLastElement) + # find the profit using the first house + dp_excludingFirstElement = nums[1:n] + profit2 = max_profit(dp_excludingFirstElement) + # return the max profit out of both the possibilites + return max( profit1, profit2 ) \ No newline at end of file From 65c455028365c92faee6cda4a26b38eea9212a39 Mon Sep 17 00:00:00 2001 From: AkshatBhat Date: Tue, 6 Oct 2020 16:20:35 +0530 Subject: [PATCH 102/204] Added 0268_Missing_Number.py --- LeetCode/0268_Missing_Number.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 LeetCode/0268_Missing_Number.py diff --git a/LeetCode/0268_Missing_Number.py b/LeetCode/0268_Missing_Number.py new file mode 100644 index 0000000..843b6dd --- /dev/null +++ b/LeetCode/0268_Missing_Number.py @@ -0,0 +1,16 @@ +class Solution: + def computeXOR(self,n:int) -> int: + if n%4==0: + return n + elif n%4==1: + return 1 + elif n%4==2: + return n+1 + else: + return 0 + def missingNumber(self, nums: List[int]) -> int: + all_xor = self.computeXOR(len(nums)) + current_xor = 0 + for i in nums: + current_xor^=i + return(all_xor^current_xor) \ No newline at end of file From c88ab092fd704603ab978fb9350ab487ecbd2add Mon Sep 17 00:00:00 2001 From: devanshi-katyal <60283765+devanshi-katyal@users.noreply.github.com> Date: Tue, 6 Oct 2020 17:13:22 +0530 Subject: [PATCH 103/204] solved strstr --- LeetCode/28_str.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 LeetCode/28_str.py diff --git a/LeetCode/28_str.py b/LeetCode/28_str.py new file mode 100644 index 0000000..5a9aa0e --- /dev/null +++ b/LeetCode/28_str.py @@ -0,0 +1,22 @@ +class Solution(object): + def strStr(self, haystack, needle): + + i = 0 + j = 0 + m = len(needle) + n = len(haystack) + if m ==0: + return 0 + while i=m: + if haystack[i] == needle[j]: + temp = i + while j Date: Tue, 6 Oct 2020 17:14:01 +0530 Subject: [PATCH 104/204] Added solution for StrStr --- LeetCode/{28_str.py => 0028_strStr.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{28_str.py => 0028_strStr.py} (100%) diff --git a/LeetCode/28_str.py b/LeetCode/0028_strStr.py similarity index 100% rename from LeetCode/28_str.py rename to LeetCode/0028_strStr.py From ab7e0f8c918bc6171b8574271b4b1c1ff43848e4 Mon Sep 17 00:00:00 2001 From: Swarn10 Date: Tue, 6 Oct 2020 18:42:01 +0530 Subject: [PATCH 105/204] Added 0036_Valid_Sudoku.py --- LeetCode/0036_Valid_Sudoku.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 LeetCode/0036_Valid_Sudoku.py diff --git a/LeetCode/0036_Valid_Sudoku.py b/LeetCode/0036_Valid_Sudoku.py new file mode 100644 index 0000000..30da2b9 --- /dev/null +++ b/LeetCode/0036_Valid_Sudoku.py @@ -0,0 +1,27 @@ +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + return self.isValidRow(board) and self.isValidCol(board) and self.isValidSquare(board) + + def isValidRow(self, board): + for row in board: + if not self.isValidUnit(row): + return False + return True + + def isValidCol(self, board): + for col in zip(*board): + if not self.isValidUnit(col): + return False + return True + + def isValidSquare(self, board): + for i in (0, 3, 6): + for j in (0, 3, 6): + square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)] + if not self.isValidUnit(square): + return False + return True + + def isValidUnit(self, unit): + array = [c for c in unit if c != '.'] + return len(set(array)) == len(array) \ No newline at end of file From 9cce32404f1e0e79183aab63abf7d679c9a654a4 Mon Sep 17 00:00:00 2001 From: utkarsh Date: Tue, 6 Oct 2020 19:07:29 +0530 Subject: [PATCH 106/204] Added a solution to LeetCode-0022 --- LeetCode/0022_GenerateParenthesis.py | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 LeetCode/0022_GenerateParenthesis.py diff --git a/LeetCode/0022_GenerateParenthesis.py b/LeetCode/0022_GenerateParenthesis.py new file mode 100644 index 0000000..0954aca --- /dev/null +++ b/LeetCode/0022_GenerateParenthesis.py @@ -0,0 +1,25 @@ +class Solution: + def generateParenthesis(self, n: int) -> List[str]: + def isValid(s: str) -> bool: + stk = [] + for b in s: + if b == '(': + stk.append(b) + else: + if stk and stk[-1] == '(': + stk.pop() + else: + return False + return stk == [] + + ans = [] + for mask in range(1<<(2*n)): + s = "" + for bit in range(2*n): + if mask & (1< Date: Tue, 6 Oct 2020 22:38:03 +0900 Subject: [PATCH 107/204] 0561_Array_Partition_I.py --- LeetCode/0561_Array_Partition_I.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 LeetCode/0561_Array_Partition_I.py diff --git a/LeetCode/0561_Array_Partition_I.py b/LeetCode/0561_Array_Partition_I.py new file mode 100644 index 0000000..1743f89 --- /dev/null +++ b/LeetCode/0561_Array_Partition_I.py @@ -0,0 +1,3 @@ +class Solution: + def arrayPairSum(self, nums: List[int]) -> int: + return sum(sorted(nums)[::2]) \ No newline at end of file From f7a4ae5900c822f50ad29d2900eb222ee27c1653 Mon Sep 17 00:00:00 2001 From: afeefaa333 Date: Tue, 6 Oct 2020 19:10:41 +0530 Subject: [PATCH 108/204] Added Python code for problem 0125-Valid Palindrome #354 --- LeetCode/0125_Valid_Palindrome.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LeetCode/0125_Valid_Palindrome.py diff --git a/LeetCode/0125_Valid_Palindrome.py b/LeetCode/0125_Valid_Palindrome.py new file mode 100644 index 0000000..acffcdd --- /dev/null +++ b/LeetCode/0125_Valid_Palindrome.py @@ -0,0 +1,18 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + alphnum = "" + #Extract only alphanumeric characters from the given string + for i in s: + #Check whether the character is a lowercase letter or a number + if ord(i)>=ord('a') and ord(i)<=ord('z') or ord(i)>=ord("0") and ord(i)<=ord("9"): + alphnum+=i + #Check whether the character is an uppercase letter. + #If yes,convert to lower case + elif ord(i)>=ord('A') and ord(i)<=ord('Z'): + i = chr(32+ord(i)) + alphnum+=i + #Reverse the alphanumeric string and check whether it is a palindrome + rev= alphnum[::-1] + result= rev==alphnum + return result + \ No newline at end of file From 08ba7b74aade83b009040baec13227dd77ad8040 Mon Sep 17 00:00:00 2001 From: Vineet-Dhaimodker Date: Tue, 6 Oct 2020 19:17:55 +0530 Subject: [PATCH 109/204] Added 1480_Running_Sum_of_1a_Array.py --- LeetCode/1480_Running_Sum_of_1d_Array.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LeetCode/1480_Running_Sum_of_1d_Array.py diff --git a/LeetCode/1480_Running_Sum_of_1d_Array.py b/LeetCode/1480_Running_Sum_of_1d_Array.py new file mode 100644 index 0000000..9697070 --- /dev/null +++ b/LeetCode/1480_Running_Sum_of_1d_Array.py @@ -0,0 +1,7 @@ +class Solution: + def runningSum(self, nums: List[int]) -> List[int]: + answers=[] + answers.append(nums[0]) + for i in range(1,len(nums)): + answers.append(answers[-1]+nums[i]) + return answers \ No newline at end of file From 5e09690745afb6b0530cb097e8c2238f6ed2af4f Mon Sep 17 00:00:00 2001 From: ishika161 <54451711+ishika161@users.noreply.github.com> Date: Tue, 6 Oct 2020 19:34:07 +0530 Subject: [PATCH 110/204] 0832_Flipping_an_Image --- LeetCode/0832_Flipping_an_Image.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/0832_Flipping_an_Image.py diff --git a/LeetCode/0832_Flipping_an_Image.py b/LeetCode/0832_Flipping_an_Image.py new file mode 100644 index 0000000..cfbe118 --- /dev/null +++ b/LeetCode/0832_Flipping_an_Image.py @@ -0,0 +1,11 @@ +class Solution: + def flipAndInvertImage(self, A: List[List[int]]) -> List[List[int]]: + for row in A: + for i in range(int((len(row) + 1) / 2)): + """ + In Python, the shortcut row[~i] = row[-i-1] = row[len(row) - 1 - i] + helps us find the i-th value of the row, counting from the right. + """ + row[i], row[~i] = row[~i] ^ 1, row[i] ^ 1 + return A + \ No newline at end of file From 66ccfbd3f93e8e306289f4dbe5dc639810f00e7b Mon Sep 17 00:00:00 2001 From: ishika161 <54451711+ishika161@users.noreply.github.com> Date: Tue, 6 Oct 2020 19:54:02 +0530 Subject: [PATCH 111/204] 1380_Lucky_Numbers_in_a_Matrix --- LeetCode/1380_Lucky_Numbers_in_a_Matrix.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 LeetCode/1380_Lucky_Numbers_in_a_Matrix.py diff --git a/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py b/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py new file mode 100644 index 0000000..44570a6 --- /dev/null +++ b/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py @@ -0,0 +1,8 @@ +class Solution: + def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: + min_n = {min(rows) for rows in matrix} + max_n = {max(columns) for columns in zip(*matrix)} + + return list(min_n & max_n) + + \ No newline at end of file From 94b169e3ef234b33d6b02e5749a88c9abd8835c0 Mon Sep 17 00:00:00 2001 From: Vineet-Dhaimodker Date: Tue, 6 Oct 2020 19:55:43 +0530 Subject: [PATCH 112/204] Added 1431_Kids_With_the_Greatest_Number_of_Candies.py --- .../1431_Kids_With_the_Greatest_Number_of_Candies.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/1431_Kids_With_the_Greatest_Number_of_Candies.py diff --git a/LeetCode/1431_Kids_With_the_Greatest_Number_of_Candies.py b/LeetCode/1431_Kids_With_the_Greatest_Number_of_Candies.py new file mode 100644 index 0000000..c6b81b6 --- /dev/null +++ b/LeetCode/1431_Kids_With_the_Greatest_Number_of_Candies.py @@ -0,0 +1,11 @@ +class Solution: + def kidsWithCandies(self, candies: List[int], extraCandies: int) -> List[bool]: + m=max(candies) + t=m-extraCandies + output=[] + for i in candies: + if i Date: Tue, 6 Oct 2020 20:10:54 +0530 Subject: [PATCH 113/204] Delete 1380_Lucky_Numbers_in_a_Matrix.py --- LeetCode/1380_Lucky_Numbers_in_a_Matrix.py | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 LeetCode/1380_Lucky_Numbers_in_a_Matrix.py diff --git a/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py b/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py deleted file mode 100644 index 44570a6..0000000 --- a/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py +++ /dev/null @@ -1,8 +0,0 @@ -class Solution: - def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: - min_n = {min(rows) for rows in matrix} - max_n = {max(columns) for columns in zip(*matrix)} - - return list(min_n & max_n) - - \ No newline at end of file From 07b5dfdb65a10486205a0b441254b5126e576033 Mon Sep 17 00:00:00 2001 From: ishika161 <54451711+ishika161@users.noreply.github.com> Date: Tue, 6 Oct 2020 20:23:55 +0530 Subject: [PATCH 114/204] 1380_Lucky_Numbers_in_a_Matrix --- LeetCode/1380_Lucky_Numbers_in_a_Matrix.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 LeetCode/1380_Lucky_Numbers_in_a_Matrix.py diff --git a/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py b/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py new file mode 100644 index 0000000..44570a6 --- /dev/null +++ b/LeetCode/1380_Lucky_Numbers_in_a_Matrix.py @@ -0,0 +1,8 @@ +class Solution: + def luckyNumbers (self, matrix: List[List[int]]) -> List[int]: + min_n = {min(rows) for rows in matrix} + max_n = {max(columns) for columns in zip(*matrix)} + + return list(min_n & max_n) + + \ No newline at end of file From 3c1494fdc96d85b2ec62b9abec7536111fec5144 Mon Sep 17 00:00:00 2001 From: ishika161 <54451711+ishika161@users.noreply.github.com> Date: Tue, 6 Oct 2020 20:40:43 +0530 Subject: [PATCH 115/204] 1374_Generate_a_String_With_Characters_That_Have_Odd_Counts --- ...te_a_String_With_Characters_That_Have_Odd_Counts.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py diff --git a/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py b/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py new file mode 100644 index 0000000..3f8c607 --- /dev/null +++ b/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py @@ -0,0 +1,10 @@ +class Solution: + def generateTheString(self, n: int) -> str: + ans=[] + if n%2==0: + ans=['x' for i in range(n-1)] + ans.append('y') + else: + ans=['x' for i in range(n)] + return ans + \ No newline at end of file From 0a2b900cb1d2e1f5e56cc44b64d41a9f4d5f156e Mon Sep 17 00:00:00 2001 From: ishika161 <54451711+ishika161@users.noreply.github.com> Date: Tue, 6 Oct 2020 20:43:12 +0530 Subject: [PATCH 116/204] 1374_Generate_a_String_With_Characters_That_Have_Odd_Counts --- ...te_a_String_With_Characters_That_Have_Odd_Counts.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py diff --git a/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py b/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py new file mode 100644 index 0000000..3f8c607 --- /dev/null +++ b/LeetCode/1374_Generate_a_String_With_Characters_That_Have_Odd_Counts.py @@ -0,0 +1,10 @@ +class Solution: + def generateTheString(self, n: int) -> str: + ans=[] + if n%2==0: + ans=['x' for i in range(n-1)] + ans.append('y') + else: + ans=['x' for i in range(n)] + return ans + \ No newline at end of file From 8209cced1662f103ace61cd99bbb37c46ede5afc Mon Sep 17 00:00:00 2001 From: Patrick Ofili Date: Tue, 6 Oct 2020 17:03:12 +0100 Subject: [PATCH 117/204] Added 0102_Binary_Tree_Level_Order_Traversal.py --- .../0102_Binary_Tree_Level_Order_Traversal.py | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 LeetCode/0102_Binary_Tree_Level_Order_Traversal.py diff --git a/LeetCode/0102_Binary_Tree_Level_Order_Traversal.py b/LeetCode/0102_Binary_Tree_Level_Order_Traversal.py new file mode 100644 index 0000000..05fe397 --- /dev/null +++ b/LeetCode/0102_Binary_Tree_Level_Order_Traversal.py @@ -0,0 +1,56 @@ +""" +Level Order Traversal - BFS + +A Tree Algorithm where the nodes in a tree are visited in a level by level fashion. +i.e Nodes at each level are processed before moving on to the next. + +Steps + 1. For every node, add to a queue. + 2. Process the node and pop from the front of the queue. + 3. Add its left and right child to the queue. + +Time complexity is O(N) since we visit every node at least once. N is the number of nodes in the tree. +Space complexity is O(N) since we make use of a queue data structure having a maximum of size N. + + +Sample Binary Tree: + + 8 + / \ + 3 10 + / \ \ + 1 6 14 + +Level-Order Traversal of this binary tree results in: +output = [[8], [3,10], [1,6,14]] +""" + +# Code implementation +def levelOrder(self, root: TreeNode) -> List[List[int]]: + import collections + output = [] + queue = collections.deque([root]) + + if root == None: + return [] + + while queue: + num_of_nodes = len(queue) + curr_level = [] + + for node in range(num_of_nodes): + curr_node = queue.popleft() + curr_level.append(curr_node.val) + + if curr_node.left: + queue.append(curr_node.left) + + if curr_node.right: + queue.append(curr_node.right) + + output.append(curr_level) + + + + return output + \ No newline at end of file From 6ccaba5ddaf9f0e7ea8f09f4b0703a6184dce198 Mon Sep 17 00:00:00 2001 From: Anusha Prabhu Date: Tue, 6 Oct 2020 21:36:08 +0530 Subject: [PATCH 118/204] Added 198 - House Robber --- LeetCode/0198_House_Robber.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0198_House_Robber.py diff --git a/LeetCode/0198_House_Robber.py b/LeetCode/0198_House_Robber.py new file mode 100644 index 0000000..097b5e6 --- /dev/null +++ b/LeetCode/0198_House_Robber.py @@ -0,0 +1,20 @@ +def rob(self, nums: List[int]) -> int: + length = len(nums) + if length == 0: + return 0 + dp = [0] * len(nums) + dp[0] = nums[0] + for i in range(1,length): + if i==1: + dp[i] = max(dp[0],nums[i]) + elif i==2: + dp[i] = dp[0]+nums[i] + else: + dp[i] = max(dp[i-2],dp[i-3]) + nums[i] + return max(dp[length-1],dp[length-2]) + +''' +n = len(nums) +Time complexity = O(n) +Space complexity = O(n) +''' \ No newline at end of file From 38b1e3bfbfb2645d6cec73f5f18bd334462c6cd8 Mon Sep 17 00:00:00 2001 From: TrushaT Date: Tue, 6 Oct 2020 21:37:06 +0530 Subject: [PATCH 119/204] Added 1605_Find_Valid_Matrix_Given_Row_and_Column_Sum --- ...5_Find_Valid_Matrix_Given_Row_and_Column_Sums.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py diff --git a/LeetCode/1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py b/LeetCode/1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py new file mode 100644 index 0000000..5631572 --- /dev/null +++ b/LeetCode/1605_Find_Valid_Matrix_Given_Row_and_Column_Sums.py @@ -0,0 +1,13 @@ +class Solution: + def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: + m = len(rowSum) + n = len(colSum) + matrix = [[0]*n for i in range(m)] + print(matrix) + for i in range(m): + for j in range(n): + matrix[i][j] = min(rowSum[i],colSum[j]) + rowSum[i] -= matrix[i][j] + colSum[j] -= matrix[i][j] + return matrix + \ No newline at end of file From 91977b618061a4f383f4d17a92dfccbdd4e76f08 Mon Sep 17 00:00:00 2001 From: Anusha Prabhu Date: Tue, 6 Oct 2020 21:57:54 +0530 Subject: [PATCH 120/204] Added H-Index --- LeetCode/0274_H_Index.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/0274_H_Index.py diff --git a/LeetCode/0274_H_Index.py b/LeetCode/0274_H_Index.py new file mode 100644 index 0000000..086042b --- /dev/null +++ b/LeetCode/0274_H_Index.py @@ -0,0 +1,11 @@ +class Solution: + def hIndex(self, citations: List[int]) -> int: + citations.sort() + n = len(citations) + if n==0: + return 0 + if set(citations) == {0}: + return 0 + for i in range(n): + if n-i<=citations[i]: + return n-i \ No newline at end of file From dc573f0fac683b4957a1e702177a7b6ace1e321a Mon Sep 17 00:00:00 2001 From: chw9 <43727884+chw9@users.noreply.github.com> Date: Tue, 6 Oct 2020 13:24:08 -0400 Subject: [PATCH 121/204] added algorithm for 1582 --- .../1582_SpecialPositionsInABinaryMatrix.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 LeetCode/1582_SpecialPositionsInABinaryMatrix.py diff --git a/LeetCode/1582_SpecialPositionsInABinaryMatrix.py b/LeetCode/1582_SpecialPositionsInABinaryMatrix.py new file mode 100644 index 0000000..221aab6 --- /dev/null +++ b/LeetCode/1582_SpecialPositionsInABinaryMatrix.py @@ -0,0 +1,22 @@ +class Solution(object): + def numSpecial(self, mat): + """ + :type mat: List[List[int]] + :rtype: int + """ + numSpecial = 0 + + for a in range(len(mat)): + for b in range(len(mat[a])): + if mat[a][b] == 1: + valid = True + for c in range(len(mat[a])): + if mat[a][c] != 0 and c != b: + valid = False + if valid: + for d in range(len(mat)): + if mat[d][b] != 0 and d != a: + valid = False + if valid: + numSpecial+=1 + return numSpecial \ No newline at end of file From 26956162d90dc7066ecbc482872d40f7a6b63c8e Mon Sep 17 00:00:00 2001 From: utkarsh Date: Tue, 6 Oct 2020 23:05:11 +0530 Subject: [PATCH 122/204] Added LeetCode 0063 - Unique Paths II --- LeetCode/0063_UniquePathsII.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 LeetCode/0063_UniquePathsII.py diff --git a/LeetCode/0063_UniquePathsII.py b/LeetCode/0063_UniquePathsII.py new file mode 100644 index 0000000..3dbb6ef --- /dev/null +++ b/LeetCode/0063_UniquePathsII.py @@ -0,0 +1,22 @@ +class Solution: + def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int: + n, m = len(obstacleGrid), len(obstacleGrid[0]) + + ways = [[0 for j in range(m)] for i in range(n)] + + for i in range(n): + if obstacleGrid[i][0] == 1: + break + ways[i][0] = 1 + + for j in range(m): + if obstacleGrid[0][j] == 1: + break + ways[0][j] = 1 + + for i in range(1, n): + for j in range(1, m): + if obstacleGrid[i][j] == 0: + ways[i][j] = ways[i - 1][j] + ways[i][j - 1] + + return ways[n - 1][m - 1] From 8743a409a242202525bb8efa66953e09927a3f0b Mon Sep 17 00:00:00 2001 From: Martmists Date: Tue, 6 Oct 2020 21:01:02 +0200 Subject: [PATCH 123/204] Create 0973_ K_Closest_Points_to_Origin.py --- LeetCode/0973_ K_Closest_Points_to_Origin.py | 28 ++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 LeetCode/0973_ K_Closest_Points_to_Origin.py diff --git a/LeetCode/0973_ K_Closest_Points_to_Origin.py b/LeetCode/0973_ K_Closest_Points_to_Origin.py new file mode 100644 index 0000000..445b56f --- /dev/null +++ b/LeetCode/0973_ K_Closest_Points_to_Origin.py @@ -0,0 +1,28 @@ +from heapq import heappop, heappush +from typing import List, Tuple + + +class Solution: + def closest_points(self, points: List[Tuple[float, float]], k: int) -> List[Tuple[float, float]]: + """ + Finds the K points closest to the origin. + + The implementation pushes the points on a Heap with their key being the distance to the origin, then removes K elements from the heap. + I chose to go with a more verbose implementation to show how it can be done, but alternatively one could do: + + >>> from heapq import nsmallest + ... nsmallest(k, points, key=self.distance) + """ + + heap = [] + for point in points: + heappush(heap, (self.distance(point), point)) + + return [heappop(heap)[1] for _ in range(k)] + + def distance(self, point: Tuple[float, float]) -> float: + """ + Pythagorean formula to get the distance to the origin. + """ + + return (point[0] ** 2 + point[1] ** 2) ** 0.5 From cb769b4300f5f6eb5ba4ab10540217ef02b9e9af Mon Sep 17 00:00:00 2001 From: Dennis P George Date: Wed, 7 Oct 2020 01:16:56 +0530 Subject: [PATCH 124/204] 0043 - Multiply Strings --- LeetCode/0043_Multiply_Strings.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 LeetCode/0043_Multiply_Strings.py diff --git a/LeetCode/0043_Multiply_Strings.py b/LeetCode/0043_Multiply_Strings.py new file mode 100644 index 0000000..35e7120 --- /dev/null +++ b/LeetCode/0043_Multiply_Strings.py @@ -0,0 +1,3 @@ +class Solution: + def multiply(self, num1: str, num2: str) -> str: + return str(int(num1)*int(num2)) \ No newline at end of file From 05bf50e7ada09c1d00bed37266288fc444e76f1c Mon Sep 17 00:00:00 2001 From: Nicolas Date: Tue, 6 Oct 2020 17:18:33 -0500 Subject: [PATCH 125/204] Solution 0104 Maximum Depth of Binary Tree --- LeetCode/0104_Maximum_Depth_of_Binary_Tree.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0104_Maximum_Depth_of_Binary_Tree.py diff --git a/LeetCode/0104_Maximum_Depth_of_Binary_Tree.py b/LeetCode/0104_Maximum_Depth_of_Binary_Tree.py new file mode 100644 index 0000000..0d0a184 --- /dev/null +++ b/LeetCode/0104_Maximum_Depth_of_Binary_Tree.py @@ -0,0 +1,12 @@ +# 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 maxDepth(self, root: TreeNode) -> int: + if root==None: + return 0 + else: + return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 From dca6e06c2f6397e7dfcfbdf8e93d7df406652393 Mon Sep 17 00:00:00 2001 From: Richard Wi <18545483+riwim@users.noreply.github.com> Date: Wed, 7 Oct 2020 00:33:01 +0200 Subject: [PATCH 126/204] Solve Leet Code problem 0500 "Keyboard Row" --- LeetCode/0500_Keyboard_Row.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 LeetCode/0500_Keyboard_Row.py diff --git a/LeetCode/0500_Keyboard_Row.py b/LeetCode/0500_Keyboard_Row.py new file mode 100644 index 0000000..40fb9c8 --- /dev/null +++ b/LeetCode/0500_Keyboard_Row.py @@ -0,0 +1,6 @@ +class Solution: + + def findWords(self, words: List[str]) -> List[str]: + rows = ["qwertyuiop", "asdfghjkl", "zxcvbnm"] + is_in_row = lambda word, row: all(letter in row for letter in set(word.lower())) + return [word for word in words if any(is_in_row(word, row) for row in rows)] From d7a9014a75a4c9ab0defccba1ade3d56efca4983 Mon Sep 17 00:00:00 2001 From: Anirudh PVS Date: Wed, 7 Oct 2020 09:14:27 +0530 Subject: [PATCH 127/204] Added Solution for problem 0279-PerfectSquares --- LeetCode/0279-PerfectSquares.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0279-PerfectSquares.py diff --git a/LeetCode/0279-PerfectSquares.py b/LeetCode/0279-PerfectSquares.py new file mode 100644 index 0000000..b94fca3 --- /dev/null +++ b/LeetCode/0279-PerfectSquares.py @@ -0,0 +1,15 @@ +class Solution(object): + def numSquares(self, n): + queue = collections.deque([(0, 0)]) + visited = set() + while queue: + val, dis = queue.popleft() + if val == n: + return dis + for i in range(1, n+1): + j = val + i*i + if j > n: + break + if j not in visited: + visited.add(j) + queue.append((j, dis+1)) \ No newline at end of file From 4f5d04815f6ea2e0b0f76dd79810fbc3317e5556 Mon Sep 17 00:00:00 2001 From: rajapuranam <64188651+rajapuranam@users.noreply.github.com> Date: Wed, 7 Oct 2020 10:05:29 +0530 Subject: [PATCH 128/204] Create 0010_Regular_Expression_Matching.py Python solution for Regular Expression Matching problem in Leetcode (leetcode no. 10) --- LeetCode/0010_Regular_Expression_Matching.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0010_Regular_Expression_Matching.py diff --git a/LeetCode/0010_Regular_Expression_Matching.py b/LeetCode/0010_Regular_Expression_Matching.py new file mode 100644 index 0000000..3f97e39 --- /dev/null +++ b/LeetCode/0010_Regular_Expression_Matching.py @@ -0,0 +1,20 @@ +class Solution: + def isMatch(self, s: str, p: str) -> bool: + string, pattern = [], [] + string[:0], pattern[:0] = s, p + string.insert(0, 0) + pattern.insert(0, 0) + s, p = len(string), len(pattern) + dp = [[False for _ in range(p)] for __ in range(s)] + dp[0][0] = True + for i in range(p): + if pattern[i] is '*' and dp[0][i-2]: dp[0][i] = True + for i in range(1, s): + for j in range(1, p): + if pattern[j] is string[i] or pattern[j] is '.': + dp[i][j] = dp[i-1][j-1] + elif pattern[j] is '*' and (pattern[j-1] is string[i] or pattern[j-1] is '.'): + dp[i][j] = dp[i][j-2] or dp[i-1][j] + elif pattern[j] is '*' and not (pattern[j-1] is string[i] or pattern[j-1] is '.'): + dp[i][j] = dp[i][j-2] + return dp[s-1][p-1] From 0697644a8590f99bdaec350f0fde50031c24d09d Mon Sep 17 00:00:00 2001 From: Rollerss Date: Tue, 6 Oct 2020 22:42:26 -0700 Subject: [PATCH 129/204] 1023_Camelcase_Matching --- LeetCode/1023_Camelcase_Matching.py | 35 +++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 LeetCode/1023_Camelcase_Matching.py diff --git a/LeetCode/1023_Camelcase_Matching.py b/LeetCode/1023_Camelcase_Matching.py new file mode 100644 index 0000000..479cc5b --- /dev/null +++ b/LeetCode/1023_Camelcase_Matching.py @@ -0,0 +1,35 @@ +import re + +class Solution: + def camelMatch(self, queries: List[str], pattern: str) -> List[bool]: + p = re.findall('[A-Z][^A-Z]*', pattern) + result = [] + + for x in queries: + y = re.findall('[A-Z][^A-Z]*', x) + if len(p) != len(y): + result.append(False) + + else: + q = [] + + for i in range(len(p)): + t = 'false' + pi = p[i] + c = len(pi) + ct = 0 + + for j in y[i]: + if j == pi[ct]: + ct += 1 + if ct == c: + t = 'true' + break + q.append(t) + + k = True + if "false" in q: + k = False + + result.append(k) + return result From 8b4c40265d1d7772d2a2d45056ad27cfdf238c7d Mon Sep 17 00:00:00 2001 From: Bauri <52131226@acsind.com> Date: Wed, 7 Oct 2020 13:28:10 +0530 Subject: [PATCH 130/204] Added Solution to Problem 47 Permutations II --- LeetCode/0047_Permutations II.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0047_Permutations II.py diff --git a/LeetCode/0047_Permutations II.py b/LeetCode/0047_Permutations II.py new file mode 100644 index 0000000..1039f98 --- /dev/null +++ b/LeetCode/0047_Permutations II.py @@ -0,0 +1,19 @@ +class Solution: + def permuteUnique(self, nums: List[int]) -> List[List[int]]: + results = [] + def Combination(permutation, counter): + if len(permutation) == len(nums): + results.append(list(permutation)) + return + + for num in counter: + if counter[num] > 0: + permutation.append(num) + counter[num] -= 1 + Combination(permutation, counter) + permutation.pop() + counter[num] += 1 + + Combination([], Counter(nums)) + + return results \ No newline at end of file From 38ec217e57cf3df3e42ee6f2a6f9de41999d39f9 Mon Sep 17 00:00:00 2001 From: Bauri <52131226@acsind.com> Date: Wed, 7 Oct 2020 13:39:59 +0530 Subject: [PATCH 131/204] Removed Solution to Problem 47 Permutations II --- LeetCode/0047_Permutations II.py | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 LeetCode/0047_Permutations II.py diff --git a/LeetCode/0047_Permutations II.py b/LeetCode/0047_Permutations II.py deleted file mode 100644 index 1039f98..0000000 --- a/LeetCode/0047_Permutations II.py +++ /dev/null @@ -1,19 +0,0 @@ -class Solution: - def permuteUnique(self, nums: List[int]) -> List[List[int]]: - results = [] - def Combination(permutation, counter): - if len(permutation) == len(nums): - results.append(list(permutation)) - return - - for num in counter: - if counter[num] > 0: - permutation.append(num) - counter[num] -= 1 - Combination(permutation, counter) - permutation.pop() - counter[num] += 1 - - Combination([], Counter(nums)) - - return results \ No newline at end of file From 405836117768af5faf79d0c11663786ad14c41ba Mon Sep 17 00:00:00 2001 From: Bauri <52131226@acsind.com> Date: Wed, 7 Oct 2020 16:43:00 +0530 Subject: [PATCH 132/204] Added Solution to Problem 47 PermutationsII --- LeetCode/0047_Permutations II.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0047_Permutations II.py diff --git a/LeetCode/0047_Permutations II.py b/LeetCode/0047_Permutations II.py new file mode 100644 index 0000000..1039f98 --- /dev/null +++ b/LeetCode/0047_Permutations II.py @@ -0,0 +1,19 @@ +class Solution: + def permuteUnique(self, nums: List[int]) -> List[List[int]]: + results = [] + def Combination(permutation, counter): + if len(permutation) == len(nums): + results.append(list(permutation)) + return + + for num in counter: + if counter[num] > 0: + permutation.append(num) + counter[num] -= 1 + Combination(permutation, counter) + permutation.pop() + counter[num] += 1 + + Combination([], Counter(nums)) + + return results \ No newline at end of file From 3e4dc91dba83a062e63d8db9dd57cdb7a989ad30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1ty=C3=A1s=20Kiglics?= Date: Wed, 7 Oct 2020 13:16:50 +0200 Subject: [PATCH 133/204] Number of islands solution --- LeetCode/0200_Number_of_Islands.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 LeetCode/0200_Number_of_Islands.py diff --git a/LeetCode/0200_Number_of_Islands.py b/LeetCode/0200_Number_of_Islands.py new file mode 100644 index 0000000..a297048 --- /dev/null +++ b/LeetCode/0200_Number_of_Islands.py @@ -0,0 +1,26 @@ +class Solution(object): + def numIslands(self, grid): + """ + :type grid: List[List[str]] + :rtype: int + """ + cnt = 0 + + for i in range(len(grid)): + for j in range(len(grid[i])): + if grid[i][j] == "1": + cnt += 1 + self.removeIsland(grid, i, j) + return cnt + + # recursive function for replacing adjacent "1"s + def removeIsland(self, grid, i, j): + if i < 0 or j < 0 or i >= len(grid) or j >= len(grid[0]): + return + if grid[i][j] == "0": + return + grid[i][j] = "0" + self.removeIsland(grid, i+1, j) + self.removeIsland(grid, i-1, j) + self.removeIsland(grid, i, j+1) + self.removeIsland(grid, i, j-1) From a7278aaad5446577f7b7ce7b62dc45b43a3fee59 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Wed, 7 Oct 2020 16:00:18 +0200 Subject: [PATCH 134/204] Update submit-a-leetcode-problem.md --- .github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md b/.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md index fa91559..8d05d3b 100644 --- a/.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md +++ b/.github/ISSUE_TEMPLATE/submit-a-leetcode-problem.md @@ -2,7 +2,7 @@ name: Submit a LeetCode Problem about: Use this Template to submit a new LeetCode Problem title: 00## - LeetCode Problem Title -labels: 'hacktoberfest, help wanted, good first issue' +labels: 'hacktoberfest' assignees: '' --- From 1f3133a3de70b9caca2c665c5796c388c546b9d6 Mon Sep 17 00:00:00 2001 From: shubhamc1200 Date: Wed, 7 Oct 2020 19:59:17 +0530 Subject: [PATCH 135/204] SAME TREE #100 --- LeetCode/0100_Same_Tree.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0100_Same_Tree.py diff --git a/LeetCode/0100_Same_Tree.py b/LeetCode/0100_Same_Tree.py new file mode 100644 index 0000000..68c723f --- /dev/null +++ b/LeetCode/0100_Same_Tree.py @@ -0,0 +1,20 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution(object): + def isSameTree(self, p, q): + if(p is None and q is None): + return True + + if(p==None or q==None): + return False + + if(p.val!=q.val): + return False + + else: + return self.isSameTree( p.right, q.right) and self.isSameTree( p.left, q.left) + \ No newline at end of file From a07a525bd5e9dbece489c05212943e6d58cef768 Mon Sep 17 00:00:00 2001 From: AshishVarshneyy <50491289+AshishVarshneyy@users.noreply.github.com> Date: Wed, 7 Oct 2020 20:21:03 +0530 Subject: [PATCH 136/204] 1108_Defanging_an_IP_Address --- LeetCode/1108_Defanging_an_IP_Address.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 LeetCode/1108_Defanging_an_IP_Address.py diff --git a/LeetCode/1108_Defanging_an_IP_Address.py b/LeetCode/1108_Defanging_an_IP_Address.py new file mode 100644 index 0000000..bdd37a7 --- /dev/null +++ b/LeetCode/1108_Defanging_an_IP_Address.py @@ -0,0 +1,3 @@ +class Solution: + def defangIPaddr(self, address: str) -> str: + return(address.replace('.','[.]')) From 8634595c4dfa3c10c844180a6cfc23941165b7a1 Mon Sep 17 00:00:00 2001 From: chw9 <43727884+chw9@users.noreply.github.com> Date: Wed, 7 Oct 2020 10:57:09 -0400 Subject: [PATCH 137/204] added algorithm for 0367 --- LeetCode/0367_ValidPerfectSquare.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0367_ValidPerfectSquare.py diff --git a/LeetCode/0367_ValidPerfectSquare.py b/LeetCode/0367_ValidPerfectSquare.py new file mode 100644 index 0000000..d6c025b --- /dev/null +++ b/LeetCode/0367_ValidPerfectSquare.py @@ -0,0 +1,15 @@ +class Solution(object): + def isPerfectSquare(self, num): + """ + :type num: int + :rtype: bool + """ + + i = 1 + sum_odds = 0 + while sum_odds < num: + sum_odds += i + if sum_odds == num: + return True + i += 2 + return False \ No newline at end of file From 0b9f62ee0d8bf5ae857bdae08f7ae2aaaff0cb09 Mon Sep 17 00:00:00 2001 From: HOD101s Date: Wed, 7 Oct 2020 20:31:06 +0530 Subject: [PATCH 138/204] added 0112_Path_Sum --- LeetCode/0112_Path_Sum.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/0112_Path_Sum.py diff --git a/LeetCode/0112_Path_Sum.py b/LeetCode/0112_Path_Sum.py new file mode 100644 index 0000000..b2faa86 --- /dev/null +++ b/LeetCode/0112_Path_Sum.py @@ -0,0 +1,14 @@ +# 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 hasPathSum(self, root: TreeNode, sum: int) -> bool: + if not root: + return False + if not root.left and not root.right: + return root.val == sum + return self.hasPathSum(root.left,sum-root.val) or self.hasPathSum(root.right,sum-root.val) \ No newline at end of file From 40ed8cbed1d59a15621f517e144def9be7478fb9 Mon Sep 17 00:00:00 2001 From: Lennard Gerdes Date: Wed, 7 Oct 2020 15:02:49 +0000 Subject: [PATCH 139/204] 1189 - Maximum Numer of Ballons --- LeetCode/1189_Maximum_Number_of_Balloons.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/1189_Maximum_Number_of_Balloons.py diff --git a/LeetCode/1189_Maximum_Number_of_Balloons.py b/LeetCode/1189_Maximum_Number_of_Balloons.py new file mode 100644 index 0000000..805eaf3 --- /dev/null +++ b/LeetCode/1189_Maximum_Number_of_Balloons.py @@ -0,0 +1,12 @@ +class Solution(object): + def maxNumberOfBalloons(self, text) -> int: + """ + :type text: str + :rtype: int + """ + a_count = text.count("b") + b_count = text.count("a") + l_count = text.count("l") / 2 + o_count = text.count("o") / 2 + n_count = text.count("n") + return int(min([a_count,b_count,l_count,o_count,n_count])) \ No newline at end of file From 89667661ca9a665871da843728e85fa051e7a681 Mon Sep 17 00:00:00 2001 From: HOD101s Date: Wed, 7 Oct 2020 20:41:07 +0530 Subject: [PATCH 140/204] added 1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays --- .../1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 LeetCode/1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py diff --git a/LeetCode/1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py b/LeetCode/1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py new file mode 100644 index 0000000..831907b --- /dev/null +++ b/LeetCode/1460_Make_Two_Arrays_Equal_by_Reversing_Sub_Arrays.py @@ -0,0 +1,5 @@ +from collections import Counter + +class Solution: + def canBeEqual(self, target: List[int], arr: List[int]) -> bool: + return Counter(target) == Counter(arr) \ No newline at end of file From 421e1bc92e9058c59adb0d95008a13d907972518 Mon Sep 17 00:00:00 2001 From: HOD101s Date: Wed, 7 Oct 2020 20:49:35 +0530 Subject: [PATCH 141/204] added 1441_build_an_array_with_stack_operations --- 1441_build_an_array_with_stack_operations.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 1441_build_an_array_with_stack_operations.py diff --git a/1441_build_an_array_with_stack_operations.py b/1441_build_an_array_with_stack_operations.py new file mode 100644 index 0000000..00854b7 --- /dev/null +++ b/1441_build_an_array_with_stack_operations.py @@ -0,0 +1,13 @@ +class Solution: + def buildArray(self, target: List[int], n: int) -> List[str]: + res = [] + j = 0 + for i in range(1,n+1): + res.append("Push") + if i == target[j]: + j += 1 + else: + res.append("Pop") + if j == len(target): + break + return res \ No newline at end of file From e9a315e06bfe2eb900fe3254d353e3b01149b697 Mon Sep 17 00:00:00 2001 From: Anirudh PVS Date: Wed, 7 Oct 2020 09:14:27 +0530 Subject: [PATCH 142/204] closes issue#435 --- LeetCode/0279-PerfectSquares.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0279-PerfectSquares.py diff --git a/LeetCode/0279-PerfectSquares.py b/LeetCode/0279-PerfectSquares.py new file mode 100644 index 0000000..b94fca3 --- /dev/null +++ b/LeetCode/0279-PerfectSquares.py @@ -0,0 +1,15 @@ +class Solution(object): + def numSquares(self, n): + queue = collections.deque([(0, 0)]) + visited = set() + while queue: + val, dis = queue.popleft() + if val == n: + return dis + for i in range(1, n+1): + j = val + i*i + if j > n: + break + if j not in visited: + visited.add(j) + queue.append((j, dis+1)) \ No newline at end of file From f9fc9c25a745c5446bfcb72afd4a8b86633a8858 Mon Sep 17 00:00:00 2001 From: GorettiRivera Date: Wed, 7 Oct 2020 10:24:36 -0700 Subject: [PATCH 143/204] solution accepted in Leetcode --- ...inimum_Remove_to_Make_Valid_Parentheses.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 LeetCode/1249_Minimum_Remove_to_Make_Valid_Parentheses.py diff --git a/LeetCode/1249_Minimum_Remove_to_Make_Valid_Parentheses.py b/LeetCode/1249_Minimum_Remove_to_Make_Valid_Parentheses.py new file mode 100644 index 0000000..b53b968 --- /dev/null +++ b/LeetCode/1249_Minimum_Remove_to_Make_Valid_Parentheses.py @@ -0,0 +1,28 @@ +class Solution: + def minRemoveToMakeValid(self, s: str) -> str: + + stackparen = [] + stackindex = [] + result = '' + result1 = '' + i = 0 + j = 0 + + while i <= len(s) - 1: + if s[i] == ')' and len(stackparen) == 0: + i += 1 + continue + if s[i] == '(': + stackparen.append(s[i]) + stackindex.append(j) + if s[i] == ')' and len(stackparen) > 0: + stackparen.pop() + stackindex.pop() + result += s[i] + j += 1 + i += 1 + + for j, i in enumerate(result): + if j not in stackindex: + result1 += result[j] + return result1 From 496a0a2cede0e9ddf1476b0171c132b11f30ee66 Mon Sep 17 00:00:00 2001 From: David Browne Date: Wed, 7 Oct 2020 19:38:36 +0200 Subject: [PATCH 144/204] Corrected 0043_Multiply_Strings --- LeetCode/0043_Multiply_Strings.py | 44 ++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/LeetCode/0043_Multiply_Strings.py b/LeetCode/0043_Multiply_Strings.py index 35e7120..890127c 100644 --- a/LeetCode/0043_Multiply_Strings.py +++ b/LeetCode/0043_Multiply_Strings.py @@ -1,3 +1,45 @@ class Solution: def multiply(self, num1: str, num2: str) -> str: - return str(int(num1)*int(num2)) \ No newline at end of file + ''' + Note: You must not use any built-in BigInteger library or convert the inputs to integer directly + ''' + l1 = len(num1) + l2 = len(num2) + + x = 0 + for char in num1: + l1 -= 1 + x += self.str_to_int(char, l1) + + y = 0 + for char in num2: + l2 -= 1 + y += self.str_to_int(char, l2) + + xy = x * y + + return str(xy) + + + def str_to_int(self, s, no_zeros): + if s == '0': + x = 0 + elif s == '1': + x = 1 + elif s == '2': + x = 2 + elif s == '3': + x = 3 + elif s == '4': + x = 4 + elif s == '5': + x = 5 + elif s == '6': + x = 6 + elif s == '7': + x = 7 + elif s == '8': + x = 8 + elif s == '9': + x = 9 + return x * pow(10, no_zeros) \ No newline at end of file From 41b265b8654c80b24f187b46871103b1faccf1dd Mon Sep 17 00:00:00 2001 From: David Browne Date: Wed, 7 Oct 2020 19:54:37 +0200 Subject: [PATCH 145/204] Added 0080 solution --- .../0080_Remove_Duplicates_from_Sorted_Array_II.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py diff --git a/LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py b/LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py new file mode 100644 index 0000000..3382396 --- /dev/null +++ b/LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py @@ -0,0 +1,12 @@ +class Solution: + def removeDuplicates(self, nums: List[int]) -> int: + i = 0 + for _ in range(len(nums)-2): + n = nums[i] + if nums[i+2] != n: + i += 1 + continue + else: + nums.pop(i+2) + + \ No newline at end of file From 35e75c9d97446df56addbe3d1f99d93056cf585d Mon Sep 17 00:00:00 2001 From: David Browne Date: Wed, 7 Oct 2020 20:02:45 +0200 Subject: [PATCH 146/204] Added 0082 Solution --- ...2_Remove_Duplicates_from_Sorted_List_II.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0082_Remove_Duplicates_from_Sorted_List_II.py diff --git a/LeetCode/0082_Remove_Duplicates_from_Sorted_List_II.py b/LeetCode/0082_Remove_Duplicates_from_Sorted_List_II.py new file mode 100644 index 0000000..0590137 --- /dev/null +++ b/LeetCode/0082_Remove_Duplicates_from_Sorted_List_II.py @@ -0,0 +1,19 @@ +# Definition for singly-linked list. +#class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def deleteDuplicates(self, head: ListNode) -> ListNode: + if head is None: + return head + + while (head.next is not None) and (head.val == head.next.val): + while (head.next is not None) and (head.val == head.next.val): + head = head.next + head = head.next + if head is None: + return head + + head.next = self.deleteDuplicates(head.next) + return head \ No newline at end of file From a3e86348706f8b4f42cf6b94fd9304692014ad55 Mon Sep 17 00:00:00 2001 From: srub Date: Wed, 7 Oct 2020 20:18:05 +0200 Subject: [PATCH 147/204] jump game accepted --- LeetCode/0055_jump_game.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0055_jump_game.py diff --git a/LeetCode/0055_jump_game.py b/LeetCode/0055_jump_game.py new file mode 100644 index 0000000..2b60469 --- /dev/null +++ b/LeetCode/0055_jump_game.py @@ -0,0 +1,12 @@ +from typing import List + + +class Solution: + def canJump(self, nums: List[int]) -> bool: + jump_length_left = 0 + for num in nums: + if jump_length_left == -1: + return False + jump_length_left = max(jump_length_left - 1, num - 1) + + return True From fa3cc1ad4b6b09febeca4b861cd63363a0811c76 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 8 Oct 2020 01:12:59 +0200 Subject: [PATCH 148/204] Solved integer break --- LeetCode/0343_Integer_Break.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 LeetCode/0343_Integer_Break.py diff --git a/LeetCode/0343_Integer_Break.py b/LeetCode/0343_Integer_Break.py new file mode 100644 index 0000000..6835228 --- /dev/null +++ b/LeetCode/0343_Integer_Break.py @@ -0,0 +1,17 @@ +class Solution: + def integerBreak(self, n: int) -> int: + if n < 3: + return 1 + if n == 3: + return 2 + mylist = [1, 2, 3] + for i in range(4, n+1): + temp = [i] + for j in range((i+1)//2): + temp.append(mylist[j]*mylist[-j-1]) + mylist.append(max(temp)) + print(mylist, temp) + return max(mylist) + +solution = Solution() +print(solution.integerBreak(n =4)) \ No newline at end of file From b60c2dc3c99bee2fb9f0b54f873a6a308e08228d Mon Sep 17 00:00:00 2001 From: Anjali Singh Date: Thu, 8 Oct 2020 08:31:13 +0530 Subject: [PATCH 149/204] Create 0051_N-Queen_1.py --- LeetCode/0051_N-Queen_1.py | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 LeetCode/0051_N-Queen_1.py diff --git a/LeetCode/0051_N-Queen_1.py b/LeetCode/0051_N-Queen_1.py new file mode 100644 index 0000000..607be73 --- /dev/null +++ b/LeetCode/0051_N-Queen_1.py @@ -0,0 +1,42 @@ +# -*- coding: utf-8 -*- +""" +Created on Wed Oct 7 20:51:57 2020 + +@author: anjalisingh +""" + +class Solution(object): + def solveNQueens(self, n): + # i is column index + # left: left diagonal: \ level-i + # right: right diagonal: / level+i + self.col = [0]*n # not occupied column + self.left = [0]*(2*n-1) # number of left diagonal + self.right = [0]*(2*n-1) + board = [['.' for x in range(n)] for y in range(n)] + self.resultBoard = [] + self.backTrack(n, 0, board) + return self.resultBoard + + def backTrack(self, n, level, board): + if level == n: # finish + res = [] + for i in range(n): + res.append(''.join(board[i])) + self.resultBoard.append(res) + return + for i in range(n): # iterate every column + # if col, left, right are all not accupied, put a queue here + if not self.col[i] and not self.left[level-i] and not self.right[level+i]: + board[level][i] = 'Q' + self.col[i] = 1 + self.left[level-i] = 1 + self.right[level+i] = 1 # choose + self.backTrack(n, level+1, board) # explore + board[level][i] = '.' # un choose + self.col[i] = 0 + self.left[level-i] = 0 + self.right[level+i] = 0 + +# Queen = Solution() +# print(Queen.solveNQueens(4)) From bf202905c6cfe794f091f014a6741d1379ae4565 Mon Sep 17 00:00:00 2001 From: DAIIVIIK Date: Thu, 8 Oct 2020 11:01:28 +0530 Subject: [PATCH 150/204] Create 1103_Distributing_Candies_to_people.py --- .../1103_Distributing_Candies_to_people.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 LeetCode/1103_Distributing_Candies_to_people.py diff --git a/LeetCode/1103_Distributing_Candies_to_people.py b/LeetCode/1103_Distributing_Candies_to_people.py new file mode 100644 index 0000000..bc3b8cf --- /dev/null +++ b/LeetCode/1103_Distributing_Candies_to_people.py @@ -0,0 +1,23 @@ +def distributeCandies(self, candies: int, num_people: int) -> List[int]: + sum1, rounds, temp = sum(range(1, num_people + 1)), 0, candies + # 1. get the number of rounds that will go through the array + while temp > 0: + temp -= sum1 + rounds * num_people ** 2 + rounds += 1 + rounds -= 1 + result = [0] * num_people + # 2. add up the number until right before the final round + if rounds > 0: + for i in range(1, num_people + 1): + result[i - 1] = (2 * i + (rounds - 1) * num_people) * rounds // 2 + candies -= result[i - 1] + base_num = num_people * rounds + # 3. add the final round of numbers + for i in range(1, num_people + 1): + if candies <= base_num + i: + result[i - 1] += candies + break + else: + result[i - 1] += base_num + i + candies -= base_num + i + return result \ No newline at end of file From f45e75bc494c2edd2271a3d538aee033707832b3 Mon Sep 17 00:00:00 2001 From: tzvi Date: Thu, 8 Oct 2020 12:16:09 +0300 Subject: [PATCH 151/204] added Majority Element number 169 --- LeetCode/0169_Majority_Element.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 LeetCode/0169_Majority_Element.py diff --git a/LeetCode/0169_Majority_Element.py b/LeetCode/0169_Majority_Element.py new file mode 100644 index 0000000..dec71e1 --- /dev/null +++ b/LeetCode/0169_Majority_Element.py @@ -0,0 +1,28 @@ +# this class will give us a solution +class Solution: + + # the function to find the majority element + def majorityElement(self, arr): + """ + finds the majority element in the arr + :param arr: List[int] a list with elements + :return: int , the majority element + """ + + # a dictionary of numbers we have seen + seen_numbers = {} + + if len(arr) <= 2: + return arr[0] + + # goes through the list of numbers and count the appearance amount + for num in arr: + # adds it to the dictionary + if num not in seen_numbers: + seen_numbers[num] = 1 + else: + if (seen_numbers[num] + 1) >= (len(arr) / 2): + return num + else: + # adds one to the counter + seen_numbers[num] += 1 From 048e1fcaf63b03e47dad9a02c5abecce3049adb4 Mon Sep 17 00:00:00 2001 From: trip-mahak <59764956+trip-mahak@users.noreply.github.com> Date: Thu, 8 Oct 2020 07:55:08 -0700 Subject: [PATCH 152/204] Split_ a_String_in_Balanced_Strings.py 1221. Split a String in Balanced Strings solution in python --- LeetCode/Split_ a_String_in_Balanced_Strings.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/Split_ a_String_in_Balanced_Strings.py diff --git a/LeetCode/Split_ a_String_in_Balanced_Strings.py b/LeetCode/Split_ a_String_in_Balanced_Strings.py new file mode 100644 index 0000000..676979f --- /dev/null +++ b/LeetCode/Split_ a_String_in_Balanced_Strings.py @@ -0,0 +1,13 @@ +class Solution: + def balancedStringSplit(self, s: str) -> int: + r= 0 + l = 0 + count = 0 + for i in range(len(s)): + if s[i] == "R": + r += 1 + else: + l += 1 + if r == l: + count += 1 + return count From 63af736a380cc022c03893aba75c0d0d3ed053a0 Mon Sep 17 00:00:00 2001 From: matheusphalves Date: Thu, 8 Oct 2020 16:53:09 -0300 Subject: [PATCH 153/204] Added 0257_Binary_Tree_Paths.py --- LeetCode/0257_Binary_Tree_Paths.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 LeetCode/0257_Binary_Tree_Paths.py diff --git a/LeetCode/0257_Binary_Tree_Paths.py b/LeetCode/0257_Binary_Tree_Paths.py new file mode 100644 index 0000000..f5debc7 --- /dev/null +++ b/LeetCode/0257_Binary_Tree_Paths.py @@ -0,0 +1,24 @@ +# 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 __init__(self): + self.listOfPaths = [] #this list will save all paths and return + + def binaryTreePaths(self, root: TreeNode, path="") -> List[str]: + if(root==None): + return [] #nothing to return (it's a empty node) ... + + path += " " + str(root.val)#actual node value becomes a 'element route' + + if(root.left==None and root.right==None): + self.listOfPaths.append(path[1:].replace(" ", "->"))#question output format + + else: + self.binaryTreePaths(root.left, path) #scan by route in left node + self.binaryTreePaths(root.right, path)#scan by route in right node + return self.listOfPaths #return all paths + From d3f8a3924503a1ab2ab7eebd674e612f31550a80 Mon Sep 17 00:00:00 2001 From: TheOrangePuff Date: Fri, 9 Oct 2020 10:28:21 +1030 Subject: [PATCH 154/204] Adding 1018 Binary Tree Prefix Divisible By 5 --- LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py diff --git a/LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py b/LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py new file mode 100644 index 0000000..41d97ee --- /dev/null +++ b/LeetCode/1018_Binary_Tree_Prefix_Divisible_By_5.py @@ -0,0 +1,12 @@ +class Solution(object): + def prefixesDivBy5(self, A): + """ + :type A: List[int] + :rtype: List[bool] + """ + prev = 0 + for i in range(len(A)): + prev = 2 * prev + A[i] + A[i] = prev % 5 == 0 + return A + From 3a06bc095b82788a46d7d013e63c824c4c29de70 Mon Sep 17 00:00:00 2001 From: frank731 <38197177+frank731@users.noreply.github.com> Date: Thu, 8 Oct 2020 18:40:31 -0700 Subject: [PATCH 155/204] Create 1053_Previous_Permutation_With_One_Swap.py --- ...1053_Previous_Permutation_With_One_Swap.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LeetCode/1053_Previous_Permutation_With_One_Swap.py diff --git a/LeetCode/1053_Previous_Permutation_With_One_Swap.py b/LeetCode/1053_Previous_Permutation_With_One_Swap.py new file mode 100644 index 0000000..6241c10 --- /dev/null +++ b/LeetCode/1053_Previous_Permutation_With_One_Swap.py @@ -0,0 +1,21 @@ +class Solution: + def prevPermOpt1(self, A: List[int]) -> List[int]: + a_length = len(A) + largest_left_index = 0 + largest_left = A[0] + for i in range(2, a_length + 1): + i *= -1 + if A[i] > A[i + 1]: + largest_left_index = i + largest_left = A[i] + break + + largest_right_index = 0 + largest_right = 0 + for i in range(a_length + largest_left_index + 1, a_length): + if A[i] > largest_right and A[i] < largest_left: + largest_right_index = i + largest_right = A[i] + + A[largest_left_index], A[largest_right_index] = A[largest_right_index], A[largest_left_index] + return A From 65923726da04cfe43cb0346e85ae15fa42dc470a Mon Sep 17 00:00:00 2001 From: rkkksss <48599078+rkkksss@users.noreply.github.com> Date: Fri, 9 Oct 2020 15:22:49 +0300 Subject: [PATCH 156/204] add 0237 --- LeetCode/237_Delete_Node_in_a_Linked_List.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/237_Delete_Node_in_a_Linked_List.py diff --git a/LeetCode/237_Delete_Node_in_a_Linked_List.py b/LeetCode/237_Delete_Node_in_a_Linked_List.py new file mode 100644 index 0000000..f9bbb08 --- /dev/null +++ b/LeetCode/237_Delete_Node_in_a_Linked_List.py @@ -0,0 +1,14 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def deleteNode(self, node): + """ + :type node: ListNode + :rtype: void Do not return anything, modify node in-place instead. + """ + node.val = node.next.val + node.next = node.next.next From 114d78d82870c6fa93cdbbe125a8b3269574cfcd Mon Sep 17 00:00:00 2001 From: Dhawal Khapre Date: Fri, 9 Oct 2020 22:16:46 +0530 Subject: [PATCH 157/204] Solves Issue #35 --- LeetCode/0126_Word_Ladder_II.py | 26 +++++++++++++++++++ ...mum Product of Two Elements in an Array.py | 7 ----- 2 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 LeetCode/0126_Word_Ladder_II.py delete mode 100644 LeetCode/1464_Maximum Product of Two Elements in an Array.py diff --git a/LeetCode/0126_Word_Ladder_II.py b/LeetCode/0126_Word_Ladder_II.py new file mode 100644 index 0000000..c00115a --- /dev/null +++ b/LeetCode/0126_Word_Ladder_II.py @@ -0,0 +1,26 @@ +class Solution: + def findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: + + from collections import defaultdict + + wordList = set(wordList) + list1 = [] + layer = {} + layer[beginWord] = [[beginWord]] + + while layer: + newlayer = defaultdict(list) + for a in layer: + if a == endWord: + list1.extend(b for b in layer[a]) + else: + for i in range(len(a)): + for j in 'abcdefghijklmnopqrstuvwxyz': + new1 = a[:i]+j+a[i+1:] + if new1 in wordList: + newlayer[new1]+=[k+[new1] for k in layer[a]] + + wordList -= set(newlayer.keys()) + layer = newlayer + + return list1 \ No newline at end of file diff --git a/LeetCode/1464_Maximum Product of Two Elements in an Array.py b/LeetCode/1464_Maximum Product of Two Elements in an Array.py deleted file mode 100644 index 83bc2db..0000000 --- a/LeetCode/1464_Maximum Product of Two Elements in an Array.py +++ /dev/null @@ -1,7 +0,0 @@ -class Solution: - def maxProduct(self, nums: List[int]) -> int: - List.sort() - - max_product = (List[-1]-1) * (List[-2]-1) - - return max_product \ No newline at end of file From c6e6e719a97868bbb6aa41cf4e8cce8f22ff69fe Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Fri, 9 Oct 2020 20:24:35 +0200 Subject: [PATCH 158/204] Delete 0041_findingLeastPositiveNumber.py problem already solved/issue not assigned --- LeetCode/0041_findingLeastPositiveNumber.py | 26 --------------------- 1 file changed, 26 deletions(-) delete mode 100644 LeetCode/0041_findingLeastPositiveNumber.py diff --git a/LeetCode/0041_findingLeastPositiveNumber.py b/LeetCode/0041_findingLeastPositiveNumber.py deleted file mode 100644 index 699b76c..0000000 --- a/LeetCode/0041_findingLeastPositiveNumber.py +++ /dev/null @@ -1,26 +0,0 @@ -# finding least positive number -# Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, -# find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. -# code contributed by devanshi katyal -# space complexity:O(1) -# time complexity:O(n) - - -def MainFunction(arr, size): - for i in range(size): - if (abs(arr[i]) - 1 < size and arr[abs(arr[i]) - 1] > 0): - arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1] - for i in range(size): - if (arr[i] > 0): - return i + 1 - return size + 1 - -def findpositive(arr, size): - j= 0 - for i in range(size): - if (arr[i] <= 0): - arr[i], arr[j] = arr[j], arr[i] - j += 1 - return MainFunction(arr[j:], size - j) -arr = list(map(int, input().split(" "))) -print("the smallest missing number", findpositive(arr, len(arr))) From 1d761d72f66ddf1bb029545981e79c6693e5bbc2 Mon Sep 17 00:00:00 2001 From: Anshul Gautam Date: Fri, 9 Oct 2020 23:59:18 +0530 Subject: [PATCH 159/204] added solution for issue 0701 --- .../0701_Insert_into_a_Binary_Search_Tree.py | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 LeetCode/0701_Insert_into_a_Binary_Search_Tree.py diff --git a/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py b/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py new file mode 100644 index 0000000..362b45c --- /dev/null +++ b/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py @@ -0,0 +1,34 @@ +# 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 + +def solve(r,k): + x = TreeNode(k) + ans = r + if(not r): + return x + while(r and (r.left or r.right)): + if(r.val < k): + if(r.right): + r = r.right + else: + r.right = x + return ans + else: + if(r.left): + r = r.left + else: + r.left = x + return ans + if(r.val < k): + r.right = x + else: + r.left = x + return ans + +class Solution: + def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode: + return solve(root,val) From 49a6a7422f2cd5788ef3b0bbced39db0e737c1f2 Mon Sep 17 00:00:00 2001 From: Anshul Gautam Date: Sat, 10 Oct 2020 00:02:30 +0530 Subject: [PATCH 160/204] added solution for issue 0701 --- LeetCode/0701_Insert_into_a_Binary_Search_Tree.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py b/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py index 362b45c..0ddd84f 100644 --- a/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py +++ b/LeetCode/0701_Insert_into_a_Binary_Search_Tree.py @@ -10,7 +10,7 @@ def solve(r,k): ans = r if(not r): return x - while(r and (r.left or r.right)): + while(r and (r.left or r.right) ): if(r.val < k): if(r.right): r = r.right From 3c42c4c0e5e8db45c45514b536440152e4fafc8d Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Fri, 9 Oct 2020 20:39:05 +0200 Subject: [PATCH 161/204] Delete 0043_Multiply_Strings.py Problem already solved/not assigned to --- LeetCode/0043_Multiply_Strings.py | 45 ------------------------------- 1 file changed, 45 deletions(-) delete mode 100644 LeetCode/0043_Multiply_Strings.py diff --git a/LeetCode/0043_Multiply_Strings.py b/LeetCode/0043_Multiply_Strings.py deleted file mode 100644 index 890127c..0000000 --- a/LeetCode/0043_Multiply_Strings.py +++ /dev/null @@ -1,45 +0,0 @@ -class Solution: - def multiply(self, num1: str, num2: str) -> str: - ''' - Note: You must not use any built-in BigInteger library or convert the inputs to integer directly - ''' - l1 = len(num1) - l2 = len(num2) - - x = 0 - for char in num1: - l1 -= 1 - x += self.str_to_int(char, l1) - - y = 0 - for char in num2: - l2 -= 1 - y += self.str_to_int(char, l2) - - xy = x * y - - return str(xy) - - - def str_to_int(self, s, no_zeros): - if s == '0': - x = 0 - elif s == '1': - x = 1 - elif s == '2': - x = 2 - elif s == '3': - x = 3 - elif s == '4': - x = 4 - elif s == '5': - x = 5 - elif s == '6': - x = 6 - elif s == '7': - x = 7 - elif s == '8': - x = 8 - elif s == '9': - x = 9 - return x * pow(10, no_zeros) \ No newline at end of file From 81cf6505fcdfeb29e45d9f5ab72d9f8b6d649cfb Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Fri, 9 Oct 2020 20:45:09 +0200 Subject: [PATCH 162/204] Delete 0080_Remove_Duplicates_from_Sorted_Array_II.py already solved --- .../0080_Remove_Duplicates_from_Sorted_Array_II.py | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py diff --git a/LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py b/LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py deleted file mode 100644 index 3382396..0000000 --- a/LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py +++ /dev/null @@ -1,12 +0,0 @@ -class Solution: - def removeDuplicates(self, nums: List[int]) -> int: - i = 0 - for _ in range(len(nums)-2): - n = nums[i] - if nums[i+2] != n: - i += 1 - continue - else: - nums.pop(i+2) - - \ No newline at end of file From 322038321196b3f9a27c8736c6f05519d1fb1940 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Fri, 9 Oct 2020 20:45:21 +0200 Subject: [PATCH 163/204] Delete 0043_Multiply_Strings.py already solved --- LeetCode/0043_Multiply_Strings.py | 45 ------------------------------- 1 file changed, 45 deletions(-) delete mode 100644 LeetCode/0043_Multiply_Strings.py diff --git a/LeetCode/0043_Multiply_Strings.py b/LeetCode/0043_Multiply_Strings.py deleted file mode 100644 index 890127c..0000000 --- a/LeetCode/0043_Multiply_Strings.py +++ /dev/null @@ -1,45 +0,0 @@ -class Solution: - def multiply(self, num1: str, num2: str) -> str: - ''' - Note: You must not use any built-in BigInteger library or convert the inputs to integer directly - ''' - l1 = len(num1) - l2 = len(num2) - - x = 0 - for char in num1: - l1 -= 1 - x += self.str_to_int(char, l1) - - y = 0 - for char in num2: - l2 -= 1 - y += self.str_to_int(char, l2) - - xy = x * y - - return str(xy) - - - def str_to_int(self, s, no_zeros): - if s == '0': - x = 0 - elif s == '1': - x = 1 - elif s == '2': - x = 2 - elif s == '3': - x = 3 - elif s == '4': - x = 4 - elif s == '5': - x = 5 - elif s == '6': - x = 6 - elif s == '7': - x = 7 - elif s == '8': - x = 8 - elif s == '9': - x = 9 - return x * pow(10, no_zeros) \ No newline at end of file From 8c9c319464731be1ab1a2ac40029c0be7a370fef Mon Sep 17 00:00:00 2001 From: AditSoni Date: Sat, 10 Oct 2020 00:20:14 +0530 Subject: [PATCH 164/204] Added code for problem 0125.Valid Palindromes --- LeetCode/0125_Valid_Palindrome.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 LeetCode/0125_Valid_Palindrome.py diff --git a/LeetCode/0125_Valid_Palindrome.py b/LeetCode/0125_Valid_Palindrome.py new file mode 100644 index 0000000..e69de29 From a82a97f00ce55defb3d1ed8bb5cfaca9b064b222 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Fri, 9 Oct 2020 21:17:01 +0200 Subject: [PATCH 165/204] Delete 1480_Running_Sum_of_1d_Array.py Problem already solved --- LeetCode/1480_Running_Sum_of_1d_Array.py | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 LeetCode/1480_Running_Sum_of_1d_Array.py diff --git a/LeetCode/1480_Running_Sum_of_1d_Array.py b/LeetCode/1480_Running_Sum_of_1d_Array.py deleted file mode 100644 index 9697070..0000000 --- a/LeetCode/1480_Running_Sum_of_1d_Array.py +++ /dev/null @@ -1,7 +0,0 @@ -class Solution: - def runningSum(self, nums: List[int]) -> List[int]: - answers=[] - answers.append(nums[0]) - for i in range(1,len(nums)): - answers.append(answers[-1]+nums[i]) - return answers \ No newline at end of file From c24967f1dbbb557bc4f4f4b79958532bf7c09e7d Mon Sep 17 00:00:00 2001 From: AditSoni Date: Sat, 10 Oct 2020 00:51:09 +0530 Subject: [PATCH 166/204] bad write --- LeetCode/0125_Valid_Palindrome.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 LeetCode/0125_Valid_Palindrome.py diff --git a/LeetCode/0125_Valid_Palindrome.py b/LeetCode/0125_Valid_Palindrome.py deleted file mode 100644 index e69de29..0000000 From 4796ca9ecf96fc0f3d89deae03fef650e93a10d6 Mon Sep 17 00:00:00 2001 From: AditSoni Date: Sat, 10 Oct 2020 00:20:14 +0530 Subject: [PATCH 167/204] Added code for problem 93 restore ip address --- LeetCode/0093_Restore_IP_address.py | 53 +++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 LeetCode/0093_Restore_IP_address.py diff --git a/LeetCode/0093_Restore_IP_address.py b/LeetCode/0093_Restore_IP_address.py new file mode 100644 index 0000000..0f2630e --- /dev/null +++ b/LeetCode/0093_Restore_IP_address.py @@ -0,0 +1,53 @@ +class Solution: + + def restoreIpAddresses(self, s: str) -> list: + + return self.convert(s) + + def convert(self,s): + + sz = len(s) + + # Check for string size + if sz > 12: + return [] + snew = s + l = [] + + # Generating different combinations. + for i in range(1, sz - 2): + for j in range(i + 1, sz - 1): + for k in range(j + 1, sz): + snew = snew[:k] + "." + snew[k:] + snew = snew[:j] + "." + snew[j:] + snew = snew[:i] + "." + snew[i:] + + # Check for the validity of combination + if self.is_valid(snew): + l.append(snew) + + snew = s + + return l + + + + + def is_valid(self,ip): + + # Splitting by "." + ip = ip.split(".") + + # Checking for the corner cases + for i in ip: + if (len(i) > 3 or int(i) < 0 or + int(i) > 255): + return False + if len(i) > 1 and int(i) == 0: + return False + if (len(i) > 1 and int(i) != 0 and + i[0] == '0'): + return False + + return True + \ No newline at end of file From 8c976ba2b8ff4c6992641d68aa2d24ab4fe6e6e9 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Fri, 9 Oct 2020 21:40:41 +0200 Subject: [PATCH 168/204] Delete 0088_Merge Sorted Array.py Problem Already Solved --- LeetCode/0088_Merge Sorted Array.py | 31 ----------------------------- 1 file changed, 31 deletions(-) delete mode 100644 LeetCode/0088_Merge Sorted Array.py diff --git a/LeetCode/0088_Merge Sorted Array.py b/LeetCode/0088_Merge Sorted Array.py deleted file mode 100644 index c70f721..0000000 --- a/LeetCode/0088_Merge Sorted Array.py +++ /dev/null @@ -1,31 +0,0 @@ -class Solution: - def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: - - ##Method1 - i=0 - while(ik): -# pos = j -# break -# j+=1 -# nums1.insert (pos,k) -# m+=1 -# for x in range(0,len(nums1)-totalLen): -# del nums1[-1] -# # print(nums1) - - \ No newline at end of file From 06484267ebc1fc341af7b9dbdc12add14d4c61d6 Mon Sep 17 00:00:00 2001 From: matheusphalves Date: Fri, 9 Oct 2020 16:53:37 -0300 Subject: [PATCH 169/204] Revert "Added 0257_Binary_Tree_Paths.py" This reverts commit 63af736a380cc022c03893aba75c0d0d3ed053a0. --- LeetCode/0257_Binary_Tree_Paths.py | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 LeetCode/0257_Binary_Tree_Paths.py diff --git a/LeetCode/0257_Binary_Tree_Paths.py b/LeetCode/0257_Binary_Tree_Paths.py deleted file mode 100644 index f5debc7..0000000 --- a/LeetCode/0257_Binary_Tree_Paths.py +++ /dev/null @@ -1,24 +0,0 @@ -# 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 __init__(self): - self.listOfPaths = [] #this list will save all paths and return - - def binaryTreePaths(self, root: TreeNode, path="") -> List[str]: - if(root==None): - return [] #nothing to return (it's a empty node) ... - - path += " " + str(root.val)#actual node value becomes a 'element route' - - if(root.left==None and root.right==None): - self.listOfPaths.append(path[1:].replace(" ", "->"))#question output format - - else: - self.binaryTreePaths(root.left, path) #scan by route in left node - self.binaryTreePaths(root.right, path)#scan by route in right node - return self.listOfPaths #return all paths - From 0dbf96dbbd03c7e7db04adb9ba925d78bc742c3f Mon Sep 17 00:00:00 2001 From: matheusphalves Date: Fri, 9 Oct 2020 16:55:17 -0300 Subject: [PATCH 170/204] identation error fixed from 0257 LeetCode problem --- LeetCode/0257_Binary_Tree_Paths.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 LeetCode/0257_Binary_Tree_Paths.py diff --git a/LeetCode/0257_Binary_Tree_Paths.py b/LeetCode/0257_Binary_Tree_Paths.py new file mode 100644 index 0000000..9dad911 --- /dev/null +++ b/LeetCode/0257_Binary_Tree_Paths.py @@ -0,0 +1,24 @@ +# 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 __init__(self): + self.listOfPaths = [] #this list will save all paths and return + + def binaryTreePaths(self, root: TreeNode, path="") -> List[str]: + if(root==None): + return [] #nothing to return (it's a empty node) ... + + path += " " + str(root.val)#actual node value becomes a 'element route' + + if(root.left==None and root.right==None): + self.listOfPaths.append(path[1:].replace(" ", "->"))#question output format + + else: + self.binaryTreePaths(root.left, path) #scan by route in left node + self.binaryTreePaths(root.right, path)#scan by route in right node + return self.listOfPaths #return all paths + From 851bcc263db9c458bb60d8f55da346d09272c034 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Fri, 9 Oct 2020 21:56:36 +0200 Subject: [PATCH 171/204] Delete 0933_Number_of_recent_calls.py Problem already solved --- LeetCode/0933_Number_of_recent_calls.py | 11 ----------- 1 file changed, 11 deletions(-) delete mode 100644 LeetCode/0933_Number_of_recent_calls.py diff --git a/LeetCode/0933_Number_of_recent_calls.py b/LeetCode/0933_Number_of_recent_calls.py deleted file mode 100644 index 9d3ef76..0000000 --- a/LeetCode/0933_Number_of_recent_calls.py +++ /dev/null @@ -1,11 +0,0 @@ -#python3 -class RecentCounter: - - def __init__(self): - self.q = collections.deque() - - def ping(self, t: int) -> int: - self.q.append(t) - while self.q[0] < t - 3000: - self.q.popleft() - return len(self.q) From af24296a8d466d7bd92a2a99490eef6ea6221892 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Fri, 9 Oct 2020 22:12:20 +0200 Subject: [PATCH 172/204] moved to LeetCode Folder --- .../1441_build_an_array_with_stack_operations.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 1441_build_an_array_with_stack_operations.py => LeetCode/1441_build_an_array_with_stack_operations.py (100%) diff --git a/1441_build_an_array_with_stack_operations.py b/LeetCode/1441_build_an_array_with_stack_operations.py similarity index 100% rename from 1441_build_an_array_with_stack_operations.py rename to LeetCode/1441_build_an_array_with_stack_operations.py From fdbed32ecbbc21e6030e2cd2b4bea43f11e2638c Mon Sep 17 00:00:00 2001 From: soum-sr Date: Sat, 10 Oct 2020 02:16:44 +0530 Subject: [PATCH 173/204] added 1559_Detect_Cycles_In_2D_Grid.py --- LeetCode/1559_Detect_Cycles_In_2D_Grid.py | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 LeetCode/1559_Detect_Cycles_In_2D_Grid.py diff --git a/LeetCode/1559_Detect_Cycles_In_2D_Grid.py b/LeetCode/1559_Detect_Cycles_In_2D_Grid.py new file mode 100644 index 0000000..92985e3 --- /dev/null +++ b/LeetCode/1559_Detect_Cycles_In_2D_Grid.py @@ -0,0 +1,55 @@ +class Solution: + def __init__(self): + self.directionX = [-1,0,1,0] + self.directionY = [0,1,0,-1] + def isValid(self, x, y, N, M): + if x < N and x >= 0 and y < M and y >= 0: + return True + return False + + def isCycle(self, x, y, arr, visited, parentX, parentY): + # Mark the current vertex as visited + visited[x][y] = True + N, M = len(arr), len(arr[0]) + + for k in range(4): + newX = x + self.directionX[k] + newY = y + self.directionY[k] + if self.isValid(newX, newY, N, M) and arr[newX][newY] == arr[x][y] and not (parentX == newX and parentY == newY): + if visited[newX][newY]: + return True + else: + + check = self.isCycle(newX, newY, arr, visited, x,y) + if check: + return True + return False + + def containsCycle(self, grid: List[List[str]]) -> bool: + N, M = len(grid), len(grid[0]) + # Initially all the cells are unvisited + visited = [[False] * M for _ in range(N)] + + # Variable to store the result + cycle = False + + # As there is no fixed position of the cycle + # we have to loop through all the elements + for i in range(N): + if cycle == True: + break + + for j in range(M): + ## Taking (-1, -1) as source node's parent + if visited[i][j] == False: + cycle = self.isCycle(i, j, grid, visited, -1, -1) + + if cycle == True: + break + + return cycle + + + + + \ No newline at end of file From cb500459da670ccb92bd048260dacea49cdbbe21 Mon Sep 17 00:00:00 2001 From: Sachin Jindal <45817023+jindalsachin@users.noreply.github.com> Date: Sat, 10 Oct 2020 02:32:57 +0530 Subject: [PATCH 174/204] Create 0448-Find-All-Numbers-Disappeared-in-an-Array.py --- .../0448-Find-All-Numbers-Disappeared-in-an-Array.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0448-Find-All-Numbers-Disappeared-in-an-Array.py diff --git a/LeetCode/0448-Find-All-Numbers-Disappeared-in-an-Array.py b/LeetCode/0448-Find-All-Numbers-Disappeared-in-an-Array.py new file mode 100644 index 0000000..ba1f630 --- /dev/null +++ b/LeetCode/0448-Find-All-Numbers-Disappeared-in-an-Array.py @@ -0,0 +1,12 @@ +class Solution: + def findDisappearedNumbers(self, nums: List[int]) -> List[int]: + List=[] + for i in range(len(nums)): + val= abs(nums[i])-1 + if(nums[val]>0): + nums[val]=-nums[val] + for i in range(len(nums)): + if(nums[i]>0): + List.append(i+1) + return List + From de916e3870298de6570e29b8ee9a81235ec74524 Mon Sep 17 00:00:00 2001 From: Drew Date: Sat, 10 Oct 2020 00:07:18 +0100 Subject: [PATCH 175/204] Issue #528: LeetCode task 1160 - 1160. Find Words That Can Be Formed by Characters --- ...60_FindWordsThatCanBeFormedByCharacters.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 LeetCode/1160_FindWordsThatCanBeFormedByCharacters.py diff --git a/LeetCode/1160_FindWordsThatCanBeFormedByCharacters.py b/LeetCode/1160_FindWordsThatCanBeFormedByCharacters.py new file mode 100644 index 0000000..f45bab0 --- /dev/null +++ b/LeetCode/1160_FindWordsThatCanBeFormedByCharacters.py @@ -0,0 +1,23 @@ +class Solution: + def countCharacters(self, words: List[str], chars: str) -> int: + charBins = {char:chars.count(char) for char in chars} + goodWords = [] + + for word in words: + if (len(word) > len(chars)): + continue + + if not set(word).issubset(chars): + continue + + letterBins = {letter:word.count(letter) for letter in word} + + goodWord = True + for letter in letterBins: + if letterBins[letter] > charBins[letter]: + goodWord = False + + if (goodWord): + goodWords.append(word) + + return sum(len(word) for word in goodWords) From 5f916962ba0b82f8a7e98ddbddb3e7b8c218fe3b Mon Sep 17 00:00:00 2001 From: Alexey Ilyukhov Date: Sat, 10 Oct 2020 02:37:31 +0300 Subject: [PATCH 176/204] Add 1499. Max Value of Equation --- LeetCode/1499_Max_Value_of_Equation.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 LeetCode/1499_Max_Value_of_Equation.py diff --git a/LeetCode/1499_Max_Value_of_Equation.py b/LeetCode/1499_Max_Value_of_Equation.py new file mode 100644 index 0000000..4c1f330 --- /dev/null +++ b/LeetCode/1499_Max_Value_of_Equation.py @@ -0,0 +1,23 @@ +class Solution(object): + def findMaxValueOfEquation(self, points, k): + """ + :type points: List[List[int]] + :type k: int + :rtype: int + """ + ans = None + + d = deque() + for x, y in points: + while len(d) > 0 and d[0][0] < x - k: + d.popleft() + + if len(d) != 0: + ans = max(ans, x + y + d[0][1] - d[0][0]) + + while (len(d) != 0) and d[-1][1] - d[-1][0] < y - x: + d.pop() + + d.append((x, y)) + + return ans From a29862ab2f17412fa3ce0516236572a6b0d3904f Mon Sep 17 00:00:00 2001 From: Alexey Ilyukhov Date: Sat, 10 Oct 2020 02:55:10 +0300 Subject: [PATCH 177/204] Add 1250. Check If It Is a Good Array --- LeetCode/1250_Check_If_It_Is_a_Good_Array.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/1250_Check_If_It_Is_a_Good_Array.py diff --git a/LeetCode/1250_Check_If_It_Is_a_Good_Array.py b/LeetCode/1250_Check_If_It_Is_a_Good_Array.py new file mode 100644 index 0000000..0673d1c --- /dev/null +++ b/LeetCode/1250_Check_If_It_Is_a_Good_Array.py @@ -0,0 +1,15 @@ +class Solution(object): + def isGoodArray(self, nums): + """ + :type nums: List[int] + :rtype: bool + """ + def gcd(a, b): + if a == 0: + return b + if a > b: + return gcd(b, a) + return gcd(b % a, a) + + return reduce(gcd, nums) == 1 + From 975c201dbd7bd60f3333d9cc82993146be062026 Mon Sep 17 00:00:00 2001 From: Nigesh Shakya Date: Fri, 9 Oct 2020 19:05:18 -0500 Subject: [PATCH 178/204] Added a leetcode solution for problem 0091 Decode Ways for hacktoberfest --- LeetCode/0091_Decode_Ways.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0091_Decode_Ways.py diff --git a/LeetCode/0091_Decode_Ways.py b/LeetCode/0091_Decode_Ways.py new file mode 100644 index 0000000..e5d83ff --- /dev/null +++ b/LeetCode/0091_Decode_Ways.py @@ -0,0 +1,20 @@ +class Solution: + def numDecodings(self, s: str) -> int: + def in_range(n): + if n[0] == '0': + return False + to_int = int(n) + if to_int <= 26 and to_int > 0: + return True + return False + + N = len(s) + a, b = 1, 1 + if N == 0 or s[0] == '0': + return 0 + + for i in range(1, N): + extra = a if in_range(s[i-1:i+1]) else 0 + c = extra + (b if in_range(s[i]) else 0) + a, b = b, c + return b From 97d27294bc151f05e2569832052582da400c6f58 Mon Sep 17 00:00:00 2001 From: Alexey Ilyukhov Date: Sat, 10 Oct 2020 03:47:26 +0300 Subject: [PATCH 179/204] Add 483. Smallest Good Base --- LeetCode/0483_Smallest_Good_Base.py | 33 +++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 LeetCode/0483_Smallest_Good_Base.py diff --git a/LeetCode/0483_Smallest_Good_Base.py b/LeetCode/0483_Smallest_Good_Base.py new file mode 100644 index 0000000..11fcd12 --- /dev/null +++ b/LeetCode/0483_Smallest_Good_Base.py @@ -0,0 +1,33 @@ +import math + +class Solution(object): + def smallestGoodBase(self, n): + """ + :type n: str + :rtype: str + """ + n = int(n) + + for length in range(64, 2, -1): + l = 2 + r = int(math.sqrt(n) + 1) + + def sum(mid): + res = 0 + for i in range(length - 1, -1, -1): + res += mid ** i + if res > n: + return res + return res + + while l < r - 1: + mid = (l + r) // 2 + if sum(mid) <= n: + l = mid + else: + r = mid + + if sum(l) == n: + return str(l) + + return str(n - 1) From f8fd6e8d157b10817f57b9ee7305ebdad2c00675 Mon Sep 17 00:00:00 2001 From: rkkksss <48599078+rkkksss@users.noreply.github.com> Date: Sat, 10 Oct 2020 04:08:56 +0300 Subject: [PATCH 180/204] Added Move Zeroes --- LeetCode/0283_Move_Zeroes.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0283_Move_Zeroes.py diff --git a/LeetCode/0283_Move_Zeroes.py b/LeetCode/0283_Move_Zeroes.py new file mode 100644 index 0000000..e445f63 --- /dev/null +++ b/LeetCode/0283_Move_Zeroes.py @@ -0,0 +1,12 @@ +class Solution: + def moveZeroes(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + pos = 0 + for i in range(len(nums)): + if nums[i]!= 0: + if pos!=i: + nums[pos], nums[i] = nums[i], nums[pos] + pos += 1 + From 9cb8026b50529f97753856dd084c12980071e20e Mon Sep 17 00:00:00 2001 From: rkkksss <48599078+rkkksss@users.noreply.github.com> Date: Sat, 10 Oct 2020 04:26:55 +0300 Subject: [PATCH 181/204] Added 771 Jewels ans Stones --- LeetCode/0771_Jewels_and_Stones.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 LeetCode/0771_Jewels_and_Stones.py diff --git a/LeetCode/0771_Jewels_and_Stones.py b/LeetCode/0771_Jewels_and_Stones.py new file mode 100644 index 0000000..f635dcc --- /dev/null +++ b/LeetCode/0771_Jewels_and_Stones.py @@ -0,0 +1,8 @@ +class Solution: + def numJewelsInStones(self, J: str, S: str) -> int: + stones = Counter(S) + count = 0 + for j in J: + if stones and j in stones: + count += stones[j] + return count From 9dc920f5b01692cf65c34c82dbf9f4934e259114 Mon Sep 17 00:00:00 2001 From: rkkksss <48599078+rkkksss@users.noreply.github.com> Date: Sat, 10 Oct 2020 04:34:47 +0300 Subject: [PATCH 182/204] Addded 258 Add digits --- LeetCode/0258_Add_Digits.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 LeetCode/0258_Add_Digits.py diff --git a/LeetCode/0258_Add_Digits.py b/LeetCode/0258_Add_Digits.py new file mode 100644 index 0000000..8f0800c --- /dev/null +++ b/LeetCode/0258_Add_Digits.py @@ -0,0 +1,5 @@ +class Solution: + def addDigits(self, num: int) -> int: + if num < 10: return num + if num % 9 == 0: return 9 + return num % 9 From 54a69ff724b8153178612076e87f7427611f300a Mon Sep 17 00:00:00 2001 From: frank731 <38197177+frank731@users.noreply.github.com> Date: Fri, 9 Oct 2020 18:41:40 -0700 Subject: [PATCH 183/204] Create 0443_String_Compression.py --- LeetCode/0443_String_Compression.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 LeetCode/0443_String_Compression.py diff --git a/LeetCode/0443_String_Compression.py b/LeetCode/0443_String_Compression.py new file mode 100644 index 0000000..609ce2a --- /dev/null +++ b/LeetCode/0443_String_Compression.py @@ -0,0 +1,16 @@ +class Solution: + def compress(self, chars: List[str]) -> int: + read = 0 + while read < len(chars) - 1: + count = 1 + read_next = read + 1 + while read < len(chars) - 1 and chars[read_next] == chars[read]: + del chars[read_next] + count += 1 + if count > 1: + for char in str(count): + chars.insert(read_next, char) + read_next += 1 + read = read_next + return len(chars) + From ffc619f9977d45b148a65e8c9301ddb58d0608c2 Mon Sep 17 00:00:00 2001 From: LCVcode Date: Fri, 9 Oct 2020 23:23:42 -0400 Subject: [PATCH 184/204] 1603 Design Parking System --- LeetCode/1603_Design_Parking_System.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/1603_Design_Parking_System.py diff --git a/LeetCode/1603_Design_Parking_System.py b/LeetCode/1603_Design_Parking_System.py new file mode 100644 index 0000000..cbba789 --- /dev/null +++ b/LeetCode/1603_Design_Parking_System.py @@ -0,0 +1,11 @@ +class ParkingSystem: + + def __init__(self, big: int, medium: int, small: int): + self._limits = [big, medium, small] + + + def addCar(self, carType: int) -> bool: + self._limits[carType - 1] -= 1 + if self._limits[carType - 1] < 0: + return False + return True From 88d297c5a45d18bd8ebbb7a7c825664a58cda9f9 Mon Sep 17 00:00:00 2001 From: sailok Date: Sat, 10 Oct 2020 08:58:43 +0530 Subject: [PATCH 185/204] Adding 0368 - Largest Divisible Subset Problem --- LeetCode/0368_Largest_Divisible_Subset.py | 27 +++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 LeetCode/0368_Largest_Divisible_Subset.py diff --git a/LeetCode/0368_Largest_Divisible_Subset.py b/LeetCode/0368_Largest_Divisible_Subset.py new file mode 100644 index 0000000..ea55aeb --- /dev/null +++ b/LeetCode/0368_Largest_Divisible_Subset.py @@ -0,0 +1,27 @@ +class Solution: + def largestDivisibleSubset(self, nums: List[int]) -> List[int]: + if len(nums) < 2: + return nums + #creating a monotonic sequence of list + nums.sort() + #creating a DP list to keep track of how many preceeding elements can divide ith element + dp = [1]*len(nums) + max_ind = 0 + #dp pass using the following condition + for i in range(1, len(nums)): + for j in range(i): + if nums[i]%nums[j] == 0: + dp[i] = max(dp[i], dp[j] + 1) + if dp[max_ind] < dp[i]: + max_ind = i + res = [] + res.append(nums[max_ind]) + prev = nums[max_ind] + #reconstructing the sequence by iterating backwards + for i in range(max_ind - 1, -1, -1): + if dp[i] > 0 and dp[max_ind]-1 == dp[i] and prev%nums[i] == 0: + res.append(nums[i]) + prev = nums[i] + max_ind = i + res.reverse() + return res \ No newline at end of file From 5df89273710bddd67e9792249eebf8cd913023e5 Mon Sep 17 00:00:00 2001 From: Sagnik Mazumder Date: Sat, 10 Oct 2020 11:53:49 +0530 Subject: [PATCH 186/204] added solution to leetcode problem 1137 --- LeetCode/1137_N_th_Tribonacci_Number.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/1137_N_th_Tribonacci_Number.py diff --git a/LeetCode/1137_N_th_Tribonacci_Number.py b/LeetCode/1137_N_th_Tribonacci_Number.py new file mode 100644 index 0000000..8c01a86 --- /dev/null +++ b/LeetCode/1137_N_th_Tribonacci_Number.py @@ -0,0 +1,14 @@ +class Solution: + def tribonacci(self, n: int) -> int: + a, b, c = 0, 1, 1 + if n == 0: + return 0 + elif n == 1 or n == 2: + return 1 + else: + for _ in range(n - 2): + temp = a + b + c + a = b + b = c + c = temp + return temp From 045177ef462f96a7b4139d40728085e61da2d354 Mon Sep 17 00:00:00 2001 From: tejasbirsingh Date: Sat, 10 Oct 2020 12:09:00 +0530 Subject: [PATCH 187/204] Add House Robber 3 Problem --- ..._House_robber.py => 0213_House_robber2.py} | 0 LeetCode/0337_House_Robber_III.py | 75 +++++++++++++++++++ 2 files changed, 75 insertions(+) rename LeetCode/{0213_House_robber.py => 0213_House_robber2.py} (100%) create mode 100644 LeetCode/0337_House_Robber_III.py diff --git a/LeetCode/0213_House_robber.py b/LeetCode/0213_House_robber2.py similarity index 100% rename from LeetCode/0213_House_robber.py rename to LeetCode/0213_House_robber2.py diff --git a/LeetCode/0337_House_Robber_III.py b/LeetCode/0337_House_Robber_III.py new file mode 100644 index 0000000..1198458 --- /dev/null +++ b/LeetCode/0337_House_Robber_III.py @@ -0,0 +1,75 @@ +''' +337. House Robber III +The thief has found himself a new place for his thievery again. +There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. +After a tour, the smart thief realized that "all houses in this place forms a binary tree". +It will automatically contact the police if two directly-linked houses were broken into on the same night. +Determine the maximum amount of money the thief can rob tonight without alerting the police. +Example 1: + Input: [3,2,3,null,3,null,1] + 3 + / \ + 2 3 + \ \ + 3 1 + +Output: 7 + Explanation: Maximum amount of money the thief can rob = 3 + 3 + 1 = 7. + +Time Complexity:- O(N) +Space Complexity:- O(N), as we are using dictionary to memoize the solution +''' + +def rob(self, root: TreeNode) -> int: + # this dp dictionary will help us reduce the time complexity by memoizing the solutions + dp = {} + + # this function will return the max profit that we can get + def rob_helper(root): + # base cases + if(root is None): + return 0 + # if we have the value for root in dp that we means we have calculated the value + # previously so we can simply return the saved value + if(root in dp.keys()): + return dp[root] + ''' + In this problem our constraints are:- + 1. If we add/rob the profit of parent then we can't add/rob profit of children + as the police will be alerted + 2. If we don't rob the parent then we can rob its child nodes + + Example:- + + lvl 1 3 + / \ + lvl 2 2 3 + \ \ + lvl 3 3 1 + In this if we add the profit for 3 then we can't add 2 and 3 from level 2 but add 3 and 1 from level 3 + If we add 2 and 3 from level 2 then we can't add profit from level 1 and 3 + Therefore, in a nutshell WE CAN'T ADD THE PROFIT OF 2 ADJACENT LEVEL/HOUSES + + ''' + + # It is the total profit if we exclude the parent and add the left and right child + profit1 = rob_helper(root.left) + rob_helper(root.right) + + # In this case we left child nodes and added the profit for parent node + profit2 = root.val + # As we robbed the parent node so we can't rob children + # but we can rob children of left and right child of parent + + # If root.left has left and right children then add there profit + if(root.left is not None): + profit2 += rob_helper(root.left.left) + rob_helper(root.left.right) + # If root.right has left and right children then add there profit + if(root.right is not None): + profit2 += rob_helper(root.right.left) + rob_helper(root.right.right) + + # save the max value in DP to memoize the solution + dp[root] = max(profit1, profit2) + + return dp[root] + + return rob_helper(root) From 54b5a1852ca87daf56a50695688e6d4053bd218c Mon Sep 17 00:00:00 2001 From: OMEGAeNcore Date: Sat, 10 Oct 2020 12:21:05 +0530 Subject: [PATCH 188/204] Adding Kth Largest Element in an Array Solution --- LeetCode/0215_Kth_Largest_Element_In_An_Array.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 LeetCode/0215_Kth_Largest_Element_In_An_Array.py diff --git a/LeetCode/0215_Kth_Largest_Element_In_An_Array.py b/LeetCode/0215_Kth_Largest_Element_In_An_Array.py new file mode 100644 index 0000000..f9994b4 --- /dev/null +++ b/LeetCode/0215_Kth_Largest_Element_In_An_Array.py @@ -0,0 +1,6 @@ +import heapq +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + heapq.heapify(nums) + res = heapq.nlargest(k,nums) + return res[len(res)-1] \ No newline at end of file From 34514b98d408982b72d6f036c3564a70f205f31c Mon Sep 17 00:00:00 2001 From: sailok Date: Sat, 10 Oct 2020 12:50:36 +0530 Subject: [PATCH 189/204] Adding 0647 Palindromic Substrings --- LeetCode/0647_Palindromic_Substrings.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LeetCode/0647_Palindromic_Substrings.py diff --git a/LeetCode/0647_Palindromic_Substrings.py b/LeetCode/0647_Palindromic_Substrings.py new file mode 100644 index 0000000..d1f8b9e --- /dev/null +++ b/LeetCode/0647_Palindromic_Substrings.py @@ -0,0 +1,21 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + N = len(s) + # declaring a DP matrix of size nxn + dp = [[0 for i in range(N)] for j in range(N)] + # looping through substring of every size and checking whether it is a valid substring + for l in range(N): + for i in range(N-l): + if l == 0: + dp[i][i] = 1 + continue + if s[i] == s[i+l]: + if l == 1: + dp[i][i+l] = 1 + elif dp[i+1][i+l-1] == 1: + dp[i][i+l] = 1 + count = 0 + for i in range(N): + for j in range(N): + count+=dp[i][j] + return count \ No newline at end of file From daed2131e6aa28760a50c6bb7df41cf3ec30ae79 Mon Sep 17 00:00:00 2001 From: AditSoni Date: Sat, 10 Oct 2020 15:04:43 +0530 Subject: [PATCH 190/204] Added problem 190 reverse bits --- LeetCode/0190_Reverse_bits.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 LeetCode/0190_Reverse_bits.py diff --git a/LeetCode/0190_Reverse_bits.py b/LeetCode/0190_Reverse_bits.py new file mode 100644 index 0000000..cfd8a99 --- /dev/null +++ b/LeetCode/0190_Reverse_bits.py @@ -0,0 +1,5 @@ +class Solution: + def reverseBits(self, n: int) -> int: + + s='{0:032b}'.format(n)[::-1] + return int(s,2) \ No newline at end of file From af4c6eeee4280d0d5d7485515707518fa718f631 Mon Sep 17 00:00:00 2001 From: AditSoni Date: Sat, 10 Oct 2020 15:11:37 +0530 Subject: [PATCH 191/204] added 191 Number of 1 bits --- LeetCode/0191_Number_of_1_bits.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 LeetCode/0191_Number_of_1_bits.py diff --git a/LeetCode/0191_Number_of_1_bits.py b/LeetCode/0191_Number_of_1_bits.py new file mode 100644 index 0000000..8454fa0 --- /dev/null +++ b/LeetCode/0191_Number_of_1_bits.py @@ -0,0 +1,4 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + + return '{0:b}'.format(n).count('1') \ No newline at end of file From c6ffee134348fdcce84e109bdf263ec779a412fa Mon Sep 17 00:00:00 2001 From: Satyam Yadav <72488628+SatyamYadav-cmd@users.noreply.github.com> Date: Sat, 10 Oct 2020 15:43:01 +0530 Subject: [PATCH 192/204] Create 0043_Multiply Strings.py --- LeetCode/0043_Multiply Strings.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LeetCode/0043_Multiply Strings.py diff --git a/LeetCode/0043_Multiply Strings.py b/LeetCode/0043_Multiply Strings.py new file mode 100644 index 0000000..e6dd828 --- /dev/null +++ b/LeetCode/0043_Multiply Strings.py @@ -0,0 +1,7 @@ +class Solution(object): + def multiply(self, num1, num2): + a,b=eval(num1),eval(num2) + c=a*b + c=str(c) + return c + From f1eaea0a76c966e832aa120baad9d9379ef959c1 Mon Sep 17 00:00:00 2001 From: Eric Teo Date: Sat, 10 Oct 2020 19:01:09 +0800 Subject: [PATCH 193/204] Rename 0523_K_diff_Pairs_in_an_Array.py to 0532_K_diff_Pairs_in_an_Array.py The problem number is 532 in Leetcode not 523. --- ...diff_Pairs_in_an_Array.py => 0532_K_diff_Pairs_in_an_Array.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{0523_K_diff_Pairs_in_an_Array.py => 0532_K_diff_Pairs_in_an_Array.py} (100%) diff --git a/LeetCode/0523_K_diff_Pairs_in_an_Array.py b/LeetCode/0532_K_diff_Pairs_in_an_Array.py similarity index 100% rename from LeetCode/0523_K_diff_Pairs_in_an_Array.py rename to LeetCode/0532_K_diff_Pairs_in_an_Array.py From 83e49c106c93d318bc0728760f6f154ab16f8862 Mon Sep 17 00:00:00 2001 From: tejasvicsr1 Date: Sat, 10 Oct 2020 16:31:29 +0530 Subject: [PATCH 194/204] Solution to issue #579 --- LeetCode/1480_Running_Sum_of_1d_array.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LeetCode/1480_Running_Sum_of_1d_array.py diff --git a/LeetCode/1480_Running_Sum_of_1d_array.py b/LeetCode/1480_Running_Sum_of_1d_array.py new file mode 100644 index 0000000..1cc9a3f --- /dev/null +++ b/LeetCode/1480_Running_Sum_of_1d_array.py @@ -0,0 +1,7 @@ +class Solution: + def runningSum(self, nums: List[int]) -> List[int]: + ans = [] + ans.append(nums[0]) + for i in range(1, len(nums)): + ans.append(ans[i-1] + nums[i]) + return ans \ No newline at end of file From d5596d40fe37cadb2fa4c76dae756b25527ccdf5 Mon Sep 17 00:00:00 2001 From: nainys <30886059+nainys@users.noreply.github.com> Date: Sat, 10 Oct 2020 17:00:09 +0530 Subject: [PATCH 195/204] add: solution to reducing dishes --- LeetCode/1402_Reducing_Dishes.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/1402_Reducing_Dishes.py diff --git a/LeetCode/1402_Reducing_Dishes.py b/LeetCode/1402_Reducing_Dishes.py new file mode 100644 index 0000000..1f2c012 --- /dev/null +++ b/LeetCode/1402_Reducing_Dishes.py @@ -0,0 +1,11 @@ +class Solution: + def maxSatisfaction(self, satisfaction: List[int]) -> int: + + satisfaction.sort(reverse=True) + ans = cur_sum = 0 + for ele in satisfaction: + cur_sum += ele + if cur_sum >= 0: + ans += cur_sum + + return ans; \ No newline at end of file From 5e618b61f082b0ae33943c26f24c80db219dd8a0 Mon Sep 17 00:00:00 2001 From: tejasvicsr1 Date: Sat, 10 Oct 2020 17:04:59 +0530 Subject: [PATCH 196/204] Solution to the problem 1470 #584 --- LeetCode/1470_Shuffle_the_array.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/1470_Shuffle_the_array.py diff --git a/LeetCode/1470_Shuffle_the_array.py b/LeetCode/1470_Shuffle_the_array.py new file mode 100644 index 0000000..bf93e11 --- /dev/null +++ b/LeetCode/1470_Shuffle_the_array.py @@ -0,0 +1,13 @@ +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + ans = [] + j = 0 + k = n + for i in range(0, len(nums)): + if i%2 == 0: + ans.append(nums[j]) + j += 1 + else: + ans.append(nums[k]) + k += 1 + return ans \ No newline at end of file From 8feaafa27944b6ceccac88b89ebeb50d557b152a Mon Sep 17 00:00:00 2001 From: Tejasvi Chebrolu Date: Sat, 10 Oct 2020 17:13:37 +0530 Subject: [PATCH 197/204] Delete 1470_Shuffle_the_array.py --- LeetCode/1470_Shuffle_the_array.py | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 LeetCode/1470_Shuffle_the_array.py diff --git a/LeetCode/1470_Shuffle_the_array.py b/LeetCode/1470_Shuffle_the_array.py deleted file mode 100644 index bf93e11..0000000 --- a/LeetCode/1470_Shuffle_the_array.py +++ /dev/null @@ -1,13 +0,0 @@ -class Solution: - def shuffle(self, nums: List[int], n: int) -> List[int]: - ans = [] - j = 0 - k = n - for i in range(0, len(nums)): - if i%2 == 0: - ans.append(nums[j]) - j += 1 - else: - ans.append(nums[k]) - k += 1 - return ans \ No newline at end of file From 4e6e98c1508b9642d4bff0db108a894fb73033c7 Mon Sep 17 00:00:00 2001 From: tejasvicsr1 Date: Sat, 10 Oct 2020 17:19:44 +0530 Subject: [PATCH 198/204] Solution to the problem 1470 #584 --- LeetCode/1470_Shuffle_the_array.py | 1 + 1 file changed, 1 insertion(+) diff --git a/LeetCode/1470_Shuffle_the_array.py b/LeetCode/1470_Shuffle_the_array.py index bf93e11..0c0ae50 100644 --- a/LeetCode/1470_Shuffle_the_array.py +++ b/LeetCode/1470_Shuffle_the_array.py @@ -1,3 +1,4 @@ +#solution to 1470 class Solution: def shuffle(self, nums: List[int], n: int) -> List[int]: ans = [] From 4ca12f3288b317a8374c9b4d4c3525286606f5b6 Mon Sep 17 00:00:00 2001 From: tejasvicsr1 Date: Sat, 10 Oct 2020 17:29:33 +0530 Subject: [PATCH 199/204] Solution to the problem 1512 #588 --- LeetCode/1512_Number_of_Good_Pairs.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 LeetCode/1512_Number_of_Good_Pairs.py diff --git a/LeetCode/1512_Number_of_Good_Pairs.py b/LeetCode/1512_Number_of_Good_Pairs.py new file mode 100644 index 0000000..f0eafe2 --- /dev/null +++ b/LeetCode/1512_Number_of_Good_Pairs.py @@ -0,0 +1,8 @@ +class Solution: + def numIdenticalPairs(self, nums: List[int]) -> int: + ans = 0 + for i in range(0, len(nums)): + for j in range(0, len(nums)): + if(nums[i] == nums[j] and i < j): + ans += 1 + return ans \ No newline at end of file From c323f3494fc65079ee7dd9e9230500f3b4717f50 Mon Sep 17 00:00:00 2001 From: Satyam Yadav <72488628+SatyamYadav-cmd@users.noreply.github.com> Date: Sat, 10 Oct 2020 18:46:59 +0530 Subject: [PATCH 200/204] Create 0088_Merge_Sorted_Array.py --- LeetCode/0088_Merge_Sorted_Array.py | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 LeetCode/0088_Merge_Sorted_Array.py diff --git a/LeetCode/0088_Merge_Sorted_Array.py b/LeetCode/0088_Merge_Sorted_Array.py new file mode 100644 index 0000000..902755b --- /dev/null +++ b/LeetCode/0088_Merge_Sorted_Array.py @@ -0,0 +1,8 @@ +class Solution: + def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: + for x in nums2: + for y in range(len(nums1)): + if nums1[y]==0: + nums1[y]+=x + break + nums1.sort() From ba8da0f7ac84da1f299be268355e1f5eb56b0e00 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sat, 10 Oct 2020 16:25:44 +0200 Subject: [PATCH 201/204] Rename 1221 --- ...ced_Strings.py => 1221_Split_ a_String_in_Balanced_Strings.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{Split_ a_String_in_Balanced_Strings.py => 1221_Split_ a_String_in_Balanced_Strings.py} (100%) diff --git a/LeetCode/Split_ a_String_in_Balanced_Strings.py b/LeetCode/1221_Split_ a_String_in_Balanced_Strings.py similarity index 100% rename from LeetCode/Split_ a_String_in_Balanced_Strings.py rename to LeetCode/1221_Split_ a_String_in_Balanced_Strings.py From 4c05a449819c85cb869e76d702f9ab8934c4f54d Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sat, 10 Oct 2020 16:28:37 +0200 Subject: [PATCH 202/204] Delete 1480_Running_Sum_of_1d_array.py Problem already merged --- LeetCode/1480_Running_Sum_of_1d_array.py | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 LeetCode/1480_Running_Sum_of_1d_array.py diff --git a/LeetCode/1480_Running_Sum_of_1d_array.py b/LeetCode/1480_Running_Sum_of_1d_array.py deleted file mode 100644 index 1cc9a3f..0000000 --- a/LeetCode/1480_Running_Sum_of_1d_array.py +++ /dev/null @@ -1,7 +0,0 @@ -class Solution: - def runningSum(self, nums: List[int]) -> List[int]: - ans = [] - ans.append(nums[0]) - for i in range(1, len(nums)): - ans.append(ans[i-1] + nums[i]) - return ans \ No newline at end of file From 10891b610416a168821d34bebf1820440f698454 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sat, 10 Oct 2020 16:28:44 +0200 Subject: [PATCH 203/204] Delete 1470_Shuffle_the_array.py Problem already merged --- LeetCode/1470_Shuffle_the_array.py | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 LeetCode/1470_Shuffle_the_array.py diff --git a/LeetCode/1470_Shuffle_the_array.py b/LeetCode/1470_Shuffle_the_array.py deleted file mode 100644 index 0c0ae50..0000000 --- a/LeetCode/1470_Shuffle_the_array.py +++ /dev/null @@ -1,14 +0,0 @@ -#solution to 1470 -class Solution: - def shuffle(self, nums: List[int], n: int) -> List[int]: - ans = [] - j = 0 - k = n - for i in range(0, len(nums)): - if i%2 == 0: - ans.append(nums[j]) - j += 1 - else: - ans.append(nums[k]) - k += 1 - return ans \ No newline at end of file From 10b4b162b4ea624fbe39b936f0ebff4533e078d9 Mon Sep 17 00:00:00 2001 From: AditSoni Date: Sat, 10 Oct 2020 20:19:45 +0530 Subject: [PATCH 204/204] Added code for 242 Valid Anagram --- LeetCode/0242_Valid_anagrams.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 LeetCode/0242_Valid_anagrams.py diff --git a/LeetCode/0242_Valid_anagrams.py b/LeetCode/0242_Valid_anagrams.py new file mode 100644 index 0000000..35a1d99 --- /dev/null +++ b/LeetCode/0242_Valid_anagrams.py @@ -0,0 +1,4 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + + return (sorted(s) == sorted(t)) \ No newline at end of file