str:
+ res = ""
+ while n > 0:
+ n -= 1
+ res = chr(65 + n % 26) + res
+ n //= 26
+ return res
diff --git a/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py b/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py
new file mode 100644
index 0000000..5ae5c6f
--- /dev/null
+++ b/python/1909_Remove_One_Element_to_Make_the_Array_Strictly_Increasing.py
@@ -0,0 +1,37 @@
+class Solution:
+ def canBeIncreasing(self, nums: List[int]) -> bool:
+ # bruteforcing the whole idxes.
+ canBe = [0] * len(nums)
+
+ # choosing the idx that will be removed.
+ for bannedIdx in range(len(nums)):
+ Flag = 1
+
+ # if the bannedIdx is 0 than the startIdx will be 2.
+ # when bannedIdx is 0, idx 2 is the first element that has a previous element.
+ # In other cases, idx 1 is the one.
+ for i in range(1 if bannedIdx != 0 else 2, len(nums)):
+ # if i is bannedIdx than just skip it.
+ if i == bannedIdx:
+ continue
+
+ # if the previous element is banned.
+ # compare [i] with [i - 2]
+ if i - 1 == bannedIdx:
+ if nums[i] <= nums[i - 2]:
+ Flag = 0
+ break
+ continue
+
+ # compare [i] with [i - 1]
+ if nums[i] <= nums[i - 1]:
+ Flag = 0
+ break
+
+ # end of loop we will get Flag that has a 0 or 1 value.
+ canBe[bannedIdx] = Flag
+
+ if sum(canBe) > 0:
+ return True
+ return False
+
diff --git a/python/204_Count Primes.py b/python/204_Count_Primes.py
similarity index 96%
rename from python/204_Count Primes.py
rename to python/204_Count_Primes.py
index 4c61aa6..3f2b1c1 100644
--- a/python/204_Count Primes.py
+++ b/python/204_Count_Primes.py
@@ -17,4 +17,4 @@ def countPrimes(self, n):
for i in xrange(2, n):
if isPrime[i]:
count += 1
- return count
\ No newline at end of file
+ return count
diff --git a/python/207_Course_Schedule.py b/python/207_Course_Schedule.py
new file mode 100644
index 0000000..0388fd9
--- /dev/null
+++ b/python/207_Course_Schedule.py
@@ -0,0 +1,28 @@
+from collections import defaultdict
+
+class Solution(object):
+ # Adapted from https://youtu.be/yPldqMtg-So
+
+ def hasCycle(self, course, deps, visited, tracker):
+ visited.add(course)
+ tracker.add(course)
+ for n in deps[course]:
+ if n not in visited and self.hasCycle(n, deps, visited, tracker):
+ return True
+ if n in tracker:
+ return True
+ tracker.remove(course)
+ return False
+
+ def canFinish(self, numCourses, prerequisites):
+ deps = defaultdict(set)
+ for course, pre in prerequisites:
+ deps[pre].add(course)
+
+ visited = set()
+ for course in range(numCourses):
+ tracker = set()
+ if self.hasCycle(course, deps, visited, tracker):
+ return False
+
+ return True
diff --git a/python/2409_Count_Days_Spent_Together.py b/python/2409_Count_Days_Spent_Together.py
new file mode 100644
index 0000000..13747f1
--- /dev/null
+++ b/python/2409_Count_Days_Spent_Together.py
@@ -0,0 +1,38 @@
+class Solution:
+ def countDaysTogether(self, arriveAlice: str, leaveAlice: str, arriveBob: str, leaveBob: str) -> int:
+ # split the dates to month and day.
+ arriveAliceMonth, arriveAliceDay = map(int, arriveAlice.split("-"))
+ leaveAliceMonth, leaveAliceDay = map(int, leaveAlice.split("-"))
+ arriveBobMonth, arriveBobDay = map(int, arriveBob.split("-"))
+ leaveBobMonth, leaveBobDay = map(int, leaveBob.split("-"))
+
+ # prefixOfCalendar : initialize the calendar and in the past we will use this to convert month to day, index is 1 - based
+ # spentTogether, aliceSpent : work as cache list. and index is 1 - based
+ calendar = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
+ prefixOfCalendar = [0] * 13
+ totalDates = sum(calendar)
+ spentTogether, aliceSpent = [0] * (totalDates + 1), [0] * (totalDates + 1)
+
+ # calculate the prefix of calendar
+ for i in range(1, len(calendar)):
+ prefixOfCalendar[i] = prefixOfCalendar[i - 1] + calendar[i]
+
+ # if the string is "01-15", it can be treat as 15 days.
+ # if the string is "02-27", it can be treat as 58 days.
+ # So, it can be "prefixOfCalendar[month - 1] + day"
+ # and in the problem it includes the leaveDate so +1 need to be in .
+ arriveAliceTotal = prefixOfCalendar[arriveAliceMonth - 1] + arriveAliceDay
+ leaveAliceTotal = prefixOfCalendar[leaveAliceMonth - 1] + leaveAliceDay
+ for i in range(arriveAliceTotal, leaveAliceTotal + 1):
+ aliceSpent[i] += 1
+
+ # check the aliceSpent[i] is True.
+ # if it is, they spentTogether is True too.
+ arriveBobTotal = prefixOfCalendar[arriveBobMonth - 1] + arriveBobDay
+ leaveBobTotal = prefixOfCalendar[leaveBobMonth - 1] + leaveBobDay
+ for i in range(arriveBobTotal, leaveBobTotal + 1):
+ if aliceSpent[i]:
+ spentTogether[i] += 1
+
+ # I used list because of this sum function.
+ return sum(spentTogether)
diff --git a/python/2413_Smallest_Even_Multiple.py b/python/2413_Smallest_Even_Multiple.py
new file mode 100644
index 0000000..02b723f
--- /dev/null
+++ b/python/2413_Smallest_Even_Multiple.py
@@ -0,0 +1,15 @@
+class Solution:
+ def smallestEvenMultiple(self, n: int) -> int:
+ """
+ n : positive integer
+ return : smallest positive integer that is a multiple of both 2 and n
+ """
+ if n % 2 == 0:
+ # if n is alreay muliply by 2
+ # return itself
+ return n
+
+ # if previous condition is false
+ # n * 2 is the smallest positive integer.
+ return n * 2
+
diff --git a/python/2420_Find_All_Good_Indices.py b/python/2420_Find_All_Good_Indices.py
new file mode 100644
index 0000000..44498cc
--- /dev/null
+++ b/python/2420_Find_All_Good_Indices.py
@@ -0,0 +1,38 @@
+#2420_Find_All_Good_Indices.py
+class Solution:
+ def goodIndices(self, nums: List[int], k: int) -> List[int]:
+ # posi : count the increasing idxes
+ # nega : count the decreasing idxes
+ posi, nega = [0], [0]
+
+ for i in range(1, len(nums)):
+ diff = nums[i] - nums[i - 1]
+
+ posi.append(posi[i - 1])
+ nega.append(nega[i - 1])
+
+ # if diff show positive or negative
+ # then the value will updated
+ if diff > 0:
+ posi[i] += 1
+ elif diff < 0:
+ nega[i] += 1
+
+ # ans : count the idxes that
+ # before k element is non increasing
+ # after k element is non decreasing
+ ans = []
+ for i in range(k, len(nums) - k):
+ if i + k >= len(nums):
+ break
+
+ # check the condition with
+ # for after, nega[i + 1], nega[i + k] is the two to check
+ # for brfore, posi[i - 1], posi[i - k] is the two to check
+ if nega[i + k] - nega[i + 1] > 0:
+ continue
+ if posi[i - 1] - posi[i - k] > 0:
+ continue
+
+ ans.append(i)
+ return ans
\ No newline at end of file
diff --git a/python/2429_Minimize_XOR.py b/python/2429_Minimize_XOR.py
new file mode 100644
index 0000000..2405feb
--- /dev/null
+++ b/python/2429_Minimize_XOR.py
@@ -0,0 +1,44 @@
+class Solution:
+ def minimizeXor(self, num1: int, num2: int) -> int:
+ # remove "0b" in front of num1, num2
+ num1, num2 = bin(num1)[2:], bin(num2)[2:]
+ lenNum1, lenNum2 = len(num1), len(num2)
+ ones = num2.count("1")
+ maxLen = max(lenNum1, lenNum2)
+
+ # ans list have elements same as the maxLen
+ ans = []
+ for _ in range(maxLen):
+ ans.append("0")
+
+ # add "0" in front of the binary numbers to make indexing easier
+ for _ in range(maxLen - lenNum1):
+ num1 = "0" + num1
+
+ for _ in range(maxLen - lenNum2):
+ num2 = "0" + num2
+
+ # now make "x XOR num1" minimal
+ # fill the ans list from index "0"
+ # because XOR give 0 when the elements are same.
+ for i in range(len(num1)):
+ if num1[i] == "1" and ones:
+ ans[i] = "1"
+ ones -= 1
+
+ # if we still got "1" to fill in the ans list.
+ # "1" need to be fill from the back of ans list.
+ # to maintain the number small.
+ for i in range(len(ans) - 1, -1, -1):
+ if ones < 1:
+ break
+
+ if ans[i] == "1":
+ continue
+
+ ans[i] = "1"
+ ones -= 1
+
+ # make the ans in string
+ ans = "".join(ans)
+ return int(ans, 2)
diff --git a/python/380_Insert_Delete_GetRandom.py b/python/380_Insert_Delete_GetRandom.py
new file mode 100644
index 0000000..f222d7d
--- /dev/null
+++ b/python/380_Insert_Delete_GetRandom.py
@@ -0,0 +1,33 @@
+import random
+
+class RandomizedSet(object):
+
+ def __init__(self):
+ self.num_to_idx = {}
+ self.num_list = []
+
+ def insert(self, val):
+ if val in self.num_to_idx:
+ return False
+ else:
+ self.num_list.append(val)
+ self.num_to_idx[val] = len(self.num_list) - 1
+ return True
+
+ def remove(self, val):
+ if val not in self.num_to_idx:
+ return False
+
+ idx = self.num_to_idx[val]
+ last = self.num_list[-1]
+
+ # swap last elem to current spot so you can pop the end
+ self.num_list[idx] = last
+ self.num_list.pop()
+ self.num_to_idx[last] = idx
+ del self.num_to_idx[val]
+
+ return True
+
+ def getRandom(self):
+ return random.choice(self.num_list)
diff --git a/python/392_Is_Subsequence.py b/python/392_Is_Subsequence.py
new file mode 100644
index 0000000..5cf66c0
--- /dev/null
+++ b/python/392_Is_Subsequence.py
@@ -0,0 +1,11 @@
+class Solution:
+ def isSubsequence(self, s: str, t: str) -> bool:
+ for a in s:
+ if a in t:
+ for b in range(0, len(t)):
+ if a==t[b]:
+ t=t[b+1:]
+ break
+ else:
+ return(False)
+ return(True)
diff --git a/python/441_Arranging_Coins.py b/python/441_Arranging_Coins.py
new file mode 100644
index 0000000..eeeb750
--- /dev/null
+++ b/python/441_Arranging_Coins.py
@@ -0,0 +1,7 @@
+class Solution(object):
+ def arrangeCoins(self, n):
+ level = 0
+ while n > level:
+ level += 1
+ n -= level
+ return level
diff --git a/python/457_Circular_Array_Loop.py b/python/457_Circular_Array_Loop.py
new file mode 100644
index 0000000..1a2e2ee
--- /dev/null
+++ b/python/457_Circular_Array_Loop.py
@@ -0,0 +1,29 @@
+class Solution:
+ def circularArrayLoop(self, nums: List[int]) -> bool:
+ for i in range(len(nums)):
+ if nums[i] == 0:
+ continue
+
+ # if slow and fast pointers collide, then there exists a loop
+ slow = i
+ fast = self.index(nums, slow)
+ while nums[slow] * nums[fast] > 0 and nums[slow] * nums[self.index(nums, fast)] > 0:
+ if slow == fast and fast != self.index(nums, fast):
+ return True
+ elif slow == fast and fast == self.index(nums, fast):
+ break
+ slow = self.index(nums, slow)
+ fast = self.index(nums, self.index(nums, fast))
+
+ # set path to all 0s since it doesn't work
+ runner = i
+ value = nums[runner]
+ while nums[runner] * value > 0:
+ temp = self.index(nums, runner)
+ nums[runner] = 0
+ runner = temp
+ return False
+
+ def index(self, nums, index):
+ length = len(nums)
+ return (index + nums[index] + length) % length
diff --git a/python/485_Max_Consecutive_Ones.py b/python/485_Max_Consecutive_Ones.py
new file mode 100644
index 0000000..4d6ffc1
--- /dev/null
+++ b/python/485_Max_Consecutive_Ones.py
@@ -0,0 +1,18 @@
+class Solution(object):
+ def findMaxConsecutiveOnes(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: int
+ """
+ ans = 0
+ curr = 0
+ for n in nums:
+ if n == 1:
+ # Add 1 to curr when encounter 1
+ curr += 1
+ if curr > ans:
+ ans = curr
+ else:
+ # Add 1 to curr when encounter 1
+ curr = 0
+ return ans
diff --git a/python/509_Fibonacci_Number.py b/python/509_Fibonacci_Number.py
new file mode 100644
index 0000000..b4ddad7
--- /dev/null
+++ b/python/509_Fibonacci_Number.py
@@ -0,0 +1,30 @@
+class Solution(object):
+
+ def __init__(self):
+ self.memo = []
+ self.memo.append(0)
+ self.memo.append(1)
+
+ def fib(self, N):
+ """
+ DP with memo
+ :type N: int
+ :rtype: int
+ """
+ if N < len(self.memo):
+ return self.memo[N]
+ for i in range(len(self.memo), N + 1):
+ self.memo.append(self.memo[i - 1] + self.memo[i - 2])
+ return self.memo[N]
+
+ # def fib(self, N):
+ # """
+ # Recursively, O(n)
+ # :type N: int
+ # :rtype: int
+ # """
+ # if N == 0:
+ # return 0
+ # if N == 1:
+ # return 1
+ # return self.fib(N - 1) + self.fib(N - 2)
diff --git a/python/523_Continuous_Subarray_Sum.py b/python/523_Continuous_Subarray_Sum.py
new file mode 100644
index 0000000..d37ceeb
--- /dev/null
+++ b/python/523_Continuous_Subarray_Sum.py
@@ -0,0 +1,20 @@
+class Solution:
+ def checkSubarraySum(self, nums: List[int], k: int) -> bool:
+ # remeainders[0] = 0 is for when x == 0
+ remainders = dict()
+ remainders[0] = 0
+ pre_sum = 0
+
+ for idx, item in enumerate(nums):
+ pre_sum += item
+ remaind = pre_sum % k
+
+ # remainder doesnt exist then it has to be init
+ # if it exists, then check the prev one has the same remainder
+ if remaind not in remainders:
+ remainders[remaind] = idx + 1
+ elif remainders[remaind] < idx:
+ return True
+
+ return False
+
diff --git a/python/541_Reverse_String_II.py b/python/541_Reverse_String_II.py
new file mode 100644
index 0000000..08fcced
--- /dev/null
+++ b/python/541_Reverse_String_II.py
@@ -0,0 +1,23 @@
+class Solution:
+ def reverseStr(self, s: str, k: int) -> str:
+ N = len(s)
+ ans = ""
+ position = 0
+ while position < N:
+ nx = s[position : position + k]
+ ans = ans + nx[::-1] + s[position + k : position + 2 * k]
+ position += 2 * k
+ return ans
+
+ # def reverseStr(self, s: str, k: int) -> str:
+ # s = list(s)
+ # for i in range(0, len(s), 2*k):
+ # s[i:i+k] = reversed(s[i:i+k])
+ # return "".join(s)
+
+
+
+s1 = Solution()
+s="abcdefg"
+k=2
+print(s1.reverseStr(s,k))
diff --git a/python/665_Non-decreasing_Array.py b/python/665_Non-decreasing_Array.py
new file mode 100644
index 0000000..b2d01c2
--- /dev/null
+++ b/python/665_Non-decreasing_Array.py
@@ -0,0 +1,38 @@
+class Solution(object):
+ # def checkPossibility(self, nums):
+ # """
+ # :type nums: List[int]
+ # :rtype: bool
+ # """
+ # pos = None
+ # # Check if there are more than 2 broken point
+ # # record first index
+ # for i in range(len(nums) - 1):
+ # if nums[i] > nums[i + 1]:
+ # if pos is not None:
+ # return False
+ # pos = i
+ # if pos is None or pos == 0 or pos == len(nums) - 2:
+ # return True
+ # # Remove pos or remove pos + 1
+ # return (nums[pos - 1] <= nums[pos + 1] or nums[pos] <= nums[pos + 2])
+
+ def checkPossibility(self, nums):
+ """
+ :type nums: List[int]
+ :rtype: bool
+ """
+ # https://leetcode.com/problems/non-decreasing-array/discuss/106826/JavaC%2B%2B-Simple-greedy-like-solution-with-explanation
+ broken_num = 0
+ for i in range(len(nums) - 1):
+ if (nums[i] > nums[i + 1]):
+ broken_num += 1
+ if broken_num >= 2:
+ return False
+ if (i - 1 < 0 or nums[i - 1] <= nums[i + 1]):
+ # Remove i
+ nums[i] = nums[i + 1]
+ else:
+ # Remove i + 1
+ nums[i + 1] = nums[i]
+ return True
diff --git a/python/668_Kth_Smallest_Number_in_Multiplication_Table.py b/python/668_Kth_Smallest_Number_in_Multiplication_Table.py
new file mode 100644
index 0000000..dcfd654
--- /dev/null
+++ b/python/668_Kth_Smallest_Number_in_Multiplication_Table.py
@@ -0,0 +1,19 @@
+class Solution:
+ def findKthNumber(self, m: int, n: int, k: int) -> int:
+ # https://leetcode.com/problems/kth-smallest-number-in-multiplication-table/solution/
+ def enough(x):
+ count = 0
+ # ith row [i, 2*i, 3*i, ..., n*i]
+ # for each column, k = x // i
+ for i in range(1, m+1):
+ count += min(x // i, n)
+ return count >= k
+
+ lo, hi = 1, m * n
+ while lo < hi:
+ mi = (lo + hi) // 2
+ if not enough(mi):
+ lo = mi + 1
+ else:
+ hi = mi
+ return lo
diff --git a/python/717_1-bit_and_2-bit_Characters.py b/python/717_1-bit_and_2-bit_Characters.py
new file mode 100644
index 0000000..104441d
--- /dev/null
+++ b/python/717_1-bit_and_2-bit_Characters.py
@@ -0,0 +1,38 @@
+# We have two special characters. The first character can be represented by one bit 0. The second character can be represented by two bits (10 or 11).
+# Now given a string represented by several bits. Return whether the last character must be a one-bit character or not. The given string will always end with a zero.
+
+# Example 1:
+# Input:
+# bits = [1, 0, 0]
+# Output: True
+# Explanation:
+# The only way to decode it is two-bit character and one-bit character. So the last character is one-bit character.
+# Example 2:
+# Input:
+# bits = [1, 1, 1, 0]
+# Output: False
+# Explanation:
+# The only way to decode it is two-bit character and two-bit character. So the last character is NOT one-bit character.
+# Note:
+
+# 1 <= len(bits) <= 1000.
+# bits[i] is always 0 or 1.
+
+# https://leetcode.com/problems/1-bit-and-2-bit-characters/solution/
+class Solution:
+ def isOneBitCharacter(self, bits: List[int]) -> bool:
+ pos = 0
+ # Go through bits
+ while pos < len(bits) - 1:
+ # if 1, pos + 2; if 0, pos + 1
+ pos += bits[pos] + 1
+ return pos == len(bits) - 1
+
+ # def isOneBitCharacter(self, bits):
+ # # From len - 2
+ # pos = len(bits) - 2
+ # # until encounter 0
+ # while pos >= 0 and bits[pos] > 0:
+ # pos -= 1
+ # # check if second last zero is even
+ # return (len(bits) - pos) % 2 == 0
diff --git a/python/728_Self_Dividing_Numbers.py b/python/728_Self_Dividing_Numbers.py
new file mode 100644
index 0000000..f7e0bac
--- /dev/null
+++ b/python/728_Self_Dividing_Numbers.py
@@ -0,0 +1,7 @@
+class Solution:
+ def selfDividingNumbers(self, left: int, right: int) -> List[int]:
+ # check every digit
+ return [x for x in range(left, right+1) if all([int(i) != 0 and x % int(i)==0 for i in str(x)])]
+
+ # def selfDividingNumbers(self, left: int, right: int) -> List[int]:
+ # return [x for x in range(left, right+1) if all((i and (x % i==0) for i in map(int, str(x))))]
diff --git a/python/732_My_Calendar_III.py b/python/732_My_Calendar_III.py
new file mode 100644
index 0000000..6347108
--- /dev/null
+++ b/python/732_My_Calendar_III.py
@@ -0,0 +1,17 @@
+from sortedcontainers import SortedDict
+
+
+class MyCalendarThree:
+ def __init__(self):
+ self.timeline = SortedDict()
+
+ def book(self, start: int, end: int) -> int:
+ self.timeline[start] = self.timeline.get(start, 0) + 1
+ self.timeline[end] = self.timeline.get(end, 0) - 1
+
+ ans = 0
+ activeEvents = 0
+
+ for count in self.timeline.values():
+ activeEvents += count
+ ans = max(ans, activeEvents)
diff --git a/python/868_Binary_Gap.py b/python/868_Binary_Gap.py
new file mode 100644
index 0000000..191d3d1
--- /dev/null
+++ b/python/868_Binary_Gap.py
@@ -0,0 +1,34 @@
+class Solution:
+
+ # def binaryGap(self, n: int) -> int:
+ # # Store index
+ # A = [i for i in xrange(32) if (N >> i) & 1]
+ # if len(A) < 2: return 0
+ # return max(A[i+1] - A[i] for i in xrange(len(A) - 1))
+
+
+ def binaryGap(self, n: int) -> int:
+ # one pass and store max
+ current = 1
+ last1 = -1
+ out = 0
+ while n > 0:
+ if n % 2 == 1:
+ if last1 >= 1:
+ out = max(out, current - last1)
+ last1 = current
+ current += 1
+ n = n // 2
+ return out
+
+ # def binaryGap(self, n: int) -> int:
+ # # one pass and store max
+ # res = 0
+ # last = -1
+ # # Get binary encoding with bin
+ # for i, curr in enumerate(bin(n)[2:]):
+ # if curr == '1':
+ # if last >= 0:
+ # res = max(res, i - last)
+ # last = i
+ # return res
diff --git a/python/937_Reorder_Log_Files.py b/python/937_Reorder_Log_Files.py
new file mode 100644
index 0000000..4d2c6ba
--- /dev/null
+++ b/python/937_Reorder_Log_Files.py
@@ -0,0 +1,23 @@
+class Solution(object):
+ # def reorderLogFiles(self, logs):
+ # """
+ # :type logs: List[str]
+ # :rtype: List[str]
+ # """
+ # def f(log):
+ # id_, rest = log.split(" ", 1)
+ # return (0, rest, id_) if rest[0].isalpha() else (1,)
+
+ # # Python sort is stable, so digit with keep their order
+ # return sorted(logs, key = f)
+
+ def reorderLogFiles(self, logs):
+ letter_logs = []
+ digit_logs = []
+ for log in logs:
+ if log.split(' ')[1].isnumeric():
+ digit_logs.append(log)
+ else:
+ letter_logs.append(log)
+ return sorted(letter_logs, key=lambda x: x.split(' ')[1:] + x.split(' ')[0]) + digit_logs
+
\ No newline at end of file
diff --git a/python/973_K_Closest_Points_to_Origin.py b/python/973_K_Closest_Points_to_Origin.py
new file mode 100644
index 0000000..b8240b9
--- /dev/null
+++ b/python/973_K_Closest_Points_to_Origin.py
@@ -0,0 +1,13 @@
+class Solution(object):
+ # def kClosest(self, points, K):
+ # """
+ # :type points: List[List[int]]
+ # :type K: int
+ # :rtype: List[List[int]]
+ # """
+ # # Sort
+ # return sorted(points, key=lambda x: x[0] ** 2 + x[1] ** 2)[:K]
+
+ def kClosest(self, points, K):
+ # K smallest heaq
+ return heapq.nsmallest(K, points, key=lambda x: x[0] ** 2 + x[1] ** 2)
diff --git a/python/977_Squares_of_a_Sorted_Array.py b/python/977_Squares_of_a_Sorted_Array.py
new file mode 100644
index 0000000..3c66191
--- /dev/null
+++ b/python/977_Squares_of_a_Sorted_Array.py
@@ -0,0 +1,31 @@
+class Solution(object):
+ # def sortedSquares(self, A):
+ # """
+ # :type A: List[int]
+ # :rtype: List[int]
+ # """
+ # # Directly sort
+ # return sorted(x * x for x in A)
+
+ def sortedSquares(self, A):
+ pos = 0
+ while pos < len(A) and A[pos] < 0:
+ pos += 1
+ # pos point to first positve
+ # npos point to larget negative
+ npos = pos - 1
+ res = []
+ while pos < len(A) and npos >= 0:
+ if A[npos] ** 2 < A[pos] ** 2:
+ res.append(A[npos] ** 2)
+ npos -= 1
+ else:
+ res.append(A[pos] ** 2)
+ pos +=1
+ while npos >= 0:
+ res.append(A[npos] ** 2)
+ npos -= 1
+ while pos < len(A):
+ res.append(A[pos] ** 2)
+ pos += 1
+ return res
diff --git a/python/981_Time_Based_Store.py b/python/981_Time_Based_Store.py
new file mode 100644
index 0000000..3320458
--- /dev/null
+++ b/python/981_Time_Based_Store.py
@@ -0,0 +1,26 @@
+from collections import defaultdict
+
+class TimeMap(object):
+
+ def __init__(self):
+ self.store = defaultdict(list)
+
+ def set(self, key, value, timestamp):
+ self.store[key].append((value, timestamp))
+
+ def get(self, key, timestamp):
+ values = self.store.get(key, [])
+ res = ""
+
+ l = 0
+ r = len(values) - 1
+
+ while l <= r:
+ mid = (l + r) // 2
+ if values[mid][1] <= timestamp:
+ l = mid + 1
+ res = values[mid][0]
+ else:
+ r = mid - 1
+
+ return res
diff --git a/python/997_Find_The_Town_Judge.py b/python/997_Find_The_Town_Judge.py
new file mode 100644
index 0000000..57e8ecd
--- /dev/null
+++ b/python/997_Find_The_Town_Judge.py
@@ -0,0 +1,21 @@
+class Solution:
+ def findJudge(self, N: int, trust: List[List[int]]) -> int:
+ if N==1:
+ return 1
+ d1={}
+ d2={}
+ for i, j in trust:
+ if j in d1:
+ d1[j]+=1
+ else:
+ d1[j]=1
+ if i in d2:
+ d2[i]+=1
+ else:
+ d2[i]=1
+ for i,j in d1.items():
+ if j==N-1:
+ if i not in d2:
+ return i
+ return -1
+
pFad - Phonifier reborn
Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies:
Alternative Proxy
pFad Proxy
pFad v3 Proxy
pFad v4 Proxy