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/357] 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/357] 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/357] 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/357] 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/357] 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/357] 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/357] 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/357] 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/357] 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/357] 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/357] 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/357] 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 53bf83af38ae66fdf5d02afd9fe11316c76484c2 Mon Sep 17 00:00:00 2001 From: sathiyajith Date: Fri, 2 Oct 2020 19:28:30 +0530 Subject: [PATCH 013/357] 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 8a9d827012e6ce882f62661dc599b79cec37d7df Mon Sep 17 00:00:00 2001 From: Mohitbalwani26 Date: Fri, 2 Oct 2020 19:30:02 +0530 Subject: [PATCH 014/357] 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 015/357] 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 016/357] 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 017/357] 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 018/357] 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 019/357] 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 020/357] 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 021/357] 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 022/357] 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 023/357] 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 024/357] 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 025/357] 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 026/357] 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 027/357] 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 028/357] 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 029/357] 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 030/357] 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 031/357] 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 032/357] 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 033/357] 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 034/357] 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 035/357] 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 036/357] 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 037/357] 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 038/357] 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 039/357] 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 040/357] 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 041/357] 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 042/357] 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 043/357] 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 044/357] 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 045/357] 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 046/357] 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 047/357] #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 048/357] 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 049/357] 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 050/357] 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 051/357] 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 052/357] 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 053/357] 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 054/357] 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 9e8770edda3a4a61310e0df01b13d077165e3d07 Mon Sep 17 00:00:00 2001 From: S-Sanyal Date: Mon, 5 Oct 2020 01:20:09 +0530 Subject: [PATCH 055/357] Added Minimum_Number_of_K_Consecutive_Bit_Flips --- ...inimum_Number_of_K_Consecutive_Bit_Flips.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LeetCode/0995_Minimum_Number_of_K_Consecutive_Bit_Flips.py diff --git a/LeetCode/0995_Minimum_Number_of_K_Consecutive_Bit_Flips.py b/LeetCode/0995_Minimum_Number_of_K_Consecutive_Bit_Flips.py new file mode 100644 index 0000000..0ec30ef --- /dev/null +++ b/LeetCode/0995_Minimum_Number_of_K_Consecutive_Bit_Flips.py @@ -0,0 +1,18 @@ +class Solution: + def minKBitFlips(self, A: List[int], K: int) -> int: + n = len(A) + flips = [0]*(n+1); ans = 0 + for i in range(n): + flips[i] += flips[i-1] if i > 0 else 0 + + if not A[i] ^ (flips[i]%2): + if i + K - 1 >= n : + print(i, K) + return -1 + ans += 1 + flips[i] += 1 + flips[i+K] -= 1 + + return ans + + \ No newline at end of file From af51600b29288fac516d2b66786c0a67697f79af Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sun, 4 Oct 2020 21:54:31 +0200 Subject: [PATCH 056/357] 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 057/357] 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 058/357] 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 059/357] 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 060/357] 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 061/357] 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 062/357] 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 063/357] 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 064/357] 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 065/357] 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 066/357] 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 067/357] 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 068/357] 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 069/357] 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 070/357] 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 071/357] 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 072/357] 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 073/357] 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 074/357] 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 075/357] 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 076/357] 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 077/357] 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 078/357] 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 079/357] 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 080/357] 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 081/357] 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 082/357] 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 083/357] 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 084/357] 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 085/357] 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 086/357] 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 087/357] 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 088/357] 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 089/357] 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 090/357] 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 091/357] 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 092/357] 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 093/357] 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 094/357] 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 095/357] 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 096/357] 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 097/357] 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 098/357] 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 099/357] 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 100/357] 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 101/357] 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 102/357] 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 103/357] 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 104/357] 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 105/357] 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 106/357] 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 107/357] 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 108/357] 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 109/357] 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 110/357] 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 111/357] 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 112/357] 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 113/357] 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 114/357] 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 115/357] 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 116/357] 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 117/357] 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 118/357] 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 119/357] 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 120/357] 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 121/357] 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 122/357] 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 123/357] 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 124/357] 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 125/357] 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 126/357] 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 127/357] 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 128/357] 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 129/357] 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 130/357] 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 131/357] 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 132/357] 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 133/357] 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 134/357] 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 135/357] 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 61718fbe77d4c7c91c0d3237d12fc4dc956869ec Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Wed, 7 Oct 2020 22:43:57 +0530 Subject: [PATCH 136/357] Added Anikdas file --- codechecker.py | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 codechecker.py diff --git a/codechecker.py b/codechecker.py new file mode 100644 index 0000000..c286bf9 --- /dev/null +++ b/codechecker.py @@ -0,0 +1,71 @@ +import requests, os, re, json +from github import Github + +from dotenv import load_dotenv + +load_dotenv(dotenv_path='sample.env') + +# load details from ENV +repo_name = os.getenv("REPO_NAME") +access_token = os.getenv("GITHUB_ACCESS_TOKEN") +pull_number = int(os.getenv("PR_NUMBER")) +leetcode_csrf_token = os.getenv("LEETCODE_CSRF_TOKEN") +leetcode_session_token = os.getenv("LEETCODE_SESSION_TOKEN") + +# authentication +g = Github(access_token) +repo = g.get_repo(repo_name) + +# get PR details +pull = repo.get_pull(pull_number) +all_files = pull.get_files() + +# get details of files from PR +file_url = "" +problem_name = "" +for i in all_files: + if i.filename[-3:] == ".py": + file_url = i.raw_url + problem_name = i.filename.lower() + +# parse question id and problem name +question_id = int(problem_name[0:4]) +problem_name = re.sub("_", "-", problem_name[5:-3]) + +# get file code +r = requests.get(file_url) +code = r.text + +# craft request +leetcode_submission_url = f"https://leetcode.com/problems/{problem_name}/submit/" +language = "python3" +headers = { + "Origin": "https://leetcode.com", + "content-type": "application/json", + "X-CSRFToken": leetcode_csrf_token, + "Referer": leetcode_submission_url, + "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0", + # "Cookie": f"csrftoken={leetcode_csrf_token};LEETCODE_SESSION={leetcode_session_token}", +} +cookies = { + "csrftoken": leetcode_csrf_token, + "LEETCODE_SESSION": leetcode_session_token, +} +body = {"question_id": str(question_id), "lang": language, "typed_code": code} + +# send request +submit = requests.post( + leetcode_submission_url, headers=headers, data=body, cookies=cookies +) + +print(submit.status_code) + +# get from submit url response +submission_id = "" + +# check submission against submission_id +leetcode_checker_url = f"https://leetcode.com/submissions/detail/{submission_id}/check/" + + +# sample request body extracted from network tab: {"question_id":"231","lang":"python3","typed_code":"class Solution:\n def isPowerOfTwo(self, x: int) -> bool:\n return (x != 0) and ((x & (x - 1)) == 0); \n"} +# get status of submission \ No newline at end of file From d57bc851a2c81180fc70fa8d19c514d27f669c2e Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Wed, 7 Oct 2020 22:49:20 +0530 Subject: [PATCH 137/357] Added file to check --- LeetCode/0001_Two_Sum.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/0001_Two_Sum.py diff --git a/LeetCode/0001_Two_Sum.py b/LeetCode/0001_Two_Sum.py new file mode 100644 index 0000000..38a449c --- /dev/null +++ b/LeetCode/0001_Two_Sum.py @@ -0,0 +1,10 @@ +class Solution(object): + def twoSum(self, nums, target): + if len(nums) <= 1: + return False + buff_dict = {} + for i in range(len(nums)): + if nums[i] in buff_dict: + return [buff_dict[nums[i]], i] + else: + buff_dict[target - nums[i]] = i \ 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 138/357] 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 139/357] 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 140/357] 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 141/357] 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 142/357] 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 143/357] 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 144/357] 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 145/357] 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 146/357] 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 147/357] 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 7e103464c74f66e20128f0e9790d59591630b19c Mon Sep 17 00:00:00 2001 From: kevin454475 <71903670+kevin454475@users.noreply.github.com> Date: Thu, 8 Oct 2020 10:58:36 -0400 Subject: [PATCH 148/357] Upload 0028_strStr.py to Leetcode folder https://leetcode.com/problems/implement-strstr/ --- LeetCode/0028_strStr.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LeetCode/0028_strStr.py diff --git a/LeetCode/0028_strStr.py b/LeetCode/0028_strStr.py new file mode 100644 index 0000000..b4ab756 --- /dev/null +++ b/LeetCode/0028_strStr.py @@ -0,0 +1,7 @@ +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + try: + res = haystack.index(needle) + return res + except: + return -1 if needle else 0 From 390389299d74f9e25d808e771ec95b4953f5eb4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1ty=C3=A1s=20Kiglics?= Date: Thu, 8 Oct 2020 20:14:49 +0200 Subject: [PATCH 149/357] solution for problem 165 --- LeetCode/0165_Compare_Version_Numbers.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/0165_Compare_Version_Numbers.py diff --git a/LeetCode/0165_Compare_Version_Numbers.py b/LeetCode/0165_Compare_Version_Numbers.py new file mode 100644 index 0000000..33fc300 --- /dev/null +++ b/LeetCode/0165_Compare_Version_Numbers.py @@ -0,0 +1,14 @@ +class Solution: + def compareVersion(self, version1: str, version2: str) -> int: + v1 = version1.split(".") + v2 = version2.split(".") + while len(v1) < len(v2): + v1.append("0") + while len(v2) < len(v1): + v2.append("0") + for i in range(len(v1)): + a = int(v1[i]) + b = int(v2[i]) + if a != b: + return (a-b)//abs(a-b) + return 0 From c2308836f799169af14ceb351579def6bb43e03f Mon Sep 17 00:00:00 2001 From: kevin454475 <71903670+kevin454475@users.noreply.github.com> Date: Thu, 8 Oct 2020 15:16:51 -0400 Subject: [PATCH 150/357] Added 0046_Permutations https://leetcode.com/problems/permutations/ --- LeetCode/0046_Permutations.py | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/LeetCode/0046_Permutations.py b/LeetCode/0046_Permutations.py index 4456739..39205ed 100644 --- a/LeetCode/0046_Permutations.py +++ b/LeetCode/0046_Permutations.py @@ -1,12 +1,3 @@ -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)) +class Solution: + def permute(self, nums: List[int]) -> List[List[int]]: + return [list(x) for x in permutations(nums)] From 63af736a380cc022c03893aba75c0d0d3ed053a0 Mon Sep 17 00:00:00 2001 From: matheusphalves Date: Thu, 8 Oct 2020 16:53:09 -0300 Subject: [PATCH 151/357] 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 152/357] 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 153/357] 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 154/357] 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 155/357] 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 156/357] 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 157/357] 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 158/357] 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 159/357] 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 160/357] 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 161/357] 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 162/357] 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 163/357] 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 164/357] 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 165/357] 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 166/357] 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 167/357] 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 168/357] 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 169/357] 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 170/357] 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 171/357] 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 172/357] 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 173/357] 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 174/357] 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 175/357] 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 176/357] 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 177/357] 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 178/357] 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 cf23ab8b46f9840997d43037cff3dbf8eada0599 Mon Sep 17 00:00:00 2001 From: Alexey Ilyukhov Date: Sat, 10 Oct 2020 04:26:06 +0300 Subject: [PATCH 179/357] Add 1340. Jump Game V --- LeetCode/1340_Jump_Game_V.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 LeetCode/1340_Jump_Game_V.py diff --git a/LeetCode/1340_Jump_Game_V.py b/LeetCode/1340_Jump_Game_V.py new file mode 100644 index 0000000..1094f4d --- /dev/null +++ b/LeetCode/1340_Jump_Game_V.py @@ -0,0 +1,28 @@ +class Solution(object): + def maxJumps(self, arr, d): + """ + :type arr: List[int] + :type d: int + :rtype: int + """ + + dp = [1] * len(arr) + + for i, _ in sorted(enumerate(arr), key=lambda x: x[1]): + max_h = None + for j in range(i - 1, max(i - d - 1, -1), -1): + max_h = max(max_h, arr[j]) + if max_h < arr[i]: + dp[i] = max(dp[i], dp[j] + 1) + else: + break + + max_h = None + for j in range(i + 1, min(i + d + 1, len(arr))): + max_h = max(max_h, arr[j]) + if max_h < arr[i]: + dp[i] = max(dp[i], dp[j] + 1) + else: + break + + return max(dp) 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 180/357] 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 181/357] 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 182/357] 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 183/357] 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 184/357] 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 574174912d9fa9e9337106f26e46c7e6086e6d1b Mon Sep 17 00:00:00 2001 From: Bhawesh Bhansali Date: Sat, 10 Oct 2020 10:19:07 +0530 Subject: [PATCH 185/357] Create 1589-maximum-sum-obtained-of-any-permutation.py --- ...maximum-sum-obtained-of-any-permutation.py | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 LeetCode/1589-maximum-sum-obtained-of-any-permutation.py diff --git a/LeetCode/1589-maximum-sum-obtained-of-any-permutation.py b/LeetCode/1589-maximum-sum-obtained-of-any-permutation.py new file mode 100644 index 0000000..9735428 --- /dev/null +++ b/LeetCode/1589-maximum-sum-obtained-of-any-permutation.py @@ -0,0 +1,46 @@ +import itertools + + +class Solution(object): + def maxSumRangeQuery(self, nums, requests): + """ + :type nums: List[int] + :type requests: List[List[int]] + :rtype: int + """ + def addmod(a, b, mod): # avoid overflow in other languages + a %= mod + b %= mod + if mod-a <= b: + b -= mod + return a+b + + def mulmod(a, b, mod): # avoid overflow in other languages + a %= mod + b %= mod + if a < b: + a, b = b, a + result = 0 + while b > 0: + if b%2 == 1: + result = addmod(result, a, mod) + a = addmod(a, a, mod) + b //= 2 + return result + + MOD = 10**9+7 + + count = [0]*len(nums) + for start, end in requests: + count[start] += 1 + if end+1 < len(count): + count[end+1] -= 1 + for i in xrange(1, len(count)): + count[i] += count[i-1] + nums.sort() + count.sort() + result = 0 + for i, (num, c) in enumerate(itertools.izip(nums, count)): + # result = addmod(result, mulmod(num, c, MOD), MOD) + result = (result+num*c)%MOD + return result From 72d674e0cfb5709201bc7ae45cb0ae23f6057b61 Mon Sep 17 00:00:00 2001 From: Sagnik Mazumder Date: Sat, 10 Oct 2020 11:36:10 +0530 Subject: [PATCH 186/357] added solution to leetcode problem 1346 --- LeetCode/1346_Check_if_N_and_its_Double_Exist.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/1346_Check_if_N_and_its_Double_Exist.py diff --git a/LeetCode/1346_Check_if_N_and_its_Double_Exist.py b/LeetCode/1346_Check_if_N_and_its_Double_Exist.py new file mode 100644 index 0000000..8c01a86 --- /dev/null +++ b/LeetCode/1346_Check_if_N_and_its_Double_Exist.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 5df89273710bddd67e9792249eebf8cd913023e5 Mon Sep 17 00:00:00 2001 From: Sagnik Mazumder Date: Sat, 10 Oct 2020 11:53:49 +0530 Subject: [PATCH 187/357] 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 188/357] 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 189/357] 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 190/357] 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 191/357] 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 192/357] 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 193/357] 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 194/357] 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 195/357] 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 196/357] 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 197/357] 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 198/357] 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 199/357] 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 200/357] 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 201/357] 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 67881f02c54d1351ff9da66c82df32762186fde3 Mon Sep 17 00:00:00 2001 From: aman1833 <33142696+aman1833@users.noreply.github.com> Date: Sat, 10 Oct 2020 19:38:54 +0530 Subject: [PATCH 202/357] Create fast_fibonacci.py --- fast_fibonacci.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 fast_fibonacci.py diff --git a/fast_fibonacci.py b/fast_fibonacci.py new file mode 100644 index 0000000..e7bdfac --- /dev/null +++ b/fast_fibonacci.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import sys + + +def fibonacci(n: int) -> int: + """ + return F(n) + >>> [fibonacci(i) for i in range(13)] + [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] + """ + if n < 0: + raise ValueError("Negative arguments are not supported") + return _fib(n)[0] + + +# returns (F(n), F(n-1)) +def _fib(n: int) -> tuple[int, int]: + if n == 0: # (F(0), F(1)) + return (0, 1) + + # F(2n) = F(n)[2F(n+1) − F(n)] + # F(2n+1) = F(n+1)^2+F(n)^2 + a, b = _fib(n // 2) + c = a * (b * 2 - a) + d = a * a + b * b + return (d, c + d) if n % 2 else (c, d) + + +if __name__ == "__main__": + n = int(sys.argv[1]) + print(f"fibonacci({n}) is {fibonacci(n)}") From ba8da0f7ac84da1f299be268355e1f5eb56b0e00 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sat, 10 Oct 2020 16:25:44 +0200 Subject: [PATCH 203/357] 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 204/357] 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 205/357] 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 206/357] 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 From de9c63c0d93c4b5b34cde57e6dd9e246062d7053 Mon Sep 17 00:00:00 2001 From: sree_gaya3 Date: Sat, 10 Oct 2020 20:46:35 +0530 Subject: [PATCH 207/357] Added the Solution Code for problem 1599 issue --- ..._Profit_of_Operating_a_Centennial_Wheel.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py diff --git a/LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py b/LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py new file mode 100644 index 0000000..64ed034 --- /dev/null +++ b/LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py @@ -0,0 +1,38 @@ +class Solution(object): + def minOperationsMaxProfit(self, customers, boardingCost, runningCost) : + """ + :type customers: List[int] + :type boardingCose: int + :type runningCose: int + :rtype: int + """ + wait = 0 + pro = 0 high = 0 + res = -1 + for i in range(len(customers)): + vacc = 4 - wait + if vacc <= 0: + wait += customers[i] - 4 + pro += 4 * boardingCost - runningCost + # board all + elif customers[i] <= vacc: # board=customers[i]+wait + pro += boardingCost * (customers[i] + wait) - runningCost + wait = 0 + else: + pro += boardingCost * 4 - runningCost + wait += customers[i] - 4 + if pro > high: + high = pro + res = i + # determine after all arrives + pro_per = boardingCost * 4 - runningCost + if pro_per > 0: + last = wait % 4 + if wait >= 4: + if boardingCost * last - runningCost > 0: + return len(customers) + wait // 4 + 1 + else: + return len(customers) + wait // 4 + if boardingCost * last - runningCost > 0: + return len(customers) + 1 + return res + 1 if res >= 0 else -1 From d57b3c6398113c9b3451222db0cd88067defe67d Mon Sep 17 00:00:00 2001 From: sree_gaya3 Date: Sat, 10 Oct 2020 20:56:19 +0530 Subject: [PATCH 208/357] Added the Solution Code for problem 1599 issue #568 --- .../1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py b/LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py index 64ed034..29c19dc 100644 --- a/LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py +++ b/LeetCode/1599_Maximum_Profit_of_Operating_a_Centennial_Wheel.py @@ -7,7 +7,8 @@ def minOperationsMaxProfit(self, customers, boardingCost, runningCost) : :rtype: int """ wait = 0 - pro = 0 high = 0 + pro = 0 + high = 0 res = -1 for i in range(len(customers)): vacc = 4 - wait From 7c8885fb2f1c6fa0b85187d8eb03bdf30ca2865f Mon Sep 17 00:00:00 2001 From: Shreeji <55141517+Shreejichandra@users.noreply.github.com> Date: Sat, 10 Oct 2020 21:23:40 +0530 Subject: [PATCH 209/357] Create 0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py --- ...nimum_Number_of_Arrows_to_Burst_Balloons.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LeetCode/0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py diff --git a/LeetCode/0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py b/LeetCode/0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py new file mode 100644 index 0000000..bd55865 --- /dev/null +++ b/LeetCode/0452_Minimum_Number_of_Arrows_to_Burst_Balloons.py @@ -0,0 +1,18 @@ +class Solution: + def findMinArrowShots(self, points: List[List[int]]) -> int: + if points == []: + return 0 + points.sort(key = lambda x: x[0]) + start = points[0][0] + end = points[0][1] + ans = len(points) + for i in range(1, len(points)): + if start <= points[i][0] <= end: + ans -= 1 + if points[i][1] < end: + end = points[i][1] + else: + start = points[i][0] + end = points[i][1] + + return ans From 166b1a308ba8746bbebca549d926b51844d45705 Mon Sep 17 00:00:00 2001 From: Davi Fontenele Date: Sat, 10 Oct 2020 12:57:58 -0300 Subject: [PATCH 210/357] Create 0006_ZigZag_Conversion.py Solution for ZigZag Conversion in python --- LeetCode/0006_ZigZag_Conversion.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LeetCode/0006_ZigZag_Conversion.py diff --git a/LeetCode/0006_ZigZag_Conversion.py b/LeetCode/0006_ZigZag_Conversion.py new file mode 100644 index 0000000..ab9f2c0 --- /dev/null +++ b/LeetCode/0006_ZigZag_Conversion.py @@ -0,0 +1,21 @@ +class Solution: + # @param {string} s + # @param {integer} numRows + # @return {string} + def convert(self, s, numRows): + + if numRows == 1: + return s + + rows = ["" for i in range(numRows)] + + direction = -1 + row = 0 + for i in range(len(s)): + + rows[row]+=s[i] + if (row == 0 or row==numRows-1): + direction *= -1 + row+=direction + + return "".join(rows) From fe872c09ec950e1cd951bc836099a074c6e1c945 Mon Sep 17 00:00:00 2001 From: sree_gaya3 Date: Sat, 10 Oct 2020 21:34:16 +0530 Subject: [PATCH 211/357] Solution to Problem 1608 issue #571 --- ...rray_With_X_Elements_Greater_Than_or_Equal_x.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py diff --git a/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py b/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py new file mode 100644 index 0000000..630f5cd --- /dev/null +++ b/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py @@ -0,0 +1,14 @@ +class Solution(object): + def specialArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums.sort() + out = -1 + for i in range(len(nums)): + if nums[~i]>=i+1: + if i==len(nums)-1 or nums[~(i+1)] Date: Sat, 10 Oct 2020 21:41:38 +0530 Subject: [PATCH 212/357] Added Solution to the Problem 1608 issue #571 --- ...rray_With_X_Elements_Greater_Than_or_Equal_x.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 LeetCode/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py diff --git a/LeetCode/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py b/LeetCode/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py new file mode 100644 index 0000000..630f5cd --- /dev/null +++ b/LeetCode/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py @@ -0,0 +1,14 @@ +class Solution(object): + def specialArray(self, nums): + """ + :type nums: List[int] + :rtype: int + """ + nums.sort() + out = -1 + for i in range(len(nums)): + if nums[~i]>=i+1: + if i==len(nums)-1 or nums[~(i+1)] Date: Sat, 10 Oct 2020 21:44:03 +0530 Subject: [PATCH 213/357] Removed one wrong file with a typo --- ...rray_With_X_Elements_Greater_Than_or_Equal_x.py | 14 -------------- 1 file changed, 14 deletions(-) delete mode 100644 1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py diff --git a/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py b/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py deleted file mode 100644 index 630f5cd..0000000 --- a/1608_Special_Array_With_X_Elements_Greater_Than_or_Equal_x.py +++ /dev/null @@ -1,14 +0,0 @@ -class Solution(object): - def specialArray(self, nums): - """ - :type nums: List[int] - :rtype: int - """ - nums.sort() - out = -1 - for i in range(len(nums)): - if nums[~i]>=i+1: - if i==len(nums)-1 or nums[~(i+1)] Date: Sat, 10 Oct 2020 12:16:47 -0400 Subject: [PATCH 214/357] added solution to 1588 --- 1588_SumOfAllOddLengthSubarrays.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 1588_SumOfAllOddLengthSubarrays.py diff --git a/1588_SumOfAllOddLengthSubarrays.py b/1588_SumOfAllOddLengthSubarrays.py new file mode 100644 index 0000000..f689d7a --- /dev/null +++ b/1588_SumOfAllOddLengthSubarrays.py @@ -0,0 +1,15 @@ +class Solution(object): + def sumOddLengthSubarrays(self, arr): + + _sum = 0 + length = len(arr) + sub_len = 1 + start = 0 + + while sub_len <= length: + for start in range(length - sub_len + 1): + for i in range(start, start + sub_len): + _sum = _sum + arr[i] + sub_len = sub_len + 2 + + return _sum \ No newline at end of file From b2220fe333e571a26f5cd3fa17ebe3577f54320e Mon Sep 17 00:00:00 2001 From: tejasvicsr1 Date: Sat, 10 Oct 2020 21:49:38 +0530 Subject: [PATCH 215/357] Solution to the problem 1365 #603 --- ...Many_Numbers_Are_Smaller_Than_the_Current_Number.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py diff --git a/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py b/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py new file mode 100644 index 0000000..bb892a0 --- /dev/null +++ b/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py @@ -0,0 +1,10 @@ +class Solution: + def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: + ans = [] + for i in range(0, len(nums)): + soln = 0 + for j in range(0, len(nums)): + if(nums[j] < nums[i] and j != i): + soln += 1 + ans. append(soln) + return ans \ No newline at end of file From 922809f67b717f6af59f6376d782d84ac23a5502 Mon Sep 17 00:00:00 2001 From: matheusphalves Date: Sat, 10 Oct 2020 13:20:41 -0300 Subject: [PATCH 216/357] Added 0342_Power_Of_Four.py --- LeetCode/0342_Power_Of_Four.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 LeetCode/0342_Power_Of_Four.py diff --git a/LeetCode/0342_Power_Of_Four.py b/LeetCode/0342_Power_Of_Four.py new file mode 100644 index 0000000..a3711ec --- /dev/null +++ b/LeetCode/0342_Power_Of_Four.py @@ -0,0 +1,9 @@ +import math +class Solution: + #Solution without loops/recursion + def isPowerOfFour(self, num: int) -> bool: + if(num!=0): #number 0 there isn't in the logarithmic function domain! + exponent = math.log(abs(num), 4) #I will discover the number which multiply 4 nth times. The result must be equal to num. Ex: 4^2 = 16 + #However, the exponent must to be an integer value for num to be a power of 4. For example, there are no 4's half number power! + return int(math.pow(4, int(exponent)))==num + return False #number zero was the input \ No newline at end of file From 787c4f299247e15f4f9491fcf37c64615c232540 Mon Sep 17 00:00:00 2001 From: frank731 <38197177+frank731@users.noreply.github.com> Date: Sat, 10 Oct 2020 09:23:34 -0700 Subject: [PATCH 217/357] Create 0437_Path_Sum_III.py --- 0437_Path_Sum_III.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 0437_Path_Sum_III.py diff --git a/0437_Path_Sum_III.py b/0437_Path_Sum_III.py new file mode 100644 index 0000000..f85e902 --- /dev/null +++ b/0437_Path_Sum_III.py @@ -0,0 +1,31 @@ +# 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: + count = 0 + past_sums = {} + + def pathSum(self, root: TreeNode, sum: int) -> int: + if root is not None: + self.recurse(root, 0, sum) + return self.count + + def recurse(self, node, summed, target): + if node is None: + return False + else: + summed += node.val + if summed == target: + self.count += 1 + if summed - target in self.past_sums: + self.count += self.past_sums[summed - target] + if summed in self.past_sums: + self.past_sums[summed] += 1 + else: + self.past_sums[summed] = 1 + self.recurse(node.left, summed, target) + self.recurse(node.right, summed, target) + self.past_sums[summed] -= 1 From c9f5b9276de10f49324707116dcce0527536e325 Mon Sep 17 00:00:00 2001 From: frank731 <38197177+frank731@users.noreply.github.com> Date: Sat, 10 Oct 2020 09:25:11 -0700 Subject: [PATCH 218/357] Rename 0437_Path_Sum_III.py to LeetCode/0437_Path_Sum_III.py --- 0437_Path_Sum_III.py => LeetCode/0437_Path_Sum_III.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename 0437_Path_Sum_III.py => LeetCode/0437_Path_Sum_III.py (100%) diff --git a/0437_Path_Sum_III.py b/LeetCode/0437_Path_Sum_III.py similarity index 100% rename from 0437_Path_Sum_III.py rename to LeetCode/0437_Path_Sum_III.py From eb446c6e24a2f87ad3ba20f45383267b5ecf4a85 Mon Sep 17 00:00:00 2001 From: Sagnik Mazumder Date: Sat, 10 Oct 2020 21:59:33 +0530 Subject: [PATCH 219/357] updated solution --- .../1346_Check_if_N_and_its_Double_Exist.py | 21 +++++++------------ 1 file changed, 8 insertions(+), 13 deletions(-) diff --git a/LeetCode/1346_Check_if_N_and_its_Double_Exist.py b/LeetCode/1346_Check_if_N_and_its_Double_Exist.py index 8c01a86..1abe45b 100644 --- a/LeetCode/1346_Check_if_N_and_its_Double_Exist.py +++ b/LeetCode/1346_Check_if_N_and_its_Double_Exist.py @@ -1,14 +1,9 @@ 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 + def checkIfExist(self, arr: List[int]) -> bool: + + seen = set() + for x in arr: + if x * 2 in seen or (not x % 2 and x // 2 in seen): + return True + seen.add(x) + return False From 74130ae869066ab3320437bcb15b11fe71ee6984 Mon Sep 17 00:00:00 2001 From: sree_gaya3 Date: Sat, 10 Oct 2020 22:07:09 +0530 Subject: [PATCH 220/357] Added Solution to the problem 1604 issue #574 --- ...hree_or_More_Times_in_a_One_Hour_Period.py | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 LeetCode/1604_Alert_Using_Same_Key_Card_Three_or_More_Times_in_a_One_Hour_Period.py diff --git a/LeetCode/1604_Alert_Using_Same_Key_Card_Three_or_More_Times_in_a_One_Hour_Period.py b/LeetCode/1604_Alert_Using_Same_Key_Card_Three_or_More_Times_in_a_One_Hour_Period.py new file mode 100644 index 0000000..afd7763 --- /dev/null +++ b/LeetCode/1604_Alert_Using_Same_Key_Card_Three_or_More_Times_in_a_One_Hour_Period.py @@ -0,0 +1,35 @@ +class Solution(object): + def alertNames(self, keyName, keyTime): + """ + :type keyName: List[str] + :type keyTime: List[str] + :rtype: List[str] + """ + mapp = {} + for i in range(len(keyName)): + name = keyName[i] + if(name not in mapp): + mapp[name] = [keyTime[i]] + else: + mapp[name].append(keyTime[i]) + res = [] + for name, arr in mapp.items(): + arr.sort() + for i in range(len(arr)-2): + time= arr[i] + t2 = arr[i+1] + t3 = arr[i+2] + if(time[0:2]=="23"): + endTime = "24:00" + if(t2<=endTime and t3<=endTime and t2>time and t3>time): + res.append(name) + break + else: + start = int(time[0:2]) + endTime = str(start+1)+time[2:] + if(start<9): + endTime = "0"+endTime + if(t2<=endTime and t3<=endTime): + res.append(name) + break + return sorted(res) From ba62c931d74ce10f3732e9dfd1a076147467b9f8 Mon Sep 17 00:00:00 2001 From: zeborg Date: Sat, 10 Oct 2020 22:18:02 +0530 Subject: [PATCH 221/357] Added solution to Problem 867 - Transpose Matrix --- LeetCode/0867_Transpose_Matrix.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 LeetCode/0867_Transpose_Matrix.py diff --git a/LeetCode/0867_Transpose_Matrix.py b/LeetCode/0867_Transpose_Matrix.py new file mode 100644 index 0000000..97fed72 --- /dev/null +++ b/LeetCode/0867_Transpose_Matrix.py @@ -0,0 +1,27 @@ +""" +Problem: Given a matrix A, return the transpose of A. The transpose of a matrix is the matrix flipped over it's main diagonal, switching the row and column indices of the matrix. + +Sample input: + [[1,2,3], + [4,5,6], + [7,8,9]] + +Sample output: + [[1,4,7], + [2,5,8], + [3,6,9]] +""" + +class Solution: + def transpose(self, A: List[List[int]]) -> List[List[int]]: + transpose=[] + k=0 + for p in range(len(A[0])): + temp=[] + for i in A: + while k Date: Sat, 10 Oct 2020 22:19:39 +0530 Subject: [PATCH 222/357] Added Solution to Problem 1606 issue #578 --- ...rs_That_Handled_Most_Number_of_Requests.py | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 LeetCode/1606_Find_Servers_That_Handled_Most_Number_of_Requests.py diff --git a/LeetCode/1606_Find_Servers_That_Handled_Most_Number_of_Requests.py b/LeetCode/1606_Find_Servers_That_Handled_Most_Number_of_Requests.py new file mode 100644 index 0000000..73d5a08 --- /dev/null +++ b/LeetCode/1606_Find_Servers_That_Handled_Most_Number_of_Requests.py @@ -0,0 +1,36 @@ +class Solution(object): + def busiestServers(self, k, arrival, load): + """ + :type k: int + :type arrival: List[int] + :type load: List[int] + :rtype: List[int] + """ + from sortedcontainers import SortedList + avail = SortedList() + for i in range(k): + avail.add(i) + h = [] + count = [0]*k + for i in range(len(arrival)): + s = arrival[i] + e = arrival[i]+load[i] + while h and h[0][0]<=s: + _, j = heappop(h) + avail.add(j) + if len(h)==k: + continue + si = avail.bisect_left(i%k) + if si==len(avail): + ser = avail[0] + else: + ser = avail[si] + avail.remove(ser) + count[ser]+=1 + heappush(h, (e, ser)) + maxReq = max(count) + ans = [] + for i in range(len(count)): + if count[i]==maxReq: + ans.append(i) + return ans From e1c45eb57b7ba4e6119ba8a8067e0333342079cd Mon Sep 17 00:00:00 2001 From: kevin454475 <71903670+kevin454475@users.noreply.github.com> Date: Sat, 10 Oct 2020 13:31:03 -0400 Subject: [PATCH 223/357] Add 0155_Min_stack.py --- LeetCode/0155_Min_stack.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 LeetCode/0155_Min_stack.py diff --git a/LeetCode/0155_Min_stack.py b/LeetCode/0155_Min_stack.py new file mode 100644 index 0000000..cdc92b4 --- /dev/null +++ b/LeetCode/0155_Min_stack.py @@ -0,0 +1,33 @@ +class MinStack: + + def __init__(self): + """ + initialize your data structure here. + """ + self.stack = [] + + + def push(self, x: int) -> None: + self.stack.append(x) + + + def pop(self) -> None: + self.stack.pop() # = self.stack[:-1] #pop() + + + def top(self) -> int: + return self.stack[-1] + + + + def getMin(self) -> int: + return min(self.stack) + + + +# Your MinStack object will be instantiated and called as such: +# obj = MinStack() +# obj.push(x) +# obj.pop() +# param_3 = obj.top() +# param_4 = obj.getMin() From 07624642411a3f4f87c972e1b3c7dd4571c48385 Mon Sep 17 00:00:00 2001 From: kevin454475 <71903670+kevin454475@users.noreply.github.com> Date: Sat, 10 Oct 2020 13:39:23 -0400 Subject: [PATCH 224/357] Delete 0028_strStr.py --- LeetCode/0028_strStr.py | 7 ------- 1 file changed, 7 deletions(-) delete mode 100644 LeetCode/0028_strStr.py diff --git a/LeetCode/0028_strStr.py b/LeetCode/0028_strStr.py deleted file mode 100644 index b4ab756..0000000 --- a/LeetCode/0028_strStr.py +++ /dev/null @@ -1,7 +0,0 @@ -class Solution: - def strStr(self, haystack: str, needle: str) -> int: - try: - res = haystack.index(needle) - return res - except: - return -1 if needle else 0 From d3f41a58430cd4fc65d71cb30e6fc8297e5670fd Mon Sep 17 00:00:00 2001 From: kevin454475 <71903670+kevin454475@users.noreply.github.com> Date: Sat, 10 Oct 2020 13:42:03 -0400 Subject: [PATCH 225/357] Delete 0046_Permutations.py --- LeetCode/0046_Permutations.py | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 LeetCode/0046_Permutations.py diff --git a/LeetCode/0046_Permutations.py b/LeetCode/0046_Permutations.py deleted file mode 100644 index 39205ed..0000000 --- a/LeetCode/0046_Permutations.py +++ /dev/null @@ -1,3 +0,0 @@ -class Solution: - def permute(self, nums: List[int]) -> List[List[int]]: - return [list(x) for x in permutations(nums)] From 352cc3b6cad8a9cb5a4346bac3457aa12f7e4222 Mon Sep 17 00:00:00 2001 From: kevin454475 <71903670+kevin454475@users.noreply.github.com> Date: Sat, 10 Oct 2020 13:44:47 -0400 Subject: [PATCH 226/357] Add files via upload --- LeetCode/0046_Permutations.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0046_Permutations.py diff --git a/LeetCode/0046_Permutations.py b/LeetCode/0046_Permutations.py new file mode 100644 index 0000000..d0ba022 --- /dev/null +++ b/LeetCode/0046_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 228afcdd56f15d39c2592295764fba8b247edd02 Mon Sep 17 00:00:00 2001 From: Richard Wi <18545483+riwim@users.noreply.github.com> Date: Sat, 10 Oct 2020 19:45:12 +0200 Subject: [PATCH 227/357] Solve Leet Code 1252 Cells with Odd Values in a Matrix --- LeetCode/1252_Cells_with_Odd_Values_in_a_Matrix.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/1252_Cells_with_Odd_Values_in_a_Matrix.py diff --git a/LeetCode/1252_Cells_with_Odd_Values_in_a_Matrix.py b/LeetCode/1252_Cells_with_Odd_Values_in_a_Matrix.py new file mode 100644 index 0000000..c6dba68 --- /dev/null +++ b/LeetCode/1252_Cells_with_Odd_Values_in_a_Matrix.py @@ -0,0 +1,13 @@ +import numpy as np + +class Solution: + + def get_summation_matrix(self, n: int, m: int, ri: int, ci: int): + mat = np.zeros([n, m], dtype=int) + mat[ri,:] += 1 + mat[:,ci] += 1 + return mat + + def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int: + matrix_inc = sum(self.get_summation_matrix(n, m, ri, ci) for ri, ci in indices) + return np.count_nonzero(matrix_inc % 2 == 1) From c2ac17dded39e0075370e36b7ae3f9cc06bfab0a Mon Sep 17 00:00:00 2001 From: kunatastic Date: Sat, 10 Oct 2020 23:36:49 +0530 Subject: [PATCH 228/357] 0326 Power of three added --- LeetCode/0326_Power_Of_Three.py | 42 +++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 LeetCode/0326_Power_Of_Three.py diff --git a/LeetCode/0326_Power_Of_Three.py b/LeetCode/0326_Power_Of_Three.py new file mode 100644 index 0000000..d39687d --- /dev/null +++ b/LeetCode/0326_Power_Of_Three.py @@ -0,0 +1,42 @@ +""" +Given an integer, write a function to determine if it is a power of three. + +Example 1: + +Input: 27 +Output: true +Example 2: + +Input: 0 +Output: false +Example 3: + +Input: 9 +Output: true +Example 4: + +Input: 45 +Output: false +Follow up: +Could you do it without using any loop / recursion? +""" +class Solution(object): + def isPowerOfThree(self, n): + if n<1: + return False + elif n == 1: + return True + elif n == 2: + return False + else: + while n > 2: + a, b = divmod(n, 3) + if b == 0: + n = a + else: + break + if n==1: + return True + else: + return False + From b7b61fe978a11b2fac3c075514ed9a84704b1cac Mon Sep 17 00:00:00 2001 From: kevin454475 <71903670+kevin454475@users.noreply.github.com> Date: Sat, 10 Oct 2020 14:25:08 -0400 Subject: [PATCH 229/357] Delete 0046_Permutations.py --- LeetCode/0046_Permutations.py | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 LeetCode/0046_Permutations.py diff --git a/LeetCode/0046_Permutations.py b/LeetCode/0046_Permutations.py deleted file mode 100644 index d0ba022..0000000 --- a/LeetCode/0046_Permutations.py +++ /dev/null @@ -1,12 +0,0 @@ -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 d3c7a7b10e9aa33006c8bd3f79434e266687a59c Mon Sep 17 00:00:00 2001 From: Andrew <54547089+ac-tam@users.noreply.github.com> Date: Sat, 10 Oct 2020 14:26:02 -0400 Subject: [PATCH 230/357] Create 0551_ Student_Attendance_Record_I.py --- LeetCode/0551_ Student_Attendance_Record_I.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0551_ Student_Attendance_Record_I.py diff --git a/LeetCode/0551_ Student_Attendance_Record_I.py b/LeetCode/0551_ Student_Attendance_Record_I.py new file mode 100644 index 0000000..f11f0eb --- /dev/null +++ b/LeetCode/0551_ Student_Attendance_Record_I.py @@ -0,0 +1,20 @@ +class Solution: + def checkRecord(self, s: str) -> bool: + aCount = 0; + lCount = 0; + for ch in s: + if ch == "L": + lCount += 1 + else: + lCount = 0 + + if ch == "A": + aCount += 1 + + if lCount > 2: + return False + if aCount > 1: + return False + + return True + From d24c979c57c8ea6b48b16c43ec345373181e089d Mon Sep 17 00:00:00 2001 From: kevin454475 <71903670+kevin454475@users.noreply.github.com> Date: Sat, 10 Oct 2020 14:28:46 -0400 Subject: [PATCH 231/357] Add files via upload was having difficulty figuring out how to rebase my fork as i had tried uploading 46 a couple days ago --- LeetCode/0046_Permutations.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0046_Permutations.py diff --git a/LeetCode/0046_Permutations.py b/LeetCode/0046_Permutations.py new file mode 100644 index 0000000..d0ba022 --- /dev/null +++ b/LeetCode/0046_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 481da4bc35b7dd7aac57ae2ecf1cb2e1d025af3e Mon Sep 17 00:00:00 2001 From: Jeff Mikels Date: Sat, 10 Oct 2020 14:50:25 -0400 Subject: [PATCH 232/357] added 0006_ZigZag_Conversion --- LeetCode/0006_ZigZag_Conversion.py | 176 +++++++++++++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 LeetCode/0006_ZigZag_Conversion.py diff --git a/LeetCode/0006_ZigZag_Conversion.py b/LeetCode/0006_ZigZag_Conversion.py new file mode 100644 index 0000000..2d7de9c --- /dev/null +++ b/LeetCode/0006_ZigZag_Conversion.py @@ -0,0 +1,176 @@ +''' +## Description of the Problem + +The string "PAYPALISHIRING" is written in a zigzag pattern +on a given number of rows like this: + +(you may want to display this pattern in a fixed font for better legibility) + +``` +P A H N +A P L S I I G +Y I R +``` + +And then read line by line: "PAHNAPLSIIGYIR" + +Write the code that will take a string and make this conversion given a number of rows: + +``` +string convert(string s, int numRows); +``` + +## Example 1: +``` +Input: s = "PAYPALISHIRING", numRows = 3 +Output: "PAHNAPLSIIGYIR" +``` + +## Example 2: +``` +Input: s = "PAYPALISHIRING", numRows = 4 +Output: "PINALSIGYAHRPI" +``` + +## Explanation: + +``` +P I N +A L S I G +Y A H R +P I +``` + +## Example 3: + +``` +Input: s = "A", numRows = 1 +Output: "A" +``` + +## Constraints: + +- 1 <= s.length <= 1000 +- s consists of English letters (lower-case and upper-case), ',' and '.'. +- 1 <= numRows <= 1000 + + +## Link To The LeetCode Problem +[6. ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) +''' + + +class Solution: + s = '' + numRows = 1 + + # transitionColumns is the number of extra columns needed to get the + # text from the bottom row back to the top row + def zigZagTransitionColumns(self) -> int: + transitionColumns = self.numRows - 2 + if transitionColumns < 0: + transitionColumns = 0 + return transitionColumns + + # patternColumns is the number of columns taken up by each full pattern + # the first column is downward, and then we need columns for the upward + def zigZagPatternColumns(self) -> int: + return 1 + self.zigZagTransitionColumns() + + # patternSize is the number of elements in each repeated pattern + def zigZagPatternLength(self) -> int: + # there are numRows letters in the first column + # followed by one letter per transitionColumn + return self.numRows + self.zigZagTransitionColumns() + + # computes the number of total columns needed by this string + def zigZagMatrixColumns(self) -> int: + patternLength = self.zigZagPatternLength() + fullPatternCount = len(self.s) // patternLength + columns = self.zigZagPatternColumns() * fullPatternCount + + # how many extra letters are there? + extraLetters = len(self.s) - (patternLength * fullPatternCount) + if extraLetters > 0: + columns += 1 + if extraLetters > self.numRows: + columns += extraLetters - self.numRows + return columns + + # converts the index of the input string to the address + # in the output matrix + def zigZagMatrixIndex(self, elementIndex: int) -> tuple: + patternLength = self.zigZagPatternLength() + + # which pattern repetition holds this element (zero-based) + patternOfElement = elementIndex // patternLength + + # where in the pattern repetition is this element + indexInPattern = elementIndex % patternLength + + matrixRow = indexInPattern + matrixColumn = patternOfElement * self.zigZagPatternColumns() + bottomRowIndex = self.numRows - 1 + + # correct the row and column numbers (remember these are zero-based) + if indexInPattern > bottomRowIndex: + extraColumns = indexInPattern - bottomRowIndex + matrixColumn = matrixColumn + extraColumns + + # row decrements by 1 for each extra column + matrixRow = bottomRowIndex - extraColumns + + # i, j + return (matrixColumn, matrixRow) + + # creates a zigzag matrix + def generateZigZagMatrix(self) -> list: + matrix = [] + for i in range(self.zigZagMatrixColumns()): + matrix.append([]) + for j in range(self.numRows): + matrix[i].append('') + for elementIndex, char in enumerate(self.s): + i, j = self.zigZagMatrixIndex(elementIndex) + matrix[i][j] = char + return matrix + + # prints out the zigzag matrix + def generateZigZagString(self, nullChar: str = ' ', lineEndings: str = '\n'): + lines = [] + matrix = self.generateZigZagMatrix() + for j in range(self.numRows): + rowChars = [] + for i in range(self.zigZagMatrixColumns()): + char = matrix[i][j] + rowChars.append(char if char != '' else nullChar) + lines.append(''.join(rowChars)) + return lineEndings.join(lines) + + def zigZagConversion(self, s: str, numRows: int, asMatrix: bool = False) -> str: + ''' + The ZigZag format fills all available rows vertically in the first column, + then, fills rows "diagonally" on the way back up to the top row of a subsequent + column, and then repeats. + + The input string is the normal content. + ''' + self.s = s + self.numRows = numRows + if asMatrix: + return self.generateZigZagString(nullChar=' ', lineEndings='\n') + else: + return self.generateZigZagString(nullChar='', lineEndings='') + + +# testing +if __name__ == '__main__': + toConvert = 'PAYPALISHIRING' + converter = Solution() + for i in range(4): + print(f'\nENCODING: {toConvert} with {i+1} rows') + print('\n-- matrix -----------------') + print(converter.zigZagConversion(toConvert, numRows=i+1, asMatrix=True)) + print('\n-- line -------------------') + print(converter.zigZagConversion(toConvert, numRows=i+1, asMatrix=False)) + print() From a13f0859a57a766ccb018cc5278a8183fc54427e Mon Sep 17 00:00:00 2001 From: frank731 <38197177+frank731@users.noreply.github.com> Date: Sat, 10 Oct 2020 12:17:10 -0700 Subject: [PATCH 233/357] Create 0445_Add_Two_Numbers_II.py --- LeetCode/0445_Add_Two_Numbers_II.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 LeetCode/0445_Add_Two_Numbers_II.py diff --git a/LeetCode/0445_Add_Two_Numbers_II.py b/LeetCode/0445_Add_Two_Numbers_II.py new file mode 100644 index 0000000..b0c6aea --- /dev/null +++ b/LeetCode/0445_Add_Two_Numbers_II.py @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def linkedListToInt(self, list_node, integer): + integer += str(list_node.val) + if list_node.next == None: + return int(integer) + else: + return self.linkedListToInt(list_node.next, integer) + + def intToLinkedList(self, integer): + integer = str(integer) + print(integer) + ll = [ListNode(int(integer[0]))] + for i in range(1, len(integer)): + ll.append(ListNode(int(integer[i]))) + ll[i - 1].next = ll[i] + return ll[0] + + def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: + first = self.linkedListToInt(l1, "") + second = self.linkedListToInt(l2, "") + summed = first + second + return self.intToLinkedList(summed) From 7b0bb1480f85a82158d5c2b6ced14741a3311a98 Mon Sep 17 00:00:00 2001 From: frank731 <38197177+frank731@users.noreply.github.com> Date: Sat, 10 Oct 2020 12:20:32 -0700 Subject: [PATCH 234/357] Delete 0445_Add_Two_Numbers_II.py --- LeetCode/0445_Add_Two_Numbers_II.py | 27 --------------------------- 1 file changed, 27 deletions(-) delete mode 100644 LeetCode/0445_Add_Two_Numbers_II.py diff --git a/LeetCode/0445_Add_Two_Numbers_II.py b/LeetCode/0445_Add_Two_Numbers_II.py deleted file mode 100644 index b0c6aea..0000000 --- a/LeetCode/0445_Add_Two_Numbers_II.py +++ /dev/null @@ -1,27 +0,0 @@ -# Definition for singly-linked list. -# class ListNode: -# def __init__(self, val=0, next=None): -# self.val = val -# self.next = next -class Solution: - def linkedListToInt(self, list_node, integer): - integer += str(list_node.val) - if list_node.next == None: - return int(integer) - else: - return self.linkedListToInt(list_node.next, integer) - - def intToLinkedList(self, integer): - integer = str(integer) - print(integer) - ll = [ListNode(int(integer[0]))] - for i in range(1, len(integer)): - ll.append(ListNode(int(integer[i]))) - ll[i - 1].next = ll[i] - return ll[0] - - def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: - first = self.linkedListToInt(l1, "") - second = self.linkedListToInt(l2, "") - summed = first + second - return self.intToLinkedList(summed) From 58dd046fd3672f94ccc97406b317c40139db15ec Mon Sep 17 00:00:00 2001 From: Jeff Mikels Date: Sat, 10 Oct 2020 15:26:27 -0400 Subject: [PATCH 235/357] completed LeetCode 0080 --- ..._Remove_Duplicates_from_Sorted_Array_II.py | 34 +++++++++++++++++++ 1 file changed, 34 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..0d63cae --- /dev/null +++ b/LeetCode/0080_Remove_Duplicates_from_Sorted_Array_II.py @@ -0,0 +1,34 @@ +''' +https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ +''' + + +class Solution: + # we want to leave at most two of each element + def removeDuplicates(self, nums: list) -> int: + length = 0 + lastNum = None + lastLastNum = None + + # iterate in reverse order so that when we modify the list + # it doesn't affect the order of the unvisited elements + i = len(nums) - 1 + while i >= 0: + el = nums[i] + if el == lastLastNum: + del nums[i] + else: + length += 1 + lastLastNum = lastNum + lastNum = el + i -= 1 + + return length + + +if __name__ == '__main__': + solution = Solution() + input = [1, 1, 1, 2, 2, 3] + solution.removeDuplicates(input) + print(input) + print(len(input)) From 685d62020c59b4d0c6a7480514ba4cccbc8e2da2 Mon Sep 17 00:00:00 2001 From: michal-dbrnowski Date: Sat, 10 Oct 2020 21:33:39 +0200 Subject: [PATCH 236/357] Create 0202_Happy_Number.py --- LeetCode/0202_Happy_Number.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/0202_Happy_Number.py diff --git a/LeetCode/0202_Happy_Number.py b/LeetCode/0202_Happy_Number.py new file mode 100644 index 0000000..119036a --- /dev/null +++ b/LeetCode/0202_Happy_Number.py @@ -0,0 +1,13 @@ +class Solution(object): + def isHappy(self, n): + """ + :type n: int + :rtype: bool + """ + checked = [] + while n != 1 and n not in checked: + checked.append(n) + n = sum([int(i) ** 2 for i in str(n)]) + if n == 1: + return True + return False \ No newline at end of file From dc71cc81a60649f5b58cb3537461a2a7005899e7 Mon Sep 17 00:00:00 2001 From: abdulrahmannaser Date: Sat, 10 Oct 2020 23:37:37 +0200 Subject: [PATCH 237/357] [ADD] LeetCode: 1550 Three Consecutive Odds --- LeetCode/1550_Three_Consecutive_Odds.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 LeetCode/1550_Three_Consecutive_Odds.py diff --git a/LeetCode/1550_Three_Consecutive_Odds.py b/LeetCode/1550_Three_Consecutive_Odds.py new file mode 100644 index 0000000..2497f74 --- /dev/null +++ b/LeetCode/1550_Three_Consecutive_Odds.py @@ -0,0 +1,6 @@ +class Solution: + def threeConsecutiveOdds(self, arr: List[int]) -> bool: + ok = False + for i in range(0, len(arr) - 2): + ok |=arr[i] & 1 and arr[i + 1] & 1 and arr[i + 2] & 1 + return ok From 80bee539deecce47112f886df7c5bd277c4198ec Mon Sep 17 00:00:00 2001 From: abdulrahmannaser Date: Sun, 11 Oct 2020 01:43:11 +0200 Subject: [PATCH 238/357] [ADD] issue #640 solution --- ...ract_the_Product_and_Sum_of_Digits_of_an_Integer.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/1281_Subtract_the_Product_and_Sum_of_Digits_of_an_Integer.py diff --git a/LeetCode/1281_Subtract_the_Product_and_Sum_of_Digits_of_an_Integer.py b/LeetCode/1281_Subtract_the_Product_and_Sum_of_Digits_of_an_Integer.py new file mode 100644 index 0000000..5fbfa4b --- /dev/null +++ b/LeetCode/1281_Subtract_the_Product_and_Sum_of_Digits_of_an_Integer.py @@ -0,0 +1,10 @@ +class Solution: + def subtractProductAndSum(self, n: int) -> int: + a = 1 + b = 0; + while(n): + a*=n%10 + b+=n%10 + n//=10 + return a - b + From 60aef69a15ed3eb1287215b2474465600c26d8ae Mon Sep 17 00:00:00 2001 From: abdulrahmannaser Date: Sun, 11 Oct 2020 01:46:47 +0200 Subject: [PATCH 239/357] [DELETE] 1550 solution because it's opened by someone else --- LeetCode/1550_Three_Consecutive_Odds.py | 6 ------ 1 file changed, 6 deletions(-) delete mode 100644 LeetCode/1550_Three_Consecutive_Odds.py diff --git a/LeetCode/1550_Three_Consecutive_Odds.py b/LeetCode/1550_Three_Consecutive_Odds.py deleted file mode 100644 index 2497f74..0000000 --- a/LeetCode/1550_Three_Consecutive_Odds.py +++ /dev/null @@ -1,6 +0,0 @@ -class Solution: - def threeConsecutiveOdds(self, arr: List[int]) -> bool: - ok = False - for i in range(0, len(arr) - 2): - ok |=arr[i] & 1 and arr[i + 1] & 1 and arr[i + 2] & 1 - return ok From 420cfab54fc15c033edb79bf7cdecbecdd8a41b7 Mon Sep 17 00:00:00 2001 From: Alexey Ilyukhov Date: Sun, 11 Oct 2020 03:16:46 +0300 Subject: [PATCH 240/357] fix --- LeetCode/1340_Jump_Game_V.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/LeetCode/1340_Jump_Game_V.py b/LeetCode/1340_Jump_Game_V.py index 1094f4d..9a8a911 100644 --- a/LeetCode/1340_Jump_Game_V.py +++ b/LeetCode/1340_Jump_Game_V.py @@ -1,5 +1,5 @@ -class Solution(object): - def maxJumps(self, arr, d): +class Solution: + def maxJumps(self, arr: List[int], d: int) -> int: """ :type arr: List[int] :type d: int @@ -9,7 +9,7 @@ def maxJumps(self, arr, d): dp = [1] * len(arr) for i, _ in sorted(enumerate(arr), key=lambda x: x[1]): - max_h = None + max_h = 0 for j in range(i - 1, max(i - d - 1, -1), -1): max_h = max(max_h, arr[j]) if max_h < arr[i]: @@ -17,7 +17,7 @@ def maxJumps(self, arr, d): else: break - max_h = None + max_h = 0 for j in range(i + 1, min(i + d + 1, len(arr))): max_h = max(max_h, arr[j]) if max_h < arr[i]: From 7514172e9077db3392e178ee95899b1e8e8331dd Mon Sep 17 00:00:00 2001 From: Alexey Ilyukhov Date: Sun, 11 Oct 2020 03:17:21 +0300 Subject: [PATCH 241/357] fix --- LeetCode/1340_Jump_Game_V.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/LeetCode/1340_Jump_Game_V.py b/LeetCode/1340_Jump_Game_V.py index 9a8a911..837a615 100644 --- a/LeetCode/1340_Jump_Game_V.py +++ b/LeetCode/1340_Jump_Game_V.py @@ -1,11 +1,5 @@ class Solution: def maxJumps(self, arr: List[int], d: int) -> int: - """ - :type arr: List[int] - :type d: int - :rtype: int - """ - dp = [1] * len(arr) for i, _ in sorted(enumerate(arr), key=lambda x: x[1]): From 151b10d36d0d00a74fee924ce9deae7469150407 Mon Sep 17 00:00:00 2001 From: Jared Gillespie Date: Sat, 10 Oct 2020 18:10:38 -0700 Subject: [PATCH 242/357] Add 589. N-ary Tree Preorder Traversal https://leetcode.com/submissions/detail/205318247/ --- LeetCode/589_Nary_Tree_Preorder_Traversal.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/589_Nary_Tree_Preorder_Traversal.py diff --git a/LeetCode/589_Nary_Tree_Preorder_Traversal.py b/LeetCode/589_Nary_Tree_Preorder_Traversal.py new file mode 100644 index 0000000..14035ce --- /dev/null +++ b/LeetCode/589_Nary_Tree_Preorder_Traversal.py @@ -0,0 +1,15 @@ +class Solution(object): + def preorder(self, root): + """ + :type root: Node + :rtype: List[int] + """ + def traverse(root): + if not root: return + ret.append(root.val) + for child in root.children: + traverse(child) + + ret = [] + traverse(root) + return ret From 9364f11529d290139fa43b3b2085b3ade9feebdd Mon Sep 17 00:00:00 2001 From: Bhawesh Bhansali Date: Sun, 11 Oct 2020 08:44:37 +0530 Subject: [PATCH 243/357] Update for Python3 --- LeetCode/1589-maximum-sum-obtained-of-any-permutation.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/LeetCode/1589-maximum-sum-obtained-of-any-permutation.py b/LeetCode/1589-maximum-sum-obtained-of-any-permutation.py index 9735428..4037231 100644 --- a/LeetCode/1589-maximum-sum-obtained-of-any-permutation.py +++ b/LeetCode/1589-maximum-sum-obtained-of-any-permutation.py @@ -14,7 +14,7 @@ def addmod(a, b, mod): # avoid overflow in other languages if mod-a <= b: b -= mod return a+b - + def mulmod(a, b, mod): # avoid overflow in other languages a %= mod b %= mod @@ -35,12 +35,12 @@ def mulmod(a, b, mod): # avoid overflow in other languages count[start] += 1 if end+1 < len(count): count[end+1] -= 1 - for i in xrange(1, len(count)): + for i in range(1, len(count)): count[i] += count[i-1] nums.sort() count.sort() result = 0 - for i, (num, c) in enumerate(itertools.izip(nums, count)): + for i, (num, c) in enumerate(zip(nums, count)): # result = addmod(result, mulmod(num, c, MOD), MOD) result = (result+num*c)%MOD return result From c8cebaa51bed35fb8fb7afd1e4a7283dee80539c Mon Sep 17 00:00:00 2001 From: grpnpraveen Date: Sun, 11 Oct 2020 10:12:46 +0530 Subject: [PATCH 244/357] Add files via upload This is an issue_template submitting a leetcode problem --- .github/ISSUE_TEMPLATE/Leetcodesubmission.md | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/Leetcodesubmission.md diff --git a/.github/ISSUE_TEMPLATE/Leetcodesubmission.md b/.github/ISSUE_TEMPLATE/Leetcodesubmission.md new file mode 100644 index 0000000..dd20366 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Leetcodesubmission.md @@ -0,0 +1,36 @@ +--- +name: Rotate image +about: Use this Template to submit a new LeetCode Problem +title: 0048_Rotate_Image +labels: 'hacktoberfest' +assignees: 'grpnpraveen' + +--- + +## Description of the Problem +You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). + +You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. + +## Code +``` +class Solution { +public: + void rotate(vector>& matrix) { + + int n = matrix.size(); + for(int i=0;i Date: Sun, 11 Oct 2020 10:13:59 +0530 Subject: [PATCH 245/357] Add files via upload A problem submitted --- LeetCode/0048_Rotate_Image.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 LeetCode/0048_Rotate_Image.py diff --git a/LeetCode/0048_Rotate_Image.py b/LeetCode/0048_Rotate_Image.py new file mode 100644 index 0000000..918e60e --- /dev/null +++ b/LeetCode/0048_Rotate_Image.py @@ -0,0 +1,9 @@ +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + for i in range(len(matrix)): + for j in range(i,len(matrix)): + if i != j: + matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j] + for each in matrix: + each.reverse() + return matrix \ No newline at end of file From 9aa1857316b4479a11e60ab1853268f1dcc32c17 Mon Sep 17 00:00:00 2001 From: grpnpraveen Date: Sun, 11 Oct 2020 10:26:06 +0530 Subject: [PATCH 246/357] Delete Leetcodesubmission.md --- .github/ISSUE_TEMPLATE/Leetcodesubmission.md | 36 -------------------- 1 file changed, 36 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/Leetcodesubmission.md diff --git a/.github/ISSUE_TEMPLATE/Leetcodesubmission.md b/.github/ISSUE_TEMPLATE/Leetcodesubmission.md deleted file mode 100644 index dd20366..0000000 --- a/.github/ISSUE_TEMPLATE/Leetcodesubmission.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -name: Rotate image -about: Use this Template to submit a new LeetCode Problem -title: 0048_Rotate_Image -labels: 'hacktoberfest' -assignees: 'grpnpraveen' - ---- - -## Description of the Problem -You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). - -You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. - -## Code -``` -class Solution { -public: - void rotate(vector>& matrix) { - - int n = matrix.size(); - for(int i=0;i Date: Sun, 11 Oct 2020 10:27:59 +0530 Subject: [PATCH 247/357] Add files via upload An issue template regarding a 0048_problem --- .github/ISSUE_TEMPLATE/Leetcodesubmission.md | 29 ++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/Leetcodesubmission.md diff --git a/.github/ISSUE_TEMPLATE/Leetcodesubmission.md b/.github/ISSUE_TEMPLATE/Leetcodesubmission.md new file mode 100644 index 0000000..11ab739 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Leetcodesubmission.md @@ -0,0 +1,29 @@ +--- +name: Rotate image +about: Use this Template to submit a new LeetCode Problem +title: 0048_Rotate_Image +labels: 'hacktoberfest' +assignees: 'grpnpraveen' + +--- + +## Description of the Problem +You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). + +You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. + +## Code +``` +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + for i in range(len(matrix)): + for j in range(i,len(matrix)): + if i != j: + matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j] + for each in matrix: + each.reverse() + return matrix +``` + +## Link To The LeetCode Problem +[LeetCode](https://leetcode.com/problems/rotate-image/) From 0f0034e83d6f01690d4b6058b37bb945ca20b510 Mon Sep 17 00:00:00 2001 From: sailok Date: Sun, 11 Oct 2020 10:38:23 +0530 Subject: [PATCH 248/357] Adding 0106 - Construct Binary Tree from Inorder and Postorder Traversal --- ...ee_from_Inorder_and_Postorder_Traversal.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 LeetCode/0106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py diff --git a/LeetCode/0106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py b/LeetCode/0106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py new file mode 100644 index 0000000..4157914 --- /dev/null +++ b/LeetCode/0106_Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal.py @@ -0,0 +1,22 @@ +class Solution: + def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: + return self.helperFunc(inorder, postorder, 0, len(inorder)-1, len(postorder)-1) + def helperFunc(self, inorder: List[int], postorder: List[int], left: int, right: int, postIndex: int) -> TreeNode: + # checks if there is node required else puts null in the binary tree + if postIndex == -1: + return + # creating the root of the subtree from the value present at current postIndex + root = TreeNode(postorder[postIndex]) + # we find the root's value in order to divide them into left and right subtree + x = 0 + for i in range(len(inorder)): + if root.val == inorder[i]: + x = i + # finding corresponding values that are roots for left and right subtrees or assign -1 + right_post = -1 if abs(right - x) == 0 else postIndex - 1 + left_post = -1 if abs(left - x) == 0 else postIndex -1 - abs(right - x) + # calling recursively helperFunc for left and right subtrees + root.left = self.helperFunc(inorder, postorder, left, x-1, left_post) + root.right = self.helperFunc(inorder, postorder, x+1, right, right_post) + return root + \ No newline at end of file From 8653fa59d90f4be4d0d72a105c760f89940b7d4e Mon Sep 17 00:00:00 2001 From: Anshul Gautam Date: Sun, 11 Oct 2020 12:13:26 +0530 Subject: [PATCH 249/357] added solution for issue 0138 --- .DS_Store | Bin 0 -> 8196 bytes .../0138_Copy_List_with_Random_Pointer.py | 31 ++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 .DS_Store create mode 100644 LeetCode/0138_Copy_List_with_Random_Pointer.py diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..2b814e5fb2bf3fee468e4839f097ac358da063b3 GIT binary patch literal 8196 zcmeHMTWl0n7(U-pV1|h>t(A+i*)0W1u!iMg5izjrwrDTVhHYuNwVmA=Vd8XVnVH>! zO=C40jS%$38;$bdHKIO=w@$#T1@Iqot{Lh>zp*Q1`Au?xk&VSDN zFQ@-E-$lADuEhjK(n;m#o38N!tj-cS&%PJYS2 zoFOe_)J6zI2uwwQZy$-ZF@rw-jraGw<>X0sHD9z$&rhYkM{HKb>^XBKd7dIG^A-6( z?vOK>^EJQZWi+=>U79m>Bd@vLrtTl=H0&nJC>wUW+ot)3yN?@pI*vsKqOaw5o5o-3{v-hKFTIT2i-tS8wTw6DLRCc=N5d&z=i>7{WIRs}$qw?Rn}=fyDC4 zSpi9GY#fqHH$bA?7H?^7+p)8~PgP5vvCFVD-z*!Al)TrcF7PP*=7M8)xJH@M?k+f1 zX}~5;WkItFB{DX)Sys+`R9F{W$Fe#c&-6{l-qYh7M|`g1fhMSW_Ii%%XMiwP%EpHYGq+}+4Ri3WpoYlr?yA)3Wlwl z_QAdM9Bkiw*fddBpt5GRD|2Bkq# zb-ByZ@`fd*HYuAWwN>sei*&_gwX#)`dkW6L043vzxlFuKQoodX`ND0Q=eHLPo7U#3 zZLf*P_we~`x^C!_LvjS&}z&`U1XQp@9YnDg@8NxXfRAw&=kPhczy!_UbzpE=sOgy=KFv zEt%_dn8bh^nHZ2yuq$BQIIDt(K9R~|M<|IdBBya=rj4P_<(o(vk^M&Gy~h5+Y|O(VB#E~5XuuXCZ5EAa!cKHx7jo#t0rU}l^F&|^ zHi|e*Bp$*r9>WM8$Fn$26n+lR;}xRtt9T8k@DAR^X(IC(qVgyB6rT~9zrlC7G>N)x z6RC^K(^0pab8XA950Y-2@)O;n5o5Ci2#fjsziH;*|0Ad(1R@0f#|WUJG1r)(1ZR3x z^1F7DYClz8xZQ}5feSUsLo&S@*#75_T JK*(F9`5TA7SFiv8 literal 0 HcmV?d00001 diff --git a/LeetCode/0138_Copy_List_with_Random_Pointer.py b/LeetCode/0138_Copy_List_with_Random_Pointer.py new file mode 100644 index 0000000..a2f9787 --- /dev/null +++ b/LeetCode/0138_Copy_List_with_Random_Pointer.py @@ -0,0 +1,31 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random +""" + +def solve(head): + d = {} + h = head + while(h): + copy = Node(h.val) + d[h] = copy + h = h.next + h = head + while(h): + copy = d[h] + if(h.next): + copy.next = d[h.next] + if(h.random): + copy.random = d[h.random] + h = h.next + if(head): + return d[head] + return None + +class Solution: + def copyRandomList(self, head: 'Node') -> 'Node': + return solve(head) From 3f4d6d020b539fea9e7cfd192276642684645689 Mon Sep 17 00:00:00 2001 From: Anshul Gautam Date: Sun, 11 Oct 2020 12:21:54 +0530 Subject: [PATCH 250/357] added solution for issue 0338 --- LeetCode/0338_Counting_Bits.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0338_Counting_Bits.py diff --git a/LeetCode/0338_Counting_Bits.py b/LeetCode/0338_Counting_Bits.py new file mode 100644 index 0000000..57d8397 --- /dev/null +++ b/LeetCode/0338_Counting_Bits.py @@ -0,0 +1,12 @@ +def solve(n): + dp = [0]*(n+1) + offset = 1 + for i in range(1,n+1): + if(not i&(i-1)): + offset = i + dp[i] = dp[i-offset] + 1 + return dp + +class Solution: + def countBits(self, num: int) -> List[int]: + return solve(num) From c381bae9175ee1709224922a4dad9793821c769d Mon Sep 17 00:00:00 2001 From: Tushar Sethi Date: Sun, 11 Oct 2020 12:26:34 +0530 Subject: [PATCH 251/357] Added 1299_Replace_Elements_with_Greatest_Elements_oon_Right_Side.py file --- ...lace_Elements_with_Greatest_Elements_on_Right_Side.py | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py diff --git a/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py b/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py new file mode 100644 index 0000000..161532f --- /dev/null +++ b/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py @@ -0,0 +1,9 @@ +class Solution(object): + def replaceElements(self, arr): + arr1 = [] + for i in range(len(arr)): + if i==len(arr)-1: + arr1.append(-1) + else: + arr1.append(max(arr[i+1:])) + return arr1 \ No newline at end of file From ee17de30953a4cc03ad7be856e19587a6a12235a Mon Sep 17 00:00:00 2001 From: Tushar Sethi Date: Sun, 11 Oct 2020 12:49:18 +0530 Subject: [PATCH 252/357] Added 1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py --- ...eplace_Elements_with_Greatest_Elements_on_Right_Side.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py b/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py index 161532f..074272b 100644 --- a/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py +++ b/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py @@ -1,9 +1,8 @@ class Solution(object): def replaceElements(self, arr): - arr1 = [] for i in range(len(arr)): if i==len(arr)-1: - arr1.append(-1) + arr[i] = -1 else: - arr1.append(max(arr[i+1:])) - return arr1 \ No newline at end of file + arr[i] = max(arr[i+1:]) + return \ No newline at end of file From 870338990c481b9f3ab74bc040bc7e7d2b0479a2 Mon Sep 17 00:00:00 2001 From: grpnpraveen Date: Sun, 11 Oct 2020 13:00:23 +0530 Subject: [PATCH 253/357] Add files via upload An issue template related to 0014 problem --- .github/ISSUE_TEMPLATE/Leetcodesubmission2.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/Leetcodesubmission2.md diff --git a/.github/ISSUE_TEMPLATE/Leetcodesubmission2.md b/.github/ISSUE_TEMPLATE/Leetcodesubmission2.md new file mode 100644 index 0000000..30f2c03 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/Leetcodesubmission2.md @@ -0,0 +1,35 @@ +--- +name: Longest Common Prefix +title: 0014_ Longest_Common_Prefix +labels: 'hacktoberfest' +assignees: 'grpnpraveen' + +--- + +## Description of the Problem +Write a function to find the longest common prefix string amongst an array of strings. + +If there is no common prefix, return an empty string "". + +## Code +``` +class Solution: + def longestCommonPrefix(self, strs): + """ + :type strs: List[str] + :rtype: str + """ + if len(strs) == 0: + return '' + res = '' + strs = sorted(strs) + for i in strs[0]: + if strs[-1].startswith(res+i): + res += i + else: + break + return res +``` + +## Link To The LeetCode Problem +[LeetCode](https://leetcode.com/problems/longest-common-prefix/) From 3cc84c6bff6326c0a4f0078a2f8b6f59ca773c39 Mon Sep 17 00:00:00 2001 From: grpnpraveen Date: Sun, 11 Oct 2020 13:01:13 +0530 Subject: [PATCH 254/357] Add files via upload 0014_LONGEST_common_prefix problem added to the leetcode --- LeetCode/0014_Longest_common_Prefix.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 LeetCode/0014_Longest_common_Prefix.py diff --git a/LeetCode/0014_Longest_common_Prefix.py b/LeetCode/0014_Longest_common_Prefix.py new file mode 100644 index 0000000..de0859d --- /dev/null +++ b/LeetCode/0014_Longest_common_Prefix.py @@ -0,0 +1,16 @@ +class Solution: + def longestCommonPrefix(self, strs): + """ + :type strs: List[str] + :rtype: str + """ + if len(strs) == 0: + return '' + res = '' + strs = sorted(strs) + for i in strs[0]: + if strs[-1].startswith(res+i): + res += i + else: + break + return res \ No newline at end of file From 686d59c33eca11e1e66d951314a3d92d60f4f361 Mon Sep 17 00:00:00 2001 From: Tushar Sethi Date: Sun, 11 Oct 2020 13:06:43 +0530 Subject: [PATCH 255/357] Added 1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py --- ...299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py b/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py index 074272b..f3134cf 100644 --- a/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py +++ b/LeetCode/1299_Replace_Elements_with_Greatest_Elements_on_Right_Side.py @@ -5,4 +5,4 @@ def replaceElements(self, arr): arr[i] = -1 else: arr[i] = max(arr[i+1:]) - return \ No newline at end of file + return arr \ No newline at end of file From 4aade0a57ec5ea58702aa250713c88398b6942d4 Mon Sep 17 00:00:00 2001 From: Varisht Date: Sun, 11 Oct 2020 13:09:33 +0530 Subject: [PATCH 256/357] Added code for LRU Cache --- LeetCode/0146_LRU_Cache.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 LeetCode/0146_LRU_Cache.py diff --git a/LeetCode/0146_LRU_Cache.py b/LeetCode/0146_LRU_Cache.py new file mode 100644 index 0000000..7a3f01d --- /dev/null +++ b/LeetCode/0146_LRU_Cache.py @@ -0,0 +1,28 @@ +class LRUCache: + + def __init__(self, capacity: int): + self.capacity = capacity + self.cache = collections.OrderedDict() + + + def get(self, key: int) -> int: + if key not in self.cache: + return -1 + else: + val = self.cache[key] + del self.cache[key] + self.cache[key] = val + return val + + def put(self, key: int, value: int) -> None: + if key in self.cache: + del self.cache[key] + elif len(self.cache) == self.capacity: + self.cache.popitem(last=False) + self.cache[key] = value + + +# Your LRUCache object will be instantiated and called as such: +# obj = LRUCache(capacity) +# param_1 = obj.get(key) +# obj.put(key,value) From acfba5342bf4c64b597bf08abb534afd9e68513e Mon Sep 17 00:00:00 2001 From: grpnpraveen Date: Sun, 11 Oct 2020 13:14:10 +0530 Subject: [PATCH 257/357] Delete Leetcodesubmission2.md --- .github/ISSUE_TEMPLATE/Leetcodesubmission2.md | 35 ------------------- 1 file changed, 35 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/Leetcodesubmission2.md diff --git a/.github/ISSUE_TEMPLATE/Leetcodesubmission2.md b/.github/ISSUE_TEMPLATE/Leetcodesubmission2.md deleted file mode 100644 index 30f2c03..0000000 --- a/.github/ISSUE_TEMPLATE/Leetcodesubmission2.md +++ /dev/null @@ -1,35 +0,0 @@ ---- -name: Longest Common Prefix -title: 0014_ Longest_Common_Prefix -labels: 'hacktoberfest' -assignees: 'grpnpraveen' - ---- - -## Description of the Problem -Write a function to find the longest common prefix string amongst an array of strings. - -If there is no common prefix, return an empty string "". - -## Code -``` -class Solution: - def longestCommonPrefix(self, strs): - """ - :type strs: List[str] - :rtype: str - """ - if len(strs) == 0: - return '' - res = '' - strs = sorted(strs) - for i in strs[0]: - if strs[-1].startswith(res+i): - res += i - else: - break - return res -``` - -## Link To The LeetCode Problem -[LeetCode](https://leetcode.com/problems/longest-common-prefix/) From 8061c39ed126c8765daa2cad521a6a50429aef94 Mon Sep 17 00:00:00 2001 From: grpnpraveen Date: Sun, 11 Oct 2020 13:14:24 +0530 Subject: [PATCH 258/357] Delete Leetcodesubmission.md --- .github/ISSUE_TEMPLATE/Leetcodesubmission.md | 29 -------------------- 1 file changed, 29 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/Leetcodesubmission.md diff --git a/.github/ISSUE_TEMPLATE/Leetcodesubmission.md b/.github/ISSUE_TEMPLATE/Leetcodesubmission.md deleted file mode 100644 index 11ab739..0000000 --- a/.github/ISSUE_TEMPLATE/Leetcodesubmission.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -name: Rotate image -about: Use this Template to submit a new LeetCode Problem -title: 0048_Rotate_Image -labels: 'hacktoberfest' -assignees: 'grpnpraveen' - ---- - -## Description of the Problem -You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). - -You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. - -## Code -``` -class Solution: - def rotate(self, matrix: List[List[int]]) -> None: - for i in range(len(matrix)): - for j in range(i,len(matrix)): - if i != j: - matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j] - for each in matrix: - each.reverse() - return matrix -``` - -## Link To The LeetCode Problem -[LeetCode](https://leetcode.com/problems/rotate-image/) From 3a899910b9a0ed6dd1d3b2ba237f9c1cea64d205 Mon Sep 17 00:00:00 2001 From: sailok Date: Sun, 11 Oct 2020 13:26:35 +0530 Subject: [PATCH 259/357] Adding 0208 Implement Trie --- LeetCode/0208_Implement_Trie.py.py | 58 ++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 LeetCode/0208_Implement_Trie.py.py diff --git a/LeetCode/0208_Implement_Trie.py.py b/LeetCode/0208_Implement_Trie.py.py new file mode 100644 index 0000000..2393881 --- /dev/null +++ b/LeetCode/0208_Implement_Trie.py.py @@ -0,0 +1,58 @@ +class TrieNode: + def __init__(self, val): + self.val = val + self.isEnd = False + self.children = [None for i in range(26)] +class Trie: + def __init__(self): + """ + Initialize your data structure here. + """ + self.root = TrieNode('*') + + + def insert(self, word: str) -> None: + """ + Inserts a word into the trie. + """ + node = self.root + for c in word: + x = ord(c) - ord('a') + if node.children[x] is None: + node.children[x] = TrieNode(c) + node = node.children[x] + node.isEnd = True + + def search(self, word: str) -> bool: + """ + Returns if the word is in the trie. + """ + node = self.root + for c in word: + x = ord(c) - ord('a') + if node.children[x] is not None: + node = node.children[x] + else: + return False + return node.isEnd + + + def startsWith(self, prefix: str) -> bool: + """ + Returns if there is any word in the trie that starts with the given prefix. + """ + node = self.root + for c in prefix: + x = ord(c) - ord('a') + if node.children[x] is not None: + node = node.children[x] + else: + return False + return True + + +# Your Trie object will be instantiated and called as such: +# obj = Trie() +# obj.insert(word) +# param_2 = obj.search(word) +# param_3 = obj.startsWith(prefix) \ No newline at end of file From 42bce83a33828e4cc60cc9af663f8696bb4a312c Mon Sep 17 00:00:00 2001 From: Tushar Sethi Date: Sun, 11 Oct 2020 13:30:21 +0530 Subject: [PATCH 260/357] Added 1436_Destination_City --- LeetCode/1436_Destination_City.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/1436_Destination_City.py diff --git a/LeetCode/1436_Destination_City.py b/LeetCode/1436_Destination_City.py new file mode 100644 index 0000000..6537894 --- /dev/null +++ b/LeetCode/1436_Destination_City.py @@ -0,0 +1,10 @@ +class Solution(object): + def destCity(self, paths): + origin, destination = [], [] + for p in paths: + origin.append(p[0]) + destination.append(p[1]) + + for d in destination: + if d not in origin : + return d \ No newline at end of file From 3b41c712b16e441c6ce17109933b593bd6876619 Mon Sep 17 00:00:00 2001 From: SushanthReddyManda Date: Sun, 11 Oct 2020 14:14:23 +0530 Subject: [PATCH 261/357] Create 1544_Make_String_Great --- LeetCode/1544_Make_string_great.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 LeetCode/1544_Make_string_great.py diff --git a/LeetCode/1544_Make_string_great.py b/LeetCode/1544_Make_string_great.py new file mode 100644 index 0000000..be04276 --- /dev/null +++ b/LeetCode/1544_Make_string_great.py @@ -0,0 +1,18 @@ +def finder(s): + a =0 + for i in range(len(s) -1): + if abs(ord(s[i]) - ord(s[i+1])) == 32 : + del s[i] + del s[i] + a =1 + break + if a == 0 : + return s + else: + return finder(s) + +class Solution: + def makeGood(self, s: str) -> str: + s = list(s) + h = finder(s) + return ("".join(h)) \ No newline at end of file From cd05aa835a7e4c3d233af412d438d9097091de4e Mon Sep 17 00:00:00 2001 From: praneshulleri Date: Sun, 11 Oct 2020 14:31:49 +0530 Subject: [PATCH 262/357] Maximum Binary Tree --- LeetCode/0654_Maximum_Binary_Tree.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/0654_Maximum_Binary_Tree.py diff --git a/LeetCode/0654_Maximum_Binary_Tree.py b/LeetCode/0654_Maximum_Binary_Tree.py new file mode 100644 index 0000000..6fc4128 --- /dev/null +++ b/LeetCode/0654_Maximum_Binary_Tree.py @@ -0,0 +1,13 @@ +class Solution: + def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: + def helper(nums, root): + if not nums: + return None + if nums: + root = TreeNode(max(nums)) + ind=nums.index(max(nums)) + root.left= helper(nums[:ind],root) + root.right=helper(nums[ind+1:],root) + return root + root=TreeNode(0) + return helper(nums,root) From 905c4aceafc20bb6a5e5cb5393ab7803650fafb5 Mon Sep 17 00:00:00 2001 From: Vinit-Dantkale Date: Sun, 11 Oct 2020 15:06:36 +0530 Subject: [PATCH 263/357] Adding solution to 1446_consecutive_characters --- LeetCode/1446_consecutive_characters.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/1446_consecutive_characters.py diff --git a/LeetCode/1446_consecutive_characters.py b/LeetCode/1446_consecutive_characters.py new file mode 100644 index 0000000..c29914c --- /dev/null +++ b/LeetCode/1446_consecutive_characters.py @@ -0,0 +1,10 @@ +class Solution: + def maxPower(self, s: str) -> int: + maxlen,currlen=1,1 + for i in range(1,len(s)): + if(s[i]==s[i-1]): + currlen=currlen+1 + maxlen=max(maxlen,currlen) + else: + currlen=1 + return maxlen \ No newline at end of file From 489f4f45c0d3f5ec629397b828ba2c57465d4b3a Mon Sep 17 00:00:00 2001 From: Andrey Zakharov Date: Sun, 11 Oct 2020 14:06:23 +0300 Subject: [PATCH 264/357] Create 0942_DI_String_Match.py 942. DI String Match --- LeetCode/0942_DI_String_Match.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/0942_DI_String_Match.py diff --git a/LeetCode/0942_DI_String_Match.py b/LeetCode/0942_DI_String_Match.py new file mode 100644 index 0000000..60eeb14 --- /dev/null +++ b/LeetCode/0942_DI_String_Match.py @@ -0,0 +1,13 @@ +class Solution: + def diStringMatch(self, S: str) -> List[int]: + mx = 0 + mn = 0 + res = [0] * (len(S) + 1) + for i in range(len(S)): + if S[i] == "I": + res[i + 1] = mx + 1 + mx += 1 + else: + res[i + 1] = mn - 1 + mn -= 1 + return [x - mn for x in res] From b2a584c29c044e2a3ea279d93904b484ac6ed694 Mon Sep 17 00:00:00 2001 From: grpnpraveen Date: Sun, 11 Oct 2020 16:41:36 +0530 Subject: [PATCH 265/357] Add files via upload 0067_Add_Binary added to leetcode --- LeetCode/0067_Add_Binary.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 LeetCode/0067_Add_Binary.py diff --git a/LeetCode/0067_Add_Binary.py b/LeetCode/0067_Add_Binary.py new file mode 100644 index 0000000..529e8b1 --- /dev/null +++ b/LeetCode/0067_Add_Binary.py @@ -0,0 +1,4 @@ +class Solution: + def addBinary(self, a: str, b: str) -> str: + sum = int(a,2) + int(b,2) + return bin(sum)[2:] \ No newline at end of file From 346c1ce8b4fcaa5ffb55aa9dc2cad10346586470 Mon Sep 17 00:00:00 2001 From: Rakshaa Viswanathan <46165429+rakshaa2000@users.noreply.github.com> Date: Sun, 11 Oct 2020 16:44:03 +0530 Subject: [PATCH 266/357] Created 0092_Decode_Ways.py --- LeetCode/0092_Decode_Ways.py | 40 ++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 LeetCode/0092_Decode_Ways.py diff --git a/LeetCode/0092_Decode_Ways.py b/LeetCode/0092_Decode_Ways.py new file mode 100644 index 0000000..0f0c382 --- /dev/null +++ b/LeetCode/0092_Decode_Ways.py @@ -0,0 +1,40 @@ +''' +Problem:- +A message containing letters from A-Z is being encoded to numbers using the following mapping: + +'A' -> 1 +'B' -> 2 +... +'Z' -> 26 +Given a non-empty string containing only digits, determine the total number of ways to decode it. + +The answer is guaranteed to fit in a 32-bit integer. + +Example 1: + +Input: s = "12" +Output: 2 +Explanation: It could be decoded as "AB" (1 2) or "L" (12). + +Example 2: + +Input: s = "226" +Output: 3 +Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). +''' + +class Solution: + def numDecodings(self, s: str) -> int: + @lru_cache(None) + def dp(i): + if i == len(s): + return 1 + ans = 0 + if s[i] != '0': + ans += dp(i+1) + if s[i] == '1' and i+1< len(s): + ans += dp(i+2) + if s[i] == '2' and i+1 < len(s) and s[i+1] <= '6': + ans += dp(i+2) + return ans + return dp(0) From ec8d7539bf1821b6a5b7d08d060561b77550e99d Mon Sep 17 00:00:00 2001 From: Rakshaa Viswanathan <46165429+rakshaa2000@users.noreply.github.com> Date: Sun, 11 Oct 2020 16:54:13 +0530 Subject: [PATCH 267/357] Create 0094_Binary_Tree_Inorder_Traversal.py --- .../0094_Binary_Tree_Inorder_Traversal.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0094_Binary_Tree_Inorder_Traversal.py diff --git a/LeetCode/0094_Binary_Tree_Inorder_Traversal.py b/LeetCode/0094_Binary_Tree_Inorder_Traversal.py new file mode 100644 index 0000000..d1b9e92 --- /dev/null +++ b/LeetCode/0094_Binary_Tree_Inorder_Traversal.py @@ -0,0 +1,19 @@ +# 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 inorderTraversal(self, root: TreeNode) -> List[int]: + res = [] + myStack = [] + curr = root + while len(myStack) or curr is not None: + while curr is not None: + myStack.append(curr) + curr = curr.left + curr = myStack.pop() + res.append(curr.val) + curr = curr.right + return res From ff648a629301b373274fff05e77fce49835257d4 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 17:14:55 +0530 Subject: [PATCH 268/357] Added Script to check and comment --- .github/workflows/leetcodeChecker.yml | 26 +++ codechecker.py | 51 ++++- leetcodeChecker.py | 311 ++++++++++++++++++++++++++ 3 files changed, 384 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/leetcodeChecker.yml create mode 100644 leetcodeChecker.py diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml new file mode 100644 index 0000000..09e8828 --- /dev/null +++ b/.github/workflows/leetcodeChecker.yml @@ -0,0 +1,26 @@ +name: py + +on: + pull_request: + +jobs: + build: + runs-on: ubuntu-latest + + steps: + # - name: checkout repo content # checkout is unecessary + # uses: actions/checkout@v2 + - name: setup python + uses: actions/setup-python@v2 + with: + python-version: 3.8 + - name: execute checker script + run: | + python codechecker.py + with: + github-token: ${{ github.token }} + env: + PR_NUMBER: ${{ github.event.pull_request.number }} + leetcode-csrf-token: ${{ secrets.LEETCODE_CSRF_TOKEN }} + leetcode-session: ${{ secrets.LEETCODE_SESSION }} + diff --git a/codechecker.py b/codechecker.py index c286bf9..2c1c6b8 100644 --- a/codechecker.py +++ b/codechecker.py @@ -5,6 +5,38 @@ load_dotenv(dotenv_path='sample.env') +def get_submissions(slug): + url = "https://leetcode-cn.com/graphql" + params = {'operationName': "Submissions", + 'variables': {"offset": 0, "limit": 20, "lastKey": '', "questionSlug": slug}, + 'query': '''query Submissions($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!) { + submissionList(offset: $offset, limit: $limit, lastKey: $lastKey, questionSlug: $questionSlug) { + lastKey + hasNext + submissions { + id + statusDisplay + lang + runtime + timestamp + url + isPending + __typename + } + __typename + } + }''' + } + + json_data = json.dumps(params).encode('utf8') + + headers = {'User-Agent': user_agent, 'Connection': 'keep-alive', 'Referer': 'https://leetcode-cn.com/accounts/login/', + "Content-Type": "application/json"} + resp = session.post(url, data=json_data, headers=headers, timeout=10) + content = resp.json() + for submission in content['data']['submissionList']['submissions']: + print(submission) + # load details from ENV repo_name = os.getenv("REPO_NAME") access_token = os.getenv("GITHUB_ACCESS_TOKEN") @@ -26,7 +58,7 @@ for i in all_files: if i.filename[-3:] == ".py": file_url = i.raw_url - problem_name = i.filename.lower() + problem_name = i.filename[9:].lower() # parse question id and problem name question_id = int(problem_name[0:4]) @@ -42,20 +74,31 @@ headers = { "Origin": "https://leetcode.com", "content-type": "application/json", - "X-CSRFToken": leetcode_csrf_token, - "Referer": leetcode_submission_url, + "Referer": "https://leetcode.com/problems/two-sum/submissions/", "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0", # "Cookie": f"csrftoken={leetcode_csrf_token};LEETCODE_SESSION={leetcode_session_token}", } + +headers = { + 'Connection': 'keep-alive', + 'Content-Type': 'application/json', + 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36', + 'Referer': 'https://leetcode.com/accounts/login/', + "origin": "https://leetcode.com" +} + cookies = { "csrftoken": leetcode_csrf_token, "LEETCODE_SESSION": leetcode_session_token, } body = {"question_id": str(question_id), "lang": language, "typed_code": code} +leetcode_submission_url2 = f"https://leetcode.com/api/problems/all" +leetcode_submission_url3 = f"https://leetcode.com/accounts/login/" # send request +sub = requests.get(leetcode_submission_url2, headers=headers, data=body, cookies=cookies) submit = requests.post( - leetcode_submission_url, headers=headers, data=body, cookies=cookies + leetcode_submission_url3, headers=headers, cookies=cookies ) print(submit.status_code) diff --git a/leetcodeChecker.py b/leetcodeChecker.py new file mode 100644 index 0000000..873d7ac --- /dev/null +++ b/leetcodeChecker.py @@ -0,0 +1,311 @@ +import requests, os, re, json, time +from github import Github +import browser_cookie3 +import keyring, pickle +from bs4 import BeautifulSoup + +from dotenv import load_dotenv + +load_dotenv(dotenv_path='sample.env') + +LC_BASE = 'https://leetcode.com' +LC_CSRF = LC_BASE + '/ensure_csrf/' +LC_LOGIN = LC_BASE + '/accounts/login/' +LC_GRAPHQL = LC_BASE + '/graphql' +LC_CATEGORY_PROBLEMS = LC_BASE + '/api/problems/{category}' +LC_PROBLEM = LC_BASE + '/problems/{slug}/description' +LC_TEST = LC_BASE + '/problems/{slug}/interpret_solution/' +LC_SUBMIT = LC_BASE + '/problems/{slug}/submit/' +LC_SUBMISSIONS = LC_BASE + '/api/submissions/{slug}' +LC_SUBMISSION = LC_BASE + '/submissions/detail/{submission}/' +LC_CHECK = LC_BASE + '/submissions/detail/{submission}/check/' +LC_PROBLEM_SET_ALL = LC_BASE + '/problemset/all/' +LC_PROGRESS_ALL = LC_BASE + '/api/progress/all/' + +def _break_code_lines(s): + return s.replace('\r\n', '\n').replace('\xa0', ' ').split('\n') + +def _break_paragraph_lines(s): + lines = _break_code_lines(s) + result = [] + # reserve one and only one empty line between two non-empty lines + for line in lines: + if line.strip() != '': # a line with only whitespaces is also empty + result.append(line) + result.append('') + return result + + +def _remove_description(code): + eod = code.find('[End of Description]') + if eod == -1: + return code + eol = code.find('\n', eod) + if eol == -1: + return '' + return code[eol+1:] + +def _split(s): + if isinstance(s, list): + lines = [] + for element in s: + lines.extend(_split(element)) + return lines + + # Replace all \r\n to \n and all \r (alone) to \n + s = s.replace('\r\n', '\n').replace('\r', '\n').replace('\0', '\n') + # str.split has an disadvantage that ''.split('\n') results in [''], but what we want + # is []. This small function returns [] if `s` is a blank string, that is, containing no + # characters other than whitespaces. + if s.strip() == '': + return [] + return s.split('\n') + +def _make_headers(): + assert is_login() + headers = {'Origin': LC_BASE, + 'Referer': LC_BASE, + 'X-Requested-With': 'XMLHttpRequest', + 'X-CSRFToken': session.cookies.get('csrftoken', '')} + return headers + +def get_progress(): + headers = _make_headers() + res = session.get(LC_PROGRESS_ALL, headers=headers) + if res.status_code != 200: + _echoerr('cannot get the progress') + return None + + data = res.json() + if 'solvedTotal' not in data: + return None + return data + +def _status_to_name(status): + if status == 10: + return 'Accepted' + if status == 11: + return 'Wrong Answer' + if status == 12: + return 'Memory Limit Exceeded' + if status == 13: + return 'Output Limit Exceeded' + if status == 14: + return 'Time Limit Exceeded' + if status == 15: + return 'Runtime Error' + if status == 16: + return 'Internal Error' + if status == 20: + return 'Compile Error' + if status == 21: + return 'Unknown Error' + return 'Unknown State' + + +def load_session_cookie(leetSession): + my_cookie = { + "version": 0, + "name": 'LEETCODE_SESSION', + "value": leetSession, + "port": None, + #"port_specified":False, + "domain": '.leetcode.com', + #"domain_specified":False, + #"domain_initial_dot":True, + "path": '/', + # "path_specified":True, + "secure": 1, + "expires": None, + "discard": True, + "comment": None, + "comment_url": None, + "rest": {}, + "rfc2109": False + } + + session_cookie = my_cookie + #session_cookie_raw = pickle.dumps(**my_cookie, protocol=0).decode('utf-8') + global session + session = requests.Session() + session.cookies.set(**session_cookie) + + progress = get_progress() + if progress is None: + keyring.delete_password('leetcode', 'SESSION_COOKIE') + return False + + return True + +def _check_result(submission_id): + + while True: + headers = _make_headers() + url = LC_CHECK.format(submission=submission_id) + res = session.get(url, headers=headers) + if res.status_code != 200: + _echoerr('cannot get the execution result') + return None + + r = res.json() + if r['state'] == 'SUCCESS': + prog_stage = 'Done ' + break + elif r['state'] == 'PENDING': + prog_stage = 'Pending ' + elif r['state'] == 'STARTED': + prog_stage = 'Running ' + + time.sleep(1) + + result = { + 'answer': r.get('code_answer', []), + 'runtime': r['status_runtime'], + 'state': _status_to_name(r['status_code']), + 'testcase': _split(r.get('input', r.get('last_testcase', ''))), + 'passed': r.get('total_correct') or 0, + 'total': r.get('total_testcases') or 0, + 'error': _split([v for k, v in r.items() if 'error' in k and v]) + } + + # the keys differs between the result of testing the code and submitting it + # for submission judge_type is 'large', and for testing judge_type does not exist + if r.get('judge_type') == 'large': + result['answer'] = _split(r.get('code_output', '')) + result['expected_answer'] = _split(r.get('expected_output', '')) + result['stdout'] = _split(r.get('std_output', '')) + result['runtime_percentile'] = r.get('runtime_percentile', '') + else: + # Test states cannot distinguish accepted answers from wrong answers. + if result['state'] == 'Accepted': + result['state'] = 'Finished' + result['stdout'] = _split(r.get('code_output', [])) + result['expected_answer'] = [] + result['runtime_percentile'] = r.get('runtime_percentile', '') + result['expected_answer'] = r.get('expected_code_answer', []) + return result + + +def submit_solution(slug, filetype, code=None): + assert is_login() + problem = get_problem(slug) + if not problem: + return None + + code = _remove_description(code) + + headers = _make_headers() + headers['Referer'] = LC_PROBLEM.format(slug=slug) + body = {'data_input': problem['testcase'], + 'lang': filetype, + 'question_id': str(problem['id']), + 'test_mode': False, + 'typed_code': code, + 'judge_type': 'large'} + url = LC_SUBMIT.format(slug=slug) + + res = session.post(url, json=body, headers=headers) + + if res.status_code != 200: + if 'too fast' in res.text: + print('you are sending the request too fast') + else: + print('cannot submit the solution for ' + slug) + return None + + result = _check_result(res.json()['submission_id']) + result['title'] = problem['title'] + return result + +def is_login(): + return session and 'LEETCODE_SESSION' in session.cookies + +def get_problem(slug): + assert is_login() + headers = _make_headers() + headers['Referer'] = LC_PROBLEM.format(slug=slug) + body = {'query': '''query getQuestionDetail($titleSlug : String!) { + question(titleSlug: $titleSlug) { + questionId + questionFrontendId + title + content + stats + difficulty + codeDefinition + sampleTestCase + enableRunCode + translatedContent + } +}''', + 'variables': {'titleSlug': slug}, + 'operationName': 'getQuestionDetail'} + res = session.post(LC_GRAPHQL, json=body, headers=headers) + if res.status_code != 200: + _echoerr('cannot get the problem: {}'.format(slug)) + return None + + q = res.json()['data']['question'] + content = q['translatedContent'] or q['content'] + if content is None: + _echoerr('cannot get the problem: {}'.format(slug)) + return None + + soup = BeautifulSoup(content, features='html.parser') + problem = {} + problem['id'] = q['questionId'] + problem['fid'] = q['questionFrontendId'] + problem['title'] = q['title'] + problem['slug'] = slug + problem['level'] = q['difficulty'] + problem['desc'] = _break_paragraph_lines(soup.get_text()) + problem['templates'] = {} + for t in json.loads(q['codeDefinition']): + problem['templates'][t['value']] = _break_code_lines(t['defaultCode']) + problem['testable'] = q['enableRunCode'] + problem['testcase'] = _split(q['sampleTestCase']) + stats = json.loads(q['stats']) + problem['total_accepted'] = stats['totalAccepted'] + problem['total_submission'] = stats['totalSubmission'] + problem['ac_rate'] = stats['acRate'] + return problem + + + +# load details from ENV +repo_name = os.getenv("REPO_NAME") +access_token = os.getenv("GITHUB_ACCESS_TOKEN") +pull_number = int(os.getenv("PR_NUMBER")) +leetcode_csrf_token = os.getenv("LEETCODE_CSRF_TOKEN") +leetcode_session_token = os.getenv("LEETCODE_SESSION_TOKEN") + +# authentication +g = Github(access_token) +repo = g.get_repo(repo_name) + +# get PR details +pull = repo.get_pull(pull_number) +all_files = pull.get_files() + +# get details of files from PR +file_url = "" +problem_name = "" +for i in all_files: + if i.filename[-3:] == ".py": + file_url = i.raw_url + problem_name = i.filename[9:].lower() + +# parse question id and problem name +question_id = int(problem_name[0:4]) +problem_name = re.sub("_", "-", problem_name[5:-3]) + +# get file code +r = requests.get(file_url) +code = r.text + +load_session_cookie(leetcode_session_token) +result = submit_solution(problem_name,'python3',code) +if result['state'] == 'Finished': + pull.create_issue_comment("All test case have been passed, can be merged") +else: + pull.create_issue_comment(result['state']) From 66aaf51a57c4b125ad8d2ed096e4e4c187930efd Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 17:24:14 +0530 Subject: [PATCH 269/357] Removed duplicate file --- .github/workflows/leetcodeChecker.yml | 2 +- codechecker.py | 114 -------------------------- leetcodeChecker.py | 3 - 3 files changed, 1 insertion(+), 118 deletions(-) delete mode 100644 codechecker.py diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 09e8828..26a34aa 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -16,7 +16,7 @@ jobs: python-version: 3.8 - name: execute checker script run: | - python codechecker.py + python leetcodeChecker.py with: github-token: ${{ github.token }} env: diff --git a/codechecker.py b/codechecker.py deleted file mode 100644 index 2c1c6b8..0000000 --- a/codechecker.py +++ /dev/null @@ -1,114 +0,0 @@ -import requests, os, re, json -from github import Github - -from dotenv import load_dotenv - -load_dotenv(dotenv_path='sample.env') - -def get_submissions(slug): - url = "https://leetcode-cn.com/graphql" - params = {'operationName': "Submissions", - 'variables': {"offset": 0, "limit": 20, "lastKey": '', "questionSlug": slug}, - 'query': '''query Submissions($offset: Int!, $limit: Int!, $lastKey: String, $questionSlug: String!) { - submissionList(offset: $offset, limit: $limit, lastKey: $lastKey, questionSlug: $questionSlug) { - lastKey - hasNext - submissions { - id - statusDisplay - lang - runtime - timestamp - url - isPending - __typename - } - __typename - } - }''' - } - - json_data = json.dumps(params).encode('utf8') - - headers = {'User-Agent': user_agent, 'Connection': 'keep-alive', 'Referer': 'https://leetcode-cn.com/accounts/login/', - "Content-Type": "application/json"} - resp = session.post(url, data=json_data, headers=headers, timeout=10) - content = resp.json() - for submission in content['data']['submissionList']['submissions']: - print(submission) - -# load details from ENV -repo_name = os.getenv("REPO_NAME") -access_token = os.getenv("GITHUB_ACCESS_TOKEN") -pull_number = int(os.getenv("PR_NUMBER")) -leetcode_csrf_token = os.getenv("LEETCODE_CSRF_TOKEN") -leetcode_session_token = os.getenv("LEETCODE_SESSION_TOKEN") - -# authentication -g = Github(access_token) -repo = g.get_repo(repo_name) - -# get PR details -pull = repo.get_pull(pull_number) -all_files = pull.get_files() - -# get details of files from PR -file_url = "" -problem_name = "" -for i in all_files: - if i.filename[-3:] == ".py": - file_url = i.raw_url - problem_name = i.filename[9:].lower() - -# parse question id and problem name -question_id = int(problem_name[0:4]) -problem_name = re.sub("_", "-", problem_name[5:-3]) - -# get file code -r = requests.get(file_url) -code = r.text - -# craft request -leetcode_submission_url = f"https://leetcode.com/problems/{problem_name}/submit/" -language = "python3" -headers = { - "Origin": "https://leetcode.com", - "content-type": "application/json", - "Referer": "https://leetcode.com/problems/two-sum/submissions/", - "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0", - # "Cookie": f"csrftoken={leetcode_csrf_token};LEETCODE_SESSION={leetcode_session_token}", -} - -headers = { - 'Connection': 'keep-alive', - 'Content-Type': 'application/json', - 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36', - 'Referer': 'https://leetcode.com/accounts/login/', - "origin": "https://leetcode.com" -} - -cookies = { - "csrftoken": leetcode_csrf_token, - "LEETCODE_SESSION": leetcode_session_token, -} -body = {"question_id": str(question_id), "lang": language, "typed_code": code} - -leetcode_submission_url2 = f"https://leetcode.com/api/problems/all" -leetcode_submission_url3 = f"https://leetcode.com/accounts/login/" -# send request -sub = requests.get(leetcode_submission_url2, headers=headers, data=body, cookies=cookies) -submit = requests.post( - leetcode_submission_url3, headers=headers, cookies=cookies -) - -print(submit.status_code) - -# get from submit url response -submission_id = "" - -# check submission against submission_id -leetcode_checker_url = f"https://leetcode.com/submissions/detail/{submission_id}/check/" - - -# sample request body extracted from network tab: {"question_id":"231","lang":"python3","typed_code":"class Solution:\n def isPowerOfTwo(self, x: int) -> bool:\n return (x != 0) and ((x & (x - 1)) == 0); \n"} -# get status of submission \ No newline at end of file diff --git a/leetcodeChecker.py b/leetcodeChecker.py index 873d7ac..ab3bb54 100644 --- a/leetcodeChecker.py +++ b/leetcodeChecker.py @@ -1,7 +1,4 @@ import requests, os, re, json, time -from github import Github -import browser_cookie3 -import keyring, pickle from bs4 import BeautifulSoup from dotenv import load_dotenv From afb25169f0e373dc330283e49afb37a4f4d1ea4a Mon Sep 17 00:00:00 2001 From: Herumb Shandilya <43719685+krypticmouse@users.noreply.github.com> Date: Sun, 11 Oct 2020 17:26:11 +0530 Subject: [PATCH 270/357] Create 0067_Add_Binary.py Added 67th LeetCode Problem --- LeetCode/0067_Add_Binary.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/0067_Add_Binary.py diff --git a/LeetCode/0067_Add_Binary.py b/LeetCode/0067_Add_Binary.py new file mode 100644 index 0000000..7277674 --- /dev/null +++ b/LeetCode/0067_Add_Binary.py @@ -0,0 +1,12 @@ +# Problem name : Add Binary +# Problem link : https://leetcode.com/problems/add-binary/ +# Contributor : Herumb Shandilya + +class Solution: + def addBinary(self, a: str, b: str) -> str: + l_a = [int(x) for x in list(a)] + l_b = [int(x) for x in list(b)] + num_a = sum([l_a[i]*(2**(len(l_a)-i-1)) for i in range(len(l_a))]) + num_b = sum([l_b[i]*(2**(len(l_b)-i-1)) for i in range(len(l_b))]) + s = num_a + num_b + return bin(s)[2:] From 090c4b970aa455da334e962d13d6d867d8c45524 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 17:30:02 +0530 Subject: [PATCH 271/357] remove env --- .github/workflows/leetcodeChecker.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 26a34aa..432535d 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -19,7 +19,6 @@ jobs: python leetcodeChecker.py with: github-token: ${{ github.token }} - env: PR_NUMBER: ${{ github.event.pull_request.number }} leetcode-csrf-token: ${{ secrets.LEETCODE_CSRF_TOKEN }} leetcode-session: ${{ secrets.LEETCODE_SESSION }} From f64b782154fef969e88a24f53cb06197bee7b8d7 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 17:35:40 +0530 Subject: [PATCH 272/357] Modified YML file --- .github/workflows/leetcodeChecker.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 432535d..ca21fe5 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -15,11 +15,12 @@ jobs: with: python-version: 3.8 - name: execute checker script - run: | - python leetcodeChecker.py with: github-token: ${{ github.token }} - PR_NUMBER: ${{ github.event.pull_request.number }} + pull-number: ${{ github.event.pull_request.number }} leetcode-csrf-token: ${{ secrets.LEETCODE_CSRF_TOKEN }} leetcode-session: ${{ secrets.LEETCODE_SESSION }} + leetcode-session: ${{ secrets.LEETCODE_SESSION }} + run: | + python leetcodeChecker.py From 6018b96fca1c69ea7db809a5ef5ec93421a422fb Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 17:38:39 +0530 Subject: [PATCH 273/357] still confused --- .github/workflows/leetcodeChecker.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index ca21fe5..688ef68 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -20,7 +20,5 @@ jobs: pull-number: ${{ github.event.pull_request.number }} leetcode-csrf-token: ${{ secrets.LEETCODE_CSRF_TOKEN }} leetcode-session: ${{ secrets.LEETCODE_SESSION }} - leetcode-session: ${{ secrets.LEETCODE_SESSION }} - run: | - python leetcodeChecker.py + run: python leetcodeChecker.py From 7173b95f7d54cd1502767c2aa61298ad623c64b2 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 17:47:57 +0530 Subject: [PATCH 274/357] ! --- .github/workflows/leetcodeChecker.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 688ef68..d9cf8c1 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -14,7 +14,8 @@ jobs: uses: actions/setup-python@v2 with: python-version: 3.8 - - name: execute checker script + - name: run python script + uses: ./ with: github-token: ${{ github.token }} pull-number: ${{ github.event.pull_request.number }} From 5b007a2e586a343a5b98ab939b23d28e507e049d Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 17:50:11 +0530 Subject: [PATCH 275/357] Either uses or run --- .github/workflows/leetcodeChecker.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index d9cf8c1..8af94aa 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -15,7 +15,6 @@ jobs: with: python-version: 3.8 - name: run python script - uses: ./ with: github-token: ${{ github.token }} pull-number: ${{ github.event.pull_request.number }} From 0fa6c2e527171f0f383d41621d68178985a68f3e Mon Sep 17 00:00:00 2001 From: Herumb Shandilya Date: Sun, 11 Oct 2020 18:00:06 +0530 Subject: [PATCH 276/357] Added 167th Problem --- LeetCode/0167_Two_Sum_II.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0167_Two_Sum_II.py diff --git a/LeetCode/0167_Two_Sum_II.py b/LeetCode/0167_Two_Sum_II.py new file mode 100644 index 0000000..6d48eb1 --- /dev/null +++ b/LeetCode/0167_Two_Sum_II.py @@ -0,0 +1,15 @@ +# Problem name : Two Sum II - Input array is sorted +# Problem link : https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ +# Contributor : Herumb Shandilya + +class Solution: + def twoSum(self, numbers: List[int], target: int) -> List[int]: + for x in numbers: + if x > target: + break + else: + if target - x == x: + return (numbers.index(x)+1,numbers.index(x)+2) + else: + if target - x in numbers: + return(numbers.index(x)+1,numbers.index(target - x)+1) \ No newline at end of file From 0772d4e668b103cab71606d5d8b14536bd83071d Mon Sep 17 00:00:00 2001 From: Soroosh Date: Sun, 11 Oct 2020 14:38:37 +0200 Subject: [PATCH 277/357] 0929 Unique Email Addresses added --- LeetCode/0929_Unique_Email_Addresses.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/0929_Unique_Email_Addresses.py diff --git a/LeetCode/0929_Unique_Email_Addresses.py b/LeetCode/0929_Unique_Email_Addresses.py new file mode 100644 index 0000000..55b5510 --- /dev/null +++ b/LeetCode/0929_Unique_Email_Addresses.py @@ -0,0 +1,11 @@ +class Solution: + def numUniqueEmails(self, emails: List[str]) -> int: + seen_emails = set() + for item in emails: + name, domain = item.split('@') + special_index = name.find('+') + if special_index != -1: + name = name[: special_index] + seen_emails.add(name.replace('.', '') + '@' + domain) + return len(seen_emails) + \ No newline at end of file From 2faf8411075bca365392628382db198bd74682bb Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:09:30 +0530 Subject: [PATCH 278/357] Added dependencies --- .github/workflows/leetcodeChecker.yml | 19 ++++++++++++------- leetcodeChecker.py | 3 ++- requirements.txt | 2 ++ 3 files changed, 16 insertions(+), 8 deletions(-) create mode 100644 requirements.txt diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 8af94aa..7df4027 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -14,11 +14,16 @@ jobs: uses: actions/setup-python@v2 with: python-version: 3.8 - - name: run python script - with: - github-token: ${{ github.token }} - pull-number: ${{ github.event.pull_request.number }} - leetcode-csrf-token: ${{ secrets.LEETCODE_CSRF_TOKEN }} - leetcode-session: ${{ secrets.LEETCODE_SESSION }} - run: python leetcodeChecker.py + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + - name: run python + run: | + python leetcodeChecker.py + env: + GITHUB_ACCESS_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ github.event.pull_request.number }} + LEETCODE_CSRF_TOKEN: ${{ secrets.LEETCODE_CSRF_TOKEN }} + LEETCODE_SESSION_TOKEN: ${{ secrets.LEETCODE_SESSION }} diff --git a/leetcodeChecker.py b/leetcodeChecker.py index ab3bb54..f98b1b0 100644 --- a/leetcodeChecker.py +++ b/leetcodeChecker.py @@ -3,7 +3,8 @@ from dotenv import load_dotenv -load_dotenv(dotenv_path='sample.env') +load_dotenv() +#load_dotenv(dotenv_path='sample.env') LC_BASE = 'https://leetcode.com' LC_CSRF = LC_BASE + '/ensure_csrf/' diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..377e066 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +requests==2.24.0 +bs4==0.0.1 From bdb71b3911ed91a668a1602abd12145b23daee71 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:12:49 +0530 Subject: [PATCH 279/357] Remove yml syntax error --- .github/workflows/leetcodeChecker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 7df4027..84dcb5d 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -16,8 +16,8 @@ jobs: python-version: 3.8 - name: Install dependencies run: | - python -m pip install --upgrade pip - pip install -r requirements.txt + python -m pip install --upgrade pip + pip install -r requirements.txt - name: run python run: | python leetcodeChecker.py From a916bee9292b66c91c29cec23d42844e42b16ac3 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:21:56 +0530 Subject: [PATCH 280/357] Unable to install via requirements.txt --- .github/workflows/leetcodeChecker.yml | 3 ++- leetcodeChecker.py | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 84dcb5d..70bc058 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -17,7 +17,8 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install -r requirements.txt + pip install requests + pip install bs4 - name: run python run: | python leetcodeChecker.py diff --git a/leetcodeChecker.py b/leetcodeChecker.py index f98b1b0..476be52 100644 --- a/leetcodeChecker.py +++ b/leetcodeChecker.py @@ -303,7 +303,9 @@ def get_problem(slug): load_session_cookie(leetcode_session_token) result = submit_solution(problem_name,'python3',code) -if result['state'] == 'Finished': +if result is None: + print("Nothing to do") +elif result['state'] == 'Finished': pull.create_issue_comment("All test case have been passed, can be merged") else: pull.create_issue_comment(result['state']) From 08916c45e5d1a2d3a3c09fb3309f5659165f83b7 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:25:45 +0530 Subject: [PATCH 281/357] Added checkout --- .github/workflows/leetcodeChecker.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 70bc058..92645a2 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -8,8 +8,8 @@ jobs: runs-on: ubuntu-latest steps: - # - name: checkout repo content # checkout is unecessary - # uses: actions/checkout@v2 + - name: checkout + uses: actions/checkout@v2 - name: setup python uses: actions/setup-python@v2 with: From 8c376540786fc546151e1418294c1a4006429890 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:28:53 +0530 Subject: [PATCH 282/357] Added dotenv in requirements --- .github/workflows/leetcodeChecker.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 92645a2..0fd6c49 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -19,6 +19,7 @@ jobs: python -m pip install --upgrade pip pip install requests pip install bs4 + pip install python-dotenv - name: run python run: | python leetcodeChecker.py From 3e9f412730903f207dadacfe0a8bf38b3f6c8efb Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:32:55 +0530 Subject: [PATCH 283/357] Added pygithub --- .github/workflows/leetcodeChecker.yml | 4 +--- requirements.txt | 1 + 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 0fd6c49..4bd67d2 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -17,9 +17,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install requests - pip install bs4 - pip install python-dotenv + pip install -r requirements.txt - name: run python run: | python leetcodeChecker.py diff --git a/requirements.txt b/requirements.txt index 377e066..77fd5f4 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,3 @@ requests==2.24.0 bs4==0.0.1 +PyGithub==1.53 From 6cc7ab1d622d24eb2ba9264f446fca9f4a2a4787 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:35:25 +0530 Subject: [PATCH 284/357] Added pythondotenv --- requirements.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/requirements.txt b/requirements.txt index 77fd5f4..455c38f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,5 @@ requests==2.24.0 bs4==0.0.1 PyGithub==1.53 +python-dotenv==0.14.0 + From 50bf8ebc88cc1e738c90e3052b055667011c6655 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:39:18 +0530 Subject: [PATCH 285/357] Added pyGithub --- leetcodeChecker.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/leetcodeChecker.py b/leetcodeChecker.py index 476be52..181a6e3 100644 --- a/leetcodeChecker.py +++ b/leetcodeChecker.py @@ -1,6 +1,6 @@ import requests, os, re, json, time from bs4 import BeautifulSoup - +from github import Github from dotenv import load_dotenv load_dotenv() From 6f1405a9a2295103d099021c46592a5344aa5776 Mon Sep 17 00:00:00 2001 From: yoyogesh01 Date: Sun, 11 Oct 2020 18:45:33 +0530 Subject: [PATCH 286/357] Git repo name --- .github/workflows/leetcodeChecker.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index 4bd67d2..d1f7d96 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -23,6 +23,7 @@ jobs: python leetcodeChecker.py env: GITHUB_ACCESS_TOKEN: ${{ github.token }} + REPO_NAME: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }} LEETCODE_CSRF_TOKEN: ${{ secrets.LEETCODE_CSRF_TOKEN }} LEETCODE_SESSION_TOKEN: ${{ secrets.LEETCODE_SESSION }} From a910002df1946b999e6870ab402103306293c4ff Mon Sep 17 00:00:00 2001 From: Deepti Date: Sun, 11 Oct 2020 19:43:08 +0530 Subject: [PATCH 287/357] add solution for LC 0216 --- LeetCode/0216_Combination_Sum_III.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/0216_Combination_Sum_III.py diff --git a/LeetCode/0216_Combination_Sum_III.py b/LeetCode/0216_Combination_Sum_III.py new file mode 100644 index 0000000..f555b1b --- /dev/null +++ b/LeetCode/0216_Combination_Sum_III.py @@ -0,0 +1,13 @@ +class Solution(object): + def combinationSum3(self, k, n): + ret = [] + self.dfs(list(range(1, 10)), k, n, [], ret) + return ret + + def dfs(self, nums, k, n, path, ret): + if k < 0 or n < 0: + return + if k == 0 and n == 0: + ret.append(path) + for i in range(len(nums)): + self.dfs(nums[i+1:], k-1, n-nums[i], path+[nums[i]], ret) \ No newline at end of file From 9890dfbe348479c7d71f0325d012a4caa89ec1b4 Mon Sep 17 00:00:00 2001 From: Deepti Date: Sun, 11 Oct 2020 19:53:41 +0530 Subject: [PATCH 288/357] add newline at the end --- LeetCode/0216_Combination_Sum_III.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/LeetCode/0216_Combination_Sum_III.py b/LeetCode/0216_Combination_Sum_III.py index f555b1b..8aedcb0 100644 --- a/LeetCode/0216_Combination_Sum_III.py +++ b/LeetCode/0216_Combination_Sum_III.py @@ -10,4 +10,5 @@ def dfs(self, nums, k, n, path, ret): if k == 0 and n == 0: ret.append(path) for i in range(len(nums)): - self.dfs(nums[i+1:], k-1, n-nums[i], path+[nums[i]], ret) \ No newline at end of file + self.dfs(nums[i+1:], k-1, n-nums[i], path+[nums[i]], ret) + \ No newline at end of file From 8028a83fb2f4a75e56b8c1e6deb0dfc2b65f5cac Mon Sep 17 00:00:00 2001 From: Deepti Date: Sun, 11 Oct 2020 19:56:05 +0530 Subject: [PATCH 289/357] remove new line --- LeetCode/0216_Combination_Sum_III.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/LeetCode/0216_Combination_Sum_III.py b/LeetCode/0216_Combination_Sum_III.py index 8aedcb0..f555b1b 100644 --- a/LeetCode/0216_Combination_Sum_III.py +++ b/LeetCode/0216_Combination_Sum_III.py @@ -10,5 +10,4 @@ def dfs(self, nums, k, n, path, ret): if k == 0 and n == 0: ret.append(path) for i in range(len(nums)): - self.dfs(nums[i+1:], k-1, n-nums[i], path+[nums[i]], ret) - \ No newline at end of file + self.dfs(nums[i+1:], k-1, n-nums[i], path+[nums[i]], ret) \ No newline at end of file From 7ddf2d13fa3ce428b2cd61ba5d35d2d261641155 Mon Sep 17 00:00:00 2001 From: Deepak2417 <71579689+Deepak2417@users.noreply.github.com> Date: Sun, 11 Oct 2020 20:10:07 +0530 Subject: [PATCH 290/357] Added solution for issue #383 (LeetCode id: 0123) I have added 0123_Best_Time_To_Buy_And_Sell_Stock_III.py file that will solve the problem stated. And this code has passed all the different test cases on LeetCode. --- ...123_Best_Time_To_Buy_And_Sell_Stock_III.py | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 LeetCode/0123_Best_Time_To_Buy_And_Sell_Stock_III.py diff --git a/LeetCode/0123_Best_Time_To_Buy_And_Sell_Stock_III.py b/LeetCode/0123_Best_Time_To_Buy_And_Sell_Stock_III.py new file mode 100644 index 0000000..96e2220 --- /dev/null +++ b/LeetCode/0123_Best_Time_To_Buy_And_Sell_Stock_III.py @@ -0,0 +1,49 @@ + +''' + Python program to solve issue: 0123- Best Time to Buy adn Sell Stock + + Issue Id: #383 +''' + + +class Solution: + + #Evalutes the all days to buy and sell stock & Generate maximum profit + def maxProfit(self, prices: List[int]) -> int: + + #Checks whether price array is empty or less then 2 elements + if prices==None or len(prices) < 2: + return 0 + + maxProfit=0 #Stores maximum profit + + minPrice=prices[0] #the minimum price from the first day to day k-1 + + #the maximum profit with at most one transaction from the first day to day k + first=[0 for x in range(0,len(prices))] + + #Evaluates maximum profit from first day to last day + for i in range(1,len(prices)): + maxProfit= max(maxProfit, prices[i]- minPrice) + first[i]= maxProfit + minPrice= min(minPrice, prices[i]) + + maxProfit=0 + maxPrice=prices[len(prices)-1] #the maximum price from day k+1 to the last day + + #the maximum profit with at most one transaction from day k to the last day + second=[0 for x in range(len(prices))] + + #Evaluates maximum profit from last day to first day + for j in range(len(prices)-2,-1,-1): + maxProfit = max(maxProfit, (maxPrice - prices[j])) + second[j] = int(maxProfit) + maxPrice = max(maxPrice, prices[j]) + + maxProfit=0 + + #Evaluates maximum profit for all days with at most TWO transaction + for k in range(0,len(prices)): + maxProfit= max(maxProfit, first[k]+second[k]) + + return maxProfit \ No newline at end of file From ce0ad409db3d08b7ff915c6d8a9273f580115db4 Mon Sep 17 00:00:00 2001 From: Rahul Date: Sun, 11 Oct 2020 20:39:56 +0530 Subject: [PATCH 291/357] Create 1598_Crawler_Log_Folder.py Added solution for Crawler Log Folder --- LeetCode/1598_Crawler_Log_Folder.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/1598_Crawler_Log_Folder.py diff --git a/LeetCode/1598_Crawler_Log_Folder.py b/LeetCode/1598_Crawler_Log_Folder.py new file mode 100644 index 0000000..411aab2 --- /dev/null +++ b/LeetCode/1598_Crawler_Log_Folder.py @@ -0,0 +1,13 @@ +class Solution: + def minOperations(self, logs: List[str]) -> int: + cnt = 0 + for log in logs: + if log == "../": + if cnt != 0: + cnt -= 1 + continue + elif log == "./": + continue + else: + cnt += 1 + return cnt if cnt > 0 else 0 From 988253113e1e3755e432ed4d5272a8cab8384c10 Mon Sep 17 00:00:00 2001 From: Wei Yang Date: Sun, 11 Oct 2020 23:12:56 +0200 Subject: [PATCH 292/357] add find 132 pattern --- LeetCode/0456_Find_132_Pattern.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 LeetCode/0456_Find_132_Pattern.py diff --git a/LeetCode/0456_Find_132_Pattern.py b/LeetCode/0456_Find_132_Pattern.py new file mode 100644 index 0000000..da095cc --- /dev/null +++ b/LeetCode/0456_Find_132_Pattern.py @@ -0,0 +1,17 @@ +import math +import sys + +class Solution: + def Find132Pattern(self, nums: List[int]): + n = len(nums) + top = n + third = -sys.maxsize + + for i in range(n-1, -1 , -1): + if nums[i] < third: + return True + while top < n and nums[i] > nums[top]: + third = nums[top] + top = top - 1 + nums[top] = nums[i] + return False From b1711aac01bf7eed5a2521cf92410a7bbdc9aa65 Mon Sep 17 00:00:00 2001 From: Wei Yang Date: Sun, 11 Oct 2020 23:49:39 +0200 Subject: [PATCH 293/357] update function name --- LeetCode/0456_Find_132_Pattern.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/LeetCode/0456_Find_132_Pattern.py b/LeetCode/0456_Find_132_Pattern.py index da095cc..4f74bd8 100644 --- a/LeetCode/0456_Find_132_Pattern.py +++ b/LeetCode/0456_Find_132_Pattern.py @@ -2,7 +2,7 @@ import sys class Solution: - def Find132Pattern(self, nums: List[int]): + def find132pattern(self, nums: List[int]): n = len(nums) top = n third = -sys.maxsize @@ -14,4 +14,4 @@ def Find132Pattern(self, nums: List[int]): third = nums[top] top = top - 1 nums[top] = nums[i] - return False + return False \ No newline at end of file From d3f6a98434d48adf10324007df5a1c7d3cb52933 Mon Sep 17 00:00:00 2001 From: Wei Yang Date: Sun, 11 Oct 2020 23:55:18 +0200 Subject: [PATCH 294/357] different approach --- LeetCode/0456_Find_132_Pattern.py | 56 ++++++++++++++++++++++++------- 1 file changed, 43 insertions(+), 13 deletions(-) diff --git a/LeetCode/0456_Find_132_Pattern.py b/LeetCode/0456_Find_132_Pattern.py index 4f74bd8..c176439 100644 --- a/LeetCode/0456_Find_132_Pattern.py +++ b/LeetCode/0456_Find_132_Pattern.py @@ -1,17 +1,47 @@ -import math -import sys - -class Solution: +class Solution(object): def find132pattern(self, nums: List[int]): - n = len(nums) - top = n - third = -sys.maxsize + if not nums or len(nums)< 2: + return False + + m=0 + ln=len(nums) + for i in range(len(nums)-1, -1, -1): + n=nums[i] + if i+1nums[i+1]: + break + else: + m+=1 + else: + return False + + ln-=m + assert(ln and m) + mi=ln + s3mx=nums[ln-1] + ln-=1 - for i in range(n-1, -1 , -1): - if nums[i] < third: + s2mx=nums[mi] + while mi nums[top]: - third = nums[top] - top = top - 1 - nums[top] = nums[i] + elif n==s3mx and mx2>s2mx: + s2mx=mx2 + elif n>s3mx: + s2mx=s3mx + s3mx=n + while mimx2 and n Date: Sun, 11 Oct 2020 16:56:29 -0500 Subject: [PATCH 295/357] 0105 --- ...ree_from_Preorder_and_Inorder_Traversal.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py diff --git a/LeetCode/0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py b/LeetCode/0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py new file mode 100644 index 0000000..51ef9c0 --- /dev/null +++ b/LeetCode/0105_Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.py @@ -0,0 +1,19 @@ +# 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 buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: + if len(preorder) == 0: + return None + + n = preorder.pop(0) + i = inorder.index(n) + + l = self.buildTree(preorder[:i], inorder[:i]) + r = self.buildTree(preorder[i:], inorder[i+1:]) + + return TreeNode(n, l, r) + From 75e83e6e1a6a851ecdf0c947c530e2d1ed8c15f9 Mon Sep 17 00:00:00 2001 From: Brian Strauch Date: Sun, 11 Oct 2020 17:13:01 -0500 Subject: [PATCH 296/357] 0101 --- LeetCode/0101_Symmetric_Tree.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/0101_Symmetric_Tree.py diff --git a/LeetCode/0101_Symmetric_Tree.py b/LeetCode/0101_Symmetric_Tree.py new file mode 100644 index 0000000..6ee51ea --- /dev/null +++ b/LeetCode/0101_Symmetric_Tree.py @@ -0,0 +1,19 @@ +# 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 isSymmetric(self, root: TreeNode) -> bool: + if root == None: + return True + + return self.isMirror(root.left, root.right) + + + def isMirror(self, a: TreeNode, b: TreeNode) -> bool: + if (a and b) and (a.val == b.val): + return self.isMirror(a.left, b.right) and self.isMirror(a.right, b.left) + + return a == None and b == None From f1cd4407ab608fb575ab9e2b4418c05000b1f456 Mon Sep 17 00:00:00 2001 From: Brian Strauch Date: Sun, 11 Oct 2020 17:30:30 -0500 Subject: [PATCH 297/357] 0107 --- ...07_Binary_Tree_Level_Order_Traversal_II.py | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 LeetCode/0107_Binary_Tree_Level_Order_Traversal_II.py diff --git a/LeetCode/0107_Binary_Tree_Level_Order_Traversal_II.py b/LeetCode/0107_Binary_Tree_Level_Order_Traversal_II.py new file mode 100644 index 0000000..0d2e142 --- /dev/null +++ b/LeetCode/0107_Binary_Tree_Level_Order_Traversal_II.py @@ -0,0 +1,27 @@ +# 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 levelOrderBottom(self, root: TreeNode) -> List[List[int]]: + q = [] + t = [] + + if root: + q.append((0, root)) + + while len(q) > 0: + level, curr = q.pop(0) + + if level >= len(t): + t.append([]) + t[level].append(curr.val) + + if curr.left: + q.append((level + 1, curr.left)) + if curr.right: + q.append((level + 1, curr.right)) + + return reversed(t) From 43b6c6968fbe5fdcdd28ca8f83bd198076abbd8c Mon Sep 17 00:00:00 2001 From: Brian Strauch Date: Sun, 11 Oct 2020 17:37:25 -0500 Subject: [PATCH 298/357] 0103 --- ...inary_Tree_Zigzag_Level_Order_Traversal.py | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 LeetCode/0103_Binary_Tree_Zigzag_Level_Order_Traversal.py diff --git a/LeetCode/0103_Binary_Tree_Zigzag_Level_Order_Traversal.py b/LeetCode/0103_Binary_Tree_Zigzag_Level_Order_Traversal.py new file mode 100644 index 0000000..09d4ed5 --- /dev/null +++ b/LeetCode/0103_Binary_Tree_Zigzag_Level_Order_Traversal.py @@ -0,0 +1,31 @@ +# 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 zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]: + q = [] + t = [] + + if root: + q.append((0, root)) + + while len(q) > 0: + level, curr = q.pop(0) + + if level >= len(t): + t.append([]) + t[level].append(curr.val) + + if curr.left: + q.append((level + 1, curr.left)) + if curr.right: + q.append((level + 1, curr.right)) + + for i in range(len(t)): + if i % 2 == 1: + t[i] = reversed(t[i]) + return t + From fee224157f4ee3c0e702fc23403ddb9a8b510c76 Mon Sep 17 00:00:00 2001 From: Satyam Yadav <72488628+SatyamYadav-cmd@users.noreply.github.com> Date: Mon, 12 Oct 2020 10:52:11 +0530 Subject: [PATCH 299/357] Create 0137_Single_Number_II.py --- LeetCode/0137_Single_Number_II.py | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 LeetCode/0137_Single_Number_II.py diff --git a/LeetCode/0137_Single_Number_II.py b/LeetCode/0137_Single_Number_II.py new file mode 100644 index 0000000..7792dcf --- /dev/null +++ b/LeetCode/0137_Single_Number_II.py @@ -0,0 +1,6 @@ +class Solution: + def singleNumber(self, nums: List[int]) -> int: + used=[] + for x in nums: + if nums.count(x)==1: + return x From 857eacfe8a7e81ae0ca318f5eb09c3e844411be5 Mon Sep 17 00:00:00 2001 From: RgnDunes Date: Mon, 12 Oct 2020 11:03:38 +0530 Subject: [PATCH 300/357] Added Binary Tree Preorder and Postorder Traversal Code --- .../0144_Binary_Tree_Preorder_Traversal.py | 16 ++++++++++ .../0145_Binary_Tree_Postorder_Traversal.py | 31 +++++++++++++++++++ PULL_REQUEST_TEMPLATE.md | 12 +++---- 3 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 LeetCode/0144_Binary_Tree_Preorder_Traversal.py create mode 100644 LeetCode/0145_Binary_Tree_Postorder_Traversal.py diff --git a/LeetCode/0144_Binary_Tree_Preorder_Traversal.py b/LeetCode/0144_Binary_Tree_Preorder_Traversal.py new file mode 100644 index 0000000..05b735d --- /dev/null +++ b/LeetCode/0144_Binary_Tree_Preorder_Traversal.py @@ -0,0 +1,16 @@ +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right +class Solution: + def preorderTraversal(self, root: TreeNode) -> List[int]: + self.ans=[] + def preorder(root): + if root is None: + return + self.ans.append(root.val) + preorder(root.left) + preorder(root.right) + preorder(root) + return self.ans \ No newline at end of file diff --git a/LeetCode/0145_Binary_Tree_Postorder_Traversal.py b/LeetCode/0145_Binary_Tree_Postorder_Traversal.py new file mode 100644 index 0000000..9442cde --- /dev/null +++ b/LeetCode/0145_Binary_Tree_Postorder_Traversal.py @@ -0,0 +1,31 @@ +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 postorderTraversal(self, root: TreeNode) -> List[int]: + postorder = [] + s = [] + v = set() + if root: + s.append(root) + while s: + r = s[-1] + if r not in v: + if r.right: + s.append(r.right) + v.add(r) + + if r.left: + s.append(r.left) + v.add(r) + + if r.right is None and r.left is None: + r = s.pop() + postorder.append(r.val) + else: + r = s.pop() + postorder.append(r.val) + + return postorder \ No newline at end of file diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index d64c54e..d0a0599 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -2,12 +2,12 @@ ### All Submissions: -* [ ] I have read the CONTRIBUTING document. -* [ ] My code is written in **Python3** and is ending with _.py_ -* [ ] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? -* [ ] I have checked that my submission does pass the test on LeetCode.com -* [ ] Does your filename follow the naming Conventions? -* [ ] Have you linked your PR to an Issue? +- [x] I have read the CONTRIBUTING document. +- [x] My code is written in **Python3** and is ending with _.py_ +- [x] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? +- [x] I have checked that my submission does pass the test on LeetCode.com +- [x] Does your filename follow the naming Conventions? +- [x] Have you linked your PR to an Issue? **Closing issues** From 249be6e43ef02df52e2f36599b7cff2c3c9f049a Mon Sep 17 00:00:00 2001 From: Cheryl An-Yiing Kong <“27339352+cakon2@users.noreply.github.com”> Date: Mon, 12 Oct 2020 14:33:59 +0900 Subject: [PATCH 301/357] Add solution file for 1351 --- .../1351_Count_Negative_Numbers_in_Sorted_Matrix.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/1351_Count_Negative_Numbers_in_Sorted_Matrix.py diff --git a/LeetCode/1351_Count_Negative_Numbers_in_Sorted_Matrix.py b/LeetCode/1351_Count_Negative_Numbers_in_Sorted_Matrix.py new file mode 100644 index 0000000..54b9947 --- /dev/null +++ b/LeetCode/1351_Count_Negative_Numbers_in_Sorted_Matrix.py @@ -0,0 +1,11 @@ +class Solution: + def countNegatives(self, grid: List[List[int]]) -> int: + count = 0 + for row in grid: + for index in range(len(row)-1, -1, -1): + if row[index] < 0: + count += 1 + else: + break + + return count \ No newline at end of file From 4017517cde5a7e8a6dae53e0706de59d40b5f0a5 Mon Sep 17 00:00:00 2001 From: Suhrid Mathur Date: Mon, 12 Oct 2020 11:59:29 +0530 Subject: [PATCH 302/357] Solution added for #1470 Shuffle The Array --- LeetCode/1470_Shuffle_The_Array | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/1470_Shuffle_The_Array diff --git a/LeetCode/1470_Shuffle_The_Array b/LeetCode/1470_Shuffle_The_Array new file mode 100644 index 0000000..0892eb7 --- /dev/null +++ b/LeetCode/1470_Shuffle_The_Array @@ -0,0 +1,13 @@ +class Solution: + def shuffle(self, nums: List[int], n: int) -> List[int]: + shuffled_list = [0]*(2*n) + left_index = 0 + right_index = n + for index in range(0, 2*n): + if index%2 == 0: + shuffled_list[index] = nums[left_index] + left_index += 1 + else: + shuffled_list[index] = nums[right_index] + right_index += 1 + return shuffled_list From cfe739f04069b5c81a86ea365ca9abad419eab6d Mon Sep 17 00:00:00 2001 From: Abhishek Tiwari <63968306+AbhishekTiwari07@users.noreply.github.com> Date: Mon, 12 Oct 2020 12:31:25 +0530 Subject: [PATCH 303/357] Create 0119_Pascal_Triangle2.py --- LeetCode/0119_Pascal_Triangle2.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0119_Pascal_Triangle2.py diff --git a/LeetCode/0119_Pascal_Triangle2.py b/LeetCode/0119_Pascal_Triangle2.py new file mode 100644 index 0000000..02171f9 --- /dev/null +++ b/LeetCode/0119_Pascal_Triangle2.py @@ -0,0 +1,20 @@ +class Solution(object): + def getRow(self, rowIndex): + """ + :type rowIndex: int + :rtype: List[int] + """ + + if rowIndex == 0: + return [1] + if rowIndex == 1: + return [1,1] + + init = [1,1] + for i in range(0, rowIndex-1): + new_vec = [] + for v in range(0, len(init)-1): + new_vec.append(init[v] + init[v+1]) + new_vec = [1] + new_vec + [1] + init = new_vec + return init From 9789939b586bcad58e7f492f8467e5f88ad1b967 Mon Sep 17 00:00:00 2001 From: javmarina Date: Mon, 12 Oct 2020 11:46:40 +0200 Subject: [PATCH 304/357] Added solution for problem 203 --- LeetCode/0203_Remove_Linked_List_Elements.py | 25 ++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 LeetCode/0203_Remove_Linked_List_Elements.py diff --git a/LeetCode/0203_Remove_Linked_List_Elements.py b/LeetCode/0203_Remove_Linked_List_Elements.py new file mode 100644 index 0000000..9f8febb --- /dev/null +++ b/LeetCode/0203_Remove_Linked_List_Elements.py @@ -0,0 +1,25 @@ +# 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 removeElements(self, head, val): + """ + :type head: ListNode + :type val: int + :rtype: ListNode + """ + while head: + if head.val == val: + head = head.next + else: + break + currentNode = head + while currentNode: + while currentNode.next and currentNode.next.val == val: + currentNode.next = currentNode.next.next + + currentNode = currentNode.next + return head From 8eb8fa7967e9ff285d9dd61f5c72069675350161 Mon Sep 17 00:00:00 2001 From: javmarina Date: Mon, 12 Oct 2020 12:17:59 +0200 Subject: [PATCH 305/357] Added solution for 1518 --- LeetCode/1518_Water_Bottles.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 LeetCode/1518_Water_Bottles.py diff --git a/LeetCode/1518_Water_Bottles.py b/LeetCode/1518_Water_Bottles.py new file mode 100644 index 0000000..d6544e5 --- /dev/null +++ b/LeetCode/1518_Water_Bottles.py @@ -0,0 +1,26 @@ +class Solution(object): + def numWaterBottles(self, numBottles, numExchange): + """ + :type numBottles: int + :type numExchange: int + :rtype: int + """ + full = numBottles + empty = 0 + drank = 0 + + while True: + # 1. Drink + empty += full + drank += full + full = 0 + + # 2. Exchange + while empty >= numExchange: + empty -= numExchange + full += 1 + + if not full: + break + + return drank From 1b5b373652c8a18a3f8a8ed0b3c0b9917326b83f Mon Sep 17 00:00:00 2001 From: polo-sec Date: Mon, 12 Oct 2020 11:34:24 +0000 Subject: [PATCH 306/357] Implemented challenge number 0617, Merge Two Binary Trees --- LeetCode/0617_Merge_Two_Binary_Trees.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0617_Merge_Two_Binary_Trees.py diff --git a/LeetCode/0617_Merge_Two_Binary_Trees.py b/LeetCode/0617_Merge_Two_Binary_Trees.py new file mode 100644 index 0000000..feb8819 --- /dev/null +++ b/LeetCode/0617_Merge_Two_Binary_Trees.py @@ -0,0 +1,20 @@ +#Definition for a binary tree node. +#class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None +class Solution: + def mergeTrees(self, t1, t2): + """ + :type t1: TreeNode + :type t2: TreeNode + :rtype: TreeNode + """ + if t1 is None: + return t2 + if t2 is not None: + t1.val += t2.val + t1.left = self.mergeTrees(t1.left, t2.left) + t1.right = self.mergeTrees(t1.right, t2.right) + return t1 From d10ecdd1ff8280bfdb41a1f735c29c5433ba0872 Mon Sep 17 00:00:00 2001 From: aman1833 <33142696+aman1833@users.noreply.github.com> Date: Mon, 12 Oct 2020 20:07:32 +0530 Subject: [PATCH 307/357] Create 997_Find_The_Town_Judge.py --- LeetCode/997_Find_The_Town_Judge.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 LeetCode/997_Find_The_Town_Judge.py diff --git a/LeetCode/997_Find_The_Town_Judge.py b/LeetCode/997_Find_The_Town_Judge.py new file mode 100644 index 0000000..63b8db5 --- /dev/null +++ b/LeetCode/997_Find_The_Town_Judge.py @@ -0,0 +1,19 @@ +def findJudge(self, N: int, trust: List[List[int]]) -> int: + if N==1: + return 1 + d1={} + d2={} + for i, j in trust: + if j in d1: + d1[j]+=1 + else: + d1[j]=1 + if i in d2: + d2[i]+=1 + else: + d2[i]=1 + for i,j in d1.items(): + if j==N-1: + if i not in d2: + return i + return -1 From b9c58b1f081b29bf0113cdc94b927a0ed456a867 Mon Sep 17 00:00:00 2001 From: aman1833 <33142696+aman1833@users.noreply.github.com> Date: Mon, 12 Oct 2020 20:46:12 +0530 Subject: [PATCH 308/357] Delete fast_fibonacci.py --- fast_fibonacci.py | 32 -------------------------------- 1 file changed, 32 deletions(-) delete mode 100644 fast_fibonacci.py diff --git a/fast_fibonacci.py b/fast_fibonacci.py deleted file mode 100644 index e7bdfac..0000000 --- a/fast_fibonacci.py +++ /dev/null @@ -1,32 +0,0 @@ -from __future__ import annotations - -import sys - - -def fibonacci(n: int) -> int: - """ - return F(n) - >>> [fibonacci(i) for i in range(13)] - [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144] - """ - if n < 0: - raise ValueError("Negative arguments are not supported") - return _fib(n)[0] - - -# returns (F(n), F(n-1)) -def _fib(n: int) -> tuple[int, int]: - if n == 0: # (F(0), F(1)) - return (0, 1) - - # F(2n) = F(n)[2F(n+1) − F(n)] - # F(2n+1) = F(n+1)^2+F(n)^2 - a, b = _fib(n // 2) - c = a * (b * 2 - a) - d = a * a + b * b - return (d, c + d) if n % 2 else (c, d) - - -if __name__ == "__main__": - n = int(sys.argv[1]) - print(f"fibonacci({n}) is {fibonacci(n)}") From 3cb5c29f3043db472ac037f519a2b930380268fc Mon Sep 17 00:00:00 2001 From: aman1833 <33142696+aman1833@users.noreply.github.com> Date: Mon, 12 Oct 2020 20:49:48 +0530 Subject: [PATCH 309/357] Update 997_Find_The_Town_Judge.py --- LeetCode/997_Find_The_Town_Judge.py | 38 +++++++++++++++-------------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/LeetCode/997_Find_The_Town_Judge.py b/LeetCode/997_Find_The_Town_Judge.py index 63b8db5..37e928f 100644 --- a/LeetCode/997_Find_The_Town_Judge.py +++ b/LeetCode/997_Find_The_Town_Judge.py @@ -1,19 +1,21 @@ -def findJudge(self, N: int, trust: List[List[int]]) -> int: - if N==1: - return 1 - d1={} - d2={} - for i, j in trust: - if j in d1: - d1[j]+=1 - else: - d1[j]=1 - if i in d2: - d2[i]+=1 - else: - d2[i]=1 - for i,j in d1.items(): - if j==N-1: - if i not in d2: - return i +class Solution: + def findJudge(self, N: int, trust: List[List[int]]) -> int: + m=len(trust) + if 1==N: + if 0==m: + return 1 + tmp={} + dic={} + for i in range(m): + tmp[trust[i][0]]=1 + for i in range(m): + if trust[i][1] not in tmp: + if trust[i][1] not in dic: + dic[trust[i][1]]=1 + else: + dic[trust[i][1]]+=1 + for key in dic: + if N-1==dic[key]: + return key return -1 + From a7e1bc083a068f7e304426fb3ea4825ebecb4ea6 Mon Sep 17 00:00:00 2001 From: Ahkam Naseek Date: Mon, 12 Oct 2020 21:03:40 +0530 Subject: [PATCH 310/357] Fixed issue #756 Count Complete tree nodes --- LeetCode/0222_Count_Complete_Tree_Nodes.py | 25 ++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 LeetCode/0222_Count_Complete_Tree_Nodes.py diff --git a/LeetCode/0222_Count_Complete_Tree_Nodes.py b/LeetCode/0222_Count_Complete_Tree_Nodes.py new file mode 100644 index 0000000..eb633a0 --- /dev/null +++ b/LeetCode/0222_Count_Complete_Tree_Nodes.py @@ -0,0 +1,25 @@ +# 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 countNodes(self, root: TreeNode) -> int: + + if root == None: return 0 + right, left = root, root + h_l , h_r = 0, 0 + + while left != None: + h_l +=1 + left = left.left + + while right != None: + h_r +=1 + right = right.right + + + if (h_l == h_r) : return(1 << h_l) -1 + + return 1+ self.countNodes(root.left) + self.countNodes(root.right) From 1557ee6b786d07e5a937c1faf7f7d35634d0c60e Mon Sep 17 00:00:00 2001 From: RgnDunes Date: Tue, 13 Oct 2020 01:00:26 +0530 Subject: [PATCH 311/357] Made necessary changes --- .../0145_Binary_Tree_Postorder_Traversal.py | 31 ------------------- PULL_REQUEST_TEMPLATE.md | 12 +++---- 2 files changed, 6 insertions(+), 37 deletions(-) delete mode 100644 LeetCode/0145_Binary_Tree_Postorder_Traversal.py diff --git a/LeetCode/0145_Binary_Tree_Postorder_Traversal.py b/LeetCode/0145_Binary_Tree_Postorder_Traversal.py deleted file mode 100644 index 9442cde..0000000 --- a/LeetCode/0145_Binary_Tree_Postorder_Traversal.py +++ /dev/null @@ -1,31 +0,0 @@ -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 postorderTraversal(self, root: TreeNode) -> List[int]: - postorder = [] - s = [] - v = set() - if root: - s.append(root) - while s: - r = s[-1] - if r not in v: - if r.right: - s.append(r.right) - v.add(r) - - if r.left: - s.append(r.left) - v.add(r) - - if r.right is None and r.left is None: - r = s.pop() - postorder.append(r.val) - else: - r = s.pop() - postorder.append(r.val) - - return postorder \ No newline at end of file diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index d0a0599..74ca7c3 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -2,12 +2,12 @@ ### All Submissions: -- [x] I have read the CONTRIBUTING document. -- [x] My code is written in **Python3** and is ending with _.py_ -- [x] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? -- [x] I have checked that my submission does pass the test on LeetCode.com -- [x] Does your filename follow the naming Conventions? -- [x] Have you linked your PR to an Issue? +- [ ] I have read the CONTRIBUTING document. +- [ ] My code is written in **Python3** and is ending with _.py_ +- [ ] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? +- [ ] I have checked that my submission does pass the test on LeetCode.com +- [ ] Does your filename follow the naming Conventions? +- [ ] Have you linked your PR to an Issue? **Closing issues** From cc865e3c00e3193269959cb877bc93613db03bd8 Mon Sep 17 00:00:00 2001 From: Divyansh Singh <61814592+RgnDunes@users.noreply.github.com> Date: Tue, 13 Oct 2020 03:03:39 +0530 Subject: [PATCH 312/357] Copied and pasted original contents in PULL_REQUEST_TEMPLATE.md --- PULL_REQUEST_TEMPLATE.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/PULL_REQUEST_TEMPLATE.md b/PULL_REQUEST_TEMPLATE.md index 74ca7c3..d64c54e 100644 --- a/PULL_REQUEST_TEMPLATE.md +++ b/PULL_REQUEST_TEMPLATE.md @@ -2,12 +2,12 @@ ### All Submissions: -- [ ] I have read the CONTRIBUTING document. -- [ ] My code is written in **Python3** and is ending with _.py_ -- [ ] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? -- [ ] I have checked that my submission does pass the test on LeetCode.com -- [ ] Does your filename follow the naming Conventions? -- [ ] Have you linked your PR to an Issue? +* [ ] I have read the CONTRIBUTING document. +* [ ] My code is written in **Python3** and is ending with _.py_ +* [ ] Have you checked to ensure there aren't other open [Pull Requests](../../../pulls) for the same update/change? +* [ ] I have checked that my submission does pass the test on LeetCode.com +* [ ] Does your filename follow the naming Conventions? +* [ ] Have you linked your PR to an Issue? **Closing issues** From 61f4604120485846939ef50efcd03d4b09e4a7c1 Mon Sep 17 00:00:00 2001 From: Cheryl An-Yiing Kong <“27339352+cakon2@users.noreply.github.com”> Date: Tue, 13 Oct 2020 09:42:06 +0900 Subject: [PATCH 313/357] Add Group_People_Given_Group_Size_They_Belong_To.py --- ...oup_People_Given_the_Group_Size_They_Belong_To.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 LeetCode/1282_Group_People_Given_the_Group_Size_They_Belong_To.py diff --git a/LeetCode/1282_Group_People_Given_the_Group_Size_They_Belong_To.py b/LeetCode/1282_Group_People_Given_the_Group_Size_They_Belong_To.py new file mode 100644 index 0000000..a257644 --- /dev/null +++ b/LeetCode/1282_Group_People_Given_the_Group_Size_They_Belong_To.py @@ -0,0 +1,12 @@ +class Solution: + def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]: + maxGroupSize= max(groupSizes) + groups = [[] for i in range(maxGroupSize)] + + for i, p in enumerate(groupSizes): + groups[p-1].append(i) + if len(groups[p-1]) == p: + groups.append(groups[p-1]) + groups[p-1] = [] + + return groups[maxGroupSize:] From c6c3c7c7f351a229db4835e2d140f4c5e0b6c972 Mon Sep 17 00:00:00 2001 From: Vikram Bais Date: Tue, 13 Oct 2020 15:25:04 +0530 Subject: [PATCH 314/357] added python code for Reverse Words in a String code for Reverse Words in a String --- LeetCode/0151_Reverse_Words_in_a_String.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/0151_Reverse_Words_in_a_String.py diff --git a/LeetCode/0151_Reverse_Words_in_a_String.py b/LeetCode/0151_Reverse_Words_in_a_String.py new file mode 100644 index 0000000..6e624f4 --- /dev/null +++ b/LeetCode/0151_Reverse_Words_in_a_String.py @@ -0,0 +1,10 @@ +class Solution: + def reverseWords(self, s): + list_of_string = s.split(' ') + #appliying filter function to remove extraspaces from list + new_list = list(filter(lambda x : True if (x!="") else False, list_of_string)) + #taking reverse of output list + new_list.reverse() + #joining the elements if list + final_string = " ".join(str(k) for k in new_list) + return final_string From c1806b462a87fd69f3721d949cd913813de5562b Mon Sep 17 00:00:00 2001 From: "Dev.ruji" <43924465+devruji@users.noreply.github.com> Date: Tue, 13 Oct 2020 17:52:11 +0700 Subject: [PATCH 315/357] Create 1556_Thousand_Separator.py --- LeetCode/1556_Thousand_Separator.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 LeetCode/1556_Thousand_Separator.py diff --git a/LeetCode/1556_Thousand_Separator.py b/LeetCode/1556_Thousand_Separator.py new file mode 100644 index 0000000..23310d2 --- /dev/null +++ b/LeetCode/1556_Thousand_Separator.py @@ -0,0 +1,11 @@ +class Solution: + def thousandSeparator(self, n: int) -> str: + num = n + ans = f'{num:,}' + return ans + + +if __name__ == '__main__': + x = Solution() + answer = x.thousandSeparator(2**31) + print(answer) From f2a83e4363c313a314ab75d58a213e6fba7b67fd Mon Sep 17 00:00:00 2001 From: "Dev.ruji" <43924465+devruji@users.noreply.github.com> Date: Tue, 13 Oct 2020 18:08:44 +0700 Subject: [PATCH 316/357] Changed comma to dot --- LeetCode/1556_Thousand_Separator.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/LeetCode/1556_Thousand_Separator.py b/LeetCode/1556_Thousand_Separator.py index 23310d2..b7899e8 100644 --- a/LeetCode/1556_Thousand_Separator.py +++ b/LeetCode/1556_Thousand_Separator.py @@ -1,11 +1,11 @@ class Solution: def thousandSeparator(self, n: int) -> str: num = n - ans = f'{num:,}' + ans = f'{num:,}'.replace(',', '.') return ans if __name__ == '__main__': x = Solution() - answer = x.thousandSeparator(2**31) + answer = x.thousandSeparator(1234) print(answer) From dd84b559af11ac1924ef9d5256f63493cebd11c9 Mon Sep 17 00:00:00 2001 From: "Dev.ruji" <43924465+devruji@users.noreply.github.com> Date: Tue, 13 Oct 2020 18:09:03 +0700 Subject: [PATCH 317/357] Changed comma to dot --- LeetCode/1556_Thousand_Separator.py | 6 ------ 1 file changed, 6 deletions(-) diff --git a/LeetCode/1556_Thousand_Separator.py b/LeetCode/1556_Thousand_Separator.py index b7899e8..ef46674 100644 --- a/LeetCode/1556_Thousand_Separator.py +++ b/LeetCode/1556_Thousand_Separator.py @@ -3,9 +3,3 @@ def thousandSeparator(self, n: int) -> str: num = n ans = f'{num:,}'.replace(',', '.') return ans - - -if __name__ == '__main__': - x = Solution() - answer = x.thousandSeparator(1234) - print(answer) From ea2f83b643413c057a1283ec1c85846c8f36997c Mon Sep 17 00:00:00 2001 From: Suhrid Mathur Date: Tue, 13 Oct 2020 18:08:28 +0530 Subject: [PATCH 318/357] Rename 1470_Shuffle_The_Array to 1470_Shuffle_The_Array.py --- LeetCode/{1470_Shuffle_The_Array => 1470_Shuffle_The_Array.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{1470_Shuffle_The_Array => 1470_Shuffle_The_Array.py} (100%) diff --git a/LeetCode/1470_Shuffle_The_Array b/LeetCode/1470_Shuffle_The_Array.py similarity index 100% rename from LeetCode/1470_Shuffle_The_Array rename to LeetCode/1470_Shuffle_The_Array.py From fb0b02dc2c5ffbc81c5b961e25fa81074358c7b2 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Wed, 28 Oct 2020 08:57:10 +0100 Subject: [PATCH 319/357] Delete 0006_ZigZag_Conversion.py --- LeetCode/0006_ZigZag_Conversion.py | 176 ----------------------------- 1 file changed, 176 deletions(-) delete mode 100644 LeetCode/0006_ZigZag_Conversion.py diff --git a/LeetCode/0006_ZigZag_Conversion.py b/LeetCode/0006_ZigZag_Conversion.py deleted file mode 100644 index 2d7de9c..0000000 --- a/LeetCode/0006_ZigZag_Conversion.py +++ /dev/null @@ -1,176 +0,0 @@ -''' -## Description of the Problem - -The string "PAYPALISHIRING" is written in a zigzag pattern -on a given number of rows like this: - -(you may want to display this pattern in a fixed font for better legibility) - -``` -P A H N -A P L S I I G -Y I R -``` - -And then read line by line: "PAHNAPLSIIGYIR" - -Write the code that will take a string and make this conversion given a number of rows: - -``` -string convert(string s, int numRows); -``` - -## Example 1: -``` -Input: s = "PAYPALISHIRING", numRows = 3 -Output: "PAHNAPLSIIGYIR" -``` - -## Example 2: -``` -Input: s = "PAYPALISHIRING", numRows = 4 -Output: "PINALSIGYAHRPI" -``` - -## Explanation: - -``` -P I N -A L S I G -Y A H R -P I -``` - -## Example 3: - -``` -Input: s = "A", numRows = 1 -Output: "A" -``` - -## Constraints: - -- 1 <= s.length <= 1000 -- s consists of English letters (lower-case and upper-case), ',' and '.'. -- 1 <= numRows <= 1000 - - -## Link To The LeetCode Problem -[6. ZigZag Conversion](https://leetcode.com/problems/zigzag-conversion/) -''' - - -class Solution: - s = '' - numRows = 1 - - # transitionColumns is the number of extra columns needed to get the - # text from the bottom row back to the top row - def zigZagTransitionColumns(self) -> int: - transitionColumns = self.numRows - 2 - if transitionColumns < 0: - transitionColumns = 0 - return transitionColumns - - # patternColumns is the number of columns taken up by each full pattern - # the first column is downward, and then we need columns for the upward - def zigZagPatternColumns(self) -> int: - return 1 + self.zigZagTransitionColumns() - - # patternSize is the number of elements in each repeated pattern - def zigZagPatternLength(self) -> int: - # there are numRows letters in the first column - # followed by one letter per transitionColumn - return self.numRows + self.zigZagTransitionColumns() - - # computes the number of total columns needed by this string - def zigZagMatrixColumns(self) -> int: - patternLength = self.zigZagPatternLength() - fullPatternCount = len(self.s) // patternLength - columns = self.zigZagPatternColumns() * fullPatternCount - - # how many extra letters are there? - extraLetters = len(self.s) - (patternLength * fullPatternCount) - if extraLetters > 0: - columns += 1 - if extraLetters > self.numRows: - columns += extraLetters - self.numRows - return columns - - # converts the index of the input string to the address - # in the output matrix - def zigZagMatrixIndex(self, elementIndex: int) -> tuple: - patternLength = self.zigZagPatternLength() - - # which pattern repetition holds this element (zero-based) - patternOfElement = elementIndex // patternLength - - # where in the pattern repetition is this element - indexInPattern = elementIndex % patternLength - - matrixRow = indexInPattern - matrixColumn = patternOfElement * self.zigZagPatternColumns() - bottomRowIndex = self.numRows - 1 - - # correct the row and column numbers (remember these are zero-based) - if indexInPattern > bottomRowIndex: - extraColumns = indexInPattern - bottomRowIndex - matrixColumn = matrixColumn + extraColumns - - # row decrements by 1 for each extra column - matrixRow = bottomRowIndex - extraColumns - - # i, j - return (matrixColumn, matrixRow) - - # creates a zigzag matrix - def generateZigZagMatrix(self) -> list: - matrix = [] - for i in range(self.zigZagMatrixColumns()): - matrix.append([]) - for j in range(self.numRows): - matrix[i].append('') - for elementIndex, char in enumerate(self.s): - i, j = self.zigZagMatrixIndex(elementIndex) - matrix[i][j] = char - return matrix - - # prints out the zigzag matrix - def generateZigZagString(self, nullChar: str = ' ', lineEndings: str = '\n'): - lines = [] - matrix = self.generateZigZagMatrix() - for j in range(self.numRows): - rowChars = [] - for i in range(self.zigZagMatrixColumns()): - char = matrix[i][j] - rowChars.append(char if char != '' else nullChar) - lines.append(''.join(rowChars)) - return lineEndings.join(lines) - - def zigZagConversion(self, s: str, numRows: int, asMatrix: bool = False) -> str: - ''' - The ZigZag format fills all available rows vertically in the first column, - then, fills rows "diagonally" on the way back up to the top row of a subsequent - column, and then repeats. - - The input string is the normal content. - ''' - self.s = s - self.numRows = numRows - if asMatrix: - return self.generateZigZagString(nullChar=' ', lineEndings='\n') - else: - return self.generateZigZagString(nullChar='', lineEndings='') - - -# testing -if __name__ == '__main__': - toConvert = 'PAYPALISHIRING' - converter = Solution() - for i in range(4): - print(f'\nENCODING: {toConvert} with {i+1} rows') - print('\n-- matrix -----------------') - print(converter.zigZagConversion(toConvert, numRows=i+1, asMatrix=True)) - print('\n-- line -------------------') - print(converter.zigZagConversion(toConvert, numRows=i+1, asMatrix=False)) - print() From 86cedd3b8bd3c695ca19f19b5f55d3ab66056c9b Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Wed, 28 Oct 2020 09:06:23 +0100 Subject: [PATCH 320/357] Delete 0092_Decode_Ways.py --- LeetCode/0092_Decode_Ways.py | 40 ------------------------------------ 1 file changed, 40 deletions(-) delete mode 100644 LeetCode/0092_Decode_Ways.py diff --git a/LeetCode/0092_Decode_Ways.py b/LeetCode/0092_Decode_Ways.py deleted file mode 100644 index 0f0c382..0000000 --- a/LeetCode/0092_Decode_Ways.py +++ /dev/null @@ -1,40 +0,0 @@ -''' -Problem:- -A message containing letters from A-Z is being encoded to numbers using the following mapping: - -'A' -> 1 -'B' -> 2 -... -'Z' -> 26 -Given a non-empty string containing only digits, determine the total number of ways to decode it. - -The answer is guaranteed to fit in a 32-bit integer. - -Example 1: - -Input: s = "12" -Output: 2 -Explanation: It could be decoded as "AB" (1 2) or "L" (12). - -Example 2: - -Input: s = "226" -Output: 3 -Explanation: It could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6). -''' - -class Solution: - def numDecodings(self, s: str) -> int: - @lru_cache(None) - def dp(i): - if i == len(s): - return 1 - ans = 0 - if s[i] != '0': - ans += dp(i+1) - if s[i] == '1' and i+1< len(s): - ans += dp(i+2) - if s[i] == '2' and i+1 < len(s) and s[i+1] <= '6': - ans += dp(i+2) - return ans - return dp(0) From 3774432b7a896e099a0bc2b4ec63b8bf20e7f4b5 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Wed, 28 Oct 2020 09:46:14 +0100 Subject: [PATCH 321/357] Delete 0046_Permutations.py --- LeetCode/0046_Permutations.py | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 LeetCode/0046_Permutations.py diff --git a/LeetCode/0046_Permutations.py b/LeetCode/0046_Permutations.py deleted file mode 100644 index d0ba022..0000000 --- a/LeetCode/0046_Permutations.py +++ /dev/null @@ -1,12 +0,0 @@ -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 68dea523387b7b3a794e5ef38af8a6548bf08cb6 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Wed, 28 Oct 2020 10:12:11 +0100 Subject: [PATCH 322/357] Delete 0067_Add_Binary.py --- LeetCode/0067_Add_Binary.py | 12 ------------ 1 file changed, 12 deletions(-) delete mode 100644 LeetCode/0067_Add_Binary.py diff --git a/LeetCode/0067_Add_Binary.py b/LeetCode/0067_Add_Binary.py deleted file mode 100644 index 7277674..0000000 --- a/LeetCode/0067_Add_Binary.py +++ /dev/null @@ -1,12 +0,0 @@ -# Problem name : Add Binary -# Problem link : https://leetcode.com/problems/add-binary/ -# Contributor : Herumb Shandilya - -class Solution: - def addBinary(self, a: str, b: str) -> str: - l_a = [int(x) for x in list(a)] - l_b = [int(x) for x in list(b)] - num_a = sum([l_a[i]*(2**(len(l_a)-i-1)) for i in range(len(l_a))]) - num_b = sum([l_b[i]*(2**(len(l_b)-i-1)) for i in range(len(l_b))]) - s = num_a + num_b - return bin(s)[2:] From d730a5a8aceaed2f16cd377082417f1f23fc4430 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Thu, 29 Oct 2020 10:28:46 +0100 Subject: [PATCH 323/357] Create 0260_Single_Number_III.py --- LeetCode/0260_Single_Number_III.py | 7 +++++++ 1 file changed, 7 insertions(+) create mode 100644 LeetCode/0260_Single_Number_III.py diff --git a/LeetCode/0260_Single_Number_III.py b/LeetCode/0260_Single_Number_III.py new file mode 100644 index 0000000..065d8e6 --- /dev/null +++ b/LeetCode/0260_Single_Number_III.py @@ -0,0 +1,7 @@ +class Solution: + def singleNumber(self, N: List[int]) -> int: + L, d = len(N), set() + for n in N: + if n in d: d.remove(n) + else: d.add(n) + return d \ No newline at end of file From 5ecf1259995cba9f6a33fb923197a67162d00894 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Thu, 29 Oct 2020 10:29:27 +0100 Subject: [PATCH 324/357] moved files to LeetCode Folder --- .DS_Store | Bin 8196 -> 0 bytes ...umbers_Are_Smaller_Than_the_Current_Number.py | 0 .../1588_SumOfAllOddLengthSubarrays.py | 0 3 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 .DS_Store rename 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py => LeetCode/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py (100%) rename 1588_SumOfAllOddLengthSubarrays.py => LeetCode/1588_SumOfAllOddLengthSubarrays.py (100%) diff --git a/.DS_Store b/.DS_Store deleted file mode 100644 index 2b814e5fb2bf3fee468e4839f097ac358da063b3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 8196 zcmeHMTWl0n7(U-pV1|h>t(A+i*)0W1u!iMg5izjrwrDTVhHYuNwVmA=Vd8XVnVH>! zO=C40jS%$38;$bdHKIO=w@$#T1@Iqot{Lh>zp*Q1`Au?xk&VSDN zFQ@-E-$lADuEhjK(n;m#o38N!tj-cS&%PJYS2 zoFOe_)J6zI2uwwQZy$-ZF@rw-jraGw<>X0sHD9z$&rhYkM{HKb>^XBKd7dIG^A-6( z?vOK>^EJQZWi+=>U79m>Bd@vLrtTl=H0&nJC>wUW+ot)3yN?@pI*vsKqOaw5o5o-3{v-hKFTIT2i-tS8wTw6DLRCc=N5d&z=i>7{WIRs}$qw?Rn}=fyDC4 zSpi9GY#fqHH$bA?7H?^7+p)8~PgP5vvCFVD-z*!Al)TrcF7PP*=7M8)xJH@M?k+f1 zX}~5;WkItFB{DX)Sys+`R9F{W$Fe#c&-6{l-qYh7M|`g1fhMSW_Ii%%XMiwP%EpHYGq+}+4Ri3WpoYlr?yA)3Wlwl z_QAdM9Bkiw*fddBpt5GRD|2Bkq# zb-ByZ@`fd*HYuAWwN>sei*&_gwX#)`dkW6L043vzxlFuKQoodX`ND0Q=eHLPo7U#3 zZLf*P_we~`x^C!_LvjS&}z&`U1XQp@9YnDg@8NxXfRAw&=kPhczy!_UbzpE=sOgy=KFv zEt%_dn8bh^nHZ2yuq$BQIIDt(K9R~|M<|IdBBya=rj4P_<(o(vk^M&Gy~h5+Y|O(VB#E~5XuuXCZ5EAa!cKHx7jo#t0rU}l^F&|^ zHi|e*Bp$*r9>WM8$Fn$26n+lR;}xRtt9T8k@DAR^X(IC(qVgyB6rT~9zrlC7G>N)x z6RC^K(^0pab8XA950Y-2@)O;n5o5Ci2#fjsziH;*|0Ad(1R@0f#|WUJG1r)(1ZR3x z^1F7DYClz8xZQ}5feSUsLo&S@*#75_T JK*(F9`5TA7SFiv8 diff --git a/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py b/LeetCode/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py similarity index 100% rename from 1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py rename to LeetCode/1365_How_Many_Numbers_Are_Smaller_Than_the_Current_Number.py diff --git a/1588_SumOfAllOddLengthSubarrays.py b/LeetCode/1588_SumOfAllOddLengthSubarrays.py similarity index 100% rename from 1588_SumOfAllOddLengthSubarrays.py rename to LeetCode/1588_SumOfAllOddLengthSubarrays.py From e07c949a958c9f76a699b9c5f3cdb9f43f0df855 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Thu, 29 Oct 2020 10:30:26 +0100 Subject: [PATCH 325/357] Delete 0001_Two_Sum.py --- LeetCode/0001_Two_Sum.py | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 LeetCode/0001_Two_Sum.py diff --git a/LeetCode/0001_Two_Sum.py b/LeetCode/0001_Two_Sum.py deleted file mode 100644 index 38a449c..0000000 --- a/LeetCode/0001_Two_Sum.py +++ /dev/null @@ -1,10 +0,0 @@ -class Solution(object): - def twoSum(self, nums, target): - if len(nums) <= 1: - return False - buff_dict = {} - for i in range(len(nums)): - if nums[i] in buff_dict: - return [buff_dict[nums[i]], i] - else: - buff_dict[target - nums[i]] = i \ No newline at end of file From 0e514d5a74e470ddfb1449a4448406a60a95c92d Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Thu, 29 Oct 2020 10:38:34 +0100 Subject: [PATCH 326/357] Update leetcodeChecker.yml --- .github/workflows/leetcodeChecker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/leetcodeChecker.yml b/.github/workflows/leetcodeChecker.yml index d1f7d96..2ca45a3 100644 --- a/.github/workflows/leetcodeChecker.yml +++ b/.github/workflows/leetcodeChecker.yml @@ -22,7 +22,7 @@ jobs: run: | python leetcodeChecker.py env: - GITHUB_ACCESS_TOKEN: ${{ github.token }} + GITHUB_ACCESS_TOKEN: ${{ github.TOKEN }} REPO_NAME: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }} LEETCODE_CSRF_TOKEN: ${{ secrets.LEETCODE_CSRF_TOKEN }} From 9b25f3c014a4cf60dbe56f48394c25703be54314 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1ty=C3=A1s=20Kiglics?= Date: Thu, 29 Oct 2020 11:33:23 +0100 Subject: [PATCH 327/357] Word search II solution --- LeetCode/0212_Word_search_II.py | 58 +++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 LeetCode/0212_Word_search_II.py diff --git a/LeetCode/0212_Word_search_II.py b/LeetCode/0212_Word_search_II.py new file mode 100644 index 0000000..b68f79d --- /dev/null +++ b/LeetCode/0212_Word_search_II.py @@ -0,0 +1,58 @@ +class Solution: + def neighbours(self, i): + n = [] + if i >= self.cols: + n.append(i-self.cols) + if i + self.cols < self.rows * self.cols: + n.append(i+self.cols) + if i % self.cols > 0: + n.append(i-1) + if i % self.cols < self.cols - 1: + n.append(i+1) + return n + + def search(self, s): + if len(self.words) == 0: + return False + l = 0 + r = len(self.words) - 1 + while l <= r-1: + c = (l+r)//2 + if self.words[c] < s: + l = c+1 + else: + r = c + if len(self.words[l]) < len(s): + return False + return self.words[l][:len(s)] == s + + def DFS(self, v, s): + if not self.search(s): + return + if s in self.words and s not in self.found: + self.found.append(s) + ne = self.neighbours(v) + for n in ne: + if self.used[n]: + continue + self.used[n] = True + self.DFS(n, s + self.board[n]) + self.used[n] = False + + + def findWords(self, board, words): + self.found = [] + self.words = sorted(words) + self.rows = len(board) + self.cols = len(board[0]) + self.board = [board[i][j] for i in range(len(board)) for j in range(len(board[0]))] + self.used = [False] * self.cols * self.rows + for i in range(len(self.board)): + self.used[i] = True + self.DFS(i, self.board[i]) + self.used[i] = False + return self.found + +# print(Solution().findWords([["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["b","c","d","e"],["f","g","h","i"],["j","k","l","m"],["n","o","p","q"],["r","s","t","u"],["v","w","x","y"],["z","z","z","z"]],["aaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaab","aaaaaaaaaaaaaaac","aaaaaaaaaaaaaaad","aaaaaaaaaaaaaaae","aaaaaaaaaaaaaaaf","aaaaaaaaaaaaaaag","aaaaaaaaaaaaaaah","aaaaaaaaaaaaaaai","aaaaaaaaaaaaaaaj","aaaaaaaaaaaaaaak","aaaaaaaaaaaaaaal","aaaaaaaaaaaaaaam","aaaaaaaaaaaaaaan","aaaaaaaaaaaaaaao","aaaaaaaaaaaaaaap","aaaaaaaaaaaaaaaq","aaaaaaaaaaaaaaar","aaaaaaaaaaaaaaas","aaaaaaaaaaaaaaat","aaaaaaaaaaaaaaau","aaaaaaaaaaaaaaav","aaaaaaaaaaaaaaaw","aaaaaaaaaaaaaaax","aaaaaaaaaaaaaaay","aaaaaaaaaaaaaaaz","aaaaaaaaaaaaaaba","aaaaaaaaaaaaaabb","aaaaaaaaaaaaaabc","aaaaaaaaaaaaaabd","aaaaaaaaaaaaaabe","aaaaaaaaaaaaaabf","aaaaaaaaaaaaaabg","aaaaaaaaaaaaaabh","aaaaaaaaaaaaaabi","aaaaaaaaaaaaaabj","aaaaaaaaaaaaaabk","aaaaaaaaaaaaaabl","aaaaaaaaaaaaaabm","aaaaaaaaaaaaaabn","aaaaaaaaaaaaaabo","aaaaaaaaaaaaaabp","aaaaaaaaaaaaaabq","aaaaaaaaaaaaaabr","aaaaaaaaaaaaaabs","aaaaaaaaaaaaaabt","aaaaaaaaaaaaaabu","aaaaaaaaaaaaaabv","aaaaaaaaaaaaaabw","aaaaaaaaaaaaaabx","aaaaaaaaaaaaaaby","aaaaaaaaaaaaaabz","aaaaaaaaaaaaaaca","aaaaaaaaaaaaaacb","aaaaaaaaaaaaaacc","aaaaaaaaaaaaaacd","aaaaaaaaaaaaaace","aaaaaaaaaaaaaacf","aaaaaaaaaaaaaacg","aaaaaaaaaaaaaach","aaaaaaaaaaaaaaci","aaaaaaaaaaaaaacj","aaaaaaaaaaaaaack","aaaaaaaaaaaaaacl","aaaaaaaaaaaaaacm","aaaaaaaaaaaaaacn","aaaaaaaaaaaaaaco","aaaaaaaaaaaaaacp","aaaaaaaaaaaaaacq","aaaaaaaaaaaaaacr","aaaaaaaaaaaaaacs","aaaaaaaaaaaaaact","aaaaaaaaaaaaaacu","aaaaaaaaaaaaaacv","aaaaaaaaaaaaaacw","aaaaaaaaaaaaaacx","aaaaaaaaaaaaaacy","aaaaaaaaaaaaaacz","aaaaaaaaaaaaaada","aaaaaaaaaaaaaadb","aaaaaaaaaaaaaadc","aaaaaaaaaaaaaadd","aaaaaaaaaaaaaade","aaaaaaaaaaaaaadf","aaaaaaaaaaaaaadg","aaaaaaaaaaaaaadh","aaaaaaaaaaaaaadi","aaaaaaaaaaaaaadj","aaaaaaaaaaaaaadk","aaaaaaaaaaaaaadl","aaaaaaaaaaaaaadm","aaaaaaaaaaaaaadn","aaaaaaaaaaaaaado","aaaaaaaaaaaaaadp","aaaaaaaaaaaaaadq","aaaaaaaaaaaaaadr","aaaaaaaaaaaaaads","aaaaaaaaaaaaaadt","aaaaaaaaaaaaaadu","aaaaaaaaaaaaaadv","aaaaaaaaaaaaaadw","aaaaaaaaaaaaaadx","aaaaaaaaaaaaaady","aaaaaaaaaaaaaadz","aaaaaaaaaaaaaaea","aaaaaaaaaaaaaaeb","aaaaaaaaaaaaaaec","aaaaaaaaaaaaaaed","aaaaaaaaaaaaaaee","aaaaaaaaaaaaaaef","aaaaaaaaaaaaaaeg","aaaaaaaaaaaaaaeh","aaaaaaaaaaaaaaei","aaaaaaaaaaaaaaej","aaaaaaaaaaaaaaek","aaaaaaaaaaaaaael","aaaaaaaaaaaaaaem","aaaaaaaaaaaaaaen","aaaaaaaaaaaaaaeo","aaaaaaaaaaaaaaep","aaaaaaaaaaaaaaeq","aaaaaaaaaaaaaaer","aaaaaaaaaaaaaaes","aaaaaaaaaaaaaaet","aaaaaaaaaaaaaaeu","aaaaaaaaaaaaaaev","aaaaaaaaaaaaaaew","aaaaaaaaaaaaaaex","aaaaaaaaaaaaaaey","aaaaaaaaaaaaaaez","aaaaaaaaaaaaaafa","aaaaaaaaaaaaaafb","aaaaaaaaaaaaaafc","aaaaaaaaaaaaaafd","aaaaaaaaaaaaaafe","aaaaaaaaaaaaaaff","aaaaaaaaaaaaaafg","aaaaaaaaaaaaaafh","aaaaaaaaaaaaaafi","aaaaaaaaaaaaaafj","aaaaaaaaaaaaaafk","aaaaaaaaaaaaaafl","aaaaaaaaaaaaaafm","aaaaaaaaaaaaaafn","aaaaaaaaaaaaaafo","aaaaaaaaaaaaaafp","aaaaaaaaaaaaaafq","aaaaaaaaaaaaaafr","aaaaaaaaaaaaaafs","aaaaaaaaaaaaaaft","aaaaaaaaaaaaaafu","aaaaaaaaaaaaaafv","aaaaaaaaaaaaaafw","aaaaaaaaaaaaaafx","aaaaaaaaaaaaaafy","aaaaaaaaaaaaaafz","aaaaaaaaaaaaaaga","aaaaaaaaaaaaaagb","aaaaaaaaaaaaaagc","aaaaaaaaaaaaaagd","aaaaaaaaaaaaaage","aaaaaaaaaaaaaagf","aaaaaaaaaaaaaagg","aaaaaaaaaaaaaagh","aaaaaaaaaaaaaagi","aaaaaaaaaaaaaagj","aaaaaaaaaaaaaagk","aaaaaaaaaaaaaagl","aaaaaaaaaaaaaagm","aaaaaaaaaaaaaagn","aaaaaaaaaaaaaago","aaaaaaaaaaaaaagp","aaaaaaaaaaaaaagq","aaaaaaaaaaaaaagr","aaaaaaaaaaaaaags","aaaaaaaaaaaaaagt","aaaaaaaaaaaaaagu","aaaaaaaaaaaaaagv","aaaaaaaaaaaaaagw","aaaaaaaaaaaaaagx","aaaaaaaaaaaaaagy","aaaaaaaaaaaaaagz","aaaaaaaaaaaaaaha","aaaaaaaaaaaaaahb","aaaaaaaaaaaaaahc","aaaaaaaaaaaaaahd","aaaaaaaaaaaaaahe","aaaaaaaaaaaaaahf","aaaaaaaaaaaaaahg","aaaaaaaaaaaaaahh","aaaaaaaaaaaaaahi","aaaaaaaaaaaaaahj","aaaaaaaaaaaaaahk","aaaaaaaaaaaaaahl","aaaaaaaaaaaaaahm","aaaaaaaaaaaaaahn","aaaaaaaaaaaaaaho","aaaaaaaaaaaaaahp","aaaaaaaaaaaaaahq","aaaaaaaaaaaaaahr","aaaaaaaaaaaaaahs","aaaaaaaaaaaaaaht","aaaaaaaaaaaaaahu","aaaaaaaaaaaaaahv","aaaaaaaaaaaaaahw","aaaaaaaaaaaaaahx","aaaaaaaaaaaaaahy","aaaaaaaaaaaaaahz","aaaaaaaaaaaaaaia","aaaaaaaaaaaaaaib","aaaaaaaaaaaaaaic","aaaaaaaaaaaaaaid","aaaaaaaaaaaaaaie","aaaaaaaaaaaaaaif","aaaaaaaaaaaaaaig","aaaaaaaaaaaaaaih","aaaaaaaaaaaaaaii","aaaaaaaaaaaaaaij","aaaaaaaaaaaaaaik","aaaaaaaaaaaaaail","aaaaaaaaaaaaaaim","aaaaaaaaaaaaaain","aaaaaaaaaaaaaaio","aaaaaaaaaaaaaaip","aaaaaaaaaaaaaaiq","aaaaaaaaaaaaaair","aaaaaaaaaaaaaais","aaaaaaaaaaaaaait","aaaaaaaaaaaaaaiu","aaaaaaaaaaaaaaiv","aaaaaaaaaaaaaaiw","aaaaaaaaaaaaaaix","aaaaaaaaaaaaaaiy","aaaaaaaaaaaaaaiz","aaaaaaaaaaaaaaja","aaaaaaaaaaaaaajb","aaaaaaaaaaaaaajc","aaaaaaaaaaaaaajd","aaaaaaaaaaaaaaje","aaaaaaaaaaaaaajf","aaaaaaaaaaaaaajg","aaaaaaaaaaaaaajh","aaaaaaaaaaaaaaji","aaaaaaaaaaaaaajj","aaaaaaaaaaaaaajk","aaaaaaaaaaaaaajl","aaaaaaaaaaaaaajm","aaaaaaaaaaaaaajn","aaaaaaaaaaaaaajo","aaaaaaaaaaaaaajp","aaaaaaaaaaaaaajq","aaaaaaaaaaaaaajr","aaaaaaaaaaaaaajs","aaaaaaaaaaaaaajt","aaaaaaaaaaaaaaju","aaaaaaaaaaaaaajv","aaaaaaaaaaaaaajw","aaaaaaaaaaaaaajx","aaaaaaaaaaaaaajy","aaaaaaaaaaaaaajz","aaaaaaaaaaaaaaka","aaaaaaaaaaaaaakb","aaaaaaaaaaaaaakc","aaaaaaaaaaaaaakd","aaaaaaaaaaaaaake","aaaaaaaaaaaaaakf","aaaaaaaaaaaaaakg","aaaaaaaaaaaaaakh","aaaaaaaaaaaaaaki","aaaaaaaaaaaaaakj","aaaaaaaaaaaaaakk","aaaaaaaaaaaaaakl","aaaaaaaaaaaaaakm","aaaaaaaaaaaaaakn","aaaaaaaaaaaaaako","aaaaaaaaaaaaaakp","aaaaaaaaaaaaaakq","aaaaaaaaaaaaaakr","aaaaaaaaaaaaaaks","aaaaaaaaaaaaaakt","aaaaaaaaaaaaaaku","aaaaaaaaaaaaaakv","aaaaaaaaaaaaaakw","aaaaaaaaaaaaaakx","aaaaaaaaaaaaaaky","aaaaaaaaaaaaaakz","aaaaaaaaaaaaaala","aaaaaaaaaaaaaalb","aaaaaaaaaaaaaalc","aaaaaaaaaaaaaald","aaaaaaaaaaaaaale","aaaaaaaaaaaaaalf","aaaaaaaaaaaaaalg","aaaaaaaaaaaaaalh","aaaaaaaaaaaaaali","aaaaaaaaaaaaaalj","aaaaaaaaaaaaaalk","aaaaaaaaaaaaaall","aaaaaaaaaaaaaalm","aaaaaaaaaaaaaaln","aaaaaaaaaaaaaalo","aaaaaaaaaaaaaalp","aaaaaaaaaaaaaalq","aaaaaaaaaaaaaalr","aaaaaaaaaaaaaals","aaaaaaaaaaaaaalt","aaaaaaaaaaaaaalu","aaaaaaaaaaaaaalv","aaaaaaaaaaaaaalw","aaaaaaaaaaaaaalx","aaaaaaaaaaaaaaly","aaaaaaaaaaaaaalz","aaaaaaaaaaaaaama","aaaaaaaaaaaaaamb","aaaaaaaaaaaaaamc","aaaaaaaaaaaaaamd","aaaaaaaaaaaaaame","aaaaaaaaaaaaaamf","aaaaaaaaaaaaaamg","aaaaaaaaaaaaaamh","aaaaaaaaaaaaaami","aaaaaaaaaaaaaamj","aaaaaaaaaaaaaamk","aaaaaaaaaaaaaaml","aaaaaaaaaaaaaamm","aaaaaaaaaaaaaamn","aaaaaaaaaaaaaamo","aaaaaaaaaaaaaamp","aaaaaaaaaaaaaamq","aaaaaaaaaaaaaamr","aaaaaaaaaaaaaams","aaaaaaaaaaaaaamt","aaaaaaaaaaaaaamu","aaaaaaaaaaaaaamv","aaaaaaaaaaaaaamw","aaaaaaaaaaaaaamx","aaaaaaaaaaaaaamy","aaaaaaaaaaaaaamz","aaaaaaaaaaaaaana","aaaaaaaaaaaaaanb","aaaaaaaaaaaaaanc","aaaaaaaaaaaaaand","aaaaaaaaaaaaaane","aaaaaaaaaaaaaanf","aaaaaaaaaaaaaang","aaaaaaaaaaaaaanh","aaaaaaaaaaaaaani","aaaaaaaaaaaaaanj","aaaaaaaaaaaaaank","aaaaaaaaaaaaaanl","aaaaaaaaaaaaaanm","aaaaaaaaaaaaaann","aaaaaaaaaaaaaano","aaaaaaaaaaaaaanp","aaaaaaaaaaaaaanq","aaaaaaaaaaaaaanr","aaaaaaaaaaaaaans","aaaaaaaaaaaaaant","aaaaaaaaaaaaaanu","aaaaaaaaaaaaaanv","aaaaaaaaaaaaaanw","aaaaaaaaaaaaaanx","aaaaaaaaaaaaaany","aaaaaaaaaaaaaanz","aaaaaaaaaaaaaaoa","aaaaaaaaaaaaaaob","aaaaaaaaaaaaaaoc","aaaaaaaaaaaaaaod","aaaaaaaaaaaaaaoe","aaaaaaaaaaaaaaof","aaaaaaaaaaaaaaog","aaaaaaaaaaaaaaoh","aaaaaaaaaaaaaaoi","aaaaaaaaaaaaaaoj","aaaaaaaaaaaaaaok","aaaaaaaaaaaaaaol","aaaaaaaaaaaaaaom","aaaaaaaaaaaaaaon","aaaaaaaaaaaaaaoo","aaaaaaaaaaaaaaop","aaaaaaaaaaaaaaoq","aaaaaaaaaaaaaaor","aaaaaaaaaaaaaaos","aaaaaaaaaaaaaaot","aaaaaaaaaaaaaaou","aaaaaaaaaaaaaaov","aaaaaaaaaaaaaaow","aaaaaaaaaaaaaaox","aaaaaaaaaaaaaaoy","aaaaaaaaaaaaaaoz","aaaaaaaaaaaaaapa","aaaaaaaaaaaaaapb","aaaaaaaaaaaaaapc","aaaaaaaaaaaaaapd","aaaaaaaaaaaaaape","aaaaaaaaaaaaaapf","aaaaaaaaaaaaaapg","aaaaaaaaaaaaaaph","aaaaaaaaaaaaaapi","aaaaaaaaaaaaaapj","aaaaaaaaaaaaaapk","aaaaaaaaaaaaaapl","aaaaaaaaaaaaaapm","aaaaaaaaaaaaaapn","aaaaaaaaaaaaaapo","aaaaaaaaaaaaaapp","aaaaaaaaaaaaaapq","aaaaaaaaaaaaaapr","aaaaaaaaaaaaaaps","aaaaaaaaaaaaaapt","aaaaaaaaaaaaaapu","aaaaaaaaaaaaaapv","aaaaaaaaaaaaaapw","aaaaaaaaaaaaaapx","aaaaaaaaaaaaaapy","aaaaaaaaaaaaaapz","aaaaaaaaaaaaaaqa","aaaaaaaaaaaaaaqb","aaaaaaaaaaaaaaqc","aaaaaaaaaaaaaaqd","aaaaaaaaaaaaaaqe","aaaaaaaaaaaaaaqf","aaaaaaaaaaaaaaqg","aaaaaaaaaaaaaaqh","aaaaaaaaaaaaaaqi","aaaaaaaaaaaaaaqj","aaaaaaaaaaaaaaqk","aaaaaaaaaaaaaaql","aaaaaaaaaaaaaaqm","aaaaaaaaaaaaaaqn","aaaaaaaaaaaaaaqo","aaaaaaaaaaaaaaqp","aaaaaaaaaaaaaaqq","aaaaaaaaaaaaaaqr","aaaaaaaaaaaaaaqs","aaaaaaaaaaaaaaqt","aaaaaaaaaaaaaaqu","aaaaaaaaaaaaaaqv","aaaaaaaaaaaaaaqw","aaaaaaaaaaaaaaqx","aaaaaaaaaaaaaaqy","aaaaaaaaaaaaaaqz","aaaaaaaaaaaaaara","aaaaaaaaaaaaaarb","aaaaaaaaaaaaaarc","aaaaaaaaaaaaaard","aaaaaaaaaaaaaare","aaaaaaaaaaaaaarf","aaaaaaaaaaaaaarg","aaaaaaaaaaaaaarh","aaaaaaaaaaaaaari","aaaaaaaaaaaaaarj","aaaaaaaaaaaaaark","aaaaaaaaaaaaaarl","aaaaaaaaaaaaaarm","aaaaaaaaaaaaaarn","aaaaaaaaaaaaaaro","aaaaaaaaaaaaaarp","aaaaaaaaaaaaaarq","aaaaaaaaaaaaaarr","aaaaaaaaaaaaaars","aaaaaaaaaaaaaart","aaaaaaaaaaaaaaru","aaaaaaaaaaaaaarv","aaaaaaaaaaaaaarw","aaaaaaaaaaaaaarx","aaaaaaaaaaaaaary","aaaaaaaaaaaaaarz","aaaaaaaaaaaaaasa","aaaaaaaaaaaaaasb","aaaaaaaaaaaaaasc","aaaaaaaaaaaaaasd","aaaaaaaaaaaaaase","aaaaaaaaaaaaaasf","aaaaaaaaaaaaaasg","aaaaaaaaaaaaaash","aaaaaaaaaaaaaasi","aaaaaaaaaaaaaasj","aaaaaaaaaaaaaask","aaaaaaaaaaaaaasl","aaaaaaaaaaaaaasm","aaaaaaaaaaaaaasn","aaaaaaaaaaaaaaso","aaaaaaaaaaaaaasp","aaaaaaaaaaaaaasq","aaaaaaaaaaaaaasr","aaaaaaaaaaaaaass","aaaaaaaaaaaaaast","aaaaaaaaaaaaaasu","aaaaaaaaaaaaaasv","aaaaaaaaaaaaaasw","aaaaaaaaaaaaaasx","aaaaaaaaaaaaaasy","aaaaaaaaaaaaaasz","aaaaaaaaaaaaaata","aaaaaaaaaaaaaatb","aaaaaaaaaaaaaatc","aaaaaaaaaaaaaatd","aaaaaaaaaaaaaate","aaaaaaaaaaaaaatf","aaaaaaaaaaaaaatg","aaaaaaaaaaaaaath","aaaaaaaaaaaaaati","aaaaaaaaaaaaaatj","aaaaaaaaaaaaaatk","aaaaaaaaaaaaaatl","aaaaaaaaaaaaaatm","aaaaaaaaaaaaaatn","aaaaaaaaaaaaaato","aaaaaaaaaaaaaatp","aaaaaaaaaaaaaatq","aaaaaaaaaaaaaatr","aaaaaaaaaaaaaats","aaaaaaaaaaaaaatt","aaaaaaaaaaaaaatu","aaaaaaaaaaaaaatv","aaaaaaaaaaaaaatw","aaaaaaaaaaaaaatx","aaaaaaaaaaaaaaty","aaaaaaaaaaaaaatz","aaaaaaaaaaaaaaua","aaaaaaaaaaaaaaub","aaaaaaaaaaaaaauc","aaaaaaaaaaaaaaud","aaaaaaaaaaaaaaue","aaaaaaaaaaaaaauf","aaaaaaaaaaaaaaug","aaaaaaaaaaaaaauh","aaaaaaaaaaaaaaui","aaaaaaaaaaaaaauj","aaaaaaaaaaaaaauk","aaaaaaaaaaaaaaul","aaaaaaaaaaaaaaum","aaaaaaaaaaaaaaun","aaaaaaaaaaaaaauo","aaaaaaaaaaaaaaup","aaaaaaaaaaaaaauq","aaaaaaaaaaaaaaur","aaaaaaaaaaaaaaus","aaaaaaaaaaaaaaut","aaaaaaaaaaaaaauu","aaaaaaaaaaaaaauv","aaaaaaaaaaaaaauw","aaaaaaaaaaaaaaux","aaaaaaaaaaaaaauy","aaaaaaaaaaaaaauz","aaaaaaaaaaaaaava","aaaaaaaaaaaaaavb","aaaaaaaaaaaaaavc","aaaaaaaaaaaaaavd","aaaaaaaaaaaaaave","aaaaaaaaaaaaaavf","aaaaaaaaaaaaaavg","aaaaaaaaaaaaaavh","aaaaaaaaaaaaaavi","aaaaaaaaaaaaaavj","aaaaaaaaaaaaaavk","aaaaaaaaaaaaaavl","aaaaaaaaaaaaaavm","aaaaaaaaaaaaaavn","aaaaaaaaaaaaaavo","aaaaaaaaaaaaaavp","aaaaaaaaaaaaaavq","aaaaaaaaaaaaaavr","aaaaaaaaaaaaaavs","aaaaaaaaaaaaaavt","aaaaaaaaaaaaaavu","aaaaaaaaaaaaaavv","aaaaaaaaaaaaaavw","aaaaaaaaaaaaaavx","aaaaaaaaaaaaaavy","aaaaaaaaaaaaaavz","aaaaaaaaaaaaaawa","aaaaaaaaaaaaaawb","aaaaaaaaaaaaaawc","aaaaaaaaaaaaaawd","aaaaaaaaaaaaaawe","aaaaaaaaaaaaaawf","aaaaaaaaaaaaaawg","aaaaaaaaaaaaaawh","aaaaaaaaaaaaaawi","aaaaaaaaaaaaaawj","aaaaaaaaaaaaaawk","aaaaaaaaaaaaaawl","aaaaaaaaaaaaaawm","aaaaaaaaaaaaaawn","aaaaaaaaaaaaaawo","aaaaaaaaaaaaaawp","aaaaaaaaaaaaaawq","aaaaaaaaaaaaaawr","aaaaaaaaaaaaaaws","aaaaaaaaaaaaaawt","aaaaaaaaaaaaaawu","aaaaaaaaaaaaaawv","aaaaaaaaaaaaaaww","aaaaaaaaaaaaaawx","aaaaaaaaaaaaaawy","aaaaaaaaaaaaaawz","aaaaaaaaaaaaaaxa","aaaaaaaaaaaaaaxb","aaaaaaaaaaaaaaxc","aaaaaaaaaaaaaaxd","aaaaaaaaaaaaaaxe","aaaaaaaaaaaaaaxf","aaaaaaaaaaaaaaxg","aaaaaaaaaaaaaaxh","aaaaaaaaaaaaaaxi","aaaaaaaaaaaaaaxj","aaaaaaaaaaaaaaxk","aaaaaaaaaaaaaaxl","aaaaaaaaaaaaaaxm","aaaaaaaaaaaaaaxn","aaaaaaaaaaaaaaxo","aaaaaaaaaaaaaaxp","aaaaaaaaaaaaaaxq","aaaaaaaaaaaaaaxr","aaaaaaaaaaaaaaxs","aaaaaaaaaaaaaaxt","aaaaaaaaaaaaaaxu","aaaaaaaaaaaaaaxv","aaaaaaaaaaaaaaxw","aaaaaaaaaaaaaaxx","aaaaaaaaaaaaaaxy","aaaaaaaaaaaaaaxz","aaaaaaaaaaaaaaya","aaaaaaaaaaaaaayb","aaaaaaaaaaaaaayc","aaaaaaaaaaaaaayd","aaaaaaaaaaaaaaye","aaaaaaaaaaaaaayf","aaaaaaaaaaaaaayg","aaaaaaaaaaaaaayh","aaaaaaaaaaaaaayi","aaaaaaaaaaaaaayj","aaaaaaaaaaaaaayk","aaaaaaaaaaaaaayl","aaaaaaaaaaaaaaym","aaaaaaaaaaaaaayn","aaaaaaaaaaaaaayo","aaaaaaaaaaaaaayp","aaaaaaaaaaaaaayq","aaaaaaaaaaaaaayr","aaaaaaaaaaaaaays","aaaaaaaaaaaaaayt","aaaaaaaaaaaaaayu","aaaaaaaaaaaaaayv","aaaaaaaaaaaaaayw","aaaaaaaaaaaaaayx","aaaaaaaaaaaaaayy","aaaaaaaaaaaaaayz","aaaaaaaaaaaaaaza","aaaaaaaaaaaaaazb","aaaaaaaaaaaaaazc","aaaaaaaaaaaaaazd","aaaaaaaaaaaaaaze","aaaaaaaaaaaaaazf","aaaaaaaaaaaaaazg","aaaaaaaaaaaaaazh","aaaaaaaaaaaaaazi","aaaaaaaaaaaaaazj","aaaaaaaaaaaaaazk","aaaaaaaaaaaaaazl","aaaaaaaaaaaaaazm","aaaaaaaaaaaaaazn","aaaaaaaaaaaaaazo","aaaaaaaaaaaaaazp","aaaaaaaaaaaaaazq","aaaaaaaaaaaaaazr","aaaaaaaaaaaaaazs","aaaaaaaaaaaaaazt","aaaaaaaaaaaaaazu","aaaaaaaaaaaaaazv","aaaaaaaaaaaaaazw","aaaaaaaaaaaaaazx","aaaaaaaaaaaaaazy","aaaaaaaaaaaaaazz"])) +print(Solution().findWords([['o','a','a','n'],['e','t','a','e'],['i','h','k','r'],['i','f','l','v']],["oath","pea","eat","rain"])) +print(Solution().findWords([['a']], [])) \ No newline at end of file From 7f7c016af246fb475cbc77626cfcc84326c2d7b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1ty=C3=A1s=20Kiglics?= Date: Thu, 29 Oct 2020 11:37:07 +0100 Subject: [PATCH 328/357] Word search II delete test lines --- LeetCode/0212_Word_search_II.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/LeetCode/0212_Word_search_II.py b/LeetCode/0212_Word_search_II.py index b68f79d..3c5de35 100644 --- a/LeetCode/0212_Word_search_II.py +++ b/LeetCode/0212_Word_search_II.py @@ -53,6 +53,3 @@ def findWords(self, board, words): self.used[i] = False return self.found -# print(Solution().findWords([["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["a","a","a","a"],["b","c","d","e"],["f","g","h","i"],["j","k","l","m"],["n","o","p","q"],["r","s","t","u"],["v","w","x","y"],["z","z","z","z"]],["aaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaab","aaaaaaaaaaaaaaac","aaaaaaaaaaaaaaad","aaaaaaaaaaaaaaae","aaaaaaaaaaaaaaaf","aaaaaaaaaaaaaaag","aaaaaaaaaaaaaaah","aaaaaaaaaaaaaaai","aaaaaaaaaaaaaaaj","aaaaaaaaaaaaaaak","aaaaaaaaaaaaaaal","aaaaaaaaaaaaaaam","aaaaaaaaaaaaaaan","aaaaaaaaaaaaaaao","aaaaaaaaaaaaaaap","aaaaaaaaaaaaaaaq","aaaaaaaaaaaaaaar","aaaaaaaaaaaaaaas","aaaaaaaaaaaaaaat","aaaaaaaaaaaaaaau","aaaaaaaaaaaaaaav","aaaaaaaaaaaaaaaw","aaaaaaaaaaaaaaax","aaaaaaaaaaaaaaay","aaaaaaaaaaaaaaaz","aaaaaaaaaaaaaaba","aaaaaaaaaaaaaabb","aaaaaaaaaaaaaabc","aaaaaaaaaaaaaabd","aaaaaaaaaaaaaabe","aaaaaaaaaaaaaabf","aaaaaaaaaaaaaabg","aaaaaaaaaaaaaabh","aaaaaaaaaaaaaabi","aaaaaaaaaaaaaabj","aaaaaaaaaaaaaabk","aaaaaaaaaaaaaabl","aaaaaaaaaaaaaabm","aaaaaaaaaaaaaabn","aaaaaaaaaaaaaabo","aaaaaaaaaaaaaabp","aaaaaaaaaaaaaabq","aaaaaaaaaaaaaabr","aaaaaaaaaaaaaabs","aaaaaaaaaaaaaabt","aaaaaaaaaaaaaabu","aaaaaaaaaaaaaabv","aaaaaaaaaaaaaabw","aaaaaaaaaaaaaabx","aaaaaaaaaaaaaaby","aaaaaaaaaaaaaabz","aaaaaaaaaaaaaaca","aaaaaaaaaaaaaacb","aaaaaaaaaaaaaacc","aaaaaaaaaaaaaacd","aaaaaaaaaaaaaace","aaaaaaaaaaaaaacf","aaaaaaaaaaaaaacg","aaaaaaaaaaaaaach","aaaaaaaaaaaaaaci","aaaaaaaaaaaaaacj","aaaaaaaaaaaaaack","aaaaaaaaaaaaaacl","aaaaaaaaaaaaaacm","aaaaaaaaaaaaaacn","aaaaaaaaaaaaaaco","aaaaaaaaaaaaaacp","aaaaaaaaaaaaaacq","aaaaaaaaaaaaaacr","aaaaaaaaaaaaaacs","aaaaaaaaaaaaaact","aaaaaaaaaaaaaacu","aaaaaaaaaaaaaacv","aaaaaaaaaaaaaacw","aaaaaaaaaaaaaacx","aaaaaaaaaaaaaacy","aaaaaaaaaaaaaacz","aaaaaaaaaaaaaada","aaaaaaaaaaaaaadb","aaaaaaaaaaaaaadc","aaaaaaaaaaaaaadd","aaaaaaaaaaaaaade","aaaaaaaaaaaaaadf","aaaaaaaaaaaaaadg","aaaaaaaaaaaaaadh","aaaaaaaaaaaaaadi","aaaaaaaaaaaaaadj","aaaaaaaaaaaaaadk","aaaaaaaaaaaaaadl","aaaaaaaaaaaaaadm","aaaaaaaaaaaaaadn","aaaaaaaaaaaaaado","aaaaaaaaaaaaaadp","aaaaaaaaaaaaaadq","aaaaaaaaaaaaaadr","aaaaaaaaaaaaaads","aaaaaaaaaaaaaadt","aaaaaaaaaaaaaadu","aaaaaaaaaaaaaadv","aaaaaaaaaaaaaadw","aaaaaaaaaaaaaadx","aaaaaaaaaaaaaady","aaaaaaaaaaaaaadz","aaaaaaaaaaaaaaea","aaaaaaaaaaaaaaeb","aaaaaaaaaaaaaaec","aaaaaaaaaaaaaaed","aaaaaaaaaaaaaaee","aaaaaaaaaaaaaaef","aaaaaaaaaaaaaaeg","aaaaaaaaaaaaaaeh","aaaaaaaaaaaaaaei","aaaaaaaaaaaaaaej","aaaaaaaaaaaaaaek","aaaaaaaaaaaaaael","aaaaaaaaaaaaaaem","aaaaaaaaaaaaaaen","aaaaaaaaaaaaaaeo","aaaaaaaaaaaaaaep","aaaaaaaaaaaaaaeq","aaaaaaaaaaaaaaer","aaaaaaaaaaaaaaes","aaaaaaaaaaaaaaet","aaaaaaaaaaaaaaeu","aaaaaaaaaaaaaaev","aaaaaaaaaaaaaaew","aaaaaaaaaaaaaaex","aaaaaaaaaaaaaaey","aaaaaaaaaaaaaaez","aaaaaaaaaaaaaafa","aaaaaaaaaaaaaafb","aaaaaaaaaaaaaafc","aaaaaaaaaaaaaafd","aaaaaaaaaaaaaafe","aaaaaaaaaaaaaaff","aaaaaaaaaaaaaafg","aaaaaaaaaaaaaafh","aaaaaaaaaaaaaafi","aaaaaaaaaaaaaafj","aaaaaaaaaaaaaafk","aaaaaaaaaaaaaafl","aaaaaaaaaaaaaafm","aaaaaaaaaaaaaafn","aaaaaaaaaaaaaafo","aaaaaaaaaaaaaafp","aaaaaaaaaaaaaafq","aaaaaaaaaaaaaafr","aaaaaaaaaaaaaafs","aaaaaaaaaaaaaaft","aaaaaaaaaaaaaafu","aaaaaaaaaaaaaafv","aaaaaaaaaaaaaafw","aaaaaaaaaaaaaafx","aaaaaaaaaaaaaafy","aaaaaaaaaaaaaafz","aaaaaaaaaaaaaaga","aaaaaaaaaaaaaagb","aaaaaaaaaaaaaagc","aaaaaaaaaaaaaagd","aaaaaaaaaaaaaage","aaaaaaaaaaaaaagf","aaaaaaaaaaaaaagg","aaaaaaaaaaaaaagh","aaaaaaaaaaaaaagi","aaaaaaaaaaaaaagj","aaaaaaaaaaaaaagk","aaaaaaaaaaaaaagl","aaaaaaaaaaaaaagm","aaaaaaaaaaaaaagn","aaaaaaaaaaaaaago","aaaaaaaaaaaaaagp","aaaaaaaaaaaaaagq","aaaaaaaaaaaaaagr","aaaaaaaaaaaaaags","aaaaaaaaaaaaaagt","aaaaaaaaaaaaaagu","aaaaaaaaaaaaaagv","aaaaaaaaaaaaaagw","aaaaaaaaaaaaaagx","aaaaaaaaaaaaaagy","aaaaaaaaaaaaaagz","aaaaaaaaaaaaaaha","aaaaaaaaaaaaaahb","aaaaaaaaaaaaaahc","aaaaaaaaaaaaaahd","aaaaaaaaaaaaaahe","aaaaaaaaaaaaaahf","aaaaaaaaaaaaaahg","aaaaaaaaaaaaaahh","aaaaaaaaaaaaaahi","aaaaaaaaaaaaaahj","aaaaaaaaaaaaaahk","aaaaaaaaaaaaaahl","aaaaaaaaaaaaaahm","aaaaaaaaaaaaaahn","aaaaaaaaaaaaaaho","aaaaaaaaaaaaaahp","aaaaaaaaaaaaaahq","aaaaaaaaaaaaaahr","aaaaaaaaaaaaaahs","aaaaaaaaaaaaaaht","aaaaaaaaaaaaaahu","aaaaaaaaaaaaaahv","aaaaaaaaaaaaaahw","aaaaaaaaaaaaaahx","aaaaaaaaaaaaaahy","aaaaaaaaaaaaaahz","aaaaaaaaaaaaaaia","aaaaaaaaaaaaaaib","aaaaaaaaaaaaaaic","aaaaaaaaaaaaaaid","aaaaaaaaaaaaaaie","aaaaaaaaaaaaaaif","aaaaaaaaaaaaaaig","aaaaaaaaaaaaaaih","aaaaaaaaaaaaaaii","aaaaaaaaaaaaaaij","aaaaaaaaaaaaaaik","aaaaaaaaaaaaaail","aaaaaaaaaaaaaaim","aaaaaaaaaaaaaain","aaaaaaaaaaaaaaio","aaaaaaaaaaaaaaip","aaaaaaaaaaaaaaiq","aaaaaaaaaaaaaair","aaaaaaaaaaaaaais","aaaaaaaaaaaaaait","aaaaaaaaaaaaaaiu","aaaaaaaaaaaaaaiv","aaaaaaaaaaaaaaiw","aaaaaaaaaaaaaaix","aaaaaaaaaaaaaaiy","aaaaaaaaaaaaaaiz","aaaaaaaaaaaaaaja","aaaaaaaaaaaaaajb","aaaaaaaaaaaaaajc","aaaaaaaaaaaaaajd","aaaaaaaaaaaaaaje","aaaaaaaaaaaaaajf","aaaaaaaaaaaaaajg","aaaaaaaaaaaaaajh","aaaaaaaaaaaaaaji","aaaaaaaaaaaaaajj","aaaaaaaaaaaaaajk","aaaaaaaaaaaaaajl","aaaaaaaaaaaaaajm","aaaaaaaaaaaaaajn","aaaaaaaaaaaaaajo","aaaaaaaaaaaaaajp","aaaaaaaaaaaaaajq","aaaaaaaaaaaaaajr","aaaaaaaaaaaaaajs","aaaaaaaaaaaaaajt","aaaaaaaaaaaaaaju","aaaaaaaaaaaaaajv","aaaaaaaaaaaaaajw","aaaaaaaaaaaaaajx","aaaaaaaaaaaaaajy","aaaaaaaaaaaaaajz","aaaaaaaaaaaaaaka","aaaaaaaaaaaaaakb","aaaaaaaaaaaaaakc","aaaaaaaaaaaaaakd","aaaaaaaaaaaaaake","aaaaaaaaaaaaaakf","aaaaaaaaaaaaaakg","aaaaaaaaaaaaaakh","aaaaaaaaaaaaaaki","aaaaaaaaaaaaaakj","aaaaaaaaaaaaaakk","aaaaaaaaaaaaaakl","aaaaaaaaaaaaaakm","aaaaaaaaaaaaaakn","aaaaaaaaaaaaaako","aaaaaaaaaaaaaakp","aaaaaaaaaaaaaakq","aaaaaaaaaaaaaakr","aaaaaaaaaaaaaaks","aaaaaaaaaaaaaakt","aaaaaaaaaaaaaaku","aaaaaaaaaaaaaakv","aaaaaaaaaaaaaakw","aaaaaaaaaaaaaakx","aaaaaaaaaaaaaaky","aaaaaaaaaaaaaakz","aaaaaaaaaaaaaala","aaaaaaaaaaaaaalb","aaaaaaaaaaaaaalc","aaaaaaaaaaaaaald","aaaaaaaaaaaaaale","aaaaaaaaaaaaaalf","aaaaaaaaaaaaaalg","aaaaaaaaaaaaaalh","aaaaaaaaaaaaaali","aaaaaaaaaaaaaalj","aaaaaaaaaaaaaalk","aaaaaaaaaaaaaall","aaaaaaaaaaaaaalm","aaaaaaaaaaaaaaln","aaaaaaaaaaaaaalo","aaaaaaaaaaaaaalp","aaaaaaaaaaaaaalq","aaaaaaaaaaaaaalr","aaaaaaaaaaaaaals","aaaaaaaaaaaaaalt","aaaaaaaaaaaaaalu","aaaaaaaaaaaaaalv","aaaaaaaaaaaaaalw","aaaaaaaaaaaaaalx","aaaaaaaaaaaaaaly","aaaaaaaaaaaaaalz","aaaaaaaaaaaaaama","aaaaaaaaaaaaaamb","aaaaaaaaaaaaaamc","aaaaaaaaaaaaaamd","aaaaaaaaaaaaaame","aaaaaaaaaaaaaamf","aaaaaaaaaaaaaamg","aaaaaaaaaaaaaamh","aaaaaaaaaaaaaami","aaaaaaaaaaaaaamj","aaaaaaaaaaaaaamk","aaaaaaaaaaaaaaml","aaaaaaaaaaaaaamm","aaaaaaaaaaaaaamn","aaaaaaaaaaaaaamo","aaaaaaaaaaaaaamp","aaaaaaaaaaaaaamq","aaaaaaaaaaaaaamr","aaaaaaaaaaaaaams","aaaaaaaaaaaaaamt","aaaaaaaaaaaaaamu","aaaaaaaaaaaaaamv","aaaaaaaaaaaaaamw","aaaaaaaaaaaaaamx","aaaaaaaaaaaaaamy","aaaaaaaaaaaaaamz","aaaaaaaaaaaaaana","aaaaaaaaaaaaaanb","aaaaaaaaaaaaaanc","aaaaaaaaaaaaaand","aaaaaaaaaaaaaane","aaaaaaaaaaaaaanf","aaaaaaaaaaaaaang","aaaaaaaaaaaaaanh","aaaaaaaaaaaaaani","aaaaaaaaaaaaaanj","aaaaaaaaaaaaaank","aaaaaaaaaaaaaanl","aaaaaaaaaaaaaanm","aaaaaaaaaaaaaann","aaaaaaaaaaaaaano","aaaaaaaaaaaaaanp","aaaaaaaaaaaaaanq","aaaaaaaaaaaaaanr","aaaaaaaaaaaaaans","aaaaaaaaaaaaaant","aaaaaaaaaaaaaanu","aaaaaaaaaaaaaanv","aaaaaaaaaaaaaanw","aaaaaaaaaaaaaanx","aaaaaaaaaaaaaany","aaaaaaaaaaaaaanz","aaaaaaaaaaaaaaoa","aaaaaaaaaaaaaaob","aaaaaaaaaaaaaaoc","aaaaaaaaaaaaaaod","aaaaaaaaaaaaaaoe","aaaaaaaaaaaaaaof","aaaaaaaaaaaaaaog","aaaaaaaaaaaaaaoh","aaaaaaaaaaaaaaoi","aaaaaaaaaaaaaaoj","aaaaaaaaaaaaaaok","aaaaaaaaaaaaaaol","aaaaaaaaaaaaaaom","aaaaaaaaaaaaaaon","aaaaaaaaaaaaaaoo","aaaaaaaaaaaaaaop","aaaaaaaaaaaaaaoq","aaaaaaaaaaaaaaor","aaaaaaaaaaaaaaos","aaaaaaaaaaaaaaot","aaaaaaaaaaaaaaou","aaaaaaaaaaaaaaov","aaaaaaaaaaaaaaow","aaaaaaaaaaaaaaox","aaaaaaaaaaaaaaoy","aaaaaaaaaaaaaaoz","aaaaaaaaaaaaaapa","aaaaaaaaaaaaaapb","aaaaaaaaaaaaaapc","aaaaaaaaaaaaaapd","aaaaaaaaaaaaaape","aaaaaaaaaaaaaapf","aaaaaaaaaaaaaapg","aaaaaaaaaaaaaaph","aaaaaaaaaaaaaapi","aaaaaaaaaaaaaapj","aaaaaaaaaaaaaapk","aaaaaaaaaaaaaapl","aaaaaaaaaaaaaapm","aaaaaaaaaaaaaapn","aaaaaaaaaaaaaapo","aaaaaaaaaaaaaapp","aaaaaaaaaaaaaapq","aaaaaaaaaaaaaapr","aaaaaaaaaaaaaaps","aaaaaaaaaaaaaapt","aaaaaaaaaaaaaapu","aaaaaaaaaaaaaapv","aaaaaaaaaaaaaapw","aaaaaaaaaaaaaapx","aaaaaaaaaaaaaapy","aaaaaaaaaaaaaapz","aaaaaaaaaaaaaaqa","aaaaaaaaaaaaaaqb","aaaaaaaaaaaaaaqc","aaaaaaaaaaaaaaqd","aaaaaaaaaaaaaaqe","aaaaaaaaaaaaaaqf","aaaaaaaaaaaaaaqg","aaaaaaaaaaaaaaqh","aaaaaaaaaaaaaaqi","aaaaaaaaaaaaaaqj","aaaaaaaaaaaaaaqk","aaaaaaaaaaaaaaql","aaaaaaaaaaaaaaqm","aaaaaaaaaaaaaaqn","aaaaaaaaaaaaaaqo","aaaaaaaaaaaaaaqp","aaaaaaaaaaaaaaqq","aaaaaaaaaaaaaaqr","aaaaaaaaaaaaaaqs","aaaaaaaaaaaaaaqt","aaaaaaaaaaaaaaqu","aaaaaaaaaaaaaaqv","aaaaaaaaaaaaaaqw","aaaaaaaaaaaaaaqx","aaaaaaaaaaaaaaqy","aaaaaaaaaaaaaaqz","aaaaaaaaaaaaaara","aaaaaaaaaaaaaarb","aaaaaaaaaaaaaarc","aaaaaaaaaaaaaard","aaaaaaaaaaaaaare","aaaaaaaaaaaaaarf","aaaaaaaaaaaaaarg","aaaaaaaaaaaaaarh","aaaaaaaaaaaaaari","aaaaaaaaaaaaaarj","aaaaaaaaaaaaaark","aaaaaaaaaaaaaarl","aaaaaaaaaaaaaarm","aaaaaaaaaaaaaarn","aaaaaaaaaaaaaaro","aaaaaaaaaaaaaarp","aaaaaaaaaaaaaarq","aaaaaaaaaaaaaarr","aaaaaaaaaaaaaars","aaaaaaaaaaaaaart","aaaaaaaaaaaaaaru","aaaaaaaaaaaaaarv","aaaaaaaaaaaaaarw","aaaaaaaaaaaaaarx","aaaaaaaaaaaaaary","aaaaaaaaaaaaaarz","aaaaaaaaaaaaaasa","aaaaaaaaaaaaaasb","aaaaaaaaaaaaaasc","aaaaaaaaaaaaaasd","aaaaaaaaaaaaaase","aaaaaaaaaaaaaasf","aaaaaaaaaaaaaasg","aaaaaaaaaaaaaash","aaaaaaaaaaaaaasi","aaaaaaaaaaaaaasj","aaaaaaaaaaaaaask","aaaaaaaaaaaaaasl","aaaaaaaaaaaaaasm","aaaaaaaaaaaaaasn","aaaaaaaaaaaaaaso","aaaaaaaaaaaaaasp","aaaaaaaaaaaaaasq","aaaaaaaaaaaaaasr","aaaaaaaaaaaaaass","aaaaaaaaaaaaaast","aaaaaaaaaaaaaasu","aaaaaaaaaaaaaasv","aaaaaaaaaaaaaasw","aaaaaaaaaaaaaasx","aaaaaaaaaaaaaasy","aaaaaaaaaaaaaasz","aaaaaaaaaaaaaata","aaaaaaaaaaaaaatb","aaaaaaaaaaaaaatc","aaaaaaaaaaaaaatd","aaaaaaaaaaaaaate","aaaaaaaaaaaaaatf","aaaaaaaaaaaaaatg","aaaaaaaaaaaaaath","aaaaaaaaaaaaaati","aaaaaaaaaaaaaatj","aaaaaaaaaaaaaatk","aaaaaaaaaaaaaatl","aaaaaaaaaaaaaatm","aaaaaaaaaaaaaatn","aaaaaaaaaaaaaato","aaaaaaaaaaaaaatp","aaaaaaaaaaaaaatq","aaaaaaaaaaaaaatr","aaaaaaaaaaaaaats","aaaaaaaaaaaaaatt","aaaaaaaaaaaaaatu","aaaaaaaaaaaaaatv","aaaaaaaaaaaaaatw","aaaaaaaaaaaaaatx","aaaaaaaaaaaaaaty","aaaaaaaaaaaaaatz","aaaaaaaaaaaaaaua","aaaaaaaaaaaaaaub","aaaaaaaaaaaaaauc","aaaaaaaaaaaaaaud","aaaaaaaaaaaaaaue","aaaaaaaaaaaaaauf","aaaaaaaaaaaaaaug","aaaaaaaaaaaaaauh","aaaaaaaaaaaaaaui","aaaaaaaaaaaaaauj","aaaaaaaaaaaaaauk","aaaaaaaaaaaaaaul","aaaaaaaaaaaaaaum","aaaaaaaaaaaaaaun","aaaaaaaaaaaaaauo","aaaaaaaaaaaaaaup","aaaaaaaaaaaaaauq","aaaaaaaaaaaaaaur","aaaaaaaaaaaaaaus","aaaaaaaaaaaaaaut","aaaaaaaaaaaaaauu","aaaaaaaaaaaaaauv","aaaaaaaaaaaaaauw","aaaaaaaaaaaaaaux","aaaaaaaaaaaaaauy","aaaaaaaaaaaaaauz","aaaaaaaaaaaaaava","aaaaaaaaaaaaaavb","aaaaaaaaaaaaaavc","aaaaaaaaaaaaaavd","aaaaaaaaaaaaaave","aaaaaaaaaaaaaavf","aaaaaaaaaaaaaavg","aaaaaaaaaaaaaavh","aaaaaaaaaaaaaavi","aaaaaaaaaaaaaavj","aaaaaaaaaaaaaavk","aaaaaaaaaaaaaavl","aaaaaaaaaaaaaavm","aaaaaaaaaaaaaavn","aaaaaaaaaaaaaavo","aaaaaaaaaaaaaavp","aaaaaaaaaaaaaavq","aaaaaaaaaaaaaavr","aaaaaaaaaaaaaavs","aaaaaaaaaaaaaavt","aaaaaaaaaaaaaavu","aaaaaaaaaaaaaavv","aaaaaaaaaaaaaavw","aaaaaaaaaaaaaavx","aaaaaaaaaaaaaavy","aaaaaaaaaaaaaavz","aaaaaaaaaaaaaawa","aaaaaaaaaaaaaawb","aaaaaaaaaaaaaawc","aaaaaaaaaaaaaawd","aaaaaaaaaaaaaawe","aaaaaaaaaaaaaawf","aaaaaaaaaaaaaawg","aaaaaaaaaaaaaawh","aaaaaaaaaaaaaawi","aaaaaaaaaaaaaawj","aaaaaaaaaaaaaawk","aaaaaaaaaaaaaawl","aaaaaaaaaaaaaawm","aaaaaaaaaaaaaawn","aaaaaaaaaaaaaawo","aaaaaaaaaaaaaawp","aaaaaaaaaaaaaawq","aaaaaaaaaaaaaawr","aaaaaaaaaaaaaaws","aaaaaaaaaaaaaawt","aaaaaaaaaaaaaawu","aaaaaaaaaaaaaawv","aaaaaaaaaaaaaaww","aaaaaaaaaaaaaawx","aaaaaaaaaaaaaawy","aaaaaaaaaaaaaawz","aaaaaaaaaaaaaaxa","aaaaaaaaaaaaaaxb","aaaaaaaaaaaaaaxc","aaaaaaaaaaaaaaxd","aaaaaaaaaaaaaaxe","aaaaaaaaaaaaaaxf","aaaaaaaaaaaaaaxg","aaaaaaaaaaaaaaxh","aaaaaaaaaaaaaaxi","aaaaaaaaaaaaaaxj","aaaaaaaaaaaaaaxk","aaaaaaaaaaaaaaxl","aaaaaaaaaaaaaaxm","aaaaaaaaaaaaaaxn","aaaaaaaaaaaaaaxo","aaaaaaaaaaaaaaxp","aaaaaaaaaaaaaaxq","aaaaaaaaaaaaaaxr","aaaaaaaaaaaaaaxs","aaaaaaaaaaaaaaxt","aaaaaaaaaaaaaaxu","aaaaaaaaaaaaaaxv","aaaaaaaaaaaaaaxw","aaaaaaaaaaaaaaxx","aaaaaaaaaaaaaaxy","aaaaaaaaaaaaaaxz","aaaaaaaaaaaaaaya","aaaaaaaaaaaaaayb","aaaaaaaaaaaaaayc","aaaaaaaaaaaaaayd","aaaaaaaaaaaaaaye","aaaaaaaaaaaaaayf","aaaaaaaaaaaaaayg","aaaaaaaaaaaaaayh","aaaaaaaaaaaaaayi","aaaaaaaaaaaaaayj","aaaaaaaaaaaaaayk","aaaaaaaaaaaaaayl","aaaaaaaaaaaaaaym","aaaaaaaaaaaaaayn","aaaaaaaaaaaaaayo","aaaaaaaaaaaaaayp","aaaaaaaaaaaaaayq","aaaaaaaaaaaaaayr","aaaaaaaaaaaaaays","aaaaaaaaaaaaaayt","aaaaaaaaaaaaaayu","aaaaaaaaaaaaaayv","aaaaaaaaaaaaaayw","aaaaaaaaaaaaaayx","aaaaaaaaaaaaaayy","aaaaaaaaaaaaaayz","aaaaaaaaaaaaaaza","aaaaaaaaaaaaaazb","aaaaaaaaaaaaaazc","aaaaaaaaaaaaaazd","aaaaaaaaaaaaaaze","aaaaaaaaaaaaaazf","aaaaaaaaaaaaaazg","aaaaaaaaaaaaaazh","aaaaaaaaaaaaaazi","aaaaaaaaaaaaaazj","aaaaaaaaaaaaaazk","aaaaaaaaaaaaaazl","aaaaaaaaaaaaaazm","aaaaaaaaaaaaaazn","aaaaaaaaaaaaaazo","aaaaaaaaaaaaaazp","aaaaaaaaaaaaaazq","aaaaaaaaaaaaaazr","aaaaaaaaaaaaaazs","aaaaaaaaaaaaaazt","aaaaaaaaaaaaaazu","aaaaaaaaaaaaaazv","aaaaaaaaaaaaaazw","aaaaaaaaaaaaaazx","aaaaaaaaaaaaaazy","aaaaaaaaaaaaaazz"])) -print(Solution().findWords([['o','a','a','n'],['e','t','a','e'],['i','h','k','r'],['i','f','l','v']],["oath","pea","eat","rain"])) -print(Solution().findWords([['a']], [])) \ No newline at end of file From 6178648ead3a4fca55b177bb41ac4a1180c002fb Mon Sep 17 00:00:00 2001 From: Nurettin <46221949+na-vural@users.noreply.github.com> Date: Thu, 29 Oct 2020 14:32:23 +0300 Subject: [PATCH 329/357] Create 0891_Sum_of_Subsequence_Widths.py --- LeetCode/0891_Sum_of_Subsequence_Widths.py | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 LeetCode/0891_Sum_of_Subsequence_Widths.py diff --git a/LeetCode/0891_Sum_of_Subsequence_Widths.py b/LeetCode/0891_Sum_of_Subsequence_Widths.py new file mode 100644 index 0000000..f355b2e --- /dev/null +++ b/LeetCode/0891_Sum_of_Subsequence_Widths.py @@ -0,0 +1,10 @@ +class Solution(object): + def sumSubseqWidths(self, A: List[int]) -> int: + ret_int = 0 + A_len = len(A) + A.sort(key=lambda x: int(x), reverse=True) + + for x in range(A_len): + ret_int += A[x] * (2**(A_len - x - 1) - 2**(x)) + + return ret_int % (10**9 + 7) From c58635ac8ce5461bd94c10ea8a7aa5f1220b215c Mon Sep 17 00:00:00 2001 From: Nurettin <46221949+na-vural@users.noreply.github.com> Date: Thu, 29 Oct 2020 14:36:30 +0300 Subject: [PATCH 330/357] Create 0273_Integer_to_English_Words.py --- LeetCode/0273_Integer_to_English_Words.py | 68 +++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 LeetCode/0273_Integer_to_English_Words.py diff --git a/LeetCode/0273_Integer_to_English_Words.py b/LeetCode/0273_Integer_to_English_Words.py new file mode 100644 index 0000000..12a4a71 --- /dev/null +++ b/LeetCode/0273_Integer_to_English_Words.py @@ -0,0 +1,68 @@ +class Solution(object): + def numberToWords(self, num: int) -> str: + def decode(triple_str): + final_list = [] + + numbers = { "1": "One", + "2": "Two", + "3": "Three", + "4": "Four", + "5": "Five", + "6": "Six", + "7": "Seven", + "8": "Eight", + "9": "Nine", + "10": "Ten", + "11": "Eleven", + "12": "Twelve", + "13": "Thirteen", + "14": "Fourteen", + "15": "Fifteen", + "16": "Sixteen", + "17": "Seventeen", + "18": "Eighteen", + "19": "Nineteen"} + + tens = { "2": "Twenty", + "3": "Thirty", + "4": "Forty", + "5": "Fifty", + "6": "Sixty", + "7": "Seventy", + "8": "Eighty", + "9": "Ninety"} + + if int(triple_str[0]) != 0: + final_list.append("{} Hundred".format(numbers[triple_str[0]])) + if int(triple_str[1]) == 1: + final_list.append("{}".format(numbers[triple_str[1:3]])) + else: + if int(triple_str[1]) != 0: + final_list.append("{}".format(tens[triple_str[1]])) + if int(triple_str[2]) != 0: + final_list.append("{}".format(numbers[triple_str[2]])) + + return final_list + + + num_str = "{:0>12}".format(str(num)) + num_list = [] + final_num = "" + digit_dict = { 0: "Billion", + 3: "Million", + 6: "Thousand"} + + for x in range(0, 12, 3): + the_triple = num_str[x:x+3] + if the_triple == "000": + continue + else: + num_list.extend(decode(the_triple)) + if x == 9: break + num_list.append(digit_dict[x]) + + final_num = " ".join(num_list) + if final_num == "": + final_num = "Zero" + + return final_num From ecc1f01430461ccfbcef5766cd820ed005458b6b Mon Sep 17 00:00:00 2001 From: suman151 Date: Thu, 29 Oct 2020 17:10:30 +0530 Subject: [PATCH 331/357] Added path with maximum gold solution --- LeetCode/1219_path_with_maximum_gold.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 LeetCode/1219_path_with_maximum_gold.py diff --git a/LeetCode/1219_path_with_maximum_gold.py b/LeetCode/1219_path_with_maximum_gold.py new file mode 100644 index 0000000..7b76fff --- /dev/null +++ b/LeetCode/1219_path_with_maximum_gold.py @@ -0,0 +1,24 @@ +class Solution: + def getMaximumGold(self, grid: List[List[int]]) -> int: + def bfs(i,j): + stack = [(grid[i][j],i,j,set([(i,j)]))] + while stack: + temp = [] + for cur,i,j,p in stack: + if cur > self.res: + self.res = cur + self.best_res = p + for x, y in [[i+1,j], [i-1,j], [i,j+1], [i,j-1]]: + if 0<=x Date: Thu, 29 Oct 2020 17:10:41 +0530 Subject: [PATCH 332/357] Added solution for Problem 0401 Binary Watch --- .vscode/settings.json | 3 ++ LeetCode/0401_Binary_Watch.py | 69 +++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 .vscode/settings.json create mode 100644 LeetCode/0401_Binary_Watch.py diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..25c729f --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "python.pythonPath": "/bin/python3" +} \ No newline at end of file diff --git a/LeetCode/0401_Binary_Watch.py b/LeetCode/0401_Binary_Watch.py new file mode 100644 index 0000000..2b9f099 --- /dev/null +++ b/LeetCode/0401_Binary_Watch.py @@ -0,0 +1,69 @@ +class Solution(object): + def combination(self, n, k, inp, res): + # inp is expected to be a list of size n + #print n,k,inp,res + if k == 0: + res.append([i for i in inp]) + return + if k > n: + return + #for i in range(1,n+1): + inp[n-1] = 1 + self.combination(n-1,k-1, inp, res) + inp[n-1] = 0 + self.combination(n-1, k, inp, res) + + + def getHours(self, h): + if h == 0: + return ["0"] + if h == 1: + return ["1", "2", "4", "8"] + if h == 2: + return ["3", "5", "6", "9", "10"] + if h == 3: + return ["7", "11"] + + def getMinutes(self, m): + inp = [0,0,0,0,0,0] + res = [] + self.combination(6, m, inp, res) + mins = [1, 2, 4, 8, 16, 32] + minutes = [] + for comb in res: + i = 0 + mn = 0 + while i < 6: + if comb[i] == 1: + mn += mins[i] + i += 1 + if mn > 59: + continue + if mn < 10: + minutes.append("0" + str(mn)) + else: + minutes.append(str(mn)) + return minutes + + def readBinaryWatch(self, num): + """ + :type num: int + :rtype: List[str] + """ + i = 0 + res = [] + + while i <= num: + h = i + m = num - i + if h < 4 and m < 6: + lh = self.getHours(h) + #print lh + lm = self.getMinutes(m) + #print lm + for hr in lh: + for mn in lm: + res.append(hr + ":" + mn) + i += 1 + + return res From 5639c2a7681ad04076efc5013d539a2390c498e1 Mon Sep 17 00:00:00 2001 From: flick-23 Date: Thu, 29 Oct 2020 17:13:59 +0530 Subject: [PATCH 333/357] Added solution for Problem 0401 Binary Watch --- LeetCode/{0401_Binary_Watch.py => 0401_Binary_Watch_.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{0401_Binary_Watch.py => 0401_Binary_Watch_.py} (100%) diff --git a/LeetCode/0401_Binary_Watch.py b/LeetCode/0401_Binary_Watch_.py similarity index 100% rename from LeetCode/0401_Binary_Watch.py rename to LeetCode/0401_Binary_Watch_.py From 7f99033a3130b9b337c675af5cd9b1862051b709 Mon Sep 17 00:00:00 2001 From: suman151 Date: Thu, 29 Oct 2020 17:25:06 +0530 Subject: [PATCH 334/357] Added path with maximum gold solution --- LeetCode/1219_path_with_maximum_gold.py | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/LeetCode/1219_path_with_maximum_gold.py b/LeetCode/1219_path_with_maximum_gold.py index 7b76fff..d8d1e5d 100644 --- a/LeetCode/1219_path_with_maximum_gold.py +++ b/LeetCode/1219_path_with_maximum_gold.py @@ -1,24 +1,22 @@ class Solution: - def getMaximumGold(self, grid: List[List[int]]) -> int: - def bfs(i,j): - stack = [(grid[i][j],i,j,set([(i,j)]))] + def getMaximumGold(self, grid): + def bfs(i, j): + stack = [(grid[i][j], i, j, set([(i, j)]))] while stack: temp = [] - for cur,i,j,p in stack: + for cur, i, j, p in stack: if cur > self.res: self.res = cur self.best_res = p - for x, y in [[i+1,j], [i-1,j], [i,j+1], [i,j-1]]: - if 0<=x Date: Thu, 29 Oct 2020 17:31:47 +0530 Subject: [PATCH 335/357] Added solution for Problem 0209 Minimum Subarray Sum --- LeetCode/0209_ Minimum_Size_Subarray_Sum_.py | 55 ++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 LeetCode/0209_ Minimum_Size_Subarray_Sum_.py diff --git a/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py b/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py new file mode 100644 index 0000000..bd17997 --- /dev/null +++ b/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py @@ -0,0 +1,55 @@ +class Solution: + def minSubArrayLen(self, s, nums): + """ + :type s: int + :type nums: List[int] + :rtype: int + """ + + # approach: + # 1. build a prefix list and iterate it + # 2. at each iteration, use binary search to find prefix+s + # 3. after search done, get length between left and i + + n = len(nums) + result = n + 1 + + if n == 0: + return 0 + + # build prefix sums array + prefix = [0 for i in range(n+1)] + for i in range(1, n+1): + prefix[i] = prefix[i-1] + nums[i-1] + + # for each iteration i, we try to use binary search to find + # prefix[i] + s, which means the sum of subarray between i + # and left will be more than s + for i in range(n): + left = i + 1 + right = n + target = prefix[i] + s + + while left <= right: + m = left + (right - left) // 2 + + if prefix[m] < target: + left = m + 1 + + # in both greater and equal cases, we have to update + # right index for finding the leftist sum which is + # larger than target + else: + right = m - 1 + + # end for-loop immediately if left is greater than n because + # it means every sum will be less than targer in following iteration + if left > n: + break + + # if left is valid, left will be the leftist element that is + # larger than target, so length between left and i is what we need + if left - i < result: + result = left - i + + return 0 if result > n else result \ No newline at end of file From 1f6384d1902d6d01d3b7ee6cdd6a531b7d248d4b Mon Sep 17 00:00:00 2001 From: flick-23 Date: Thu, 29 Oct 2020 17:38:32 +0530 Subject: [PATCH 336/357] Added solution for Problem 0209 Minimum Subarray Sum --- LeetCode/0209_ Minimum_Size_Subarray_Sum_.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py b/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py index bd17997..0917675 100644 --- a/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py +++ b/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py @@ -10,7 +10,7 @@ def minSubArrayLen(self, s, nums): # 1. build a prefix list and iterate it # 2. at each iteration, use binary search to find prefix+s # 3. after search done, get length between left and i - + n = len(nums) result = n + 1 From cc5d6cf192f97ed6b21bbb3b571f61c8b8a970cf Mon Sep 17 00:00:00 2001 From: Venkatesh Dhongadi <51364640+flick-23@users.noreply.github.com> Date: Thu, 29 Oct 2020 18:00:59 +0530 Subject: [PATCH 337/357] Delete 0209_ Minimum_Size_Subarray_Sum_.py --- LeetCode/0209_ Minimum_Size_Subarray_Sum_.py | 55 -------------------- 1 file changed, 55 deletions(-) delete mode 100644 LeetCode/0209_ Minimum_Size_Subarray_Sum_.py diff --git a/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py b/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py deleted file mode 100644 index 0917675..0000000 --- a/LeetCode/0209_ Minimum_Size_Subarray_Sum_.py +++ /dev/null @@ -1,55 +0,0 @@ -class Solution: - def minSubArrayLen(self, s, nums): - """ - :type s: int - :type nums: List[int] - :rtype: int - """ - - # approach: - # 1. build a prefix list and iterate it - # 2. at each iteration, use binary search to find prefix+s - # 3. after search done, get length between left and i - - n = len(nums) - result = n + 1 - - if n == 0: - return 0 - - # build prefix sums array - prefix = [0 for i in range(n+1)] - for i in range(1, n+1): - prefix[i] = prefix[i-1] + nums[i-1] - - # for each iteration i, we try to use binary search to find - # prefix[i] + s, which means the sum of subarray between i - # and left will be more than s - for i in range(n): - left = i + 1 - right = n - target = prefix[i] + s - - while left <= right: - m = left + (right - left) // 2 - - if prefix[m] < target: - left = m + 1 - - # in both greater and equal cases, we have to update - # right index for finding the leftist sum which is - # larger than target - else: - right = m - 1 - - # end for-loop immediately if left is greater than n because - # it means every sum will be less than targer in following iteration - if left > n: - break - - # if left is valid, left will be the leftist element that is - # larger than target, so length between left and i is what we need - if left - i < result: - result = left - i - - return 0 if result > n else result \ No newline at end of file From 4ed65a287d3b2d8b12f219240a894e62422f6b2d Mon Sep 17 00:00:00 2001 From: flick-23 Date: Thu, 29 Oct 2020 18:02:55 +0530 Subject: [PATCH 338/357] Added solution for Problem 0209 Minimum Size Sub Array Sum --- 0209_Minimum_Size_Subarray_Sum_.py | 55 ++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 0209_Minimum_Size_Subarray_Sum_.py diff --git a/0209_Minimum_Size_Subarray_Sum_.py b/0209_Minimum_Size_Subarray_Sum_.py new file mode 100644 index 0000000..0917675 --- /dev/null +++ b/0209_Minimum_Size_Subarray_Sum_.py @@ -0,0 +1,55 @@ +class Solution: + def minSubArrayLen(self, s, nums): + """ + :type s: int + :type nums: List[int] + :rtype: int + """ + + # approach: + # 1. build a prefix list and iterate it + # 2. at each iteration, use binary search to find prefix+s + # 3. after search done, get length between left and i + + n = len(nums) + result = n + 1 + + if n == 0: + return 0 + + # build prefix sums array + prefix = [0 for i in range(n+1)] + for i in range(1, n+1): + prefix[i] = prefix[i-1] + nums[i-1] + + # for each iteration i, we try to use binary search to find + # prefix[i] + s, which means the sum of subarray between i + # and left will be more than s + for i in range(n): + left = i + 1 + right = n + target = prefix[i] + s + + while left <= right: + m = left + (right - left) // 2 + + if prefix[m] < target: + left = m + 1 + + # in both greater and equal cases, we have to update + # right index for finding the leftist sum which is + # larger than target + else: + right = m - 1 + + # end for-loop immediately if left is greater than n because + # it means every sum will be less than targer in following iteration + if left > n: + break + + # if left is valid, left will be the leftist element that is + # larger than target, so length between left and i is what we need + if left - i < result: + result = left - i + + return 0 if result > n else result \ No newline at end of file From 8d2a8a313b32bdf06e1de34c9ecb3ea466ad9498 Mon Sep 17 00:00:00 2001 From: Venkatesh Dhongadi <51364640+flick-23@users.noreply.github.com> Date: Thu, 29 Oct 2020 18:06:42 +0530 Subject: [PATCH 339/357] Delete 0209_Minimum_Size_Subarray_Sum_.py --- 0209_Minimum_Size_Subarray_Sum_.py | 55 ------------------------------ 1 file changed, 55 deletions(-) delete mode 100644 0209_Minimum_Size_Subarray_Sum_.py diff --git a/0209_Minimum_Size_Subarray_Sum_.py b/0209_Minimum_Size_Subarray_Sum_.py deleted file mode 100644 index 0917675..0000000 --- a/0209_Minimum_Size_Subarray_Sum_.py +++ /dev/null @@ -1,55 +0,0 @@ -class Solution: - def minSubArrayLen(self, s, nums): - """ - :type s: int - :type nums: List[int] - :rtype: int - """ - - # approach: - # 1. build a prefix list and iterate it - # 2. at each iteration, use binary search to find prefix+s - # 3. after search done, get length between left and i - - n = len(nums) - result = n + 1 - - if n == 0: - return 0 - - # build prefix sums array - prefix = [0 for i in range(n+1)] - for i in range(1, n+1): - prefix[i] = prefix[i-1] + nums[i-1] - - # for each iteration i, we try to use binary search to find - # prefix[i] + s, which means the sum of subarray between i - # and left will be more than s - for i in range(n): - left = i + 1 - right = n - target = prefix[i] + s - - while left <= right: - m = left + (right - left) // 2 - - if prefix[m] < target: - left = m + 1 - - # in both greater and equal cases, we have to update - # right index for finding the leftist sum which is - # larger than target - else: - right = m - 1 - - # end for-loop immediately if left is greater than n because - # it means every sum will be less than targer in following iteration - if left > n: - break - - # if left is valid, left will be the leftist element that is - # larger than target, so length between left and i is what we need - if left - i < result: - result = left - i - - return 0 if result > n else result \ No newline at end of file From 99861bc23be4bb1ba6c6e0384319a9e594d827c5 Mon Sep 17 00:00:00 2001 From: UdeshAthukorala Date: Thu, 29 Oct 2020 19:33:25 +0530 Subject: [PATCH 340/357] Add 0084_Largest_Rectangle_in_Histogram.py --- LeetCode/0084_Largest_Rectangle_in_Histogram.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 LeetCode/0084_Largest_Rectangle_in_Histogram.py diff --git a/LeetCode/0084_Largest_Rectangle_in_Histogram.py b/LeetCode/0084_Largest_Rectangle_in_Histogram.py new file mode 100644 index 0000000..8e1b7e0 --- /dev/null +++ b/LeetCode/0084_Largest_Rectangle_in_Histogram.py @@ -0,0 +1,15 @@ +class Solution: + def largestRectangleArea(self, heights: List[int]) -> int: + heights.append(0) + lst = [-1] + output = 0 + + for i in range(len(heights)): + while (heights[i] < heights[lst[-1]]): + height = heights[lst.pop()] + width = i - lst[-1] - 1 + output = max(output, height * width) + lst.append(i) + + heights.pop() + return output From 833fb6dd3e0455d316290347e2166dbbff7fb6b4 Mon Sep 17 00:00:00 2001 From: Soroosh Date: Thu, 29 Oct 2020 20:22:49 +0100 Subject: [PATCH 341/357] Solution added passing leetcode test --- LeetCode/0371_sum_of_two_integers.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/0371_sum_of_two_integers.py diff --git a/LeetCode/0371_sum_of_two_integers.py b/LeetCode/0371_sum_of_two_integers.py new file mode 100644 index 0000000..5f01711 --- /dev/null +++ b/LeetCode/0371_sum_of_two_integers.py @@ -0,0 +1,13 @@ +class Solution: + def getSum(self, a: int, b: int) -> int: + # 32 bits integer max and min + MAX = 0x7FFFFFFF + MIN = 0x80000000 + + mask = 0xFFFFFFFF + + while b != 0: + carry = a & b + a, b = (a ^ b) & mask, (carry << 1) & mask + + return a if a <= MAX else ~(a ^ mask) \ No newline at end of file From 8f27130d92fd1e9428477c30ae65b6fa85ac2aa3 Mon Sep 17 00:00:00 2001 From: Achyut-sudo <71660666+Achyut-sudo@users.noreply.github.com> Date: Fri, 30 Oct 2020 01:59:19 +0530 Subject: [PATCH 342/357] uploaded code --- ...bstring_with_Concatenation_of_All_Words.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 LeetCode/0030_Substring_with_Concatenation_of_All_Words.py diff --git a/LeetCode/0030_Substring_with_Concatenation_of_All_Words.py b/LeetCode/0030_Substring_with_Concatenation_of_All_Words.py new file mode 100644 index 0000000..5ca0881 --- /dev/null +++ b/LeetCode/0030_Substring_with_Concatenation_of_All_Words.py @@ -0,0 +1,26 @@ +class Solution: + + def findSubstring(self,s, words): + self.Incr = len(words[0]) + self.LenWords = len(words) + self.Index = 0 + self.m = self.Incr * self.LenWords + self.Max = len(s) - self.m + self.output = [] + while self.Index <= self.Max : + WordsCopy = words.copy() + upperBound = self.Index + lowerBound = upperBound + self.m + for i in range(upperBound,lowerBound,self.Incr): + tempStr = s[i: i + self.Incr] + if tempStr in WordsCopy : + WordsCopy.remove(tempStr) + else: + break + if WordsCopy == [] : + self.output.append(self.Index) + self.Index += 1 + return self.output + + + \ No newline at end of file From afc5b6f4d0eaa49238b96ed9b758e6ae103a2e0c Mon Sep 17 00:00:00 2001 From: Sounakde Date: Fri, 30 Oct 2020 14:15:32 +0530 Subject: [PATCH 343/357] adding 0389_FindThe Difference solution for merging --- LeetCode/0389_FindTheDifference.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 LeetCode/0389_FindTheDifference.py diff --git a/LeetCode/0389_FindTheDifference.py b/LeetCode/0389_FindTheDifference.py new file mode 100644 index 0000000..06c2265 --- /dev/null +++ b/LeetCode/0389_FindTheDifference.py @@ -0,0 +1,30 @@ +import sys +import random + +# The function which will do the main operation of finding the difference + +class Solution: + def FindTheDifference(self, s: str, t: str) -> str: + for char in s: + if 96 <= ord(char) <= 123: + if 0 < len(s) < 1000: + if len(t) == len(s) + 1: + extra_char = t[-1] + return extra_char + else: + print("Differnce between second and first string is more than 1") + if s == '': + if 0 <= len(s) <= 1000: + if len(t) == len(s) + 1: + extra_char = t[-1] + return extra_char + else: + print("Differnce between second and first string is more than 1") + +if __name__ == "__main__": + # Initialising the string variable with input from the user + s = sys.argv[1] + # Initialising the second string variable with input from user + t = sys.argv[2] + solution = Solution().FindTheDifference(s, t) + print(solution) \ No newline at end of file From e3cf5dff48bec066be1ff8bfcf3c4b031f3b898a Mon Sep 17 00:00:00 2001 From: Achyut-sudo <71660666+Achyut-sudo@users.noreply.github.com> Date: Fri, 30 Oct 2020 21:14:40 +0530 Subject: [PATCH 344/357] Uploaded code --- LeetCode/0289_Game_of_Life.py | 42 +++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 LeetCode/0289_Game_of_Life.py diff --git a/LeetCode/0289_Game_of_Life.py b/LeetCode/0289_Game_of_Life.py new file mode 100644 index 0000000..a312714 --- /dev/null +++ b/LeetCode/0289_Game_of_Life.py @@ -0,0 +1,42 @@ +class Solution: + def gameOfLife(self, board): + self.m = len(board) + self.n = len(board[0]) + self.board = [rows.copy() for rows in board] + for i in range(self.m): + for j in range(self.n): + state = self.board[i][j] + dataDict = self.CheckNeighbors(i,j) + nextGen = self.NextGenState(state,dataDict) + board[i][j] = nextGen + + + def CheckNeighbors(self,row,column): + retDict = {"live":0,"dead":0} + lb = max(column-1,0) + rb = min(column+2,self.n) + tb = max(row -1,0) + bb = min(row+2,self.m) + for rows in range(tb,bb): + for columns in range(lb,rb): + if rows != row or columns != column : + neighbor = self.board[rows][columns] + if neighbor == 1: + retDict["live"] += 1 + else: + retDict["dead"] += 1 + return retDict + + def NextGenState(self,state,dataDict): + finalState = 0 + liveNeighbors = dataDict["live"] + if state == 1: + if liveNeighbors == 2 or liveNeighbors == 3: + finalState = 1 + else: + if liveNeighbors == 3: + finalState = 1 + return finalState + + + From 9f7896659ed72ca3d3bab4f577dfcae2aff0c174 Mon Sep 17 00:00:00 2001 From: Biraj De Date: Fri, 30 Oct 2020 23:59:56 +0530 Subject: [PATCH 345/357] Added 1550_Three_Consecutive_Odds.py --- LeetCode/1550_Three_Consecutive_Odds.py | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 LeetCode/1550_Three_Consecutive_Odds.py diff --git a/LeetCode/1550_Three_Consecutive_Odds.py b/LeetCode/1550_Three_Consecutive_Odds.py new file mode 100644 index 0000000..cc99bea --- /dev/null +++ b/LeetCode/1550_Three_Consecutive_Odds.py @@ -0,0 +1,3 @@ +class Solution: + def threeConsecutiveOdds(self, arr: List[int]) -> bool: + return '111' in "".join([str(i%2) for i in arr]) \ No newline at end of file From 72f8973c98ccb66b0d4c3688f021b8e091fe20e5 Mon Sep 17 00:00:00 2001 From: Bar Rotstein Date: Sat, 31 Oct 2020 11:42:36 +0200 Subject: [PATCH 346/357] added a buddy strings implementation --- LeetCode/0859_Buddy_String.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 LeetCode/0859_Buddy_String.py diff --git a/LeetCode/0859_Buddy_String.py b/LeetCode/0859_Buddy_String.py new file mode 100644 index 0000000..fdcec92 --- /dev/null +++ b/LeetCode/0859_Buddy_String.py @@ -0,0 +1,13 @@ +class Solution: + def buddyStrings(self, A: str, B: str) -> bool: + indexes_to_swap = [] + for idx, string in enumerate(A): + if string != B[idx]: + indexes_to_swap.append(idx) + if len(indexes_to_swap) > 2: + return False + + if len(indexes_to_swap) != 2: + return false + + return A[indexes_to_swap[0]] == B[indexes_to_swap[1]] and A[indexes_to_swap[1]] == B[indexes_to_swap[0]] From 1c40079195ffe5f055e098dc12c20a65b7d3fbd6 Mon Sep 17 00:00:00 2001 From: barrotsteindev Date: Sat, 31 Oct 2020 12:06:35 +0200 Subject: [PATCH 347/357] pass all LeetCode tests --- LeetCode/0859_Buddy_String.py | 44 ++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/LeetCode/0859_Buddy_String.py b/LeetCode/0859_Buddy_String.py index fdcec92..69f4602 100644 --- a/LeetCode/0859_Buddy_String.py +++ b/LeetCode/0859_Buddy_String.py @@ -1,13 +1,31 @@ -class Solution: - def buddyStrings(self, A: str, B: str) -> bool: - indexes_to_swap = [] - for idx, string in enumerate(A): - if string != B[idx]: - indexes_to_swap.append(idx) - if len(indexes_to_swap) > 2: - return False - - if len(indexes_to_swap) != 2: - return false - - return A[indexes_to_swap[0]] == B[indexes_to_swap[1]] and A[indexes_to_swap[1]] == B[indexes_to_swap[0]] +class Solution: + @staticmethod + def update_char_count(char, char_count): + curr_char_count = char_count.get(char, 0) + curr_char_count += 1 + char_count[char] = curr_char_count + + + def buddyStrings(self, A: str, B: str) -> bool: + char_count = {} + indexes_to_swap = [] + dup = False + for idx, string in enumerate(A): + curr_char_count = char_count.get(string, 0) + curr_char_count += 1 + char_count[string] = curr_char_count + if (curr_char_count > 1): + dup = True + if string != B[idx]: + indexes_to_swap.append(idx) + if len(indexes_to_swap) > 2: + return False + + if len(indexes_to_swap) == 1: + return False + + if len(indexes_to_swap) == 2: + return A[indexes_to_swap[0]] == B[indexes_to_swap[1]] and A[indexes_to_swap[1]] == B[indexes_to_swap[0]] + return dup + +print(Solution().buddyStrings("aa", "aa")) From fdf2ed0cb42d979e2d83ef1a8c61bfc4c77b98b0 Mon Sep 17 00:00:00 2001 From: barrotsteindev Date: Sat, 31 Oct 2020 12:09:09 +0200 Subject: [PATCH 348/357] removed unused code --- LeetCode/0859_Buddy_String.py | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/LeetCode/0859_Buddy_String.py b/LeetCode/0859_Buddy_String.py index 69f4602..ddd3014 100644 --- a/LeetCode/0859_Buddy_String.py +++ b/LeetCode/0859_Buddy_String.py @@ -1,12 +1,7 @@ class Solution: - @staticmethod - def update_char_count(char, char_count): - curr_char_count = char_count.get(char, 0) - curr_char_count += 1 - char_count[char] = curr_char_count - - - def buddyStrings(self, A: str, B: str) -> bool: + def buddyStrings(self, A: str, B: str) -> bool: + if len(A) != len(B): + return False char_count = {} indexes_to_swap = [] dup = False From d1e334ce19f10e77859511a986fea30d018b3a46 Mon Sep 17 00:00:00 2001 From: barrotsteindev Date: Sat, 31 Oct 2020 12:09:34 +0200 Subject: [PATCH 349/357] removed print() --- LeetCode/0859_Buddy_String.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/LeetCode/0859_Buddy_String.py b/LeetCode/0859_Buddy_String.py index ddd3014..55695c9 100644 --- a/LeetCode/0859_Buddy_String.py +++ b/LeetCode/0859_Buddy_String.py @@ -22,5 +22,3 @@ def buddyStrings(self, A: str, B: str) -> bool: if len(indexes_to_swap) == 2: return A[indexes_to_swap[0]] == B[indexes_to_swap[1]] and A[indexes_to_swap[1]] == B[indexes_to_swap[0]] return dup - -print(Solution().buddyStrings("aa", "aa")) From ded0eff51ec486b22c442ace5793c6d68006ffcc Mon Sep 17 00:00:00 2001 From: Sounakde Date: Sat, 31 Oct 2020 15:44:07 +0530 Subject: [PATCH 350/357] adding 0389_FindTheDifference solution for merging with corresponding issue --- LeetCode/0389_FindTheDifference.py | 40 +++++++++++------------------- 1 file changed, 15 insertions(+), 25 deletions(-) diff --git a/LeetCode/0389_FindTheDifference.py b/LeetCode/0389_FindTheDifference.py index 06c2265..7495dcf 100644 --- a/LeetCode/0389_FindTheDifference.py +++ b/LeetCode/0389_FindTheDifference.py @@ -1,30 +1,20 @@ import sys -import random - -# The function which will do the main operation of finding the difference class Solution: def FindTheDifference(self, s: str, t: str) -> str: - for char in s: - if 96 <= ord(char) <= 123: - if 0 < len(s) < 1000: - if len(t) == len(s) + 1: - extra_char = t[-1] - return extra_char - else: - print("Differnce between second and first string is more than 1") - if s == '': - if 0 <= len(s) <= 1000: - if len(t) == len(s) + 1: - extra_char = t[-1] - return extra_char - else: - print("Differnce between second and first string is more than 1") + a = 0 + b = 0 + if 0 <= len(s) <= 1000: + for chars in s: + if 97 <= ord(chars) <= 122: + a += ord(chars) + for letters in t: + if 97 <= ord(letters) <= 122: + b += ord(letters) + return chr(b - a) + -if __name__ == "__main__": - # Initialising the string variable with input from the user - s = sys.argv[1] - # Initialising the second string variable with input from user - t = sys.argv[2] - solution = Solution().FindTheDifference(s, t) - print(solution) \ No newline at end of file +s = sys.argv[1] +t = sys.argv[2] +solution = Solution().FindTheDifference(s,t) +print(solution) \ No newline at end of file From f74d5624d8adba23b943a0fdc7d304bd7a39c5d6 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Sat, 31 Oct 2020 19:23:50 +0100 Subject: [PATCH 351/357] Delete settings.json --- .vscode/settings.json | 3 --- 1 file changed, 3 deletions(-) delete mode 100644 .vscode/settings.json diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 25c729f..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "python.pythonPath": "/bin/python3" -} \ No newline at end of file From 8a66d3bfbaeda24b360f54dda00b41bbe10a57b6 Mon Sep 17 00:00:00 2001 From: chw9 <43727884+chw9@users.noreply.github.com> Date: Sat, 31 Oct 2020 15:06:28 -0400 Subject: [PATCH 352/357] added solution to 0599 --- .../0599_Minimum_Index_Sum_of_Two_Lists.py | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 LeetCode/0599_Minimum_Index_Sum_of_Two_Lists.py diff --git a/LeetCode/0599_Minimum_Index_Sum_of_Two_Lists.py b/LeetCode/0599_Minimum_Index_Sum_of_Two_Lists.py new file mode 100644 index 0000000..d43ce31 --- /dev/null +++ b/LeetCode/0599_Minimum_Index_Sum_of_Two_Lists.py @@ -0,0 +1,20 @@ +class Solution(object): + def findRestaurant(self, list1, list2): + ind1 = 0 + ind2 = 0 + ind_sum = sys.maxsize + rest = list() + + for restaurant1 in list1: + for restaurant2 in list2: + if (restaurant1 == restaurant2) and ((ind1 + ind2) < ind_sum): + ind_sum = ind1 + ind2 + rest = [] + rest.append(restaurant2) + elif (restaurant1 == restaurant2) and ((ind1 + ind2) == ind_sum): + rest.append(restaurant2) + ind2 = ind2 + 1 + ind1 = ind1 + 1 + ind2 = 0 + + return rest \ No newline at end of file From eabee1b0320242e977f1d65b7bb2459e75d87d91 Mon Sep 17 00:00:00 2001 From: Sounakde <65114561+Sounakde@users.noreply.github.com> Date: Sun, 1 Nov 2020 09:59:42 +0530 Subject: [PATCH 353/357] Update 0389_FindTheDifference.py I have edited the file and checked the solution in LeetCode website a 2nd time. The solution is being accepted by the website now. --- LeetCode/0389_FindTheDifference.py | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/LeetCode/0389_FindTheDifference.py b/LeetCode/0389_FindTheDifference.py index 7495dcf..0da6419 100644 --- a/LeetCode/0389_FindTheDifference.py +++ b/LeetCode/0389_FindTheDifference.py @@ -1,7 +1,5 @@ -import sys - class Solution: - def FindTheDifference(self, s: str, t: str) -> str: + def findTheDifference(self, s: str, t: str) -> str: a = 0 b = 0 if 0 <= len(s) <= 1000: @@ -12,9 +10,3 @@ def FindTheDifference(self, s: str, t: str) -> str: if 97 <= ord(letters) <= 122: b += ord(letters) return chr(b - a) - - -s = sys.argv[1] -t = sys.argv[2] -solution = Solution().FindTheDifference(s,t) -print(solution) \ No newline at end of file From dc3323840e9d8121c596338273ce96e958fd541f Mon Sep 17 00:00:00 2001 From: flick-23 Date: Sun, 1 Nov 2020 13:36:22 +0530 Subject: [PATCH 354/357] Added Solution to Problem 0234 Palindrome Linked List --- LeetCode/0234_Palindrome_Linked_List_.py | 42 ++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 LeetCode/0234_Palindrome_Linked_List_.py diff --git a/LeetCode/0234_Palindrome_Linked_List_.py b/LeetCode/0234_Palindrome_Linked_List_.py new file mode 100644 index 0000000..2522fc7 --- /dev/null +++ b/LeetCode/0234_Palindrome_Linked_List_.py @@ -0,0 +1,42 @@ +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + + def reverse(self, head): + p = head.next + while p and p.next: + tmp = p.next + p.next = p.next.next + tmp.next = head.next + head.next = tmp + + def isPalindrome(self, head): + """ + :type head: ListNode + :rtype: bool + """ + + #get middle pointer + p1 = ListNode(0) + p1.next = head + p2 = p1 + while p2 and p2.next: + p1 = p1.next + p2 = p2.next.next + + # reverse second half of list + self.reverse(p1) + + # check palindrome + p1 = p1.next + p2 = head + while p1: + if p1.val != p2.val: + return False + p1 = p1.next + p2 = p2.next + return True \ No newline at end of file From 8675615a41c52c6fb38532e888e97a82ebeb718e Mon Sep 17 00:00:00 2001 From: Prince Singh Tomar Date: Mon, 2 Nov 2020 02:31:06 +0530 Subject: [PATCH 355/357] added code of Questions 0052,0110 and 0145 --- LeetCode/0052_N_Queens_2.py | 13 ++++++++++++ LeetCode/0110_balanced_binary_tree.py | 21 +++++++++++++++++++ .../0145_binary_tree_postorder_traversal.py | 18 ++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 LeetCode/0052_N_Queens_2.py create mode 100644 LeetCode/0110_balanced_binary_tree.py create mode 100644 LeetCode/0145_binary_tree_postorder_traversal.py diff --git a/LeetCode/0052_N_Queens_2.py b/LeetCode/0052_N_Queens_2.py new file mode 100644 index 0000000..30b03d1 --- /dev/null +++ b/LeetCode/0052_N_Queens_2.py @@ -0,0 +1,13 @@ +class Solution(object): + # @return an integer + def totalNQueens(self, n): + return self.totalNQueensRecu([], 0, n) + + def totalNQueensRecu(self, solution, row, n): + if row == n: + return 1 + result = 0 + for i in xrange(n): + if i not in solution and reduce(lambda acc, j: abs(row - j) != abs(i - solution[j]) and acc, xrange(len(solution)), True): + result += self.totalNQueensRecu(solution + [i], row + 1, n) + return result \ No newline at end of file diff --git a/LeetCode/0110_balanced_binary_tree.py b/LeetCode/0110_balanced_binary_tree.py new file mode 100644 index 0000000..e99066c --- /dev/null +++ b/LeetCode/0110_balanced_binary_tree.py @@ -0,0 +1,21 @@ +#class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + + +class Solution(object): + # @param root, a tree node + # @return a boolean + def isBalanced(self, root): + def getHeight(root): + if root is None: + return 0 + left_height, right_height = \ + getHeight(root.left), getHeight(root.right) + if left_height < 0 or right_height < 0 or \ + abs(left_height - right_height) > 1: + return -1 + return max(left_height, right_height) + 1 + return (getHeight(root) >= 0) \ No newline at end of file diff --git a/LeetCode/0145_binary_tree_postorder_traversal.py b/LeetCode/0145_binary_tree_postorder_traversal.py new file mode 100644 index 0000000..ef7c7fc --- /dev/null +++ b/LeetCode/0145_binary_tree_postorder_traversal.py @@ -0,0 +1,18 @@ +class Solution(object): + def postorderTraversal(self, root): + """ + :type root: TreeNode + :rtype: List[int] + """ + result, stack = [], [(root, False)] + while stack: + root, is_visited = stack.pop() + if root is None: + continue + if is_visited: + result.append(root.val) + else: + stack.append((root, True)) + stack.append((root.right, False)) + stack.append((root.left, False)) + return result \ No newline at end of file From 72e0608ba0ce41229653e75f0b03ea212be8f88e Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Mon, 2 Nov 2020 00:18:37 +0100 Subject: [PATCH 356/357] Renaming Files Missing Leading Zero --- ...e_in_a_Linked_List.py => 0237_Delete_Node_in_a_Linked_List.py} | 0 ...Preorder_Traversal.py => 0589_Nary_Tree_Preorder_Traversal.py} | 0 .../{997_Find_The_Town_Judge.py => 0997_Find_The_Town_Judge.py} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename LeetCode/{237_Delete_Node_in_a_Linked_List.py => 0237_Delete_Node_in_a_Linked_List.py} (100%) rename LeetCode/{589_Nary_Tree_Preorder_Traversal.py => 0589_Nary_Tree_Preorder_Traversal.py} (100%) rename LeetCode/{997_Find_The_Town_Judge.py => 0997_Find_The_Town_Judge.py} (100%) diff --git a/LeetCode/237_Delete_Node_in_a_Linked_List.py b/LeetCode/0237_Delete_Node_in_a_Linked_List.py similarity index 100% rename from LeetCode/237_Delete_Node_in_a_Linked_List.py rename to LeetCode/0237_Delete_Node_in_a_Linked_List.py diff --git a/LeetCode/589_Nary_Tree_Preorder_Traversal.py b/LeetCode/0589_Nary_Tree_Preorder_Traversal.py similarity index 100% rename from LeetCode/589_Nary_Tree_Preorder_Traversal.py rename to LeetCode/0589_Nary_Tree_Preorder_Traversal.py diff --git a/LeetCode/997_Find_The_Town_Judge.py b/LeetCode/0997_Find_The_Town_Judge.py similarity index 100% rename from LeetCode/997_Find_The_Town_Judge.py rename to LeetCode/0997_Find_The_Town_Judge.py From 7256a9e3bb71d37614c8cfa7bbb6d011ac456ae3 Mon Sep 17 00:00:00 2001 From: Viktoria Jechsmayr Date: Tue, 21 Sep 2021 20:57:08 +0200 Subject: [PATCH 357/357] Update README.md --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 46f4b1a..491214d 100644 --- a/README.md +++ b/README.md @@ -86,7 +86,8 @@ git push origin branch-name * PRs that "correct" Typos or spam files with comments * PRs that "correct" Coding Styles - Please accept that everybody has a different style -## Hacktoberfest +## Hacktoberfest 2020 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. +This Repository is open for **Hacktoberfest 2020 ONLY**! No PRs/Issues for Hacktoberfest 2021 or later will be accepted and marked as **invalid/spam** __Thank You!__