├── .gitignore
├── 0019-remove-nth-node-from-end-of-list
├── 0019-remove-nth-node-from-end-of-list.java
├── NOTES.md
└── README.md
├── 0169-majority-element
├── 0169-majority-element.java
├── NOTES.md
└── README.md
├── 0229-majority-element-ii
├── 0229-majority-element-ii.java
├── NOTES.md
└── README.md
├── 0231-power-of-two
├── 0231-power-of-two.java
├── NOTES.md
└── README.md
├── 0326-power-of-three
├── 0326-power-of-three.java
├── NOTES.md
└── README.md
├── 100-same-tree
├── 100-same-tree.java
├── NOTES.md
└── README.md
├── 101-symmetric-tree
├── 101-symmetric-tree.java
├── NOTES.md
└── README.md
├── 104-maximum-depth-of-binary-tree
├── 104-maximum-depth-of-binary-tree.java
├── NOTES.md
└── README.md
├── 108-convert-sorted-array-to-binary-search-tree
├── 108-convert-sorted-array-to-binary-search-tree.java
├── NOTES.md
└── README.md
├── 111-minimum-depth-of-binary-tree
├── 111-minimum-depth-of-binary-tree.java
├── NOTES.md
└── README.md
├── 112-path-sum
├── 112-path-sum.java
├── NOTES.md
└── README.md
├── 118-pascals-triangle
├── 118-pascals-triangle.java
├── NOTES.md
└── README.md
├── 119-pascals-triangle-ii
├── 119-pascals-triangle-ii.java
├── NOTES.md
└── README.md
├── 121-best-time-to-buy-and-sell-stock
├── 121-best-time-to-buy-and-sell-stock.java
├── NOTES.md
└── README.md
├── 125-valid-palindrome
├── 125-valid-palindrome.java
├── NOTES.md
└── README.md
├── 136-single-number
├── 136-single-number.java
├── NOTES.md
└── README.md
├── 141-linked-list-cycle
├── NOTES.md
└── README.md
├── 144-binary-tree-preorder-traversal
├── 144-binary-tree-preorder-traversal.java
└── NOTES.md
├── 145-binary-tree-postorder-traversal
├── 145-binary-tree-postorder-traversal.java
├── NOTES.md
└── README.md
├── 160-intersection-of-two-linked-lists
├── 160-intersection-of-two-linked-lists.java
├── NOTES.md
└── README.md
├── 168-excel-sheet-column-title
├── 168-excel-sheet-column-title.java
├── NOTES.md
└── README.md
├── 1780-check-if-number-is-a-sum-of-powers-of-three
├── 1780-check-if-number-is-a-sum-of-powers-of-three.java
├── NOTES.md
└── README.md
├── 2095-delete-the-middle-node-of-a-linked-list
├── 2095-delete-the-middle-node-of-a-linked-list.java
├── NOTES.md
└── README.md
├── 3-longest-substring-without-repeating-characters
├── 3-longest-substring-without-repeating-characters.java
├── NOTES.md
└── README.md
├── 5-longest-palindromic-substring
├── 5-longest-palindromic-substring.java
├── NOTES.md
└── README.md
├── 54-spiral-matrix
├── 54-spiral-matrix.java
├── NOTES.md
└── README.md
├── 589-n-ary-tree-preorder-traversal
├── 589-n-ary-tree-preorder-traversal.java
├── NOTES.md
└── README.md
├── 590-n-ary-tree-postorder-traversal
├── 590-n-ary-tree-postorder-traversal.java
├── NOTES.md
└── README.md
├── 8-string-to-integer-atoi
├── 8-string-to-integer-atoi.java
├── NOTES.md
└── README.md
├── 83-remove-duplicates-from-sorted-list
├── 83-remove-duplicates-from-sorted-list.java
├── NOTES.md
└── README.md
├── 88-merge-sorted-array
├── 88-merge-sorted-array.java
├── NOTES.md
└── README.md
├── 94-binary-tree-inorder-traversal
├── 94-binary-tree-inorder-traversal.java
├── NOTES.md
└── README.md
└── src
├── DivideTwoIntegers.java
├── LengthOfLastWord.java
├── LetterCombinationsOfPhoneNumber.java
├── MergeTwoSortedLists.java
├── PacificAtlanticWaterFlow.java
├── PlusOne.java
├── PolindromeNumber.java
├── RemoveDuplicatesFromSortedArray.java
├── SearchInsertPosition.java
├── ValidParentheses.java
└── ValidSudoku.java
/.gitignore:
--------------------------------------------------------------------------------
1 | out/
2 | .idea/
3 | .idea_modules/
4 | *.iml
5 | *.ipr
6 | *.iws
--------------------------------------------------------------------------------
/0019-remove-nth-node-from-end-of-list/0019-remove-nth-node-from-end-of-list.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * public class ListNode {
4 | * int val;
5 | * ListNode next;
6 | * ListNode() {}
7 | * ListNode(int val) { this.val = val; }
8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9 | * }
10 | */
11 | class Solution {
12 | public ListNode removeNthFromEnd(ListNode head, int n) {
13 | int count = 0;
14 | ListNode temp = head;
15 | while (temp != null) {
16 | count++;
17 | temp = temp.next;
18 | }
19 | temp = head;
20 | ListNode result = null;
21 | int i = 0;
22 | while (temp != null) {
23 | if (i != count - n){
24 | result = insertEnd(result, temp.val);
25 | }
26 | temp = temp.next;
27 | i++;
28 | }
29 |
30 | return result;
31 | }
32 |
33 | static ListNode newNode(int val) {
34 | ListNode node = new ListNode();
35 | node.val = val;
36 | node.next = null;
37 | return node;
38 | }
39 |
40 | public static ListNode insertEnd(ListNode result, int val) {
41 | if (result == null) {
42 | return newNode(val);
43 | } else {
44 | result.next = insertEnd(result.next, val);
45 | }
46 |
47 | return result;
48 | }
49 | }
--------------------------------------------------------------------------------
/0019-remove-nth-node-from-end-of-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0019-remove-nth-node-from-end-of-list/README.md:
--------------------------------------------------------------------------------
1 |
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 |
--------------------------------------------------------------------------------
/0169-majority-element/0169-majority-element.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int majorityElement(int[] nums) {
3 | return Arrays.stream(nums)
4 | .boxed()
5 | .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
6 | .entrySet()
7 | .stream()
8 | .filter(e -> e.getValue() > (nums.length / 2) )
9 | .findFirst()
10 | .map(Map.Entry::getKey)
11 | .orElse(0);
12 | }
13 | }
--------------------------------------------------------------------------------
/0169-majority-element/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0169-majority-element/README.md:
--------------------------------------------------------------------------------
1 | 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?
--------------------------------------------------------------------------------
/0229-majority-element-ii/0229-majority-element-ii.java:
--------------------------------------------------------------------------------
1 |
2 | import java.util.stream.Collectors;
3 |
4 | class Solution {
5 | public List majorityElement(int[] nums) {
6 | return Arrays.stream(nums)
7 | .boxed()
8 | .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
9 | .entrySet()
10 | .stream()
11 | .filter(e -> e.getValue() > (nums.length / 3))
12 | .map(Map.Entry::getKey)
13 | .collect(Collectors.toList());
14 | }
15 | }
--------------------------------------------------------------------------------
/0229-majority-element-ii/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0229-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 |
--------------------------------------------------------------------------------
/0231-power-of-two/0231-power-of-two.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public boolean isPowerOfTwo(int n) {
3 | if (n == 1) {
4 | return true;
5 | }
6 | if (n % 2 != 0 || n == 0) {
7 | return false;
8 | }
9 |
10 | return isPowerOfTwo(n / 2);
11 | }
12 | }
--------------------------------------------------------------------------------
/0231-power-of-two/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0231-power-of-two/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer n
, return true
if it is a power of two. Otherwise, return false
.
2 |
3 |
An integer n
is a power of two, if there exists an integer x
such that n == 2x
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: n = 1
9 | Output: true
10 | Explanation: 20 = 1
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: n = 16
16 | Output: true
17 | Explanation: 24 = 16
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: n = 3
23 | Output: false
24 |
25 |
26 |
27 |
Constraints:
28 |
29 |
30 | -231 <= n <= 231 - 1
31 |
32 |
33 |
34 |
Follow up: Could you solve it without loops/recursion?
--------------------------------------------------------------------------------
/0326-power-of-three/0326-power-of-three.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public boolean isPowerOfThree(int num) {
3 | if (num == 1) {
4 | return true;
5 | }
6 | if (num % 3 != 0 || num == 0) {
7 | return false;
8 | }
9 |
10 | return isPowerOfThree(num / 3);
11 | }
12 | }
--------------------------------------------------------------------------------
/0326-power-of-three/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/0326-power-of-three/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer n
, return true
if it is a power of three. Otherwise, return false
.
2 |
3 |
An integer n
is a power of three, if there exists an integer x
such that n == 3x
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: n = 27
9 | Output: true
10 | Explanation: 27 = 33
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: n = 0
16 | Output: false
17 | Explanation: There is no x where 3x = 0.
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: n = -1
23 | Output: false
24 | Explanation: There is no x where 3x = (-1).
25 |
26 |
27 |
28 |
Constraints:
29 |
30 |
31 | -231 <= n <= 231 - 1
32 |
33 |
34 |
35 |
Follow up: Could you solve it without loops/recursion?
--------------------------------------------------------------------------------
/100-same-tree/100-same-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public boolean isSameTree(TreeNode p, TreeNode q) {
18 | return traverse(p, q);
19 |
20 | }
21 |
22 | public boolean traverse(TreeNode p, TreeNode q) {
23 | if ((p == null && q != null) || (p != null && q == null)) {
24 | return false;
25 | } else if (p != null && q != null) {
26 | return traverse(p.left, q.left) && p.val == q.val && traverse(p.right, q.right);
27 | }
28 | return true;
29 | }
30 | }
--------------------------------------------------------------------------------
/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/101-symmetric-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public boolean isSymmetric(TreeNode root) {
18 | return traverse(root.left, root.right);
19 | }
20 |
21 | public boolean traverse(TreeNode p, TreeNode q) {
22 | if (p == null && q == null) return true;
23 | if (p == null || q == null) return false;
24 | return (p.val == q.val) && traverse(p.left, q.right) && traverse(p.right, q.left);
25 | }
26 |
27 | //Alternative
28 | public boolean isSymmetric2(TreeNode root) {
29 | return traverse2(root.left, true).equals(traverse2(root.right, false));
30 | }
31 |
32 | public String traverse2(TreeNode root, boolean left) {
33 | if (root == null) {
34 | return " ";
35 | }
36 | String result = "";
37 | if (left) {
38 | result += traverse2(root.left, true);
39 | result += traverse2(root.right, false);
40 | } else {
41 | result += traverse2(root.right, false);
42 | result += traverse2(root.left, true);
43 | }
44 | result += root.val;
45 | return result;
46 | }
47 | }
--------------------------------------------------------------------------------
/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.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public int maxDepth(TreeNode root) {
18 | return traverse(root);
19 | }
20 |
21 | public int traverse(TreeNode root) {
22 | if (root == null) {
23 | return 0;
24 | }
25 | return 1 + Math.max(traverse(root.left) , traverse(root.right));
26 | }
27 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/108-convert-sorted-array-to-binary-search-tree/108-convert-sorted-array-to-binary-search-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public TreeNode sortedArrayToBST(int[] nums) {
18 | return toBST(nums, 0, nums.length - 1);
19 | }
20 |
21 | public TreeNode toBST(int nums[], int left, int right) {
22 | if (left == right) return new TreeNode(nums[left]);
23 | else if (left > right) return null;
24 | else {
25 | int mid = (left + right) / 2;
26 | TreeNode curr = new TreeNode(nums[mid]);
27 | curr.left = toBST(nums, left, mid - 1);
28 | curr.right = toBST(nums, mid + 1, right);
29 | return curr;
30 | }
31 | }
32 | }
--------------------------------------------------------------------------------
/108-convert-sorted-array-to-binary-search-tree/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/108-convert-sorted-array-to-binary-search-tree/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
2 |
3 |
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: nums = [-10,-3,0,5,9]
9 | Output: [0,-3,9,-10,null,5]
10 | Explanation: [0,-10,5,null,-3,null,9] is also accepted:
11 |
12 |
13 |
14 |
Example 2:
15 |

