├── 0 - 1 Knapsack Problem - GFG
├── 0-1-knapsack-problem.py
└── README.md
├── 1-two-sum
├── 1-two-sum.py
├── NOTES.md
└── README.md
├── 100-same-tree
├── 100-same-tree.py
├── NOTES.md
└── README.md
├── 101-symmetric-tree
├── 101-symmetric-tree.py
├── NOTES.md
└── README.md
├── 104-maximum-depth-of-binary-tree
├── 104-maximum-depth-of-binary-tree.py
├── NOTES.md
└── README.md
├── 1046-last-stone-weight
├── 1046-last-stone-weight.py
├── NOTES.md
└── README.md
├── 110-balanced-binary-tree
├── 110-balanced-binary-tree.py
├── NOTES.md
└── README.md
├── 1108-defanging-an-ip-address
├── 1108-defanging-an-ip-address.py
├── NOTES.md
└── README.md
├── 111-minimum-depth-of-binary-tree
├── 111-minimum-depth-of-binary-tree.py
├── NOTES.md
└── README.md
├── 1143-longest-common-subsequence
├── 1143-longest-common-subsequence.py
├── NOTES.md
└── README.md
├── 1150-check-if-a-number-is-majority-element-in-a-sorted-array
├── 1150-check-if-a-number-is-majority-element-in-a-sorted-array.py
├── NOTES.md
└── README.md
├── 118-pascals-triangle
├── 118-pascals-triangle.py
├── NOTES.md
└── README.md
├── 1200-minimum-absolute-difference
├── 1200-minimum-absolute-difference.py
├── NOTES.md
└── README.md
├── 1207-unique-number-of-occurrences
├── 1207-unique-number-of-occurrences.py
├── NOTES.md
└── README.md
├── 121-best-time-to-buy-and-sell-stock
├── 121-best-time-to-buy-and-sell-stock.py
├── NOTES.md
└── README.md
├── 1249-minimum-remove-to-make-valid-parentheses
├── 1249-minimum-remove-to-make-valid-parentheses.py
├── NOTES.md
└── README.md
├── 125-valid-palindrome
├── 125-valid-palindrome.py
├── NOTES.md
└── README.md
├── 128-longest-consecutive-sequence
├── 128-longest-consecutive-sequence.py
├── NOTES.md
└── README.md
├── 1295-find-numbers-with-even-number-of-digits
├── 1295-find-numbers-with-even-number-of-digits.py
├── NOTES.md
└── README.md
├── 136-single-number
├── 136-single-number.py
├── NOTES.md
└── README.md
├── 1365-how-many-numbers-are-smaller-than-the-current-number
├── 1365-how-many-numbers-are-smaller-than-the-current-number.py
├── NOTES.md
└── README.md
├── 1389-create-target-array-in-the-given-order
├── 1389-create-target-array-in-the-given-order.py
├── NOTES.md
└── README.md
├── 14-longest-common-prefix
├── 14-longest-common-prefix.py
├── NOTES.md
└── README.md
├── 141-linked-list-cycle
├── 141-linked-list-cycle.py
├── NOTES.md
└── README.md
├── 142-linked-list-cycle-ii
├── 142-linked-list-cycle-ii.py
├── NOTES.md
└── README.md
├── 144-binary-tree-preorder-traversal
├── 144-binary-tree-preorder-traversal.py
├── NOTES.md
└── README.md
├── 1470-shuffle-the-array
├── 1470-shuffle-the-array.py
├── NOTES.md
└── README.md
├── 1480-running-sum-of-1d-array
├── 1480-running-sum-of-1d-array.py
├── NOTES.md
└── README.md
├── 151-reverse-words-in-a-string
├── 151-reverse-words-in-a-string.py
├── NOTES.md
└── README.md
├── 1512-number-of-good-pairs
├── 1512-number-of-good-pairs.py
├── NOTES.md
└── README.md
├── 1539-kth-missing-positive-number
├── 1539-kth-missing-positive-number.py
├── NOTES.md
└── README.md
├── 155-min-stack
├── 155-min-stack.py
├── NOTES.md
└── README.md
├── 160-intersection-of-two-linked-lists
├── 160-intersection-of-two-linked-lists.py
├── NOTES.md
└── README.md
├── 1662-check-if-two-string-arrays-are-equivalent
├── 1662-check-if-two-string-arrays-are-equivalent.py
├── NOTES.md
└── README.md
├── 167-two-sum-ii-input-array-is-sorted
├── 167-two-sum-ii-input-array-is-sorted.py
├── NOTES.md
└── README.md
├── 169-majority-element
├── 169-majority-element.py
├── NOTES.md
└── README.md
├── 1748-sum-of-unique-elements
├── 1748-sum-of-unique-elements.py
├── NOTES.md
└── README.md
├── 1822-sign-of-the-product-of-an-array
├── 1822-sign-of-the-product-of-an-array.py
├── NOTES.md
└── README.md
├── 1859-sorting-the-sentence
├── 1859-sorting-the-sentence.py
├── NOTES.md
└── README.md
├── 19-remove-nth-node-from-end-of-list
├── 19-remove-nth-node-from-end-of-list.py
├── NOTES.md
└── README.md
├── 1920-build-array-from-permutation
├── 1920-build-array-from-permutation.py
├── NOTES.md
└── README.md
├── 1929-concatenation-of-array
├── 1929-concatenation-of-array.py
├── NOTES.md
└── README.md
├── 2-add-two-numbers
├── 2-add-two-numbers.py
├── NOTES.md
└── README.md
├── 20-valid-parentheses
├── 20-valid-parentheses.py
├── NOTES.md
└── README.md
├── 2006-count-number-of-pairs-with-absolute-difference-k
├── 2006-count-number-of-pairs-with-absolute-difference-k.py
├── NOTES.md
└── README.md
├── 2011-final-value-of-variable-after-performing-operations
├── 2011-final-value-of-variable-after-performing-operations.py
├── NOTES.md
└── README.md
├── 206-reverse-linked-list
├── 206-reverse-linked-list.py
├── NOTES.md
└── README.md
├── 2089-find-target-indices-after-sorting-array
├── 2089-find-target-indices-after-sorting-array.py
├── NOTES.md
└── README.md
├── 2103-rings-and-rods
├── 2103-rings-and-rods.py
├── NOTES.md
└── README.md
├── 215-kth-largest-element-in-an-array
├── 215-kth-largest-element-in-an-array.py
├── NOTES.md
└── README.md
├── 217-contains-duplicate
├── 217-contains-duplicate.py
├── NOTES.md
└── README.md
├── 2176-count-equal-and-divisible-pairs-in-an-array
├── 2176-count-equal-and-divisible-pairs-in-an-array.py
└── README.md
├── 2235-add-two-integers
├── 2235-add-two-integers.py
├── NOTES.md
└── README.md
├── 226-invert-binary-tree
├── 226-invert-binary-tree.py
├── NOTES.md
└── README.md
├── 229-majority-element-ii
├── 229-majority-element-ii.py
├── NOTES.md
└── README.md
├── 232-implement-queue-using-stacks
├── 232-implement-queue-using-stacks.py
├── NOTES.md
└── README.md
├── 234-palindrome-linked-list
├── 234-palindrome-linked-list.py
├── NOTES.md
└── README.md
├── 237-delete-node-in-a-linked-list
├── 237-delete-node-in-a-linked-list.py
├── NOTES.md
└── README.md
├── 242-valid-anagram
├── 242-valid-anagram.py
├── NOTES.md
└── README.md
├── 257-binary-tree-paths
├── 257-binary-tree-paths.py
├── NOTES.md
└── README.md
├── 268-missing-number
├── 268-missing-number.py
├── NOTES.md
└── README.md
├── 278-first-bad-version
├── 278-first-bad-version.py
├── NOTES.md
└── README.md
├── 287-find-the-duplicate-number
├── 287-find-the-duplicate-number.py
├── NOTES.md
└── README.md
├── 31-next-permutation
├── 31-next-permutation.py
├── NOTES.md
└── README.md
├── 322-coin-change
├── 322-coin-change.py
├── NOTES.md
└── README.md
├── 346-moving-average-from-data-stream
├── 346-moving-average-from-data-stream.py
├── NOTES.md
└── README.md
├── 347-top-k-frequent-elements
├── 347-top-k-frequent-elements.py
├── NOTES.md
└── README.md
├── 349-intersection-of-two-arrays
├── 349-intersection-of-two-arrays.py
├── NOTES.md
└── README.md
├── 35-search-insert-position
├── 35-search-insert-position.py
├── NOTES.md
└── README.md
├── 359-logger-rate-limiter
├── 359-logger-rate-limiter.py
├── NOTES.md
└── README.md
├── 367-valid-perfect-square
├── 367-valid-perfect-square.py
├── NOTES.md
└── README.md
├── 37-sudoku-solver
├── 37-sudoku-solver.py
├── NOTES.md
└── README.md
├── 389-find-the-difference
├── 389-find-the-difference.py
├── NOTES.md
└── README.md
├── 412-fizz-buzz
├── 412-fizz-buzz.py
├── NOTES.md
└── README.md
├── 415-add-strings
├── 415-add-strings.py
├── NOTES.md
└── README.md
├── 416-partition-equal-subset-sum
├── 416-partition-equal-subset-sum.py
├── NOTES.md
└── README.md
├── 451-sort-characters-by-frequency
├── 451-sort-characters-by-frequency.py
├── NOTES.md
└── README.md
├── 48-rotate-image
├── 48-rotate-image.py
├── NOTES.md
└── README.md
├── 485-max-consecutive-ones
├── 485-max-consecutive-ones.py
├── NOTES.md
└── README.md
├── 50-powx-n
├── 50-powx-n.py
├── NOTES.md
└── README.md
├── 509-fibonacci-number
├── 509-fibonacci-number.py
├── NOTES.md
└── README.md
├── 53-maximum-subarray
├── 53-maximum-subarray.py
├── NOTES.md
└── README.md
├── 540-single-element-in-a-sorted-array
├── 540-single-element-in-a-sorted-array.py
├── NOTES.md
└── README.md
├── 543-diameter-of-binary-tree
├── 543-diameter-of-binary-tree.py
├── NOTES.md
└── README.md
├── 56-merge-intervals
├── 56-merge-intervals.py
├── NOTES.md
└── README.md
├── 572-subtree-of-another-tree
├── 572-subtree-of-another-tree.py
├── NOTES.md
└── README.md
├── 58-length-of-last-word
├── 58-length-of-last-word.py
├── NOTES.md
└── README.md
├── 589-n-ary-tree-preorder-traversal
├── 589-n-ary-tree-preorder-traversal.py
├── NOTES.md
└── README.md
├── 66-plus-one
├── 66-plus-one.py
├── NOTES.md
└── README.md
├── 69-sqrtx
├── 69-sqrtx.py
├── NOTES.md
└── README.md
├── 692-top-k-frequent-words
├── 692-top-k-frequent-words.py
├── NOTES.md
└── README.md
├── 704-binary-search
├── 704-binary-search.py
├── NOTES.md
└── README.md
├── 73-set-matrix-zeroes
├── 73-set-matrix-zeroes.py
├── NOTES.md
└── README.md
├── 74-search-a-2d-matrix
├── 74-search-a-2d-matrix.py
├── NOTES.md
└── README.md
├── 75-sort-colors
├── 75-sort-colors.py
├── NOTES.md
└── README.md
├── 818-race-car
├── 818-race-car.py
├── NOTES.md
└── README.md
├── 832-flipping-an-image
├── 832-flipping-an-image.py
├── NOTES.md
└── README.md
├── 844-backspace-string-compare
├── 844-backspace-string-compare.py
├── NOTES.md
└── README.md
├── 852-peak-index-in-a-mountain-array
├── 852-peak-index-in-a-mountain-array.py
├── NOTES.md
└── README.md
├── 876-middle-of-the-linked-list
├── 876-middle-of-the-linked-list.py
├── NOTES.md
└── README.md
├── 88-merge-sorted-array
├── 88-merge-sorted-array.py
├── NOTES.md
└── README.md
├── 905-sort-array-by-parity
├── 905-sort-array-by-parity.py
├── NOTES.md
└── README.md
├── 912-sort-an-array
├── 912-sort-an-array.py
├── NOTES.md
└── README.md
├── Coin Change - GFG
├── README.md
└── coin-change.py
├── Find minimum and maximum element in an array - GFG
├── README.md
└── find-minimum-and-maximum-element-in-an-array.py
├── Height of Binary Tree - GFG
├── README.md
└── height-of-binary-tree.py
├── Knapsack with Duplicate Items - GFG
├── README.md
└── knapsack-with-duplicate-items.py
├── Longest Common Substring - GFG
├── README.md
└── longest-common-substring.py
├── Perfect Sum Problem - GFG
├── README.md
└── perfect-sum-problem.py
├── Print adjacency list - GFG
├── README.md
└── print-adjacency-list.py
├── README.md
├── Rod Cutting - GFG
├── README.md
└── rod-cutting.py
├── set-matrix-zeroes
├── README.md
└── set-matrix-zeroes.py
├── smallest-integer-divisible-by-k
├── README.md
└── smallest-integer-divisible-by-k.py
└── two-sum
├── README.md
└── two-sum.py
/0 - 1 Knapsack Problem - GFG/0-1-knapsack-problem.py:
--------------------------------------------------------------------------------
1 | #User function Template for python3
2 |
3 | class Solution:
4 |
5 | #Function to return max value that can be put in knapsack of capacity W.
6 | def knapSack(self,W, wt, val, n):
7 | #taking a matrix of W+1 columns and n+1 rows.
8 | DP = []
9 | for row in range(n+1):
10 | columns = [-1] * (W+1)
11 | DP.append(columns)
12 |
13 | #Initialization(equivalent to the recursive code )
14 | for i in range(n+1):
15 | for j in range(W+1):
16 | if i == 0 or j == 0:
17 | DP[i][j] = 0
18 | #filling the remaining ones.
19 | for i in range(1, n+1):
20 | for j in range(1, W+1):
21 | if wt[i-1] <= j:
22 | DP[i][j] = max(val[i-1]+DP[i-1][j-wt[i-1]], DP[i-1][j])
23 | else:
24 | DP[i][j] = DP[i-1][j]
25 | return DP[n][W]
26 |
27 |
28 | #{
29 | # Driver Code Starts
30 | #Initial Template for Python 3
31 | import atexit
32 | import io
33 | import sys
34 |
35 | # Contributed by : Nagendra Jha
36 |
37 | if __name__ == '__main__':
38 | test_cases = int(input())
39 | for cases in range(test_cases):
40 | n = int(input())
41 | W = int(input())
42 | val = list(map(int,input().strip().split()))
43 | wt = list(map(int,input().strip().split()))
44 | ob=Solution()
45 | print(ob.knapSack(W,wt,val,n))
46 | # } Driver Code Ends
--------------------------------------------------------------------------------
/1-two-sum/1-two-sum.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def twoSum(self, nums: List[int], target: int) -> List[int]:
3 | D = {}
4 | D[nums[0]] = 0
5 | for n in range(1, len(nums)):
6 | diff = target - nums[n]
7 | if diff in D:
8 | return [D[diff], n]
9 | else:
10 | D[nums[n]] = n
11 |
12 |
--------------------------------------------------------------------------------
/1-two-sum/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1-two-sum/README.md:
--------------------------------------------------------------------------------
1 |
Easy
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
2 |
3 |
You may assume that each input would have exactly one solution, and you may not use the same element twice.
4 |
5 |
You can return the answer in any order.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: nums = [2,7,11,15], target = 9
11 | Output: [0,1]
12 | Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: nums = [3,2,4], target = 6
18 | Output: [1,2]
19 |
20 |
21 |
Example 3:
22 |
23 |
Input: nums = [3,3], target = 6
24 | Output: [0,1]
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 2 <= nums.length <= 104
32 | -109 <= nums[i] <= 109
33 | -109 <= target <= 109
34 | - Only one valid answer exists.
35 |
36 |
37 |
38 |
Follow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?
--------------------------------------------------------------------------------
/100-same-tree/100-same-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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
9 | if p == None and q == None:
10 | return True
11 | elif p == None and q != None:
12 | return False
13 | elif p != None and q == None:
14 | return False
15 | left = self.isSameTree(p.left, q.left)
16 | right = self.isSameTree(p.right, q.right)
17 | if (p.val == q.val) and left == True and right == True:
18 | return True
19 | return False
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/100-same-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/100-same-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the roots of two binary trees p
and q
, write a function to check if they are the same or not.
2 |
3 |
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: p = [1,2,3], q = [1,2,3]
9 | Output: true
10 |
11 |
12 |
Example 2:
13 |

14 |
Input: p = [1,2], q = [1,null,2]
15 | Output: false
16 |
17 |
18 |
Example 3:
19 |

20 |
Input: p = [1,2,1], q = [1,1,2]
21 | Output: false
22 |
23 |
24 |
25 |
Constraints:
26 |
27 |
28 | - The number of nodes in both trees is in the range
[0, 100]
.
29 | -104 <= Node.val <= 104
30 |
31 |
--------------------------------------------------------------------------------
/101-symmetric-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/101-symmetric-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: root = [1,2,2,3,4,4,3]
7 | Output: true
8 |
9 |
10 |
Example 2:
11 |

