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 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/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 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 diff --git a/LeetCode/0212_Word_search_II.py b/LeetCode/0212_Word_search_II.py new file mode 100644 index 0000000..3c5de35 --- /dev/null +++ b/LeetCode/0212_Word_search_II.py @@ -0,0 +1,55 @@ +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 + 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 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/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 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 + + + 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 diff --git a/LeetCode/0389_FindTheDifference.py b/LeetCode/0389_FindTheDifference.py new file mode 100644 index 0000000..0da6419 --- /dev/null +++ b/LeetCode/0389_FindTheDifference.py @@ -0,0 +1,12 @@ +class Solution: + def findTheDifference(self, s: str, t: str) -> str: + 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) 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 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/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 diff --git a/LeetCode/0859_Buddy_String.py b/LeetCode/0859_Buddy_String.py new file mode 100644 index 0000000..55695c9 --- /dev/null +++ b/LeetCode/0859_Buddy_String.py @@ -0,0 +1,24 @@ +class Solution: + def buddyStrings(self, A: str, B: str) -> bool: + if len(A) != len(B): + return False + 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 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) 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 diff --git a/LeetCode/1219_path_with_maximum_gold.py b/LeetCode/1219_path_with_maximum_gold.py new file mode 100644 index 0000000..d8d1e5d --- /dev/null +++ b/LeetCode/1219_path_with_maximum_gold.py @@ -0,0 +1,22 @@ +class Solution: + 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: + 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 < m and 0 <= y < n and grid[x][y] and (x, y) not in p: + temp.append((cur + grid[x][y], x, y, p | {(x, y)})) + stack = temp + m, n = len(grid), len(grid[0]) + self.res = 0 + self.best_res = set() + for row in range(m): + for col in range(n): + if grid[row][col] and (row, col) not in self.best_res: + bfs(row, col) + return self.res 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 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!__