16 |
Input: nums = [1,3]
17 | Output: [3,1]
18 | Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
19 |
20 |
21 |
22 |
Constraints:
23 |
24 |
25 | 1 <= nums.length <= 104
26 | -104 <= nums[i] <= 104
27 | nums
is sorted in a strictly increasing order.
28 |
29 |
--------------------------------------------------------------------------------
/111-minimum-depth-of-binary-tree/111-minimum-depth-of-binary-tree.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public int minDepth(TreeNode root) {
18 | return height(root);
19 | }
20 |
21 | public int height(TreeNode node) {
22 | if (node == null) {
23 | return 0;
24 | }
25 | if (node.left == null && node.right == null) {
26 | return 1;
27 | }
28 |
29 | int leftDepth = Integer.MAX_VALUE;
30 | int rightDepth = Integer.MAX_VALUE;
31 |
32 | if (node.left != null) {
33 | leftDepth = height(node.left) + 1;
34 | }
35 | if (node.right != null) {
36 | rightDepth = height(node.right) + 1;
37 | }
38 |
39 | return Math.min(leftDepth, rightDepth);
40 |
41 | }
42 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/112-path-sum/112-path-sum.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public boolean hasPathSum(TreeNode root, int targetSum) {
18 |
19 | return reachToSum(root, targetSum);
20 | }
21 |
22 | public boolean reachToSum(TreeNode root, int targetSum) {
23 | if (root == null) {
24 | return false;
25 | }
26 |
27 | if (targetSum - root.val == 0 && root.left == null && root.right == null) {
28 | return true;
29 | }
30 |
31 | return reachToSum(root.left, targetSum - root.val) || reachToSum(root.right, targetSum - root.val);
32 | }
33 | }
--------------------------------------------------------------------------------
/112-path-sum/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/112-path-sum/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree and an integer targetSum
, return true
if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum
.
2 |
3 |
A leaf is a node with no children.
4 |
5 |
6 |
Example 1:
7 |

8 |
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
9 | Output: true
10 | Explanation: The root-to-leaf path with the target sum is shown.
11 |
12 |
13 |
Example 2:
14 |