12 |
Input: root = [1,2,2,null,3,null,3]
13 | Output: false
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | - The number of nodes in the tree is in the range
[1, 1000]
.
21 | -100 <= Node.val <= 100
22 |
23 |
24 |
25 |
Follow up: Could you solve it both recursively and iteratively?
--------------------------------------------------------------------------------
/104-maximum-depth-of-binary-tree/104-maximum-depth-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 maxDepth(self, root: Optional[TreeNode]) -> int:
9 | if root is None:
10 | return 0
11 | left = self.maxDepth(root.left)
12 | right = self.maxDepth(root.right)
13 | return 1 + max(left, right)
14 |
--------------------------------------------------------------------------------
/104-maximum-depth-of-binary-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/104-maximum-depth-of-binary-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree, return its maximum depth.
2 |
3 |
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: root = [3,9,20,null,null,15,7]
9 | Output: 3
10 |
11 |
12 |
Example 2:
13 |
14 |
Input: root = [1,null,2]
15 | Output: 2
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | - The number of nodes in the tree is in the range
[0, 104]
.
23 | -100 <= Node.val <= 100
24 |
25 |
--------------------------------------------------------------------------------
/1046-last-stone-weight/1046-last-stone-weight.py:
--------------------------------------------------------------------------------
1 | import heapq as heap
2 | class Solution:
3 | def lastStoneWeight(self, stones: List[int]) -> int:
4 | for s in range(len(stones)):
5 | stones[s] = stones[s] * -1
6 | heap.heapify(stones)
7 | while len(stones) > 1:
8 | y = heap.heappop(stones) * -1
9 | x = heap.heappop(stones) * -1
10 | if x != y:
11 | heap.heappush(stones, (y-x) * -1)
12 | if len(stones) == 0:
13 | return 0
14 | return stones[0] * -1
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/1046-last-stone-weight/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/110-balanced-binary-tree/110-balanced-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 height(self, root):
9 | if root is None:
10 | return 0
11 | return 1 + max(self.height(root.left), self.height(root.right))
12 |
13 | def isBalanced(self, root: Optional[TreeNode]) -> bool:
14 | if root is None:
15 | return True
16 | l = self.isBalanced(root.left)
17 | r = self.isBalanced(root.right)
18 | left = self.height(root.left)
19 | right = self.height(root.right)
20 | if abs(left-right) <= 1 and l == True and r == True:
21 | return True
22 | return False
23 |
--------------------------------------------------------------------------------
/110-balanced-binary-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/110-balanced-binary-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a binary tree, determine if it is height-balanced.
2 |
3 |
For this problem, a height-balanced binary tree is defined as:
4 |
5 |
6 | a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
7 |
8 |
9 |
10 |
Example 1:
11 |

12 |
Input: root = [3,9,20,null,null,15,7]
13 | Output: true
14 |
15 |
16 |
Example 2:
17 |

18 |
Input: root = [1,2,2,3,3,null,null,4,4]
19 | Output: false
20 |
21 |
22 |
Example 3:
23 |
24 |
Input: root = []
25 | Output: true
26 |
27 |
28 |
29 |
Constraints:
30 |
31 |
32 | - The number of nodes in the tree is in the range
[0, 5000]
.
33 | -104 <= Node.val <= 104
34 |
35 |
--------------------------------------------------------------------------------
/1108-defanging-an-ip-address/1108-defanging-an-ip-address.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def defangIPaddr(self, address: str) -> str:
3 | ans = ""
4 | for a in address:
5 | if a == ".":
6 | ans += "[.]"
7 | else:
8 | ans += a
9 | return ans
10 |
--------------------------------------------------------------------------------
/1108-defanging-an-ip-address/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1108-defanging-an-ip-address/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a valid (IPv4) IP address
, return a defanged version of that IP address.
2 |
3 |
A defanged IP address replaces every period "."
with "[.]"
.
4 |
5 |
6 |
Example 1:
7 |
Input: address = "1.1.1.1"
8 | Output: "1[.]1[.]1[.]1"
9 |
Example 2:
10 |
Input: address = "255.100.50.0"
11 | Output: "255[.]100[.]50[.]0"
12 |
13 |
14 |
Constraints:
15 |
16 |
17 | - The given
address
is a valid IPv4 address.
18 |
--------------------------------------------------------------------------------
/111-minimum-depth-of-binary-tree/111-minimum-depth-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 minDepth(self, root: Optional[TreeNode]) -> int:
9 | if root is None:
10 | return 0
11 | left = self.minDepth(root.left)
12 | right = self.minDepth(root.right)
13 | if left == 0:
14 | return 1 + right
15 | elif right == 0:
16 | return 1 + left
17 | return 1 + min(left,right)
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/111-minimum-depth-of-binary-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/111-minimum-depth-of-binary-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a binary tree, find its minimum depth.
2 |
3 |
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
4 |
5 |
Note: A leaf is a node with no children.
6 |
7 |
8 |
Example 1:
9 |

10 |
Input: root = [3,9,20,null,null,15,7]
11 | Output: 2
12 |
13 |
14 |
Example 2:
15 |
16 |
Input: root = [2,null,3,null,4,null,5,null,6]
17 | Output: 5
18 |
19 |
20 |
21 |
Constraints:
22 |
23 |
24 | - The number of nodes in the tree is in the range
[0, 105]
.
25 | -1000 <= Node.val <= 1000
26 |
27 |
--------------------------------------------------------------------------------
/1143-longest-common-subsequence/1143-longest-common-subsequence.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def longestCommonSubsequence(self, text1: str, text2: str) -> int:
3 | #tabulation/iterative
4 | n = len(text1)
5 | m = len(text2)
6 | DP = []
7 | for rows in range(n+1):
8 | column = [-1] *(m+1)
9 | DP.append(column)
10 | for i in range(n+1):
11 | for j in range(m+1):
12 | if i == 0 or j == 0:
13 | DP[i][j] = 0
14 | for i in range(1, n+1):
15 | for j in range(1, m+1):
16 | if text1[i-1] == text2[j-1]:
17 | DP[i][j] = 1 + DP[i-1][j-1]
18 | else:
19 | DP[i][j] = max(DP[i][j-1], DP[i-1][j])
20 | return DP[n][m]
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/1143-longest-common-subsequence/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1150-check-if-a-number-is-majority-element-in-a-sorted-array/1150-check-if-a-number-is-majority-element-in-a-sorted-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isMajorityElement(self, nums: List[int], target: int) -> bool:
3 | D = {}
4 | majority = len(nums) // 2
5 | for n in nums:
6 | if n in D:
7 | D[n] += 1
8 | else:
9 | D[n] = 1
10 | if target in D and D[target] > majority:
11 | return True
12 | return False
13 |
14 |
--------------------------------------------------------------------------------
/1150-check-if-a-number-is-majority-element-in-a-sorted-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1150-check-if-a-number-is-majority-element-in-a-sorted-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer array nums
sorted in non-decreasing order and an integer target
, return true
if target
is a majority element, or false
otherwise.
2 |
3 |
A majority element in an array nums
is an element that appears more than nums.length / 2
times in the array.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [2,4,5,5,5,5,5,6,6], target = 5
9 | Output: true
10 | Explanation: The value 5 appears 5 times and the length of the array is 9.
11 | Thus, 5 is a majority element because 5 > 9/2 is true.
12 |
13 |
14 |
Example 2:
15 |
16 |
Input: nums = [10,100,101,101], target = 101
17 | Output: false
18 | Explanation: The value 101 appears 2 times and the length of the array is 4.
19 | Thus, 101 is not a majority element because 2 > 4/2 is false.
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | 1 <= nums.length <= 1000
27 | 1 <= nums[i], target <= 109
28 | nums
is sorted in non-decreasing order.
29 |
30 |
--------------------------------------------------------------------------------
/118-pascals-triangle/118-pascals-triangle.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def generate(self, numRows: int) -> List[List[int]]:
3 | if numRows == 1:
4 | return [[1]]
5 | if numRows == 2:
6 | return [[1] , [1,1]]
7 | Ans = [[1] , [1,1]] #2
8 | n = numRows - 2
9 | for i in range(n):
10 | Ans2 = [1]
11 | for j in range(len(Ans[-1])):
12 | if j < (len(Ans[-1])-1):
13 | s = Ans[-1][j] + Ans[-1][j+1]
14 | Ans2.append(s)
15 | Ans2.append(1)
16 | Ans.append(Ans2)
17 | return Ans
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/118-pascals-triangle/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/118-pascals-triangle/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer numRows
, return the first numRows of Pascal's triangle.
2 |
3 |
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
4 |

