diff --git a/Python/balanced-binary-tree.py b/Python/balanced-binary-tree.py
index fbf1326ab..c65c301ba 100644
--- a/Python/balanced-binary-tree.py
+++ b/Python/balanced-binary-tree.py
@@ -3,37 +3,32 @@
#
# Given a binary tree, determine if it is height-balanced.
#
-# For this problem, a height-balanced binary tree is defined as a binary tree
-# in which the depth of the two subtrees of every node never differ by more than 1.
+# For this problem, a height-balanced binary tree is defined as a binary
+# tree
+# in which the depth of the two subtrees of every node never differ by more
+# than 1.
#
+
# Definition for a binary tree node
-class TreeNode:
+class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
-class Solution:
+
+class Solution(object):
# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
- return (self.getHeight(root) >= 0)
-
- def getHeight(self, root):
- if root is None:
- return 0
- left_height, right_height = self.getHeight(root.left), self.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
-
-if __name__ == "__main__":
- root = TreeNode(0)
- root.left = TreeNode(1)
- result = Solution().isBalanced(root)
- print result
-
- root.left.left = TreeNode(2)
- result = Solution().isBalanced(root)
- print result
+ 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)
diff --git a/Python/base-7.py b/Python/base-7.py
index b6544bd02..5fbc956a7 100644
--- a/Python/base-7.py
+++ b/Python/base-7.py
@@ -11,9 +11,11 @@
# Output: "-10"
# Note: The input will be in range of [-1e7, 1e7].
+
class Solution(object):
def convertToBase7(self, num):
- if num < 0: return '-' + self.convertToBase7(-num)
+ if num < 0:
+ return '-' + self.convertToBase7(-num)
result = ''
while num:
result = str(num % 7) + result
@@ -27,6 +29,8 @@ def convertToBase7(self, num):
:type num: int
:rtype: str
"""
- if num < 0: return '-' + self.convertToBase7(-num)
- if num < 7: return str(num)
+ if num < 0:
+ return '-' + self.convertToBase7(-num)
+ if num < 7:
+ return str(num)
return self.convertToBase7(num // 7) + str(num % 7)
diff --git a/Python/baseball-game.py b/Python/baseball-game.py
index ede8ff9d9..309e1a45f 100644
--- a/Python/baseball-game.py
+++ b/Python/baseball-game.py
@@ -4,38 +4,45 @@
# You're now a baseball game point recorder.
# Given a list of strings, each string can be one of the 4 following types:
#
-# 1. Integer (one round's score): Directly represents the number of points you get in this round.
-# 2. "+" (one round's score): Represents that the points you get in this round are
-# the sum of the last two valid round's points.
-# 3. "D" (one round's score): Represents that the points you get in this round are
-# the doubled data of the last valid round's points.
-# 4. "C" (an operation, which isn't a round's score): Represents the last valid round's points
-# you get were invalid and should be removed.
-#
-# Each round's operation is permanent and could have an impact on the round before and the round after.
+# 1. Integer (one round's score): Directly represents the number of points
+# you get in this round.
+# 2. "+" (one round's score): Represents that the points you get in
+# this round are the sum of the last two valid
+# round's points.
+# 3. "D" (one round's score): Represents that the points you get in this round
+# are the doubled data of the last valid round's
+# points.
+# 4. "C" (an operation, which isn't a round's score): Represents the last
+# valid round's points you get were invalid and
+# should be removed.
+#
+# Each round's operation is permanent and could have an impact on the round
+# before and the round after.
# You need to return the sum of the points you could get in all the rounds.
#
# Example 1:
#
# Input: ["5","2","C","D","+"]
# Output: 30
-# Explanation:
+# Explanation:
# Round 1: You could get 5 points. The sum is: 5.
# Round 2: You could get 2 points. The sum is: 7.
-# Operation 1: The round 2's data was invalid. The sum is: 5.
-# Round 3: You could get 10 points (the round 2's data has been removed). The sum is: 15.
+# Operation 1: The round 2's data was invalid. The sum is: 5.
+# Round 3: You could get 10 points (the round 2's data has been removed).
+# The sum is: 15.
# Round 4: You could get 5 + 10 = 15 points. The sum is: 30.
-#
+#
# Example 2:
#
# Input: ["5","-2","4","C","D","9","+","+"]
# Output: 27
-# Explanation:
+# Explanation:
# Round 1: You could get 5 points. The sum is: 5.
# Round 2: You could get -2 points. The sum is: 3.
# Round 3: You could get 4 points. The sum is: 7.
-# Operation 1: The round 3's data is invalid. The sum is: 3.
-# Round 4: You could get -4 points (the round 3's data has been removed). The sum is: -1.
+# Operation 1: The round 3's data is invalid. The sum is: 3.
+# Round 4: You could get -4 points (the round 3's data has been removed).
+# The sum is: -1.
# Round 5: You could get 9 points. The sum is: 8.
# Round 6: You could get -4 + 9 = 5 points. The sum is 13.
# Round 7: You could get 9 + 5 = 14 points. The sum is 27.
@@ -43,7 +50,8 @@
# Note:
# The size of the input list will be between 1 and 1000.
# Every integer represented in the list will be between -30000 and 30000.
-
+
+
class Solution(object):
def calPoints(self, ops):
"""
diff --git a/Python/basic-calculator-ii.py b/Python/basic-calculator-ii.py
index 4575b8a69..03df2953e 100644
--- a/Python/basic-calculator-ii.py
+++ b/Python/basic-calculator-ii.py
@@ -3,7 +3,7 @@
#
# Implement a basic calculator to evaluate a simple expression string.
#
-# The expression string contains only non-negative integers, +, -, *, /
+# The expression string contains only non-negative integers, +, -, *, /
# operators and empty spaces . The integer division should truncate toward zero.
#
# You may assume that the given expression is always valid.
@@ -38,10 +38,10 @@ def calculate(self, s):
while operators[-1] != ')':
self.compute(operands, operators)
operators.pop()
-
+
while operators:
self.compute(operands, operators)
-
+
return operands[-1]
def compute(self, operands, operators):
diff --git a/Python/basic-calculator-iii.py b/Python/basic-calculator-iii.py
index 0010d2a4d..04568b2cf 100644
--- a/Python/basic-calculator-iii.py
+++ b/Python/basic-calculator-iii.py
@@ -46,10 +46,10 @@ def calculate(self, s):
while operators[-1] != ')':
self.compute(operands, operators)
operators.pop()
-
+
while operators:
self.compute(operands, operators)
-
+
return operands[-1]
def compute(self, operands, operators):
@@ -63,4 +63,4 @@ def compute(self, operands, operators):
operands.append(left * right)
elif op == '/':
operands.append(left / right)
-
+
diff --git a/Python/basic-calculator.py b/Python/basic-calculator.py
index ea4ca3245..cae7f5527 100644
--- a/Python/basic-calculator.py
+++ b/Python/basic-calculator.py
@@ -32,10 +32,10 @@ def calculate(self, s):
while operators[-1] != ')':
self.compute(operands, operators)
operators.pop()
-
+
while operators:
self.compute(operands, operators)
-
+
return operands[-1]
def compute(self, operands, operators):
diff --git a/Python/battleships-in-a-board.py b/Python/battleships-in-a-board.py
index 9f9c49944..7d6c7490b 100644
--- a/Python/battleships-in-a-board.py
+++ b/Python/battleships-in-a-board.py
@@ -9,7 +9,7 @@
# Battleships can only be placed horizontally or vertically. In other words,
# they can only be made of the shape 1xN (1 row, N columns) or Nx1 (N rows, 1 column),
# where N can be of any size.
-# At least one horizontal or vertical cell separates between two battleships -
+# At least one horizontal or vertical cell separates between two battleships -
# there are no adjacent battleships.
#
# Example:
diff --git a/Python/beautiful-arrangement-ii.py b/Python/beautiful-arrangement-ii.py
index 007a28eb6..e9617beec 100644
--- a/Python/beautiful-arrangement-ii.py
+++ b/Python/beautiful-arrangement-ii.py
@@ -3,7 +3,7 @@
# Given two integers n and k,
# you need to construct a list which contains n different positive integers ranging
-# from 1 to n and obeys the following requirement:
+# from 1 to n and obeys the following requirement:
# Suppose this list is [a1, a2, a3, ... , an],
# then the list [|a1 - a2|, |a2 - a3|, |a3 - a4|, ... , |an-1 - an|] has exactly k distinct integers.
#
diff --git a/Python/beautiful-arrangement.py b/Python/beautiful-arrangement.py
index 383209c20..64327bfcd 100644
--- a/Python/beautiful-arrangement.py
+++ b/Python/beautiful-arrangement.py
@@ -2,7 +2,7 @@
# Space: O(n)
# Suppose you have N integers from 1 to N.
-# We define a beautiful arrangement as an array that is constructed by these N numbers successfully
+# We define a beautiful arrangement as an array that is constructed by these N numbers successfully
# if one of the following is true for the ith position (1 <= i <= N) in this array:
#
# The number at the ith position is divisible by i.
@@ -12,7 +12,7 @@
# Example 1:
# Input: 2
# Output: 2
-# Explanation:
+# Explanation:
#
# The first beautiful arrangement is [1, 2]:
#
diff --git a/Python/best-meeting-point.py b/Python/best-meeting-point.py
index 52b481624..ca5554f63 100644
--- a/Python/best-meeting-point.py
+++ b/Python/best-meeting-point.py
@@ -13,10 +13,10 @@ def minTotalDistance(self, grid):
y = [j for row in grid for j, v in enumerate(row) if v == 1]
mid_x = self.findKthLargest(x, len(x) / 2 + 1)
mid_y = self.findKthLargest(y, len(y) / 2 + 1)
-
+
return sum([abs(mid_x-i) + abs(mid_y-j) \
for i, row in enumerate(grid) for j, v in enumerate(row) if v == 1])
-
+
def findKthLargest(self, nums, k):
left, right = 0, len(nums) - 1
while left <= right:
@@ -28,7 +28,7 @@ def findKthLargest(self, nums, k):
right = new_pivot_idx - 1
else: # new_pivot_idx < k - 1.
left = new_pivot_idx + 1
-
+
def PartitionAroundPivot(self, left, right, pivot_idx, nums):
pivot_value = nums[pivot_idx]
new_pivot_idx = left
@@ -37,6 +37,6 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums):
if nums[i] > pivot_value:
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
-
+
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
diff --git a/Python/best-time-to-buy-and-sell-stock-ii.py b/Python/best-time-to-buy-and-sell-stock-ii.py
index 133ed078a..b0d12c7a9 100644
--- a/Python/best-time-to-buy-and-sell-stock-ii.py
+++ b/Python/best-time-to-buy-and-sell-stock-ii.py
@@ -1,13 +1,13 @@
# Time: O(n)
# Space: O(1)
#
-# Say you have an array for which the ith element is
+# Say you have an array for which the ith element is
# the price of a given stock on day i.
#
-# Design an algorithm to find the maximum profit.
-# You may complete as many transactions as you like
-# (ie, buy one and sell one share of the stock multiple times).
-# However, you may not engage in multiple transactions at the same time
+# Design an algorithm to find the maximum profit.
+# You may complete as many transactions as you like
+# (ie, buy one and sell one share of the stock multiple times).
+# However, you may not engage in multiple transactions at the same time
# (ie, you must sell the stock before you buy again).
@@ -17,7 +17,7 @@ class Solution:
def maxProfit(self, prices):
profit = 0
for i in xrange(len(prices) - 1):
- profit += max(0, prices[i + 1] - prices[i])
+ profit += max(0, prices[i + 1] - prices[i])
return profit
def maxProfit2(self, prices):
diff --git a/Python/best-time-to-buy-and-sell-stock-iii.py b/Python/best-time-to-buy-and-sell-stock-iii.py
index 114c1b321..89109f853 100644
--- a/Python/best-time-to-buy-and-sell-stock-iii.py
+++ b/Python/best-time-to-buy-and-sell-stock-iii.py
@@ -1,14 +1,14 @@
# Time: O(n)
# Space: O(1)
#
-# Say you have an array for which the ith element
+# Say you have an array for which the ith element
# is the price of a given stock on day i.
#
-# Design an algorithm to find the maximum profit.
+# Design an algorithm to find the maximum profit.
# You may complete at most two transactions.
#
# Note:
-# You may not engage in multiple transactions at the same time
+# You may not engage in multiple transactions at the same time
# (ie, you must sell the stock before you buy again).
#
@@ -26,7 +26,7 @@ def maxProfit(self, prices):
release1 = max(release1, hold1 + i)
hold1 = max(hold1, -i);
return release2
-
+
# Time: O(k * n)
# Space: O(k)
class Solution2:
@@ -34,7 +34,7 @@ class Solution2:
# @return an integer
def maxProfit(self, prices):
return self.maxAtMostKPairsProfit(prices, 2)
-
+
def maxAtMostKPairsProfit(self, prices, k):
max_buy = [float("-inf") for _ in xrange(k + 1)]
max_sell = [0 for _ in xrange(k + 1)]
@@ -47,7 +47,7 @@ def maxAtMostKPairsProfit(self, prices, k):
return max_sell[k]
# Time: O(n)
-# Space: O(n)
+# Space: O(n)
class Solution3:
# @param prices, a list of integer
# @return an integer
@@ -57,19 +57,19 @@ def maxProfit(self, prices):
min_price = min(min_price, price)
max_profit_from_left = max(max_profit_from_left, price - min_price)
max_profits_from_left.append(max_profit_from_left)
-
+
max_price, max_profit_from_right, max_profits_from_right = 0, 0, []
for i in reversed(range(len(prices))):
max_price = max(max_price, prices[i])
max_profit_from_right = max(max_profit_from_right, max_price - prices[i])
max_profits_from_right.insert(0, max_profit_from_right)
-
+
max_profit = 0
for i in range(len(prices)):
max_profit = max(max_profit, max_profits_from_left[i] + max_profits_from_right[i])
-
+
return max_profit
-
+
if __name__ == "__main__":
result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6])
print result
diff --git a/Python/best-time-to-buy-and-sell-stock-iv.py b/Python/best-time-to-buy-and-sell-stock-iv.py
index 0235f07df..2d0071909 100644
--- a/Python/best-time-to-buy-and-sell-stock-iv.py
+++ b/Python/best-time-to-buy-and-sell-stock-iv.py
@@ -2,15 +2,15 @@
# Space: O(k)
#
# Say you have an array for which the ith element is the price of a given stock on day i.
-#
+#
# Design an algorithm to find the maximum profit. You may complete at most k transactions.
-#
+#
# Note:
# You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
#
class Solution:
- # @return an integer as the maximum profit
+ # @return an integer as the maximum profit
def maxProfit(self, k, prices):
if k >= len(prices) / 2:
return self.maxAtMostNPairsProfit(prices)
@@ -20,7 +20,7 @@ def maxProfit(self, k, prices):
def maxAtMostNPairsProfit(self, prices):
profit = 0
for i in xrange(len(prices) - 1):
- profit += max(0, prices[i + 1] - prices[i])
+ profit += max(0, prices[i + 1] - prices[i])
return profit
def maxAtMostKPairsProfit(self, prices, k):
diff --git a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py
index 7393b5b6e..4b622e833 100644
--- a/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py
+++ b/Python/best-time-to-buy-and-sell-stock-with-transaction-fee.py
@@ -39,4 +39,4 @@ def maxProfit(self, prices, fee):
cash = max(cash, hold+prices[i]-fee)
hold = max(hold, cash-prices[i])
return cash
-
+
diff --git a/Python/best-time-to-buy-and-sell-stock.py b/Python/best-time-to-buy-and-sell-stock.py
index 2c86c4a74..748b5e638 100644
--- a/Python/best-time-to-buy-and-sell-stock.py
+++ b/Python/best-time-to-buy-and-sell-stock.py
@@ -1,11 +1,11 @@
# Time: O(n)
# Space: O(1)
#
-# Say you have an array for which the ith element
+# Say you have an array for which the ith element
# is the price of a given stock on day i.
#
-# If you were only permitted to complete at most one transaction
-# (ie, buy one and sell one share of the stock),
+# If you were only permitted to complete at most one transaction
+# (ie, buy one and sell one share of the stock),
# design an algorithm to find the maximum profit.
#
@@ -16,10 +16,10 @@ def maxProfit(self, prices):
max_profit, min_price = 0, float("inf")
for price in prices:
min_price = min(min_price, price)
- max_profit = max(max_profit, price - min_price)
+ max_profit = max(max_profit, price - min_price)
return max_profit
if __name__ == "__main__":
result = Solution().maxProfit([3, 2, 1, 4, 2, 5, 6])
print result
-
+
diff --git a/Python/binary-number-with-alternating-bits.py b/Python/binary-number-with-alternating-bits.py
index ff066353a..e8f06d5b9 100644
--- a/Python/binary-number-with-alternating-bits.py
+++ b/Python/binary-number-with-alternating-bits.py
@@ -27,7 +27,7 @@
# Output: True
# Explanation:
# The binary representation of 10 is: 1010.
-
+
class Solution(object):
def hasAlternatingBits(self, n):
"""
diff --git a/Python/binary-search-tree-iterator.py b/Python/binary-search-tree-iterator.py
index 428c8d4a3..ae455dea3 100644
--- a/Python/binary-search-tree-iterator.py
+++ b/Python/binary-search-tree-iterator.py
@@ -1,11 +1,11 @@
# Time: O(1)
# Space: O(h), h is height of binary tree
-#
+#
# Implement an iterator over a binary search tree (BST).
# Your iterator will be initialized with the root node of a BST.
-#
+#
# Calling next() will return the next smallest number in the BST.
-#
+#
# Note: next() and hasNext() should run in average O(1) time
# and uses O(h) memory, where h is the height of the tree.
#
@@ -32,19 +32,19 @@ def next(self):
while self.cur:
self.stack.append(self.cur)
self.cur = self.cur.left
-
+
self.cur = self.stack.pop()
node = self.cur
self.cur = self.cur.right
-
+
return node.val
-
+
if __name__ == "__main__":
root = TreeNode(2)
root.left = TreeNode(1)
-
+
# Your BSTIterator will be called like this:
i, v = BSTIterator(root), []
while i.hasNext(): v.append(i.next())
-
+
print v
diff --git a/Python/binary-tree-inorder-traversal.py b/Python/binary-tree-inorder-traversal.py
index 11448e3fa..b82319cfe 100644
--- a/Python/binary-tree-inorder-traversal.py
+++ b/Python/binary-tree-inorder-traversal.py
@@ -39,7 +39,7 @@ def inorderTraversal(self, root):
node = curr.left
while node.right and node.right != curr:
node = node.right
-
+
if node.right is None:
node.right = curr
curr = curr.left
@@ -47,7 +47,7 @@ def inorderTraversal(self, root):
result.append(curr.val)
node.right = None
curr = curr.right
-
+
return result
diff --git a/Python/binary-tree-level-order-traversal-ii.py b/Python/binary-tree-level-order-traversal-ii.py
index a03432a5d..0973c82e2 100644
--- a/Python/binary-tree-level-order-traversal-ii.py
+++ b/Python/binary-tree-level-order-traversal-ii.py
@@ -3,7 +3,7 @@
# Given a binary tree, return the bottom-up level order traversal of its nodes' values.
# (ie, from left to right, level by level from leaf to root).
-#
+#
# For example:
# Given binary tree {3,9,20,#,#,15,7},
# 3
diff --git a/Python/binary-tree-level-order-traversal.py b/Python/binary-tree-level-order-traversal.py
index f1b8c9c47..8e48c8372 100644
--- a/Python/binary-tree-level-order-traversal.py
+++ b/Python/binary-tree-level-order-traversal.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(n)
#
-# Given a binary tree, return the level order traversal of its nodes' values.
+# Given a binary tree, return the level order traversal of its nodes' values.
# (ie, from left to right, level by level).
#
# For example:
diff --git a/Python/binary-tree-longest-consecutive-sequence-ii.py b/Python/binary-tree-longest-consecutive-sequence-ii.py
index 99c88f13c..b7c0f7bec 100644
--- a/Python/binary-tree-longest-consecutive-sequence-ii.py
+++ b/Python/binary-tree-longest-consecutive-sequence-ii.py
@@ -36,4 +36,4 @@ def longestConsecutiveHelper(root):
self.max_len = 0
longestConsecutiveHelper(root)
return self.max_len
-
+
diff --git a/Python/binary-tree-longest-consecutive-sequence.py b/Python/binary-tree-longest-consecutive-sequence.py
index 769c417ee..e9c6c7444 100644
--- a/Python/binary-tree-longest-consecutive-sequence.py
+++ b/Python/binary-tree-longest-consecutive-sequence.py
@@ -19,10 +19,10 @@ def longestConsecutive(self, root):
def longestConsecutiveHelper(root):
if not root:
return 0
-
+
left_len = longestConsecutiveHelper(root.left)
right_len = longestConsecutiveHelper(root.right)
-
+
cur_len = 1
if root.left and root.left.val == root.val + 1:
cur_len = max(cur_len, left_len + 1);
diff --git a/Python/binary-tree-maximum-path-sum.py b/Python/binary-tree-maximum-path-sum.py
index d71f6eeba..b3d25e94a 100644
--- a/Python/binary-tree-maximum-path-sum.py
+++ b/Python/binary-tree-maximum-path-sum.py
@@ -2,12 +2,12 @@
# Space: O(h), h is height of binary tree
#
# Given a binary tree, find the maximum path sum.
-#
+#
# The path may start and end at any node in the tree.
-#
+#
# For example:
# Given the below binary tree,
-#
+#
# 1
# / \
# 2 3
@@ -27,7 +27,7 @@ class Solution:
def maxPathSum(self, root):
self.maxPathSumRecu(root)
return self.maxSum
-
+
def maxPathSumRecu(self, root):
if root is None:
return 0
@@ -35,7 +35,7 @@ def maxPathSumRecu(self, root):
right = max(0, self.maxPathSumRecu(root.right))
self.maxSum = max(self.maxSum, root.val + left + right)
return root.val + max(left, right)
-
+
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
diff --git a/Python/binary-tree-paths.py b/Python/binary-tree-paths.py
index 657e8d579..770adfdfb 100644
--- a/Python/binary-tree-paths.py
+++ b/Python/binary-tree-paths.py
@@ -29,7 +29,7 @@ def binaryTreePaths(self, root):
result, path = [], []
self.binaryTreePathsRecu(root, path, result)
return result
-
+
def binaryTreePathsRecu(self, node, path, result):
if node is None:
return
diff --git a/Python/binary-tree-postorder-traversal.py b/Python/binary-tree-postorder-traversal.py
index c5a47b0c8..e0ae110cd 100644
--- a/Python/binary-tree-postorder-traversal.py
+++ b/Python/binary-tree-postorder-traversal.py
@@ -40,7 +40,7 @@ def postorderTraversal(self, root):
node = cur.left
while node.right and node.right != cur:
node = node.right
-
+
if node.right is None:
node.right = cur
cur = cur.left
@@ -48,9 +48,9 @@ def postorderTraversal(self, root):
result += self.traceBack(cur.left, node)
node.right = None
cur = cur.right
-
+
return result
-
+
def traceBack(self, frm, to):
result, cur = [], frm
while cur is not to:
@@ -63,7 +63,7 @@ def traceBack(self, frm, to):
# Time: O(n)
# Space: O(h)
-# Stack Solution
+# Stack Solution
class Solution2(object):
def postorderTraversal(self, root):
"""
diff --git a/Python/binary-tree-preorder-traversal.py b/Python/binary-tree-preorder-traversal.py
index 2ba22d545..9cf12ee7a 100644
--- a/Python/binary-tree-preorder-traversal.py
+++ b/Python/binary-tree-preorder-traversal.py
@@ -39,7 +39,7 @@ def preorderTraversal(self, root):
node = curr.left
while node.right and node.right != curr:
node = node.right
-
+
if node.right is None:
result.append(curr.val)
node.right = curr
@@ -47,13 +47,13 @@ def preorderTraversal(self, root):
else:
node.right = None
curr = curr.right
-
+
return result
# Time: O(n)
# Space: O(h)
-# Stack Solution
+# Stack Solution
class Solution2(object):
def preorderTraversal(self, root):
"""
diff --git a/Python/binary-tree-right-side-view.py b/Python/binary-tree-right-side-view.py
index 56d5e3db2..effd0ad13 100644
--- a/Python/binary-tree-right-side-view.py
+++ b/Python/binary-tree-right-side-view.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(h)
#
-# Given a binary tree, imagine yourself standing on the right side of it,
+# Given a binary tree, imagine yourself standing on the right side of it,
# return the values of the nodes you can see ordered from top to bottom.
#
# For example:
@@ -28,27 +28,27 @@ def rightSideView(self, root):
result = []
self.rightSideViewDFS(root, 1, result)
return result
-
+
def rightSideViewDFS(self, node, depth, result):
if not node:
return
-
+
if depth > len(result):
result.append(node.val)
-
+
self.rightSideViewDFS(node.right, depth+1, result)
self.rightSideViewDFS(node.left, depth+1, result)
# BFS solution
# Time: O(n)
-# Space: O(n)
+# Space: O(n)
class Solution2:
# @param root, a tree node
# @return a list of integers
def rightSideView(self, root):
if root is None:
return []
-
+
result, current = [], [root]
while current:
next_level = []
@@ -60,7 +60,7 @@ def rightSideView(self, root):
if i == len(current) - 1:
result.append(node.val)
current = next_level
-
+
return result
if __name__ == "__main__":
diff --git a/Python/binary-tree-tilt.py b/Python/binary-tree-tilt.py
index e1ed02783..76ca7e745 100644
--- a/Python/binary-tree-tilt.py
+++ b/Python/binary-tree-tilt.py
@@ -10,12 +10,12 @@
# The tilt of the whole tree is defined as the sum of all nodes' tilt.
#
# Example:
-# Input:
+# Input:
# 1
# / \
# 2 3
# Output: 1
-# Explanation:
+# Explanation:
# Tilt of node 2 : 0
# Tilt of node 3 : 0
# Tilt of node 1 : |2-3| = 1
diff --git a/Python/binary-tree-upside-down.py b/Python/binary-tree-upside-down.py
index 51315ff94..e68f4e923 100644
--- a/Python/binary-tree-upside-down.py
+++ b/Python/binary-tree-upside-down.py
@@ -1,27 +1,27 @@
# Time: O(n)
# Space: O(1)
#
-# Given a binary tree where all the right nodes are either leaf nodes with a sibling
-# (a left node that shares the same parent node) or empty, flip it upside down and
-# turn it into a tree where the original right nodes turned into left leaf nodes.
+# Given a binary tree where all the right nodes are either leaf nodes with a sibling
+# (a left node that shares the same parent node) or empty, flip it upside down and
+# turn it into a tree where the original right nodes turned into left leaf nodes.
# Return the new root.
-#
+#
# For example:
# Given a binary tree {1,2,3,4,5},
-#
+#
# 1
# / \
# 2 3
# / \
# 4 5
-#
+#
# return the root of the binary tree [4,5,2,#,#,3,1].
-#
+#
# 4
# / \
# 5 2
# / \
-# 3 1
+# 3 1
#
# Definition for a binary tree node
@@ -36,7 +36,7 @@ class Solution:
# @return root of the upside down tree
def upsideDownBinaryTree(self, root):
p, parent, parent_right = root, None, None
-
+
while p:
left = p.left
p.left = parent_right
@@ -44,7 +44,7 @@ def upsideDownBinaryTree(self, root):
p.right = parent
parent = p
p = left
-
+
return parent
# Time: O(n)
@@ -54,16 +54,16 @@ class Solution2:
# @return root of the upside down tree
def upsideDownBinaryTree(self, root):
return self.upsideDownBinaryTreeRecu(root, None)
-
+
def upsideDownBinaryTreeRecu(self, p, parent):
if p is None:
return parent
-
+
root = self.upsideDownBinaryTreeRecu(p.left, p)
if parent:
p.left = parent.right
else:
p.left = None
p.right = parent
-
+
return root
\ No newline at end of file
diff --git a/Python/binary-tree-zigzag-level-order-traversal.py b/Python/binary-tree-zigzag-level-order-traversal.py
index 7a6261e05..1a5dac583 100644
--- a/Python/binary-tree-zigzag-level-order-traversal.py
+++ b/Python/binary-tree-zigzag-level-order-traversal.py
@@ -2,7 +2,7 @@
# Space: O(n)
#
# Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
-#
+#
# For example:
# Given binary tree {3,9,20,#,#,15,7},
# 3
diff --git a/Python/bitwise-and-of-numbers-range.py b/Python/bitwise-and-of-numbers-range.py
index 369a5a803..0dc2cad71 100644
--- a/Python/bitwise-and-of-numbers-range.py
+++ b/Python/bitwise-and-of-numbers-range.py
@@ -1,7 +1,7 @@
# Time: O(1)
# Space: O(1)
#
-# Given a range [m, n] where 0 <= m <= n <= 2147483647,
+# Given a range [m, n] where 0 <= m <= n <= 2147483647,
# return the bitwise AND of all numbers in this range, inclusive.
#
# For example, given the range [5, 7], you should return 4.
diff --git a/Python/boundary-of-binary-tree.py b/Python/boundary-of-binary-tree.py
index ad7a6a6b3..c71ed0df4 100644
--- a/Python/boundary-of-binary-tree.py
+++ b/Python/boundary-of-binary-tree.py
@@ -31,7 +31,7 @@ def rightBoundary(root, nodes):
else:
rightBoundary(root.right, nodes)
nodes.append(root.val)
-
+
def leaves(root, nodes):
if not root:
return
@@ -43,7 +43,7 @@ def leaves(root, nodes):
if not root:
return []
-
+
nodes = [root.val]
leftBoundary(root.left, nodes)
leaves(root.left, nodes)
diff --git a/Python/bricks-falling-when-hit.py b/Python/bricks-falling-when-hit.py
index 3a94f4bd5..9901572c7 100644
--- a/Python/bricks-falling-when-hit.py
+++ b/Python/bricks-falling-when-hit.py
@@ -12,19 +12,19 @@
# Return an array representing the number of bricks that will drop after each erasure in sequence.
#
# Example 1:
-# Input:
+# Input:
# grid = [[1,0,0,0],[1,1,1,0]]
# hits = [[1,0]]
# Output: [2]
-# Explanation:
+# Explanation:
# If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2.
#
# Example 2:
-# Input:
+# Input:
# grid = [[1,0,0,0],[1,1,0,0]]
# hits = [[1,1],[1,0]]
# Output: [0,0]
-# Explanation:
+# Explanation:
# When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move.
# So each erasure will cause no bricks dropping.
# Note that the erased brick (1, 0) will not be counted as a dropped brick.
@@ -56,7 +56,7 @@ def union_set(self, x, y):
def top(self):
return self.size[self.find_set(len(self.size)-1)]
-
+
class Solution(object):
def hitBricks(self, grid, hits):
@@ -67,7 +67,7 @@ def hitBricks(self, grid, hits):
"""
def index(C, r, c):
return r*C+c
-
+
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
R, C = len(grid), len(grid[0])
diff --git a/Python/bulb-switcher-ii.py b/Python/bulb-switcher-ii.py
index 3ce93572a..3bb37192d 100644
--- a/Python/bulb-switcher-ii.py
+++ b/Python/bulb-switcher-ii.py
@@ -24,7 +24,7 @@
# Output: 4
# Explanation: Status can be: [off, on, off], [on, off, on], [off, off, off], [off, on, on].
# Note: n and m both fit in range [0, 1000].
-
+
class Solution(object):
def flipLights(self, n, m):
"""
diff --git a/Python/burst-balloons.py b/Python/burst-balloons.py
index acdd5c15e..4cb6ebd9c 100644
--- a/Python/burst-balloons.py
+++ b/Python/burst-balloons.py
@@ -1,20 +1,20 @@
# Time: O(n^3)
# Space: O(n^2)
-# Given n balloons, indexed from 0 to n-1.
-# Each balloon is painted with a number on it
-# represented by array nums.
+# Given n balloons, indexed from 0 to n-1.
+# Each balloon is painted with a number on it
+# represented by array nums.
# You are asked to burst all the balloons.
-# If the you burst balloon i you will get
-# nums[left] * nums[i] * nums[right] coins.
-# Here left and right are adjacent indices of i.
+# If the you burst balloon i you will get
+# nums[left] * nums[i] * nums[right] coins.
+# Here left and right are adjacent indices of i.
# After the burst, the left and right then
# becomes adjacent.
#
-# Find the maximum coins you can collect by
+# Find the maximum coins you can collect by
# bursting the balloons wisely.
#
-# Note:
+# Note:
# (1) You may imagine nums[-1] = nums[n] = 1.
# They are not real therefore you can not burst them.
# (2) 0 <= n <= 500, 0 <= nums[i] <= 100
@@ -38,7 +38,7 @@ def maxCoins(self, nums):
coins = [1] + [i for i in nums if i > 0] + [1]
n = len(coins)
max_coins = [[0 for _ in xrange(n)] for _ in xrange(n)]
-
+
for k in xrange(2, n):
for left in xrange(n - k):
right = left + k
@@ -48,4 +48,4 @@ def maxCoins(self, nums):
max_coins[left][i] + max_coins[i][right])
return max_coins[0][-1]
-
+
diff --git a/Python/can-i-win.py b/Python/can-i-win.py
index 1877b04e9..8e482cf30 100644
--- a/Python/can-i-win.py
+++ b/Python/can-i-win.py
@@ -53,7 +53,7 @@ def canIWinHelper(maxChoosableInteger, desiredTotal, visited, lookup):
mask <<= 1
lookup[visited] = False
return False
-
+
if (1 + maxChoosableInteger) * (maxChoosableInteger / 2) < desiredTotal:
return False
diff --git a/Python/candy-crush.py b/Python/candy-crush.py
index 782f4af05..591398830 100644
--- a/Python/candy-crush.py
+++ b/Python/candy-crush.py
@@ -25,7 +25,7 @@
#
# Example 1:
# Input:
-# board =
+# board =
# [[110,5,112,113,114],[210,211,5,213,214],[310,311,3,313,314],[410,411,412,5,414],[5,1,512,3,3],[610,4,1,613,614],[710,1,2,713,714],[810,1,2,1,1],[1,1,2,2,2],[4,1,4,4,1014]]
# Output:
# [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[110,0,0,0,114],[210,0,0,0,214],[310,0,0,113,314],[410,0,0,213,414],[610,211,112,313,614],[710,311,412,613,714],[810,411,512,713,1014]]
@@ -43,7 +43,7 @@ def candyCrush(self, board):
"""
R, C = len(board), len(board[0])
changed = True
-
+
while changed:
changed = False
diff --git a/Python/candy.py b/Python/candy.py
index daf2f8153..eded6772a 100644
--- a/Python/candy.py
+++ b/Python/candy.py
@@ -2,9 +2,9 @@
# Space: O(n)
#
# There are N children standing in a line. Each child is assigned a rating value.
-#
+#
# You are giving candies to these children subjected to the following requirements:
-#
+#
# Each child must have at least one candy.
# Children with a higher rating get more candies than their neighbors.
# What is the minimum candies you must give?
@@ -20,13 +20,13 @@ def candy(self, ratings):
for i in xrange(1, len(ratings)):
if ratings[i] > ratings[i - 1]:
candies[i] = candies[i - 1] + 1
-
+
for i in reversed(xrange(1, len(ratings))):
if ratings[i - 1] > ratings[i] and candies[i - 1] <= candies[i]:
candies[i - 1] = candies[i] + 1
-
+
return reduce(operator.add, candies)
-
+
if __name__ == "__main__":
result = Solution().candy([1, 2, 3, 2, 3, 5, 2, 5])
print result
diff --git a/Python/cherry-pickup.py b/Python/cherry-pickup.py
index 4764f990d..f5815a5ab 100644
--- a/Python/cherry-pickup.py
+++ b/Python/cherry-pickup.py
@@ -20,7 +20,7 @@
# [1, 0, -1],
# [1, 1, 1]]
# Output: 5
-# Explanation:
+# Explanation:
# The player started at (0, 0) and went down, down, right right to reach (2, 2).
# 4 cherries were picked up during this single trip, and the matrix becomes [[0,1,-1],[0,0,-1],[0,0,0]].
# Then, the player went left, up, up, left to return home, picking up one more cherry.
@@ -38,7 +38,7 @@ def cherryPickup(self, grid):
:rtype: int
"""
# dp holds the max # of cherries two k-length paths can pickup.
- # The two k-length paths arrive at (i, k - i) and (j, k - j),
+ # The two k-length paths arrive at (i, k - i) and (j, k - j),
# respectively.
n = len(grid)
dp = [[-1 for _ in xrange(n)] for _ in xrange(n)]
diff --git a/Python/circular-array-loop.py b/Python/circular-array-loop.py
index f1b9e10e4..32c7f87c7 100644
--- a/Python/circular-array-loop.py
+++ b/Python/circular-array-loop.py
@@ -26,18 +26,18 @@ def circularArrayLoop(self, nums):
"""
def next_index(nums, i):
return (i + nums[i]) % len(nums)
-
+
for i in xrange(len(nums)):
if nums[i] == 0:
continue
-
+
slow, fast = i, i
while nums[next_index(nums, slow)] * nums[i] > 0 and \
nums[next_index(nums, fast)] * nums[i] > 0 and \
nums[next_index(nums, next_index(nums, fast))] * nums[i] > 0:
slow = next_index(nums, slow)
fast = next_index(nums, next_index(nums, fast))
- if slow == fast:
+ if slow == fast:
if slow == next_index(nums, slow):
break
return True
diff --git a/Python/climbing-stairs.py b/Python/climbing-stairs.py
index 6511a1dee..a6ccff427 100644
--- a/Python/climbing-stairs.py
+++ b/Python/climbing-stairs.py
@@ -2,8 +2,8 @@
# Space: O(1)
#
# You are climbing a stair case. It takes n steps to reach to the top.
-#
-# Each time you can either climb 1 or 2 steps.
+#
+# Each time you can either climb 1 or 2 steps.
# In how many distinct ways can you climb to the top?
@@ -15,7 +15,7 @@ class Solution:
def climbStairs(self, n):
prev, current = 0, 1
for i in xrange(n):
- prev, current = current, prev + current,
+ prev, current = current, prev + current,
return current
# Time: O(2^n)
diff --git a/Python/clone-graph.py b/Python/clone-graph.py
index 87ecec311..a4a0b0338 100644
--- a/Python/clone-graph.py
+++ b/Python/clone-graph.py
@@ -2,21 +2,21 @@
# Space: O(n)
#
# Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
-#
-#
+#
+#
# OJ's undirected graph serialization:
# Nodes are labeled uniquely.
-#
+#
# We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
# As an example, consider the serialized graph {0,1,2#1,2#2,2}.
-#
+#
# The graph has a total of three nodes, and therefore contains three parts as separated by #.
-#
+#
# First node is labeled as 0. Connect node 0 to both nodes 1 and 2.
# Second node is labeled as 1. Connect node 1 to node 2.
# Third node is labeled as 2. Connect node 2 to node 2 (itself), thus forming a self-cycle.
# Visually, the graph looks like the following:
-#
+#
# 1
# / \
# / \
@@ -38,7 +38,7 @@ def cloneGraph(self, node):
return None
cloned_node = UndirectedGraphNode(node.label)
cloned, queue = {node:cloned_node}, [node]
-
+
while queue:
current = queue.pop()
for neighbor in current.neighbors:
diff --git a/Python/closest-binary-search-tree-value-ii.py b/Python/closest-binary-search-tree-value-ii.py
index 4672e0cc6..3abd38a54 100644
--- a/Python/closest-binary-search-tree-value-ii.py
+++ b/Python/closest-binary-search-tree-value-ii.py
@@ -27,11 +27,11 @@ def nextNode(stack, child1, child2):
child = stack.pop()
while stack and child is child2(stack):
child = stack.pop()
-
+
# The forward or backward iterator.
backward = lambda stack: stack[-1].left
forward = lambda stack: stack[-1].right
-
+
# Build the stack to the closest node.
stack = []
while root:
@@ -39,11 +39,11 @@ def nextNode(stack, child1, child2):
root = root.left if target < root.val else root.right
dist = lambda node: abs(node.val - target)
forward_stack = stack[:stack.index(min(stack, key=dist))+1]
-
+
# Get the stack to the next smaller node.
backward_stack = list(forward_stack)
nextNode(backward_stack, backward, forward)
-
+
# Get the closest k values by advancing the iterators of the stacks.
result = []
for _ in xrange(k):
@@ -74,7 +74,7 @@ def __init__(self, stack, child1, child2):
self.cur = self.stack.pop()
self.child1 = child1
self.child2 = child2
-
+
# @return an integer, the next node
def next(self):
node = None
@@ -103,7 +103,7 @@ def next(self):
root = root.left if target < root.val else root.right
dist = lambda node: abs(node.val - target) if node else float("inf")
stack = stack[:stack.index(min(stack, key=dist))+1]
-
+
# The forward or backward iterator.
backward = lambda node: node.left
forward = lambda node: node.right
diff --git a/Python/coin-change-2.py b/Python/coin-change-2.py
index d65707685..c85c9d196 100644
--- a/Python/coin-change-2.py
+++ b/Python/coin-change-2.py
@@ -27,9 +27,9 @@
# Explanation: the amount of 3 cannot be made up just with coins of 2.
# Example 3:
#
-# Input: amount = 10, coins = [10]
+# Input: amount = 10, coins = [10]
# Output: 1
-
+
class Solution(object):
def change(self, amount, coins):
"""
diff --git a/Python/coin-change.py b/Python/coin-change.py
index f762c382a..093d4429b 100644
--- a/Python/coin-change.py
+++ b/Python/coin-change.py
@@ -35,4 +35,4 @@ def coinChange(self, coins, amount):
if i + coin <= amount:
amounts[i + coin] = min(amounts[i + coin], amounts[i] + 1)
return amounts[amount] if amounts[amount] != INF else -1
-
+
diff --git a/Python/combination-sum-ii.py b/Python/combination-sum-ii.py
index d11d74295..31975069d 100644
--- a/Python/combination-sum-ii.py
+++ b/Python/combination-sum-ii.py
@@ -1,20 +1,20 @@
# Time: O(k * C(n, k))
# Space: O(k)
-#
-# Given a collection of candidate numbers (C) and a target number (T),
+#
+# Given a collection of candidate numbers (C) and a target number (T),
# find all unique combinations in C where the candidate numbers sums to T.
-#
+#
# Each number in C may only be used once in the combination.
-#
+#
# Note:
# All numbers (including target) will be positive integers.
# Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).
# The solution set must not contain duplicate combinations.
-# For example, given candidate set 10,1,2,7,6,1,5 and target 8,
-# A solution set is:
-# [1, 7]
-# [1, 2, 5]
-# [2, 6]
+# For example, given candidate set 10,1,2,7,6,1,5 and target 8,
+# A solution set is:
+# [1, 7]
+# [1, 2, 5]
+# [2, 6]
# [1, 1, 6]
#
@@ -26,7 +26,7 @@ def combinationSum2(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
-
+
def combinationSumRecu(self, candidates, result, start, intermediate, target):
if target == 0:
result.append(list(intermediate))
@@ -41,5 +41,5 @@ def combinationSumRecu(self, candidates, result, start, intermediate, target):
if __name__ == "__main__":
candidates, target = [10, 1, 2, 7, 6, 1, 5], 8
- result = Solution().combinationSum2(candidates, target)
- print result
+ result = Solution().combinationSum2(candidates, target)
+ print result
diff --git a/Python/combination-sum-iii.py b/Python/combination-sum-iii.py
index ddc4ba260..f5accf25a 100644
--- a/Python/combination-sum-iii.py
+++ b/Python/combination-sum-iii.py
@@ -32,7 +32,7 @@ def combinationSum3(self, k, n):
result = []
self.combinationSumRecu(result, [], 1, k, n)
return result
-
+
def combinationSumRecu(self, result, intermediate, start, k, target):
if k == 0 and target == 0:
result.append(list(intermediate))
diff --git a/Python/combination-sum.py b/Python/combination-sum.py
index ce0d14f11..0120a7cdb 100644
--- a/Python/combination-sum.py
+++ b/Python/combination-sum.py
@@ -1,19 +1,19 @@
# Time: O(k * n^k)
# Space: O(k)
#
-# Given a set of candidate numbers (C) and a target number (T),
+# Given a set of candidate numbers (C) and a target number (T),
# find all unique combinations in C where the candidate numbers sums to T.
-#
+#
# The same repeated number may be chosen from C unlimited number of times.
-#
+#
# Note:
# All numbers (including target) will be positive integers.
# Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).
# The solution set must not contain duplicate combinations.
-# For example, given candidate set 2,3,6,7 and target 7,
-# A solution set is:
-# [7]
-# [2, 2, 3]
+# For example, given candidate set 2,3,6,7 and target 7,
+# A solution set is:
+# [7]
+# [2, 2, 3]
#
class Solution:
@@ -24,7 +24,7 @@ def combinationSum(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
-
+
def combinationSumRecu(self, candidates, result, start, intermediate, target):
if target == 0:
result.append(list(intermediate))
@@ -36,5 +36,5 @@ def combinationSumRecu(self, candidates, result, start, intermediate, target):
if __name__ == "__main__":
candidates, target = [2, 3, 6, 7], 7
- result = Solution().combinationSum(candidates, target)
- print result
+ result = Solution().combinationSum(candidates, target)
+ print result
diff --git a/Python/combinations.py b/Python/combinations.py
index 7a4ba2a5f..e57640ab1 100644
--- a/Python/combinations.py
+++ b/Python/combinations.py
@@ -2,10 +2,10 @@
# Space: O(k)
# Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
-#
+#
# For example,
# If n = 4 and k = 2, a solution is:
-#
+#
# [
# [2,4],
# [3,4],
@@ -36,7 +36,7 @@ def combine(self, n, k):
combination.append(i)
i += 1
return result
-
+
class Solution2(object):
def combine(self, n, k):
diff --git a/Python/compare-version-numbers.py b/Python/compare-version-numbers.py
index 4b67b70e4..342dff213 100644
--- a/Python/compare-version-numbers.py
+++ b/Python/compare-version-numbers.py
@@ -4,17 +4,17 @@
# Compare two version numbers version1 and version1.
# If version1 > version2 return 1, if version1 < version2
# return -1, otherwise return 0.
-#
+#
# You may assume that the version strings are non-empty and
# contain only digits and the . character.
-# The . character does not represent a decimal point and
+# The . character does not represent a decimal point and
# is used to separate number sequences.
# For instance, 2.5 is not "two and a half" or "half way to
# version three", it is the fifth second-level revision of
# the second first-level revision.
-#
+#
# Here is an example of version numbers ordering:
-#
+#
# 0.1 < 1.1 < 1.2 < 13.37
#
import itertools
@@ -56,12 +56,12 @@ def compareVersion(self, version1, version2):
:rtype: int
"""
v1, v2 = version1.split("."), version2.split(".")
-
+
if len(v1) > len(v2):
v2 += ['0' for _ in xrange(len(v1) - len(v2))]
elif len(v1) < len(v2):
v1 += ['0' for _ in xrange(len(v2) - len(v1))]
-
+
i = 0
while i < len(v1):
if int(v1[i]) > int(v2[i]):
@@ -70,7 +70,7 @@ def compareVersion(self, version1, version2):
return -1
else:
i += 1
-
+
return 0
def compareVersion2(self, version1, version2):
diff --git a/Python/concatenated-words.py b/Python/concatenated-words.py
index 8d89f5e36..6fceb631c 100644
--- a/Python/concatenated-words.py
+++ b/Python/concatenated-words.py
@@ -12,8 +12,8 @@
#
# Output: ["catsdogcats","dogcatsdog","ratcatdogcat"]
#
-# Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
-# "dogcatsdog" can be concatenated by "dog", "cats" and "dog";
+# Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
+# "dogcatsdog" can be concatenated by "dog", "cats" and "dog";
# "ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
# Note:
# The number of elements of the given array will not exceed 10,000
@@ -29,15 +29,15 @@ def findAllConcatenatedWordsInADict(self, words):
"""
lookup = set(words)
result = []
- for word in words:
+ for word in words:
dp = [False] * (len(word)+1)
dp[0] = True
for i in xrange(len(word)):
if not dp[i]:
continue
-
+
for j in xrange(i+1, len(word)+1):
- if j - i < len(word) and word[i:j] in lookup:
+ if j - i < len(word) and word[i:j] in lookup:
dp[j] = True
if dp[len(word)]:
diff --git a/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py b/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py
index 991009a93..294594fa5 100644
--- a/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py
+++ b/Python/construct-binary-tree-from-inorder-and-postorder-traversal.py
@@ -2,7 +2,7 @@
# Space: O(n)
#
# Given inorder and postorder traversal of a tree, construct the binary tree.
-#
+#
# Note:
# You may assume that duplicates do not exist in the tree.
#
@@ -23,7 +23,7 @@ def buildTree(self, inorder, postorder):
for i, num in enumerate(inorder):
lookup[num] = i
return self.buildTreeRecu(lookup, postorder, inorder, len(postorder), 0, len(inorder))
-
+
def buildTreeRecu(self, lookup, postorder, inorder, post_end, in_start, in_end):
if in_start == in_end:
return None
diff --git a/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py b/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py
index e3196454d..a316ecdd2 100644
--- a/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py
+++ b/Python/construct-binary-tree-from-preorder-and-inorder-traversal.py
@@ -2,7 +2,7 @@
# Space: O(n)
#
# Given preorder and inorder traversal of a tree, construct the binary tree.
-#
+#
# Note:
# You may assume that duplicates do not exist in the tree.
#
@@ -23,7 +23,7 @@ def buildTree(self, preorder, inorder):
for i, num in enumerate(inorder):
lookup[num] = i
return self.buildTreeRecu(lookup, preorder, inorder, 0, 0, len(inorder))
-
+
def buildTreeRecu(self, lookup, preorder, inorder, pre_start, in_start, in_end):
if in_start == in_end:
return None
diff --git a/Python/construct-string-from-binary-tree.py b/Python/construct-string-from-binary-tree.py
index 8bba46ba5..b2dac24ee 100644
--- a/Python/construct-string-from-binary-tree.py
+++ b/Python/construct-string-from-binary-tree.py
@@ -5,7 +5,7 @@
# the preorder traversing way.
#
# The null node needs to be represented by empty parenthesis pair "()".
-# And you need to omit all the empty parenthesis pairs that don't affect
+# And you need to omit all the empty parenthesis pairs that don't affect
# the one-to-one mapping relationship between the string and the original binary tree.
#
# Example 1:
@@ -13,25 +13,25 @@
# 1
# / \
# 2 3
-# /
-# 4
+# /
+# 4
#
# Output: "1(2(4))(3)"
#
-# Explanation: Originallay it needs to be "1(2(4)())(3()())",
-# but you need to omit all the unnecessary empty parenthesis pairs.
+# Explanation: Originallay it needs to be "1(2(4)())(3()())",
+# but you need to omit all the unnecessary empty parenthesis pairs.
# And it will be "1(2(4))(3)".
# Example 2:
# Input: Binary tree: [1,2,3,null,4]
# 1
# / \
# 2 3
-# \
-# 4
+# \
+# 4
#
# Output: "1(2()(4))(3)"
#
-# Explanation: Almost the same as the first example,
+# Explanation: Almost the same as the first example,
# except we can't omit the first parenthesis pair to break the one-to-one mapping relationship
# between the input and the output.
diff --git a/Python/contain-virus.py b/Python/contain-virus.py
index abf74ca92..3fc0e7569 100644
--- a/Python/contain-virus.py
+++ b/Python/contain-virus.py
@@ -11,7 +11,7 @@
#
# Every night, the virus spreads to all neighboring cells in all four directions unless blocked by a wall.
# Resources are limited.
-# Each day, you can install walls around only one region --
+# Each day, you can install walls around only one region --
# the affected area (continuous block of infected cells) that
# threatens the most uninfected cells the following night.
# There will never be a tie.
@@ -20,7 +20,7 @@
# If not, and the world becomes fully infected, return the number of walls used.
#
# Example 1:
-# Input: grid =
+# Input: grid =
# [[0,1,0,0,0,0,0,1],
# [0,1,0,0,0,0,0,1],
# [0,0,0,0,0,0,0,1],
@@ -38,7 +38,7 @@
# On the second day, add 5 walls to quarantine the viral region on the right. The virus is fully contained.
#
# Example 2:
-# Input: grid =
+# Input: grid =
# [[1,1,1],
# [1,0,1],
# [1,1,1]]
@@ -47,7 +47,7 @@
# Notice that walls are only built on the shared boundary of two different cells.
#
# Example 3:
-# Input: grid =
+# Input: grid =
# [[1,1,1,0,0,0,0,0,0],
# [1,0,1,0,1,1,1,1,1],
# [1,1,1,0,0,0,0,0,0]]
diff --git a/Python/container-with-most-water.py b/Python/container-with-most-water.py
index aa81a7018..5522e0080 100644
--- a/Python/container-with-most-water.py
+++ b/Python/container-with-most-water.py
@@ -1,13 +1,13 @@
# Time: O(n)
# Space: O(1)
#
-# Given n non-negative integers a1, a2, ..., an,
-# where each represents a point at coordinate (i, ai).
-# n vertical lines are drawn such that the two endpoints of
-# line i is at (i, ai) and (i, 0). Find two lines,
-# which together with x-axis forms a container,
+# Given n non-negative integers a1, a2, ..., an,
+# where each represents a point at coordinate (i, ai).
+# n vertical lines are drawn such that the two endpoints of
+# line i is at (i, ai) and (i, 0). Find two lines,
+# which together with x-axis forms a container,
# such that the container contains the most water.
-#
+#
# Note: You may not slant the container.
#
@@ -22,7 +22,7 @@ def maxArea(self, height):
else:
j -= 1
return max_area
-
+
if __name__ == "__main__":
height = [1, 2, 3, 4, 3, 2, 1, 5]
result = Solution().maxArea(height)
diff --git a/Python/contains-duplicate-ii.py b/Python/contains-duplicate-ii.py
index 451a6bdde..ca5206a55 100644
--- a/Python/contains-duplicate-ii.py
+++ b/Python/contains-duplicate-ii.py
@@ -1,8 +1,8 @@
# Time: O(n)
# Space: O(n)
#
-# Given an array of integers and an integer k, return true if
-# and only if there are two distinct indices i and j in the array
+# Given an array of integers and an integer k, return true if
+# and only if there are two distinct indices i and j in the array
# such that nums[i] = nums[j] and the difference between i and j is at most k.
#
diff --git a/Python/contains-duplicate.py b/Python/contains-duplicate.py
index 16c26a3c3..a6ba14224 100644
--- a/Python/contains-duplicate.py
+++ b/Python/contains-duplicate.py
@@ -2,7 +2,7 @@
# Space: O(n)
#
# Given an array of integers, find if the array contains any duplicates.
-# Your function should return true if any value appears at least twice in the array,
+# Your function should return true if any value appears at least twice in the array,
# and it should return false if every element is distinct.
#
diff --git a/Python/contiguous-array.py b/Python/contiguous-array.py
index f16e9147d..104194c0b 100644
--- a/Python/contiguous-array.py
+++ b/Python/contiguous-array.py
@@ -27,5 +27,5 @@ def findMaxLength(self, nums):
result = max(result, i - lookup[count])
else:
lookup[count] = i
-
+
return result
diff --git a/Python/continuous-subarray-sum.py b/Python/continuous-subarray-sum.py
index b9991538f..7e46a53bc 100644
--- a/Python/continuous-subarray-sum.py
+++ b/Python/continuous-subarray-sum.py
@@ -36,5 +36,5 @@ def checkSubarraySum(self, nums, k):
return True
else:
lookup[count] = i
-
+
return False
diff --git a/Python/convert-bst-to-greater-tree.py b/Python/convert-bst-to-greater-tree.py
index c0ff15309..5262d45dd 100644
--- a/Python/convert-bst-to-greater-tree.py
+++ b/Python/convert-bst-to-greater-tree.py
@@ -17,7 +17,7 @@
# 18
# / \
# 20 13
-
+
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
diff --git a/Python/convert-sorted-array-to-binary-search-tree.py b/Python/convert-sorted-array-to-binary-search-tree.py
index 4f5858c07..ac3789fb5 100644
--- a/Python/convert-sorted-array-to-binary-search-tree.py
+++ b/Python/convert-sorted-array-to-binary-search-tree.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(logn)
#
-# Given an array where elements are sorted in ascending order,
+# Given an array where elements are sorted in ascending order,
# convert it to a height balanced BST.
#
# Definition for a binary tree node
@@ -28,7 +28,7 @@ def sortedArrayToBSTRecu(self, nums, start, end):
node.left = self.sortedArrayToBSTRecu(nums, start, mid)
node.right = self.sortedArrayToBSTRecu(nums, mid + 1, end)
return node
-
+
def perfect_tree_pivot(self, n):
"""
Find the point to partition n keys for a perfect binary search tree
@@ -44,8 +44,8 @@ def perfect_tree_pivot(self, n):
else:
return n - x // 2 # case 2 == n - (x//2 - 1) - 1 : the left subtree of the root
# has more nodes and the right subtree is perfect.
-
-
+
+
if __name__ == "__main__":
num = [1, 2, 3]
result = Solution().sortedArrayToBST(num)
diff --git a/Python/convert-sorted-list-to-binary-search-tree.py b/Python/convert-sorted-list-to-binary-search-tree.py
index f0624af6c..a1e2a5166 100644
--- a/Python/convert-sorted-list-to-binary-search-tree.py
+++ b/Python/convert-sorted-list-to-binary-search-tree.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(logn)
#
-# Given a singly linked list where elements are sorted in ascending order,
+# Given a singly linked list where elements are sorted in ascending order,
# convert it to a height balanced BST.
#
# Definition for a binary tree node
@@ -27,14 +27,14 @@ def sortedListToBST(self, head):
current, length = current.next, length + 1
self.head = head
return self.sortedListToBSTRecu(0, length)
-
+
def sortedListToBSTRecu(self, start, end):
if start == end:
return None
mid = start + (end - start) / 2
left = self.sortedListToBSTRecu(start, mid)
current = TreeNode(self.head.val)
- current.left = left
+ current.left = left
self.head = self.head.next
current.right = self.sortedListToBSTRecu(mid + 1, end)
return current
diff --git a/Python/convex-polygon.py b/Python/convex-polygon.py
index 27286efd6..a552142c3 100644
--- a/Python/convex-polygon.py
+++ b/Python/convex-polygon.py
@@ -19,4 +19,4 @@ def det(A):
return False
prev = curr
return True
-
+
diff --git a/Python/copy-list-with-random-pointer.py b/Python/copy-list-with-random-pointer.py
index 9f4e8675f..483aa2a3e 100644
--- a/Python/copy-list-with-random-pointer.py
+++ b/Python/copy-list-with-random-pointer.py
@@ -3,7 +3,7 @@
#
# A linked list is given such that each node contains an additional random pointer
# which could point to any node in the list or null.
-#
+#
# Return a deep copy of the list.
#
@@ -25,14 +25,14 @@ def copyRandomList(self, head):
copied.next = current.next
current.next = copied
current = copied.next
-
+
# update random node in copied list
current = head
while current:
if current.random:
current.next.random = current.random.next
current = current.next.next
-
+
# split copied list from combined one
dummy = RandomListNode(0)
copied_current, current = dummy, head
@@ -50,19 +50,19 @@ class Solution2:
def copyRandomList(self, head):
dummy = RandomListNode(0)
current, prev, copies = head, dummy, {}
-
+
while current:
copied = RandomListNode(current.label)
copies[current] = copied
prev.next = copied
prev, current = prev.next, current.next
-
+
current = head
while current:
if current.random:
copies[current].random = copies[current.random]
current = current.next
-
+
return dummy.next
diff --git a/Python/count-and-say.py b/Python/count-and-say.py
index f1b27c374..2bbfc3a4e 100644
--- a/Python/count-and-say.py
+++ b/Python/count-and-say.py
@@ -3,12 +3,12 @@
#
# The count-and-say sequence is the sequence of integers beginning as follows:
# 1, 11, 21, 1211, 111221, ...
-#
+#
# 1 is read off as "one 1" or 11.
# 11 is read off as "two 1s" or 21.
# 21 is read off as "one 2, then one 1" or 1211.
# Given an integer n, generate the nth sequence.
-#
+#
# Note: The sequence of integers will be represented as a string.
#
@@ -19,11 +19,11 @@ def countAndSay(self, n):
for i in xrange(n - 1):
seq = self.getNext(seq)
return seq
-
+
def getNext(self, seq):
i, next_seq = 0, ""
while i < len(seq):
- cnt = 1
+ cnt = 1
while i < len(seq) - 1 and seq[i] == seq[i + 1]:
cnt += 1
i += 1
@@ -35,4 +35,4 @@ def getNext(self, seq):
for i in xrange(1, 4):
print Solution().countAndSay(i)
-
+
diff --git a/Python/count-binary-substrings.py b/Python/count-binary-substrings.py
index f282b349a..e28ba957a 100644
--- a/Python/count-binary-substrings.py
+++ b/Python/count-binary-substrings.py
@@ -20,7 +20,7 @@
# Input: "10101"
# Output: 4
# Explanation: There are 4 substrings: "10", "01", "10", "01" that have equal number of consecutive 1's and 0's.
-#
+#
# Note:
# s.length will be between 1 and 50,000.
# s will only consist of "0" or "1" characters.
diff --git a/Python/count-complete-tree-nodes.py b/Python/count-complete-tree-nodes.py
index 24695387b..dcd6e490a 100644
--- a/Python/count-complete-tree-nodes.py
+++ b/Python/count-complete-tree-nodes.py
@@ -22,12 +22,12 @@ class Solution:
def countNodes(self, root):
if root is None:
return 0
-
+
node, level = root, 0
while node.left is not None:
node = node.left
level += 1
-
+
# Binary search.
left, right = 2 ** level, 2 ** (level + 1)
while left < right:
@@ -36,16 +36,16 @@ def countNodes(self, root):
right = mid
else:
left = mid + 1
-
+
return left - 1
-
+
# Check if the nth node exist.
def exist(self, root, n):
k = 1
while k <= n:
k <<= 1
k >>= 2
-
+
node = root
while k > 0:
if (n & k) == 0:
diff --git a/Python/count-different-palindromic-subsequences.py b/Python/count-different-palindromic-subsequences.py
index e0b4e7452..f1b5ecf1e 100644
--- a/Python/count-different-palindromic-subsequences.py
+++ b/Python/count-different-palindromic-subsequences.py
@@ -11,19 +11,19 @@
# Two sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i.
#
# Example 1:
-# Input:
+# Input:
# S = 'bccb'
# Output: 6
-# Explanation:
+# Explanation:
# The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
# Note that 'bcb' is counted only once, even though it occurs twice.
#
# Example 2:
-# Input:
+# Input:
# S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
# Output: 104860361
-#
-# Explanation:
+#
+# Explanation:
# There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.
# Note:
# - The length of S will be in the range [1, 1000].
@@ -50,20 +50,20 @@ def dp(i, j, prv, nxt, lookup):
result %= P
lookup[i][j] = result
return result
-
+
prv = [None] * len(S)
nxt = [None] * len(S)
-
+
last = [None] * 4
for i in xrange(len(S)):
last[ord(S[i])-ord('a')] = i
prv[i] = tuple(last)
-
+
last = [None] * 4
for i in reversed(xrange(len(S))):
last[ord(S[i])-ord('a')] = i
nxt[i] = tuple(last)
-
+
P = 10**9 + 7
- lookup = [[None] * len(S) for _ in xrange(len(S))]
+ lookup = [[None] * len(S) for _ in xrange(len(S))]
return dp(0, len(S)-1, prv, nxt, lookup) - 1
diff --git a/Python/count-of-range-sum.py b/Python/count-of-range-sum.py
index eb87af804..01242acc0 100644
--- a/Python/count-of-range-sum.py
+++ b/Python/count-of-range-sum.py
@@ -39,7 +39,7 @@ def countAndMergeSort(sums, start, end, lower, upper):
while j < end and sums[j] - sums[i] <= upper:
j += 1
count += j - k
-
+
# Merge the two sorted arrays into tmp.
while r < end and sums[r] < sums[i]:
tmp.append(sums[r])
@@ -80,7 +80,7 @@ def countAndMergeSort(sums, start, end, lower, upper):
while j <= end and sums[j] - sums[i] <= upper:
j += 1
count += j - k
-
+
# Merge the two sorted arrays into tmp.
while r <= end and sums[r] < sums[i]:
tmp.append(sums[r])
diff --git a/Python/count-of-smaller-numbers-after-self.py b/Python/count-of-smaller-numbers-after-self.py
index 7011fa583..42f49c324 100644
--- a/Python/count-of-smaller-numbers-after-self.py
+++ b/Python/count-of-smaller-numbers-after-self.py
@@ -1,9 +1,9 @@
# Time: O(nlogn)
# Space: O(n)
-# You are given an integer array nums and you have to
-# return a new counts array. The counts array has the
-# property where counts[i] is the number of smaller
+# You are given an integer array nums and you have to
+# return a new counts array. The counts array has the
+# property where counts[i] is the number of smaller
# elements to the right of nums[i].
#
# Example:
@@ -77,7 +77,7 @@ def add(self, i, val):
while i < len(self.__bit):
self.__bit[i] += val
i += (i & -i)
-
+
def query(self, i):
ret = 0
while i > 0:
@@ -114,17 +114,17 @@ def countSmaller(self, nums):
res[i] = bst.query(nums[i])
return res
-
+
class BST(object):
class BSTreeNode(object):
def __init__(self, val):
self.val = val
self.count = 0
self.left = self.right = None
-
+
def __init__(self):
self.root = None
-
+
# Insert node into BST.
def insertNode(self, val):
node = self.BSTreeNode(val)
@@ -147,7 +147,7 @@ def insertNode(self, val):
else:
curr.right = node
break
-
+
# Query the smaller count of the value.
def query(self, val):
count = 0
@@ -160,5 +160,5 @@ def query(self, val):
count += 1 + curr.count # Count the number of the smaller nodes.
curr = curr.right
else: # Equal.
- return count + curr.count
+ return count + curr.count
return 0
diff --git a/Python/count-primes.py b/Python/count-primes.py
index 46ad88ddf..569abf3d0 100644
--- a/Python/count-primes.py
+++ b/Python/count-primes.py
@@ -14,7 +14,7 @@ class Solution:
def countPrimes(self, n):
if n <= 2:
return 0
-
+
is_prime = [True] * n
num = n / 2
for i in xrange(3, n, 2):
diff --git a/Python/count-the-repetitions.py b/Python/count-the-repetitions.py
index eeaee7b70..37d8b47cf 100644
--- a/Python/count-the-repetitions.py
+++ b/Python/count-the-repetitions.py
@@ -4,7 +4,7 @@
# Define S = [s,n] as the string S which consists of n connected strings s.
# For example, ["abc", 3] ="abcabcabc".
#
-# On the other hand, we define that string s1 can be obtained from string s2
+# On the other hand, we define that string s1 can be obtained from string s2
# if we can remove some characters from s2 such that it becomes s1.
# For example, “abc” can be obtained from “abdbec” based on our definition, but it can not be obtained from “acbbe”.
#
@@ -38,7 +38,7 @@ def getMaxRepetitions(self, s1, n1, s2, n2):
if s1[i] == s2[j]:
j = (j + 1) % len(s2)
count += (j == 0)
-
+
if j in lookup: # cyclic
i = lookup[j]
prefix_count = repeat_count[i]
@@ -47,5 +47,5 @@ def getMaxRepetitions(self, s1, n1, s2, n2):
return (prefix_count + pattern_count + suffix_count) / n2
lookup[j] = k
repeat_count[k] = count
-
+
return repeat_count[n1] / n2 # not cyclic iff n1 <= s2
diff --git a/Python/count-univalue-subtrees.py b/Python/count-univalue-subtrees.py
index a393f4304..c70a5ba5d 100644
--- a/Python/count-univalue-subtrees.py
+++ b/Python/count-univalue-subtrees.py
@@ -27,6 +27,6 @@ def isUnivalSubtrees(self, root, count):
return [True, count]
return [False, count]
-
+
def isSame(self, root, child, is_uni):
return not child or (is_uni and root.val == child.val)
diff --git a/Python/counting-bits.py b/Python/counting-bits.py
index 6ef845380..8da8a2185 100644
--- a/Python/counting-bits.py
+++ b/Python/counting-bits.py
@@ -2,7 +2,7 @@
# Space: O(n)
# Given a non negative integer number num. For every numbers i
-# in the range 0 <= i <= num calculate the number
+# in the range 0 <= i <= num calculate the number
# of 1's in their binary representation and return them as an array.
#
# Example:
@@ -10,8 +10,8 @@
#
# Follow up:
#
-# It is very easy to come up with a solution with run
-# time O(n*sizeof(integer)). But can you do it in
+# It is very easy to come up with a solution with run
+# time O(n*sizeof(integer)). But can you do it in
# linear time O(n) /possibly in a single pass?
# Space complexity should be O(n).
# Can you do it like a boss? Do it without using
diff --git a/Python/couples-holding-hands.py b/Python/couples-holding-hands.py
index 2348c41c8..0801bcd81 100644
--- a/Python/couples-holding-hands.py
+++ b/Python/couples-holding-hands.py
@@ -15,7 +15,7 @@ def minSwapsCouples(self, row):
for couch1, couch2 in couples:
adj[couch1].append(couch2)
adj[couch2].append(couch1)
-
+
result = 0
for couch in xrange(N):
if not adj[couch]: continue
diff --git a/Python/course-schedule.py b/Python/course-schedule.py
index ecb7fbf72..ddd5fc3de 100644
--- a/Python/course-schedule.py
+++ b/Python/course-schedule.py
@@ -2,27 +2,27 @@
# Space: O(|E|)
#
# There are a total of n courses you have to take, labeled from 0 to n - 1.
-#
-# Some courses may have prerequisites, for example to take course 0
+#
+# Some courses may have prerequisites, for example to take course 0
# you have to first take course 1, which is expressed as a pair: [0,1]
-#
+#
# Given the total number of courses and a list of prerequisite pairs,
# is it possible for you to finish all courses?
-#
+#
# For example:
-#
+#
# 2, [[1,0]]
-# There are a total of 2 courses to take. To take course 1
+# There are a total of 2 courses to take. To take course 1
# you should have finished course 0. So it is possible.
-#
+#
# 2, [[1,0],[0,1]]
-# There are a total of 2 courses to take. To take course 1 you should have
+# There are a total of 2 courses to take. To take course 1 you should have
# finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
-#
+#
# click to show more hints.
-#
+#
# Hints:
-# This problem is equivalent to finding if a cycle exists in a directed graph.
+# This problem is equivalent to finding if a cycle exists in a directed graph.
# If a cycle exists, no topological ordering exists and therefore it will be impossible to take all courses.
# There are several ways to represent a graph. For example, the input prerequisites is a graph represented by
# a list of edges. Is this graph representation appropriate?
@@ -41,7 +41,7 @@ def canFinish(self, numCourses, prerequisites):
:rtype: bool
"""
zero_in_degree_queue, in_degree, out_degree = collections.deque(), {}, {}
-
+
for i, j in prerequisites:
if i not in in_degree:
in_degree[i] = set()
@@ -49,25 +49,25 @@ def canFinish(self, numCourses, prerequisites):
out_degree[j] = set()
in_degree[i].add(j)
out_degree[j].add(i)
-
+
for i in xrange(numCourses):
if i not in in_degree:
zero_in_degree_queue.append(i)
-
+
while zero_in_degree_queue:
prerequisite = zero_in_degree_queue.popleft()
-
+
if prerequisite in out_degree:
for course in out_degree[prerequisite]:
in_degree[course].discard(prerequisite)
if not in_degree[course]:
zero_in_degree_queue.append(course)
-
+
del out_degree[prerequisite]
-
+
if out_degree:
return False
-
+
return True
diff --git a/Python/cracking-the-safe.py b/Python/cracking-the-safe.py
index 916fc26fc..e4874bfcd 100644
--- a/Python/cracking-the-safe.py
+++ b/Python/cracking-the-safe.py
@@ -16,12 +16,12 @@
# Input: n = 1, k = 2
# Output: "01"
# Note: "10" will be accepted too.
-#
+#
# Example 2:
# Input: n = 2, k = 2
# Output: "00110"
# Note: "01100", "10011", "11001" will be accepted too.
-#
+#
# Note:
# - n will be in the range [1, 4].
# - k will be in the range [1, 10].
@@ -88,7 +88,7 @@ def dfs(k, node, lookup, result):
result.append(str(i))
dfs(k, neighbor[1:], lookup, result)
break
-
+
result = [str(k-1)]*(n-1)
lookup = set()
dfs(k, "".join(result), lookup, result)
diff --git a/Python/create-maximum-number.py b/Python/create-maximum-number.py
index af1d98541..c946b12fa 100644
--- a/Python/create-maximum-number.py
+++ b/Python/create-maximum-number.py
@@ -57,7 +57,7 @@ def delete_digit(nums):
res = res[:i] + res[i+1:]
break
return res
-
+
def merge(a, b):
return [max(a, b).pop(0) for _ in xrange(len(a)+len(b))]
diff --git a/Python/daily-temperatures.py b/Python/daily-temperatures.py
index 841982d81..49e55ab96 100644
--- a/Python/daily-temperatures.py
+++ b/Python/daily-temperatures.py
@@ -25,4 +25,4 @@ def dailyTemperatures(self, temperatures):
idx = stk.pop()
result[idx] = i-idx
stk.append(i)
- return result
+ return result
diff --git a/Python/decode-string.py b/Python/decode-string.py
index ab0256f17..c3030c3b5 100644
--- a/Python/decode-string.py
+++ b/Python/decode-string.py
@@ -3,8 +3,8 @@
# Given an encoded string, return it's decoded string.
#
-# The encoding rule is: k[encoded_string],
-# where the encoded_string inside the square brackets is
+# The encoding rule is: k[encoded_string],
+# where the encoded_string inside the square brackets is
# being repeated exactly k times. Note that k is guaranteed
# to be a positive integer.
#
diff --git a/Python/decode-ways.py b/Python/decode-ways.py
index 2f474480b..7d60cfa09 100644
--- a/Python/decode-ways.py
+++ b/Python/decode-ways.py
@@ -2,16 +2,16 @@
# Space: O(1)
#
# A message containing letters from A-Z is being encoded to numbers using the following mapping:
-#
+#
# 'A' -> 1
# 'B' -> 2
# ...
# 'Z' -> 26
# Given an encoded message containing digits, determine the total number of ways to decode it.
-#
+#
# For example,
# Given encoded message "12", it could be decoded as "AB" (1 2) or "L" (12).
-#
+#
# The number of ways decoding "12" is 2.
#
diff --git a/Python/delete-and-earn.py b/Python/delete-and-earn.py
index 4327d0d2b..4f4c82aba 100644
--- a/Python/delete-and-earn.py
+++ b/Python/delete-and-earn.py
@@ -12,14 +12,14 @@
# Example 1:
# Input: nums = [3, 4, 2]
# Output: 6
-# Explanation:
+# Explanation:
# Delete 4 to earn 4 points, consequently 3 is also deleted.
# Then, delete 2 to earn 2 points. 6 total points are earned.
#
# Example 2:
# Input: nums = [2, 2, 3, 3, 3, 4]
# Output: 9
-# Explanation:
+# Explanation:
# Delete 3 to earn 3 points, deleting both 2's and the 4.
# Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
# 9 total points are earned.
diff --git a/Python/design-in-memory-file-system.py b/Python/design-in-memory-file-system.py
index ae5ee030c..0785bfff0 100644
--- a/Python/design-in-memory-file-system.py
+++ b/Python/design-in-memory-file-system.py
@@ -24,7 +24,7 @@
# readContentFromFile: Given a file path, return its content in string format.
#
# Example:
-# Input:
+# Input:
# ["FileSystem","ls","mkdir","addContentToFile","ls","readContentFromFile"]
# [[],["/"],["/a/b/c"],["/a/b/c/d","hello"],["/"],["/a/b/c/d"]]
# Output:
@@ -37,10 +37,10 @@
# users will not attempt to retrieve file content or list a directory or file that does not exist.
# 3. You can assume that all directory names and file names only contain lower-case letters,
# and same names won't exist in the same directory.
-
+
class TrieNode(object):
-
+
def __init__(self):
self.is_file = False
self.children = {}
@@ -50,7 +50,7 @@ class FileSystem(object):
def __init__(self):
self.__root = TrieNode()
-
+
def ls(self, path):
"""
@@ -58,11 +58,11 @@ def ls(self, path):
:rtype: List[str]
"""
curr = self.__getNode(path)
-
+
if curr.is_file:
return [self.__split(path, '/')[-1]]
- return sorted(curr.children.keys())
+ return sorted(curr.children.keys())
def mkdir(self, path):
@@ -72,7 +72,7 @@ def mkdir(self, path):
"""
curr = self.__putNode(path)
curr.is_file = False
-
+
def addContentToFile(self, filePath, content):
"""
diff --git a/Python/design-log-storage-system.py b/Python/design-log-storage-system.py
index 976a44f50..ca9a90979 100644
--- a/Python/design-log-storage-system.py
+++ b/Python/design-log-storage-system.py
@@ -2,14 +2,14 @@
# retrieve: O(n + dlogd), n is the size of the total logs
# , d is the size of the found logs
# Space: O(n)
-
+
class LogSystem(object):
def __init__(self):
self.__logs = []
self.__granularity = {'Year': 4, 'Month': 7, 'Day': 10, \
'Hour': 13, 'Minute': 16, 'Second': 19}
-
+
def put(self, id, timestamp):
"""
@@ -19,7 +19,7 @@ def put(self, id, timestamp):
"""
self.__logs.append((id, timestamp))
-
+
def retrieve(self, s, e, gra):
"""
:type s: str
diff --git a/Python/design-phone-directory.py b/Python/design-phone-directory.py
index d0c2af2a1..2d039ca18 100644
--- a/Python/design-phone-directory.py
+++ b/Python/design-phone-directory.py
@@ -28,7 +28,7 @@ def get(self):
self.__curr += 1
self.__used[number] = True
return number
-
+
def check(self, number):
"""
@@ -38,7 +38,7 @@ def check(self, number):
"""
return 0 <= number < len(self.__numbers) and \
not self.__used[number]
-
+
def release(self, number):
"""
@@ -52,7 +52,7 @@ def release(self, number):
self.__used[number] = False
self.__curr -= 1
self.__numbers[self.__curr] = number
-
+
# Your PhoneDirectory object will be instantiated and called as such:
# obj = PhoneDirectory(maxNumbers)
diff --git a/Python/diagonal-traverse.py b/Python/diagonal-traverse.py
index 8410476a4..639c64adf 100644
--- a/Python/diagonal-traverse.py
+++ b/Python/diagonal-traverse.py
@@ -26,11 +26,11 @@ def findDiagonalOrder(self, matrix):
"""
if not matrix or not matrix[0]:
return []
-
+
result = []
row, col, d = 0, 0, 0
dirs = [(-1, 1), (1, -1)]
-
+
for i in xrange(len(matrix) * len(matrix[0])):
result.append(matrix[row][col])
row += dirs[d][0]
@@ -50,6 +50,6 @@ def findDiagonalOrder(self, matrix):
elif col < 0:
col = 0
d = 1 - d
-
+
return result
-
+
diff --git a/Python/diameter-of-binary-tree.py b/Python/diameter-of-binary-tree.py
index 736e93b3b..063a60ffc 100644
--- a/Python/diameter-of-binary-tree.py
+++ b/Python/diameter-of-binary-tree.py
@@ -6,12 +6,12 @@
# any two nodes in a tree. This path may or may not pass through the root.
#
# Example:
-# Given a binary tree
+# Given a binary tree
# 1
# / \
# 2 3
-# / \
-# 4 5
+# / \
+# 4 5
# Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
#
# Note: The length of path between two nodes is represented by the number of edges between them.
@@ -34,5 +34,5 @@ def depth(root, diameter):
left, diameter = depth(root.left, diameter)
right, diameter = depth(root.right, diameter)
return 1 + max(left, right), max(diameter, 1 + left + right)
-
+
return depth(root, 1)[1] - 1
diff --git a/Python/distinct-subsequences.py b/Python/distinct-subsequences.py
index 48709899e..5d4aad7bc 100644
--- a/Python/distinct-subsequences.py
+++ b/Python/distinct-subsequences.py
@@ -2,14 +2,14 @@
# Space: O(n)
#
# Given a string S and a string T, count the number of distinct subsequences of T in S.
-#
-# A subsequence of a string is a new string which is formed from the original string
-# by deleting some (can be none) of the characters without disturbing the relative positions
+#
+# A subsequence of a string is a new string which is formed from the original string
+# by deleting some (can be none) of the characters without disturbing the relative positions
# of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE" while "AEC" is not).
-#
+#
# Here is an example:
# S = "rabbbit", T = "rabbit"
-#
+#
# Return 3.
#
@@ -23,10 +23,10 @@ def numDistinct(self, S, T):
if S_char == T_char:
ways[j + 1] += ways[j]
return ways[len(T)]
-
+
if __name__ == "__main__":
S = "rabbbit"
T = "rabbit"
result = Solution().numDistinct(S, T)
print result
-
+
diff --git a/Python/distribute-candies.py b/Python/distribute-candies.py
index a04064883..827919c11 100644
--- a/Python/distribute-candies.py
+++ b/Python/distribute-candies.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(n)
-# Given an integer array with even length, where different numbers
+# Given an integer array with even length, where different numbers
# in this array represent different kinds of candies.
# Each number means one candy of the corresponding kind.
# You need to distribute these candies equally in number to brother and sister.
@@ -12,14 +12,14 @@
# Output: 3
# Explanation:
# There are three different kinds of candies (1, 2 and 3), and two candies for each kind.
-# Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too.
-# The sister has three different kinds of candies.
+# Optimal distribution: The sister has candies [1,2,3] and the brother has candies [1,2,3], too.
+# The sister has three different kinds of candies.
#
# Example 2:
# Input: candies = [1,1,2,3]
# Output: 2
-# Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1].
-# The sister has two different kinds of candies, the brother has only one kind of candies.
+# Explanation: For example, the sister has candies [2,3] and the brother has candies [1,1].
+# The sister has two different kinds of candies, the brother has only one kind of candies.
#
# Note:
# The length of the given array is in range [2, 10,000], and will be even.
diff --git a/Python/divide-two-integers.py b/Python/divide-two-integers.py
index b024170f6..9e2bd8193 100644
--- a/Python/divide-two-integers.py
+++ b/Python/divide-two-integers.py
@@ -1,6 +1,6 @@
# Time: O(logn) = O(1)
# Space: O(1)
-#
+#
# Divide two integers without using multiplication, division and mod operator.
@@ -44,7 +44,7 @@ def divide2(self, dividend, divisor):
if not positive:
res = -res
return min(max(-2147483648, res), 2147483647)
-
+
if __name__ == "__main__":
print Solution().divide(123, 12)
print Solution().divide(123, -12)
diff --git a/Python/dungeon-game.py b/Python/dungeon-game.py
index 9348828cb..d42e5d1a3 100644
--- a/Python/dungeon-game.py
+++ b/Python/dungeon-game.py
@@ -1,33 +1,33 @@
# Time: O(m * n)
# Space: O(m + n)
#
-# The demons had captured the princess (P) and imprisoned her
+# The demons had captured the princess (P) and imprisoned her
# in the bottom-right corner of a dungeon. T
-# he dungeon consists of M x N rooms laid out in a 2D grid.
-# Our valiant knight (K) was initially positioned in the top-left room
+# he dungeon consists of M x N rooms laid out in a 2D grid.
+# Our valiant knight (K) was initially positioned in the top-left room
# and must fight his way through the dungeon to rescue the princess.
-#
-# The knight has an initial health point represented by a positive integer.
+#
+# The knight has an initial health point represented by a positive integer.
# If at any point his health point drops to 0 or below, he dies immediately.
-#
-# Some of the rooms are guarded by demons,
-# so the knight loses health (negative integers) upon entering these rooms;
+#
+# Some of the rooms are guarded by demons,
+# so the knight loses health (negative integers) upon entering these rooms;
# other rooms are either empty (0's) or contain magic orbs that increase the knight's health (positive integers).
-#
-# In order to reach the princess as quickly as possible,
+#
+# In order to reach the princess as quickly as possible,
# the knight decides to move only rightward or downward in each step.
-#
-#
-# Write a function to determine the knight's minimum initial health
+#
+#
+# Write a function to determine the knight's minimum initial health
# so that he is able to rescue the princess.
-#
-# For example, given the dungeon below, the initial health of
+#
+# For example, given the dungeon below, the initial health of
# the knight must be at least 7 if he follows the optimal path RIGHT-> RIGHT -> DOWN -> DOWN.
-#
+#
# Notes:
-#
+#
# The knight's health has no upper bound.
-# Any room can contain threats or power-ups, even the first room the knight enters
+# Any room can contain threats or power-ups, even the first room the knight enters
# and the bottom-right room where the princess is imprisoned.
#
@@ -37,16 +37,16 @@ class Solution:
def calculateMinimumHP(self, dungeon):
DP = [float("inf") for _ in dungeon[0]]
DP[-1] = 1
-
+
for i in reversed(xrange(len(dungeon))):
DP[-1] = max(DP[-1] - dungeon[i][-1], 1)
for j in reversed(xrange(len(dungeon[i]) - 1)):
min_HP_on_exit = min(DP[j], DP[j + 1])
DP[j] = max(min_HP_on_exit - dungeon[i][j], 1)
-
+
return DP[0]
-# Time: O(m * n logk), where k is the possible maximum sum of loses
+# Time: O(m * n logk), where k is the possible maximum sum of loses
# Space: O(m + n)
class Solution2:
# @param dungeon, a list of lists of integers
@@ -57,9 +57,9 @@ def calculateMinimumHP(self, dungeon):
for room in rooms:
if room < 0:
maximum_loses += abs(room)
-
+
return self.binarySearch(dungeon, maximum_loses)
-
+
def binarySearch(self, dungeon, maximum_loses):
start, end = 1, maximum_loses + 1
result = 0
@@ -70,20 +70,20 @@ def binarySearch(self, dungeon, maximum_loses):
else:
start = mid + 1
return start
-
+
def DP(self, dungeon, HP):
remain_HP = [0 for _ in dungeon[0]]
remain_HP[0] = HP + dungeon[0][0]
for j in xrange(1, len(remain_HP)):
- if remain_HP[j - 1] > 0:
+ if remain_HP[j - 1] > 0:
remain_HP[j] = max(remain_HP[j - 1] + dungeon[0][j], 0)
-
+
for i in xrange(1, len(dungeon)):
if remain_HP[0] > 0:
remain_HP[0] = max(remain_HP[0] + dungeon[i][0], 0)
else:
remain_HP[0] = 0
-
+
for j in xrange(1, len(remain_HP)):
remain = 0
if remain_HP[j - 1] > 0:
@@ -99,9 +99,9 @@ def DP(self, dungeon, HP):
[ -5, -10, 1], \
[ 10, 30, -5]]
print Solution().calculateMinimumHP(dungeon)
-
+
dungeon = [[ -200]]
print Solution().calculateMinimumHP(dungeon)
-
+
dungeon = [[0, -3]]
print Solution().calculateMinimumHP(dungeon)
\ No newline at end of file
diff --git a/Python/edit-distance.py b/Python/edit-distance.py
index 8498a2f57..2ca1e67c4 100644
--- a/Python/edit-distance.py
+++ b/Python/edit-distance.py
@@ -1,11 +1,11 @@
# Time: O(n * m)
# Space: O(n + m)
#
-# Given two words word1 and word2, find the minimum number of steps
+# Given two words word1 and word2, find the minimum number of steps
# required to convert word1 to word2. (each operation is counted as 1 step.)
-#
+#
# You have the following 3 operations permitted on a word:
-#
+#
# a) Insert a character
# b) Delete a character
# c) Replace a character
@@ -16,9 +16,9 @@ class Solution:
def minDistance(self, word1, word2):
if len(word1) < len(word2):
return self.minDistance(word2, word1)
-
+
distance = [i for i in xrange(len(word2) + 1)]
-
+
for i in xrange(1, len(word1) + 1):
pre_distance_i_j = distance[0]
distance[0] = i
@@ -37,10 +37,10 @@ def minDistance(self, word1, word2):
# Space: O(n * m)
class Solution2:
# @return an integer
- def minDistance(self, word1, word2):
+ def minDistance(self, word1, word2):
distance = [[i] for i in xrange(len(word1) + 1)]
distance[0] = [j for j in xrange(len(word2) + 1)]
-
+
for i in xrange(1, len(word1) + 1):
for j in xrange(1, len(word2) + 1):
insert = distance[i][j - 1] + 1
@@ -49,7 +49,7 @@ def minDistance(self, word1, word2):
if word1[i - 1] != word2[j - 1]:
replace += 1
distance[i].append(min(insert, delete, replace))
-
+
return distance[-1][-1]
if __name__ == "__main__":
diff --git a/Python/encode-and-decode-strings.py b/Python/encode-and-decode-strings.py
index 39445a51a..b6e33bbda 100644
--- a/Python/encode-and-decode-strings.py
+++ b/Python/encode-and-decode-strings.py
@@ -5,7 +5,7 @@ class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string.
-
+
:type strs: List[str]
:rtype: str
"""
@@ -17,7 +17,7 @@ def encode(self, strs):
def decode(self, s):
"""Decodes a single string to a list of strings.
-
+
:type s: str
:rtype: List[str]
"""
@@ -26,5 +26,5 @@ def decode(self, s):
while i < len(s):
l = int(s[i:i+8], 16)
strs.append(s[i+8:i+8+l])
- i += 8+l
+ i += 8+l
return strs
diff --git a/Python/encode-string-with-shortest-length.py b/Python/encode-string-with-shortest-length.py
index 6988e6d4c..667663b29 100644
--- a/Python/encode-string-with-shortest-length.py
+++ b/Python/encode-string-with-shortest-length.py
@@ -23,6 +23,6 @@ def encode_substr(dp, s, i, j):
if len(dp[i][k]) + len(dp[k+1][j]) < len(dp[i][j]):
dp[i][j] = dp[i][k] + dp[k+1][j]
encoded_string = encode_substr(dp, s, i, j)
- if len(encoded_string) < len(dp[i][j]):
+ if len(encoded_string) < len(dp[i][j]):
dp[i][j] = encoded_string
return dp[0][len(s) - 1]
diff --git a/Python/escape-the-ghosts.py b/Python/escape-the-ghosts.py
index be1e5f43f..0dff9431f 100644
--- a/Python/escape-the-ghosts.py
+++ b/Python/escape-the-ghosts.py
@@ -17,27 +17,27 @@
# Return True if and only if it is possible to escape.
#
# Example 1:
-# Input:
+# Input:
# ghosts = [[1, 0], [0, 3]]
# target = [0, 1]
# Output: true
-# Explanation:
+# Explanation:
# You can directly reach the destination (0, 1) at time 1,
# while the ghosts located at (1, 0) or (0, 3) have no way to catch up with you.
#
# Example 2:
-# Input:
+# Input:
# ghosts = [[1, 0]]
# target = [2, 0]
# Output: false
-# Explanation:
+# Explanation:
# You need to reach the destination (2, 0), but the ghost at (1, 0) lies between you and the destination.
# Example 3:
-# Input:
+# Input:
# ghosts = [[2, 0]]
# target = [1, 0]
# Output: false
-# Explanation:
+# Explanation:
# The ghost can reach the target at the same time as you.
#
# Note:
diff --git a/Python/evaluate-reverse-polish-notation.py b/Python/evaluate-reverse-polish-notation.py
index e437aaf09..b64bad971 100644
--- a/Python/evaluate-reverse-polish-notation.py
+++ b/Python/evaluate-reverse-polish-notation.py
@@ -2,9 +2,9 @@
# Space: O(n)
#
# Evaluate the value of an arithmetic expression in Reverse Polish Notation.
-#
+#
# Valid operators are +, -, *, /. Each operand may be an integer or another expression.
-#
+#
# Some examples:
# ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
# ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
@@ -23,7 +23,7 @@ def evalRPN(self, tokens):
y, x = numerals.pop(), numerals.pop()
numerals.append(int(operators[token](x * 1.0, y)))
return numerals.pop()
-
+
if __name__ == "__main__":
print Solution().evalRPN(["2", "1", "+", "3", "*"])
print Solution().evalRPN(["4", "13", "5", "/", "+"])
diff --git a/Python/excel-sheet-column-number.py b/Python/excel-sheet-column-number.py
index 667233c59..ad16cb326 100644
--- a/Python/excel-sheet-column-number.py
+++ b/Python/excel-sheet-column-number.py
@@ -2,18 +2,18 @@
# Space: O(1)
# Related to question Excel Sheet Column Title
-#
+#
# Given a column title as appear in an Excel sheet, return its corresponding column number.
-#
+#
# For example:
-#
+#
# A -> 1
# B -> 2
# C -> 3
# ...
# Z -> 26
# AA -> 27
-# AB -> 28
+# AB -> 28
class Solution(object):
def titleToNumber(self, s):
diff --git a/Python/excel-sheet-column-title.py b/Python/excel-sheet-column-title.py
index a2160e9d5..041031253 100644
--- a/Python/excel-sheet-column-title.py
+++ b/Python/excel-sheet-column-title.py
@@ -2,16 +2,16 @@
# Space: O(1)
# Given a positive integer, return its corresponding column title as appear in an Excel sheet.
-#
+#
# For example:
-#
+#
# 1 -> A
# 2 -> B
# 3 -> C
# ...
# 26 -> Z
# 27 -> AA
-# 28 -> AB
+# 28 -> AB
class Solution(object):
def convertToTitle(self, n):
@@ -20,11 +20,11 @@ def convertToTitle(self, n):
:rtype: str
"""
result, dvd = "", n
-
+
while dvd:
result += chr((dvd - 1) % 26 + ord('A'))
dvd = (dvd - 1) / 26
-
+
return result[::-1]
diff --git a/Python/exclusive-time-of-functions.py b/Python/exclusive-time-of-functions.py
index 02127e25c..fff0bcbf7 100644
--- a/Python/exclusive-time-of-functions.py
+++ b/Python/exclusive-time-of-functions.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(n)
-# Given the running logs of n functions that are executed
+# Given the running logs of n functions that are executed
# in a nonpreemptive single threaded CPU, find the exclusive time of these functions.
#
# Each function has a unique id, start from 0 to n-1.
@@ -19,7 +19,7 @@
# Example 1:
# Input:
# n = 2
-# logs =
+# logs =
# ["0:start:0",
# "1:start:2",
# "1:end:5",
@@ -27,9 +27,9 @@
# Output:[3, 4]
#
# Explanation:
-# Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1.
+# Function 0 starts at time 0, then it executes 2 units of time and reaches the end of time 1.
# Now function 0 calls function 1, function 1 starts at time 2, executes 4 units of time and end at time 5.
-# Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time.
+# Function 0 is running again at time 6, and also end at the time 6, thus executes 1 unit of time.
# So function 0 totally execute 2 + 1 = 3 units of time, and function 1 totally execute 4 units of time.
#
# Note:
diff --git a/Python/expression-add-operators.py b/Python/expression-add-operators.py
index 15d972d3f..f26c4c7ad 100644
--- a/Python/expression-add-operators.py
+++ b/Python/expression-add-operators.py
@@ -1,13 +1,13 @@
# Time: O(4^n)
# Space: O(n)
#
-# Given a string that contains only digits 0-9
-# and a target value, return all possibilities
+# Given a string that contains only digits 0-9
+# and a target value, return all possibilities
# to add operators +, -, or * between the digits
# so they evaluate to the target value.
#
-# Examples:
-# "123", 6 -> ["1+2+3", "1*2*3"]
+# Examples:
+# "123", 6 -> ["1+2+3", "1*2*3"]
# "232", 8 -> ["2*3+2", "2+3*2"]
# "00", 0 -> ["0+0", "0-0", "0*0"]
# "3456237490", 9191 -> []
@@ -47,21 +47,21 @@ def addOperatorsDFS(self, num, target, pos, operand1, operand2, expr, result):
# Avoid "00...".
if str(val) != val_str:
break
-
+
# Case '+':
expr.append("+" + val_str)
self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, val, expr, result)
expr.pop()
-
+
# Case '-':
expr.append("-" + val_str)
self.addOperatorsDFS(num, target, i + 1, operand1 + operand2, -val, expr, result)
expr.pop()
-
+
# Case '*':
expr.append("*" + val_str)
self.addOperatorsDFS(num, target, i + 1, operand1, operand2 * val, expr, result)
expr.pop()
-
+
i += 1
-
+
diff --git a/Python/factorial-trailing-zeroes.py b/Python/factorial-trailing-zeroes.py
index 106b59beb..bccfd7e75 100644
--- a/Python/factorial-trailing-zeroes.py
+++ b/Python/factorial-trailing-zeroes.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given an integer n, return the number of trailing zeroes in n!.
-#
+#
# Note: Your solution should be in logarithmic time complexity.
#
diff --git a/Python/find-all-anagrams-in-a-string.py b/Python/find-all-anagrams-in-a-string.py
index e80e46ee0..4122bc0bc 100644
--- a/Python/find-all-anagrams-in-a-string.py
+++ b/Python/find-all-anagrams-in-a-string.py
@@ -45,7 +45,7 @@ def findAnagrams(self, s, p):
cnts = [0] * 26
for c in p:
cnts[ord(c) - ord('a')] += 1
-
+
left, right = 0, 0
while right < len(s):
cnts[ord(s[right]) - ord('a')] -= 1
diff --git a/Python/find-all-duplicates-in-an-array.py b/Python/find-all-duplicates-in-an-array.py
index a9f4f054d..47a601d3a 100644
--- a/Python/find-all-duplicates-in-an-array.py
+++ b/Python/find-all-duplicates-in-an-array.py
@@ -28,7 +28,7 @@ def findDuplicates(self, nums):
else:
nums[abs(i)-1] *= -1
return result
-
+
# Time: O(n)
# Space: O(1)
@@ -42,7 +42,7 @@ def findDuplicates(self, nums):
i = 0
while i < len(nums):
if nums[i] != nums[nums[i]-1]:
- nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
+ nums[nums[i]-1], nums[i] = nums[i], nums[nums[i]-1]
else:
i += 1
diff --git a/Python/find-bottom-left-tree-value.py b/Python/find-bottom-left-tree-value.py
index bda1f8710..15dbde147 100644
--- a/Python/find-bottom-left-tree-value.py
+++ b/Python/find-bottom-left-tree-value.py
@@ -12,7 +12,7 @@
#
# Output:
# 1
-# Example 2:
+# Example 2:
# Input:
#
# 1
diff --git a/Python/find-k-pairs-with-smallest-sums.py b/Python/find-k-pairs-with-smallest-sums.py
index 272a4ccff..6a1750aee 100644
--- a/Python/find-k-pairs-with-smallest-sums.py
+++ b/Python/find-k-pairs-with-smallest-sums.py
@@ -24,7 +24,7 @@
# The first 2 pairs are returned from the sequence:
# [1,1],[1,1],[1,2],[2,1],[1,2],[2,2],[1,3],[1,3],[2,3]
# Example 3:
-# Given nums1 = [1,2], nums2 = [3], k = 3
+# Given nums1 = [1,2], nums2 = [3], k = 3
#
# Return: [1,3],[2,3]
#
diff --git a/Python/find-k-th-smallest-pair-distance.py b/Python/find-k-th-smallest-pair-distance.py
index 6badaf3c1..970fe106a 100644
--- a/Python/find-k-th-smallest-pair-distance.py
+++ b/Python/find-k-th-smallest-pair-distance.py
@@ -8,7 +8,7 @@
# Input:
# nums = [1,3,1]
# k = 1
-# Output: 0
+# Output: 0
# Explanation:
# Here are all the pairs:
# (1,3) -> 2
diff --git a/Python/find-largest-value-in-each-tree-row.py b/Python/find-largest-value-in-each-tree-row.py
index 0ddc4af54..0343ca2a7 100644
--- a/Python/find-largest-value-in-each-tree-row.py
+++ b/Python/find-largest-value-in-each-tree-row.py
@@ -4,13 +4,13 @@
# You need to find the largest value in each row of a binary tree.
#
# Example:
-# Input:
+# Input:
#
# 1
# / \
# 3 2
-# / \ \
-# 5 3 9
+# / \ \
+# 5 3 9
#
# Output: [1, 3, 9]
@@ -56,4 +56,4 @@ def largestValues(self, root):
result.append(max(node.val for node in curr))
curr = [child for node in curr for child in (node.left, node.right) if child]
return result
-
+
diff --git a/Python/find-median-from-data-stream.py b/Python/find-median-from-data-stream.py
index 3e3f968fb..df79d898e 100644
--- a/Python/find-median-from-data-stream.py
+++ b/Python/find-median-from-data-stream.py
@@ -1,11 +1,11 @@
# Time: O(nlogn) for total n addNums, O(logn) per addNum, O(1) per findMedian.
# Space: O(n), total space
-# Median is the middle value in an ordered integer list.
-# If the size of the list is even, there is no middle value.
+# Median is the middle value in an ordered integer list.
+# If the size of the list is even, there is no middle value.
# So the median is the mean of the two middle value.
#
-# Examples:
+# Examples:
# [2,3,4] , the median is 3
#
# [2,3], the median is (2 + 3) / 2 = 2.5
@@ -19,7 +19,7 @@
# add(1)
# add(2)
# findMedian() -> 1.5
-# add(3)
+# add(3)
# findMedian() -> 2
# Heap solution.
diff --git a/Python/find-minimum-in-rotated-sorted-array-ii.py b/Python/find-minimum-in-rotated-sorted-array-ii.py
index fcb09d212..911eacbb7 100644
--- a/Python/find-minimum-in-rotated-sorted-array-ii.py
+++ b/Python/find-minimum-in-rotated-sorted-array-ii.py
@@ -3,14 +3,14 @@
#
# Follow up for "Find Minimum in Rotated Sorted Array":
# What if duplicates are allowed?
-#
+#
# Would this affect the run-time complexity? How and why?
# Suppose a sorted array is rotated at some pivot unknown to you beforehand.
-#
+#
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
-#
+#
# Find the minimum element.
-#
+#
# The array may contain duplicates.
#
@@ -43,7 +43,7 @@ def findMin(self, nums):
left, right = 0, len(nums) - 1
while left < right and nums[left] >= nums[right]:
mid = left + (right - left) / 2
-
+
if nums[mid] == nums[left]:
left += 1
elif nums[mid] < nums[left]:
diff --git a/Python/find-mode-in-binary-search-tree.py b/Python/find-mode-in-binary-search-tree.py
index 60a53fa65..facb55471 100644
--- a/Python/find-mode-in-binary-search-tree.py
+++ b/Python/find-mode-in-binary-search-tree.py
@@ -39,7 +39,7 @@ def findMode(self, root):
def inorder(root, prev, cnt, max_cnt, result):
if not root:
return prev, cnt, max_cnt
-
+
prev, cnt, max_cnt = inorder(root.left, prev, cnt, max_cnt, result)
if prev:
if root.val == prev.val:
@@ -53,7 +53,7 @@ def inorder(root, prev, cnt, max_cnt, result):
elif cnt == max_cnt:
result.append(root.val)
return inorder(root.right, root, cnt, max_cnt, result)
-
+
if not root:
return []
result = []
diff --git a/Python/find-peak-element.py b/Python/find-peak-element.py
index dfa85fd2d..b986c43bf 100644
--- a/Python/find-peak-element.py
+++ b/Python/find-peak-element.py
@@ -2,15 +2,15 @@
# Space: O(1)
# A peak element is an element that is greater than its neighbors.
-#
+#
# Given an input array where num[i] != num[i+1],
# find a peak element and return its index.
-#
-# The array may contain multiple peaks, in that case
+#
+# The array may contain multiple peaks, in that case
# return the index to any one of the peaks is fine.
-#
+#
# You may imagine that num[-1] = num[n] = -infinite.
-#
+#
# For example, in array [1, 2, 3, 1], 3 is a peak element
# and your function should return the index number 2.
#
@@ -18,21 +18,21 @@
# Your solution should be in logarithmic complexity.
-class Solution(object):
+class Solution(object):
def findPeakElement(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
left, right = 0, len(nums) - 1
-
+
while left < right:
mid = left + (right - left) / 2
if nums[mid] > nums[mid + 1]:
right = mid
else:
left = mid + 1
-
+
return left
diff --git a/Python/find-pivot-index.py b/Python/find-pivot-index.py
index 5ca035a46..37880950f 100644
--- a/Python/find-pivot-index.py
+++ b/Python/find-pivot-index.py
@@ -10,18 +10,18 @@
# you should return the left-most pivot index.
#
# Example 1:
-# Input:
+# Input:
# nums = [1, 7, 3, 6, 5, 6]
# Output: 3
-# Explanation:
+# Explanation:
# The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
# Also, 3 is the first index where this occurs.
#
# Example 2:
-# Input:
+# Input:
# nums = [1, 2, 3]
# Output: -1
-# Explanation:
+# Explanation:
# There is no index that satisfies the conditions in the problem statement.
#
# Note:
@@ -41,4 +41,4 @@ def pivotIndex(self, nums):
return i
left_sum += num
return -1
-
+
diff --git a/Python/find-the-duplicate-number.py b/Python/find-the-duplicate-number.py
index c7c9fe49d..011afc5be 100644
--- a/Python/find-the-duplicate-number.py
+++ b/Python/find-the-duplicate-number.py
@@ -55,7 +55,7 @@ def findDuplicate(self, nums):
if num <= mid:
count += 1
if count > mid:
- right = mid - 1
+ right = mid - 1
else:
left = mid + 1
return left
diff --git a/Python/first-bad-version.py b/Python/first-bad-version.py
index af2bdc0a5..32ff42d2b 100644
--- a/Python/first-bad-version.py
+++ b/Python/first-bad-version.py
@@ -4,16 +4,16 @@
# You are a product manager and currently leading a team to
# develop a new product. Unfortunately, the latest version of
# your product fails the quality check. Since each version is
-# developed based on the previous version, all the versions
+# developed based on the previous version, all the versions
# after a bad version are also bad.
#
-# Suppose you have n versions [1, 2, ..., n] and you want to
-# find out the first bad one, which causes all the following
+# Suppose you have n versions [1, 2, ..., n] and you want to
+# find out the first bad one, which causes all the following
# ones to be bad.
#
-# You are given an API bool isBadVersion(version) which will
-# return whether version is bad. Implement a function to find
-# the first bad version. You should minimize the number of
+# You are given an API bool isBadVersion(version) which will
+# return whether version is bad. Implement a function to find
+# the first bad version. You should minimize the number of
# calls to the API.
#
diff --git a/Python/first-missing-positive.py b/Python/first-missing-positive.py
index 134baa714..eb09936d4 100644
--- a/Python/first-missing-positive.py
+++ b/Python/first-missing-positive.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# Given an unsorted integer array, find the first missing positive integer.
-#
+#
# For example,
# Given [1,2,0] return 3,
# and [3,4,-1,1] return 2.
-#
+#
# Your algorithm should run in O(n) time and uses constant space.
#
@@ -20,12 +20,12 @@ def firstMissingPositive(self, A):
A[A[i]-1], A[i] = A[i], A[A[i]-1]
else:
i += 1
-
+
for i, integer in enumerate(A):
if integer != i + 1:
return i + 1
return len(A) + 1
-
+
if __name__ == "__main__":
print Solution().firstMissingPositive([1,2,0])
print Solution().firstMissingPositive([3,4,-1,1])
diff --git a/Python/flatten-2d-vector.py b/Python/flatten-2d-vector.py
index 7b40db259..7443014cb 100644
--- a/Python/flatten-2d-vector.py
+++ b/Python/flatten-2d-vector.py
@@ -26,7 +26,7 @@ def hasNext(self):
return self.x != len(self.vec) and self.y != len(self.vec[self.x])
def adjustNextIter(self):
- while self.x != len(self.vec) and self.y == len(self.vec[self.x]):
+ while self.x != len(self.vec) and self.y == len(self.vec[self.x]):
self.x += 1
if self.x != len(self.vec):
self.y = 0
diff --git a/Python/flatten-binary-tree-to-linked-list.py b/Python/flatten-binary-tree-to-linked-list.py
index 579f2e319..581275cb0 100644
--- a/Python/flatten-binary-tree-to-linked-list.py
+++ b/Python/flatten-binary-tree-to-linked-list.py
@@ -2,10 +2,10 @@
# Space: O(h), h is height of binary tree
#
# Given a binary tree, flatten it to a linked list in-place.
-#
+#
# For example,
# Given
-#
+#
# 1
# / \
# 2 5
@@ -37,7 +37,7 @@ class Solution:
# @return nothing, do it in place
def flatten(self, root):
return self.flattenRecu(root, None)
-
+
def flattenRecu(self, root, list_head):
if root != None:
list_head = self.flattenRecu(root.right, list_head)
@@ -47,7 +47,7 @@ def flattenRecu(self, root, list_head):
return root
else:
return list_head
-
+
class Solution2:
list_head = None
# @param root, a tree node
@@ -60,7 +60,7 @@ def flatten(self, root):
root.left = None
self.list_head = root
return root
-
+
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
diff --git a/Python/flatten-nested-list-iterator.py b/Python/flatten-nested-list-iterator.py
index e9646fb69..255847377 100644
--- a/Python/flatten-nested-list-iterator.py
+++ b/Python/flatten-nested-list-iterator.py
@@ -59,7 +59,7 @@ def hasNext(self):
self.__depth[-1][1] += 1
self.__depth.append([nestedList[i].getList(), 0])
return False
-
+
# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
diff --git a/Python/flip-game.py b/Python/flip-game.py
index 8c8760f43..b366ed982 100644
--- a/Python/flip-game.py
+++ b/Python/flip-game.py
@@ -29,4 +29,4 @@ def generatePossibleNextMoves(self, s):
:rtype: List[str]
"""
return [s[:i] + "--" + s[i+2:] for i in xrange(len(s) - 1) if s[i:i+2] == "++"]
-
+
diff --git a/Python/flood-fill.py b/Python/flood-fill.py
index 7f1149a0f..701117bea 100644
--- a/Python/flood-fill.py
+++ b/Python/flood-fill.py
@@ -15,12 +15,12 @@
# At the end, return the modified image.
#
# Example 1:
-# Input:
+# Input:
# image = [[1,1,1],[1,1,0],[1,0,1]]
# sr = 1, sc = 1, newColor = 2
# Output: [[2,2,2],[2,2,0],[2,0,1]]
-# Explanation:
-# From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
+# Explanation:
+# From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
# by a path of the same color as the starting pixel are colored with the new color.
# Note the bottom corner is not colored 2, because it is not 4-directionally connected
# to the starting pixel.
@@ -46,11 +46,11 @@ def dfs(image, r, c, newColor, color):
0 <= c < len(image[0]) and \
image[r][c] == color):
return
-
+
image[r][c] = newColor
for d in directions:
dfs(image, r+d[0], c+d[1], newColor, color)
-
+
color = image[sr][sc]
if color == newColor: return image
dfs(image, sr, sc, newColor, color)
diff --git a/Python/fraction-to-recurring-decimal.py b/Python/fraction-to-recurring-decimal.py
index 98dff2202..7fed92fb2 100644
--- a/Python/fraction-to-recurring-decimal.py
+++ b/Python/fraction-to-recurring-decimal.py
@@ -3,11 +3,11 @@
# Given two integers representing the numerator and denominator of a fraction,
# return the fraction in string format.
-#
+#
# If the fractional part is repeating, enclose the repeating part in parentheses.
-#
+#
# For example,
-#
+#
# Given numerator = 1, denominator = 2, return "0.5".
# Given numerator = 2, denominator = 1, return "2".
# Given numerator = 2, denominator = 3, return "0.(6)".
@@ -20,8 +20,8 @@ def fractionToDecimal(self, numerator, denominator):
:rtype: str
"""
result = ""
- if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0):
- result = "-"
+ if (numerator > 0 and denominator < 0) or (numerator < 0 and denominator > 0):
+ result = "-"
dvd, dvs = abs(numerator), abs(denominator)
result += str(dvd / dvs)
diff --git a/Python/friend-circles.py b/Python/friend-circles.py
index 19ee1f376..486294dfd 100644
--- a/Python/friend-circles.py
+++ b/Python/friend-circles.py
@@ -12,21 +12,21 @@
# otherwise not. And you have to output the total number of friend circles among all the students.
#
# Example 1:
-# Input:
+# Input:
# [[1,1,0],
# [1,1,0],
# [0,0,1]]
# Output: 2
-# Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
+# Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
# The 2nd student himself is in a friend circle. So return 2.
#
# Example 2:
-# Input:
+# Input:
# [[1,1,0],
# [1,1,1],
# [0,1,1]]
# Output: 1
-# Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
+# Explanation:The 0th and 1st students are direct friends, the 1st and 2nd students are direct friends,
# so the 0th and 2nd students are indirect friends. All of them are in the same friend circle, so return 1.
#
# Note:
@@ -45,12 +45,12 @@ class UnionFind(object):
def __init__(self, n):
self.set = range(n)
self.count = n
-
+
def find_set(self, x):
if self.set[x] != x:
self.set[x] = self.find_set(self.set[x]) # path compression.
return self.set[x]
-
+
def union_set(self, x, y):
x_root, y_root = map(self.find_set, (x, y))
if x_root != y_root:
@@ -63,4 +63,4 @@ def union_set(self, x, y):
if M[i][j] and i != j:
circles.union_set(i, j)
return circles.count
-
+
diff --git a/Python/frog-jump.py b/Python/frog-jump.py
index 447071fbe..3b1ca8637 100644
--- a/Python/frog-jump.py
+++ b/Python/frog-jump.py
@@ -1,8 +1,8 @@
-# Time: O(n) ~ O(n^2)
+# Time: O(n) ~ O(n^2)
# Space: O(n)
# A frog is crossing a river. The river is divided into x units and
-# at each unit there may or may not exist a stone.
+# at each unit there may or may not exist a stone.
# The frog can jump on a stone, but it must not jump into the water.
#
# Given a list of stones' positions (in units) in sorted ascending order,
@@ -26,15 +26,15 @@
# third stone at the 3rd unit, and so on...
# The last stone at the 17th unit.
#
-# Return true. The frog can jump to the last stone by jumping
-# 1 unit to the 2nd stone, then 2 units to the 3rd stone, then
-# 2 units to the 4th stone, then 3 units to the 6th stone,
+# Return true. The frog can jump to the last stone by jumping
+# 1 unit to the 2nd stone, then 2 units to the 3rd stone, then
+# 2 units to the 4th stone, then 3 units to the 6th stone,
# 4 units to the 7th stone, and 5 units to the 8th stone.
# Example 2:
#
# [0,1,2,3,4,8,9,11]
#
-# Return false. There is no way to jump to the last stone as
+# Return false. There is no way to jump to the last stone as
# the gap between the 5th and 6th stone is too large.
# DP with hash table
diff --git a/Python/game-of-life.py b/Python/game-of-life.py
index f569bde1f..8e2a4132a 100644
--- a/Python/game-of-life.py
+++ b/Python/game-of-life.py
@@ -1,35 +1,35 @@
# Time: O(m * n)
# Space: O(1)
-# According to the Wikipedia's article:
-# "The Game of Life, also known simply as Life,
-# is a cellular automaton devised by the British
+# According to the Wikipedia's article:
+# "The Game of Life, also known simply as Life,
+# is a cellular automaton devised by the British
# mathematician John Horton Conway in 1970."
#
-# Given a board with m by n cells, each cell has
-# an initial state live (1) or dead (0).
+# Given a board with m by n cells, each cell has
+# an initial state live (1) or dead (0).
# Each cell interacts with its eight neighbors
# (horizontal, vertical, diagonal)
-# using the following four rules
+# using the following four rules
# (taken from the above Wikipedia article):
#
# - Any live cell with fewer than two live neighbors dies,
# as if caused by under-population.
-# - Any live cell with two or three live neighbors lives
+# - Any live cell with two or three live neighbors lives
# on to the next generation.
# - Any live cell with more than three live neighbors dies,
# as if by over-population..
-# - Any dead cell with exactly three live neighbors
+# - Any dead cell with exactly three live neighbors
# becomes a live cell, as if by reproduction.
#
-# Write a function to compute the next state
+# Write a function to compute the next state
# (after one update) of the board given its current state.
#
-# Follow up:
+# Follow up:
# - Could you solve it in-place? Remember that the board needs
# to be updated at the same time: You cannot update some cells
# first and then use their updated values to update other cells.
-# - In this question, we represent the board using a 2D array.
+# - In this question, we represent the board using a 2D array.
# In principle, the board is infinite, which would cause problems
# when the active area encroaches the border of the array.
# How would you address these problems?
@@ -57,7 +57,7 @@ def gameOfLife(self, board):
# Any live cell with two live neighbors.
# Any dead cell with exactly three live neighbors lives.
if (count == 4 and board[i][j]) or count == 3:
- board[i][j] |= 2 # Mark as live.
+ board[i][j] |= 2 # Mark as live.
for i in xrange(m):
for j in xrange(n):
diff --git a/Python/gas-station.py b/Python/gas-station.py
index 72d6a0806..30a6fe5cc 100644
--- a/Python/gas-station.py
+++ b/Python/gas-station.py
@@ -2,12 +2,12 @@
# Space: O(1)
#
# 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, otherwise return -1.
-#
+#
# Note:
# The solution is guaranteed to be unique.
#
@@ -27,7 +27,7 @@ def canCompleteCircuit(self, gas, cost):
current_sum = 0
if total_sum >= 0:
return start
-
+
return -1
if __name__ == "__main__":
diff --git a/Python/generate-parentheses.py b/Python/generate-parentheses.py
index 0b9712875..2ffcfc194 100644
--- a/Python/generate-parentheses.py
+++ b/Python/generate-parentheses.py
@@ -1,11 +1,11 @@
# Time: O(4^n / n^(3/2)) ~= Catalan numbers
# Space: O(n)
#
-# Given n pairs of parentheses, write a function to generate
+# Given n pairs of parentheses, write a function to generate
# all combinations of well-formed parentheses.
-#
+#
# For example, given n = 3, a solution set is:
-#
+#
# "((()))", "(()())", "(())()", "()(())", "()()()"
#
@@ -16,7 +16,7 @@ def generateParenthesis(self, n):
result = []
self.generateParenthesisRecu(result, "", n, n)
return result
-
+
def generateParenthesisRecu(self, result, current, left, right):
if left == 0 and right == 0:
result.append(current)
diff --git a/Python/global-and-local-inversions.py b/Python/global-and-local-inversions.py
index 2ee8525b0..2c7e22024 100644
--- a/Python/global-and-local-inversions.py
+++ b/Python/global-and-local-inversions.py
@@ -30,4 +30,4 @@ def isIdealPermutation(self, A):
:rtype: bool
"""
return all(abs(v-i) <= 1 for i,v in enumerate(A))
-
+
diff --git a/Python/gray-code.py b/Python/gray-code.py
index 415e0f752..f54b9b421 100644
--- a/Python/gray-code.py
+++ b/Python/gray-code.py
@@ -2,22 +2,22 @@
# Space: O(1)
# The gray code is a binary numeral system where two successive values differ in only one bit.
-#
-# Given a non-negative integer n representing the total number of bits in the code,
+#
+# Given a non-negative integer n representing the total number of bits in the code,
# print the sequence of gray code. A gray code sequence must begin with 0.
-#
+#
# For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
-#
+#
# 00 - 0
# 01 - 1
# 11 - 3
# 10 - 2
# Note:
# For a given n, a gray code sequence is not uniquely defined.
-#
+#
# For example, [0,2,3,1] is also a valid gray code sequence according
# to the above definition.
-#
+#
# For now, the judge is able to judge based on one instance of gray code
# sequence. Sorry about that.
diff --git a/Python/guess-number-higher-or-lower-ii.py b/Python/guess-number-higher-or-lower-ii.py
index 48e7139a8..9de4bf3bc 100644
--- a/Python/guess-number-higher-or-lower-ii.py
+++ b/Python/guess-number-higher-or-lower-ii.py
@@ -26,7 +26,7 @@
# Hint:
#
# The best strategy to play the game is to minimize the maximum loss
-# you could possibly face. Another strategy is to minimize the expected loss.
+# you could possibly face. Another strategy is to minimize the expected loss.
# Here, we are interested in the first scenario.
# Take a small example (n = 3). What do you end up paying in the worst case?
# Check out this article if you're still stuck.
diff --git a/Python/h-index.py b/Python/h-index.py
index 4ad07afdb..ab47ad881 100644
--- a/Python/h-index.py
+++ b/Python/h-index.py
@@ -4,15 +4,15 @@
# Given an array of citations (each citation is a non-negative integer)
# of a researcher, write a function to compute the researcher's h-index.
#
-# According to the definition of h-index on Wikipedia:
+# According to the definition of h-index on Wikipedia:
# "A scientist has index h if h of his/her N papers have
# at least h citations each, and the other N − h papers have
# no more than h citations each."
#
-# For example, given citations = [3, 0, 6, 1, 5],
+# For example, given citations = [3, 0, 6, 1, 5],
# which means the researcher has 5 papers in total
-# and each of them had received 3, 0, 6, 1, 5 citations respectively.
-# Since the researcher has 3 papers with at least 3 citations each and
+# and each of them had received 3, 0, 6, 1, 5 citations respectively.
+# Since the researcher has 3 papers with at least 3 citations each and
# the remaining two with no more than 3 citations each, his h-index is 3.
#
# Note: If there are several possible values for h, the maximum one is taken as the h-index.
@@ -57,7 +57,7 @@ def hIndex(self, citations):
else:
break
return h
-
+
# Time: O(nlogn)
# Space: O(n)
class Solution3(object):
@@ -67,4 +67,4 @@ def hIndex(self, citations):
:rtype: int
"""
return sum(x >= i + 1 for i, x in enumerate(sorted(citations, reverse=True)))
-
+
diff --git a/Python/happy-number.py b/Python/happy-number.py
index 7ea4a5675..588f655e5 100644
--- a/Python/happy-number.py
+++ b/Python/happy-number.py
@@ -3,11 +3,11 @@
#
# Write an algorithm to determine if a number is "happy".
#
-# A happy number is a number defined by the following process:
-# Starting with any positive integer, replace the number by the sum
-# of the squares of its digits, and repeat the process until
-# the number equals 1 (where it will stay), or it loops endlessly
-# in a cycle which does not include 1. Those numbers for which
+# A happy number is a number defined by the following process:
+# Starting with any positive integer, replace the number by the sum
+# of the squares of its digits, and repeat the process until
+# the number equals 1 (where it will stay), or it loops endlessly
+# in a cycle which does not include 1. Those numbers for which
# this process ends in 1 are happy numbers.
#
# Example: 19 is a happy number
@@ -26,7 +26,7 @@ def isHappy(self, n):
lookup[n] = True
n = self.nextNumber(n)
return n == 1
-
+
def nextNumber(self, n):
new = 0
for char in str(n):
diff --git a/Python/house-robber-ii.py b/Python/house-robber-ii.py
index 554ed4828..5f1b2fbff 100644
--- a/Python/house-robber-ii.py
+++ b/Python/house-robber-ii.py
@@ -3,13 +3,13 @@
#
# Note: This is an extension of House Robber.
#
-# After robbing those houses on that street, the thief has found himself a new place
-# for his thievery so that he will not get too much attention. This time, all houses
-# at this place are arranged in a circle. That means the first house is the neighbor
-# of the last one. Meanwhile, the security system for these houses remain the same as
+# After robbing those houses on that street, the thief has found himself a new place
+# for his thievery so that he will not get too much attention. This time, all houses
+# at this place are arranged in a circle. That means the first house is the neighbor
+# of the last one. Meanwhile, the security system for these houses remain the same as
# for those in the previous street.
#
-# Given a list of non-negative integers representing the amount of money of each house,
+# Given a list of non-negative integers representing the amount of money of each house,
# determine the maximum amount of money you can rob tonight without alerting the police.
#
class Solution:
@@ -18,19 +18,19 @@ class Solution:
def rob(self, nums):
if len(nums) == 0:
return 0
-
+
if len(nums) == 1:
return nums[0]
-
+
return max(self.robRange(nums, 0, len(nums) - 1),\
self.robRange(nums, 1, len(nums)))
-
+
def robRange(self, nums, start, end):
num_i, num_i_1 = nums[start], 0
for i in xrange(start + 1, end):
num_i_1, num_i_2 = num_i, num_i_1
num_i = max(nums[i] + num_i_2, num_i_1);
-
+
return num_i
if __name__ == '__main__':
diff --git a/Python/house-robber-iii.py b/Python/house-robber-iii.py
index 06d4ea317..a1ed8c3a1 100644
--- a/Python/house-robber-iii.py
+++ b/Python/house-robber-iii.py
@@ -2,11 +2,11 @@
# Space: O(h)
# The thief has found himself a new place for his thievery again.
-# There is only one entrance to this area, called the "root."
+# 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
+# police if two directly-linked houses were broken into on the
# same night.
#
# Determine the maximum amount of money the thief can rob tonight
@@ -16,14 +16,14 @@
# 3
# / \
# 2 3
-# \ \
+# \ \
# 3 1
# Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.
# Example 2:
# 3
# / \
# 4 5
-# / \ \
+# / \ \
# 1 3 1
# Maximum amount of money the thief can rob = 4 + 5 = 9.
#
@@ -45,5 +45,5 @@ def robHelper(root):
return (0, 0)
left, right = robHelper(root.left), robHelper(root.right)
return (root.val + left[1] + right[1], max(left) + max(right))
-
+
return max(robHelper(root))
diff --git a/Python/house-robber.py b/Python/house-robber.py
index 3efd6e8a0..d94ae3b53 100644
--- a/Python/house-robber.py
+++ b/Python/house-robber.py
@@ -1,12 +1,12 @@
# Time: O(n)
# Space: O(1)
#
-# You are a professional robber planning to rob houses along a street.
-# Each house has a certain amount of money stashed, the only constraint stopping you
+# You are a professional robber planning to rob houses along a street.
+# Each house has a certain amount of money stashed, the only constraint stopping you
# from robbing each of them is that adjacent houses have 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 representing the amount of money of each house,
+# Given a list of non-negative integers representing the amount of money of each house,
# determine the maximum amount of money you can rob tonight without alerting the police.
#
class Solution:
@@ -15,15 +15,15 @@ class Solution:
def rob(self, num):
if len(num) == 0:
return 0
-
+
if len(num) == 1:
return num[0]
-
+
num_i, num_i_1 = max(num[1], num[0]), num[0]
for i in xrange(2, len(num)):
num_i_1, num_i_2 = num_i, num_i_1
num_i = max(num[i] + num_i_2, num_i_1);
-
+
return num_i
def rob2(self, nums):
diff --git a/Python/image-smoother.py b/Python/image-smoother.py
index 232662103..cd51b2fbc 100644
--- a/Python/image-smoother.py
+++ b/Python/image-smoother.py
@@ -22,7 +22,7 @@
# Note:
# The value in the given matrix is in the range of [0, 255].
# The length and width of the given matrix are in the range of [1, 150].
-
+
class Solution(object):
def imageSmoother(self, M):
"""
diff --git a/Python/implement-queue-using-stacks.py b/Python/implement-queue-using-stacks.py
index 02b3e4860..9c32c8197 100644
--- a/Python/implement-queue-using-stacks.py
+++ b/Python/implement-queue-using-stacks.py
@@ -32,14 +32,14 @@ def push(self, x):
def pop(self):
self.peek()
return self.B.pop()
-
+
# @return an integer
def peek(self):
if not self.B:
while self.A:
self.B.append(self.A.pop())
return self.B[-1]
-
+
# @return an boolean
def empty(self):
return not self.A and not self.B
diff --git a/Python/implement-strstr.py b/Python/implement-strstr.py
index a592a3654..1e7a5919a 100644
--- a/Python/implement-strstr.py
+++ b/Python/implement-strstr.py
@@ -2,7 +2,7 @@
# Space: O(k)
#
# Implement strStr().
-#
+#
# Returns a pointer to the first occurrence of needle in haystack,
# or null if needle is not part of haystack.
#
@@ -18,9 +18,9 @@ def strStr(self, haystack, needle):
"""
if not needle:
return 0
-
+
return self.KMP(haystack, needle)
-
+
def KMP(self, text, pattern):
prefix = self.getPrefix(pattern)
j = -1
@@ -32,7 +32,7 @@ def KMP(self, text, pattern):
if j == len(pattern) - 1:
return i - j
return -1
-
+
def getPrefix(self, pattern):
prefix = [-1] * len(pattern)
j = -1
@@ -44,7 +44,7 @@ def getPrefix(self, pattern):
prefix[i] = j
return prefix
-
+
# Time: O(n * k)
# Space: O(k)
class Solution2(object):
diff --git a/Python/implement-trie-prefix-tree.py b/Python/implement-trie-prefix-tree.py
index 0301555ad..a062f91ba 100644
--- a/Python/implement-trie-prefix-tree.py
+++ b/Python/implement-trie-prefix-tree.py
@@ -12,7 +12,7 @@ class TrieNode:
def __init__(self):
self.is_string = False
self.leaves = {}
-
+
class Trie:
@@ -37,7 +37,7 @@ def search(self, word):
node = self.childSearch(word)
if node:
return node.is_string
- return False
+ return False
# @param {string} prefix
# @return {boolean}
diff --git a/Python/increasing-subsequences.py b/Python/increasing-subsequences.py
index e246be299..6639959bc 100644
--- a/Python/increasing-subsequences.py
+++ b/Python/increasing-subsequences.py
@@ -1,8 +1,8 @@
# Time: O(n * 2^n)
# Space: O(n^2)
-# Given an integer array, your task is
-# to find all the different possible increasing
+# Given an integer array, your task is
+# to find all the different possible increasing
# subsequences of the given array,
# and the length of an increasing subsequence should be at least 2 .
#
diff --git a/Python/insert-delete-getrandom-o1-duplicates-allowed.py b/Python/insert-delete-getrandom-o1-duplicates-allowed.py
index 3aa6ab1a7..f0dbf9c63 100644
--- a/Python/insert-delete-getrandom-o1-duplicates-allowed.py
+++ b/Python/insert-delete-getrandom-o1-duplicates-allowed.py
@@ -43,7 +43,7 @@ def __init__(self):
"""
self.__list = []
self.__used = defaultdict(list)
-
+
def insert(self, val):
"""
diff --git a/Python/insert-delete-getrandom-o1.py b/Python/insert-delete-getrandom-o1.py
index 136636091..9ae83a0be 100644
--- a/Python/insert-delete-getrandom-o1.py
+++ b/Python/insert-delete-getrandom-o1.py
@@ -45,7 +45,7 @@ def __init__(self):
"""
self.__set = []
self.__used = {}
-
+
def insert(self, val):
"""
@@ -60,7 +60,7 @@ def insert(self, val):
self.__used[val] = len(self.__set)-1
return True
-
+
def remove(self, val):
"""
diff --git a/Python/insert-interval.py b/Python/insert-interval.py
index 16cf7c0a7..33dd83cec 100644
--- a/Python/insert-interval.py
+++ b/Python/insert-interval.py
@@ -4,13 +4,13 @@
# Given a set of non-overlapping intervals, insert a new interval into the
# intervals (merge if necessary).
# You may assume that the intervals were initially sorted according to their start times.
-#
+#
# Example 1:
# Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
-#
+#
# Example 2:
# Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
-#
+#
# This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
# Definition for an interval.
@@ -18,7 +18,7 @@ class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
-
+
def __repr__(self):
return "[{}, {}]".format(self.start, self.end)
diff --git a/Python/insertion-sort-list.py b/Python/insertion-sort-list.py
index fa7c9616c..30a8a7500 100644
--- a/Python/insertion-sort-list.py
+++ b/Python/insertion-sort-list.py
@@ -9,7 +9,7 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
@@ -22,7 +22,7 @@ class Solution:
def insertionSortList(self, head):
if head is None or self.isSorted(head):
return head
-
+
dummy = ListNode(-2147483648)
dummy.next = head
cur, sorted_tail = head.next, head
@@ -31,13 +31,13 @@ def insertionSortList(self, head):
while prev.next.val < cur.val:
prev = prev.next
if prev == sorted_tail:
- cur, sorted_tail = cur.next, cur
+ cur, sorted_tail = cur.next, cur
else:
cur.next, prev.next, sorted_tail.next = prev.next, cur, cur.next
cur = sorted_tail.next
-
+
return dummy.next
-
+
def isSorted(self, head):
while head and head.next:
if head.val > head.next.val:
diff --git a/Python/integer-break.py b/Python/integer-break.py
index c2127f3e9..ca3bab0e5 100644
--- a/Python/integer-break.py
+++ b/Python/integer-break.py
@@ -31,15 +31,15 @@ def integerBreak(self, n):
# ai <= 2 * (ai - 2)
# - For each aj >= 5, we can always maximize the product by:
# aj <= 3 * (aj - 3)
- #
+ #
# Conclusion 1:
# - For n >= 4, the max of the product must be in the form of
# 3^a * 2^b, s.t. 3a + 2b = n
- #
+ #
# 2. To maximize the product = 3^a * 2^b s.t. 3a + 2b = n
# - For each b >= 3, we can always maximize the product by:
# 3^a * 2^b <= 3^(a+2) * 2^(b-3) s.t. 3(a+2) + 2(b-3) = n
- #
+ #
# Conclusion 2:
# - For n >= 4, the max of the product must be in the form of
# 3^Q * 2^R, 0 <= R < 3 s.t. 3Q + 2R = n
diff --git a/Python/integer-replacement.py b/Python/integer-replacement.py
index 8ec74bf04..4820bf85a 100644
--- a/Python/integer-replacement.py
+++ b/Python/integer-replacement.py
@@ -49,9 +49,9 @@ def integerReplacement(self, n):
else:
n /= 2
result += 1
-
+
return result
-
+
# Time: O(logn)
# Space: O(logn)
@@ -70,4 +70,4 @@ def integerReplacement(self, n):
return self.integerReplacement((n - 1) / 4) + 3
else:
return self.integerReplacement((n + 1) / 4) + 3
-
+
diff --git a/Python/integer-to-english-words.py b/Python/integer-to-english-words.py
index 3c5ab64db..6097cf02f 100644
--- a/Python/integer-to-english-words.py
+++ b/Python/integer-to-english-words.py
@@ -57,7 +57,7 @@ def threeDigits(self, num, lookup, unit):
if unit != "":
res.append(unit)
return " ".join(res)
-
+
def twoDigits(self, num, lookup):
if num in lookup:
return lookup[num]
diff --git a/Python/integer-to-roman.py b/Python/integer-to-roman.py
index eed075b1b..672201a80 100644
--- a/Python/integer-to-roman.py
+++ b/Python/integer-to-roman.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given an integer, convert it to a roman numeral.
-#
+#
# Input is guaranteed to be within the range from 1 to 3999.
#
@@ -17,16 +17,16 @@ def intToRoman(self, num):
100: "C", 400: "CD", 500: "D", 900: "CM", \
1000: "M"}
keyset, result = sorted(numeral_map.keys()), []
-
+
while num > 0:
for key in reversed(keyset):
while num / key > 0:
num -= key
result += numeral_map[key]
-
+
return "".join(result)
-
+
if __name__ == "__main__":
print Solution().intToRoman(999)
print Solution().intToRoman(3999)
diff --git a/Python/interleaving-string.py b/Python/interleaving-string.py
index fd92f6141..8e0ff98c6 100644
--- a/Python/interleaving-string.py
+++ b/Python/interleaving-string.py
@@ -2,16 +2,16 @@
# Space: O(m + n)
#
# Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
-#
+#
# For example,
# Given:
# s1 = "aabcc",
# s2 = "dbbca",
-#
+#
# When s3 = "aadbbcbcac", return true.
# When s3 = "aadbbbaccc", return false.
#
-
+
# Time: O(m * n)
# Space: O(m + n)
# Dynamic Programming + Sliding Window
@@ -55,7 +55,7 @@ def isInterleave(self, s1, s2, s3):
# Time: O(m * n)
# Space: O(m * n)
-# Recursive + Hash
+# Recursive + Hash
class Solution3:
# @return a boolean
def isInterleave(self, s1, s2, s3):
@@ -63,22 +63,22 @@ def isInterleave(self, s1, s2, s3):
if len(s1) + len(s2) != len(s3):
return False
return self.isInterleaveRecu(s1, s2, s3, 0, 0, 0)
-
+
def isInterleaveRecu(self, s1, s2, s3, a, b, c):
if repr([a, b]) in self.match.keys():
return self.match[repr([a, b])]
-
+
if c == len(s3):
return True
-
+
result = False
if a < len(s1) and s1[a] == s3[c]:
result = result or self.isInterleaveRecu(s1, s2, s3, a + 1, b, c + 1)
if b < len(s2) and s2[b] == s3[c]:
result = result or self.isInterleaveRecu(s1, s2, s3, a, b + 1, c + 1)
-
- self.match[repr([a, b])] = result
-
+
+ self.match[repr([a, b])] = result
+
return result
if __name__ == "__main__":
diff --git a/Python/intersection-of-two-arrays-ii.py b/Python/intersection-of-two-arrays-ii.py
index 9e3f626c6..df7776dca 100644
--- a/Python/intersection-of-two-arrays-ii.py
+++ b/Python/intersection-of-two-arrays-ii.py
@@ -44,7 +44,7 @@ def intersect(self, nums1, nums2):
"""
if len(nums1) > len(nums2):
return self.intersect(nums2, nums1)
-
+
lookup = collections.defaultdict(int)
for i in nums1:
lookup[i] += 1
@@ -102,7 +102,7 @@ def binary_search(compare, nums, left, right, target):
if left != len(nums2) and nums2[left] == i:
res += i,
left += 1
-
+
return res
@@ -120,7 +120,7 @@ def intersect(self, nums1, nums2):
nums1.sort(), nums2.sort() # Make sure it is sorted, doesn't count in time.
res = []
-
+
it1, it2 = 0, 0
while it1 < len(nums1) and it2 < len(nums2):
if nums1[it1] < nums2[it2]:
@@ -131,7 +131,7 @@ def intersect(self, nums1, nums2):
res += nums1[it1],
it1 += 1
it2 += 1
-
+
return res
@@ -149,7 +149,7 @@ def intersect(self, nums1, nums2):
nums1.sort(), nums2.sort() # O(max(m, n) * log(max(m, n)))
res = []
-
+
it1, it2 = 0, 0
while it1 < len(nums1) and it2 < len(nums2):
if nums1[it1] < nums2[it2]:
@@ -160,5 +160,5 @@ def intersect(self, nums1, nums2):
res += nums1[it1],
it1 += 1
it2 += 1
-
+
return res
diff --git a/Python/intersection-of-two-arrays.py b/Python/intersection-of-two-arrays.py
index e04ff0c40..fb90f68eb 100644
--- a/Python/intersection-of-two-arrays.py
+++ b/Python/intersection-of-two-arrays.py
@@ -22,7 +22,7 @@ def intersection(self, nums1, nums2):
"""
if len(nums1) > len(nums2):
return self.intersection(nums2, nums1)
-
+
lookup = set()
for i in nums1:
lookup.add(i)
@@ -75,7 +75,7 @@ def binary_search(compare, nums, left, right, target):
if left != len(nums2) and nums2[left] == i:
res += i,
left = binary_search(lambda x, y: x > y, nums2, left, len(nums2), i)
-
+
return res
@@ -91,7 +91,7 @@ def intersection(self, nums1, nums2):
"""
nums1.sort(), nums2.sort()
res = []
-
+
it1, it2 = 0, 0
while it1 < len(nums1) and it2 < len(nums2):
if nums1[it1] < nums2[it2]:
@@ -103,5 +103,5 @@ def intersection(self, nums1, nums2):
res += nums1[it1],
it1 += 1
it2 += 1
-
+
return res
diff --git a/Python/intersection-of-two-linked-lists.py b/Python/intersection-of-two-linked-lists.py
index 328df54fb..3d18b7918 100644
--- a/Python/intersection-of-two-linked-lists.py
+++ b/Python/intersection-of-two-linked-lists.py
@@ -2,20 +2,20 @@
# Space: O(1)
#
# Write a program to find the node at which the intersection of two singly linked lists begins.
-#
-#
+#
+#
# For example, the following two linked lists:
-#
+#
# A: a1 - a2
# \
# c1 - c2 - c3
-# /
+# /
# B: b1 - b2 - b3
# begin to intersect at node c1.
-#
-#
+#
+#
# Notes:
-#
+#
# If the two linked lists have no intersection at all, return null.
# The linked lists must retain their original structure after the function returns.
# You may assume there are no cycles anywhere in the entire linked structure.
@@ -34,14 +34,14 @@ class Solution:
def getIntersectionNode(self, headA, headB):
curA, curB = headA, headB
begin, tailA, tailB = None, None, None
-
+
# a->c->b->c
# b->c->a->c
while curA and curB:
if curA == curB:
begin = curA
break
-
+
if curA.next:
curA = curA.next
elif tailA is None:
@@ -49,7 +49,7 @@ def getIntersectionNode(self, headA, headB):
curA = headB
else:
break
-
+
if curB.next:
curB = curB.next
elif tailB is None:
@@ -57,5 +57,5 @@ def getIntersectionNode(self, headA, headB):
curB = headA
else:
break
-
+
return begin
diff --git a/Python/ip-to-cidr.py b/Python/ip-to-cidr.py
index 3c4bb3b6f..fe9a17788 100644
--- a/Python/ip-to-cidr.py
+++ b/Python/ip-to-cidr.py
@@ -39,7 +39,7 @@
# but our answer was the shortest possible.
#
# Also note that a representation beginning with say, "255.0.0.7/30" would be incorrect,
-# because it includes addresses like 255.0.0.4 = 11111111 00000000 00000000 00000100
+# because it includes addresses like 255.0.0.4 = 11111111 00000000 00000000 00000100
# that are outside the specified range.
# Note:
# - ip will be a valid IPv4 address.
diff --git a/Python/is-graph-bipartite.py b/Python/is-graph-bipartite.py
index 213d8e372..5b9890e91 100644
--- a/Python/is-graph-bipartite.py
+++ b/Python/is-graph-bipartite.py
@@ -8,7 +8,7 @@
# one node in A and another node in B.
#
# The graph is given in the following form: graph[i] is a list of indexes j
-# for which the edge between nodes i and j exists.
+# for which the edge between nodes i and j exists.
# Each node is an integer between 0 and graph.length - 1.
# There are no self edges or parallel edges: graph[i] does not contain i,
# and it doesn't contain any element twice.
@@ -16,18 +16,18 @@
# Example 1:
# Input: [[1,3], [0,2], [1,3], [0,2]]
# Output: true
-# Explanation:
+# Explanation:
# The graph looks like this:
# 0----1
# | |
# | |
# 3----2
# We can divide the vertices into two groups: {0, 2} and {1, 3}.
-#
+#
# Example 2:
# Input: [[1,2,3], [0,2], [0,1,3], [0,2]]
# Output: false
-# Explanation:
+# Explanation:
# The graph looks like this:
# 0----1
# | \ |
diff --git a/Python/is-subsequence.py b/Python/is-subsequence.py
index e92eceef0..a47504b7d 100644
--- a/Python/is-subsequence.py
+++ b/Python/is-subsequence.py
@@ -6,7 +6,7 @@
# You may assume that there is only lower case English letters in both s and t.
# t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).
#
-# A subsequence of a string is a new string which is formed from
+# A subsequence of a string is a new string which is formed from
# the original string by deleting some (can be none) of the characters
# without disturbing the relative positions of the remaining characters.
# (ie, "ace" is a subsequence of "abcde" while "aec" is not).
diff --git a/Python/isomorphic-strings.py b/Python/isomorphic-strings.py
index e22243e67..4268ab641 100644
--- a/Python/isomorphic-strings.py
+++ b/Python/isomorphic-strings.py
@@ -5,8 +5,8 @@
#
# Two strings are isomorphic if the characters in s can be replaced to get t.
#
-# All occurrences of a character must be replaced with another character
-# while preserving the order of characters. No two characters may map to
+# All occurrences of a character must be replaced with another character
+# while preserving the order of characters. No two characters may map to
# the same character but a character may map to itself.
#
# For example,
@@ -35,7 +35,7 @@ def isIsomorphic(self, s, t):
for p, w in izip(s, t):
if w not in s2t and p not in t2s:
s2t[w] = p
- t2s[p] = w
+ t2s[p] = w
elif w not in s2t or s2t[w] != p:
# Contradict mapping.
return False
@@ -48,7 +48,7 @@ class Solution2(object):
def isIsomorphic(self, s, t):
if len(s) != len(t):
return False
-
+
return self.halfIsom(s, t) and self.halfIsom(t, s)
def halfIsom(self, s, t):
diff --git a/Python/jewels-and-stones.py b/Python/jewels-and-stones.py
index 18fbbd812..61fa6936d 100644
--- a/Python/jewels-and-stones.py
+++ b/Python/jewels-and-stones.py
@@ -30,4 +30,4 @@ def numJewelsInStones(self, J, S):
"""
lookup = set(J)
return sum(s in lookup for s in S)
-
+
diff --git a/Python/judge-route-circle.py b/Python/judge-route-circle.py
index 79cfe6d5d..8aafd1fee 100644
--- a/Python/judge-route-circle.py
+++ b/Python/judge-route-circle.py
@@ -14,7 +14,7 @@
# Example 2:
# Input: "LL"
# Output: false
-
+
class Solution(object):
def judgeCircle(self, moves):
"""
diff --git a/Python/jump-game-ii.py b/Python/jump-game-ii.py
index 571c405d4..d99f97642 100644
--- a/Python/jump-game-ii.py
+++ b/Python/jump-game-ii.py
@@ -2,14 +2,14 @@
# Space: O(1)
#
# Given an array of non-negative integers, you are initially positioned at the first index of the array.
-#
+#
# Each element in the array represents your maximum jump length at that position.
-#
+#
# Your goal is to reach the last index in the minimum number of jumps.
-#
+#
# For example:
# Given array A = [2,3,1,1,4]
-#
+#
# The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
#
@@ -29,8 +29,8 @@ def jump(self, A):
jump_count += 1
reachable = max(reachable, i + length)
return jump_count
-
-
+
+
if __name__ == "__main__":
print Solution().jump([2,3,1,1,4])
print Solution().jump([3,2,1,0,4])
diff --git a/Python/jump-game.py b/Python/jump-game.py
index f3e18cce6..de25a28b3 100644
--- a/Python/jump-game.py
+++ b/Python/jump-game.py
@@ -2,14 +2,14 @@
# Space: O(1)
#
# Given an array of non-negative integers, you are initially positioned at the first index of the array.
-#
+#
# Each element in the array represents your maximum jump length at that position.
-#
+#
# Determine if you are able to reach the last index.
-#
+#
# For example:
# A = [2,3,1,1,4], return true.
-#
+#
# A = [3,2,1,0,4], return false.
class Solution:
@@ -22,7 +22,7 @@ def canJump(self, A):
break
reachable = max(reachable, i + length)
return reachable >= len(A) - 1
-
+
if __name__ == "__main__":
print Solution().canJump([2,3,1,1,4])
print Solution().canJump([3,2,1,0,4])
\ No newline at end of file
diff --git a/Python/k-diff-pairs-in-an-array.py b/Python/k-diff-pairs-in-an-array.py
index 58a4b29b5..9331f8a74 100644
--- a/Python/k-diff-pairs-in-an-array.py
+++ b/Python/k-diff-pairs-in-an-array.py
@@ -5,7 +5,7 @@
# Total Submissions: 20941
# Difficulty: Easy
# Contributors: murali.kf370
-# Given an array of integers and an integer k,
+# Given an array of integers and an integer k,
# you need to find the number of unique k-diff pairs in the array.
# Here a k-diff pair is defined as an integer pair (i, j),
# where i and j are both numbers in the array and their absolute difference is k.
diff --git a/Python/k-empty-slots.py b/Python/k-empty-slots.py
index ca99f58b1..c87e9005a 100644
--- a/Python/k-empty-slots.py
+++ b/Python/k-empty-slots.py
@@ -18,14 +18,14 @@
# If there isn't such day, output -1.
#
# Example 1:
-# Input:
+# Input:
# flowers: [1,3,2]
# k: 1
# Output: 2
# Explanation: In the second day, the first and the third flower have become blooming.
#
# Example 2:
-# Input:
+# Input:
# flowers: [1,2,3]
# k: 1
# Output: -1
@@ -45,10 +45,10 @@ def kEmptySlots(self, flowers, k):
result = float("inf")
i, left, right = 0, 0, k+1
while right < len(days):
- if days[i] < days[left] or days[i] <= days[right]:
+ if days[i] < days[left] or days[i] <= days[right]:
if i == right:
result = min(result, max(days[left], days[right]))
left, right = i, k+1+i;
i += 1
return -1 if result == float("inf") else result+1
-
+
diff --git a/Python/k-inverse-pairs-array.py b/Python/k-inverse-pairs-array.py
index da1e592dd..1845a3c44 100644
--- a/Python/k-inverse-pairs-array.py
+++ b/Python/k-inverse-pairs-array.py
@@ -12,12 +12,12 @@
# Example 1:
# Input: n = 3, k = 0
# Output: 1
-# Explanation:
+# Explanation:
# Only the array [1,2,3] which consists of numbers from 1 to 3 has exactly 0 inverse pair.
# Example 2:
# Input: n = 3, k = 1
# Output: 2
-# Explanation:
+# Explanation:
# The array [1,3,2] and [2,1,3] have exactly 1 inverse pair.
# Note:
# The integer n is in the range [1, 1000] and k is in the range [0, 1000].
diff --git a/Python/k-th-smallest-in-lexicographical-order.py b/Python/k-th-smallest-in-lexicographical-order.py
index 4a969c6d5..8a15760be 100644
--- a/Python/k-th-smallest-in-lexicographical-order.py
+++ b/Python/k-th-smallest-in-lexicographical-order.py
@@ -78,7 +78,7 @@ def count(n, prefix):
number *= 10
result -= max(number/10 - (n - prefix/10 + 1), 0)
return result
-
+
def findKthNumberHelper(n, k, cur, index):
if cur:
index += 1
@@ -98,5 +98,5 @@ def findKthNumberHelper(n, k, cur, index):
i += 1
cur /= 10
return (0, index)
-
+
return findKthNumberHelper(n, k, 0, 0)[0]
diff --git a/Python/k-th-symbol-in-grammar.py b/Python/k-th-symbol-in-grammar.py
index dbed8a5f6..8980720a1 100644
--- a/Python/k-th-symbol-in-grammar.py
+++ b/Python/k-th-symbol-in-grammar.py
@@ -45,5 +45,5 @@ def bitCount(n):
n &= n - 1
result += 1
return result
-
+
return bitCount(K-1) % 2
diff --git a/Python/keyboard-row.py b/Python/keyboard-row.py
index 9291dcf63..ef825d00c 100644
--- a/Python/keyboard-row.py
+++ b/Python/keyboard-row.py
@@ -18,7 +18,7 @@ def findWords(self, words):
:rtype: List[str]
"""
rows = [set(['q', 'w', 'e', 'r', 't', 'y','u', 'i', 'o', 'p']),
- set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']),
+ set(['a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l']),
set(['z', 'x', 'c', 'v', 'b' ,'n', 'm'])]
result = []
diff --git a/Python/knight-probability-in-chessboard.py b/Python/knight-probability-in-chessboard.py
index cb87d07ed..2f493ca96 100644
--- a/Python/knight-probability-in-chessboard.py
+++ b/Python/knight-probability-in-chessboard.py
@@ -1,6 +1,6 @@
# Time: O(k * n^2)
# Space: O(n^2)
-
+
# On an NxN chessboard, a knight starts at the r-th row and c-th column and
# attempts to make exactly K moves. The rows and columns are 0 indexed,
# so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1).
@@ -17,7 +17,7 @@
# Example:
# Input: 3, 2, 0, 0
# Output: 0.0625
-#
+#
# Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board.
# From each of those positions, there are also two moves that will keep the knight on the board.
# The total probability the knight stays on the board is 0.0625.
diff --git a/Python/kth-largest-element-in-an-array.py b/Python/kth-largest-element-in-an-array.py
index 08dd0b788..55e1af2a9 100644
--- a/Python/kth-largest-element-in-an-array.py
+++ b/Python/kth-largest-element-in-an-array.py
@@ -18,7 +18,7 @@ def findKthLargest(self, nums, k):
right = new_pivot_idx - 1
else: # new_pivot_idx < k - 1.
left = new_pivot_idx + 1
-
+
def PartitionAroundPivot(self, left, right, pivot_idx, nums):
pivot_value = nums[pivot_idx]
new_pivot_idx = left
@@ -27,7 +27,7 @@ def PartitionAroundPivot(self, left, right, pivot_idx, nums):
if nums[i] > pivot_value:
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
-
+
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
-
+
diff --git a/Python/kth-smallest-element-in-a-bst.py b/Python/kth-smallest-element-in-a-bst.py
index ee7216094..89457f4e9 100644
--- a/Python/kth-smallest-element-in-a-bst.py
+++ b/Python/kth-smallest-element-in-a-bst.py
@@ -3,7 +3,7 @@
# Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
#
-# Note:
+# Note:
# You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
#
# Follow up:
diff --git a/Python/kth-smallest-element-in-a-sorted-matrix.py b/Python/kth-smallest-element-in-a-sorted-matrix.py
index be66a8b8f..1bf17df12 100644
--- a/Python/kth-smallest-element-in-a-sorted-matrix.py
+++ b/Python/kth-smallest-element-in-a-sorted-matrix.py
@@ -18,7 +18,7 @@
# k = 8,
#
# return 13.
-# Note:
+# Note:
# You may assume k is always valid, 1 <= k <= n^2.
from heapq import heappush, heappop
diff --git a/Python/kth-smallest-number-in-multiplication-table.py b/Python/kth-smallest-number-in-multiplication-table.py
index dc5ee176e..17c4225b8 100644
--- a/Python/kth-smallest-number-in-multiplication-table.py
+++ b/Python/kth-smallest-number-in-multiplication-table.py
@@ -9,8 +9,8 @@
#
# Example 1:
# Input: m = 3, n = 3, k = 5
-# Output:
-# Explanation:
+# Output:
+# Explanation:
# The Multiplication Table:
# 1 2 3
# 2 4 6
@@ -19,8 +19,8 @@
# The 5-th smallest number is 3 (1, 2, 2, 3, 3).
# Example 2:
# Input: m = 2, n = 3, k = 6
-# Output:
-# Explanation:
+# Output:
+# Explanation:
# The Multiplication Table:
# 1 2 3
# 2 4 6
diff --git a/Python/largest-bst-subtree.py b/Python/largest-bst-subtree.py
index 35d18f1be..78359e2bb 100644
--- a/Python/largest-bst-subtree.py
+++ b/Python/largest-bst-subtree.py
@@ -25,7 +25,7 @@ def largestBSTSubtreeHelper(root):
left_size, left_min, left_max = 0, root.val, root.val
if root.left is not None:
left_size, left_min, left_max = largestBSTSubtreeHelper(root.left)
-
+
right_size, right_min, right_max = 0, root.val, root.val
if root.right is not None:
right_size, right_min, right_max = largestBSTSubtreeHelper(root.right)
diff --git a/Python/largest-number.py b/Python/largest-number.py
index 8317a617b..008d5e0e7 100644
--- a/Python/largest-number.py
+++ b/Python/largest-number.py
@@ -2,9 +2,9 @@
# Space: O(1)
#
# Given a list of non negative integers, arrange them such that they form the largest number.
-#
+#
# For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
-#
+#
# Note: The result may be very large, so you need to return a string instead of an integer.
#
@@ -19,4 +19,4 @@ def largestNumber(self, num):
if __name__ == "__main__":
num = [3, 30, 34, 5, 9]
- print Solution().largestNumber(num)
+ print Solution().largestNumber(num)
diff --git a/Python/largest-palindrome-product.py b/Python/largest-palindrome-product.py
index c189a0011..66c4b3fee 100644
--- a/Python/largest-palindrome-product.py
+++ b/Python/largest-palindrome-product.py
@@ -20,7 +20,7 @@ def largestPalindrome(self, n):
"""
if n == 1:
return 9
-
+
upper, lower = 10**n-1, 10**(n-1)
for i in reversed(xrange(lower, upper+1)):
candidate = int(str(i) + str(i)[::-1])
diff --git a/Python/largest-plus-sign.py b/Python/largest-plus-sign.py
index 5b47e514b..3d068753c 100644
--- a/Python/largest-plus-sign.py
+++ b/Python/largest-plus-sign.py
@@ -20,7 +20,7 @@ def orderOfLargestPlusSign(self, N, mines):
for j in reversed(xrange(N)):
l = 0 if (i, j) in lookup else l+1
dp[i][j] = min(dp[i][j], l)
-
+
for j in xrange(N):
l = 0
for i in xrange(N):
diff --git a/Python/largest-rectangle-in-histogram.py b/Python/largest-rectangle-in-histogram.py
index e3dea568b..3e4d6fa82 100644
--- a/Python/largest-rectangle-in-histogram.py
+++ b/Python/largest-rectangle-in-histogram.py
@@ -1,10 +1,10 @@
# Time: O(n)
# Space: O(n)
#
-# Given n non-negative integers representing the histogram's bar
+# Given n non-negative integers representing the histogram's bar
# height where the width of each bar is 1,
# find the area of largest rectangle in the histogram.
-#
+#
# For example,
# Given height = [2,1,5,6,2,3],
# return 10.
@@ -30,4 +30,4 @@ def largestRectangleArea(self, height):
if __name__ == "__main__":
print Solution().largestRectangleArea([2, 0, 2])
print Solution().largestRectangleArea([2, 1, 5, 6, 2, 3])
-
+
diff --git a/Python/length-of-last-word.py b/Python/length-of-last-word.py
index 0e713d1a1..ec1c239e0 100644
--- a/Python/length-of-last-word.py
+++ b/Python/length-of-last-word.py
@@ -2,12 +2,12 @@
# Space: O(1)
#
# Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.
-#
+#
# If the last word does not exist, return 0.
-#
+#
# Note: A word is defined as a character sequence consists of non-space characters only.
-#
-# For example,
+#
+# For example,
# Given s = "Hello World",
# return 5.
#
diff --git a/Python/letter-combinations-of-a-phone-number.py b/Python/letter-combinations-of-a-phone-number.py
index c876137ca..ca3d1c347 100644
--- a/Python/letter-combinations-of-a-phone-number.py
+++ b/Python/letter-combinations-of-a-phone-number.py
@@ -2,11 +2,11 @@
# Space: O(n)
#
# Given a digit string, return all possible letter combinations that the number could represent.
-#
+#
# A mapping of digit to letters (just like on the telephone buttons) is given below.
-#
+#
# lookup = ["", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"]
-#
+#
# Input:Digit string "23"
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
# Note:
@@ -19,18 +19,18 @@ class Solution:
def letterCombinations(self, digits):
if not digits:
return []
-
+
lookup, result = ["", "", "abc", "def", "ghi", "jkl", "mno", \
"pqrs", "tuv", "wxyz"], [""]
for digit in reversed(digits):
choices = lookup[int(digit)]
m, n = len(choices), len(result)
- result += [result[i % n] for i in xrange(n, m * n)]
+ result += [result[i % n] for i in xrange(n, m * n)]
for i in xrange(m * n):
- result[i] = choices[i / n] + result[i]
-
+ result[i] = choices[i / n] + result[i]
+
return result
@@ -46,7 +46,7 @@ def letterCombinations(self, digits):
"pqrs", "tuv", "wxyz"], []
self.letterCombinationsRecu(result, digits, lookup, "", 0)
return result
-
+
def letterCombinationsRecu(self, result, digits, lookup, cur, n):
if n == len(digits):
result.append(cur)
diff --git a/Python/lexicographical-numbers.py b/Python/lexicographical-numbers.py
index 789aa4d51..20e3f896a 100644
--- a/Python/lexicographical-numbers.py
+++ b/Python/lexicographical-numbers.py
@@ -18,7 +18,7 @@ def lexicalOrder(self, n):
while i * 10**k <= n:
result.append(i * 10**k)
k += 1
-
+
num = result[-1] + 1
while num <= n and num % 10:
result.append(num)
@@ -31,7 +31,7 @@ def lexicalOrder(self, n):
while num % 10 == 9:
num /= 10
-
+
i = num+1
return result
diff --git a/Python/linked-list-cycle-ii.py b/Python/linked-list-cycle-ii.py
index 74ea144ca..281e465fc 100644
--- a/Python/linked-list-cycle-ii.py
+++ b/Python/linked-list-cycle-ii.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
-#
+#
# Follow up:
# Can you solve it without using extra space?
#
@@ -12,13 +12,13 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __str__(self):
if self:
return "{}".format(self.val)
else:
return None
-
+
class Solution:
# @param head, a ListNode
# @return a list node
diff --git a/Python/linked-list-cycle.py b/Python/linked-list-cycle.py
index b2288624d..6073a78be 100644
--- a/Python/linked-list-cycle.py
+++ b/Python/linked-list-cycle.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given a linked list, determine if it has a cycle in it.
-#
+#
# Follow up:
# Can you solve it without using extra space?
#
diff --git a/Python/linked-list-random-node.py b/Python/linked-list-random-node.py
index 1e6d7de0f..7ac0718fc 100644
--- a/Python/linked-list-random-node.py
+++ b/Python/linked-list-random-node.py
@@ -46,7 +46,7 @@ def getRandom(self):
reservoir = curr.val if randint(1, n+1) == 1 else reservoir
curr, n = curr.next, n+1
return reservoir
-
+
# Your Solution object will be instantiated and called as such:
# obj = Solution(head)
diff --git a/Python/longest-absolute-file-path.py b/Python/longest-absolute-file-path.py
index bc29abb10..065458aa2 100644
--- a/Python/longest-absolute-file-path.py
+++ b/Python/longest-absolute-file-path.py
@@ -28,7 +28,7 @@
# For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext",
# and its length is 32 (not including the double quotes).
#
-# Given a string representing the file system in the above format,
+# Given a string representing the file system in the above format,
# return the length of the longest absolute path to file in the abstracted file system.
# If there is no file in the system, return 0.
#
diff --git a/Python/longest-consecutive-sequence.py b/Python/longest-consecutive-sequence.py
index df70be6e9..240b109e0 100644
--- a/Python/longest-consecutive-sequence.py
+++ b/Python/longest-consecutive-sequence.py
@@ -2,11 +2,11 @@
# Space: O(n)
#
# Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
-#
+#
# For example,
# Given [100, 4, 200, 1, 3, 2],
# The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
-#
+#
# Your algorithm should run in O(n) complexity.
#
diff --git a/Python/longest-continuous-increasing-subsequence.py b/Python/longest-continuous-increasing-subsequence.py
index c374bbea3..9ae2635e1 100644
--- a/Python/longest-continuous-increasing-subsequence.py
+++ b/Python/longest-continuous-increasing-subsequence.py
@@ -7,13 +7,13 @@
# Example 1:
# Input: [1,3,5,4,7]
# Output: 3
-# Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
+# Explanation: The longest continuous increasing subsequence is [1,3,5], its length is 3.
# Even though [1,3,5,7] is also an increasing subsequence,
-# it's not a continuous one where 5 and 7 are separated by 4.
+# it's not a continuous one where 5 and 7 are separated by 4.
# Example 2:
# Input: [2,2,2,2,2]
# Output: 1
-# Explanation: The longest continuous increasing subsequence is [2], its length is 1.
+# Explanation: The longest continuous increasing subsequence is [2], its length is 1.
# Note: Length of the array will not exceed 10,000.
class Solution(object):
diff --git a/Python/longest-increasing-path-in-a-matrix.py b/Python/longest-increasing-path-in-a-matrix.py
index f5685d3a7..c95688f2e 100644
--- a/Python/longest-increasing-path-in-a-matrix.py
+++ b/Python/longest-increasing-path-in-a-matrix.py
@@ -3,8 +3,8 @@
# Given an integer matrix, find the length of the longest increasing path.
#
-# From each cell, you can either move to four directions: left, right, up
-# or down. You may NOT move diagonally or move outside of the boundary
+# From each cell, you can either move to four directions: left, right, up
+# or down. You may NOT move diagonally or move outside of the boundary
# (i.e. wrap-around is not allowed).
#
# Example 1:
@@ -40,7 +40,7 @@ def longestIncreasingPath(self, matrix):
def longestpath(matrix, i, j, max_lengths):
if max_lengths[i][j]:
return max_lengths[i][j]
-
+
max_depth = 0
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
for d in directions:
@@ -56,5 +56,5 @@ def longestpath(matrix, i, j, max_lengths):
for i in xrange(len(matrix)):
for j in xrange(len(matrix[0])):
res = max(res, longestpath(matrix, i, j, max_lengths))
-
+
return res
diff --git a/Python/longest-increasing-subsequence.py b/Python/longest-increasing-subsequence.py
index ac477873b..f176202be 100644
--- a/Python/longest-increasing-subsequence.py
+++ b/Python/longest-increasing-subsequence.py
@@ -1,7 +1,7 @@
# Time: O(nlogn)
# Space: O(n)
#
-# Given an unsorted array of integers,
+# Given an unsorted array of integers,
# find the length of longest increasing subsequence.
#
# For example,
diff --git a/Python/longest-palindromic-substring.py b/Python/longest-palindromic-substring.py
index 2c0f238d9..2621a208d 100644
--- a/Python/longest-palindromic-substring.py
+++ b/Python/longest-palindromic-substring.py
@@ -24,7 +24,7 @@ def preProcess(s):
return T
T = preProcess(s)
- P = [0] * len(T)
+ P = [0] * len(T)
center, right = 0, 0
for i in xrange(1, len(T) - 1):
i_mirror = 2 * center - i
@@ -37,8 +37,8 @@ def preProcess(s):
P[i] += 1
if i + P[i] > right:
- center, right = i, i + P[i]
-
+ center, right = i, i + P[i]
+
max_i = 0
for i in xrange(1, len(T) - 1):
if P[i] > P[max_i]:
@@ -46,6 +46,6 @@ def preProcess(s):
start = (max_i - 1 - P[max_i]) / 2
return s[start : start + P[max_i]]
-
+
if __name__ == "__main__":
print Solution().longestPalindrome("abb")
diff --git a/Python/longest-substring-with-at-most-k-distinct-characters.py b/Python/longest-substring-with-at-most-k-distinct-characters.py
index a5f6d0c45..fd974b83c 100644
--- a/Python/longest-substring-with-at-most-k-distinct-characters.py
+++ b/Python/longest-substring-with-at-most-k-distinct-characters.py
@@ -13,12 +13,12 @@ def lengthOfLongestSubstringKDistinct(self, s, k):
if visited[ord(char)] == 0:
distinct_count += 1
visited[ord(char)] += 1
-
+
while distinct_count > k:
visited[ord(s[start])] -= 1
if visited[ord(s[start])] == 0:
distinct_count -= 1
start += 1
-
+
longest = max(longest, i - start + 1)
return longest
diff --git a/Python/longest-substring-with-at-most-two-distinct-characters.py b/Python/longest-substring-with-at-most-two-distinct-characters.py
index 3a58b3024..0eb42603b 100644
--- a/Python/longest-substring-with-at-most-two-distinct-characters.py
+++ b/Python/longest-substring-with-at-most-two-distinct-characters.py
@@ -1,11 +1,11 @@
# Time: O(n)
# Space: O(1)
#
-# Given a string, find the length of the longest substring T
+# Given a string, find the length of the longest substring T
# that contains at most 2 distinct characters.
-#
+#
# For example, Given s = "eceba",
-#
+#
# T is "ece" which its length is 3.
#
@@ -18,15 +18,15 @@ def lengthOfLongestSubstringTwoDistinct(self, s):
if visited[ord(char)] == 0:
distinct_count += 1
visited[ord(char)] += 1
-
+
while distinct_count > 2:
visited[ord(s[start])] -= 1
if visited[ord(s[start])] == 0:
distinct_count -= 1
start += 1
-
+
longest = max(longest, i - start + 1)
return longest
-
+
if __name__ == "__main__":
print Solution().lengthOfLongestSubstringTwoDistinct("eceba")
diff --git a/Python/longest-substring-without-repeating-characters.py b/Python/longest-substring-without-repeating-characters.py
index c7f711c73..8208f643c 100644
--- a/Python/longest-substring-without-repeating-characters.py
+++ b/Python/longest-substring-without-repeating-characters.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given a string, find the length of the longest substring without repeating characters.
-# For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
+# For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3.
# For "bbbbb" the longest substring is "b", with the length of 1.
#
diff --git a/Python/longest-uncommon-subsequence-i.py b/Python/longest-uncommon-subsequence-i.py
index 007cee665..9d64937f1 100644
--- a/Python/longest-uncommon-subsequence-i.py
+++ b/Python/longest-uncommon-subsequence-i.py
@@ -15,9 +15,9 @@
# Example 1:
# Input: "aba", "cdc"
# Output: 3
-# Explanation: The longest uncommon subsequence is "aba" (or "cdc"),
-# because "aba" is a subsequence of "aba",
-# but not a subsequence of any other strings in the group of two strings.
+# Explanation: The longest uncommon subsequence is "aba" (or "cdc"),
+# because "aba" is a subsequence of "aba",
+# but not a subsequence of any other strings in the group of two strings.
# Note:
#
# Both strings' lengths will not exceed 100.
diff --git a/Python/longest-univalue-path.py b/Python/longest-univalue-path.py
index 795f4d485..d7fd3b9b9 100644
--- a/Python/longest-univalue-path.py
+++ b/Python/longest-univalue-path.py
@@ -52,6 +52,6 @@ def dfs(node):
right = (right+1) if node.right and node.right.val == node.val else 0
result[0] = max(result[0], left+right)
return max(left, right)
-
+
dfs(root)
return result[0]
diff --git a/Python/longest-valid-parentheses.py b/Python/longest-valid-parentheses.py
index dd0376eb8..3c8888175 100644
--- a/Python/longest-valid-parentheses.py
+++ b/Python/longest-valid-parentheses.py
@@ -1,11 +1,11 @@
# Time: O(n)
# Space: O(1)
#
-# Given a string containing just the characters '(' and ')',
+# Given a string containing just the characters '(' and ')',
# find the length of the longest valid (well-formed) parentheses substring.
-#
+#
# For "(()", the longest valid parentheses substring is "()", which has length = 2.
-#
+#
# Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
#
diff --git a/Python/longest-word-in-dictionary-through-deleting.py b/Python/longest-word-in-dictionary-through-deleting.py
index 7437ca338..548d3797c 100644
--- a/Python/longest-word-in-dictionary-through-deleting.py
+++ b/Python/longest-word-in-dictionary-through-deleting.py
@@ -12,13 +12,13 @@
# Input:
# s = "abpcplea", d = ["ale","apple","monkey","plea"]
#
-# Output:
+# Output:
# "apple"
# Example 2:
# Input:
# s = "abpcplea", d = ["a","b","c"]
#
-# Output:
+# Output:
# "a"
# Note:
# All the strings in the input will only contain lower-case letters.
diff --git a/Python/lru-cache.py b/Python/lru-cache.py
index 14cc5333d..9913918fc 100644
--- a/Python/lru-cache.py
+++ b/Python/lru-cache.py
@@ -37,7 +37,7 @@ class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
-
+
def insert(self, node):
node.next, node.prev = None, None # avoid dirty node
if self.head is None:
@@ -46,7 +46,7 @@ def insert(self, node):
self.tail.next = node
node.prev = self.tail
self.tail = node
-
+
def delete(self, node):
if node.prev:
node.prev.next = node.next
@@ -65,12 +65,12 @@ def __init__(self, capacity):
self.list = LinkedList()
self.dict = {}
self.capacity = capacity
-
+
def _insert(self, key, val):
node = ListNode(key, val)
self.list.insert(node)
self.dict[key] = node
-
+
# @return an integer
def get(self, key):
@@ -80,7 +80,7 @@ def get(self, key):
self._insert(key, val)
return val
return -1
-
+
# @param key, an integer
# @param value, an integer
@@ -92,8 +92,8 @@ def put(self, key, val):
del self.dict[self.list.head.key]
self.list.delete(self.list.head)
self._insert(key, val)
-
-
+
+
import collections
class LRUCache2(object):
def __init__(self, capacity):
@@ -115,7 +115,7 @@ def put(self, key, value):
self.cache.popitem(last=False)
self.cache[key] = value
-
+
if __name__ == "__main__":
cache = LRUCache(3)
cache.set(1, 1)
@@ -124,4 +124,4 @@ def put(self, key, value):
print cache.get(1)
cache.set(4, 4)
print cache.get(2)
-
+
diff --git a/Python/majority-element-ii.py b/Python/majority-element-ii.py
index 849bde6cb..40f02dee3 100644
--- a/Python/majority-element-ii.py
+++ b/Python/majority-element-ii.py
@@ -1,8 +1,8 @@
# Time: O(n)
# Space: O(1)
-# Given an integer array of size n,
-# find all elements that appear more than [n/3] times.
+# Given an integer array of size n,
+# find all elements that appear more than [n/3] times.
# The algorithm should run in linear time and in O(1) space.
import collections
diff --git a/Python/majority-element.py b/Python/majority-element.py
index f39f2c0d7..2f39c0403 100644
--- a/Python/majority-element.py
+++ b/Python/majority-element.py
@@ -3,7 +3,7 @@
#
# Given an array of size n, find the majority element.
# The majority element is the element that appears more than [n/2] times.
-#
+#
# You may assume that the array is non-empty and the majority element always exist in the array.
import collections
@@ -15,7 +15,7 @@ def majorityElement(self, nums):
:rtype: int
"""
idx, cnt = 0, 1
-
+
for i in xrange(1, len(nums)):
if nums[idx] == nums[i]:
cnt += 1
@@ -24,7 +24,7 @@ def majorityElement(self, nums):
if cnt == 0:
idx = i
cnt = 1
-
+
return nums[idx]
def majorityElement2(self, nums):
diff --git a/Python/matchsticks-to-square.py b/Python/matchsticks-to-square.py
index 9728cccff..18338e2ee 100644
--- a/Python/matchsticks-to-square.py
+++ b/Python/matchsticks-to-square.py
@@ -44,7 +44,7 @@ def makesquare(self, nums):
for subset in xrange(fullset+1):
subset_total_len = 0
- for i in xrange(len(nums)):
+ for i in xrange(len(nums)):
if subset & (1 << i):
subset_total_len += nums[i]
@@ -56,5 +56,5 @@ def makesquare(self, nums):
if valid_half_subsets[fullset ^ valid_half_subset]:
return True
used_subsets.append(subset)
-
+
return False
diff --git a/Python/max-chunks-to-make-sorted-ii.py b/Python/max-chunks-to-make-sorted-ii.py
index 363d313f9..af0b3e7c7 100644
--- a/Python/max-chunks-to-make-sorted-ii.py
+++ b/Python/max-chunks-to-make-sorted-ii.py
@@ -39,7 +39,7 @@ def maxChunksToSorted(self, arr):
"""
def compare(i1, i2):
return arr[i1]-arr[i2] if arr[i1] != arr[i2] else i1-i2
-
+
idxs = [i for i in xrange(len(arr))]
result, max_i = 0, 0
for i, v in enumerate(sorted(idxs, cmp=compare)):
diff --git a/Python/max-sum-of-sub-matrix-no-larger-than-k.py b/Python/max-sum-of-sub-matrix-no-larger-than-k.py
index d21b3fe78..5d18781af 100644
--- a/Python/max-sum-of-sub-matrix-no-larger-than-k.py
+++ b/Python/max-sum-of-sub-matrix-no-larger-than-k.py
@@ -38,7 +38,7 @@
# Time: O(min(m, n)^2 * max(m, n)^2)
# Space: O(max(m, n))
-from bisect import bisect_left, insort
+from bisect import bisect_left, insort
class Solution(object):
def maxSumSubmatrix(self, matrix, k):
@@ -59,7 +59,7 @@ def maxSumSubmatrix(self, matrix, k):
for j in xrange(i, m):
for l in xrange(n):
sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j]
-
+
# Find the max subarray no more than K.
accu_sum_set, accu_sum = [0], 0
for sum in sums:
@@ -86,7 +86,7 @@ def __init__(self, val):
self.val = val
self.left = None
self.right = None
-
+
def insert(self, val): # Time: O(h) = O(logn) ~ O(n)
curr = self
while curr:
@@ -102,7 +102,7 @@ def insert(self, val): # Time: O(h) = O(logn) ~ O(n)
else:
curr.right = BST(val)
return
-
+
def lower_bound(self, val): # Time: O(h) = O(logn) ~ O(n)
result, curr = None, self
while curr:
@@ -125,7 +125,7 @@ def lower_bound(self, val): # Time: O(h) = O(logn) ~ O(n)
for j in xrange(i, m):
for l in xrange(n):
sums[l] += matrix[j][l] if m == len(matrix) else matrix[l][j]
-
+
# Find the max subarray no more than K.
accu_sum_set = BST(0)
accu_sum = 0
diff --git a/Python/maximal-rectangle.py b/Python/maximal-rectangle.py
index 85420c608..f4f7f374f 100644
--- a/Python/maximal-rectangle.py
+++ b/Python/maximal-rectangle.py
@@ -1,7 +1,7 @@
# Time: O(n^2)
# Space: O(n)
-# Given a 2D binary matrix filled with 0's and 1's,
+# Given a 2D binary matrix filled with 0's and 1's,
# find the largest rectangle containing all ones and return its area.
# Ascending stack solution.
@@ -49,7 +49,7 @@ def maximalRectangle(self, matrix):
"""
if not matrix:
return 0
-
+
result = 0
m = len(matrix)
n = len(matrix[0])
@@ -68,7 +68,7 @@ def maximalRectangle(self, matrix):
H[j] = 0
R[j] = n
left = j + 1
-
+
right = n
for j in reversed(xrange(n)):
if matrix[i][j] == '1':
@@ -76,7 +76,7 @@ def maximalRectangle(self, matrix):
result = max(result, H[j] * (R[j] - L[j]))
else:
right = j
-
+
return result
if __name__ == "__main__":
diff --git a/Python/maximal-square.py b/Python/maximal-square.py
index 2f95f9b99..bb9029526 100644
--- a/Python/maximal-square.py
+++ b/Python/maximal-square.py
@@ -1,7 +1,7 @@
# Time: O(n^2)
# Space: O(n)
#
-# Given a 2D binary matrix filled with 0's and 1's,
+# Given a 2D binary matrix filled with 0's and 1's,
# find the largest square containing all 1's and return its area.
#
# For example, given the following matrix:
@@ -24,12 +24,12 @@ def maximalSquare(self, matrix):
m, n = len(matrix), len(matrix[0])
size = [[0 for j in xrange(n)] for i in xrange(2)]
max_size = 0
-
+
for j in xrange(n):
if matrix[0][j] == '1':
size[0][j] = 1
max_size = max(max_size, size[0][j])
-
+
for i in xrange(1, m):
if matrix[i][0] == '1':
size[i % 2][0] = 1
@@ -43,7 +43,7 @@ def maximalSquare(self, matrix):
max_size = max(max_size, size[i % 2][j])
else:
size[i % 2][j] = 0
-
+
return max_size * max_size
@@ -60,12 +60,12 @@ def maximalSquare(self, matrix):
m, n = len(matrix), len(matrix[0])
size = [[0 for j in xrange(n)] for i in xrange(m)]
max_size = 0
-
+
for j in xrange(n):
if matrix[0][j] == '1':
size[0][j] = 1
max_size = max(max_size, size[0][j])
-
+
for i in xrange(1, m):
if matrix[i][0] == '1':
size[i][0] = 1
@@ -79,10 +79,10 @@ def maximalSquare(self, matrix):
max_size = max(max_size, size[i][j])
else:
size[i][j] = 0
-
+
return max_size * max_size
-
-
+
+
# Time: O(n^2)
# Space: O(n^2)
# DP.
@@ -92,7 +92,7 @@ class Solution3:
def maximalSquare(self, matrix):
if not matrix:
return 0
-
+
H, W = 0, 1
# DP table stores (h, w) for each (i, j).
table = [[[0, 0] for j in xrange(len(matrix[0]))] \
@@ -108,7 +108,7 @@ def maximalSquare(self, matrix):
if j + 1 < len(matrix[i]):
w = table[i][j + 1][W] + 1
table[i][j] = [h, w]
-
+
# A table stores the length of largest square for each (i, j).
s = [[0 for j in xrange(len(matrix[0]))] \
for i in xrange(len(matrix))]
@@ -122,6 +122,6 @@ def maximalSquare(self, matrix):
side = min(s[i + 1][j + 1] + 1, side)
s[i][j] = side
max_square_area = max(max_square_area, side * side)
-
+
return max_square_area;
-
+
diff --git a/Python/maximum-binary-tree.py b/Python/maximum-binary-tree.py
index e32134c97..c95d5ff82 100644
--- a/Python/maximum-binary-tree.py
+++ b/Python/maximum-binary-tree.py
@@ -16,8 +16,8 @@
# 6
# / \
# 3 5
-# \ /
-# 2 0
+# \ /
+# 2 0
# \
# 1
# Note:
diff --git a/Python/maximum-depth-of-binary-tree.py b/Python/maximum-depth-of-binary-tree.py
index 016f720a6..2889d824a 100644
--- a/Python/maximum-depth-of-binary-tree.py
+++ b/Python/maximum-depth-of-binary-tree.py
@@ -2,7 +2,7 @@
# Space: O(h), h is height of binary tree
#
# Given a binary tree, find its maximum depth.
-#
+#
# The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
#
@@ -19,7 +19,7 @@ class Solution:
def maxDepth(self, root):
if root is None:
return 0
- else:
+ else:
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
if __name__ == "__main__":
diff --git a/Python/maximum-gap.py b/Python/maximum-gap.py
index 2003ab711..06d771637 100644
--- a/Python/maximum-gap.py
+++ b/Python/maximum-gap.py
@@ -1,16 +1,16 @@
# Time: O(n)
# Space: O(n)
-# Given an unsorted array, find the maximum difference between
-#
+# Given an unsorted array, find the maximum difference between
+#
# the successive elements in its sorted form.
-#
+#
# Try to solve it in linear time/space.
-#
+#
# Return 0 if the array contains less than 2 elements.
-#
+#
# You may assume all elements in the array are non-negative integers
-#
+#
# and fit in the 32-bit signed integer range.
# bucket sort
@@ -24,7 +24,7 @@ def maximumGap(self, nums):
"""
if len(nums) < 2:
return 0
-
+
# Init bucket.
max_val, min_val = max(nums), min(nums)
gap = max(1, (max_val - min_val) / (len(nums) - 1))
@@ -36,11 +36,11 @@ def maximumGap(self, nums):
for n in nums:
# min_val / max_val is in the first / last bucket.
if n in (max_val, min_val):
- continue
+ continue
i = (n - min_val) / gap
bucket[i]['min'] = min(bucket[i]['min'], n)
bucket[i]['max'] = max(bucket[i]['max'], n)
-
+
# Count each bucket gap between the first and the last bucket.
max_gap, pre_bucket_max = 0, min_val
for i in xrange(bucket_size):
@@ -51,8 +51,8 @@ def maximumGap(self, nums):
max_gap = max(max_gap, bucket[i]['min'] - pre_bucket_max)
pre_bucket_max = bucket[i]['max']
# Count the last bucket.
- max_gap = max(max_gap, max_val - pre_bucket_max)
-
+ max_gap = max(max_gap, max_val - pre_bucket_max)
+
return max_gap
@@ -67,11 +67,11 @@ def maximumGap(self, nums):
if len(nums) < 2:
return 0
-
+
nums.sort()
pre = nums[0]
max_gap = float("-inf")
-
+
for i in nums:
max_gap = max(max_gap, i - pre)
pre = i
diff --git a/Python/maximum-product-of-word-lengths.py b/Python/maximum-product-of-word-lengths.py
index ddc03bd4b..66a870888 100644
--- a/Python/maximum-product-of-word-lengths.py
+++ b/Python/maximum-product-of-word-lengths.py
@@ -2,7 +2,7 @@
# Space: O(n)
# Given a string array words, find the maximum value of
-# length(word[i]) * length(word[j]) where the two words
+# length(word[i]) * length(word[j]) where the two words
# do not share common letters. You may assume that each
# word will contain only lower case letters. If no such
# two words exist, return 0.
diff --git a/Python/maximum-product-subarray.py b/Python/maximum-product-subarray.py
index 50d08388a..cf502bd5f 100644
--- a/Python/maximum-product-subarray.py
+++ b/Python/maximum-product-subarray.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Find the contiguous subarray within an array (containing at least one number) which has the largest product.
-#
+#
# For example, given the array [2,3,-2,4],
# the contiguous subarray [2,3] has the largest product = 6.
diff --git a/Python/maximum-subarray.py b/Python/maximum-subarray.py
index 35fcd74ae..07a0fcafe 100644
--- a/Python/maximum-subarray.py
+++ b/Python/maximum-subarray.py
@@ -2,12 +2,12 @@
# Space: O(1)
#
# Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
-#
+#
# For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
# the contiguous subarray [4,-1,2,1] has the largest sum = 6.
-#
+#
# click to show more practice.
-#
+#
# More practice:
# If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
#
diff --git a/Python/maximum-sum-of-3-non-overlapping-subarrays.py b/Python/maximum-sum-of-3-non-overlapping-subarrays.py
index 7defc2939..30b4f8a1d 100644
--- a/Python/maximum-sum-of-3-non-overlapping-subarrays.py
+++ b/Python/maximum-sum-of-3-non-overlapping-subarrays.py
@@ -11,7 +11,7 @@
# Example:
# Input: [1,2,1,2,6,7,5,1], 2
# Output: [0, 3, 5]
- #
+ #
# Explanation: Subarrays [1, 2], [2, 6], [7, 5] correspond to the starting indices [0, 3, 5].
# We could have also taken [2, 1], but an answer of [1, 3, 5] would be lexicographically larger.
#
@@ -31,7 +31,7 @@ def maxSumOfThreeSubarrays(self, nums, k):
accu = [0]
for num in nums:
accu.append(accu[-1]+num)
-
+
left_pos = [0] * n
total = accu[k]-accu[0]
for i in xrange(k, n):
@@ -40,7 +40,7 @@ def maxSumOfThreeSubarrays(self, nums, k):
total = accu[i+1]-accu[i+1-k]
else:
left_pos[i] = left_pos[i-1]
-
+
right_pos = [n-k] * n
total = accu[n]-accu[n-k]
for i in reversed(xrange(n-k)):
@@ -49,7 +49,7 @@ def maxSumOfThreeSubarrays(self, nums, k):
total = accu[i+k]-accu[i]
else:
right_pos[i] = right_pos[i+1]
-
+
result, max_sum = [], 0
for i in xrange(k, n-2*k+1):
left, right = left_pos[i-1], right_pos[i+k]
diff --git a/Python/maximum-width-of-binary-tree.py b/Python/maximum-width-of-binary-tree.py
index 4bb5125c0..b0362eee8 100644
--- a/Python/maximum-width-of-binary-tree.py
+++ b/Python/maximum-width-of-binary-tree.py
@@ -10,53 +10,53 @@
# where the null nodes between the end-nodes are also counted into the length calculation.
#
# Example 1:
-# Input:
+# Input:
#
# 1
# / \
# 3 2
-# / \ \
-# 5 3 9
+# / \ \
+# 5 3 9
#
# Output: 4
# Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
# Example 2:
-# Input:
+# Input:
#
# 1
-# /
-# 3
-# / \
-# 5 3
+# /
+# 3
+# / \
+# 5 3
#
# Output: 2
# Explanation: The maximum width existing in the third level with the length 2 (5,3).
# Example 3:
-# Input:
+# Input:
#
# 1
# / \
-# 3 2
-# /
-# 5
+# 3 2
+# /
+# 5
#
# Output: 2
# Explanation: The maximum width existing in the second level with the length 2 (3,2).
# Example 4:
-# Input:
+# Input:
#
# 1
# / \
# 3 2
-# / \
-# 5 9
+# / \
+# 5 9
# / \
# 6 7
# Output: 8
# Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
#
# Note: Answer will in the range of 32-bit signed integer.
-#
+#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
diff --git a/Python/maximum-xor-of-two-numbers-in-an-array.py b/Python/maximum-xor-of-two-numbers-in-an-array.py
index 20f541afe..6a3156b19 100644
--- a/Python/maximum-xor-of-two-numbers-in-an-array.py
+++ b/Python/maximum-xor-of-two-numbers-in-an-array.py
@@ -22,7 +22,7 @@ def findMaximumXOR(self, nums):
:rtype: int
"""
result = 0
-
+
for i in reversed(xrange(32)):
result <<= 1
prefixes = set()
diff --git a/Python/median-of-two-sorted-arrays.py b/Python/median-of-two-sorted-arrays.py
index 14ce80108..2450b65bf 100644
--- a/Python/median-of-two-sorted-arrays.py
+++ b/Python/median-of-two-sorted-arrays.py
@@ -1,6 +1,6 @@
# Time: O(log(min(m, n)))
# Space: O(1)
-
+
# There are two sorted arrays nums1 and nums2 of size m and n respectively.
# Find the median of the two sorted arrays.
# The overall run time complexity should be O(log (m+n)).
@@ -13,7 +13,7 @@ def findMedianSortedArrays(self, nums1, nums2):
:rtype: float
"""
len1, len2 = len(nums1), len(nums2)
- if (len1 + len2) % 2 == 1:
+ if (len1 + len2) % 2 == 1:
return self.getKth(nums1, nums2, (len1 + len2)/2 + 1)
else:
return (self.getKth(nums1, nums2, (len1 + len2)/2) + \
@@ -24,7 +24,7 @@ def getKth(self, A, B, k):
if m > n:
return self.getKth(B, A, k)
- left, right = 0, m
+ left, right = 0, m
while left < right:
mid = left + (right - left) / 2
if 0 <= k - 1 - mid < n and A[mid] >= B[k - 1 - mid]:
@@ -49,7 +49,7 @@ def findMedianSortedArrays(self, nums1, nums2):
:rtype: float
"""
len1, len2 = len(nums1), len(nums2)
- if (len1 + len2) % 2 == 1:
+ if (len1 + len2) % 2 == 1:
return self.getKth([nums1, nums2], (len1 + len2)/2 + 1)
else:
return (self.getKth([nums1, nums2], (len1 + len2)/2) + \
@@ -85,4 +85,4 @@ def match(arrays, num, target):
if __name__ == "__main__":
print Solution().findMedianSortedArrays([1, 3, 5, 7], [2, 4, 6])
print Solution().findMedianSortedArrays([1, 3, 5], [2, 4, 6])
-
+
diff --git a/Python/meeting-rooms.py b/Python/meeting-rooms.py
index f8ef52f66..de7d864c6 100644
--- a/Python/meeting-rooms.py
+++ b/Python/meeting-rooms.py
@@ -12,7 +12,7 @@ class Solution:
# @return {boolean}
def canAttendMeetings(self, intervals):
intervals.sort(key=lambda x: x.start)
-
+
for i in xrange(1, len(intervals)):
if intervals[i].start < intervals[i-1].end:
return False
diff --git a/Python/merge-intervals.py b/Python/merge-intervals.py
index 953798275..1e279e4d6 100644
--- a/Python/merge-intervals.py
+++ b/Python/merge-intervals.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given a collection of intervals, merge all overlapping intervals.
-#
+#
# For example,
# Given [1,3],[2,6],[8,10],[15,18],
# return [1,6],[8,10],[15,18].
@@ -13,7 +13,7 @@ class Interval:
def __init__(self, s=0, e=0):
self.start = s
self.end = e
-
+
def __repr__(self):
return "[{}, {}]".format(self.start, self.end)
@@ -30,7 +30,7 @@ def merge(self, intervals):
result = [intervals[0]]
for i in xrange(1, len(intervals)):
prev, current = result[-1], intervals[i]
- if current.start <= prev.end:
+ if current.start <= prev.end:
prev.end = max(prev.end, current.end)
else:
result.append(current)
diff --git a/Python/merge-k-sorted-lists.py b/Python/merge-k-sorted-lists.py
index edc3c9d4a..0acffe1af 100644
--- a/Python/merge-k-sorted-lists.py
+++ b/Python/merge-k-sorted-lists.py
@@ -67,7 +67,7 @@ def mergeTwoLists(l1, l2):
curr = curr.next
curr.next = l1 or l2
return dummy.next
-
+
def mergeKListsHelper(lists, begin, end):
if begin > end:
return None
@@ -75,7 +75,7 @@ def mergeKListsHelper(lists, begin, end):
return lists[begin]
return mergeTwoLists(mergeKListsHelper(lists, begin, (begin + end) / 2), \
mergeKListsHelper(lists, (begin + end) / 2 + 1, end))
-
+
return mergeKListsHelper(lists, 0, len(lists) - 1)
@@ -89,19 +89,19 @@ class Solution3:
def mergeKLists(self, lists):
dummy = ListNode(0)
current = dummy
-
+
heap = []
for sorted_list in lists:
if sorted_list:
heapq.heappush(heap, (sorted_list.val, sorted_list))
-
+
while heap:
smallest = heapq.heappop(heap)[1]
current.next = smallest
current = current.next
if smallest.next:
heapq.heappush(heap, (smallest.next.val, smallest.next))
-
+
return dummy.next
@@ -110,5 +110,5 @@ def mergeKLists(self, lists):
list1.next = ListNode(3)
list2 = ListNode(2)
list2.next = ListNode(4)
-
+
print Solution().mergeKLists([list1, list2])
diff --git a/Python/merge-sorted-array.py b/Python/merge-sorted-array.py
index 5b6a275fc..b8ace9bb5 100644
--- a/Python/merge-sorted-array.py
+++ b/Python/merge-sorted-array.py
@@ -2,9 +2,9 @@
# Space: O(1)
#
# Given two sorted integer arrays A and B, merge B into A as one sorted array.
-#
+#
# Note:
-# You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B.
+# You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B.
# The number of elements initialized in A and B are m and n respectively.
#
@@ -16,7 +16,7 @@ class Solution:
# @return nothing
def merge(self, A, m, B, n):
last, i, j = m + n - 1, m - 1, n - 1
-
+
while i >= 0 and j >= 0:
if A[i] > B[j]:
A[last] = A[i]
@@ -24,7 +24,7 @@ def merge(self, A, m, B, n):
else:
A[last] = B[j]
last, j = last - 1, j - 1
-
+
while j >= 0:
A[last] = B[j]
last, j = last - 1, j - 1
@@ -34,7 +34,7 @@ def merge(self, A, m, B, n):
B = [2, 4, 6, 7]
Solution().merge(A, 3, B, 4)
print A
-
+
# Time: O(n)
# Space: O(n)
diff --git a/Python/merge-two-binary-trees.py b/Python/merge-two-binary-trees.py
index 3fc1c04ef..89341b1e3 100644
--- a/Python/merge-two-binary-trees.py
+++ b/Python/merge-two-binary-trees.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(h)
-# Given two binary trees and imagine that
+# Given two binary trees and imagine that
# when you put one of them to cover the other,
# some nodes of the two trees are overlapped
# while the others are not.
@@ -12,21 +12,21 @@
# Otherwise, the NOT null node will be used as the node of new tree.
#
# Example 1:
-# Input:
-# Tree 1 Tree 2
-# 1 2
-# / \ / \
-# 3 2 1 3
-# / \ \
-# 5 4 7
-# Output:
+# Input:
+# Tree 1 Tree 2
+# 1 2
+# / \ / \
+# 3 2 1 3
+# / \ \
+# 5 4 7
+# Output:
# Merged tree:
# 3
# / \
# 4 5
-# / \ \
+# / \ \
# 5 4 7
-#
+#
# Note: The merging process must start from the root nodes of both trees.
# Definition for a binary tree node.
diff --git a/Python/merge-two-sorted-lists.py b/Python/merge-two-sorted-lists.py
index 0d965d2b9..c94df5a8b 100644
--- a/Python/merge-two-sorted-lists.py
+++ b/Python/merge-two-sorted-lists.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(1)
#
-# Merge two sorted linked lists and return it as a new list.
+# Merge two sorted linked lists and return it as a new list.
# The new list should be made by splicing together the nodes of the first two lists.
#
@@ -42,5 +42,5 @@ def mergeTwoLists(self, l1, l2):
l2 = ListNode (2)
l2.next = ListNode(3)
print Solution().mergeTwoLists(l1, l2)
-
-
+
+
diff --git a/Python/min-stack.py b/Python/min-stack.py
index 12df16163..ff31748a8 100644
--- a/Python/min-stack.py
+++ b/Python/min-stack.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
-#
+#
# push(x) -- Push element x onto stack.
# pop() -- Removes the element on top of the stack.
# top() -- Get the top element.
@@ -13,7 +13,7 @@ class MinStack:
def __init__(self):
self.min = None
self.stack = []
-
+
# @param x, an integer
# @return an integer
def push(self, x):
@@ -38,7 +38,7 @@ def top(self):
return x + self.min
else:
return self.min
-
+
# @return an integer
def getMin(self):
return self.min
@@ -67,11 +67,11 @@ def pop(self):
self.minStack[-1][1] -= 1
if self.minStack[-1][1] == 0:
self.minStack.pop()
-
+
# @return an integer
def top(self):
return self.stack[-1]
-
+
# @return an integer
def getMin(self):
return self.minStack[-1][0]
@@ -80,4 +80,4 @@ def getMin(self):
stack = MinStack()
stack.push(-1)
print [stack.top(), stack.getMin()]
-
+
diff --git a/Python/minimize-max-distance-to-gas-station.py b/Python/minimize-max-distance-to-gas-station.py
index 4b56a68e8..a8676a4a4 100644
--- a/Python/minimize-max-distance-to-gas-station.py
+++ b/Python/minimize-max-distance-to-gas-station.py
@@ -13,7 +13,7 @@
#
# Input: stations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], K = 9
# Output: 0.500000
-#
+#
# Note:
# - stations.length will be an integer in range [10, 2000].
# - stations[i] will be an integer in range [0, 10^8].
diff --git a/Python/minimum-depth-of-binary-tree.py b/Python/minimum-depth-of-binary-tree.py
index 2833dcaab..709093e51 100644
--- a/Python/minimum-depth-of-binary-tree.py
+++ b/Python/minimum-depth-of-binary-tree.py
@@ -2,7 +2,7 @@
# Space: O(h), h is height of binary tree
#
# Given a binary tree, find its minimum depth.
-#
+#
# The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
#
@@ -19,7 +19,7 @@ class Solution:
def minDepth(self, root):
if root is None:
return 0
-
+
if root.left and root.right:
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
else:
diff --git a/Python/minimum-distance-between-bst-nodes.py b/Python/minimum-distance-between-bst-nodes.py
index ca26974c7..dfb2ad825 100644
--- a/Python/minimum-distance-between-bst-nodes.py
+++ b/Python/minimum-distance-between-bst-nodes.py
@@ -16,8 +16,8 @@
# 4
# / \
# 2 6
-# / \
-# 1 3
+# / \
+# 1 3
#
# while the minimum difference in this tree is 1,
# it occurs between node 1 and node 2, also between node 3 and node 2.
@@ -51,4 +51,4 @@ def dfs(node):
self.result = float('inf')
dfs(root)
return self.result
-
+
diff --git a/Python/minimum-factorization.py b/Python/minimum-factorization.py
index 52d72293a..756c20e81 100644
--- a/Python/minimum-factorization.py
+++ b/Python/minimum-factorization.py
@@ -16,4 +16,4 @@ def smallestFactorization(self, a):
result = mul*i + result
mul *= 10
return result if a == 1 and result < 2**31 else 0
-
+
diff --git a/Python/minimum-genetic-mutation.py b/Python/minimum-genetic-mutation.py
index 900510bb7..bd89371fe 100644
--- a/Python/minimum-genetic-mutation.py
+++ b/Python/minimum-genetic-mutation.py
@@ -1,26 +1,26 @@
# Time: O(n * b), n is the length of gene string, b is size of bank
# Space: O(b)
-# A gene string can be represented by an 8-character long string,
-# with choices from "A","C","G","T".
-# Suppose we need to investigate about a mutation (mutation from "start" to "end"),
-# where ONE mutation is defined as ONE single character changed in the gene string.
-# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
+# A gene string can be represented by an 8-character long string,
+# with choices from "A","C","G","T".
+# Suppose we need to investigate about a mutation (mutation from "start" to "end"),
+# where ONE mutation is defined as ONE single character changed in the gene string.
+# For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
# Also, there is a given gene "bank", which records all the valid gene mutations.
-# A gene must be in the bank to make it a valid gene string.
+# A gene must be in the bank to make it a valid gene string.
#
# Now, given 3 things - start, end, bank,
# your task is to determine what is the minimum number of mutations needed to
-# mutate from "start" to "end". If there is no such a mutation, return -1.
+# mutate from "start" to "end". If there is no such a mutation, return -1.
#
# NOTE: 1. Starting point is assumed to be valid, so it might not be included in the bank.
# 2. If multiple mutations are needed, all mutations during in the sequence must be valid.
#
-# For example,
-#
-# bank: "AACCGGTA"
-# start: "AACCGGTT"
-# end: "AACCGGTA"
+# For example,
+#
+# bank: "AACCGGTA"
+# start: "AACCGGTT"
+# end: "AACCGGTA"
# return: 1
#
# bank: "AACCGGTA", "AACCGCTA", "AAACGGTA"
diff --git a/Python/minimum-moves-to-equal-array-elements-ii.py b/Python/minimum-moves-to-equal-array-elements-ii.py
index ee447cd6f..49207b3bd 100644
--- a/Python/minimum-moves-to-equal-array-elements-ii.py
+++ b/Python/minimum-moves-to-equal-array-elements-ii.py
@@ -19,7 +19,7 @@ def PartitionAroundPivot(left, right, pivot_idx, nums):
if nums[i] > pivot_value:
nums[i], nums[new_pivot_idx] = nums[new_pivot_idx], nums[i]
new_pivot_idx += 1
-
+
nums[right], nums[new_pivot_idx] = nums[new_pivot_idx], nums[right]
return new_pivot_idx
diff --git a/Python/minimum-path-sum.py b/Python/minimum-path-sum.py
index f6c4edfd0..af07387ca 100644
--- a/Python/minimum-path-sum.py
+++ b/Python/minimum-path-sum.py
@@ -1,9 +1,9 @@
# Time: O(m * n)
# Space: O(m + n)
#
-# Given a m x n grid filled with non-negative numbers,
+# Given a m x n grid filled with non-negative numbers,
# find a path from top left to bottom right which minimizes the sum of all numbers along its path.
-#
+#
# Note: You can only move either down or right at any point in time.
#
@@ -19,9 +19,9 @@ def minPathSum(self, grid):
sum[0] += grid[i][0]
for j in xrange(1, len(grid[0])):
sum[j] = min(sum[j - 1], sum[j]) + grid[i][j]
-
+
return sum[-1]
-
+
if __name__ == "__main__":
print Solution().minPathSum([[0,1]
,[1,0]])
diff --git a/Python/minimum-size-subarray-sum.py b/Python/minimum-size-subarray-sum.py
index 24d56ced0..e9ba17541 100644
--- a/Python/minimum-size-subarray-sum.py
+++ b/Python/minimum-size-subarray-sum.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(1)
#
-# Given an array of n positive integers and a positive integer s,
+# Given an array of n positive integers and a positive integer s,
# find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead.
#
# For example, given the array [2,3,1,2,4,3] and s = 7,
@@ -49,7 +49,7 @@ def minSubArrayLen(self, s, nums):
min_size = min(min_size, end - i + 1)
return min_size if min_size != float("inf") else 0
-
+
def binarySearch(self, compare, A, start, end, target):
while start < end:
mid = start + (end - start) / 2
diff --git a/Python/minimum-swaps-to-make-sequences-increasing.py b/Python/minimum-swaps-to-make-sequences-increasing.py
index d3806d0d9..4ba4acc85 100644
--- a/Python/minimum-swaps-to-make-sequences-increasing.py
+++ b/Python/minimum-swaps-to-make-sequences-increasing.py
@@ -15,7 +15,7 @@
# Example:
# Input: A = [1,3,5,4], B = [1,2,3,7]
# Output: 1
-# Explanation:
+# Explanation:
# Swap A[3] and B[3]. Then the sequences are:
# A = [1, 3, 5, 7] and B = [1, 2, 3, 4]
# which are both strictly increasing.
diff --git a/Python/minimum-window-subsequence.py b/Python/minimum-window-subsequence.py
index 647dcea4c..3fb65630c 100644
--- a/Python/minimum-window-subsequence.py
+++ b/Python/minimum-window-subsequence.py
@@ -12,7 +12,7 @@ def minWindow(self, S, T):
for j, c in enumerate(S):
if c == T[0]:
dp[0][j] = j
-
+
for i in xrange(1, len(T)):
prev = None
dp[i%2] = [None] * len(S)
diff --git a/Python/minimum-window-substring.py b/Python/minimum-window-substring.py
index d006f4f1e..d70f8c212 100644
--- a/Python/minimum-window-substring.py
+++ b/Python/minimum-window-substring.py
@@ -3,16 +3,16 @@
# Given a string S and a string T, find the minimum window in S which
# will contain all the characters in T in complexity O(n).
-#
+#
# For example,
# S = "ADOBECODEBANC"
# T = "ABC"
# Minimum window is "BANC".
-#
+#
# Note:
# If there is no such window in S that covers all characters in T,
# return the emtpy string "".
-#
+#
# If there are multiple such windows, you are guaranteed that
# there will always be only one unique minimum window in S.
@@ -25,32 +25,32 @@ def minWindow(self, s, t):
"""
current_count = [0 for i in xrange(52)]
expected_count = [0 for i in xrange(52)]
-
+
for char in t:
expected_count[ord(char) - ord('a')] += 1
-
+
i, count, start, min_width, min_start = 0, 0, 0, float("inf"), 0
while i < len(s):
current_count[ord(s[i]) - ord('a')] += 1
if current_count[ord(s[i]) - ord('a')] <= expected_count[ord(s[i]) - ord('a')]:
count += 1
-
+
if count == len(t):
while expected_count[ord(s[start]) - ord('a')] == 0 or \
current_count[ord(s[start]) - ord('a')] > expected_count[ord(s[start]) - ord('a')]:
current_count[ord(s[start]) - ord('a')] -= 1
start += 1
-
+
if min_width > i - start + 1:
min_width = i - start + 1
min_start = start
i += 1
-
+
if min_width == float("inf"):
return ""
-
+
return s[min_start:min_start + min_width]
if __name__ == "__main__":
- print Solution().minWindow("ADOBECODEBANC", "ABC")
+ print Solution().minWindow("ADOBECODEBANC", "ABC")
diff --git a/Python/missing-ranges.py b/Python/missing-ranges.py
index e43b6104c..16f3a36a5 100644
--- a/Python/missing-ranges.py
+++ b/Python/missing-ranges.py
@@ -3,8 +3,8 @@
#
# Given a sorted integer array where the range of elements are [lower, upper] inclusive,
# return its missing ranges.
-#
-# For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99,
+#
+# For example, given [0, 1, 3, 50, 75], lower = 0 and upper = 99,
# return ["2", "4->49", "51->74", "76->99"].
#
@@ -23,7 +23,7 @@ def getRange(lower, upper):
return "{}->{}".format(lower, upper)
ranges = []
pre = lower - 1
-
+
for i in xrange(len(nums) + 1):
if i == len(nums):
cur = upper + 1
@@ -31,9 +31,9 @@ def getRange(lower, upper):
cur = nums[i]
if cur - pre >= 2:
ranges.append(getRange(pre + 1, cur - 1))
-
+
pre = cur
-
+
return ranges
diff --git a/Python/monotone-increasing-digits.py b/Python/monotone-increasing-digits.py
index 111fb299c..b7b1e508f 100644
--- a/Python/monotone-increasing-digits.py
+++ b/Python/monotone-increasing-digits.py
@@ -14,11 +14,11 @@
# Example 2:
# Input: N = 1234
# Output: 1234
-#
+#
# Example 3:
# Input: N = 332
# Output: 299
-#
+#
# Note: N is an integer in the range [0, 10^9].
class Solution(object):
diff --git a/Python/move-zeroes.py b/Python/move-zeroes.py
index fb121754c..410eb8ffe 100644
--- a/Python/move-zeroes.py
+++ b/Python/move-zeroes.py
@@ -2,10 +2,10 @@
# Space: O(1)
# Given an array nums, write a function to move all 0's
-# to the end of it while maintaining the relative order
+# to the end of it while maintaining the relative order
# of the non-zero elements.
#
-# For example, given nums = [0, 1, 0, 3, 12], after
+# For example, given nums = [0, 1, 0, 3, 12], after
# calling your function, nums should be [1, 3, 12, 0, 0].
#
# Note:
@@ -44,9 +44,9 @@ def moveZeroes(self, nums):
if nums[i]:
nums[pos] = nums[i]
pos += 1
-
+
for i in xrange(pos, len(nums)):
- nums[i] = 0
+ nums[i] = 0
if __name__ == '__main__':
diff --git a/Python/multiply-strings.py b/Python/multiply-strings.py
index 6df6c3f12..cfb6d12d8 100644
--- a/Python/multiply-strings.py
+++ b/Python/multiply-strings.py
@@ -2,7 +2,7 @@
# Space: O(m + n)
#
# Given two numbers represented as strings, return multiplication of the numbers as a string.
-#
+#
# Note: The numbers can be arbitrarily large and are non-negative.
#
diff --git a/Python/my-calendar-i.py b/Python/my-calendar-i.py
index 8814fc510..050d01f9b 100644
--- a/Python/my-calendar-i.py
+++ b/Python/my-calendar-i.py
@@ -21,7 +21,7 @@
# MyCalendar.book(10, 20); // returns true
# MyCalendar.book(15, 25); // returns false
# MyCalendar.book(20, 30); // returns true
-# Explanation:
+# Explanation:
# The first event can be booked. The second can't because time 15 is already booked by another event.
# The third event can be booked, as the first event takes every time less than 20, but not including 20.
#
@@ -87,7 +87,7 @@ def book(self, start, end):
if start < j and end > i:
return False
self.__calendar.append((start, end))
- return True
+ return True
# Your MyCalendar object will be instantiated and called as such:
diff --git a/Python/my-calendar-ii.py b/Python/my-calendar-ii.py
index 0dc4f14e6..104ccf4b5 100644
--- a/Python/my-calendar-ii.py
+++ b/Python/my-calendar-ii.py
@@ -25,7 +25,7 @@
# MyCalendar.book(5, 10); // returns true
# MyCalendar.book(25, 55); // returns true
#
-# Explanation:
+# Explanation:
# The first two events can be booked. The third event can be double booked.
# The fourth event (5, 15) can't be booked, because it would result in a triple booking.
# The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked.
@@ -35,7 +35,7 @@
# Note:
# - The number of calls to MyCalendar.book per test case will be at most 1000.
# - In calls to MyCalendar.book(start, end), start and end are integers in the range [0, 10^9].
-
+
class MyCalendarTwo(object):
def __init__(self):
diff --git a/Python/n-queens-ii.py b/Python/n-queens-ii.py
index 56e4c8f22..ee48742e4 100644
--- a/Python/n-queens-ii.py
+++ b/Python/n-queens-ii.py
@@ -2,7 +2,7 @@
# Space: O(n)
#
# Follow up for N-Queens problem.
-#
+#
# Now, instead outputting board configurations, return the total number of distinct solutions.
#
@@ -14,7 +14,7 @@ def totalNQueens(self, n):
self.main_diag = [False] * (2 * n)
self.anti_diag = [False] * (2 * n)
return self.totalNQueensRecu([], 0, n)
-
+
def totalNQueensRecu(self, solution, row, n):
if row == n:
return 1
@@ -31,7 +31,7 @@ class Solution2:
# @return an integer
def totalNQueens(self, n):
return self.totalNQueensRecu([], 0, n)
-
+
def totalNQueensRecu(self, solution, row, n):
if row == n:
return 1
diff --git a/Python/n-queens.py b/Python/n-queens.py
index 9ca999b96..6140a2e53 100644
--- a/Python/n-queens.py
+++ b/Python/n-queens.py
@@ -1,23 +1,23 @@
# Time: O(n!)
# Space: O(n)
-# The n-queens puzzle is the problem of placing n queens on
+# The n-queens puzzle is the problem of placing n queens on
# an nxn chess board such that no two queens attack each other.
-#
+#
# Given an integer n, return all distinct solutions to the n-queens puzzle.
-#
-# Each solution contains a distinct board configuration of the n-queens' placement,
+#
+# Each solution contains a distinct board configuration of the n-queens' placement,
# where 'Q' and '.' both indicate a queen and an empty space respectively.
-#
+#
# For example,
# There exist two distinct solutions to the 4-queens puzzle:
-#
+#
# [
# [".Q..", // Solution 1
# "...Q",
# "Q...",
# "..Q."],
-#
+#
# ["..Q.", // Solution 2
# "Q...",
# "...Q",
@@ -43,22 +43,22 @@ def dfs(curr, cols, main_diag, anti_diag, result):
dfs(curr, cols, main_diag, anti_diag, result)
curr.pop()
cols[i] = main_diag[row+i] = anti_diag[row-i+n] = False
-
+
result = []
cols, main_diag, anti_diag = [False]*n, [False]*(2*n), [False]*(2*n)
dfs([], cols, main_diag, anti_diag, result)
return result
-
+
# For any point (x,y), if we want the new point (p,q) don't share the same row, column, or diagonal.
-# then there must have ```p+q != x+y``` and ```p-q!= x-y```
-# the former focus on eliminate 'left bottom right top' diagonal;
+# then there must have ```p+q != x+y``` and ```p-q!= x-y```
+# the former focus on eliminate 'left bottom right top' diagonal;
# the latter focus on eliminate 'left top right bottom' diagonal
# - col_per_row: the list of column index per row
# - cur_row:current row we are seraching for valid column
# - xy_diff:the list of x-y
-# - xy_sum:the list of x+y
+# - xy_sum:the list of x+y
class Solution2(object):
def solveNQueens(self, n):
"""
@@ -75,7 +75,7 @@ def dfs(col_per_row, xy_diff, xy_sum):
ress = []
dfs([], [], [])
return [['.'*i + 'Q' + '.'*(n-i-1) for i in res] for res in ress]
-
-
+
+
if __name__ == "__main__":
print Solution().solveNQueens(8)
diff --git a/Python/nested-list-weight-sum-ii.py b/Python/nested-list-weight-sum-ii.py
index 0594d091c..8eb003d4f 100644
--- a/Python/nested-list-weight-sum-ii.py
+++ b/Python/nested-list-weight-sum-ii.py
@@ -40,7 +40,7 @@ def depthSumInverseHelper(list, depth, result):
else:
for l in list.getList():
depthSumInverseHelper(l, depth + 1, result)
-
+
result = []
for list in nestedList:
depthSumInverseHelper(list, 0, result)
diff --git a/Python/next-greater-element-ii.py b/Python/next-greater-element-ii.py
index 03ee1c106..6a75d5e1f 100644
--- a/Python/next-greater-element-ii.py
+++ b/Python/next-greater-element-ii.py
@@ -10,8 +10,8 @@
# Example 1:
# Input: [1,2,1]
# Output: [2,-1,2]
-# Explanation: The first 1's next greater number is 2;
-# The number 2 can't find next greater number;
+# Explanation: The first 1's next greater number is 2;
+# The number 2 can't find next greater number;
# The second 1's next greater number needs to search circularly, which is also 2.
# Note: The length of given array won't exceed 10000.
diff --git a/Python/next-permutation.py b/Python/next-permutation.py
index 48056e9c6..def9a572d 100644
--- a/Python/next-permutation.py
+++ b/Python/next-permutation.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
-#
+#
# If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
-#
+#
# The replacement must be in-place, do not allocate extra memory.
-#
+#
# Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
# 1,2,3 -> 1,3,2
# 3,2,1 -> 1,2,3
@@ -21,15 +21,15 @@ def nextPermutation(self, num):
for i in xrange(len(num) - 1):
if num[i] < num[i + 1]:
k = i
-
+
if k == -1:
num.reverse()
return
-
+
for i in xrange(k + 1, len(num)):
if num[i] > num[k]:
l = i
-
+
num[k], num[l] = num[l], num[k]
num[k + 1:] = num[:k:-1]
diff --git a/Python/nim-game.py b/Python/nim-game.py
index f1eadb01a..e14d788df 100644
--- a/Python/nim-game.py
+++ b/Python/nim-game.py
@@ -2,13 +2,13 @@
# Space: O(1)
#
# You are playing the following Nim Game with your friend:
-# There is a heap of stones on the table, each time one of
+# There is a heap of stones on the table, each time one of
# you take turns to remove 1 to 3 stones.
# The one who removes the last stone will be the winner.
# You will take the first turn to remove the stones.
#
# Both of you are very clever and have optimal strategies for
-# the game. Write a function to determine whether you can win
+# the game. Write a function to determine whether you can win
# the game given the number of stones in the heap.
#
# For example, if there are 4 stones in the heap, then you will
diff --git a/Python/non-decreasing-array.py b/Python/non-decreasing-array.py
index e5e51c42f..d556d531d 100644
--- a/Python/non-decreasing-array.py
+++ b/Python/non-decreasing-array.py
@@ -9,9 +9,9 @@
# Example 1:
# Input: [4,2,3]
# Output: True
-# Explanation: You could modify the first
+# Explanation: You could modify the first
# 4
-# to
+# to
# 1
# to get a non-decreasing array.
# Example 2:
@@ -39,4 +39,4 @@ def checkPossibility(self, nums):
else:
prev = nums[i]
return True
-
+
diff --git a/Python/non-negative-integers-without-consecutive-ones.py b/Python/non-negative-integers-without-consecutive-ones.py
index 37d59f055..5847fe8ba 100644
--- a/Python/non-negative-integers-without-consecutive-ones.py
+++ b/Python/non-negative-integers-without-consecutive-ones.py
@@ -7,7 +7,7 @@
# Example 1:
# Input: 5
# Output: 5
-# Explanation:
+# Explanation:
# Here are the non-negative integers <= 5 with their corresponding binary representations:
# 0 : 0
# 1 : 1
@@ -15,7 +15,7 @@
# 3 : 11
# 4 : 100
# 5 : 101
-# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
+# Among them, only integer 3 disobeys the rule (two consecutive ones) and the other 5 satisfy the rule.
# Note: 1 <= n <= 10^9
class Solution(object):
diff --git a/Python/number-of-1-bits.py b/Python/number-of-1-bits.py
index 1d3f12f2a..065c5db7c 100644
--- a/Python/number-of-1-bits.py
+++ b/Python/number-of-1-bits.py
@@ -1,10 +1,10 @@
# Time: O(logn) = O(32)
# Space: O(1)
#
-# Write a function that takes an unsigned integer
+# Write a function that takes an unsigned integer
# and returns the number of '1' bits it has (also known as the Hamming weight).
-#
-# For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011,
+#
+# For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011,
# so the function should return 3.
#
class Solution:
diff --git a/Python/number-of-boomerangs.py b/Python/number-of-boomerangs.py
index e31756e0f..84ff01205 100644
--- a/Python/number-of-boomerangs.py
+++ b/Python/number-of-boomerangs.py
@@ -1,7 +1,7 @@
# Time: O(n^2)
# Space: O(n)
-# Given n points in the plane that are all pairwise distinct,
+# Given n points in the plane that are all pairwise distinct,
# a "boomerang" is a tuple of points (i, j, k) such that the distance
# between i and j equals the distance between i and k (the order of the tuple matters).
#
@@ -35,11 +35,11 @@ def numberOfBoomerangs(self, points):
continue
dx, dy = points[i][0] - points[j][0], points[i][1] - points[j][1]
group[dx**2 + dy**2] += 1
-
+
for _, v in group.iteritems():
if v > 1:
result += v * (v-1)
-
+
return result
def numberOfBoomerangs2(self, points):
diff --git a/Python/number-of-corner-rectangles.py b/Python/number-of-corner-rectangles.py
index 6dbe75bee..5988e1885 100644
--- a/Python/number-of-corner-rectangles.py
+++ b/Python/number-of-corner-rectangles.py
@@ -7,7 +7,7 @@
# Note that only the corners need to have the value 1. Also, all four 1s used must be distinct.
#
# Example 1:
-# Input: grid =
+# Input: grid =
# [[1, 0, 0, 1, 0],
# [0, 0, 1, 0, 1],
# [0, 0, 0, 1, 0],
@@ -16,7 +16,7 @@
# Explanation: There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].
#
# Example 2:
-# Input: grid =
+# Input: grid =
# [[1, 1, 1],
# [1, 1, 1],
# [1, 1, 1]]
@@ -24,7 +24,7 @@
# Explanation: There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.
#
# Example 3:
-# Input: grid =
+# Input: grid =
# [[1, 1, 1, 1]]
# Output: 0
# Explanation: Rectangles must have four distinct corners.
diff --git a/Python/number-of-distinct-islands-ii.py b/Python/number-of-distinct-islands-ii.py
index 4b1197c5c..49de00acc 100644
--- a/Python/number-of-distinct-islands-ii.py
+++ b/Python/number-of-distinct-islands-ii.py
@@ -34,7 +34,7 @@ def normalize(island):
p[0] -= origin[0]
p[1] -= origin[1]
return min(shapes)
-
+
islands = set()
for i in xrange(len(grid)):
for j in xrange(len(grid[0])):
diff --git a/Python/number-of-islands-ii.py b/Python/number-of-islands-ii.py
index 3c36a265e..c76a1a5df 100644
--- a/Python/number-of-islands-ii.py
+++ b/Python/number-of-islands-ii.py
@@ -20,7 +20,7 @@ def find_set(x):
def union_set(x, y):
x_root, y_root = find_set(x), find_set(y)
set[min(x_root, y_root)] = max(x_root, y_root)
-
+
numbers = []
number = 0
directions = [(0, -1), (0, 1), (-1, 0), (1, 0)]
diff --git a/Python/number-of-islands.py b/Python/number-of-islands.py
index 89bff89d1..6f34748dd 100644
--- a/Python/number-of-islands.py
+++ b/Python/number-of-islands.py
@@ -1,8 +1,8 @@
# Time: O(m * n)
# Space: O(m * n)
#
-# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
-# An island is surrounded by water and is formed by connecting adjacent lands horizontally
+# Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
+# An island is surrounded by water and is formed by connecting adjacent lands horizontally
# or vertically. You may assume all four edges of the grid are all surrounded by water.
#
# Example 1:
@@ -28,9 +28,9 @@ class Solution:
def numIslands(self, grid):
if not grid:
return 0
-
+
row = len(grid)
- col = len(grid[0])
+ col = len(grid[0])
count = 0
for i in xrange(row):
for j in xrange(col):
@@ -43,7 +43,7 @@ def dfs(self, grid, row, col, x, y):
if grid[x][y] == '0':
return
grid[x][y] = '0'
-
+
if x != 0:
self.dfs(grid, row, col, x - 1, y)
if x != row - 1:
diff --git a/Python/number-of-lines-to-write-string.py b/Python/number-of-lines-to-write-string.py
index 886f139c3..b2e047002 100644
--- a/Python/number-of-lines-to-write-string.py
+++ b/Python/number-of-lines-to-write-string.py
@@ -11,22 +11,22 @@
# and what is the width used by the last such line? Return your answer as an integer list of length 2.
#
# Example :
-# Input:
+# Input:
# widths = [10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
# S = "abcdefghijklmnopqrstuvwxyz"
# Output: [3, 60]
#
-# Explanation:
+# Explanation:
# All letters have the same length of 10. To write all 26 letters,
# we need two full lines and one line with 60 units.
# Example :
-# Input:
+# Input:
# widths = [4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10]
# S = "bbbcccdddaaa"
# Output: [2, 4]
#
-# Explanation:
-# All letters except 'a' have the same length of 10, and
+# Explanation:
+# All letters except 'a' have the same length of 10, and
# "bbbcccdddaa" will cover 9 * 10 + 2 * 4 = 98 units.
# For the last 'a', it is written on the second line because
# there is only 2 units left in the first line.
diff --git a/Python/number-of-longest-increasing-subsequence.py b/Python/number-of-longest-increasing-subsequence.py
index 9a45cadb1..3068056a1 100644
--- a/Python/number-of-longest-increasing-subsequence.py
+++ b/Python/number-of-longest-increasing-subsequence.py
@@ -14,7 +14,7 @@
# 5 subsequences' length is 1, so output 5.
# Note: Length of the given array will be not exceed 2000 and the answer is guaranteed
# to be fit in 32-bit signed int.
-
+
class Solution(object):
def findNumberOfLIS(self, nums):
"""
diff --git a/Python/number-of-subarrays-with-bounded-maximum.py b/Python/number-of-subarrays-with-bounded-maximum.py
index 56aaaaffc..17ab89de5 100644
--- a/Python/number-of-subarrays-with-bounded-maximum.py
+++ b/Python/number-of-subarrays-with-bounded-maximum.py
@@ -8,7 +8,7 @@
# such that the value of the maximum array element in that subarray is at least L and at most R.
#
# Example :
-# Input:
+# Input:
# A = [2, 1, 4, 3]
# L = 2
# R = 3
diff --git a/Python/odd-even-linked-list.py b/Python/odd-even-linked-list.py
index 457c48ac3..166f649f1 100644
--- a/Python/odd-even-linked-list.py
+++ b/Python/odd-even-linked-list.py
@@ -15,7 +15,7 @@
#
# Note:
# The relative order inside both the even and odd groups
-# should remain as it was in the input.
+# should remain as it was in the input.
# The first node is considered odd, the second node even
# and so on ...
diff --git a/Python/one-edit-distance.py b/Python/one-edit-distance.py
index 4e11cfe29..25a54f523 100644
--- a/Python/one-edit-distance.py
+++ b/Python/one-edit-distance.py
@@ -16,7 +16,7 @@ def isOneEditDistance(self, s, t):
return self.isOneEditDistance(t, s)
if n - m > 1:
return False
-
+
i, shift = 0, n - m
while i < m and s[i] == t[i]:
i += 1
@@ -24,9 +24,9 @@ def isOneEditDistance(self, s, t):
i += 1
while i < m and s[i] == t[i + shift]:
i += 1
-
+
return i == m
-
+
if __name__ == "__main__":
print Solution().isOneEditDistance("teacher", "acher")
diff --git a/Python/ones-and-zeroes.py b/Python/ones-and-zeroes.py
index 388bf960f..19a0b3f80 100644
--- a/Python/ones-and-zeroes.py
+++ b/Python/ones-and-zeroes.py
@@ -17,7 +17,7 @@
# Input: Array = {"10", "0001", "111001", "1", "0"}, m = 5, n = 3
# Output: 4
#
-# Explanation: This are totally 4 strings can be formed
+# Explanation: This are totally 4 strings can be formed
# by the using of 5 0s and 3 1s, which are “10,”0001”,”1”,”0”
# Example 2:
# Input: Array = {"10", "0", "1"}, m = 1, n = 1
@@ -42,7 +42,7 @@ def findMaxForm(self, strs, m, n):
elif c == '1':
one_count += 1
- for i in reversed(xrange(zero_count, m+1)):
- for j in reversed(xrange(one_count, n+1)):
+ for i in reversed(xrange(zero_count, m+1)):
+ for j in reversed(xrange(one_count, n+1)):
dp[i][j] = max(dp[i][j], dp[i-zero_count][j-one_count]+1)
return dp[m][n]
diff --git a/Python/optimal-division.py b/Python/optimal-division.py
index 0435f174f..5283e2e81 100644
--- a/Python/optimal-division.py
+++ b/Python/optimal-division.py
@@ -13,8 +13,8 @@
# Output: "1000/(100/10/2)"
# Explanation:
# 1000/(100/10/2) = 1000/((100/10)/2) = 200
-# However, the bold parenthesis in "1000/((100/10)/2)" are redundant,
-# since they don't influence the operation priority. So you should return "1000/(100/10/2)".
+# However, the bold parenthesis in "1000/((100/10)/2)" are redundant,
+# since they don't influence the operation priority. So you should return "1000/(100/10/2)".
#
# Other cases:
# 1000/(100/10)/2 = 50
diff --git a/Python/output-contest-matches.py b/Python/output-contest-matches.py
index 1606a031e..8887fbf89 100644
--- a/Python/output-contest-matches.py
+++ b/Python/output-contest-matches.py
@@ -11,4 +11,4 @@ def findContestMatch(self, n):
while len(matches)/2:
matches = ["({},{})".format(matches[i], matches[-i-1]) for i in xrange(len(matches)/2)]
return matches[0]
-
+
diff --git a/Python/pacific-atlantic-water-flow.py b/Python/pacific-atlantic-water-flow.py
index 57a0566e2..628dbe9d6 100644
--- a/Python/pacific-atlantic-water-flow.py
+++ b/Python/pacific-atlantic-water-flow.py
@@ -5,7 +5,7 @@
# each unit cell in a continent, the "Pacific ocean" touches the left and
# top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
#
-# Water can only flow in four directions (up, down, left, or right)
+# Water can only flow in four directions (up, down, left, or right)
# from a cell to another one with height equal or lower.
#
# Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
@@ -17,7 +17,7 @@
#
# Given the following 5x5 matrix:
#
-# Pacific ~ ~ ~ ~ ~
+# Pacific ~ ~ ~ ~ ~
# ~ 1 2 2 3 (5) *
# ~ 3 2 3 (4) (4) *
# ~ 2 4 (5) 3 1 *
@@ -44,13 +44,13 @@ def pacificAtlanticHelper(matrix, x, y, prev_height, prev_val, visited, res):
(visited[x][y] | prev_val) == visited[x][y]:
return
- visited[x][y] |= prev_val
+ visited[x][y] |= prev_val
if visited[x][y] == (PACIFIC | ATLANTIC):
res.append((x, y))
-
+
for d in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
pacificAtlanticHelper(matrix, x + d[0], y + d[1], matrix[x][y], visited[x][y], visited, res)
-
+
if not matrix:
return []
diff --git a/Python/paint-house-ii.py b/Python/paint-house-ii.py
index 724de0c42..18557f1c2 100644
--- a/Python/paint-house-ii.py
+++ b/Python/paint-house-ii.py
@@ -23,7 +23,7 @@ def minCostII(self, costs):
"""
if not costs:
return 0
-
+
n = len(costs)
k = len(costs[0])
min_cost = [costs[0], [0] * k]
diff --git a/Python/paint-house.py b/Python/paint-house.py
index 24e42a96b..d59b581a8 100644
--- a/Python/paint-house.py
+++ b/Python/paint-house.py
@@ -9,9 +9,9 @@ def minCost(self, costs):
"""
if not costs:
return 0
-
+
min_cost = [costs[0], [0, 0, 0]]
-
+
n = len(costs)
for i in xrange(1, n):
min_cost[i % 2][0] = costs[i][0] + \
@@ -33,11 +33,11 @@ def minCost(self, costs):
"""
if not costs:
return 0
-
+
n = len(costs)
for i in xrange(1, n):
costs[i][0] += min(costs[i - 1][1], costs[i - 1][2])
costs[i][1] += min(costs[i - 1][0], costs[i - 1][2])
costs[i][2] += min(costs[i - 1][0], costs[i - 1][1])
-
+
return min(costs[n - 1])
diff --git a/Python/palindrome-number.py b/Python/palindrome-number.py
index f7745350e..91a16269b 100644
--- a/Python/palindrome-number.py
+++ b/Python/palindrome-number.py
@@ -2,15 +2,15 @@
# Space: O(1)
#
# Determine whether an integer is a palindrome. Do this without extra space.
-#
+#
# Some hints:
# Could negative integers be palindromes? (ie, -1)
-#
+#
# If you are thinking of converting the integer to string, note the restriction of using extra space.
-#
-# You could also try reversing an integer. However, if you have solved the problem "Reverse Integer",
+#
+# You could also try reversing an integer. However, if you have solved the problem "Reverse Integer",
# you know that the reversed integer might overflow. How would you handle such case?
-#
+#
# There is a more generic way of solving this problem.
#
@@ -20,12 +20,12 @@ def isPalindrome(self, x):
if x < 0:
return False
copy, reverse = x, 0
-
+
while copy:
reverse *= 10
reverse += copy % 10
copy //= 10
-
+
return x == reverse
if __name__ == "__main__":
diff --git a/Python/palindrome-partitioning-ii.py b/Python/palindrome-partitioning-ii.py
index c2f3d98aa..192c6f0de 100644
--- a/Python/palindrome-partitioning-ii.py
+++ b/Python/palindrome-partitioning-ii.py
@@ -2,9 +2,9 @@
# Space: O(n^2)
#
# Given a string s, partition s such that every substring of the partition is a palindrome.
-#
+#
# Return the minimum cuts needed for a palindrome partitioning of s.
-#
+#
# For example, given s = "aab",
# Return 1 since the palindrome partitioning ["aa","b"] could be produced using 1 cut.
#
@@ -15,13 +15,13 @@ class Solution:
def minCut(self, s):
lookup = [[False for j in xrange(len(s))] for i in xrange(len(s))]
mincut = [len(s) - 1 - i for i in xrange(len(s) + 1)]
-
+
for i in reversed(xrange(len(s))):
for j in xrange(i, len(s)):
if s[i] == s[j] and (j - i < 2 or lookup[i + 1][j - 1]):
lookup[i][j] = True
mincut[i] = min(mincut[i], mincut[j + 1] + 1)
-
+
return mincut[0]
if __name__ == "__main__":
diff --git a/Python/palindrome-partitioning.py b/Python/palindrome-partitioning.py
index fbba4054f..49bec0641 100644
--- a/Python/palindrome-partitioning.py
+++ b/Python/palindrome-partitioning.py
@@ -2,12 +2,12 @@
# Space: O(n^2)
#
# Given a string s, partition s such that every substring of the partition is a palindrome.
-#
+#
# Return all possible palindrome partitioning of s.
-#
+#
# For example, given s = "aab",
# Return
-#
+#
# [
# ["aa","b"],
# ["a","a","b"]
@@ -21,12 +21,12 @@ class Solution:
# @return a list of lists of string
def partition(self, s):
n = len(s)
-
+
is_palindrome = [[0 for j in xrange(n)] for i in xrange(n)]
for i in reversed(xrange(0, n)):
for j in xrange(i, n):
is_palindrome[i][j] = s[i] == s[j] and ((j - i < 2 ) or is_palindrome[i + 1][j - 1])
-
+
sub_partition = [[] for i in xrange(n)]
for i in reversed(xrange(n)):
for j in xrange(i, n):
@@ -36,7 +36,7 @@ def partition(self, s):
sub_partition[i].append([s[i:j + 1]] + p)
else:
sub_partition[i].append([s[i:j + 1]])
-
+
return sub_partition[0]
# Time: O(2^n)
@@ -49,7 +49,7 @@ def partition(self, s):
result = []
self.partitionRecu(result, [], s, 0)
return result
-
+
def partitionRecu(self, result, cur, s, i):
if i == len(s):
result.append(list(cur))
@@ -59,7 +59,7 @@ def partitionRecu(self, result, cur, s, i):
cur.append(s[i: j + 1])
self.partitionRecu(result, cur, s, j + 1)
cur.pop()
-
+
def isPalindrome(self, s):
for i in xrange(len(s) / 2):
if s[i] != s[-(i + 1)]:
diff --git a/Python/palindromic-substrings.py b/Python/palindromic-substrings.py
index 7cc38189e..5f2668515 100644
--- a/Python/palindromic-substrings.py
+++ b/Python/palindromic-substrings.py
@@ -25,7 +25,7 @@ def countSubstrings(self, s):
"""
def manacher(s):
s = '^#' + '#'.join(s) + '#$'
- P = [0] * len(s)
+ P = [0] * len(s)
C, R = 0, 0
for i in xrange(1, len(s) - 1):
i_mirror = 2*C-i
@@ -34,6 +34,6 @@ def manacher(s):
while s[i+1+P[i]] == s[i-1-P[i]]:
P[i] += 1
if i+P[i] > R:
- C, R = i, i+P[i]
+ C, R = i, i+P[i]
return P
return sum((max_len+1)/2 for max_len in manacher(s))
diff --git a/Python/parse-lisp-expression.py b/Python/parse-lisp-expression.py
index e0ecf7b80..24ec81409 100644
--- a/Python/parse-lisp-expression.py
+++ b/Python/parse-lisp-expression.py
@@ -61,7 +61,7 @@
# Explanation: Even though (let x 4 x) has a deeper scope, it is outside the context
# of the final x in the add-expression. That final x will equal 2.
#
-# Input: (let a1 3 b2 (add a1 1) b2)
+# Input: (let a1 3 b2 (add a1 1) b2)
# Output 4
# Explanation: Variable names can contain digits after the first character.
#
diff --git a/Python/partition-list.py b/Python/partition-list.py
index ec5b0a3c1..076f277b8 100644
--- a/Python/partition-list.py
+++ b/Python/partition-list.py
@@ -2,9 +2,9 @@
# Space: O(1)
#
# Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
-#
+#
# You should preserve the original relative order of the nodes in each of the two partitions.
-#
+#
# For example,
# Given 1->4->3->2->5->2 and x = 3,
# return 1->2->2->4->3->5.
@@ -15,7 +15,7 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
@@ -27,7 +27,7 @@ class Solution:
def partition(self, head, x):
dummySmaller, dummyGreater = ListNode(-1), ListNode(-1)
smaller, greater = dummySmaller, dummyGreater
-
+
while head:
if head.val < x:
smaller.next = head
@@ -36,10 +36,10 @@ def partition(self, head, x):
greater.next = head
greater = greater.next
head = head.next
-
+
smaller.next = dummyGreater.next
greater.next = None
-
+
return dummySmaller.next
if __name__ == "__main__":
@@ -51,4 +51,3 @@ def partition(self, head, x):
head.next.next.next.next.next = ListNode(2)
print Solution().partition(head, 3)
-
\ No newline at end of file
diff --git a/Python/partition-to-k-equal-sum-subsets.py b/Python/partition-to-k-equal-sum-subsets.py
index 60ed1b5ce..6dd49fab1 100644
--- a/Python/partition-to-k-equal-sum-subsets.py
+++ b/Python/partition-to-k-equal-sum-subsets.py
@@ -28,15 +28,15 @@ def dfs(nums, target, used, todo, lookup):
for i, num in enumerate(nums) \
if ((used>>i) & 1) == 0 and num <= targ)
return lookup[used]
-
+
total = sum(nums)
if total%k or max(nums) > total//k:
return False
lookup = [None] * (1 << len(nums))
lookup[-1] = True
return dfs(nums, total//k, 0, total, lookup)
-
-
+
+
# Time: O(k^(n-k) * k!)
# Space: O(n)
# DFS solution with pruning.
diff --git a/Python/pascals-triangle-ii.py b/Python/pascals-triangle-ii.py
index 9f7cfd63d..d5aff1748 100644
--- a/Python/pascals-triangle-ii.py
+++ b/Python/pascals-triangle-ii.py
@@ -2,10 +2,10 @@
# Space: O(1)
# Given an index k, return the kth row of the Pascal's triangle.
-#
+#
# For example, given k = 3,
# Return [1,3,3,1].
-#
+#
# Note:
# Could you optimize your algorithm to use only O(k) extra space?
#
diff --git a/Python/pascals-triangle.py b/Python/pascals-triangle.py
index 19b03a607..14194cc75 100644
--- a/Python/pascals-triangle.py
+++ b/Python/pascals-triangle.py
@@ -2,10 +2,10 @@
# Space: O(1)
#
# Given numRows, generate the first numRows of Pascal's triangle.
-#
+#
# For example, given numRows = 5,
# Return
-#
+#
# [
# [1],
# [1,1],
diff --git a/Python/patching-array.py b/Python/patching-array.py
index ce91f1f6e..8b9a681af 100644
--- a/Python/patching-array.py
+++ b/Python/patching-array.py
@@ -11,9 +11,9 @@
# nums = [1, 3], n = 6
# Return 1.
#
-# Combinations of nums are [1], [3], [1,3], which form
+# Combinations of nums are [1], [3], [1,3], which form
# possible sums of: 1, 3, 4.
-# Now if we add/patch 2 to nums, the combinations are:
+# Now if we add/patch 2 to nums, the combinations are:
# [1], [2], [3], [1,3], [2,3], [1,2,3].
# Possible sums are 1, 2, 3, 4, 5, 6, which now covers
# the range [1, 6].
diff --git a/Python/path-sum-ii.py b/Python/path-sum-ii.py
index df35acde8..03a2fbf3a 100644
--- a/Python/path-sum-ii.py
+++ b/Python/path-sum-ii.py
@@ -2,7 +2,7 @@
# Space: O(h), h is height of binary tree
#
# Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
-#
+#
# For example:
# Given the below binary tree and sum = 22,
# 5
@@ -33,21 +33,21 @@ class Solution:
def pathSum(self, root, sum):
return self.pathSumRecu([], [], root, sum)
-
+
def pathSumRecu(self, result, cur, root, sum):
if root is None:
return result
-
+
if root.left is None and root.right is None and root.val == sum:
result.append(cur + [root.val])
return result
-
+
cur.append(root.val)
self.pathSumRecu(result, cur, root.left, sum - root.val)
self.pathSumRecu(result, cur,root.right, sum - root.val)
cur.pop()
return result
-
+
if __name__ == "__main__":
root = TreeNode(5)
diff --git a/Python/path-sum.py b/Python/path-sum.py
index b24c951a1..70040766d 100644
--- a/Python/path-sum.py
+++ b/Python/path-sum.py
@@ -1,9 +1,9 @@
# Time: O(n)
# Space: O(h), h is height of binary tree
#
-# Given a binary tree and a sum, determine if the tree has a root-to-leaf path
+# Given a binary tree and a sum, determine if the tree has a root-to-leaf path
# such that adding up all the values along the path equals the given sum.
-#
+#
# For example:
# Given the below binary tree and sum = 22,
# 5
@@ -22,7 +22,7 @@ def __init__(self, x):
self.val = x
self.left = None
self.right = None
-
+
class Solution:
# @param root, a tree node
# @param sum, an integer
@@ -30,12 +30,12 @@ class Solution:
def hasPathSum(self, root, sum):
if root is None:
return False
-
+
if root.left is None and root.right is None and root.val == sum:
return True
-
+
return self.hasPathSum(root.left, sum - root.val) or self.hasPathSum(root.right, sum - root.val)
-
+
if __name__ == "__main__":
root = TreeNode(5)
root.left = TreeNode(4)
diff --git a/Python/peeking-iterator.py b/Python/peeking-iterator.py
index f21db1fa3..f59311e0d 100644
--- a/Python/peeking-iterator.py
+++ b/Python/peeking-iterator.py
@@ -48,7 +48,7 @@ def __init__(self, iterator):
self.val_ = None
self.has_next_ = iterator.hasNext()
self.has_peeked_ = False
-
+
def peek(self):
"""
diff --git a/Python/perfect-number.py b/Python/perfect-number.py
index a3fefe5b5..d8d9f30cc 100644
--- a/Python/perfect-number.py
+++ b/Python/perfect-number.py
@@ -4,7 +4,7 @@
# We define the Perfect Number is a positive integer that is equal
# to the sum of all its positive divisors except itself.
#
-# Now, given an integer n, write a function that returns true
+# Now, given an integer n, write a function that returns true
# when it is a perfect number and false when it is not.
# Example:
# Input: 28
@@ -20,7 +20,7 @@ def checkPerfectNumber(self, num):
"""
if num <= 0:
return False
-
+
sqrt_num = int(num ** 0.5)
total = sum(i+num//i for i in xrange(1, sqrt_num+1) if num%i == 0)
if sqrt_num ** 2 == num:
diff --git a/Python/perfect-rectangle.py b/Python/perfect-rectangle.py
index 7a3822f41..3cd7e513b 100644
--- a/Python/perfect-rectangle.py
+++ b/Python/perfect-rectangle.py
@@ -1,11 +1,11 @@
# Time: O(n)
# Space: O(n)
-# Given N axis-aligned rectangles where N > 0,
+# Given N axis-aligned rectangles where N > 0,
# determine if they all together form an exact cover of a rectangular region.
#
-# Each rectangle is represented as a bottom-left point and a top-right point.
-# For example, a unit square is represented as [1,1,2,2].
+# Each rectangle is represented as a bottom-left point and a top-right point.
+# For example, a unit square is represented as [1,1,2,2].
# (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
#
# Example 1:
diff --git a/Python/perfect-squares.py b/Python/perfect-squares.py
index 2cee23f58..2201bc73b 100644
--- a/Python/perfect-squares.py
+++ b/Python/perfect-squares.py
@@ -1,7 +1,7 @@
# Time: O(n * sqrt(n))
# Space: O(n)
#
-# Given a positive integer n, find the least number of perfect
+# Given a positive integer n, find the least number of perfect
# square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
#
# For example, given n = 12, return 3 because 12 = 4 + 4 + 4;
diff --git a/Python/permutation-sequence.py b/Python/permutation-sequence.py
index cc8b59603..9382f662c 100644
--- a/Python/permutation-sequence.py
+++ b/Python/permutation-sequence.py
@@ -2,10 +2,10 @@
# Space: O(n)
# The set [1,2,3,...,n] contains a total of n! unique permutations.
-#
+#
# By listing and labeling all of the permutations in order,
# We get the following sequence (ie, for n = 3):
-#
+#
# "123"
# "132"
# "213"
@@ -13,7 +13,7 @@
# "312"
# "321"
# Given n and k, return the kth permutation sequence.
-#
+#
# Note: Given n will be between 1 and 9 inclusive.
import math
@@ -37,6 +37,6 @@ def getPermutation(self, n, k):
fact /= i
return seq
-
+
if __name__ == "__main__":
print Solution().getPermutation(3, 2)
diff --git a/Python/permutations-ii.py b/Python/permutations-ii.py
index 2b98e265c..17a03fd77 100644
--- a/Python/permutations-ii.py
+++ b/Python/permutations-ii.py
@@ -2,7 +2,7 @@
# Space: O(n)
#
# Given a collection of numbers that might contain duplicates, return all possible unique permutations.
-#
+#
# For example,
# [1,1,2] have the following unique permutations:
# [1,1,2], [1,2,1], and [2,1,1].
@@ -19,7 +19,7 @@ def permuteUnique(self, nums):
used = [False] * len(nums)
self.permuteUniqueRecu(result, used, [], nums)
return result
-
+
def permuteUniqueRecu(self, result, used, cur, nums):
if len(cur) == len(nums):
result.append(cur + [])
@@ -32,13 +32,13 @@ def permuteUniqueRecu(self, result, used, cur, nums):
self.permuteUniqueRecu(result, used, cur, nums)
cur.pop()
used[i] = False
-
+
class Solution2:
# @param num, a list of integer
# @return a list of lists of integers
def permuteUnique(self, nums):
solutions = [[]]
-
+
for num in nums:
next = []
for solution in solutions:
@@ -46,9 +46,9 @@ def permuteUnique(self, nums):
candidate = solution[:i] + [num] + solution[i:]
if candidate not in next:
next.append(candidate)
-
- solutions = next
-
+
+ solutions = next
+
return solutions
if __name__ == "__main__":
diff --git a/Python/permutations.py b/Python/permutations.py
index c615f05aa..0a56829ca 100644
--- a/Python/permutations.py
+++ b/Python/permutations.py
@@ -2,7 +2,7 @@
# Space: O(n)
#
# Given a collection of numbers, return all possible permutations.
-#
+#
# For example,
# [1,2,3] have the following permutations:
# [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
@@ -17,7 +17,7 @@ def permute(self, num):
used = [False] * len(num)
self.permuteRecu(result, used, [], num)
return result
-
+
def permuteRecu(self, result, used, cur, num):
if len(cur) == len(num):
result.append(cur[:])
diff --git a/Python/populating-next-right-pointers-in-each-node-ii.py b/Python/populating-next-right-pointers-in-each-node-ii.py
index e4f206e2f..2029f3293 100644
--- a/Python/populating-next-right-pointers-in-each-node-ii.py
+++ b/Python/populating-next-right-pointers-in-each-node-ii.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# Follow up for problem "Populating Next Right Pointers in Each Node".
-#
+#
# What if the given tree could be any binary tree? Would your previous solution still work?
-#
+#
# Note:
-#
+#
# You may only use constant extra space.
# For example,
# Given the following binary tree,
@@ -30,7 +30,7 @@ def __init__(self, x):
self.left = None
self.right = None
self.next = None
-
+
def __repr__(self):
if self is None:
return "Nil"
@@ -50,21 +50,21 @@ def connect(self, root):
next_head = cur.left
elif cur.right:
next_head = cur.right
-
+
if cur.left:
if prev:
prev.next = cur.left
prev = cur.left
-
+
if cur.right:
if prev:
prev.next = cur.right
prev = cur.right
-
+
cur = cur.next
head = next_head
-
-
+
+
if __name__ == "__main__":
root, root.left, root.right = TreeNode(1), TreeNode(2), TreeNode(3)
@@ -73,4 +73,3 @@ def connect(self, root):
print root
print root.left
print root.left.left
-
\ No newline at end of file
diff --git a/Python/populating-next-right-pointers-in-each-node.py b/Python/populating-next-right-pointers-in-each-node.py
index 79b50a7d8..54d7a63fc 100644
--- a/Python/populating-next-right-pointers-in-each-node.py
+++ b/Python/populating-next-right-pointers-in-each-node.py
@@ -2,18 +2,18 @@
# Space: O(1)
#
# Given a binary tree
-#
+#
# struct TreeLinkNode {
# TreeLinkNode *left;
# TreeLinkNode *right;
# TreeLinkNode *next;
# }
# Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
-#
+#
# Initially, all next pointers are set to NULL.
-#
+#
# Note:
-#
+#
# You may only use constant extra space.
# You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
# For example,
@@ -37,7 +37,7 @@ def __init__(self, x):
self.left = None
self.right = None
self.next = None
-
+
def __repr__(self):
if self is None:
return "Nil"
@@ -81,4 +81,4 @@ def connect(self, root):
print root
print root.left
print root.left.left
-
+
diff --git a/Python/pour-water.py b/Python/pour-water.py
index 7d331cac1..2b13679e8 100644
--- a/Python/pour-water.py
+++ b/Python/pour-water.py
@@ -33,7 +33,7 @@
# # w #
# ## # ###
# #########
-# 0123456
+# 0123456
#
# When moving left or right, the water can only move to the same level or a lower level.
# (By level, we mean the total height of the terrain plus any water in that column.)
@@ -44,7 +44,7 @@
# # #
# ## w# ###
# #########
-# 0123456
+# 0123456
#
# Since moving left will not make it fall, it stays in place. The next droplet falls:
#
@@ -52,7 +52,7 @@
# # w #
# ## w# ###
# #########
-# 0123456
+# 0123456
#
# Since the new droplet moving left will eventually make it fall, it moves left.
# Notice that the droplet still preferred to move left,
@@ -62,13 +62,13 @@
# # w #
# ## w# ###
# #########
-# 0123456
+# 0123456
#
# # #
# # #
# ##ww# ###
# #########
-# 0123456
+# 0123456
#
# After those steps, the third droplet falls.
# Since moving left would not eventually make it fall, it tries to move right.
@@ -78,13 +78,13 @@
# # w #
# ##ww# ###
# #########
-# 0123456
+# 0123456
#
# # #
# # #
# ##ww#w###
# #########
-# 0123456
+# 0123456
#
# Finally, the fourth droplet falls.
# Since moving left would not eventually make it fall, it tries to move right.
@@ -94,14 +94,14 @@
# # w #
# ##ww#w###
# #########
-# 0123456
+# 0123456
#
# The final answer is [2,2,2,3,2,2,2]:
#
-# #
-# #######
-# #######
-# 0123456
+# #
+# #######
+# #######
+# 0123456
#
# Example 2:
# Input: heights = [1,2,3,4], V = 2, K = 2
diff --git a/Python/power-of-three.py b/Python/power-of-three.py
index 02f90144b..e81d1873e 100644
--- a/Python/power-of-three.py
+++ b/Python/power-of-three.py
@@ -21,7 +21,7 @@ def isPowerOfThree(self, n):
"""
return n > 0 and self.__max_pow3 % n == 0
-
+
class Solution2(object):
def isPowerOfThree(self, n):
return n > 0 and (math.log10(n)/math.log10(3)).is_integer()
diff --git a/Python/predict-the-winner.py b/Python/predict-the-winner.py
index b64a44cf3..6c871ef7a 100644
--- a/Python/predict-the-winner.py
+++ b/Python/predict-the-winner.py
@@ -13,10 +13,10 @@
# Example 1:
# Input: [1, 5, 2]
# Output: False
-# Explanation: Initially, player 1 can choose between 1 and 2.
+# Explanation: Initially, player 1 can choose between 1 and 2.
# If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5.
-# If player 2 chooses 5, then player 1 will be left with 1 (or 2).
-# So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
+# If player 2 chooses 5, then player 1 will be left with 1 (or 2).
+# So, final score of player 1 is 1 + 2 = 3, and player 2 is 5.
# Hence, player 1 will never be the winner and you need to return False.
# Example 2:
# Input: [1, 5, 233, 7]
@@ -45,4 +45,4 @@ def PredictTheWinner(self, nums):
dp[j] = max(nums[i] - dp[j], nums[j] - dp[j - 1])
return dp[-1] >= 0
-
+
diff --git a/Python/prime-number-of-set-bits-in-binary-representation.py b/Python/prime-number-of-set-bits-in-binary-representation.py
index ce38e8afd..f843f9714 100644
--- a/Python/prime-number-of-set-bits-in-binary-representation.py
+++ b/Python/prime-number-of-set-bits-in-binary-representation.py
@@ -14,7 +14,7 @@ def bitCount(n):
n &= n-1
result += 1
return result
-
+
primes = {2, 3, 5, 7, 11, 13, 17, 19}
return sum(bitCount(i) in primes
for i in xrange(L, R+1))
diff --git a/Python/print-binary-tree.py b/Python/print-binary-tree.py
index 33b00ff1d..9d7fd5460 100644
--- a/Python/print-binary-tree.py
+++ b/Python/print-binary-tree.py
@@ -38,10 +38,10 @@
# 1
# / \
# 2 5
-# /
-# 3
-# /
-# 4
+# /
+# 3
+# /
+# 4
# Output:
#
# [["", "", "", "", "", "", "", "1", "", "", "", "", "", "", ""]
@@ -49,7 +49,7 @@
# ["", "3", "", "", "", "", "", "", "", "", "", "", "", "", ""]
# ["4", "", "", "", "", "", "", "", "", "", "", "", "", "", ""]]
# Note: The height of binary tree is in the range of [1, 10].
-#
+#
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
@@ -72,7 +72,7 @@ def getHeight(root):
if not root:
return 0
return max(getHeight(root.left), getHeight(root.right)) + 1
-
+
def preorderTraversal(root, level, left, right, result):
if not root:
return
diff --git a/Python/product-of-array-except-self.py b/Python/product-of-array-except-self.py
index f9646d83a..02b3e1a83 100644
--- a/Python/product-of-array-except-self.py
+++ b/Python/product-of-array-except-self.py
@@ -22,11 +22,11 @@ class Solution:
def productExceptSelf(self, nums):
if not nums:
return []
-
+
left_product = [1 for _ in xrange(len(nums))]
for i in xrange(1, len(nums)):
left_product[i] = left_product[i - 1] * nums[i - 1]
-
+
right_product = 1
for i in xrange(len(nums) - 2, -1, -1):
right_product *= nums[i + 1]
diff --git a/Python/pyramid-transition-matrix.py b/Python/pyramid-transition-matrix.py
index 413a4df90..6c3073b3d 100644
--- a/Python/pyramid-transition-matrix.py
+++ b/Python/pyramid-transition-matrix.py
@@ -1,6 +1,6 @@
-# Time: O((a^(b+1)-a)/(a-1)) = O(a^b) , a is the size of allowed,
+# Time: O((a^(b+1)-a)/(a-1)) = O(a^b) , a is the size of allowed,
# b is the length of bottom
-# Space: O((a^(b+1)-a)/(a-1)) = O(a^b)
+# Space: O((a^(b+1)-a)/(a-1)) = O(a^b)
# We are stacking blocks to form a pyramid. Each block has a color which is a one letter string, like `'Z'`.
#
@@ -55,7 +55,7 @@ def dfs(bottom, edges, new_bottom, idx, lookup):
if dfs(bottom, edges, new_bottom, idx+1, lookup):
return True
return False
-
+
if len(bottom) == 1:
return True
if bottom in lookup:
@@ -66,7 +66,7 @@ def dfs(bottom, edges, new_bottom, idx, lookup):
return False
new_bottom = ['A']*(len(bottom)-1)
return dfs(bottom, edges, new_bottom, 0, lookup)
-
+
edges = [[[] for _ in xrange(7)] for _ in xrange(7)]
for s in allowed:
edges[ord(s[0])-ord('A')][ord(s[1])-ord('A')].append(ord(s[2])-ord('A'))
diff --git a/Python/queue-reconstruction-by-height.py b/Python/queue-reconstruction-by-height.py
index 7863a79ff..afd5f76cd 100644
--- a/Python/queue-reconstruction-by-height.py
+++ b/Python/queue-reconstruction-by-height.py
@@ -1,8 +1,8 @@
# Time: O(n * sqrt(n))
# Space: O(n)
-# Suppose you have a random list of people standing in a queue.
-# Each person is described by a pair of integers (h, k),
+# Suppose you have a random list of people standing in a queue.
+# Each person is described by a pair of integers (h, k),
# where h is the height of the person and k is the number of people
# in front of this person who have a height greater than or equal to h.
# Write an algorithm to reconstruct the queue.
@@ -29,7 +29,7 @@ def reconstructQueue(self, people):
blocks = [[]]
for p in people:
index = p[1]
-
+
for i, block in enumerate(blocks):
if index <= len(block):
break
@@ -39,7 +39,7 @@ def reconstructQueue(self, people):
if len(block) * len(block) > len(people):
blocks.insert(i+1, block[len(block)/2:])
del block[len(block)/2:]
-
+
return [p for block in blocks for p in block]
diff --git a/Python/random-pick-index.py b/Python/random-pick-index.py
index f8034c6da..b812c932e 100644
--- a/Python/random-pick-index.py
+++ b/Python/random-pick-index.py
@@ -27,7 +27,7 @@ class Solution(object):
def __init__(self, nums):
"""
-
+
:type nums: List[int]
:type numsSize: int
"""
diff --git a/Python/range-addition-ii.py b/Python/range-addition-ii.py
index e63e660d6..641bff3db 100644
--- a/Python/range-addition-ii.py
+++ b/Python/range-addition-ii.py
@@ -11,22 +11,22 @@
# in the matrix after performing all the operations.
#
# Example 1:
-# Input:
+# Input:
# m = 3, n = 3
# operations = [[2,2],[3,3]]
# Output: 4
-# Explanation:
-# Initially, M =
+# Explanation:
+# Initially, M =
# [[0, 0, 0],
# [0, 0, 0],
# [0, 0, 0]]
#
-# After performing [2,2], M =
+# After performing [2,2], M =
# [[1, 1, 0],
# [1, 1, 0],
# [0, 0, 0]]
#
-# After performing [3,3], M =
+# After performing [3,3], M =
# [[2, 2, 1],
# [2, 2, 1],
# [1, 1, 1]]
diff --git a/Python/range-sum-query-2d-immutable.py b/Python/range-sum-query-2d-immutable.py
index 786f74939..91e444fd6 100644
--- a/Python/range-sum-query-2d-immutable.py
+++ b/Python/range-sum-query-2d-immutable.py
@@ -57,7 +57,7 @@ def sumRegion(self, row1, col1, row2, col2):
"""
return self.__sums[row2+1][col2+1] - self.__sums[row2+1][col1] - \
self.__sums[row1][col2+1] + self.__sums[row1][col1]
-
+
# Your NumMatrix object will be instantiated and called as such:
# numMatrix = NumMatrix(matrix)
diff --git a/Python/range-sum-query-immutable.py b/Python/range-sum-query-immutable.py
index a5c6d7775..b3b503b53 100644
--- a/Python/range-sum-query-immutable.py
+++ b/Python/range-sum-query-immutable.py
@@ -22,18 +22,18 @@ def __init__(self, nums):
:type nums: List[int]
"""
self.accu = [0]
- for num in nums:
+ for num in nums:
self.accu.append(self.accu[-1] + num),
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
- :type i: int
+ :type i: int
:type j: int
- :rtype: int
+ :rtype: int
"""
return self.accu[j + 1] - self.accu[i]
-
+
# Your NumArray object will be instantiated and called as such:
# numArray = NumArray(nums)
diff --git a/Python/range-sum-query-mutable.py b/Python/range-sum-query-mutable.py
index d9b7db624..5e8ed8136 100644
--- a/Python/range-sum-query-mutable.py
+++ b/Python/range-sum-query-mutable.py
@@ -3,7 +3,7 @@
# query: O(logn)
# Space: O(n)
-# Given an integer array nums, find the sum of
+# Given an integer array nums, find the sum of
# the elements between indices i and j (i <= j), inclusive.
#
# The update(i, val) function modifies nums by
@@ -46,7 +46,7 @@ def update(self, i, val):
if val - self.__nums[i]:
self.__add(i, val - self.__nums[i])
self.__nums[i] = val
-
+
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
@@ -87,21 +87,21 @@ def __init__(self, nums):
def buildHelper(nums, start, end):
if start > end:
return None
-
+
# The root's start and end is given by build method.
root = self._SegmentTreeNode(start, end, 0)
-
+
# If start equals to end, there will be no children for this node.
if start == end:
root.sum = nums[start]
return root
-
+
# Left child: start=nums.left, end=(nums.left + nums.right) / 2.
root.left = buildHelper(nums, start, (start + end) / 2)
-
+
# Right child: start=(nums.left + nums.right) / 2 + 1, end=nums.right.
root.right = buildHelper(nums, (start + end) / 2 + 1, end)
-
+
# Update sum.
root.sum = (root.left.sum if root.left else 0) + \
(root.right.sum if root.right else 0)
@@ -119,22 +119,22 @@ def updateHelper(root, i, val):
# Out of range.
if not root or root.start > i or root.end < i:
return
-
+
# Change the node's value with [i] to the new given value.
if root.start == i and root.end == i:
root.sum = val
return
-
+
updateHelper(root.left, i, val)
updateHelper(root.right, i, val)
-
+
# Update sum.
root.sum = (root.left.sum if root.left else 0) + \
(root.right.sum if root.right else 0)
if self.__nums[i] != val:
self.__nums[i] = val
updateHelper(self.__root, i, val)
-
+
def sumRange(self, i, j):
"""
sum of elements nums[i..j], inclusive.
diff --git a/Python/ransom-note.py b/Python/ransom-note.py
index 917334555..0d175fdd4 100644
--- a/Python/ransom-note.py
+++ b/Python/ransom-note.py
@@ -4,7 +4,7 @@
# Given an arbitrary ransom note string and another string containing letters
# from all the magazines, write a function that will return true if
# the ransom note can be constructed from the magazines ;
-# otherwise, it will return false.
+# otherwise, it will return false.
#
# Each letter in the magazine string can only be used once in your ransom note.
#
diff --git a/Python/read-n-characters-given-read4-ii-call-multiple-times.py b/Python/read-n-characters-given-read4-ii-call-multiple-times.py
index 2645c5fd0..70dccb689 100644
--- a/Python/read-n-characters-given-read4-ii-call-multiple-times.py
+++ b/Python/read-n-characters-given-read4-ii-call-multiple-times.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# The API: int read4(char *buf) reads 4 characters at a time from a file.
-#
+#
# The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
-#
+#
# By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
-#
+#
# Note:
# The read function may be called multiple times.
#
@@ -20,13 +20,13 @@ def read4(buf):
while i < len(file_content) and i < 4:
buf[i] = file_content[i]
i += 1
-
+
if len(file_content) > 4:
file_content = file_content[4:]
else:
file_content = ""
return i
-
+
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
@@ -37,7 +37,7 @@ def __init__(self):
self.__buf4 = [''] * 4
self.__i4 = 0
self.__n4 = 0
-
+
def read(self, buf, n):
"""
:type buf: Destination buffer (List[str])
@@ -56,7 +56,7 @@ def read(self, buf, n):
self.__i4 = 0
else: # Buffer has been empty.
break
-
+
return i
if __name__ == "__main__":
@@ -65,4 +65,4 @@ def read(self, buf, n):
buf = ['' for _ in xrange(100)]
file_content = "ab"
print buf[:sol.read(buf, 1)]
- print buf[:sol.read(buf, 2)]
+ print buf[:sol.read(buf, 2)]
diff --git a/Python/read-n-characters-given-read4.py b/Python/read-n-characters-given-read4.py
index 1581cca20..2c754e9f7 100644
--- a/Python/read-n-characters-given-read4.py
+++ b/Python/read-n-characters-given-read4.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# The API: int read4(char *buf) reads 4 characters at a time from a file.
-#
+#
# The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
-#
+#
# By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
-#
+#
# Note:
# The read function will only be called once for each test case.
#
@@ -20,13 +20,13 @@ def read4(buf):
while i < len(file_content) and i < 4:
buf[i] = file_content[i]
i += 1
-
+
if len(file_content) > 4:
file_content = file_content[4:]
else:
file_content = ""
return i
-
+
class Solution(object):
def read(self, buf, n):
"""
@@ -49,6 +49,6 @@ def read(self, buf, n):
global file_content
buf = ['' for _ in xrange(100)]
file_content = "a"
- print buf[:Solution().read(buf, 9)]
+ print buf[:Solution().read(buf, 9)]
file_content = "abcdefghijklmnop"
print buf[:Solution().read(buf, 9)]
diff --git a/Python/reconstruct-original-digits-from-english.py b/Python/reconstruct-original-digits-from-english.py
index ff7797bde..eb67abeab 100644
--- a/Python/reconstruct-original-digits-from-english.py
+++ b/Python/reconstruct-original-digits-from-english.py
@@ -30,10 +30,10 @@ def originalDigits(self, s):
cnts = [Counter(_) for _ in ["zero", "one", "two", "three", \
"four", "five", "six", "seven", \
"eight", "nine"]]
-
+
# The order for greedy method.
order = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
-
+
# The unique char in the order.
unique_chars = ['z', 'o', 'w', 't', 'u', \
'f', 'x', 's', 'g', 'n']
diff --git a/Python/recover-binary-search-tree.py b/Python/recover-binary-search-tree.py
index 0cc9ddda1..073967d9e 100644
--- a/Python/recover-binary-search-tree.py
+++ b/Python/recover-binary-search-tree.py
@@ -2,9 +2,9 @@
# Space: O(1)
#
# Two elements of a binary search tree (BST) are swapped by mistake.
-#
+#
# Recover the tree without changing its structure.
-#
+#
# Note:
# A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
#
@@ -14,8 +14,8 @@ class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
- self.right = None
-
+ self.right = None
+
def __repr__(self):
if self:
serial = []
@@ -23,21 +23,21 @@ def __repr__(self):
while queue:
cur = queue[0]
-
+
if cur:
serial.append(cur.val)
queue.append(cur.left)
queue.append(cur.right)
else:
serial.append("#")
-
+
queue = queue[1:]
-
+
while serial[-1] == "#":
serial.pop()
-
+
return repr(serial)
-
+
else:
return None
@@ -46,13 +46,13 @@ class Solution:
# @return a tree node
def recoverTree(self, root):
return self.MorrisTraversal(root)
-
+
def MorrisTraversal(self, root):
if root is None:
return
broken = [None, None]
pre, cur = None, root
-
+
while cur:
if cur.left is None:
self.detectBroken(broken, pre, cur)
@@ -62,7 +62,7 @@ def MorrisTraversal(self, root):
node = cur.left
while node.right and node.right != cur:
node = node.right
-
+
if node.right is None:
node.right =cur
cur = cur.left
@@ -71,20 +71,19 @@ def MorrisTraversal(self, root):
node.right = None
pre = cur
cur = cur.right
-
+
broken[0].val, broken[1].val = broken[1].val, broken[0].val
-
+
return root
-
+
def detectBroken(self, broken, pre, cur):
if pre and pre.val > cur.val:
if broken[0] is None:
broken[0] = pre
broken[1] = cur
-
+
if __name__ == "__main__":
root = TreeNode(0)
root.left = TreeNode(1)
print root
print Solution().recoverTree(root)
-
\ No newline at end of file
diff --git a/Python/redundant-connection-ii.py b/Python/redundant-connection-ii.py
index 39f86635f..79e613c68 100644
--- a/Python/redundant-connection-ii.py
+++ b/Python/redundant-connection-ii.py
@@ -56,7 +56,7 @@ def union_set(self, x, y):
self.count -= 1
return True
-
+
class Solution(object):
def findRedundantDirectedConnection(self, edges):
"""
diff --git a/Python/redundant-connection.py b/Python/redundant-connection.py
index c26efe3dd..c490e4743 100644
--- a/Python/redundant-connection.py
+++ b/Python/redundant-connection.py
@@ -59,4 +59,4 @@ def findRedundantConnection(self, edges):
if not union_find.union_set(*edge):
return edge
return []
-
+
diff --git a/Python/regular-expression-matching.py b/Python/regular-expression-matching.py
index 3101c52c7..ef240b84a 100644
--- a/Python/regular-expression-matching.py
+++ b/Python/regular-expression-matching.py
@@ -2,15 +2,15 @@
# Space: O(n)
#
# Implement regular expression matching with support for '.' and '*'.
-#
+#
# '.' Matches any single character.
# '*' Matches zero or more of the preceding element.
-#
+#
# The matching should cover the entire input string (not partial).
-#
+#
# The function prototype should be:
# bool isMatch(const char *s, const char *p)
-#
+#
# Some examples:
# isMatch("aa","a") -> false
# isMatch("aa","aa") -> true
@@ -27,12 +27,12 @@ class Solution:
def isMatch(self, s, p):
k = 3
result = [[False for j in xrange(len(p) + 1)] for i in xrange(k)]
-
+
result[0][0] = True
for i in xrange(2, len(p) + 1):
if p[i-1] == '*':
result[0][i] = result[0][i-2]
-
+
for i in xrange(1,len(s) + 1):
if i > 1:
result[0][0] = False
@@ -41,7 +41,7 @@ def isMatch(self, s, p):
result[i % k][j] = result[(i-1) % k][j-1] and (s[i-1] == p[j-1] or p[j-1] == '.')
else:
result[i % k][j] = result[i % k][j-2] or (result[(i-1) % k][j] and (s[i-1] == p[j-2] or p[j-2] == '.'))
-
+
return result[len(s) % k][len(p)]
# dp
@@ -51,19 +51,19 @@ class Solution2:
# @return a boolean
def isMatch(self, s, p):
result = [[False for j in xrange(len(p) + 1)] for i in xrange(len(s) + 1)]
-
+
result[0][0] = True
for i in xrange(2, len(p) + 1):
if p[i-1] == '*':
result[0][i] = result[0][i-2]
-
+
for i in xrange(1,len(s) + 1):
for j in xrange(1, len(p) + 1):
if p[j-1] != '*':
result[i][j] = result[i-1][j-1] and (s[i-1] == p[j-1] or p[j-1] == '.')
else:
result[i][j] = result[i][j-2] or (result[i-1][j] and (s[i-1] == p[j-2] or p[j-2] == '.'))
-
+
return result[len(s)][len(p)]
# iteration
@@ -84,7 +84,7 @@ def isMatch(self, s, p):
[last_s_ptr, last_p_ptr] = last_ptr.pop()
while last_ptr and p[last_p_ptr - 2] != s[last_s_ptr] and p[last_p_ptr - 2] != '.':
[last_s_ptr, last_p_ptr] = last_ptr.pop()
-
+
if p[last_p_ptr - 2] == s[last_s_ptr] or p[last_p_ptr - 2] == '.':
last_s_ptr += 1
s_ptr = last_s_ptr
@@ -94,19 +94,19 @@ def isMatch(self, s, p):
return False
else:
return False
-
+
while p_ptr < len(p) - 1 and p[p_ptr] == '.' and p[p_ptr + 1] == '*':
p_ptr += 2
-
+
return p_ptr == len(p)
-
+
# recursive
class Solution4:
# @return a boolean
def isMatch(self, s, p):
if not p:
return not s
-
+
if len(p) == 1 or p[1] != '*':
if len(s) > 0 and (p[0] == s[0] or p[0] == '.'):
return self.isMatch(s[1:], p[1:])
diff --git a/Python/relative-ranks.py b/Python/relative-ranks.py
index 3b32dd9a4..35b12842f 100644
--- a/Python/relative-ranks.py
+++ b/Python/relative-ranks.py
@@ -9,7 +9,7 @@
# Input: [5, 4, 3, 2, 1]
# Output: ["Gold Medal", "Silver Medal", "Bronze Medal", "4", "5"]
# Explanation: The first three athletes got the top three highest scores,
-# so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
+# so they got "Gold Medal", "Silver Medal" and "Bronze Medal".
# For the left two athletes, you just need to output
# their relative ranks according to their scores.
# Note:
diff --git a/Python/remove-9.py b/Python/remove-9.py
index ec7ad01e3..234f57714 100644
--- a/Python/remove-9.py
+++ b/Python/remove-9.py
@@ -1,6 +1,6 @@
# Time: O(logn)
# Space: O(1)
-
+
class Solution(object):
def newInteger(self, n):
"""
diff --git a/Python/remove-boxes.py b/Python/remove-boxes.py
index a34b96d6a..e1012647e 100644
--- a/Python/remove-boxes.py
+++ b/Python/remove-boxes.py
@@ -1,7 +1,7 @@
# Time: O(n^3) ~ O(n^4)
# Space: O(n^3)
-# Given several boxes with different colors represented by different positive numbers.
+# Given several boxes with different colors represented by different positive numbers.
# You may experience several rounds to remove boxes until there is no box left.
# Each time you can choose some continuous boxes with the same color (composed of k boxes, k >= 1),
# remove them and get k*k points.
@@ -14,10 +14,10 @@
# Output:
# 23
# Explanation:
-# [1, 3, 2, 2, 2, 3, 4, 3, 1]
-# ----> [1, 3, 3, 4, 3, 1] (3*3=9 points)
-# ----> [1, 3, 3, 3, 1] (1*1=1 points)
-# ----> [1, 1] (3*3=9 points)
+# [1, 3, 2, 2, 2, 3, 4, 3, 1]
+# ----> [1, 3, 3, 4, 3, 1] (3*3=9 points)
+# ----> [1, 3, 3, 3, 1] (1*1=1 points)
+# ----> [1, 1] (3*3=9 points)
# ----> [] (2*2=4 points)
# Note: The number of boxes n would not exceed 100.
diff --git a/Python/remove-comments.py b/Python/remove-comments.py
index 5b8707e0e..57895225a 100644
--- a/Python/remove-comments.py
+++ b/Python/remove-comments.py
@@ -11,15 +11,15 @@
# rest of the characters to the right of it in the same line should be ignored.
#
# The string /* denotes a block comment,
-# which represents that all characters until the next (non-overlapping) occurrence of */
-# should be ignored. (Here, occurrences happen in reading order: line by line from left to right.)
+# which represents that all characters until the next (non-overlapping) occurrence of */
+# should be ignored. (Here, occurrences happen in reading order: line by line from left to right.)
# To be clear, the string /*/ does not yet end the block comment, as the ending would be overlapping the beginning.
#
# The first effective comment takes precedence over others:
# if the string // occurs in a block comment, it is ignored.
# Similarly, if the string /* occurs in a line or block comment, it is also ignored.
#
-# If a certain line of code is empty after removing comments,
+# If a certain line of code is empty after removing comments,
# you must not output that line: each string in the answer list will be non-empty.
#
# There will be no control characters, single quote, or double quote characters.
@@ -34,18 +34,18 @@
# After removing the comments from the source code, return the source code in the same format.
#
# Example 1:
-# Input:
+# Input:
# source = ["/*Test program */", "int main()", "{ ", " // variable declaration ", "int a, b, c;", "/* This is a test", " multiline ", " comment for ", " testing */", "a = b + c;", "}"]
#
# The line by line code is visualized as below:
# /*Test program */
# int main()
-# {
-# // variable declaration
+# {
+# // variable declaration
# int a, b, c;
# /* This is a test
-# multiline
-# comment for
+# multiline
+# comment for
# testing */
# a = b + c;
# }
@@ -54,19 +54,19 @@
#
# The line by line code is visualized as below:
# int main()
-# {
+# {
# int a, b, c;
# a = b + c;
# }
-# Explanation:
-# The string
+# Explanation:
+# The string
# /*
-# denotes a block comment, including line 1 and lines 6-9. The string
+# denotes a block comment, including line 1 and lines 6-9. The string
# //
# denotes line 4 as comments.
#
# Example 2:
-# Input:
+# Input:
# source = ["a/*comment", "line", "more_comment*/b"]
# Output: ["ab"]
# Explanation: The original source string is "a/*comment\nline\nmore_comment*/b",
diff --git a/Python/remove-duplicates-from-sorted-array-ii.py b/Python/remove-duplicates-from-sorted-array-ii.py
index 794b192ae..104161e0a 100644
--- a/Python/remove-duplicates-from-sorted-array-ii.py
+++ b/Python/remove-duplicates-from-sorted-array-ii.py
@@ -3,10 +3,10 @@
#
# Follow up for "Remove Duplicates":
# What if duplicates are allowed at most twice?
-#
+#
# For example,
# Given sorted array A = [1,1,1,2,2,3],
-#
+#
# Your function should return length = 5, and A is now [1,1,2,2,3].
#
@@ -16,7 +16,7 @@ class Solution:
def removeDuplicates(self, A):
if not A:
return 0
-
+
last, i, same = 0, 1, False
while i < len(A):
if A[last] != A[i] or not same:
@@ -24,7 +24,7 @@ def removeDuplicates(self, A):
last += 1
A[last] = A[i]
i += 1
-
+
return last + 1
if __name__ == "__main__":
diff --git a/Python/remove-duplicates-from-sorted-array.py b/Python/remove-duplicates-from-sorted-array.py
index 7ea358680..b2a94cc23 100644
--- a/Python/remove-duplicates-from-sorted-array.py
+++ b/Python/remove-duplicates-from-sorted-array.py
@@ -2,12 +2,12 @@
# Space: O(1)
#
# Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
-#
+#
# Do not allocate extra space for another array, you must do this in place with constant memory.
-#
+#
# For example,
# Given input array A = [1,1,2],
-#
+#
# Your function should return length = 2, and A is now [1,2].
#
@@ -17,14 +17,14 @@ class Solution:
def removeDuplicates(self, A):
if not A:
return 0
-
+
last, i = 0, 1
while i < len(A):
if A[last] != A[i]:
last += 1
A[last] = A[i]
i += 1
-
+
return last + 1
if __name__ == "__main__":
diff --git a/Python/remove-duplicates-from-sorted-list-ii.py b/Python/remove-duplicates-from-sorted-list-ii.py
index 0f21f2171..9d4d364be 100644
--- a/Python/remove-duplicates-from-sorted-list-ii.py
+++ b/Python/remove-duplicates-from-sorted-list-ii.py
@@ -3,7 +3,7 @@
#
# Given a sorted linked list, delete all nodes that have duplicate numbers,
# leaving only distinct numbers from the original list.
-#
+#
# For example,
# Given 1->2->3->3->4->4->5, return 1->2->5.
# Given 1->1->1->2->3, return 2->3.
@@ -14,7 +14,7 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self is None:
return "Nil"
@@ -40,10 +40,10 @@ def deleteDuplicates(self, head):
pre = cur
cur = cur.next
return dummy.next
-
+
if __name__ == "__main__":
head, head.next, head.next.next = ListNode(1), ListNode(2), ListNode(3)
head.next.next.next, head.next.next.next.next = ListNode(3), ListNode(4)
head.next.next.next.next.next, head.next.next.next.next.next.next = ListNode(4), ListNode(5)
print Solution().deleteDuplicates(head)
-
+
diff --git a/Python/remove-element.py b/Python/remove-element.py
index a24b77318..edb0f237b 100644
--- a/Python/remove-element.py
+++ b/Python/remove-element.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given an array and a value, remove all instances of that value in place and return the new length.
-#
+#
# The order of elements can be changed. It doesn't matter what you leave beyond the new length.
#
@@ -19,6 +19,6 @@ def removeElement(self, A, elem):
else:
i += 1
return last + 1
-
+
if __name__ == "__main__":
print Solution().removeElement([1, 2, 3, 4, 5, 2, 2], 2)
\ No newline at end of file
diff --git a/Python/remove-invalid-parentheses.py b/Python/remove-invalid-parentheses.py
index 35504e3ca..348e4291e 100644
--- a/Python/remove-invalid-parentheses.py
+++ b/Python/remove-invalid-parentheses.py
@@ -54,7 +54,7 @@ def removeInvalidParenthesesHelper(start, left_removed, right_removed):
if isValid(tmp):
res.append(tmp)
return
-
+
for i in xrange(start, len(s)):
if right_removed == 0 and left_removed > 0 and s[i] == '(':
if i == start or s[i] != s[i - 1]: # Skip duplicated.
diff --git a/Python/remove-k-digits.py b/Python/remove-k-digits.py
index ec30523a3..b9b9ee749 100644
--- a/Python/remove-k-digits.py
+++ b/Python/remove-k-digits.py
@@ -16,7 +16,7 @@
#
# Input: num = "10200", k = 1
# Output: "200"
-# Explanation: Remove the leading 1 and the number is 200.
+# Explanation: Remove the leading 1 and the number is 200.
# Note that the output must not contain leading zeroes.
# Example 3:
#
diff --git a/Python/remove-linked-list-elements.py b/Python/remove-linked-list-elements.py
index 347370e88..316f1d6de 100644
--- a/Python/remove-linked-list-elements.py
+++ b/Python/remove-linked-list-elements.py
@@ -21,15 +21,15 @@ def removeElements(self, head, val):
dummy = ListNode(float("-inf"))
dummy.next = head
prev, curr = dummy, dummy.next
-
+
while curr:
if curr.val == val:
prev.next = curr.next
else:
prev = curr
-
+
curr = curr.next
-
+
return dummy.next
-
-
+
+
diff --git a/Python/remove-nth-node-from-end-of-list.py b/Python/remove-nth-node-from-end-of-list.py
index ea655cd08..637c8c198 100644
--- a/Python/remove-nth-node-from-end-of-list.py
+++ b/Python/remove-nth-node-from-end-of-list.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# Given a linked list, remove the nth node from the end of list and return its head.
-#
+#
# For example,
-#
+#
# Given linked list: 1->2->3->4->5, and n = 2.
-#
+#
# After removing the second node from the end, the linked list becomes 1->2->3->5.
# Note:
# Given n will always be valid.
@@ -24,22 +24,22 @@ def __repr__(self):
return "Nil"
else:
return "{} -> {}".format(self.val, repr(self.next))
-
+
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
dummy = ListNode(-1)
dummy.next = head
slow, fast = dummy, dummy
-
+
for i in xrange(n):
fast = fast.next
-
+
while fast.next:
slow, fast = slow.next, fast.next
-
+
slow.next = slow.next.next
-
+
return dummy.next
if __name__ == "__main__":
@@ -48,5 +48,5 @@ def removeNthFromEnd(self, head, n):
head.next.next = ListNode(3)
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
-
+
print Solution().removeNthFromEnd(head, 2)
\ No newline at end of file
diff --git a/Python/reorder-list.py b/Python/reorder-list.py
index a80c0fede..8d5541c83 100644
--- a/Python/reorder-list.py
+++ b/Python/reorder-list.py
@@ -3,9 +3,9 @@
#
# Given a singly linked list L: L0->L1->...->Ln-1->Ln,
# reorder it to: L0->Ln->L1->Ln-1->L2->Ln-2->...
-#
+#
# You must do this in-place without altering the nodes' values.
-#
+#
# For example,
# Given {1,2,3,4}, reorder it to {1,4,2,3}.
#
@@ -15,26 +15,26 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
-
+
class Solution:
# @param head, a ListNode
# @return nothing
def reorderList(self, head):
if head == None or head.next == None:
return head
-
+
fast, slow, prev = head, head, None
while fast != None and fast.next != None:
fast, slow, prev = fast.next.next, slow.next, slow
current, prev.next, prev = slow, None, None
-
+
while current != None:
current.next, prev, current = prev, current, current.next
-
+
l1, l2 = head, prev
dummy = ListNode(0)
current = dummy
@@ -42,7 +42,7 @@ def reorderList(self, head):
while l1 != None and l2 != None:
current.next, current, l1 = l1, l1, l1.next
current.next, current, l2 = l2, l2, l2.next
-
+
return dummy.next
if __name__ == "__main__":
diff --git a/Python/repeated-dna-sequences.py b/Python/repeated-dna-sequences.py
index 901af0451..bb9373bfa 100644
--- a/Python/repeated-dna-sequences.py
+++ b/Python/repeated-dna-sequences.py
@@ -1,9 +1,9 @@
# Time: O(n)
# Space: O(n)
-# All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T,
+# All DNA is composed of a series of nucleotides abbreviated as A, C, G, and T,
# for example: "ACGAATTCCG". When studying DNA, it is sometimes useful to identify repeated sequences within the DNA.
-#
+#
# Write a function to find all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule.
#
# For example,
diff --git a/Python/reshape-the-matrix.py b/Python/reshape-the-matrix.py
index acbe6bdb2..6c5eba08e 100644
--- a/Python/reshape-the-matrix.py
+++ b/Python/reshape-the-matrix.py
@@ -15,24 +15,24 @@
# output the new reshaped matrix; Otherwise, output the original matrix.
#
# Example 1:
-# Input:
-# nums =
+# Input:
+# nums =
# [[1,2],
# [3,4]]
# r = 1, c = 4
-# Output:
+# Output:
# [[1,2,3,4]]
# Explanation:
# The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix,
# fill it row by row by using the previous list.
#
# Example 2:
-# Input:
-# nums =
+# Input:
+# nums =
# [[1,2],
# [3,4]]
# r = 2, c = 4
-# Output:
+# Output:
# [[1,2],
# [3,4]]
# Explanation:
diff --git a/Python/restore-ip-addresses.py b/Python/restore-ip-addresses.py
index 504ce6c6c..e1e338b64 100644
--- a/Python/restore-ip-addresses.py
+++ b/Python/restore-ip-addresses.py
@@ -2,10 +2,10 @@
# Space: O(n * m) = O(3 * 4)
#
# Given a string containing only digits, restore it by returning all possible valid IP address combinations.
-#
+#
# For example:
# Given "25525511135",
-#
+#
# return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
#
@@ -16,12 +16,12 @@ def restoreIpAddresses(self, s):
result = []
self.restoreIpAddressesRecur(result, s, 0, "", 0)
return result
-
+
def restoreIpAddressesRecur(self, result, s, start, current, dots):
# pruning to improve performance
if (4 - dots) * 3 < len(s) - start or (4 - dots) > len(s) - start:
return
-
+
if start == len(s) and dots == 4:
result.append(current[:-1])
else:
@@ -30,11 +30,11 @@ def restoreIpAddressesRecur(self, result, s, start, current, dots):
current += s[start:i + 1] + '.'
self.restoreIpAddressesRecur(result, s, i + 1, current, dots + 1)
current = current[:-(i - start + 2)]
-
+
def isValid(self, s):
if len(s) == 0 or (s[0] == '0' and s != "0"):
return False
return int(s) < 256
-
+
if __name__ == "__main__":
print Solution().restoreIpAddresses("0000")
diff --git a/Python/reverse-bits.py b/Python/reverse-bits.py
index 636684e0e..baecdb400 100644
--- a/Python/reverse-bits.py
+++ b/Python/reverse-bits.py
@@ -29,6 +29,6 @@ def reverseBits2(self, n):
else:
string = string[:2] + string[2:].zfill(32)[::-1]
return int(string, 2)
-
+
if __name__ == '__main__':
print Solution().reverseBits(1)
diff --git a/Python/reverse-integer.py b/Python/reverse-integer.py
index 6b213a576..8533bbe1c 100644
--- a/Python/reverse-integer.py
+++ b/Python/reverse-integer.py
@@ -2,21 +2,21 @@
# Space: O(1)
#
# Reverse digits of an integer.
-#
+#
# Example1: x = 123, return 321
# Example2: x = -123, return -321
-#
+#
# click to show spoilers.
-#
+#
# Have you thought about this?
# Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
-#
+#
# If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
-#
-# Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer,
+#
+# Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer,
# then the reverse of 1000000003 overflows. How should you handle such cases?
-#
-# Throw an exception? Good, but what if throwing an exception is not an option?
+#
+# Throw an exception? Good, but what if throwing an exception is not an option?
# You would then have to re-design the function (ie, add an extra parameter).
@@ -34,7 +34,7 @@ def reverse(self, x):
result = result * 10 + x % 10
x //= 10
return result if result <= 0x7fffffff else 0 # Handle overflow.
-
+
def reverse2(self, x):
"""
:type x: int
diff --git a/Python/reverse-linked-list-ii.py b/Python/reverse-linked-list-ii.py
index 4314d1b6f..d18404785 100644
--- a/Python/reverse-linked-list-ii.py
+++ b/Python/reverse-linked-list-ii.py
@@ -2,12 +2,12 @@
# Space: O(1)
#
# Reverse a linked list from position m to n. Do it in-place and in one-pass.
-#
+#
# For example:
# Given 1->2->3->4->5->NULL, m = 2 and n = 4,
-#
+#
# return 1->4->3->2->5->NULL.
-#
+#
# Note:
# Given m, n satisfy the following condition:
# 1 <= m <= n <= length of list.
@@ -18,7 +18,7 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
@@ -30,17 +30,17 @@ class Solution:
def reverseBetween(self, head, m, n):
diff, dummy, cur = n - m + 1, ListNode(-1), head
dummy.next = head
-
+
last_unswapped = dummy
while cur and m > 1:
cur, last_unswapped, m = cur.next, cur, m - 1
-
+
prev, first_swapped = last_unswapped, cur
while cur and diff > 0:
cur.next, prev, cur, diff = prev, cur, cur.next, diff - 1
-
+
last_unswapped.next, first_swapped.next = prev, cur
-
+
return dummy.next
if __name__ == "__main__":
@@ -50,4 +50,3 @@ def reverseBetween(self, head, m, n):
head.next.next.next = ListNode(4)
head.next.next.next.next = ListNode(5)
print Solution().reverseBetween(head, 2, 4)
-
\ No newline at end of file
diff --git a/Python/reverse-linked-list.py b/Python/reverse-linked-list.py
index 8e8441ddc..b000888f2 100644
--- a/Python/reverse-linked-list.py
+++ b/Python/reverse-linked-list.py
@@ -14,7 +14,7 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
@@ -31,27 +31,27 @@ def reverseList(self, head):
# Time: O(n)
# Space: O(n)
-# Recursive solution.
+# Recursive solution.
class Solution2:
# @param {ListNode} head
# @return {ListNode}
def reverseList(self, head):
[begin, end] = self.reverseListRecu(head)
return begin
-
+
def reverseListRecu(self, head):
if not head:
return [None, None]
-
+
[begin, end] = self.reverseListRecu(head.next)
-
+
if end:
end.next = head
head.next = None
return [begin, head]
else:
return [head, head]
-
+
if __name__ == "__main__":
head = ListNode(1)
head.next = ListNode(2)
diff --git a/Python/reverse-nodes-in-k-group.py b/Python/reverse-nodes-in-k-group.py
index 359fce169..15f95d5fa 100644
--- a/Python/reverse-nodes-in-k-group.py
+++ b/Python/reverse-nodes-in-k-group.py
@@ -2,18 +2,18 @@
# Space: O(1)
#
# Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
-#
+#
# If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
-#
+#
# You may not alter the values in the nodes, only nodes itself may be changed.
-#
+#
# Only constant memory is allowed.
-#
+#
# For example,
# Given this linked list: 1->2->3->4->5
-#
+#
# For k = 2, you should return: 2->1->4->3->5
-#
+#
# For k = 3, you should return: 3->2->1->4->5
#
@@ -21,8 +21,8 @@
class ListNode:
def __init__(self, x):
self.val = x
- self.next = None
-
+ self.next = None
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
@@ -34,27 +34,27 @@ class Solution:
def reverseKGroup(self, head, k):
dummy = ListNode(-1)
dummy.next = head
-
+
cur, cur_dummy = head, dummy
length = 0
-
+
while cur:
next_cur = cur.next
length = (length + 1) % k
-
+
if length == 0:
next_dummy = cur_dummy.next
self.reverse(cur_dummy, cur.next)
cur_dummy = next_dummy
-
+
cur = next_cur
-
+
return dummy.next
-
+
def reverse(self, begin, end):
first = begin.next
cur = first.next
-
+
while cur != end:
first.next = cur.next
cur.next = begin.next
diff --git a/Python/reverse-vowels-of-a-string.py b/Python/reverse-vowels-of-a-string.py
index f7eb88ae2..359c71f8a 100644
--- a/Python/reverse-vowels-of-a-string.py
+++ b/Python/reverse-vowels-of-a-string.py
@@ -1,7 +1,7 @@
# Time: O(n)
# Space: O(1)
-# Write a function that takes a string as input
+# Write a function that takes a string as input
# and reverse only the vowels of a string.
#
# Example 1:
diff --git a/Python/reverse-words-in-a-string-ii.py b/Python/reverse-words-in-a-string-ii.py
index 6656ae327..e87268406 100644
--- a/Python/reverse-words-in-a-string-ii.py
+++ b/Python/reverse-words-in-a-string-ii.py
@@ -3,14 +3,14 @@
#
# Given an input string, reverse the string word by word.
# A word is defined as a sequence of non-space characters.
-#
+#
# The input string does not contain leading or trailing spaces
# and the words are always separated by a single space.
-#
+#
# For example,
# Given s = "the sky is blue",
# return "blue is sky the".
-#
+#
# Could you do it in-place without allocating extra space?
#
diff --git a/Python/reverse-words-in-a-string.py b/Python/reverse-words-in-a-string.py
index 4d4bddc90..e660e205c 100644
--- a/Python/reverse-words-in-a-string.py
+++ b/Python/reverse-words-in-a-string.py
@@ -2,13 +2,13 @@
# Space: O(n)
#
# Given an input string, reverse the string word by word.
-#
+#
# For example,
# Given s = "the sky is blue",
# return "blue is sky the".
-#
+#
# click to show clarification.
-#
+#
# Clarification:
# What constitutes a word?
# A sequence of non-space characters constitutes a word.
diff --git a/Python/roman-to-integer.py b/Python/roman-to-integer.py
index 2b858fea1..a5d2d05d9 100644
--- a/Python/roman-to-integer.py
+++ b/Python/roman-to-integer.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given a roman numeral, convert it to an integer.
-#
+#
# Input is guaranteed to be within the xrange from 1 to 3999.
#
diff --git a/Python/rotate-array.py b/Python/rotate-array.py
index 1139d6a33..7e5484fca 100644
--- a/Python/rotate-array.py
+++ b/Python/rotate-array.py
@@ -60,7 +60,7 @@ def apply_cycle_permutation(self, k, offset, cycle_len, nums):
nums[(offset + i * k) % len(nums)], tmp = tmp, nums[(offset + i * k) % len(nums)]
nums[offset] = tmp
-
+
class Solution3:
"""
:type nums: List[int]
@@ -82,7 +82,7 @@ def rotate(self, nums, k):
if start == curr:
break
start += 1
-
+
if __name__ == '__main__':
nums = [1, 2, 3, 4, 5, 6, 7]
diff --git a/Python/rotate-image.py b/Python/rotate-image.py
index dabc2734f..648b4c715 100644
--- a/Python/rotate-image.py
+++ b/Python/rotate-image.py
@@ -2,9 +2,9 @@
# Space: O(1)
#
# You are given an n x n 2D matrix representing an image.
-#
+#
# Rotate the image by 90 degrees (clockwise).
-#
+#
# Follow up:
# Could you do this in-place?
#
@@ -16,19 +16,19 @@ class Solution:
# @return a list of lists of integers
def rotate(self, matrix):
n = len(matrix)
-
+
# anti-diagonal mirror
for i in xrange(n):
for j in xrange(n - i):
matrix[i][j], matrix[n-1-j][n-1-i] = matrix[n-1-j][n-1-i], matrix[i][j]
-
+
# horizontal mirror
for i in xrange(n / 2):
for j in xrange(n):
matrix[i][j], matrix[n-1-i][j] = matrix[n-1-i][j], matrix[i][j]
-
+
return matrix
-
+
# Time: O(n^2)
# Space: O(n^2)
class Solution2:
@@ -36,7 +36,7 @@ class Solution2:
# @return a list of lists of integers
def rotate(self, matrix):
return [list(reversed(x)) for x in zip(*matrix)]
-
+
if __name__ == "__main__":
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print Solution().rotate(matrix)
diff --git a/Python/rotate-list.py b/Python/rotate-list.py
index 6a536da17..59ecb567e 100644
--- a/Python/rotate-list.py
+++ b/Python/rotate-list.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given a list, rotate the list to the right by k places, where k is non-negative.
-#
+#
# For example:
# Given 1->2->3->4->5->NULL and k = 2,
# return 4->5->1->2->3->NULL.
@@ -13,11 +13,11 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
-
+
class Solution(object):
def rotateRight(self, head, k):
"""
@@ -42,7 +42,7 @@ def rotateRight(self, head, k):
return cur
-
+
if __name__ == "__main__":
head = ListNode(1)
head.next = ListNode(2)
diff --git a/Python/rotate-string.py b/Python/rotate-string.py
index b988e3bf4..3a8f5151a 100644
--- a/Python/rotate-string.py
+++ b/Python/rotate-string.py
@@ -32,7 +32,7 @@ def check(index):
if len(A) != len(B):
return False
-
+
M, p = 10**9+7, 113
p_inv = pow(p, M-2, M)
@@ -98,12 +98,12 @@ def getPrefix(pattern):
if not needle:
return 0
return KMP(haystack, needle)
-
+
if len(A) != len(B):
return False
return strStr(A*2, B) != -1
-
+
# Time: O(n^2)
# Space: O(n)
class Solution3(object):
diff --git a/Python/rotated-digits.py b/Python/rotated-digits.py
index 4a0f1baf4..98223aa44 100644
--- a/Python/rotated-digits.py
+++ b/Python/rotated-digits.py
@@ -12,7 +12,7 @@
# Example:
# Input: 10
# Output: 4
-# Explanation:
+# Explanation:
# There are four good numbers in the range [1, 10] : 2, 5, 6, 9.
# Note that 1 and 10 are not good numbers, since they remain unchanged after rotating.
#
@@ -40,11 +40,11 @@ def dp(A, i, is_prefix_equal, is_good, lookup):
lookup)
lookup[i, is_prefix_equal, is_good] = result
return lookup[i, is_prefix_equal, is_good]
-
+
lookup = {}
return dp(A, 0, True, False, lookup)
-
-
+
+
# Time: O(n)
# Space: O(n)
class Solution2(object):
@@ -66,7 +66,7 @@ def rotatedDigits(self, N):
if i*10+j <= N:
dp[i*10+j] = DIFF
return dp.count(DIFF)
-
+
# Time: O(nlogn) = O(n), because O(logn) = O(32) by this input
# Space: O(logn) = O(1)
@@ -85,4 +85,4 @@ def rotatedDigits(self, N):
if diff & lookup:
result += 1
return result
-
+
diff --git a/Python/russian-doll-envelopes.py b/Python/russian-doll-envelopes.py
index 2f695b9c4..50685c92b 100644
--- a/Python/russian-doll-envelopes.py
+++ b/Python/russian-doll-envelopes.py
@@ -3,7 +3,7 @@
# You have a number of envelopes with widths and heights given
# as a pair of integers (w, h). One envelope can fit into another
-# if and only if both the width and height of one envelope is greater
+# if and only if both the width and height of one envelope is greater
# than the width and height of the other envelope.
#
# What is the maximum number of envelopes can you Russian doll?
diff --git a/Python/same-tree.py b/Python/same-tree.py
index c7e799c94..6418ffc0e 100644
--- a/Python/same-tree.py
+++ b/Python/same-tree.py
@@ -2,7 +2,7 @@
# Space: O(h), h is height of binary tree
#
# Given two binary trees, write a function to check if they are equal or not.
-#
+#
# Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
#
@@ -20,12 +20,12 @@ class Solution:
def isSameTree(self, p, q):
if p is None and q is None:
return True
-
+
if p is not None and q is not None:
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
-
+
return False
-
+
if __name__ == "__main__":
root1, root1.left, root1.right = TreeNode(1), TreeNode(2), TreeNode(3)
root2, root2.left, root2.right = TreeNode(1), TreeNode(2), TreeNode(3)
diff --git a/Python/scramble-string.py b/Python/scramble-string.py
index 7969954b0..2627135af 100644
--- a/Python/scramble-string.py
+++ b/Python/scramble-string.py
@@ -2,9 +2,9 @@
# Space: O(n^3)
#
# Given a string s1, we may represent it as a binary tree by partitioning it to two non-empty substrings recursively.
-#
+#
# Below is one possible representation of s1 = "great":
-#
+#
# great
# / \
# gr eat
@@ -13,9 +13,9 @@
# / \
# a t
# To scramble the string, we may choose any non-leaf node and swap its two children.
-#
+#
# For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".
-#
+#
# rgeat
# / \
# rg eat
@@ -24,9 +24,9 @@
# / \
# a t
# We say that "rgeat" is a scrambled string of "great".
-#
+#
# Similarly, if we continue to swap the children of nodes "eat" and "at", it produces a scrambled string "rgtae".
-#
+#
# rgtae
# / \
# rg tae
@@ -35,7 +35,7 @@
# / \
# t a
# We say that "rgtae" is a scrambled string of "great".
-#
+#
# Given two strings s1 and s2 of the same length, determine if s2 is a scrambled string of s1.
#
@@ -54,7 +54,7 @@ def isScramble(self, s1, s2):
for j in xrange(len(s2)):
if s1[i] == s2[j]:
result[1][i][j] = True
-
+
for n in xrange(2, len(s1) + 1):
for i in xrange(len(s1) - n + 1):
for j in xrange(len(s2) - n + 1):
@@ -63,7 +63,7 @@ def isScramble(self, s1, s2):
result[k][i][j + n - k] and result[n - k][i + k][j]:
result[n][i][j] = True
break
-
+
return result[n][0][0]
if __name__ == "__main__":
diff --git a/Python/search-a-2d-matrix-ii.py b/Python/search-a-2d-matrix-ii.py
index 3540dfd6c..e61290905 100644
--- a/Python/search-a-2d-matrix-ii.py
+++ b/Python/search-a-2d-matrix-ii.py
@@ -30,11 +30,11 @@ def searchMatrix(self, matrix, target):
m = len(matrix)
if m == 0:
return False
-
+
n = len(matrix[0])
if n == 0:
return False
-
+
i, j = 0, n - 1
while i < m and j >= 0:
if matrix[i][j] == target:
@@ -43,5 +43,5 @@ def searchMatrix(self, matrix, target):
j -= 1
else:
i += 1
-
+
return False
diff --git a/Python/search-a-2d-matrix.py b/Python/search-a-2d-matrix.py
index cc0e67e95..793894f2a 100644
--- a/Python/search-a-2d-matrix.py
+++ b/Python/search-a-2d-matrix.py
@@ -2,13 +2,13 @@
# Space: O(1)
#
# Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
-#
+#
# Integers in each row are sorted from left to right.
# The first integer of each row is greater than the last integer of the previous row.
# For example,
-#
+#
# Consider the following matrix:
-#
+#
# [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
@@ -26,7 +26,7 @@ def searchMatrix(self, matrix, target):
"""
if not matrix:
return False
-
+
m, n = len(matrix), len(matrix[0])
left, right = 0, m * n
while left < right:
diff --git a/Python/search-for-a-range.py b/Python/search-for-a-range.py
index 74bf58ac7..9d3ad9766 100644
--- a/Python/search-for-a-range.py
+++ b/Python/search-for-a-range.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# Given a sorted array of integers, find the starting and ending position of a given target value.
-#
+#
# Your algorithm's runtime complexity must be in the order of O(log n).
-#
+#
# If the target is not found in the array, return [-1, -1].
-#
+#
# For example,
# Given [5, 7, 7, 8, 8, 10] and target value 8,
# return [3, 4].
@@ -26,7 +26,7 @@ def searchRange(self, nums, target):
# Find the first idx where nums[idx] > target
right = self.binarySearch(lambda x, y: x > y, nums, target)
return [left, right - 1]
-
+
def binarySearch(self, compare, nums, target):
left, right = 0, len(nums)
while left < right:
diff --git a/Python/search-in-rotated-sorted-array-ii.py b/Python/search-in-rotated-sorted-array-ii.py
index 8649ec528..43a607f05 100644
--- a/Python/search-in-rotated-sorted-array-ii.py
+++ b/Python/search-in-rotated-sorted-array-ii.py
@@ -3,9 +3,9 @@
#
# Follow up for "Search in Rotated Sorted Array":
# What if duplicates are allowed?
-#
+#
# Would this affect the run-time complexity? How and why?
-#
+#
# Write a function to determine if a given target is in the array.
#
@@ -17,10 +17,10 @@ def search(self, nums, target):
:rtype: int
"""
left, right = 0, len(nums) - 1
-
+
while left <= right:
mid = left + (right - left) / 2
-
+
if nums[mid] == target:
return True
elif nums[mid] == nums[left]:
@@ -32,7 +32,7 @@ def search(self, nums, target):
left = mid + 1
return False
-
+
if __name__ == "__main__":
print Solution().search([3, 5, 1], 3)
diff --git a/Python/search-in-rotated-sorted-array.py b/Python/search-in-rotated-sorted-array.py
index d95d92382..4c93474b0 100644
--- a/Python/search-in-rotated-sorted-array.py
+++ b/Python/search-in-rotated-sorted-array.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# Suppose a sorted array is rotated at some pivot unknown to you beforehand.
-#
+#
# (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
-#
+#
# You are given a target value to search. If found in the array return its index, otherwise return -1.
-#
+#
# You may assume no duplicate exists in the array.
#
@@ -18,10 +18,10 @@ def search(self, nums, target):
:rtype: int
"""
left, right = 0, len(nums) - 1
-
+
while left <= right:
mid = left + (right - left) / 2
-
+
if nums[mid] == target:
return mid
elif (nums[mid] >= nums[left] and nums[left] <= target < nums[mid]) or \
@@ -31,7 +31,7 @@ def search(self, nums, target):
left = mid + 1
return -1
-
+
if __name__ == "__main__":
print Solution().search([3, 5, 1], 3)
diff --git a/Python/search-insert-position.py b/Python/search-insert-position.py
index a5be023ed..89b3f18de 100644
--- a/Python/search-insert-position.py
+++ b/Python/search-insert-position.py
@@ -2,11 +2,11 @@
# Space: O(1)
#
# Given a sorted array and a target value, return the index if the target is found.
-#
+#
# If not, return the index where it would be if it were inserted in order.
-#
+#
# You may assume no duplicates in the array.
-#
+#
# Here are few examples.
# [1,3,5,6], 5 -> 2
# [1,3,5,6], 2 -> 1
diff --git a/Python/self-crossing.py b/Python/self-crossing.py
index cdb4439ab..76fd0d7d2 100644
--- a/Python/self-crossing.py
+++ b/Python/self-crossing.py
@@ -46,7 +46,7 @@ def isSelfCrossing(self, x):
# 2
# 3 ┌────┐
# └─══>┘1
- # 4 0 (overlapped)
+ # 4 0 (overlapped)
return True
for i in xrange(3, len(x)):
@@ -61,7 +61,7 @@ def isSelfCrossing(self, x):
x[i - 1] <= x[i - 3] and x[i - 5] + x[i - 1] >= x[i - 3]:
# Case 2:
# i-4
- # ┌──┐
+ # ┌──┐
# │i<┼─┐
# i-3│ i-5│i-1
# └────┘
diff --git a/Python/self-dividing-numbers.py b/Python/self-dividing-numbers.py
index 84050e5a8..d3428690d 100644
--- a/Python/self-dividing-numbers.py
+++ b/Python/self-dividing-numbers.py
@@ -12,7 +12,7 @@
# including the bounds if possible.
#
# Example 1:
-# Input:
+# Input:
# left = 1, right = 22
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
#
@@ -33,7 +33,7 @@ def isDividingNumber(num):
return False
n /= 10
return True
-
+
result = []
for num in xrange(left, right+1):
if isDividingNumber(num):
diff --git a/Python/sentence-screen-fitting.py b/Python/sentence-screen-fitting.py
index 91f45ca0c..eb5f98046 100644
--- a/Python/sentence-screen-fitting.py
+++ b/Python/sentence-screen-fitting.py
@@ -12,7 +12,7 @@ def wordsTyping(self, sentence, rows, cols):
def words_fit(sentence, start, cols):
if len(sentence[start]) > cols:
return 0
-
+
s, count = len(sentence[start]), 1
i = (start + 1) % len(sentence)
while s + 1 + len(sentence[i]) <= cols:
diff --git a/Python/serialize-and-deserialize-binary-tree.py b/Python/serialize-and-deserialize-binary-tree.py
index d69f43dd0..1806df30f 100644
--- a/Python/serialize-and-deserialize-binary-tree.py
+++ b/Python/serialize-and-deserialize-binary-tree.py
@@ -6,10 +6,10 @@
# or memory buffer, or transmitted across a network connection link
# to be reconstructed later in the same or another computer environment.
#
-# Design an algorithm to serialize and deserialize a binary tree.
+# Design an algorithm to serialize and deserialize a binary tree.
# There is no restriction on how your serialization/deserialization
-# algorithm should work. You just need to ensure that a binary tree can
-# be serialized to a string and this string can be deserialized to the
+# algorithm should work. You just need to ensure that a binary tree can
+# be serialized to a string and this string can be deserialized to the
# original tree structure.
#
# For example, you may serialize the following tree
@@ -20,9 +20,9 @@
# / \
# 4 5
# as "[1,2,3,null,null,4,5]", just the same as how LeetCode OJ serializes
-# a binary tree. You do not necessarily need to follow this format, so
+# a binary tree. You do not necessarily need to follow this format, so
# please be creative and come up with different approaches yourself.
-# Note: Do not use class member/global/static variables to store states.
+# Note: Do not use class member/global/static variables to store states.
# Your serialize and deserialize algorithms should be stateless.
#
@@ -36,7 +36,7 @@ class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
-
+
:type root: TreeNode
:rtype: str
"""
@@ -54,7 +54,7 @@ def serializeHelper(node):
def deserialize(self, data):
"""Decodes your encoded data to tree.
-
+
:type data: str
:rtype: TreeNode
"""
diff --git a/Python/set-matrix-zeroes.py b/Python/set-matrix-zeroes.py
index ea770632c..4a08ded96 100644
--- a/Python/set-matrix-zeroes.py
+++ b/Python/set-matrix-zeroes.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
-#
+#
# Follow up:
# Did you use extra space?
# A straight forward solution using O(mn) space is probably a bad idea.
@@ -16,21 +16,21 @@ class Solution:
def setZeroes(self, matrix):
first_col = reduce(lambda acc, i: acc or matrix[i][0] == 0, xrange(len(matrix)), False)
first_row = reduce(lambda acc, j: acc or matrix[0][j] == 0, xrange(len(matrix[0])), False)
-
+
for i in xrange(1, len(matrix)):
for j in xrange(1, len(matrix[0])):
if matrix[i][j] == 0:
matrix[i][0], matrix[0][j] = 0, 0
-
+
for i in xrange(1, len(matrix)):
for j in xrange(1, len(matrix[0])):
if matrix[i][0] == 0 or matrix[0][j] == 0:
matrix[i][j] = 0
-
+
if first_col:
for i in xrange(len(matrix)):
matrix[i][0] = 0
-
+
if first_row:
for j in xrange(len(matrix[0])):
matrix[0][j] = 0
diff --git a/Python/set-mismatch.py b/Python/set-mismatch.py
index 662ae25d4..d9a24acda 100644
--- a/Python/set-mismatch.py
+++ b/Python/set-mismatch.py
@@ -37,7 +37,7 @@ def findErrorNums(self, nums):
# Time: O(n)
-# Space: O(1)
+# Space: O(1)
class Solution2(object):
def findErrorNums(self, nums):
"""
@@ -59,7 +59,7 @@ def findErrorNums(self, nums):
# Time: O(n)
-# Space: O(1)
+# Space: O(1)
class Solution3(object):
def findErrorNums(self, nums):
"""
diff --git a/Python/shopping-offers.py b/Python/shopping-offers.py
index 63fe142b0..743d8d0a3 100644
--- a/Python/shopping-offers.py
+++ b/Python/shopping-offers.py
@@ -19,24 +19,24 @@
# Example 1:
# Input: [2,5], [[3,0,5],[1,2,10]], [3,2]
# Output: 14
-# Explanation:
-# There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
+# Explanation:
+# There are two kinds of items, A and B. Their prices are $2 and $5 respectively.
# In special offer 1, you can pay $5 for 3A and 0B
-# In special offer 2, you can pay $10 for 1A and 2B.
+# In special offer 2, you can pay $10 for 1A and 2B.
# You need to buy 3A and 2B, so you may pay $10 for 1A and 2B (special offer #2), and $4 for 2A.
# Example 2:
# Input: [2,3,4], [[1,1,0,4],[2,2,1,9]], [1,2,1]
# Output: 11
-# Explanation:
-# The price of A is $2, and $3 for B, $4 for C.
-# You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
-# You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
+# Explanation:
+# The price of A is $2, and $3 for B, $4 for C.
+# You may pay $4 for 1A and 1B, and $9 for 2A ,2B and 1C.
+# You need to buy 1A ,2B and 1C, so you may pay $4 for 1A and 1B (special offer #1), and $3 for 1B, $4 for 1C.
# You cannot add more items, though only $9 for 2A ,2B and 1C.
# Note:
# There are at most 6 kinds of items, 100 special offers.
# For each item, you need to buy at most 6 of them.
# You are not allowed to buy more items than you want, even if that would lower the overall price.
-
+
class Solution(object):
def shoppingOffers(self, price, special, needs):
"""
diff --git a/Python/shortest-distance-from-all-buildings.py b/Python/shortest-distance-from-all-buildings.py
index 7b5fd2ae5..19a0b0082 100644
--- a/Python/shortest-distance-from-all-buildings.py
+++ b/Python/shortest-distance-from-all-buildings.py
@@ -10,7 +10,7 @@ def shortestDistance(self, grid):
def bfs(grid, dists, cnts, x, y):
dist, m, n = 0, len(grid), len(grid[0])
visited = [[False for _ in xrange(n)] for _ in xrange(m)]
-
+
pre_level = [(x, y)]
visited[x][y] = True
while pre_level:
@@ -24,7 +24,7 @@ def bfs(grid, dists, cnts, x, y):
dists[I][J] += dist
cur_level.append((I, J))
visited[I][J] = True
-
+
pre_level = cur_level
diff --git a/Python/shortest-palindrome.py b/Python/shortest-palindrome.py
index f092ca4bf..e267e597e 100644
--- a/Python/shortest-palindrome.py
+++ b/Python/shortest-palindrome.py
@@ -1,8 +1,8 @@
# Time: O(n)
# Space: O(n)
#
-# Given a string S, you are allowed to convert it to a palindrome
-# by adding characters in front of it. Find and return the shortest
+# Given a string S, you are allowed to convert it to a palindrome
+# by adding characters in front of it. Find and return the shortest
# palindrome you can find by performing this transformation.
#
# For example:
@@ -32,7 +32,7 @@ def getPrefix(pattern):
if not s:
return s
-
+
A = s + s[::-1]
prefix = getPrefix(A)
i = prefix[-1]
@@ -60,7 +60,7 @@ def preProcess(s):
return string
string = preProcess(s)
- palindrome = [0] * len(string)
+ palindrome = [0] * len(string)
center, right = 0, 0
for i in xrange(1, len(string) - 1):
i_mirror = 2 * center - i
@@ -73,8 +73,8 @@ def preProcess(s):
palindrome[i] += 1
if i + palindrome[i] > right:
- center, right = i, i + palindrome[i]
-
+ center, right = i, i + palindrome[i]
+
max_len = 0
for i in xrange(1, len(string) - 1):
if i - palindrome[i] == 1:
diff --git a/Python/shortest-unsorted-continuous-subarray.py b/Python/shortest-unsorted-continuous-subarray.py
index 1de3ba3fe..637b692a0 100644
--- a/Python/shortest-unsorted-continuous-subarray.py
+++ b/Python/shortest-unsorted-continuous-subarray.py
@@ -31,7 +31,7 @@ def findUnsortedSubarray(self, nums):
min_from_right = min(min_from_right, nums[n-1-i])
if nums[i] < max_from_left: right = i
if nums[n-1-i] > min_from_right: left = n-1-i
-
+
# Time: O(nlogn)
# Space: O(n)
diff --git a/Python/simplify-path.py b/Python/simplify-path.py
index b55e73a11..532b544c1 100644
--- a/Python/simplify-path.py
+++ b/Python/simplify-path.py
@@ -2,12 +2,12 @@
# Space: O(n)
#
# Given an absolute path for a file (Unix-style), simplify it.
-#
+#
# For example,
# path = "/home/", => "/home"
# path = "/a/./b/../../c/", => "/c"
# click to show corner cases.
-#
+#
# Corner Cases:
# Did you consider the case where path = "/../"?
# In this case, you should return "/".
diff --git a/Python/single-element-in-a-sorted-array.py b/Python/single-element-in-a-sorted-array.py
index 4a7dcb18b..ef54a8bef 100644
--- a/Python/single-element-in-a-sorted-array.py
+++ b/Python/single-element-in-a-sorted-array.py
@@ -12,7 +12,7 @@
# Input: [3,3,7,7,10,11,11]
# Output: 10
# Note: Your solution should run in O(log n) time and O(1) space.
-
+
class Solution(object):
def singleNonDuplicate(self, nums):
"""
diff --git a/Python/single-number-ii.py b/Python/single-number-ii.py
index e87276c96..586b80c30 100644
--- a/Python/single-number-ii.py
+++ b/Python/single-number-ii.py
@@ -1,8 +1,8 @@
# Time: O(n)
# Space: O(1)
-#
+#
# Given an array of integers, every element appears three times except for one. Find that single one.
-#
+#
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
import collections
@@ -16,7 +16,7 @@ def singleNumber(self, A):
for x in A:
one, two = (~x & one) | (x & ~one & ~two), (~x & two) | (x & one)
return one
-
+
class Solution2(object):
# @param A, a list of integer
# @return an integer
diff --git a/Python/single-number.py b/Python/single-number.py
index 88047ae25..742ea9c09 100644
--- a/Python/single-number.py
+++ b/Python/single-number.py
@@ -2,7 +2,7 @@
# Space: O(1)
#
# Given an array of integers, every element appears twice except for one. Find that single one.
-#
+#
# Note:
# Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
#
diff --git a/Python/sliding-window-maximum.py b/Python/sliding-window-maximum.py
index eeaffeedb..1fb613e50 100644
--- a/Python/sliding-window-maximum.py
+++ b/Python/sliding-window-maximum.py
@@ -19,7 +19,7 @@
# 1 3 -1 -3 5 [3 6 7] 7
# Therefore, return the max sliding window as [3,3,5,5,6,7].
#
-# Note:
+# Note:
# You may assume k is always valid, ie: 1 <= k <= input array's size for non-empty array.
#
# Follow up:
diff --git a/Python/smallest-rotation-with-highest-score.py b/Python/smallest-rotation-with-highest-score.py
index c46d7421d..c37570ea0 100644
--- a/Python/smallest-rotation-with-highest-score.py
+++ b/Python/smallest-rotation-with-highest-score.py
@@ -1,9 +1,9 @@
# Time: O(n)
# Space: O(n)
-# Given an array A, we may rotate it by a non-negative integer K
+# Given an array A, we may rotate it by a non-negative integer K
# so that the array becomes A[K], A[K+1], A{K+2], ... A[A.length - 1], A[0], A[1], ..., A[K-1].
-# Afterward, any entries that are less than or equal to their index are worth 1 point.
+# Afterward, any entries that are less than or equal to their index are worth 1 point.
#
# For example, if we have [2, 4, 1, 3, 0], and we rotate by K = 2,
# it becomes [1, 3, 0, 2, 4].
@@ -17,8 +17,8 @@
# Example 1:
# Input: [2, 3, 1, 4, 0]
# Output: 3
-# Explanation:
-# Scores for each K are listed below:
+# Explanation:
+# Scores for each K are listed below:
# K = 0, A = [2,3,1,4,0], score 2
# K = 1, A = [3,1,4,0,2], score 3
# K = 2, A = [1,4,0,2,3], score 3
@@ -35,7 +35,7 @@
# Note:
# - A will have length at most 20000.
# - A[i] will be in the range [0, A.length].
-
+
class Solution(object):
def bestRotation(self, A):
"""
@@ -49,4 +49,4 @@ def bestRotation(self, A):
for i in xrange(1, N):
change[i] += change[i-1]
return change.index(max(change))
-
+
diff --git a/Python/sort-colors.py b/Python/sort-colors.py
index 5e42aa69b..9a7b2b8dd 100644
--- a/Python/sort-colors.py
+++ b/Python/sort-colors.py
@@ -1,21 +1,21 @@
# Time: O(n)
# Space: O(1)
#
-# Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent,
+# Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent,
# with the colors in the order red, white and blue.
-#
+#
# Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
-#
+#
# Note:
# You are not suppose to use the library's sort function for this problem.
-#
+#
# click to show follow up.
-#
+#
# Follow up:
# A rather straight forward solution is a two-pass algorithm using counting sort.
-# First, iterate the array counting number of 0's, 1's, and 2's,
+# First, iterate the array counting number of 0's, 1's, and 2's,
# then overwrite array with total number of 0's, then 1's and followed by 2's.
-#
+#
# Could you come up with an one-pass algorithm using only constant space?
#
@@ -27,7 +27,7 @@ def sortColors(self, nums):
"""
def triPartition(nums, target):
i, j, n = 0, 0, len(nums) - 1
-
+
while j <= n:
if nums[j] < target:
nums[i], nums[j] = nums[j], nums[i]
diff --git a/Python/sort-list.py b/Python/sort-list.py
index 5427a88bd..d01ed7f56 100644
--- a/Python/sort-list.py
+++ b/Python/sort-list.py
@@ -9,43 +9,43 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, repr(self.next))
class Solution:
# @param head, a ListNode
- # @return a ListNode
+ # @return a ListNode
def sortList(self, head):
if head == None or head.next == None:
return head
-
+
fast, slow, prev = head, head, None
while fast != None and fast.next != None:
prev, fast, slow = slow, fast.next.next, slow.next
prev.next = None
-
+
sorted_l1 = self.sortList(head)
sorted_l2 = self.sortList(slow)
-
+
return self.mergeTwoLists(sorted_l1, sorted_l2)
-
+
def mergeTwoLists(self, l1, l2):
dummy = ListNode(0)
-
+
cur = dummy
while l1 != None and l2 != None:
if l1.val <= l2.val:
cur.next, cur, l1 = l1, l1, l1.next
else:
cur.next, cur, l2 = l2, l2, l2.next
-
+
if l1 != None:
cur.next = l1
if l2 != None:
cur.next = l2
-
+
return dummy.next
if __name__ == "__main__":
diff --git a/Python/special-binary-string.py b/Python/special-binary-string.py
index b743a60fa..ab8a7ced5 100644
--- a/Python/special-binary-string.py
+++ b/Python/special-binary-string.py
@@ -8,7 +8,7 @@
# Every prefix of the binary string has at least as many 1's as 0's.
# Given a special string S, a move consists of choosing two consecutive, non-empty,
# special substrings of S, and swapping them.
-# (Two strings are consecutive if the last character of the first string is
+# (Two strings are consecutive if the last character of the first string is
# exactly one index before the first character of the second string.)
#
# At the end of any number of moves, what is the lexicographically largest resulting string possible?
diff --git a/Python/spiral-matrix-ii.py b/Python/spiral-matrix-ii.py
index d0b870bd5..d23da6b19 100644
--- a/Python/spiral-matrix-ii.py
+++ b/Python/spiral-matrix-ii.py
@@ -2,10 +2,10 @@
# Space: O(1)
#
# Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
-#
+#
# For example,
# Given n = 3,
-#
+#
# You should return the following matrix:
# [
# [ 1, 2, 3 ],
@@ -18,9 +18,9 @@ class Solution:
# @return a list of lists of integer
def generateMatrix(self, n):
matrix = [[0 for _ in xrange(n)] for _ in xrange(n)]
-
+
left, right, top, bottom, num = 0, n - 1, 0, n - 1, 1
-
+
while left <= right and top <= bottom:
for j in xrange(left, right + 1):
matrix[top][j] = num
@@ -37,7 +37,7 @@ def generateMatrix(self, n):
matrix[i][left] = num
num += 1
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
-
+
return matrix
diff --git a/Python/spiral-matrix.py b/Python/spiral-matrix.py
index 5071ccc54..1e0734fe1 100644
--- a/Python/spiral-matrix.py
+++ b/Python/spiral-matrix.py
@@ -2,10 +2,10 @@
# Space: O(1)
#
# Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
-#
+#
# For example,
# Given the following matrix:
-#
+#
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
@@ -21,9 +21,9 @@ def spiralOrder(self, matrix):
result = []
if matrix == []:
return result
-
+
left, right, top, bottom = 0, len(matrix[0]) - 1, 0, len(matrix) - 1
-
+
while left <= right and top <= bottom:
for j in xrange(left, right + 1):
result.append(matrix[top][j])
@@ -36,7 +36,7 @@ def spiralOrder(self, matrix):
if left < right:
result.append(matrix[i][left])
left, right, top, bottom = left + 1, right - 1, top + 1, bottom - 1
-
+
return result
diff --git a/Python/split-array-into-consecutive-subsequences.py b/Python/split-array-into-consecutive-subsequences.py
index c5c0008ca..2e6b113d5 100644
--- a/Python/split-array-into-consecutive-subsequences.py
+++ b/Python/split-array-into-consecutive-subsequences.py
@@ -9,14 +9,14 @@
# Input: [1,2,3,3,4,5]
# Output: True
# Explanation:
-# You can split them into two consecutive subsequences :
+# You can split them into two consecutive subsequences :
# 1, 2, 3
# 3, 4, 5
# Example 2:
# Input: [1,2,3,3,4,4,5,5]
# Output: True
# Explanation:
-# You can split them into two consecutive subsequences :
+# You can split them into two consecutive subsequences :
# 1, 2, 3, 4, 5
# 3, 4, 5
# Example 3:
diff --git a/Python/split-array-with-equal-sum.py b/Python/split-array-with-equal-sum.py
index 036df2334..825e79418 100644
--- a/Python/split-array-with-equal-sum.py
+++ b/Python/split-array-with-equal-sum.py
@@ -9,7 +9,7 @@ def splitArray(self, nums):
"""
if len(nums) < 7:
return False
-
+
accumulated_sum = [0] * len(nums)
accumulated_sum[0] = nums[0]
for i in xrange(1, len(nums)):
diff --git a/Python/split-array-with-same-average.py b/Python/split-array-with-same-average.py
index aaca0d8bf..f4a83ec9f 100644
--- a/Python/split-array-with-same-average.py
+++ b/Python/split-array-with-same-average.py
@@ -8,7 +8,7 @@
# the average value of B is equal to the average value of C, and B and C are both non-empty.
#
# Example :
-# Input:
+# Input:
# [1,2,3,4,5,6,7,8]
# Output: true
# Explanation: We can split the array into [1,4,5,8] and [2,3,6,7], and both of them have the average of 4.5.
diff --git a/Python/split-concatenated-strings.py b/Python/split-concatenated-strings.py
index 4693b532e..4ad1d593f 100644
--- a/Python/split-concatenated-strings.py
+++ b/Python/split-concatenated-strings.py
@@ -17,9 +17,9 @@
# Example:
# Input: "abc", "xyz"
# Output: "zyxcba"
-# Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-",
-# where '-' represents the looped status.
-# The answer string came from the fourth looped one,
+# Explanation: You can get the looped string "-abcxyz-", "-abczyx-", "-cbaxyz-", "-cbazyx-",
+# where '-' represents the looped status.
+# The answer string came from the fourth looped one,
# where you could cut from the middle character 'a' and get "zyxcba".
# Note:
# The input strings will only contain lowercase letters.
diff --git a/Python/split-linked-list-in-parts.py b/Python/split-linked-list-in-parts.py
index 27b6e791f..4189510f1 100644
--- a/Python/split-linked-list-in-parts.py
+++ b/Python/split-linked-list-in-parts.py
@@ -15,7 +15,7 @@
#
# Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]
# Example 1:
-# Input:
+# Input:
# root = [1, 2, 3], k = 5
# Output: [[1],[2],[3],[],[]]
# Explanation:
@@ -26,7 +26,7 @@
# The last element output[4] is null, but it's string representation as a ListNode is [].
#
# Example 2:
-# Input:
+# Input:
# root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
# Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
# Explanation:
diff --git a/Python/sqrtx.py b/Python/sqrtx.py
index 8ac7af2c8..05296b789 100644
--- a/Python/sqrtx.py
+++ b/Python/sqrtx.py
@@ -2,7 +2,7 @@
# Space: O(1)
# Implement int sqrt(int x).
-#
+#
# Compute and return the square root of x.
class Solution(object):
@@ -13,7 +13,7 @@ def mySqrt(self, x):
"""
if x < 2:
return x
-
+
left, right = 1, x // 2
while left <= right:
mid = left + (right - left) // 2
@@ -27,4 +27,4 @@ def mySqrt(self, x):
if __name__ == "__main__":
print Solution().mySqrt(10)
-
+
diff --git a/Python/squirrel-simulation.py b/Python/squirrel-simulation.py
index 11935ae5e..f0057eec2 100644
--- a/Python/squirrel-simulation.py
+++ b/Python/squirrel-simulation.py
@@ -13,7 +13,7 @@ def minDistance(self, height, width, tree, squirrel, nuts):
"""
def distance(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
-
+
result = 0
d = float("inf")
for nut in nuts:
diff --git a/Python/strange-printer.py b/Python/strange-printer.py
index 534463942..811933aaf 100644
--- a/Python/strange-printer.py
+++ b/Python/strange-printer.py
@@ -17,11 +17,11 @@
# Example 2:
# Input: "aba"
# Output: 2
-# Explanation: Print "aaa" first and then print "b" from
+# Explanation: Print "aaa" first and then print "b" from
# the second place of the string, which will cover the existing character 'a'.
#
# Hint: Length of the given string will not exceed 100.
-
+
class Solution(object):
def strangePrinter(self, s):
"""
diff --git a/Python/string-to-integer-atoi.py b/Python/string-to-integer-atoi.py
index 56b6c78e8..d59faea1a 100644
--- a/Python/string-to-integer-atoi.py
+++ b/Python/string-to-integer-atoi.py
@@ -2,27 +2,27 @@
# Space: O(1)
#
# Implement atoi to convert a string to an integer.
-#
-# Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below
+#
+# Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below
# and ask yourself what are the possible input cases.
-#
+#
# Notes: It is intended for this problem to be specified vaguely (ie, no given input specs).
# You are responsible to gather all the input requirements up front.
-#
+#
# spoilers alert... click to show requirements for atoi.
-#
+#
# Requirements for atoi:
-# The function first discards as many whitespace characters as necessary
-# until the first non-whitespace character is found. Then, starting from this character,
+# The function first discards as many whitespace characters as necessary
+# until the first non-whitespace character is found. Then, starting from this character,
# takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
-#
-# The string can contain additional characters after those that
+#
+# The string can contain additional characters after those that
# form the integral number, which are ignored and have no effect on the behavior of this function.
-#
-# If the first sequence of non-whitespace characters in str is not a valid integral number,
+#
+# If the first sequence of non-whitespace characters in str is not a valid integral number,
# or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
-#
-# If no valid conversion could be performed, a zero value is returned.
+#
+# If no valid conversion could be performed, a zero value is returned.
# If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
#
@@ -35,14 +35,14 @@ def myAtoi(self, str):
INT_MAX = 2147483647
INT_MIN = -2147483648
result = 0
-
+
if not str:
return result
-
+
i = 0
while i < len(str) and str[i].isspace():
i += 1
-
+
sign = 1
if str[i] == "+":
i += 1
@@ -55,13 +55,13 @@ def myAtoi(self, str):
return INT_MAX if sign > 0 else INT_MIN
result = result * 10 + int(str[i])
i += 1
-
+
return sign * result
if __name__ == "__main__":
- print Solution().atoi("")
+ print Solution().atoi("")
print Solution().atoi("-1")
- print Solution().atoi("2147483647")
- print Solution().atoi("2147483648")
- print Solution().atoi("-2147483648")
- print Solution().atoi("-2147483649")
+ print Solution().atoi("2147483647")
+ print Solution().atoi("2147483648")
+ print Solution().atoi("-2147483648")
+ print Solution().atoi("-2147483649")
diff --git a/Python/strobogrammatic-number-ii.py b/Python/strobogrammatic-number-ii.py
index da089c481..a914402b2 100644
--- a/Python/strobogrammatic-number-ii.py
+++ b/Python/strobogrammatic-number-ii.py
@@ -14,7 +14,7 @@ def findStrobogrammaticRecu(self, n, k):
return ['']
elif k == 1:
return ['0', '1', '8']
-
+
result = []
for num in self.findStrobogrammaticRecu(n, k - 2):
for key, val in self.lookup.iteritems():
diff --git a/Python/strobogrammatic-number-iii.py b/Python/strobogrammatic-number-iii.py
index d45aa3d49..23bf9b7b1 100644
--- a/Python/strobogrammatic-number-iii.py
+++ b/Python/strobogrammatic-number-iii.py
@@ -25,7 +25,7 @@ def countStrobogrammaticUntil(self, num, can_start_with_0):
count += 1
self.cache[num] = count
return count
-
+
for key, val in self.lookup.iteritems():
if can_start_with_0 or key != '0':
if num[0] > key:
@@ -36,7 +36,7 @@ def countStrobogrammaticUntil(self, num, can_start_with_0):
elif num[0] == key:
if len(num) == 2: # num is like 12".
if num[-1] >= val:
- count += 1
+ count += 1
else:
if num[-1] >= val: # num is like "102".
count += self.countStrobogrammaticUntil(self.getMid(num), True);
diff --git a/Python/strong-password-checker.py b/Python/strong-password-checker.py
index 90269f9fc..2776c8dfa 100644
--- a/Python/strong-password-checker.py
+++ b/Python/strong-password-checker.py
@@ -36,7 +36,7 @@ def strongPasswordChecker(self, s):
while i < len(s) and s[i] == s[i-1]:
length += 1
i += 1
-
+
total_change_cnt += length / 3
if length % 3 == 0:
one_change_cnt += 1
@@ -46,16 +46,16 @@ def strongPasswordChecker(self, s):
three_change_cnt += 1
else:
i += 1
-
+
if len(s) < 6:
return max(missing_type_cnt, 6 - len(s))
elif len(s) <= 20:
return max(missing_type_cnt, total_change_cnt)
else:
delete_cnt = len(s) - 20
-
+
total_change_cnt -= min(delete_cnt, one_change_cnt * 1) / 1
total_change_cnt -= min(max(delete_cnt - one_change_cnt, 0), two_change_cnt * 2) / 2
total_change_cnt -= min(max(delete_cnt - one_change_cnt - 2 * two_change_cnt, 0), three_change_cnt * 3) / 3
-
+
return delete_cnt + max(missing_type_cnt, total_change_cnt)
diff --git a/Python/student-attendance-record-i.py b/Python/student-attendance-record-i.py
index 07c836558..e63511eae 100644
--- a/Python/student-attendance-record-i.py
+++ b/Python/student-attendance-record-i.py
@@ -34,4 +34,4 @@ def checkRecord(self, s):
if i < len(s) - 2 and s[i] == s[i+1] == s[i+2] == 'L':
return False
return True
-
+
diff --git a/Python/student-attendance-record-ii.py b/Python/student-attendance-record-ii.py
index 2b1cc99b6..c52793b45 100644
--- a/Python/student-attendance-record-ii.py
+++ b/Python/student-attendance-record-ii.py
@@ -14,11 +14,11 @@
#
# Example 1:
# Input: n = 2
-# Output: 8
+# Output: 8
# Explanation:
# There are 8 records with length 2 will be regarded as rewardable:
# "PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"
-# Only "AA" won't be regarded as rewardable owing to more than one absent times.
+# Only "AA" won't be regarded as rewardable owing to more than one absent times.
# Note: The value of n won't exceed 100,000.
class Solution(object):
diff --git a/Python/subarray-product-less-than-k.py b/Python/subarray-product-less-than-k.py
index 3650ab757..9d947ca72 100644
--- a/Python/subarray-product-less-than-k.py
+++ b/Python/subarray-product-less-than-k.py
@@ -35,4 +35,4 @@ def numSubarrayProductLessThanK(self, nums, k):
start += 1
result += i-start+1
return result
-
+
diff --git a/Python/subsets-ii.py b/Python/subsets-ii.py
index f30e20486..ebd20f0bb 100644
--- a/Python/subsets-ii.py
+++ b/Python/subsets-ii.py
@@ -2,13 +2,13 @@
# Space: O(1)
# Given a collection of integers that might contain duplicates, S, return all possible subsets.
-#
+#
# Note:
# Elements in a subset must be in non-descending order.
# The solution set must not contain duplicate subsets.
# For example,
# If S = [1,2,2], a solution is:
-#
+#
# [
# [2],
# [1],
@@ -49,7 +49,7 @@ def subsetsWithDup(self, nums):
result = []
i, count = 0, 1 << len(nums)
nums.sort()
-
+
while i < count:
cur = []
for j in xrange(len(nums)):
@@ -58,7 +58,7 @@ def subsetsWithDup(self, nums):
if cur not in result:
result.append(cur)
i += 1
-
+
return result
@@ -73,7 +73,7 @@ def subsetsWithDup(self, nums):
result = []
self.subsetsWithDupRecu(result, [], sorted(nums))
return result
-
+
def subsetsWithDupRecu(self, result, cur, nums):
if not nums:
if cur not in result:
@@ -82,6 +82,6 @@ def subsetsWithDupRecu(self, result, cur, nums):
self.subsetsWithDupRecu(result, cur, nums[1:])
self.subsetsWithDupRecu(result, cur + [nums[0]], nums[1:])
-
+
if __name__ == "__main__":
print Solution().subsetsWithDup([1, 2, 2])
diff --git a/Python/subsets.py b/Python/subsets.py
index 113b810e7..83ba120db 100644
--- a/Python/subsets.py
+++ b/Python/subsets.py
@@ -2,13 +2,13 @@
# Space: O(1)
# Given a set of distinct integers, S, return all possible subsets.
-#
+#
# Note:
# Elements in a subset must be in non-descending order.
# The solution set must not contain duplicate subsets.
# For example,
# If S = [1,2,3], a solution is:
-#
+#
# [
# [3],
# [1],
@@ -47,7 +47,7 @@ def subsets(self, nums):
result = []
i, count = 0, 1 << len(nums)
nums.sort()
-
+
while i < count:
cur = []
for j in xrange(len(nums)):
@@ -55,7 +55,7 @@ def subsets(self, nums):
cur.append(nums[j])
result.append(cur)
i += 1
-
+
return result
@@ -68,11 +68,11 @@ def subsets(self, nums):
:rtype: List[List[int]]
"""
return self.subsetsRecu([], sorted(nums))
-
+
def subsetsRecu(self, cur, nums):
if not nums:
return [cur]
-
+
return self.subsetsRecu(cur, nums[1:]) + self.subsetsRecu(cur + [nums[0]], nums[1:])
diff --git a/Python/subtree-of-another-tree.py b/Python/subtree-of-another-tree.py
index 9b0987f33..423941776 100644
--- a/Python/subtree-of-another-tree.py
+++ b/Python/subtree-of-another-tree.py
@@ -16,7 +16,7 @@
# / \
# 1 2
# Given tree t:
-# 4
+# 4
# / \
# 1 2
# Return true, because t has the same structure and node values with a subtree of s.
@@ -64,5 +64,5 @@ def preOrderTraverse(s, t):
(isSame(s, t) or \
preOrderTraverse(s.left, t) or \
preOrderTraverse(s.right, t))
-
+
return preOrderTraverse(s, t)
diff --git a/Python/sudoku-solver.py b/Python/sudoku-solver.py
index fff654616..39835b421 100644
--- a/Python/sudoku-solver.py
+++ b/Python/sudoku-solver.py
@@ -2,9 +2,9 @@
# Space: (1)
#
# Write a program to solve a Sudoku puzzle by filling the empty cells.
-#
+#
# Empty cells are indicated by the character '.'.
-#
+#
# You may assume that there will be only one unique solution.
#
@@ -29,7 +29,7 @@ def isValid(board, x, y):
j += 1
i += 1
return True
-
+
def solver(board):
for i in xrange(len(board)):
for j in xrange(len(board[0])):
diff --git a/Python/sum-of-left-leaves.py b/Python/sum-of-left-leaves.py
index 4ca0bd5c0..fb0787415 100644
--- a/Python/sum-of-left-leaves.py
+++ b/Python/sum-of-left-leaves.py
@@ -34,5 +34,5 @@ def sumOfLeftLeavesHelper(root, is_left):
return root.val if is_left else 0
return sumOfLeftLeavesHelper(root.left, True) + \
sumOfLeftLeavesHelper(root.right, False)
-
+
return sumOfLeftLeavesHelper(root, False)
diff --git a/Python/sum-root-to-leaf-numbers.py b/Python/sum-root-to-leaf-numbers.py
index 775c1920b..faad48bff 100644
--- a/Python/sum-root-to-leaf-numbers.py
+++ b/Python/sum-root-to-leaf-numbers.py
@@ -2,19 +2,19 @@
# Space: O(h), h is height of binary tree
#
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
-#
+#
# An example is the root-to-leaf path 1->2->3 which represents the number 123.
-#
+#
# Find the total sum of all root-to-leaf numbers.
-#
+#
# For example,
-#
+#
# 1
# / \
# 2 3
# The root-to-leaf path 1->2 represents the number 12.
# The root-to-leaf path 1->3 represents the number 13.
-#
+#
# Return the sum = 12 + 13 = 25.
#
@@ -30,18 +30,18 @@ class Solution:
# @return an integer
def sumNumbers(self, root):
return self.sumNumbersRecu(root, 0)
-
+
def sumNumbersRecu(self, root, num):
if root is None:
return 0
-
+
if root.left is None and root.right is None:
return num * 10 + root.val
-
+
return self.sumNumbersRecu(root.left, num * 10 + root.val) + self.sumNumbersRecu(root.right, num * 10 + root.val)
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
- print Solution().sumNumbers(root)
+ print Solution().sumNumbers(root)
diff --git a/Python/super-washing-machines.py b/Python/super-washing-machines.py
index 1db926366..202cba8db 100644
--- a/Python/super-washing-machines.py
+++ b/Python/super-washing-machines.py
@@ -20,27 +20,27 @@
#
# Output: 3
#
-# Explanation:
+# Explanation:
# 1st move: 1 0 <-- 5 => 1 1 4
-# 2nd move: 1 <-- 1 <-- 4 => 2 1 3
-# 3rd move: 2 1 <-- 3 => 2 2 2
+# 2nd move: 1 <-- 1 <-- 4 => 2 1 3
+# 3rd move: 2 1 <-- 3 => 2 2 2
# Example2
#
# Input: [0,3,0]
#
# Output: 2
#
-# Explanation:
-# 1st move: 0 <-- 3 0 => 1 2 0
-# 2nd move: 1 2 --> 0 => 1 1 1
+# Explanation:
+# 1st move: 0 <-- 3 0 => 1 2 0
+# 2nd move: 1 2 --> 0 => 1 1 1
# Example3
#
# Input: [0,2,0]
#
# Output: -1
#
-# Explanation:
-# It's impossible to make all the three washing machines have the same number of dresses.
+# Explanation:
+# It's impossible to make all the three washing machines have the same number of dresses.
# Note:
# The range of n is [1, 10000].
# The range of dresses number in a super washing machine is [0, 1e5].
@@ -54,7 +54,7 @@ def findMinMoves(self, machines):
total = sum(machines)
if total % len(machines): return -1
- result, target, curr = 0, total / len(machines), 0
+ result, target, curr = 0, total / len(machines), 0
for n in machines:
curr += n - target
result = max(result, max(n - target, abs(curr)))
diff --git a/Python/swap-nodes-in-pairs.py b/Python/swap-nodes-in-pairs.py
index c11df1225..91c039f8f 100644
--- a/Python/swap-nodes-in-pairs.py
+++ b/Python/swap-nodes-in-pairs.py
@@ -2,10 +2,10 @@
# Space: O(1)
#
# Given a linked list, swap every two adjacent nodes and return its head.
-#
+#
# For example,
# Given 1->2->3->4, you should return the list as 2->1->4->3.
-#
+#
# Your algorithm should use only constant space.
# You may not modify the values in the list, only nodes itself can be changed.
#
@@ -15,7 +15,7 @@ class ListNode:
def __init__(self, x):
self.val = x
self.next = None
-
+
def __repr__(self):
if self:
return "{} -> {}".format(self.val, self.next)
@@ -39,4 +39,3 @@ def swapPairs(self, head):
head = ListNode(1)
head.next, head.next.next, head.next.next.next = ListNode(2), ListNode(3), ListNode(4)
print Solution().swapPairs(head)
-
\ No newline at end of file
diff --git a/Python/swim-in-rising-water.py b/Python/swim-in-rising-water.py
index 0418afd34..f2034acac 100644
--- a/Python/swim-in-rising-water.py
+++ b/Python/swim-in-rising-water.py
@@ -54,7 +54,7 @@ def union_set(self, x, y):
return False
self.set[min(x_root, y_root)] = max(x_root, y_root)
return True
-
+
class Solution(object):
def swimInWater(self, grid):
@@ -68,7 +68,7 @@ def swimInWater(self, grid):
for j in xrange(n):
positions[grid[i][j]] = (i, j)
directions = ((-1, 0), (1, 0), (0, -1), (0, 1))
-
+
union_find = UnionFind(n**2)
for elevation in xrange(n**2):
i, j = positions[elevation]
@@ -79,4 +79,4 @@ def swimInWater(self, grid):
if union_find.find_set(0) == union_find.find_set(n**2-1):
return elevation
return n**2-1
-
+
diff --git a/Python/symmetric-tree.py b/Python/symmetric-tree.py
index 709864217..3bc99e50b 100644
--- a/Python/symmetric-tree.py
+++ b/Python/symmetric-tree.py
@@ -1,9 +1,9 @@
# Time: O(n)
# Space: O(h), h is height of binary tree
# Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
-#
+#
# For example, this binary tree is symmetric:
-#
+#
# 1
# / \
# 2 2
@@ -36,24 +36,24 @@ def isSymmetric(self, root):
stack = []
stack.append(root.left)
stack.append(root.right)
-
+
while stack:
p, q = stack.pop(), stack.pop()
-
+
if p is None and q is None:
continue
-
+
if p is None or q is None or p.val != q.val:
return False
-
+
stack.append(p.left)
stack.append(q.right)
-
+
stack.append(p.right)
stack.append(q.left)
-
+
return True
-
+
# Recursive solution
class Solution2:
# @param root, a tree node
@@ -61,9 +61,9 @@ class Solution2:
def isSymmetric(self, root):
if root is None:
return True
-
+
return self.isSymmetricRecu(root.left, root.right)
-
+
def isSymmetricRecu(self, left, right):
if left is None and right is None:
return True
@@ -77,4 +77,4 @@ def isSymmetricRecu(self, left, right):
root.left.left, root.right.right = TreeNode(3), TreeNode(3)
root.left.right, root.right.left = TreeNode(4), TreeNode(4)
print Solution().isSymmetric(root)
-
+
diff --git a/Python/tag-validator.py b/Python/tag-validator.py
index 25946efa0..7409ec413 100644
--- a/Python/tag-validator.py
+++ b/Python/tag-validator.py
@@ -10,7 +10,7 @@
#