15 |
Input: root = [1,2,3], targetSum = 5
16 | Output: false
17 | Explanation: There two root-to-leaf paths in the tree:
18 | (1 --> 2): The sum is 3.
19 | (1 --> 3): The sum is 4.
20 | There is no root-to-leaf path with sum = 5.
21 |
22 |
23 |
Example 3:
24 |
25 |
Input: root = [], targetSum = 0
26 | Output: false
27 | Explanation: Since the tree is empty, there are no root-to-leaf paths.
28 |
29 |
30 |
31 |
Constraints:
32 |
33 |
34 | - The number of nodes in the tree is in the range
[0, 5000]
.
35 | -1000 <= Node.val <= 1000
36 | -1000 <= targetSum <= 1000
37 |
38 |
--------------------------------------------------------------------------------
/118-pascals-triangle/118-pascals-triangle.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public List> generate(int numRows) {
3 |
4 | if (numRows == 1) {
5 | return List.of(List.of(1));
6 | }
7 | if (numRows == 2) {
8 | return List.of(List.of(1),List.of(1,1));
9 | }
10 | List> result = new ArrayList<>();
11 | result.add(List.of(1));
12 | result.add(List.of(1,1));
13 | List prev = result.get(1);
14 | for (int i = 2; i < numRows; i++){
15 | List temp = new ArrayList<>();
16 | temp.add(1);
17 | for (int j = 0; j < prev.size() - 1; j++) {
18 | temp.add(prev.get(j) + prev.get(j + 1));
19 | }
20 | temp.add(1);
21 | prev = temp;
22 | result.add(temp);
23 | }
24 |
25 | return result;
26 | }
27 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/119-pascals-triangle-ii/119-pascals-triangle-ii.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public List getRow(int rowIndex) {
3 | return generate(rowIndex + 1).get(rowIndex);
4 | }
5 |
6 | public List> generate(int numRows) {
7 |
8 | if (numRows == 1) {
9 | return List.of(List.of(1));
10 | }
11 | if (numRows == 2) {
12 | return List.of(List.of(1),List.of(1,1));
13 | }
14 | List> result = new ArrayList<>();
15 | result.add(List.of(1));
16 | result.add(List.of(1,1));
17 | List prev = result.get(1);
18 | for (int i = 2; i < numRows; i++){
19 | List temp = new ArrayList<>();
20 | temp.add(1);
21 | for (int j = 0; j < prev.size() - 1; j++) {
22 | temp.add(prev.get(j) + prev.get(j + 1));
23 | }
24 | temp.add(1);
25 | prev = temp;
26 | result.add(temp);
27 | }
28 |
29 | return result;
30 | }
31 | }
--------------------------------------------------------------------------------
/119-pascals-triangle-ii/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/119-pascals-triangle-ii/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer rowIndex
, return the rowIndexth
(0-indexed) row of the 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: rowIndex = 3
8 | Output: [1,3,3,1]
9 |
Example 2:
10 |
Input: rowIndex = 0
11 | Output: [1]
12 |
Example 3:
13 |
Input: rowIndex = 1
14 | Output: [1,1]
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | 0 <= rowIndex <= 33
21 |
22 |
23 |
24 |
Follow up: Could you optimize your algorithm to use only O(rowIndex)
extra space?
25 |
--------------------------------------------------------------------------------
/121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int maxProfit(int[] prices) {
3 | int profit = 0;
4 | int minPrice = prices[0];
5 | for (int i = 0; i < prices.length; i++) {
6 | minPrice = Math.min(minPrice, prices[i]);
7 | profit = Math.max(profit, prices[i] - minPrice);
8 | }
9 | return profit;
10 | }
11 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/125-valid-palindrome/125-valid-palindrome.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public boolean isPalindrome(String s) {
3 | s = s.trim().toLowerCase().replaceAll("[^a-z0-9]", "");
4 | if (s.length() == 0) {
5 | return true;
6 | }
7 | for (int i = 0, j = s.length() - 1; i < s.length() && j >= 0; i++, j--) {
8 | if (s.charAt(i) != s.charAt(j)) {
9 | return false;
10 | }
11 | }
12 | return true;
13 | }
14 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/136-single-number/136-single-number.java:
--------------------------------------------------------------------------------
1 | import java.util.Optional;
2 |
3 | class Solution {
4 |
5 | public int singleNumber2(int[] nums) {
6 | List s = new ArrayList<>();
7 | s.add(nums[0]);
8 | for (int i = 1; i < nums.length; i++) {
9 | if (s.contains(nums[i])){
10 | s.remove((Integer) nums[i]);
11 | } else {
12 | s.add(nums[i]);
13 |
14 | }
15 | }
16 | return s.get(0);
17 | }
18 |
19 | //Alternative
20 | public int singleNumber(int[] nums) {
21 |
22 | return Arrays.stream(nums)
23 | .boxed()
24 | .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
25 | .entrySet()
26 | .stream()
27 | .filter(e -> e.getValue() == 1)
28 | .findFirst()
29 | .map(Map.Entry::getKey)
30 | .orElse(-1);
31 | }
32 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/141-linked-list-cycle/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/141-linked-list-cycle/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given head
, the head of a linked list, determine if the linked list has a cycle in it.
2 |
3 |
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next
pointer. Internally, pos
is used to denote the index of the node that tail's next
pointer is connected to. Note that pos
is not passed as a parameter.
4 |
5 |
Return true
if there is a cycle in the linked list. Otherwise, return false
.
6 |
7 |
8 |
Example 1:
9 |

10 |
Input: head = [3,2,0,-4], pos = 1
11 | Output: true
12 | Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
13 |
14 |
15 |
Example 2:
16 |

17 |
Input: head = [1,2], pos = 0
18 | Output: true
19 | Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
20 |
21 |
22 |
Example 3:
23 |

24 |
Input: head = [1], pos = -1
25 | Output: false
26 | Explanation: There is no cycle in the linked list.
27 |
28 |
29 |
30 |
Constraints:
31 |
32 |
33 | - The number of the nodes in the list is in the range
[0, 104]
.
34 | -105 <= Node.val <= 105
35 | pos
is -1
or a valid index in the linked-list.
36 |
37 |
38 |
39 |
Follow up: Can you solve it using O(1)
(i.e. constant) memory?
40 |
--------------------------------------------------------------------------------
/144-binary-tree-preorder-traversal/144-binary-tree-preorder-traversal.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public List preorderTraversal(TreeNode root) {
18 | return traverse(root);
19 | }
20 |
21 | public List traverse(TreeNode root) {
22 | if (root == null) {
23 | return List.of();
24 | }
25 |
26 | List result = new ArrayList<>();
27 | result.add(root.val);
28 | result.addAll(traverse(root.left));
29 | result.addAll(traverse(root.right));
30 |
31 | return result;
32 | }
33 | }
--------------------------------------------------------------------------------
/144-binary-tree-preorder-traversal/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/145-binary-tree-postorder-traversal/145-binary-tree-postorder-traversal.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public List postorderTraversal(TreeNode root) {
18 | return traverse(root);
19 | }
20 |
21 | public List traverse(TreeNode root) {
22 | if (root == null) {
23 | return List.of();
24 | }
25 |
26 | List result = new ArrayList<>();
27 | result.addAll(traverse(root.left));
28 | result.addAll(traverse(root.right));
29 | result.add(root.val);
30 |
31 | return result;
32 | }
33 | }
--------------------------------------------------------------------------------
/145-binary-tree-postorder-traversal/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/145-binary-tree-postorder-traversal/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree, return the postorder traversal of its nodes' values.
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: root = [1,null,2,3]
7 | Output: [3,2,1]
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 the 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?
--------------------------------------------------------------------------------
/160-intersection-of-two-linked-lists/160-intersection-of-two-linked-lists.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * public class ListNode {
4 | * int val;
5 | * ListNode next;
6 | * ListNode(int x) {
7 | * val = x;
8 | * next = null;
9 | * }
10 | * }
11 | */
12 | public class Solution {
13 | public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
14 | ListNode tempA = headA;
15 |
16 | while (tempA != null) {
17 | ListNode tempB = headB;
18 | while (tempB != null) {
19 | if (tempA == tempB){
20 | return tempB;
21 | }
22 | tempB = tempB.next;
23 | }
24 | tempA = tempA.next;
25 | }
26 | return null;
27 |
28 | }
29 | }
--------------------------------------------------------------------------------
/160-intersection-of-two-linked-lists/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/160-intersection-of-two-linked-lists/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the heads of two singly linked-lists headA
and headB
, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null
.
2 |
3 |
For example, the following two linked lists begin to intersect at node c1
:
4 |

5 |
The test cases are generated such that there are no cycles anywhere in the entire linked structure.
6 |
7 |
Note that the linked lists must retain their original structure after the function returns.
8 |
9 |
Custom Judge:
10 |
11 |
The inputs to the judge are given as follows (your program is not given these inputs):
12 |
13 |
14 | intersectVal
- The value of the node where the intersection occurs. This is 0
if there is no intersected node.
15 | listA
- The first linked list.
16 | listB
- The second linked list.
17 | skipA
- The number of nodes to skip ahead in listA
(starting from the head) to get to the intersected node.
18 | skipB
- The number of nodes to skip ahead in listB
(starting from the head) to get to the intersected node.
19 |
20 |
21 |
The judge will then create the linked structure based on these inputs and pass the two heads, headA
and headB
to your program. If you correctly return the intersected node, then your solution will be accepted.
22 |
23 |
24 |
Example 1:
25 |

26 |
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
27 | Output: Intersected at '8'
28 | Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
29 | From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
30 | - Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory.
31 |
32 |
33 |
Example 2:
34 |

35 |
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
36 | Output: Intersected at '2'
37 | Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
38 | From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
39 |
40 |
41 |
Example 3:
42 |