5 |
6 |
Example 1:
7 |
Input: numRows = 5
8 | Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
9 |
Example 2:
10 |
Input: numRows = 1
11 | Output: [[1]]
12 |
13 |
14 |
Constraints:
15 |
16 |
17 | 1 <= numRows <= 30
18 |
19 |
--------------------------------------------------------------------------------
/1200-minimum-absolute-difference/1200-minimum-absolute-difference.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
3 | arr.sort()
4 | mini = 10000000000000000
5 | ans = []
6 | for a in range(len(arr) -1):
7 | if (arr[a+1] - arr[a]) < mini:
8 | mini = arr[a+1] - arr[a]
9 | for a in range(len(arr) -1):
10 | if (arr[a+1] - arr[a]) == mini:
11 | ans.append([arr[a], arr[a+1]])
12 | return ans
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/1200-minimum-absolute-difference/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1200-minimum-absolute-difference/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array of distinct integers arr
, find all pairs of elements with the minimum absolute difference of any two elements.
2 |
3 |
Return a list of pairs in ascending order(with respect to pairs), each pair [a, b]
follows
4 |
5 |
6 | a, b
are from arr
7 | a < b
8 | b - a
equals to the minimum absolute difference of any two elements in arr
9 |
10 |
11 |
12 |
Example 1:
13 |
14 |
Input: arr = [4,2,1,3]
15 | Output: [[1,2],[2,3],[3,4]]
16 | Explanation: The minimum absolute difference is 1. List all pairs with difference equal to 1 in ascending order.
17 |
18 |
Example 2:
19 |
20 |
Input: arr = [1,3,6,10,15]
21 | Output: [[1,3]]
22 |
23 |
24 |
Example 3:
25 |
26 |
Input: arr = [3,8,-10,23,19,-4,-14,27]
27 | Output: [[-14,-10],[19,23],[23,27]]
28 |
29 |
30 |
31 |
Constraints:
32 |
33 |
34 | 2 <= arr.length <= 105
35 | -106 <= arr[i] <= 106
36 |
37 |
--------------------------------------------------------------------------------
/1207-unique-number-of-occurrences/1207-unique-number-of-occurrences.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def uniqueOccurrences(self, arr: List[int]) -> bool:
3 | Freq = {}
4 | for a in arr:
5 | if a in Freq:
6 | Freq[a] += 1
7 | else:
8 | Freq[a] = 1
9 | Values = Freq.values()
10 | V = list(Values)
11 | V.sort()
12 | #print(V)
13 | for v in range(1, len(V)):
14 | if V[v] == V[v-1]:
15 | return False
16 | return True
17 |
18 |
--------------------------------------------------------------------------------
/1207-unique-number-of-occurrences/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1207-unique-number-of-occurrences/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array of integers arr
, return true
if the number of occurrences of each value in the array is unique, or false
otherwise.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: arr = [1,2,2,1,1,3]
7 | Output: true
8 | Explanation: The value 1 has 3 occurrences, 2 has 2 and 3 has 1. No two values have the same number of occurrences.
9 |
10 |
Example 2:
11 |
12 |
Input: arr = [1,2]
13 | Output: false
14 |
15 |
16 |
Example 3:
17 |
18 |
Input: arr = [-3,0,1,-3,1,1,1,-3,10,0]
19 | Output: true
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | 1 <= arr.length <= 1000
27 | -1000 <= arr[i] <= 1000
28 |
29 |
--------------------------------------------------------------------------------
/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxProfit(self, prices: List[int]) -> int:
3 | maxi = prices[-1]
4 | diff = 0
5 | for i in range(len(prices)-2 , -1 , -1):
6 | if prices[i] > maxi:
7 | maxi = prices[i]
8 | else:
9 | dif = maxi - prices[i]
10 | diff = max(diff, dif)
11 | return diff
12 |
13 |
--------------------------------------------------------------------------------
/121-best-time-to-buy-and-sell-stock/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/121-best-time-to-buy-and-sell-stock/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
2 |
3 |
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
4 |
5 |
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: prices = [7,1,5,3,6,4]
11 | Output: 5
12 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
13 | Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
14 |
15 |
16 |
Example 2:
17 |
18 |
Input: prices = [7,6,4,3,1]
19 | Output: 0
20 | Explanation: In this case, no transactions are done and the max profit = 0.
21 |
22 |
23 |
24 |
Constraints:
25 |
26 |
27 | 1 <= prices.length <= 105
28 | 0 <= prices[i] <= 104
29 |
30 |
--------------------------------------------------------------------------------
/1249-minimum-remove-to-make-valid-parentheses/1249-minimum-remove-to-make-valid-parentheses.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 | class Solution:
3 | def minRemoveToMakeValid(self, s: str) -> str:
4 | S = deque() #
5 | D = {}
6 | news = ""
7 | for i in range(len(s)): #8
8 | if s[i] == "(":
9 | S.append((s[i], i))
10 | elif s[i] == ")" and len(S) != 0:
11 | S.pop()
12 | elif s[i] == ")" and len(S) == 0:
13 | D[i] = None
14 | while S:
15 | t = S.pop()
16 | D[t[1]] = None
17 | for i in range(len(s)):
18 | if i not in D:
19 | news += s[i]
20 | return news
21 |
22 |
23 |
24 |
25 |
26 |
--------------------------------------------------------------------------------
/1249-minimum-remove-to-make-valid-parentheses/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/125-valid-palindrome/125-valid-palindrome.py:
--------------------------------------------------------------------------------
1 | import copy
2 | class Solution:
3 | def isPalindrome(self, s: str) -> bool:
4 | nums = {"1","2","3","4","5","6","7","8","9","0"}
5 | s1 = ""
6 | for i in s:
7 | if i >= "a" and i < "z":
8 | s1 += i
9 | elif i >= "A" and i < "Z":
10 | s1 += i.lower()
11 | elif i in nums:
12 | s1 += i
13 | s2 = ""
14 | for s in range(len(s1)-1, -1, -1):
15 | s2 += s1[s]
16 | if s1 == s2:
17 | return True
18 | return False
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/125-valid-palindrome/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/125-valid-palindrome/README.md:
--------------------------------------------------------------------------------
1 | Easy
A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers.
2 |
3 |
Given a string s
, return true
if it is a palindrome, or false
otherwise.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: s = "A man, a plan, a canal: Panama"
9 | Output: true
10 | Explanation: "amanaplanacanalpanama" is a palindrome.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: s = "race a car"
16 | Output: false
17 | Explanation: "raceacar" is not a palindrome.
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: s = " "
23 | Output: true
24 | Explanation: s is an empty string "" after removing non-alphanumeric characters.
25 | Since an empty string reads the same forward and backward, it is a palindrome.
26 |
27 |
28 |
29 |
Constraints:
30 |
31 |
32 | 1 <= s.length <= 2 * 105
33 | s
consists only of printable ASCII characters.
34 |
35 |
--------------------------------------------------------------------------------
/128-longest-consecutive-sequence/128-longest-consecutive-sequence.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def longestConsecutive(self, nums: List[int]) -> int:
3 | nums.sort()
4 | #[1,2,3,4,100,200,201,202,203,204,205]
5 | if len(nums) == 0:
6 | return 0
7 | cnt = 0
8 | maxi = 0
9 | for n in range(1, len(nums)): #5
10 | if nums[n] - nums[n-1] == 1: #nums[3] - nums[2] == 1
11 | cnt += 1 #3
12 | maxi = max(maxi, cnt) #3
13 | elif nums[n] - nums[n-1] > 1:
14 | cnt = 0
15 | return maxi + 1
16 |
17 |
18 |
--------------------------------------------------------------------------------
/128-longest-consecutive-sequence/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/128-longest-consecutive-sequence/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an unsorted array of integers nums
, return the length of the longest consecutive elements sequence.
2 |
3 |
You must write an algorithm that runs in O(n)
time.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [100,4,200,1,3,2]
9 | Output: 4
10 | Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]
. Therefore its length is 4.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [0,3,7,2,5,8,4,6,0,1]
16 | Output: 9
17 |
18 |
19 |
20 |
Constraints:
21 |
22 |
23 | 0 <= nums.length <= 105
24 | -109 <= nums[i] <= 109
25 |
26 |
--------------------------------------------------------------------------------
/1295-find-numbers-with-even-number-of-digits/1295-find-numbers-with-even-number-of-digits.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findNumbers(self, nums: List[int]) -> int:
3 | ans = 0
4 | for n in nums:
5 | dig = 0
6 | while n != 0:
7 | dig += 1
8 | n = n // 10
9 | if dig % 2 == 0:
10 | ans += 1
11 | return ans
12 |
13 |
--------------------------------------------------------------------------------
/1295-find-numbers-with-even-number-of-digits/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1295-find-numbers-with-even-number-of-digits/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array nums
of integers, return how many of them contain an even number of digits.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: nums = [12,345,2,6,7896]
7 | Output: 2
8 | Explanation:
9 | 12 contains 2 digits (even number of digits).
10 | 345 contains 3 digits (odd number of digits).
11 | 2 contains 1 digit (odd number of digits).
12 | 6 contains 1 digit (odd number of digits).
13 | 7896 contains 4 digits (even number of digits).
14 | Therefore only 12 and 7896 contain an even number of digits.
15 |
16 |
17 |
Example 2:
18 |
19 |
Input: nums = [555,901,482,1771]
20 | Output: 1
21 | Explanation:
22 | Only 1771 contains an even number of digits.
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
29 | 1 <= nums.length <= 500
30 | 1 <= nums[i] <= 105
31 |
32 |
--------------------------------------------------------------------------------
/136-single-number/136-single-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def singleNumber(self, nums: List[int]) -> int:
3 | D = {}
4 | for n in nums:
5 | if n in D:
6 | D[n] += 1
7 | else:
8 | D[n] = 1
9 | for n in nums:
10 | if D[n] == 1:
11 | return n
12 |
--------------------------------------------------------------------------------
/136-single-number/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/136-single-number/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
2 |
3 |
You must implement a solution with a linear runtime complexity and use only constant extra space.
4 |
5 |
6 |
Example 1:
7 |
Input: nums = [2,2,1]
8 | Output: 1
9 |
Example 2:
10 |
Input: nums = [4,1,2,1,2]
11 | Output: 4
12 |
Example 3:
13 |
Input: nums = [1]
14 | Output: 1
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | 1 <= nums.length <= 3 * 104
21 | -3 * 104 <= nums[i] <= 3 * 104
22 | - Each element in the array appears twice except for one element which appears only once.
23 |
24 |
--------------------------------------------------------------------------------
/1365-how-many-numbers-are-smaller-than-the-current-number/1365-how-many-numbers-are-smaller-than-the-current-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
3 | ans = []
4 | for i in range(len(nums)):
5 | cnt = 0
6 | for j in range(len(nums)):
7 | if nums[j] < nums[i]:
8 | cnt += 1
9 | ans.append(cnt)
10 | return ans
11 |
12 |
--------------------------------------------------------------------------------
/1365-how-many-numbers-are-smaller-than-the-current-number/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1365-how-many-numbers-are-smaller-than-the-current-number/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the array nums
, for each nums[i]
find out how many numbers in the array are smaller than it. That is, for each nums[i]
you have to count the number of valid j's
such that j != i
and nums[j] < nums[i]
.
2 |
3 |
Return the answer in an array.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [8,1,2,2,3]
9 | Output: [4,0,1,1,3]
10 | Explanation:
11 | For nums[0]=8 there exist four smaller numbers than it (1, 2, 2 and 3).
12 | For nums[1]=1 does not exist any smaller number than it.
13 | For nums[2]=2 there exist one smaller number than it (1).
14 | For nums[3]=2 there exist one smaller number than it (1).
15 | For nums[4]=3 there exist three smaller numbers than it (1, 2 and 2).
16 |
17 |
18 |
Example 2:
19 |
20 |
Input: nums = [6,5,4,8]
21 | Output: [2,1,0,3]
22 |
23 |
24 |
Example 3:
25 |
26 |
Input: nums = [7,7,7,7]
27 | Output: [0,0,0,0]
28 |
29 |
30 |
31 |
Constraints:
32 |
33 |
34 | 2 <= nums.length <= 500
35 | 0 <= nums[i] <= 100
36 |
37 |
--------------------------------------------------------------------------------
/1389-create-target-array-in-the-given-order/1389-create-target-array-in-the-given-order.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
3 | ans = []
4 | for i in range(len(nums)):
5 | ans.insert(index[i] , nums[i])
6 | return ans
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/1389-create-target-array-in-the-given-order/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/14-longest-common-prefix/14-longest-common-prefix.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def longestCommonPrefix(self, strs: List[str]) -> str:
3 | mini = min(strs)
4 | lmini = len(mini)
5 | ans = ""
6 | for i in range(lmini):
7 | for string in strs:
8 | if string[i] != mini[i]:
9 | return ans
10 | ans += mini[i]
11 | return ans
12 |
13 |
--------------------------------------------------------------------------------
/14-longest-common-prefix/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/14-longest-common-prefix/README.md:
--------------------------------------------------------------------------------
1 | Easy
Write a function to find the longest common prefix string amongst an array of strings.
2 |
3 |
If there is no common prefix, return an empty string ""
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: strs = ["flower","flow","flight"]
9 | Output: "fl"
10 |
11 |
12 |
Example 2:
13 |
14 |
Input: strs = ["dog","racecar","car"]
15 | Output: ""
16 | Explanation: There is no common prefix among the input strings.
17 |
18 |
19 |
20 |
Constraints:
21 |
22 |
23 | 1 <= strs.length <= 200
24 | 0 <= strs[i].length <= 200
25 | strs[i]
consists of only lower-case English letters.
26 |
27 |
--------------------------------------------------------------------------------
/141-linked-list-cycle/141-linked-list-cycle.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def hasCycle(self, head: Optional[ListNode]) -> bool:
9 | slow = head
10 | fast = head
11 | while fast and fast.next:
12 | slow = slow.next
13 | fast = fast.next.next
14 | if slow == fast:
15 | return True
16 | return False
17 |
18 |
--------------------------------------------------------------------------------
/141-linked-list-cycle/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/142-linked-list-cycle-ii/142-linked-list-cycle-ii.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
9 | slow = head
10 | fast = head
11 | first = head
12 | while fast and fast.next:
13 | slow = slow.next
14 | fast = fast.next.next
15 | if slow == fast:
16 | while first != slow:
17 | first = first.next
18 | slow = slow.next
19 | return first
20 | return None
21 |
--------------------------------------------------------------------------------
/142-linked-list-cycle-ii/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/144-binary-tree-preorder-traversal/144-binary-tree-preorder-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 |
8 | from collections import deque
9 | class Solution:
10 | def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
11 | if root is None:
12 | return []
13 | stack = deque()
14 | stack.append(root)
15 | ans = []
16 | while len(stack) > 0:
17 | temp = stack.pop()
18 | ans.append(temp.val)
19 | if temp.right != None:
20 | stack.append(temp.right)
21 | if temp.left != None:
22 | stack.append(temp.left)
23 | return ans
24 |
25 |
--------------------------------------------------------------------------------
/144-binary-tree-preorder-traversal/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/144-binary-tree-preorder-traversal/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree, return the preorder traversal of its nodes' values.
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: root = [1,null,2,3]
7 | Output: [1,2,3]
8 |
9 |
10 |
Example 2:
11 |
12 |
Input: root = []
13 | Output: []
14 |
15 |
16 |
Example 3:
17 |
18 |
Input: root = [1]
19 | Output: [1]
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | - The number of nodes in the tree is in the range
[0, 100]
.
27 | -100 <= Node.val <= 100
28 |
29 |
30 |
31 |
Follow up: Recursive solution is trivial, could you do it iteratively?
32 |
--------------------------------------------------------------------------------
/1470-shuffle-the-array/1470-shuffle-the-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def shuffle(self, nums: List[int], n: int) -> List[int]:
3 | ans = []
4 | la = 0
5 | ln = len(nums)
6 | i = 0
7 | while la != ln:
8 | if i <= ln:
9 | ans.append(nums[i])
10 | la += 1
11 | if n <= ln:
12 | ans.append(nums[n])
13 | la += 1
14 | i += 1
15 | n += 1
16 | return ans
--------------------------------------------------------------------------------
/1470-shuffle-the-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1470-shuffle-the-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the array nums
consisting of 2n
elements in the form [x1,x2,...,xn,y1,y2,...,yn]
.
2 |
3 |
Return the array in the form [x1,y1,x2,y2,...,xn,yn]
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [2,5,1,3,4,7], n = 3
9 | Output: [2,3,5,4,1,7]
10 | Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [1,2,3,4,4,3,2,1], n = 4
16 | Output: [1,4,2,3,3,2,4,1]
17 |
18 |
19 |
Example 3:
20 |
21 |
Input: nums = [1,1,2,2], n = 2
22 | Output: [1,2,1,2]
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
29 | 1 <= n <= 500
30 | nums.length == 2n
31 | 1 <= nums[i] <= 10^3
32 |
--------------------------------------------------------------------------------
/1480-running-sum-of-1d-array/1480-running-sum-of-1d-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def runningSum(self, nums: List[int]) -> List[int]:
3 | Ans = []
4 | Ans.append(nums[0])
5 | for i in range(1 , len(nums)):
6 | nextt = Ans[-1] + nums[i]
7 | Ans.append(nextt)
8 | return Ans
9 |
10 |
--------------------------------------------------------------------------------
/1480-running-sum-of-1d-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1480-running-sum-of-1d-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array nums
. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i])
.
2 |
3 |
Return the running sum of nums
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [1,2,3,4]
9 | Output: [1,3,6,10]
10 | Explanation: Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].
11 |
12 |
Example 2:
13 |
14 |
Input: nums = [1,1,1,1,1]
15 | Output: [1,2,3,4,5]
16 | Explanation: Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].
17 |
18 |
Example 3:
19 |
20 |
Input: nums = [3,1,2,10,1]
21 | Output: [3,4,6,16,17]
22 |
23 |
24 |
25 |
Constraints:
26 |
27 |
28 | 1 <= nums.length <= 1000
29 | -10^6 <= nums[i] <= 10^6
30 |
--------------------------------------------------------------------------------
/151-reverse-words-in-a-string/151-reverse-words-in-a-string.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def revword(self, word):
3 | revword = ""
4 | for j in range(len(word)-1, -1, -1):
5 | revword += word[j]
6 | return revword
7 |
8 | def reverseWords(self, s: str) -> str:
9 | ans = ""
10 | word = ""
11 | for i in range(len(s)-1, -1, -1): #14, -1, -1
12 | if s[i] == " " and len(word) > 0:
13 | cword = "" #eulb #si #yks
14 | cword = self.revword(word) #blue #is #sky
15 | if len(ans) != 0: #
16 | ans += " " #blue
17 | ans += cword #blue is sky
18 | word = "" #"" "" ""
19 | elif s[i] == " " and len(word) == 0:
20 | continue
21 | else:
22 | word += s[i] #si yks eht
23 |
24 | if len(word) > 0:
25 | cword = ""
26 | cword = self.revword(word)
27 | if len(ans) != 0: #
28 | ans += " " #blue
29 | ans += cword
30 | return ans
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/151-reverse-words-in-a-string/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1512-number-of-good-pairs/1512-number-of-good-pairs.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def numIdenticalPairs(self, nums: List[int]) -> int:
3 | ans = 0
4 | for i in range(len(nums)):
5 | for j in range(1 , len(nums)):
6 | if nums[i] == nums[j] and i < j:
7 | ans += 1
8 | return ans
9 |
--------------------------------------------------------------------------------
/1512-number-of-good-pairs/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1512-number-of-good-pairs/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array of integers nums
, return the number of good pairs.
2 |
3 |
A pair (i, j)
is called good if nums[i] == nums[j]
and i
< j
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [1,2,3,1,1,3]
9 | Output: 4
10 | Explanation: There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [1,1,1,1]
16 | Output: 6
17 | Explanation: Each pair in the array are good.
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: nums = [1,2,3]
23 | Output: 0
24 |
25 |
26 |
27 |
Constraints:
28 |
29 |
30 | 1 <= nums.length <= 100
31 | 1 <= nums[i] <= 100
32 |
33 |
--------------------------------------------------------------------------------
/1539-kth-missing-positive-number/1539-kth-missing-positive-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findKthPositive(self, arr: List[int], k: int) -> int:
3 | maxi = max(arr)
4 | m = maxi
5 | D = {}
6 | for a in arr:
7 | D[a] = None
8 | #print(D)
9 | ans = []
10 | for i in range(1, maxi+1):
11 | if i not in D:
12 | ans.append(i)
13 | #print(ans)
14 | if len(ans) == 0:
15 | while k != 0:
16 | m += 1
17 | ans.append(m)
18 | k -= 1
19 | return ans[k-1]
20 | elif len(ans) < k:
21 | diff = k - len(ans)
22 | while diff != 0:
23 | m += 1
24 | ans.append(m)
25 | diff -= 1
26 | return ans[k-1]
27 | else:
28 | return ans[k-1]
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 | """
41 | arr[1] = 0 -> 1
42 | arr[2] = 1 , 0
43 | arr[3] = 2 , 1
44 | arr[4] = 3 , 2
45 | arr[5] = 4 -> 2
46 | arr[6] = 5 -> 3
47 | arr[7] = 6
48 | arr[8] = 7 , 3
49 | arr[9] = 8 -> 4
50 | arr[10] = 9 -> 5
51 | arr[11] = 10 , 4
52 | """
53 |
--------------------------------------------------------------------------------
/1539-kth-missing-positive-number/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1539-kth-missing-positive-number/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array arr
of positive integers sorted in a strictly increasing order, and an integer k
.
2 |
3 |
Find the kth
positive integer that is missing from this array.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: arr = [2,3,4,7,11], k = 5
9 | Output: 9
10 | Explanation: The missing positive integers are [1,5,6,8,9,10,12,13,...]. The 5th missing positive integer is 9.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: arr = [1,2,3,4], k = 2
16 | Output: 6
17 | Explanation: The missing positive integers are [5,6,7,...]. The 2nd missing positive integer is 6.
18 |
19 |
20 |
21 |
Constraints:
22 |
23 |
24 | 1 <= arr.length <= 1000
25 | 1 <= arr[i] <= 1000
26 | 1 <= k <= 1000
27 | arr[i] < arr[j]
for 1 <= i < j <= arr.length
28 |
29 |
--------------------------------------------------------------------------------
/155-min-stack/155-min-stack.py:
--------------------------------------------------------------------------------
1 | import sys
2 | class MinStack:
3 |
4 | def __init__(self):
5 | self.s1 = []
6 |
7 | #self.s1 = [(2,2), (1, 1)]
8 |
9 | def push(self, val: int) -> None:
10 | if len(self.s1) == 0:
11 | self.s1.append((val,val ))
12 | else:
13 | self.s1.append((val, min(self.s1[-1][1], val)))
14 |
15 | def pop(self) -> None:
16 | self.s1.pop()
17 |
18 |
19 | def top(self) -> int:
20 | if len(self.s1) != 0:
21 | return self.s1[-1][0]
22 |
23 | def getMin(self) -> int:
24 | return self.s1[-1][1]
25 |
26 |
27 |
28 | # Your MinStack object will be instantiated and called as such:
29 | # obj = MinStack()
30 | # obj.push(val)
31 | # obj.pop()
32 | # param_3 = obj.top()
33 | # param_4 = obj.getMin()
--------------------------------------------------------------------------------
/155-min-stack/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/155-min-stack/README.md:
--------------------------------------------------------------------------------
1 | Easy
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
2 |
3 |
Implement the MinStack
class:
4 |
5 |
6 | MinStack()
initializes the stack object.
7 | void push(int val)
pushes the element val
onto the stack.
8 | void pop()
removes the element on the top of the stack.
9 | int top()
gets the top element of the stack.
10 | int getMin()
retrieves the minimum element in the stack.
11 |
12 |
13 |
14 |
Example 1:
15 |
16 |
Input
17 | ["MinStack","push","push","push","getMin","pop","top","getMin"]
18 | [[],[-2],[0],[-3],[],[],[],[]]
19 |
20 | Output
21 | [null,null,null,null,-3,null,0,-2]
22 |
23 | Explanation
24 | MinStack minStack = new MinStack();
25 | minStack.push(-2);
26 | minStack.push(0);
27 | minStack.push(-3);
28 | minStack.getMin(); // return -3
29 | minStack.pop();
30 | minStack.top(); // return 0
31 | minStack.getMin(); // return -2
32 |
33 |
34 |
35 |
Constraints:
36 |
37 |
38 | -231 <= val <= 231 - 1
39 | - Methods
pop
, top
and getMin
operations will always be called on non-empty stacks.
40 | - At most
3 * 104
calls will be made to push
, pop
, top
, and getMin
.
41 |
42 |
--------------------------------------------------------------------------------
/160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def llength(self, head):
9 | cnt = 0
10 | temp = head
11 | while temp:
12 | cnt += 1
13 | temp = temp.next
14 | return cnt
15 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
16 | cntA = self.llength(headA)
17 | cntB = self.llength(headB)
18 | temp1 = headA
19 | temp2 = headB
20 | if cntA > cntB:
21 | diff = abs(cntA- cntB)
22 | while diff:
23 | temp1 = temp1.next
24 | diff -= 1
25 | elif cntA < cntB:
26 | diff = cntB - cntA
27 | while diff:
28 | temp2 = temp2.next
29 | diff -= 1
30 | while temp1:
31 | if temp1 == temp2:
32 | return temp1
33 | temp1 = temp1.next
34 | temp2 = temp2.next
35 | return None
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/160-intersection-of-two-linked-lists/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1662-check-if-two-string-arrays-are-equivalent/1662-check-if-two-string-arrays-are-equivalent.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
3 | w1 = ""
4 | w2 = ""
5 | for w in word1:
6 | w1 += w
7 | for v in word2:
8 | w2 += v
9 | if w1 == w2:
10 | return True
11 | else:
12 | return False
13 |
--------------------------------------------------------------------------------
/1662-check-if-two-string-arrays-are-equivalent/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1662-check-if-two-string-arrays-are-equivalent/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given two string arrays word1
and word2
, return true
if the two arrays represent the same string, and false
otherwise.
2 |
3 |
A string is represented by an array if the array elements concatenated in order forms the string.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
9 | Output: true
10 | Explanation:
11 | word1 represents string "ab" + "c" -> "abc"
12 | word2 represents string "a" + "bc" -> "abc"
13 | The strings are the same, so return true.
14 |
15 |
Example 2:
16 |
17 |
Input: word1 = ["a", "cb"], word2 = ["ab", "c"]
18 | Output: false
19 |
20 |
21 |
Example 3:
22 |
23 |
Input: word1 = ["abc", "d", "defg"], word2 = ["abcddefg"]
24 | Output: true
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 1 <= word1.length, word2.length <= 103
32 | 1 <= word1[i].length, word2[i].length <= 103
33 | 1 <= sum(word1[i].length), sum(word2[i].length) <= 103
34 | word1[i]
and word2[i]
consist of lowercase letters.
35 |
36 |
--------------------------------------------------------------------------------
/167-two-sum-ii-input-array-is-sorted/167-two-sum-ii-input-array-is-sorted.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def twoSum(self, numbers: List[int], target: int) -> List[int]:
3 | n = len(numbers)#4
4 | start = 0 #1
5 | last = n-1 #3
6 | ans = []
7 | while start <= last:
8 | if numbers[start] + numbers[last] == target:
9 | ans.append(start + 1)
10 | ans.append(last + 1 )
11 | return ans
12 | elif numbers[start] + numbers[last] > target:
13 | last -= 1
14 | elif numbers[start] + numbers[last] < target:
15 | start += 1
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/167-two-sum-ii-input-array-is-sorted/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/169-majority-element/169-majority-element.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def majorityElement(self, nums: List[int]) -> int:
3 | majority = len(nums) // 2
4 | D = {}
5 | for n in nums:
6 | if n in D:
7 | D[n] += 1
8 | else:
9 | D[n] = 1
10 | for n in nums:
11 | if D[n] > majority:
12 | return n
13 |
--------------------------------------------------------------------------------
/169-majority-element/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/169-majority-element/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array nums
of size n
, return the majority element.
2 |
3 |
The majority element is the element that appears more than ⌊n / 2⌋
times. You may assume that the majority element always exists in the array.
4 |
5 |
6 |
Example 1:
7 |
Input: nums = [3,2,3]
8 | Output: 3
9 |
Example 2:
10 |
Input: nums = [2,2,1,1,1,2,2]
11 | Output: 2
12 |
13 |
14 |
Constraints:
15 |
16 |
17 | n == nums.length
18 | 1 <= n <= 5 * 104
19 | -109 <= nums[i] <= 109
20 |
21 |
22 |
23 |
Follow-up: Could you solve the problem in linear time and in
O(1)
space?
--------------------------------------------------------------------------------
/1748-sum-of-unique-elements/1748-sum-of-unique-elements.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sumOfUnique(self, nums: List[int]) -> int:
3 | D = {}
4 | for n in nums:
5 | if n in D:
6 | D[n] += 1
7 | else:
8 | D[n] = 1
9 | ans = 0
10 | for n in nums:
11 | if D[n] == 1:
12 | ans += n
13 | return ans
14 |
--------------------------------------------------------------------------------
/1748-sum-of-unique-elements/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1748-sum-of-unique-elements/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are given an integer array nums
. The unique elements of an array are the elements that appear exactly once in the array.
2 |
3 |
Return the sum of all the unique elements of nums
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [1,2,3,2]
9 | Output: 4
10 | Explanation: The unique elements are [1,3], and the sum is 4.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [1,1,1,1,1]
16 | Output: 0
17 | Explanation: There are no unique elements, and the sum is 0.
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: nums = [1,2,3,4,5]
23 | Output: 15
24 | Explanation: The unique elements are [1,2,3,4,5], and the sum is 15.
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 1 <= nums.length <= 100
32 | 1 <= nums[i] <= 100
33 |
34 |
--------------------------------------------------------------------------------
/1822-sign-of-the-product-of-an-array/1822-sign-of-the-product-of-an-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def signFunc(self, product):
3 | if product > 0:
4 | return 1
5 | elif product < 0:
6 | return -1
7 | if product == 0:
8 | return 0
9 |
10 | def arraySign(self, nums: List[int]) -> int:
11 | product = 1
12 | for n in nums:
13 | product = n * product
14 | return self.signFunc(product)
15 |
--------------------------------------------------------------------------------
/1822-sign-of-the-product-of-an-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1822-sign-of-the-product-of-an-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
There is a function signFunc(x)
that returns:
2 |
3 |
4 | 1
if x
is positive.
5 | -1
if x
is negative.
6 | 0
if x
is equal to 0
.
7 |
8 |
9 |
You are given an integer array nums
. Let product
be the product of all values in the array nums
.
10 |
11 |
Return signFunc(product)
.
12 |
13 |
14 |
Example 1:
15 |
16 |
Input: nums = [-1,-2,-3,-4,3,2,1]
17 | Output: 1
18 | Explanation: The product of all values in the array is 144, and signFunc(144) = 1
19 |
20 |
21 |
Example 2:
22 |
23 |
Input: nums = [1,5,0,2,-3]
24 | Output: 0
25 | Explanation: The product of all values in the array is 0, and signFunc(0) = 0
26 |
27 |
28 |
Example 3:
29 |
30 |
Input: nums = [-1,1,-1,1,-1]
31 | Output: -1
32 | Explanation: The product of all values in the array is -1, and signFunc(-1) = -1
33 |
34 |
35 |
36 |
Constraints:
37 |
38 |
39 | 1 <= nums.length <= 1000
40 | -100 <= nums[i] <= 100
41 |
42 |
--------------------------------------------------------------------------------
/1859-sorting-the-sentence/1859-sorting-the-sentence.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sortSentence(self, s: str) -> str:
3 | s = s.split()
4 | D = {}
5 | for i in s:
6 | D[i[-1]] = i
7 | K = D.keys()
8 | Keys = list(K)
9 | for k in range(len(Keys)):
10 | Keys[k] = int(Keys[k])
11 | Keys.sort()
12 | ans = ""
13 | integers = {"1","2","3","4","5","6","7","8","9","0"}
14 | for k in Keys:
15 | r = D[str(k)]
16 | for j in r:
17 | if j in integers:
18 | ans += " "
19 | else:
20 | ans += j
21 | mans = ""
22 | for a in range(len(ans)-1):
23 | mans += ans[a]
24 | return mans
25 |
--------------------------------------------------------------------------------
/1859-sorting-the-sentence/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/19-remove-nth-node-from-end-of-list/19-remove-nth-node-from-end-of-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 lenn(self, head):
8 | cnt = 0
9 | temp = head
10 | while temp:
11 | cnt += 1
12 | temp = temp.next
13 | return cnt
14 |
15 | def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
16 | length = self.lenn(head) #2
17 | #print(length)
18 | remove = length - (n-1) #2-(2-1) = 2-1 = 1
19 | if remove == 1:
20 | head = head.next
21 | return head
22 | temp = head
23 | cnt = 0
24 | while temp:
25 | cnt += 1 #1
26 | if cnt == remove - 1:
27 | temp.next = temp.next.next
28 | temp = temp.next
29 | return head
30 |
--------------------------------------------------------------------------------
/19-remove-nth-node-from-end-of-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/19-remove-nth-node-from-end-of-list/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given the head
of a linked list, remove the nth
node from the end of the list and return its head.
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: head = [1,2,3,4,5], n = 2
7 | Output: [1,2,3,5]
8 |
9 |
10 |
Example 2:
11 |
12 |
Input: head = [1], n = 1
13 | Output: []
14 |
15 |
16 |
Example 3:
17 |
18 |
Input: head = [1,2], n = 1
19 | Output: [1]
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | - The number of nodes in the list is
sz
.
27 | 1 <= sz <= 30
28 | 0 <= Node.val <= 100
29 | 1 <= n <= sz
30 |
31 |
32 |
33 |
Follow up: Could you do this in one pass?
34 |
--------------------------------------------------------------------------------
/1920-build-array-from-permutation/1920-build-array-from-permutation.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def buildArray(self, nums: List[int]) -> List[int]:
3 | ans = []
4 | for i in range(len(nums)):
5 | ans.insert(i, nums[nums[i]])
6 | return ans
7 |
--------------------------------------------------------------------------------
/1920-build-array-from-permutation/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1929-concatenation-of-array/1929-concatenation-of-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def getConcatenation(self, nums: List[int]) -> List[int]:
3 | ans = []
4 | i = 0
5 | while i < 2:
6 | for n in nums:
7 | ans.append(n)
8 | i += 1
9 | return ans
10 |
--------------------------------------------------------------------------------
/1929-concatenation-of-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1929-concatenation-of-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer array nums
of length n
, you want to create an array ans
of length 2n
where ans[i] == nums[i]
and ans[i + n] == nums[i]
for 0 <= i < n
(0-indexed).
2 |
3 |
Specifically, ans
is the concatenation of two nums
arrays.
4 |
5 |
Return the array ans
.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: nums = [1,2,1]
11 | Output: [1,2,1,1,2,1]
12 | Explanation: The array ans is formed as follows:
13 | - ans = [nums[0],nums[1],nums[2],nums[0],nums[1],nums[2]]
14 | - ans = [1,2,1,1,2,1]
15 |
16 |
Example 2:
17 |
18 |
Input: nums = [1,3,2,1]
19 | Output: [1,3,2,1,1,3,2,1]
20 | Explanation: The array ans is formed as follows:
21 | - ans = [nums[0],nums[1],nums[2],nums[3],nums[0],nums[1],nums[2],nums[3]]
22 | - ans = [1,3,2,1,1,3,2,1]
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
29 | n == nums.length
30 | 1 <= n <= 1000
31 | 1 <= nums[i] <= 1000
32 |
33 |
--------------------------------------------------------------------------------
/2-add-two-numbers/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/2-add-two-numbers/README.md:
--------------------------------------------------------------------------------
1 | Medium
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
2 |
3 |
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: l1 = [2,4,3], l2 = [5,6,4]
9 | Output: [7,0,8]
10 | Explanation: 342 + 465 = 807.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: l1 = [0], l2 = [0]
16 | Output: [0]
17 |
18 |
19 |
Example 3:
20 |
21 |
Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
22 | Output: [8,9,9,9,0,0,0,1]
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
29 | - The number of nodes in each linked list is in the range
[1, 100]
.
30 | 0 <= Node.val <= 9
31 | - It is guaranteed that the list represents a number that does not have leading zeros.
32 |
33 |
--------------------------------------------------------------------------------
/20-valid-parentheses/20-valid-parentheses.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 | class Solution:
3 | def isValid(self, s: str) -> bool:
4 | if len(s) % 2 != 0:
5 | return False
6 | Pairs = {('(',')'): None, ('[',']'): None , ('{','}'): None }
7 | Open = ("[", "(", "{")
8 | S = deque()
9 | for i in s:
10 | if i in Open:
11 | S.append(i)
12 | if i not in Open and len(S) == 0:
13 | return False
14 | if i not in Open:
15 | t = S.pop()
16 | if (t,i) not in Pairs:
17 | return False
18 | if len(S) != 0:
19 | return False
20 | return True
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/20-valid-parentheses/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/20-valid-parentheses/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a string s
containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
2 |
3 |
An input string is valid if:
4 |
5 |
6 | - Open brackets must be closed by the same type of brackets.
7 | - Open brackets must be closed in the correct order.
8 |
9 |
10 |
11 |
Example 1:
12 |
13 |
Input: s = "()"
14 | Output: true
15 |
16 |
17 |
Example 2:
18 |
19 |
Input: s = "()[]{}"
20 | Output: true
21 |
22 |
23 |
Example 3:
24 |
25 |
Input: s = "(]"
26 | Output: false
27 |
28 |
29 |
30 |
Constraints:
31 |
32 |
33 | 1 <= s.length <= 104
34 | s
consists of parentheses only '()[]{}'
.
35 |
36 |
--------------------------------------------------------------------------------
/2006-count-number-of-pairs-with-absolute-difference-k/2006-count-number-of-pairs-with-absolute-difference-k.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def countKDifference(self, nums: List[int], k: int) -> int:
3 | cnt = 0
4 | for i in range(len(nums)):
5 | for j in range(1 , len(nums)):
6 | if i < j and abs(nums[i] - nums[j]) == k:
7 | cnt += 1
8 | return cnt
9 |
--------------------------------------------------------------------------------
/2006-count-number-of-pairs-with-absolute-difference-k/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/2011-final-value-of-variable-after-performing-operations/2011-final-value-of-variable-after-performing-operations.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def finalValueAfterOperations(self, operations: List[str]) -> int:
3 | X = 0
4 | for o in operations:
5 | if o == "++X":
6 | X = X + 1
7 | elif o == "X++":
8 | X = X + 1
9 | elif o == "--X":
10 | X = X -1
11 | else:
12 | X = X -1
13 | return X
14 |
15 |
--------------------------------------------------------------------------------
/2011-final-value-of-variable-after-performing-operations/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/206-reverse-linked-list/206-reverse-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 reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
8 | prev = None #1
9 | temp = head
10 | t = None
11 | while temp: #2
12 | t = temp #2
13 | temp = temp.next #3
14 | t.next = prev #2.next = 1
15 | prev = t
16 | head = t
17 | return head
18 |
19 |
--------------------------------------------------------------------------------
/206-reverse-linked-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/206-reverse-linked-list/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the head
of a singly linked list, reverse the list, and return the reversed list.
2 |
3 |
4 |
Example 1:
5 |

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

