Skip to content

Commit

Permalink
feat(python): solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
hongbo-miao committed Jun 15, 2022
1 parent 68a7aef commit 0b726b1
Show file tree
Hide file tree
Showing 9 changed files with 330 additions and 36 deletions.
34 changes: 32 additions & 2 deletions Python/0004. Median of Two Sorted Arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,44 @@ class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
nums = nums1 + nums2
nums.sort()
if len(nums) % 2 != 0:
if len(nums) % 2 == 1:
return nums[len(nums) // 2]
else:
return (nums[len(nums) // 2 - 1] + nums[len(nums) // 2]) / 2


# Binary Search
# 2) Binary Search (Notion)
# https://zxi.mytechroad.com/blog/algorithms/binary-search/leetcode-4-median-of-two-sorted-arrays/
#
# Time O(log(m + n))
# Space O(1)
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
n1 = len(nums1)
n2 = len(nums2)
if n1 > n2:
return self.findMedianSortedArrays(nums2, nums1)

k = (n1 + n2 + 1) // 2
l = 0
r = n1
while l < r:
m1 = (l + r) // 2
m2 = k - m1
if nums1[m1] < nums2[m2 - 1]:
l = m1 + 1
else:
r = m1
m1 = l
m2 = k - l
c1 = max(
-float("inf") if m1 == 0 else nums1[m1 - 1],
-float("inf") if m2 == 0 else nums2[m2 - 1],
)
if (n1 + n2) % 2 == 1:
return c1
c2 = min(
float("inf") if m1 == n1 else nums1[m1],
float("inf") if m2 == n2 else nums2[m2],
)
return (c1 + c2) / 2
4 changes: 2 additions & 2 deletions Python/0022. Generate Parentheses.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []

def go(l: int, r: int, s: str):
def go(l, r, s):
if len(s) == 2 * n:
res.append(s)
return
Expand All @@ -40,7 +40,7 @@ class Solution:
def generateParenthesis(self, n: int) -> List[str]:
res = []

def go(l: int, r: int, s: str):
def go(l, r, s):
if l == 0 and r == 0:
res.append(s)
return
Expand Down
14 changes: 9 additions & 5 deletions Python/0341. Flatten Nested List Iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,18 +56,22 @@
# Return None if this NestedInteger holds a single integer
# """

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())


class NestedIterator:
def __init__(self, nestedList: [NestedInteger]):
self.stack = nestedList[::-1]
self.st = nestedList[::-1]

def next(self) -> int:
return self.stack.pop().getInteger()
return self.st.pop().getInteger()

def hasNext(self) -> bool:
while self.stack:
top = self.stack[-1]
while self.st:
top = self.st[-1]
if top.isInteger():
return True
self.stack = self.stack[:-1] + top.getList()[::-1]
self.st = self.st[:-1] + top.getList()[::-1]
return False
49 changes: 49 additions & 0 deletions Python/0609. Find Duplicate File in System.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Given a list paths of directory info, including the directory path, and all the files with contents in this directory, return all the duplicate files in the file system in terms of their paths. You may return the answer in any order.
# A group of duplicate files consists of at least two files that have the same content.
# A single directory info string in the input list has the following format:
# - "root/d1/d2/.../dm f1.txt(f1_content) f2.txt(f2_content) ... fn.txt(fn_content)"
# It means there are n files (f1.txt, f2.txt ... fn.txt) with content (f1_content, f2_content ... fn_content) respectively in the directory "root/d1/d2/.../dm". Note that n >= 1 and m >= 0. If m = 0, it means the directory is just the root directory.
# The output is a list of groups of duplicate file paths. For each group, it contains all the file paths of the files that have the same content. A file path is a string that has the following format:
# - "directory_path/file_name.txt"
#
# Example 1:
#
# Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)","root 4.txt(efgh)"]
# Output: [["root/a/2.txt","root/c/d/4.txt","root/4.txt"],["root/a/1.txt","root/c/3.txt"]]
#
# Example 2:
#
# Input: paths = ["root/a 1.txt(abcd) 2.txt(efgh)","root/c 3.txt(abcd)","root/c/d 4.txt(efgh)"]
# Output: [["root/a/2.txt","root/c/d/4.txt"],["root/a/1.txt","root/c/3.txt"]]
#
# Constraints:
#
# 1 <= paths.length <= 2 * 10^4
# 1 <= paths[i].length <= 3000
# 1 <= sum(paths[i].length) <= 5 * 10^5
# paths[i] consist of English letters, digits, '/', '.', '(', ')', and ' '.
# You may assume no files or directories share the same name in the same directory.
# You may assume each given directory info represents a unique directory. A single blank space separates the directory path and file info.
#
# Follow up:
#
# Imagine you are given a real file system, how will you search files? DFS or BFS?
# If the file content is very large (GB level), how will you modify your solution?
# If you can only read the file by 1kb each time, how will you modify your solution?
# What is the time complexity of your modified solution? What is the most time-consuming part and memory-consuming part of it? How to optimize?
# How to make sure the duplicated files you find are not false positive?

from collections import defaultdict


class Solution:
def findDuplicate(self, paths: List[str]) -> List[List[str]]:
groups = defaultdict(list)
for path in paths:
dir, *files = path.split()
for f in files:
name, content = f.split("(")
content = content[:-1]
path = dir + "/" + name
groups[content].append(path)
return [path for path in groups.values() if len(path) > 1]
45 changes: 45 additions & 0 deletions Python/0759. Employee Free Time.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# We are given a list schedule of employees, which represents the working time for each employee.
# Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order.
# Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.
# (Even though we are representing Intervals in the form [x, y], the objects inside are Intervals, not lists or arrays. For example, schedule[0][0].start = 1, schedule[0][0].end = 2, and schedule[0][0][0] is not defined). Also, we wouldn't include intervals like [5, 5] in our answer, as they have zero length.
#
# Example 1:
#
# Input: schedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]
# Output: [[3,4]]
# Explanation: There are a total of three employees, and all common
# free time intervals would be [-inf, 1], [3, 4], [10, inf].
# We discard any intervals that contain inf as they aren't finite.
#
# Example 2:
#
# Input: schedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]
# Output: [[5,6],[7,9]]
#
# Constraints:
#
# 1 <= schedule.length , schedule[i].length <= 50
# 0 <= schedule[i].start < schedule[i].end <= 10^8


"""
# Definition for an Interval.
class Interval:
def __init__(self, start: int = None, end: int = None):
self.start = start
self.end = end
"""


# Similar to 56. Merge Intervals
# It doesn't matter which employee an interval belongs to, so just flatten
class Solution:
def employeeFreeTime(self, schedule: "[[Interval]]") -> "[Interval]":
intervals = sorted([i for s in schedule for i in s], key=lambda i: i.start)
res = []
end = intervals[0].end
for i in intervals[1:]:
if i.start > end:
res.append(Interval(end, i.start))
end = max(end, i.end)
return res
93 changes: 66 additions & 27 deletions Python/0798. Smallest Rotation with Highest Score.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,36 +27,75 @@
# 0 <= nums[i] < nums.length


# https://leetcode.com/problems/smallest-rotation-with-highest-score/solution/
# https://leetcode.com/problems/smallest-rotation-with-highest-score/discuss/118725/C%2B%2BJavaPython-Solution-with-Explanation
# Assume that the input array is [2, 3, 1, 4, 0] so that the expected output is 3.
#
# Time O(N)
# Space O(N)
# Initialize the change array with [1] * N, where N = len(A).
#
# index = `[0, 1, 2, 3, 4]`
# nums = `[2, 3, 1, 4, 0]`
# change = `[1, 1, 1, 1, 1]`
# For the first loop, the idea is to find the index of K that starts losing points. The constraint is that any entries that are less than or equal to their index are worth 1 point. So i - A[i] + 1 comes, and % N is to guarantee the indices within the change's array range.
#
# With change[(i - A[i] + 1) % N] -= 1:
#
# + i = 0:
#
# + change[(0 - 2 + 1) % 5] -= 1 => change[4] = 1 - 1 = 0
#
# index = `[0, 1, 2, 3, 4]`
# nums = `[2, 3, 1, 4, 0]`
# change = `[1, 1, 1, 1, 0]` # update after i = 0.
#
# + i = 1:
#
# + change[(1 - 3 + 1) % 5] -= 1 => change[4] = 0 - 1 = -1
#
# index = `[0, 1, 2, 3, 4]`
# nums = `[2, 3, 1, 4, 0]`
# change = `[1, 1, 1, 1, -1]` # update after i = 1.
#
# + i = 2:
#
# Intuition
# Say N = 10 and A[2] = 5. Then there are 5 rotations that are bad for this number: rotation indexes 0, 1, 2, 8, 9 - these rotations will cause this number to not get 1 point later.
# In general, for each number in the array, we can map out what rotation indexes will be bad for this number. It will always be a region of one interval, possibly two if the interval wraps around (eg. 8, 9, 0, 1, 2 wraps around, to become [8, 9] and [0, 1, 2].)
# At the end of plotting these intervals, we need to know which rotation index has the least intervals overlapping it - this one is the answer.
# + change[(2 - 1 + 1) % 5] -= 1 => change[2] = 1 - 1 = 0
#
# Algorithm
# First, an element like A[2] = 5 will not get score in (up to) 5 posiitons: when the 5 is at final index 0, 1, 2, 3, or 4. When we shift by 2, we'll get final index 0. If we shift 5-1 = 4 before this, this element will end up at final index 4. In general (modulo N), a shift of i - A[i] + 1 to i will be the rotation indexes that will make A[i] not score a point.
# If we are trying to plot an interval like [2, 3, 4], then instead of doing bad[2]--; bad[3]--; bad[4]--;, what we will do instead is keep track of the cumulative total: bad[2]--; bad[5]++. For "wrap-around" intervals like [8, 9, 0, 1, 2], we will keep track of this as two separate intervals: bad[8]--, bad[10]++, bad[0]--, bad[3]++. (Actually, because of our implementation, we don't need to remember the bad[10]++ part.)
# At the end, we want to find a rotation index with the least intervals overlapping. We'll maintain a cumulative total cur representing how many intervals are currently overlapping our current rotation index, then update it as we step through each rotation index.
# index = `[0, 1, 2, 3, 4]`
# nums = `[2, 3, 1, 4, 0]`
# change = `[1, 1, 0, 1, -1]` # update after i = 2.
#
# + i = 3:
#
# + change[(3 - 4 + 1) % 5] -= 1 => change[0] = 1 - 1 = 0
#
# index = `[0, 1, 2, 3, 4]`
# nums = `[2, 3, 1, 4, 0]`
# change = `[0, 1, 0, 1, -1]` # update after i = 3.
#
# + i = 4:
#
# + change[(4 - 0 + 1) % 5] -= 1 => change[0] = 0 - 1 = -1
#
# index = `[0, 1, 2, 3, 4]`
# nums = `[2, 3, 1, 4, 0]`
# change = `[-1, 1, 0, 1, -1]` # update after i = 4.
# Now you can see that the change array becomes [-1, 1, 0, 1, -1].
#
# The second for loop actually calculate total changes in k step moving left via k - 1, so you could think of
# totalChange[k] = totalChange[k - 1] + change[k], as an equivalent as change[k] += change[k - 1]
# After the second loop, the change array is:
# (old) change = `[-1, 1, 0, 1, -1]`
# index = `[0, 1, 2, 3, 4]`
# change = `[-1, 0, 0, 1, 0]`
# Return the index of the max value of the change array, which is 3.
#
# Time O(N)
# Space O(N)
class Solution:
def bestRotation(self, nums: List[int]) -> int:
N = len(nums)
bad = [0] * N
for i, x in enumerate(nums):
left, right = (i - x + 1) % N, (i + 1) % N
bad[left] -= 1
bad[right] += 1
if left > right:
bad[0] -= 1

best = -N
res = cur = 0
for i, score in enumerate(bad):
cur += score
if cur > best:
best = cur
res = i
return res
change = [1] * N
for i in range(N):
change[(i - nums[i] + 1) % N] -= 1
for i in range(1, N):
change[i] += change[i - 1]
return change.index(max(change))
61 changes: 61 additions & 0 deletions Python/1024. Video Stitching.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# You are given a series of video clips from a sporting event that lasted time seconds. These video clips can be overlapping with each other and have varying lengths.
# Each video clip is described by an array clips where clips[i] = [start_i, end_i] indicates that the ith clip started at start_i and ended at end_i.
# We can cut these clips into segments freely.
# - For example, a clip [0, 7] can be cut into segments [0, 1] + [1, 3] + [3, 7].
# Return the minimum number of clips needed so that we can cut the clips into segments that cover the entire sporting event [0, time]. If the task is impossible, return -1.
#
# Example 1:
#
# Input: clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10
# Output: 3
# Explanation: We take the clips [0,2], [8,10], [1,9]; a total of 3 clips.
# Then, we can reconstruct the sporting event as follows:
# We cut [1,9] into segments [1,2] + [2,8] + [8,9].
# Now we have segments [0,2] + [2,8] + [8,10] which cover the sporting event [0, 10].
#
# Example 2:
#
# Input: clips = [[0,1],[1,2]], time = 5
# Output: -1
# Explanation: We cannot cover [0,5] with only [0,1] and [1,2].
#
# Example 3:
#
# Input: clips = [[0,1],[6,8],[0,2],[5,6],[0,4],[0,3],[6,7],[1,3],[4,7],[1,4],[2,5],[2,6],[3,4],[4,5],[5,7],[6,9]], time = 9
# Output: 3
# Explanation: We can take clips [0,4], [4,7], and [6,9].
#
# Constraints:
#
# 1 <= clips.length <= 100
# 0 <= start_i <= end_i <= 100
# 1 <= time <= 100

# https://leetcode.com/problems/video-stitching/discuss/484877/Python-(24-ms-beats-99)-Jump-Game-II-O(N)-time-O(1)-memory
# Idea
# Convert clips to the furthest point you can jump from each point. O(N)
# Do a jump game O(N).
#
# e.g. clips = [[0,2],[4,6],[8,10],[1,9],[1,5],[5,9]], time = 10
# max_jumps = [2, 9, 0, 0, 6, 9, 0, 0, 10, 0, 0]
# lo hi
# 0 0
# 0 2
# 2 9
class Solution:
def videoStitching(self, clips: List[List[int]], time: int) -> int:
max_jumps = [0] * 101
for l, r in clips:
max_jumps[l] = max(max_jumps[l], r)
# print(max_jumps)

# It is then a jump game
count = 0
lo = hi = 0
while hi < time:
# print(lo, hi)
lo, hi = hi, max(max_jumps[lo : hi + 1])
if hi <= lo:
return -1
count += 1
return count
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@


# https://leetcode.com/problems/maximum-nesting-depth-of-two-valid-parentheses-strings/discuss/358419/Confused-by-this-problem-I-was-too-%3A(-Here-is-how-it-became-crystal-clear...
# Some examples:
#
# "(())" can be grouped into A = "()" and B = "()" or, A = "" and B = "(())", but, for example, not A = "((" and B = "))" as those are not VPS
# "(())()" can be grouped into A = "(())" and B = "()", and many other ways
# However, the goal is to minimize the max depth of both groups.
#
# In the last example ("(())()"), the grouping (A = "(())" and B = "()") is not minimal, because A has a max-depth of 2 while there exists a grouping where both only have a depth of 1, namely: A = ()() and B = (), or to visualize the designation:
#
# parentheses = [ (, (, ), ), (, )]
# depths = [ 1, 2, 2, 1, 1, 1 ]
# groups = [ A, B, B, A, A, A]
# solution = [ 0, 1, 1, 0, 0, 0]
#
# Cut any stack in half while making sure that the resulting half-stacks are
# balanced VPS. There are many ways of doing that, but one of the easiest (
# and seemingly a very common) approach is the odd/even strategy:
Expand Down
Loading

0 comments on commit 0b726b1

Please sign in to comment.