43 |
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
44 | Output: No intersection
45 | Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
46 | Explanation: The two lists do not intersect, so return null.
47 |
48 |
49 |
50 |
Constraints:
51 |
52 |
53 | - The number of nodes of
listA
is in the m
.
54 | - The number of nodes of
listB
is in the n
.
55 | 1 <= m, n <= 3 * 104
56 | 1 <= Node.val <= 105
57 | 0 <= skipA < m
58 | 0 <= skipB < n
59 | intersectVal
is 0
if listA
and listB
do not intersect.
60 | intersectVal == listA[skipA] == listB[skipB]
if listA
and listB
intersect.
61 |
62 |
63 |
64 |
Follow up: Could you write a solution that runs in
O(m + n)
time and use only
O(1)
memory?
--------------------------------------------------------------------------------
/168-excel-sheet-column-title/168-excel-sheet-column-title.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public String convertToTitle(int columnNumber) { //%100 fast
3 | StringBuilder result = new StringBuilder();
4 | while (columnNumber > 0) {
5 | columnNumber--;
6 | result.insert(0, (char) ((columnNumber % 26) + 65));
7 | columnNumber /= 26;
8 | }
9 |
10 | return result.toString();
11 | }
12 |
13 | public static String convertToTitle2(int columnNumber) { //%20 fast - alternative
14 | return new StringBuilder(recursive(columnNumber)).reverse().toString();
15 | }
16 |
17 | public static String recursive(int columnNumber) {
18 | if (columnNumber == 0) {
19 | return "";
20 | }
21 | columnNumber--;
22 | return (char) ((columnNumber % 26) + 65) +
23 | recursive(columnNumber / 26);
24 | }
25 | }
--------------------------------------------------------------------------------
/168-excel-sheet-column-title/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/168-excel-sheet-column-title/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given an integer columnNumber
, return its corresponding column title as it appears in an Excel sheet.
2 |
3 |
For example:
4 |
5 |
A -> 1
6 | B -> 2
7 | C -> 3
8 | ...
9 | Z -> 26
10 | AA -> 27
11 | AB -> 28
12 | ...
13 |
14 |
15 |
16 |
Example 1:
17 |
18 |
Input: columnNumber = 1
19 | Output: "A"
20 |
21 |
22 |
Example 2:
23 |
24 |
Input: columnNumber = 28
25 | Output: "AB"
26 |
27 |
28 |
Example 3:
29 |
30 |
Input: columnNumber = 701
31 | Output: "ZY"
32 |
33 |
34 |
35 |
Constraints:
36 |
37 |
38 | 1 <= columnNumber <= 231 - 1
39 |
40 |
--------------------------------------------------------------------------------
/1780-check-if-number-is-a-sum-of-powers-of-three/1780-check-if-number-is-a-sum-of-powers-of-three.java:
--------------------------------------------------------------------------------
1 | import java.math.BigDecimal;
2 | import java.math.MathContext;
3 |
4 |
5 | class Solution {
6 | public boolean checkPowersOfThree(int n) {
7 | return checkPowersOfThree(n, new ArrayList<>());
8 | }
9 |
10 | public static boolean checkPowersOfThree(int n, List check) {
11 | if (n == 1 || n == 0) {
12 | return true;
13 | }
14 | if (n == 2 || n < 0) {
15 | return false;
16 | }
17 | int x = BigDecimal.valueOf(Math.log(n) / Math.log(3)).round(MathContext.DECIMAL32).intValue();
18 | int pow = (int) (Math.pow(3, x));
19 | if (check.contains(pow)){
20 | return false;
21 | } else {
22 | check.add(pow);
23 | }
24 | return checkPowersOfThree(n - pow, check);
25 | }
26 | }
--------------------------------------------------------------------------------
/1780-check-if-number-is-a-sum-of-powers-of-three/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/1780-check-if-number-is-a-sum-of-powers-of-three/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an integer n
, return true
if it is possible to represent n
as the sum of distinct powers of three. Otherwise, return false
.
2 |
3 |
An integer y
is a power of three if there exists an integer x
such that y == 3x
.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: n = 12
9 | Output: true
10 | Explanation: 12 = 31 + 32
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: n = 91
16 | Output: true
17 | Explanation: 91 = 30 + 32 + 34
18 |
19 |
20 |
Example 3:
21 |
22 |
Input: n = 21
23 | Output: false
24 |
25 |
26 |
27 |
Constraints:
28 |
29 |
32 |
--------------------------------------------------------------------------------
/2095-delete-the-middle-node-of-a-linked-list/2095-delete-the-middle-node-of-a-linked-list.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * public class ListNode {
4 | * int val;
5 | * ListNode next;
6 | * ListNode() {}
7 | * ListNode(int val) { this.val = val; }
8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9 | * }
10 | */
11 | class Solution {
12 | public ListNode deleteMiddle(ListNode head) {
13 | if (head.next == null) {
14 | return null;
15 | }
16 | int count = 0;
17 | ListNode result = head;
18 | ListNode temp = head;
19 | while (temp != null) {
20 | count += 1;
21 | temp = temp.next;
22 | }
23 |
24 | int middle = count / 2;
25 |
26 |
27 | for (int i = 0; i < middle- 1; i++) {
28 | result = result.next;
29 | }
30 | result.next = result.next.next;
31 | return head;
32 | }
33 |
34 |
35 |
36 | }
--------------------------------------------------------------------------------
/2095-delete-the-middle-node-of-a-linked-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/2095-delete-the-middle-node-of-a-linked-list/README.md:
--------------------------------------------------------------------------------
1 | Medium
You are given the head
of a linked list. Delete the middle node, and return the head
of the modified linked list.
2 |
3 |
The middle node of a linked list of size n
is the ⌊n / 2⌋th
node from the start using 0-based indexing, where ⌊x⌋
denotes the largest integer less than or equal to x
.
4 |
5 |
6 | - For
n
= 1
, 2
, 3
, 4
, and 5
, the middle nodes are 0
, 1
, 1
, 2
, and 2
, respectively.
7 |
8 |
9 |
10 |
Example 1:
11 |

12 |
Input: head = [1,3,4,7,1,2,6]
13 | Output: [1,3,4,1,2,6]
14 | Explanation:
15 | The above figure represents the given linked list. The indices of the nodes are written below.
16 | Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
17 | We return the new list after removing this node.
18 |
19 |
20 |
Example 2:
21 |

22 |
Input: head = [1,2,3,4]
23 | Output: [1,2,4]
24 | Explanation:
25 | The above figure represents the given linked list.
26 | For n = 4, node 2 with value 3 is the middle node, which is marked in red.
27 |
28 |
29 |
Example 3:
30 |

31 |
Input: head = [2,1]
32 | Output: [2]
33 | Explanation:
34 | The above figure represents the given linked list.
35 | For n = 2, node 1 with value 1 is the middle node, which is marked in red.
36 | Node 0 with value 2 is the only node remaining after removing node 1.
37 |
38 |
39 |
Constraints:
40 |
41 |
42 | - The number of nodes in the list is in the range
[1, 105]
.
43 | 1 <= Node.val <= 105
44 |
45 |
--------------------------------------------------------------------------------
/3-longest-substring-without-repeating-characters/3-longest-substring-without-repeating-characters.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public static int lengthOfLongestSubstring(String s) {
3 | if(s == null || s.length() < 1){
4 | return 0;
5 | }
6 | int a_ptr = 0;
7 | int max = 0;
8 |
9 | Set set = new HashSet();
10 |
11 |
12 | for (int b_ptr = 0; b_ptr < s.length(); b_ptr++){
13 | if (!set.contains(s.charAt(b_ptr))){
14 | set.add(s.charAt(b_ptr));
15 |
16 | }else{
17 | while (set.contains(s.charAt(b_ptr))){
18 | set.remove(s.charAt(a_ptr));
19 | a_ptr++;
20 | }
21 | set.add(s.charAt(b_ptr));
22 | }
23 | max = Math.max(b_ptr - a_ptr + 1, max);
24 |
25 | }
26 | return max;
27 | }
28 | }
--------------------------------------------------------------------------------
/3-longest-substring-without-repeating-characters/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/3-longest-substring-without-repeating-characters/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given a string s
, find the length of the longest substring without repeating characters.
2 |
3 |
4 |
Example 1:
5 |
6 |
Input: s = "abcabcbb"
7 | Output: 3
8 | Explanation: The answer is "abc", with the length of 3.
9 |
10 |
11 |
Example 2:
12 |
13 |
Input: s = "bbbbb"
14 | Output: 1
15 | Explanation: The answer is "b", with the length of 1.
16 |
17 |
18 |
Example 3:
19 |
20 |
Input: s = "pwwkew"
21 | Output: 3
22 | Explanation: The answer is "wke", with the length of 3.
23 | Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
24 |
25 |
26 |
27 |
Constraints:
28 |
29 |
30 | 0 <= s.length <= 5 * 104
31 | s
consists of English letters, digits, symbols and spaces.
32 |
33 |
--------------------------------------------------------------------------------
/5-longest-palindromic-substring/5-longest-palindromic-substring.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public String longestPalindrome(String s) {
3 | if (s.length() <= 1 || isPalindrome(s)) {
4 | return s;
5 | }
6 | String result = "";
7 | for (int i = 0; i < s.length(); i++) {
8 | String substring = s.substring(i);
9 | for (int j = substring.length(); j >= 0; j--){
10 | substring = substring.substring(0,j);
11 | if (isPalindrome(substring)){
12 | if (substring.length() > result.length()) {
13 | result = substring;
14 | }
15 | }
16 | }
17 | }
18 | return result;
19 | }
20 |
21 | public static boolean isPalindrome(String s) {
22 | int i = 0, j = s.length() - 1;
23 | while (i < j) {
24 | if (s.charAt(i) != s.charAt(j)){
25 | return false;
26 | }
27 | i++;
28 | j--;
29 | }
30 | return true;
31 | }
32 | }
--------------------------------------------------------------------------------
/5-longest-palindromic-substring/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/5-longest-palindromic-substring/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given a string s
, return the longest palindromic substring in s
.
2 |
3 |
A string is called a palindrome string if the reverse of that string is the same as the original string.
4 |
5 |
6 |
Example 1:
7 |
8 |
Input: s = "babad"
9 | Output: "bab"
10 | Explanation: "aba" is also a valid answer.
11 |
12 |
13 |
Example 2:
14 |
15 |
Input: s = "cbbd"
16 | Output: "bb"
17 |
18 |
19 |
20 |
Constraints:
21 |
22 |
23 | 1 <= s.length <= 1000
24 | s
consist of only digits and English letters.
25 |
26 |
--------------------------------------------------------------------------------
/54-spiral-matrix/54-spiral-matrix.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public List spiralOrder(int[][] arr) {
3 | //Time Complexity: O(M*N). To traverse the matrix O(M*M) time is required.
4 | //Auxiliary Space: O(1). No extra space is required.
5 | //T = Top corner, B = bottom corner, L = Left corner, R = right corner, dir = direction
6 | int T = 0, B = arr.length-1, L = 0, R = arr[0].length -1, dir = 0;
7 | List result = new ArrayList<>();
8 | while (T <= B && L <= R) {
9 | if (dir == 0) { //Traverse left to right
10 | for (int i = L; i <= R; i++) {
11 | result.add(arr[T][i]);
12 | }
13 | T++;
14 | } else if (dir == 1) { //Traverse right to bottom
15 | for (int i = T; i <= B; i++) {
16 | result.add(arr[i][R]);
17 | }
18 | R--;
19 | } else if (dir == 2) { // right to left
20 | for (int i = R; i >= L; i--){
21 | result.add(arr[B][i]);
22 | }
23 | B--;
24 | } else if (dir == 3) { //bottom to top
25 | for (int i = B; i >= T; i--) {
26 | result.add(arr[i][L]);
27 | }
28 | L++;
29 | }
30 | dir = (dir + 1) % 4; //1 = next direction, 4 = direction count
31 | }
32 | return result;
33 | }
34 | }
--------------------------------------------------------------------------------
/54-spiral-matrix/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/54-spiral-matrix/README.md:
--------------------------------------------------------------------------------
1 | Medium
Given an m x n
matrix
, return all elements of the matrix
in spiral order.
2 |
3 |
4 |
Example 1:
5 |

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