12 |
Input: head = [1,2]
13 | Output: [2,1]
14 |
15 |
16 |
Example 3:
17 |
18 |
Input: head = []
19 | Output: []
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | - The number of nodes in the list is the range
[0, 5000]
.
27 | -5000 <= Node.val <= 5000
28 |
29 |
30 |
31 |
Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?
32 |
--------------------------------------------------------------------------------
/2089-find-target-indices-after-sorting-array/2089-find-target-indices-after-sorting-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def targetIndices(self, nums: List[int], target: int) -> List[int]:
3 | ans = []
4 | nums.sort()
5 | for n in range(len(nums)):
6 | if nums[n] == target:
7 | ans.append(n)
8 | return ans
--------------------------------------------------------------------------------
/2089-find-target-indices-after-sorting-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/2103-rings-and-rods/2103-rings-and-rods.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def countPoints(self, rings: str) -> int:
3 | #"B0R0G0R9R0B0G0"
4 | L = []
5 | for l in range(10):
6 | l = set()
7 | L.append(l)
8 | #L = [{"B","R"}, {}, {}, {}, {},{},{},{},{},{}]
9 | N = {"0","1","2","3","4","5","6","7","8","9"}
10 | ans = 0
11 | for r in range(len(rings)): #(14)
12 | #r = 3
13 | if rings[r] in N:#rings[1] == "0"
14 | L[int(rings[r])].add(rings[r-1])
15 | for l in L:
16 | if len(l) == 3:
17 | ans += 1
18 | return ans
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/2103-rings-and-rods/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/215-kth-largest-element-in-an-array/215-kth-largest-element-in-an-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findKthLargest(self, nums: List[int], k: int) -> int:
3 | nums.sort()
4 | return nums[-k]
5 |
--------------------------------------------------------------------------------
/215-kth-largest-element-in-an-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/215-kth-largest-element-in-an-array/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an integer array nums
and an integer k
, return the kth
largest element in the array.
2 |
3 |
Note that it is the kth
largest element in the sorted order, not the kth
distinct element.
4 |
5 |
6 |
Example 1:
7 |
Input: nums = [3,2,1,5,6,4], k = 2
8 | Output: 5
9 |
Example 2:
10 |
Input: nums = [3,2,3,1,2,4,5,5,6], k = 4
11 | Output: 4
12 |
13 |
14 |
Constraints:
15 |
16 |
17 | 1 <= k <= nums.length <= 104
18 | -104 <= nums[i] <= 104
19 |
20 |
--------------------------------------------------------------------------------
/217-contains-duplicate/217-contains-duplicate.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def containsDuplicate(self, nums: List[int]) -> bool:
3 | nums.sort()
4 | for n in range(len(nums)-1):
5 | if nums[n] == nums[n+1]:
6 | return True
7 | return False
8 |
--------------------------------------------------------------------------------
/217-contains-duplicate/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/217-contains-duplicate/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer array nums
, return true
if any value appears at least twice in the array, and return false
if every element is distinct.
2 |
3 |
4 |
Example 1:
5 |
Input: nums = [1,2,3,1]
6 | Output: true
7 |
Example 2:
8 |
Input: nums = [1,2,3,4]
9 | Output: false
10 |
Example 3:
11 |
Input: nums = [1,1,1,3,3,4,3,2,4,2]
12 | Output: true
13 |
14 |
15 |
Constraints:
16 |
17 |
18 | 1 <= nums.length <= 105
19 | -109 <= nums[i] <= 109
20 |
21 |
--------------------------------------------------------------------------------
/2176-count-equal-and-divisible-pairs-in-an-array/2176-count-equal-and-divisible-pairs-in-an-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def countPairs(self, nums: List[int], k: int) -> int:
3 | ans = 0
4 | for i in range(len(nums)):
5 | for j in range(i+1, len(nums)):
6 | if i < j:
7 | if (nums[i] == nums[j]) and ((i * j) % k == 0):
8 | ans += 1
9 | return ans
10 |
11 |
--------------------------------------------------------------------------------
/2176-count-equal-and-divisible-pairs-in-an-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a
0-indexed integer array
nums
of length
n
and an integer
k
, return
the number of pairs (i, j)
where 0 <= i < j < n
,
such that nums[i] == nums[j]
and (i * j)
is divisible by k
.
2 |
3 |
Example 1:
4 |
5 |
Input: nums = [3,1,2,2,2,1,3], k = 2
6 | Output: 4
7 | Explanation:
8 | There are 4 pairs that meet all the requirements:
9 | - nums[0] == nums[6], and 0 * 6 == 0, which is divisible by 2.
10 | - nums[2] == nums[3], and 2 * 3 == 6, which is divisible by 2.
11 | - nums[2] == nums[4], and 2 * 4 == 8, which is divisible by 2.
12 | - nums[3] == nums[4], and 3 * 4 == 12, which is divisible by 2.
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: nums = [1,2,3,4], k = 1
18 | Output: 0
19 | Explanation: Since no value in nums is repeated, there are no pairs (i,j) that meet all the requirements.
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | 1 <= nums.length <= 100
27 | 1 <= nums[i], k <= 100
28 |
29 |
--------------------------------------------------------------------------------
/2235-add-two-integers/2235-add-two-integers.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sum(self, num1: int, num2: int) -> int:
3 | return num1 + num2
4 |
--------------------------------------------------------------------------------
/2235-add-two-integers/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/2235-add-two-integers/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given two integers
num1
and
num2
, return
the sum of the two integers.
2 |
3 |
Example 1:
4 |
5 |
Input: num1 = 12, num2 = 5
6 | Output: 17
7 | Explanation: num1 is 12, num2 is 5, and their sum is 12 + 5 = 17, so 17 is returned.
8 |
9 |
10 |
Example 2:
11 |
12 |
Input: num1 = -10, num2 = 4
13 | Output: -6
14 | Explanation: num1 + num2 = -6, so -6 is returned.
15 |
16 |
17 |
18 |
Constraints:
19 |
20 |
21 | -100 <= num1, num2 <= 100
22 |
23 |
--------------------------------------------------------------------------------
/226-invert-binary-tree/226-invert-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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
9 | if root is None:
10 | return
11 | self.invertTree(root.left)
12 | self.invertTree(root.right)
13 | l = root.left
14 | r = root.right
15 | root.left = r
16 | root.right = l
17 | return root
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/226-invert-binary-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/226-invert-binary-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree, invert the tree, and return its root.
2 |
3 |
4 |
Example 1:
5 |

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

12 |
Input: root = [2,1,3]
13 | Output: [2,3,1]
14 |
15 |
16 |
Example 3:
17 |
18 |
Input: root = []
19 | Output: []
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | - The number of nodes in the tree is in the range
[0, 100]
.
27 | -100 <= Node.val <= 100
28 |
29 |
--------------------------------------------------------------------------------
/229-majority-element-ii/229-majority-element-ii.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def majorityElement(self, nums: List[int]) -> List[int]:
3 | n = len(nums)
4 | majority = n//3
5 | D = {}
6 | for n in nums:
7 | if n in D:
8 | D[n] += 1
9 | else:
10 | D[n] = 1
11 | s = set()
12 | for n in nums:
13 | if D[n] > majority:
14 | s.add(n)
15 | return s
16 |
17 |
--------------------------------------------------------------------------------
/229-majority-element-ii/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/229-majority-element-ii/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an integer array of size n
, find all elements that appear more than ⌊ n/3 ⌋
times.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: nums = [3,2,3]
7 | Output: [3]
8 |
9 |
10 |
Example 2:
11 |
12 |
Input: nums = [1]
13 | Output: [1]
14 |
15 |
16 |
Example 3:
17 |
18 |
Input: nums = [1,2]
19 | Output: [1,2]
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | 1 <= nums.length <= 5 * 104
27 | -109 <= nums[i] <= 109
28 |
29 |
30 |
31 |
Follow up: Could you solve the problem in linear time and in O(1)
space?
32 |
--------------------------------------------------------------------------------
/232-implement-queue-using-stacks/232-implement-queue-using-stacks.py:
--------------------------------------------------------------------------------
1 | class MyQueue:
2 |
3 | def __init__(self):
4 | self.S1 = [] #[1,2]
5 | self.S2 = [] #[2]
6 |
7 | def push(self, x: int) -> None:
8 | self.S1.append(x)
9 |
10 | def peek(self) -> int:
11 | if len(self.S2) != 0:
12 | return self.S2[-1]
13 | else:
14 | return self.S1[0] #[1]
15 |
16 | def pop(self) -> int:
17 | if len(self.S2) == 0:
18 | while len(self.S1) != 0:
19 | temp = self.S1.pop() #2
20 | self.S2.append(temp)
21 | return self.S2.pop()
22 |
23 | def empty(self) -> bool:
24 | if len(self.S1) == 0 and len(self.S2) == 0:
25 | return True
26 | return False
27 |
28 |
29 |
30 | # Your MyQueue object will be instantiated and called as such:
31 | # obj = MyQueue()
32 | # obj.push(x)
33 | # param_2 = obj.pop()
34 | # param_3 = obj.peek()
35 | # param_4 = obj.empty()
--------------------------------------------------------------------------------
/232-implement-queue-using-stacks/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/234-palindrome-linked-list/234-palindrome-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 notexactcopy(self, head, newnode):
8 | if head is None:
9 | head = newnode
10 | else:
11 | newnode.next = head
12 | head = newnode
13 | return head
14 |
15 |
16 | def isPalindrome(self, head: Optional[ListNode]) -> bool:
17 | head1 = None
18 | temp = head
19 | while temp:
20 | newnode = ListNode(temp.val) #1
21 | head1 = self.notexactcopy(head1, newnode)
22 | temp = temp.next
23 | t1 = head
24 | t2 = head1
25 | while t1:
26 | if t1.val != t2.val:
27 | return False
28 | t1 = t1.next
29 | t2 = t2.next
30 | return True
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/234-palindrome-linked-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/234-palindrome-linked-list/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the head
of a singly linked list, return true
if it is a palindrome.
2 |
3 |
4 |
Example 1:
5 |

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

