();
9 | }
10 |
11 | public void addNum(int num) {
12 | if (firstHalf.size() == 0 || num <= firstHalf.peek()) {
13 | firstHalf.add(num);
14 | if (firstHalf.size() > secondHalf.size() + 1)
15 | secondHalf.add(firstHalf.poll());
16 | } else {
17 | secondHalf.add(num);
18 | if (secondHalf.size() > firstHalf.size())
19 | firstHalf.add(secondHalf.poll());
20 | }
21 | }
22 |
23 | public double findMedian() {
24 | if (firstHalf.size() > secondHalf.size()) {
25 | return 1.0 * firstHalf.peek();
26 | } else {
27 | double sum = firstHalf.peek() + secondHalf.peek();
28 | return sum / 2;
29 | }
30 | }
31 | }
32 |
33 | /**
34 | * Your MedianFinder object will be instantiated and called as such:
35 | * MedianFinder obj = new MedianFinder();
36 | * obj.addNum(num);
37 | * double param_2 = obj.findMedian();
38 | */
--------------------------------------------------------------------------------
/295-find-median-from-data-stream/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/3-longest-substring-without-repeating-characters/3-longest-substring-without-repeating-characters.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def lengthOfLongestSubstring(self, str1: str) -> int:
3 | d = {}
4 | startwindow = 0
5 | longest = 0
6 |
7 | for i in range(len(str1)):
8 | right = str1[i]
9 | if right in d:
10 | startwindow = max(startwindow, d[right] + 1)
11 | d[right] = i
12 | longest = max(longest, i - startwindow + 1)
13 |
14 | return longest
15 |
--------------------------------------------------------------------------------
/3-longest-substring-without-repeating-characters/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/30-substring-with-concatenation-of-all-words/30-substring-with-concatenation-of-all-words.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findSubstring(self, s: str, words: List[str]) -> List[int]:
3 | if len(words) == 0 or len(words[0]) == 0:
4 | return []
5 | result = []
6 | word_freq = {}
7 | for w in words:
8 | if w not in word_freq:
9 | word_freq[w] = 0
10 | word_freq[w] += 1
11 | count = len(words)
12 | length = len(words[0])
13 | for i in range((len(s) - count * length)+1):
14 | seen = {}
15 | for j in range(count):
16 | next_index = i + j * length
17 | word = s[next_index: next_index + length]
18 |
19 | if word not in word_freq: break
20 | if word not in seen:
21 | seen[word] = 0
22 | seen[word] += 1
23 | if seen[word] > word_freq.get(word, 0): break
24 | if j+1 == count: result.append(i)
25 |
26 |
27 | return result
--------------------------------------------------------------------------------
/30-substring-with-concatenation-of-all-words/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/303-range-sum-query-immutable/303-range-sum-query-immutable.py:
--------------------------------------------------------------------------------
1 | class NumArray:
2 |
3 | def __init__(self, nums: List[int]):
4 | self.nums = nums
5 |
6 | def sumRange(self, left: int, right: int) -> int:
7 | i = left
8 | n = right
9 | summ = 0
10 | while i <= n:
11 | summ += self.nums[i]
12 | i+= 1
13 | return summ
14 |
15 |
16 | # Your NumArray object will be instantiated and called as such:
17 | # obj = NumArray(nums)
18 | # param_1 = obj.sumRange(left,right)
--------------------------------------------------------------------------------
/303-range-sum-query-immutable/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/304-range-sum-query-2d-immutable/304-range-sum-query-2d-immutable.py:
--------------------------------------------------------------------------------
1 | class NumMatrix:
2 |
3 | def __init__(self, matrix: List[List[int]]):
4 | m = len(matrix)
5 | n = len(matrix[0])
6 |
7 | self.prefix = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
8 | for i in range(1,m+1):
9 | for j in range(1,n+1):
10 | self.prefix[i][j] = self.prefix[i-1][j] + self.prefix[i][j-1] + matrix[i-1][j-1] - self.prefix[i-1][j-1]
11 |
12 |
13 | def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
14 | return self.prefix[row2+1][col2+1] - self.prefix[row1][col2+1] - self.prefix[row2+1][col1] + self.prefix[row1][col1]
15 |
16 |
17 | # Your NumMatrix object will be instantiated and called as such:
18 | # obj = NumMatrix(matrix)
19 | # param_1 = obj.sumRegion(row1,col1,row2,col2)
--------------------------------------------------------------------------------
/304-range-sum-query-2d-immutable/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/326-power-of-three/326-power-of-three.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isPowerOfThree(self, n: int) -> bool:
3 | if n < 0:
4 | return False
5 | if n == 1 or n == 3:
6 | return True
7 |
8 | if n > 3:
9 | n = n / 3
10 | return self.isPowerOfThree(n)
11 | else:
12 | return False
13 |
--------------------------------------------------------------------------------
/326-power-of-three/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/326-power-of-three/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer n
, return true
if it is a power of three. Otherwise, return false
.
2 |
3 |
An integer n
is a power of three, if there exists an integer x
such that n == 3x
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: n = 27
9 | Output: true
10 |
11 |
12 |
Example 2:
13 |
14 |
Input: n = 0
15 | Output: false
16 |
17 |
18 |
Example 3:
19 |
20 |
Input: n = 9
21 | Output: true
22 |
23 |
24 |
25 |
Constraints:
26 |
27 |
28 | -231 <= n <= 231 - 1
29 |
30 |
31 |
32 |
Follow up: Could you solve it without loops/recursion?
--------------------------------------------------------------------------------
/33-search-in-rotated-sorted-array/33-search-in-rotated-sorted-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def search(self, nums: List[int], target: int) -> int:
3 | for i in nums:
4 | if i == target:
5 | return nums.index(i)
6 | return -1
7 |
--------------------------------------------------------------------------------
/33-search-in-rotated-sorted-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/34-find-first-and-last-position-of-element-in-sorted-array/34-find-first-and-last-position-of-element-in-sorted-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchRange(self, nums: List[int], target: int) -> List[int]:
3 | for i in range(len(nums)):
4 | if nums[i] == target:
5 | start = i
6 | while i+1 < len(nums) and nums[i+1] == target:
7 | i+= 1
8 | return[start, i]
9 | return [-1, -1]
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/34-find-first-and-last-position-of-element-in-sorted-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/342-power-of-four/342-power-of-four.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isPowerOfFour(self, n: int) -> bool:
3 | #Negative
4 | if n < 0:
5 | return False
6 | #Base Case
7 | if n == 1 or n == 4:
8 | return True
9 | #Recursive
10 | elif n > 4:
11 | n = n / 4
12 | return self.isPowerOfFour(n)
13 | else:
14 | return False
15 |
16 | #Complixity = lg(n)
17 | #Space = lg(n)
--------------------------------------------------------------------------------
/342-power-of-four/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/344-reverse-string/344-reverse-string.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseString(self, s: List[str]) -> None:
3 | """
4 | Do not return anything, modify s in-place instead.
5 | """
6 | i = 0
7 | j = len(s) - 1
8 | while i < j :
9 | s[i], s[j] = s[j], s[i]
10 | i += 1
11 | j -= 1
12 |
13 |
--------------------------------------------------------------------------------
/344-reverse-string/README.md:
--------------------------------------------------------------------------------
1 | Easy
Write a function that reverses a string. The input string is given as an array of characters s
.
2 |
3 |
You must do this by modifying the input array in-place with O(1)
extra memory.
4 |
5 |
6 |
Example 1:
7 |
Input: s = ["h","e","l","l","o"]
8 | Output: ["o","l","l","e","h"]
9 |
Example 2:
10 |
Input: s = ["H","a","n","n","a","h"]
11 | Output: ["h","a","n","n","a","H"]
12 |
13 |
14 |
Constraints:
15 |
16 |
20 |
--------------------------------------------------------------------------------
/349-intersection-of-two-arrays/349-intersection-of-two-arrays.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
3 | l = []
4 | a = 0
5 | b = 0
6 | if len(nums1) > len(nums2):
7 | a = len(nums1)
8 | else:
9 | b = len(nums2)
10 |
11 | if a:
12 | for it in nums2:
13 | if it in nums1:
14 | l.append(it)
15 | nums1.remove(it)
16 | else:
17 | for it in nums1:
18 | if it in nums2:
19 | l.append(it)
20 | nums2.remove(it)
21 |
22 |
23 | return list(set(l))
24 |
--------------------------------------------------------------------------------
/349-intersection-of-two-arrays/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/349-intersection-of-two-arrays/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: nums1 = [1,2,2,1], nums2 = [2,2]
7 | Output: [2]
8 |
9 |
10 |
Example 2:
11 |
12 |
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
13 | Output: [9,4]
14 | Explanation: [4,9] is also accepted.
15 |
16 |
17 |
18 |
Constraints:
19 |
20 |
21 | 1 <= nums1.length, nums2.length <= 1000
22 | 0 <= nums1[i], nums2[i] <= 1000
23 |
24 |
--------------------------------------------------------------------------------
/35-search-insert-position/35-search-insert-position.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchInsert(self, nums: List[int], target: int) -> int:
3 | low = 0
4 | high = len(nums) - 1
5 | mid = (low + high) // 2
6 | while low <= high:
7 | if target < nums[mid]:
8 | high = mid - 1
9 | elif target > nums[mid]:
10 | low = mid + 1
11 | elif target == nums[mid]:
12 | return mid
13 | mid = (low + high) // 2
14 | return mid + 1
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/35-search-insert-position/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/392-is-subsequence/392-is-subsequence.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isSubsequence(self, s: str, t: str) -> bool:
3 | n = len(s)
4 | m = len(t)
5 |
6 | if n == 0:
7 | return True
8 | if m == 0:
9 | return False
10 |
11 | if s[n-1] == t[m-1]:
12 | return self.isSubsequence(s[:n-1], t[:m-1])
13 | return self.isSubsequence(s[:n], t[:m-1])
14 |
15 |
--------------------------------------------------------------------------------
/4-median-of-two-sorted-arrays/4-median-of-two-sorted-arrays.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchInsert(self, nums: List[int], target: int,priority) -> int:
3 | low = 0
4 | high = len(nums) - 1
5 | mid = (low + high) // 2
6 | while low <= high:
7 | if target < nums[mid]:
8 | high = mid - 1
9 | elif target > nums[mid]:
10 | low = mid + 1
11 | elif target == nums[mid]:
12 | if priority:
13 | low = mid +1
14 | else:
15 | high = mid -1
16 | mid = (low + high) // 2
17 | return mid + 1
18 |
19 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
20 | n = len(nums1) + len(nums2)
21 | needed = []
22 | med = []
23 | needed.append(n // 2)
24 | if n % 2 == 0:
25 | needed.append(n // 2 - 1)
26 | for i in range(len(nums1)):
27 | m = i + self.searchInsert(nums2, nums1[i],True)
28 | if m in needed:
29 | needed.remove(m)
30 | med.append(nums1[i])
31 | for i in range(len(nums2)):
32 | m = i + self.searchInsert(nums1, nums2[i],False)
33 | if m in needed:
34 | needed.remove(m)
35 | med.append(nums2[i])
36 | return sum(med) / len(med)
37 |
--------------------------------------------------------------------------------
/4-median-of-two-sorted-arrays/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/409-longest-palindrome/409-longest-palindrome.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def longestPalindrome(self, s: str) -> int:
3 | #longest palindrome length = number of even repeated + number of the max(odd)
4 | d = {}
5 | mx = 0
6 | sm = 0
7 | odd = False
8 |
9 | if len(s) == 2 and s[0] == s[1]:
10 | return len(s)
11 | elif len(s) == 1 or len(s) == 2:
12 | return 1
13 |
14 | for k in s:
15 | if k not in d:
16 | d[k] = 1
17 | else:
18 | d[k] += 1
19 |
20 | for v in d.values():
21 | if v % 2 == 0:
22 | sm += v
23 | else:
24 | mx = max(mx, v) #mx = 3
25 | sm += v - 1
26 | odd = True
27 | if not odd:
28 | return sm
29 | return sm + 1
30 |
--------------------------------------------------------------------------------
/409-longest-palindrome/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/41-first-missing-positive/41-first-missing-positive.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def firstMissingPositive(self, nums: List[int]) -> int:
3 | d = {}
4 | for i in nums:
5 | if i not in d:
6 | d[i] = 1
7 |
8 | a = 1
9 | while True:
10 | v = d.get(a, -1)
11 | if v == -1: #not here
12 | return a
13 | a+= 1
--------------------------------------------------------------------------------
/41-first-missing-positive/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/41-first-missing-positive/README.md:
--------------------------------------------------------------------------------
1 | Hard
Given an unsorted integer array nums
, return the smallest missing positive integer.
2 |
3 |
You must implement an algorithm that runs in O(n)
time and uses constant extra space.
4 |
5 |
6 |
Example 1:
7 |
Input: nums = [1,2,0]
8 | Output: 3
9 |
Example 2:
10 |
Input: nums = [3,4,-1,1]
11 | Output: 2
12 |
Example 3:
13 |
Input: nums = [7,8,9,11,12]
14 | Output: 1
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | 1 <= nums.length <= 5 * 105
21 | -231 <= nums[i] <= 231 - 1
22 |
23 |
--------------------------------------------------------------------------------
/412-fizz-buzz/412-fizz-buzz.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def fizzBuzz(self, n: int) -> List[str]:
3 | l = []
4 | for i in range(1, n+1):
5 | if i % 3 == 0 and i % 5 == 0:
6 | l.append("FizzBuzz")
7 | elif i % 3 ==0:
8 | l.append("Fizz")
9 | elif i % 5 == 0:
10 | l.append("Buzz")
11 | else:
12 | l.append(str(i))
13 | return l
14 |
--------------------------------------------------------------------------------
/414-third-maximum-number/414-third-maximum-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def thirdMax(self, nums: List[int]) -> int:
3 | l = sorted(nums)
4 | k = []
5 | for i in l:
6 | if i not in k:
7 | k.append(i)
8 | if len(k) < 3:
9 | return k[-1]
10 | else:
11 | return k[-3]
12 |
--------------------------------------------------------------------------------
/414-third-maximum-number/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/417-pacific-atlantic-water-flow/417-pacific-atlantic-water-flow.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def pacificAtlantic(self, height: List[List[int]]) -> List[List[int]]:
3 | n = len(height) #rows
4 | m = len(height[0]) #cols
5 | pac = set()
6 | atle = set()
7 |
8 |
9 | def dfs_helper(i, j, visited, prev):
10 | try:
11 | cur = height[i][j]
12 | except:
13 | pass
14 |
15 |
16 | #check the coordinations
17 | if (j < 0) or (i < 0) or j == m or i == n or (cur < prev) or (i, j) in visited:
18 | return
19 | #add the pair to visit
20 | visited.add((i, j))
21 | #check neighbor
22 | dfs_helper(i,j+1,visited,cur)
23 | dfs_helper(i,j-1,visited,cur)
24 | dfs_helper(i+1,j,visited,cur)
25 | dfs_helper(i-1,j,visited,cur)
26 |
27 |
28 | #check top and bottom rows
29 | for c in range(m):
30 | dfs_helper(0, c, pac, height[0][c])
31 | dfs_helper(n-1, c, atle, height[n-1][c])
32 | #check left and right cols
33 | for r in range(n):
34 | dfs_helper(r, 0, pac, height[r][0])
35 | dfs_helper(r, m-1, atle, height[r][m-1])
36 |
37 | winner = []
38 | #announce the winners
39 | for row in range(n):
40 | for col in range(m):
41 | if (row, col) in pac and (row, col) in atle:
42 | winner.append((row, col))
43 |
44 | return winner
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/417-pacific-atlantic-water-flow/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/424-longest-repeating-character-replacement/424-longest-repeating-character-replacement.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def characterReplacement(self, s: str, k: int) -> int:
3 | d = {}
4 | longest, max_repeat, start = 0, 0, 0
5 | for end in range(len(s)):
6 | right = s[end]
7 | if right not in d:
8 | d[right] = 0
9 | d[right] += 1
10 |
11 | max_repeat = max(max_repeat, d[right])
12 | if (end - start - max_repeat + 1) > k:
13 | left = s[start]
14 | d[left] -= 1
15 | start += 1
16 |
17 | longest = max(longest, end - start + 1)
18 | return longest
--------------------------------------------------------------------------------
/424-longest-repeating-character-replacement/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/437-path-sum-iii/437-path-sum-iii.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
9 | self.total = 0
10 | def helper(node, cur):
11 | if not node:
12 | return
13 | helper(node.right, cur + node.val)
14 | helper(node.left, cur + node.val)
15 | if cur + node.val == targetSum: self.total += 1
16 | def dfs(node):
17 | if not node: return
18 | helper(node, 0)
19 | dfs(node.left)
20 | dfs(node.right)
21 | dfs(root)
22 | return self.total
23 |
24 |
--------------------------------------------------------------------------------
/437-path-sum-iii/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/437-path-sum-iii/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given the root
of a binary tree and an integer targetSum
, return the number of paths where the sum of the values along the path equals targetSum
.
2 |
3 |
The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
9 | Output: 3
10 | Explanation: The paths that sum to 8 are shown.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
16 | Output: 3
17 |
18 |
19 |
20 |
Constraints:
21 |
22 |
23 | - The number of nodes in the tree is in the range
[0, 1000]
.
24 | -109 <= Node.val <= 109
25 | -1000 <= targetSum <= 1000
26 |
27 |
--------------------------------------------------------------------------------
/438-find-all-anagrams-in-a-string/438-find-all-anagrams-in-a-string.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findAnagrams(self, str1: str, pattern: str) -> List[int]:
3 | result_indexes = []
4 | d = {}
5 | start, matched = 0, 0
6 | for p in pattern:
7 | if p not in d:
8 | d[p] = 0
9 | d[p] += 1
10 |
11 | for end in range(len(str1)):
12 | right = str1[end]
13 | if right in d:
14 | d[right] -= 1
15 | if d[right] == 0:
16 | matched += 1
17 |
18 | if matched == len(d): result_indexes.append(start)
19 |
20 | #Shrinking the window
21 | if end >= len(pattern) - 1: #need to move
22 | left = str1[start]
23 | start += 1
24 | if left in d:
25 | if d[left] == 0:
26 | matched -= 1
27 | d[left] += 1
28 |
29 | return result_indexes
--------------------------------------------------------------------------------
/438-find-all-anagrams-in-a-string/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/442-find-all-duplicates-in-an-array/442-find-all-duplicates-in-an-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findDuplicates(self, nums: List[int]) -> List[int]:
3 | nums.sort()
4 | arr = []
5 | for i in range(1, len(nums)):
6 | if nums[i-1] == nums[i]:
7 | arr.append(nums[i-1])
8 | return set(arr)
--------------------------------------------------------------------------------
/442-find-all-duplicates-in-an-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/448-find-all-numbers-disappeared-in-an-array/448-find-all-numbers-disappeared-in-an-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
3 | a = set(nums)
4 | l = [i for i in range(1, len(nums)+1)]
5 | arr = []
6 | for i in range(len(nums)):
7 | if l[i] not in a:
8 | arr.append(l[i])
9 | return arr
10 |
--------------------------------------------------------------------------------
/448-find-all-numbers-disappeared-in-an-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/448-find-all-numbers-disappeared-in-an-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array nums
of n
integers where nums[i]
is in the range [1, n]
, return an array of all the integers in the range [1, n]
that do not appear in nums
.
2 |
3 |
4 |
Example 1:
5 |
Input: nums = [4,3,2,7,8,2,3,1]
6 | Output: [5,6]
7 |
Example 2:
8 |
Input: nums = [1,1]
9 | Output: [2]
10 |
11 |
12 |
Constraints:
13 |
14 |
15 | n == nums.length
16 | 1 <= n <= 105
17 | 1 <= nums[i] <= n
18 |
19 |
20 |
21 |
Follow up: Could you do it without extra space and in O(n)
runtime? You may assume the returned list does not count as extra space.
22 |
--------------------------------------------------------------------------------
/451-sort-characters-by-frequency/451-sort-characters-by-frequency.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def frequencySort(self, s: str) -> str:
3 | t = ""
4 | d = {}
5 | for c in s:
6 | if c not in d.keys():
7 | d[c] = 1
8 | else:
9 | d[c] += 1
10 |
11 | d = dict(sorted(d.items(), key=lambda item: item[1], reverse = True))
12 | for k, v in d.items():
13 | t+= k*v
14 |
15 | return t
16 |
--------------------------------------------------------------------------------
/451-sort-characters-by-frequency/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/457-circular-array-loop/457-circular-array-loop.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def find_index(self, arr, is_forward, current_index):
3 | direction = arr[current_index]>= 0
4 | if is_forward != direction:
5 | return -1
6 | next_index = (current_index + arr[current_index]) % len(arr)
7 | if next_index == current_index:
8 | next_index = -1
9 |
10 | return next_index
11 |
12 | def circularArrayLoop(self, nums: List[int]) -> bool:
13 | for i in range(len(nums)):
14 | is_forward = nums[i] >= 0
15 | slow, fast = i, i
16 | while True:
17 | slow = self.find_index(nums, is_forward, slow)
18 | fast = self.find_index(nums, is_forward, fast)
19 | if fast != -1:
20 | fast = self.find_index(nums, is_forward, fast)
21 | if fast == -1 or slow == fast or slow == -1:
22 | break
23 | if fast == slow and slow != -1:
24 | return True
25 | return False
26 |
27 |
--------------------------------------------------------------------------------
/457-circular-array-loop/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/46-permutations/46-permutations.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def permute(self, nums: List[int]) -> List[List[int]]:
3 | ans=[]
4 | if len(nums)==1:
5 | return [list(nums)]
6 |
7 | for i in range(len(nums)):
8 | n=nums.pop(0)
9 | li=self.permute(nums)
10 | for j in li:
11 | j.append(n)
12 | ans.extend(li)
13 | nums.append(n)
14 | return ans
--------------------------------------------------------------------------------
/46-permutations/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/46-permutations/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an array nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
2 |
3 |
4 |
Example 1:
5 |
Input: nums = [1,2,3]
6 | Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
7 |
Example 2:
8 |
Input: nums = [0,1]
9 | Output: [[0,1],[1,0]]
10 |
Example 3:
11 |
Input: nums = [1]
12 | Output: [[1]]
13 |
14 |
15 |
Constraints:
16 |
17 |
18 | 1 <= nums.length <= 6
19 | -10 <= nums[i] <= 10
20 | - All the integers of
nums
are unique.
21 |
22 |
--------------------------------------------------------------------------------
/463-island-perimeter/463-island-perimeter.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def islandPerimeter(self, grid: List[List[int]]) -> int:
3 | n = len(grid)
4 | m = len(grid[0])
5 | prem = 0
6 | grid = [[0]*m] + grid + [[0]*m] #add rows of only zeros at top and bottom of grid
7 | for i in range(n+2):
8 | grid[i] = [0]+grid[i]+[0]
9 |
10 |
11 | for r in range(1, n+1):
12 | for c in range(1, m+1):
13 | if grid[r][c] == 1:
14 | #check corners
15 | if not grid[r-1][c]: prem += 1
16 | if not grid[r+1][c]: prem += 1
17 | if not grid[r][c-1]: prem += 1
18 | if not grid[r][c+1]: prem += 1
19 | return prem
20 |
21 |
--------------------------------------------------------------------------------
/49-group-anagrams/49-group-anagrams.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
3 | d = {} #key and list
4 | for i in strs:
5 | s = ''.join(sorted(i))
6 | if s not in d.keys():
7 | d[s] = [i]
8 | else:
9 | d[s] += [i]
10 |
11 | return list(d.values())
12 |
13 |
14 |
--------------------------------------------------------------------------------
/49-group-anagrams/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/50-powx-n/50-powx-n.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def myPow(self, x: float, n: int) -> float:
3 | return x**n
--------------------------------------------------------------------------------
/50-powx-n/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/500-keyboard-row/500-keyboard-row.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findWords(self, words: List[str]) -> List[str]:
3 | r1 = "qwertyuiop"
4 | r2 = "asdfghjkl"
5 | r3 = "zxcvbnm"
6 | l = []
7 | for k in words:
8 | c1, c2, c3 = 0,0,0
9 | i = k.lower()
10 | for j in i:
11 | if j in r1:
12 | c1 += 1
13 | elif j in r2:
14 | c2 += 1
15 | elif j in r3:
16 | c3 += 1
17 | if c1 == len(k) or c2 == len(k) or c3 == len(k):
18 | l.append(k)
19 | return l
--------------------------------------------------------------------------------
/500-keyboard-row/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/509-fibonacci-number/509-fibonacci-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def fib(self, n: int) -> int:
3 | if n == 0:
4 | return 0
5 | elif n == 1:
6 | return 1
7 | else:
8 | return self.fib(n-1) + self.fib(n-2)
--------------------------------------------------------------------------------
/515-find-largest-value-in-each-tree-row/515-find-largest-value-in-each-tree-row.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def largestValues(self, root: Optional[TreeNode]) -> List[int]:
9 | result = []
10 | level = [root]
11 | while any(level):
12 | result.append(max([node.val for node in level]))
13 | new_level = []
14 | for node in level:
15 | if node.left:
16 | new_level.append(node.left)
17 | if node.right:
18 | new_level.append(node.right)
19 | level = new_level
20 | return result
--------------------------------------------------------------------------------
/515-find-largest-value-in-each-tree-row/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/515-find-largest-value-in-each-tree-row/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given the root
of a binary tree, return an array of the largest value in each row of the tree (0-indexed).
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: root = [1,3,2,5,3,null,9]
7 | Output: [1,3,9]
8 |
9 |
10 |
Example 2:
11 |
12 |
Input: root = [1,2,3]
13 | Output: [1,3]
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | - The number of nodes in the tree will be in the range
[0, 104]
.
21 | -231 <= Node.val <= 231 - 1
22 |
23 |
--------------------------------------------------------------------------------
/53-maximum-subarray/53-maximum-subarray.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxSubArray(self, nums: List[int]) -> int:
3 | w = 0
4 | s = float('-inf')
5 | i = 0
6 | while i < len(nums):
7 | w += nums[i]
8 | s = max(s, w)
9 | w = max(w, 0)
10 |
11 | i += 1
12 | return s
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/53-maximum-subarray/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/532-k-diff-pairs-in-an-array/532-k-diff-pairs-in-an-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findPairs(self, nums: List[int], k: int) -> int:
3 | d = {}
4 | p = 0
5 | r = []
6 | #save the unique
7 | for i in nums:
8 | if i not in d.keys():
9 | d[i] = 1
10 | else:
11 | d[i] += 1
12 | r.append(i)
13 | if k == 0:
14 | return len(set(r))
15 | #check
16 | for s in d.keys():
17 | if (s+k) in d.keys() and (s+k) != s:
18 | p+=1
19 | return p
20 |
--------------------------------------------------------------------------------
/532-k-diff-pairs-in-an-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/543-diameter-of-binary-tree/543-diameter-of-binary-tree.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
9 | res = [0]
10 | def dfs(node):
11 | if not node: return -1
12 | left = dfs(node.left)
13 | right = dfs(node.right)
14 | res[0] = max(res[0], 2 + left + right)
15 |
16 | return 1 + max(left, right)
17 | dfs(root)
18 | return res[0]
--------------------------------------------------------------------------------
/543-diameter-of-binary-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/547-number-of-provinces/547-number-of-provinces.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findCircleNum(self, isConnected: List[List[int]]) -> int:
3 | def dfs(a):
4 | visited.add(a)
5 | for b in range(len(isConnected)):
6 | if b not in visited and isConnected[a][b]:
7 | dfs(b)
8 |
9 |
10 | prov = 0
11 | visited = set()
12 | for a in range(len(isConnected)): #row by row
13 | if a not in visited:
14 | prov += 1
15 | dfs(a)
16 |
17 | return prov
18 |
--------------------------------------------------------------------------------
/547-number-of-provinces/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/56-merge-intervals/56-merge-intervals.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]:
3 | l = []
4 | #sorting
5 | intervals.sort(key = lambda x: x[0])
6 | s, e = intervals[0]
7 |
8 | for i in range(1, len(intervals)):
9 | if s <= intervals[i][0] <= e or s <= intervals[i][1] <= e:
10 | s, e = [min(s, intervals[i][0]), max(e, intervals[i][1])]
11 | continue
12 |
13 | l.append([s, e])
14 | s, e = intervals[i]
15 | l.append([s, e])
16 | return l
--------------------------------------------------------------------------------
/56-merge-intervals/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/56-merge-intervals/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an array of intervals
where intervals[i] = [starti, endi]
, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
7 | Output: [[1,6],[8,10],[15,18]]
8 | Explanation: Since intervals [1,3] and [2,6] overlap, merge them into [1,6].
9 |
10 |
11 |
Example 2:
12 |
13 |
Input: intervals = [[1,4],[4,5]]
14 | Output: [[1,5]]
15 | Explanation: Intervals [1,4] and [4,5] are considered overlapping.
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | 1 <= intervals.length <= 104
23 | intervals[i].length == 2
24 | 0 <= starti <= endi <= 104
25 |
26 |
--------------------------------------------------------------------------------
/58-length-of-last-word/58-length-of-last-word.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def lengthOfLastWord(self, s: str) -> int:
3 | l = s.strip(" ").split(" ")
4 | return len(l[-1])
5 |
--------------------------------------------------------------------------------
/58-length-of-last-word/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/581-shortest-unsorted-continuous-subarray/581-shortest-unsorted-continuous-subarray.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findUnsortedSubarray(self, arr: List[int]) -> int:
3 | low, high = 0, len(arr) - 1
4 | # find the first number out of sorting order from the beginning
5 | while (low < len(arr) - 1 and arr[low] <= arr[low + 1]):
6 | low += 1
7 |
8 | if low == len(arr) - 1: # if the array is sorted
9 | return 0
10 |
11 | # find the first number out of sorting order from the end
12 | while (high > 0 and arr[high] >= arr[high - 1]):
13 | high -= 1
14 |
15 | # find the maximum and minimum of the subarray
16 | subarray_max = -math.inf
17 | subarray_min = math.inf
18 | for k in range(low, high+1):
19 | subarray_max = max(subarray_max, arr[k])
20 | subarray_min = min(subarray_min, arr[k])
21 |
22 | # extend the subarray to include any number which is bigger than the minimum of the subarray
23 | while (low > 0 and arr[low-1] > subarray_min):
24 | low -= 1
25 | # extend the subarray to include any number which is smaller than the maximum of the subarray
26 | while (high < len(arr)-1 and arr[high+1] < subarray_max):
27 | high += 1
28 |
29 | return high - low + 1
30 |
31 |
--------------------------------------------------------------------------------
/581-shortest-unsorted-continuous-subarray/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/60-permutation-sequence/60-permutation-sequence.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def getPermutation(self, n: int, k: int) -> str:
3 | #build permutions with memorization
4 | permutations = []
5 | unused = list(range(1, n+1))
6 | fact = [1]*(n+1) #base case
7 | for i in range(1, n+1):
8 | fact[i] = i * fact[i-1]
9 | k -= 1
10 | while n > 0:
11 | len_part = fact[n] // n
12 | i = k//len_part
13 | permutations.append(unused[i])
14 | unused.pop(i)
15 | n -= 1
16 | k %= len_part
17 | return ''.join(map(str, permutations))
18 |
--------------------------------------------------------------------------------
/60-permutation-sequence/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/637-average-of-levels-in-binary-tree/637-average-of-levels-in-binary-tree.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
9 | def avg(a):
10 | return sum(a) / len(a)
11 | result = []
12 | level = [root]
13 | av = []
14 | while any(level):
15 | result.append([node.val for node in level])
16 | new_level = []
17 | for node in level:
18 | if node.left:
19 | new_level.append(node.left)
20 | if node.right:
21 | new_level.append(node.right)
22 | level = new_level
23 | for l in result:
24 | av.append(avg(l))
25 | return av
26 |
--------------------------------------------------------------------------------
/637-average-of-levels-in-binary-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/637-average-of-levels-in-binary-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the
root
of a binary tree, return
the average value of the nodes on each level in the form of an array. Answers within
10-5
of the actual answer will be accepted.
2 |
3 |
Example 1:
4 |

5 |
Input: root = [3,9,20,null,null,15,7]
6 | Output: [3.00000,14.50000,11.00000]
7 | Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
8 | Hence return [3, 14.5, 11].
9 |
10 |
11 |
Example 2:
12 |

13 |
Input: root = [3,9,20,15,7]
14 | Output: [3.00000,14.50000,11.00000]
15 |
16 |
17 |
18 |
Constraints:
19 |
20 |
21 | - The number of nodes in the tree is in the range
[1, 104]
.
22 | -231 <= Node.val <= 231 - 1
23 |
24 |
--------------------------------------------------------------------------------
/643-maximum-average-subarray-i/643-maximum-average-subarray-i.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findMaxAverage(self, nums: List[int], k: int) -> float:
3 | arrsum, arrstart = 0, 0
4 | res = []
5 | for arrend in range(len(nums)):
6 | arrsum += nums[arrend]
7 | if arrend >= k-1:
8 | res.append(arrsum/k)
9 | arrsum -= nums[arrstart]
10 | arrstart+=1
11 | return max(res)
--------------------------------------------------------------------------------
/643-maximum-average-subarray-i/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/643-maximum-average-subarray-i/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are given an integer array nums
consisting of n
elements, and an integer k
.
2 |
3 |
Find a contiguous subarray whose length is equal to k
that has the maximum average value and return this value. Any answer with a calculation error less than 10-5
will be accepted.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [1,12,-5,-6,50,3], k = 4
9 | Output: 12.75000
10 | Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [5], k = 1
16 | Output: 5.00000
17 |
18 |
19 |
20 |
Constraints:
21 |
22 |
23 | n == nums.length
24 | 1 <= k <= n <= 105
25 | -104 <= nums[i] <= 104
26 |
27 |
--------------------------------------------------------------------------------
/645-set-mismatch/645-set-mismatch.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findErrorNums(self, nums: List[int]) -> List[int]:
3 | i = 0
4 | while i < len(nums):
5 | j = nums[i] - 1
6 | if nums[i] != nums[j]:
7 | nums[i], nums[j] = nums[j], nums[i]
8 | else:
9 | i += 1
10 |
11 |
12 | for i in range(len(nums)):
13 | if nums[i] != i + 1:
14 | return [nums[i], i+1]
15 | return [-1, -1]
16 |
17 |
--------------------------------------------------------------------------------
/645-set-mismatch/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/67-add-binary/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/69-sqrtx/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/70-climbing-stairs/70-climbing-stairs.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def climbStairs(self, n: int) -> int:
3 | one, two = 1, 1
4 | for i in range(n-1):
5 | temp = one
6 | one = one + two
7 | two = temp
8 | return one
--------------------------------------------------------------------------------
/70-climbing-stairs/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/70-climbing-stairs/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are climbing a staircase. It takes n
steps to reach the top.
2 |
3 |
Each time you can either climb 1
or 2
steps. In how many distinct ways can you climb to the top?
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: n = 2
9 | Output: 2
10 | Explanation: There are two ways to climb to the top.
11 | 1. 1 step + 1 step
12 | 2. 2 steps
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: n = 3
18 | Output: 3
19 | Explanation: There are three ways to climb to the top.
20 | 1. 1 step + 1 step + 1 step
21 | 2. 1 step + 2 steps
22 | 3. 2 steps + 1 step
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
31 |
--------------------------------------------------------------------------------
/704-binary-search/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/724-find-pivot-index/724-find-pivot-index.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def pivotIndex(self, nums: List[int]) -> int:
3 | k = 0
4 | r = sum(nums)
5 | for i in range(len(nums)):
6 | r -= nums[i]
7 | if k == r:
8 | return i
9 | k += nums[i]
10 |
11 | return -1
--------------------------------------------------------------------------------
/73-set-matrix-zeroes/73-set-matrix-zeroes.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def setZeroes(self, matrix: List[List[int]]) -> None:
3 | """
4 | Do not return anything, modify matrix in-place instead.
5 | """
6 | menna = [x[:] for x in matrix]
7 | n = len(matrix) # high
8 | m = len(matrix[0]) # width
9 |
10 | for i in range(n):
11 | for j in range(m):
12 | if menna[i][j] == 0:
13 | for k in range(n):
14 | matrix[k][j] = 0
15 | for k in range(m):
16 | matrix[i][k] = 0
17 |
--------------------------------------------------------------------------------
/73-set-matrix-zeroes/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/74-search-a-2d-matrix/74-search-a-2d-matrix.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
3 | row,col=len(matrix),len(matrix[0])
4 | low,high=0,row*col-1
5 | while(low<=high):
6 | mid=(low+high)//2
7 |
8 | num=matrix[mid//col][mid%col]
9 |
10 | if num==target:
11 | return True
12 | elif(num None:
3 | """
4 | Do not return anything, modify nums in-place instead.
5 | """
6 | for i in range(len(nums)):
7 | for j in range(len(nums)):
8 | if nums[i] < nums[j]:
9 | nums[i], nums[j] = nums[j], nums[i]
10 | return nums
11 |
--------------------------------------------------------------------------------
/75-sort-colors/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/752-open-the-lock/752-open-the-lock.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def openLock(self, deadends: List[str], target: str) -> int:
3 | if "0000" in deadends:
4 | return -1
5 |
6 | def childern(lock):
7 | res = []
8 | for i in range(4):
9 | #increment
10 | digit = str((int(lock[i]) + 1) % 10)
11 | res.append(lock[:i] + digit + lock[i+1:])
12 | #decrement
13 | digit = str((int(lock[i]) - 1 + 10) % 10)
14 | res.append(lock[:i] + digit + lock[i+1:])
15 | return res
16 |
17 | q = deque()
18 | visit = set(deadends)
19 | q.append(["0000", 0]) #lock steps
20 | while q:
21 | lock, steps = q.popleft()
22 | if lock == target:
23 | return steps
24 | for child in childern(lock):
25 | if child not in visit:
26 | visit.add(child)
27 | q.append([child, steps+1])
28 |
29 | return -1
--------------------------------------------------------------------------------
/76-minimum-window-substring/76-minimum-window-substring.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minWindow(self, s: str, t: str) -> str:
3 | start, substr, matched = 0, 0, 0
4 | d = {}
5 | min_length = len(s) + 1
6 | for i in t:
7 | if i not in d:
8 | d[i] = 0
9 | d[i] += 1
10 |
11 | for end in range(len(s)):
12 | right = s[end]
13 | if right in d:
14 | d[right] -= 1
15 | if d[right] == 0:
16 | matched += 1
17 | while matched == len(d):
18 | if min_length > end - start + 1:
19 | min_length = end - start + 1
20 | substr = start
21 |
22 | left = s[start]
23 | start += 1
24 |
25 | if left in d:
26 | if d[left] == 0:
27 | matched -= 1
28 | d[left] += 1
29 |
30 | if min_length > len(s):
31 | return ""
32 | return s[substr:substr + min_length]
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/771-jewels-and-stones/771-jewels-and-stones.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numJewelsInStones(self, jewels: str, stones: str) -> int:
3 | c = 0
4 | for i in jewels:
5 | c += stones.count(i)
6 | return c
--------------------------------------------------------------------------------
/771-jewels-and-stones/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/771-jewels-and-stones/README.md:
--------------------------------------------------------------------------------
1 | Easy
You're given strings jewels
representing the types of stones that are jewels, and stones
representing the stones you have. Each character in stones
is a type of stone you have. You want to know how many of the stones you have are also jewels.
2 |
3 |
Letters are case sensitive, so "a"
is considered a different type of stone from "A"
.
4 |
5 |
6 |
Example 1:
7 |
Input: jewels = "aA", stones = "aAAbbbb"
8 | Output: 3
9 |
Example 2:
10 |
Input: jewels = "z", stones = "ZZ"
11 | Output: 0
12 |
13 |
14 |
Constraints:
15 |
16 |
17 | 1 <= jewels.length, stones.length <= 50
18 | jewels
and stones
consist of only English letters.
19 | - All the characters of
jewels
are unique.
20 |
21 |
--------------------------------------------------------------------------------
/78-subsets/78-subsets.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def subsets(self, nums: List[int]) -> List[List[int]]:
3 | subsets = []
4 | subsets.append([])
5 | for current in nums:
6 | n = len(subsets)
7 | for i in range(n):
8 | set1 = list(subsets[i])
9 | set1.append(current)
10 | subsets.append(set1)
11 | return subsets
--------------------------------------------------------------------------------
/78-subsets/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/78-subsets/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an integer array nums
of unique elements, return all possible subsets (the power set).
2 |
3 |
The solution set must not contain duplicate subsets. Return the solution in any order.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [1,2,3]
9 | Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
10 |
11 |
12 |
Example 2:
13 |
14 |
Input: nums = [0]
15 | Output: [[],[0]]
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | 1 <= nums.length <= 10
23 | -10 <= nums[i] <= 10
24 | - All the numbers of
nums
are unique.
25 |
26 |
--------------------------------------------------------------------------------
/79-word-search/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/81-search-in-rotated-sorted-array-ii/81-search-in-rotated-sorted-array-ii.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def search(self, nums: List[int], target: int) -> bool:
3 | for i in nums:
4 | if i == target:
5 | return True
6 | return False
7 |
--------------------------------------------------------------------------------
/81-search-in-rotated-sorted-array-ii/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/83-remove-duplicates-from-sorted-list.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, val=0, next=None):
4 | # self.val = val
5 | # self.next = next
6 | class Solution:
7 | def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
8 | if head:
9 | current = head
10 | while current.next:
11 | if current.val == current.next.val:
12 | current.next = current.next.next
13 | else:
14 | current = current.next
15 | return head
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: head = [1,1,2]
7 | Output: [1,2]
8 |
9 |
10 |
Example 2:
11 |

12 |
Input: head = [1,1,2,3,3]
13 | Output: [1,2,3]
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | - The number of nodes in the list is in the range
[0, 300]
.
21 | -100 <= Node.val <= 100
22 | - The list is guaranteed to be sorted in ascending order.
23 |
24 |
--------------------------------------------------------------------------------
/836-rectangle-overlap/836-rectangle-overlap.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def isRectangleOverlap(self, rec1, rec2):
3 | # check if either rectangle is actually a line
4 | if (rec1[0] == rec1[2] or rec1[1] == rec1[3] or \
5 | rec2[0] == rec2[2] or rec2[1] == rec2[3]):
6 | # the line cannot have positive overlap
7 | return False
8 |
9 | return not (rec1[2] <= rec2[0] or # left
10 | rec1[3] <= rec2[1] or # bottom
11 | rec1[0] >= rec2[2] or # right
12 | rec1[1] >= rec2[3]) # top
--------------------------------------------------------------------------------
/841-keys-and-rooms/841-keys-and-rooms.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
3 | visited = set()
4 | stack = [0]
5 | while stack:
6 | room = stack.pop()
7 | visited.add(room)
8 | for k in rooms[room]:
9 | if k not in visited:
10 | stack.append(k)
11 | return len(visited) == len(rooms)
--------------------------------------------------------------------------------
/841-keys-and-rooms/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/841-keys-and-rooms/README.md:
--------------------------------------------------------------------------------
1 | Medium
There are n
rooms labeled from 0
to n - 1
and all the rooms are locked except for room 0
. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key.
2 |
3 |
When you visit a room, you may find a set of distinct keys in it. Each key has a number on it, denoting which room it unlocks, and you can take all of them with you to unlock the other rooms.
4 |
5 |
Given an array rooms
where rooms[i]
is the set of keys that you can obtain if you visited room i
, return true
if you can visit all the rooms, or false
otherwise.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: rooms = [[1],[2],[3],[]]
11 | Output: true
12 | Explanation:
13 | We visit room 0 and pick up key 1.
14 | We then visit room 1 and pick up key 2.
15 | We then visit room 2 and pick up key 3.
16 | We then visit room 3.
17 | Since we were able to visit every room, we return true.
18 |
19 |
20 |
Example 2:
21 |
22 |
Input: rooms = [[1,3],[3,0,1],[2],[0]]
23 | Output: false
24 | Explanation: We can not enter room number 2 since the only key that unlocks it is in that room.
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | n == rooms.length
32 | 2 <= n <= 1000
33 | 0 <= rooms[i].length <= 1000
34 | 1 <= sum(rooms[i].length) <= 3000
35 | 0 <= rooms[i][j] < n
36 | - All the values of
rooms[i]
are unique.
37 |
38 |
--------------------------------------------------------------------------------
/841-lclighter-data-idlgt257723750-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-keys-and-rooms-lclighterdiv-classlinerthreadicon-linerfirst-data-highlight-id257723750-data-bundle-id0-idlgt257723750-stylebackground-image-url-and-quot-https-profilegetlinercom-liner-service-bucket-user-photo-default-color-10-wsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div/841-lclighter-data-idlgt257723750-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-keys-and-rooms-lclighterdiv-classlinerthreadicon-linerfirst-data-highlight-id257723750-data-bundle-id0-idlgt257723750-stylebackground-image-url-and-quot-https-profilegetlinercom-liner-service-bucket-user-photo-default-color-10-wsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:
3 | visited = set()
4 | stack = collections.deque([0])
5 | while stack:
6 | room = stack.pop()
7 | visited.add(room)
8 | for k in rooms[room]:
9 | if k not in visited:
10 | stack.append(k)
11 | return len(visited) == len(rooms)
--------------------------------------------------------------------------------
/841-lclighter-data-idlgt257723750-data-bundle-id0-stylebackground-image-linear-gradienttransparent-0-transparent-calc50-4px-rgb204-242-241-calc50-4px-rgb204-242-241-100-transition-background-position-120ms-ease-in-out-0s-padding-120ms-ease-in-out-0s-background-size-100-200-background-position-initial-user-select-auto-keys-and-rooms-lclighterdiv-classlinerthreadicon-linerfirst-data-highlight-id257723750-data-bundle-id0-idlgt257723750-stylebackground-image-url-and-quot-https-profilegetlinercom-liner-service-bucket-user-photo-default-color-10-wsvg-and-quot-user-select-auto-div-classlinerthreadicon-dim-styleuser-select-auto-div-div-classlinerthreadicon-mentioned-styleuser-select-auto-div-classlinerthreadicon-mentionedimg-styleuser-select-auto-div-div-div-classlinerthreadicon-onlyme-styleuser-select-auto-div-classlinerthreadicon-onlymeimg-styleuser-select-auto-div-div-div/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/844-backspace-string-compare/844-backspace-string-compare.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def backspaceCompare(self, s: str, t: str) -> bool:
3 | def remove(s):
4 | stack = []
5 | i = 0
6 | while i < len(s):
7 | if s[i] == '#' and len(stack) > 0:
8 | stack.pop()
9 | i += 1
10 | elif s[i] == '#' and len(stack) == 0:
11 | i += 1
12 | else:
13 | stack.append(s[i])
14 | i += 1
15 | return stack
16 |
17 | return remove(s) == remove(t)
--------------------------------------------------------------------------------
/852-peak-index-in-a-mountain-array/852-peak-index-in-a-mountain-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def peakIndexInMountainArray(self, arr: List[int]) -> int:
3 | mx, mx1 = 0, 0
4 | i = 0
5 | while i < len(arr):
6 | mx = max(arr[:i+1])
7 | mx1 = max(arr[i:])
8 | if mx == mx1:
9 | return i
10 | i+= 1
11 |
--------------------------------------------------------------------------------
/860-lemonade-change/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/876-middle-of-the-linked-list/876-middle-of-the-linked-list.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, val=0, next=None):
4 | # self.val = val
5 | # self.next = next
6 | class Solution:
7 | def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
8 | s, f = head, head.next
9 | while f and f.next:
10 | s = s.next
11 | f = f.next.next
12 | if f:
13 | return s.next
14 | return s
15 |
16 |
--------------------------------------------------------------------------------
/876-middle-of-the-linked-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/876-middle-of-the-linked-list/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the head
of a singly linked list, return the middle node of the linked list.
2 |
3 |
If there are two middle nodes, return the second middle node.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: head = [1,2,3,4,5]
9 | Output: [3,4,5]
10 | Explanation: The middle node of the list is node 3.
11 |
12 |
13 |
Example 2:
14 |

15 |
Input: head = [1,2,3,4,5,6]
16 | Output: [4,5,6]
17 | Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one.
18 |
19 |
20 |
21 |
Constraints:
22 |
23 |
24 | - The number of nodes in the list is in the range
[1, 100]
.
25 | 1 <= Node.val <= 100
26 |
27 |
--------------------------------------------------------------------------------
/9-palindrome-number/9-palindrome-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isPalindrome(self, x: int) -> bool:
3 | x = str(x)
4 | i = 0
5 | j = len(x) - 1
6 | while i < j:
7 | if x[i] != x[j]:
8 | return False
9 | else:
10 | i += 1
11 | j -= 1
12 | return True
13 |
14 |
--------------------------------------------------------------------------------
/9-palindrome-number/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/904-fruit-into-baskets/904-fruit-into-baskets.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def totalFruit(self, fruits: List[int]) -> int:
3 | d = {}
4 | startwindow = 0
5 | longest = 0
6 |
7 | for i in range(len(fruits)):
8 | right = fruits[i]
9 | if right not in d:
10 | d[right] = 0
11 | d[right] += 1
12 |
13 | while len(d) > 2:
14 | left_char = fruits[startwindow]
15 | d[left_char] -= 1
16 | if d[left_char] == 0:
17 | del d[left_char]
18 | startwindow += 1
19 | longest = max(longest, i - startwindow + 1)
20 |
21 | return longest
--------------------------------------------------------------------------------
/904-fruit-into-baskets/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/912-sort-an-array/912-sort-an-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sortArray(self, nums: List[int]) -> List[int]:
3 | nums.sort()
4 | return nums
--------------------------------------------------------------------------------
/912-sort-an-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/912-sort-an-array/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an array of integers nums
, sort the array in ascending order and return it.
2 |
3 |
You must solve the problem without using any built-in functions in O(nlog(n))
time complexity and with the smallest space complexity possible.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [5,2,3,1]
9 | Output: [1,2,3,5]
10 | Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [5,1,1,2,0,0]
16 | Output: [0,0,1,1,2,5]
17 | Explanation: Note that the values of nums are not necessairly unique.
18 |
19 |
20 |
21 |
Constraints:
22 |
23 |
24 | 1 <= nums.length <= 5 * 104
25 | -5 * 104 <= nums[i] <= 5 * 104
26 |
27 |
--------------------------------------------------------------------------------
/94-binary-tree-inorder-traversal/94-binary-tree-inorder-traversal.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
9 | if not root:
10 | return []
11 | return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
--------------------------------------------------------------------------------
/94-binary-tree-inorder-traversal/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/986-interval-list-intersections/986-interval-list-intersections.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def intervalIntersection(self, firstList: List[List[int]], secondList: List[List[int]]) -> List[List[int]]:
3 | res = []
4 | a_ptr, b_ptr = 0, 0
5 | sa, sb = len(firstList), len(secondList)
6 | temp = []
7 | while a_ptr < sa and b_ptr < sb:
8 | if secondList[b_ptr][0] <= firstList[a_ptr][1] and firstList[a_ptr][0] <= secondList[b_ptr][1]:
9 | temp.append(max(firstList[a_ptr][0], secondList[b_ptr][0]))
10 | temp.append(min(firstList[a_ptr][1], secondList[b_ptr][1]))
11 | res.append(temp)
12 | temp = []
13 | if firstList[a_ptr][1] > secondList[b_ptr][1]:
14 | b_ptr += 1
15 | else:
16 | a_ptr += 1
17 | return res
--------------------------------------------------------------------------------
/986-interval-list-intersections/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/DoublyLinkedList Insertion:
--------------------------------------------------------------------------------
1 | # import requests
2 | # import mysql.connector
3 | # import pandas as pd
4 |
5 | class NodeList():
6 | def __init__(self, data):
7 | self.data = data
8 | self.next = None
9 | self.prev = None
10 |
11 | class List():
12 | def __init__(self):
13 | self.head = None
14 |
15 | def insert_h(self, vl):
16 | node = NodeList(data = vl)
17 | node.next = self.head
18 |
19 | if self.head is not None:
20 | self.head.prev = node
21 | else:
22 | self.head = node
23 |
24 | def insert_t(self, val):
25 | #create a new node
26 | node = NodeList(data = val)
27 | #Storing the original head
28 | last = self.head
29 |
30 | #Empty list
31 | if self.head is None:
32 | node.prev = None
33 | self.head = node
34 | return
35 |
36 | #reach the last node in the current list
37 | while last.next is not None:
38 | last = last.next
39 |
40 | last.next = node
41 | node.prev = last
42 |
43 |
44 |
--------------------------------------------------------------------------------
/Easy/BinarySearch:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def search(self, nums: List[int], target: int) -> int:
3 | low = 0
4 | high = len(nums) - 1
5 | while low <= high:
6 | mid = (low + high) // 2
7 | if target < nums[mid]:
8 | high = mid - 1
9 | elif target > nums[mid]:
10 | low = mid + 1
11 | elif target == nums[mid]:
12 | return nums.index(target)
13 | return -1
14 |
--------------------------------------------------------------------------------
/Easy/FirstBadVersion:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def firstBadVersion(self, n: int) -> int:
3 | high = n + 1
4 | low = 1
5 | while low <= high:
6 | mid = (low + high) // 2
7 | if isBadVersion(mid):
8 | high = mid - 1
9 | else:
10 | low = mid + 1
11 | mid = low
12 | return mid
13 |
--------------------------------------------------------------------------------
/Easy/Number of 1 Bits:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def hammingWeight(self, n: int) -> int:
3 | return len(''.join(str(bin(n)).split('0')))-1
4 |
--------------------------------------------------------------------------------
/Easy/RansomNote:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def canConstruct(self, ransomNote: str, magazine: str) -> bool:
3 | ransomNote = list(ransomNote)
4 | magazine = list(magazine)
5 | for k in ransomNote:
6 | if k not in magazine:
7 | return False
8 | else:
9 | magazine.remove(k)
10 | #ransomNote.remove(k)
11 | return True
12 |
--------------------------------------------------------------------------------
/Easy/SearchInsertPosition:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchInsert(self, nums: List[int], target: int) -> int:
3 | low = 0
4 | high = len(nums) - 1
5 | mid = (low + high) // 2
6 | while low <= high:
7 | if target < nums[mid]:
8 | high = mid - 1
9 | elif target > nums[mid]:
10 | low = mid + 1
11 | elif target == nums[mid]:
12 | return mid
13 | mid = (low + high) // 2
14 | return mid + 1
15 |
--------------------------------------------------------------------------------
/Easy/SortArrayByParty:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sortArrayByParity(self, A: List[int]) -> List[int]:
3 | le = []
4 | lo = []
5 | for i in range(len(A)):
6 | if A[i]%2 == 0:
7 | le.append(A[i])
8 | else:
9 | lo.append(A[i])
10 | return le + lo
11 |
--------------------------------------------------------------------------------
/Easy/TwoSum:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def twoSum(self, nums: List[int], target: int) -> List[int]:
3 | new = sorted(nums)
4 | i = 0
5 | j = len(nums) - 1
6 | ls = []
7 | while j > i:
8 | l = new[i]
9 | m = new[j]
10 | k = l + m
11 | if k == target:
12 | ls.append(nums.index(l))
13 | nums[nums.index(l)] = '_'
14 | ls.append(nums.index(m))
15 | return ls
16 | else:
17 | if k > target:
18 | j-=1
19 | else:
20 | i+=1
21 |
--------------------------------------------------------------------------------
/Helpful.md:
--------------------------------------------------------------------------------
1 | To Generate list of chars with numbers
2 | ```python
3 | characters = {}
4 | for character in string.ascii.lowercase:
5 | characters[character] = 0
6 |
7 | dict = {chr(ord('a') + i) : chr(ord('a') + i) for i in range(26)}
8 |
9 | ```
10 | #merge Intervals:
11 | https://leetcode.com/problems/insert-interval/
12 | https://leetcode.com/problems/non-overlapping-intervals/
13 | https://leetcode.com/problems/meeting-rooms-ii/ [course]
14 | https://leetcode.com/discuss/interview-question/396248/Facebook-or-Phone-Screen-or-Point-in-max-overlapping-intervals
15 | https://leetcode.com/discuss/interview-question/124552/minimum-number-of-train-stops
16 | https://leetcode.com/problems/maximum-profit-in-job-scheduling/
17 | https://leetcode.com/problems/employee-free-time/
18 |
19 | #Cyclic Sort
20 | https://leetcode.com/problems/find-all-duplicates-in-an-array/submissions/
21 | https://leetcode.com/problems/kth-missing-positive-number/
22 | https://leetcode.com/problems/kth-missing-positive-number/
23 |
24 | #Reverse LinkedList
25 | https://leetcode.com/problems/reverse-linked-list-ii/
26 | https://leetcode.com/problems/reverse-nodes-in-k-group/
27 |
28 | #Heaps
29 | https://leetcode.com/problems/find-median-from-data-stream/
30 | https://leetcode.com/problems/sliding-window-median/
31 | https://leetcode.com/problems/ipo/
32 | https://www.youtube.com/watch?v=e7ZYZmGImSE&ab_channel=ImranSarwar
33 | https://leetcode.com/problems/find-right-interval/
34 |
35 | #Subset
36 | https://leetcode.com/problems/subsets/
37 | https://leetcode.com/problems/subsets-ii/
38 |
39 |
40 |
--------------------------------------------------------------------------------
/hard/median-of-two-sorted-arrays.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def searchInsert(self, nums: List[int], target: int,priority) -> int:
3 | low = 0
4 | high = len(nums) - 1
5 | mid = (low + high) // 2
6 | while low <= high:
7 | if target < nums[mid]:
8 | high = mid - 1
9 | elif target > nums[mid]:
10 | low = mid + 1
11 | elif target == nums[mid]:
12 | if priority:
13 | low = mid +1
14 | else:
15 | high = mid -1
16 | mid = (low + high) // 2
17 | return mid + 1
18 |
19 | def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
20 | n = len(nums1) + len(nums2)
21 | needed = []
22 | med = []
23 | needed.append(n // 2)
24 | if n % 2 == 0:
25 | needed.append(n // 2 - 1)
26 | for i in range(len(nums1)):
27 | m = i + self.searchInsert(nums2, nums1[i],True)
28 | if m in needed:
29 | needed.remove(m)
30 | med.append(nums1[i])
31 | for i in range(len(nums2)):
32 | m = i + self.searchInsert(nums1, nums2[i],False)
33 | if m in needed:
34 | needed.remove(m)
35 | med.append(nums2[i])
36 | return sum(med) / len(med)
37 |
--------------------------------------------------------------------------------
/medium/Add Two Numbers:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, val=0, next=None):
4 | # self.val = val
5 | # self.next = next
6 |
7 | class Solution:
8 | def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
9 | a1 = ""
10 | a2 = ""
11 | while l1.next != None:
12 | a1 += str(l1.val)
13 | l1 = l1.next
14 | while l2.next != None:
15 | a2 += str(l2.val)
16 | l2 = l2.next
17 | a1 += str(l1.val)
18 | a2 += str(l2.val)
19 | a1 = a1[::-1]
20 | a2 = a2[::-1]
21 | a3 = int(a1) + int(a2)
22 | a3 = list(str(a3))
23 | x = ListNode()
24 | for i in range(0,len(a3)):
25 | if i == len(a3)-1:
26 | x.val = a3[i]
27 | else:
28 | temp = ListNode()
29 | temp.val = a3[i]
30 | temp.next = x.next
31 | x.next = temp
32 | return x
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/medium/BinaryTree_Right_Side:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
9 | result = []
10 | if root is None:
11 | return
12 |
13 | queue = deque()
14 | queue.append(root)
15 | while queue:
16 | levelSize = len(queue)
17 | count = 0
18 | # connect all nodes of this level
19 | for _ in range(levelSize):
20 | currentNode = queue.popleft()
21 | count += 1
22 | if count == levelSize:
23 | result.append(currentNode.val)
24 |
25 | # insert the children of current node in the queue
26 | if currentNode.left:
27 | queue.append(currentNode.left)
28 | if currentNode.right:
29 | queue.append(currentNode.right)
30 | return result
31 |
--------------------------------------------------------------------------------
/medium/Coin Change.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 |
3 | def __init__(self):
4 | self.ls = {0: (0, True)}
5 | def coins(self, c, a):
6 | if a in self.ls.keys():
7 | return self.ls[a]
8 | else:
9 | ans = []
10 | for i in range(len(c)):
11 | if a >= c[i]:
12 | k = self.coins(c, a - c[i])
13 | f = k[1]
14 | if f:
15 | ans.append(k[0]+1)
16 | if len(ans) == 0:
17 | self.ls[a] = (0, False)
18 | return (0, False)
19 | m = min(ans)
20 | self.ls[a] = (m, True)
21 | return (m, True)
22 |
23 | def coinChange(self, c: List[int], a: int) -> int:
24 | k = self.coins(c, a)
25 | if k[1]:
26 | return k[0]
27 | return -1
28 |
--------------------------------------------------------------------------------
/medium/Domino and Trimino:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numTilings(self, n: int) -> int:
3 | num = {}
4 | md = 1e9
5 | md += 7
6 | num[0] = 0
7 | num[1] = 1
8 | num[2] = 2
9 | num[3] = 5
10 | if n <= 3:
11 | return num[n]
12 | for i in range(4, n+1):
13 | num[i] = 2*num[i-1] + num[i-3]
14 | num[i]%=md
15 | return int(num[n])
16 |
17 |
--------------------------------------------------------------------------------
/medium/Heap_HireK:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def totalCost(self, costs: List[int], k: int, candidates: int) -> int:
3 | heap = []
4 | left = 0
5 |
6 | for i, v in enumerate(costs):
7 | if len(heap) < candidates:
8 | heap.append([costs[i], i])
9 | left = i
10 |
11 |
12 | right = len(costs)
13 | while right > left + 1 and len(heap) < candidates * 2:
14 | right -= 1
15 | heap.append([costs[right], right])
16 |
17 | res = 0
18 | heapify(heap)
19 |
20 | while k:
21 | cost, index = heappop(heap)
22 | res += cost
23 | k -= 1
24 | if index <= left:
25 | if left + 1 < right:
26 | left += 1
27 | heappush(heap,[costs[left], left])
28 | elif index >= right:
29 | if right - 1 > left:
30 | right -= 1
31 | heappush(heap, [costs[right], right])
32 |
33 |
34 | return res
35 |
--------------------------------------------------------------------------------
/number-of-provinces/number-of-provinces.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findCircleNum(self, isConnected: List[List[int]]) -> int:
3 | def dfs(a):
4 | visited.add(a)
5 | for b in range(len(isConnected)):
6 | if b not in visited and isConnected[a][b]:
7 | dfs(b)
8 |
9 |
10 | prov = 0
11 | visited = set()
12 | for a in range(len(isConnected)): #row by row
13 | if a not in visited:
14 | prov += 1
15 | dfs(a)
16 |
17 | return prov
18 |
--------------------------------------------------------------------------------