12 |
Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13 | Output: [1,2,3,4,8,12,11,10,9,5,6,7]
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | m == matrix.length
21 | n == matrix[i].length
22 | 1 <= m, n <= 10
23 | -100 <= matrix[i][j] <= 100
24 |
25 |
--------------------------------------------------------------------------------
/589-n-ary-tree-preorder-traversal/589-n-ary-tree-preorder-traversal.java:
--------------------------------------------------------------------------------
1 | /*
2 | // Definition for a Node.
3 | class Node {
4 | public int val;
5 | public List children;
6 |
7 | public Node() {}
8 |
9 | public Node(int _val) {
10 | val = _val;
11 | }
12 |
13 | public Node(int _val, List _children) {
14 | val = _val;
15 | children = _children;
16 | }
17 | };
18 | */
19 |
20 | class Solution {
21 | public List preorder(Node root) {
22 | return traverse(root);
23 | }
24 |
25 | public List traverse(Node root) {
26 | if (root == null) {
27 | return List.of();
28 | }
29 |
30 | List result = new ArrayList<>();
31 | result.add(root.val);
32 |
33 | for(Node node: root.children) {
34 | result.addAll(traverse(node));
35 | }
36 |
37 | return result;
38 | }
39 | }
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/590-n-ary-tree-postorder-traversal/590-n-ary-tree-postorder-traversal.java:
--------------------------------------------------------------------------------
1 | /*
2 | // Definition for a Node.
3 | class Node {
4 | public int val;
5 | public List children;
6 |
7 | public Node() {}
8 |
9 | public Node(int _val) {
10 | val = _val;
11 | }
12 |
13 | public Node(int _val, List _children) {
14 | val = _val;
15 | children = _children;
16 | }
17 | };
18 | */
19 |
20 | class Solution {
21 | public List postorder(Node root) {
22 | return traverse(root);
23 | }
24 |
25 | public List traverse(Node root) {
26 | if(root == null) {
27 | return List.of();
28 | }
29 |
30 | List result = new ArrayList<>();
31 | for(Node node: root.children) {
32 | result.addAll(traverse(node));
33 | }
34 |
35 | result.add(root.val);
36 |
37 | return result;
38 | }
39 | }
--------------------------------------------------------------------------------
/590-n-ary-tree-postorder-traversal/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/590-n-ary-tree-postorder-traversal/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of an n-ary tree, return the postorder 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 |
Input: root = [1,null,3,2,4,null,5,6]
9 | Output: [5,6,3,2,4,1]
10 |
11 |
12 |
Example 2:
13 |

