text stringlengths 37 1.41M |
|---|
Words = "Why sometimes I have believed as many as six impossible things before breakfast".split()
print(Words)
'''To generate an a list comprehension, the syntax is [expression(item) for item in iterable] Fore mexample:'''
print([len(word) for word in Words])
print([len(word) for word in Words if len(word)>3])
#This is the same as doing this:
lengths = []
for word in Words:
lengths.append(len(word))
print(lengths) |
# HomeWork_3
# Maayan Nadivi - 208207068
# Alice Aidlin - 208448326
def main():
A = [[4, 2, 0], [2, 10, 4], [0, 4, 5]]
b = [[2], [6], [5]]
choise = int(input('Select the desired iterative method:\n1.Jacobi\n2.Gaus Zaidl\n'))
if choise == 1:
Jacobi(A, b)
main()
elif choise == 2:
Gauss_Zeidl(A, b)
main()
else:
print('Wrong Choice ! Try again ! ')
main()
def Dominant_diagonal(matrix):
if abs(matrix[0][1])+abs(matrix[0][2]) > matrix[0][0]:
print('There is no dominant diagonal')
return False
if abs(matrix[1][0])+abs(matrix[1][2]) > matrix[1][1]:
print('There is no dominant diagonal')
return False
if abs(matrix[2][0])+abs(matrix[2][1]) > matrix[2][2]:
print('There is no dominant diagonal')
return False
return True
def Jacobi(A, b):
if Dominant_diagonal(A) is True:
mat = list(range(3)) # make it list
for i in range(3):
mat[i] = list(range(1))
eps = 0.00001
counter = 0
x_r = 0
y_r = 0
z_r = 0
mat[0][0] = x_r
mat[1][0] = y_r
mat[2][0] = z_r
print('Iteration {} '.format(counter))
print(mat)
counter = counter+1
x_r1 = (b[0][0] - A[0][1] * y_r - A[0][2] * z_r) / A[0][0]
y_r1 = (b[1][0] - A[1][0] * x_r - A[1][2] * z_r) / A[1][1]
z_r1 = (b[2][0] - A[2][0] * x_r - A[2][1] * y_r) / A[2][2]
mat[0][0] = x_r1
mat[1][0] = y_r1
mat[2][0] = z_r1
print('Iteration {} '.format(counter))
print(mat)
while abs(x_r1 - x_r) > eps:
counter = counter+1
x_r = x_r1
y_r = y_r1
z_r = z_r1
x_r1 = (b[0][0] - A[0][1] * y_r - A[0][2] * z_r) / A[0][0]
y_r1 = (b[1][0] - A[1][0] * x_r - A[1][2] * z_r) / A[1][1]
z_r1 = (b[2][0] - A[2][0] * x_r - A[2][1] * y_r) / A[2][2]
mat[0][0] = x_r1
mat[1][0] = y_r1
mat[2][0] = z_r1
print('Iteration {} '.format(counter))
print(mat)
def Gauss_Zeidl(A, b):
if Dominant_diagonal(A) is True:
mat = list(range(3)) # make it list
for i in range(3):
mat[i] = list(range(1))
eps = 0.00001
counter = 0
x_r = 0
y_r = 0
z_r = 0
mat[0][0] = x_r
mat[1][0] = y_r
mat[2][0] = z_r
print('Iteration {} '.format(counter))
print(mat)
counter = counter+1
x_r1 = (b[0][0] - A[0][1] * y_r - A[0][2] * z_r) / A[0][0]
y_r1 = (b[1][0] - A[1][0] * x_r1 - A[1][2] * z_r) / A[1][1]
z_r1 = (b[2][0] - A[2][0] * x_r1 - A[2][1] * y_r1) / A[2][2]
mat[0][0] = x_r1
mat[1][0] = y_r1
mat[2][0] = z_r1
print('Iteration {} '.format(counter))
print(mat)
while abs(x_r1 - x_r) > eps:
counter = counter+1
x_r = x_r1
y_r = y_r1
z_r = z_r1
x_r1 = (b[0][0] - A[0][1] * y_r - A[0][2] * z_r) / A[0][0]
y_r1 = (b[1][0] - A[1][0] * x_r1 - A[1][2] * z_r) / A[1][1]
z_r1 = (b[2][0] - A[2][0] * x_r1 - A[2][1] * y_r1) / A[2][2]
mat[0][0] = x_r1
mat[1][0] = y_r1
mat[2][0] = z_r1
print('Iteration {} '.format(counter))
print(mat)
main() |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def _init_(self, data):
self.head = Node(data)
def append(self, data):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(data)
def get_node(self, idx):
cnt = 0
node = self.head
while cnt < idx:
cnt += 1
node = node.next
return node
def add_node(self, idx, value):
new_node = Node(value)
if (idx == 0):
new_node.next = self.head
self.head = new_node
return
node = self.get_node(idx-1)
next_node = node_next
node_next = new_node
new_node.next = next_node
def delete_node(self, index):
if index == 0:
self.head = self.head.next
return
node = self.get_node(index-1)
node.next = node.next.next
|
def myfun():
print("welcome to my calc")
a = int(input("enter first num:"))
b = int(input("enter second num:"))
print("1. Sum \n2. Multi \n3. Div \n4. sub")
choice = int(input("Select your choice: "))
if choice == 1:
print(a + b)
elif choice == 2:
print(a * b)
elif choice == 3:
print(a/b)
elif choice == 4:
print(a - b)
else:
print("Try again:\n")
return myfun()
myfun()
|
# binary tree
# https://www.interviewbit.com/problems/max-depth-of-binary-tree/
# Time: O(nodes)
# Space: O(max-depth)
# Find max depth of binary tree
# Uses two stacks instead of recursion
# http://stackoverflow.com/a/19914505/3542151
def max_depth_nr(root):
depth = 0
path, explore = [], [root]
while explore:
node = explore[-1]
if path and path[-1] is node:
depth = max(depth, len(path))
explore.pop()
path.pop()
else:
path.append(node)
if node.left: explore.append(node.left)
if node.right: explore.append(node.right)
return depth
|
# binary tree, recursion
# https://www.interviewbit.com/problems/sorted-array-to-balanced-bst/
# Time: O(n)
# Space: O(log n)
# Construct balanced binary tree form sorted array
def btree_from_sorted_array(array, start = 0, end = None):
if end is None: end = len(array)
if end == start: return None
mid = (start + end) // 2
root = TreeNode(array[mid])
root.left = btree_from_sorted_array(array, start, mid)
root.right = btree_from_sorted_array(array, mid + 1, end)
return root
class TreeNode:
def __init__(self, val):
self.val = val
self.left = self.right = None
|
class Solution:
def twoSum(self, numbers, target):
"""
:type numbers: List[int]
:type target: int
:rtype: List[int]
"""
solution = []
for i in range(len(numbers)):
real_target = target - numbers[i]
index = binary_search(numbers, i + 1, real_target)
if index != -1:
solution.append(i + 1)
solution.append(index + 1)
return solution
def binary_search(array, lo, target):
hi = len(array) - 1
while lo <= hi:
mid = (lo + hi) // 2
if array[mid] == target:
return mid
elif array[mid] > target:
hi = mid - 1
else:
lo = mid + 1
return -1 |
'''
-Hard-
*DP*
A farmer has a rectangular grid of land with m rows and n columns that can be divided into unit cells. Each cell is either fertile (represented by a 1) or barren (represented by a 0). All cells outside the grid are considered barren.
A pyramidal plot of land can be defined as a set of cells with the following criteria:
The number of cells in the set has to be greater than 1 and all cells must be fertile.
The apex of a pyramid is the topmost cell of the pyramid. The height of a pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r <= i <= r + h - 1 and c - (i - r) <= j <= c + (i - r).
An inverse pyramidal plot of land can be defined as a set of cells with similar criteria:
The number of cells in the set has to be greater than 1 and all cells must be fertile.
The apex of an inverse pyramid is the bottommost cell of the inverse pyramid. The height of an inverse pyramid is the number of rows it covers. Let (r, c) be the apex of the pyramid, and its height be h. Then, the plot comprises of cells (i, j) where r - h + 1 <= i <= r and c - (r - i) <= j <= c + (r - i).
Some examples of valid and invalid pyramidal (and inverse pyramidal) plots are shown below. Black cells indicate fertile cells.
Given a 0-indexed m x n binary matrix grid representing the farmland, return the total number of pyramidal and inverse pyramidal plots that can be found in grid.
Example 1:
Input: grid = [[0,1,1,0],[1,1,1,1]]
Output: 2
Explanation: The 2 possible pyramidal plots are shown in blue and red respectively.
There are no inverse pyramidal plots in this grid.
Hence total number of pyramidal and inverse pyramidal plots is 2 + 0 = 2.
Example 2:
Input: grid = [[1,1,1],[1,1,1]]
Output: 2
Explanation: The pyramidal plot is shown in blue, and the inverse pyramidal plot is shown in red.
Hence the total number of plots is 1 + 1 = 2.
Example 3:
Input: grid = [[1,1,1,1,0],[1,1,1,1,1],[1,1,1,1,1],[0,1,0,0,1]]
Output: 13
Explanation: There are 7 pyramidal plots, 3 of which are shown in the 2nd and 3rd figures.
There are 6 inverse pyramidal plots, 2 of which are shown in the last figure.
The total number of plots is 7 + 6 = 13.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 1000
1 <= m * n <= 105
grid[i][j] is either 0 or 1.
'''
from typing import List
class Solution:
def countPyramids(self, grid: List[List[int]]) -> int:
reversed_grid = []
for i in range(len(grid) - 1, -1, -1):
reversed_grid.append(grid[i][:])
output = self.helper(grid)
output += self.helper(reversed_grid)
return output
def helper(self, grid):
output, rows, cols = 0, len(grid), len(grid[0])
for i in range(1, rows):
for j in range(1, cols - 1):
if grid[i][j] and grid[i - 1][j]:
grid[i][j] = min(grid[i - 1][j - 1], grid[i - 1][j + 1]) + 1
output += grid[i][j] - 1
return output
if __name__ == "__main__":
print(Solution().countPyramids(grid = [[0,1,1,0],[1,1,1,1]])) |
'''
-Easy-
Given an integer array nums, find three numbers whose product is maximum and return the maximum product.
Example 1:
Input: nums = [1,2,3]
Output: 6
Example 2:
Input: nums = [1,2,3,4]
Output: 24
Example 3:
Input: nums = [-1,-2,-3]
Output: -6
Constraints:
3 <= nums.length <= 10^4
-1000 <= nums[i] <= 1000
'''
from typing import List
class Solution:
def maximumProduct(self, nums: List[int]) -> int:
max1 = max2 = max3 = -float('inf')
min1 = min2 = float('inf')
for i in nums:
if i > max1:
max3, max2, max1 = max2, max1, i
elif i > max2:
max3, max2 = max2, i
elif i > max3:
max3 = i
if i < min1:
min2, min1 = min1, i
elif i < min2:
min2 = i
return max(max1*max2*max3, min1*min2*max1)
if __name__ == '__main__':
print(Solution().maximumProduct([1,2,3])) |
'''
-Medium-
Given a binary tree, find the subtree with maximum average. Return the root of the subtree.
LintCode will print the subtree which root is your return node.
It's guaranteed that there is only one subtree with maximum average.
样例
Example 1
Input:
{1,-5,11,1,2,4,-2}
Output:11
Explanation:
The tree is look like this:
1
/ \
-5 11
/ \ / \
1 2 4 -2
The average of subtree of 11 is 4.3333, is the maximun.
Example 2
Input:
{1,-5,11}
Output:11
Explanation:
1
/ \
-5 11
The average of subtree of 1,-5,11 is 2.333,-5,11. So the subtree of 11 is the maximun.
标签
企业
Amazon
相关题目
632
Binary Tree Maximum Node
简单
628
Maximum Subtree
简单
596
Minimum Subtree
简单
'''
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
from BinaryTree import (null, constructBinaryTree, TreeNode)
class Solution:
"""
@param root: the root of binary tree
@return: the root of the maximum average of subtree
"""
def findSubtree2(self, root):
# write your code here
self.ans = None
maxAve = [-float('inf')]
def helper(node):
if not node: return (0, 0)
ls, ln = helper(node.left)
rs, rn = helper(node.right)
n = rn + ln + 1
s = ls + rs + node.val
ave = s/n
if maxAve[0] < ave:
maxAve[0] = ave
self.ans = node
return s, n
helper(root)
return self.ans
if __name__ == "__main__":
root = constructBinaryTree([1,-5,11,1,2,4,-2])
root.prettyPrint()
ans = Solution().findSubtree2(root)
print(ans.val)
root = constructBinaryTree([1,-5,11])
root.prettyPrint()
ans = Solution().findSubtree2(root)
print(ans.val) |
'''
-Medium-
*Union Find*
*BFS*
Given a list of pairs of equivalent words synonyms and a sentence text,
Return all possible synonymous sentences sorted lexicographically.
Example 1:
Input:
synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]],
text = "I am happy today but was sad yesterday"
Output:
["I am cheerful today but was sad yesterday",
"I am cheerful today but was sorrow yesterday",
"I am happy today but was sad yesterday",
"I am happy today but was sorrow yesterday",
"I am joy today but was sad yesterday",
"I am joy today but was sorrow yesterday"]
Example 2:
Input: synonyms = [["happy","joy"],["cheerful","glad"]], text = "I am happy today but was sad yesterday"
Output: ["I am happy today but was sad yesterday","I am joy today but was sad yesterday"]
Example 3:
Input: synonyms = [["a","b"],["c","d"],["e","f"]], text = "a c e"
Output: ["a c e","a c f","a d e","a d f","b c e","b c f","b d e","b d f"]
Example 4:
Input: synonyms = [["a","QrbCl"]], text = "d QrbCl ya ya NjZQ"
Output: ["d QrbCl ya ya NjZQ","d a ya ya NjZQ"]
Constraints:
0 <= synonyms.length <= 10
synonyms[i].length == 2
synonyms[i][0] != synonyms[i][1]
All words consist of at most 10 English letters only.
text is a single space separated sentence of at most 10 words.
Hints
Find all synonymous groups of words.
Use union-find data structure.
By backtracking, generate all possible statements.
'''
from collections import defaultdict, deque
class UnionFind(object):
"""
groups: word to group mapping
"""
def __init__(self, pairs = None):
self.groups = {}
'''
for w1,w2 in pairs:
self.groups[w1] = w1
self.groups[w2] = w2
for w1,w2 in pairs:
self.union(w1, w2)
'''
def find(self, word):
"""
Return the group of the given word
Add the word if the word does not already exist
"""
if word not in self.groups:
self.groups[word] = word
return self.groups[word]
#if word == self.groups[word]:
# return word
#return self.find(self.groups[word])
def union(self, word1, word2):
"""
Union the 2 groups and keep the lexicographically smallest group
"""
group1, group2 = self.find(word1), self.find(word2) # O(1)
if group1 == group2: # already in the same group
return
if group1 > group2: # let group1 be the lexicographically smaller group
group1, group2 = group2, group1
for word in self.groups: # worst case O(# words in group) which is less than O(N)
if self.groups[word] == group2:
self.groups[word] = group1
class Solution(object):
def generateSentences(self, synonyms, text):
"""
:type synonyms: List[List[str]], N pairs
:type text: str, M words
:rtype: List[str]
"""
#return self.generateSentencesBFS(synonyms, text)
return self.generateSentencesUnionFind(synonyms, text)
def generateSentencesBFS(self, synonyms, text):
graph = defaultdict(list)
for w1, w2 in synonyms:
graph[w1].append(w2)
graph[w2].append(w1)
words = text.split(' ')
res = [[]]
def bfs(word):
res = []
candidates = deque([word])
visited = set([word])
while candidates:
candidate = candidates.popleft()
res.append(candidate)
for synonym in graph[candidate]:
if synonym not in visited:
candidates.append(synonym)
visited.add(synonym)
return res
for word in words:
candidates = sorted(bfs(word))
res = [r + [candidate] for r in res for candidate in candidates]
return [" ".join(sentence) for sentence in res]
def generateSentencesUnionFind(self, synonyms, text):
uf = UnionFind()
# overall this is probably O(NlogN) instead of O(N^2)
for w1, w2 in synonyms: # O(N)
uf.union(w1, w2)
words = text.split(" ")
res = []
def backtrack(idx, sentence):
if idx == len(words): # we've reached the end
res.append(" ".join(sentence))
else:
word = words[idx]
group = uf.groups.get(word) # O(1)
if group:
candidates = sorted(word for word in uf.groups if uf.groups[word] == group) # O(N)
for candidate in candidates:
backtrack(idx + 1, sentence + [candidate])
else:
backtrack(idx + 1, sentence + [word])
backtrack(0, [])
return res
if __name__ == "__main__":
synonyms = [["happy","joy"],["cheerful","glad"]]
text = "I am happy today but was sad yesterday"
print(Solution().generateSentences(synonyms, text))
synonyms = [["happy","joy"],["sad","sorrow"],["joy","cheerful"]]
text = "I am happy today but was sad yesterday"
print(Solution().generateSentences(synonyms, text))
|
'''
-Medium-
*Sweep Line*
You are given a 0-indexed array nums and a non-negative integer k.
In one operation, you can do the following:
Choose an index i that hasn't been chosen before from the range [0, nums.length - 1].
Replace nums[i] with any integer from the range [nums[i] - k, nums[i] + k].
The beauty of the array is the length of the longest subsequence consisting of equal elements.
Return the maximum possible beauty of the array nums after applying the operation any number of times.
Note that you can apply the operation to each index only once.
A subsequence of an array is a new array generated from the original array by deleting some elements (possibly none) without changing the order of the remaining elements.
Example 1:
Input: nums = [4,6,1,2], k = 2
Output: 3
Explanation: In this example, we apply the following operations:
- Choose index 1, replace it with 4 (from range [4,8]), nums = [4,4,1,2].
- Choose index 3, replace it with 4 (from range [0,4]), nums = [4,4,1,4].
After the applied operations, the beauty of the array nums is 3 (subsequence consisting of indices 0, 1, and 3).
It can be proven that 3 is the maximum possible length we can achieve.
Example 2:
Input: nums = [1,1,1,1], k = 10
Output: 4
Explanation: In this example we don't have to apply any operations.
The beauty of the array nums is 4 (whole array).
Constraints:
1 <= nums.length <= 105
0 <= nums[i], k <= 105
'''
from typing import List
class Solution:
def maximumBeauty(self, nums: List[int], k: int) -> int:
events = []
for i in nums:
events.append((i-k, -1))
events.append((i+k, 1))
events.sort()
ans, tot = 0, 0
# print(events)
for v,t in events:
if t == -1:
tot += 1
else:
tot -= 1
ans = max(ans, tot)
return ans
if __name__ == "__main__":
print(Solution().maximumBeauty(nums = [4,6,1,2], k = 2))
print(Solution().maximumBeauty(nums = [1,1,1,1], k = 10))
print(Solution().maximumBeauty(nums = [13,46,71], k = 29))
|
'''
-Hard-
*Monotonic Stack*
*Prefix Max*
*Suffix Min*
You are given an integer array arr.
We split arr into some number of chunks (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array.
Return the largest number of chunks we can make to sort the array.
Example 1:
Input: arr = [5,4,3,2,1]
Output: 1
Explanation:
Splitting into two or more chunks will not return the required result.
For example, splitting into [5, 4], [3, 2, 1] will result in [4, 5, 1, 2, 3], which isn't sorted.
Example 2:
Input: arr = [2,1,3,4,4]
Output: 4
Explanation:
We can split into two chunks, such as [2, 1], [3, 4, 4].
However, splitting into [2, 1], [3], [4], [4] is the highest number of chunks possible.
Constraints:
1 <= arr.length <= 2000
0 <= arr[i] <= 108
'''
from typing import List
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
# Intuition: the mono-stack keeps the max of each chunk, when
# the max of current chunk is larger than next number, merge next
# number to current chunk (with stack.pop())
stack = []
for num in arr:
largest = num
while stack and stack[-1] > num:
largest = max(largest, stack.pop())
stack.append(largest)
return len(stack)
def maxChunksToSorted2(self, arr: List[int]) -> int:
n = len(arr)
preMax, sufMin = [0]*n, [0]*n
preMax[0] = arr[0]
for i in range(1, n):
preMax[i] = max(preMax[i-1], arr[i])
sufMin[-1] = arr[-1]
for i in range(n-2, -1, -1):
sufMin[i] = min(sufMin[i+1], arr[i])
res = 0
for i in range(n-1):
if preMax[i] <= sufMin[i+1]: res += 1
return res+1
if __name__ == "__main__":
print(Solution().maxChunksToSorted(arr = [5,4,3,2,1]))
print(Solution().maxChunksToSorted(arr = [2,1,3,4,4]))
print(Solution().maxChunksToSorted2(arr = [5,4,3,2,1]))
print(Solution().maxChunksToSorted2(arr = [2,1,3,4,4])) |
'''
-Hard-
*DP*
*Memoization*
*Memoization with tuple*
*Memoization with bitmask*
You are given four integers, m, n, introvertsCount, and extrovertsCount. You have an m x n grid, and
there are two types of people: introverts and extroverts. There are introvertsCount introverts and
extrovertsCount extroverts.
You should decide how many people you want to live in the grid and assign each of them one grid cell.
Note that you do not have to have all the people living in the grid.
The happiness of each person is calculated as follows:
Introverts start with 120 happiness and lose 30 happiness for each neighbor (introvert or extrovert).
Extroverts start with 40 happiness and gain 20 happiness for each neighbor (introvert or extrovert).
Neighbors live in the directly adjacent cells north, east, south, and west of a person's cell.
The grid happiness is the sum of each person's happiness. Return the maximum possible grid happiness.
Example 1:
Input: m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2
Output: 240
Explanation: Assume the grid is 1-indexed with coordinates (row, column).
We can put the introvert in cell (1,1) and put the extroverts in cells (1,3) and (2,3).
- Introvert at (1,1) happiness: 120 (starting happiness) - (0 * 30) (0 neighbors) = 120
- Extrovert at (1,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
- Extrovert at (2,3) happiness: 40 (starting happiness) + (1 * 20) (1 neighbor) = 60
The grid happiness is 120 + 60 + 60 = 240.
The above figure shows the grid in this example with each person's happiness. The introvert stays in the light green cell while the extroverts live on the light purple cells.
Example 2:
Input: m = 3, n = 1, introvertsCount = 2, extrovertsCount = 1
Output: 260
Explanation: Place the two introverts in (1,1) and (3,1) and the extrovert at (2,1).
- Introvert at (1,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
- Extrovert at (2,1) happiness: 40 (starting happiness) + (2 * 20) (2 neighbors) = 80
- Introvert at (3,1) happiness: 120 (starting happiness) - (1 * 30) (1 neighbor) = 90
The grid happiness is 90 + 80 + 90 = 260.
Example 3:
Input: m = 2, n = 2, introvertsCount = 4, extrovertsCount = 0
Output: 240
Constraints:
1 <= m, n <= 5
0 <= introvertsCount, extrovertsCount <= min(m * n, 6)
'''
from functools import lru_cache
class Solution(object):
def getMaxGridHappiness(self, m, n, introvertsCount, extrovertsCount):
"""
:type m: int
:type n: int
:type introvertsCount: int
:type extrovertsCount: int
:rtype: int
"""
def calc_cost(r, c, in_mask, ex_mask, d):
ans, up = 0, (1 << (n - 1))
if c > 0 and (in_mask & 1):
ans += d - 30;
if r > 0 and (in_mask & up):
ans += d - 30;
if c > 0 and (ex_mask & 1):
ans += d + 20;
if r > 0 and (ex_mask & up):
ans += d + 20;
return ans;
@lru_cache(None)
def dp(idx, in_mask, ex_mask, in_cnt, ex_cnt):
r, c = divmod(idx, n)
if r >= m:
return 0
n_in_mask = (in_mask << 1) & ((1 << n) - 1)
n_ex_mask = (ex_mask << 1) & ((1 << n) - 1)
#if r == 0 and c == 1 and ex_cnt == 1 and in_cnt == 1:
# print('{:04b}'.format(ex_mask),
# '{:04b}'.format(ex_mask<<1),
# '{:04b}'.format(n_ex_mask))
ans = dp(idx + 1, n_in_mask, n_ex_mask, in_cnt, ex_cnt)
if in_cnt > 0:
cur = 120 + calc_cost(r, c, in_mask, ex_mask, -30)
ans = max(ans, cur + dp(idx + 1, n_in_mask + 1, n_ex_mask, in_cnt - 1, ex_cnt))
if ex_cnt > 0:
cur = 40 + calc_cost(r, c, in_mask, ex_mask, 20)
ans = max(ans, cur + dp(idx + 1, n_in_mask, n_ex_mask + 1, in_cnt, ex_cnt - 1))
return ans
return dp(0, 0, 0, introvertsCount, extrovertsCount)
def getMaxGridHappinessFast(self, m, n, introvertsCount, extrovertsCount):
"""
:type m: int
:type n: int
:type introvertsCount: int
:type extrovertsCount: int
:rtype: int
"""
@lru_cache(None)
def helper(i, memory, intros, extros):
if intros == extros == 0 or i == N:
return 0
# 1 up n
# | | |
# # # # * * * *
# * * * X <--current pos
# ^
# |
# left
# memory holds state information (0, 1, 2) for all '*' positions
# its length is n (num of columns)
up, left = memory[0], memory[-1]
# leave room empty
best = helper(i+1, memory[1:] + tuple([0]), intros, extros)
# add an introvert
j = i % C
if intros:
score = 120 + score_map[(up, 1)] + bool(j) * score_map[(left, 1)]
best = max(best, score + helper(i+1, memory[1:] + tuple([1]), intros - 1, extros))
# add an extrovert
if extros:
score = 40 + score_map[(up, 2)] + bool(j) * score_map[(left, 2)]
best = max(best, score + helper(i+1, memory[1:] + tuple([2]), intros, extros - 1))
return best
score_map ={(0, 1): 0, # empty neighbor (0) add introvert (1) to current cell
(0, 2): 0, # empty neighbor (0) add extrovert (2) to current cell
(1, 1): -30 - 30, # introvert neighbor (1) add introvert (1) to current cell
(2, 1): 20 - 30, # extrovert neighbor (2) add introvert (1) to current cell
(1, 2): -30 + 20, # introvert neighbor (1) add extrovert (2) to current cell
(2, 2): 20 + 20} # extrovert neighbor (2) add extrovert (2) to current cell
N = m * n
C, R = sorted((m, n))
memory = tuple([0 for _ in range(C)])
return helper(0, memory, introvertsCount, extrovertsCount)
if __name__ == "__main__":
print(Solution().getMaxGridHappiness(m = 2, n = 3, introvertsCount = 1, extrovertsCount = 2)) |
'''
-Medium-
You have a binary tree with a small defect. There is exactly one invalid node where its
right child incorrectly points to another node at the same depth but to the invalid
node's right.
Given the root of the binary tree with this defect, root, return the root of the binary
tree after removing this invalid node and every node underneath it (minus the node
it incorrectly points to).
Custom testing:
The test input is read as 3 lines:
TreeNode root
int fromNode (not available to correctBinaryTree)
int toNode (not available to correctBinaryTree)
After the binary tree rooted at root is parsed, the TreeNode with value of fromNode
will have its right child pointer pointing to the TreeNode with a value of toNode.
Then, root is passed to correctBinaryTree.
Example 1:
Input: root = [1,2,3], fromNode = 2, toNode = 3
Output: [1,null,3]
Explanation: The node with value 2 is invalid, so remove it.
Example 2:
Input: root = [8,3,1,7,null,9,4,2,null,null,null,5,6], fromNode = 7, toNode = 4
Output: [8,3,1,null,null,9,4,null,null,5,6]
Explanation: The node with value 7 is invalid, so remove it and the node underneath it, node 2.
Constraints:
The number of nodes in the tree is in the range [3, 10^4].
-10^9 <= Node.val <= 10^9
All Node.val are unique.
fromNode != toNode
fromNode and toNode will exist in the tree and will be on the same depth.
toNode is to the right of fromNode.
fromNode.right is null in the initial tree from the test data.
'''
from BinaryTree import (null, TreeNode, constructBinaryTree)
from collections import deque
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def correctBinaryTreeLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
Q = deque([root])
remove = None
while Q:
nxt = deque()
n = len(Q)
m = {}
for i in range(n):
node = Q.popleft()
if node.left:
nxt.append(node.left)
if node.right:
nxt.append(node.right)
#if len(nxt) > 1:
for i in range(len(nxt)):
if nxt[i] in m:
remove = m[nxt[i]]
break
m[nxt[i].right] = nxt[i]
Q = nxt
if remove: break
def sever(root, delete):
if not root: return
if root.left == delete:
root.left.right = None
root.left = None
if root.right == delete:
root.right.right = None
root.right = None
sever(root.left, delete)
sever(root.right, delete)
print(remove.val)
sever(root, remove)
return root
def __init__(self):
self.visited = set()
def correctBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root: return None
if root.right and root.right.val in self.visited: return None
self.visited.add(root.val)
root.right = self.correctBinaryTree(root.right)
root.left = self.correctBinaryTree(root.left)
return root
if __name__=="__main__":
root = constructBinaryTree([8,3,1,7,null,9,4,2,null,null,null,null,null,5,6])
root.prettyPrint()
seven, four = None, None
def helper(root, val):
if not root: return None
if root.val == val:
return root
return helper(root.left, val) or helper(root.right, val)
seven = helper(root, 7)
four = helper(root, 4)
seven.right = four
root = Solution().correctBinaryTree(root)
root.prettyPrint()
|
'''
-Medium-
You are given the customer visit log of a shop represented by a 0-indexed string customers consisting only of characters 'N' and 'Y':
if the ith character is 'Y', it means that customers come at the ith hour
whereas 'N' indicates that no customers come at the ith hour.
If the shop closes at the jth hour (0 <= j <= n), the penalty is calculated as follows:
For every hour when the shop is open and no customers come, the penalty increases by 1.
For every hour when the shop is closed and customers come, the penalty increases by 1.
Return the earliest hour at which the shop must be closed to incur a minimum penalty.
Note that if a shop closes at the jth hour, it means the shop is closed at the hour j.
Example 1:
Input: customers = "YYNY"
Output: 2
Explanation:
- Closing the shop at the 0th hour incurs in 1+1+0+1 = 3 penalty.
- Closing the shop at the 1st hour incurs in 0+1+0+1 = 2 penalty.
- Closing the shop at the 2nd hour incurs in 0+0+0+1 = 1 penalty.
- Closing the shop at the 3rd hour incurs in 0+0+1+1 = 2 penalty.
- Closing the shop at the 4th hour incurs in 0+0+1+0 = 1 penalty.
Closing the shop at 2nd or 4th hour gives a minimum penalty. Since 2 is earlier, the optimal closing time is 2.
Example 2:
Input: customers = "NNNNN"
Output: 0
Explanation: It is best to close the shop at the 0th hour as no customers arrive.
Example 3:
Input: customers = "YYYY"
Output: 4
Explanation: It is best to close the shop at the 4th hour as customers arrive at each hour.
Constraints:
1 <= customers.length <= 105
customers consists only of characters 'Y' and 'N'.
'''
class Solution:
def bestClosingTime(self, customers: str) -> int:
S = customers
n = len(S)
preSum = [0]*(n+1)
for i,c in enumerate(S):
if c == 'N':
preSum[i+1] = preSum[i]+1
else:
preSum[i+1] = preSum[i]
# print(preSum)
ans, mx = -1, n+1
for i in range(n+1):
p = preSum[i] + ((n-i) - (preSum[n]-preSum[i]))
# print(i, p, preSum[n], preSum[i])
if p < mx:
mx = p
ans = i
# print(mx, ans)
return ans
def bestClosingTime2(self, customers: str) -> int:
S = customers
n = len(S)
tot = sum(1 for c in S if c == 'N')
k = n - tot
preSum, ans, mx = 0, -1, n+1
for i in range(n+1):
p = 2 * preSum + k - i
preSum += 1 if i < n and S[i] == 'N' else 0
if p < mx:
mx, ans = p, i
return ans
if __name__=="__main__":
print(Solution().bestClosingTime(customers = "YYNY"))
print(Solution().bestClosingTime(customers = "NNNNN"))
print(Solution().bestClosingTime(customers = "YYYY"))
print(Solution().bestClosingTime2(customers = "YYNY"))
print(Solution().bestClosingTime2(customers = "NNNNN"))
print(Solution().bestClosingTime2(customers = "YYYY")) |
'''
-Medium-
Given a string str, find the longest substring with no fewer than k repetitions
and return the length. The substring can have overlapping parts, but cannot
completely overlap.
1 <= str.length <= 1000
1 < k < str.length
We guarantee that the problem will certainly can be solved
样例
Example 1:
Input: str = "aaa", k = 2,
Output: 2.
Explanation:
The longest subsequence with no fewer than k repetitions is "aa", and the length is 2.
Example 2:
Input: str = "aabcbcbcbc", k = 2,
Output: 6.
Explanation:
Subsequences repeat no fewer than twice are "a", "bc", "bcbc" and "bcbcbc", and the longest is "bcbcbc", and the length is 6.
'''
class SuffixArray:
""" by Karp, Miller, Rosenberg 1972
s is the string to analyze.
P[k][i] is the pseudo rank of s[i:i+K] for K = 1<<k
among all strings of length K. Pseudo, because the pseudo rank numbers are
in order but not necessarily consecutive.
Initialization of the data structure has complexity O(n log^2 n).
"""
def __init__(self, s):
self.n = len(s)
if self.n == 1: # special case: single char strings
self.P = [[0]]
self.suf_sorted = [0]
return
self.P = [list(map(ord, s))]
k = 1
length = 1 # length is 2 ** (k - 1)
while length < self.n:
L = [] # prepare L
for i in range(self.n - length):
L.append((self.P[k - 1][i], self.P[k - 1][i + length], i))
for i in range(self.n - length, self.n): # pad with -1
L.append((self.P[k - 1][i], -1, i))
L.sort() # bucket sort would be quicker
self.P.append([0] * self.n) # produce k-th row in P
for i in range(self.n):
if i > 0 and L[i-1][:2] == L[i][:2]: # same as previous
self.P[k][ L[i][2] ] = self.P[k][ L[i-1][2] ]
else:
self.P[k][ L[i][2] ] = i
k += 1
length <<= 1 # or *=2 as you prefer
self.suf_sorted = [0] * self.n # generate the inverse:
for i, si in enumerate(self.P[-1]): # lexic. sorted suffixes
self.suf_sorted[si] = i
def longest_common_prefix(self, i, j):
"""returns the length of
the longest common prefix of s[i:] and s[j:].
complexity: O(log n), for n = len(s).
"""
if i == j:
return self.n - i # length of suffix
answer = 0
length = 1 << (len(self.P) - 1) # length is 2 ** k
for k in range(len(self.P) - 1, -1, -1):
length = 1 << k
if self.P[k][i] == self.P[k][j]: # aha, s[i:i+length] == s[j:j+length]
answer += length
i += length
j += length
if i == self.n or j == self.n: # not needed if s is appended by $
break
length >>= 1
return answer
def longestRepeatingSubsequenceII(self, k):
res = 0
lcp = self.longest_common_prefix(0, 1)
print('lcp', lcp)
for i in range(self.n-k):
lcp = self.longest_common_prefix(i, i+k-1)
res = max(res, lcp)
lcp = self.longest_common_prefix(i, i+k)
res = max(res, lcp)
return res
class Solution:
"""
@param str: The input string
@param k: The repeated times
@return: The answer
"""
def longestRepeatingSubsequenceII(self, str, k):
# Write your code here
n = len(str)
count = {}
# enumerate every substring:
# each substring of str is a prefix of a suffix of str
for i in range(n):
hashValue = 0
for j in range(i, n):
hashValue = (31 * hashValue + ord(str[j]) - ord('a')) % 1000000007
if (hashValue, j - i + 1) in count:
count[(hashValue, j - i + 1)] += 1
else:
count[(hashValue, j - i + 1)] = 1
ans = 0
for key, value in count.items():
if value >= k:
ans = max(ans, key[1])
return ans
def longestRepeatingSubsequenceII2(self, str, k):
sa = SuffixArray(str)
return sa.longestRepeatingSubsequenceII(k)
if __name__ == "__main__":
print(Solution().longestRepeatingSubsequenceII(str = "aabcbcbcbc", k = 2))
print(Solution().longestRepeatingSubsequenceII2(str = "aabcbcbcbc", k = 2))
print(Solution().longestRepeatingSubsequenceII2(str = "aaa", k = 2))
s = "ccbbcbaabcccbabcbcaaaacabbaccccacaabcbbacacaacabcbccbaabcabbbccaabbcbbcacabcaaacacabacbccbaacbcbcaacacbaaaaccacccbaacaaabacaccabcbcbabbbacbabcaaccbccacbcbacacacbcaccabaccbccbaaaaabbacbacacbccbabcaacbbcccaccbcbacbacbcabaababccaaaacccccbbaabbccbcccabbacacaacbcccbaaacacabccabcccccabcaaaabbbcbbbaabccacccabacbcbbcbabacabbbbbbabbcabcbcbcaabcbcccbabaccccabbabbbacbbacbcccaaacaccababcccbcaccbcbcaacacbccbacbccbccaccbcbcabbbccabaacaccbcccbccaccbbcbcccbbccbacbcbcbbcbabcbacbbababcbcacbaaabbabacabbcbccbaccbbc"
print(Solution().longestRepeatingSubsequenceII2(s, 2)) |
'''
-Medium-
*DP*
Given an array of unique integers, arr, where each integer arr[i] is strictly greater
than 1.
We make a binary tree using these integers, and each number may be used for any
number of times. Each non-leaf node's value should be equal to the product of the
values of its children.
Return the number of binary trees we can make. The answer may be too large so return
the answer modulo 10^9 + 7.
Example 1:
Input: arr = [2,4]
Output: 3
Explanation: We can make these trees: [2], [4], [4, 2, 2]
Example 2:
Input: arr = [2,4,5,10]
Output: 7
Explanation: We can make these trees: [2], [4], [5], [10], [4, 2, 2], [10, 2, 5],
[10, 5, 2].
Constraints:
1 <= arr.length <= 1000
2 <= arr[i] <= 10^9
'''
from collections import defaultdict
class Solution(object):
def numFactoredBinaryTrees(self, arr):
"""
:type arr: List[int]
:rtype: int
"""
arr.sort()
dp = defaultdict(int)
for i in range(len(arr)):
dp[arr[i]] = 1
for j in range(i):
if arr[i] % arr[j] == 0 and arr[i]//arr[j] in dp:
dp[arr[i]] = (dp[arr[i]] + dp[arr[j]] * dp[arr[i]//arr[j]]) \
% (10**9+7)
res = 0
for t in dp: res = (res + dp[t]) % (10**9+7)
return res
if __name__=="__main__":
print(Solution().numFactoredBinaryTrees([2,4,5,10])) |
'''
Given an array, rotate the array to the right by k steps, where k is non-negative.
Follow up:
Try to come up as many solutions as you can, there are at least 3 different ways to
solve this problem.
Could you do it in-place with O(1) extra space?
Example 1:
Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]
Example 2:
Input: nums = [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
Explanation:
rotate 1 steps to the right: [99,-1,-100,3]
rotate 2 steps to the right: [3,99,-1,-100]
Constraints:
1 <= nums.length <= 2 * 104
-231 <= nums[i] <= 231 - 1
0 <= k <= 105
'''
class Solution(object):
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: None Do not return anything, modify nums in-place instead.
"""
n = len(nums)
if k >= n:
k %= n
def reverse(left,right):
l, r = left, right
while l <= r:
nums[l], nums[r] = nums[r], nums[l]
l += 1
r -= 1
reverse(0, n-1)
reverse(0, k-1)
reverse(k, n-1)
return
if __name__ == "__main__":
a = [1,2,3,4,5,6,7]
k = 3
Solution().rotate(a,k)
print(a)
a = [-1,-100,3,99]
k = 2
Solution().rotate(a,k)
print(a)
|
'''
-Hard-
*DP*
You are given an array nums consisting of positive integers and an integer k.
Partition the array into two ordered groups such that each element is in exactly one group. A partition is called great if the sum of elements of each group is greater than or equal to k.
Return the number of distinct great partitions. Since the answer may be too large, return it modulo 109 + 7.
Two partitions are considered distinct if some element nums[i] is in different groups in the two partitions.
Example 1:
Input: nums = [1,2,3,4], k = 4
Output: 6
Explanation: The great partitions are: ([1,2,3], [4]), ([1,3], [2,4]), ([1,4], [2,3]), ([2,3], [1,4]), ([2,4], [1,3]) and ([4], [1,2,3]).
Example 2:
Input: nums = [3,3,3], k = 4
Output: 0
Explanation: There are no great partitions for this array.
Example 3:
Input: nums = [6,6], k = 2
Output: 2
Explanation: We can either put nums[0] in the first partition or in the second partition.
The great partitions will be ([6], [6]) and ([6], [6]).
Constraints:
1 <= nums.length, k <= 1000
1 <= nums[i] <= 109
'''
from typing import List
class Solution:
def countPartitions(self, nums: List[int], k: int) -> int:
MOD = 10**9 + 7
A = nums
if sum(A) < k * 2: return 0
dp = [1] + [0] * (k - 1)
for a in A:
for i in range(k - 1 - a, -1, -1):
dp[i + a] += dp[i]
return (pow(2, len(A), MOD) - sum(dp) * 2) % MOD
def countPartitions2(self, nums: List[int], k: int) -> int:
n = len(nums)
dp = [[0] * (k + 1)] + [[-1] * (k + 1) for _ in range(n)]
dp[0][0] = 1
def subsetSumCounts(s, idx):
if s < 0:
return 0
if dp[idx][s] < 0:
dp[idx][s] = subsetSumCounts(s, idx - 1) + subsetSumCounts(s - nums[idx - 1], idx - 1)
return dp[idx][s]
invalid_pairs = sum([subsetSumCounts(i, n) for i in range(k)]) * 2
return max(2**n - invalid_pairs, 0) % (10**9 + 7)
def countPartitions3(self, nums: List[int], k: int) -> int:
MOD = 10**9 + 7
n = len(nums)
dp = [[0] * k for _ in range(n)]
for i in range(n):
for j in range(k):
if i == 0 and j == 0: # base case
dp[i][j] = 1
continue
if i == 0: # j > 0
if j == nums[i]: dp[i][j] = 1
continue
if nums[i] > j: dp[i][j] = dp[i-1][j] # can not include nums[i]
else:
dp[i][j] = dp[i-1][j] + dp[i-1][j-nums[i]] # either not include nums[i] or include
dp[i][j] %= MOD
invalid = sum(dp[n-1]) % MOD
return max(2**n - 2*invalid, 0) % MOD
if __name__ == "__main__":
print(Solution().countPartitions(nums = [1,2,3,4], k = 4)) |
'''
-Easy-
Given a list of the scores of different students, items, where items[i] = [IDi, scorei]
represents one score from a student with IDi, calculate each student's top five average.
Return the answer as an array of pairs result, where result[j] = [IDj, topFiveAveragej]
represents the student with IDj and their top five average. Sort result by IDj in increasing order.
A student's top five average is calculated by taking the sum of their top five scores
and dividing it by 5 using integer division.
Example 1:
Input: items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
Output: [[1,87],[2,88]]
Explanation:
The student with ID = 1 got scores 91, 92, 60, 65, 87, and 100. Their top five average is (100 + 92 + 91 + 87 + 65) / 5 = 87.
The student with ID = 2 got scores 93, 97, 77, 100, and 76. Their top five average is (100 + 97 + 93 + 77 + 76) / 5 = 88.6, but with integer division their average converts to 88.
Example 2:
Input: items = [[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100],[1,100],[7,100]]
Output: [[1,100],[7,100]]
Constraints:
1 <= items.length <= 1000
items[i].length == 2
1 <= ID_i <= 1000
0 <= score_i <= 100
For each IDi, there will be at least five scores.
'''
from collections import defaultdict
import heapq
class Solution(object):
def highFive(self, items):
"""
:type items: List[List[int]]
:rtype: List[List[int]]
"""
m = defaultdict(list)
for i,score in items:
if len(m[i]) < 5:
heapq.heappush(m[i], score)
else:
heapq.heappushpop(m[i], score)
res = []
for i in sorted(m.keys()):
print(m[i])
res.append(sum(m[i])//5)
return res
def highFiveLint(self, results):
"""
:type items: List[List[int]]
:rtype: List[List[int]]
"""
m = defaultdict(list)
for r in results:
if len(m[r.id]) < 5:
heapq.heappush(m[r.id], r.score)
else:
heapq.heappushpop(m[r.id], r.score)
res = {}
for i in sorted(m.keys()):
res[i] = sum(m[i])/5
return res
if __name__ == "__main__":
print(Solution().highFive([[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]))
|
'''
Say you have an array for which the i-th 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).
Example 1:
Input: [2,4,1], k = 2
Output: 2
Explanation: Buy on day 1 (price = 2) and sell on day 2 (price = 4),
profit = 4-2 = 2.
Example 2:
Input: [3,2,6,5,0,3], k = 2
Output: 7
Explanation: Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4.
Then buy on day 5 (price = 0) and sell on day 6 (price = 3),
profit = 3-0 = 3.
'''
class Solution(object):
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
'''
Another way of using dynamic programming is to define dp[i,k] as the
largest profit we could make on day i with transaction k. Therefore
the transition function is:
dp[i][k] = max(dp[i-1][k], price[i]-price[j]+dp[j-1][k-1] for j < i)
With a small tweak of the function, instead of looking for
max(prices[i]-prices[j]+dp[j-1,k-1]), we can look for
max(dp[j-1,k-1]-prices[j], for j in [0,i-1]), so that we can store this value along with
the outer iteration
'''
if len(prices) < 2:
return 0
if k >= len(prices)//2:
ret = 0
for i in range(1,len(prices)):
ret += max(0,prices[i]-prices[i-1])
return ret
dp = [[0 for _ in range(k+1)] for _ in range(len(prices))]
for kk in range(1,k+1):
tmpMax = -prices[0]
for i in range(1,len(prices)):
dp[i][kk] = max(dp[i-1][kk], prices[i]+tmpMax)
tmpMax = max(tmpMax, dp[i-1][kk-1]-prices[i])
return dp[-1][-1]
if __name__ == "__main__":
s=Solution()
print(s.maxProfit(2, [3,2,6,5,0,3])) |
'''
-Easy-
Given the root of a binary tree and an integer targetSum, return true if the
tree has a root-to-leaf path such that adding up all the values along the path
equals targetSum.
A leaf is a node with no children.
Example 1:
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
Output: true
Example 2:
Input: root = [1,2,3], targetSum = 5
Output: false
Example 3:
Input: root = [1,2], targetSum = 0
Output: false
Constraints:
The number of nodes in the tree is in the range [0, 5000].
-1000 <= Node.val <= 1000
-1000 <= targetSum <= 1000
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from BinaryTree import (TreeNode, null, constructBinaryTree)
class Solution(object):
def hasPathSum(self, root, targetSum):
"""
:type root: TreeNode
:type targetSum: int
:rtype: bool
"""
if not root: return False
if not root.left and not root.right:
if targetSum == root.val: return True
else: return False
if root.left and self.hasPathSum(root.left, targetSum-root.val):
return True
if root.right and self.hasPathSum(root.right, targetSum-root.val):
return True
return False
if __name__ == "__main__":
root = constructBinaryTree([5,4,8,11,null,13,4,7,2,null,null,null,1])
print(Solution().hasPathSum(root, 22))
root = constructBinaryTree([1, 2, 3])
print(Solution().hasPathSum(root, 5))
root = constructBinaryTree([1, 2, null])
print(Solution().hasPathSum(root, 1))
|
'''
-Medium-
Given an undirected tree, return its diameter: the number of edges in a
longest path in that tree.
The tree is given as an array of edges where edges[i] = [u, v] is a
bidirectional edge between nodes u and v. Each node has labels in the
set {0, 1, ..., edges.length}.
Example 1:
Input: edges = [[0,1],[0,2]]
Output: 2
Explanation:
A longest path of the tree is the path 1 - 0 - 2.
Example 2:
Input: edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
Output: 4
Explanation:
A longest path of the tree is the path 3 - 2 - 1 - 4 - 5.
Constraints:
0 <= edges.length < 10^4
edges[i][0] != edges[i][1]
0 <= edges[i][j] <= edges.length
The given edges form an undirected tree.
'''
from typing import List
from collections import deque, defaultdict
class Solution(object):
def treeDiameter(self, edges):
n = len(edges)+1
degrees = [0]*n
visited = [False]*n
graph = defaultdict(set)
que = deque()
for u,v in edges:
graph[u].add(v)
graph[v].add(u)
degrees[u] += 1
degrees[v] += 1
for i in range(n):
if degrees[i] == 1:
que.append(i)
visited[i] = True
depth = 0
#print(que)
remaining = n
while que and remaining > 2:
nxt = deque()
size = len(que)
for _ in range(len(que)):
u = que.popleft()
degrees[u] -= 1
for v in graph[u]:
degrees[v] -= 1
if degrees[v] == 1 and not visited[v]:
nxt.append(v)
visited[v] = True
que = nxt
remaining -= size
depth += 1
return depth*2 if remaining == 1 else depth*2+1
def treeDiameter2(self, edges):
n = len(edges)+1
graph = defaultdict(set)
for u,v in edges:
graph[u].add(v)
graph[v].add(u)
def bfs(src):
visited = {src}
q = deque([(src, 0)]) # Pair of (vertex, distance)
farthestNode, farthestDist = -1, 0
while len(q) > 0:
farthestNode, farthestDist = u, d = q.popleft()
for v in graph[u]:
if v not in visited:
visited.add(v)
q.append((v, d + 1))
return farthestNode, farthestDist
farthestNode, _ = bfs(0)
_, dist = bfs(farthestNode)
return dist
if __name__ == "__main__":
edges = [[0,1],[1,2],[2,3],[1,4],[4,5]]
print(Solution().treeDiameter(edges))
print(Solution().treeDiameter2(edges))
|
'''
-Medium-
Given a Binary Search Tree (BST) with root node root, and a target value V,
split the tree into two subtrees where one subtree has nodes that are all
smaller or equal to the target value, while the other subtree has all
nodes that are greater than the target value. It’s not necessarily the
case that the tree contains a node with value V.
Additionally, most of the structure of the original tree should remain.
Formally, for any child C with parent P in the original tree, if they
are both in the same subtree after the split, then node C should still have the parent P.
You should output the root TreeNode of both subtrees after splitting, in any order.
Example 1:
Input: root = [4,2,6,1,3,5,7], V = 2
Output: [[2,1],[4,3,6,null,null,5,7]]
Explanation:
Note that root, output[0], and output[1] are TreeNode objects, not arrays.
The given tree [4,2,6,1,3,5,7] is represented by the following diagram:
4
/ \
2 6
/ \ / \
1 3 5 7
while the diagrams for the outputs are:
4
/ \
3 6 and 2
/ \ /
5 7 1
Note:
The size of the BST will not exceed 50.
The BST is always valid and each node’s value is different.
'''
from BinaryTree import (null, TreeNode, constructBinaryTree)
class Solution(object):
def splitBST(self, root, V):
res = [None, None]
if not root: return res
if root.val <= V:
res = self.splitBST(root.right, V)
root.right = res[0]
res[0] = root
else:
res = self.splitBST(root.left, V)
root.left = res[0]
res[1] = root
return res
if __name__ == "__main__":
root = constructBinaryTree([4,2,6,1,3,5,7])
root.prettyPrint()
res = Solution().splitBST(root, 2)
|
'''
-Medium-
*Sorting*
Given a list of folders folder, return the folders after removing all sub-folders in those folders. You may return the answer in any order.
If a folder[i] is located within another folder[j], it is called a sub-folder of it.
The format of a path is one or more concatenated strings of the form: '/' followed by one or more lowercase English letters.
For example, "/leetcode" and "/leetcode/problems" are valid paths while an empty string and "/" are not.
Example 1:
Input: folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]
Output: ["/a","/c/d","/c/f"]
Explanation: Folders "/a/b" is a subfolder of "/a" and "/c/d/e" is inside of folder "/c/d" in our filesystem.
Example 2:
Input: folder = ["/a","/a/b/c","/a/b/d"]
Output: ["/a"]
Explanation: Folders "/a/b/c" and "/a/b/d" will be removed because they are subfolders of "/a".
Example 3:
Input: folder = ["/a/b/c","/a/b/ca","/a/b/d"]
Output: ["/a/b/c","/a/b/ca","/a/b/d"]
Constraints:
1 <= folder.length <= 4 * 104
2 <= folder[i].length <= 100
folder[i] contains only lowercase letters and '/'.
folder[i] always starts with the character '/'.
Each folder name is unique.
'''
from typing import List
class Solution:
def removeSubfolders(self, folder: List[str]) -> List[str]:
folder.sort(key = lambda x: x.count('/'))
m = set()
ans = []
for d in folder:
s = '/'
isSub = False
for x in d.split('/')[1:]:
s += x
if s in m:
isSub = True
break
s += '/'
if not isSub:
ans.append(d)
m.add(d)
return ans
def removeSubfolders2(self, folder: List[str]) -> List[str]:
# folder.sort(key = lambda x: x.count('/'))
folder.sort()
ans = []
for s in folder:
if not ans or not s.startswith(ans[-1]+'/'):
ans.append(s)
return ans
if __name__ == "__main__":
print(Solution().removeSubfolders(folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]))
print(Solution().removeSubfolders(folder = ["/a","/a/b/c","/a/b/d"]))
print(Solution().removeSubfolders(folder = ["/a/b/c","/a/b/ca","/a/b/d"]))
print(Solution().removeSubfolders2(folder = ["/a","/a/b","/c/d","/c/d/e","/c/f"]))
print(Solution().removeSubfolders2(folder = ["/a","/a/b/c","/a/b/d"]))
print(Solution().removeSubfolders2(folder = ["/a/b/c","/a/b/ca","/a/b/d"])) |
'''
-Medium-
*Greedy*
We have a two dimensional matrix A where each value is 0 or 1.
A move consists of choosing any row or column, and toggling each value
in that row or column: changing all 0s to 1s, and all 1s to 0s.
After making any number of moves, every row of this matrix is interpreted
as a binary number, and the score of the matrix is the sum of these numbers.
Return the highest possible score.
Example 1:
Input: [[0,0,1,1],[1,0,1,0],[1,1,0,0]]
Output: 39
Explanation:
Toggled to [[1,1,1,1],[1,0,0,1],[1,1,1,1]].
0b1111 + 0b1001 + 0b1111 = 15 + 9 + 15 = 39
Note:
1 <= A.length <= 20
1 <= A[0].length <= 20
A[i][j] is 0 or 1.
'''
class Solution(object):
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
m = len(A)
n = len(A[0])
ans = 0
for i in range(m):
if A[i][0] == 0:
A[i][:] = [1-x for x in A[i]]
for j in range(1,n):
cnt = 0
for i in range(m):
cnt += 1 if A[i][j] == 1 else 0
if cnt < m-cnt:
for i in range(m):
A[i][j] = 1-A[i][j]
for i in range(m):
ans += int('0b'+''.join([str(x) for x in A[i]]), base=0)
return ans
if __name__ == "__main__":
A = [[0,0,1,1],
[1,0,1,0],
[1,1,0,0]]
print(Solution().matrixScore(A)) |
'''
-Medium-
*Binary Search*
*Sorting*
You are given two positive integer arrays nums1 and nums2, both of length n.
The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).
You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.
Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.
|x| is defined as:
x if x >= 0, or
-x if x < 0.
Example 1:
Input: nums1 = [1,7,5], nums2 = [2,3,5]
Output: 3
Explanation: There are two possible optimal solutions:
- Replace the second element with the first: [1,7,5] => [1,1,5], or
- Replace the second element with the third: [1,7,5] => [1,5,5].
Both will yield an absolute sum difference of |1-2| + (|1-3| or |5-3|) + |5-5| = 3.
Example 2:
Input: nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]
Output: 0
Explanation: nums1 is equal to nums2 so no replacement is needed. This will result in an
absolute sum difference of 0.
Example 3:
Input: nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4]
Output: 20
Explanation: Replace the first element with the second: [1,10,4,4,2,7] => [10,10,4,4,2,7].
This yields an absolute sum difference of |10-9| + |10-3| + |4-5| + |4-1| + |2-7| + |7-4| = 20
Constraints:
n == nums1.length
n == nums2.length
1 <= n <= 105
1 <= nums1[i], nums2[i] <= 105
'''
from typing import List
import bisect
class Solution:
def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
diffs = [(abs(x-y), i) for i, (x, y) in enumerate(zip(nums1, nums2))]
A = sorted(nums1)
MOD = 10**9 + 7
sums = 0
for x in diffs:
sums += x[0]
diffs.sort(reverse = True)
ans = sums
for d, i in diffs:
if d == 0: break
idx = bisect.bisect_left(A, nums2[i])
if 0 < idx < len(A):
candidate = A[idx] if A[idx] - nums2[i] < nums2[i] - A[idx-1] else A[idx-1]
elif idx == 0:
candidate = A[0]
else:
candidate = A[-1]
# print(nums2[i], idx, candidate, d, abs(candidate-nums2[i]))
ans = min(ans, sums-d+abs(candidate-nums2[i]))
return ans % MOD
if __name__ == "__main__":
print(Solution().minAbsoluteSumDiff(nums1 = [2,4,6,8,10], nums2 = [2,4,6,8,10]))
print(Solution().minAbsoluteSumDiff(nums1 = [1,7,5], nums2 = [2,3,5]))
print(Solution().minAbsoluteSumDiff(nums1 = [1,10,4,4,2,7], nums2 = [9,3,5,1,7,4])) |
'''
-Medium-
In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the
competition.
The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the
first position, we consider the second position to resolve the conflict, if they tie again, we continue this
process until the ties are resolved. If two or more teams are still tied after considering all positions,
we rank them alphabetically based on their team letter.
Given an array of strings votes which is the votes of all voters in the ranking systems. Sort all teams
according to the ranking system described above.
Return a string of all teams sorted by the ranking system.
Example 1:
Input: votes = ["ABC","ACB","ABC","ACB","ACB"]
Output: "ACB"
Explanation: Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.
Team B was ranked second by 2 voters and was ranked third by 3 voters.
Team C was ranked second by 3 voters and was ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team and team B is the third.
Example 2:
Input: votes = ["WXYZ","XYZW"]
Output: "XWYZ"
Explanation: X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position.
Example 3:
Input: votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
Output: "ZMNAGUEDSJYLBOPHRQICWFXTVK"
Explanation: Only one voter so his votes are used for the ranking.
Example 4:
Input: votes = ["BCA","CAB","CBA","ABC","ACB","BAC"]
Output: "ABC"
Explanation:
Team A was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team B was ranked first by 2 voters, second by 2 voters and third by 2 voters.
Team C was ranked first by 2 voters, second by 2 voters and third by 2 voters.
There is a tie and we rank teams ascending by their IDs.
Example 5:
Input: votes = ["M","M","M","M"]
Output: "M"
Explanation: Only team M in the competition so it has the first rank.
Constraints:
1 <= votes.length <= 1000
1 <= votes[i].length <= 26
votes[i].length == votes[j].length for 0 <= i, j < votes.length.
votes[i][j] is an English upper-case letter.
All characters of votes[i] are unique.
All the characters that occur in votes[0] also occur in votes[j] where 1 <= j < votes.length.
'''
from typing import List
from collections import defaultdict
class Solution:
def rankTeams(self, votes: List[str]) -> str:
n = len(votes)
m = len(votes[0])
print('n, m', n,m)
books = [defaultdict(int) for _ in range(26)]
score = [0]*26
for s in votes:
for i,c in enumerate(s):
if c == 'R':
print(i)
score[ord(c)-ord('A')] += (m-i)
books[ord(c)-ord('A')][i] += 1
#print(score)
#print([chr(i+ord('A')) for i,s in enumerate(score)])
print([(k, books[ord('R')-ord('A')][k]) for k in sorted(books[ord('R')-ord('A')].keys())])
print([(k, books[ord('V')-ord('A')][k]) for k in sorted(books[ord('V')-ord('A')].keys())])
ranks = [(s,i) for i,s in enumerate(score)]
ranks.sort(key=lambda x: (-x[0],x[1]))
res = ''
for s,i in ranks:
if s != 0:
res += chr(i+ord('A'))
return res
def rankTeams2(self, votes: List[str]) -> str:
n = len(votes)
m = len(votes[0])
ranks = [[0]*m for _ in range(26)]
for s in votes:
for i,c in enumerate(s):
ranks[ord(c)-ord('A')][i] += 1
teams = [i for i in range(26)]
teams.sort(key=lambda x: tuple(-ranks[x][y] for y in range(m))+(x,))
return ''.join([chr(t+ord('A')) for t in teams if chr(t+ord('A')) in votes[0]])
if __name__ == "__main__":
print(Solution().rankTeams2(["ABC","ACB","ABC","ACB","ACB"]))
print(Solution().rankTeams2(["ZMNAGUEDSJYLBOPHRQICWFXTVK"]))
print(Solution().rankTeams2(["M","M","M","M"]))
print(Solution().rankTeams2(["BCA","CAB","CBA","ABC","ACB","BAC"]))
print(Solution().rankTeams2(["WXYZ","XYZW"]))
votes = ["FVSHJIEMNGYPTQOURLWCZKAX","AITFQORCEHPVJMXGKSLNZWUY","OTERVXFZUMHNIYSCQAWGPKJL","VMSERIJYLZNWCPQTOKFUHAXG","VNHOZWKQCEFYPSGLAMXJIUTR","ANPHQIJMXCWOSKTYGULFVERZ","RFYUXJEWCKQOMGATHZVILNSP","SCPYUMQJTVEXKRNLIOWGHAFZ","VIKTSJCEYQGLOMPZWAHFXURN","SVJICLXKHQZTFWNPYRGMEUAO","JRCTHYKIGSXPOZLUQAVNEWFM","NGMSWJITREHFZVQCUKXYAPOL","WUXJOQKGNSYLHEZAFIPMRCVT","PKYQIOLXFCRGHZNAMJVUTWES","FERSGNMJVZXWAYLIKCPUQHTO","HPLRIUQMTSGYJVAXWNOCZEKF","JUVWPTEGCOFYSKXNRMHQALIZ","MWPIAZCNSLEYRTHFKQXUOVGJ","EZXLUNFVCMORSIWKTYHJAQPG","HRQNLTKJFIEGMCSXAZPYOVUW","LOHXVYGWRIJMCPSQENUAKTZF","XKUTWPRGHOAQFLVYMJSNEIZC","WTCRQMVKPHOSLGAXZUEFYNJI"]
#print(Solution().rankTeams(votes))
print(Solution().rankTeams2(votes))
|
'''
-Hard-
A city is represented as a bi-directional connected graph with n vertices where each
vertex is labeled from 1 to n (inclusive). The edges in the graph are represented as
a 2D integer array edges, where each edges[i] = [ui, vi] denotes a bi-directional
edge between vertex ui and vertex vi. Every vertex pair is connected by at most
one edge, and no vertex has an edge to itself. The time taken to traverse any edge
is time minutes.
Each vertex has a traffic signal which changes its color from green to red and
vice versa every change minutes. All signals change at the same time. You can
enter a vertex at any time, but can leave a vertex only when the signal is green.
You cannot wait at a vertex if the signal is green.
The second minimum value is defined as the smallest value strictly larger than
the minimum value.
For example the second minimum value of [2, 3, 4] is 3, and the second minimum
value of [2, 2, 4] is 4.
Given n, edges, time, and change, return the second minimum time it will take to
go from vertex 1 to vertex n.
Notes:
You can go through any vertex any number of times, including 1 and n.
You can assume that when the journey starts, all signals have just turned green.
Example 1:
Input: n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5
Output: 13
Explanation:
The figure on the left shows the given graph.
The blue path in the figure on the right is the minimum time path.
The time taken is:
- Start at 1, time elapsed=0
- 1 -> 4: 3 minutes, time elapsed=3
- 4 -> 5: 3 minutes, time elapsed=6
Hence the minimum time needed is 6 minutes.
The red path shows the path to get the second minimum time.
- Start at 1, time elapsed=0
- 1 -> 3: 3 minutes, time elapsed=3
- 3 -> 4: 3 minutes, time elapsed=6
- Wait at 4 for 4 minutes, time elapsed=10
- 4 -> 5: 3 minutes, time elapsed=13
Hence the second minimum time is 13 minutes.
Example 2:
Input: n = 2, edges = [[1,2]], time = 3, change = 2
Output: 11
Explanation:
The minimum time path is 1 -> 2 with time = 3 minutes.
The second minimum time path is 1 -> 2 -> 1 -> 2 with time = 11 minutes.
Constraints:
2 <= n <= 10^4
n - 1 <= edges.length <= min(2 * 10^4, n * (n - 1) / 2)
edges[i].length == 2
1 <= ui, vi <= n
ui != vi
There are no duplicate edges.
Each vertex can be reached directly or indirectly from every other vertex.
1 <= time, change <= 10^3
'''
from typing import List
from collections import deque, defaultdict
class Solution:
def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
que, graph = deque(), defaultdict(list)
visited = [[False]*2 for _ in range(n+1)]
curTime, firstArrive = 0, -1
visTime = [-1]*(n+1)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
que.append((1, curTime))
visited[1][0] = True
while que:
u, cur = que.popleft()
if u == n:
if firstArrive == -1:
firstArrive = cur
#elif cur > firstArrive:
else: return cur
for v in graph[u]:
redLight = (cur // change) % 2
arrivalTime = cur + time
if redLight: arrivalTime += change - (cur % change)
if visTime[v] != arrivalTime and not visited[v][0]:
visTime[v] = arrivalTime
visited[v][0] = True
que.append((v, arrivalTime))
elif visTime[v] != arrivalTime and not visited[v][1]:
visTime[v] = arrivalTime
visited[v][1] = True
que.append((v, arrivalTime))
return -1
def secondMinimum2(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
que, graph = deque(), defaultdict(list)
visited = [[False]*2 for _ in range(n+1)]
curTime, firstArrive = 0, -1
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
que.append((1, curTime))
visited[1][0] = True
while que:
u, cur = que.popleft()
if u == n:
if firstArrive == -1:
firstArrive = cur
elif cur > firstArrive:
return cur
#else: return cur
for v in graph[u]:
redLight = (cur // change) % 2
arrivalTime = cur + time
if redLight: arrivalTime += change - (cur % change)
if not visited[v][0]:
visited[v][0] = True
que.append((v, arrivalTime))
elif not visited[v][1]:
visited[v][1] = True
que.append((v, arrivalTime))
return -1
def secondMinimum3(self, n: int, edges: List[List[int]], time: int, change: int) -> int:
que, graph = deque(), defaultdict(list)
INT_MAX = float('inf')
firstArrivedTime = INT_MAX
visTime = [INT_MAX]*(n+1)
visCount = [0]*(n+1)
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
que.append((1, 0))
while que:
u, cur = que.popleft()
if v == n and firstArrivedTime == INT_MAX:
firstArrivedTime = cur
if v == n and cur > firstArrivedTime:
return cur
for v in graph[u]:
redLight = (cur // change) % 2
arrivalTime = cur + time
if redLight: arrivalTime += change - (cur % change)
# visTime[next] != arrivalTime to avoid the same arrival time, think about this graph,
# 0->1->3 0->2->3, so 0 can reach 1 and 2 and then reach 3, there are 2 times
# that can reach to point 3 and we will use the 2nd time(it is the same as the
# 1st reach time) as our answer but we know that it is not right, so we need
# this condition.
if visTime[v] != arrivalTime and visCount[v] <= 1:
visTime[v] = arrivalTime
visCount[v] += 1
que.append((v, arrivalTime))
return -1
if __name__ == "__main__":
print(Solution().secondMinimum(n = 5, edges = [[1,2],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5))
print(Solution().secondMinimum(n = 2, edges = [[1,2]], time = 3, change = 2))
print(Solution().secondMinimum(n = 5, edges = [[1,2],[2,5],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5))
print(Solution().secondMinimum2(n = 5, edges = [[1,2],[2,5],[1,3],[1,4],[3,4],[4,5]], time = 3, change = 5))
|
'''
-Medium-
You are given an array nums of length n and an integer m. You need to determine if it is possible to split the array into n non-empty arrays by performing a series of steps.
In each step, you can select an existing array (which may be the result of previous steps) with a length of at least two and split it into two subarrays, if, for each resulting subarray, at least one of the following holds:
The length of the subarray is one, or
The sum of elements of the subarray is greater than or equal to m.
Return true if you can split the given array into n arrays, otherwise return false.
Note: A subarray is a contiguous non-empty sequence of elements within an array.
Example 1:
Input: nums = [2, 2, 1], m = 4
Output: true
Explanation: We can split the array into [2, 2] and [1] in the first step. Then, in the second step, we can split [2, 2] into [2] and [2]. As a result, the answer is true.
Example 2:
Input: nums = [2, 1, 3], m = 5
Output: false
Explanation: We can try splitting the array in two different ways: the first way is to have [2, 1] and [3], and the second way is to have [2] and [1, 3]. However, both of these ways are not valid. So, the answer is false.
Example 3:
Input: nums = [2, 3, 3, 2, 3], m = 6
Output: true
Explanation: We can split the array into [2, 3, 3, 2] and [3] in the first step. Then, in the second step, we can split [2, 3, 3, 2] into [2, 3, 3] and [2]. Then, in the third step, we can split [2, 3, 3] into [2] and [3, 3]. And in the last step we can split [3, 3] into [3] and [3]. As a result, the answer is true.
Constraints:
1 <= n == nums.length <= 100
1 <= nums[i] <= 100
1 <= m <= 200
'''
from typing import List
from functools import lru_cache
class Solution:
def canSplitArray(self, nums: List[int], m: int) -> bool:
def dfs(A):
if len(A) <= 2:
return True
s, t = sum(A), 0
for i in range(len(A)-1):
t += A[i]
if i == 0 and s-t >= m or i==len(A)-2 and t >= m or t >= m and s-t >= m:
l = dfs(A[:i+1])
r = dfs(A[i+1:])
if l and r:
return True
return False
return dfs(nums)
def canSplitArray2(self, nums: List[int], m: int) -> bool:
n = len(nums)
preSum = [0]*(n+1)
for i in range(1,n+1):
preSum[i] = preSum[i-1] + nums[i-1]
@lru_cache(None)
def dfs(i, j):
if i == j or i+1 == j:
return True
t, s = 0, preSum[j+1] - preSum[i]
for k in range(i, j):
t += nums[k]
if k == i and s-t >= m or k==j-1 and t >= m or t >= m and s-t >= m:
l = dfs(i, k)
r = dfs(k+1, j)
if l and r:
# print(i, k, j, t, s-t)
return True
return False
return dfs(0, n-1)
if __name__ == "__main__":
print(Solution().canSplitArray2(nums = [2, 1, 2], m = 4))
# print(Solution().canSplitArray2(nums = [2, 2, 1], m = 4))
# print(Solution().canSplitArray2(nums = [2, 1, 3], m = 5))
# print(Solution().canSplitArray2(nums = [2, 3, 3, 2, 3], m = 6))
nums = [38, 96, 25, 55, 62, 62, 58, 55, 4, 32, 35, 100, 12, 87, 16, 55, 16, 53, 77, 57, 44, 87, 23]
m = 143
print(Solution().canSplitArray2(nums = nums, m = m)) |
'''
-Medium-
Given the root of a binary tree, return the zigzag level order traversal of its nodes' values.
(i.e., from left to right, then right to left for the next level and alternate between).
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]
Example 2:
Input: root = [1]
Output: [[1]]
Example 3:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 2000].
-100 <= Node.val <= 100
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from BinaryTree import (null, TreeNode, constructBinaryTree)
from collections import deque
class Solution(object):
def zigzagLevelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root: return []
q = deque([root])
res = []
lev = 1
while q:
nxt = deque()
nums = []
while q:
node = q.popleft()
if node.left: nxt.append(node.left)
if node.right: nxt.append(node.right)
nums.append(node.val)
if lev % 2 == 0:
nums = nums[::-1]
res.append(nums)
q = nxt
lev += 1
return res
if __name__ == "__main__":
root = constructBinaryTree([3,9,20,null,null,15,7])
root.prettyPrint()
print(Solution().zigzagLevelOrder(root)) |
'''
-Medium-
*Trie*
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string
containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
'''
from collections import defaultdict
class Node(defaultdict):
def __init__(self):
super().__init__(Node)
self.terminal = False
class WordDictionary(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = Node()
def addWord(self, word):
"""
Adds a word into the data structure.
:type word: str
:rtype: None
"""
node = self.root
for c in word:
node = node[c]
node.terminal = True
def search(self, word):
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
:type word: str
:rtype: bool
"""
node = self.root
def dfs(root, word):
if not word:
return root.terminal
c = word[0]
if c == '.':
if len(root) == 0:
return False
for k in root:
if dfs(root[k], word[1:]):
return True
return False
else:
node = root.get(c)
if node is None:
return False
return dfs(node, word[1:])
return dfs(node, word)
if __name__ == "__main__":
obj = WordDictionary()
obj.addWord("bad")
obj.addWord("dad")
obj.addWord("mad")
print(obj.search("pad"))
print(obj.search("bad"))
print(obj.search(".ad"))
print(obj.search("b.."))
obj = WordDictionary()
obj.addWord("a")
obj.addWord("a")
print(obj.search("."))
print(obj.search("a"))
print(obj.search("aa"))
print(obj.search("a"))
print(obj.search(".a"))
print(obj.search("a."))
obj = WordDictionary()
obj.addWord("at")
obj.addWord("and")
obj.addWord("an")
obj.addWord("add")
print(obj.search("a"))
print(obj.search(".at"))
obj.addWord("bat")
print(obj.search(".at"))
|
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 30 00:24:20 2017
@author: merli
-Medium-
*Recursion*
*DFS*
Given the root of a binary tree, then value v and depth d, you need to add a row
of nodes with value v at the given depth d. The root node is at depth 1.
The adding rule is: given a positive integer depth d, for each NOT null tree nodes
N in depth d-1, create two tree nodes with value v as N's left subtree root and
right subtree root. And N's original left subtree should be the left subtree of
the new left subtree root, its original right subtree should be the right subtree
of the new right subtree root. If depth d is 1 that means there is no depth d-1 at
all, then create a tree node with value v as the new root of the whole original tree,
and the original tree is the new root's left subtree.
Example 1:
Input:
A binary tree as following:
4
/ \
2 6
/ \ /
3 1 5
v = 1
d = 2
Output:
4
/ \
1 1
/ \
2 6
/ \ /
3 1 5
Example 2:
Input:
A binary tree as following:
4
/
2
/ \
3 1
v = 1
d = 3
Output:
4
/
2
/ \
1 1
/ \
3 1
Note:
The given d is in range [1, maximum depth of the given tree + 1].
The given binary tree has at least one tree node.
"""
from collections import deque
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def addOneRowSP(self, root, v, d):
dummy, dummy.left = TreeNode(None), root
row = [dummy]
#for _ in range(d - 1):
# row = [kid for node in row for kid in (node.left, node.right) if kid]
for _ in range(d-1):
row1 = []
for node in row:
for kid in (node.left, node.right):
if kid:
row1.append(kid)
row = row1
for node in row:
node.left, node.left.left = TreeNode(v), node.left
node.right, node.right.right = TreeNode(v), node.right
return dummy.left
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root:
return 1+max(self.maxDepth(root.left), self.maxDepth(root.right))
else:
return 0
def addOneRow(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode
"""
if d==1:
nr = TreeNode(v)
nr.left = root
return nr
else:
q=deque()
depth = 1
q.append((root, depth))
while q and depth < d:
(node, depth) = q.popleft()
if node.left:
q.append((node.left, depth+1))
if node.right:
q.append((node.right, depth+1))
if depth+1 == d:
nl = TreeNode(v)
nr = TreeNode(v)
nl.left = node.left
nr.right = node.right
node.left = nl
node.right = nr
return root
#print root.left.left.val
def addOneRowDFS(self, root, v, d):
"""
:type root: TreeNode
:type v: int
:type d: int
:rtype: TreeNode
"""
def helper(node, depth):
if not node: return
if depth == d-1:
orig_left = node.left
orig_right = node.right
node.left = TreeNode(v)
node.right = TreeNode(v)
node.left.left = orig_left
node.right.right = orig_right
return
helper(node.left, depth+1)
helper(node.right, depth+1)
if d == 1:
node = TreeNode(v)
node.left = root
return node
helper(root, 1)
return root
if __name__ == "__main__":
root=TreeNode(4)
root.left = TreeNode(2)
root.left.right = TreeNode(1)
root.right = TreeNode(6)
root.right.left = TreeNode(5)
root.left.left = TreeNode(3)
print(Solution().maxDepth(root))
#newtree = Solution().addOneRow(root, 1, 3)
#newtree = Solution().addOneRowSP(root, 1, 3)
newtree = Solution().addOneRowDFS(root, 1, 3)
print(Solution().maxDepth(newtree)) |
'''
Given an array of meeting time intervals consisting of start and end times
[[s1,e1],[s2,e2],...] (si < ei), determine if a person could attend
all meetings.
Example 1:
Input: [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: [[7,10],[2,4]]
Output: true
NOTE: input types have been changed on April 15, 2019. Please reset to
default code definition to get new method signature.
'''
import sys
class Solution(object):
def attend(self, meetings):
meets = sorted(meetings, key=lambda x: x[1])
e = -sys.maxsize-1
for m in meets:
if m[0] < e:
return False
e = m[1]
return True
print(Solution().attend([[0,30],[5,10],[15,20]]))
|
'''
-Medium-
*BFS*
*Bidirectional BFS*
Chell is the protagonist of the Portal Video game series developed by Valve Corporation.
One day, She fell into a maze. The maze can be thought of as an array of 2D characters of
size n x m. It has 4 kinds of rooms. 'S' represents where Chell started(Only one starting point).
'E' represents the exit of the maze(When chell arrives, she will leave the maze, this question
may have multiple exits). '*' represents the room that Chell can pass. '#' represents a wall,
Chell can not pass the wall.
She can spend a minute moving up,down,left and right to reach a room, but she can not reach the wall.
Now, can you tell me how much time she needs at least to leave the maze?
If she can not leave, return -1.
We guarantee that the size of the maze is n x m, and 1<=n<=200,1<=m<=200.
There is only one 'S', and one or more 'E'.
样例
Example1
Input:
[
['S','E','*'],
['*','*','*'],
['*','*','*']
]
Output: 1
Explanation:
Chell spent one minute walking from (0,0) to (0,1).
Example2
Input:
[
['S','#','#'],
['#','*','#'],
['#','*','*'],
['#','*','E']
]
Output: -1
Explanation:
Chell can not leave the maze.
'''
from collections import deque
class Solution:
"""
@param Maze:
@return: nothing
"""
def Portal(self, Maze):
#
A = Maze
m, n = len(Maze), len(Maze[0])
qs, qt = deque(), deque()
vs, vt = set(), set()
dirs = [ (-1,0), (1,0), (0,-1), (0,1)]
for i in range(m):
for j in range(n):
if A[i][j] == 'S':
qs.append((i,j))
vs.add((i,j))
if A[i][j] == 'E':
qt.append((i,j))
vt.add((i,j))
sk, tk = 0, 0
while qs and qt:
nxt = deque()
for _ in range(len(qs)):
si,sj = qs.popleft()
if (si, sj) in vt:
return sk+tk
for dx,dy in dirs:
x, y = si+dx, sj+dy
if x >= 0 and x < m and y >= 0 and y < n and (x,y) not in vs and A[x][y]!='#':
vs.add((x,y))
nxt.append((x,y))
sk += 1
qs = nxt
nxt = deque()
for _ in range(len(qt)):
si,sj = qt.popleft()
if (si, sj) in vs:
return sk+tk
for dx,dy in dirs:
x, y = si+dx, sj+dy
if x >= 0 and x < m and y >= 0 and y < n and (x,y) not in vt and A[x][y]!='#':
vt.add((x,y))
nxt.append((x,y))
tk += 1
qt = nxt
return -1
if __name__ == "__main__":
maze = [
['S','E','*'],
['*','*','*'],
['*','*','*']
]
print(Solution().Portal(maze))
maze = [
['S','#','#'],
['#','*','#'],
['#','*','*'],
['#','*','E']
]
print(Solution().Portal(maze))
maze = ["S*E",
"***",
"#**",
"##E"]
print(Solution().Portal(maze))
|
'''
-Hard-
The hash of a 0-indexed string s of length k, given integers p and m, is computed
using the following function:
hash(s, p, m) = (val(s[0]) * p0 + val(s[1]) * p1 + ... + val(s[k-1]) * pk-1) mod m.
Where val(s[i]) represents the index of s[i] in the alphabet from val('a') = 1
to val('z') = 26.
You are given a string s and the integers power, modulo, k, and hashValue.
Return sub, the first substring of s of length k such that
hash(sub, power, modulo) == hashValue.
The test cases will be generated such that an answer always exists.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0
Output: "ee"
Explanation: The hash of "ee" can be computed to be hash("ee", 7, 20) = (5 * 1 + 5 * 7) mod 20 = 40 mod 20 = 0.
"ee" is the first substring of length 2 with hashValue 0. Hence, we return "ee".
Example 2:
Input: s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32
Output: "fbx"
Explanation: The hash of "fbx" can be computed to be hash("fbx", 31, 100) = (6 * 1 + 2 * 31 + 24 * 312) mod 100 = 23132 mod 100 = 32.
The hash of "bxz" can be computed to be hash("bxz", 31, 100) = (2 * 1 + 24 * 31 + 26 * 312) mod 100 = 25732 mod 100 = 32.
"fbx" is the first substring of length 3 with hashValue 32. Hence, we return "fbx".
Note that "bxz" also has a hash of 32 but it appears later than "fbx".
Constraints:
1 <= k <= s.length <= 2 * 10^4
1 <= power, modulo <= 10^9
0 <= hashValue < modulo
s consists of lowercase English letters only.
The test cases are generated such that an answer always exists.
'''
class Solution:
def subStrHash(self, s: str, power: int, modulo: int, k: int, hashValue: int) -> str:
n = len(s)
def val(c):
return ord(c) - ord('a') + 1
d, q = power, modulo
h, p = 0, pow(d, k, q)
res = n
for i in range(n-1, -1, -1):
h = (h*d + val(s[i])) % q
if i + k < n:
h = (h - val(s[i+k])*p) % q
if h == hashValue:
res = i
return s[res:res+k]
if __name__ == "__main__":
print(Solution().subStrHash(s = "fbxzaad", power = 31, modulo = 100, k = 3, hashValue = 32))
print(Solution().subStrHash(s = "leetcode", power = 7, modulo = 20, k = 2, hashValue = 0))
print(Solution().subStrHash(s = "nekv", power = 15,
modulo = 94, k = 4, hashValue = 16))
print(Solution().subStrHash(s = "xxterzixjqrghqyeketqeynekvqhc", power = 15,
modulo = 94, k = 4, hashValue = 16))
|
'''
-Medium-
Given the root of a binary tree, construct a 0-indexed m x n string matrix res that
represents a formatted layout of the tree. The formatted layout matrix should be
constructed using the following rules:
The height of the tree is height and the number of rows m should be equal to height + 1.
The number of columns n should be equal to 2height+1 - 1.
Place the root node in the middle of the top row (more formally, at location res[0][(n-1)/2]).
For each node that has been placed in the matrix at position res[r][c],
place its left child at res[r+1][c-2height-r-1] and its right child at res[r+1][c+2height-r-1].
Continue this process until all the nodes in the tree have been placed.
Any empty cells should contain the empty string "".
Return the constructed matrix res.
Example 1:
Input: root = [1,2]
Output:
[["","1",""],
["2","",""]]
Example 2:
Input: root = [1,2,3,null,4]
Output:
[["","","","1","","",""],
["","2","","","","3",""],
["","","4","","","",""]]
Constraints:
The number of nodes in the tree is in the range [1, 2^10].
-99 <= Node.val <= 99
The depth of the tree will be in the range [1, 10].
'''
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from typing import Optional, List
from BinaryTree import null, TreeNode, constructBinaryTree
class Solution:
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
def height(node):
if not node: return 0
return 1 + max(height(node.left), height(node.right))
def update(node, row, left, right):
if not node: return
mid = left + (right-left)//2
res[row][mid] = str(node.val)
update(node.left, row+1, left, mid-1)
update(node.right, row+1, mid+1, right)
h = height(root) - 1
w = 2**(h+1)-1
res = [['']*w for _ in range(h+1)]
update(root, 0, 0, w-1)
return res
if __name__ == "__main__":
root = constructBinaryTree([1,2,3,null,4])
root.prettyPrint()
for row in Solution().printTree(root):
print(row)
|
'''
-Medium-
*DFS*
Given an undirected tree consisting of n vertices numbered from 0 to n-1, which has some apples
in their vertices. You spend 1 second to walk over one edge of the tree. Return the minimum
time in seconds you have to spend to collect all apples in the tree, starting at vertex 0 and
coming back to this vertex.
The edges of the undirected tree are given in the array edges, where edges[i] = [ai, bi] means
that exists an edge connecting the vertices ai and bi. Additionally, there is a boolean array
hasApple, where hasApple[i] = true means that vertex i has an apple; otherwise, it does not
have any apple.
Example 1:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]],
hasApple = [false,false,true,false,true,true,false]
Output: 8
Explanation: The figure above represents the given tree where red vertices have an apple. One
optimal path to collect all apples is shown by the green arrows.
Example 2:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]],
hasApple = [false,false,true,false,false,true,false]
Output: 6
Explanation: The figure above represents the given tree where red vertices have an apple.
One optimal path to collect all apples is shown by the green arrows.
Example 3:
Input: n = 7, edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]],
hasApple = [false,false,false,false,false,false,false]
Output: 0
Constraints:
1 <= n <= 10^5
edges.length == n - 1
edges[i].length == 2
0 <= ai < bi <= n - 1
fromi < toi
hasApple.length == n
'''
from collections import defaultdict
class Solution(object):
def minTime(self, n, edges, hasApple):
"""
:type n: int
:type edges: List[List[int]]
:type hasApple: List[bool]
:rtype: int
"""
graph = defaultdict(list)
for e in edges:
graph[e[0]].append(e[1])
graph[e[1]].append(e[0])
visited = [False]*n
visited[0] = True
def dfs(node):
cost = 0
for nxt in graph[node]:
if not visited[nxt]:
visited[nxt] = True
cost += dfs(nxt)
if node != 0:
if cost > 0: cost += 2
elif hasApple[node]: cost += 2
return cost
return dfs(0)
if __name__ == "__main__":
edges = [[0,1],[0,2],[1,4],[1,5],[2,3],[2,6]]
hasApple = [False, False, True, False, True, True, False]
print(Solution().minTime(7, edges, hasApple))
edges = [[0,1],[1,2],[0,3]]
hasApple = [True, True, True, True]
print(Solution().minTime(4, edges, hasApple)) |
'''
-Hard-
*DP*
You are given a string s containing lowercase letters and an integer k. You need to :
First, change some characters of s to other lowercase English letters.
Then divide s into k non-empty disjoint substrings such that each substring is a palindrome.
Return the minimal number of characters that you need to change to divide the string.
Example 1:
Input: s = "abc", k = 2
Output: 1
Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.
Example 2:
Input: s = "aabbc", k = 3
Output: 0
Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.
Example 3:
Input: s = "leetcode", k = 8
Output: 0
Constraints:
1 <= k <= s.length <= 100.
s only contains lowercase English letters.
'''
class Solution:
def palindromePartition(self, s: str, k: int) -> int:
n = len(s)
memo = {}
def cost(s,i,j): #calculate the cost of transferring one substring into palindrome string
r = 0
while i < j:
if s[i] != s[j]:
r += 1
i += 1
j -= 1
return r
def dfs(i, k):
if (i, k) in memo: return memo[(i, k)] #case already in memo
if n - i == k: #base case that each substring just have one character
return 0
if k == 1: #base case that need to transfer whole substring into palidrome
return cost(s, i, n - 1)
res = float('inf')
for j in range(i + 1, n - k + 2): # keep making next part of substring into palidrome
res = min(res, dfs(j, k - 1) + cost(s,i, j - 1)) #compare different divisions to get the minimum cost
memo[(i, k)] = res
return res
return dfs(0 , k)
def palindromePartition2(self, s: str, k: int) -> int:
n = len(s)
memo = {}
c = [[0]*n for _ in range(n)]
def cost(s,i,j): #calculate the cost of transferring one substring into palindrome string
r = 0
while i < j:
if s[i] != s[j]:
r += 1
i += 1
j -= 1
return r
for i in range(n):
for j in range(n):
c[i][j] = cost(s, i, j)
def dfs(i, k):
if (i, k) in memo: return memo[(i, k)] #case already in memo
if n - i == k: #base case that each substring just have one character
return 0
if k == 1: #base case that need to transfer whole substring into palidrome
return c[i][n - 1]
res = float('inf')
for j in range(i + 1, n - k + 2): # keep making next part of substring into palidrome
res = min(res, dfs(j, k - 1) + c[i][j - 1]) #compare different divisions to get the minimum cost
memo[(i, k)] = res
return res
return dfs(0, k)
if __name__ == "__main__":
print(Solution().palindromePartition(s = "abc", k = 2))
print(Solution().palindromePartition2(s = "abc", k = 2)) |
'''
-Medium-
$$$
The alternating sum of a 0-indexed array is defined as the sum of the elements
at even indices minus the sum of the elements at odd indices.
Given an array find the maximum alternating subarray sum.
Example: [-1,2,-1,4,7]
Output is 7
Explanation:
Subarray [2,-1,4] has sum 2-(-1)+4=7
Subarray [7] has also sum 7
'''
from typing import List
class Solution:
def maximumAlternatingSubarraySum(self, nums: List[int]) -> int:
ans = -float('inf')
even = 0 # subarray sum starting from an even index
odd = 0 # subarray sum starting from an odd index
for i in range(len(nums)):
if (i & 1) == 0: # must pick
even += nums[i]
else: # fresh start or minus
even = max(0, even - nums[i])
ans = max(ans, even)
for i in range(1, len(nums)):
if i & 1: # must pick
odd += nums[i]
else: # fresh start or minus
odd = max(0, odd - nums[i])
ans = max(ans, odd)
return ans
if __name__ == "__main__":
print(Solution().maximumAlternatingSubarraySum([-1,2,-1,4,7])) |
'''
-Medium-
*Binary Search*
On a horizontal number line, we have gas stations at positions stations[0],
stations[1], ..., stations[N-1], where N = stations.length.
Now, we add K more gas stations so that D, the maximum distance between
adjacent gas stations, is minimized.
Return the smallest possible value of D.
Example:
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].
K will be an integer in range [1, 10^6].
Answers within 10^-6 of the true value will be accepted as correct.
'''
class Solution(object):
def minmaxGasDist(self, stations, K):
n = len(stations)
dist = [ i-j for i,j in zip(stations[1:], stations[:-1])]
def condition(mid):
cnt = 0
for i in range(1, n):
cnt += int((stations[i]-stations[i-1])/mid)
return cnt <= K
l, r = 0, max(dist)
while r-l > 1.e-6:
mid = l + (r-l)/2
if condition(mid):
r = mid
else:
l = mid
return l
if __name__ == "__main__":
print(Solution().minmaxGasDist([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9))
print(Solution().minmaxGasDist([3,6,12,19,33,44,67,72,89,95], 2))
|
'''
-Easy-
*Rolling Hash*
*Rabin Karp*
*KMP*
Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Subscribe to see which companies asked this question
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is
consistent to C's strstr() and Java's indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0
Constraints:
0 <= haystack.length, needle.length <= 5 * 10^4
haystack and needle consist of only lower-case English characters.
'''
from collections import defaultdict
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack:
return -1
if len(needle) > len(haystack):
return -1
for i in range(len(haystack)-len(needle)+1):
find = True
for j in range(len(needle)):
#print i, j, haystack[i+j], needle[j]
if haystack[i+j] != needle[j]:
find = False
break
if find:
return i
return -1
def strStrRabinKarp(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack:
return -1
if len(needle) > len(haystack):
return -1
m, n = len(needle), len(haystack)
q = 10**9+7
d = 26
h = pow(d, m-1, q)
p, t = 0, 0
for i in range(m):
p = (d*p+ord(needle[i]))%q
t = (d*t+ord(haystack[i]))%q
for i in range(n-m+1):
if p == t:
find = True
for j in range(m):
if haystack[i+j] != needle[j]:
find = False
break
if find:
return i
if i < n-m:
t = (d*(t - ord(haystack[i])*h) + ord(haystack[i+m]))%q
return -1
def strStrSunday(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack:
return -1
if len(needle) > len(haystack):
return -1
m, n = len(needle), len(haystack)
skip = defaultdict(int)
for i,c in enumerate(needle):
skip[c] = m-i
idx = 0
while idx < n-m+1:
j = idx
while j < idx+m:
if needle[j-idx] != haystack[j]:
break
j += 1
if j != idx+m:
#c = haystack[idx+m]
k = idx+m
if k < n and haystack[k] in skip:
idx += skip[haystack[k]]
else:
idx += m
else:
return idx
return -1
def strStrKMP(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack:
return -1
if len(needle) > len(haystack):
return -1
m, n = len(needle), len(haystack)
def partialMatchTable(P):
pt = [0]*m
k = 0
for q in range(1,m): # start matching at index 1, no need to match itself
while k > 0 and P[k] != P[q]:
k = pt[k-1] # note the difference from CLRS text which has k = pt[k]
if P[k] == P[q]:
k += 1
pt[q] = k
return pt
table = partialMatchTable(needle)
j = 0
for i in range(n):
while j > 0 and needle[j] != haystack[i]:
j = table[j-1] # note the difference from CLRS text which has k = pt[k]
if needle[j] == haystack[i]:
j += 1
if j == m:
return i-m+1 # note the difference from CLRS text which has i-m
return -1
def strStrKMP2(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if not haystack:
return -1
if len(needle) > len(haystack):
return -1
m, n = len(needle), len(haystack)
b = [0] * (m + 1)
i, j = 0, -1
b[i] = j
# prepare roll-back table
while i < m:
# roll-back
while j >= 0 and needle[i] != needle[j]:
j = b[j]
j += 1
i += 1
b[i] = j
i = j = 0
while i < n:
#for i in range(m):
# roll-back
while j >= 0 and needle[j] != haystack[i]:
j = b[j]
j += 1
i += 1
if j == m:
return i - m
return -1
if __name__ == "__main__":
#assert Solution().strStr("abcdefg", "ab") == 0
#assert Solution().strStr("abcdefg", "bc") == 1
#assert Solution().strStr("abcdefg", "cd") == 2
'''
assert Solution().strStr("abcdefg", "fg") == 5
#assert Solution().strStr("abcdefg", "bcf") == -1
assert Solution().strStr("a", "a") == 0
assert Solution().strStrRabinKarp("abcdefg", "fg") == 5
assert Solution().strStrRabinKarp("a", "a") == 0
assert Solution().strStrRabinKarp("aaaaa", "bba") == -1
assert Solution().strStrSunday("aaaaa", "aab") == -1
assert Solution().strStrSunday("hello", "ll") == 2
assert Solution().strStrSunday("mississippi","a") == -1
assert Solution().strStrSunday("mississippi","issi") == 1
'''
assert Solution().strStrKMP("aaaaa", "aab") == -1
assert Solution().strStrKMP("hello", "ll") == 2
assert Solution().strStrKMP("mississippi","a") == -1
assert Solution().strStrKMP("mississippi","issi") == 1
#'''
# this test case will fail Sunday and Brute Force with TLE
# only Rabin-Karp and KMP can pass AC
source = "a"*99999+'b'+"a"*99999
target = "a"*100000
# from collections import Counter
# cs = Counter(source)
# ct = Counter(target)
#print(cs, ct)
print(Solution().strStrRabinKarp(source, target))
print(Solution().strStrKMP(source, target))
print(source.find(target))
print(Solution().strStr(source, target))
#'''
|
'''
-Medium-
*Monotonic Stack*
Given string num representing a non-negative integer num, and an integer k, return the smallest possible integer after removing k digits from num.
Example 1:
Input: num = "1432219", k = 3
Output: "1219"
Explanation: Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
Example 2:
Input: num = "10200", k = 1
Output: "200"
Explanation: Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
Example 3:
Input: num = "10", k = 2
Output: "0"
Explanation: Remove all the digits from the number and it is left with nothing which is 0.
Constraints:
1 <= k <= num.length <= 105
num consists of only digits.
num does not have any leading zeros except for the zero itself.
'''
class Solution:
def removeKdigits(self, num: str, k: int) -> str:
st = []
for n in num:
while st and k and st[-1] > n:
st.pop()
k -= 1
if st or n != '0': # prevent leading zeros
st.append(n)
if k: # not fully spent
st = st[0:-k]
return ''.join(st) or '0'
if __name__ == "__main__":
print(Solution().removeKdigits(num = "1432219", k = 3))
print(Solution().removeKdigits(num = "21462", k = 2)) |
'''
-Hard-
*BFS*
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file 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. 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 original tree structure.
Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.
Example 1:
Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]
Example 2:
Input: root = []
Output: []
Constraints:
The number of nodes in the tree is in the range [0, 104].
-1000 <= Node.val <= 1000
'''
from BinaryTree import (TreeNode, constructBinaryTree, null)
from collections import deque
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: TreeNode
:rtype: str
"""
q = deque()
L = []
if root:
q.append(root)
else:
return ''
while q:
node = q.popleft()
if node:
q.append(node.left)
q.append(node.right)
L.append(str(node.val) if node else '#')
return ','.join(L)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: TreeNode
"""
if not data: return None
nodes = data.split(',')
root = TreeNode(int(nodes[0]))
q = deque([root])
index = 1
while q:
node = q.popleft()
if nodes[index] is not '#':
node.left = TreeNode(int(nodes[index]))
q.append(node.left)
index += 1
if nodes[index] is not '#':
node.right = TreeNode(int(nodes[index]))
q.append(node.right)
index += 1
return root
if __name__ == "__main__":
# Your Codec object will be instantiated and called as such:
codec = Codec()
root = constructBinaryTree([1,2,3,null,null,4,5])
#root = constructBinaryTree([5,2,3,null,null,2,4,3,1])
print(codec.serialize(root))
print(codec.deserialize(codec.serialize(root))) |
'''
-Medium-
There is a class with m students and n exams. You are given a 0-indexed m x n integer matrix score, where each row represents one student and score[i][j] denotes the score the ith student got in the jth exam. The matrix score contains distinct integers only.
You are also given an integer k. Sort the students (i.e., the rows of the matrix) by their scores in the kth (0-indexed) exam from the highest to the lowest.
Return the matrix after sorting it.
Example 1:
Input: score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2
Output: [[7,5,11,2],[10,6,9,1],[4,8,3,15]]
Explanation: In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 11 in exam 2, which is the highest score, so they got first place.
- The student with index 0 scored 9 in exam 2, which is the second highest score, so they got second place.
- The student with index 2 scored 3 in exam 2, which is the lowest score, so they got third place.
Example 2:
Input: score = [[3,4],[5,6]], k = 0
Output: [[5,6],[3,4]]
Explanation: In the above diagram, S denotes the student, while E denotes the exam.
- The student with index 1 scored 5 in exam 0, which is the highest score, so they got first place.
- The student with index 0 scored 3 in exam 0, which is the lowest score, so they got second place.
Constraints:
m == score.length
n == score[i].length
1 <= m, n <= 250
1 <= score[i][j] <= 105
score consists of distinct integers.
0 <= k < n
'''
from typing import List
class Solution:
def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:
m, n = len(score), len(score[0])
col, ans = [], [[0]*n for _ in range(m)]
for i in range(m):
col.append((score[i][k],i))
col.sort(reverse=True)
for i in range(m):
for j in range(n):
ans[i][j] = score[col[i][1]][j]
return ans
if __name__ == '__main__':
print(Solution().sortTheStudents(score = [[10,6,9,1],[7,5,11,2],[4,8,3,15]], k = 2)) |
'''
Amazon is running a promotion in which customers receive prizes for purchasing a secret combination of
fruits. The combination will change each day, and the team running the promotion wants to use a code
list to make it easy to change the combination. The code list contains groups of fruits. Both the
order of the groups within the code list and the order of the fruits within the groups matter. However,
between the groups of fruits, any number, and type of fruit is allowable. The term "anything" is used
to allow for any type of fruit to appear in that location within the group.
Consider the following secret code list: [[apple, apple], [banana, anything, banana]]
Based on the above secret code list, a customer who made either of the following purchases would win the prize:
orange, apple, apple, banana, orange, banana
apple, apple, orange, orange, banana, apple, banana, banana
Write an algorithm to output 1 if the customer is a winner else output 0.
Input
The input to the function/method consists of two arguments:
codeList, a list of lists of strings representing the order and grouping of specific fruits that must be purchased in order to win the prize for the day.
shoppingCart, a list of strings representing the order in which a customer purchases fruit.
Output
Return an integer 1 if the customer is a winner else return 0.
Note
'anything' in the codeList represents that any fruit can be ordered in place of 'anything' in the group. 'anything' has to be something, it cannot be "nothing."
'anything' must represent one and only one fruit.
If secret code list is empty then it is assumed that the customer is a winner.
Example 1:
Input: codeList = [[apple, apple], [banana, anything, banana]] shoppingCart = [orange, apple, apple, banana, orange, banana]
Output: 1
Explanation:
codeList contains two groups - [apple, apple] and [banana, anything, banana].
The second group contains 'anything' so any fruit can be ordered in place of 'anything' in the shoppingCart. The customer is a winner as the customer has added fruits in the order of fruits in the groups and the order of groups in the codeList is also maintained in the shoppingCart.
Example 2:
Input: codeList = [[apple, apple], [banana, anything, banana]]
shoppingCart = [banana, orange, banana, apple, apple]
Output: 0
Explanation:
The customer is not a winner as the customer has added the fruits in order of groups but group [banana, orange, banana] is not following the group [apple, apple] in the codeList.
Example 3:
Input: codeList = [[apple, apple], [banana, anything, banana]] shoppingCart = [apple, banana, apple, banana, orange, banana]
Output: 0
Explanation:
The customer is not a winner as the customer has added the fruits in an order which is not following the order of fruit names in the first group.
Example 4:
Input: codeList = [[apple, apple], [apple, apple, banana]] shoppingCart = [apple, apple, apple, banana]
Output: 0
Explanation:
The customer is not a winner as the first 2 fruits form group 1, all three fruits would form group 2, but can't because it would contain all fruits of group 1.
'''
class Solution(object):
def is_winner(self, promotions, orders):
"""
Approach: Two Pointers
Time Complexity: O(MN)
promotion_list = [["apple", "apple"], ["banana", "anything", "banana"]]
order = ["orange", "apple", "apple", "banana", "orange", "banana"]
:param promotions:
:param orders:
:return:
"""
# initialize indexes to 0
p_idx = o_idx = 0
# 1st loop until both index reach their size
while p_idx < len(promotions) and o_idx < len(orders):
# put the each promotion combination into a list
promo_combination = promotions[p_idx]
# initialize the above combination index
promo_idx = 0
# loop through the promo_combination and orders to see if
# it satisfies
while promo_idx < len(promo_combination) and o_idx < len(orders):
# now compare each combination with the order and also wild card anything
if promo_combination[promo_idx] == orders[o_idx] or promo_combination[promo_idx] == "anything":
# increment the promo_idx
promo_idx += 1
else:
# if not start the comparision from beginning
promo_idx = 0
# move to next order
o_idx += 1
if promo_idx != len(promo_combination):
return False
# move to next promotion combinations
p_idx += 1
# if the promotion index is less than total promotions
# return False
if p_idx < len(promotions):
return False
return True
if __name__ == "__main__":
codeList = [['apple', 'apple'], ['apple', 'apple', 'banana']]
shoppingCart = ['apple', 'apple', 'apple', 'banana']
print(Solution().is_winner(codeList, shoppingCart))
|
'''
-Medium-
*Backtracking*
You are given a string s that consists of only digits.
Check if we can split s into two or more non-empty substrings such that
the numerical values of the substrings are in descending order and the
difference between numerical values of every two adjacent substrings is
equal to 1.
For example, the string s = "0090089" can be split into ["0090", "089"]
with numerical values [90,89]. The values are in descending order and
adjacent values differ by 1, so this way is valid.
Another example, the string s = "001" can be split into ["0", "01"], ["00", "1"], or ["0", "0", "1"]. However all the ways are invalid because they have numerical values [0,1], [0,1], and [0,0,1] respectively, all of which are not in descending order.
Return true if it is possible to split s as described above, or false otherwise.
A substring is a contiguous sequence of characters in a string.
Example 1:
Input: s = "1234"
Output: false
Explanation: There is no valid way to split s.
Example 2:
Input: s = "050043"
Output: true
Explanation: s can be split into ["05", "004", "3"] with numerical values [5,4,3].
The values are in descending order with adjacent values differing by 1.
Example 3:
Input: s = "9080701"
Output: false
Explanation: There is no valid way to split s.
Example 4:
Input: s = "10009998"
Output: true
Explanation: s can be split into ["100", "099", "98"] with numerical values [100,99,98].
The values are in descending order with adjacent values differing by 1.
Constraints:
1 <= s.length <= 20
s only consists of digits.
'''
class Solution:
def splitString(self, s: str) -> bool:
def helper(str, pre, ns):
if not str:
if ns >= 2:
return True
return False
for i in range(len(str)):
num = int(str[:i+1])
if pre == -1 or pre - num == 1:
if helper(str[i+1:], num, ns+1):
return True
return False
return helper(s, -1, 0)
if __name__=="__main__":
print(Solution().splitString("10009998"))
print(Solution().splitString("050043"))
print(Solution().splitString("9080701"))
print(Solution().splitString("1234"))
print(Solution().splitString("10"))
|
'''
-Hard-
You are installing a billboard and want it to have the largest height. The
billboard will have two steel supports, one on each side. Each steel support
must be an equal height.
You are given a collection of rods that can be welded together. For example,
if you have rods of lengths 1, 2, and 3, you can weld them together to make
a support of length 6.
Return the largest possible height of your billboard installation. If you
cannot support the billboard, return 0.
Example 1:
Input: rods = [1,2,3,6]
Output: 6
Explanation: We have two disjoint subsets {1,2,3} and {6}, which have the same sum = 6.
Example 2:
Input: rods = [1,2,3,4,5,6]
Output: 10
Explanation: We have two disjoint subsets {2,3,5} and {4,6}, which have the same sum = 10.
Example 3:
Input: rods = [1,2]
Output: 0
Explanation: The billboard cannot be supported, so we return 0.
Constraints:
1 <= rods.length <= 20
1 <= rods[i] <= 1000
sum(rods[i]) <= 5000
'''
from typing import List
import collections
class Solution:
def tallestBillboard(self, rods: List[int]) -> int:
n = len(rods)
sum_ = sum(rods)
dp = [[0]*(sum_+1) for _ in range(n+1)]
for i in range(sum_+1): dp[0][i] = -10**9
dp[0][0] = 0
for i in range(1, n+1):
for j in range(sum_):
dp[i][j] = dp[i - 1][j]
if j >= rods[i - 1]:
dp[i][j] = max(dp[i][j], dp[i - 1][j - rods[i - 1]] + rods[i - 1])
else:
dp[i][j] = max(dp[i][j], dp[i - 1][rods[i - 1] - j] + j)
if j + rods[i - 1] <= sum_:
dp[i][j] = max(dp[i][j], dp[i - 1][j + rods[i - 1]])
return dp[n][0]
def tallestBillboard2(self, rods: List[int]) -> int:
sum_ = sum(rods)
dp = [-10**9]*(sum_+1)
dp[0] = 0
for x in rods:
cur = dp[:]
for d in range(sum_-x+1):
dp[d + x] = max(dp[d + x], cur[d])
dp[abs(d - x)] = max(dp[abs(d - x)], cur[d] + min(d, x))
return dp[0]
def tallestBillboard3(self, rods):
#Consider this problem as:
#Given a list of numbers, multiply each number with 1 or 0 or -1, make the
# sum of all numbers to 0. Find a combination which has the largest sum
# of all positive numbers.
#e.g. Given [1,2,3,4,5,6], we have 1*0 + 2 + 3 - 4 + 5 - 6 = 0, the sum
# of all positive numbers is 2 + 3 + 5 = 10. The answer is 10.
# This is a knapsack problem.
# dp[i][j] represents whether the sum of first i numbers can be j - 5000.
# dp[0][5000] = true.
# Then dp[i + 1][j] = dp[i][j - rods[i]] | dp[i][j + rods[i]] | dp[i][j].
# max[i][j] represents the largest sum of all positive numbers when the
# sum of first i numbers is j - 5000.
# Time complexity: O(N*sum)
# It is like a knapsack problem.
# Consider this problem as:
# Given a list of numbers, multiply each number with 1 or 0 or -1, make the
# sum of all numbers to 0. Find a combination which has the largest sum of
# all positive numbers.
# We can consider the sum as the key and positive number sum as the value.
# We initally have dp[0] = 0
# We iterate through the numbers and calculate the pairs that we got. In
# the case that we have same sum but different postive number sum, we only
# keep the largest postive number sum.
# Let's run through a example, [1,2,3]
# First we have {0:0}.
# After 1, we have {0: 0, 1: 1, -1: 0}
# After 2, we have {0:0, 2:2, -2:0, 1:1, 3:3,-1:1, -1:0,1:2,-3:0}
# we will drop 1:1 and -1:0 since they have smaller value with the same key[1]and [-1].
# That left us with {0:0, 2:2, -2:0, 3:3,-1:1,1:2,-3:0}
# Number 3 is doing pretty much the same.
# Then we will get the final result with dp[0]
dp = dict()
dp[0] = 0
for i in rods:
cur = collections.defaultdict(int)
for s in dp:
cur[s+i] = max(dp[s] + i, cur[s+i])
cur[s] = max(dp[s], cur[s])
cur[s-i] = max(dp[s], cur[s-i])
dp = cur
return dp[0]
if __name__ == "__main__":
print(Solution().tallestBillboard([1,2,3,6]))
print(Solution().tallestBillboard2([1,2,3,6]))
print(Solution().tallestBillboard3([1,2,3,6])) |
'''
-Easy-
*Two Pointers*
Given an array of integers nums, half of the integers in nums are odd, and the other half are even.
Sort the array so that whenever nums[i] is odd, i is odd, and whenever nums[i] is even, i is even.
Return any answer array that satisfies this condition.
Example 1:
Input: nums = [4,2,5,7]
Output: [4,5,2,7]
Explanation: [4,7,2,5], [2,5,4,7], [2,7,4,5] would also have been accepted.
Example 2:
Input: nums = [2,3]
Output: [2,3]
Constraints:
2 <= nums.length <= 2 * 10^4
nums.length is even.
Half of the integers in nums are even.
0 <= nums[i] <= 1000
Follow Up: Could you solve it in-place?
use two pointers
'''
from typing import List
class Solution:
def sortArrayByParityII(self, nums: List[int]) -> List[int]:
n, e, o = len(nums), 0, 1
res = [0]*n
for i in nums:
if i % 2 == 0:
res[e] = i
e += 2
else:
res[o] = i
o += 2
return res
def sortArrayByParityIIInPlace(self, nums: List[int]) -> List[int]:
n, e, o = len(nums), 0, 1
while e <= n-2 and o <= n-1:
if nums[e] % 2 == 0 and nums[o] % 2 == 1:
e += 2; o += 2
elif nums[e] % 2 == 1 and nums[o] % 2 == 0:
nums[e], nums[o] = nums[o], nums[e]
e += 2; o += 2
elif nums[e] % 2 == 1 and nums[o] % 2 == 1:
o += 2
else: e += 2
return nums
if __name__ == "__main__":
print(Solution().sortArrayByParityII([4,2,5,7]))
print(Solution().sortArrayByParityIIInPlace([4,2,5,7]))
|
'''
-Medium-
*Binary Search*
Given an array of integers nums and an integer threshold, we will choose a
positive integer divisor and divide all the array by it and sum the result
of the division. Find the smallest divisor such that the result mentioned
above is less than or equal to threshold.
Each result of division is rounded to the nearest integer greater than or
equal to that element. (For example: 7/3 = 3 and 10/2 = 5).
It is guaranteed that there will be an answer.
Example 1:
Input: nums = [1,2,5,9], threshold = 6
Output: 5
Explanation: We can get a sum to 17 (1+2+5+9) if the divisor is 1.
If the divisor is 4 we can get a sum to 7 (1+1+2+3) and if the divisor is 5 the sum will be 5 (1+1+1+2).
Example 2:
Input: nums = [2,3,5,7,11], threshold = 11
Output: 3
Example 3:
Input: nums = [19], threshold = 5
Output: 4
Constraints:
1 <= nums.length <= 5 * 10^4
1 <= nums[i] <= 10^6
nums.length <= threshold <= 10^6
'''
import math
class Solution(object):
def smallestDivisor(self, nums, threshold):
"""
:type nums: List[int]
:type threshold: int
:rtype: int
"""
def divsum(denom):
sm = 0
for i in nums:
sm += math.ceil(i/denom)
return sm
l, r = 1, max(nums)
while l < r:
m = l + (r-l)//2
if divsum(m) <= threshold:
r = m
else:
l = m+1
return l
if __name__ == "__main__":
#'''
print(Solution().smallestDivisor([2,3,5,7,11], 11))
print(Solution().smallestDivisor([1,2,5,9], 6))
print(Solution().smallestDivisor([9,9,9,9], 6))
print(Solution().smallestDivisor([19], 5))
print(Solution().smallestDivisor([1,2,3],1000000))
#'''
print(Solution().smallestDivisor([962551,933661,905225,923035,990560], 10)) |
'''
-Medium-
*DP*
You are currently designing a dynamic array. You are given a 0-indexed integer array nums, where nums[i] is the number of elements that will be in the array at time i. In addition, you are given an integer k, the maximum number of times you can resize the array (to any size).
The size of the array at time t, sizet, must be at least nums[t] because there needs to be enough space in the array to hold all the elements. The space wasted at time t is defined as sizet - nums[t], and the total space wasted is the sum of the space wasted across every time t where 0 <= t < nums.length.
Return the minimum total space wasted if you can resize the array at most k times.
Note: The array can have any size at the start and does not count towards the number of resizing operations.
Example 1:
Input: nums = [10,20], k = 0
Output: 10
Explanation: size = [20,20].
We can set the initial size to be 20.
The total wasted space is (20 - 10) + (20 - 20) = 10.
Example 2:
Input: nums = [10,20,30], k = 1
Output: 10
Explanation: size = [20,20,30].
We can set the initial size to be 20 and resize to 30 at time 2.
The total wasted space is (20 - 10) + (20 - 20) + (30 - 30) = 10.
Example 3:
Input: nums = [10,20,15,30,20], k = 2
Output: 15
Explanation: size = [10,20,20,30,30].
We can set the initial size to 10, resize to 20 at time 1, and resize to 30 at time 3.
The total wasted space is (10 - 10) + (20 - 20) + (20 - 15) + (30 - 30) + (30 - 20) = 15.
Constraints:
1 <= nums.length <= 200
1 <= nums[i] <= 106
0 <= k <= nums.length - 1
'''
from typing import List
from functools import lru_cache
class Solution:
def minSpaceWastedKResizing(self, nums: List[int], k: int) -> int:
n = len(nums)
dp = [[float('inf')]*(k+1) for _ in range(n)]
mx, sm = 0, 0
for i in range(n):
mx = max(mx, nums[i])
sm += nums[i]
dp[i][0] = mx*(i+1) - sm
for i in range(1, n):
for j in range(1, min(i,k)+1):
mx, invsum = 0, 0
for s in range(i, max(j-2, 0), -1):
mx = max(mx, nums[s])
invsum += nums[s]
dp[i][j] = min(dp[i][j], dp[s-1][j-1]+mx*(i-s+1)-invsum)
return min(dp[n-1])
def minSpaceWastedKResizing2(self, nums: List[int], k: int) -> int:
# Solution similar to 1335. Minimum Difficulty of a Job Schedule
# https://leetcode.com/problems/minimum-difficulty-of-a-job-schedule/
n, INF = len(nums), 200 * 1e6
# dp(i, k) denote the minimum space wasted if we can resize k times of nums[i..n-1].
@lru_cache(None)
def dp(i, k):
if i == n: return 0
if k == -1: return INF
ans = INF
maxNum = 0
totalSum = 0
for j in range(i, n-k):
# make 1 adjustment in range [i, j]
maxNum = max(maxNum, nums[j])
totalSum += nums[j]
# total space wasted in range [i, j]
wasted = maxNum * (j - i + 1) - totalSum
ans = min(ans, dp(j + 1, k - 1) + wasted)
return ans
return dp(0, k)
if __name__ == "__main__":
print(Solution().minSpaceWastedKResizing(nums = [10,20,15,30,20], k = 2))
|
'''
-Medium-
An integer array original is transformed into a doubled array changed by appending twice the
value of every element in original, and then randomly shuffling the resulting array.
Given an array changed, return original if changed is a doubled array. If changed is not a
doubled array, return an empty array. The elements in original may be returned in any order.
Example 1:
Input: changed = [1,3,4,2,6,8]
Output: [1,3,4]
Explanation: One possible original array could be [1,3,4]:
- Twice the value of 1 is 1 * 2 = 2.
- Twice the value of 3 is 3 * 2 = 6.
- Twice the value of 4 is 4 * 2 = 8.
Other original arrays could be [4,3,1] or [3,1,4].
Example 2:
Input: changed = [6,3,0,1]
Output: []
Explanation: changed is not a doubled array.
Example 3:
Input: changed = [1]
Output: []
Explanation: changed is not a doubled array.
Constraints:
1 <= changed.length <= 10^5
0 <= changed[i] <= 10^5
'''
from typing import List
from collections import defaultdict
class Solution:
def findOriginalArray(self, changed: List[int]) -> List[int]:
n = len(changed)
if n % 2 == 1: return []
m = defaultdict(int)
res = []
for i in changed:
if i%2 == 0 and i//2 in m:
m[i//2] -= 1
if m[i//2] == 0:
m.pop(i//2)
res.append(i//2)
elif i*2 in m:
m[i*2] -= 1
if m[i*2] == 0:
m.pop(i*2)
res.append(i)
else:
m[i] += 1
#print(m)
if not m: return res
return []
def findOriginalArray2(self, changed: List[int]) -> List[int]:
n = len(changed)
changed.sort()
if n % 2 == 1: return []
m = defaultdict(int)
res = []
for i in changed:
j = i // 2
if i%2 == 0 and j in m:
m[j] -= 1
if m[j] == 0:
m.pop(j)
res.append(j)
else:
m[i] += 1
#print(m)
if not m: return res
return []
if __name__=="__main__":
#print(Solution().findOriginalArray([1,3,4,2,6,8]))
#print(Solution().findOriginalArray([6,3,0,1]))
#print(Solution().findOriginalArray([1]))
print(Solution().findOriginalArray([4,4,16,20,8,8,2,10]))
print(Solution().findOriginalArray2([4,4,16,20,8,8,2,10])) |
'''
-Medium-
Given an integer array nums and an integer k, return the number of subarrays of nums where the greatest common divisor of the subarray's elements is k.
A subarray is a contiguous non-empty sequence of elements within an array.
The greatest common divisor of an array is the largest integer that evenly divides all the array elements.
Example 1:
Input: nums = [9,3,1,2,6,3], k = 3
Output: 4
Explanation: The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are:
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
Example 2:
Input: nums = [4], k = 7
Output: 0
Explanation: There are no subarrays of nums where 7 is the greatest common divisor of all the subarray's elements.
Constraints:
1 <= nums.length <= 1000
1 <= nums[i], k <= 109
'''
from math import gcd
from typing import List
from collections import Counter
class Solution:
def subarrayGCD(self, nums: List[int], k: int) -> int:
n, ans = len(nums), 0
for i in range(n):
g = nums[i]
if g == k:
ans += 1
for j in range(i+1,n):
g = gcd(g, nums[j])
if g == k:
ans += 1
return ans
def subarrayGCD2(self, nums: List[int], k: int) -> int:
n, ans = len(nums), 0
gcds = Counter()
for i in range(n):
gcds1 = Counter()
if nums[i] % k == 0:
gcds[nums[i]] += 1
for prev,cnt in gcds.items():
gcds1[gcd(prev, nums[i])] += cnt
ans += gcds1[k]
gcds, gcds1 = gcds1, gcds
return ans
if __name__ == "__main__":
print(Solution().subarrayGCD(nums = [9,3,1,2,6,3], k = 3))
print(Solution().subarrayGCD2(nums = [9,3,1,2,6,3], k = 3)) |
"""
Given an unsorted array of integers, find the length of longest increasing
subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4.
Note that there may be more than one LIS combination, it is only necessary
for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
"""
import bisect
__author__ = 'Daniel'
class Solution(object):
def binary_search_corr(self, L, a):
l = -1
r = len(L)
print(l, r)
while r-l > 1:
m = l+(r-l)/2
if L[m] >= a:
r = m
else:
l = m
print(l, r, m)
return r
def lengthOfLIS_nlogn(self, A):
if not A:
return 0
def bisect_diy(l, r, a):
while l<r:
m = l+(r-l)//2
if A[bis[m]] >= a:
r = m
else:
l = m+1
return r
# bis[k] : the index the best increasing sequence of length k ends at
# k = 0, ll-1
bis=[0]*len(A)
prev = [-1]*len(A)
ll = 1 # length of LIS, which is 1 initially for len(A)=1
for i in range(1, len(A)):
if A[i] < A[bis[0]]:
bis[0] = i # new smallest value
elif A[i] > A[bis[ll-1]]: # A[i] can extend the LIS found so far
prev[i] = bis[ll-1]
bis[ll] = i # after the extension the longest IS ends at i
ll +=1 # after the extension the longest length is ll
else:
j = bisect_diy(0, ll, A[i]) # find a location j in [0, ll)
prev[i] = bis[j-1] # such that A[bis[j-1]] < A[i] < A[bis[j]]
bis[j] = i # replace bis[j] with i, indicating we have found a
# better bis[j] ending with A[i]
#for i in bis[:ll]:
# print(A[i])
#print('******************************')
#print(prev)
#print('******************************')
i = bis[ll-1]
while i>=0:
# print(i, A[i])
i = prev[i]
# print a, ind, bis
#print bis
return ll
def lengthOfLIS_dp(self, A):
"""
dp
let F[i] be the LIS length ends at A[i]
F[i] = max(F[j]+1 for all j < i if A[i] > A[j])
avoid max() arg is an empty sequence
O(n^2)
:type nums: List[int]
:rtype: int
"""
if not A:
return 0
F=[1]*len(A)
maxa = 1
for i in range(1, len(A)):
# starting from index i, traverse back until index 0,
# if A[i] > any given number A[j], we have a potential
# new LIS with length F[j]+1, update F[i] and the result
for j in range(i):
if A[i] > A[j] and F[i] < 1+F[j]:
F[i] = 1+F[j]
maxa = max(maxa, F[i])
print(F)
return maxa
def lengthOfLIS_nlogn2(self, nums):
lis = []
for i, x in enumerate(nums):
if len(lis) == 0 or lis[-1] < x: # Append to LIS if new element is >= last element in LIS
lis.append(x)
elif x < lis[0]:
lis[0] = x
else:
idx = bisect.bisect_left(lis, x) # Find the index of the smallest number > x
if idx < len(lis):
lis[idx] = x # Replace that number with x
return len(lis)
if __name__ == "__main__":
#assert Solution().lengthOfLIS_dp([10, 9, 2, 5, 3, 7, 101, 18]) == 4
#print(Solution().lengthOfLIS_dp([5, 10, 4, 4, 3, 8, 9]))
print(Solution().lengthOfLIS_nlogn([5, 10, 6, 4, 3, 8, 9]))
print(Solution().lengthOfLIS_nlogn2([5, 10, 6, 4, 3, 8, 9]))
print(Solution().lengthOfLIS_nlogn([0,1,0,3,2,3]))
print(Solution().lengthOfLIS_nlogn2([0,1,0,3,2,3]))
print(Solution().lengthOfLIS_nlogn([7,7,7,7,7,7,7]))
print(Solution().lengthOfLIS_nlogn2([7,7,7,7,7,7,7]))
assert Solution().lengthOfLIS_nlogn([10, 9, 2, 5, 3, 7, 101, 18]) == 4
assert Solution().lengthOfLIS_nlogn2([10, 9, 2, 5, 3, 7, 101, 18]) == 4
print(Solution().lengthOfLIS_nlogn([4,10,4,3,8,9]))
print(Solution().lengthOfLIS_nlogn2([4,10,4,3,8,9]))
#assert
# Solution().lengthOfLIS_nlogn([0, 8, 4, 12, 2, 10, 6, 14,
# 1, 9, 5, 13, 3, 11, 7, 15]) == 6
#assert Solution().lengthOfLIS_dp([2, 4, 6, 8, 10, 1]) == 5
#assert Solution().lengthOfLIS_nlogn([2, 4, 6, 8, 10, 1]) == 5
L = [2, 4, 6, 9, 11, 15]
a = 8
#print Solution().binary_search_corr(L, a)
#print bisect.bisect_left(L, a) |
'''
-Hard-
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]. (coordinate of
bottom-left point is (1, 1) and top-right point is (2, 2)).
Example 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
Return true. All 5 rectangles together form an exact cover of a rectangular region.
Example 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
Return false. Because there is a gap between the two rectangular regions.
Example 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
Return false. Because there is a gap in the top center.
Example 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
Return false. Because two of the rectangles overlap with each other.
'''
class Solution(object):
def isRectangleCover(self, rectangles):
"""
:type rectangles: List[List[int]]
:rtype: bool
"""
X1, Y1, X2, Y2 = float('inf'), float('inf'), -float('inf'), -float('inf')
allarea = 0
vertices = set()
for x1,y1,x2,y2 in rectangles:
X1 = min(x1, X1)
Y1 = min(y1, Y1)
X2 = max(x2, X2)
Y2 = max(y2, Y2)
allarea += (y2-y1)*(x2-x1)
for (x,y) in [(x1,y1), (x2,y1), (x1,y2), (x2,y2)]:
if (x, y) in vertices:
vertices.remove((x,y))
else:
vertices.add((x,y))
area = (Y2-Y1)*(X2-X1)
if area != allarea: return False
if len(vertices) != 4: return False
if (X1,Y1) not in vertices: return False
if (X1,Y2) not in vertices: return False
if (X2,Y1) not in vertices: return False
if (X2,Y2) not in vertices: return False
return True
if __name__ == "__main__":
rect = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
print(Solution().isRectangleCover(rect))
rect = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
print(Solution().isRectangleCover(rect))
|
'''
-Hard-
You are given a list of strings of the same length words and a string target.
Your task is to form target using the given words under the following rules:
target should be formed from left to right.
To form the ith character (0-indexed) of target, you can choose the kth character of the jth string in words if target[i] = words[j][k].
Once you use the kth character of the jth string of words, you can no longer use the xth character of any string in words where x <= k. In other words, all characters to the left of or at index k become unusuable for every string.
Repeat the process until you form the string target.
Notice that you can use multiple characters from the same string in words provided the conditions above are met.
Return the number of ways to form target from words. Since the answer may be too large, return it modulo 109 + 7.
Example 1:
Input: words = ["acca","bbbb","caca"], target = "aba"
Output: 6
Explanation: There are 6 ways to form target.
"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("caca")
"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("caca")
"aba" -> index 0 ("acca"), index 1 ("bbbb"), index 3 ("acca")
"aba" -> index 0 ("acca"), index 2 ("bbbb"), index 3 ("acca")
"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("acca")
"aba" -> index 1 ("caca"), index 2 ("bbbb"), index 3 ("caca")
Example 2:
Input: words = ["abba","baab"], target = "bab"
Output: 4
Explanation: There are 4 ways to form target.
"bab" -> index 0 ("baab"), index 1 ("baab"), index 2 ("abba")
"bab" -> index 0 ("baab"), index 1 ("baab"), index 3 ("baab")
"bab" -> index 0 ("baab"), index 2 ("baab"), index 3 ("baab")
"bab" -> index 1 ("abba"), index 2 ("baab"), index 3 ("baab")
Constraints:
1 <= words.length <= 1000
1 <= words[i].length <= 1000
All strings in words have the same length.
1 <= target.length <= 1000
words[i] and target contain only lowercase English letters.
'''
from typing import List
from collections import Counter
from functools import lru_cache
class Solution:
def numWays(self, words: List[str], target: str) -> int:
n, m = len(words[0]), len(target)
freq = [Counter() for _ in range(n)]
# pos = [set() for _ in range(26)]
MOD = 10**9+7
for word in words:
for i in range(n):
freq[i][word[i]] += 1
# pos[ord(word[i]) - ord('a')].add(i)
# for i in range(26):
# pos[i] = sorted(list(pos[i]))
@lru_cache(None)
def dp(i, j):
if i == m: return 1
if j == n: return 0
ans = 0
# l = n-m+i+1
for k in range(j, n-m+i+1):
# for k in pos[ord(target[i]) - ord('a')]:
# ret = dp(i+1, k+1)
# if i == 0:
# print(k, ret, freq[k][target[i]])
# ans += freq[k][target[i]] * ret
# if j <= k <l and target[i] in freq[k]:
if target[i] in freq[k]:
ans = (ans + freq[k][target[i]] * dp(i+1, k+1)) % MOD
return ans
return dp(0, 0)
def numWays2(self, words: List[str], target: str) -> int:
n, m = len(words[0]), len(target)
freq = [Counter() for _ in range(n)]
MOD = 10**9+7
for word in words:
for i in range(n):
freq[i][word[i]] += 1
@lru_cache(None)
def dp(i, j):
if i == m: return 1
if j == n: return 0
if n-j < m-i: return 0
ans = dp(i, j+1)
if target[i] in freq[j]:
ans = (ans + freq[j][target[i]] * dp(i+1, j+1)) % MOD
return ans
return dp(0, 0)
if __name__ == "__main__":
print(Solution().numWays(words = ["acca","bbbb","caca"], target = "aba"))
print(Solution().numWays(words = ["abba","baab"], target = "bab"))
|
'''
-Medium-
*Sorting*
There are two mice and n different types of cheese, each type of cheese should be eaten by exactly one mouse.
A point of the cheese with index i (0-indexed) is:
reward1[i] if the first mouse eats it.
reward2[i] if the second mouse eats it.
You are given a positive integer array reward1, a positive integer array reward2, and a non-negative integer k.
Return the maximum points the mice can achieve if the first mouse eats exactly k types of cheese.
Example 1:
Input: reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2
Output: 15
Explanation: In this example, the first mouse eats the 2nd (0-indexed) and the 3rd types of cheese, and the second mouse eats the 0th and the 1st types of cheese.
The total points are 4 + 4 + 3 + 4 = 15.
It can be proven that 15 is the maximum total points that the mice can achieve.
Example 2:
Input: reward1 = [1,1], reward2 = [1,1], k = 2
Output: 2
Explanation: In this example, the first mouse eats the 0th (0-indexed) and 1st types of cheese, and the second mouse does not eat any cheese.
The total points are 1 + 1 = 2.
It can be proven that 2 is the maximum total points that the mice can achieve.
Constraints:
1 <= n == reward1.length == reward2.length <= 105
1 <= reward1[i], reward2[i] <= 1000
0 <= k <= n
'''
from typing import List
class Solution:
def miceAndCheese(self, reward1: List[int], reward2: List[int], k: int) -> int:
n = len(reward2)
arr = [(r2 - r1, i) for i, (r1, r2) in enumerate(zip(reward1, reward2))]
arr.sort()
ans = 0
for i in range(k):
ans += reward1[arr[i][1]]
for i in range(n-k):
ans += reward2[arr[n-i-1][1]]
return ans
if __name__ == '__main__':
print(Solution().miceAndCheese(reward1 = [1,1,3,4], reward2 = [4,4,1,1], k = 2))
print(Solution().miceAndCheese(reward1 = [1,1], reward2 = [1,1], k = 2))
print(Solution().miceAndCheese(reward1 = [2,1], reward2 = [1,2], k = 1))
print(Solution().miceAndCheese(reward1 = [4,1,5,3,3], reward2 = [3,4,4,5,2], k = 3)) |
'''
-Medium-
*Math*
Given two integers tomatoSlices and cheeseSlices. The ingredients of different burgers are as follows:
Jumbo Burger: 4 tomato slices and 1 cheese slice.
Small Burger: 2 Tomato slices and 1 cheese slice.
Return [total_jumbo, total_small] so that the number of remaining tomatoSlices equal to 0 and the number of remaining cheeseSlices equal to 0. If it is not possible to make the remaining tomatoSlices and cheeseSlices equal to 0 return [].
Example 1:
Input: tomatoSlices = 16, cheeseSlices = 7
Output: [1,6]
Explantion: To make one jumbo burger and 6 small burgers we need 4*1 + 2*6 = 16 tomato and 1 + 6 = 7 cheese.
There will be no remaining ingredients.
Example 2:
Input: tomatoSlices = 17, cheeseSlices = 4
Output: []
Explantion: There will be no way to use all ingredients to make small and jumbo burgers.
Example 3:
Input: tomatoSlices = 4, cheeseSlices = 17
Output: []
Explantion: Making 1 jumbo burger there will be 16 cheese remaining and making 2 small burgers there will be 15 cheese remaining.
Constraints:
0 <= tomatoSlices, cheeseSlices <= 10^7
'''
from typing import List
class Solution:
def numOfBurgers(self, tomatoSlices: int, cheeseSlices: int) -> List[int]:
t, c = tomatoSlices, cheeseSlices
return [t / 2 - c, c * 2 - t / 2] if t % 2 == 0 and c * 2 <= t <= c * 4 else []
if __name__ == "__main__":
print(Solution().numOfBurgers(tomatoSlices = 16, cheeseSlices = 7)) |
'''
-Hard-
*DP*
You have a keyboard layout as shown above in the X-Y plane, where each English uppercase letter is located at some coordinate.
For example, the letter 'A' is located at coordinate (0, 0), the letter 'B' is located at coordinate (0, 1), the letter 'P' is located at coordinate (2, 3) and the letter 'Z' is located at coordinate (4, 1).
Given the string word, return the minimum total distance to type such string using only two fingers.
The distance between coordinates (x1, y1) and (x2, y2) is |x1 - x2| + |y1 - y2|.
Note that the initial positions of your two fingers are considered free so do not count towards your total distance, also your two fingers do not have to start at the first letter or the first two letters.
Example 1:
Input: word = "CAKE"
Output: 3
Explanation: Using two fingers, one optimal way to type "CAKE" is:
Finger 1 on letter 'C' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'C' to letter 'A' = 2
Finger 2 on letter 'K' -> cost = 0
Finger 2 on letter 'E' -> cost = Distance from letter 'K' to letter 'E' = 1
Total distance = 3
Example 2:
Input: word = "HAPPY"
Output: 6
Explanation: Using two fingers, one optimal way to type "HAPPY" is:
Finger 1 on letter 'H' -> cost = 0
Finger 1 on letter 'A' -> cost = Distance from letter 'H' to letter 'A' = 2
Finger 2 on letter 'P' -> cost = 0
Finger 2 on letter 'P' -> cost = Distance from letter 'P' to letter 'P' = 0
Finger 1 on letter 'Y' -> cost = Distance from letter 'A' to letter 'Y' = 4
Total distance = 6
Constraints:
2 <= word.length <= 300
word consists of uppercase English letters.
'''
class Solution:
def minimumDistance(self, word: str) -> int:
def dist(s, t):
if s == 26: return 0
y = s // 6
x = s % 6
y2 = t // 6
x2 = t % 6
return abs(y2-y) + abs(x2-x)
n = len(word)
dp = [[[0]*27 for _ in range(27)] for _ in range(n+1)]
for i in range(n-1, -1, -1):
for j in range(27):
for k in range(27):
d1 = dist(j, ord(word[i])-ord('A'))
d2 = dist(k, ord(word[i])-ord('A'))
dp[i][j][k] = min(dp[i+1][ord(word[i])-ord('A')][k]+d1,
dp[i+1][j][ord(word[i])-ord('A')]+d2)
return dp[0][26][26]
def minimumDistance2(self, word: str) -> int:
def dist(s, t):
if s == 26: return 0
y = s // 6
x = s % 6
y2 = t // 6
x2 = t % 6
return abs(y2-y) + abs(x2-x)
n = len(word)
dp = [[[0]*27 for _ in range(27)] for _ in range(2)]
for i in range(n-1, -1, -1):
l = ord(word[i])-ord('A')
for j in range(27):
for k in range(27):
d1 = dist(j, l)
d2 = dist(k, l)
dp[i%2][j][k] = min(dp[(i+1)%2][l][k]+d1,
dp[(i+1)%2][j][l]+d2)
return dp[0][26][26]
def minimumDistance2(self, word: str) -> int:
def dist(s, t):
if s == 26: return 0
y, x = divmod(s, 6)
y2, x2 = divmod(t, 6)
return abs(y2-y) + abs(x2-x)
n = len(word)
dis = [[0]*27 for _ in range(27)]
for j in range(27):
for k in range(27):
dis[j][k] = dist(j, k)
dp = [[[0]*27 for _ in range(27)] for _ in range(2)]
for i in range(n-1, -1, -1):
l = ord(word[i])-ord('A')
for j in range(27):
for k in range(27):
d1 = dis[j][l]
d2 = dis[k][l]
dp[i%2][j][k] = min(dp[(i+1)%2][l][k]+d1,
dp[(i+1)%2][j][l]+d2)
return dp[0][26][26]
|
'''
Searches for a 2D pattern in a 2D text. Assumes that both the pattern and the
text are rectangles of characters.
O(Mr * Nr * Nc), where Mr is the pattern row length, Nr is the text row length
and Nc is the text column length
'''
MOD = 10**9+7
class RabinKarp2D(object):
def __init__(self, rad, pattern):
#Radix of the alphabet. Assumes ASCII characters
self.RADIX = rad
self.pattern = pattern
self.height = len(pattern)
self.width = len(pattern[0])
#self.factors = [0]*(self.height - 1 + self.width - 1 + 1)
self.factors = [0]*self.width
self.factors[0] = 1
for i in range(1, len(self.factors)):
self.factors[i] = (self.RADIX * self.factors[i - 1]) % MOD
self.patternHash = self.hash(pattern)
#print('pattern hash = ', self.patternHash)
#print('factors = ', self.factors)
def hash(self, data):
result = 0
for i in range(self.height):
rowHash = 0
for j in range(self.width):
rowHash = (self.RADIX * rowHash + ord(data[i][j])) % MOD
#result = (self.RADIX * result + rowHash) % MOD
result += rowHash
return result
def check(self, text, i, j):
x, y = i, j
for a in range(self.height):
for b in range(self.width):
if text[x][y] != self.pattern[a][b]:
return False
y += 1
x += 1
y = j
return True
def search(self, text):
rowStartHash = self.hash(text)
#print(rowStartHash)
hash = rowStartHash
for i in range(len(text)-self.height+1):
if i > 0:
# Remove previous row from rolling hash
for j in range(self.width):
#hash = (hash + MOD - self.factors[self.width - 1 -j]
# * ord(text[i-1][j])%MOD) % MOD
hash = (hash - self.factors[self.width - 1 -j]
* ord(text[i-1][j])%MOD) % MOD
# Add next row in rolling hash
for j in range(self.width):
hash = (hash + self.factors[self.width - 1 -j]
* ord(text[i+self.height-1][j])) % MOD
textHash = hash
if textHash == self.patternHash and self.check(text, i, 0):
return [i, 0]
for j in range(self.width, len(text[0])):
# Remove previous column from rolling hash
for k in range(self.height):
textHash = (textHash + MOD - self.factors[self.width-1]
* ord(text[i+k][j-self.width])%MOD) % MOD
# Add next column in rolling hash
for k in range(self.height):
if k == 0:
textHash = (textHash*self.RADIX + ord(text[i+k][j])) % MOD
else:
textHash = (textHash + ord(text[i+k][j])) % MOD
'''
if i == 1 and j - self.width + 1 == 2:
print(textHash)
print(self.check(text, i, j - self.width + 1))
if textHash == self.patternHash:
print(i, j)
'''
#print(i, j, textHash, self.patternHash)
if textHash == self.patternHash and self.check(text, i, j - self.width + 1):
return [i, j - self.width + 1]
'''
if hash == self.patternHash and self.check(text, i, 0):
return [i, 0]
for j in range(len(text[0]) - self.width):
hash = self.shiftRight(hash, text, i, j)
if hash == self.patternHash and self.check(text, i, j + 1):
return [i, j + 1]
rowStartHash = self.shiftDown(rowStartHash, text, i)
hash = rowStartHash
'''
return None
class RabinKarp2DV2(object):
def __init__(self, rad, pattern):
#Radix of the alphabet. Assumes ASCII characters
self.RADIX = rad
self.pattern = pattern
self.height = len(pattern)
self.width = len(pattern[0])
self.factors = [0]*((self.height - 1)+(self.width - 1) + 1)
self.factors[0] = 1
for i in range(1, len(self.factors)):
self.factors[i] = (self.RADIX * self.factors[i - 1]) % MOD
self.patternHash = self.hash(pattern)
#print('pattern hash = ', self.patternHash)
#print('factors = ', self.factors)
def hash(self, data):
result = 0
for i in range(self.height):
rowHash = 0
for j in range(self.width):
rowHash = (self.RADIX * rowHash + ord(data[i][j])) % MOD
result = (self.RADIX * result + rowHash) % MOD
return result
def check(self, text, i, j):
x, y = i, j
for a in range(self.height):
for b in range(self.width):
if text[x][y] != self.pattern[a][b]:
return False
y += 1
x += 1
y = j
return True
def search(self, text):
rowStartHash = self.hash(text)
#print(rowStartHash)
hash = rowStartHash
for i in range(len(text)-self.height+1):
if hash == self.patternHash and self.check(text, i, 0):
return [i, 0]
for j in range(len(text[0]) - self.width):
hash = self.shiftRight(hash, text, i, j)
if hash == self.patternHash and self.check(text, i, j + 1):
return [i, j + 1]
rowStartHash = self.shiftDown(rowStartHash, text, i)
hash = rowStartHash
return None
''' Given the hash of the block at i, j, returns the hash of the block at i + 1, j.'''
def shiftDown(self, hash, text, i):
# TODO You have to write this
# Remove previous row from rolling hash
for j in range(self.width):
#hash = (hash + MOD - self.factors[self.width - 1 -j]
# * ord(text[i-1][j])%MOD) % MOD
hash = (hash - self.factors[self.width + self.height - 1 - j]
* ord(text[i][j])%MOD) % MOD
for j in range(self.width):
hash = (hash + self.factors[self.width - j]
* ord(text[i+self.height][j])%MOD) % MOD
return hash
''' Given the hash of the block at i, j, returns the hash of the block at i, j + 1. '''
def shiftRight(self, hash, text, i, j) :
# TODO You have to write this
for k in range(self.height):
hash = (hash + MOD - self.factors[self.width+self.height-1-k]
* ord(text[i+k][j])%MOD) % MOD
# Add next column in rolling hash
for k in range(self.height):
if k == 0:
hash = (hash*self.RADIX + ord(text[i+k][j+self.width])) % MOD
else:
hash = (hash + ord(text[i+k][j+self.width])) % MOD
return -1
class RabinKarp2DV3(object):
def __init__(self, rad, pattern):
#Radix of the alphabet. Assumes ASCII characters
self.RADIX = rad
self.pattern = pattern
self.height = len(pattern)
self.width = len(pattern[0])
self.factors_col = [0]*(self.height)
self.factors_row = [0]*(self.width)
self.factors_col[0] = 1
for i in range(1, len(self.factors_col)):
self.factors_col[i] = (self.RADIX * self.factors_col[i - 1]) % MOD
self.factors_row[0] = 1
for i in range(1, len(self.factors_row)):
self.factors_row[i] = (self.RADIX * self.factors_row[i - 1]) % MOD
hash1d_p = [0]*self.width
self.hash2D(self.pattern, hash1d_p, self.width)
self.patternHash = self.SingleHash(hash1d_p)
#print('pattern hash = ', self.patternHash)
#print('factors = ', self.factors)
def hash2D(self, data, hash1d, hei):
for i in range(hei):
hash1d[i] = 0
for j in range(self.height):
hash1d[i] = (self.RADIX * hash1d[i] + ord(data[j][i])) % MOD
def rehash2D(self, data, hash1d, hei, j):
for i in range(hei):
hash1d[i] = self.RADIX*((hash1d[i] + MOD - self.factors_col[self.height-1]
* ord(data[j][i])%MOD) % MOD) % MOD
hash1d[i] = (hash1d[i] + ord(data[j+self.height][i])) % MOD
def SingleHash(self, hash1d):
res = 0
for i in range(self.width):
res = (self.RADIX * res + hash1d[i]) % MOD
return res
def SingleReHash(self, hash, hash1d, pos):
hash = self.RADIX*((hash + MOD - self.factors_row[self.width-1]*hash1d[pos]%MOD) % MOD) % MOD
hash = (hash + hash1d[pos+self.width]) % MOD
return hash
def check(self, text, i, j):
x, y = i, j
for a in range(self.height):
for b in range(self.width):
if text[x][y] != self.pattern[a][b]:
return False
y += 1
x += 1
y = j
return True
def search(self, text):
hash1d = [0]*len(text[0])
for i in range(len(text)-self.height+1):
if i == 0:
self.hash2D(text, hash1d, len(text[0]))
else:
self.rehash2D(text, hash1d, len(text[0]), i-1)
textHash = 0
for j in range(len(text[0]) - self.width+1):
if j == 0:
textHash = self.SingleHash(hash1d)
else:
textHash = self.SingleReHash(textHash, hash1d, j-1)
#print(i, j, textHash, patternHash)
if textHash == self.patternHash and self.check(text, i, j):
return [i, j]
return None
class BruteForce(object):
def __init__(self, pattern):
self.pattern = pattern
self.height = len(pattern)
self.width = len(pattern[0])
def check(self, text, i, j):
x, y = i, j
for a in range(self.height):
for b in range(self.width):
if text[x][y] != self.pattern[a][b]:
return False
y += 1
x += 1
y = j
return True
def search(self, text):
for i in range(len(text)-self.height+1):
for j in range(len(text[0]) - self.width+1):
if self.check(text, i, j):
return [i, j]
return None
if __name__ == "__main__":
pattern1 = ["RE",
"NE"]
pattern2 = ["AB",
"RE"]
text1 =["ABCD",
"RERE",
"DRNE",
"XPQZ"]
matcher = RabinKarp2D(256, pattern1)
print(matcher.search(text1))
matcher = RabinKarp2DV3(256, pattern1)
print(matcher.search(text1))
pattern2 = ["ERE",
"RNE"]
matcher = RabinKarp2DV3(256, pattern2)
print(matcher.search(text1))
matcher = BruteForce(pattern2)
print(matcher.search(text1))
import random
import string
import time
chars = string.ascii_uppercase
im, jm = 1000, 2000
text = []
for i in range(im):
s = ''
for j in range(jm):
s += random.choice(chars)
text.append(s)
for t in text:
print(t)
pattern = []
for i in range(40):
pattern.append(text[357+i][478:478+60])
for p in pattern:
print(p)
start_time = time.time()
matcher = RabinKarp2DV3(256, pattern)
print(matcher.search(text))
print("--- %s seconds ---" % (time.time() - start_time))
start_time = time.time()
matcher = BruteForce(pattern)
print(matcher.search(text))
print("--- %s seconds ---" % (time.time() - start_time))
#matcher = RabinKarp2D(256, pattern)
#print(matcher.search(text))
|
'''
-Medium-
*Prefix Sum*
You are given a 2D integer array grid of size m x n, where each cell contains a positive integer.
A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell.
The product of a path is defined as the product of all the values in the path.
Return the maximum number of trailing zeros in the product of a cornered path found in grid.
Note:
Horizontal movement means moving in either the left or right direction.
Vertical movement means moving in either the up or down direction.
Example 1:
Input: grid = [[23,17,15,3,20],[8,1,20,27,11],[9,4,6,2,21],[40,9,1,10,6],[22,7,4,5,3]]
Output: 3
Explanation: The grid on the left shows a valid cornered path.
It has a product of 15 * 20 * 6 * 1 * 10 = 18000 which has 3 trailing zeros.
It can be shown that this is the maximum trailing zeros in the product of a cornered path.
The grid in the middle is not a cornered path as it has more than one turn.
The grid on the right is not a cornered path as it requires a return to a previously visited cell.
Example 2:
Input: grid = [[4,3,2],[7,6,1],[8,8,8]]
Output: 0
Explanation: The grid is shown in the figure above.
There are no cornered paths in the grid that result in a product with a trailing zero.
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 105
1 <= m * n <= 105
1 <= grid[i][j] <= 1000
'''
from typing import List
class Solution:
def maxTrailingZeros(self, A: List[List[int]]) -> int:
m, n = len(A), len(A[0])
left = [[[0, 0] for _ in range(n)] for _ in range(m)]
top = [[[0, 0] for _ in range(n)] for _ in range(m)]
def helper(num):
a, b = 0, 0
while num % 2 == 0:
num //= 2
a += 1
while num % 5 == 0:
num //= 5
b += 1
return [a, b]
for i in range(m):
for j in range(n):
if j == 0:
left[i][j] = helper(A[i][j])
else:
a, b = helper(A[i][j])
left[i][j][0] = left[i][j - 1][0] + a
left[i][j][1] = left[i][j - 1][1] + b
for j in range(n):
for i in range(m):
if i == 0:
top[i][j] = helper(A[i][j])
else:
a, b, = helper(A[i][j])
top[i][j][0] = top[i - 1][j][0] + a
top[i][j][1] = top[i - 1][j][1] + b
ans = 0
for i in range(m):
for j in range(n):
a, b = top[m - 1][j]
d, e = left[i][n - 1]
x, y = helper(A[i][j])
a1, b1 = top[i][j]
a2, b2 = left[i][j]
tmp = [a1 + a2 - x, b1 + b2 - y]
ans = max(ans, min(tmp))
tmp = [d - a2 + a1, e - b2 + b1]
ans = max(ans, min(tmp))
tmp = [a - a1 + a2, b - b1 + b2]
ans = max(ans, min(tmp))
tmp = [a + d - a1 - a2 + x, b + e - b1 - b2 + y]
ans = max(ans, min(tmp))
return ans |
'''
Given an array nums of integers, we need to find the maximum possible sum of
elements of the array such that it is divisible by three.
Example 1:
Input: nums = [3,6,5,1,8]
Output: 18
Explanation: Pick numbers 3, 6, 1 and 8 their sum is 18 (maximum sum divisible by 3).
Example 2:
Input: nums = [4]
Output: 0
Explanation: Since 4 is not divisible by 3, do not pick any number.
Example 3:
Input: nums = [1,2,3,4,4]
Output: 12
Explanation: Pick numbers 1, 3, 4 and 4 their sum is 12 (maximum sum divisible by 3).
Constraints:
1 <= nums.length <= 4 * 10^4
1 <= nums[i] <= 10^4
'''
class Solution(object):
def maxSumDivThree(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
state = [0, float('-inf'), float('-inf')]
for num in nums:
if num % 3 == 0:
state = [state[0] + num, state[1] + num, state[2] + num]
if num % 3 == 1:
a = max(state[2] + num, state[0])
b = max(state[0] + num, state[1])
c = max(state[1] + num, state[2])
state = [a, b, c]
if num % 3 == 2:
a = max(state[1] + num, state[0])
b = max(state[2] + num, state[1])
c = max(state[0] + num, state[2])
state = [a, b, c]
return state[0]
def maxSumDivThreeTotalSumSubstraction(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ones = [float('inf')]*2
twos = [float('inf')]*2
total = 0
for i in nums:
total += i
if i % 3 == 1:
if i < ones[0]:
ones[1] = ones[0]
ones[0] = i
elif i < ones[1]: ones[1] = i
if i % 3 == 2:
if i < twos[0]:
twos[1] = twos[0]
twos[0] = i
elif i < twos[1]: twos[1] = i
#print(sorted(nums))
#print(total, ones, twos)
if total % 3 == 0: return total
elif total % 3 == 1:
if ones[0] > sum(twos): return total - sum(twos)
return total - ones[0]
elif total % 3 == 2:
if twos[0] > sum(ones): return total - sum(ones)
return total - twos[0]
return 0
if __name__ == '__main__':
nums = [366,809,6,792,822,181,210,588,344,618,341,410,121,864,191,749,637,169,123,472,358,908,235,914,322,946,738,754,908,272,267,326,587,267,803,281,586,707,94,627,724,469,568,57,103,984,787,552,14,545,866,494,263,157,479,823,835,100,495,773,729,921,348,871,91,386,183,979,716,806,639,290,612,322,289,910,484,300,195,546,499,213,8,623,490,473,603,721,793,418,551,331,598,670,960,483,154,317,834,352]
print(Solution().maxSumDivThreeTotalSumSubstraction(nums))
|
from collections import deque
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
#matplotlib.use('TkAgg')
NIL = 0
INF = float('inf')
class BipGraph(object):
# To add edge from u to v and v to u
def addEdge(self, u, v):
#Add u to v’s list.
self.adj[u].append(v)
def __init__(self, m, n):
# m and n are number of vertices on left
# and right sides of Bipartite Graph
self.m, self.n = m, n
# adj[u] stores adjacents of left side
# vertex 'u'. The value of u ranges
# from 1 to m. 0 is used for dummy vertex
self.adj = [[] for _ in range(m+1)]
# These are basically pointers to arrays
# needed for hopcroftKarp()
# pairU[u] stores pair of u in matching where u
# is a vertex on left side of Bipartite Graph.
# If u doesn't have any pair, then pairU[u] is NIL
self.pairU = [0]*(m+1)
# pairV[v] stores pair of v in matching. If v
# doesn't have any pair, then pairU[v] is NIL
self.pairV = [0]*(n+1)
# dist[u] stores distance of left side vertices
# dist[u] is one more than dist[u'] if u is next
# to u'in augmenting path
self.dist = [0]*(m+1)
# Returns size of maximum matching
def hopcroftKarp(self):
result = 0
# Keep updating the result while
# there is an augmenting path.
k = 0
while self.bfs():
print('before dfs, dist = ', self.dist)
print('before dfs, pairU = ', self.pairU)
# Find a free vertex
for u in range(1, self.m+1):
# If current vertex is free and there is
# an augmenting path from current vertex
if self.pairU[u] == NIL and self.dfs(u):
result += 1
k += 1
print('After iteration ', k)
print('PairU : ',self.pairU)
print('PairV : ', self.pairV)
print('after dfs, dist = ',self.dist)
print('matchings: ', result)
return result
# Returns true if there is an augmenting
# path, else returns false
def bfs(self):
# An integer queue
Q = deque()
# First layer of vertices (set distance as 0)
for u in range(1, self.m+1):
# If this is a free vertex,
# add it to queue
if self.pairU[u] == NIL:
# u is not matched
self.dist[u] = 0
Q.append(u)
# Else set distance as infinite
# so that this vertex is
# considered next time
else: # if this vertex has been matched, set dist to INF
self.dist[u] = INF
# Initialize distance to
# NIL as infinite
self.dist[NIL] = INF
print("size of Q: ", len(Q))
# Q is going to contain vertices
# of left side only.
while Q:
# Dequeue a vertex
u = Q.popleft()
# If this node is not NIL and
# can provide a shorter path to NIL
if self.dist[u] < self.dist[NIL]:
# Get all adjacent vertices of
# the dequeued vertex u
for v in self.adj[u]:
# If pair of v is not considered
# so far (v, pairV[V]) is not yet
# explored edge.
# we require in our BFS that when going from V to U,
# we always select a matched edge.
if self.dist[self.pairV[v]] == INF:
# Consider the pair and add
# it to queue
#if self.pairV[v] == NIL:
# print('u,v', u, v, self.dist[u])
self.dist[self.pairV[v]] = self.dist[u] + 1
Q.append(self.pairV[v])
# If we could come back to NIL using
# alternating path of distinct vertices
# then there is an augmenting path
# If no path has been found, then there are no augmenting paths left
# and the matching is maximal. bfs returns false to terminate the while loop
return self.dist[NIL] != INF
# Returns true if there is an augmenting
# path beginning with free vertex u
def dfs(self, u):
if u != NIL:
for v in self.adj[u]:
# Follow the distances set by BFS
# Note that the code ensures that all augmenting paths
# that we consider are vertex disjoint. Indeed, after
# doing the symmetric difference for a path, none of its
# vertices could be considered again in the DFS, just because
# the Dist[Pair_V[v]] will not be equal to Dist[u] + 1 (it would be exactly Dist[u]).
if self.dist[self.pairV[v]] == self.dist[u] + 1:
# If dfs for pair of v also returns
# true
print(u, v, self.pairV[v], self.dist[self.pairV[v]], self.dist[u] )
if self.dfs(self.pairV[v]):
self.pairV[v] = u
self.pairU[u] = v
return True
# If there is no augmenting path
# beginning with u.
# When we were not able to find any shortest augmenting path from a vertex u,
# then the DFS marks vertex u by setting Dist[u] to infinity, so that these
# vertices are not visited again.
self.dist[u] = INF
return False
return True
#Driver code
if __name__ == "__main__":
# the graph is from the link below
# https://en.wikipedia.org/wiki/Hopcroft%E2%80%93Karp_algorithm#/media/File:HopcroftKarpExample.png
g = BipGraph(5, 5);
edges = [(1,1), (1,2), (2,1), (3,3), (2,5), (4,1), (5,2), (5,4)]
'''
g.addEdge(1, 1);
g.addEdge(1, 2);
g.addEdge(2, 1);
g.addEdge(2, 5);
g.addEdge(3, 3);
#g.addEdge(3, 4);
g.addEdge(4, 1);
#g.addEdge(4, 5);
g.addEdge(5, 2);
g.addEdge(5, 4);
'''
for e in edges:
g.addEdge(*e)
print("Size of maximum matching is " +
str(g.hopcroftKarp()))
B = nx.Graph()
B.add_nodes_from(list(range(1,6)), bipartite=0, label='left')
B.add_nodes_from(list('ABCDE'), bipartite=1, label='right')
edges = [(1,'A'), (1,'B'), (2,'A'), (3,'C'), (2, 'E'), (4,'A'), (5,'B'), (5,'D')]
#B.add_edges_from(edges, label='connect')
for e in edges:
if ord(e[1])-ord('A')+1 == g.pairU[e[0]]:
B.add_edge(e[0],e[1],color='r')
else:
B.add_edge(e[0],e[1],color='g')
# Now instead of spring_layout, use bipartite_layout
# First specify the nodes you want on left or top
left_or_top = list(range(1,6))
# Then create a bipartite layout
pos = nx.bipartite_layout(B, left_or_top)
colors = nx.get_edge_attributes(B,'color').values()
# Pass that layout to nx.draw
nx.draw(B,pos,node_color='#A0CBE2',edge_color=colors,width=2,
edge_cmap=plt.cm.Blues,with_labels=True)
plt.show()
|
'''
-Easy-
*Greedy*
A robot on an infinite grid starts at point (0, 0) and faces north. The
robot can receive one of three possible types of commands:
-2: turn left 90 degrees,
-1: turn right 90 degrees, or
1 <= x <= 9: move forward x units
Some of the grid squares are obstacles. The ith obstacle is at grid
point obstacles[i] = (xi, yi).
If the robot would try to move onto them, the robot stays on the previous
grid square instead (but still continues following the rest of the route.)
Return the square of the maximum Euclidean distance that the robot will
be from the origin.
Example 1:
Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)
Example 2:
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and
going to (1, 8)
Constraints:
1 <= commands.length <= 10^4
commands[i] is in the list [-2,-1,1,2,3,4,5,6,7,8,9].
0 <= obstacles.length <= 10^4
-3 * 10^4 <= xi, yi <= 3 * 10^4
The answer is guaranteed to be less than 2^31.
'''
class Solution(object):
def robotSim(self, commands, obstacles):
"""
:type commands: List[int]
:type obstacles: List[List[int]]
:rtype: int
"""
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
x = y = di = 0
obstacleSet = set(map(tuple, obstacles))
ans = 0
for c in commands:
if c == -2:
di = (di-1)%4
elif c == -1:
di = (di+1)%4
else:
for _ in range(c):
xi = x + dx[di]
yi = y + dy[di]
if (xi,yi) not in obstacleSet:
x, y = xi, yi
ans = max(ans, x*x+y*y)
else:
break
return ans
if __name__ == "__main__":
print(Solution().robotSim([4,-1,4,-2,4], [[2,4]])) |
'''
Given a node from a Circular Linked List which is sorted in ascending
order, write a function to insert a value insertVal into the list such
that it remains a sorted circular list. The given node can be a reference
to any single node in the list, and may not be necessarily the smallest
value in the circular list.
If there are multiple suitable places for insertion, you may choose any
place to insert the new value. After the insertion, the circular list
should remain sorted.
If the list is empty (i.e., given node is null), you should create a new
single circular list and return the reference to that single node.
Otherwise, you should return the original given node.
'''
class Node(object):
def __init__(self, value, next = None):
self.val = value
self.next = next
class Solution(object):
def insert(self, head, insertVal):
'''
:type head: Node
:type insertVal: int
:rtype: Node
'''
if not head:
head = Node(insertVal)
head.next = head
return head
pre, cur = head, head.next
while cur != head:
if pre.val <= insertVal <= cur.val:
break
if pre.val > cur.val and (insertVal >= pre.val or
insertVal <= cur.val):
break
pre = cur
cur = cur.next
pre.next = Node(insertVal, cur)
return head
if __name__=="__main__":
h = head = Node(3)
head.next = Node(4)
head = head.next
head.next = Node(1)
head = head.next
head.next = h
pre, cur = h, h.next
while cur != h:
print(pre.val)
pre = cur
cur = cur.next
print(pre.val)
print('======================')
head = Solution().insert(h, 2)
pre, cur = head, head.next
while cur != head:
print(pre.val)
pre = cur
cur = pre.next
print(pre.val)
print('======================')
head = Solution().insert(head, 5)
pre, cur = head, head.next
while cur != head:
print(pre.val)
pre = cur
cur = pre.next
print(pre.val)
|
'''
-Easy-
You are given an array of integers stones where stones[i] is the
weight of the ith stone.
We are playing a game with the stones. On each turn, we choose the
heaviest two stones and smash them together. Suppose the heaviest
two stones have weights x and y with x <= y. The result of this
smash is:
If x == y, both stones are destroyed, and
If x != y, the stone of weight x is destroyed, and the stone of
weight y has new weight y - x.
At the end of the game, there is at most one stone left.
Return the smallest possible weight of the left stone. If there
are no stones left, return 0.
Example 1:
Input: stones = [2,7,4,1,8,1]
Output: 1
Explanation:
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
Example 2:
Input: stones = [1]
Output: 1
Constraints:
1 <= stones.length <= 30
1 <= stones[i] <= 1000
'''
from typing import List
import heapq
class Solution:
def lastStoneWeight(self, stones: List[int]) -> int:
pq = []
for x in stones:
heapq.heappush(pq, -x)
while pq:
y = heapq.heappop(pq)
if pq:
x = heapq.heappop(pq)
if x > y:
heapq.heappush(pq, y-x)
else:
return -y
return 0
if __name__ == "__main__":
print(Solution().lastStoneWeight([2,7,4,1,8,1]))
print(Solution().lastStoneWeight([1])) |
"""
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one
LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
"""
import bisect
__author__ = 'Daniel'
class Solution(object):
def bisect_diy(self, L, a):
#l = -1
l = 0
r = len(L)
# print l, r
#while r-l > 1:
while l<r:
m = l+(r-l)//2
if L[m] >= a:
r = m
else:
#l = m
l = m+1
# print l, r, m
return r
def bisect_diynew(self, L, a):
l = 0
r = len(L)-1
while l<=r:
m = l+(r-l)//2
if L[m] > a:
r = m-1
elif L[m] < a:
l = m+1
else:
return m
# print(l, r, m)
return l
def binary_search(self, L, a):
l = 0
r = len(L)-1
while l<=r:
m = l+(r-l)//2
if L[m] > a:
r = m-1
elif L[m] < a:
l = m+1
else:
return m
# print(l, r, m)
return -1
def binarysearch(self, L, a):
l = 0 # left close
r = len(L) # right open
while l<r:
m = l+(r-l)//2
if L[m] == a:
return m
elif L[m] > a:
r = m
elif L[m] < a:
l = m+1
# print(l, r, m)
return -1
def lower_bound(self, L, a):
'''
find first number not smaller than a
variation: return r-1 if we are looking for
the last number less than a
'''
l = 0
r = len(L)
while l < r:
m = l+(r-l)//2
if L[m] < a:
l = m+1
else:
r = m
return r
def upper_bound(self, L, a):
'''
find first number larger than a
variation: return r-1 if we are looking for
the last number not larger than a
'''
l = 0
r = len(L)
while l < r:
m = l+(r-l)//2
if L[m] <= a:
l = m+1
else:
r = m
return r
import sys
if __name__ == "__main__":
L = [2, 4, 6, 9, 11, 15]
#a = sys.argv[1]
A = [0, 3, 5, 8, 9, 12, 15, 20]
#print Solution().binary_search_corr(L, a)
print(Solution().binary_search(L, 9))
print(Solution().binarysearch(L, 9))
#print bisect.bisect_left(L, a)
#print(bisect.bisect_left(L, 9))
#print(bisect.bisect(L, 9))
#for a in A:
#assert Solution().bisect_diynew(L, a) == bisect.bisect_left(L, a)
#assert Solution().binary_search_pos(L, a) == bisect.bisect_left(L, a)
# assert Solution().binary_search_pos(L, a) == bisect.bisect(L, a)
#for a in A:
# print(Solution().binary_search(L, a))
# print(Solution().binary_search_pos(L, 10))
|
'''
-Medium-
*DP*
You are given a m x n matrix grid. Initially, you are located at the top-left corner (0, 0), and in each step, you can only move right or down in the matrix.
Among all possible paths starting from the top-left corner (0, 0) and ending in the bottom-right corner (m - 1, n - 1), find the path with the maximum non-negative product. The product of a path is the product of all integers in the grid cells visited along the path.
Return the maximum non-negative product modulo 109 + 7. If the maximum product is negative, return -1.
Notice that the modulo is performed after getting the maximum product.
Example 1:
Input: grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
Output: -1
Explanation: It is not possible to get non-negative product in the path from (0, 0) to (2, 2), so return -1.
Example 2:
Input: grid = [[1,-2,1],[1,-2,1],[3,-4,1]]
Output: 8
Explanation: Maximum non-negative product is shown (1 * 1 * -2 * -4 * 1 = 8).
Example 3:
Input: grid = [[1,3],[0,-4]]
Output: 0
Explanation: Maximum non-negative product is shown (1 * 0 * -4 = 0).
Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 15
-4 <= grid[i][j] <= 4
'''
from typing import List
class Solution:
def maxProductPath(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
pos = [[0]*(n+1) for _ in range(m+1)]
neg = [[0]*(n+1) for _ in range(m+1)]
for j in range(n+1):
pos[0][j] = -float('inf')
neg[0][j] = float('inf')
for i in range(m+1):
pos[i][0] = -float('inf')
neg[i][0] = float('inf')
pos[1][0] = 1
pos[0][1] = 1
neg[1][0] = 1
neg[0][1] = 1
for i in range(1, m+1):
for j in range(1, n+1):
val = grid[i-1][j-1]
if val > 0:
pos[i][j] = max(pos[i-1][j], pos[i][j-1])*val
neg[i][j] = min(neg[i-1][j], neg[i][j-1])*val
elif val < 0:
pos[i][j] = min(neg[i-1][j], neg[i][j-1])*val
neg[i][j] = max(pos[i-1][j], pos[i][j-1])*val
else:
pos[i][j] = 0
neg[i][j] = 0
return -1 if pos[m][n] < 0 else pos[m][n]%(10**9+7)
if __name__ == "__main__":
grid = [[-1,-2,-3],[-2,-3,-3],[-3,-3,-2]]
print(Solution().maxProductPath(grid))
grid = [[1,-2,1],[1,-2,1],[3,-4,1]]
print(Solution().maxProductPath(grid))
grid = [[1,3],[0,-4]]
print(Solution().maxProductPath(grid))
|
'''
-Medium-
*Dijkstra's Algorithm*
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads
between some intersections. The inputs are generated such that you can reach any intersection from any
other intersection and that there is at most one road between any two intersections.
You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there
is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many
ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time.
Return the number of ways you can arrive at your destination in the shortest amount of time. Since the
answer may be large, return it modulo 109 + 7.
Example 1:
Input: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]
Output: 4
Explanation: The shortest amount of time it takes to go from intersection 0 to intersection 6 is 7 minutes.
The four ways to get there in 7 minutes are:
- 0 ➝ 6
- 0 ➝ 4 ➝ 6
- 0 ➝ 1 ➝ 2 ➝ 5 ➝ 6
- 0 ➝ 1 ➝ 3 ➝ 5 ➝ 6
Example 2:
Input: n = 2, roads = [[1,0,10]]
Output: 1
Explanation: There is only one way to go from intersection 0 to intersection 1, and it takes 10 minutes.
Constraints:
1 <= n <= 200
n - 1 <= roads.length <= n * (n - 1) / 2
roads[i].length == 3
0 <= ui, vi <= n - 1
1 <= timei <= 109
ui != vi
There is at most one road connecting any two intersections.
You can reach any intersection from any other intersection.
'''
from collections import defaultdict
import math
import heapq
from functools import lru_cache
class Solution(object):
def countPaths(self, n, roads):
"""
:type n: int
:type roads: List[List[int]]
:rtype: int
"""
graph = defaultdict(list)
for u, v, time in roads:
graph[u].append([v, time])
graph[v].append([u, time])
def dijkstra(src):
dist = [math.inf] * n
ways = [0] * n
minHeap = [(0, src)] # dist, src
dist[src] = 0
ways[src] = 1
while minHeap:
d, u = heapq.heappop(minHeap)
if u == n-1:
print('at n-1:', d)
if dist[u] < d: continue # Skip if `d` is not updated to latest version!
for v, time in graph[u]: # we found better candidate, so
# we update distance
if dist[v] > d + time:
dist[v] = d + time
ways[v] = ways[u]
heapq.heappush(minHeap, (dist[v], v))
elif dist[v] == d + time: # means we found one more way to
# reach node with minimal cost.
ways[v] = (ways[v] + ways[u]) % 1_000_000_007
print('time to dest:', dist[n-1])
return ways[n - 1]
return dijkstra(0)
def countPathsArray(self, n, roads):
def create_adjlist():
adjlist = defaultdict(list)
for v1, v2, t in roads:
adjlist[v1].append((v2, t))
adjlist[v2].append((v1, t))
return adjlist
adjlist = create_adjlist()
mincost = [0] + [math.inf] * (n-1)
pred = defaultdict(list)
decided = set()
for _ in range(n):
minidx = min((idx for idx in range(n) if idx not in decided), key=mincost.__getitem__)
decided.add(minidx)
for v, t in adjlist[minidx]:
if mincost[minidx] + t < mincost[v]:
pred[v][:] = [minidx]
mincost[v] = mincost[minidx] + t
elif mincost[minidx] + t == mincost[v]:
pred[v].append(minidx)
# Compute number of ways
@lru_cache(None)
def count(dest):
return sum(count(v) for v in pred[dest]) if pred[dest] else 1
return count(n-1) % (10**9+7)
if __name__ == "__main__":
print(Solution().countPaths(n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]))
print(Solution().countPathsArray(n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]]))
|
'''
-Medium-
*Sorting*
In a warehouse, there is a row of barcodes, where the ith barcode is barcodes[i].
Rearrange the barcodes so that no two adjacent barcodes are equal. You may return
any answer, and it is guaranteed an answer exists.
Example 1:
Input: barcodes = [1,1,1,2,2,2]
Output: [2,1,2,1,2,1]
Example 2:
Input: barcodes = [1,1,1,1,2,2,3,3]
Output: [1,3,1,3,1,2,1,2]
Constraints:
1 <= barcodes.length <= 10000
1 <= barcodes[i] <= 10000
'''
from typing import List
from collections import Counter
class Solution:
def rearrangeBarcodes(self, barcodes: List[int]) -> List[int]:
A = barcodes
counter = Counter(A)
print(counter)
A.sort(reverse=True, key=lambda x: (counter[x],x))
print(A)
res = [0]*len(A)
j = 0
for i in range(0, len(A), 2):
res[i] = A[j]
j += 1
for i in range(1, len(A), 2):
res[i] = A[j]
j += 1
return res
if __name__ == "__main__":
print(Solution().rearrangeBarcodes([1,1,1,2,2,2]))
print(Solution().rearrangeBarcodes([1,1,1,1,2,2,3,3]))
print(Solution().rearrangeBarcodes([2,2,1,3]))
print(Solution().rearrangeBarcodes([1,1,2]))
print(Solution().rearrangeBarcodes([7,7,7,8,5,7,5,5,5,8])) |
'''
-Hard-
You have two fruit baskets containing n fruits each. You are given two 0-indexed integer arrays basket1 and basket2 representing the cost of fruit in each basket. You want to make both baskets equal. To do so, you can use the following operation as many times as you want:
Chose two indices i and j, and swap the ith fruit of basket1 with the jth fruit of basket2.
The cost of the swap is min(basket1[i],basket2[j]).
Two baskets are considered equal if sorting them according to the fruit cost makes them exactly the same baskets.
Return the minimum cost to make both the baskets equal or -1 if impossible.
Example 1:
Input: basket1 = [4,2,2,2], basket2 = [1,4,1,2]
Output: 1
Explanation: Swap index 1 of basket1 with index 0 of basket2, which has cost 1. Now basket1 = [4,1,2,2] and basket2 = [2,4,1,2]. Rearranging both the arrays makes them equal.
Example 2:
Input: basket1 = [2,3,4,1], basket2 = [3,2,5,1]
Output: -1
Explanation: It can be shown that it is impossible to make both the baskets equal.
Constraints:
basket1.length == bakste2.length
1 <= basket1.length <= 105
1 <= basket1[i],basket2[i] <= 109
'''
from typing import List
from collections import Counter
class Solution:
def minCost(self, basket1: List[int], basket2: List[int]) -> int:
# Wrong
cnt1, cnt2 = Counter(basket1), Counter(basket2)
cnt = cnt1 + cnt2
for c in cnt:
if cnt[c] % 2: return -1
arr1 = sorted(cnt1)
arr2 = sorted(cnt2)
# arr = sorted(cnt.items())
# i1, j1 = 0, len(arr1)-1
# i2, j2 = 0, len(arr2)-1
ans = 0
i, j = 0, len(arr2)-1
while i < len(arr1) and j >= 0:
while i < len(arr1) and cnt1[arr1[i]] <= cnt2[arr1[i]]:
i += 1
if i == len(arr1): break
mov = (cnt1[arr1[i]] - cnt2[arr1[i]]) // 2
while j >= 0 and cnt1[arr2[j]] >= cnt2[arr2[j]]:
j -= 1
if j == -1: break
mov1 = (cnt2[arr2[j]] - cnt1[arr2[j]]) // 2
x = min(arr1[i], arr2[j])
print(i,j,mov, mov1, arr1[i], arr2[j],x)
print('A', cnt1, cnt2)
if mov <= mov1:
ans += mov * x
cnt2[arr2[j]] -= mov
cnt1[arr2[j]] += mov
cnt1[arr1[i]] -= mov
cnt2[arr1[i]] += mov
i += 1
if mov == mov1:
j -= 1
else:
ans += mov1 * x
cnt1[arr1[i]] -= mov1
cnt2[arr1[i]] += mov1
cnt2[arr2[j]] -= mov1
cnt1[arr2[j]] += mov1
j -= 1
print('B', ans, cnt1, cnt2)
print(i,j,ans)
print(cnt1, cnt2)
return ans
def minCost2(self, basket1: List[int], basket2: List[int]) -> int:
# Wrong
cnt1, cnt2 = Counter(basket1), Counter(basket2)
cnt = cnt1 + cnt2
for c in cnt:
if cnt[c] % 2: return -1
mi = min(min(basket1), min(basket2))
# arr1 = sorted(cnt1)
# arr2 = sorted(cnt2)
ans = 0
for a in cnt:
if a != mi:
ans += mi * abs(cnt1[a] - cnt2[a])//2
return ans
def minCost3(self, basket1: List[int], basket2: List[int]) -> int:
cnt = Counter(basket1)
for x in basket2: cnt[x] -= 1
last = []
for k, v in cnt.items():
# if v is odd, an even distribution is never possible
if v % 2 != 0:
return -1
# the count of transferred k is |v|/2
last += [k] * abs(v // 2)
# find the min of two input arrays as the intermediate
minx = min(basket1 + basket2)
# Use quickselect instead of sort can get a better complexity
last.sort()
# The first half may be the cost
return sum(min(2*minx, x) for x in last[0:len(last)//2])
if __name__ == '__main__':
print(Solution().minCost2(basket1 = [4,2,2,2], basket2 = [1,4,1,2]))
print(Solution().minCost2(basket1 = [2,3,4,1], basket2 = [3,2,5,1]))
print(Solution().minCost2(basket1 = [5,8,15,7], basket2 = [5,7,8,15]))
print(Solution().minCost2(basket1 = [84,80,43,8,80,88,43,14,100,88],
basket2 = [32,32,42,68,68,100,42,84,14,8]))
print(Solution().minCost2(basket1 = [4,4,4,4,3], basket2 =[5,5,5,5,3]))
|
'''
-Medium-
*DP*
There is a 3 lane road of length n that consists of n + 1 points labeled from 0 to n. A frog starts at point 0 in the second lane and wants to jump to point n. However, there could be obstacles along the way.
You are given an array obstacles of length n + 1 where each obstacles[i] (ranging from 0 to 3) describes an obstacle on the lane obstacles[i] at point i. If obstacles[i] == 0, there are no obstacles at point i. There will be at most one obstacle in the 3 lanes at each point.
For example, if obstacles[2] == 1, then there is an obstacle on lane 1 at point 2.
The frog can only travel from point i to point i + 1 on the same lane if there is not an obstacle on the lane at point i + 1. To avoid obstacles, the frog can also perform a side jump to jump to another lane (even if they are not adjacent) at the same point if there is no obstacle on the new lane.
For example, the frog can jump from lane 3 at point 3 to lane 1 at point 3.
Return the minimum number of side jumps the frog needs to reach any lane at point n starting from lane 2 at point 0.
Note: There will be no obstacles on points 0 and n.
Example 1:
Input: obstacles = [0,1,2,3,0]
Output: 2
Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps (red arrows).
Note that the frog can jump over obstacles only when making side jumps (as shown at point 2).
Example 2:
Input: obstacles = [0,1,1,3,3,0]
Output: 0
Explanation: There are no obstacles on lane 2. No side jumps are required.
Example 3:
Input: obstacles = [0,2,1,0,3,0]
Output: 2
Explanation: The optimal solution is shown by the arrows above. There are 2 side jumps.
Constraints:
obstacles.length == n + 1
1 <= n <= 5 * 105
0 <= obstacles[i] <= 3
obstacles[0] == obstacles[n] == 0
'''
from typing import List
from random import randint
class Solution:
def minSideJumps(self, obstacles: List[int]) -> int:
O, n = obstacles, len(obstacles)-1
dp = [[float('inf')]*3 for _ in range(n+1)]
dp[n][0] = dp[n][1] = dp[n][2] = 0
for i in range(n-1, -1, -1):
o = O[i] - 1
if o != 0:
dp[i][0] = min(dp[i+1][0], 1+dp[i+1][1] if o != 1 else float('inf'), 1+dp[i+1][2] if o != 2 else float('inf'))
if o != 1:
dp[i][1] = min(dp[i+1][1], 1+dp[i+1][0] if o != 0 else float('inf'), 1+dp[i+1][2] if o != 2 else float('inf'))
if o != 2:
dp[i][2] = min(dp[i+1][2], 1+dp[i+1][1] if o != 1 else float('inf'), 1+dp[i+1][0] if o != 0 else float('inf'))
# for i in range(3):
# for j in range(n+1):
# print(dp[j][i],end=' ')
# print("\n")
return dp[0][1]
def minSideJumps2(self, obstacles: List[int]) -> int:
O, n = obstacles, len(obstacles)-1
dp = [[float('inf')]*3 for _ in range(n+1)]
dp[n][0] = dp[n][1] = dp[n][2] = 0
for i in range(n-1, -1, -1):
o = O[i] - 1
if o == -1:
dp[i][0] = min(dp[i+1][0], 1+dp[i+1][1], 1+dp[i+1][2])
dp[i][1] = min(dp[i+1][1], 1+dp[i+1][0], 1+dp[i+1][2])
dp[i][2] = min(dp[i+1][2], 1+dp[i+1][1], 1+dp[i+1][0])
elif o == 0:
dp[i][1] = min(dp[i+1][1], 1+dp[i+1][2])
dp[i][2] = min(dp[i+1][2], 1+dp[i+1][1])
elif o == 1:
dp[i][0] = min(dp[i+1][0], 1+dp[i+1][2])
dp[i][2] = min(dp[i+1][2], 1+dp[i+1][0])
else:
dp[i][0] = min(dp[i+1][0], 1+dp[i+1][1])
dp[i][1] = min(dp[i+1][1], 1+dp[i+1][0])
return dp[0][1]
def minSideJumps3(self, obstacles: List[int]) -> int:
O, n = obstacles, len(obstacles)-1
dp_0 = [0]*3
dp_1 = [0]*3
for i in range(n-1, -1, -1):
o = O[i] - 1
if o == -1:
dp_1[0] = min(dp_0[0], 1+dp_0[1], 1+dp_0[2])
dp_1[1] = min(dp_0[1], 1+dp_0[0], 1+dp_0[2])
dp_1[2] = min(dp_0[2], 1+dp_0[1], 1+dp_0[0])
elif o == 0:
dp_1[0] = float('inf')
dp_1[1] = min(dp_0[1], 1+dp_0[2])
dp_1[2] = min(dp_0[2], 1+dp_0[1])
elif o == 1:
dp_1[1] = float('inf')
dp_1[0] = min(dp_0[0], 1+dp_0[2])
dp_1[2] = min(dp_0[2], 1+dp_0[0])
else:
dp_1[2] = float('inf')
dp_1[0] = min(dp_0[0], 1+dp_0[1])
dp_1[1] = min(dp_0[1], 1+dp_0[0])
dp_0, dp_1 = dp_1, dp_0
# print(i, dp_0)
return dp_0[1]
def minSideJumps4(self, obstacles: List[int]) -> int:
O, n = obstacles, len(obstacles)-1
dp = [0, 0, 0]
for i in range(n-1, -1, -1):
if O[i]:
dp[O[i]-1] = float('inf')
for k in range(3):
if O[i] != k+1:
dp[k] = min(dp[k], 1+dp[(k+1)%3], 1+dp[(k+2)%3])
return dp[1]
if __name__ == "__main__":
print(Solution().minSideJumps(obstacles = [0,1,2,3,0]))
print(Solution().minSideJumps3(obstacles = [0,1,2,3,0]))
print(Solution().minSideJumps4(obstacles = [0,1,2,3,0]))
print(Solution().minSideJumps(obstacles = [0,1,1,3,3,0]))
print(Solution().minSideJumps4(obstacles = [0,1,1,3,3,0]))
print(Solution().minSideJumps(obstacles = [0,2,1,0,3,0]))
print(Solution().minSideJumps4(obstacles = [0,2,1,0,3,0]))
N = 5*10**5
obstacles = []
for i in range(N):
obstacles.append(randint(0, 3))
obstacles[0] = 0
obstacles[N-1] = 0
# print(Solution().minSideJumps(obstacles = obstacles))
# print(Solution().minSideJumps2(obstacles = obstacles))
print(Solution().minSideJumps3(obstacles = obstacles))
print(Solution().minSideJumps4(obstacles = obstacles))
|
'''
-Medium-
*Binary Search*
You are given a sorted array consisting of only integers where every
element appears exactly twice, except for one element which appears exactly once.
Return the single element that appears only once.
Your solution must run in O(log n) time and O(1) space.
Example 1:
Input: nums = [1,1,2,3,3,4,4,8,8]
Output: 2
Example 2:
Input: nums = [3,3,7,7,10,11,11]
Output: 10
Constraints:
1 <= nums.length <= 10^5
0 <= nums[i] <= 10^5
'''
from typing import List
class Solution:
def singleNonDuplicate(self, nums: List[int]) -> int:
n = len(nums)
l, r = 0, n-1
while l < r:
mid = l + (r-l)//2
if nums[mid] == nums[mid+1]:
if (n-1-mid)%2 == 1: r = mid
else: l = mid + 1
else:
if mid == 0 or nums[mid] != nums[mid-1]:
return nums[mid]
if (n-1-mid)%2 == 0: r = mid
else: l = mid + 1
return nums[l]
def singleNonDuplicate2(self, nums: List[int]) -> int:
n = len(nums)
l, r = 0, n-1
while l < r:
mid = l + (r-l)//2
if nums[mid] == nums[mid^1]:
l = mid + 1
else:
r = mid
return nums[l]
if __name__ == "__main__":
print(Solution().singleNonDuplicate(nums = [1,1,2,3,3,4,4,8,8]))
print(Solution().singleNonDuplicate(nums = [3,3,7,7,10,11,11]))
print(Solution().singleNonDuplicate2(nums = [1,1,2,3,3,4,4,8,8]))
print(Solution().singleNonDuplicate2(nums = [3,3,7,7,10,11,11]))
|
'''
-Hard-
*Union Find*
You are given an integer array nums, and you can perform the following operation any
number of times on nums:
Swap the positions of two elements nums[i] and nums[j] if gcd(nums[i], nums[j]) > 1
where gcd(nums[i], nums[j]) is the greatest common divisor of nums[i] and nums[j].
Return true if it is possible to sort nums in non-decreasing order using the
above swap method, or false otherwise.
Example 1:
Input: nums = [7,21,3]
Output: true
Explanation: We can sort [7,21,3] by performing the following operations:
- Swap 7 and 21 because gcd(7,21) = 7. nums = [21,7,3]
- Swap 21 and 3 because gcd(21,3) = 3. nums = [3,7,21]
Example 2:
Input: nums = [5,2,6,2]
Output: false
Explanation: It is impossible to sort the array because 5 cannot be swapped with any other element.
Example 3:
Input: nums = [10,5,9,3,15]
Output: true
We can sort [10,5,9,3,15] by performing the following operations:
- Swap 10 and 15 because gcd(10,15) = 5. nums = [15,5,9,3,10]
- Swap 15 and 3 because gcd(15,3) = 3. nums = [3,5,9,15,10]
- Swap 10 and 15 because gcd(10,15) = 5. nums = [3,5,9,10,15]
Constraints:
1 <= nums.length <= 3 * 104
2 <= nums[i] <= 105
'''
from typing import List
from collections import defaultdict, Counter
import math
class UnionFind:
def __init__(self):
self.parent = {}
def find(self, u):
if u != self.parent.setdefault(u, u):
self.parent[u] = self.find(self.parent[u]) # Path compression
return self.parent[u]
def union(self, u, v):
pu, pv = self.find(u), self.find(v)
if pu != pv: self.parent[pu] = pv
class Solution:
def gcdSort(self, nums: List[int]) -> bool:
n = len(nums)
graph = defaultdict(list)
sortIndex = sorted([i for i,_ in enumerate(nums)], key=lambda x: nums[x])
def sieve(n):
A = [i for i in range(n+1)]
for p in range(2, math.floor(math.sqrt(n))+1):
if A[p]:
j = p*p
while j <= n:
A[j] = 0
j += p
L = []
for p in range(2, n+1):
if A[p]:
L.append(A[p])
return L
def primes_set(m):
for i in range(2, int(math.sqrt(m))+1):
if m % i == 0:
return primes_set(m//i) | set([i])
return set([m])
roots = [i for i in range(n)]
ranks = [0]*n
def find(x):
while x != roots[x]:
roots[x] = roots[roots[x]]
x = roots[x]
return x
def union(x, y):
fx, fy = find(x), find(y)
if fx != fy:
if ranks[fx] > ranks[fy]:
roots[fy] = fx
else:
roots[fx] = fy
if ranks[fx] == ranks[fy]:
ranks[fy] += 1
#L = set(sieve(10**5))
for i in range(n):
L = primes_set(nums[i])
for j in L:
graph[j].append(i)
for k in graph:
idx = graph[k]
for i in range(len(idx)-1):
union(idx[i], idx[i+1])
for i in range(n):
if find(i) != find(sortIndex[i]):
return False
# cnt = defaultdict(list)
# for i in range(n):
# cnt[find(i)].append(i)
# for r in cnt:
# match = set()
# for j in cnt[r]:
# match.add(sortIndex[j])
# if match != set(cnt[r]):
# return False
return True
def gcdSort(self, nums: List[int]) -> bool:
def sieve(n): # O(N*log(logN)) ~ O(N)
spf = [i for i in range(n)]
for i in range(2, n):
if spf[i] != i: continue # Skip if it's a not prime number
for j in range(i * i, n, i):
if spf[j] > i: # update to the smallest prime factor of j
spf[j] = i
return spf
def getPrimeFactors(num, spf): # O(logNum)
while num > 1:
yield spf[num]
num //= spf[num]
spf = sieve(max(nums) + 1)
uf = UnionFind()
for x in nums:
for f in getPrimeFactors(x, spf):
uf.union(x, f)
for x, y in zip(nums, sorted(nums)):
if uf.find(x) != uf.find(y):
return False
return True
if __name__ == "__main__":
# print(Solution().gcdSort([7,21,3]))
# print(Solution().gcdSort([5,2,6,2]))
# print(Solution().gcdSort([10,5,9,3,15]))
print(Solution().gcdSort([8,9,4,2,3])) |
'''
-Hard-
*Sliding Window*
*Two Pointers*
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 empty string "".
If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.
'''
from collections import defaultdict
import collections
import sys
class Solution(object):
def minWindowFrameWork(self, s, t):
'''
use the sliding window framework
'''
need = defaultdict(int)
window = defaultdict(int)
for c in t: need[c] += 1
left, right = 0, 0
valid = 0
# 记录最小覆盖子串的起始索引及长度
start, lth = 0, sys.maxsize
while right < len(s):
# c 是将移入窗口的字符
c = s[right]
# 右移窗口
right += 1
# 进行窗口内数据的一系列更新
if c in need:
window[c] += 1
if window[c] == need[c]:
valid += 1
# 判断左侧窗口是否要收缩
while valid == len(need):
# 在这里更新最小覆盖子串
if right - left < lth:
start = left
lth = right - left
# d 是将移出窗口的字符
d = s[left]
# 左移窗口
left += 1
# 进行窗口内数据的一系列更新
if d in need:
if window[d] == need[d]:
valid -= 1
window[d] -= 1
#返回最小覆盖子串
return "" if lth == sys.maxsize \
else s[start:start+lth]
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
start = end = 0
char_need = defaultdict(int) # the count of char needed by current window, negative means current window has it but not needs it
#char_need = {}
count_need = len(t) # count of chars not in current window but in t
min_length = len(s)+1
min_start = 0
#print('length s :', len(s))
for i in t:
char_need[i] += 1 # current window needs all char in t
while end < len(s):
if char_need[s[end]] > 0:
count_need -= 1
char_need[s[end]] -= 1 # current window contains s[end] now,
# so does not need it any more;
# char_need[s[end]] could become negative
end += 1
print(end, s[end-1], count_need, char_need)
# shrink the window only when all chars in T are still present in
# the window: dictated by count_need=0
while count_need == 0:
if min_length > end - start:
min_length = end - start
min_start = start
#if s[start] in char_need:
char_need[s[start]] += 1 # current window does not contain s[start] any more
if char_need[s[start]] > 0: # when some count in char_need is positive, it means there is char in t but not current window
count_need += 1
start += 1
print(start, end, min_start, min_length)
return "" if min_length == len(s)+1 else s[min_start:min_start + min_length]
def minWindowAC(self, s, t):
"""
The current window is s[i:j] and the result window is s[I:J]. In
need[c] I store how many times I need character c (can be negative)
and missing tells how many characters are still missing. In the loop,
first add the new character to the window. Then, if nothing is missing,
remove as much as possible from the window start and then update the
result.
"""
need, missing = collections.Counter(t), len(t)
i = I = J = 0
for j, c in enumerate(s, 1):
missing -= need[c] > 0
need[c] -= 1
if not missing:
while i < j and need[s[i]] < 0:
need[s[i]] += 1
i += 1
if not J or j - i <= J - I:
I, J = i, j
return s[I:J]
if __name__ == "__main__":
#assert Solution().minWindow("ADOBECODEBANC", "ABC") == "BANC"
assert Solution().minWindowFrameWork("ADOBECODEBANC", "ABC") == "BANC"
#print(Solution().minWindowAC("ADOBECODEBANC", "ABCC")) |
'''
-Hard-
*DP*
We are given n different types of stickers. Each sticker has a lowercase
English word on it.
You would like to spell out the given string target by cutting individual
letters from your collection of stickers and rearranging them. You can use
each sticker more than once if you want, and you have infinite quantities
of each sticker.
Return the minimum number of stickers that you need to spell out target.
If the task is impossible, return -1.
Note: In all test cases, all words were chosen randomly from the 1000 most
common US English words, and target was chosen as a concatenation of two
random words.
Example 1:
Input: stickers = ["with","example","science"], target = "thehat"
Output: 3
Explanation:
We can use 2 "with" stickers, and 1 "example" sticker.
After cutting and rearrange the letters of those stickers, we can form the target "thehat".
Also, this is the minimum number of stickers necessary to form the target string.
Example 2:
Input: stickers = ["notice","possible"], target = "basicbasic"
Output: -1
Explanation:
We cannot form the target "basicbasic" from cutting letters from the given stickers.
Constraints:
n == stickers.length
1 <= n <= 50
1 <= stickers[i].length <= 10
1 <= target <= 15
stickers[i] and target consist of lowercase English letters.
'''
from typing import List
class Solution:
def minStickers(self, stickers: List[str], target: str) -> int:
stickers.sort(key = lambda x:len(x),reverse = True)
targetLength = len(target)
dp = [-1]*(1 << targetLength)
dp[0] = 0
for sticker in stickers:
for state in range(1 << targetLength):
if dp[state] >= 0:
curState = state
for i in range(len(sticker)):
for j in range(targetLength):
if sticker[i] == target[j] and curState & (1 << j) == 0:
curState |= 1 << j
break
if dp[curState] == -1:
dp[curState] = dp[state] + 1
else:
dp[curState] = min(dp[curState], dp[state] + 1)
return dp[(1 << targetLength) - 1]
def minStickers2(self, stickers: List[str], target: str) -> int:
m = len(stickers)
mp = [[0]*26 for y in range(m)]
for i in range(m):
for c in stickers[i]:
mp[i][ord(c)-ord('a')] += 1
dp = {}
dp[""] = 0
def helper(dp, mp, target):
if target in dp:
return dp[target]
tar = [0]*26
for c in target:
tar[ord(c)-ord('a')] += 1
ans = float('inf')
for i in range(m):
if mp[i][ord(target[0])-ord('a')] == 0:
continue
s = ''
for j in range(26):
if tar[j] > mp[i][j]:
s += chr(ord('a')+j)*(tar[j] - mp[i][j])
tmp = helper(dp, mp, s)
if tmp != -1:
ans = min(ans, 1+tmp)
dp[target] = -1 if ans == float('inf') else ans
return dp[target]
return helper(dp, mp, target)
if __name__ == '__main__':
print(Solution().minStickers(stickers = ["with","example","science"], target = "thehat"))
print(Solution().minStickers2(stickers = ["with","example","science"], target = "thehat")) |
'''
-Medium-
You are given a 0-indexed 2D integer array of events where
events[i] = [startTimei, endTimei, valuei]. The ith event starts at
startTimei and ends at endTimei, and if you attend this event, you will
receive a value of valuei. You can choose at most two non-overlapping events
to attend such that the sum of their values is maximized.
Return this maximum sum.
Note that the start time and end time is inclusive: that is, you cannot
attend two events where one of them starts and the other ends at the same time.
More specifically, if you attend an event with end time t, the next event
must start at or after t + 1.
Example 1:
Input: events = [[1,3,2],[4,5,2],[2,4,3]]
Output: 4
Explanation: Choose the green events, 0 and 1 for a sum of 2 + 2 = 4.
Example 2:
Example 1 Diagram
Input: events = [[1,3,2],[4,5,2],[1,5,5]]
Output: 5
Explanation: Choose event 2 for a sum of 5.
Example 3:
Input: events = [[1,5,3],[1,5,1],[6,6,5]]
Output: 8
Explanation: Choose events 0 and 2 for a sum of 3 + 5 = 8.
Constraints:
2 <= events.length <= 10^5
events[i].length == 3
1 <= startTimei <= endTimei <= 10^9
1 <= valuei <= 10^6
'''
from typing import List
import bisect
class Solution:
def maxTwoEvents(self, events: List[List[int]]) -> int:
n, sortStart, sortEnd = len(events), [], []
for i, (s, e, v) in enumerate(events):
sortStart.append((s, i))
sortEnd.append((e, i))
sortStart.sort()
sortEnd.sort()
# Q: How can we quickly get the maximum score of an interval not intersecting
# with the interval we chose?
# A: precompute the maximum score at the index binary search finds
maxScoreSt, maxScoreEn = [0]*n, [0]*n
maxScoreSt[-1] = events[sortStart[-1][1]][2]
maxScoreEn[0] = events[sortEnd[0][1]][2]
for i in range(1, n):
maxScoreEn[i] = max(maxScoreEn[i-1], events[sortEnd[i][1]][2])
for i in range(n-2,-1,-1):
maxScoreSt[i] = max(maxScoreSt[i+1], events[sortStart[i][1]][2])
ans = 0
for i, (s, e, v) in enumerate(events):
ans = max(ans, v)
idx = bisect.bisect_left(sortEnd, (s,0)) - 1
if idx >= 0:
ans = max(ans, v+maxScoreEn[idx])
idx = bisect.bisect_right(sortStart, (e,n)) + 1
if idx < n:
ans = max(ans, v+maxScoreSt[idx])
return ans
def maxTwoEvents2(self, events: List[List[int]]) -> int:
n, sortStart, sortEnd = len(events), [], []
for i, (s, e, v) in enumerate(events):
sortStart.append((s, i))
sortEnd.append((e, i))
sortStart.sort()
sortEnd.sort()
st = [s[0] for s in sortStart]
se = [s[0] for s in sortEnd]
# Q: How can we quickly get the maximum score of an interval not intersecting
# with the interval we chose?
# A: precompute the maximum score at the index binary search finds
maxScoreSt, maxScoreEn = [0]*n, [0]*n
maxScoreSt[-1] = events[sortStart[-1][1]][2]
maxScoreEn[0] = events[sortEnd[0][1]][2]
for i in range(1, n):
maxScoreEn[i] = max(maxScoreEn[i-1], events[sortEnd[i][1]][2])
for i in range(n-2,-1,-1):
maxScoreSt[i] = max(maxScoreSt[i+1], events[sortStart[i][1]][2])
ans = 0
for i, (s, e, v) in enumerate(events):
ans = max(ans, v)
idx = bisect.bisect_left(se, s) - 1
if idx >= 0:
ans = max(ans, v+maxScoreEn[idx])
idx = bisect.bisect_right(st, e) + 1
if idx < n:
ans = max(ans, v+maxScoreSt[idx])
return ans
if __name__ == "__main__":
print(Solution().maxTwoEvents([[1,3,2],[4,5,2],[2,4,3]]))
print(Solution().maxTwoEvents([[1,3,2],[4,5,2],[1,5,5]]))
print(Solution().maxTwoEvents([[1,5,3],[1,5,1],[6,6,5]]))
print(Solution().maxTwoEvents([[1,1,1],[1,1,1]]))
print(Solution().maxTwoEvents2([[1,3,2],[4,5,2],[2,4,3]]))
print(Solution().maxTwoEvents2([[1,3,2],[4,5,2],[1,5,5]]))
print(Solution().maxTwoEvents2([[1,5,3],[1,5,1],[6,6,5]]))
print(Solution().maxTwoEvents2([[1,1,1],[1,1,1]])) |
'''
-Medium-
*Simulation*
There is an n x n grid, with the top-left cell at (0, 0) and the bottom-right cell
at (n - 1, n - 1). You are given the integer n and an integer array startPos where
startPos = [startrow, startcol] indicates that a robot is initially at
cell (startrow, startcol).
You are also given a 0-indexed string s of length m where s[i] is the ith
instruction for the robot: 'L' (move left), 'R' (move right), 'U' (move up),
and 'D' (move down).
The robot can begin executing from any ith instruction in s. It executes the
instructions one by one towards the end of s but it stops if either of these
conditions is met:
The next instruction will move the robot off the grid.
There are no more instructions left to execute.
Return an array answer of length m where answer[i] is the number of instructions
the robot can execute if the robot begins executing from the ith instruction in s.
Example 1:
Input: n = 3, startPos = [0,1], s = "RRDDLU"
Output: [1,5,4,3,1,0]
Explanation: Starting from startPos and beginning execution from the ith instruction:
- 0th: "RRDDLU". Only one instruction "R" can be executed before it moves off the grid.
- 1st: "RDDLU". All five instructions can be executed while it stays in the grid and ends at (1, 1).
- 2nd: "DDLU". All four instructions can be executed while it stays in the grid and ends at (1, 0).
- 3rd: "DLU". All three instructions can be executed while it stays in the grid and ends at (0, 0).
- 4th: "LU". Only one instruction "L" can be executed before it moves off the grid.
- 5th: "U". If moving up, it would move off the grid.
Example 2:
Input: n = 2, startPos = [1,1], s = "LURD"
Output: [4,1,0,0]
Explanation:
- 0th: "LURD".
- 1st: "URD".
- 2nd: "RD".
- 3rd: "D".
Example 3:
Input: n = 1, startPos = [0,0], s = "LRUD"
Output: [0,0,0,0]
Explanation: No matter which instruction the robot begins execution from, it would move off the grid.
Constraints:
m == s.length
1 <= n, m <= 500
startPos.length == 2
0 <= startrow, startcol < n
s consists of 'L', 'R', 'U', and 'D'.
'''
from typing import List
class Solution:
def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
# DP overkills
m = len(s)
xs,ys = startPos
dp = [[[0]*(m+1) for _ in range(n)] for _ in range(n)]
for k in range(m-1, -1, -1):
for i in range(n):
for j in range(n):
if s[k] == 'L':
ans = 1+dp[i][j-1][k+1] if j > 0 else 0
if s[k] == 'R':
ans = 1+dp[i][j+1][k+1] if j < n-1 else 0
if s[k] == 'U':
ans = 1+dp[i-1][j][k+1] if i > 0 else 0
if s[k] == 'D':
ans = 1+dp[i+1][j][k+1] if i < n-1 else 0
dp[i][j][k] = ans
return [dp[xs][ys][i] for i in range(m)]
def executeInstructions2(self, n: int, startPos: List[int], s: str) -> List[int]:
m = len(s)
x, y = startPos
ans = [0]*m
for l in range(m):
x, y = startPos
k = l
while k < m:
if s[k] == 'L':
y -= 1
if s[k] == 'R':
y += 1
if s[k] == 'U':
x -= 1
if s[k] == 'D':
x += 1
if x < 0 or x >= n or y < 0 or y >= n:
break
k += 1
ans[l] = k-l
return ans
if __name__ == "__main__":
print(Solution().executeInstructions(n = 3, startPos = [0,1], s = "RRDDLU"))
print(Solution().executeInstructions2(n = 3, startPos = [0,1], s = "RRDDLU"))
s = "LULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDLLULLDLUDRDUDLRRDDDUURLLDL"
print(Solution().executeInstructions2(n = 145, startPos = [139,133], s = s))
|
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 06 22:08:37 2017
We are given two arrays ar1[0…m-1] and ar2[0..n-1] and a number x,
we need to find the pair ar1[i] + ar2[j] such that absolute value
of (ar1[i] + ar2[j] – x) is minimum.
@author: merli
"""
import sys
class Solution():
def closestPair(self, l1, l2, x):
i, j, dist = 0, 0, sys.maxint
l3 = [x-n for n in l2][::-1]
#print l3
i1, j1 = 0, 0
while i < len(l1) and j < len(l3):
d = abs(l1[i]-l3[j])
if d < dist:
dist = d
i1, j1 = i,j
if l1[i] < l3[j]:
i += 1
else:
j += 1
#print i1, j1
return [l1[i1], l2[len(l2)-(j1+1)]]
if __name__ == "__main__":
ar1 = [ 1, 4, 5, 7]
ar2 = [10, 20, 30, 40]
print Solution().closestPair(ar1, ar2, 32)
print Solution().closestPair(ar1, ar2, 50) |
"""
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12
is the sequence of the first 10 ugly numbers.
Note that 1 is typically treated as an ugly number.
"""
import heapq
__author__ = 'Daniel'
class Solution(object):
def nthUglyNumber(self, n):
"""
Prime factor: 2, 3, 5
Heap
:type n: int
:rtype: int
"""
if n <= 0:
return 0
if n == 1:
return 1
t2,t3,t5=0,0,0
k=[0]*n
k[0] = 1
for i in range(1, n):
k[i] = min(k[t2]*2, k[t3]*3, k[t5]*5)
print(i, k[i], t2, t3, t5, k[t2], k[t3], k[t5])
if k[i] == k[t2]*2:
t2 += 1
if k[i] == k[t3]*3:
t3 += 1
if k[i] == k[t5]*5:
t5 += 1
print(i, k[i], t2, t3, t5)
return k[n-1]
if __name__ == "__main__":
print(Solution().nthUglyNumber(17))
|
'''
-Medium-
A perfectly straight street is represented by a number line. The street has street lamp(s)
on it and is represented by a 2D integer array lights. Each lights[i] = [positioni, rangei]
indicates that there is a street lamp at position positioni that lights up the area from
[positioni - rangei, positioni + rangei] (inclusive).
The brightness of a position p is defined as the number of street lamp that light up the
position p.
Given lights, return the brightest position on the street. If there are multiple brightest
positions, return the smallest one.
Example 1:
Input: lights = [[-3,2],[1,2],[3,3]]
Output: -1
Explanation:
The first street lamp lights up the area from [(-3) - 2, (-3) + 2] = [-5, -1].
The second street lamp lights up the area from [1 - 2, 1 + 2] = [-1, 3].
The third street lamp lights up the area from [3 - 3, 3 + 3] = [0, 6].
Position -1 has a brightness of 2, illuminated by the first and second street light.
Positions 0, 1, 2, and 3 have a brightness of 2, illuminated by the second and third street light.
Out of all these positions, -1 is the smallest, so return it.
Example 2:
Input: lights = [[1,0],[0,1]]
Output: 1
Explanation:
The first street lamp lights up the area from [1 - 0, 1 + 0] = [1, 1].
The second street lamp lights up the area from [0 - 1, 0 + 1] = [-1, 1].
Position 1 has a brightness of 2, illuminated by the first and second street light.
Return 1 because it is the brightest position on the street.
Example 3:
Input: lights = [[1,2]]
Output: -1
Explanation:
The first street lamp lights up the area from [1 - 2, 1 + 2] = [-1, 3].
Positions -1, 0, 1, 2, and 3 have a brightness of 1, illuminated by the first street light.
Out of all these positions, -1 is the smallest, so return it.
Constraints:
1 <= lights.length <= 10^5
lights[i].length == 2
-10^8 <= positioni <= 10^8
0 <= rangei <= 10^8
'''
from collections import defaultdict
from sortedcontainers import SortedDict
class Solution(object):
def brightestPosition(self, lights):
sd = SortedDict()
# 差分记录开闭区间,将右边改为开区间方便处理
for pos, r in lights:
st, ed = pos - r, pos + r + 1
sd.setdefault(st, 0)
sd.setdefault(ed, 0)
sd[st] += 1
sd[ed] -= 1
res = int(-1e9)
tot, max_ = 0, 0
entrys = sd.items()
# 遍历 map 得到最优位置
for pos, cnt in entrys:
tot += cnt
if tot > max_:
max_ = tot
res = pos
return res
def brightestPosition2(self, lights):
sd = defaultdict(int)
# 差分记录开闭区间,将右边改为开区间方便处理
for pos, r in lights:
st, ed = pos - r, pos + r + 1
sd[st] += 1
sd[ed] -= 1
res = int(-1e9)
tot, max_ = 0, 0
# 遍历 map 得到最优位置
for pos in sorted(sd.keys()):
tot += sd[pos]
if tot > max_:
max_ = tot
res = pos
return res
if __name__ == "__main__":
print(Solution().brightestPosition([[0, 5], [1, 3], [5, 4], [8, 3]]))
print(Solution().brightestPosition2([[0, 5], [1, 3], [5, 4], [8, 3]]))
print(Solution().brightestPosition([[1,0],[0,1]]))
print(Solution().brightestPosition2([[1,0],[0,1]]))
|
'''
-Medium-
*Monotonic Stack*
You are given a 0-indexed integer array nums. In one step, remove all elements nums[i] where nums[i - 1] > nums[i] for all 0 < i < nums.length.
Return the number of steps performed until nums becomes a non-decreasing array.
Example 1:
Input: nums = [5,3,4,4,7,3,6,11,8,5,11]
Output: 3
Explanation: The following are the steps performed:
- Step 1: [5,3,4,4,7,3,6,11,8,5,11] becomes [5,4,4,7,6,11,11]
- Step 2: [5,4,4,7,6,11,11] becomes [5,4,7,11,11]
- Step 3: [5,4,7,11,11] becomes [5,7,11,11]
[5,7,11,11] is a non-decreasing array. Therefore, we return 3.
Example 2:
Input: nums = [4,5,7,7,13]
Output: 0
Explanation: nums is already a non-decreasing array. Therefore, we return 0.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
'''
from typing import List
import collections
class Solution:
def totalSteps2(self, nums: List[int]) -> int:
# wrong answer
n = len(nums)
A = nums
queue = collections.deque()
firstLargerToRight = [n]*len(A)
for i,v in enumerate(A):
while queue and A[queue[-1]] <= v:
firstLargerToRight[queue.pop()] = i
queue.append(i)
# print(firstLargerToRight)
ans = 0
i = 0
while i < n:
while i < n and firstLargerToRight[i]-i <= 1:
i += 1
if i < n:
k, j = 0, i+1
# print(i, j, firstLargerToRight[i])
while j < min(firstLargerToRight[i], n):
while j < min(firstLargerToRight[i],n-1) and A[j] > A[j+1]:
j += 1
print(k, j, i, A[j])
j += 1
k += 1
# if j == n and A[j-1] < A[i]:
# k += 1
ans = max(ans, k)
i = firstLargerToRight[i]
# i = j
return ans
def totalSteps(self, nums: List[int]) -> int:
A = nums
st = [[A[0], 0]]
ans = 0
for a in A[1:]:
t = 0
while st and st[-1][0] <= a:
t = max(t, st[-1][1])
# if t == 0:
# t = st[-1][1]
st.pop()
if st:
t += 1
else:
t = 0
ans = max(ans, t)
st.append([a, t])
return ans
def totalSteps3(self, nums: List[int]) -> int:
# wrong answer
A = nums
queue = []
firstLargerToLeft = [-1]*len(A)
for i,v in enumerate(A):
while queue and A[queue[-1]] <= v:
queue.pop()
if queue:
firstLargerToLeft[i] = queue[-1]
queue.append(i)
# print(firstLargerToLeft)
rounds = [i-j if j != -1 else -1 for i,j in enumerate(firstLargerToLeft) ]
# print(rounds)
return 0
print(Solution().totalSteps(nums = [5,3,4,4,7,3,6,11,8,5,11]))
print(Solution().totalSteps(nums = [4,5,7,7,13]))
print(Solution().totalSteps(nums = [10,1,2,3,4,5,6,1,2,3]))
print(Solution().totalSteps(nums = [5,11,7,8,11]))
print(Solution().totalSteps(nums = [7,14,4,14,13,2,6,13]))
# print(Solution().totalSteps3(nums = [5,3,4,4,7,3,6,11,8,5,11]))
# print(Solution().totalSteps3(nums = [4,5,7,7,13]))
# print(Solution().totalSteps3(nums = [10,1,2,3,4,5,6,1,2,3]))
# print(Solution().totalSteps3(nums = [5,11,7,8,11]))
# print(Solution().totalSteps3(nums = [7,14,4,14,13,2,6,13])) |
'''
-Hard-
*DP*
*Bitmask*
You are given an integer array nums. We call a subset of nums good if its product
can be represented as a product of one or more distinct prime numbers.
For example, if nums = [1, 2, 3, 4]:
[2, 3], [1, 2, 3], and [1, 3] are good subsets with products 6 = 2*3, 6 = 2*3,
and 3 = 3 respectively.
[1, 4] and [4] are not good subsets with products 4 = 2*2 and 4 = 2*2 respectively.
Return the number of different good subsets in nums modulo 109 + 7.
A subset of nums is any array that can be obtained by deleting some (possibly none or all)
elements from nums. Two subsets are different if and only if the chosen indices
to delete are different.
Example 1:
Input: nums = [1,2,3,4]
Output: 6
Explanation: The good subsets are:
- [1,2]: product is 2, which is the product of distinct prime 2.
- [1,2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [1,3]: product is 3, which is the product of distinct prime 3.
- [2]: product is 2, which is the product of distinct prime 2.
- [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [3]: product is 3, which is the product of distinct prime 3.
Example 2:
Input: nums = [4,2,3,15]
Output: 5
Explanation: The good subsets are:
- [2]: product is 2, which is the product of distinct prime 2.
- [2,3]: product is 6, which is the product of distinct primes 2 and 3.
- [2,15]: product is 30, which is the product of distinct primes 2, 3, and 5.
- [3]: product is 3, which is the product of distinct prime 3.
- [15]: product is 15, which is the product of distinct primes 3 and 5.
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 30
'''
from typing import List
from collections import Counter
from functools import lru_cache
import math
class Solution:
def numberOfGoodSubsets(self, nums: List[int]) -> int:
arr, ones, mod = [], 0, 10**9+7
for i in nums:
if i == 1: ones += 1
else: arr.append(i)
nums = arr
n = len(nums)
def primes_list(m):
for i in range(2, int(math.sqrt(m))+1):
if m % i == 0:
return primes_list(m//i) + [i]
return [m]
primes, num2prime = set(), [None for _ in range(31)]
for i in range(2, 31):
ps = primes_list(i)
num2prime[i] = ps
primes |= set(ps)
index = {v:i for i,v in enumerate(sorted(list(primes)))}
m = len(primes)
allmask = (1 << m) - 1
#print(m, primes, num2prime)
@lru_cache(None)
def dp(i, mask):
if mask == allmask: return 1
if i == n: return 0
ans = dp(i+1, mask) # not picking number i
present = False
newmask = mask
for p in num2prime[nums[i]]:
if newmask & (1 << index[p]) > 0:
present = True
break
newmask |= 1 << index[p]
if not present:
ans += 1 + dp(i+1, newmask)
ans %= mod
return ans
ans = dp(0, 0)
#print(ans, ones)
return (ones + 1)*ans
def numberOfGoodSubsets2(self, nums: List[int]) -> int:
M = 10**9 + 7
P = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
cnt = Counter(nums)
bm = [sum(1<<i for i, p in enumerate(P) if x % p == 0) for x in range(31)]
bad = set([4, 8, 9, 12, 16, 18, 20, 24, 25, 27, 28])
M = 10**9 + 7
@lru_cache(None)
def dp(mask, num):
if num == 1: return 1
ans = dp(mask, num - 1)
if num not in bad and mask | bm[num] == mask:
ans += dp(mask ^ bm[num], num - 1) * cnt[num]
return ans % M
# - 1 is for subtracting count of empty subset 1
return ((dp(1023, 30) - 1) * pow(2, cnt[1], M)) % M
def numberOfGoodSubsets3(self, nums: List[int]) -> int:
M = 10**9 + 7
P = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
cnt = Counter(nums)
bm = [sum(1<<i for i, p in enumerate(P) if x % p == 0) for x in range(31)]
bad = set([4, 8, 9, 12, 16, 18, 20, 24, 25, 27, 28])
M = 10**9 + 7
@lru_cache(None)
def dp(mask, num):
if num == 1: return 1
if mask == 1023: return 1
ans = dp(mask, num - 1)
if num not in bad and mask & bm[num] == 0:
ans += dp(mask | bm[num], num - 1) * cnt[num]
return ans % M
return ((dp(0, 30) - 1) * pow(2, cnt[1], M)) % M
if __name__ == "__main__":
print(Solution().numberOfGoodSubsets([1,2,3,4]))
#print(Solution().numberOfGoodSubsets([2,3,4]))
#print(Solution().numberOfGoodSubsets([4,2,3,15]))
print(Solution().numberOfGoodSubsets([5,10,1,26,24,21,24,23,11,12,27,4,17,16,2,6,1,1,6,8,13,30,24,20,2,19]))
print(Solution().numberOfGoodSubsets2([5,10,1,26,24,21,24,23,11,12,27,4,17,16,2,6,1,1,6,8,13,30,24,20,2,19]))
print(Solution().numberOfGoodSubsets3([5,10,1,26,24,21,24,23,11,12,27,4,17,16,2,6,1,1,6,8,13,30,24,20,2,19])) |
'''
-Medium-
Given an integer num, find the closest two integers in absolute difference whose product equals num + 1 or num + 2.
Return the two integers in any order.
Example 1:
Input: num = 8
Output: [3,3]
Explanation: For num + 1 = 9, the closest divisors are 3 & 3, for num + 2 = 10, the closest divisors are 2 & 5, hence 3 & 3 is chosen.
Example 2:
Input: num = 123
Output: [5,25]
Example 3:
Input: num = 999
Output: [40,25]
Constraints:
1 <= num <= 10^9
'''
from typing import List
from math import sqrt
class Solution:
def closestDivisors(self, num: int) -> List[int]:
ans = []
diff = float('inf')
k = num + 1
for i in range(1, int(sqrt(k))+1):
if k % i == 0:
d = abs(i - k//i)
if diff > d:
diff = d
ans = [i, k//i]
k = num + 2
for i in range(1, int(sqrt(k))+1):
if k % i == 0:
d = abs(i - k//i)
if diff > d:
diff = d
ans = [i, k//i]
return ans
if __name__ == '__main__':
print(Solution().closestDivisors(8))
print(Solution().closestDivisors(123))
print(Solution().closestDivisors(999)) |
'''
-Medium-
*DFS*
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.
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
'''
class Solution(object):
mapping={'0':'', '1':'', '2':'abc','3':'def','4':'ghi','5':'jkl','6':'mno',
'7':'pqrs','8':'tuv','9':'wxyz'}
def letterCombinations(self, digits):
res = []
if not digits:
return res
c=digits[0]
subs = self.letterCombinations(digits[1:])
for a in self.mapping[c]:
if subs:
for s in subs:
res.append(a+s)
else:
res.append(a)
return res
def letterCombinationsBFS(self, digits):
res = []
if not digits:
return res
res.append("")
for c in digits:
tempres = []
for a in self.mapping[c]:
for b in res:
tempres.append(b+a)
res = tempres
#print res
return res
if __name__ == "__main__":
assert(Solution().letterCombinations("23") ==
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"])
#assert(Solution().letterCombinations("234") ==
#["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"])
#assert(Solution().letterCombinationsBFS("23") ==
#["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"])
print(Solution().letterCombinationsBFS("23"))
|
'''
-Medium-
Given the root of a binary tree, the depth of each node is the shortest distance
to the root.
Return the smallest subtree such that it contains all the deepest nodes in the
original tree.
A node is called the deepest if it has the largest depth possible among any node
in the entire tree.
The subtree of a node is tree consisting of that node, plus the set of all
descendants of that node.
Note: This question is the same as 1123:
https://leetcode.com/problems/lowest-common-ancestor-of-deepest-leaves/
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4]
Output: [2,7,4]
Explanation: We return the node with value 2, colored in yellow in the diagram.
The nodes coloured in blue are the deepest nodes of the tree.
Notice that nodes 5, 3 and 2 contain the deepest nodes in the tree but node 2
is the smallest subtree among them, so we return it.
Example 2:
Input: root = [1]
Output: [1]
Explanation: The root is the deepest node in the tree.
Example 3:
Input: root = [0,1,3,null,2]
Output: [2]
Explanation: The deepest node in the tree is 2, the valid subtrees are the
subtrees of nodes 2, 1 and 0 but the subtree of node 2 is the smallest.
Constraints:
The number of nodes in the tree will be in the range [1, 500].
0 <= Node.val <= 500
The values of the nodes in the tree are unique.
'''
from BinaryTree import (TreeNode, constructBinaryTree, preOrder, null)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def subtreeWithAllDeepest(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def helper(node, depth):
if not node:
return (depth, None)
dl, l = helper(node.left, depth+1)
dr, r = helper(node.right, depth+1)
if dl == dr:
return (dl, node)
elif dl > dr:
return (dl, l)
else:
return (dr, r)
(_, node) = helper(root, 0)
return node
if __name__ == "__main__":
root = constructBinaryTree([3,5,1,6,2,0,8,null,null,7,4])
node = Solution().subtreeWithAllDeepest(root)
print(node.val)
root = constructBinaryTree([1])
node = Solution().subtreeWithAllDeepest(root)
print(node.val)
root = constructBinaryTree([0,1,3,null,2])
node = Solution().subtreeWithAllDeepest(root)
print(node.val)
#preOrder(root) |
'''
-Hard-
*Priority Queue*
You are given an integer n. There are n rooms numbered from 0 to n - 1.
You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique.
Meetings are allocated to rooms in the following manner:
Each meeting will take place in the unused room with the lowest number.
If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting.
When a room becomes unused, meetings that have an earlier original start time should be given the room.
Return the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.
A half-closed interval [a, b) is the interval between a and b including a and not including b.
Example 1:
Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]
Output: 0
Explanation:
- At time 0, both rooms are not being used. The first meeting starts in room 0.
- At time 1, only room 1 is not being used. The second meeting starts in room 1.
- At time 2, both rooms are being used. The third meeting is delayed.
- At time 3, both rooms are being used. The fourth meeting is delayed.
- At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10).
- At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11).
Both rooms 0 and 1 held 2 meetings, so we return 0.
Example 2:
Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]]
Output: 1
Explanation:
- At time 1, all three rooms are not being used. The first meeting starts in room 0.
- At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1.
- At time 3, only room 2 is not being used. The third meeting starts in room 2.
- At time 4, all three rooms are being used. The fourth meeting is delayed.
- At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10).
- At time 6, all three rooms are being used. The fifth meeting is delayed.
- At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12).
Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so we return 1.
Constraints:
1 <= n <= 100
1 <= meetings.length <= 105
meetings[i].length == 2
0 <= starti < endi <= 5 * 105
All the values of starti are unique.
'''
from typing import List
import heapq
class Solution:
def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
meetings.sort()
avail = [i for i in range(n)]
used = []
count = [0]*n
for s, e in meetings:
while used and used[0][0] <= s:
_, r = heapq.heappop(used)
heapq.heappush(avail, r)
if avail:
r = heapq.heappop(avail)
count[r] += 1
heapq.heappush(used, (e, r)) # (ending time, room number)
else:
t, r = heapq.heappop(used)
count[r] += 1
heapq.heappush(used, (t + e - s, r)) # new ending time = old one + e - s
ans = 0
for i in range(n):
if count[i] > count[ans]:
ans = i
return ans
if __name__ == "__main__":
print(Solution().mostBooked(n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]]))
|
'''
-Hard-
*DP*
Given a 1-indexed m x n integer matrix mat, you can select any cell in the matrix as your starting cell.
From the starting cell, you can move to any other cell in the same row or column, but only if the value of the destination cell is strictly greater than the value of the current cell. You can repeat this process as many times as possible, moving from cell to cell until you can no longer make any moves.
Your task is to find the maximum number of cells that you can visit in the matrix by starting from some cell.
Return an integer denoting the maximum number of cells that can be visited.
Example 1:
Input: mat = [[3,1],[3,4]]
Output: 2
Explanation: The image shows how we can visit 2 cells starting from row 1, column 2. It can be shown that we cannot visit more than 2 cells no matter where we start from, so the answer is 2.
Example 2:
Input: mat = [[1,1],[1,1]]
Output: 1
Explanation: Since the cells must be strictly increasing, we can only visit one cell in this example.
Example 3:
Input: mat = [[3,1,6],[-9,5,7]]
Output: 4
Explanation: The image above shows how we can visit 4 cells starting from row 2, column 1. It can be shown that we cannot visit more than 4 cells no matter where we start from, so the answer is 4.
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 105
1 <= m * n <= 105
-105 <= mat[i][j] <= 105
'''
from collections import defaultdict
from typing import List
class Solution:
def maxIncreasingCells(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
ranks = [1]*(m*n)
mat1 = [0]*(m*n)
for i in range(m):
for j in range(n):
mat1[i*n+j] = mat[i][j]
arr = []
row, col = {}, {}
for i in range(m):
for j in range(n):
arr.append((mat[i][j], i, j))
arr.sort()
for a,(v,i,j) in enumerate(arr):
idx = i*n+j
k, l = 0, 0
if i in row or j in col:
# print(ranks[row[i]], ranks[col[j]])
k = ranks[row[i]] if i in row and v > mat1[row[i]] else 0
l = ranks[col[j]] if j in col and v > mat1[col[j]] else 0
print(k,l, idx, row, col)
ranks[idx] = 1 + max(k, l)
# else:
if a == 0 or ( a > 0 and v > arr[a-1][0]):
row[i] = idx
col[j] = idx
print(i, j, v, row, col, ranks)
return max(ranks)
def maxIncreasingCells2(self, mat: List[List[int]]) -> int:
# Wrong
m, n = len(mat), len(mat[0])
ranks = [1]*(m*n)
dp = [[1]*n for _ in range(m)]
arr = []
row, col = {}, {}
ans = 1
for i in range(m):
for j in range(n):
arr.append((mat[i][j], i, j))
arr.sort()
for a,(v,i,j) in enumerate(arr):
idx = i*n+j
k, l = 0, 0
# print('A', i, j, v, row, col)
if i in row or j in col:
# print(ranks[row[i]], ranks[col[j]])
old_x1, old_y1 = -1, -1
old_x2, old_y2 = -1, -1
if i in row and v > row[i][1]:
old_x1, old_y1 = row[i][2], row[i][3]
row[i] = (row[i][0]+1, v, i, j)
if j in col and v > col[j][1]:
old_x2, old_y2 = col[j][2], col[j][3]
col[j] = (col[j][0]+1, v, i, j)
if i not in row:
row[i] = (1, v, i, j)
if j not in col:
col[j] = (1, v, i, j)
# print('C', i, j, v, row[i], col[j])
dp[i][j] = max(row[i][0], col[j][0], 1 + max(dp[old_x1][old_y1] if old_x1 != -1 else 0, dp[old_x2][old_y2] if old_x2 != -1 else 0))
else:
row[i] = (1, v, i, j)
col[j] = (1, v, i, j)
# print('B', i, j, v, row, col)
# for r in dp:
# print(r)
return max(max(r) for r in dp)
def maxIncreasingCells3(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
A = defaultdict(list)
for i in range(m):
for j in range(n):
A[mat[i][j]].append([i, j])
dp = [[0] * n for i in range(m)]
res = [0] * (n + m)
for a in sorted(A):
for i, j in A[a]:
dp[i][j] = max(res[i], res[m + j]) + 1
for i, j in A[a]:
res[m + j] = max(res[m + j], dp[i][j])
res[i] = max(res[i], dp[i][j])
return max(res)
def maxIncreasingCells4(self, mat: List[List[int]]) -> int:
m, n = len(mat), len(mat[0])
A = defaultdict(list)
for i in range(m):
for j in range(n):
A[mat[i][j]].append([i, j])
dp = [[0] * n for i in range(m)]
row, col = [0]*m, [0]*n
# row[i] the longest increasing path so far for row i
# col[j] the longest increasing path so far for col j
for a in sorted(A):
# the key insight here is to update all duplicated cells all together in one iteration
# separately, first for dp values
for i, j in A[a]: # update all i/j's dp value using current row/col values
dp[i][j] = max(row[i], col[j]) + 1
# and then for row/col array
for i, j in A[a]: # update row/col values using new dp
# a common mistake here is to do
# row[i] = col[j] = dp[i][j] which is conflicting with the definition of row/col above
col[j] = max(col[j], dp[i][j])
row[i] = max(row[i], dp[i][j])
return max(max(col), max(row))
if __name__ == "__main__":
# print(Solution().maxIncreasingCells2(mat = [[3,1],[3,4]]))
# print(Solution().maxIncreasingCells2(mat = [[1,1],[1,1]]))
# print(Solution().maxIncreasingCells2(mat = [[3,1,6],[-9,5,7]]))
# print(Solution().maxIncreasingCells2(mat = [[2,-4,2,-2,6]]))
# print(Solution().maxIncreasingCells2(mat = [[0,-1],[-6,-6],[-1,8]]))
# print(Solution().maxIncreasingCells2(mat = [[7,6,3],[-7,-5,6],[-7,0,-4],[6,6,0],[-8,6,0]]))
print(Solution().maxIncreasingCells2(mat = [[9,-3,-2,0,-3],[-1,-4,7,5,9],[1,8,0,-7,-6]]))
|
'''
-Medium-
*Difference Array*
You are driving a vehicle that has capacity empty seats initially available
for passengers. The vehicle only drives east (ie. it cannot turn around
and drive west.)
Given a list of trips, trip[i] = [num_passengers, start_location, end_location]
contains information about the i-th trip: the number of passengers that must
be picked up, and the locations to pick them up and drop them off. The locations
are given as the number of kilometers due east from your vehicle's initial
location.
Return true if and only if it is possible to pick up and drop off all passengers
for all the given trips.
Example 1:
Input: trips = [[2,1,5],[3,3,7]], capacity = 4
Output: false
Example 2:
Input: trips = [[2,1,5],[3,3,7]], capacity = 5
Output: true
Example 3:
Input: trips = [[2,1,5],[3,5,7]], capacity = 3
Output: true
Example 4:
Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
Output: true
Constraints:
trips.length <= 1000
trips[i].length == 3
1 <= trips[i][0] <= 100
0 <= trips[i][1] < trips[i][2] <= 1000
1 <= capacity <= 100000
'''
from collections import defaultdict
class Solution(object):
def carPoolingDiffArray(self, trips, capacity):
N = 1001
df = [0]*(N+1)
for np, sp, ep in trips:
df[sp] += np
df[ep] -= np #这个地方不能加1,考虑同一站既有上车又有下车(题目说了先下后上)
sm = 0
for i in range(N+1):
sm += df[i]
if sm > capacity: return False
return True
def carPooling(self, trips, capacity):
"""
:type trips: List[List[int]]
:type capacity: int
:rtype: bool
"""
seat_left = capacity
n = len(trips)
sPos = []
ePos = []
for t in trips:
np, sp, ep = t
sPos.append((sp, np))
ePos.append((ep, np))
sPos.sort()
ePos.sort()
i = j = 0
while i < n and j < n:
if sPos[i][0] < ePos[j][0]:
seat_left -= sPos[i][1]
i += 1
elif sPos[i][0] > ePos[j][0]:
seat_left += ePos[j][1]
j += 1
else:
seat_left += ePos[j][1]
while j+1 < n and ePos[j+1][0] == ePos[j][0]:
j += 1
seat_left += ePos[j][1]
seat_left -= sPos[i][1]
while i+1 < n and sPos[i+1][0] == sPos[i][0]:
i += 1
seat_left -= sPos[i][1]
i += 1
j += 1
if seat_left < 0:
return False
if i == n:
break
return True
if __name__ == "__main__":
print(Solution().carPooling([[2,1,5],[3,3,7]], 4))
print(Solution().carPooling([[2,1,5],[3,3,7]], 5))
print(Solution().carPooling([[2,1,5],[3,5,7]], 3))
print(Solution().carPooling([[3,2,7],[3,7,9],[8,3,9]], 11))
print(Solution().carPooling([[5,4,7],[7,4,8],[4,1,8]], 17))
print(Solution().carPooling([[9,3,4],[9,1,7],[4,2,4],[7,4,5]], 23))
print(Solution().carPooling([[3,5,9],[4,2,5],[3,4,6],[9,1,4],[5,6,8],[5,4,6]], 14))
print("------------------------")
print(Solution().carPoolingDiffArray([[2,1,5],[3,3,7]], 4))
print(Solution().carPoolingDiffArray([[2,1,5],[3,3,7]], 5))
print(Solution().carPoolingDiffArray([[2,1,5],[3,5,7]], 3))
print(Solution().carPoolingDiffArray([[3,2,7],[3,7,9],[8,3,9]], 11))
print(Solution().carPoolingDiffArray([[5,4,7],[7,4,8],[4,1,8]], 17))
print(Solution().carPoolingDiffArray([[9,3,4],[9,1,7],[4,2,4],[7,4,5]], 23))
print(Solution().carPoolingDiffArray([[3,5,9],[4,2,5],[3,4,6],[9,1,4],
[5,6,8],[5,4,6]], 14))
|
'''
-Hard-
Due to a bug, there are many duplicate folders in a file system. You are given a 2D array paths, where paths[i]
is an array representing an absolute path to the ith folder in the file system.
For example, ["one", "two", "three"] represents the path "/one/two/three".
Two folders (not necessarily on the same level) are identical if they contain the same non-empty set of identical
subfolders and underlying subfolder structure. The folders do not need to be at the root level to be identical. If
two or more folders are identical, then mark the folders as well as all their subfolders.
For example, folders "/a" and "/b" in the file structure below are identical. They (as well as their subfolders)
should all be marked:
/a
/a/x
/a/x/y
/a/z
/b
/b/x
/b/x/y
/b/z
However, if the file structure also included the path "/b/w", then the folders "/a" and "/b" would not be identical.
Note that "/a/x" and "/b/x" would still be considered identical even with the added folder.
Once all the identical folders and their subfolders have been marked, the file system will delete all of them.
The file system only runs the deletion once, so any folders that become identical after the initial deletion
are not deleted.
Return the 2D array ans containing the paths of the remaining folders after deleting all the marked folders.
The paths may be returned in any order.
Example 1:
Input: paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]]
Output: [["d"],["d","a"]]
Explanation: The file structure is as shown.
Folders "/a" and "/c" (and their subfolders) are marked for deletion because they both contain an empty
folder named "b".
Example 2:
Input: paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]]
Output: [["c"],["c","b"],["a"],["a","b"]]
Explanation: The file structure is as shown.
Folders "/a/b/x" and "/w" (and their subfolders) are marked for deletion because they both contain an empty folder named "y".
Note that folders "/a" and "/c" are identical after the deletion, but they are not deleted because they were not marked beforehand.
Example 3:
Input: paths = [["a","b"],["c","d"],["c"],["a"]]
Output: [["c"],["c","d"],["a"],["a","b"]]
Explanation: All folders are unique in the file system.
Note that the returned array can be in a different order as the order does not matter.
Example 4:
Input: paths = [["a"],["a","x"],["a","x","y"],["a","z"],["b"],["b","x"],["b","x","y"],["b","z"]]
Output: []
Explanation: The file structure is as shown.
Folders "/a/x" and "/b/x" (and their subfolders) are marked for deletion because they both contain an
empty folder named "y".
Folders "/a" and "/b" (and their subfolders) are marked for deletion because they both contain an empty
folder "z" and the folder "x" described above.
Example 5:
Input: paths = [["a"],["a","x"],["a","x","y"],["a","z"],["b"],["b","x"],["b","x","y"],["b","z"],["b","w"]]
Output: [["b"],["b","w"],["b","z"],["a"],["a","z"]]
Explanation: This has the same structure as the previous example, except with the added "/b/w".
Folders "/a/x" and "/b/x" are still marked, but "/a" and "/b" are no longer marked because "/b" has the
empty folder named "w" and "/a" does not.
Note that "/a/z" and "/b/z" are not marked because the set of identical subfolders must be non-empty, but these folders are empty.
Constraints:
1 <= paths.length <= 2 * 10^4
1 <= paths[i].length <= 500
1 <= paths[i][j].length <= 10
1 <= sum(paths[i][j].length) <= 2 * 10^5
path[i][j] consists of lowercase English letters.
No two paths lead to the same folder.
For any folder not at the root level, its parent folder will also be in the input.
Accepted
2,631
Submissions
4,315
'''
from collections import defaultdict
class Node(object):
def __init__(self, name):
self.fname = name
self.delete = False
self.subfolders = {}
class Solution(object):
def deleteDuplicateFolder(self, paths):
"""
:type paths: List[List[str]]
:rtype: List[List[str]]
"""
paths.sort()
root = Node('/')
for path in paths:
cur = root
for p in path:
if p not in cur.subfolders:
cur.subfolders[p] = Node(p)
cur = cur.subfolders[p]
seen = {}
def helper(node):
subs = ''
for sub in node.subfolders:
subs += helper(node.subfolders[sub])
if subs:
if subs in seen:
seen[subs].delete = True
node.delete = True
else:
seen[subs] = node
return "("+node.fname+subs+")"
helper(root)
res = []
def gather(node, path):
if node.delete: return
res.append(path+[node.fname])
if not node.subfolders:
return
for sub in node.subfolders:
gather(node.subfolders[sub], path+[node.fname])
for sb in root.subfolders:
gather(root.subfolders[sb], [])
return res
if __name__=="__main__":
paths = [["a"],["c"],["d"],["a","b"],["c","b"],["d","a"]]
print(Solution().deleteDuplicateFolder(paths))
paths = [["a"],["c"],["a","b"],["c","b"],["a","b","x"],["a","b","x","y"],["w"],["w","y"]]
print(Solution().deleteDuplicateFolder(paths))
paths = [["a","b"],["c","d"],["c"],["a"]]
print(Solution().deleteDuplicateFolder(paths))
paths = [["a"],["a","x"],["a","x","y"],["a","z"],["b"],["b","x"],["b","x","y"],["b","z"]]
print(Solution().deleteDuplicateFolder(paths))
paths = [["a"],["a","x"],["a","x","y"],["a","z"],["b"],["b","x"],["b","x","y"],["b","z"],["b","w"]]
print(Solution().deleteDuplicateFolder(paths))
paths = [["trs","krj","xlg","tvzn"],["trs","krj","xlg"],["trs","krj"],["trs"],["trs","krj","xlg","drye"],["trs","krj","xlg","npzy"],["dem","wbv","wcq","tvzn"],["dem","wbv","wcq"],["dem","wbv"],["dem"],["dem","wbv","wcq","drye"],["dem","wbv","wcq","n"]]
print(Solution().deleteDuplicateFolder(paths))
paths = [["b"],["f"],["f","r"],["f","r","g"],["f","r","g","c"],["f","r","g","c","r"],["f","o"],["f","o","x"],["f","o","x","t"],["f","o","x","d"],["f","o","l"],["l"],["l","q"],["c"],["h"],["h","t"],["h","o"],["h","o","d"],["h","o","t"]]
print(Solution().deleteDuplicateFolder(paths))
#'''
|
'''
-Medium-
Given the root of a binary tree and a leaf node, reroot the tree so that the leaf is the new root.
You can reroot the tree with the following steps for each node cur on the path starting from the leaf up to the root excluding the root:
If cur has a left child, then that child becomes cur's right child.
cur's original parent becomes cur's left child. Note that in this process the original parent's pointer to cur becomes null, making it have at most one child.
Return the new root of the rerooted tree.
Note: Ensure that your solution sets the Node.parent pointers correctly after rerooting or you will receive "Wrong Answer".
Example 1:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], leaf = 7
Output: [7,2,null,5,4,3,6,null,null,null,1,null,null,0,8]
Example 2:
Input: root = [3,5,1,6,2,0,8,null,null,7,4], leaf = 0
Output: [0,1,null,3,8,5,null,null,null,6,2,null,null,7,4]
Constraints:
The number of nodes in the tree is in the range [2, 100].
-109 <= Node.val <= 109
All Node.val are unique.
leaf exist in the tree.
'''
from typing import Optional
from BinaryTree import (TreeNode, constructBinaryTree, null)
class Solution:
def changeRoot(self, root: Optional[TreeNode], leaf: int) -> Optional[TreeNode]:
parent = {}
def findParent(node, par):
if not node: return None
if node.val == leaf:
parent[node] = par
return node
cur = findParent(node.left, node)
if cur:
parent[node] = par
return cur
cur = findParent(node.right, node)
if cur:
parent[node] = par
return cur
return None
orig_root = root
root = findParent(root, None)
def makeTree(node, child):
if node != orig_root:
if node.left and node.left != root:
node.right = node.left
node.left = parent[node]
makeTree(parent[node], node)
else:
if child == node.left:
node.left = None
else:
node.right = None
return
makeTree(root, None)
return root
if __name__ == "__main__":
root = constructBinaryTree([3,5,1,6,2,0,8,null,null,7,4])
root.prettyPrint()
root = Solution().changeRoot(root=root, leaf=7)
root.prettyPrint()
root = constructBinaryTree([3,5,1,6,2,0,8,null,null,7,4])
root.prettyPrint()
root = Solution().changeRoot(root=root, leaf=0)
root.prettyPrint()
|
'''
-Medium-
You are playing a game that has n levels numbered from 0 to n - 1. You are given
a 0-indexed integer array damage where damage[i] is the amount of health you will
lose to complete the ith level.
You are also given an integer armor. You may use your armor ability at most once
during the game on any level which will protect you from at most armor damage.
You must complete the levels in order and your health must be greater than 0 at
all times to beat the game.
Return the minimum health you need to start with to beat the game.
Example 1:
Input: damage = [2,7,4,3], armor = 4
Output: 13
Explanation: One optimal way to beat the game starting at 13 health is:
On round 1, take 2 damage. You have 13 - 2 = 11 health.
On round 2, take 7 damage. You have 11 - 7 = 4 health.
On round 3, use your armor to protect you from 4 damage. You have 4 - 0 = 4 health.
On round 4, take 3 damage. You have 4 - 3 = 1 health.
Note that 13 is the minimum health you need to start with to beat the game.
Example 2:
Input: damage = [2,5,3,4], armor = 7
Output: 10
Explanation: One optimal way to beat the game starting at 10 health is:
On round 1, take 2 damage. You have 10 - 2 = 8 health.
On round 2, use your armor to protect you from 5 damage. You have 8 - 0 = 8 health.
On round 3, take 3 damage. You have 8 - 3 = 5 health.
On round 4, take 4 damage. You have 5 - 4 = 1 health.
Note that 10 is the minimum health you need to start with to beat the game.
Example 3:
Input: damage = [3,3,3], armor = 0
Output: 10
Explanation: One optimal way to beat the game starting at 10 health is:
On round 1, take 3 damage. You have 10 - 3 = 7 health.
On round 2, take 3 damage. You have 7 - 3 = 4 health.
On round 3, take 3 damage. You have 4 - 3 = 1 health.
Note that you did not use your armor ability.
Constraints:
n == damage.length
1 <= n <= 105
0 <= damage[i] <= 105
0 <= armor <= 105
'''
from typing import List
class Solution:
def minimumHealth(self, damage: List[int], armor: int) -> int:
D = damage
sm = sum(D)
mx = max(D)
return sm+1 - (mx if mx < armor else armor)
if __name__ == "__main__":
print(Solution().minimumHealth(damage = [2,7,4,3], armor = 4))
print(Solution().minimumHealth(damage = [2,5,3,4], armor = 7))
print(Solution().minimumHealth(damage = [3,3,3], armor = 0)) |
'''
Design your implementation of the circular queue. The circular queue is a linear
data structure in which the operations are performed based on FIFO (First In
First Out) principle and the last position is connected back to the first
position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the spaces
in front of the queue. In a normal queue, once the queue becomes full, we cannot
insert the next element even if there is a space in front of the queue. But using
the circular queue, we can use the space to store new values.
Your implementation should support following operations:
MyCircularQueue(k): Constructor, set the size of the queue to be k.
Front: Get the front item from the queue. If the queue is empty, return -1.
Rear: Get the last item from the queue. If the queue is empty, return -1.
enQueue(value): Insert an element into the circular queue. Return true if the
operation is successful.
deQueue(): Delete an element from the circular queue. Return true if the
operation is successful.
isEmpty(): Checks whether the circular queue is empty or not.
isFull(): Checks whether the circular queue is full or not.
Example:
MyCircularQueue circularQueue = new MyCircularQueue(3); // set the size to be 3
circularQueue.enQueue(1); // return true
circularQueue.enQueue(2); // return true
circularQueue.enQueue(3); // return true
circularQueue.enQueue(4); // return false, the queue is full
circularQueue.Rear(); // return 3
circularQueue.isFull(); // return true
circularQueue.deQueue(); // return true
circularQueue.enQueue(4); // return true
circularQueue.Rear(); // return 4
'''
class MyCircularQueue(object):
def __init__(self, k):
"""
Initialize your data structure here. Set the size of the queue to be k.
:type k: int
"""
self.capacity = k
self.size = 0
self.tail = 0
self.head = k-1
self.data = [0] * k
def enQueue(self, value):
"""
Insert an element into the circular queue. Return true if the operation is successful.
:type value: int
:rtype: bool
"""
if self.isFull(): return False
self.data[self.tail] = value
self.tail = (self.tail+1) % self.capacity
self.size += 1
#print('enq: tail-> ', self.tail)
#print('enq: data-> ', self.data)
return True
def deQueue(self):
"""
Delete an element from the circular queue. Return true if the operation is successful.
:rtype: bool
"""
if self.isEmpty(): return False
self.head = (self.head+1) % self.capacity
self.size -= 1
#print('deq: head-> ', self.head)
#print('deq: data-> ', self.data)
return True
def Front(self):
"""
Get the front item from the queue.
:rtype: int
"""
return -1 if self.isEmpty() else self.data[(self.head+1)%self.capacity]
def Rear(self):
"""
Get the last item from the queue.
:rtype: int
"""
return -1 if self.isEmpty() else self.data[(self.tail-1)%self.capacity]
def isEmpty(self):
"""
Checks whether the circular queue is empty or not.
:rtype: bool
"""
return self.size == 0
def isFull(self):
"""
Checks whether the circular queue is full or not.
:rtype: bool
"""
return self.size == self.capacity
if __name__=="__main__":
circularQueue = MyCircularQueue(5)
print(circularQueue.enQueue(1)) # return true
print(circularQueue.enQueue(2)) # return true
print(circularQueue.enQueue(3)) # return true
#print(circularQueue.enQueue(4)) # return false, the queue is full
#print(circularQueue.enQueue(5)) # return false, the queue is full
print(circularQueue.Rear()) # return 3
print(circularQueue.isFull()) # return true
print(circularQueue.deQueue()) # return true
print(circularQueue.Front()) # return true
print(circularQueue.enQueue(4)) # return true
print(circularQueue.Rear()) # return 4
|
'''
-Medium-
Given an array of integers citations where citations[i] is the number of citations a researcher
received for their ith paper and citations is sorted in an ascending order, return compute
the researcher's h-index.
According to the definition of h-index on Wikipedia: A scientist has an index h if h of their
n papers have at least h citations each, and the other n − h papers have no more than h
citations each.
If there are several possible values for h, the maximum one is taken as the h-index.
Example 1:
Input: citations = [0,1,3,5,6]
Output: 3
Explanation: [0,1,3,5,6] means the researcher has 5 papers in total and each of them had received 0, 1, 3, 5, 6 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, their h-index is 3.
Example 2:
Input: citations = [1,2,100]
Output: 2
Constraints:
n == citations.length
1 <= n <= 10^5
0 <= citations[i] <= 1000
citations is sorted in ascending order.
Follow up: Could you solve it in logarithmic time complexity?
'''
class Solution(object):
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
"""
To understand this we should have a clear understanding of the origin solution to this problem.
It is on wikipage: https://en.wikipedia.org/wiki/H-index
Summary here:
Sort the array descending order, give each a index start from 1.
From right to left, find the last number >= its index, the result is its index.
....c: 25, 8, 5, 3, 3
index:1, 2, 3, 4, 5
number 5, H-index 3.
After understand this origin solution, we can go to the binary search one.
First, the different is the order changed, in this problem, the array sorted in ascending.
We need somehow transfer it to original problem.
For example, we have those number, and their index starts with 0
......c: 3, 3, 5, 8, 25
index: 0, 1, 2, 3, 4
We can covert it using n the length of the array. We subtract n with the index, we get:
........c: 3, 3, 5, 8, 25
index0: 0, 1, 2, 3, 4
index1: 5, 4, 3, 2, 1
We can see we almost have the original form now except the order. It is easy, in the original
problem we try to find the last one >= its index, now we find the first one >= its index.
So now we just using binary search to find the number, a thing here we need to mind is the
index0 here we are using, but we need to convert it to index1.
"""
n = len(citations)
l, r = 0, n
while l < r:
m = (l + r) // 2
# recast index i from [0, 1, ....n-1] to j [n, n-1, ... 1]
# by doing j = n-i
# search for the first recasted index j where c[j] >= j
if citations[m] < n - m:
l = m + 1
else:
r = m
return n - l
if __name__ == "__main__":
print(Solution().hIndex([0,1,3,5,6])) |
'''
-Medium-
*Binary Search*
You are given a positive integer array grades which represents the grades of students in a university. You would like to enter all these students into a competition in ordered non-empty groups, such that the ordering meets the following conditions:
The sum of the grades of students in the ith group is less than the sum of the grades of students in the (i + 1)th group, for all groups (except the last).
The total number of students in the ith group is less than the total number of students in the (i + 1)th group, for all groups (except the last).
Return the maximum number of groups that can be formed.
Example 1:
Input: grades = [10,6,12,7,3,5]
Output: 3
Explanation: The following is a possible way to form 3 groups of students:
- 1st group has the students with grades = [12]. Sum of grades: 12. Student count: 1
- 2nd group has the students with grades = [6,7]. Sum of grades: 6 + 7 = 13. Student count: 2
- 3rd group has the students with grades = [10,3,5]. Sum of grades: 10 + 3 + 5 = 18. Student count: 3
It can be shown that it is not possible to form more than 3 groups.
Example 2:
Input: grades = [8,8]
Output: 1
Explanation: We can only form 1 group, since forming 2 groups would lead to an equal number of students in both groups.
Constraints:
1 <= grades.length <= 105
1 <= grades[i] <= 105
'''
from typing import List
class Solution:
def maximumGroups(self, grades: List[int]) -> int:
n = len(grades)
i = 1
while i*(i+1)//2 <= n:
i += 1
return i-1
def maximumGroups2(self, grades: List[int]) -> int:
n = len(grades)
l, r = 1, n+1
while l < r:
m = l + (r-l)//2
if m*(m+1)//2 <= n:
l = m+1
else:
r = m
return l-1
if __name__ == "__main__":
print(Solution().maximumGroups(grades = [10,6,12,7,3,5]))
print(Solution().maximumGroups(grades = [8,8]))
print(Solution().maximumGroups2(grades = [10,6,12,7,3,5]))
print(Solution().maximumGroups2(grades = [8,8])) |
'''
-Medium-
*Greedy*
*DP*
You are given a binary string s and a positive integer k.
Return the length of the longest subsequence of s that makes up a binary number less than or equal to k.
Note:
The subsequence can contain leading zeroes.
The empty string is considered to be equal to 0.
A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters.
Example 1:
Input: s = "1001010", k = 5
Output: 5
Explanation: The longest subsequence of s that makes up a binary number less than or equal to 5 is "00010", as this number is equal to 2 in decimal.
Note that "00100" and "00101" are also possible, which are equal to 4 and 5 in decimal, respectively.
The length of this subsequence is 5, so 5 is returned.
Example 2:
Input: s = "00101001", k = 1
Output: 6
Explanation: "000001" is the longest subsequence of s that makes up a binary number less than or equal to 1, as this number is equal to 1 in decimal.
The length of this subsequence is 6, so 6 is returned.
Constraints:
1 <= s.length <= 1000
s[i] is either '0' or '1'.
1 <= k <= 109
'''
class Solution:
def longestSubsequence(self, s: str, k: int) -> int:
val, cnt, pow = 0, 0, 1
for i in range(len(s) - 1, -1, -1):
if s[i] == '1':
cnt += 1
val += pow
pow <<= 1
if val + pow > k: break
return s.count('0') + cnt
def longestSubsequence2(self, s: str, k: int) -> int:
n = len(s)
# dp[i] denotes the minimum binary value of a subsequence of length i
dp = [0x3f3f3f3f]*(n+1)
dp[0] = 0
dp[1] = int(s[0] == '1')
for i in range(1, n):
for j in range(i, -1, -1):
cur = (dp[j] << 1) + int(s[i] == '1')
if cur < dp[j+1]:
dp[j+1] = cur
print(dp)
ret = 1
for i in range(2, n+1):
if dp[i] <= k: ret = i
return ret
def longestSubsequence3(self, s: str, k: int) -> int:
# TLE
# dp[i][j] denotes the minimum value of a subsequence of j length
# using values upto 0 to i index of array.
# i -> index of array
# j -> len of subsequence
n, INT_MAX = len(s), 0x3f3f3f3f
dp = [[INT_MAX]*(n+1) for _ in range(n+1)]
for i in range(n+1):
dp[i][0] = 0
for i in range(1, n+1):
for j in range(1, i+1):
dp[i][j] = min(dp[i-1][j],dp[i][j])
if dp[i-1][j-1] != INT_MAX:
dp[i][j] = min(dp[i][j],dp[i-1][j-1]*2+int(s[i-1]=='1'))
ret = 1
for i in range(1, n+1):
for j in range(n+1):
if dp[i][j] <= k:
ret = max(ret, j)
return ret
if __name__ == "__main__":
print(Solution().longestSubsequence(s = "1001010", k = 5))
print(Solution().longestSubsequence(s = "00101001", k = 1))
print(Solution().longestSubsequence2(s = "1001010", k = 5))
print(Solution().longestSubsequence2(s = "00101001", k = 1)) |
'''
-Medium-
You are given a 0-indexed m x n binary matrix grid. You can move from a cell (row, col) to any of the cells (row + 1, col) or (row, col + 1).
Return true if there is a path from (0, 0) to (m - 1, n - 1) that visits an equal number of 0's and 1's. Otherwise return false.
Example 1:
Input: grid = [[0,1,0,0],[0,1,0,0],[1,0,1,0]]
Output: true
Explanation: The path colored in blue in the above diagram is a valid path because we have 3 cells with a value of 1 and 3 with a value of 0. Since there is a valid path, we return true.
Example 2:
Input: grid = [[1,1,0],[0,0,1],[1,0,0]]
Output: false
Explanation: There is no path in this grid with an equal number of 0's and 1's.
Constraints:
m == grid.length
n == grid[i].length
2 <= m, n <= 100
grid[i][j] is either 0 or 1.
'''
from typing import List
from collections import deque
from functools import lru_cache
class Solution:
def isThereAPath(self, grid: List[List[int]]) -> bool:
# TLE
m, n = len(grid), len(grid[0])
que = deque([(-1 if grid[0][0] == 0 else 1, 0, 0)])
while que:
val, x, y = que.popleft()
if x == m-1 and y == n-1 and val == 0:
return True
for dx, dy in [(0, 1), (1, 0)]:
i, j = x + dx, y + dy
if 0 <= i < m and 0 <= j < n:
que.append((val + (-1 if grid[i][j] == 0 else 1), i, j))
return False
def isThereAPath2(self, grid: List[List[int]]) -> bool:
m, n = len(grid), len(grid[0])
s = m + n - 1
if s & 1: return False
s >>= 1
dp = [[set() for _ in range(n)] for _ in range(m)]
dp[0][0].add(-1 if grid[0][0] == 0 else 1)
for i in range(m):
for j in range(n):
if i == 0 and j == 0: continue
if j > 0:
for x in dp[i][j-1]:
k = x + (-1 if grid[i][j] == 0 else 1)
if k > s or k < -s : continue
dp[i][j].add(k)
if i > 0:
for x in dp[i-1][j]:
k = x + (-1 if grid[i][j] == 0 else 1)
if k > s or k < -s : continue
dp[i][j].add(k)
return 0 in dp[m-1][n-1]
def isThereAPath3(self, grid: List[List[int]]) -> bool:
@lru_cache(None)
def dfs(i, j, k):
if i >= m or j >= n:
return False
k += grid[i][j]
if k > s or i + j + 1 - k > s:
return False
if i == m - 1 and j == n - 1:
return k == s
return dfs(i + 1, j, k) or dfs(i, j + 1, k)
m, n = len(grid), len(grid[0])
s = m + n - 1
if s & 1:
return False
s >>= 1
return dfs(0, 0, 0)
import time
import random
if __name__ == "__main__":
grid = [[0,1,0,0],[0,1,0,0],[1,0,1,0]]
print(Solution().isThereAPath(grid=grid))
print(Solution().isThereAPath2(grid=grid))
grid = [[1,1,0],[0,0,1],[1,0,0]]
print(Solution().isThereAPath(grid=grid))
print(Solution().isThereAPath2(grid=grid))
m, n = 100, 99
grid = []
for i in range(m):
t = []
for j in range(n):
t.append(1 if random.random() > 0.7 else 0)
grid.append(t)
start = time.time()
print(Solution().isThereAPath2(grid=grid))
end = time.time()
print('elapsed time: ', end-start)
start = time.time()
print(Solution().isThereAPath3(grid=grid))
end = time.time()
print('elapsed time: ', end-start)
|
'''
-Hard-
*Greedy*
*DP*
You are given two 0-indexed integer arrays nums1 and nums2 of equal length. Every second, for all indices 0 <= i < nums1.length, value of nums1[i] is incremented by nums2[i]. After this is done, you can do the following operation:
Choose an index 0 <= i < nums1.length and make nums1[i] = 0.
You are also given an integer x.
Return the minimum time in which you can make the sum of all elements of nums1 to be less than or equal to x, or -1 if this is not possible.
Example 1:
Input: nums1 = [1,2,3], nums2 = [1,2,3], x = 4
Output: 3
Explanation:
For the 1st second, we apply the operation on i = 0. Therefore nums1 = [0,2+2,3+3] = [0,4,6].
For the 2nd second, we apply the operation on i = 1. Therefore nums1 = [0+1,0,6+3] = [1,0,9].
For the 3rd second, we apply the operation on i = 2. Therefore nums1 = [1+1,0+2,0] = [2,2,0].
Now sum of nums1 = 4. It can be shown that these operations are optimal, so we return 3.
Example 2:
Input: nums1 = [1,2,3], nums2 = [3,3,3], x = 4
Output: -1
Explanation: It can be shown that the sum of nums1 will always be greater than x, no matter which operations are performed.
Constraints:
1 <= nums1.length <= 103
1 <= nums1[i] <= 103
0 <= nums2[i] <= 103
nums1.length == nums2.length
0 <= x <= 106
'''
from typing import List
class Solution:
def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:
n = len(nums1)
s1, s2 = sum(nums1), sum(nums2)
dp = [[0]*(n+1) for _ in range(n+1)]
A = list(zip(nums1, nums2))
A.sort(key = lambda x: x[1])
for i in range(1, n+1):
for j in range(1, i+1):
dp[i][j] = max(dp[i-1][j], dp[i-1][j-1] + A[i-1][1]*j + A[i-1][0])
for t in range(n+1):
if s1 + s2*t - dp[n][t] <= x:
return t
return -1
if __name__ == "__main__":
print(Solution().minimumTime(nums1 = [1,2,3], nums2 = [1,2,3], x = 4))
print(Solution().minimumTime(nums1 = [1,2,3], nums2 = [3,3,3], x = 4)) |
'''
-Medium-
Yash is a student at MIT and has to do a lot of work. He has finished k homeworks and
the deadlines of these homeworks lie between 0 to 𝑘^2 - 1.
Help Yash sort these homeworks in non-decreasing order of deadlines with expected time
and space complexity O(k).
Input: k = 5, homeworks = [13, 24, 1, 17, 8]
Output: [1, 8, 13, 17, 24]
'''
class RadixSort(object):
def sort(self, n, arr):
digitNum = 2
size = n
dataCopy = [[i,v] for i,v in enumerate(arr)]
#print(dataCopy)
def countingSortDigit():
digitData =[]
for i in range(size):
digitData.append((i, dataCopy[i][1] % size))
dataCopy[i][1] //= size
countArray = [0]*size
for digit in digitData:
countArray[digit[1]] += 1
for i in range(1,size):
countArray[i] += countArray[i-1]
#print(digitData, countArray)
auxData = dataCopy[:]
for i in range(size - 1, -1, -1):
countArray[digitData[i][1]] -= 1
curIdx = countArray[digitData[i][1]]
dataCopy[curIdx] = auxData[digitData[i][0]]
# print(dataCopy)
for _ in range(1,digitNum+1):
countingSortDigit()
auxData = arr[:]
for i in range(size):
arr[i] = auxData[dataCopy[i][0]]
return arr
from random import randint
import time
if __name__ == "__main__":
print(RadixSort().sort(5, [13, 24, 1, 15, 8]))
#print(RadixSort().sort(5, [ 100, 24, 70, 99, 8]))
k = 1000000
mx = k**2-1
arr = []
for i in range(k):
arr.append(randint(0, mx))
starttime = time.time()
RadixSort().sort(k, arr)
print("elapsed {}s".format(time.time()-starttime))
starttime = time.time()
arr.sort()
print("elapsed {}s".format(time.time()-starttime))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.