12 |
Input: head = [1,2]
13 | Output: false
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | - The number of nodes in the list is in the range
[1, 105]
.
21 | 0 <= Node.val <= 9
22 |
23 |
24 |
25 |
Follow up: Could you do it in
O(n)
time and
O(1)
space?
--------------------------------------------------------------------------------
/237-delete-node-in-a-linked-list/237-delete-node-in-a-linked-list.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, x):
4 | # self.val = x
5 | # self.next = None
6 |
7 | class Solution:
8 | def deleteNode(self, node):
9 | """
10 | :type node: ListNode
11 | :rtype: void Do not return anything, modify node in-place instead.
12 | """
13 | temp = node.next
14 | node.val = temp.val
15 | node.next = node.next.next
16 | del(temp)
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/237-delete-node-in-a-linked-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/242-valid-anagram/242-valid-anagram.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isAnagram(self, s: str, t: str) -> bool:
3 | if len(s) != len(t):
4 | return False
5 | DC1 = {}
6 | DC2 = {}
7 | for i in s:
8 | if i in DC1:
9 | DC1[i] += 1
10 | else:
11 | DC1[i] = 1
12 | for j in t:
13 | if j in DC2:
14 | DC2[j] += 1
15 | else:
16 | DC2[j] = 1
17 | for k in s:
18 | if k not in DC2.keys():
19 | return False
20 | if DC1[k] != DC2[k]:
21 | return False
22 | return True
23 |
--------------------------------------------------------------------------------
/242-valid-anagram/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/242-valid-anagram/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given two strings s
and t
, return true
if t
is an anagram of s
, and false
otherwise.
2 |
3 |
An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.
4 |
5 |
6 |
Example 1:
7 |
Input: s = "anagram", t = "nagaram"
8 | Output: true
9 |
Example 2:
10 |
Input: s = "rat", t = "car"
11 | Output: false
12 |
13 |
14 |
Constraints:
15 |
16 |
17 | 1 <= s.length, t.length <= 5 * 104
18 | s
and t
consist of lowercase English letters.
19 |
20 |
21 |
22 |
Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?
23 |
--------------------------------------------------------------------------------
/257-binary-tree-paths/257-binary-tree-paths.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 |
9 | def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
10 | if root is None:
11 | return []
12 | l = self.binaryTreePaths(root.left) #2-> []
13 | r = self.binaryTreePaths(root.right) #5-> left ->[], 5-> r->[]
14 | ans = []
15 | a = "" #""
16 | a += str(root.val)
17 | if l == [] and r == []:
18 | ans.append(a)
19 | return ans
20 | a += "->"
21 | if l == [] and r != []:
22 | for j in r:
23 | ans.append(a + j)
24 | return ans
25 | if r == [] and l != []:
26 | for i in l:
27 | ans.append(a + i)
28 | return ans
29 | for i in l:
30 | ans.append(a + i)
31 | for j in r:
32 | ans.append(a + j)
33 | return ans
34 |
35 |
36 |
37 | #l: left subtree paths from root to leaf ["2->5"]
38 | #r: right subtree paths from root to leaf ["3"]
39 |
40 | """
41 | ans = [1]
42 | l = ["2,3,1", "2,4,5"]
43 | """
--------------------------------------------------------------------------------
/257-binary-tree-paths/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/257-binary-tree-paths/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree, return all root-to-leaf paths in any order.
2 |
3 |
A leaf is a node with no children.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: root = [1,2,3,null,5]
9 | Output: ["1->2->5","1->3"]
10 |
11 |
12 |
Example 2:
13 |
14 |
Input: root = [1]
15 | Output: ["1"]
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | - The number of nodes in the tree is in the range
[1, 100]
.
23 | -100 <= Node.val <= 100
24 |
25 |
--------------------------------------------------------------------------------
/268-missing-number/268-missing-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def missingNumber(self, nums: List[int]) -> int:
3 | n = len(nums)
4 | total = n*(n+1) // 2
5 | summ = 0
6 | for i in nums:
7 | summ += i
8 | return total - summ
9 |
--------------------------------------------------------------------------------
/268-missing-number/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/278-first-bad-version/278-first-bad-version.py:
--------------------------------------------------------------------------------
1 | # The isBadVersion API is already defined for you.
2 | #def isBadVersion(version: int) -> bool:
3 |
4 | class Solution:
5 | def firstBadVersion(self, n: int) -> int:
6 | low = 1
7 | high = n
8 | ans = 0
9 | while low <= high:
10 | mid = (low+high)//2
11 | if isBadVersion(mid) == True:
12 | ans = mid
13 | high = mid-1
14 | elif isBadVersion(mid) != True:
15 | low = mid + 1
16 | return ans
17 |
18 |
19 |
20 |
21 |
22 | """
23 | low = 0
24 | high = len(a) -1
25 | while low <= high:
26 | mid = (low+high) // 2
27 | if arr[mid] == target:
28 | return True
29 | if arr[mid] < target:
30 | low = mid + 1
31 | if arr[mid] > target:
32 | high = mid - 1
33 |
34 | """
35 |
36 |
--------------------------------------------------------------------------------
/278-first-bad-version/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/278-first-bad-version/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad.
2 |
3 |
Suppose you have n
versions [1, 2, ..., n]
and you want to find out the first bad one, which causes all the following ones to be bad.
4 |
5 |
You are given an API bool isBadVersion(version)
which returns whether version
is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: n = 5, bad = 4
11 | Output: 4
12 | Explanation:
13 | call isBadVersion(3) -> false
14 | call isBadVersion(5) -> true
15 | call isBadVersion(4) -> true
16 | Then 4 is the first bad version.
17 |
18 |
19 |
Example 2:
20 |
21 |
Input: n = 1, bad = 1
22 | Output: 1
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
29 | 1 <= bad <= n <= 231 - 1
30 |
31 |
--------------------------------------------------------------------------------
/287-find-the-duplicate-number/287-find-the-duplicate-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findDuplicate(self, nums: List[int]) -> int:
3 | start = 1
4 | end = len(nums) -1
5 | while start <= end:
6 | mid = (start+end) // 2
7 | cnt = 0
8 | for n in nums:
9 | if n <= mid:
10 | cnt += 1
11 | if cnt > mid:
12 | end = mid -1
13 | else:
14 | start = mid + 1
15 | return start
16 |
17 |
--------------------------------------------------------------------------------
/287-find-the-duplicate-number/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/287-find-the-duplicate-number/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an array of integers nums
containing n + 1
integers where each integer is in the range [1, n]
inclusive.
2 |
3 |
There is only one repeated number in nums
, return this repeated number.
4 |
5 |
You must solve the problem without modifying the array nums
and uses only constant extra space.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: nums = [1,3,4,2,2]
11 | Output: 2
12 |
13 |
14 |
Example 2:
15 |
16 |
Input: nums = [3,1,3,4,2]
17 | Output: 3
18 |
19 |
20 |
21 |
Constraints:
22 |
23 |
24 | 1 <= n <= 105
25 | nums.length == n + 1
26 | 1 <= nums[i] <= n
27 | - All the integers in
nums
appear only once except for precisely one integer which appears two or more times.
28 |
29 |
30 |
31 |
Follow up:
32 |
33 |
34 | - How can we prove that at least one duplicate number must exist in
nums
?
35 | - Can you solve the problem in linear runtime complexity?
36 |
37 |
--------------------------------------------------------------------------------
/31-next-permutation/31-next-permutation.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def nextgreaterindex(self, nums, target, i):
3 | start = i
4 | end = len(nums) - 1
5 | larger = -1
6 | while start <= end:
7 | mid = (start + end) // 2
8 | if nums[mid] > target:
9 | start = mid + 1
10 | larger = mid
11 | elif nums[mid] <= target:
12 | end = mid - 1
13 | return larger
14 |
15 | def reversee(self, nums, i):
16 | start = i
17 | end = len(nums) - 1
18 | while start < end:
19 | nums[start] , nums[end] = nums[end], nums[start]
20 | start += 1
21 | end -= 1
22 |
23 |
24 | def nextPermutation(self, nums: List[int]) -> None:
25 | """
26 | Do not return anything, modify nums in-place instead.
27 | """
28 |
29 | if len(nums) == 1:
30 | return nums
31 | for n in range(len(nums)-2, -1, -1):
32 | if nums[n] < nums[n+1]:
33 | largerele = self.nextgreaterindex(nums, nums[n], n+1)
34 | nums[n] , nums[largerele] = nums[largerele] , nums[n]
35 | self.reversee(nums, n+1)
36 | return nums
37 | nums.reverse()
38 | return nums
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 | """
49 | #Recursion #Bitwise
50 | Brute-Force 2**n
51 | > Find all the possible permutations
52 | > sort
53 | > given -> next
54 | """
55 |
56 |
57 |
--------------------------------------------------------------------------------
/31-next-permutation/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/322-coin-change/322-coin-change.py:
--------------------------------------------------------------------------------
1 | import sys
2 | class Solution:
3 | def coinChange(self, coins: List[int], amount: int) -> int:
4 | n = len(coins)
5 | DP = []
6 | for row in range(n+1):
7 | columns = [-1] * (amount+1)
8 | DP.append(columns)
9 | #initialization
10 | for j in range(amount+1):
11 | DP[0][j] = sys.maxsize - 1
12 | for i in range(1, n+1):
13 | DP[i][0] = 0
14 | for i in range(1, n+1):
15 | for j in range(1, amount +1):
16 | if i == 1:
17 | if (j % coins[i-1]) == 0:
18 | DP[i][j] = (j // coins[i-1])
19 | else:
20 | DP[i][j] = sys.maxsize - 1
21 | #code
22 | for i in range(2, n+1):
23 | for j in range(1, amount+1):
24 | if coins[i-1] > j:
25 | DP[i][j] = DP[i-1][j]
26 | else:
27 | DP[i][j] = min(1 + DP[i][j-coins[i-1]], DP[i-1][j])
28 | if DP[n][amount] != sys.maxsize-1:
29 | return DP[n][amount]
30 | return -1
31 |
32 |
--------------------------------------------------------------------------------
/322-coin-change/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/322-coin-change/README.md:
--------------------------------------------------------------------------------
1 | Medium
You are given an integer array coins
representing coins of different denominations and an integer amount
representing a total amount of money.
2 |
3 |
Return the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1
.
4 |
5 |
You may assume that you have an infinite number of each kind of coin.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: coins = [1,2,5], amount = 11
11 | Output: 3
12 | Explanation: 11 = 5 + 5 + 1
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: coins = [2], amount = 3
18 | Output: -1
19 |
20 |
21 |
Example 3:
22 |
23 |
Input: coins = [1], amount = 0
24 | Output: 0
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 1 <= coins.length <= 12
32 | 1 <= coins[i] <= 231 - 1
33 | 0 <= amount <= 104
34 |
35 |
--------------------------------------------------------------------------------
/346-moving-average-from-data-stream/346-moving-average-from-data-stream.py:
--------------------------------------------------------------------------------
1 | class MovingAverage:
2 |
3 | def __init__(self, size: int):
4 | self.windowsize = size
5 | self.curr_size = 0
6 | self.prev_avg = 0
7 | self.prev_size = 0
8 | self.values = []
9 | self.minus = 0
10 |
11 | def next(self, val: int) -> float:
12 | self.curr_size += 1
13 | self.values.append(val)
14 | if self.curr_size <= self.windowsize:
15 | self.prev_avg = (self.prev_avg * self.prev_size + val)/(self.curr_size)
16 | self.prev_size += 1
17 | elif self.curr_size > self.windowsize:
18 | self.prev_avg = (self.prev_avg * self.windowsize - self.values[self.minus] + val)/ self.windowsize
19 | self.minus += 1
20 | return self.prev_avg
21 |
22 |
23 |
24 |
25 |
26 | # Your MovingAverage object will be instantiated and called as such:
27 | # obj = MovingAverage(size)
28 | # param_1 = obj.next(val)
29 |
30 | """
31 | pseudo code:
32 |
33 | step1: w.size = 3, sod = 1, 1/1
34 | 1/1 = 1.0
35 | prevavg * prevsize + newnum/ currsize
36 | 1.0 * 1 + 10/ 2
37 | step2: w.size = 3, sod = 2, sum/2
38 | step3: w.size == stream.size, sum/size
39 | step4: stream -> initial pos pop -> next new element insert
40 | (4.66667 *3 - 1 + 5)= sum/size
41 | 1 + 10 + 3/ 3
42 | avg * 3 - 1 + 5 = /3
43 | """
--------------------------------------------------------------------------------
/346-moving-average-from-data-stream/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/346-moving-average-from-data-stream/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a stream of integers and a window size, calculate the moving average of all integers in the sliding window.
2 |
3 |
Implement the MovingAverage
class:
4 |
5 |
6 | MovingAverage(int size)
Initializes the object with the size of the window size
.
7 | double next(int val)
Returns the moving average of the last size
values of the stream.
8 |
9 |
10 |
11 |
Example 1:
12 |
13 |
Input
14 | ["MovingAverage", "next", "next", "next", "next"]
15 | [[3], [1], [10], [3], [5]]
16 | Output
17 | [null, 1.0, 5.5, 4.66667, 6.0]
18 |
19 | Explanation
20 | MovingAverage movingAverage = new MovingAverage(3);
21 | movingAverage.next(1); // return 1.0 = 1 / 1
22 | movingAverage.next(10); // return 5.5 = (1 + 10) / 2
23 | movingAverage.next(3); // return 4.66667 = (1 + 10 + 3) / 3
24 | movingAverage.next(5); // return 6.0 = (10 + 3 + 5) / 3
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 1 <= size <= 1000
32 | -105 <= val <= 105
33 | - At most
104
calls will be made to next
.
34 |
35 |
--------------------------------------------------------------------------------
/347-top-k-frequent-elements/347-top-k-frequent-elements.py:
--------------------------------------------------------------------------------
1 | import heapq as heap
2 | class Solution:
3 | def topKFrequent(self, nums: List[int], k: int) -> List[int]:
4 | D = {}
5 | for n in nums:
6 | if n in D:
7 | D[n] += 1
8 | else:
9 | D[n] = 1
10 | max_heap = []
11 | S = set()
12 | ans = []
13 | for n in range(len(nums)):
14 | if nums[n] not in S:
15 | heap.heappush(max_heap, (-1 * D[nums[n]], nums[n]))
16 | S.add(nums[n])
17 | while k > 0:
18 | mini = heap.heappop(max_heap) #(cnt, num)
19 | ans.append(mini[1])
20 | k -= 1
21 | return ans
22 |
23 |
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/347-top-k-frequent-elements/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/347-top-k-frequent-elements/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an integer array nums
and an integer k
, return the k
most frequent elements. You may return the answer in any order.
2 |
3 |
4 |
Example 1:
5 |
Input: nums = [1,1,1,2,2,3], k = 2
6 | Output: [1,2]
7 |
Example 2:
8 |
Input: nums = [1], k = 1
9 | Output: [1]
10 |
11 |
12 |
Constraints:
13 |
14 |
15 | 1 <= nums.length <= 105
16 | -104 <= nums[i] <= 104
17 | k
is in the range [1, the number of unique elements in the array]
.
18 | - It is guaranteed that the answer is unique.
19 |
20 |
21 |
22 |
Follow up: Your algorithm's time complexity must be better than O(n log n)
, where n is the array's size.
23 |
--------------------------------------------------------------------------------
/349-intersection-of-two-arrays/349-intersection-of-two-arrays.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def Binarysearch(self, arr, target):
3 | low = 0
4 | high = len(arr) - 1
5 | while low <= high:
6 | mid = (low+high)//2
7 | if arr[mid] == target:
8 | return True
9 | elif arr[mid] > target:
10 | high = mid - 1
11 | else:
12 | low = mid + 1
13 | return False
14 |
15 | def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
16 | l1 = len(nums1)
17 | l2 = len(nums2)
18 | S = set()
19 | nums1.sort()
20 | nums2.sort()
21 | if l1 < l2:
22 | for i in nums1:
23 | if self.Binarysearch(nums2, i) == True:
24 | S.add(i)
25 | else:
26 | for i in nums2:
27 | if self.Binarysearch(nums1, i) == True:
28 | S.add(i)
29 | return S
30 |
31 |
32 |
33 |
34 |
35 |
--------------------------------------------------------------------------------
/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 | """
4 | [1,3,5,6]
5 | 2
6 | """
7 | low = 0
8 | high = len(nums)-1 #3
9 | ans = high + 1
10 | while low <= high: #0<3
11 | mid = (low+high)//2 #1
12 | if nums[mid] == target:
13 | return mid
14 | if nums[mid] > target:
15 | high = mid -1 #0
16 | ans = mid
17 | if nums[mid] < target:
18 | low = mid + 1 #low = 4
19 | return ans
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 | """
31 | low = 0
32 | high = len(arr)-1
33 | while low <= high:
34 | mid = (low+high)//2
35 | if arr[mid] == target:
36 | return mid
37 | if arr[mid] > target:
38 | high = mid -1
39 | if arr[mid] < target:
40 | low = mid + 1
41 |
42 | """
43 |
--------------------------------------------------------------------------------
/35-search-insert-position/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/35-search-insert-position/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
2 |
3 |
You must write an algorithm with O(log n)
runtime complexity.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [1,3,5,6], target = 5
9 | Output: 2
10 |
11 |
12 |
Example 2:
13 |
14 |
Input: nums = [1,3,5,6], target = 2
15 | Output: 1
16 |
17 |
18 |
Example 3:
19 |
20 |
Input: nums = [1,3,5,6], target = 7
21 | Output: 4
22 |
23 |
24 |
25 |
Constraints:
26 |
27 |
28 | 1 <= nums.length <= 104
29 | -104 <= nums[i] <= 104
30 | nums
contains distinct values sorted in ascending order.
31 | -104 <= target <= 104
32 |
33 |
--------------------------------------------------------------------------------
/359-logger-rate-limiter/359-logger-rate-limiter.py:
--------------------------------------------------------------------------------
1 | class Logger:
2 |
3 | def __init__(self):
4 | self.logger = {}
5 |
6 | #["Logger","shouldPrintMessage","shouldPrintMessage"]
7 | #[[],[100,"bug"],[111,"bug"]]
8 |
9 | def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
10 | if message in self.logger:
11 | if self.logger[message] + 10 <= timestamp:
12 | self.logger[message] = timestamp
13 | return True
14 | else:
15 | return False
16 | elif message not in self.logger:
17 | self.logger[message] = timestamp #{"bug" : 100}
18 | return True
19 |
20 |
21 |
22 | # Your Logger object will be instantiated and called as such:
23 | # obj = Logger()
24 | # param_1 = obj.shouldPrintMessage(timestamp,message)
25 |
26 |
27 | """
28 | Pseudo Code:
29 | [[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | """
--------------------------------------------------------------------------------
/359-logger-rate-limiter/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/367-valid-perfect-square/367-valid-perfect-square.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def isPerfectSquare(self, num: int) -> bool:
3 | if num == 1:
4 | return True
5 | low = 1
6 | high = num // 2
7 | while low <= high:
8 | mid = (low+high) // 2
9 | if mid * mid == num:
10 | return True
11 | elif mid * mid > num:
12 | high = mid - 1
13 | elif mid * mid < num:
14 | low = mid + 1
15 | return False
16 |
17 |
--------------------------------------------------------------------------------
/367-valid-perfect-square/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/367-valid-perfect-square/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a positive integer num, write a function which returns True if num is a perfect square else False.
2 |
3 |
Follow up: Do not use any built-in library function such as sqrt
.
4 |
5 |
6 |
Example 1:
7 |
Input: num = 16
8 | Output: true
9 |
Example 2:
10 |
Input: num = 14
11 | Output: false
12 |
13 |
14 |
Constraints:
15 |
16 |
17 | 1 <= num <= 2^31 - 1
18 |
19 |
--------------------------------------------------------------------------------
/37-sudoku-solver/37-sudoku-solver.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def issafe(self, row, col, board, value):
3 | for i in range(9):
4 | if board[row][i] == value:
5 | return False
6 | if board[i][col] == value:
7 | return False
8 | if board[3* (row//3) + i// 3][3 * (col//3) + i % 3] == value:
9 | return False
10 | return True
11 |
12 | def solve(self, board):
13 | n = 9
14 | for i in range(9):
15 | for j in range(9):
16 | if board[i][j] == ".":
17 | for k in range(1, 10):
18 | if self.issafe(i, j, board, str(k)):
19 | board[i][j] = str(k)
20 | aagey = self.solve(board)
21 | if aagey:
22 | return True
23 | else:
24 | board[i][j] = "."
25 | return False
26 | return True
27 |
28 |
29 | def solveSudoku(self, board: List[List[str]]) -> None:
30 | """
31 | Do not return anything, modify board in-place instead.
32 | """
33 | self.solve(board)
--------------------------------------------------------------------------------
/37-sudoku-solver/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/389-find-the-difference/389-find-the-difference.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findTheDifference(self, s: str, t: str) -> str:
3 | D1 = {}
4 | for i in s:
5 | if i in D1:
6 | D1[i] += 1
7 | else:
8 | D1[i] = 1
9 | D2 = {}
10 | for j in t:
11 | if j in D2:
12 | D2[j] += 1
13 | else:
14 | D2[j] = 1
15 | for k in t:
16 | if k not in D1:
17 | return k
18 | elif (D1[k] != D2[k]):
19 | return k
20 |
--------------------------------------------------------------------------------
/389-find-the-difference/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/389-find-the-difference/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are given two strings s
and t
.
2 |
3 |
String t
is generated by random shuffling string s
and then add one more letter at a random position.
4 |
5 |
Return the letter that was added to t
.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: s = "abcd", t = "abcde"
11 | Output: "e"
12 | Explanation: 'e' is the letter that was added.
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: s = "", t = "y"
18 | Output: "y"
19 |
20 |
21 |
22 |
Constraints:
23 |
24 |
25 | 0 <= s.length <= 1000
26 | t.length == s.length + 1
27 | s
and t
consist of lowercase English letters.
28 |
29 |
--------------------------------------------------------------------------------
/412-fizz-buzz/412-fizz-buzz.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def fizzBuzz(self, n: int) -> List[str]:
3 | Ans = [0] * (n+1)
4 | #print(Ans)
5 | for i in range(1 , n+1):
6 | if i % 3 == 0 and i % 5 == 0:
7 | Ans[i] = "FizzBuzz"
8 | elif i % 3 == 0:
9 | Ans[i] = "Fizz"
10 | elif i % 5 == 0:
11 | Ans[i] = "Buzz"
12 | else:
13 | Ans[i] = str(i)
14 | Ans.pop(0)
15 | return Ans
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/412-fizz-buzz/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/412-fizz-buzz/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer n
, return a string array answer
(1-indexed) where:
2 |
3 |
4 | answer[i] == "FizzBuzz"
if i
is divisible by 3
and 5
.
5 | answer[i] == "Fizz"
if i
is divisible by 3
.
6 | answer[i] == "Buzz"
if i
is divisible by 5
.
7 | answer[i] == i
(as a string) if none of the above conditions are true.
8 |
9 |
10 |
11 |
Example 1:
12 |
Input: n = 3
13 | Output: ["1","2","Fizz"]
14 |
Example 2:
15 |
Input: n = 5
16 | Output: ["1","2","Fizz","4","Buzz"]
17 |
Example 3:
18 |
Input: n = 15
19 | Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]
20 |
21 |
22 |
Constraints:
23 |
24 |
27 |
--------------------------------------------------------------------------------
/415-add-strings/415-add-strings.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def addStrings(self, num1: str, num2: str) -> str:
3 | num1 = int(num1)
4 | num2 = int(num2)
5 | ans = num1 + num2
6 | return str(ans)
7 |
--------------------------------------------------------------------------------
/415-add-strings/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/415-add-strings/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given two non-negative integers, num1
and num2
represented as string, return the sum of num1
and num2
as a string.
2 |
3 |
You must solve the problem without using any built-in library for handling large integers (such as BigInteger
). You must also not convert the inputs to integers directly.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: num1 = "11", num2 = "123"
9 | Output: "134"
10 |
11 |
12 |
Example 2:
13 |
14 |
Input: num1 = "456", num2 = "77"
15 | Output: "533"
16 |
17 |
18 |
Example 3:
19 |
20 |
Input: num1 = "0", num2 = "0"
21 | Output: "0"
22 |
23 |
24 |
25 |
Constraints:
26 |
27 |
28 | 1 <= num1.length, num2.length <= 104
29 | num1
and num2
consist of only digits.
30 | num1
and num2
don't have any leading zeros except for the zero itself.
31 |
32 |
--------------------------------------------------------------------------------
/416-partition-equal-subset-sum/416-partition-equal-subset-sum.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def subsetsum(self, nums, summ, n):
3 | #To write whether the array contains a subset whose sum is equivalent to the given sum.
4 | #This is basically a subset sum problem. Will be doing it using recursion + memoization first.
5 | #This is also a variation of 0-1 knapsack.
6 |
7 | #creating a 2D matrix for the changing variables. taking rows as n+1 and columns as summ+1
8 | DP = []
9 | for row in range(n+1):
10 | column = [-1] * (summ+1)
11 | DP.append(column)
12 | #initialization
13 | for j in range(summ+1):
14 | DP[0][j] = False
15 | for i in range(n+1):
16 | DP[i][0] = True
17 | #code
18 | for i in range(1, n+1):
19 | for j in range(1, summ+1):
20 | if nums[i-1] <= j:
21 | DP[i][j] = DP[i-1][j-nums[i-1]] or DP[i-1][j]
22 | else:
23 | DP[i][j] = DP[i-1][j]
24 | return DP[n][summ]
25 |
26 | def canPartition(self, nums: List[int]) -> bool:
27 | summ = 0
28 | for n in nums:
29 | summ = summ + n
30 | if summ % 2 != 0:
31 | return False
32 | return self.subsetsum(nums, summ//2, len(nums))
33 |
34 |
--------------------------------------------------------------------------------
/416-partition-equal-subset-sum/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/416-partition-equal-subset-sum/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given a non-empty array nums
containing only positive integers, find if the array can be partitioned into two subsets such that the sum of elements in both subsets is equal.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: nums = [1,5,11,5]
7 | Output: true
8 | Explanation: The array can be partitioned as [1, 5, 5] and [11].
9 |
10 |
11 |
Example 2:
12 |
13 |
Input: nums = [1,2,3,5]
14 | Output: false
15 | Explanation: The array cannot be partitioned into equal sum subsets.
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | 1 <= nums.length <= 200
23 | 1 <= nums[i] <= 100
24 |
25 |
--------------------------------------------------------------------------------
/451-sort-characters-by-frequency/451-sort-characters-by-frequency.py:
--------------------------------------------------------------------------------
1 | import heapq as heap
2 | class Solution:
3 | def frequencySort(self, s: str) -> str:
4 | D = {}
5 | for i in s:
6 | if i in D:
7 | D[i] += 1
8 | else:
9 | D[i] = 1
10 | h = []
11 | ans = ""
12 | for key,value in D.items():
13 | h.append((value * -1, key))
14 | heapq.heapify(h)
15 | #print(h)
16 | #[(-2, 'e'), (-1, 'r'), (-1, 't')]
17 | lenn = len(s)
18 | leng = 0
19 | while leng != lenn:
20 | largest = heapq.heappop(h)
21 | for i in range(largest[0] * -1):
22 | ans += largest[1]
23 | leng += 1
24 | return ans
25 |
26 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/451-sort-characters-by-frequency/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/451-sort-characters-by-frequency/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given a string s
, sort it in decreasing order based on the frequency of the characters. The frequency of a character is the number of times it appears in the string.
2 |
3 |
Return the sorted string. If there are multiple answers, return any of them.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: s = "tree"
9 | Output: "eert"
10 | Explanation: 'e' appears twice while 'r' and 't' both appear once.
11 | So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
12 |
13 |
14 |
Example 2:
15 |
16 |
Input: s = "cccaaa"
17 | Output: "aaaccc"
18 | Explanation: Both 'c' and 'a' appear three times, so both "cccaaa" and "aaaccc" are valid answers.
19 | Note that "cacaca" is incorrect, as the same characters must be together.
20 |
21 |
22 |
Example 3:
23 |
24 |
Input: s = "Aabb"
25 | Output: "bbAa"
26 | Explanation: "bbaA" is also a valid answer, but "Aabb" is incorrect.
27 | Note that 'A' and 'a' are treated as two different characters.
28 |
29 |
30 |
31 |
Constraints:
32 |
33 |
34 | 1 <= s.length <= 5 * 105
35 | s
consists of uppercase and lowercase English letters and digits.
36 |
37 |
--------------------------------------------------------------------------------
/48-rotate-image/48-rotate-image.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def rotate(self, matrix: List[List[int]]) -> None:
3 | """
4 | Do not return anything, modify matrix in-place instead.
5 | """
6 | row = len(matrix)
7 | column = len(matrix[0])
8 | for r in range(row):
9 | for c in range(r, column):
10 | matrix[r][c] , matrix[c][r] = matrix[c][r], matrix[r][c]
11 | for m in matrix:
12 | m.reverse()
13 |
--------------------------------------------------------------------------------
/48-rotate-image/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/48-rotate-image/README.md:
--------------------------------------------------------------------------------
1 | Medium
You are given an n x n
2D matrix
representing an image, rotate the image by 90 degrees (clockwise).
2 |
3 |
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
9 | Output: [[7,4,1],[8,5,2],[9,6,3]]
10 |
11 |
12 |
Example 2:
13 |

14 |
Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
15 | Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | n == matrix.length == matrix[i].length
23 | 1 <= n <= 20
24 | -1000 <= matrix[i][j] <= 1000
25 |
26 |
--------------------------------------------------------------------------------
/485-max-consecutive-ones/485-max-consecutive-ones.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
3 | maxi = 0
4 | cnt = 0
5 | for n in nums:
6 | if n == 1:
7 | cnt += 1
8 | maxi = max(maxi, cnt)
9 | else:
10 | cnt = 0
11 | return maxi
12 |
13 |
--------------------------------------------------------------------------------
/485-max-consecutive-ones/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/485-max-consecutive-ones/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a binary array nums
, return the maximum number of consecutive 1
's in the array.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: nums = [1,1,0,1,1,1]
7 | Output: 3
8 | Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.
9 |
10 |
11 |
Example 2:
12 |
13 |
Input: nums = [1,0,1,1,0,1]
14 | Output: 2
15 |
16 |
17 |
18 |
Constraints:
19 |
20 |
21 | 1 <= nums.length <= 105
22 | nums[i]
is either 0
or 1
.
23 |
24 |
--------------------------------------------------------------------------------
/50-powx-n/50-powx-n.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def myPow(self, x: float, n: int) -> float: #2 n = 3
3 | if n == 0:
4 | return 1
5 | if n == 1:
6 | return x
7 | if n % 2 == 0:
8 | y = self.myPow(x , n//2)
9 | return y * y
10 | if n > 0:
11 | return x * self.myPow(x, n-1)
12 | if n < 0:
13 | return 1 / x * self.myPow(x, n+1)
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/50-powx-n/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/50-powx-n/README.md:
--------------------------------------------------------------------------------
1 | Medium
Implement pow(x, n), which calculates x
raised to the power n
(i.e., xn
).
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: x = 2.00000, n = 10
7 | Output: 1024.00000
8 |
9 |
10 |
Example 2:
11 |
12 |
Input: x = 2.10000, n = 3
13 | Output: 9.26100
14 |
15 |
16 |
Example 3:
17 |
18 |
Input: x = 2.00000, n = -2
19 | Output: 0.25000
20 | Explanation: 2-2 = 1/22 = 1/4 = 0.25
21 |
22 |
23 |
24 |
Constraints:
25 |
26 |
27 | -100.0 < x < 100.0
28 | -231 <= n <= 231-1
29 | -104 <= xn <= 104
30 |
31 |
--------------------------------------------------------------------------------
/509-fibonacci-number/509-fibonacci-number.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def fib(self, n: int) -> int:
3 | ans = [0,1]
4 | #[0,1,1,2,3]
5 | if n == 0:
6 | return ans[0]
7 | elif n == 1:
8 | return ans[1]
9 | #n = 4
10 | for i in range(1, n): #(2, 4) 3
11 | new = ans[-1] + ans[-2] #new = 1 + 0 = 1 #ans = [0,1,1]
12 | ans.append(new)
13 | return ans[-1]
14 |
15 |
--------------------------------------------------------------------------------
/509-fibonacci-number/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/509-fibonacci-number/README.md:
--------------------------------------------------------------------------------
1 | Easy
The Fibonacci numbers, commonly denoted F(n)
form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0
and 1
. That is,
2 |
3 |
F(0) = 0, F(1) = 1
4 | F(n) = F(n - 1) + F(n - 2), for n > 1.
5 |
6 |
7 |
Given n
, calculate F(n)
.
8 |
9 |
10 |
Example 1:
11 |
12 |
Input: n = 2
13 | Output: 1
14 | Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
15 |
16 |
17 |
Example 2:
18 |
19 |
Input: n = 3
20 | Output: 2
21 | Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
22 |
23 |
24 |
Example 3:
25 |
26 |
Input: n = 4
27 | Output: 3
28 | Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
29 |
30 |
31 |
32 |
Constraints:
33 |
34 |
37 |
--------------------------------------------------------------------------------
/53-maximum-subarray/53-maximum-subarray.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxSubArray(self, nums: List[int]) -> int:
3 | ans = -1000000000000000000
4 | add = 0
5 | for n in nums:
6 | add = add + n #1
7 | ans = max(add,ans) #1
8 | if add < 0:
9 | add = 0
10 | return ans
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/53-maximum-subarray/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/53-maximum-subarray/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
2 |
3 |
A subarray is a contiguous part of an array.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
9 | Output: 6
10 | Explanation: [4,-1,2,1] has the largest sum = 6.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [1]
16 | Output: 1
17 |
18 |
19 |
Example 3:
20 |
21 |
Input: nums = [5,4,-1,7,8]
22 | Output: 23
23 |
24 |
25 |
26 |
Constraints:
27 |
28 |
29 | 1 <= nums.length <= 105
30 | -104 <= nums[i] <= 104
31 |
32 |
33 |
34 |
Follow up: If you have figured out the O(n)
solution, try coding another solution using the divide and conquer approach, which is more subtle.
35 |
--------------------------------------------------------------------------------
/540-single-element-in-a-sorted-array/540-single-element-in-a-sorted-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def singleNonDuplicate(self, nums: List[int]) -> int:
3 | D = {}
4 | for n in nums:
5 | if n in D:
6 | D[n] += 1
7 | else:
8 | D[n] = 1
9 | for n in nums:
10 | if D[n] == 1:
11 | return n
12 |
13 |
--------------------------------------------------------------------------------
/540-single-element-in-a-sorted-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/540-single-element-in-a-sorted-array/README.md:
--------------------------------------------------------------------------------
1 | Medium
You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.
2 |
3 |
Return the single element that appears only once.
4 |
5 |
Your solution must run in O(log n)
time and O(1)
space.
6 |
7 |
8 |
Example 1:
9 |
Input: nums = [1,1,2,3,3,4,4,8,8]
10 | Output: 2
11 |
Example 2:
12 |
Input: nums = [3,3,7,7,10,11,11]
13 | Output: 10
14 |
15 |
16 |
Constraints:
17 |
18 |
19 | 1 <= nums.length <= 105
20 | 0 <= nums[i] <= 105
21 |
22 |
--------------------------------------------------------------------------------
/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 heighbt(self, root):
9 | if root is None:
10 | return 0
11 | return 1 + max(self.heighbt(root.left), self.heighbt(root.right))
12 |
13 | def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
14 | if root is None:
15 | return 0
16 | ldia = self.diameterOfBinaryTree(root.left)
17 | rdia = self.diameterOfBinaryTree(root.right)
18 | maxdia = max(ldia, rdia)
19 | lheight = self.heighbt(root.left)
20 | rheight = self.heighbt(root.right)
21 | return max((lheight + rheight), maxdia)
22 |
23 |
24 | #root: height of left + height of right
25 |
26 |
27 |
--------------------------------------------------------------------------------
/543-diameter-of-binary-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/543-diameter-of-binary-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree, return the length of the diameter of the tree.
2 |
3 |
The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root
.
4 |
5 |
The length of a path between two nodes is represented by the number of edges between them.
6 |
7 |
8 |
Example 1:
9 |

10 |
Input: root = [1,2,3,4,5]
11 | Output: 3
12 | Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: root = [1,2]
18 | Output: 1
19 |
20 |
21 |
22 |
Constraints:
23 |
24 |
25 | - The number of nodes in the tree is in the range
[1, 104]
.
26 | -100 <= Node.val <= 100
27 |
28 |
--------------------------------------------------------------------------------
/56-merge-intervals/56-merge-intervals.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def merge(self, intervals: List[List[int]]) -> List[List[int]]:
3 | intervals = sorted(intervals , key = lambda x:x[0])
4 | start = -1000000
5 | end = -1000000
6 | mergedintervals = []
7 | for i in range(len(intervals)):
8 | temp = intervals[i]
9 | if temp[0] > end:
10 | if i != 0:
11 | mergedintervals.append([start , end])
12 | start = temp[0]
13 | end = temp[1]
14 | else:
15 | end = max(end , temp[1])
16 |
17 | if end != -1000000 and [start, end] not in mergedintervals:
18 | mergedintervals.append([start,end])
19 | #print("Merged intervals are >> ")
20 | return mergedintervals
21 |
--------------------------------------------------------------------------------
/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] overlaps, 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 |
--------------------------------------------------------------------------------
/572-subtree-of-another-tree/572-subtree-of-another-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 |
8 | class Solution:
9 | def sametree(self, root1, root2):
10 | if root1 == None and root2 == None:
11 | return True
12 | if root1 == None and root2 != None:
13 | return False
14 | if root1 != None and root2 == None:
15 | return False
16 | l = self.sametree(root1.left, root2.left)
17 | r = self.sametree(root1.right, root2.right)
18 | if (root1.val == root2.val) and l == True and r == True:
19 | return True
20 | return False
21 |
22 | def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
23 | if root == None and subRoot == None:
24 | return True
25 | if root == None and subRoot != None:
26 | return False
27 | if root != None and subRoot == None:
28 | return True
29 | left = self.isSubtree(root.left, subRoot) #(4,4) -> (1,4) -> False
30 | right = self.isSubtree(root.right, subRoot)
31 | if root.val == subRoot.val:
32 | l = self.sametree(root.left, subRoot.left)
33 | r = self.sametree(root.right, subRoot.right)
34 | if l == True and r == True:
35 | return True
36 | if left == True or right == True:
37 | return True
38 | return False
39 |
40 |
41 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/572-subtree-of-another-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/572-subtree-of-another-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the roots of two binary trees root
and subRoot
, return true
if there is a subtree of root
with the same structure and node values of subRoot
and false
otherwise.
2 |
3 |
A subtree of a binary tree tree
is a tree that consists of a node in tree
and all of this node's descendants. The tree tree
could also be considered as a subtree of itself.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
9 | Output: true
10 |
11 |
12 |
Example 2:
13 |

14 |
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
15 | Output: false
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | - The number of nodes in the
root
tree is in the range [1, 2000]
.
23 | - The number of nodes in the
subRoot
tree is in the range [1, 1000]
.
24 | -104 <= root.val <= 104
25 | -104 <= subRoot.val <= 104
26 |
27 |
--------------------------------------------------------------------------------
/58-length-of-last-word/58-length-of-last-word.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def lengthOfLastWord(self, s: str) -> int:
3 | s = s.split()
4 | return len(s[-1])
5 |
--------------------------------------------------------------------------------
/58-length-of-last-word/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/58-length-of-last-word/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a string s
consisting of words and spaces, return the length of the last word in the string.
2 |
3 |
A word is a maximal substring consisting of non-space characters only.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: s = "Hello World"
9 | Output: 5
10 | Explanation: The last word is "World" with length 5.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: s = " fly me to the moon "
16 | Output: 4
17 | Explanation: The last word is "moon" with length 4.
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: s = "luffy is still joyboy"
23 | Output: 6
24 | Explanation: The last word is "joyboy" with length 6.
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 1 <= s.length <= 104
32 | s
consists of only English letters and spaces ' '
.
33 | - There will be at least one word in
s
.
34 |
35 |
--------------------------------------------------------------------------------
/589-n-ary-tree-preorder-traversal/589-n-ary-tree-preorder-traversal.py:
--------------------------------------------------------------------------------
1 | """
2 | # Definition for a Node.
3 | class Node:
4 | def __init__(self, val=None, children=None):
5 | self.val = val
6 | self.children = children
7 | """
8 | from collections import deque
9 | class Solution:
10 | def preorder(self, root: 'Node') -> List[int]:
11 | if root is None:
12 | return
13 | Stack = deque()
14 | Stack.append(root)
15 | ans = []
16 | while len(Stack) > 0:
17 | temp = Stack.pop()
18 | ans.append(temp.val)
19 | for c in range(len(temp.children)-1, -1, -1):
20 | if temp.children[c] != None:
21 | Stack.append( temp.children[c])
22 | return ans
23 |
--------------------------------------------------------------------------------
/589-n-ary-tree-preorder-traversal/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/589-n-ary-tree-preorder-traversal/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of an n-ary tree, return the preorder traversal of its nodes' values.
2 |
3 |
Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)
4 |
5 |
6 |
Example 1:
7 |
8 |

9 |
10 |
Input: root = [1,null,3,2,4,null,5,6]
11 | Output: [1,3,5,6,2,4]
12 |
13 |
14 |
Example 2:
15 |
16 |

17 |
18 |
Input: root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
19 | Output: [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
20 |
21 |
22 |
23 |
Constraints:
24 |
25 |
26 | - The number of nodes in the tree is in the range
[0, 104]
.
27 | 0 <= Node.val <= 104
28 | - The height of the n-ary tree is less than or equal to
1000
.
29 |
30 |
31 |
32 |
Follow up: Recursive solution is trivial, could you do it iteratively?
33 |
--------------------------------------------------------------------------------
/66-plus-one/66-plus-one.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def plusOne(self, digits: List[int]) -> List[int]:
3 | n = ""
4 | for d in digits:
5 | n += str(d)
6 | n = int(n)
7 | n = n +1
8 | ans = []
9 | while n != 0:
10 | dig = n % 10
11 | ans.insert(0,dig)
12 | n = n // 10
13 | return ans
--------------------------------------------------------------------------------
/66-plus-one/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/69-sqrtx/69-sqrtx.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def mySqrt(self, x: int) -> int:
3 | if x == 1:
4 | return 1
5 | if x == 0:
6 | return 0
7 | low = 1
8 | high = x//2
9 | #8
10 | while low <= high: #1 < 7
11 | mid = (low+high)//2 #3
12 | if mid * mid == x:
13 | return mid
14 | if mid * mid > x:
15 | high = mid - 1 #3
16 | if mid * mid < x:
17 | low = mid + 1 #3
18 | return high
19 | """
20 | low = 0
21 | high = len(arr)-1
22 | while low < high:
23 | mid = (low + high)// 2
24 | if arr[mid] == target:
25 | return mid
26 | if arr[mid] > target:
27 | high = mid - 1
28 | if arr[mid] < target:
29 | low = mid + 1
30 | return -1
31 | """
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/69-sqrtx/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/69-sqrtx/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given a non-negative integer x
, compute and return the square root of x
.
2 |
3 |
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
4 |
5 |
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5)
or x ** 0.5
.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: x = 4
11 | Output: 2
12 |
13 |
14 |
Example 2:
15 |
16 |
Input: x = 8
17 | Output: 2
18 | Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
19 |
20 |
21 |
Constraints:
22 |
23 |
24 | 0 <= x <= 231 - 1
25 |
26 |
--------------------------------------------------------------------------------
/692-top-k-frequent-words/692-top-k-frequent-words.py:
--------------------------------------------------------------------------------
1 | import heapq as heap
2 | class Solution:
3 | def topKFrequent(self, words: List[str], k: int) -> List[str]:
4 | D = {}
5 | for w in words:
6 | if w in D:
7 | D[w] += 1
8 | else:
9 | D[w] = 1
10 | ans = []
11 | Heap = []
12 | for key,value in D.items():
13 | Heap.append((value * -1, key))
14 | heap.heapify(Heap)
15 | while k > 0:
16 | largest = heap.heappop(Heap)
17 | ans.append(largest[1])
18 | k -= 1
19 | return ans
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/692-top-k-frequent-words/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/704-binary-search/704-binary-search.py:
--------------------------------------------------------------------------------
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 nums[mid] == target:
8 | return mid
9 | elif nums[mid] > target:
10 | high = mid - 1
11 | elif nums[mid] < target:
12 | low = mid + 1
13 | return -1
14 |
15 |
16 |
--------------------------------------------------------------------------------
/704-binary-search/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/704-binary-search/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an array of integers nums
which is sorted in ascending order, and an integer target
, write a function to search target
in nums
. If target
exists, then return its index. Otherwise, return -1
.
2 |
3 |
You must write an algorithm with O(log n)
runtime complexity.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [-1,0,3,5,9,12], target = 9
9 | Output: 4
10 | Explanation: 9 exists in nums and its index is 4
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [-1,0,3,5,9,12], target = 2
16 | Output: -1
17 | Explanation: 2 does not exist in nums so return -1
18 |
19 |
20 |
21 |
Constraints:
22 |
23 |
24 | 1 <= nums.length <= 104
25 | -104 < nums[i], target < 104
26 | - All the integers in
nums
are unique.
27 | nums
is sorted in ascending order.
28 |
29 |
--------------------------------------------------------------------------------
/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 | rowl = len(matrix) #3 >> 0,1,2
7 | coll = len(matrix[0]) #4 >> 0,1,2,3
8 | """
9 | [
10 | [1,1,1,1]
11 | [1,0,1,1]
12 | [1,1,1,1]
13 | ]
14 | """
15 | row = False
16 | col = False
17 | for i in range(rowl): #i=1
18 | if matrix[i][0] == 0:
19 | col = True
20 | for j in range(coll): #j = 1
21 | if i == 0:
22 | if matrix[0][j] == 0:
23 | row = True
24 | if i != 0 and j != 0:
25 | if matrix[i][j] == 0:
26 | matrix[i][0] = 0
27 | matrix[0][j] = 0
28 | for i in range(1, rowl):
29 | for j in range(1, coll):
30 | if matrix[i][0] == 0 or matrix[0][j] == 0:
31 | matrix[i][j] = 0
32 | if row == True:
33 | for j in range(coll):
34 | matrix[0][j] = 0
35 | if col == True:
36 | for i in range(rowl):
37 | matrix[i][0] = 0
38 |
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/73-set-matrix-zeroes/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/73-set-matrix-zeroes/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an m x n
integer matrix matrix
, if an element is 0
, set its entire row and column to 0
's, and return the matrix.
2 |
3 |
You must do it in place.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
9 | Output: [[1,0,1],[0,0,0],[1,0,1]]
10 |
11 |
12 |
Example 2:
13 |

14 |
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
15 | Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | m == matrix.length
23 | n == matrix[0].length
24 | 1 <= m, n <= 200
25 | -231 <= matrix[i][j] <= 231 - 1
26 |
27 |
28 |
29 |
Follow up:
30 |
31 |
32 | - A straightforward solution using
O(mn)
space is probably a bad idea.
33 | - A simple improvement uses
O(m + n)
space, but still not the best solution.
34 | - Could you devise a constant space solution?
35 |
36 |
--------------------------------------------------------------------------------
/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 = len(matrix) #3
4 | col = len(matrix[0])-1 #3
5 | r = 0
6 | while (r < row and col >= 0):
7 | if matrix[r][col] == target:
8 | return True
9 | elif matrix[r][col] > target: #m[1][3]
10 | col -= 1 #1
11 | elif matrix[r][col] < target: #mat[0][3] <
12 | r += 1 #1
13 | return False
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/74-search-a-2d-matrix/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/74-search-a-2d-matrix/README.md:
--------------------------------------------------------------------------------
1 | Medium
Write an efficient algorithm that searches for a value target
in an m x n
integer matrix matrix
. This matrix has the following properties:
2 |
3 |
4 | - Integers in each row are sorted from left to right.
5 | - The first integer of each row is greater than the last integer of the previous row.
6 |
7 |
8 |
9 |
Example 1:
10 |

11 |
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
12 | Output: true
13 |
14 |
15 |
Example 2:
16 |

17 |
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
18 | Output: false
19 |
20 |
21 |
22 |
Constraints:
23 |
24 |
25 | m == matrix.length
26 | n == matrix[i].length
27 | 1 <= m, n <= 100
28 | -104 <= matrix[i][j], target <= 104
29 |
30 |
--------------------------------------------------------------------------------
/75-sort-colors/75-sort-colors.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sortColors(self, nums: List[int]) -> None:
3 | """
4 | Do not return anything, modify nums in-place instead.
5 | """
6 | #[2,0,2,1,1,0]
7 | maxi = max(nums) #2
8 | L = [0] * (maxi+1) #[0,0,0]
9 | #print(L)
10 | for i in nums: #i = 0
11 | L[i] += 1 #[2,2,2]
12 | #print(L)#L = [2,2,2]
13 | j = 0 #0
14 | k = 0 #0
15 | while j < len(L): #3
16 | if L[j] != 0: #j = 0, k = 2
17 | nums[k] = j #[0,0,2,1,1,0]
18 | k += 1 #2
19 | L[j] -= 1 #[0,2,2]
20 | else:
21 | #k += 1
22 | j += 1
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/75-sort-colors/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/75-sort-colors/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an array nums
with n
objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.
2 |
3 |
We will use the integers 0
, 1
, and 2
to represent the color red, white, and blue, respectively.
4 |
5 |
You must solve this problem without using the library's sort function.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: nums = [2,0,2,1,1,0]
11 | Output: [0,0,1,1,2,2]
12 |
13 |
14 |
Example 2:
15 |
16 |
Input: nums = [2,0,1]
17 | Output: [0,1,2]
18 |
19 |
20 |
21 |
Constraints:
22 |
23 |
24 | n == nums.length
25 | 1 <= n <= 300
26 | nums[i]
is either 0
, 1
, or 2
.
27 |
28 |
29 |
30 |
Follow up: Could you come up with a one-pass algorithm using only constant extra space?
31 |
--------------------------------------------------------------------------------
/818-race-car/818-race-car.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 | class Solution:
3 | def racecar(self, target: int) -> int:
4 | if target == 0:
5 | return 0
6 | pos = 0
7 | speed = 1
8 | Q = deque()
9 | Q.append((pos, speed, 0))
10 | while Q:
11 | temp = Q.popleft()
12 |
13 | if temp[0] + temp[1] == target:
14 | return temp[2] + 1
15 | Q.append((temp[0] + temp[1] , temp[1] * 2, temp[2] + 1 ))
16 | if temp[0] + temp[1] > target and temp[1] > 0:
17 | Q.append((temp[0], -1, temp[2] +1))
18 | if temp[0] + temp[1] < target and temp[1] < 0:
19 | Q.append((temp[0], 1, temp[2] +1 ))
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/818-race-car/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/832-flipping-an-image/832-flipping-an-image.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def rev(self, l):
3 | first = 0
4 | last = len(l) - 1
5 | while first <= last:
6 | l[first], l[last] = l[last], l[first]
7 | if first == last and l[first] == 0:
8 | l[first] = 1
9 | elif first == last and l[first] == 1:
10 | l[first] = 0
11 | else:
12 | if l[first] == 0:
13 | l[first] = 1
14 | elif l[first] == 1:
15 | l[first] = 0
16 | if l[last] == 0:
17 | l[last] = 1
18 | elif l[last] == 1:
19 | l[last] = 0
20 | first += 1
21 | last -= 1
22 | return l
23 | def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
24 | for i in image:
25 | self.rev(i)
26 | #print(image)
27 | #[[0,1,1], [0,1,0], [1,1,1]]
28 | """
29 | for j in range(len(image)):#3
30 | for k in range(len(image[j])):#3
31 | if image[j][k] == 0:
32 | image[j][k] = 1
33 | elif image[j][k] == 1:
34 | image[j][k] = 0
35 | """
36 | return image
37 |
38 |
39 |
--------------------------------------------------------------------------------
/832-flipping-an-image/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/844-backspace-string-compare/844-backspace-string-compare.py:
--------------------------------------------------------------------------------
1 | from collections import deque
2 | class Solution:
3 | def backspaceCompare(self, s: str, t: str) -> bool:
4 | S1 = deque()
5 | S2 = deque()
6 | news = ""
7 | newt = ""
8 | for i in s:
9 | if i == "#" and len(S1) == 0:
10 | continue
11 | if i == "#":
12 | S1.pop()
13 | else:
14 | S1.append(i)
15 | for j in t:
16 | if j == "#" and len(S2) == 0:
17 | continue
18 | if j == "#":
19 | S2.pop()
20 | else:
21 | S2.append(j)
22 | while S1:
23 | t = S1.pop()
24 | news += t
25 | while S2:
26 | t1 = S2.pop()
27 | newt += t1
28 | if news == newt:
29 | return True
30 | return False
31 |
32 |
33 |
--------------------------------------------------------------------------------
/844-backspace-string-compare/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/844-backspace-string-compare/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given two strings s
and t
, return true
if they are equal when both are typed into empty text editors. '#'
means a backspace character.
2 |
3 |
Note that after backspacing an empty text, the text will continue empty.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: s = "ab#c", t = "ad#c"
9 | Output: true
10 | Explanation: Both s and t become "ac".
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: s = "ab##", t = "c#d#"
16 | Output: true
17 | Explanation: Both s and t become "".
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: s = "a#c", t = "b"
23 | Output: false
24 | Explanation: s becomes "c" while t becomes "b".
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 1 <= s.length, t.length <= 200
32 | s
and t
only contain lowercase letters and '#'
characters.
33 |
34 |
35 |
36 |
Follow up: Can you solve it in O(n)
time and O(1)
space?
37 |
--------------------------------------------------------------------------------
/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 | start = 1
4 | end = len(arr)-2
5 | while (start <= end):
6 | mid = start + (end-start) // 2
7 | if (arr[mid-1] < arr[mid]) and (arr[mid] > arr[mid+1]):
8 | return mid
9 | elif (arr[mid] < arr[mid-1]):
10 | end = mid -1 #end = 1
11 | elif (arr[mid] < arr[mid+1]):
12 | start = mid + 1
13 |
14 |
15 |
16 | #[1,3,5,18,13,12,7]
17 | """
18 | [8,3,2,1] or [1,2,3,8]
19 |
20 | """
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/852-peak-index-in-a-mountain-array/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 | slow = head
9 | fast = head
10 | while fast != None and fast.next != None:
11 | slow = slow.next
12 | fast = fast.next.next
13 | return slow
14 |
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 |
--------------------------------------------------------------------------------
/88-merge-sorted-array/88-merge-sorted-array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
3 | """
4 | Do not return anything, modify nums1 in-place instead.
5 | """
6 | for n in nums2:
7 | nums1[m] = n
8 | m += 1
9 | nums1.sort()
10 |
11 |
--------------------------------------------------------------------------------
/88-merge-sorted-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/905-sort-array-by-parity/905-sort-array-by-parity.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sortArrayByParity(self, nums: List[int]) -> List[int]:
3 | first = 0
4 | last = len(nums) - 1
5 | while first < last:
6 | #firstcase: starting -> odd , end -> even
7 | if nums[last] % 2 == 0 and nums[first] % 2 != 0:
8 | nums[last], nums[first] = nums[first], nums[last]
9 | first += 1
10 | last -= 1
11 | #secondcase: start -> even, end -> even
12 | elif nums[last] % 2 == 0 and nums[first] % 2 == 0:
13 | first += 1
14 | #thirdcase: start -> even, last-> odd
15 | elif nums[last] % 2 != 0 and nums[first] % 2 == 0:
16 | first += 1
17 | last -= 1
18 | #forthcase: start -> odd , end = odd
19 | elif nums[last] % 2 != 0 and nums[first] % 2 != 0:
20 | last -= 1
21 | return nums
22 |
23 |
--------------------------------------------------------------------------------
/905-sort-array-by-parity/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/905-sort-array-by-parity/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer array nums
, move all the even integers at the beginning of the array followed by all the odd integers.
2 |
3 |
Return any array that satisfies this condition.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: nums = [3,1,2,4]
9 | Output: [2,4,3,1]
10 | Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: nums = [0]
16 | Output: [0]
17 |
18 |
19 |
20 |
Constraints:
21 |
22 |
23 | 1 <= nums.length <= 5000
24 | 0 <= nums[i] <= 5000
25 |
26 |
--------------------------------------------------------------------------------
/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
5 |
--------------------------------------------------------------------------------
/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.
2 |
3 |
4 |
Example 1:
5 |
Input: nums = [5,2,3,1]
6 | Output: [1,2,3,5]
7 |
Example 2:
8 |
Input: nums = [5,1,1,2,0,0]
9 | Output: [0,0,1,1,2,5]
10 |
11 |
12 |
Constraints:
13 |
14 |
15 | 1 <= nums.length <= 5 * 104
16 | -5 * 104 <= nums[i] <= 5 * 104
17 |
18 |
--------------------------------------------------------------------------------
/Coin Change - GFG/coin-change.py:
--------------------------------------------------------------------------------
1 | #User function Template for python3
2 |
3 | class Solution:
4 | def count(self, S, m, n):
5 | # code here
6 | #Item = S
7 | #m = arr size
8 | #n = sum/weight of bag
9 | DP = []
10 | for rows in range(m+1):
11 | column = [-1] * (n+1)
12 | DP.append(column)
13 |
14 | for j in range(n+1):
15 | DP[0][j] = 0
16 | for i in range(m+1):
17 | DP[i][0] = 1
18 |
19 | for i in range(1, m+1):
20 | for j in range(1, n+1):
21 | if S[i-1] <= j:
22 | DP[i][j] = DP[i][j-S[i-1]] + DP[i-1][j]
23 | else:
24 | DP[i][j] = DP[i-1][j]
25 | return DP[m][n]
26 |
27 |
28 | #{
29 | # Driver Code Starts
30 | #Initial Template for Python 3
31 |
32 | import sys
33 | sys.setrecursionlimit(10**6)
34 |
35 | if __name__ == '__main__':
36 | t = int(input())
37 | for _ in range(t):
38 | n,m = list(map(int, input().strip().split()))
39 | S = list(map(int, input().strip().split()))
40 | ob = Solution()
41 | print(ob.count(S,m,n))
42 | # } Driver Code Ends
--------------------------------------------------------------------------------
/Find minimum and maximum element in an array - GFG/find-minimum-and-maximum-element-in-an-array.py:
--------------------------------------------------------------------------------
1 | #User function Template for python3
2 |
3 | def getMinMax( a, n):
4 | mini = 10000000000000000
5 | maxi = -10000000000000000
6 | for A in a:
7 | if A < mini:
8 | mini = A
9 | if A > maxi:
10 | maxi = A
11 | return mini, maxi
12 |
13 |
14 |
15 |
16 |
17 | #{
18 | # Driver Code Starts
19 | #Initial Template for Python 3
20 |
21 | def main():
22 |
23 | T = int(input())
24 |
25 | while(T > 0):
26 | n = int(input())
27 | a = [int(x) for x in input().strip().split()]
28 |
29 | product = getMinMax(a, n)
30 | print(product[0], end=" ")
31 | print(product[1])
32 |
33 | T -= 1
34 |
35 |
36 | if __name__ == "__main__":
37 | main()
38 |
39 |
40 |
41 | # } Driver Code Ends
--------------------------------------------------------------------------------
/Height of Binary Tree - GFG/README.md:
--------------------------------------------------------------------------------
1 | # Height of Binary Tree
2 | ## Medium
3 |
4 |
Given a binary tree, find its height.
5 |
6 |
7 | Example 1:
8 |
9 |
Input:
10 | 1
11 | / \
12 | 2 3
13 | Output: 2
14 |
15 |
16 |
Example 2:
17 |
18 |
Input:
19 | 2
20 | \
21 | 1
22 | /
23 | 3
24 | Output: 3
25 |
26 |
27 | Your Task:
28 | You don't need to read input or print anything. Your task is to complete the function height() which takes root node of the tree as input parameter and returns an integer denoting the height of the tree. If the tree is empty, return 0.
29 |
30 |
31 | Expected Time Complexity: O(N)
32 | Expected Auxiliary Space: O(N)
33 |
34 |
35 | Constraints:
36 | 1 <= Number of nodes <= 105
37 | 1 <= Data of a node <= 105
38 |
39 |
--------------------------------------------------------------------------------
/Knapsack with Duplicate Items - GFG/knapsack-with-duplicate-items.py:
--------------------------------------------------------------------------------
1 | #User function Template for python3
2 |
3 | class Solution:
4 | def knapSack(self, N, W, val, wt):
5 | # code here
6 | DP = []
7 | for row in range(N+1):
8 | column = [-1] * (W+1)
9 | DP.append(column)
10 |
11 | #initialization
12 | for i in range(N+1):
13 | for j in range(W+1):
14 | if i == 0 or j == 0:
15 | DP[i][j] = 0
16 |
17 | #code
18 | for i in range(1, N+1):
19 | for j in range(1, W+1):
20 | if wt[i-1] <= j:
21 | DP[i][j] = max(val[i-1] + DP[i][j-wt[i-1]], DP[i-1][j])
22 | else:
23 | DP[i][j] = DP[i-1][j]
24 |
25 | return DP[N][W]
26 |
27 | #{
28 | # Driver Code Starts
29 | #Initial Template for Python 3
30 |
31 | if __name__ == '__main__':
32 | t = int(input())
33 | for _ in range(t):
34 | N, W = [int(x) for x in input().split()]
35 | val = input().split()
36 | for itr in range(N):
37 | val[itr] = int(val[itr])
38 | wt = input().split()
39 | for it in range(N):
40 | wt[it] = int(wt[it])
41 |
42 | ob = Solution()
43 | print(ob.knapSack(N, W, val, wt))
44 | # } Driver Code Ends
--------------------------------------------------------------------------------
/Longest Common Substring - GFG/README.md:
--------------------------------------------------------------------------------
1 | # Longest Common Substring
2 | ## Medium
3 |
4 |
Given two strings. The task is to find the length of the longest common substring.
5 |
6 |
7 | Example 1:
8 |
9 |
Input: S1 = "ABCDGH", S2 = "ACDGHR"
10 | Output: 4
11 | Explanation: The longest common substring
12 | is "CDGH" which has length 4.
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: S1 = "ABC", S2 "ACB"
18 | Output: 1
19 | Explanation: The longest common substrings
20 | are "A", "B", "C" all having length 1.
21 |
22 |
23 |
24 | Your Task:
25 | You don't need to read input or print anything. Your task is to complete the function longestCommonSubstr() which takes the string S1, string S2 and their length n and m as inputs and returns the length of the longest common substring in S1 and S2.
26 |
27 |
28 | Expected Time Complexity: O(n*m).
29 | Expected Auxiliary Space: O(n*m).
30 |
31 |
32 | Constraints:
33 | 1<=n, m<=1000
34 |
35 |
--------------------------------------------------------------------------------
/Longest Common Substring - GFG/longest-common-substring.py:
--------------------------------------------------------------------------------
1 | #User function Template for python3
2 |
3 | class Solution:
4 | def longestCommonSubstr(self, S1, S2, n, m):
5 | #code here
6 | DP = []
7 | for rows in range(n+1):
8 | column = [-1] * (m+1)
9 | DP.append(column)
10 | for i in range(n+1):
11 | for j in range(m+1):
12 | if i == 0 or j == 0:
13 | DP[i][j] = 0
14 | for i in range(1, n+1):
15 | for j in range(1, m+1):
16 | if S1[i-1] == S2[j-1]:
17 | DP[i][j] = 1 + DP[i-1][j-1]
18 | else:
19 | DP[i][j] = 0
20 | maxi = -99999999999999999
21 | for i in range(n+1):
22 | for j in range(m+1):
23 | if DP[i][j] > maxi:
24 | maxi = DP[i][j]
25 | return maxi
26 |
27 |
28 | #{
29 | # Driver Code Starts
30 | #Initial Template for Python 3
31 |
32 | if __name__=='__main__':
33 | t=int(input())
34 | for _ in range(t):
35 | n,m = input().strip().split(" ")
36 | n,m = int(n), int(m)
37 | S1 = input().strip()
38 | S2 = input().strip()
39 |
40 |
41 | ob=Solution()
42 | print(ob.longestCommonSubstr(S1, S2, n, m))
43 | # } Driver Code Ends
--------------------------------------------------------------------------------
/Perfect Sum Problem - GFG/perfect-sum-problem.py:
--------------------------------------------------------------------------------
1 | #User function Template for python3
2 | class Solution:
3 | def perfectSum(self, arr, n, sum):
4 | # code here
5 | #DP = [[-1] * (sum+1) for row in range(n+1)]
6 | DP = []
7 | for row in range(n+1):
8 | column = [-1] * (sum+1)
9 | DP.append(column)
10 |
11 | for j in range(sum+1):
12 | DP[0][j] = 0
13 | DP[0][0] = 1
14 | for i in range(1, n+1):
15 | for j in range(0, sum+1):
16 | if arr[i-1] > j:
17 | DP[i][j] = DP[i-1][j]
18 | else:
19 | DP[i][j] = DP[i-1][j-arr[i-1]] + DP[i-1][j]
20 | ans = DP[n][sum]
21 | return ans % 1000000007
22 |
23 | """
24 | DP = []
25 | for row in range(n+1):
26 | for columns in range(sum+1):
27 | column = [-1] * (sum+1) #[-1, -1, -1, -1, -1, -1]
28 | DP.append(column)
29 | """
30 |
31 |
32 | #{
33 | # Driver Code Starts
34 | #Initial Template for Python 3
35 |
36 | if __name__ == '__main__':
37 | T=int(input())
38 | for i in range(T):
39 | n,sum = input().split()
40 | n,sum = int(n),int(sum)
41 | arr = [int(x) for x in input().split()]
42 | ob = Solution()
43 | ans = ob.perfectSum(arr,n,sum)
44 | print(ans)
45 |
46 | # } Driver Code Ends
--------------------------------------------------------------------------------
/Print adjacency list - GFG/print-adjacency-list.py:
--------------------------------------------------------------------------------
1 | #User function Template for python3
2 |
3 | class Solution:
4 | #Function to return the adjacency list for each vertex.
5 | def printGraph(self, V, adj):
6 | # code here
7 | #adj= [[3,2], [2], [1,0], [0]]
8 | ans = []
9 | j = 0
10 | for i in adj:
11 | i.sort()
12 | i.insert(0, j)
13 | ans.append(i)
14 | j += 1
15 | return ans
16 |
17 |
18 | #{
19 | # Driver Code Starts
20 | if __name__ == '__main__':
21 |
22 | T=int(input())
23 | for i in range(T):
24 | V, E = map(int, input().split())
25 | adj = [[] for i in range(V)]
26 | for _ in range(E):
27 | u, v = map(int, input().split())
28 | adj[u].append(v)
29 | adj[v].append(u)
30 | obj = Solution()
31 | ans = obj.printGraph(V, adj)
32 | for i in range(len(ans)):
33 | for j in range(len(ans[i])-1):
34 | print(ans[i][j], end = "-> ")
35 | print(ans[i][len(ans[i])-1]);
36 |
37 | # } Driver Code Ends
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 100daysofcoding
--------------------------------------------------------------------------------
/set-matrix-zeroes/README.md:
--------------------------------------------------------------------------------
1 | 73. Set Matrix Zeroes
Medium
Given an m x n
integer matrix matrix
, if an element is 0
, set its entire row and column to 0
's, and return the matrix.
2 |
3 |
You must do it in place.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
9 | Output: [[1,0,1],[0,0,0],[1,0,1]]
10 |
11 |
12 |
Example 2:
13 |

14 |
Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
15 | Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | m == matrix.length
23 | n == matrix[0].length
24 | 1 <= m, n <= 200
25 | -231 <= matrix[i][j] <= 231 - 1
26 |
27 |
28 |
29 |
Follow up:
30 |
31 |
32 | - A straightforward solution using
O(mn)
space is probably a bad idea.
33 | - A simple improvement uses
O(m + n)
space, but still not the best solution.
34 | - Could you devise a constant space solution?
35 |
36 |
--------------------------------------------------------------------------------
/set-matrix-zeroes/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 | rows = [0]*len(matrix) #[0,1,0]
7 | columns = [0]*len(matrix[0]) #[0,1,0]
8 | for i in range(len(matrix)):
9 | for j in range(len(matrix[i])):
10 | if matrix[i][j] == 0:
11 | rows[i] = 1
12 | columns[j] = 1
13 |
14 | for i in range(len(matrix)):
15 | for j in range(len(matrix[i])):
16 | if rows[i] == 1 or columns[j] == 1:
17 | matrix[i][j] = 0
18 |
--------------------------------------------------------------------------------
/smallest-integer-divisible-by-k/README.md:
--------------------------------------------------------------------------------
1 | 1015. Smallest Integer Divisible by K
Medium
Given a positive integer k
, you need to find the length of the smallest positive integer n
such that n
is divisible by k
, and n
only contains the digit 1
.
2 |
3 |
Return the length of n
. If there is no such n
, return -1.
4 |
5 |
Note: n
may not fit in a 64-bit signed integer.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: k = 1
11 | Output: 1
12 | Explanation: The smallest answer is n = 1, which has length 1.
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: k = 2
18 | Output: -1
19 | Explanation: There is no such positive integer n divisible by 2.
20 |
21 |
22 |
Example 3:
23 |
24 |
Input: k = 3
25 | Output: 3
26 | Explanation: The smallest answer is n = 111, which has length 3.
27 |
28 |
29 |
30 |
Constraints:
31 |
32 |
35 |
--------------------------------------------------------------------------------
/smallest-integer-divisible-by-k/smallest-integer-divisible-by-k.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def smallestRepunitDivByK(self, k: int) -> int:
3 | S = set()
4 | n = 1
5 | l = 1
6 | while True:
7 | rem = n % k
8 | if rem == 0:
9 | return l
10 | if rem in S:
11 | return -1
12 | n = 10*rem + 1
13 | l += 1
14 | S.add(rem)
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/two-sum/README.md:
--------------------------------------------------------------------------------
1 | 1. Two Sum
Easy
Given an array of integers nums
and an integer target
, return indices of the two numbers such that they add up to target
.
2 |
3 |
You may assume that each input would have exactly one solution, and you may not use the same element twice.
4 |
5 |
You can return the answer in any order.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: nums = [2,7,11,15], target = 9
11 | Output: [0,1]
12 | Output: Because nums[0] + nums[1] == 9, we return [0, 1].
13 |
14 |
15 |
Example 2:
16 |
17 |
Input: nums = [3,2,4], target = 6
18 | Output: [1,2]
19 |
20 |
21 |
Example 3:
22 |
23 |
Input: nums = [3,3], target = 6
24 | Output: [0,1]
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | 2 <= nums.length <= 104
32 | -109 <= nums[i] <= 109
33 | -109 <= target <= 109
34 | - Only one valid answer exists.
35 |
36 |
37 |
38 |
Follow-up: Can you come up with an algorithm that is less than
O(n2)
time complexity?
--------------------------------------------------------------------------------
/two-sum/two-sum.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def twoSum(self, nums: List[int], target: int) -> List[int]:
3 | D = {}
4 | for n in range(len(nums)):
5 | sub = target - nums[n]
6 | if sub in D:
7 | return [D[sub] , n]
8 | D[nums[n]] = n
9 |
--------------------------------------------------------------------------------