14 |
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]
15 | Output: [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
16 |
17 |
18 |
19 |
Constraints:
20 |
21 |
22 | - The number of nodes in the tree is in the range
[0, 104]
.
23 | 0 <= Node.val <= 104
24 | - The height of the n-ary tree is less than or equal to
1000
.
25 |
26 |
27 |
28 |
Follow up: Recursive solution is trivial, could you do it iteratively?
29 |
--------------------------------------------------------------------------------
/8-string-to-integer-atoi/8-string-to-integer-atoi.java:
--------------------------------------------------------------------------------
1 | import java.math.BigDecimal;
2 |
3 |
4 | class Solution {
5 | public int myAtoi(String s) {
6 | s = s.trim();
7 | if (s.length() == 0) {
8 | return 0;
9 | }
10 | if (!Character.isDigit(s.charAt(0)) && (s.charAt(0) != '-' && s.charAt(0) != '+')) {
11 | return 0;
12 | }
13 | s = s.replace("[^\\d[-|+]]", "");
14 | String trimmed = "";
15 | boolean flag = false;
16 | boolean digitOccured = false;
17 | for (int i = 0; i < s.length(); i++) {
18 | if ((s.charAt(i) == '-' || s.charAt(i) == '+') && !digitOccured) {
19 | if (!flag) {
20 | trimmed += s.charAt(i);
21 | flag = true;
22 | } else {
23 | return 0;
24 | }
25 |
26 | } else if (Character.isDigit(s.charAt(i))) {
27 | digitOccured = true;
28 | if (trimmed.length() == 0 && s.charAt(i) == '0') {
29 | continue;
30 | }
31 | trimmed += s.charAt(i);
32 | } else {
33 | break;
34 | }
35 | }
36 | if (trimmed.length() == 0) {
37 | return 0;
38 | }
39 | if (trimmed.length() == 1 && (s.charAt(0) == '-' || s.charAt(0) == '+')) {
40 | return 0;
41 | }
42 |
43 | BigDecimal result;
44 | try {
45 | result = BigDecimal.valueOf(Long.parseLong(trimmed));
46 | } catch (NumberFormatException e) {
47 | if (trimmed.charAt(0) == '-') {
48 | result = BigDecimal.valueOf(Integer.MIN_VALUE);
49 | } else {
50 | result = BigDecimal.valueOf(Integer.MAX_VALUE);
51 | }
52 | }
53 | if (result.compareTo(BigDecimal.valueOf(Integer.MAX_VALUE)) > 0) {
54 | result = BigDecimal.valueOf(Integer.MAX_VALUE);
55 | } else if (result.compareTo(BigDecimal.valueOf(Integer.MIN_VALUE)) < 0) {
56 | result = BigDecimal.valueOf(Integer.MIN_VALUE);
57 | }
58 | return result.intValue();
59 | }
60 | }
--------------------------------------------------------------------------------
/8-string-to-integer-atoi/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/8-string-to-integer-atoi/README.md:
--------------------------------------------------------------------------------
1 | Medium
Implement the myAtoi(string s)
function, which converts a string to a 32-bit signed integer (similar to C/C++'s atoi
function).
2 |
3 |
The algorithm for myAtoi(string s)
is as follows:
4 |
5 |
6 | - Read in and ignore any leading whitespace.
7 | - Check if the next character (if not already at the end of the string) is
'-'
or '+'
. Read this character in if it is either. This determines if the final result is negative or positive respectively. Assume the result is positive if neither is present.
8 | - Read in next the characters until the next non-digit character or the end of the input is reached. The rest of the string is ignored.
9 | - Convert these digits into an integer (i.e.
"123" -> 123
, "0032" -> 32
). If no digits were read, then the integer is 0
. Change the sign as necessary (from step 2).
10 | - If the integer is out of the 32-bit signed integer range
[-231, 231 - 1]
, then clamp the integer so that it remains in the range. Specifically, integers less than -231
should be clamped to -231
, and integers greater than 231 - 1
should be clamped to 231 - 1
.
11 | - Return the integer as the final result.
12 |
13 |
14 |
Note:
15 |
16 |
17 | - Only the space character
' '
is considered a whitespace character.
18 | - Do not ignore any characters other than the leading whitespace or the rest of the string after the digits.
19 |
20 |
21 |
22 |
Example 1:
23 |
24 |
Input: s = "42"
25 | Output: 42
26 | Explanation: The underlined characters are what is read in, the caret is the current reader position.
27 | Step 1: "42" (no characters read because there is no leading whitespace)
28 | ^
29 | Step 2: "42" (no characters read because there is neither a '-' nor '+')
30 | ^
31 | Step 3: "42" ("42" is read in)
32 | ^
33 | The parsed integer is 42.
34 | Since 42 is in the range [-231, 231 - 1], the final result is 42.
35 |
36 |
37 |
Example 2:
38 |
39 |
Input: s = " -42"
40 | Output: -42
41 | Explanation:
42 | Step 1: " -42" (leading whitespace is read and ignored)
43 | ^
44 | Step 2: " -42" ('-' is read, so the result should be negative)
45 | ^
46 | Step 3: " -42" ("42" is read in)
47 | ^
48 | The parsed integer is -42.
49 | Since -42 is in the range [-231, 231 - 1], the final result is -42.
50 |
51 |
52 |
Example 3:
53 |
54 |
Input: s = "4193 with words"
55 | Output: 4193
56 | Explanation:
57 | Step 1: "4193 with words" (no characters read because there is no leading whitespace)
58 | ^
59 | Step 2: "4193 with words" (no characters read because there is neither a '-' nor '+')
60 | ^
61 | Step 3: "4193 with words" ("4193" is read in; reading stops because the next character is a non-digit)
62 | ^
63 | The parsed integer is 4193.
64 | Since 4193 is in the range [-231, 231 - 1], the final result is 4193.
65 |
66 |
67 |
68 |
Constraints:
69 |
70 |
71 | 0 <= s.length <= 200
72 | s
consists of English letters (lower-case and upper-case), digits (0-9
), ' '
, '+'
, '-'
, and '.'
.
73 |
74 |
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/83-remove-duplicates-from-sorted-list.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for singly-linked list.
3 | * public class ListNode {
4 | * int val;
5 | * ListNode next;
6 | * ListNode() {}
7 | * ListNode(int val) { this.val = val; }
8 | * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
9 | * }
10 | */
11 | class Solution {
12 | public ListNode deleteDuplicates(ListNode head) {
13 | if (head == null) return null;
14 | ListNode result = newNode(head.val);
15 |
16 | while (head.next != null) {
17 | int current = head.val;
18 | head = head.next;
19 | if (head.val != current) {
20 | result = insertEnd(result, head.val);
21 | }
22 | }
23 | return result;
24 | }
25 |
26 | public ListNode newNode(int val) {
27 | ListNode node = new ListNode();
28 | node.val = val;
29 | node.next = null;
30 | return node;
31 | }
32 |
33 | public ListNode insertEnd(ListNode result, int val) {
34 | if (result == null) {
35 | return newNode(val);
36 | } else {
37 | result.next = insertEnd(result.next, val);
38 | }
39 |
40 | return result;
41 | }
42 | }
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/83-remove-duplicates-from-sorted-list/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
2 |
3 |
4 |
Example 1:
5 |

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

12 |
Input: head = [1,1,2,3,3]
13 | Output: [1,2,3]
14 |
15 |
16 |
17 |
Constraints:
18 |
19 |
20 | - The number of nodes in the list is in the range
[0, 300]
.
21 | -100 <= Node.val <= 100
22 | - The list is guaranteed to be sorted in ascending order.
23 |
24 |
--------------------------------------------------------------------------------
/88-merge-sorted-array/88-merge-sorted-array.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public void merge(int[] nums1, int m, int[] nums2, int n) {
3 | List l1 = new ArrayList<>(Arrays.stream(nums1).boxed().toList().subList(0, m));
4 | List l2 = Arrays.stream(nums2).boxed().toList().subList(0, n);
5 | l1.addAll(l2);
6 |
7 | Collections.sort(l1);
8 |
9 | IntStream.range(0, m + n).forEach(i -> nums1[i] = l1.get(i));
10 | }
11 | }
--------------------------------------------------------------------------------
/88-merge-sorted-array/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/88-merge-sorted-array/README.md:
--------------------------------------------------------------------------------
1 | Easy
You are given two integer arrays nums1
and nums2
, sorted in non-decreasing order, and two integers m
and n
, representing the number of elements in nums1
and nums2
respectively.
2 |
3 |
Merge nums1
and nums2
into a single array sorted in non-decreasing order.
4 |
5 |
The final sorted array should not be returned by the function, but instead be stored inside the array nums1
. To accommodate this, nums1
has a length of m + n
, where the first m
elements denote the elements that should be merged, and the last n
elements are set to 0
and should be ignored. nums2
has a length of n
.
6 |
7 |
8 |
Example 1:
9 |
10 |
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
11 | Output: [1,2,2,3,5,6]
12 | Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
13 | The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
14 |
15 |
16 |
Example 2:
17 |
18 |
Input: nums1 = [1], m = 1, nums2 = [], n = 0
19 | Output: [1]
20 | Explanation: The arrays we are merging are [1] and [].
21 | The result of the merge is [1].
22 |
23 |
24 |
Example 3:
25 |
26 |
Input: nums1 = [0], m = 0, nums2 = [1], n = 1
27 | Output: [1]
28 | Explanation: The arrays we are merging are [] and [1].
29 | The result of the merge is [1].
30 | Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
31 |
32 |
33 |
34 |
Constraints:
35 |
36 |
37 | nums1.length == m + n
38 | nums2.length == n
39 | 0 <= m, n <= 200
40 | 1 <= m + n <= 200
41 | -109 <= nums1[i], nums2[j] <= 109
42 |
43 |
44 |
45 |
Follow up: Can you come up with an algorithm that runs in O(m + n)
time?
46 |
--------------------------------------------------------------------------------
/94-binary-tree-inorder-traversal/94-binary-tree-inorder-traversal.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * public class TreeNode {
4 | * int val;
5 | * TreeNode left;
6 | * TreeNode right;
7 | * TreeNode() {}
8 | * TreeNode(int val) { this.val = val; }
9 | * TreeNode(int val, TreeNode left, TreeNode right) {
10 | * this.val = val;
11 | * this.left = left;
12 | * this.right = right;
13 | * }
14 | * }
15 | */
16 | class Solution {
17 | public List inorderTraversal(TreeNode root) {
18 | return traverse(root);
19 | }
20 |
21 | public static List traverse(TreeNode root) {
22 | if (root == null) {
23 | return List.of();
24 | }
25 | List result = new ArrayList<>();
26 | result.addAll(traverse(root.left));
27 | result.add(root.val);
28 | result.addAll(traverse(root.right));
29 | return result;
30 | }
31 | }
--------------------------------------------------------------------------------
/94-binary-tree-inorder-traversal/NOTES.md:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/94-binary-tree-inorder-traversal/README.md:
--------------------------------------------------------------------------------
1 | Easy
Given the root
of a binary tree, return the inorder traversal of its nodes' values.
2 |
3 |
4 |
Example 1:
5 |

