binaryTreePaths(TreeNode root) {
18 |
19 | if (root == null) return res;
20 | preorder(root, new StringBuilder());
21 | return res;
22 |
23 | }
24 |
25 | public void preorder(TreeNode root, StringBuilder sb) {
26 |
27 | if (root == null) return;
28 |
29 | sb.append(root.val);
30 | if (root.left == null && root.right == null) {
31 | res.add(sb.toString());
32 | return;
33 | }
34 | sb.append("->");
35 |
36 | preorder(root.left, new StringBuilder(sb));
37 | preorder(root.right, new StringBuilder(sb));
38 |
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/ConvertBST.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 538. Convert BST to Greater Tree (Medium)
4 | * https://leetcode.com/problems/convert-bst-to-greater-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/3
9 | */
10 | public class ConvertBST {
11 |
12 | private int sum = 0;
13 |
14 | public TreeNode convertBST(TreeNode root) {
15 | inorder(root);
16 | return root;
17 | }
18 |
19 | public void inorder(TreeNode root) {
20 |
21 | if (root == null) return;
22 |
23 | inorder(root.right);
24 | sum += root.val;
25 | root.val = sum;
26 | inorder(root.left);
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/GetTargetCopy.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree (Medium)
4 | * https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/1
9 | */
10 | public class GetTargetCopy {
11 |
12 | private int target;
13 | private TreeNode res;
14 |
15 | public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
16 | this.target = target.val;
17 | preorder(cloned);
18 | return res;
19 | }
20 |
21 |
22 | public void preorder(TreeNode root) {
23 |
24 | if (root == null) return;
25 |
26 | /*
27 | The values of the nodes of the tree are unique
28 | */
29 | if (root.val == target) {
30 | res = root;
31 | return;
32 | }
33 |
34 | preorder(root.left);
35 | preorder(root.right);
36 |
37 | }
38 |
39 | }
40 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/GoodNodes.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 1448. Count Good Nodes in Binary Tree (Medium)
4 | * https://leetcode.com/problems/count-good-nodes-in-binary-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/30
9 | */
10 | public class GoodNodes {
11 |
12 | private int res = 0;
13 |
14 | public int goodNodes(TreeNode root) {
15 | preorder(root, Integer.MIN_VALUE);
16 | return res;
17 | }
18 |
19 |
20 | public void preorder(TreeNode root, int max) {
21 |
22 | // Base case
23 | if (root == null) return;
24 |
25 | if (root.val >= max) {
26 | res++;
27 | max = root.val;
28 | }
29 |
30 | preorder(root.left, max);
31 | preorder(root.right, max);
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/IsSameTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 100. Same Tree (Easy)
4 | * https://leetcode.com/problems/same-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/30
9 | */
10 | public class IsSameTree {
11 | public boolean isSameTree(TreeNode p, TreeNode q) {
12 |
13 | /*
14 | Preorder traversal
15 | */
16 | if (p == null && q == null) return true;
17 |
18 | if (p != null && q != null && p.val != q.val) return false;
19 |
20 | if (p == null || q == null) return false;
21 |
22 | return isSameTree(p.left == null ? null : p.left, q.left == null ? null : q.left)
23 | && isSameTree(p.right == null ? null : p.right, q.right == null ? null : q.right);
24 |
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/IsUnivalTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 965. Univalued Binary Tree
4 | * https://leetcode.com/problems/univalued-binary-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/30
9 | */
10 | public class IsUnivalTree {
11 |
12 | private int uniqueVal;
13 |
14 | public boolean isUnivalTree(TreeNode root) {
15 |
16 | if (root == null) return true;
17 | uniqueVal = root.val;
18 |
19 | return preorder(root);
20 |
21 | }
22 |
23 | public boolean preorder(TreeNode root) {
24 |
25 | if (root == null) return true;
26 |
27 | if (root.val != uniqueVal) return false;
28 |
29 | return preorder(root.left) && preorder(root.right);
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/MaxAncestorDiff.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 1026. Maximum Difference Between Node and Ancestor (Medium)
4 | * https://leetcode.com/problems/maximum-difference-between-node-and-ancestor/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/31
9 | */
10 | public class MaxAncestorDiff {
11 |
12 | private int res = 0;
13 |
14 | public int maxAncestorDiff(TreeNode root) {
15 |
16 | if (root == null) return 0;
17 |
18 | preorder(root, root.val, root.val);
19 |
20 | return res;
21 |
22 | }
23 |
24 | public void preorder(TreeNode root, int minVal, int maxVal) {
25 |
26 | if (root == null) return;
27 |
28 | minVal = Math.min(minVal, root.val);
29 | maxVal = Math.max(maxVal, root.val);
30 | res = Math.max(res, Math.abs(maxVal - minVal));
31 |
32 | preorder(root.left, minVal, maxVal);
33 | preorder(root.right, minVal, maxVal);
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/RangeSumBST.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 938. Range Sum of BST (Easy)
4 | * https://leetcode.com/problems/range-sum-of-bst/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/30
9 | */
10 | public class RangeSumBST {
11 | private int res = 0;
12 | private int low;
13 | private int high;
14 |
15 | public int rangeSumBST(TreeNode root, int low, int high) {
16 |
17 | if (root == null) return 0;
18 | this.low = low;
19 | this.high = high;
20 |
21 | preorder(root);
22 |
23 | return res;
24 |
25 | }
26 |
27 | public void preorder(TreeNode root) {
28 |
29 | if (root == null) return;
30 |
31 | int cur = root.val;
32 |
33 | if (cur >= low && cur <= high) {
34 | res += cur;
35 | preorder(root.left);
36 | preorder(root.right);
37 | } else if (cur < low) {
38 | preorder(root.right);
39 | } else {
40 | preorder(root.left);
41 | }
42 |
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/SearchBST.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 700. Search in a Binary Search Tree (Easy)
4 | * https://leetcode.com/problems/search-in-a-binary-search-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/30
9 | */
10 | public class SearchBST {
11 | public TreeNode searchBST(TreeNode root, int val) {
12 |
13 | if (root == null) return null;
14 |
15 | /*
16 | Preorder traversal
17 | */
18 | if (val == root.val) return root;
19 |
20 | if (val < root.val) {
21 | return searchBST(root.left, val);
22 | } else {
23 | return searchBST(root.right, val);
24 | }
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/SortedArrayToBST.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 108. Convert Sorted Array to Binary Search Tree (Easy)
4 | * https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/30
9 | */
10 | public class SortedArrayToBST {
11 |
12 | private int[] nums;
13 |
14 | public TreeNode sortedArrayToBST(int[] nums) {
15 | this.nums = nums;
16 | return preorder(0, nums.length - 1);
17 | }
18 |
19 | public TreeNode preorder(int left, int right) {
20 |
21 | // Base case
22 | if (left > right) return null;
23 |
24 | int mid = left + (right - left) / 2;
25 | TreeNode newNode = new TreeNode(nums[mid]);
26 |
27 | newNode.left = preorder(left, mid - 1);
28 | newNode.right = preorder(mid + 1, right);
29 |
30 | return newNode;
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/SumEvenGrandparent.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 1315. Sum of Nodes with Even-Valued Grandparent (Medium)
4 | * https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/31
9 | */
10 | public class SumEvenGrandparent {
11 |
12 | private int res = 0;
13 |
14 | public int sumEvenGrandparent(TreeNode root) {
15 |
16 | /*
17 | The value of nodes is between 1 and 100
18 | so, -1 represents null
19 | */
20 | preorder(root, -1, -1);
21 | return res;
22 | }
23 |
24 | public void preorder(TreeNode root, int parent, int grandParent) {
25 |
26 | if (root == null) return;
27 |
28 | if (grandParent != -1 && grandParent % 2 == 0) res += root.val;
29 |
30 | preorder(root.left, root.val, parent);
31 | preorder(root.right, root.val, parent);
32 |
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/exercises/tree/src/main/java/TreeNode.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | *
4 | *
5 | *
6 | * @author ceezyyy
7 | * @since 2021/3/24
8 | */
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 |
14 | public TreeNode(int val) {
15 | this.val = val;
16 | }
17 |
18 | public TreeNode(int val, TreeNode left, TreeNode right) {
19 | this.val = val;
20 | this.left = left;
21 | this.right = right;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/exercises/two-pointers/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | exercises
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | two-pointers
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/exercises/two-pointers/src/main/java/RemoveDuplicates.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 26. Remove Duplicates from Sorted Array (Easy)
4 | * https://leetcode.com/problems/remove-duplicates-from-sorted-array/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/18
9 | */
10 | public class RemoveDuplicates {
11 | public int removeDuplicates(int[] nums) {
12 |
13 | if (nums == null || nums.length == 0) return 0;
14 | int index = 0;
15 | int cmp = nums[0];
16 | int cur;
17 |
18 | for (int i = 1; i < nums.length; i++) {
19 |
20 | cur = nums[i];
21 |
22 | if (cur != cmp) {
23 | nums[++index] = cur;
24 | cmp = cur;
25 | }
26 |
27 | }
28 |
29 | return index + 1;
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/exercises/two-pointers/src/main/java/TwoSumII.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 167. 两数之和 II - 输入有序数组 (Easy)
4 | * Two Sum 变式
5 | * https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/
6 | *
7 | *
8 | * @author ceezyyy
9 | * @since 2021/4/18
10 | */
11 | public class TwoSumII {
12 | }
13 |
--------------------------------------------------------------------------------
/exercises/two-pointers/src/main/java/TwoSumLessThanK.java:
--------------------------------------------------------------------------------
1 | import java.util.Arrays;
2 |
3 | /**
4 | *
5 | * 1099. 小于 K 的两数之和 (Easy)
6 | * Two Sum 变式
7 | * https://leetcode-cn.com/problems/two-sum-less-than-k/
8 | *
9 | *
10 | * @author ceezyyy
11 | * @since 2021/4/18
12 | */
13 | class TwoSumLessThanK {
14 |
15 | private int res = -1;
16 |
17 | public int twoSumLessThanK(int[] nums, int k) {
18 |
19 | Arrays.sort(nums);
20 | int i = 0;
21 | int j = nums.length - 1;
22 |
23 | while (i < j) {
24 |
25 | int sum = nums[i] + nums[j];
26 | // Keep tracking of "res"
27 | if (sum < k) res = Math.max(sum, res);
28 |
29 | if (sum >= k) {
30 | j--;
31 | } else {
32 | i++;
33 | }
34 |
35 | }
36 |
37 | return res;
38 |
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/exercises/two-pointers/two-pointers.iml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/interviews/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/interviews/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/interviews/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
--------------------------------------------------------------------------------
/interviews/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/interviews/array/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | array
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/array/src/main/java/MajorityElement.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 169. Majority Element (Easy)
4 | * Moore-Voting Algorithm
5 | * https://leetcode.com/problems/majority-element/
6 | *
7 | *
8 | * @author ceezyyy
9 | * @since 2021/4/22
10 | */
11 | public class MajorityElement {
12 | public int majorityElement(int[] nums) {
13 |
14 | int n = nums.length;
15 | // Init
16 | int cand = nums[0];
17 | int cnt = 1;
18 |
19 | for (int i = 1; i < n; i++) {
20 | if (cnt == 0) {
21 | // Change candidate
22 | cand = nums[i];
23 | cnt = 1;
24 | continue;
25 | }
26 | cnt = nums[i] == cand ? cnt + 1 : cnt - 1;
27 | }
28 |
29 | return cand;
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/interviews/array/src/main/java/MaxConsecutiveOnes.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 485. Max Consecutive Ones (Easy)
4 | * https://leetcode.com/problems/max-consecutive-ones/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/22
9 | */
10 | public class MaxConsecutiveOnes {
11 | public int findMaxConsecutiveOnes(int[] nums) {
12 |
13 | int res = 0;
14 | int n = nums.length;
15 | int cnt = 0;
16 |
17 | for (int num : nums) {
18 | if (num == 1) {
19 | cnt++;
20 | } else {
21 | res = Math.max(cnt, res);
22 | cnt = 0;
23 | }
24 | }
25 |
26 | return Math.max(cnt, res);
27 |
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/interviews/array/src/main/java/MoveZeroes.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 283. Move Zeroes (Easy)
4 | * https://leetcode.com/problems/move-zeroes/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/18
9 | */
10 | public class MoveZeroes {
11 | public void moveZeroes(int[] nums) {
12 |
13 | // 1 <= nums.length <= 10^4
14 | int n = nums.length;
15 |
16 | int i = 0;
17 |
18 | // "j" should start from zero!
19 | for (int j = 0; j < n; j++) {
20 | if (nums[j] != 0) {
21 | nums[i] = nums[j];
22 | i++;
23 | }
24 | }
25 |
26 | // Filling w/ zero
27 | while (i < n) {
28 | nums[i] = 0;
29 | i++;
30 | }
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/interviews/array/src/main/java/RotateArray.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 189. Rotate Array (Medium)
4 | * https://leetcode.com/problems/rotate-array/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/18
9 | */
10 | public class RotateArray {
11 |
12 | private int[] nums;
13 | private int n;
14 |
15 | public void rotate(int[] nums, int k) {
16 |
17 | this.nums = nums;
18 | this.n = nums.length;
19 |
20 | // k is non-negative
21 | k = k % n;
22 |
23 | reverse(0, - 1);
24 | reverse(0, k - 1);
25 | reverse(k, n - 1);
26 |
27 | }
28 |
29 | public void reverse(int i, int j) {
30 | while (i < j) {
31 | int tmp = nums[i];
32 | nums[i] = nums[j];
33 | nums[j] = tmp;
34 | i++;
35 | j--;
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/interviews/array/src/main/java/SearchMatrix.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 240. Search a 2D Matrix II (Medium)
4 | * https://leetcode.com/problems/search-a-2d-matrix-ii/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/22
9 | */
10 | public class SearchMatrix {
11 | public boolean searchMatrix(int[][] matrix, int target) {
12 |
13 | // 1 <= n, m <= 300
14 | int rows = matrix.length;
15 | int cols = matrix[0].length;
16 | // Upper-right
17 | int i = 0;
18 | int j = cols - 1;
19 |
20 | while (i < rows && j >= 0) {
21 | int cur = matrix[i][j];
22 | if (target == cur) return true;
23 | if (target < cur) j--;
24 | if (target > cur) i++;
25 | }
26 |
27 | return false;
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/interviews/binary-search/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | binary-search
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/bit-manipulation/bit-manipulation.iml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/interviews/bit-manipulation/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | bit-manipulation
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/divide-and-conquer/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | divide-and-conquer
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/dynamic-programming/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | dynamic-programming
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/dynamic-programming/src/main/java/ClimbStairs.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 70. Climbing Stairs (Easy)
4 | * https://leetcode.com/problems/climbing-stairs/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/18
9 | */
10 | public class ClimbStairs {
11 | public int climbStairs(int n) {
12 |
13 | // Corner case
14 | if (n == 1) return 1;
15 |
16 | int[] dp = new int[n + 1];
17 | // One step
18 | dp[1] = 1;
19 | // Two steps
20 | dp[2] = 2;
21 |
22 | for (int i = 3; i <= n; i++) {
23 | dp[i] = dp[i - 1] + dp[i - 2];
24 | }
25 |
26 | // N steps
27 | return dp[n];
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/interviews/graph/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | graph
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/greedy/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | greedy
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/hashtable/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | hashtable
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/hashtable/src/main/java/TwoSum.java:
--------------------------------------------------------------------------------
1 | import java.util.HashMap;
2 | import java.util.Map;
3 |
4 | /**
5 | *
6 | * 1. Two Sum
7 | * https://leetcode.com/problems/two-sum/
8 | *
9 | *
10 | * @author ceezyyy
11 | * @since 2021/4/15
12 | */
13 | class TwoSum {
14 | public int[] twoSum(int[] nums, int target) {
15 |
16 | int n = nums.length;
17 | /*
18 | We need to find element frequently
19 | so, we use hashtable
20 |
21 | */
22 | Map map = new HashMap<>();
23 |
24 | for (int i = 0; i < n; i++) {
25 |
26 | int k = target - nums[i];
27 |
28 | if (map.containsKey(k)) return new int[]{i, map.get(k)};
29 | map.put(nums[i], i);
30 |
31 | }
32 |
33 | return new int[2];
34 |
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/interviews/interviews.iml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/interviews/linked-list/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | linked-list
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/linked-list/src/main/java/ListNode.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | *
4 | *
5 | *
6 | * @author ceezyyy
7 | * @since 2021/3/24
8 | */
9 | class ListNode {
10 |
11 | int val;
12 | ListNode next;
13 |
14 | ListNode(int x) {
15 | val = x;
16 | next = null;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/interviews/linked-list/src/main/java/RemoveNthFromEnd.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 19. Remove Nth Node From End of List (Medium)
4 | * https://leetcode.com/problems/remove-nth-node-from-end-of-list/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/16
9 | */
10 | public class RemoveNthFromEnd {
11 | public ListNode removeNthFromEnd(ListNode head, int n) {
12 |
13 | ListNode dummy = new ListNode(-1);
14 | dummy.next = head;
15 | ListNode cur = head;
16 | int size = 0;
17 | int steps = 0;
18 |
19 | // Get the size
20 | while (cur != null) {
21 | cur = cur.next;
22 | size++;
23 | }
24 |
25 | // The relationship between size and n-th from the end
26 | steps = size - n;
27 | cur = dummy;
28 |
29 | while (steps-- > 0) cur = cur.next;
30 | cur.next = cur.next.next;
31 |
32 | return dummy.next;
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/interviews/linked-list/src/main/java/ReverseList.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 206. Reverse Linked List (Easy)
4 | * https://leetcode.com/problems/reverse-linked-list/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/16
9 | */
10 | public class ReverseList {
11 | public ListNode reverseList(ListNode head) {
12 |
13 | ListNode pre = null;
14 | ListNode cur = head;
15 | ListNode post;
16 |
17 | while (cur != null) {
18 | post = cur.next;
19 | cur.next = pre;
20 | pre = cur;
21 | cur = post;
22 | }
23 |
24 | return pre;
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/interviews/math/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | math
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/math/src/main/java/ExcelSheetColumnNumber.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 171. Excel Sheet Column Number (Easy)
4 | * https://leetcode.com/problems/excel-sheet-column-number/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/22
9 | */
10 | public class ExcelSheetColumnNumber {
11 | public int titleToNumber(String columnTitle) {
12 |
13 | String s = new StringBuilder(columnTitle).reverse().toString();
14 | char[] nums = s.toCharArray();
15 | int n = nums.length;
16 | int res = 0;
17 |
18 | for (int i = 0; i < n; i++) {
19 | int cur = nums[i] - 'A' + 1;
20 | // 26-Base
21 | res += cur * (int) Math.pow(26, i);
22 | }
23 |
24 | return res;
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/interviews/math/src/main/java/MissingNumber.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | *
4 | *
5 | *
6 | * @author ceezyyy
7 | * @since 2021/4/22
8 | */
9 | public class MissingNumber {
10 | public int missingNumber(int[] nums) {
11 |
12 | int n = nums.length;
13 | int actual = 0;
14 |
15 | for (int num : nums) actual += num;
16 | // Gauss' Formula
17 | int expected = (1 + n) * n / 2;
18 |
19 | return expected - actual;
20 |
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/interviews/math/src/main/java/PlusOne.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 66. Plus One (Easy)
4 | * https://leetcode.com/problems/plus-one/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/18
9 | */
10 | public class PlusOne {
11 | public int[] plusOne(int[] digits) {
12 |
13 | int n = digits.length;
14 |
15 | // Backwards
16 | for (int i = n - 1; i >= 0; i--) {
17 |
18 | // No carry
19 | if (digits[i] < 9) {
20 | digits[i]++;
21 | return digits;
22 | }
23 |
24 | // Carry
25 | digits[i] = 0;
26 |
27 | }
28 |
29 | // Still not returned
30 | digits = new int[n + 1];
31 | digits[0] = 1;
32 | return digits;
33 |
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/interviews/searching/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | searching
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/sorting/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | sorting
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/sorting/src/main/java/App.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | *
4 | *
5 | *
6 | * @author ceezyyy
7 | * @since 2021/3/26
8 | */
9 | public class App {
10 | public static void main(String[] args) {
11 |
12 | // int[] arr = new int[]{3, 4, 1, 32, 0, 1, 5, 12, 2, 5, 7, 8, 9, 2, 44, 111, 5};
13 |
14 | int[] arr = new int[]{1, -1, 2, 0 };
15 | QuickSort.sort(arr, 0, arr.length - 1);
16 |
17 | for (int i = 0; i < arr.length; i++) {
18 | System.out.print(arr[i]);
19 | System.out.print(" ");
20 | }
21 |
22 | }
23 |
24 | }
25 |
--------------------------------------------------------------------------------
/interviews/sorting/src/main/java/InsertionSort.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * Insertion Sort
4 | * Finding the location of data[i] within the sorted list
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/26
9 | */
10 | public class InsertionSort {
11 |
12 | public static int[] sort(int[] arr) {
13 |
14 | int n = arr.length;
15 |
16 | for (int i = 1; i < n; i++) {
17 |
18 | /*
19 | Pick the card
20 | */
21 | int card = arr[i];
22 |
23 | int j = i - 1;
24 | while (j >= 0 && arr[j] > card) {
25 | arr[j + 1] = arr[j];
26 | j--;
27 | }
28 |
29 | /*
30 | Placing card at its correct position
31 | */
32 | arr[j + 1] = card;
33 |
34 | }
35 |
36 | return arr;
37 |
38 | }
39 |
40 | }
41 |
42 |
43 | /**
44 | * Average: O(n^2)
45 | * Best: O(n)
46 | * Worse: O(n^2)
47 | * Space: O(1)
48 | * Stable
49 | */
50 |
--------------------------------------------------------------------------------
/interviews/sorting/target/classes/App.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/interviews/sorting/target/classes/App.class
--------------------------------------------------------------------------------
/interviews/sorting/target/classes/InsertionSort.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/interviews/sorting/target/classes/InsertionSort.class
--------------------------------------------------------------------------------
/interviews/sorting/target/classes/MergeSort.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/interviews/sorting/target/classes/MergeSort.class
--------------------------------------------------------------------------------
/interviews/sorting/target/classes/QuickSort.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/interviews/sorting/target/classes/QuickSort.class
--------------------------------------------------------------------------------
/interviews/sorting/target/classes/SelectionSort.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/interviews/sorting/target/classes/SelectionSort.class
--------------------------------------------------------------------------------
/interviews/stack-and-queue/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | stack-and-queue
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/stack-and-queue/src/main/java/DailyTemperatures.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayDeque;
2 | import java.util.Deque;
3 |
4 | /**
5 | *
6 | * 739. Daily Temperatures
7 | * https://leetcode.com/problems/daily-temperatures/
8 | *
9 | *
10 | * @author ceezyyy
11 | * @since 2021/3/22
12 | */
13 | class DailyTemperatures {
14 | public int[] dailyTemperatures(int[] T) {
15 |
16 | Deque decreasingStack = new ArrayDeque<>();
17 | int[] res = new int[T.length];
18 |
19 | for (int i = 0; i < T.length; i++) {
20 |
21 | int cur = T[i];
22 |
23 | while (!decreasingStack.isEmpty() && T[decreasingStack.peek()] < cur) {
24 | int index = decreasingStack.pop();
25 | res[index] = i - index;
26 | }
27 |
28 | decreasingStack.push(i);
29 |
30 | }
31 |
32 | return res;
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/interviews/string/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | string
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/string/src/main/java/ValidAnagram.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 242. Valid Anagram (Easy)
4 | * https://leetcode.com/problems/valid-anagram/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/19
9 | */
10 | public class ValidAnagram {
11 | public boolean isAnagram(String s, String t) {
12 |
13 | // s and t consist of lowercase English letters
14 | int[] visited = new int[26];
15 |
16 | for (char c : s.toCharArray()) {
17 | int e = c - 'a';
18 | visited[e]++;
19 | }
20 |
21 | for (char c : t.toCharArray()) {
22 | int e = c - 'a';
23 | visited[e]--;
24 | }
25 |
26 | for (int e : visited) {
27 | if (e != 0) return false;
28 | }
29 |
30 | return true;
31 |
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/interviews/string/src/main/java/ValidPalindrome.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 125. Valid Palindrome (Easy)
4 | * https://leetcode.com/problems/valid-palindrome/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/20
9 | */
10 | public class ValidPalindrome {
11 | public boolean isPalindrome(String s) {
12 |
13 | char[] nums = s.toCharArray();
14 | int i = 0;
15 | int j = nums.length - 1;
16 |
17 | while (true) {
18 |
19 | while (i <= j && !Character.isLetterOrDigit(nums[i])) {
20 | i++;
21 | }
22 | while (i <= j && !Character.isLetterOrDigit(nums[j])) {
23 | j--;
24 | }
25 |
26 | // Failed cases
27 | if (i >= j) break;
28 | if (Character.toLowerCase(nums[i]) != Character.toLowerCase(nums[j])) return false;
29 |
30 | // Keep going
31 | i++;
32 | j--;
33 |
34 | }
35 |
36 | return true;
37 |
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/interviews/tree/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | tree
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/tree/src/main/java/DiameterOfBinaryTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 543. Diameter of Binary Tree (Easy)
4 | * https://leetcode.com/problems/diameter-of-binary-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/24
9 | */
10 | class DiameterOfBinaryTree {
11 |
12 | private int res = 0;
13 |
14 | public int diameterOfBinaryTree(TreeNode root) {
15 | getMaxDepth(root);
16 | return res;
17 |
18 | }
19 |
20 | public int getMaxDepth(TreeNode root) {
21 |
22 | if (root == null) return 0;
23 |
24 | /*
25 | For each node:
26 |
27 | 1) Get the max depth of left & right child
28 |
29 | 2) Keep tracking the max path, because the longest path
30 | may or may not pass through the root
31 | */
32 | int left = getMaxDepth(root.left);
33 | int right = getMaxDepth(root.right);
34 |
35 | if (left + right > res) res = left + right;
36 |
37 | return Math.max(left, right) + 1;
38 |
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/interviews/tree/src/main/java/InvertBinaryTree.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 226. Invert Binary Tree (Easy)
4 | * https://leetcode.com/problems/invert-binary-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/24
9 | */
10 | class InvertBinaryTree {
11 | public TreeNode invertTree(TreeNode root) {
12 |
13 | if (root == null) return root;
14 |
15 | /*
16 | For each node:
17 |
18 | 1) invert its left & right child
19 | 2) the left / right pointer points to the "invertedRight" / "invertedLeft"
20 | */
21 | TreeNode invertedLeft = invertTree(root.left);
22 | TreeNode invertedRight = invertTree(root.right);
23 |
24 | root.left = invertedRight;
25 | root.right = invertedLeft;
26 |
27 | return root;
28 |
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/interviews/tree/src/main/java/KthSmallest.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 230. Kth Smallest Element in a BST (Medium)
4 | * https://leetcode.com/problems/kth-smallest-element-in-a-bst/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/3
9 | */
10 | public class KthSmallest {
11 |
12 | private int res = 0;
13 | private int counter = 0;
14 | private int k = 0;
15 |
16 | public int kthSmallest(TreeNode root, int k) {
17 | this.k = k;
18 | inorder(root);
19 | return res;
20 | }
21 |
22 | public void inorder(TreeNode root) {
23 |
24 | if (root == null) return;
25 |
26 | inorder(root.left);
27 | counter++;
28 | if (counter == k) {
29 | res = root.val;
30 | return;
31 | }
32 | inorder(root.right);
33 |
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/interviews/tree/src/main/java/LowestCommonAncestor.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 236. Lowest Common Ancestor of a Binary Tree (Medium)
4 | * https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/3
9 | */
10 | public class LowestCommonAncestor {
11 |
12 | public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
13 |
14 | /*
15 | We allow a node to be a descendant of itself
16 | */
17 | if (root == null || root == p || root == q) return root;
18 |
19 | TreeNode left = lowestCommonAncestor(root.left, p, q);
20 | TreeNode right = lowestCommonAncestor(root.right, p, q);
21 |
22 | /*
23 | Bottom up -> lowest
24 | */
25 | if (left != null && right != null) return root;
26 |
27 | /*
28 | Constraint: p and q will exist in the tree
29 | So, at least one node is not null
30 | */
31 | return left == null ? right : left;
32 |
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/interviews/tree/src/main/java/MaxDepth.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 104. Maximum Depth of Binary Tree (Easy)
4 | * https://leetcode.com/problems/maximum-depth-of-binary-tree/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/24
9 | */
10 | class MaxDepth {
11 | public int maxDepth(TreeNode root) {
12 | if (root == null) return 0;
13 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/interviews/tree/src/main/java/MinDepth.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 111. Minimum Depth of Binary Tree (Easy)
4 | *
5 | *
6 | * @author ceezyyy
7 | * @since 2021/3/29
8 | */
9 | public class MinDepth {
10 | public int minDepth(TreeNode root) {
11 |
12 | if (root == null) return 0;
13 |
14 | int leftDepth = minDepth(root.left);
15 | int rightDepth = minDepth(root.right);
16 |
17 | /*
18 | min path is from root to leaf
19 | so when we decide to choose a non-empty element between a and b
20 | we can just add them together ("a + b")
21 | */
22 | if (leftDepth == 0 || rightDepth == 0) return leftDepth + rightDepth + 1;
23 |
24 | return Math.min(leftDepth, rightDepth) + 1;
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/interviews/tree/src/main/java/PathSum.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 112. Path Sum (Easy)
4 | * https://leetcode.com/problems/path-sum/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/3/29
9 | */
10 | public class PathSum {
11 | public boolean hasPathSum(TreeNode root, int target) {
12 |
13 | // root-to-leaf path
14 | // e.g: [1, null, 2, null, 3] -> path sum: 6
15 | if (root == null) return false;
16 |
17 | // leaf
18 | if (root.left == null && root.right == null && root.val == target) return true;
19 |
20 | // If current node is not a leaf
21 | return hasPathSum(root.left, target - root.val) || hasPathSum(root.right, target - root.val);
22 |
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/interviews/tree/src/main/java/TreeNode.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | *
4 | *
5 | *
6 | * @author ceezyyy
7 | * @since 2021/3/24
8 | */
9 | class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 |
14 | public TreeNode(int val) {
15 | this.val = val;
16 | }
17 |
18 | public TreeNode(int val, TreeNode left, TreeNode right) {
19 | this.val = val;
20 | this.left = left;
21 | this.right = right;
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/interviews/two-pointers/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | interviews
7 | org.example
8 | 1.0-SNAPSHOT
9 |
10 | 4.0.0
11 |
12 | two-pointers
13 |
14 |
15 | 8
16 | 8
17 |
18 |
19 |
--------------------------------------------------------------------------------
/interviews/two-pointers/src/main/java/ListNode.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | *
4 | *
5 | *
6 | * @author ceezyyy
7 | * @since 2021/3/24
8 | */
9 | class ListNode {
10 |
11 | int val;
12 | ListNode next;
13 |
14 | ListNode(int x) {
15 | val = x;
16 | next = null;
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/interviews/two-pointers/src/main/java/ReverseString.java:
--------------------------------------------------------------------------------
1 | /**
2 | *
3 | * 344. Reverse String
4 | * https://leetcode.com/problems/reverse-string/
5 | *
6 | *
7 | * @author ceezyyy
8 | * @since 2021/4/15
9 | */
10 | class ReverseString {
11 |
12 | private char[] s;
13 |
14 | public void reverseString(char[] s) {
15 |
16 | this.s = s;
17 | int i = 0;
18 | int j = s.length - 1;
19 |
20 | while (i < j) {
21 | swap(i, j);
22 | i++;
23 | j--;
24 | }
25 |
26 | }
27 |
28 | public void swap(int i, int j) {
29 | char tmp = s[i];
30 | s[i] = s[j];
31 | s[j] = tmp;
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/others/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/.DS_Store
--------------------------------------------------------------------------------
/others/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/others/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/others/.idea/others.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/others/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/others/Python3/006.ZigZag Conversion.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 006. ZigZag Conversion
3 | @Tag: string
4 | @Date: Feb-21 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def convert(self, S: str, R: int) -> str:
12 | if R == 1 or R > len(S): # corner case
13 | return S
14 | res, i, step = ['' for r in range(R)], 0, 0 # a string for each line
15 | for s in S:
16 | res[i] += s
17 | if i == 0: # first row
18 | step = 1 # down
19 | if i == R - 1: # last row
20 | step = -1 # up
21 | i += step
22 | return "".join(res)
23 |
24 |
25 | """
26 | Runtime: 52 ms, faster than 86.77% of Python3 online submissions for ZigZag Conversion.
27 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for ZigZag Conversion.
28 | """
29 |
--------------------------------------------------------------------------------
/others/Python3/007.Reverse Integer.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 007. Reverse Integer
3 | @Tag: str
4 | @Date: Jan-03 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def reverse(self, x: int) -> int:
12 | k = str(x) # int -> str
13 | if k[0] == '-': # negative number
14 | k = k[1:] # get rid of the '-' first
15 | return -(int(k[::-1])) if -(int(k[::-1])) > -2**31 else 0
16 | else: # positive number
17 | return int(k[::-1]) if int(k[::-1]) < 2**31-1 else 0
18 |
19 |
20 | """
21 | within the 32-bit signed integer range: [−231, 231 − 1]
22 | """
23 |
24 |
25 | """
26 | Runtime: 20 ms, faster than 98.66% of Python3 online submissions for Reverse Integer.
27 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Reverse Integer.
28 | """
29 |
--------------------------------------------------------------------------------
/others/Python3/011.Container With Most Water.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 011. Container With Most Water
3 | @Tag: two pointers
4 | @Date: Jan-25 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def maxArea(self, height: List[int]) -> int:
12 | left, right, res = 0, len(height) - 1, 0 # two pointers & max area
13 | while left < right: # one pass
14 | res = max((right - left) * min(height[left], height[right]), res)
15 | if height[left] < height[right]:
16 | left += 1
17 | else:
18 | right -= 1
19 | return res
20 |
21 |
22 | """
23 | Runtime: 152 ms, faster than 11.71% of Python3 online submissions for Container With Most Water.
24 | Memory Usage: 14.3 MB, less than 92.63% of Python3 online submissions for Container With Most Water.
25 | """
26 |
27 |
28 | """
29 | Time Complexity: O(n)
30 | Space Complexity: O(1)
31 | """
32 |
--------------------------------------------------------------------------------
/others/Python3/013.Roman to Integer.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 013. Roman to Integer
3 | @Tag: string
4 | @Date: Jan-31 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def romanToInt(self, s: str) -> int:
12 | symbol, res = {'I': 1, 'V': 5, 'X': 10,
13 | 'L': 50, 'C': 100, 'D': 500, 'M': 1000}, 0
14 | for i in range(len(s) - 1):
15 | if symbol[s[i]] < symbol[s[i+1]]:
16 | res -= symbol[s[i]]
17 | else:
18 | res += symbol[s[i]]
19 | res += symbol[s[-1]] # always add the last element
20 | return res
21 |
22 |
23 | """
24 | Runtime: 44 ms, faster than 73.05% of Python3 online submissions for Roman to Integer.
25 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Roman to Integer.
26 | """
27 |
28 |
29 | """
30 | Time Complexity: O(n)
31 | Space Complexity: O(1)
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/020.Valid Parentheses.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 020. Valid Parentheses
3 | @Tag: stack / string
4 | @Date: Jan-27 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def isValid(self, s: str) -> bool:
12 | if len(s) % 2 != 0:
13 | return False
14 | mapping, stack = {")": "(", "]": "[", "}": "{"}, []
15 | for ch in s:
16 | if ch in mapping.keys(): # right
17 | if not stack or stack.pop() != mapping[ch]:
18 | return False
19 | else: # left
20 | stack.append(ch)
21 | return not stack
22 |
23 |
24 | """
25 | Runtime: 24 ms, faster than 90.29% of Python3 online submissions for Valid Parentheses.
26 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Valid Parentheses.
27 | """
28 |
29 |
30 | """
31 | Time Complexity: O(n)
32 | Space Complexity: O(n)
33 | """
34 |
--------------------------------------------------------------------------------
/others/Python3/049.Group Anagrams.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 049. Group Anagrams
3 | @Tag: hashtable
4 | @Date: Mar-10 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | import collections as c
11 |
12 |
13 | class Solution:
14 | def groupAnagrams(self, S: List[str]) -> List[List[str]]:
15 | d = c.defaultdict(list)
16 | for s in S:
17 | d["".join(sorted(s))].append(s)
18 | return d.values()
19 |
20 |
21 | """
22 | Runtime: 104 ms, faster than 54.29% of Python3 online submissions for Group Anagrams.
23 | Memory Usage: 15.9 MB, less than 67.92% of Python3 online submissions for Group Anagrams.
24 | """
25 |
26 |
27 | """
28 | Time Complexity: O(n * nlogn)
29 | Space Complexity: O(n)
30 | """
31 |
--------------------------------------------------------------------------------
/others/Python3/053.Maximum Subarray.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 053. Maximum Subarray
3 | @Tag: dp
4 | @Date: Dec-19 019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | @Reference: @Back To Back SWE
8 | https://www.youtube.com/watch?v=2MmGzdiKR9Y
9 | """
10 |
11 |
12 | class Solution:
13 | def maxSubArray(self, nums: List[int]) -> int:
14 | # corner case
15 | if len(nums) == 1: # containing at least one number
16 | return nums[0]
17 | dp = [0]*len(nums) # memory
18 | dp[0] = nums[0] # the first element / initialization
19 | res = dp[0] # a crucial step, initialized the res to dp[0]
20 | for i in range(1, len(nums)): # for loop
21 | dp[i] = max(dp[i-1]+nums[i], nums[i])
22 | if dp[i] > res:
23 | res = dp[i] # update the res
24 | return res
25 |
26 |
27 | """
28 | Runtime: 68 ms, faster than 82.83% of Python3 online submissions for Maximum Subarray.
29 | Memory Usage: 13.5 MB, less than 90.24% of Python3 online submissions for Maximum Subarray.
30 | """
31 |
--------------------------------------------------------------------------------
/others/Python3/056.Merge Intervals.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 056. Merge Intervals
3 | @Tag: array / sort
4 | @Date: Feb-22 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def merge(self, I: List[List[int]]) -> List[List[int]]:
12 | res, I = [], sorted(I)
13 | if not I: # corner case
14 | return None
15 | for i in I:
16 | if not res or i[0] > res[-1][1]: # new event
17 | res.append(i)
18 | else: # overlapping
19 | res[-1][1] = max(i[1], res[-1][1]) # update the finish time
20 | return res
21 |
22 |
23 | """
24 | Runtime: 88 ms, faster than 67.59% of Python3 online submissions for Merge Intervals.
25 | Memory Usage: 14.6 MB, less than 6.52% of Python3 online submissions for Merge Intervals.
26 | """
27 |
28 |
29 | """
30 | Time Complexity: O(nlogn)
31 | Space Complexity: O(n)
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/062.Unique Paths.py:
--------------------------------------------------------------------------------
1 | """
2 | @Topic: 062. Unique Paths
3 | @Tag: dp
4 | @Date: Dec-15 2019
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def uniquePaths(self, m: int, n: int) -> int:
12 | dp = [0]*(m*n) # memory
13 | dp[0] = 1 # only one grid
14 | for i in range(1, n*m):
15 | if i < n: # the first row without "top"
16 | dp[i] = dp[i-1]
17 | elif (i % n == 0): # the first col without "left"
18 | dp[i] = dp[i-n]
19 | else:
20 | dp[i] = dp[i-1]+dp[i-n] # recursion
21 | return dp[m*n-1] # the bottom-right
22 |
23 |
24 | """
25 | Runtime: 20 ms, faster than 99.18% of Python3 online submissions for Unique Paths.
26 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Unique Paths.
27 | """
28 |
--------------------------------------------------------------------------------
/others/Python3/066.Plus One.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 066. Plus One
3 | @Tag: array
4 | @Date: Mar-10 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | # Approach 1: (Naive)
11 |
12 | class Solution:
13 | def plusOne(self, A: List[int]) -> List[int]:
14 | s, res = 0, []
15 | for a in A:
16 | s = s * 10 + a
17 | s += 1
18 | while s > 0:
19 | res.append(s % 10)
20 | s //= 10
21 | return res[::-1]
22 |
23 |
24 | """
25 | Runtime: 32 ms, faster than 48.52% of Python3 online submissions for Plus One.
26 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Plus One.
27 | """
28 |
29 |
30 | """
31 | Time Complexity: O(n)
32 | Space Complexity: O(1)
33 | """
34 |
--------------------------------------------------------------------------------
/others/Python3/070.Climbing Stairs.py:
--------------------------------------------------------------------------------
1 | """
2 | @Topic: 070. Climbing Stairs
3 | @Tag: dp
4 | @Date: Dec-14 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def climbStairs(self, n: int) -> int:
12 | # corner case
13 | if n == 0 or n == 1:
14 | return 1
15 | if n == 2:
16 | return 2
17 | dp = [0]*(n+1) # memory
18 | # exit
19 | dp[0] = 1
20 | dp[1] = 1
21 | dp[2] = 2
22 | for i in range(3, n+1):
23 | dp[i] = dp[i-1]+dp[i-2] # recursion
24 | return dp[i]
25 |
26 |
27 | """
28 | Runtime: 24 ms, faster than 94.38% of Python3 online submissions for Climbing Stairs.
29 | Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Climbing Stairs.
30 | """
31 |
--------------------------------------------------------------------------------
/others/Python3/077.Combinations.py:
--------------------------------------------------------------------------------
1 | """
2 | @Topic: 077. Combinations
3 | @Tag: dfs/backtracking
4 | @Date: Dec-13 2019
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def combine(self, n: int, k: int) -> List[List[int]]:
12 | res = []
13 | if n >= k: # avoid corner case
14 | self.dfs(n, k, 1, [], res) # dfs/backtracking
15 | return res
16 |
17 | def dfs(self, n: int, k: int, index: int, cur: List[int], res: List[int]):
18 | if len(cur) == k: # the exit of dfs
19 | res.append(cur[:]) # deep copy
20 | for i in range(index, n+1):
21 | cur.append(i)
22 | self.dfs(n, k, i+1, cur, res)
23 | cur.pop() # backtracking
24 |
25 |
26 | """
27 | Runtime: 552 ms, faster than 57.89% of Python3 online submissions for Combinations.
28 | Memory Usage: 14.2 MB, less than 100.00% of Python3 online submissions for Combinations.
29 | """
30 |
--------------------------------------------------------------------------------
/others/Python3/100.Same Tree.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 100. Same Tree
3 | @Tag: binary tree
4 | @Date: Mar-04 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | # Definition for a binary tree node.
11 | # class TreeNode:
12 | # def __init__(self, x):
13 | # self.val = x
14 | # self.left = None
15 | # self.right = None
16 |
17 |
18 | class Solution:
19 | def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
20 | if not p and not q: # base case 1
21 | return True
22 | elif not p or not q: # base case 2
23 | return False
24 | elif p.val != q.val: # base case 3
25 | return False
26 | else:
27 | return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
28 |
29 |
30 | """
31 | Runtime: 28 ms, faster than 69.59% of Python3 online submissions for Same Tree.
32 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Same Tree.
33 | """
34 |
35 |
36 | """
37 | Time Complexity: O(n)
38 | Space Complexity: O(n)
39 | """
40 |
--------------------------------------------------------------------------------
/others/Python3/1016.Binary String With Substrings Representing 1 To N.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1016. Binary String With Substrings Representing 1 To N
3 | @Tag: str
4 | @Date: Jan-26 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def queryString(self, S: str, N: int) -> bool:
12 | for i in range(1, N + 1): # from 1 to N
13 | sub = "{0:b}".format(i) # int -> binary string
14 | if sub not in S:
15 | return False
16 | return True
17 |
18 |
19 | """
20 | Runtime: 76 ms, faster than 8.28% of Python3 online submissions for Binary String With Substrings Representing 1 To N.
21 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Binary String With Substrings Representing 1 To N.
22 | """
23 |
--------------------------------------------------------------------------------
/others/Python3/104.Maximum Depth of Binary Tree.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 104. Maximum Depth of Binary Tree
3 | @Tag: binary tree
4 | @Date: Mar-04 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | # Definition for a binary tree node.
11 | # class TreeNode:
12 | # def __init__(self, x):
13 | # self.val = x
14 | # self.left = None
15 | # self.right = None
16 |
17 |
18 | class Solution:
19 | def maxDepth(self, root: TreeNode) -> int:
20 | if not root:
21 | return 0
22 | left, right = self.maxDepth(root.left), self.maxDepth(root.right)
23 | return max(left, right) + 1
24 |
25 |
26 | """
27 | Runtime: 40 ms, faster than 68.10% of Python3 online submissions for Maximum Depth of Binary Tree.
28 | Memory Usage: 14.5 MB, less than 93.75% of Python3 online submissions for Maximum Depth of Binary Tree.
29 | """
30 |
31 |
32 | """
33 | """
34 |
--------------------------------------------------------------------------------
/others/Python3/1051.Height Checker.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1051. Height Checker
3 | @Tag: list
4 | @Date: Oct-22 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | # def heightChecker(self, heights: List[int]) -> int:
12 | def heightChecker(self, heights) -> int:
13 | res=0
14 | new_heights=sorted(heights)
15 | # The sorted() function returns a sorted list of the specified iterable object.
16 | for i,j in zip(heights,new_heights):
17 | if i!=j:
18 | res=res+1
19 | return res
20 |
21 |
22 | def main():
23 | s=Solution()
24 | print(s.heightChecker([1,1,4,2,1,3]))
25 |
26 |
27 | if __name__ == "__main__":
28 | main()
29 |
30 |
31 | """
32 | Runtime: 44 ms, faster than 58.44% of Python3 online submissions for Height Checker.
33 | Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Height Checker.
34 | """
--------------------------------------------------------------------------------
/others/Python3/1078.Occurrences After Bigram.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1078. Occurrences After Bigram
3 | @Tag: str
4 | @Date: Nov-05 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 | from typing import List
10 |
11 |
12 | class Solution:
13 | def findOccurrences(self, text: str, first: str, second: str) -> List[str]:
14 | res = []
15 | # str.split(separator, maxsplit)
16 | text = text.split() #
17 | for i in range(len(text)-2):
18 | if text[i] == first and text[i+1] == second:
19 | res.append(text[i+2])
20 | return res
21 |
22 |
23 | def test():
24 | s = Solution()
25 | res = s.findOccurrences("we will we will rock you", "we", "will")
26 | print(res)
27 |
28 |
29 | if __name__ == "__main__":
30 | test()
31 |
--------------------------------------------------------------------------------
/others/Python3/1089.Duplicate Zeros.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1089. Duplicate Zeros
3 | @Tag: array
4 | @Date: Feb-05 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def duplicateZeros(self, A: List[int]) -> None:
12 | """
13 | Do not return anything, modify arr in-place instead.
14 | """
15 | if A.count(0) == 0:
16 | return
17 | B, n = [], len(A)
18 | for a in A:
19 | B.append(a)
20 | if a == 0:
21 | B.append(0)
22 | A[:] = B[:n] # replace
23 |
24 |
25 | """
26 | Runtime: 68 ms, faster than 82.00% of Python3 online submissions for Duplicate Zeros.
27 | Memory Usage: 13.5 MB, less than 100.00% of Python3 online submissions for Duplicate Zeros.
28 | """
29 |
30 |
31 | """
32 | Time Complexity: O(n)
33 | Space Complexity: O(n)
34 | """
35 |
--------------------------------------------------------------------------------
/others/Python3/1103.Distribute Candies to People.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1103. Distribute Candies to People
3 | @Tag: array
4 | @Date: Feb-25 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def distributeCandies(self, c: int, n: int) -> List[int]:
12 | res = [0] * n
13 | i, per = 0, 1 # i: index, per: the money for i-th person(each turn)
14 | while c > 0: # until we run out of candies
15 | if i == n: # last person -> first person
16 | i = 0
17 | res[i], c, per = res[i] + per, c - per, per + 1
18 | # the last person receive all of our remaining candies
19 | per = c if c < per + 1 else per
20 | i += 1 # go on
21 | return res
22 |
23 |
24 | """
25 | Runtime: 36 ms, faster than 66.20% of Python3 online submissions for Distribute Candies to People.
26 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Distribute Candies to People.
27 | """
28 |
--------------------------------------------------------------------------------
/others/Python3/1108.Defanging an IP Address.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1108. Defanging an IP Address
3 | @Tag: str
4 | @Date: Oct-22 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def defangIPaddr(self, address: str) -> str:
12 | return address.replace('.','[.]')
13 |
14 |
15 | def main():
16 | s=Solution()
17 | print(s.defangIPaddr("1.1.1.1"))
18 |
19 |
20 | if __name__=="__main__":
21 | main()
22 |
23 |
--------------------------------------------------------------------------------
/others/Python3/1137.N-th Tribonacci Number.py:
--------------------------------------------------------------------------------
1 | """
2 | @Topic: 1137. N-th Tribonacci Number
3 | @Tag: dp
4 | @Date: Dec-14 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def tribonacci(self, n: int) -> int:
12 | # corner case
13 | if n == 0:
14 | return 0
15 | if n == 1:
16 | return 1
17 | if n == 2:
18 | return 1
19 | res = [0]*(n+1) # memory dp
20 | res[0] = 0 # T0 = 0
21 | res[1] = 1 # T1 = 1
22 | res[2] = 1 # T2 = 1
23 | for i in range(3, n+1):
24 | res[i] = res[i-3]+res[i-2]+res[i-1]
25 | return res[n]
26 |
27 |
28 | """
29 | Runtime: 24 ms, faster than 94.36% of Python3 online submissions for N-th Tribonacci Number.
30 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for N-th Tribonacci Number.
31 | """
32 |
--------------------------------------------------------------------------------
/others/Python3/1154.Day of the Year.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1154. Day of the Year
3 | @Tag: math
4 | @Date: Jan-22 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import calendar
11 |
12 |
13 | class Solution:
14 | def dayOfYear(self, date: str) -> int:
15 | month_days, leap_month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [
16 | 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
17 | year, month, day = int(date[:4]), int(date[5:7]), int(date[8:10])
18 | return sum(leap_month_days[:month - 1]) + day if calendar.isleap(year) else sum(month_days[:month - 1]) + day
19 |
20 |
21 | """
22 | Runtime: 32 ms, faster than 24.55% of Python3 online submissions for Day of the Year.
23 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Day of the Year.
24 | """
25 |
--------------------------------------------------------------------------------
/others/Python3/1160.Find Words That Can Be Formed by Characters.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1160. Find Words That Can Be Formed by Characters
3 | @Tag: string
4 | @Date: Jan-28 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import collections
11 |
12 |
13 | class Solution:
14 | def countCharacters(self, words: List[str], chars: str) -> int:
15 | res = 0
16 | for word in words:
17 | if all(collections.Counter(word)[ch] <= collections.Counter(chars)[ch] for ch in word):
18 | res += len(word)
19 | return res
20 |
21 |
22 | """
23 | To form a string using characters from chars, the frequency of each character in chars must be greater than or equal the frequency of that character in the string to be formed.
24 | """
25 |
26 |
27 | """
28 | Python all() Function
29 | The all() function returns True if all items in an iterable are true, otherwise it returns False. If the iterable object is empty, the all() function also returns True.
30 | """
31 |
--------------------------------------------------------------------------------
/others/Python3/118.Pascal's Triangle.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 118. Pascal's Triangle
3 | @Tag: dp
4 | @Date: Dec-31 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def generate(self, numRows: int) -> List[List[int]]:
12 | # memorization (set default as one)
13 | dp = [[1 for j in range(i+1)] for i in range(numRows)]
14 | for row in range(2, numRows): # start from the row[2]
15 | for col in range(1, row):
16 | dp[row][col] = dp[row-1][col-1]+dp[row-1][col]
17 | return dp
18 |
19 |
20 | """
21 | Runtime: 28 ms, faster than 81.27% of Python3 online submissions for Pascal's Triangle.
22 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Pascal's Triangle.
23 | """
24 |
25 |
26 | """
27 | Time Complexity: O(m*n)
28 | Space Complexity: O(m*n)
29 | """
30 |
--------------------------------------------------------------------------------
/others/Python3/1184.Distance Between Bus Stops.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1184. Distance Between Bus Stops
3 | @Tag: array
4 | @Date: Jan-24 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
12 | start, destination = min(start, destination), max(
13 | start, destination) # redefine
14 | distance *= 2 # cycle
15 | return min(sum(distance[start: destination]), sum(distance[destination: start + len(distance) // 2]))
16 |
17 |
18 | """
19 | Time Complexity: O(n)
20 | Space Complexity: O(n)
21 | """
22 |
--------------------------------------------------------------------------------
/others/Python3/1185.Day of the Week.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1185. Day of the Week
3 | @Tag:
4 | @Date: Feb-06 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import datetime
11 |
12 |
13 | class Solution:
14 | def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
15 | return datetime.date(year, month, day).strftime("%A")
16 |
17 |
18 | """
19 | Runtime: 24 ms, faster than 85.23% of Python3 online submissions for Day of the Week.
20 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Day of the Week.
21 | """
22 |
--------------------------------------------------------------------------------
/others/Python3/1189.Maximum Number of Balloons.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1189. Maximum Number of Balloons
3 | @Tag: dict
4 | @Date: Oct-22 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def maxNumberOfBalloons(self, text: str) -> int:
12 | aim='balon'
13 | # dict.fromkeys() is a classmethod as well as the initialization of dict
14 | # d={'b','a','l','o','n'}
15 | d=dict.fromkeys(aim,0)
16 | for i in text:
17 | if i in d:
18 | d[i]=d[i]+1
19 | d['l']=int(d['l']/2) # 'l' appears twice
20 | d['o']=int(d['o']/2) # 'o' appears twice
21 | return min(d.values())
22 |
23 |
24 | def main():
25 | s=Solution()
26 | print(s.maxNumberOfBalloons("loonbalxballpoon"))
27 |
28 |
29 | if __name__ == "__main__":
30 | main()
31 |
--------------------------------------------------------------------------------
/others/Python3/1200.Minimum Absolute Difference.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1200. Minimum Absolute Difference
3 | @Tag: list
4 | @Date: Oct-23 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | from typing import List
11 | class Solution:
12 | def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
13 | res=[]
14 | arr=sorted(arr)
15 | temp=arr[1]-arr[0]
16 | for i in range(1,len(arr)-1):
17 | temp=min(arr[i+1]-arr[i],temp)
18 | for i in range(len(arr)-1):
19 | if arr[i+1]-arr[i]==temp:
20 | res.append([arr[i],arr[i+1]])
21 | return res
22 |
23 |
24 | def main():
25 | s=Solution()
26 | print(s.minimumAbsDifference([3,8,-10,23,19,-4,-14,27]))
27 |
28 |
29 | if __name__ == "__main__":
30 | main()
31 |
32 |
33 | """
34 | Runtime: 444 ms, faster than 30.95% of Python3 online submissions for Minimum Absolute Difference.
35 | Memory Usage: 28 MB, less than 100.00% of Python3 online submissions for Minimum Absolute Difference.
36 | """
--------------------------------------------------------------------------------
/others/Python3/1207.Unique Number of Occurrences.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1207. Unique Number of Occurrences
3 | @Tag: dict
4 | @Date: Nov-11 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def uniqueOccurrences(self, arr: List[int]) -> bool:
12 | res = []
13 | d = {item: {'occurrence': 0} for item in arr} # dict
14 | for c in arr:
15 | d[c]['occurrence'] += 1
16 | for c in d:
17 | res.append(d[c]['occurrence'])
18 | return len(set(res)) == len(res)
19 |
20 |
21 | """
22 | Runtime: 36 ms, faster than 95.70% of Python3 online submissions for Unique Number of Occurrences.
23 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Unique Number of Occurrences.
24 | """
25 |
--------------------------------------------------------------------------------
/others/Python3/121.Best Time to Buy and Sell Stock.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 121. Best Time to Buy and Sell Stock
3 | @Tag: stack
4 | @Date: Dec-17 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def maxProfit(self, prices: List[int]) -> int:
12 | # corner case
13 | if not prices:
14 | return 0
15 | stack = [prices[0]] # initialization
16 | profit = 0
17 | for i in range(1, len(prices)):
18 | if prices[i] < stack[-1]: # always the min element
19 | stack.pop()
20 | stack.append(prices[i])
21 | # find the maximum profit
22 | profit = max(prices[i]-stack[-1], profit)
23 | return profit
24 |
25 |
26 | """
27 | Runtime: 68 ms, faster than 71.83% of Python3 online submissions for Best Time to Buy and Sell Stock.
28 | Memory Usage: 13.8 MB, less than 98.85% of Python3 online submissions for Best Time to Buy and Sell Stock.
29 | """
30 |
--------------------------------------------------------------------------------
/others/Python3/1217.Play with Chips.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1217. Play with Chips
3 | @Tag: array
4 | @Date: Feb-05 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def minCostToMoveChips(self, index: List[int]) -> int:
12 | odd, even = 0, 0
13 | for i in index:
14 | if i % 2 == 0:
15 | even += 1
16 | else:
17 | odd += 1
18 | return min(odd, even)
19 |
20 |
21 | """
22 | Runtime: 24 ms, faster than 95.04% of Python3 online submissions for Play with Chips.
23 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Play with Chips.
24 | """
25 |
26 |
27 | """
28 | Time Complexity: O(n)
29 | Space Complexity: O(1)
30 | """
31 |
--------------------------------------------------------------------------------
/others/Python3/122.Best Time to Buy and Sell Stock II.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 122. Best Time to Buy and Sell Stock II
3 | @Tag:
4 | @Date: Dec-18 2019
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def maxProfit(self, prices: List[int]) -> int:
12 | profit = 0
13 | # no corner case
14 | for i in range(len(prices)-1): # for loop
15 | # benefit of each transaction in order to get the maximum profit
16 | if prices[i+1]-prices[i] > 0: # benefit
17 | profit += prices[i+1]-prices[i] # accumulation
18 | return profit
19 |
20 |
21 | """
22 | Runtime: 60 ms, faster than 91.03% of Python3 online submissions for Best Time to Buy and Sell Stock II.
23 | Memory Usage: 13.8 MB, less than 87.81% of Python3 online submissions for Best Time to Buy and Sell Stock II.
24 | """
25 |
--------------------------------------------------------------------------------
/others/Python3/1221.Split a String in Balanced Strings.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1221. Split a String in Balanced Strings
3 | @Tag: string
4 | @Date: Jan-26 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def balancedStringSplit(self, s: str) -> int:
12 | count, res = 0, 0
13 | for ch in s:
14 | count += 1 if ch == "L" else -1
15 | if count == 0:
16 | res += 1
17 | return res
18 |
19 |
20 | """
21 | Runtime: 28 ms, faster than 67.62% of Python3 online submissions for Split a String in Balanced Strings.
22 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Split a String in Balanced Strings.
23 | """
24 |
--------------------------------------------------------------------------------
/others/Python3/1232.Check If It Is a Straight Line.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1232. Check If It Is a Straight Line
3 | @Tag: math
4 | @Date: Nov-04 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 | from typing import List
10 |
11 |
12 | class Solution:
13 | def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
14 | slope = []
15 | for i in range(len(coordinates)-1):
16 | # if denominator == 0 -> ZeroDivisionError
17 | if coordinates[i+1][0]-coordinates[i][0] == 0:
18 | return False
19 | slope.append(
20 | (coordinates[i+1][1]-coordinates[i][1])/(coordinates[i+1][0]-coordinates[i][0]))
21 | return slope[1:] == slope[:-1] # all equal
22 |
23 |
24 | def test():
25 | s = Solution()
26 | print(s.checkStraightLine(
27 | [[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]]))
28 | print(s.checkStraightLine(
29 | [[1, 1], [2, 2], [3, 4], [4, 5], [5, 6], [7, 7]]))
30 |
31 |
32 | if __name__ == "__main__":
33 | test()
34 |
--------------------------------------------------------------------------------
/others/Python3/1252.Cells with Odd Values in a Matrix.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1252. Cells with Odd Values in a Matrix
3 | @Tag: array
4 | @Date: Jan-31 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def oddCells(self, n: int, m: int, indices: List[List[int]]) -> int:
12 | rows, cols, res = [0] * n, [0] * m, 0 # initialization
13 | for i, j in indices:
14 | rows[i], cols[j] = rows[i] ^ 1, cols[j] ^ 1 # 0 -> even, 1 -> odd
15 | for i in range(n):
16 | for j in range(m):
17 | res += 1 if rows[i] ^ cols[j] == 1 else 0
18 | return res
19 |
20 |
21 | """
22 | Runtime: 60 ms, faster than 26.87% of Python3 online submissions for Cells with Odd Values in a Matrix.
23 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Cells with Odd Values in a Matrix.
24 | """
25 |
26 |
27 | """
28 | Time Complexity: O(n^2)
29 | Space Complexity: O(n)
30 | """
31 |
--------------------------------------------------------------------------------
/others/Python3/1260.Shift 2D Grid.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1260. Shift 2D Grid
3 | @Tag: array
4 | @Date: Feb-01 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
12 | rows, cols = len(grid), len(grid[0]),
13 | temp, res = [], [0] * (rows * cols)
14 | for i in range(rows): # 2D -> 1D
15 | for j in range(cols):
16 | temp.append(grid[i][j])
17 | for i in range(len(res)): # shifting
18 | res[(i + k) % (rows * cols)] = temp[i]
19 | for i in range(rows): # 1D -> 2D
20 | for j in range(cols):
21 | grid[i][j] = res[i * cols + j]
22 | return grid
23 |
24 |
25 | """
26 | Runtime: 184 ms, faster than 43.64% of Python3 online submissions for Shift 2D Grid.
27 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Shift 2D Grid.
28 | """
29 |
30 |
31 | """
32 | Time Complexity: O(m*n)
33 | Space Complexity: O(m*n)
34 | """
35 |
--------------------------------------------------------------------------------
/others/Python3/1266.Minimum Time Visiting All Points.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1266. Minimum Time Visiting All Points
3 | @Tag: math
4 | @Date: Jan-23 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def minTimeToVisitAllPoints(self, points: List[List[int]]) -> int:
12 | res, hor, ver = 0, [h[0] for h in points], [v[1]
13 | for v in points] # horizontal & vertical
14 | for k in range(len(hor) - 1):
15 | # kinda like Manhattan distance
16 | res += max(abs(hor[k+1] - hor[k]), abs(ver[k+1] - ver[k]))
17 | return res
18 |
19 |
20 | """
21 | Runtime: 76 ms, faster than 11.34% of Python3 online submissions for Minimum Time Visiting All Points.
22 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Minimum Time Visiting All Points.
23 | """
24 |
--------------------------------------------------------------------------------
/others/Python3/1281.Subtract the Product and Sum of Digits of an Integer.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1281. Subtract the Product and Sum of Digits of an Integer
3 | @Tag:
4 | @Date: Jan-12 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def subtractProductAndSum(self, n: int) -> int:
12 | res = []
13 | while n > 0:
14 | res.append(n % 10)
15 | n //= 10
16 | # math.prod() is available in Python 3.8
17 | return math.prod(res) - sum(res)
18 |
19 |
20 | """
21 | Runtime: 24 ms, faster than 83.24% of Python3 online submissions for Subtract the Product and Sum of Digits of an Integer.
22 | Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Subtract the Product and Sum of Digits of an Integer.
23 | """
24 |
--------------------------------------------------------------------------------
/others/Python3/1287.Element Appearing More Than 25% In Sorted Array.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1287. Element Appearing More Than 25% In Sorted Array
3 | @Tag: array
4 | @Date: Jan-26 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import collections
11 |
12 |
13 | class Solution:
14 | def findSpecialInteger(self, arr: List[int]) -> int:
15 | return collections.Counter(arr).most_common(1)[0][0]
16 |
17 |
18 | """
19 | Runtime: 104 ms, faster than 21.14% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array.
20 | Memory Usage: 14.1 MB, less than 100.00% of Python3 online submissions for Element Appearing More Than 25% In Sorted Array.
21 | """
22 |
--------------------------------------------------------------------------------
/others/Python3/1295.Find Numbers with Even Number of Digits.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1295. Find Numbers with Even Number of Digits
3 | @Tag: array
4 | @Date: Jan-02 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def findNumbers(self, nums: List[int]) -> int:
12 | res = 0
13 | for i in range(len(nums)):
14 | digit = 0 # the digit of each number
15 | while nums[i] > 0:
16 | nums[i] = nums[i] // 10
17 | digit += 1
18 | if digit % 2 == 0: # even number of digit
19 | res += 1
20 | return res
21 |
22 |
23 | """
24 | Runtime: 52 ms, faster than 72.51% of Python3 online submissions for Find Numbers with Even Number of Digits.
25 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Find Numbers with Even Number of Digits.
26 | """
27 |
28 |
29 | """
30 | Time Complexity: O(n)
31 | Space Complexity: O(1)
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/1304.Find N Unique Integers Sum up to Zero.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1304. Find N Unique Integers Sum up to Zero
3 | @Tag: array
4 | @Date: Jan-01 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def sumZero(self, n: int) -> List[int]:
12 | res = []
13 | if n % 2 != 0: # n is odd
14 | res.append(0)
15 | for i in range(1, (n//2)+1):
16 | res.append(i)
17 | res.append(-i)
18 | else: # n is even
19 | for j in range(1, (n//2)+1):
20 | res.append(j)
21 | res.append(-j)
22 | return res
23 |
24 |
25 | """
26 | Runtime: 32 ms, faster than 58.15% of Python3 online submissions for Find N Unique Integers Sum up to Zero.
27 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Find N Unique Integers Sum up to Zero.
28 | """
29 |
30 |
31 | """
32 | Time Complexity: O(n)
33 | Space Complexity: O(n)
34 | """
35 |
--------------------------------------------------------------------------------
/others/Python3/1306.Jump Game III.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1306. Jump Game III
3 | @Tag: recursion
4 | @Date: Feb-14 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def canReach(self, A: List[int], i: int) -> bool:
12 | if (0 <= i < len(A)) and A[i] >= 0:
13 | if A[i] == 0:
14 | return True
15 | A[i] = -A[i] # have seen before
16 | # either
17 | return self.canReach(A, i + A[i]) or self.canReach(A, i - A[i])
18 | return False
19 |
20 |
21 | """
22 | Runtime: 248 ms, faster than 45.58% of Python3 online submissions for Jump Game III.
23 | Memory Usage: 19.2 MB, less than 100.00% of Python3 online submissions for Jump Game III.
24 | """
25 |
26 |
27 | """
28 | Time Complexity: O(n)
29 | Space Complexity: O(n)
30 | """
31 |
--------------------------------------------------------------------------------
/others/Python3/1313.Decompress Run-Length Encoded List.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1313. Decompress Run-Length Encoded List
3 | @Tag: array
4 | @Date: Feb-06 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def decompressRLElist(self, nums: List[int]) -> List[int]:
12 | res, n = [], len(nums)
13 | for i in range(1, n, 2):
14 | temp = [nums[i]] * nums[i-1]
15 | res.extend(temp)
16 | return res
17 |
18 |
19 | """
20 | Runtime: 68 ms, faster than 71.87% of Python3 online submissions for Decompress Run-Length Encoded List.
21 | Memory Usage: 13 MB, less than 100.00% of Python3 online submissions for Decompress Run-Length Encoded List.
22 | """
23 |
24 |
25 | """
26 | Time Complexity: O(n)
27 | Space Complexity: O(1)
28 | """
29 |
--------------------------------------------------------------------------------
/others/Python3/1317.Convert Integer to the Sum of Two No-Zero Integers.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1317. Convert Integer to the Sum of Two No-Zero Integers
3 | @Tag: math
4 | @Date: Feb-04 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def getNoZeroIntegers(self, n: int) -> List[int]:
12 | for i in range(1, n): # loop through all elements from 1 to n
13 | if self.check(i) and self.check(n - i):
14 | return [i, n - i]
15 |
16 | def check(self, n: int) -> bool: # check if n is No-Zero integer
17 | while n > 0:
18 | if n % 10 == 0:
19 | return False
20 | n //= 10
21 | return True
22 |
23 |
24 | """
25 | Runtime: 40 ms, faster than 9.04% of Python3 online submissions for Convert Integer to the Sum of Two No-Zero Integers.
26 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Convert Integer to the Sum of Two No-Zero Integers.
27 | """
28 |
--------------------------------------------------------------------------------
/others/Python3/1324.Print Words Vertically.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1324. Print Words Vertically
3 | @Tag: string
4 | @Date: Feb-14 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def printVertically(self, s: str) -> List[str]:
12 | s = s.split(" ")
13 | n = max([len(w) for w in s])
14 | res = [""] * n
15 | for i in range(n):
16 | for word in s:
17 | res[i] += word[i] if i < len(word) else " "
18 | res[i] = res[i].rstrip() # remove trailing spaces
19 | return res
20 |
21 |
22 | """
23 | Runtime: 20 ms, faster than 97.48% of Python3 online submissions for Print Words Vertically.
24 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Print Words Vertically.
25 | """
26 |
--------------------------------------------------------------------------------
/others/Python3/1328.Break a Palindrome.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1328. Break a Palindrome
3 | @Tag: string
4 | @Date: Feb-12 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def breakPalindrome(self, p: str) -> str:
12 | if len(p) == 1: # corner case
13 | return ""
14 | p = list(p) # convert to list in order to modify
15 | for i, ch in enumerate(p):
16 | if ch != 'a' and i != len(p) // 2: # e.g: "aba"
17 | p[i] = 'a' # modify
18 | break
19 | if i == len(p) - 1: # the last element
20 | p[i] = 'b' # e.g: "aaa"
21 | return "".join(p)
22 |
23 |
24 | """
25 | Runtime: 24 ms, faster than 90.00% of Python3 online submissions for Break a Palindrome.
26 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Break a Palindrome.
27 | """
28 |
29 |
30 | """
31 | Time Complexity: O(n)
32 | Space Complexity: O(1)
33 | """
34 |
--------------------------------------------------------------------------------
/others/Python3/1331.Rank Transform of an Array.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1331. Rank Transform of an Array
3 | @Tag: array
4 | @Date: Feb-01 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def arrayRankTransform(self, arr: List[int]) -> List[int]:
12 | num_rank = {} # easy to add "key-value"
13 | for num in sorted(arr):
14 | if num not in num_rank: # avoid duplicate element
15 | num_rank[num] = len(num_rank) + 1 # starting from 1
16 | return [num_rank[num] for num in arr] # return List[int]
17 |
18 |
19 | """
20 | Runtime: 384 ms, faster than 75.10% of Python3 online submissions for Rank Transform of an Array.
21 | Memory Usage: 30.6 MB, less than 100.00% of Python3 online submissions for Rank Transform of an Array.
22 | """
23 |
24 |
25 | """
26 | Time Complexity: O(nlogn)
27 | Space Complexity: O(n)
28 | """
29 |
--------------------------------------------------------------------------------
/others/Python3/1337.The K Weakest Rows in a Matrix.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1337. The K Weakest Rows in a Matrix
3 | @Tag: array
4 | @Date: Feb-04 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | # Version one:
11 |
12 |
13 | class Solution:
14 | def kWeakestRows(self, M: List[List[int]], k: int) -> List[int]:
15 | S = [[sum(m), i] for i, m in enumerate(M)] # S -> [[soldiers, index]]
16 | S = sorted(S) # weakest -> strongest
17 | # "s[1]" -> index, "[:k]" -> the first k rows
18 | return [s[1] for s in S][:k]
19 |
20 |
21 | # Version two(1-line):
22 |
23 |
24 | class Solution:
25 | def kWeakestRows(self, M: List[List[int]], k: int) -> List[int]:
26 | return [s[1] for s in sorted([[sum(m), i] for i, m in enumerate(M)])][:k]
27 |
28 |
29 | """
30 | Runtime: 108 ms, faster than 92.47% of Python3 online submissions for The K Weakest Rows in a Matrix.
31 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for The K Weakest Rows in a Matrix.
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/1338.Reduce Array Size to The Half.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1338. Reduce Array Size to The Half
3 | @Tag: array
4 | @Date: Feb-11 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | import collections
11 |
12 |
13 | class Solution:
14 | def minSetSize(self, A: List[int]) -> int:
15 | res, temp, n = 0, 0, len(A) / 2
16 | for a, freq in collections.Counter(A).most_common():
17 | temp += freq # the number of the elements which should be removed
18 | res += 1
19 | if temp >= n: # at least half of the integers of the array are removed
20 | return res
21 | return res
22 |
23 |
24 | """
25 | Runtime: 616 ms, faster than 85.79% of Python3 online submissions for Reduce Array Size to The Half.
26 | Memory Usage: 34.3 MB, less than 100.00% of Python3 online submissions for Reduce Array Size to The Half.
27 | """
28 |
29 |
30 | """
31 | Time Complexity: O(n)
32 | Space Complexity: O(1)
33 | """
34 |
--------------------------------------------------------------------------------
/others/Python3/1342.Number of Steps to Reduce a Number to Zero.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1342. Number of Steps to Reduce a Number to Zero
3 | @Tag: bit manipulation
4 | @Date: Feb-09 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def numberOfSteps(self, num: int) -> int:
12 | res = 0
13 | while num:
14 | if num % 2 == 0:
15 | num //= 2
16 | else:
17 | num -= 1
18 | res += 1
19 | return res
20 |
21 |
22 | """
23 | Runtime: 28 ms, faster than 66.67% of Python3 online submissions for Number of Steps to Reduce a Number to Zero.
24 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Number of Steps to Reduce a Number to Zero.
25 | """
26 |
--------------------------------------------------------------------------------
/others/Python3/1344.Angle Between Hands of a Clock.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1344. Angle Between Hands of a Clock
3 | @Tag: math
4 | @Date: Feb-10 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def angleClock(self, h: int, m: int) -> float:
12 | # "m / 60 * 5" means how the minute hand affects the position of the hour hand
13 | h = 0 + m / 60 * 5 if h == 12 else h * 5 + m / 60 * 5 # convert hrs to mins
14 | return min(abs(m - h) * 6, 360 - abs(m - h) * 6) # the smaller one
15 |
16 |
17 | """
18 | Runtime: 32 ms, faster than 22.88% of Python3 online submissions for Angle Between Hands of a Clock.
19 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Angle Between Hands of a Clock.
20 | """
21 |
--------------------------------------------------------------------------------
/others/Python3/1346.Check If N and Its Double Exist.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1346. Check If N and Its Double Exist
3 | @Tag: array
4 | @Date: Feb-09 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def checkIfExist(self, arr: List[int]) -> bool:
12 | if arr.count(0) >= 2: # corner case
13 | return True
14 | for a in set(sorted(arr)):
15 | if a < 0: # negative
16 | if a / 2 in arr:
17 | return True
18 | if a > 0: # positive
19 | if a * 2 in arr:
20 | return True
21 | return False
22 |
23 |
24 | """
25 | Time Complexity: O(n)
26 | Space Complexity: O(1)
27 | """
28 |
--------------------------------------------------------------------------------
/others/Python3/1347.Minimum Number of Steps to Make Two Strings Anagram.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1347. Minimum Number of Steps to Make Two Strings Anagram
3 | @Tag: string
4 | @Date: Feb-09 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def minSteps(self, s: str, t: str) -> int:
12 | res, freq = 0, [0] * 26 # lower-case English letters only
13 | for ch in s:
14 | freq[ord(ch) - ord('a')] += 1
15 | for ch in t:
16 | freq[ord(ch) - ord('a')] -= 1
17 | if freq[ord(ch) - ord('a')] < 0:
18 | res += 1
19 | return res
20 |
21 |
22 | """
23 | Time Complexity: O(n)
24 | Space Complexity: O(1)
25 | """
26 |
--------------------------------------------------------------------------------
/others/Python3/1351.Count Negative Numbers in a Sorted Matrix.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1351. Count Negative Numbers in a Sorted Matrix
3 | @Tag: array
4 | @Date: Feb-16 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def countNegatives(self, G: List[List[int]]) -> int:
12 | row, col, res = len(G), len(G[0]), 0
13 | for i in range(row):
14 | for j in range(col):
15 | if G[i][j] < 0:
16 | res += 1
17 | return res
18 |
19 |
20 | """
21 | Time Complexity: O(n^2)
22 | Space Complexity: O(1)
23 | """
24 |
--------------------------------------------------------------------------------
/others/Python3/1360.Number of Days Between Two Dates.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1360. Number of Days Between Two Dates
3 | @Tag:
4 | @Date: Feb-23 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | from datetime import datetime
11 |
12 |
13 | class Solution:
14 | def daysBetweenDates(self, date1: str, date2: str) -> int:
15 | date_format = "%Y-%m-%d"
16 | a = datetime.strptime(date1, date_format)
17 | b = datetime.strptime(date2, date_format)
18 | return abs((b - a).days)
19 |
20 |
21 | """
22 | Runtime: 32 ms, faster than 100.00% of Python3 online submissions for Number of Days Between Two Dates.
23 | Memory Usage: 13 MB, less than 100.00% of Python3 online submissions for Number of Days Between Two Dates.
24 | """
25 |
--------------------------------------------------------------------------------
/others/Python3/1389.Create Target Array in the Given Order.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1389. Create Target Array in the Given Order
3 | @Tag: array
4 | @Date: Mar-22 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
12 | res = []
13 | for i, v in zip(index, nums):
14 | res.insert(i, v)
15 | return res
16 |
17 |
18 | """
19 | Time Complexity: O(n)
20 | Space Complexity: O(1)
21 | """
22 |
--------------------------------------------------------------------------------
/others/Python3/1390.Four Divisors.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 1390. Four Divisors
3 | @Tag: math
4 | @Date: Mar-22 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | import math
11 |
12 |
13 | class Solution:
14 | def sumFourDivisors(self, nums: List[int]) -> int:
15 | res = 0
16 | for n in nums:
17 | temp = []
18 | for i in range(1, int(math.sqrt(n)) + 1): # find all the divisors
19 | if n % i == 0:
20 | temp.extend([i, n // i])
21 | if len(temp) > 4: # accelerate the process
22 | break
23 | if len(temp) == 4 and len(temp) == len(set(temp)): # check whether unique divisors
24 | res += sum(temp)
25 | return res
26 |
27 |
28 | """
29 | Time Complexity: O(n^2)
30 | Space Complexity: O(n)
31 | """
32 |
--------------------------------------------------------------------------------
/others/Python3/141.Linked List Cycle.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 141. Linked List Cycle
3 | @Tag: linked list
4 | @Date: Jan-08 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | # Definition for singly-linked list.
11 | # class ListNode:
12 | # def __init__(self, x):
13 | # self.val = x
14 | # self.next = None
15 |
16 |
17 | class Solution:
18 | def hasCycle(self, head: ListNode) -> bool:
19 | cur = head
20 | while cur:
21 | if cur.val == None:
22 | return True
23 | else:
24 | cur.val = None
25 | cur = cur.next
26 | return False
27 |
28 |
29 | """
30 | Runtime: 48 ms, faster than 63.49% of Python3 online submissions for Linked List Cycle.
31 | Memory Usage: 15.7 MB, less than 100.00% of Python3 online submissions for Linked List Cycle.
32 | """
33 |
34 |
35 | """
36 | Time Complexity: O(n)
37 | Space Complexity: O(1)
38 | """
39 |
--------------------------------------------------------------------------------
/others/Python3/148.Sort List.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 148. Sort List
3 | @Tag: linked-list / sort
4 | @Date: Feb-22 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | # Definition for singly-linked list.
11 | class ListNode:
12 | def __init__(self, x):
13 | self.val = x
14 | self.next = None
15 |
16 |
17 | class Solution:
18 | def sortList(self, head: ListNode) -> ListNode:
19 | cur, res = head, []
20 | while cur:
21 | res.append(cur.val)
22 | cur = cur.next
23 | res, cur = sorted(res), head
24 | while cur:
25 | cur.val = res.pop(0)
26 | cur = cur.next
27 | return head
28 |
29 |
30 | """
31 | Runtime: 160 ms, faster than 85.63% of Python3 online submissions for Sort List.
32 | Memory Usage: 20.1 MB, less than 100.00% of Python3 online submissions for Sort List.
33 | """
34 |
35 |
36 | """
37 | Time Complexity: O(nlogn)
38 | Space Complexity: O(n)
39 | """
40 |
--------------------------------------------------------------------------------
/others/Python3/151.Reverse Words in a String.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 151. Reverse Words in a String
3 | @Tag: string
4 | @Date: Feb-29 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def reverseWords(self, s: str) -> str:
12 | return " ".join(s.split()[::-1])
13 |
14 |
15 | """
16 | Runtime: 24 ms, faster than 90.00% of Python3 online submissions for Reverse Words in a String.
17 | Memory Usage: 13.2 MB, less than 100.00% of Python3 online submissions for Reverse Words in a String.
18 | """
19 |
20 |
21 | """
22 | Time Complexity: O(n)
23 | Space Complexity: O(1)
24 | """
25 |
--------------------------------------------------------------------------------
/others/Python3/162.Find Peak Element.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 162. Find Peak Element
3 | @Tag: array / binary search
4 | @Date: Jan-22 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def findPeakElement(self, nums: List[int]) -> int:
12 | # nums[-1] = nums[n] = -∞
13 | nums.insert(0, float("-inf"))
14 | nums.insert(len(nums), float("-inf"))
15 | for i in range(1, len(nums) - 1): # linear scan
16 | if nums[i] > nums[i-1] and nums[i] > nums[i+1]:
17 | return i - 1
18 |
19 |
20 | """
21 | Runtime: 64 ms, faster than 7.76% of Python3 online submissions for Find Peak Element.
22 | Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Find Peak Element.
23 | """
24 |
25 |
26 | """
27 | Time Complexity: O(n)
28 | Space Complexity: O(1)
29 | """
30 |
--------------------------------------------------------------------------------
/others/Python3/168.Excel Sheet Column Title.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 168. Excel Sheet Column Title
3 | @Tag: math / string
4 | @Date: Feb-03 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def convertToTitle(self, n: int) -> str:
12 | res = ""
13 | while n > 0:
14 | n -= 1 # 26 -> "Z"
15 | res += chr(n % 26 + ord('A'))
16 | n //= 26
17 | return res[::-1]
18 |
19 |
20 | """
21 | Runtime: 20 ms, faster than 96.45% of Python3 online submissions for Excel Sheet Column Title.
22 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Excel Sheet Column Title.
23 | """
24 |
25 |
26 | """
27 | Time Complexity: O(n)
28 | Space Complexity: O(1)
29 | """
30 |
--------------------------------------------------------------------------------
/others/Python3/169.Majority Element.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 169. Majority Element
3 | @Tag: hashtable
4 | @Date: Mar-04 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import collections as c
11 |
12 |
13 | class Solution:
14 | def majorityElement(self, A: List[int]) -> int:
15 | d = c.defaultdict(int)
16 | for a in A:
17 | d[a] += 1
18 | if d[a] > len(A) // 2:
19 | return a
20 |
21 |
22 | """
23 | Runtime: 192 ms, faster than 28.49% of Python3 online submissions for Majority Element.
24 | Memory Usage: 13.9 MB, less than 100.00% of Python3 online submissions for Majority Element.
25 | """
26 |
27 |
28 | """
29 | Time Complexity: O(n)
30 | Space Complexity: O(n)
31 | """
32 |
--------------------------------------------------------------------------------
/others/Python3/171.Excel Sheet Column Number.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 171. Excel Sheet Column Number
3 | @Tag: math / bit
4 | @Date: Jan-21 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def titleToNumber(self, s: str) -> int:
12 | length, res = len(s), 0
13 | for ch in s:
14 | length -= 1
15 | res += (ord(ch) - ord('A') + 1) * 26 ** length # 26-based
16 | return res
17 |
18 |
19 | """
20 | Runtime: 28 ms, faster than 79.39% of Python3 online submissions for Excel Sheet Column Number.
21 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Excel Sheet Column Number.
22 | """
23 |
24 |
25 | """
26 | Time Complexity: O(n)
27 | Space Complexity: O(1)
28 | """
29 |
--------------------------------------------------------------------------------
/others/Python3/189.Rotate Array.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 189. Rotate Array
3 | @Tag: array
4 | @Date: Jan-01 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def rotate(self, nums: List[int], k: int) -> None:
12 | """
13 | Do not return anything, modify nums in-place instead.
14 | """
15 | new_nums = nums.copy() # a copy of nums, which means we create an extra space
16 | for i in range(len(nums)-1, -1, -1): # reverse order
17 | nums[(i+k) % len(nums)] = new_nums[i] # modify in-place
18 |
19 |
20 | """
21 | Runtime: 64 ms, faster than 75.63% of Python3 online submissions for Rotate Array.
22 | Memory Usage: 14.1 MB, less than 5.09% of Python3 online submissions for Rotate Array.
23 | """
24 |
25 |
26 | """
27 | Time Complexity: O(n)
28 | Space Complexity: O(n)
29 | """
30 |
--------------------------------------------------------------------------------
/others/Python3/206.Reverse Linked List.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 206. Reverse Linked List
3 | @Tag: linked list
4 | @Date: Jan-06 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | # Definition for singly-linked list.
11 | # class ListNode:
12 | # def __init__(self, x):
13 | # self.val = x
14 | # self.next = None
15 |
16 |
17 | class Solution:
18 | def reverseList(self, head: ListNode) -> ListNode: # a utility problem
19 | pre = None # previous node
20 | cur = head # current node
21 | while cur: # iteratively
22 | nxt = cur.next # save the next node
23 | cur.next = pre # reverse
24 | # go ahead
25 | pre = cur
26 | cur = nxt
27 | return pre
28 |
29 |
30 | """
31 | Runtime: 36 ms, faster than 46.08% of Python3 online submissions for Reverse Linked List.
32 | Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Reverse Linked List.
33 | """
34 |
35 |
36 | """
37 | Time Complexity: O(n)
38 | Space Complexity: O(1)
39 | """
40 |
--------------------------------------------------------------------------------
/others/Python3/209.Minimum Size Subarray Sum.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 209. Minimum Size Subarray Sum
3 | @Tag: sliding window
4 | @Date: Feb-24 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def minSubArrayLen(self, s: int, A: List[int]) -> int:
12 | res, left, temp = float("inf"), 0, 0
13 | for i, a in enumerate(A):
14 | temp += a
15 | while temp >= s:
16 | res = min(res, i - left + 1) # update the value first
17 | temp -= A[left]
18 | left += 1 # move the left boundary
19 | return res if res != float("inf") else 0
20 |
21 |
22 | """
23 | Runtime: 72 ms, faster than 88.72% of Python3 online submissions for Minimum Size Subarray Sum.
24 | Memory Usage: 15.2 MB, less than 7.69% of Python3 online submissions for Minimum Size Subarray Sum.
25 | """
26 |
27 |
28 | """
29 | Time Complexity: O(n)
30 | Space Complexity: O(1)
31 | """
32 |
--------------------------------------------------------------------------------
/others/Python3/217.Contains Duplicate.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 217. Contains Duplicate
3 | @Tag: array / hashtable
4 | @Date: Feb-22 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import collections
11 |
12 |
13 | class Solution:
14 | def containsDuplicate(self, A: List[int]) -> bool:
15 | d = collections.defaultdict(int)
16 | for a in A:
17 | d[a] += 1
18 | if d[a] > 1:
19 | return True
20 | return False
21 |
22 |
23 | """
24 | Runtime: 124 ms, faster than 84.43% of Python3 online submissions for Contains Duplicate.
25 | Memory Usage: 19.1 MB, less than 16.98% of Python3 online submissions for Contains Duplicate.
26 | """
27 |
28 |
29 | """
30 | Time Complexity: O(n)
31 | Space Complexity: O(n)
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/219.Contains Duplicate II.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 219. Contains Duplicate II
3 | @Tag: hashset
4 | @Date: Feb-23 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import collections as c
11 |
12 |
13 | class Solution:
14 | def containsNearbyDuplicate(self, A: List[int], k: int) -> bool:
15 | d, flag = c.defaultdict(int), False # hashset, flag
16 | for i, a in enumerate(A):
17 | if a in d: # appeared more than once
18 | if i - d[a] <= k:
19 | flag = True
20 | d[a] = i # value: position
21 | return flag
22 |
23 |
24 | """
25 | Runtime: 96 ms, faster than 64.19% of Python3 online submissions for Contains Duplicate II.
26 | Memory Usage: 20.3 MB, less than 68.75% of Python3 online submissions for Contains Duplicate II.
27 | """
28 |
29 |
30 | """
31 | Time Complexity: O(n)
32 | Space Complexity: O(n)
33 | """
34 |
--------------------------------------------------------------------------------
/others/Python3/223.Rectangle Area.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 223. Rectangle Area
3 | @Tag: math
4 | @Date: Jan-15 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | class Solution:
11 | def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
12 | width, height = min(C, G) - max(A, E), min(D, H) - max(B, F)
13 | overlap = height * width if (height > 0 and width > 0) else 0
14 | return (C - A) * (D - B) + (G - E) * (H - F) - overlap
15 |
16 |
17 | """
18 | Runtime: 44 ms, faster than 90.49% of Python3 online submissions for Rectangle Area.
19 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Rectangle Area.
20 | """
21 |
--------------------------------------------------------------------------------
/others/Python3/234.Palindrome Linked List.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 234. Palindrome Linked List
3 | @Tag: linked list
4 | @Date: Jan-09 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | # Definition for singly-linked list.
11 | # class ListNode:
12 | # def __init__(self, x):
13 | # self.val = x
14 | # self.next = None
15 |
16 |
17 | class Solution:
18 | def isPalindrome(self, head: ListNode) -> bool:
19 | arr, cur = [], head
20 | while cur: # linked list -> array
21 | arr.append(cur.val)
22 | cur = cur.next # go ahead
23 | return arr == arr[::-1]
24 |
25 |
26 | """
27 | Runtime: 68 ms, faster than 73.41% of Python3 online submissions for Palindrome Linked List.
28 | Memory Usage: 22.9 MB, less than 100.00% of Python3 online submissions for Palindrome Linked List.
29 | """
30 |
31 |
32 | """
33 | Time Complexity: O(n)
34 | Space Complexity: O(n)
35 | """
36 |
--------------------------------------------------------------------------------
/others/Python3/242.Valid Anagram.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 242. Valid Anagram
3 | @Tag: str
4 | @Date: Jan-04 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def isAnagram(self, s: str, t: str) -> bool:
12 | freq = [0] * 26 # the frequency of each letters
13 | if len(s) != len(t): # s and t should have the same length
14 | return False
15 | for i in range(len(s)):
16 | freq[ord(s[i])-ord('a')] += 1
17 | freq[ord(t[i])-ord('a')] -= 1
18 | # all the element should be the same -- zero
19 | return len(set(freq)) == 1
20 |
21 |
22 | """
23 | Runtime: 56 ms, faster than 25.61% of Python3 online submissions for Valid Anagram.
24 | Memory Usage: 13.1 MB, less than 96.88% of Python3 online submissions for Valid Anagram.
25 | """
26 |
--------------------------------------------------------------------------------
/others/Python3/290.Word Pattern.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 290. Word Pattern
3 | @Tag: hashtable
4 | @Date: Feb-27 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def wordPattern(self, P: str, S: str) -> bool:
12 | S, d1, d2 = S.split(), {}, {}
13 | if len(P) != len(S):
14 | return False
15 | for p, s in zip(P, S): # bijection (one to one)
16 | if p not in d1 and s not in d2: # both not in
17 | d1[p], d2[s] = s, p
18 | elif p in d1 and s in d2: # both in
19 | if (d1[p], d2[s]) != (s, p):
20 | return False
21 | else: # not a bijection
22 | return False
23 | return True
24 |
25 |
26 | """
27 | Runtime: 24 ms, faster than 86.40% of Python3 online submissions for Word Pattern.
28 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Word Pattern.
29 | """
30 |
31 |
32 | """
33 | Time Complexity: O(n)
34 | Space Complexity: O(n)
35 | """
36 |
--------------------------------------------------------------------------------
/others/Python3/292.Nim Game.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 292. Nim Game
3 | @Tag: brainteaser
4 | @Date: Jan-25 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def canWinNim(self, n: int) -> bool:
12 | return n % 4 != 0
13 |
14 |
15 | """
16 | Runtime: 40 ms, faster than 6.96% of Python3 online submissions for Nim Game.
17 | Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Nim Game.
18 | """
19 |
--------------------------------------------------------------------------------
/others/Python3/347.Top K Frequent Elements.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 347. Top K Frequent Elements
3 | @Tag: Counter
4 | @Date: Nov-13 2019
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | import collections
11 | from typing import List
12 |
13 |
14 | class Solution:
15 | def topKFrequent(self, nums: List[int], k: int) -> List[int]:
16 | return [item[0] for item in collections.Counter(nums).most_common(k)]
17 |
18 |
19 | def test():
20 | s = Solution()
21 | res = s.topKFrequent([1, 1, 1, 2, 2, 3], 3)
22 | print(res)
23 |
24 |
25 | if __name__ == "__main__":
26 | test()
27 |
28 |
29 | """
30 | Runtime: 104 ms, faster than 98.05% of Python3 online submissions for Top K Frequent Elements.
31 | Memory Usage: 17.1 MB, less than 6.25% of Python3 online submissions for Top K Frequent Elements.
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/389.Find the Difference.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 389. Find the Difference
3 | @Tag: hashmap
4 | @Date: Feb-23 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import collections as c
11 |
12 |
13 | class Solution:
14 | def findTheDifference(self, s: str, t: str) -> str:
15 | d = c.defaultdict(int)
16 | for ch in s:
17 | d[ch] += 1
18 | for ch in t:
19 | d[ch] -= 1
20 | if d[ch] < 0:
21 | return ch
22 |
23 |
24 | """
25 | Runtime: 32 ms, faster than 69.08% of Python3 online submissions for Find the Difference.
26 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Find the Difference.
27 | """
28 |
29 |
30 | """
31 | Time Complexity: O(n)
32 | Space Complexity: O(n)
33 | """
34 |
--------------------------------------------------------------------------------
/others/Python3/412.Fizz Buzz.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 412. Fizz Buzz
3 | @Tag: math
4 | @Date: Jan-23 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def fizzBuzz(self, n: int) -> List[str]:
12 | res = []
13 | for i in range(1, n+1):
14 | if i % 3 == 0 and i % 5 == 0:
15 | res.append("FizzBuzz")
16 | elif i % 3 == 0:
17 | res.append("Fizz")
18 | elif i % 5 == 0:
19 | res.append("Buzz")
20 | else:
21 | res.append(str(i))
22 | return res
23 |
24 |
25 | """
26 | Runtime: 52 ms, faster than 8.70% of Python3 online submissions for Fizz Buzz.
27 | Memory Usage: 13.5 MB, less than 100.00% of Python3 online submissions for Fizz Buzz.
28 | """
29 |
30 |
31 | """
32 | Time Complexity: O(n)
33 | Space Complexity: O(1)
34 | """
35 |
--------------------------------------------------------------------------------
/others/Python3/415.Add Strings.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 415. Add Strings
3 | @Tag: string
4 | @Date: Jan-28 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def addStrings(self, num1: str, num2: str) -> str:
12 | return str(self.convert(num1) + self.convert(num2))
13 |
14 | def convert(self, num: str) -> int:
15 | res, i = 0, 0 # result, pointer
16 | while i < len(num):
17 | res = res * 10 + int(num[i])
18 | i += 1
19 | return res
20 |
21 |
22 | """
23 | Runtime: 52 ms, faster than 29.51% of Python3 online submissions for Add Strings.
24 | Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Add Strings.
25 | """
26 |
--------------------------------------------------------------------------------
/others/Python3/442.Find All Duplicates in an Array.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 442. Find All Duplicates in an Array
3 | @Tag: array / hashtable
4 | @Date: Feb-22 2020
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | import collections as c
11 |
12 |
13 | class Solution:
14 | def findDuplicates(self, A: List[int]) -> List[int]:
15 | res, d = [], c.defaultdict(int)
16 | for a in A:
17 | d[a] += 1
18 | if d[a] == 2:
19 | res.append(a)
20 | return res
21 |
22 |
23 | """
24 | Runtime: 392 ms, faster than 65.88% of Python3 online submissions for Find All Duplicates in an Array.
25 | Memory Usage: 21.2 MB, less than 7.14% of Python3 online submissions for Find All Duplicates in an Array.
26 | """
27 |
28 |
29 | """
30 | Time Complexity: O(n)
31 | Space Complexity: O(n)
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/448.Find All Numbers Disappeared in an Array.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 448. Find All Numbers Disappeared in an Array
3 | @Tag: array
4 | @Date: Feb-26 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def findDisappearedNumbers(self, A: List[int]) -> List[int]:
12 | n, res = len(A), []
13 | A = set(A)
14 | for i in range(1, n+1): # [1, n]
15 | if i not in A:
16 | res.append(i)
17 | return res
18 |
19 |
20 | """
21 | Runtime: 356 ms, faster than 94.59% of Python3 online submissions for Find All Numbers Disappeared in an Array.
22 | Memory Usage: 22.9 MB, less than 7.14% of Python3 online submissions for Find All Numbers Disappeared in an Array.
23 | """
24 |
--------------------------------------------------------------------------------
/others/Python3/461.Hamming Distance.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 461. Hamming Distance
3 | @Tag: bit shifting
4 | @Date: Jan-15 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def hammingDistance(self, x: int, y: int) -> int:
12 | return bin(x ^ y).count('1')
13 |
14 |
15 | """
16 | Runtime: 28 ms, faster than 61.17% of Python3 online submissions for Hamming Distance.
17 | Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Hamming Distance.
18 | """
19 |
20 |
21 | """
22 | Thanks to: @yuyuyu0905
23 | https://leetcode.com/problems/hamming-distance/discuss/94697/Python-1-line-49ms
24 | """
25 |
--------------------------------------------------------------------------------
/others/Python3/509.Fibonacci Number.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 509. Fibonacci Number
3 | @Tag: dp
4 | @Date: Dec-23 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def fib(self, N: int) -> int:
12 | # corner case
13 | if N == 0:
14 | return 0
15 | if N == 1:
16 | return 1
17 | dp = [0 for i in range(N+1)] # memorization
18 | dp[0], dp[1] = 0, 1 # initialization
19 | for n in range(2, N+1):
20 | dp[n] = dp[n-1]+dp[n-2]
21 | return dp[n]
22 |
23 |
24 | """
25 | Runtime: 20 ms, faster than 99.01% of Python3 online submissions for Fibonacci Number.
26 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Fibonacci Number.
27 | """
28 |
--------------------------------------------------------------------------------
/others/Python3/5315.Maximum 69 Number.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 5315. Maximum 69 Number
3 | @Tag: string
4 | @Date: Jan-19 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def maximum69Number(self, num: int) -> int:
12 | # str.replace(old, new[,a max])
13 | return int(str(num).replace('6', '9', 1))
14 |
15 |
16 | """
17 | Runtime: 28 ms, faster than 66.67% of Python3 online submissions for Maximum 69 Number.
18 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Maximum 69 Number.
19 | """
20 |
--------------------------------------------------------------------------------
/others/Python3/557.Reverse Words in a String III.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 557. Reverse Words in a String III
3 | @Tag: str
4 | @Date: Jan-26 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def reverseWords(self, s: str) -> str:
12 | return " ".join(word[::-1] for word in s.split())
13 |
14 |
15 | """
16 | Runtime: 80 ms, faster than 14.46% of Python3 online submissions for Reverse Words in a String III.
17 | Memory Usage: 13.1 MB, less than 96.15% of Python3 online submissions for Reverse Words in a String III.
18 | """
19 |
--------------------------------------------------------------------------------
/others/Python3/589.N-ary Tree Preorder Traversal.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 589. N-ary Tree Preorder Traversal
3 | @Tag: N-ary tree
4 | @Date: Feb-06 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | """
11 | # Definition for a Node.
12 | class Node:
13 | def __init__(self, val=None, children=None):
14 | self.val = val
15 | self.children = children
16 | """
17 |
18 |
19 | class Solution:
20 | def preorder(self, root: 'Node') -> List[int]:
21 | if not root:
22 | return []
23 | stack, res = [root], []
24 | while stack:
25 | node = stack.pop()
26 | res.append(node.val)
27 | stack.extend([child for child in node.children][::-1])
28 | return res
29 |
30 |
31 | """
32 | Runtime: 52 ms, faster than 58.70% of Python3 online submissions for N-ary Tree Preorder Traversal.
33 | Memory Usage: 14.7 MB, less than 100.00% of Python3 online submissions for N-ary Tree Preorder Traversal.
34 | """
35 |
36 |
37 | """
38 | Time Complexity: O(n)
39 | Space Complexity: O(n)
40 | """
41 |
--------------------------------------------------------------------------------
/others/Python3/590.N-ary Tree Postorder Traversal.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 590. N-ary Tree Postorder Traversal
3 | @Tag: tree
4 | @Date: Oct-28 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | from typing import List
11 |
12 | """
13 | # Definition for a Node.
14 | class Node:
15 | def __init__(self, val, children):
16 | self.val = val
17 | self.children = children
18 | """
19 |
20 |
21 | class Solution:
22 | def postorder(self, root: 'Node') -> List[int]:
23 | res = []
24 | if not root:
25 | return res
26 | for child in root.children:
27 | res.extend(self.postorder(child))
28 | res.append(root.val) # 'root' is also a paramete
29 | return res
30 |
31 |
32 | """
33 | Runtime: 644 ms, faster than 94.72% of Python3 online submissions for N-ary Tree Postorder Traversal.
34 | Memory Usage: 95.2 MB, less than 7.14% of Python3 online submissions for N-ary Tree Postorder Traversal.
35 | """
36 |
--------------------------------------------------------------------------------
/others/Python3/643.Maximum Average Subarray I.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 643. Maximum Average Subarray I
3 | @Tag: array
4 | @Date: Jan-30 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def findMaxAverage(self, nums: List[int], k: int) -> float:
12 | left, right, cur = 0, k - 1, 0 # initialization
13 | for i in range(k): # first k elements
14 | cur += nums[i]
15 | res = cur
16 | while right + 1 < len(nums):
17 | left, right = left + 1, right + 1 # move on
18 | cur = cur - nums[left - 1] + nums[right]
19 | res = cur if cur > res else res
20 | return res / k
21 |
22 |
23 | """
24 | Runtime: 1152 ms, faster than 6.92% of Python3 online submissions for Maximum Average Subarray I.
25 | Memory Usage: 15.9 MB, less than 12.50% of Python3 online submissions for Maximum Average Subarray I.
26 | """
27 |
28 |
29 | """
30 | Time Complexity: O(n)
31 | Space Complexity: O(1)
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/704.Binary Search.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 704. Binary Search
3 | @Tag: binary search
4 | @Date: Dec-27 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def search(self, nums: List[int], target: int) -> int:
12 | left, right = 0, len(nums)-1 # left & right bound
13 | while left <= right:
14 | mid = (left+right)//2 # the half
15 | if target == nums[mid]: # nailed it
16 | return mid # return the index
17 | else: # not found
18 | if target > nums[mid]: # the right part
19 | left = mid+1
20 | else: # the left part
21 | right = mid-1
22 | # If target exists then return its index, otherwise return -1
23 | return -1
24 |
25 |
26 | """
27 | Runtime: 248 ms, faster than 99.30% of Python3 online submissions for Binary Search.
28 | Memory Usage: 14 MB, less than 100.00% of Python3 online submissions for Binary Search.
29 | """
30 |
--------------------------------------------------------------------------------
/others/Python3/746.Min Cost Climbing Stairs.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 746. Min Cost Climbing Stairs
3 | @Tag: DP
4 | @Date: Nov-17 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 | from typing import List
10 |
11 |
12 | class Solution:
13 | def minCostClimbingStairs(self, cost: List[int]) -> int:
14 | # Memory recursion
15 | # min cost to n-th step(exclude the cost of n-th step)
16 | dp = [0]*(len(cost)+1)
17 | for n in range(2, len(cost)+1):
18 | dp[n] = min(dp[n-1]+cost[n-1], dp[n-2]+cost[n-2])
19 | return dp[n]
20 |
21 |
22 | def test():
23 | s = Solution()
24 | res = s.minCostClimbingStairs(
25 | [10, 15, 1, 20, 100, 30, 100, 1, 2, 30, 60, 100])
26 | print(res) # 124
27 |
28 |
29 | if __name__ == "__main__":
30 | test()
31 |
32 |
33 | """
34 | Runtime: 56 ms, faster than 96.49% of Python3 online submissions for Min Cost Climbing Stairs.
35 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Min Cost Climbing Stairs.
36 | """
37 |
--------------------------------------------------------------------------------
/others/Python3/788.Rotated Digits.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 788. Rotated Digits
3 | @Tag: string
4 | @Date: Jan-29 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def rotatedDigits(self, N: int) -> int:
12 | res = 0
13 | for n in range(1, N + 1): # from 1 to N are good
14 | if self.isGoodNum(n):
15 | res += 1
16 | return res
17 |
18 | def isGoodNum(self, N: int) -> bool:
19 | good, bad, valid = [2, 5, 6, 9], [3, 4, 7], False
20 | while N:
21 | if N % 10 in bad: # each digit must be rotated - we cannot choose to leave it alone
22 | return False
23 | if N % 10 in good: # at least one which can be rotated and different from previous
24 | valid = True
25 | N //= 10
26 | return valid
27 |
28 |
29 | """
30 | Runtime: 96 ms, faster than 57.78% of Python3 online submissions for Rotated Digits.
31 | Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Rotated Digits.
32 | """
33 |
--------------------------------------------------------------------------------
/others/Python3/819.Most Common Word.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 819. Most Common Word
3 | @Tag: string
4 | @Date: Jan-27 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | import string
11 | import collections
12 |
13 |
14 | class Solution:
15 | def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
16 | # remove all the punctuations from paragraph
17 | for punc in string.punctuation:
18 | paragraph = paragraph.replace(punc, " ")
19 | ban, res, most_freq = set(banned), "", 0
20 | # get the frequency of each element
21 | for word, freq in collections.Counter(paragraph.lower().split()).items():
22 | if word not in ban and freq > most_freq:
23 | res, most_freq = word, freq
24 | return res
25 |
26 |
27 | """
28 | Runtime: 32 ms, faster than 68.47% of Python3 online submissions for Most Common Word.
29 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Most Common Word.
30 | """
31 |
--------------------------------------------------------------------------------
/others/Python3/824.Goat Latin.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 824. Goat Latin
3 | @Tag: string
4 | @Date: Jan-29 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def toGoatLatin(self, S: str) -> str:
12 | index, vowels, res = 1, list("aeiouAEIOU"), []
13 | for word in S.split():
14 | if word[0] in vowels: # rule one
15 | word += "ma"
16 | else: # rule two
17 | word = word[1:] + word[0] + "ma"
18 | word += index * 'a' # rule three
19 | index += 1
20 | res.append(word)
21 | return " ".join(res)
22 |
23 |
24 | """
25 | Runtime: 28 ms, faster than 65.95% of Python3 online submissions for Goat Latin.
26 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Goat Latin.
27 | """
28 |
--------------------------------------------------------------------------------
/others/Python3/836.Rectangle Overlap.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 836. Rectangle Overlap
3 | @Tag: math
4 | @Date: Jan-15 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
12 | width = min(rec1[2], rec2[2]) - max(rec1[0],
13 | rec2[0]) # min_right - max_left
14 | height = min(rec1[3], rec2[3]) - max(rec1[1],
15 | rec2[1]) # min_high - max_low
16 | return width > 0 and height > 0
17 |
18 |
19 | """
20 | Runtime: 12 ms, faster than 100.00% of Python3 online submissions for Rectangle Overlap.
21 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Rectangle Overlap.
22 | """
23 |
--------------------------------------------------------------------------------
/others/Python3/844.Backspace String Compare.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 844. Backspace String Compare
3 | @Tag: stack
4 | @Date: Jan-17 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def backspaceCompare(self, S: str, T: str) -> bool:
12 | s, t = [], []
13 | for ch in S:
14 | if ch == "#": # backspace
15 | if s:
16 | s.pop()
17 | else:
18 | s.append(ch)
19 | for ch in T:
20 | if ch == "#":
21 | if t:
22 | t.pop()
23 | else:
24 | t.append(ch)
25 | return s == t
26 |
27 |
28 | """
29 | Runtime: 28 ms, faster than 70.38% of Python3 online submissions for Backspace String Compare.
30 | Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Backspace String Compare.
31 | """
32 |
33 |
34 | """
35 | Time Complexity: O(n)
36 | Space Complexity: O(n)
37 | """
38 |
--------------------------------------------------------------------------------
/others/Python3/859.Buddy Strings.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 859. Buddy Strings
3 | @Tag: string
4 | @Date: Feb-25 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def buddyStrings(self, A: str, B: str) -> bool:
12 | if len(A) != len(B):
13 | return False
14 | if A == B:
15 | if len(A) == len(set(A)): # "abcdefg"
16 | return False
17 | else: # "aaaa"
18 | return True
19 | n = len(A)
20 | res = [(x, y) for x, y in zip(A, B) if x != y] # pairs
21 | return len(res) == 2 and res[0] == res[1][::-1]
22 |
23 |
24 | """
25 | Runtime: 32 ms, faster than 61.54% of Python3 online submissions for Buddy Strings.
26 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Buddy Strings.
27 | """
28 |
--------------------------------------------------------------------------------
/others/Python3/888.Fair Candy Swap.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 888. Fair Candy Swap
3 | @Tag: array
4 | @Date: Feb-02 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def fairCandySwap(self, A: List[int], B: List[int]) -> List[int]:
12 | for j in set(B): # accelerate
13 | # solve the equation: "y - x = (sum(B) - sum(A)) / 2"
14 | if j - (sum(B) - sum(A)) // 2 in A:
15 | return [j - (sum(B) - sum(A)) // 2, j]
16 |
17 |
18 | """
19 | Runtime: 6864 ms, faster than 5.16% of Python3 online submissions for Fair Candy Swap.
20 | Memory Usage: 15.1 MB, less than 41.67% of Python3 online submissions for Fair Candy Swap.
21 | """
22 |
--------------------------------------------------------------------------------
/others/Python3/908.Smallest Range I.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 908. Smallest Range I
3 | @Tag: math
4 | @Date: Feb-03 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def smallestRangeI(self, A: List[int], K: int) -> int:
12 | return max(A) - min(A) - 2 * K if max(A) - min(A) > 2 * K else 0
13 |
14 |
15 | """
16 | Runtime: 116 ms, faster than 88.17% of Python3 online submissions for Smallest Range I.
17 | Memory Usage: 13.8 MB, less than 88.89% of Python3 online submissions for Smallest Range I.
18 | """
19 |
20 |
21 | """
22 | Time Complexity: O(n)
23 | Space Complexity: O(1)
24 | """
25 |
--------------------------------------------------------------------------------
/others/Python3/929.Unique Email Addresses.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 929. Unique Email Addresses
3 | @Tag: string
4 | @Date: Jan-30 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | class Solution:
11 | def numUniqueEmails(self, emails: List[str]) -> int:
12 | res = []
13 | for email in emails: # each email
14 | local, domain = email.split("@")[0], email.split("@")[1]
15 | local = local.replace(".", "") # rule one
16 | if "+" in local:
17 | local = local[:local.index('+')] # rule two
18 | res.append(local + "@" + domain)
19 | return len(set(res))
20 |
21 |
22 | """
23 | Runtime: 44 ms, faster than 92.49% of Python3 online submissions for Unique Email Addresses.
24 | Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Unique Email Addresses.
25 | """
26 |
--------------------------------------------------------------------------------
/others/Python3/946.Validate Stack Sequences.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 946. Validate Stack Sequences
3 | @Tag: stack
4 | @Date: Oct-26 2019
5 | @Author: ceezyyy
6 | @Difficulty: Medium
7 | """
8 |
9 |
10 | import collections
11 | from typing import List
12 |
13 | class Solution:
14 | def validateStackSequences(self, pushed: List[int], popped: List[int]) -> bool:
15 | stack = []
16 | for i in pushed:
17 | stack.append(i)
18 | while stack and popped and stack[-1] == popped[0]: # stack top
19 | stack.pop()
20 | popped.pop(0)
21 | return not stack
22 |
23 |
24 | def test():
25 | s = Solution()
26 | print(s.validateStackSequences([1, 2, 3, 4, 5], [4, 5, 3, 2, 1]))
27 |
28 |
29 | if __name__ == "__main__":
30 | test()
31 |
--------------------------------------------------------------------------------
/others/Python3/965.Univalued Binary Tree.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 965. Univalued Binary Tree
3 | @Tag: binary tree
4 | @Date: Mar-05 2020
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | # Definition for a binary tree node.
11 | # class TreeNode:
12 | # def __init__(self, x):
13 | # self.val = x
14 | # self.left = None
15 | # self.right = None
16 |
17 | class Solution:
18 | def isUnivalTree(self, root: TreeNode) -> bool:
19 | return self.dfs(root, root.val)
20 |
21 | def dfs(self, node, v):
22 | if node:
23 | return False if node.val != v else self.dfs(node.left, v) and self.dfs(node.right, v)
24 | return True
25 |
26 |
27 | """
28 | Runtime: 24 ms, faster than 98.45% of Python3 online submissions for Univalued Binary Tree.
29 | Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Univalued Binary Tree.
30 | """
31 |
32 |
33 | """
34 | Time Complexity: O(n)
35 | Space Complexity: O(n)
36 | """
37 |
--------------------------------------------------------------------------------
/others/Python3/989.Add to Array-Form of Integer.py:
--------------------------------------------------------------------------------
1 | """
2 | @Title: 989. Add to Array-Form of Integer
3 | @Tag: list
4 | @Date: Oct-31 2019
5 | @Author: ceezyyy
6 | @Difficulty: Easy
7 | """
8 |
9 |
10 | from typing import List
11 |
12 |
13 | class Solution:
14 | def addToArrayForm(self, A: List[int], K: int) -> List[int]:
15 | total = 0
16 | for i in range(len(A)):
17 | total = total*10+A[i]
18 | total += K
19 | return list(str(total))
20 |
21 |
22 | '''
23 | Runtime: 440 ms, faster than 15.26% of Python3 online submissions for Add to Array-Form of Integer.
24 | Memory Usage: 14.1 MB, less than 5.00% of Python3 online submissions for Add to Array-Form of Integer.
25 | '''
26 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Recursion & Backtracking/.DS_Store
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/.idea/Recursion & Backtracking.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/backtracking.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Recursion & Backtracking/backtracking.jpg
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/backtracking.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/combinations/combinations.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/count-sorted-vowel-strings/count-sorted-vowel-strings.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/generate-parentheses/generate-parentheses.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/iterator-for-combination/iterator-for-combination.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/letter-combinations-of-a-phone-number/letter-combinations-of-a-phone-number.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/permutations/permutations.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/phone_number.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Recursion & Backtracking/phone_number.png
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/subsets-ii/subsets-ii.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/subsets/subsets.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/sudoku.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Recursion & Backtracking/sudoku.png
--------------------------------------------------------------------------------
/others/Recursion & Backtracking/sudoku1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Recursion & Backtracking/sudoku1.png
--------------------------------------------------------------------------------
/others/Stacks & Queues/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Stacks & Queues/.DS_Store
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/.DS_Store
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 | # Datasource local storage ignored files
5 | /dataSources/
6 | /dataSources.local.xml
7 | # Editor-based HTTP Client requests
8 | /httpRequests/
9 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/.idea/Tree, Binary Tree, BST.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/116_sample.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/116_sample.png
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/538.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/538.png
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/binary_tree.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/binary_tree.png
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/construct-binary-tree-from-inorder-and-postorder-traversal/construct-binary-tree-from-inorder-and-postorder-traversal.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/construct-binary-tree-from-preorder-and-inorder-traversal/construct-binary-tree-from-preorder-and-inorder-traversal.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/convert-bst-to-greater-tree/convert-bst-to-greater-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/convert-bst-to-greater-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Convert BST to Greater Tree
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | private int sum = 0;
13 |
14 | public TreeNode convertBST(TreeNode root) {
15 | calculateBST(root);
16 | return root;
17 | }
18 |
19 | public void calculateBST(TreeNode root) {
20 |
21 | // Corner case
22 | if (root == null) return;
23 |
24 | calculateBST(root.right);
25 | // Key point
26 | sum += root.val;
27 | root.val = sum;
28 | calculateBST(root.left);
29 |
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/count-complete-tree-nodes/count-complete-tree-nodes.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/count-complete-tree-nodes/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Count Complete Tree Nodes
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | public int countNodes(TreeNode root) {
13 |
14 | // Corner case
15 | if (root == null) return 0;
16 |
17 | return countNodes(root.left) + countNodes(root.right) + 1;
18 |
19 | }
20 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/ex_depth.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/ex_depth.jpg
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/flatten-binary-tree-to-linked-list/flatten-binary-tree-to-linked-list.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/flatten-binary-tree-to-linked-list/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Flatten Binary Tree to Linked List
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | private TreeNode tail = null;
13 |
14 | public void flatten(TreeNode root) {
15 |
16 | // Corner case
17 | if (root == null) return;
18 |
19 | TreeNode left = root.left;
20 | TreeNode right = root.right;
21 |
22 | flatten(left);
23 | flatten(right);
24 |
25 | root.left = null;
26 | root.right = left;
27 |
28 | // "left" may be null, to avoid NullPointerException
29 | // We need a cursor to reach the tail of the linked list
30 | tail = root;
31 | while (tail.right != null) tail = tail.right;
32 |
33 | // Now at the tail of the linked list
34 | tail.right = right;
35 |
36 | }
37 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/inorder-traversal/inorder-traversal.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/inorder-traversal/src/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 | import java.util.List;
3 |
4 |
5 | /**
6 | * Binary Tree Inorder Traversal
7 | */
8 | class Solution {
9 |
10 | public class TreeNode {
11 | int val;
12 | TreeNode left;
13 | TreeNode right;
14 | }
15 |
16 | private List result = new LinkedList<>();
17 |
18 | public List inorderTraversal(TreeNode root) {
19 | in(root);
20 | return result;
21 | }
22 |
23 | public void in(TreeNode node) {
24 | if (node == null) return;
25 | in(node.left);
26 | result.add(node.val);
27 | in(node.right);
28 | }
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/insert-into-a-binary-search-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Insert into a Binary Search Tree
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 |
11 | TreeNode(int val) {
12 | this.val = val;
13 | }
14 | }
15 |
16 | public TreeNode insertIntoBST(TreeNode root, int val) {
17 |
18 | if (root == null) return new TreeNode(val);
19 |
20 | // It's guaranteed that val does not exist in the original BST
21 | if (val < root.val) {
22 | root.left = insertIntoBST(root.left, val);
23 | } else {
24 | root.right = insertIntoBST(root.right, val);
25 | }
26 |
27 | return root;
28 |
29 | }
30 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/insert_bst.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/insert_bst.jpg
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/invert-binary-tree/invert-binary-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/invert-binary-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Invert Binary Tree
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | public TreeNode invertTree(TreeNode root) {
13 |
14 | if (root == null) return null;
15 |
16 | // Swap children
17 | TreeNode temp = root.left;
18 | root.left = root.right;
19 | root.right = temp;
20 |
21 | invertTree(root.left);
22 | invertTree(root.right);
23 |
24 | return root;
25 |
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/kth-smallest-element-in-a-bst/src/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.ArrayList;
2 | import java.util.List;
3 |
4 | /**
5 | * Kth Smallest Element in a BST
6 | */
7 | class Solution {
8 |
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 |
14 | }
15 |
16 | public List elements = new ArrayList<>();
17 |
18 | public int kthSmallest(TreeNode root, int k) {
19 | // The number of elements of the BST is between 1 to 10^4
20 | inorder(root);
21 | // You may assume k is always valid, 1 ≤ k ≤ BST's total elements
22 | return elements.get(k - 1);
23 | }
24 |
25 | public void inorder(TreeNode root) {
26 | // Corner case
27 | if (root == null) {
28 | return;
29 | }
30 | inorder(root.left);
31 | elements.add(root.val);
32 | inorder(root.right);
33 | }
34 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/maximum-binary-tree/maximum-binary-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/maximum-depth-of-binary-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Maximum Depth of Binary Tree
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | // Bottom-up
13 | public int maxDepth(TreeNode root) {
14 | if (root == null) return 0;
15 | return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
16 | }
17 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/minimum-depth-of-binary-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Minimum Depth of Binary Tree
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | public int minDepth(TreeNode root) {
13 |
14 | // Corner case
15 | if (root == null) return 0;
16 |
17 | // Leaf node
18 | if (root.left == null && root.right == null) return 1;
19 |
20 | int left = minDepth(root.left);
21 | int right = minDepth(root.right);
22 |
23 | // One side
24 | if (root.left == null || root.right == null) return left + right + 1;
25 |
26 | return Math.min(left, right) + 1;
27 |
28 | }
29 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/mirror_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/mirror_1.png
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/mirror_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/mirror_2.png
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/path-sum/path-sum.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/path-sum/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Path Sum
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | public boolean hasPathSum(TreeNode root, int sum) {
13 |
14 | // Corner case
15 | if (root == null) return false;
16 |
17 | // Leaf
18 | if (root.left == null && root.right == null && sum == root.val) {
19 | return true;
20 | }
21 |
22 | return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
23 |
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/populating-next-right-pointers-in-each-node/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Populating Next Right Pointers in Each Node
3 | */
4 | class Solution {
5 |
6 | public class Node {
7 | public int val;
8 | public Node left;
9 | public Node right;
10 | public Node next;
11 | }
12 |
13 | public Node connect(Node root) {
14 | if (root == null) return root;
15 | connect(root.left, root.right);
16 | return root;
17 | }
18 |
19 | public void connect(Node left, Node right) {
20 |
21 | if (left == null || right == null) return;
22 |
23 | left.next = right;
24 | right.next = null;
25 |
26 | connect(left.left, left.right);
27 | connect(left.right, right.left);
28 | connect(right.left, right.right);
29 |
30 | }
31 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/postorder-traversal/postorder-traversal.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/postorder-traversal/src/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 | import java.util.List;
3 |
4 | /**
5 | * Binary Tree Postorder Traversal
6 | */
7 | class Solution {
8 |
9 | public class TreeNode {
10 | int val;
11 | TreeNode left;
12 | TreeNode right;
13 | }
14 |
15 | private List result = new LinkedList<>();
16 |
17 | public List postorderTraversal(TreeNode root) {
18 | post(root);
19 | return result;
20 | }
21 |
22 | public void post(TreeNode node) {
23 | if (node == null) return;
24 | post(node.left);
25 | post(node.right);
26 | result.add(node.val);
27 | }
28 |
29 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/preorder-traversal/preorder-traversal.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/preorder-traversal/src/Solution.java:
--------------------------------------------------------------------------------
1 | import java.util.LinkedList;
2 | import java.util.List;
3 |
4 |
5 | /**
6 | * Binary Tree Preorder Traversal
7 | */
8 | class Solution {
9 |
10 | public class TreeNode {
11 | int val;
12 | TreeNode left;
13 | TreeNode right;
14 | }
15 |
16 | private List result = new LinkedList<>();
17 |
18 | public List preorderTraversal(TreeNode root) {
19 | pre(root);
20 | return result;
21 | }
22 |
23 | public void pre(TreeNode node) {
24 | if (node == null) return;
25 | result.add(node.val);
26 | pre(node.left);
27 | pre(node.right);
28 | }
29 |
30 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/se_de.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/se_de.jpg
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/search-in-a-binary-search-tree/search-in-a-binary-search-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/search-in-a-binary-search-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Search in a Binary Search Tree
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | public TreeNode searchBST(TreeNode root, int val) {
13 |
14 | // Corner case
15 | if (root == null) return null;
16 |
17 | // Bingo
18 | if (root.val == val) return root;
19 |
20 | if (val < root.val) {
21 | return searchBST(root.left, val);
22 | } else {
23 | return searchBST(root.right, val);
24 | }
25 |
26 | }
27 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/serialize-and-deserialize-binary-tree/serialize-and-deserialize-binary-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/symmetric-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Symmetric Tree
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | public boolean isSymmetric(TreeNode root) {
13 | return isMirror(root, root);
14 | }
15 |
16 | // Top-down
17 | public boolean isMirror(TreeNode n1, TreeNode n2) {
18 | // Corner cases
19 | if (n1 == null && n2 == null) return true;
20 | if (n1 == null || n2 == null) return false;
21 |
22 | return (n1.val == n2.val) && isMirror(n1.left, n2.right) && isMirror(n1.right, n2.left);
23 | }
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/symmetric-tree/symmetric-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/unival.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/Tree, Binary Tree, BST/unival.png
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/univalued-binary-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Univalued Binary Tree
3 | *
4 | * A binary tree is univalued if every node in the tree has the same value.
5 | */
6 | class Solution {
7 |
8 | public class TreeNode {
9 | int val;
10 | TreeNode left;
11 | TreeNode right;
12 | }
13 |
14 | public boolean isUnivalTree(TreeNode root) {
15 | // The number of nodes in the given tree will be in the range [1, 100]
16 | return isUnivalTree(root, root.val);
17 | }
18 |
19 | public boolean isUnivalTree(TreeNode root, int val) {
20 |
21 | // Corner case
22 | if (root == null) return true;
23 |
24 | if (root.val != val) return false;
25 |
26 | return isUnivalTree(root.left, val) && isUnivalTree(root.right, val);
27 |
28 | }
29 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/univalued-binary-tree/univalued-binary-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/validate-binary-search-tree/src/Solution.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Validate Binary Search Tree
3 | */
4 | class Solution {
5 |
6 | public class TreeNode {
7 | int val;
8 | TreeNode left;
9 | TreeNode right;
10 | }
11 |
12 | public boolean isValidBST(TreeNode root) {
13 |
14 | // Corner case
15 | if (root == null) return true;
16 |
17 | // Use Long instead of Integer
18 | return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
19 |
20 | }
21 |
22 | public boolean isValidBST(TreeNode root, long min, long max) {
23 |
24 | // Corner case
25 | if (root == null) return true;
26 |
27 | // Root: -inf < root < inf
28 | // Left subtree: -inf < left < root
29 | // Right subtree: root < right < inf
30 | int val = root.val;
31 | if (val >= max || val <= min) return false;
32 |
33 | return isValidBST(root.left, min, val) && isValidBST(root.right, val, max);
34 |
35 | }
36 | }
--------------------------------------------------------------------------------
/others/Tree, Binary Tree, BST/validate-binary-search-tree/validate-binary-search-tree.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/others/cpp/001.Two Sum.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Source: LeetCode 001.Two Sum
3 | * Author: ceezyyy
4 | * Date: 03-01-2019
5 | */
6 |
7 | /*
8 | Easy
9 |
10 | Share
11 | Given an array of integers, return indices of the two numbers such that they add up to a specific target.
12 | You may assume that each input would have exactly one solution, and you may not use the same element twice.
13 |
14 | Example:
15 | Given nums = [2, 7, 11, 15], target = 9,
16 | Because nums[0] + nums[1] = 2 + 7 = 9,
17 | return [0, 1].
18 |
19 | */
20 |
21 |
22 | #include
23 | #include
24 | #include
25 | using namespace std;
26 |
27 | class Solution {
28 | public:
29 | vector twoSum(vector& nums, int target)
30 | {
31 | vector res;
32 | for (int i = 0; i < nums.size(); i++)
33 | {
34 | int start = nums[i];
35 | for (int j = i + 1; j < nums.size(); j++)
36 | {
37 | if (start + nums[j] == target)
38 | {
39 | res.push_back(i);
40 | res.push_back(j);
41 | }
42 | }
43 | }
44 | return res;
45 | }
46 | };
47 |
--------------------------------------------------------------------------------
/others/cpp/1046.Last Stone Weight.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/1046.Last Stone Weight.cpp
--------------------------------------------------------------------------------
/others/cpp/231.Power of Two.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Source: LeetCode 231. Power of Two
3 | * Author: ceezyyy
4 | * Date: 03-23-2019
5 | */
6 |
7 |
8 | /*
9 | Easy
10 |
11 | Share
12 | Given an integer, write a function to determine if it is a power of two.
13 |
14 | Example 1:
15 | Input: 1
16 | Output: true
17 | Explanation: 20 = 1
18 |
19 | Example 2:
20 | Input: 16
21 | Output: true
22 | Explanation: 24 = 16
23 |
24 | Example 3:
25 | Input: 218
26 | Output: false
27 |
28 | */
29 |
30 |
31 | #include
32 | #include
33 | using namespace std;
34 | class Solution {
35 | public:
36 | bool isPowerOfTwo(int n) {
37 | if (n == 1 || n == 2 || n == 4 || n == 8) { return true; }
38 | for (int i = 0; i <= sqrt(n); i++) {
39 | if (pow(2, i) == n) {
40 | return true;
41 | }
42 | }
43 | return false;
44 | }
45 | };
46 |
47 |
48 | /**
49 | * Submission Detail:
50 | * Runtime: 24 ms, faster than 50.20% of C++ online submissions for Power of Two.
51 | * Memory Usage: 8.3 MB, less than 5.11% of C++ online submissions for Power of Two.
52 | */
53 |
--------------------------------------------------------------------------------
/others/cpp/345.Reverse Vowels of a String.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/345.Reverse Vowels of a String.cpp
--------------------------------------------------------------------------------
/others/cpp/350.Intersection of Two Arrays II.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/350.Intersection of Two Arrays II.cpp
--------------------------------------------------------------------------------
/others/cpp/374.Guess Number Higher or Lower.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/374.Guess Number Higher or Lower.cpp
--------------------------------------------------------------------------------
/others/cpp/387.First Unique Character in a String.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/387.First Unique Character in a String.cpp
--------------------------------------------------------------------------------
/others/cpp/496.Next Greater Element I.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/496.Next Greater Element I.cpp
--------------------------------------------------------------------------------
/others/cpp/500.Keyboard Row.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/500.Keyboard Row.cpp
--------------------------------------------------------------------------------
/others/cpp/532.K-diff Pairs in an Array.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/532.K-diff Pairs in an Array.cpp
--------------------------------------------------------------------------------
/others/cpp/557.Reverse Words in a String III.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/557.Reverse Words in a String III.cpp
--------------------------------------------------------------------------------
/others/cpp/622.Design Circular Queue.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/622.Design Circular Queue.cpp
--------------------------------------------------------------------------------
/others/cpp/645.Set Mismatch.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/645.Set Mismatch.cpp
--------------------------------------------------------------------------------
/others/cpp/674.Longest Continuous Increasing Subsequence.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/674.Longest Continuous Increasing Subsequence.cpp
--------------------------------------------------------------------------------
/others/cpp/709.To Lower Case.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | Source: LeetCode 709. To Lower Case
3 | Author: ceezyyy
4 | Date: 03-04-2019
5 | */
6 |
7 | /*
8 |
9 | 709. To Lower Case
10 |
11 | Easy
12 |
13 | Share
14 | Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase.
15 |
16 | Example 1:
17 | Input: “Hello”
18 | Output: “hello”
19 |
20 | Example 2:
21 | Input: “here”
22 | Output: “here”
23 |
24 | Example 3:
25 | Input: “LOVELY”
26 | Output: “lovely”
27 |
28 | */
29 |
30 |
31 | #include
32 | #include
33 | #include
34 | using namespace std;
35 |
36 | class Solution {
37 | public:
38 | string toLowerCase(string str) {
39 | for (int i = 0; i < str.length(); i++) {
40 | if (str[i] >= 'A' && str[i] <= 'Z')
41 | str[i] = tolower(str[i]);
42 | }
43 | return str;
44 | }
45 | };
46 |
--------------------------------------------------------------------------------
/others/cpp/724.Find Pivot Index.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/724.Find Pivot Index.cpp
--------------------------------------------------------------------------------
/others/cpp/747.Largest Number At Least Twice of Others.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/747.Largest Number At Least Twice of Others.cpp
--------------------------------------------------------------------------------
/others/cpp/766.Toeplitz Matrix.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/766.Toeplitz Matrix.cpp
--------------------------------------------------------------------------------
/others/cpp/830.Positions of Large Groups.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/830.Positions of Large Groups.cpp
--------------------------------------------------------------------------------
/others/cpp/917.Reverse Only Letters.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/917.Reverse Only Letters.cpp
--------------------------------------------------------------------------------
/others/cpp/941.Valid Mountain Array.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/941.Valid Mountain Array.cpp
--------------------------------------------------------------------------------
/others/cpp/942.DI String Match.cpp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ceezyyy/leetcode/feb04d00b62f1debe79aea820db9d43bea1d4632/others/cpp/942.DI String Match.cpp
--------------------------------------------------------------------------------