6 |
Input: root = [1,null,2,3]
7 | Output: [1,3,2]
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?
--------------------------------------------------------------------------------
/src/DivideTwoIntegers.java:
--------------------------------------------------------------------------------
1 | public class DivideTwoIntegers {
2 |
3 | //https://leetcode.com/problems/divide-two-integers/
4 | /*
5 | 10 / 3 = 10 - 3 = 7 +1
6 | 7 - 3 = 4 +1
7 | 4 - 3 = 1 +1
8 | 1 - 3 = -2 0
9 | 3 = 111
10 | */
11 |
12 | public static void main(String[] args) {
13 |
14 | System.out.println(divide(Integer.MIN_VALUE, -1)); //2147483647 +1 - 2147483647
15 | System.out.println(divide(-10, 10));
16 |
17 | }
18 |
19 | public static int divide(int dividend, int divisor) {
20 | if (dividend == Integer.MIN_VALUE && divisor == -1) return Integer.MAX_VALUE;
21 | if (dividend == Integer.MIN_VALUE && divisor == 1) return Integer.MIN_VALUE;
22 | if (dividend == divisor) return 1;
23 | if (divisor == 1) return dividend;
24 | if (divisor == -1) return -dividend;
25 |
26 | int sign = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) ? -1 : 1;
27 |
28 | dividend = Math.abs(dividend);
29 | divisor = Math.abs(divisor);
30 |
31 | if (dividend == divisor) return -1;
32 | int result = 0;
33 | while ((dividend - divisor) >= 0) {
34 | result++;
35 | dividend = dividend - divisor;
36 | }
37 |
38 | return sign < 0 ? -result : result;
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/LengthOfLastWord.java:
--------------------------------------------------------------------------------
1 | public class LengthOfLastWord {
2 |
3 | //https://leetcode.com/problems/length-of-last-word/
4 |
5 | public static void main(String[] args) {
6 | System.out.println(lengthOfLastWord(" fly me to the moon "));
7 | }
8 |
9 | public static int lengthOfLastWord(String s) {
10 | String[] sArr = s.trim().split(" ");
11 | return sArr[sArr.length-1].length();
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/LetterCombinationsOfPhoneNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 | import java.util.Map;
4 | import java.util.stream.Collectors;
5 |
6 | public class LetterCombinationsOfPhoneNumber {
7 |
8 | /*
9 | [[a, b, c], [d, e, f], [g, h, i]]
10 | "adg" = 0,0, 1,0, 2,0
11 | "adh" = 0,0, 1,0, 2,1,
12 | "adi" = 0,0, 1,0, 2,2
13 | ["adg","adh","adi","aeg","aeh","aei","afg","afh","afi","bdg","bdh","bdi","beg","beh","bei","bfg","bfh","bfi","cdg","cdh","cdi","ceg","ceh","cei","cfg","cfh","cfi"]
14 | */
15 | public static void main(String[] args) {
16 | System.out.println(letterCombinations("234"));
17 |
18 | }
19 |
20 | static Map> phoneNumbers = Map.of(
21 | "2", List.of("a","b","c"),
22 | "3", List.of("d","e","f"),
23 | "4", List.of("g","h","i"),
24 | "5", List.of("j","k","l"),
25 | "6", List.of("m","n","o"),
26 | "7", List.of("p","q","r","s"),
27 | "8", List.of("t","u","v"),
28 | "9", List.of("w","x","y","z")
29 | );
30 |
31 | public static List letterCombinations(String digits) {
32 | if (digits == null || digits.isEmpty()) {
33 | return new ArrayList<>();
34 | }
35 | return getLetterCombination(digits);
36 |
37 | }
38 | public static List getLetterCombination(String digits){
39 | if(digits.length() == 0){
40 | return List.of("");
41 | }
42 |
43 | String firstDigit = digits.substring(0, 1);
44 | String restDigits = digits.substring(1);
45 |
46 | return phoneNumbers.get(firstDigit)
47 | .stream()
48 | .flatMap(s -> getLetterCombination(restDigits).stream().map(s1 -> s + s1))
49 | .collect(Collectors.toList());
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/MergeTwoSortedLists.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 | import java.util.List;
3 |
4 | public class MergeTwoSortedLists {
5 |
6 | //https://leetcode.com/problems/merge-two-sorted-lists/
7 |
8 | public static void main(String[] args) {
9 |
10 | ListNode list1 = null;
11 | list1 = insertEnd(list1, 1);
12 | list1 = insertEnd(list1, 2);
13 | list1 = insertEnd(list1, 4);
14 |
15 | printListNode(list1);
16 |
17 | ListNode list2 = null;
18 | list2 = insertEnd(list2, 1);
19 | list2 = insertEnd(list2, 3);
20 | list2 = insertEnd(list2, 4);
21 |
22 | printListNode(list2);
23 |
24 | printListNode(mergeTwoLists(list1, list2));
25 |
26 | }
27 |
28 | public static class ListNode {
29 | int val;
30 | ListNode next;
31 |
32 | ListNode() {
33 | }
34 |
35 | ListNode(int val) {
36 | this.val = val;
37 | }
38 |
39 | ListNode(int val, ListNode next) {
40 | this.val = val;
41 | this.next = next;
42 | }
43 | }
44 |
45 | static ListNode newNode(int val) {
46 | ListNode node = new ListNode();
47 | node.val = val;
48 | node.next = null;
49 | return node;
50 | }
51 |
52 | public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
53 | if (list1 == null && list2 == null) {
54 | return null;
55 | }
56 |
57 | ListNode result = null;
58 |
59 | while (list1 != null || list2 != null) {
60 | if (list1 == null && list2 != null) {
61 | result = insertEnd(result, list2.val);
62 | list2 = list2.next;
63 | } else if (list1 != null && list2 == null) {
64 | result = insertEnd(result, list1.val);
65 | list1 = list1.next;
66 | } else {
67 | result = insertEnd(result, Math.min(list1.val, list2.val));
68 | if (list1.val <= list2.val) {
69 | list1 = list1.next;
70 | } else {
71 | list2 = list2.next;
72 | }
73 | }
74 | }
75 |
76 | return result;
77 | }
78 |
79 | public static ListNode insertEnd(ListNode result, int val) {
80 | if (result == null) {
81 | return newNode(val);
82 | } else {
83 | result.next = insertEnd(result.next, val);
84 | }
85 |
86 | return result;
87 | }
88 |
89 | public static void printListNode(ListNode listNode) {
90 | System.out.print("ListNode : [");
91 | while (listNode != null) {
92 | System.out.print(listNode.val + " ");
93 | listNode = listNode.next;
94 | }
95 | System.out.println("]");
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/PacificAtlanticWaterFlow.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 |
3 | public class PacificAtlanticWaterFlow {
4 |
5 | //https://leetcode.com/problems/pacific-atlantic-water-flow/
6 |
7 | public static void main(String[] args) {
8 | System.out.println("Pacific Atlantic Water Flow");
9 |
10 | List> heights = new ArrayList<>(List.of(
11 | List.of(1, 2, 2, 3, 5),
12 | List.of(3, 2, 3, 4, 4),
13 | List.of(2, 4, 5, 3, 1),
14 | List.of(6, 7, 1, 4, 5),
15 | List.of(5, 1, 1, 2, 4)
16 | ));
17 |
18 | System.out.println(pacificAtlantic(heights.stream()
19 | .map(l -> l.stream().mapToInt(Integer::intValue).toArray())
20 | .toArray(int[][]::new)));
21 | System.out.println();
22 | System.out.println(alternativeSolution(heights));
23 | }
24 |
25 | public static List> pacificAtlantic(int[][] heights) {
26 | int rows = heights.length, cols = heights[0].length;
27 | boolean[][] pac = new boolean[rows][cols];
28 | boolean[][] atl = new boolean[rows][cols];
29 |
30 | for (int col = 0; col< cols; col++){
31 | dfs(0, col, rows, cols, pac, heights[0][col], heights);
32 | dfs(rows-1, col,rows, cols, atl, heights[rows-1][col], heights);
33 | }
34 |
35 | for (int row = 0; row> result = new ArrayList>();
40 | for (int i = 0; i < rows; i++)
41 | for (int j = 0; j < cols; j++){
42 | if (pac[i][j] && atl[i][j])
43 | result.add(Arrays.asList(i,j));
44 | }
45 | return result;
46 | }
47 |
48 | private static void dfs(int row, int col, int rows, int cols, boolean[][] visited, int prevHeight, int[][] heights){
49 | if (row < 0 || row >= rows || col < 0 || col >= cols || visited[row][col] || prevHeight > heights[row][col])
50 | return;
51 | visited[row][col]= true;
52 | dfs(row+1, col, rows, cols, visited, heights[row][col], heights);
53 | dfs(row-1, col, rows, cols, visited, heights[row][col], heights);
54 | dfs(row, col+1, rows, cols, visited, heights[row][col], heights);
55 | dfs(row, col-1, rows, cols, visited, heights[row][col], heights);
56 |
57 | }
58 |
59 | public static List> alternativeSolution(List> heights) {
60 | Set> result = new HashSet<>();
61 |
62 | for (int i = 0; i < heights.size(); i++) {
63 | int max = heights.get(i).stream().max(Integer::compareTo).orElse(0);
64 | for (int j = 0; j < heights.get(i).size(); j++) {
65 | int current = heights.get(i).get(j);
66 | int north = i > 0 ? heights.get(i - 1).get(j) : 0;
67 | int south = i + 1 < heights.size() ? heights.get(i + 1).get(j) : 0;
68 | int west = j > 0 ? heights.get(i).get(j - 1) : 0;
69 | int east = j + 1 < heights.get(i).size() ? heights.get(i).get(j + 1) : 0;
70 |
71 | if (current == max && (current >= north || current >= south || current >= west || current >= east)) {
72 | result.add(List.of(i, j));
73 | }
74 | }
75 | }
76 |
77 | int t = 0;
78 | //System.out.println(temp);
79 |
80 | for (int i = 0; i < heights.size(); i++) {
81 | for (int j = 0; j < heights.get(i).size(); j++) {
82 | int max = heights.get(j).stream().max(Integer::compareTo).orElse(0);
83 | int current = heights.get(j).get(i);
84 | int north = j > 0 ? heights.get(j - 1).get(j) : 0;
85 | int south = j + 1 < heights.size() ? heights.get(j + 1).get(i) : 0;
86 | int west = i > 0 ? heights.get(j).get(i - 1) : 0;
87 | int east = i + 1 < heights.get(j).size() ? heights.get(j).get(i + 1) : 0;
88 |
89 | if (current == max && (current > north || current > south || current > west || current > east)) {
90 | result.add(List.of(i, j));
91 | }
92 | }
93 | }
94 |
95 | return result.stream().toList();
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/src/PlusOne.java:
--------------------------------------------------------------------------------
1 | import java.math.BigDecimal;
2 | import java.util.ArrayList;
3 | import java.util.List;
4 |
5 | public class PlusOne {
6 |
7 | //https://leetcode.com/problems/plus-one/
8 |
9 | public static void main(String[] args) {
10 |
11 | int[] a = plusOne(new int[]{9,9});
12 |
13 | for (int i: a) {
14 | System.out.print(i);
15 | }
16 |
17 | }
18 |
19 | public static int[] plusOne(int[] digits) {
20 | for (int i = digits.length-1; i >= 0; i--) {
21 | if (digits[i] == 9) {
22 | digits[i] = 0;
23 | } else {
24 | digits[i] = digits[i] + 1;
25 | break;
26 | }
27 | }
28 | if (digits[0] == 0) {
29 | int[] result = new int[digits.length + 1];
30 | result[0] = 1;
31 | return result;
32 | }
33 | return digits;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/PolindromeNumber.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 | import java.util.Collections;
3 | import java.util.List;
4 | import java.util.Stack;
5 | import java.util.stream.Collectors;
6 |
7 | public class PolindromeNumber {
8 |
9 | public static void main(String[] args) {
10 |
11 | System.out.println(isPalindrome2(12112));
12 |
13 | }
14 |
15 | public static boolean isPalindrome(int x) {
16 | String s = String.valueOf(x);
17 |
18 | List cArr = new java.util.ArrayList<>(s.chars().mapToObj(e -> (char) e).toList());
19 |
20 | Collections.reverse(cArr);
21 |
22 | return cArr.stream().map(String::valueOf).collect(Collectors.joining()).equals(s);
23 | }
24 |
25 | public static boolean isPalindrome2(int x) {
26 | String s = String.valueOf(x);
27 |
28 | Stack stack = new Stack<>();
29 | stack.addAll(s.chars().mapToObj(e -> (char) e).toList());
30 |
31 | int i = 0;
32 | while (!stack.isEmpty()) {
33 | if (!(stack.pop() == s.charAt(i))) {
34 | return false;
35 | }
36 | i++;
37 | }
38 |
39 | return true;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/RemoveDuplicatesFromSortedArray.java:
--------------------------------------------------------------------------------
1 | import java.util.*;
2 | import java.util.stream.Collectors;
3 |
4 | public class RemoveDuplicatesFromSortedArray {
5 |
6 | //https://leetcode.com/problems/remove-duplicates-from-sorted-array/
7 |
8 | public static void main(String[] args) {
9 | System.out.println("result : " + removeDuplicates(new int[] {-3,-1,0,0,0,3,3}));
10 | }
11 |
12 | public static int removeDuplicates(int[] nums) {
13 | Set a = Arrays.stream(nums).boxed().sorted().collect(Collectors.toCollection(LinkedHashSet::new));
14 | int[] nums2 = a.stream().mapToInt(Integer::intValue).toArray();
15 | for (int i = 0; i < a.size(); i++) {
16 | if (nums[i] != nums2[i]){
17 | nums[i] = nums2[i];
18 | }
19 | }
20 |
21 | return a.size();
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/SearchInsertPosition.java:
--------------------------------------------------------------------------------
1 | public class SearchInsertPosition {
2 |
3 | //https://leetcode.com/problems/search-insert-position/
4 |
5 | public static void main(String[] args) {
6 |
7 | }
8 |
9 | public int searchInsert(int[] nums, int target) {
10 | int i = 0;
11 | for (; i < nums.length; i++) {
12 | if (nums[i] >= target) {
13 | break;
14 | }
15 | }
16 | return i;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/ValidParentheses.java:
--------------------------------------------------------------------------------
1 | import java.util.Map;
2 | import java.util.Stack;
3 |
4 | public class ValidParentheses {
5 |
6 | //https://leetcode.com/problems/valid-parentheses/
7 |
8 | public static void main(String[] args) {
9 | System.out.println(isValid("({[]}){"));
10 | }
11 |
12 | public static boolean isValid(String s) {
13 | if (s == null || s.isEmpty() || s.length() % 2 != 0) {
14 | return false;
15 | }
16 | Map map = Map.of(
17 | '(', ')',
18 | '[', ']',
19 | '{', '}'
20 | );
21 |
22 | Map map1 = Map.of(
23 | ')', '(',
24 | ']', '[',
25 | '}', '{'
26 | );
27 |
28 | Stack cStack = new Stack<>();
29 | for (int i = 0; i < s.length(); i++) {
30 | char current = s.charAt(i);
31 | if (map.containsKey(current)) {
32 | cStack.push(current);
33 | } else {
34 | if (cStack.isEmpty())
35 | return false;
36 | else if (map1.get(current) == cStack.peek() && map.get(cStack.peek()) == current) {
37 | cStack.pop();
38 | } else
39 | break;
40 | }
41 | }
42 |
43 | return cStack.isEmpty();
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/ValidSudoku.java:
--------------------------------------------------------------------------------
1 | import java.util.HashSet;
2 | import java.util.Set;
3 |
4 | public class ValidSudoku {
5 |
6 | //https://leetcode.com/problems/valid-sudoku/
7 |
8 | public static void main(String[] args) {
9 | char[][] board = {
10 | {'5','3','.','.','7','.','.','.','.'},
11 | {'6','.','.','1','9','5','.','.','.'},
12 | {'.','9','8','.','.','.','.','6','.'},
13 | {'8','.','.','.','6','.','.','.','3'},
14 | {'4','.','.','8','.','3','.','.','1'},
15 | {'7','.','.','.','2','.','.','.','6'},
16 | {'.','6','.','.','.','.','2','8','.'},
17 | {'.','.','.','4','1','9','.','.','5'},
18 | {'.','.','.','.','8','.','.','7','9'}
19 | };
20 |
21 | System.out.println(isValidSudoku(board));
22 | }
23 |
24 | public static boolean isValidSudoku(char[][] board) {
25 | for (int i = 0; i < board.length; i++) {
26 | Set charSet = new HashSet<>();
27 | for (int j = 0; j < board.length; j++) {
28 | if (board[i][j] == '.') {
29 | continue;
30 | }
31 | if (charSet.contains(board[i][j])) {
32 | return false;
33 | }
34 | charSet.add(board[i][j]);
35 | }
36 | }
37 |
38 | for (int i = 0; i < board.length; i++) {
39 | Set charSet = new HashSet<>();
40 | for (int j = 0; j < board.length; j++) {
41 | if (board[j][i] == '.') {
42 | continue;
43 | }
44 | if (charSet.contains(board[j][i])) {
45 | return false;
46 | }
47 | charSet.add(board[j][i]);
48 | }
49 | }
50 |
51 | for (int i = 0; i < board.length; i = i + 3) {
52 | for (int j = 0; j < board.length; j = j + 3) {
53 | Set charSet = new HashSet<>();
54 | for (int l = i, count = 0; count < 3; count++, l++) {
55 | for (int k = j, cnt = 0; cnt < 3; cnt++, k++) {
56 | if (board[l][k] == '.') {
57 | continue;
58 | }
59 | if (charSet.contains(board[l][k])) {
60 | return false;
61 | }
62 | charSet.add(board[l][k]);
63 | }
64 | }
65 |
66 | }
67 | }
68 | return true;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------