├── Easy
├── 100. Same Tree
│ ├── README.md
│ └── Same Tree.cpp
├── 104. Maximum Depth of Binary Tree
│ ├── Maximum Depth of Binary Tree.cpp
│ └── README.md
├── 1071. Greatest Common Divisor of Strings
│ ├── Greatest Common Divisor of Strings
│ └── README.md
├── 1137. N-th Tribonacci Number
│ ├── N-th Tribonacci Number.cpp
│ └── README.md
├── 121. Best Time to Buy and Sell Stock
│ ├── 1 - Best Time to Buy and Sell Stock.cpp
│ ├── 2 - Best Time to Buy and Sell Stock.java
│ ├── 3 - Best Time to Buy and Sell Stock.py
│ ├── 4 - Best Time to Buy and Sell Stock.js
│ └── README.md
├── 1470. Shuffle the Array
│ ├── README.md
│ └── Shuffle the Array.cpp
├── 1523. Count Odd Numbers in an Interval Range
│ ├── Count Odd Numbers in an Interval Range.cpp
│ └── README.md
├── 1539. Kth Missing Positive Number
│ ├── 1 - Kth Missing Positive Numbercpp
│ ├── 2 - Kth Missing Positive Number.java
│ ├── 3 - Kth Missing Positive Number.py
│ ├── 4 - Kth Missing Positive Number.js
│ └── README.md
├── 226. Invert Binary Tree
│ ├── 1 - Invert Binary Tree.cpp
│ ├── 2 - Invert Binary Tree.js
│ └── README.md
├── 35. Search Insert Position
│ ├── 1 - Search Insert Position.cpp
│ ├── 2 - Search Insert Position.cpp
│ ├── 3 - Search Insert Position.js
│ └── README.md
├── 67. Add Binary
│ ├── Add Binary.cpp
│ └── README.md
├── 783. Minimum Distance Between BST Nodes
│ ├── 1 - Minimum Distance Between BST Nodes.cpp
│ ├── 2 - Minimum Distance Between BST Nodes.cpp
│ └── README.md
├── 953. Verifying an Alien Dictionary
│ ├── README.md
│ └── Verifying an Alien Dictionary.cpp
├── 989. Add to Array-Form of Integer
│ ├── Add to Array-Form of Integer.cpp
│ └── README.md
└── 997. Find the Town Judge
│ ├── Find the Town Judge.cpp
│ └── README.md
├── Hard
├── 1345. Jump Game IV
│ ├── 1 - Jump Game IV.cpp
│ ├── 2 - Jump Game IV.java
│ ├── 3 - Jump Game IV.py
│ ├── 4 - Jump Game IV.js
│ └── README.md
├── 1675. Minimize Deviation in Array
│ ├── 1 - Minimize Deviation in Array.cpp
│ ├── 2 - Minimize Deviation in Array.java
│ ├── 3 - Minimize Deviation in Array.py
│ ├── 4 - Minimize Deviation in Array.js
│ └── README.md
├── 2246. Longest Path With Different Adjacent Characters
│ ├── Longest Path With Different Adjacent Characters.cpp
│ └── README.md
├── 2306. Naming a Company
│ ├── 2306. Naming a Company.cpp
│ └── README.md
├── 2421. Number of Good Paths
│ ├── Number of Good Paths.cpp
│ └── README.md
├── 2444. Count Subarrays With Fixed Bounds
│ ├── 1 - Count Subarrays With Fixed Bounds.cpp
│ ├── 2 - Count Subarrays With Fixed Bounds.java
│ ├── 3 - Count Subarrays With Fixed Bounds.py
│ ├── 4 - Count Subarrays With Fixed Bounds.js
│ └── README.md
├── 352. Data Stream as Disjoint Intervals
│ ├── Data Stream as Disjoint Intervals.cpp
│ └── README.md
├── 460. LFU Cache
│ ├── LFU Cache.cpp
│ └── README.md
├── 472. Concatenated Words
│ ├── Concatenated Words.cpp
│ └── README.md
├── 502. IPO
│ ├── 1 - IPO.cpp
│ ├── 2 - IPO.java
│ ├── 3 - IPO.py
│ ├── 4 - IPO.js
│ └── README.md
├── 540. Single Element in a Sorted Array
│ ├── 1 - Single Element in a Sorted Array.cpp
│ ├── 2 - Single Element in a Sorted Array.java
│ ├── 3 - Single Element in a Sorted Array.py
│ ├── 4 - Single Element in a Sorted Array.js
│ └── README.md
└── 72. Edit Distance
│ ├── 1 - Edit Distance.cpp
│ ├── 2 - Edit Distance.cpp
│ ├── 3 - Edit Distance.java
│ ├── 4 - Edit Distance.py
│ ├── 5 - Edit Distance.js
│ └── README.md
├── Medium
├── 1011. Capacity To Ship Packages Within D Days
│ ├── 1 - Capacity To Ship Packages Within D Days.cpp
│ ├── 2 - Capacity To Ship Packages Within D Days.java
│ ├── 3 - Capacity To Ship Packages Within D Days.py
│ ├── 4 - Capacity To Ship Packages Within D Days.js
│ └── README.md
├── 103. Binary Tree Zigzag Level Order Traversal
│ ├── 1 - Binary Tree Zigzag Level Order Traversal.cpp
│ ├── 2 - Binary Tree Zigzag Level Order Traversal.js
│ └── README.md
├── 1061. Lexicographically Smallest Equivalent String
│ ├── Lexicographically Smallest Equivalent String.cpp
│ └── README.md
├── 1129. Shortest Path with Alternating Colors
│ ├── README.md
│ └── Shortest Path with Alternating Colors.cpp
├── 1162. As Far from Land as Possible
│ ├── As Far from Land as Possible.cpp
│ └── README.md
├── 131. Palindrome Partitioning
│ ├── Palindrome Partitioning.cpp
│ └── README.md
├── 142. Linked List Cycle II
│ ├── 1 - Linked List Cycle II.cpp
│ ├── 2 - Linked List Cycle II.java
│ ├── 3 - Linked List Cycle II.py
│ ├── 4 - Linked List Cycle II.js
│ └── README.md
├── 1443. Minimum Time to Collect All Apples in a Tree
│ ├── Minimum Time to Collect All Apples in a Tree.cpp
│ └── README.md
├── 1519. Number of Nodes in the Sub-Tree With the Same Label
│ ├── Number of Nodes in the Sub-Tree With the Same Label.cpp
│ └── README.md
├── 1626. Best Team With No Conflicts
│ ├── Best Team With No Conflicts.cpp
│ └── README.md
├── 2187. Minimum Time to Complete Trips
│ ├── 1 - Minimum Time to Complete Trips.cpp
│ ├── 2 - Minimum Time to Complete Trips.java
│ ├── 3 - Minimum Time to Complete Trips.py
│ ├── 4 - Minimum Time to Complete Trips.js
│ └── README.md
├── 2359. Find Closest Node to Given Two Nodes
│ ├── Find Closest Node to Given Two Nodes.cpp
│ └── README.md
├── 2477. Minimum Fuel Cost to Report to the Capital
│ ├── Minimum Fuel Cost to Report to the Capital.cpp
│ └── README.md
├── 28. Find the Index of the First Occurrence in a String
│ ├── 1 - Find the Index of the First Occurrence in a String.cpp
│ ├── 2 - Find the Index of the First Occurrence in a String.java
│ ├── 3 - Find the Index of the First Occurrence in a String.py
│ ├── 4 - Find the Index of the First Occurrence in a String.js
│ └── README.md
├── 427. Construct Quad Tree
│ ├── 1 - Construct Quad Tree.cpp
│ ├── 2 - Construct Quad Tree.java
│ ├── 3 - Construct Quad Tree.py
│ ├── 4 - Construct Quad Tree.js
│ └── README.md
├── 438. Find All Anagrams in a String
│ ├── Find All Anagrams in a String.cpp
│ └── README.md
├── 443. String Compression
│ ├── 1 - String Compression.cpp
│ ├── 2 - String Compression.java
│ ├── 3 - String Compression.py
│ ├── 4 - String Compression.js
│ └── README.md
├── 45. Jump Game II
│ ├── 45. Jump Game II.cpp
│ └── README.md
├── 491. Non-decreasing Subsequences
│ ├── Non-decreasing Subsequences.cpp
│ └── README.md
├── 567. Permutation in String
│ ├── Permutation in String.cpp
│ └── README.md
├── 57. Insert Interval
│ ├── Insert Interval.cpp
│ └── README.md
├── 6. Zigzag Conversion
│ ├── 6. Zigzag Conversion.cpp
│ └── README.md
├── 652. Find Duplicate Subtrees
│ ├── 1 - Find Duplicate Subtrees.cpp
│ ├── 2 - Find Duplicate Subtrees.java
│ ├── 3 - Find Duplicate Subtrees.py
│ ├── 4 - Find Duplicate Subtrees.js
│ └── README.md
├── 787. Cheapest Flights Within K Stops
│ ├── Cheapest Flights Within K Stops.cpp
│ └── README.md
├── 875. Koko Eating Bananas
│ ├── 1 - Koko Eating Bananas.cpp
│ ├── 2 - Koko Eating Bananas.java
│ ├── 3 - Koko Eating Bananas.py
│ ├── 4 - Koko Eating Bananas.js
│ └── README.md
├── 904. Fruit Into Baskets
│ ├── 904. Fruit Into Baskets.cpp
│ └── README.md
├── 909. Snakes and Ladders
│ ├── README.md
│ └── Snakes and Ladders.cpp
├── 912. Sort an Array
│ ├── 1 - Sort an Array.cpp
│ ├── 2 - Sort an Array.java
│ ├── 3 - Sort an Array.py
│ ├── 4 - Sort an Array.js
│ └── README.md
├── 918. Maximum Sum Circular Subarray
│ ├── Maximum Sum Circular Subarray.cpp
│ └── README.md
├── 926. Flip String to Monotone Increasing
│ ├── Flip String to Monotone Increasing.cpp
│ └── README.md
├── 93. Restore IP Addresses
│ ├── README.md
│ └── Restore IP Addresses.cpp
└── 974. Subarray Sums Divisible by K
│ ├── README.md
│ └── Subarray Sums Divisible by K.cpp
├── README.md
└── The Blind 75 LeetCode Questions
├── README.md
└── solutions
├── 1. Two Sum
├── 1 - Two Sum.cpp
├── 2 - Two Sum.java
├── 3 - Two Sum.py
├── 4 - Two Sum.js
└── 5 - Two Sum.dart
├── 121. Best Time to Buy and Sell Stock
├── 1 - Best Time to Buy and Sell Stock.cpp
├── 2 - Best Time to Buy and Sell Stock.java
├── 3 - Best Time to Buy and Sell Stock.py
├── 4 - Best Time to Buy and Sell Stock.js
└── 5 - Best Time to Buy and Sell Stock.dart
└── 217. Contains Duplicate
├── 1 - Contains Duplicate.cpp
├── 2 - Contains Duplicate.java
├── 3 - Contains Duplicate.py
├── 4 - Contains Duplicate.js
└── 5 - Contains Duplicate.dart
/Easy/100. Same Tree/README.md:
--------------------------------------------------------------------------------
1 | # Same Tree
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/same-tree/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://www.youtube.com/watch?v=m_oZLz8tk8g)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | // C++
17 |
18 | /**
19 | * Definition for a binary tree node.
20 | * struct TreeNode {
21 | * int val;
22 | * TreeNode *left;
23 | * TreeNode *right;
24 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
25 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
26 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
27 | * };
28 | */
29 | class Solution {
30 | public:
31 | bool isSameTree(TreeNode* p, TreeNode* q) {
32 | if (!p && !q) return true;
33 | if (!p || !q) return false;
34 |
35 | return (
36 | p->val == q->val &&
37 | isSameTree(p->left, q->left) &&
38 | isSameTree(p->right, q->right)
39 | );
40 | }
41 | };
42 | ```
43 |
--------------------------------------------------------------------------------
/Easy/100. Same Tree/Same Tree.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 | * };
11 | */
12 | class Solution {
13 | public:
14 | bool isSameTree(TreeNode* p, TreeNode* q) {
15 | if (!p && !q) return true;
16 | if (!p || !q) return false;
17 |
18 | return (
19 | p->val == q->val &&
20 | isSameTree(p->left, q->left) &&
21 | isSameTree(p->right, q->right)
22 | );
23 | }
24 | };
25 |
--------------------------------------------------------------------------------
/Easy/104. Maximum Depth of Binary Tree/Maximum Depth of Binary Tree.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 | * };
11 | */
12 | class Solution {
13 | public:
14 | int maxDepth(TreeNode* root) {
15 | if (!root)
16 | return 0;
17 |
18 | return 1 + max(maxDepth(root->left), maxDepth(root->right));
19 | }
20 | };
21 |
--------------------------------------------------------------------------------
/Easy/104. Maximum Depth of Binary Tree/README.md:
--------------------------------------------------------------------------------
1 | # Maximum Depth of Binary Tree
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/maximum-depth-of-binary-tree/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/on_-LAV20L4)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | /**
17 | * Definition for a binary tree node.
18 | * struct TreeNode {
19 | * int val;
20 | * TreeNode *left;
21 | * TreeNode *right;
22 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
23 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
24 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
25 | * };
26 | */
27 | class Solution {
28 | public:
29 | int maxDepth(TreeNode* root) {
30 | if (!root)
31 | return 0;
32 |
33 | return 1 + max(maxDepth(root->left), maxDepth(root->right));
34 | }
35 | };
36 | ```
37 |
--------------------------------------------------------------------------------
/Easy/1071. Greatest Common Divisor of Strings/Greatest Common Divisor of Strings:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | string gcdOfStrings(string str1, string str2) {
4 | int sz = min(str1.size(), str2.size());
5 | string cur = "", divisor = "";
6 | for (int i = 0; i < sz; ++i) {
7 | cur += str1[i];
8 |
9 | if (isDivisor(cur, str1) && isDivisor(cur, str2))
10 | divisor = cur;
11 | }
12 |
13 | return divisor;
14 | }
15 |
16 | bool isDivisor(string &div, string &str) {
17 | string divisor = div;
18 | while (divisor.size() < str.size())
19 | divisor += div;
20 |
21 | return divisor == str;
22 | }
23 | };
24 |
--------------------------------------------------------------------------------
/Easy/1071. Greatest Common Divisor of Strings/README.md:
--------------------------------------------------------------------------------
1 | # Greatest Common Divisor of Strings
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/greatest-common-divisor-of-strings/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/611hikvil4Y)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | string gcdOfStrings(string str1, string str2) {
19 | int sz = min(str1.size(), str2.size());
20 | string cur = "", divisor = "";
21 | for (int i = 0; i < sz; ++i) {
22 | cur += str1[i];
23 |
24 | if (isDivisor(cur, str1) && isDivisor(cur, str2))
25 | divisor = cur;
26 | }
27 |
28 | return divisor;
29 | }
30 |
31 | bool isDivisor(string &div, string &str) {
32 | string divisor = div;
33 | while (divisor.size() < str.size())
34 | divisor += div;
35 |
36 | return divisor == str;
37 | }
38 | };
39 | ```
40 |
--------------------------------------------------------------------------------
/Easy/1137. N-th Tribonacci Number/N-th Tribonacci Number.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int tribonacci(int n) {
4 | vector seq(3);
5 | seq[1] = seq[2] = 1;
6 |
7 | for (int i = 3; i <= n; ++i)
8 | seq[i % 3] = seq[(i - 1) % 3] + seq[(i - 2) % 3] + seq[(i - 3) % 3];
9 |
10 | return seq[n % 3];
11 | }
12 | };
13 |
--------------------------------------------------------------------------------
/Easy/1137. N-th Tribonacci Number/README.md:
--------------------------------------------------------------------------------
1 | # N-th Tribonacci Number
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/n-th-tribonacci-number/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/KgewaEdfIt8)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | int tribonacci(int n) {
19 | vector seq(3);
20 | seq[1] = seq[2] = 1;
21 |
22 | for (int i = 3; i <= n; ++i)
23 | seq[i % 3] = seq[(i - 1) % 3] + seq[(i - 2) % 3] + seq[(i - 3) % 3];
24 |
25 | return seq[n % 3];
26 | }
27 | };
28 | ```
29 |
--------------------------------------------------------------------------------
/Easy/121. Best Time to Buy and Sell Stock/1 - Best Time to Buy and Sell Stock.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int maxProfit(vector& prices) {
4 | int minPrice = prices[0], maxProfit = 0;
5 |
6 | for (int &price : prices) {
7 | minPrice = min(minPrice, price);
8 | maxProfit = max(maxProfit, price - minPrice);
9 | }
10 |
11 | return maxProfit;
12 | }
13 | };
14 |
--------------------------------------------------------------------------------
/Easy/121. Best Time to Buy and Sell Stock/2 - Best Time to Buy and Sell Stock.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int maxProfit(int[] prices) {
3 | int minPrice = prices[0], maxProfit = 0;
4 |
5 | for (int price : prices) {
6 | minPrice = Math.min(minPrice, price);
7 | maxProfit = Math.max(maxProfit, price - minPrice);
8 | }
9 |
10 | return maxProfit;
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/Easy/121. Best Time to Buy and Sell Stock/3 - Best Time to Buy and Sell Stock.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def maxProfit(self, prices: List[int]) -> int:
3 | minPrice, maxProfit = prices[0], 0
4 |
5 | for price in prices:
6 | minPrice = min(minPrice, price)
7 | maxProfit = max(maxProfit, price - minPrice)
8 |
9 | return maxProfit
10 |
--------------------------------------------------------------------------------
/Easy/121. Best Time to Buy and Sell Stock/4 - Best Time to Buy and Sell Stock.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} prices
3 | * @return {number}
4 | */
5 | var maxProfit = function(prices) {
6 | let minPrice = prices[0], maxProfit = 0;
7 |
8 | for (const price of prices) {
9 | minPrice = Math.min(minPrice, price);
10 | maxProfit = Math.max(maxProfit, price - minPrice);
11 | }
12 |
13 | return maxProfit;
14 | };
15 |
--------------------------------------------------------------------------------
/Easy/121. Best Time to Buy and Sell Stock/README.md:
--------------------------------------------------------------------------------
1 | # Best Time to Buy and Sell Stock
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/7saQ5sIuG7A)
10 |
--------------------------------------------------------------------------------
/Easy/1470. Shuffle the Array/README.md:
--------------------------------------------------------------------------------
1 | # Shuffle the Array
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/shuffle-the-array/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/rtq9T_cq_YQ)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | vector shuffle(vector& nums, int n) {
19 | vector res(n << 1);
20 | int x = 0, y = n, idx = 0;
21 |
22 | while (idx < (n << 1)) {
23 | res[idx++] = nums[x++];
24 | res[idx++] = nums[y++];
25 | }
26 |
27 | return res;
28 | }
29 | };
30 | ```
31 |
--------------------------------------------------------------------------------
/Easy/1470. Shuffle the Array/Shuffle the Array.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector shuffle(vector& nums, int n) {
4 | vector res(n << 1);
5 | int x = 0, y = n, idx = 0;
6 |
7 | while (idx < (n << 1)) {
8 | res[idx++] = nums[x++];
9 | res[idx++] = nums[y++];
10 | }
11 |
12 | return res;
13 | }
14 | };
15 |
--------------------------------------------------------------------------------
/Easy/1523. Count Odd Numbers in an Interval Range/Count Odd Numbers in an Interval Range.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int countOdds(int low, int high) {
4 | return ((high + 1) >> 1) - (low >> 1);
5 | }
6 | };
7 |
--------------------------------------------------------------------------------
/Easy/1523. Count Odd Numbers in an Interval Range/README.md:
--------------------------------------------------------------------------------
1 | # Count Odd Numbers in an Interval Range
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/ze_-jOFHcBw)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | int countOdds(int low, int high) {
19 | return ((high + 1) >> 1) - (low >> 1);
20 | }
21 | };
22 | ```
23 |
--------------------------------------------------------------------------------
/Easy/1539. Kth Missing Positive Number/1 - Kth Missing Positive Numbercpp:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | class Solution {
3 | public:
4 | int findKthPositive(vector& arr, int k) {
5 | for (int num : arr) {
6 | if (num <= k)
7 | k++;
8 | else
9 | break;
10 | }
11 |
12 | return k;
13 | }
14 | };
15 |
16 | // solution - 2
17 | class Solution {
18 | public:
19 | int findKthPositive(vector& arr, int k) {
20 | int lo = 0, hi = arr.size() - 1;
21 | while (lo <= hi) {
22 | int mid = lo + (hi - lo >> 1);
23 |
24 | if (arr[mid] - mid - 1 < k)
25 | lo = mid + 1;
26 | else
27 | hi = mid - 1;
28 | }
29 | return lo + k;
30 | }
31 | };
32 |
--------------------------------------------------------------------------------
/Easy/1539. Kth Missing Positive Number/2 - Kth Missing Positive Number.java:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | class Solution {
3 | public int findKthPositive(int[] arr, int k) {
4 | for (int num : arr) {
5 | if (num <= k)
6 | k++;
7 | else
8 | break;
9 | }
10 |
11 | return k;
12 | }
13 | }
14 |
15 | // solution - 2
16 | class Solution {
17 | public int findKthPositive(int[] arr, int k) {
18 | int lo = 0, hi = arr.length - 1;
19 | while (lo <= hi) {
20 | int mid = lo + (hi - lo >> 1);
21 |
22 | if (arr[mid] - mid - 1 < k)
23 | lo = mid + 1;
24 | else
25 | hi = mid - 1;
26 | }
27 | return lo + k;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Easy/1539. Kth Missing Positive Number/3 - Kth Missing Positive Number.py:
--------------------------------------------------------------------------------
1 | # solution - 1
2 | class Solution:
3 | def findKthPositive(self, arr: List[int], k: int) -> int:
4 | for num in arr:
5 | if num <= k:
6 | k += 1
7 | else:
8 | break
9 |
10 | return k
11 |
12 |
13 | # solution - 2
14 | class Solution:
15 | def findKthPositive(self, arr: List[int], k: int) -> int:
16 | lo, hi = 0, len(arr) - 1
17 | while lo <= hi:
18 | mid = lo + (hi - lo >> 1)
19 |
20 | if arr[mid] - mid - 1 < k:
21 | lo = mid + 1
22 | else:
23 | hi = mid - 1
24 |
25 | return lo + k
26 |
--------------------------------------------------------------------------------
/Easy/1539. Kth Missing Positive Number/4 - Kth Missing Positive Number.js:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | /**
3 | * @param {number[]} arr
4 | * @param {number} k
5 | * @return {number}
6 | */
7 | var findKthPositive = function(arr, k) {
8 | for (let num of arr) {
9 | if (num <= k)
10 | k++;
11 | else
12 | break;
13 | }
14 |
15 | return k;
16 | };
17 |
18 | // solution - 2
19 | /**
20 | * @param {number[]} arr
21 | * @param {number} k
22 | * @return {number}
23 | */
24 | var findKthPositive = function(arr, k) {
25 | let lo = 0, hi = arr.length - 1;
26 | while (lo <= hi) {
27 | const mid = lo + (hi - lo >> 1);
28 |
29 | if (arr[mid] - mid - 1 < k)
30 | lo = mid + 1;
31 | else
32 | hi = mid - 1;
33 | }
34 | return lo + k;
35 | };
36 |
--------------------------------------------------------------------------------
/Easy/1539. Kth Missing Positive Number/README.md:
--------------------------------------------------------------------------------
1 | # Kth Missing Positive Number
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/kth-missing-positive-number/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/FEJ5frSSEeU)
10 |
--------------------------------------------------------------------------------
/Easy/226. Invert Binary Tree/1 - Invert Binary Tree.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 | * };
11 | */
12 | class Solution {
13 | public:
14 | TreeNode* invertTree(TreeNode* root) {
15 | if (!root)
16 | return root;
17 |
18 | swap(root->left, root->right);
19 | invertTree(root->left);
20 | invertTree(root->right);
21 |
22 | return root;
23 | }
24 | };
25 |
--------------------------------------------------------------------------------
/Easy/226. Invert Binary Tree/2 - Invert Binary Tree.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * function TreeNode(val, left, right) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.left = (left===undefined ? null : left)
6 | * this.right = (right===undefined ? null : right)
7 | * }
8 | */
9 | /**
10 | * @param {TreeNode} root
11 | * @return {TreeNode}
12 | */
13 | var invertTree = function(root) {
14 | const swap = (node) => {
15 | if (!node)
16 | return;
17 |
18 | [node.left, node.right] = [node.right, node.left];
19 |
20 | swap(node.left);
21 | swap(node.right);
22 | };
23 |
24 | swap(root);
25 |
26 | return root;
27 | };
28 |
--------------------------------------------------------------------------------
/Easy/226. Invert Binary Tree/README.md:
--------------------------------------------------------------------------------
1 | # Invert Binary Tree
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/invert-binary-tree/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/goJ5L5OJV8M)
10 |
11 |
12 |
13 | ## Code - C++
14 |
15 | ```cpp
16 | /**
17 | * Definition for a binary tree node.
18 | * struct TreeNode {
19 | * int val;
20 | * TreeNode *left;
21 | * TreeNode *right;
22 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
23 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
24 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
25 | * };
26 | */
27 | class Solution {
28 | public:
29 | TreeNode* invertTree(TreeNode* root) {
30 | if (!root)
31 | return root;
32 |
33 | swap(root->left, root->right);
34 | invertTree(root->left);
35 | invertTree(root->right);
36 |
37 | return root;
38 | }
39 | };
40 | ```
41 |
42 | ## Code - JS
43 | ```js
44 | /**
45 | * Definition for a binary tree node.
46 | * function TreeNode(val, left, right) {
47 | * this.val = (val===undefined ? 0 : val)
48 | * this.left = (left===undefined ? null : left)
49 | * this.right = (right===undefined ? null : right)
50 | * }
51 | */
52 | /**
53 | * @param {TreeNode} root
54 | * @return {TreeNode}
55 | */
56 | var invertTree = function(root) {
57 | const swap = (node) => {
58 | if (!node)
59 | return;
60 |
61 | [node.left, node.right] = [node.right, node.left];
62 |
63 | swap(node.left);
64 | swap(node.right);
65 | };
66 |
67 | swap(root);
68 |
69 | return root;
70 | };
71 | ```
72 |
--------------------------------------------------------------------------------
/Easy/35. Search Insert Position/1 - Search Insert Position.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int searchInsert(vector& nums, int target) {
4 | int lo = 0, hi = nums.size() - 1, mid;
5 | while (lo < hi) {
6 | mid = lo + (hi - lo) / 2;
7 |
8 | if (nums[mid] <= target)
9 | lo = mid;
10 | else
11 | hi = mid - 1;
12 | }
13 |
14 | return lo;
15 | }
16 | };
17 |
--------------------------------------------------------------------------------
/Easy/35. Search Insert Position/2 - Search Insert Position.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int searchInsert(vector& nums, int target) {
4 | return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
5 | }
6 | };
7 |
--------------------------------------------------------------------------------
/Easy/35. Search Insert Position/3 - Search Insert Position.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @param {number} target
4 | * @return {number}
5 | */
6 | var searchInsert = function(nums, target) {
7 | let lo = 0, hi = nums.length - 1;
8 | while (lo <= hi) {
9 | const mid = Math.floor((lo + hi) / 2);
10 | if (nums[mid] == target) return mid;
11 |
12 | if (nums[mid] < target)
13 | lo = mid + 1;
14 | else
15 | hi = mid - 1;
16 | }
17 | return lo;
18 | };
19 |
--------------------------------------------------------------------------------
/Easy/35. Search Insert Position/README.md:
--------------------------------------------------------------------------------
1 | # Search Insert Position
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/search-insert-position/description/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/pNxA8pUyVsI)
10 |
--------------------------------------------------------------------------------
/Easy/67. Add Binary/Add Binary.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | string addBinary(string a, string b) {
4 | int i = a.size() - 1, j = b.size() - 1;
5 | int sum = 0, carry = 0;
6 | string res = "";
7 |
8 | while (i >= 0 || j >= 0 || carry) {
9 | sum = carry;
10 | sum += i >= 0 ? a[i--] - '0' : 0;
11 | sum += j >= 0 ? b[j--] - '0' : 0;
12 |
13 | carry = sum > 1;
14 |
15 | res += to_string(sum % 2);
16 | }
17 |
18 | reverse(res.begin(), res.end());
19 |
20 | return res;
21 | }
22 | };
23 |
--------------------------------------------------------------------------------
/Easy/67. Add Binary/README.md:
--------------------------------------------------------------------------------
1 | # Add Binary
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/add-binary/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/Svca2XuIHug)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | string addBinary(string a, string b) {
19 | int i = a.size() - 1, j = b.size() - 1;
20 | int sum = 0, carry = 0;
21 | string res = "";
22 |
23 | while (i >= 0 || j >= 0 || carry) {
24 | sum = carry;
25 | sum += i >= 0 ? a[i--] - '0' : 0;
26 | sum += j >= 0 ? b[j--] - '0' : 0;
27 |
28 | carry = sum > 1;
29 |
30 | res += to_string(sum % 2);
31 | }
32 |
33 | reverse(res.begin(), res.end());
34 |
35 | return res;
36 | }
37 | };
38 | ```
39 |
--------------------------------------------------------------------------------
/Easy/783. Minimum Distance Between BST Nodes/1 - Minimum Distance Between BST Nodes.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 | * };
11 | */
12 | class Solution {
13 | private:
14 | vector values;
15 | public:
16 | int minDiffInBST(TreeNode* root) {
17 | inorderTraversal(root);
18 |
19 | int n = values.size(), minDiff = INT_MAX;
20 | for (int i = 1; i < n; ++i)
21 | minDiff = min(minDiff, values[i] - values[i - 1]);
22 |
23 | return minDiff;
24 | }
25 |
26 | void inorderTraversal(TreeNode* root) {
27 | if (!root)
28 | return;
29 |
30 | inorderTraversal(root->left);
31 | values.push_back(root->val);
32 | inorderTraversal(root->right);
33 | }
34 | };
35 |
--------------------------------------------------------------------------------
/Easy/783. Minimum Distance Between BST Nodes/2 - Minimum Distance Between BST Nodes.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 | * };
11 | */
12 | class Solution {
13 | private:
14 | int minDiff = INT_MAX;
15 | int preValue = -1;
16 | public:
17 | int minDiffInBST(TreeNode* root) {
18 | inorderTraversal(root);
19 |
20 | return minDiff;
21 | }
22 |
23 | void inorderTraversal(TreeNode* root) {
24 | if (!root)
25 | return;
26 |
27 | inorderTraversal(root->left);
28 |
29 | if (preValue != -1)
30 | minDiff = min(minDiff, root->val - preValue);
31 |
32 | preValue = root->val;
33 |
34 | inorderTraversal(root->right);
35 | }
36 | };
37 |
--------------------------------------------------------------------------------
/Easy/783. Minimum Distance Between BST Nodes/README.md:
--------------------------------------------------------------------------------
1 | # Minimum Distance Between BST Nodes
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/minimum-distance-between-bst-nodes/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/rAPvpq61iB8)
10 |
11 |
12 |
13 | ## code - 1
14 | ```cpp
15 | /**
16 | * Definition for a binary tree node.
17 | * struct TreeNode {
18 | * int val;
19 | * TreeNode *left;
20 | * TreeNode *right;
21 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
22 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
23 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
24 | * };
25 | */
26 | class Solution {
27 | private:
28 | vector values;
29 | public:
30 | int minDiffInBST(TreeNode* root) {
31 | inorderTraversal(root);
32 |
33 | int n = values.size(), minDiff = INT_MAX;
34 | for (int i = 1; i < n; ++i)
35 | minDiff = min(minDiff, values[i] - values[i - 1]);
36 |
37 | return minDiff;
38 | }
39 |
40 | void inorderTraversal(TreeNode* root) {
41 | if (!root)
42 | return;
43 |
44 | inorderTraversal(root->left);
45 | values.push_back(root->val);
46 | inorderTraversal(root->right);
47 | }
48 | };
49 | ```
50 |
51 | ## code - 2
52 | ```cpp
53 | /**
54 | * Definition for a binary tree node.
55 | * struct TreeNode {
56 | * int val;
57 | * TreeNode *left;
58 | * TreeNode *right;
59 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
60 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
61 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
62 | * };
63 | */
64 | class Solution {
65 | private:
66 | int minDiff = INT_MAX;
67 | int preValue = -1;
68 | public:
69 | int minDiffInBST(TreeNode* root) {
70 | inorderTraversal(root);
71 |
72 | return minDiff;
73 | }
74 |
75 | void inorderTraversal(TreeNode* root) {
76 | if (!root)
77 | return;
78 |
79 | inorderTraversal(root->left);
80 |
81 | if (preValue != -1)
82 | minDiff = min(minDiff, root->val - preValue);
83 |
84 | preValue = root->val;
85 |
86 | inorderTraversal(root->right);
87 | }
88 | };
89 | ```
90 |
--------------------------------------------------------------------------------
/Easy/953. Verifying an Alien Dictionary/README.md:
--------------------------------------------------------------------------------
1 | # Verifying an Alien Dictionary
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/verifying-an-alien-dictionary/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/bv9FCCnZbCw)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | bool isAlienSorted(vector& words, string order) {
19 | unordered_map weight;
20 | for (int i = 0; i < 26; ++i)
21 | weight[order[i]] = i;
22 |
23 | int n = words.size();
24 | for (int i = 1; i < n; ++i)
25 | if (compare(words[i - 1], words[i], weight))
26 | return false;
27 |
28 | return true;
29 | }
30 |
31 | // return true if w1 > w2
32 | bool compare(string &w1, string &w2, unordered_map &weight) {
33 | int sz = min(w1.size(), w2.size());
34 | for (int i = 0; i < sz; ++i)
35 | if (weight[w1[i]] != weight[w2[i]])
36 | return weight[w1[i]] > weight[w2[i]];
37 |
38 | return w1.size() > w2.size();
39 | }
40 | };
41 | ```
42 |
--------------------------------------------------------------------------------
/Easy/953. Verifying an Alien Dictionary/Verifying an Alien Dictionary.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool isAlienSorted(vector& words, string order) {
4 | unordered_map weight;
5 | for (int i = 0; i < 26; ++i)
6 | weight[order[i]] = i;
7 |
8 | int n = words.size();
9 | for (int i = 1; i < n; ++i)
10 | if (compare(words[i - 1], words[i], weight))
11 | return false;
12 |
13 | return true;
14 | }
15 |
16 | // return true if w1 > w2
17 | bool compare(string &w1, string &w2, unordered_map &weight) {
18 | int sz = min(w1.size(), w2.size());
19 | for (int i = 0; i < sz; ++i)
20 | if (weight[w1[i]] != weight[w2[i]])
21 | return weight[w1[i]] > weight[w2[i]];
22 |
23 | return w1.size() > w2.size();
24 | }
25 | };
26 |
--------------------------------------------------------------------------------
/Easy/989. Add to Array-Form of Integer/Add to Array-Form of Integer.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector addToArrayForm(vector& num, int k) {
4 | int n = num.size();
5 | for (int i = n - 1; i >= 0; --i) {
6 | num[i] += k;
7 | k = num[i] / 10;
8 | num[i] %= 10;
9 | }
10 |
11 | while (k) {
12 | num.insert(num.begin(), k % 10);
13 | k /= 10;
14 | }
15 |
16 | return num;
17 | }
18 | };
19 |
--------------------------------------------------------------------------------
/Easy/989. Add to Array-Form of Integer/README.md:
--------------------------------------------------------------------------------
1 | # Add to Array-Form of Integer
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/add-to-array-form-of-integer/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/Xj3bzE7wcLo)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | vector addToArrayForm(vector& num, int k) {
19 | int n = num.size();
20 | for (int i = n - 1; i >= 0; --i) {
21 | num[i] += k;
22 | k = num[i] / 10;
23 | num[i] %= 10;
24 | }
25 |
26 | while (k) {
27 | num.insert(num.begin(), k % 10);
28 | k /= 10;
29 | }
30 |
31 | return num;
32 | }
33 | };
34 | ```
35 |
--------------------------------------------------------------------------------
/Easy/997. Find the Town Judge/Find the Town Judge.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findJudge(int n, vector>& trust) {
4 | vector trusted(n + 1);
5 | for (auto &vc : trust) {
6 | trusted[vc[0]]--;
7 | trusted[vc[1]]++;
8 | }
9 |
10 | for (int i = 1; i <= n; ++i)
11 | if (trusted[i] == n - 1)
12 | return i;
13 |
14 | return -1;
15 | }
16 | };
17 |
--------------------------------------------------------------------------------
/Easy/997. Find the Town Judge/README.md:
--------------------------------------------------------------------------------
1 | # Find the Town Judge
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/find-the-town-judge/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/9awmbPLGkTU)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | int findJudge(int n, vector>& trust) {
19 | vector trusted(n + 1);
20 | for (auto &vc : trust) {
21 | trusted[vc[0]]--;
22 | trusted[vc[1]]++;
23 | }
24 |
25 | for (int i = 1; i <= n; ++i)
26 | if (trusted[i] == n - 1)
27 | return i;
28 |
29 | return -1;
30 | }
31 | };
32 | ```
33 |
--------------------------------------------------------------------------------
/Hard/1345. Jump Game IV/1 - Jump Game IV.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int minJumps(vector& arr) {
4 | int n = arr.size();
5 | unordered_map> idxs;
6 |
7 | for (int i = 0; i < n; ++i)
8 | idxs[arr[i]].push_back(i);
9 |
10 | return BFS(n, idxs, arr);
11 | }
12 |
13 | int BFS(int n, unordered_map>& idxs, vector& arr) {
14 | queue qu;
15 | qu.push(0);
16 |
17 | vector vis(n);
18 | vis[0] = true;
19 |
20 | int steps = 0;
21 | while (!qu.empty()) {
22 | int level = qu.size();
23 | while (level--) {
24 | int idx = qu.front();
25 | qu.pop();
26 |
27 | if (idx == n - 1)
28 | return steps;
29 |
30 | vector& nxtIdxs = idxs[arr[idx]];
31 | nxtIdxs.push_back(idx - 1);
32 | nxtIdxs.push_back(idx + 1);
33 |
34 | for (int nxt : nxtIdxs) {
35 | if (nxt >= 0 && nxt < n && !vis[nxt]) {
36 | qu.push(nxt);
37 | vis[nxt] = true;
38 | }
39 | }
40 |
41 | nxtIdxs.clear();
42 | }
43 |
44 | steps++;
45 | }
46 |
47 | return -1;
48 | }
49 | };
50 |
--------------------------------------------------------------------------------
/Hard/1345. Jump Game IV/2 - Jump Game IV.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int minJumps(int[] arr) {
3 | int n = arr.length;
4 | Map> idxs = new HashMap<>();
5 |
6 | for (int i = 0; i < n; ++i)
7 | idxs.computeIfAbsent(arr[i], v -> new ArrayList<>()).add(i);
8 |
9 | return BFS(n, idxs, arr);
10 | }
11 |
12 | int BFS(int n, Map> idxs, int[] arr) {
13 | Queue qu = new LinkedList<>();
14 | qu.add(0);
15 |
16 | boolean[] vis = new boolean[n];
17 | vis[0] = true;
18 |
19 | int steps = 0;
20 | while (!qu.isEmpty()) {
21 | int level = qu.size();
22 | while (level-- > 0) {
23 | int idx = qu.poll();
24 |
25 | if (idx == n - 1)
26 | return steps;
27 |
28 | List nxtIdxs = idxs.get(arr[idx]);
29 | nxtIdxs.add(idx - 1);
30 | nxtIdxs.add(idx + 1);
31 |
32 | for (int nxt : nxtIdxs) {
33 | if (nxt >= 0 && nxt < n && !vis[nxt]) {
34 | qu.add(nxt);
35 | vis[nxt] = true;
36 | }
37 | }
38 |
39 | nxtIdxs.clear();
40 | }
41 |
42 | steps++;
43 | }
44 |
45 | return -1;
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/Hard/1345. Jump Game IV/3 - Jump Game IV.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minJumps(self, arr: List[int]) -> int:
3 | n = len(arr)
4 | idxs = defaultdict(list)
5 |
6 | for i in range(n):
7 | idxs[arr[i]].append(i)
8 |
9 | return self.BFS(n, idxs, arr)
10 |
11 | def BFS(self, n, idxs, arr):
12 | qu = deque()
13 | qu.append(0)
14 |
15 | vis = [False] * n
16 | vis[0] = True
17 |
18 | steps = 0;
19 | while qu:
20 | level = len(qu)
21 | for i in range(level):
22 | idx = qu.popleft()
23 |
24 | if idx == n - 1:
25 | return steps
26 |
27 | nxtIdxs = idxs[arr[idx]]
28 | nxtIdxs.append(idx - 1)
29 | nxtIdxs.append(idx + 1)
30 |
31 | for nxt in nxtIdxs:
32 | if nxt >= 0 and nxt < n and not vis[nxt]:
33 | qu.append(nxt)
34 | vis[nxt] = True
35 |
36 | nxtIdxs.clear()
37 |
38 | steps += 1
39 |
40 | return -1
41 |
--------------------------------------------------------------------------------
/Hard/1345. Jump Game IV/4 - Jump Game IV.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} arr
3 | * @return {number}
4 | */
5 | var minJumps = function(arr) {
6 | const n = arr.length;
7 | const idxs = {};
8 |
9 | for (let i = 0; i < n; ++i)
10 | if (idxs[arr[i]])
11 | idxs[arr[i]].push(i);
12 | else
13 | idxs[arr[i]] = [i];
14 |
15 | return BFS(n, idxs, arr);
16 | };
17 |
18 | const BFS = (n, idxs, arr) => {
19 | const qu = [0];
20 |
21 | const vis = Array(n).fill(false);
22 | vis[0] = true;
23 |
24 | let steps = 0;
25 | while (qu.length) {
26 | let level = qu.length;
27 | while (level--) {
28 | const idx = qu.shift();
29 |
30 | if (idx == n - 1)
31 | return steps;
32 |
33 |
34 | idxs[arr[idx]].push(idx - 1);
35 | idxs[arr[idx]].push(idx + 1);
36 |
37 | for (const nxt of idxs[arr[idx]]) {
38 | if (nxt >= 0 && nxt < n && !vis[nxt]) {
39 | qu.push(nxt);
40 | vis[nxt] = true;
41 | }
42 | }
43 |
44 | idxs[arr[idx]] = [];
45 | }
46 |
47 | steps++;
48 | }
49 |
50 | return -1;
51 | };
52 |
--------------------------------------------------------------------------------
/Hard/1345. Jump Game IV/README.md:
--------------------------------------------------------------------------------
1 | # 1345. Jump Game IV
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/jump-game-iv/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/21G-27YHDdY)
10 |
--------------------------------------------------------------------------------
/Hard/1675. Minimize Deviation in Array/1 - Minimize Deviation in Array.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int minimumDeviation(vector& nums) {
4 | int mn = INT_MAX;
5 | priority_queue pq;
6 |
7 | for (int &num : nums) {
8 | if (num & 1)
9 | num <<= 1;
10 |
11 | mn = min(mn, num);
12 | pq.push(num);
13 | }
14 |
15 | int res = INT_MAX;
16 | while (true) {
17 | int mx = pq.top();
18 | pq.pop();
19 |
20 | res = min(res, mx - mn);
21 |
22 | if (mx & 1)
23 | break;
24 |
25 | mn = min(mn, mx >> 1);
26 | pq.push(mx >> 1);
27 | }
28 |
29 | return res;
30 | }
31 | };
32 |
--------------------------------------------------------------------------------
/Hard/1675. Minimize Deviation in Array/2 - Minimize Deviation in Array.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int minimumDeviation(int[] nums) {
3 | int min = Integer.MAX_VALUE;
4 | PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder());
5 |
6 | for (int num : nums) {
7 | if ((num & 1) == 1)
8 | num <<= 1;
9 |
10 | min = Math.min(min, num);
11 | pq.add(num);
12 | }
13 |
14 | int res = Integer.MAX_VALUE;
15 | while (true) {
16 | int max = pq.poll();
17 |
18 | res = Math.min(res, max - min);
19 |
20 | if ((max & 1) == 1)
21 | break;
22 |
23 | min = Math.min(min, max >> 1);
24 | pq.add(max >> 1);
25 | }
26 |
27 | return res;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/Hard/1675. Minimize Deviation in Array/3 - Minimize Deviation in Array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minimumDeviation(self, nums: List[int]) -> int:
3 | mn = 2000000000
4 | pq = []
5 |
6 | for num in nums:
7 | if num & 1:
8 | num <<= 1
9 |
10 | mn = min(mn, num)
11 | heappush(pq, -num)
12 |
13 | res = 2000000000
14 | while True:
15 | mx = -heappop(pq)
16 |
17 | res = min(res, mx - mn)
18 |
19 | if mx & 1:
20 | break
21 |
22 | mn = min(mn, mx >> 1)
23 | heappush(pq, -(mx >> 1))
24 |
25 | return res
26 |
--------------------------------------------------------------------------------
/Hard/1675. Minimize Deviation in Array/4 - Minimize Deviation in Array.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number}
4 | */
5 | var minimumDeviation = function(nums) {
6 | let min = Infinity;
7 | const pq = new MaxPriorityQueue();
8 |
9 | for (let num of nums) {
10 | if (num & 1)
11 | num <<= 1;
12 |
13 | min = Math.min(min, num);
14 | pq.enqueue(num);
15 | }
16 |
17 | let res = Infinity;
18 | while (true) {
19 | let max = pq.dequeue().priority;
20 |
21 | res = Math.min(res, max - min);
22 |
23 | if (max & 1)
24 | break;
25 |
26 | min = Math.min(min, max >> 1);
27 | pq.enqueue(max >> 1);
28 | }
29 |
30 | return res;
31 | };
32 |
--------------------------------------------------------------------------------
/Hard/1675. Minimize Deviation in Array/README.md:
--------------------------------------------------------------------------------
1 | # Minimize Deviation in Array
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/minimize-deviation-in-array/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/O5b8QIV2Gic)
10 |
--------------------------------------------------------------------------------
/Hard/2246. Longest Path With Different Adjacent Characters/Longest Path With Different Adjacent Characters.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int longestPath(vector& parent, string s) {
4 | int n = parent.size();
5 | vector> tree(n);
6 | for (int i = 1; i < n; ++i)
7 | tree[parent[i]].push_back(i);
8 |
9 | int globalMax = 0;
10 | DFS(0, globalMax, tree, s);
11 | return globalMax;
12 | }
13 |
14 | int DFS(int node, int &globalMax, vector> &tree, string &s) {
15 | priority_queue, greater> max2;
16 | max2.push(0); max2.push(0);
17 |
18 | for (auto &child : tree[node]) {
19 | int maxFromChild = DFS(child, globalMax, tree, s);
20 |
21 | if (s[child] != s[node]) {
22 | max2.push(maxFromChild);
23 | max2.pop();
24 | }
25 | }
26 |
27 | int secondMax = max2.top(); max2.pop();
28 | int firstMax = max2.top(); max2.pop();
29 | globalMax = max(globalMax, 1 + firstMax + secondMax);
30 |
31 | return 1 + firstMax;
32 | }
33 | };
34 |
--------------------------------------------------------------------------------
/Hard/2246. Longest Path With Different Adjacent Characters/README.md:
--------------------------------------------------------------------------------
1 | # Longest Path With Different Adjacent Characters
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/longest-path-with-different-adjacent-characters/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://www.youtube.com/watch?v=tQADaLkER2I)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | // C++
17 |
18 | class Solution {
19 | public:
20 | int longestPath(vector& parent, string s) {
21 | int n = parent.size();
22 | vector> tree(n);
23 | for (int i = 1; i < n; ++i)
24 | tree[parent[i]].push_back(i);
25 |
26 | int globalMax = 0;
27 | DFS(0, globalMax, tree, s);
28 | return globalMax;
29 | }
30 |
31 | int DFS(int node, int &globalMax, vector> &tree, string &s) {
32 | priority_queue, greater> max2;
33 | max2.push(0); max2.push(0);
34 |
35 | for (auto &child : tree[node]) {
36 | int maxFromChild = DFS(child, globalMax, tree, s);
37 |
38 | if (s[child] != s[node]) {
39 | max2.push(maxFromChild);
40 | max2.pop();
41 | }
42 | }
43 |
44 | int secondMax = max2.top(); max2.pop();
45 | int firstMax = max2.top(); max2.pop();
46 | globalMax = max(globalMax, 1 + firstMax + secondMax);
47 |
48 | return 1 + firstMax;
49 | }
50 | };
51 | ```
52 |
--------------------------------------------------------------------------------
/Hard/2306. Naming a Company/2306. Naming a Company.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | long long distinctNames(vector& ideas) {
4 | vector> groups(26);
5 | for (auto &idea : ideas)
6 | groups[idea[0] - 'a'].insert(idea.substr(1));
7 |
8 | long long numOfNames = 0;
9 | for (int i = 0; i < 26; ++i) {
10 | for (int j = i + 1; j < 26; ++j) {
11 | int numOfSuffixes = 0;
12 | for (auto &idea : groups[i])
13 | numOfSuffixes += groups[j].count(idea);
14 |
15 | numOfNames += 2LL * (groups[i].size() - numOfSuffixes) * (groups[j].size() - numOfSuffixes);
16 | }
17 | }
18 |
19 | return numOfNames;
20 | }
21 | };
22 |
--------------------------------------------------------------------------------
/Hard/2306. Naming a Company/README.md:
--------------------------------------------------------------------------------
1 | # Naming a Company
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/naming-a-company/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/LJG_o25WVWM)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | long long distinctNames(vector& ideas) {
19 | vector> groups(26);
20 | for (auto &idea : ideas)
21 | groups[idea[0] - 'a'].insert(idea.substr(1));
22 |
23 | long long numOfNames = 0;
24 | for (int i = 0; i < 26; ++i) {
25 | for (int j = i + 1; j < 26; ++j) {
26 | int numOfSuffixes = 0;
27 | for (auto &idea : groups[i])
28 | numOfSuffixes += groups[j].count(idea);
29 |
30 | numOfNames += 2LL * (groups[i].size() - numOfSuffixes) * (groups[j].size() - numOfSuffixes);
31 | }
32 | }
33 |
34 | return numOfNames;
35 | }
36 | };
37 | ```
38 |
--------------------------------------------------------------------------------
/Hard/2421. Number of Good Paths/Number of Good Paths.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private:
3 | struct DSU {
4 | vector par, sz;
5 | int cnt;
6 |
7 | void init(int n) {
8 | par = vector(n);
9 | iota(par.begin(), par.end(), 0);
10 |
11 | sz = vector(n, 1);
12 | cnt = n;
13 | }
14 |
15 | int find(int x) {
16 | if (par[x] == x) return x;
17 | return par[x] = find(par[x]);
18 | }
19 |
20 | void merge(int u, int v) {
21 | u = find(u);
22 | v = find(v);
23 | if (u == v) return;
24 |
25 | if (sz[u] < sz[v]) swap(u, v);
26 | par[v] = u;
27 | sz[u] += sz[v];
28 | cnt--;
29 | }
30 | };
31 | public:
32 | int numberOfGoodPaths(vector& vals, vector>& edges) {
33 | int n = vals.size();
34 |
35 | vector> tree(n);
36 | for (auto &edge : edges) {
37 | if (vals[edge[0]] >= vals[edge[1]])
38 | tree[edge[0]].push_back(edge[1]);
39 | else
40 | tree[edge[1]].push_back(edge[0]);
41 | }
42 |
43 | map> nodesHasSameValue;
44 | for (int i = 0; i < n; ++i)
45 | nodesHasSameValue[vals[i]].push_back(i);
46 |
47 | DSU dsu;
48 | dsu.init(n);
49 |
50 | int numOfPathes = 0;
51 | for (auto &[value, nodes] : nodesHasSameValue) {
52 | for (auto &node : nodes)
53 | for (auto &child : tree[node])
54 | dsu.merge(node, child);
55 |
56 | unordered_map component;
57 | for (auto &node : nodes)
58 | component[dsu.find(node)]++;
59 |
60 | numOfPathes += nodes.size();
61 |
62 | for (auto &[xx, cnt] : component)
63 | numOfPathes += cnt * (cnt - 1) / 2;
64 | }
65 |
66 | return numOfPathes;
67 | }
68 | };
69 |
--------------------------------------------------------------------------------
/Hard/2421. Number of Good Paths/README.md:
--------------------------------------------------------------------------------
1 | # 2421. Number of Good Paths
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/number-of-good-paths/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/ShcXjwJhM0k)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | private:
18 | struct DSU {
19 | vector par, sz;
20 | int cnt;
21 |
22 | void init(int n) {
23 | par = vector(n);
24 | iota(par.begin(), par.end(), 0);
25 |
26 | sz = vector(n, 1);
27 | cnt = n;
28 | }
29 |
30 | int find(int x) {
31 | if (par[x] == x) return x;
32 | return par[x] = find(par[x]);
33 | }
34 |
35 | void merge(int u, int v) {
36 | u = find(u);
37 | v = find(v);
38 | if (u == v) return;
39 |
40 | if (sz[u] < sz[v]) swap(u, v);
41 | par[v] = u;
42 | sz[u] += sz[v];
43 | cnt--;
44 | }
45 | };
46 | public:
47 | int numberOfGoodPaths(vector& vals, vector>& edges) {
48 | int n = vals.size();
49 |
50 | vector> tree(n);
51 | for (auto &edge : edges) {
52 | if (vals[edge[0]] >= vals[edge[1]])
53 | tree[edge[0]].push_back(edge[1]);
54 | else
55 | tree[edge[1]].push_back(edge[0]);
56 | }
57 |
58 | map> nodesHasSameValue;
59 | for (int i = 0; i < n; ++i)
60 | nodesHasSameValue[vals[i]].push_back(i);
61 |
62 | DSU dsu;
63 | dsu.init(n);
64 |
65 | int numOfPathes = 0;
66 | for (auto &[value, nodes] : nodesHasSameValue) {
67 | for (auto &node : nodes)
68 | for (auto &child : tree[node])
69 | dsu.merge(node, child);
70 |
71 | unordered_map component;
72 | for (auto &node : nodes)
73 | component[dsu.find(node)]++;
74 |
75 | numOfPathes += nodes.size();
76 |
77 | for (auto &[xx, cnt] : component)
78 | numOfPathes += cnt * (cnt - 1) / 2;
79 | }
80 |
81 | return numOfPathes;
82 | }
83 | };
84 | ```
85 |
--------------------------------------------------------------------------------
/Hard/2444. Count Subarrays With Fixed Bounds/1 - Count Subarrays With Fixed Bounds.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | long long countSubarrays(vector& nums, int minK, int maxK) {
4 | int n = nums.size();
5 | long long res = 0;
6 | int minPos = -1, maxPos = -1, leftBound = -1;
7 |
8 | for (int i = 0; i < n; ++i) {
9 | if (nums[i] < minK || nums[i] > maxK)
10 | leftBound = i;
11 |
12 | if (nums[i] == minK)
13 | minPos = i;
14 |
15 | if (nums[i] == maxK)
16 | maxPos = i;
17 |
18 | res += max(0, min(maxPos, minPos) - leftBound);
19 | }
20 |
21 | return res;
22 | }
23 | };
24 |
--------------------------------------------------------------------------------
/Hard/2444. Count Subarrays With Fixed Bounds/2 - Count Subarrays With Fixed Bounds.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public long countSubarrays(int[] nums, int minK, int maxK) {
3 | int n = nums.length;
4 | long res = 0;
5 | int minPos = -1, maxPos = -1, leftBound = -1;
6 |
7 | for (int i = 0; i < n; ++i) {
8 | if (nums[i] < minK || nums[i] > maxK)
9 | leftBound = i;
10 |
11 | if (nums[i] == minK)
12 | minPos = i;
13 |
14 | if (nums[i] == maxK)
15 | maxPos = i;
16 |
17 | res += Math.max(0, Math.min(maxPos, minPos) - leftBound);
18 | }
19 |
20 | return res;
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/Hard/2444. Count Subarrays With Fixed Bounds/3 - Count Subarrays With Fixed Bounds.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def countSubarrays(self, nums: List[int], minK: int, maxK: int) -> int:
3 | n, res = len(nums), 0
4 | minPos = maxPos = leftBound = -1
5 |
6 | for i in range(n):
7 | if nums[i] < minK or nums[i] > maxK:
8 | leftBound = i
9 |
10 | if nums[i] == minK:
11 | minPos = i
12 |
13 | if nums[i] == maxK:
14 | maxPos = i
15 |
16 | res += max(0, min(maxPos, minPos) - leftBound)
17 |
18 | return res
19 |
--------------------------------------------------------------------------------
/Hard/2444. Count Subarrays With Fixed Bounds/4 - Count Subarrays With Fixed Bounds.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @param {number} minK
4 | * @param {number} maxK
5 | * @return {number}
6 | */
7 | var countSubarrays = function(nums, minK, maxK) {
8 | const n = nums.length;
9 | let res = 0, minPos = -1, maxPos = -1, leftBound = -1;
10 |
11 | for (let i = 0; i < n; ++i) {
12 | if (nums[i] < minK || nums[i] > maxK)
13 | leftBound = i;
14 |
15 | if (nums[i] == minK)
16 | minPos = i;
17 |
18 | if (nums[i] == maxK)
19 | maxPos = i;
20 |
21 | res += Math.max(0, Math.min(maxPos, minPos) - leftBound);
22 | }
23 |
24 | return res;
25 | };
26 |
--------------------------------------------------------------------------------
/Hard/2444. Count Subarrays With Fixed Bounds/README.md:
--------------------------------------------------------------------------------
1 | # Count Subarrays With Fixed Bounds
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/count-subarrays-with-fixed-bounds/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/fkHpIESGLjA)
10 |
--------------------------------------------------------------------------------
/Hard/352. Data Stream as Disjoint Intervals/Data Stream as Disjoint Intervals.cpp:
--------------------------------------------------------------------------------
1 | class SummaryRanges {
2 | private:
3 | set nums;
4 | public:
5 | SummaryRanges() {
6 |
7 | }
8 |
9 | void addNum(int value) {
10 | nums.insert(value);
11 | }
12 |
13 | vector> getIntervals() {
14 | if (nums.empty()) return {};
15 |
16 | vector> intervals;
17 | int left = -1, right = -1;
18 | for (auto &num : nums) {
19 | if (left < 0)
20 | left = right = num;
21 | else if (num == right + 1)
22 | right = num;
23 | else {
24 | intervals.push_back({left, right});
25 | left = right = num;
26 | }
27 | }
28 | intervals.push_back({left, right});
29 |
30 | return intervals;
31 | }
32 | };
33 |
34 | /**
35 | * Your SummaryRanges object will be instantiated and called as such:
36 | * SummaryRanges* obj = new SummaryRanges();
37 | * obj->addNum(value);
38 | * vector> param_2 = obj->getIntervals();
39 | */
40 |
--------------------------------------------------------------------------------
/Hard/352. Data Stream as Disjoint Intervals/README.md:
--------------------------------------------------------------------------------
1 | # Data Stream as Disjoint Intervals
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/data-stream-as-disjoint-intervals/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/y-SBX7-1prc)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class SummaryRanges {
17 | private:
18 | set nums;
19 | public:
20 | SummaryRanges() {
21 |
22 | }
23 |
24 | void addNum(int value) {
25 | nums.insert(value);
26 | }
27 |
28 | vector> getIntervals() {
29 | if (nums.empty()) return {};
30 |
31 | vector> intervals;
32 | int left = -1, right = -1;
33 | for (auto &num : nums) {
34 | if (left < 0)
35 | left = right = num;
36 | else if (num == right + 1)
37 | right = num;
38 | else {
39 | intervals.push_back({left, right});
40 | left = right = num;
41 | }
42 | }
43 | intervals.push_back({left, right});
44 |
45 | return intervals;
46 | }
47 | };
48 |
49 | /**
50 | * Your SummaryRanges object will be instantiated and called as such:
51 | * SummaryRanges* obj = new SummaryRanges();
52 | * obj->addNum(value);
53 | * vector> param_2 = obj->getIntervals();
54 | */
55 | ```
56 |
--------------------------------------------------------------------------------
/Hard/460. LFU Cache/LFU Cache.cpp:
--------------------------------------------------------------------------------
1 | class LFUCache {
2 | int capacity, minFreq;
3 |
4 | struct Element {
5 | int value, fr;
6 | list::iterator it;
7 | };
8 |
9 | unordered_map cache;
10 | unordered_map > freq;
11 |
12 | public:
13 | LFUCache(int capacity) {
14 | this->capacity = capacity;
15 | }
16 |
17 | int get(int key) {
18 | if (!cache.count(key)) return -1;
19 |
20 | freq[cache[key].fr].erase(cache[key].it);
21 |
22 | cache[key].fr++;
23 | freq[cache[key].fr].push_back(key);
24 | cache[key].it = prev(freq[ cache[key].fr].end());
25 |
26 | minFreq += freq[minFreq].empty();
27 |
28 | return cache[key].value;
29 | }
30 |
31 | void put(int key, int value) {
32 | if (!capacity) return;
33 |
34 | if (get(key) != -1) {
35 | cache[key].value = value;
36 | return;
37 | }
38 |
39 | if (cache.size() == capacity){
40 | cache.erase(freq[minFreq].front());
41 | freq[minFreq].pop_front();
42 | }
43 |
44 | freq[1].push_back(key);
45 | cache[key] = {value, 1, prev(freq[1].end())};
46 | minFreq = 1;
47 | }
48 | };
49 |
50 | /**
51 | * Your LFUCache object will be instantiated and called as such:
52 | * LFUCache* obj = new LFUCache(capacity);
53 | * int param_1 = obj->get(key);
54 | * obj->put(key,value);
55 | */
56 |
--------------------------------------------------------------------------------
/Hard/460. LFU Cache/README.md:
--------------------------------------------------------------------------------
1 | # LFU Cache
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/lfu-cache/description/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/uyaOlNOTUA8)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class LFUCache {
17 | int capacity, minFreq;
18 |
19 | struct Element {
20 | int value, fr;
21 | list::iterator it;
22 | };
23 |
24 | unordered_map cache;
25 | unordered_map > freq;
26 |
27 | public:
28 | LFUCache(int capacity) {
29 | this->capacity = capacity;
30 | }
31 |
32 | int get(int key) {
33 | if (!cache.count(key)) return -1;
34 |
35 | freq[cache[key].fr].erase(cache[key].it);
36 |
37 | cache[key].fr++;
38 | freq[cache[key].fr].push_back(key);
39 | cache[key].it = prev(freq[ cache[key].fr].end());
40 |
41 | minFreq += freq[minFreq].empty();
42 |
43 | return cache[key].value;
44 | }
45 |
46 | void put(int key, int value) {
47 | if (!capacity) return;
48 |
49 | if (get(key) != -1) {
50 | cache[key].value = value;
51 | return;
52 | }
53 |
54 | if (cache.size() == capacity){
55 | cache.erase(freq[minFreq].front());
56 | freq[minFreq].pop_front();
57 | }
58 |
59 | freq[1].push_back(key);
60 | cache[key] = {value, 1, prev(freq[1].end())};
61 | minFreq = 1;
62 | }
63 | };
64 |
65 | /**
66 | * Your LFUCache object will be instantiated and called as such:
67 | * LFUCache* obj = new LFUCache(capacity);
68 | * int param_1 = obj->get(key);
69 | * obj->put(key,value);
70 | */
71 | ```
72 |
--------------------------------------------------------------------------------
/Hard/472. Concatenated Words/Concatenated Words.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private:
3 | unordered_set dictionary;
4 | unordered_map dp;
5 | public:
6 | vector findAllConcatenatedWordsInADict(vector& words) {
7 | dictionary = unordered_set(words.begin(), words.end());
8 |
9 | vector res;
10 | for (auto &word : words)
11 | if (numOfConcatenatedWords(word) > 1)
12 | res.push_back(word);
13 |
14 | return res;
15 | }
16 |
17 | int numOfConcatenatedWords(string word) {
18 | if (word.empty()) return 0;
19 | if (dp.count(word)) return dp[word];
20 |
21 | string curPrefix = "";
22 | int sz = word.size(), maxNumOfWords = INT_MIN;
23 | for (int i = 0; i < sz; ++i) {
24 | curPrefix += word[i];
25 |
26 | if (dictionary.count(curPrefix))
27 | maxNumOfWords = max(
28 | maxNumOfWords,
29 | 1 + numOfConcatenatedWords(word.substr(i + 1))
30 | );
31 | }
32 |
33 | return dp[word] = maxNumOfWords;
34 | }
35 | };
36 |
--------------------------------------------------------------------------------
/Hard/472. Concatenated Words/README.md:
--------------------------------------------------------------------------------
1 | # Concatenated Words
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/concatenated-words/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/ARFt1KUt1RQ)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | private:
18 | unordered_set dictionary;
19 | unordered_map dp;
20 | public:
21 | vector findAllConcatenatedWordsInADict(vector& words) {
22 | dictionary = unordered_set(words.begin(), words.end());
23 |
24 | vector res;
25 | for (auto &word : words)
26 | if (numOfConcatenatedWords(word) > 1)
27 | res.push_back(word);
28 |
29 | return res;
30 | }
31 |
32 | int numOfConcatenatedWords(string word) {
33 | if (word.empty()) return 0;
34 | if (dp.count(word)) return dp[word];
35 |
36 | string curPrefix = "";
37 | int sz = word.size(), maxNumOfWords = INT_MIN;
38 | for (int i = 0; i < sz; ++i) {
39 | curPrefix += word[i];
40 |
41 | if (dictionary.count(curPrefix))
42 | maxNumOfWords = max(
43 | maxNumOfWords,
44 | 1 + numOfConcatenatedWords(word.substr(i + 1))
45 | );
46 | }
47 |
48 | return dp[word] = maxNumOfWords;
49 | }
50 | };
51 | ```
52 |
--------------------------------------------------------------------------------
/Hard/502. IPO/1 - IPO.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int findMaximizedCapital(int k, int w, vector& profits, vector& capital) {
4 | int n = profits.size();
5 | vector> projects(n);
6 |
7 | for (int i = 0; i < n; ++i)
8 | projects[i] = {capital[i], profits[i]};
9 |
10 | sort(projects.rbegin(), projects.rend());
11 |
12 | priority_queue maxProfit;
13 | while (k--) {
14 | while (!projects.empty() && projects.back().first <= w) {
15 | maxProfit.push(projects.back().second);
16 | projects.pop_back();
17 | }
18 |
19 | if (maxProfit.empty())
20 | break;
21 |
22 | w += maxProfit.top();
23 | maxProfit.pop();
24 | }
25 |
26 | return w;
27 | }
28 | };
29 |
--------------------------------------------------------------------------------
/Hard/502. IPO/2 - IPO.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
3 | int n = profits.length;
4 | int[][] projects = new int[n][2];
5 |
6 | for (int i = 0; i < n; ++i) {
7 | projects[i][0] = capital[i];
8 | projects[i][1] = profits[i];
9 | }
10 |
11 | Arrays.sort(projects, (A, B) -> Integer.compare(A[0], B[0]));
12 |
13 | PriorityQueue maxProfit = new PriorityQueue<>(Collections.reverseOrder());
14 | int idx = 0;
15 | while (k-- > 0) {
16 | while (idx < n && projects[idx][0] <= w)
17 | maxProfit.add(projects[idx++][1]);
18 |
19 | if (maxProfit.isEmpty())
20 | break;
21 |
22 | w += maxProfit.poll();
23 | }
24 |
25 | return w;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Hard/502. IPO/3 - IPO.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
3 | n = len(profits)
4 |
5 | projects = [(capital[i], profits[i]) for i in range(n)]
6 | projects.sort()
7 |
8 | maxProfit = []
9 | idx = 0
10 | for _ in range(k):
11 | while idx < n and projects[idx][0] <= w:
12 | heappush(maxProfit, -projects[idx][1])
13 | idx += 1
14 |
15 | if not maxProfit:
16 | break
17 |
18 | w -= heappop(maxProfit)
19 |
20 | return w;
21 |
--------------------------------------------------------------------------------
/Hard/502. IPO/4 - IPO.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number} k
3 | * @param {number} w
4 | * @param {number[]} profits
5 | * @param {number[]} capital
6 | * @return {number}
7 | */
8 | var findMaximizedCapital = function(k, w, profits, capital) {
9 | const n = profits.length;
10 | let projects = [];
11 |
12 | for (let i = 0; i < n; ++i)
13 | projects.push([capital[i], profits[i]]);
14 |
15 | projects.sort((A, B) => A[0] - B[0]);
16 |
17 | let maxProfit = new MaxPriorityQueue();
18 | let idx = 0;
19 | while (k--) {
20 | while (idx < n && projects[idx][0] <= w)
21 | maxProfit.enqueue(projects[idx++][1]);
22 |
23 | if (maxProfit.isEmpty())
24 | break;
25 |
26 | w += maxProfit.dequeue().priority;
27 | }
28 |
29 | return w;
30 | };
31 |
--------------------------------------------------------------------------------
/Hard/502. IPO/README.md:
--------------------------------------------------------------------------------
1 | # IPO
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/ipo/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/IjddNQDZxWQ)
10 |
--------------------------------------------------------------------------------
/Hard/540. Single Element in a Sorted Array/1 - Single Element in a Sorted Array.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int singleNonDuplicate(vector& nums) {
4 | int n = nums.size();
5 |
6 | int lo = 0, hi = n / 2, res;
7 | while (lo <= hi) {
8 | int mid = lo + (hi - lo) / 2;
9 | int idx = mid * 2;
10 |
11 | if (idx + 1 >= n || nums[idx] != nums[idx + 1]) {
12 | res = nums[idx];
13 | hi = mid - 1;
14 | }
15 | else
16 | lo = mid + 1;
17 | }
18 |
19 | return res;
20 | }
21 | };
22 |
--------------------------------------------------------------------------------
/Hard/540. Single Element in a Sorted Array/2 - Single Element in a Sorted Array.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int singleNonDuplicate(int[] nums) {
3 | int n = nums.length;
4 | int lo = 0, hi = n / 2, res = -1;
5 |
6 | while (lo <= hi) {
7 | int mid = lo + (hi - lo) / 2;
8 | int idx = mid * 2;
9 |
10 | if (idx + 1 >= n || nums[idx] != nums[idx + 1]) {
11 | res = nums[idx];
12 | hi = mid - 1;
13 | }
14 | else
15 | lo = mid + 1;
16 | }
17 |
18 | return res;
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/Hard/540. Single Element in a Sorted Array/3 - Single Element in a Sorted Array.py:
--------------------------------------------------------------------------------
1 | class Solution(object):
2 | def singleNonDuplicate(self, nums):
3 | """
4 | :type nums: List[int]
5 | :rtype: int
6 | """
7 | n = len(nums);
8 | lo, hi, res = 0, n // 2, -1
9 |
10 | while lo <= hi:
11 | mid = lo + (hi - lo) // 2
12 | idx = mid * 2
13 |
14 | if idx + 1 >= n or nums[idx] != nums[idx + 1]:
15 | res = nums[idx];
16 | hi = mid - 1
17 | else:
18 | lo = mid + 1
19 |
20 | return res
21 |
--------------------------------------------------------------------------------
/Hard/540. Single Element in a Sorted Array/4 - Single Element in a Sorted Array.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} nums
3 | * @return {number}
4 | */
5 | var singleNonDuplicate = function(nums) {
6 | const n = nums.length;
7 | let lo = 0, hi = n >> 1, res = -1;
8 |
9 | while (lo <= hi) {
10 | const mid = lo + (hi - lo >> 1);
11 | const idx = mid << 1;
12 |
13 | if (idx + 1 >= n || nums[idx] != nums[idx + 1]) {
14 | res = nums[idx];
15 | hi = mid - 1;
16 | }
17 | else
18 | lo = mid + 1
19 | }
20 |
21 | return res
22 | };
23 |
--------------------------------------------------------------------------------
/Hard/540. Single Element in a Sorted Array/README.md:
--------------------------------------------------------------------------------
1 | # Single Element in a Sorted Array
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/single-element-in-a-sorted-array/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/FCZWPtMza8s)
10 |
--------------------------------------------------------------------------------
/Hard/72. Edit Distance/1 - Edit Distance.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int minDistance(string word1, string word2) {
4 | int n = word1.size(), m = word2.size();
5 | vector> dp(n + 1, vector(m + 1));
6 |
7 | for (int i = 0; i <= n; ++i) {
8 | for (int j = 0; j <= m; ++j) {
9 | if (!i || !j)
10 | dp[i][j] = i + j;
11 | else if (word1[i - 1] == word2[j - 1])
12 | dp[i][j] = dp[i - 1][j - 1];
13 | else
14 | dp[i][j] = 1 + min({
15 | dp[i][j - 1], // insert
16 | dp[i - 1][j], // delete
17 | dp[i - 1][j - 1] // replace
18 | });
19 | }
20 | }
21 |
22 | return dp[n][m];
23 | }
24 | };
25 |
--------------------------------------------------------------------------------
/Hard/72. Edit Distance/2 - Edit Distance.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int n, m;
4 | vector> dp;
5 |
6 | int minDistance(string word1, string word2) {
7 | n = word1.size(), m = word2.size();
8 | dp = vector>(n + 1, vector(m + 1, -1));
9 |
10 | return solve(n, m, word1, word2);
11 | }
12 |
13 | int solve(int i, int j, string &str1, string &str2) {
14 | if (!i || !j) return i + j;
15 |
16 | int &ret = dp[i][j];
17 | if (~ret) return ret;
18 |
19 | if (str1[i - 1] == str2[j - 1])
20 | return ret = solve(i - 1, j - 1, str1, str2);
21 |
22 | return ret = 1 + min({
23 | solve(i, j - 1, str1, str2), // insert
24 | solve(i - 1, j, str1, str2), // delete
25 | solve(i - 1, j - 1, str1, str2) // replace
26 | });
27 | }
28 | };
29 |
--------------------------------------------------------------------------------
/Hard/72. Edit Distance/3 - Edit Distance.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int minDistance(String word1, String word2) {
3 | int n = word1.length(), m = word2.length();
4 | int dp[][] = new int[n + 1][m + 1];
5 |
6 | for (int i = 0; i <= n; ++i) {
7 | for (int j = 0; j <= m; ++j) {
8 | if (i == 0 || j == 0)
9 | dp[i][j] = i + j;
10 | else if (word1.charAt(i - 1) == word2.charAt(j - 1))
11 | dp[i][j] = dp[i - 1][j - 1];
12 | else
13 | dp[i][j] = 1 + min(
14 | dp[i][j - 1], // insert
15 | dp[i - 1][j], // delete
16 | dp[i - 1][j - 1] // replace
17 | );
18 | }
19 | }
20 |
21 | return dp[n][m];
22 | }
23 |
24 | public int min(int x, int y, int z) {
25 | return Math.min(x, Math.min(y, z));
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/Hard/72. Edit Distance/4 - Edit Distance.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minDistance(self, word1: str, word2: str) -> int:
3 | n, m = len(word1), len(word2)
4 | dp = [[0] * (m + 1) for _ in range(n + 1)]
5 |
6 | for i in range(n + 1):
7 | for j in range(m + 1):
8 | if i == 0 or j == 0:
9 | dp[i][j] = i + j
10 | elif word1[i - 1] == word2[j - 1]:
11 | dp[i][j] = dp[i - 1][j - 1]
12 | else:
13 | dp[i][j] = 1 + min(
14 | dp[i][j - 1], # insert
15 | dp[i - 1][j], # delete
16 | dp[i - 1][j - 1] # replace
17 | )
18 |
19 | return dp[n][m];
20 |
--------------------------------------------------------------------------------
/Hard/72. Edit Distance/5 - Edit Distance.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {string} word1
3 | * @param {string} word2
4 | * @return {number}
5 | */
6 | var minDistance = function(word1, word2) {
7 | const n = word1.length, m = word2.length;
8 | const dp = new Array(n + 1).fill(0).map(item => new Array(m + 1).fill(0));
9 |
10 | for (let i = 0; i <= n; ++i) {
11 | for (let j = 0; j <= m; ++j) {
12 | if (!i || !j)
13 | dp[i][j] = i + j;
14 | else if (word1[i - 1] == word2[j - 1])
15 | dp[i][j] = dp[i - 1][j - 1];
16 | else
17 | dp[i][j] = 1 + Math.min(
18 | dp[i][j - 1], // insert
19 | dp[i - 1][j], // delete
20 | dp[i - 1][j - 1] // replace
21 | );
22 | }
23 | }
24 |
25 | return dp[n][m];
26 | };
27 |
--------------------------------------------------------------------------------
/Hard/72. Edit Distance/README.md:
--------------------------------------------------------------------------------
1 | # Edit Distance
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/edit-distance/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/rOHeIwyAO9g)
10 |
--------------------------------------------------------------------------------
/Medium/1011. Capacity To Ship Packages Within D Days/1 - Capacity To Ship Packages Within D Days.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int shipWithinDays(vector& weights, int days) {
4 | int totalWeights = 0, maxWeight = 0;
5 | for (auto &weight : weights) {
6 | totalWeights += weight;
7 | maxWeight = max(maxWeight, weight);
8 | }
9 |
10 | return BinarySearch(maxWeight, totalWeights, days, weights);
11 | }
12 |
13 | int BinarySearch(int lo, int hi, int days, vector &weights) {
14 | int res = 0;
15 | while (lo <= hi) {
16 | int mid = lo + (hi - lo >> 1);
17 |
18 | if (numOfDaysNeeded(mid, weights) <= days) {
19 | res = mid;
20 | hi = mid - 1;
21 | }
22 | else
23 | lo = mid + 1;
24 | }
25 |
26 | return res;
27 | }
28 |
29 | int numOfDaysNeeded(int capacity, vector &weights) {
30 | int days = 1, curCapacity = 0;
31 | for (auto &weight : weights) {
32 | if (curCapacity + weight > capacity) {
33 | days++;
34 | curCapacity = 0;
35 | }
36 |
37 | curCapacity += weight;
38 | }
39 |
40 | return days;
41 | }
42 | };
43 |
--------------------------------------------------------------------------------
/Medium/1011. Capacity To Ship Packages Within D Days/2 - Capacity To Ship Packages Within D Days.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int shipWithinDays(int[] weights, int days) {
3 | int totalWeights = 0, maxWeight = 0;
4 | for (int weight : weights) {
5 | totalWeights += weight;
6 | maxWeight = Math.max(maxWeight, weight);
7 | }
8 |
9 | return BinarySearch(maxWeight, totalWeights, days, weights);
10 | }
11 |
12 | private int BinarySearch(int lo, int hi, int days, int[] weights) {
13 | int res = 0;
14 | while (lo <= hi) {
15 | int mid = lo + (hi - lo >> 1);
16 |
17 | if (numOfDaysNeeded(mid, weights) <= days) {
18 | res = mid;
19 | hi = mid - 1;
20 | }
21 | else
22 | lo = mid + 1;
23 | }
24 |
25 | return res;
26 | }
27 |
28 | private int numOfDaysNeeded(int capacity, int[] weights) {
29 | int days = 1, curCapacity = 0;
30 | for (int weight : weights) {
31 | if (curCapacity + weight > capacity) {
32 | days++;
33 | curCapacity = 0;
34 | }
35 |
36 | curCapacity += weight;
37 | }
38 |
39 | return days;
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/Medium/1011. Capacity To Ship Packages Within D Days/3 - Capacity To Ship Packages Within D Days.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def shipWithinDays(self, weights: List[int], days: int) -> int:
3 | lo, hi, res = max(weights), sum(weights), 0
4 | while lo <= hi:
5 | mid = lo + (hi - lo >> 1)
6 |
7 | if self.numOfDaysNeeded(mid, weights) <= days:
8 | res = mid
9 | hi = mid - 1
10 | else:
11 | lo = mid + 1;
12 |
13 | return res
14 |
15 |
16 | def numOfDaysNeeded(self, capacity, weights):
17 | days, curCapacity= 1, 0
18 | for weight in weights:
19 | if curCapacity + weight > capacity:
20 | days += 1
21 | curCapacity = 0
22 |
23 | curCapacity += weight
24 |
25 | return days
26 |
--------------------------------------------------------------------------------
/Medium/1011. Capacity To Ship Packages Within D Days/4 - Capacity To Ship Packages Within D Days.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} weights
3 | * @param {number} days
4 | * @return {number}
5 | */
6 | var shipWithinDays = function(weights, days) {
7 | let totalWeights = 0, maxWeight = 0;
8 | for (const weight of weights) {
9 | totalWeights += weight;
10 | maxWeight = Math.max(maxWeight, weight);
11 | }
12 |
13 | return BinarySearch(maxWeight, totalWeights, days, weights);
14 | };
15 |
16 | const BinarySearch = (lo, hi, days, weights) => {
17 | let res = 0;
18 | while (lo <= hi) {
19 | const mid = lo + (hi - lo >> 1);
20 |
21 | if (numOfDaysNeeded(mid, weights) <= days) {
22 | res = mid;
23 | hi = mid - 1;
24 | }
25 | else
26 | lo = mid + 1;
27 | }
28 |
29 | return res;
30 | }
31 |
32 | const numOfDaysNeeded = (capacity, weights) => {
33 | let days = 1, curCapacity = 0;
34 | for (const weight of weights) {
35 | if (curCapacity + weight > capacity) {
36 | days++;
37 | curCapacity = 0;
38 | }
39 |
40 | curCapacity += weight;
41 | }
42 |
43 | return days;
44 | }
45 |
--------------------------------------------------------------------------------
/Medium/1011. Capacity To Ship Packages Within D Days/README.md:
--------------------------------------------------------------------------------
1 | # Capacity To Ship Packages Within D Days
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/YaUbxrMnLwA)
10 |
--------------------------------------------------------------------------------
/Medium/103. Binary Tree Zigzag Level Order Traversal/1 - Binary Tree Zigzag Level Order Traversal.cpp:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * struct TreeNode {
4 | * int val;
5 | * TreeNode *left;
6 | * TreeNode *right;
7 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
8 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10 | * };
11 | */
12 | class Solution {
13 | public:
14 | vector> zigzagLevelOrder(TreeNode* root) {
15 | if (!root)
16 | return {};
17 |
18 | vector> res;
19 |
20 | queue qu;
21 | qu.push(root);
22 |
23 | bool rightToLeft = false;
24 |
25 | while (!qu.empty()) {
26 | vector curLevel;
27 |
28 | int sz = qu.size();
29 | for (int i = 0; i < sz; ++i) {
30 | auto node = qu.front();
31 | qu.pop();
32 |
33 | curLevel.push_back(node->val);
34 |
35 | if (node->left) qu.push(node->left);
36 | if (node->right) qu.push(node->right);
37 | }
38 |
39 | if (rightToLeft)
40 | reverse(curLevel.begin(), curLevel.end());
41 |
42 | rightToLeft = !rightToLeft;
43 |
44 | res.push_back(curLevel);
45 | }
46 |
47 | return res;
48 | }
49 | };
50 |
--------------------------------------------------------------------------------
/Medium/103. Binary Tree Zigzag Level Order Traversal/2 - Binary Tree Zigzag Level Order Traversal.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Definition for a binary tree node.
3 | * function TreeNode(val, left, right) {
4 | * this.val = (val===undefined ? 0 : val)
5 | * this.left = (left===undefined ? null : left)
6 | * this.right = (right===undefined ? null : right)
7 | * }
8 | */
9 | /**
10 | * @param {TreeNode} root
11 | * @return {number[][]}
12 | */
13 | var zigzagLevelOrder = function(root) {
14 | if(!root) return [];
15 |
16 | const queue = [root], ret = [];
17 | let lvl = 0;
18 | while(queue.length) {
19 | const queueSize = queue.length;
20 | const level = [];
21 |
22 | for (let i = 0; i < queueSize; ++i) {
23 | const curNode = queue.shift();
24 | if (lvl & 1) level.unshift(curNode.val);
25 | else level.push(curNode.val);
26 |
27 | if (curNode.left) queue.push(curNode.left);
28 | if (curNode.right) queue.push(curNode.right);
29 | }
30 |
31 | ret.push(level)
32 | lvl++;
33 | }
34 |
35 |
36 | return ret;
37 | };
38 |
--------------------------------------------------------------------------------
/Medium/103. Binary Tree Zigzag Level Order Traversal/README.md:
--------------------------------------------------------------------------------
1 | # Binary Tree Zigzag Level Order Traversal
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/F9r-7SEdpCQ)
10 |
11 |
12 |
13 | ## code - C++
14 |
15 | ```cpp
16 | /**
17 | * Definition for a binary tree node.
18 | * struct TreeNode {
19 | * int val;
20 | * TreeNode *left;
21 | * TreeNode *right;
22 | * TreeNode() : val(0), left(nullptr), right(nullptr) {}
23 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
24 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
25 | * };
26 | */
27 | class Solution {
28 | public:
29 | vector> zigzagLevelOrder(TreeNode* root) {
30 | if (!root)
31 | return {};
32 |
33 | vector> res;
34 |
35 | queue qu;
36 | qu.push(root);
37 |
38 | bool rightToLeft = false;
39 |
40 | while (!qu.empty()) {
41 | vector curLevel;
42 |
43 | int sz = qu.size();
44 | for (int i = 0; i < sz; ++i) {
45 | auto node = qu.front();
46 | qu.pop();
47 |
48 | curLevel.push_back(node->val);
49 |
50 | if (node->left) qu.push(node->left);
51 | if (node->right) qu.push(node->right);
52 | }
53 |
54 | if (rightToLeft)
55 | reverse(curLevel.begin(), curLevel.end());
56 |
57 | rightToLeft = !rightToLeft;
58 |
59 | res.push_back(curLevel);
60 | }
61 |
62 | return res;
63 | }
64 | };
65 | ```
66 |
67 | # Code - JS
68 | ```js
69 | /**
70 | * Definition for a binary tree node.
71 | * function TreeNode(val, left, right) {
72 | * this.val = (val===undefined ? 0 : val)
73 | * this.left = (left===undefined ? null : left)
74 | * this.right = (right===undefined ? null : right)
75 | * }
76 | */
77 | /**
78 | * @param {TreeNode} root
79 | * @return {number[][]}
80 | */
81 | var zigzagLevelOrder = function(root) {
82 | if(!root) return [];
83 |
84 | const queue = [root], ret = [];
85 | let lvl = 0;
86 | while(queue.length) {
87 | const queueSize = queue.length;
88 | const level = [];
89 |
90 | for (let i = 0; i < queueSize; ++i) {
91 | const curNode = queue.shift();
92 | if (lvl & 1) level.unshift(curNode.val);
93 | else level.push(curNode.val);
94 |
95 | if (curNode.left) queue.push(curNode.left);
96 | if (curNode.right) queue.push(curNode.right);
97 | }
98 |
99 | ret.push(level)
100 | lvl++;
101 | }
102 |
103 |
104 | return ret;
105 | };
106 | ```
107 |
--------------------------------------------------------------------------------
/Medium/1061. Lexicographically Smallest Equivalent String/Lexicographically Smallest Equivalent String.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | string smallestEquivalentString(string s1, string s2, string baseStr) {
4 | vector parent(26);
5 | iota(parent.begin(), parent.end(), 0);
6 |
7 | int sz = s1.size();
8 | for (int i = 0; i < sz; ++i)
9 | merge(s1[i] - 'a', s2[i] - 'a', parent);
10 |
11 | string ret = "";
12 | for (auto &ch : baseStr)
13 | ret += (find(ch - 'a', parent) + 'a');
14 |
15 | return ret;
16 | }
17 |
18 | void merge(int u, int v, vector &parent) {
19 | u = find(u, parent);
20 | v = find(v, parent);
21 |
22 | if (u != v)
23 | parent[max(u, v)] = min(u, v);
24 | }
25 |
26 | int find(int x, vector &parent) {
27 | if (parent[x] == x)
28 | return x;
29 |
30 | return parent[x] = find(parent[x], parent);
31 | }
32 | };
33 |
--------------------------------------------------------------------------------
/Medium/1061. Lexicographically Smallest Equivalent String/README.md:
--------------------------------------------------------------------------------
1 | # Lexicographically Smallest Equivalent String
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/lexicographically-smallest-equivalent-string/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/W08k6IqGU8E)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | // C++
17 |
18 | class Solution {
19 | public:
20 | string smallestEquivalentString(string s1, string s2, string baseStr) {
21 | vector parent(26);
22 | iota(parent.begin(), parent.end(), 0);
23 |
24 | int sz = s1.size();
25 | for (int i = 0; i < sz; ++i)
26 | merge(s1[i] - 'a', s2[i] - 'a', parent);
27 |
28 | string ret = "";
29 | for (auto &ch : baseStr)
30 | ret += (find(ch - 'a', parent) + 'a');
31 |
32 | return ret;
33 | }
34 |
35 | void merge(int u, int v, vector &parent) {
36 | u = find(u, parent);
37 | v = find(v, parent);
38 |
39 | if (u != v)
40 | parent[max(u, v)] = min(u, v);
41 | }
42 |
43 | int find(int x, vector &parent) {
44 | if (parent[x] == x)
45 | return x;
46 |
47 | return parent[x] = find(parent[x], parent);
48 | }
49 | };
50 | ```
51 |
--------------------------------------------------------------------------------
/Medium/1129. Shortest Path with Alternating Colors/README.md:
--------------------------------------------------------------------------------
1 | # Shortest Path with Alternating Colors
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/shortest-path-with-alternating-colors/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/cxIu0zYPax4)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | private:
18 | const int OO = 0x3f3f3f3f;
19 | public:
20 | vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) {
21 | vector>> graph(n, vector>(n));
22 | for (auto &edge : redEdges)
23 | graph[edge[0]].push_back({edge[1], 0});
24 |
25 | for (auto &edge : blueEdges)
26 | graph[edge[0]].push_back({edge[1], 1});
27 |
28 | return BFS(0, n, graph);
29 | }
30 |
31 | vector BFS(int src, int n, vector>> &graph) {
32 | queue> qu;
33 | qu.push({src, 0, 0});
34 | qu.push({src, 0, 1});
35 |
36 | vector dis(n, -1);
37 | dis[0] = 0;
38 |
39 | vector> visited(n, vector(2));
40 |
41 | while (!qu.empty()) {
42 | auto vc = qu.front();
43 | qu.pop();
44 |
45 | int node = vc[0], nodeDis = vc[1], nodeColor = vc[2];
46 | visited[node][nodeColor] = true;
47 |
48 | for (auto &[neighbor, neighborColor] : graph[node]) {
49 | if (!visited[neighbor][neighborColor] && nodeColor != neighborColor) {
50 | if (dis[neighbor] == -1)
51 | dis[neighbor] = nodeDis + 1;
52 |
53 | qu.push({neighbor, nodeDis + 1, neighborColor});
54 | }
55 | }
56 | }
57 |
58 | return dis;
59 | }
60 | };
61 | ```
62 |
--------------------------------------------------------------------------------
/Medium/1129. Shortest Path with Alternating Colors/Shortest Path with Alternating Colors.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private:
3 | const int OO = 0x3f3f3f3f;
4 | public:
5 | vector shortestAlternatingPaths(int n, vector>& redEdges, vector>& blueEdges) {
6 | vector>> graph(n, vector>(n));
7 | for (auto &edge : redEdges)
8 | graph[edge[0]].push_back({edge[1], 0});
9 |
10 | for (auto &edge : blueEdges)
11 | graph[edge[0]].push_back({edge[1], 1});
12 |
13 | return BFS(0, n, graph);
14 | }
15 |
16 | vector BFS(int src, int n, vector>> &graph) {
17 | queue> qu;
18 | qu.push({src, 0, 0});
19 | qu.push({src, 0, 1});
20 |
21 | vector dis(n, -1);
22 | dis[0] = 0;
23 |
24 | vector> visited(n, vector(2));
25 |
26 | while (!qu.empty()) {
27 | auto vc = qu.front();
28 | qu.pop();
29 |
30 | int node = vc[0], nodeDis = vc[1], nodeColor = vc[2];
31 | visited[node][nodeColor] = true;
32 |
33 | for (auto &[neighbor, neighborColor] : graph[node]) {
34 | if (!visited[neighbor][neighborColor] && nodeColor != neighborColor) {
35 | if (dis[neighbor] == -1)
36 | dis[neighbor] = nodeDis + 1;
37 |
38 | qu.push({neighbor, nodeDis + 1, neighborColor});
39 | }
40 | }
41 | }
42 |
43 | return dis;
44 | }
45 | };
46 |
--------------------------------------------------------------------------------
/Medium/1162. As Far from Land as Possible/As Far from Land as Possible.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private:
3 | const int OO = 0x3f3f3f3f;
4 | vector dx = {0, 0, 1, -1};
5 | vector dy = {1, -1, 0, 0};
6 | int n;
7 |
8 | public:
9 | int maxDistance(vector>& grid) {
10 | n = grid.size();
11 | vector> dis(n, vector(n));
12 | queue> qu;
13 | for (int i = 0; i < n; ++i) {
14 | for (int j = 0; j < n; ++j) {
15 | dis[i][j] = OO;
16 | if (grid[i][j]) {
17 | qu.push({i, j});
18 | dis[i][j] = 0;
19 | }
20 | }
21 | }
22 |
23 | while (!qu.empty()) {
24 | auto [i, j] = qu.front();
25 | qu.pop();
26 |
27 | for (int k = 0; k < 4; ++k) {
28 | int x = i + dx[k];
29 | int y = j + dy[k];
30 |
31 | if (valid(x, y) && !grid[x][y] && dis[x][y] > dis[i][j] + 1) {
32 | dis[x][y] = dis[i][j] + 1;
33 | qu.push({x, y});
34 | }
35 | }
36 | }
37 |
38 | int mx = -1;
39 | for (int i = 0; i < n; ++i)
40 | for (int j = 0; j < n; ++j)
41 | if (dis[i][j] != OO && dis[i][j])
42 | mx = max(mx, dis[i][j]);
43 |
44 | return mx;
45 | }
46 |
47 | bool valid(int i, int j) {
48 | return i >= 0 && i < n && j >= 0 && j < n;
49 | }
50 | };
51 |
--------------------------------------------------------------------------------
/Medium/1162. As Far from Land as Possible/README.md:
--------------------------------------------------------------------------------
1 | # As Far from Land as Possible
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/as-far-from-land-as-possible/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/DayD3YvLeSw)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | private:
18 | const int OO = 0x3f3f3f3f;
19 | vector dx = {0, 0, 1, -1};
20 | vector dy = {1, -1, 0, 0};
21 | int n;
22 |
23 | public:
24 | int maxDistance(vector>& grid) {
25 | n = grid.size();
26 | vector> dis(n, vector(n));
27 | queue> qu;
28 | for (int i = 0; i < n; ++i) {
29 | for (int j = 0; j < n; ++j) {
30 | dis[i][j] = OO;
31 | if (grid[i][j]) {
32 | qu.push({i, j});
33 | dis[i][j] = 0;
34 | }
35 | }
36 | }
37 |
38 | while (!qu.empty()) {
39 | auto [i, j] = qu.front();
40 | qu.pop();
41 |
42 | for (int k = 0; k < 4; ++k) {
43 | int x = i + dx[k];
44 | int y = j + dy[k];
45 |
46 | if (valid(x, y) && !grid[x][y] && dis[x][y] > dis[i][j] + 1) {
47 | dis[x][y] = dis[i][j] + 1;
48 | qu.push({x, y});
49 | }
50 | }
51 | }
52 |
53 | int mx = -1;
54 | for (int i = 0; i < n; ++i)
55 | for (int j = 0; j < n; ++j)
56 | if (dis[i][j] != OO && dis[i][j])
57 | mx = max(mx, dis[i][j]);
58 |
59 | return mx;
60 | }
61 |
62 | bool valid(int i, int j) {
63 | return i >= 0 && i < n && j >= 0 && j < n;
64 | }
65 | };
66 | ```
67 |
--------------------------------------------------------------------------------
/Medium/131. Palindrome Partitioning/Palindrome Partitioning.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private:
3 | int n;
4 | vector> res;
5 | vector cur;
6 | public:
7 | vector> partition(string s) {
8 | n = s.size();
9 | solve(0, s);
10 | return res;
11 | }
12 |
13 | void solve(int idx, string &s) {
14 | if (idx == n) {
15 | res.push_back(cur);
16 | return;
17 | }
18 |
19 | string curPalindrome = "";
20 | for (int i = idx; i < n; ++i) {
21 | curPalindrome += s[i];
22 |
23 | if (isPalindrome(curPalindrome)) {
24 | cur.push_back(curPalindrome);
25 | solve(i + 1, s);
26 | cur.pop_back();
27 | }
28 | }
29 | }
30 |
31 | bool isPalindrome(string &str) {
32 | int sz = str.size();
33 | for (int i = 0; i < sz / 2; ++i)
34 | if (str[i] != str[sz - i - 1])
35 | return false;
36 |
37 | return true;
38 | }
39 | };
40 |
--------------------------------------------------------------------------------
/Medium/131. Palindrome Partitioning/README.md:
--------------------------------------------------------------------------------
1 | # Palindrome Partitioning
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/palindrome-partitioning/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/9xtJz4R-2gw)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | private:
18 | int n;
19 | vector> res;
20 | vector cur;
21 | public:
22 | vector> partition(string s) {
23 | n = s.size();
24 | solve(0, s);
25 | return res;
26 | }
27 |
28 | void solve(int idx, string &s) {
29 | if (idx == n) {
30 | res.push_back(cur);
31 | return;
32 | }
33 |
34 | string curPalindrome = "";
35 | for (int i = idx; i < n; ++i) {
36 | curPalindrome += s[i];
37 |
38 | if (isPalindrome(curPalindrome)) {
39 | cur.push_back(curPalindrome);
40 | solve(i + 1, s);
41 | cur.pop_back();
42 | }
43 | }
44 | }
45 |
46 | bool isPalindrome(string &str) {
47 | int sz = str.size();
48 | for (int i = 0; i < sz / 2; ++i)
49 | if (str[i] != str[sz - i - 1])
50 | return false;
51 |
52 | return true;
53 | }
54 | };
55 | ```
56 |
--------------------------------------------------------------------------------
/Medium/142. Linked List Cycle II/1 - Linked List Cycle II.cpp:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | /**
3 | * Definition for singly-linked list.
4 | * struct ListNode {
5 | * int val;
6 | * ListNode *next;
7 | * ListNode(int x) : val(x), next(NULL) {}
8 | * };
9 | */
10 | class Solution {
11 | public:
12 | ListNode *detectCycle(ListNode *head) {
13 | unordered_set nodes;
14 | while (head && !nodes.count(head)) {
15 | nodes.insert(head);
16 | head = head->next;
17 | }
18 | return head;
19 | }
20 | };
21 |
22 |
23 |
24 | // solution - 2
25 | /**
26 | * Definition for singly-linked list.
27 | * struct ListNode {
28 | * int val;
29 | * ListNode *next;
30 | * ListNode(int x) : val(x), next(NULL) {}
31 | * };
32 | */
33 | class Solution {
34 | public:
35 | ListNode *detectCycle(ListNode *head) {
36 | ListNode *fast = head, *slow = head;
37 | while (fast && fast->next && fast->next->next) {
38 | slow = slow->next;
39 | fast = fast->next->next;
40 | if (slow == fast) {
41 | slow = head;
42 | while (slow != fast) {
43 | slow = slow->next;
44 | fast = fast->next;
45 | }
46 | return slow;
47 | }
48 | }
49 | return nullptr;
50 | }
51 | };
52 |
--------------------------------------------------------------------------------
/Medium/142. Linked List Cycle II/2 - Linked List Cycle II.java:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | /**
3 | * Definition for singly-linked list.
4 | * class ListNode {
5 | * int val;
6 | * ListNode next;
7 | * ListNode(int x) {
8 | * val = x;
9 | * next = null;
10 | * }
11 | * }
12 | */
13 | public class Solution {
14 | public ListNode detectCycle(ListNode head) {
15 | Set nodes = new HashSet<>();
16 | while (head != null && !nodes.contains(head)) {
17 | nodes.add(head);
18 | head = head.next;
19 | }
20 | return head;
21 | }
22 | }
23 |
24 |
25 |
26 | // solution - 2
27 | /**
28 | * Definition for singly-linked list.
29 | * class ListNode {
30 | * int val;
31 | * ListNode next;
32 | * ListNode(int x) {
33 | * val = x;
34 | * next = null;
35 | * }
36 | * }
37 | */
38 | public class Solution {
39 | public ListNode detectCycle(ListNode head) {
40 | ListNode fast = head, slow = head;
41 | while (fast != null && fast.next != null && fast.next.next != null) {
42 | slow = slow.next;
43 | fast = fast.next.next;
44 | if (slow == fast) {
45 | slow = head;
46 | while (slow != fast) {
47 | slow = slow.next;
48 | fast = fast.next;
49 | }
50 | return slow;
51 | }
52 | }
53 | return null;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Medium/142. Linked List Cycle II/3 - Linked List Cycle II.py:
--------------------------------------------------------------------------------
1 | # solution - 1
2 | # Definition for singly-linked list.
3 | # class ListNode:
4 | # def __init__(self, x):
5 | # self.val = x
6 | # self.next = None
7 |
8 | class Solution:
9 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
10 | nodes = set()
11 |
12 | while head and head not in nodes:
13 | nodes.add(head)
14 | head = head.next
15 |
16 | return head
17 |
18 |
19 | # solution - 2
20 | # Definition for singly-linked list.
21 | # class ListNode:
22 | # def __init__(self, x):
23 | # self.val = x
24 | # self.next = None
25 |
26 | class Solution:
27 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
28 | fast = slow = head
29 | while fast and fast.next and fast.next.next:
30 | slow = slow.next
31 | fast = fast.next.next
32 |
33 | if slow == fast:
34 | slow = head
35 | while slow != fast:
36 | slow = slow.next
37 | fast = fast.next
38 | return slow
39 |
40 | return None
41 |
--------------------------------------------------------------------------------
/Medium/142. Linked List Cycle II/4 - Linked List Cycle II.js:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | /**
3 | * Definition for singly-linked list.
4 | * function ListNode(val) {
5 | * this.val = val;
6 | * this.next = null;
7 | * }
8 | */
9 |
10 | /**
11 | * @param {ListNode} head
12 | * @return {ListNode}
13 | */
14 | var detectCycle = function(head) {
15 | const nodes = new Set();
16 |
17 | while (head && !nodes.has(head)) {
18 | nodes.add(head);
19 | head = head.next;
20 | }
21 |
22 | return head;
23 | };
24 |
25 |
26 | // solution - 2
27 | /**
28 | * Definition for singly-linked list.
29 | * function ListNode(val) {
30 | * this.val = val;
31 | * this.next = null;
32 | * }
33 | */
34 |
35 | /**
36 | * @param {ListNode} head
37 | * @return {ListNode}
38 | */
39 | var detectCycle = function(head) {
40 | let fast = head, slow = head;
41 | while (fast && fast.next && fast.next.next) {
42 | slow = slow.next;
43 | fast = fast.next.next;
44 |
45 | if (slow === fast) {
46 | slow = head;
47 | while (slow !== fast) {
48 | slow = slow.next;
49 | fast = fast.next;
50 | }
51 | return slow;
52 | }
53 | }
54 |
55 | return null;
56 | };
57 |
--------------------------------------------------------------------------------
/Medium/142. Linked List Cycle II/README.md:
--------------------------------------------------------------------------------
1 | # Linked List Cycle II
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/linked-list-cycle-ii/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/YDAmeMHWkjo)
10 |
--------------------------------------------------------------------------------
/Medium/1443. Minimum Time to Collect All Apples in a Tree/Minimum Time to Collect All Apples in a Tree.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int minTime(int n, vector>& edges, vector& hasApple) {
4 | vector> tree(n);
5 | for (auto edge : edges) {
6 | tree[edge[0]].push_back(edge[1]);
7 | tree[edge[1]].push_back(edge[0]);
8 | }
9 |
10 | return max(0, DFS(0, -1, tree, hasApple) - 2);
11 | }
12 |
13 | int DFS(int node, int parent, vector> &tree, vector &hasApple) {
14 | int time = 0;
15 | for (auto child : tree[node]) {
16 | if (child != parent)
17 | time += DFS(child, node, tree, hasApple);
18 | }
19 |
20 | return (time > 0 || hasApple[node] ? time + 2 : 0);
21 | }
22 | };
23 |
--------------------------------------------------------------------------------
/Medium/1443. Minimum Time to Collect All Apples in a Tree/README.md:
--------------------------------------------------------------------------------
1 | # Minimum Time to Collect All Apples in a Tree
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/minimum-time-to-collect-all-apples-in-a-tree/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://www.youtube.com/watch?v=hIVslN8zDco)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | // C++
17 |
18 | class Solution {
19 | public:
20 | int minTime(int n, vector>& edges, vector& hasApple) {
21 | vector> tree(n);
22 | for (auto edge : edges) {
23 | tree[edge[0]].push_back(edge[1]);
24 | tree[edge[1]].push_back(edge[0]);
25 | }
26 |
27 | return max(0, DFS(0, -1, tree, hasApple) - 2);
28 | }
29 |
30 | int DFS(int node, int parent, vector> &tree, vector &hasApple) {
31 | int time = 0;
32 | for (auto child : tree[node]) {
33 | if (child != parent)
34 | time += DFS(child, node, tree, hasApple);
35 | }
36 |
37 | return (time > 0 || hasApple[node] ? time + 2 : 0);
38 | }
39 | };
40 | ```
41 |
--------------------------------------------------------------------------------
/Medium/1519. Number of Nodes in the Sub-Tree With the Same Label/Number of Nodes in the Sub-Tree With the Same Label.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector countSubTrees(int n, vector>& edges, string labels) {
4 | vector> tree(n);
5 | for (auto &edge : edges) {
6 | tree[edge[0]].push_back(edge[1]);
7 | tree[edge[1]].push_back(edge[0]);
8 | }
9 |
10 | vector ans(n);
11 | DFS(0, -1, ans, tree, labels);
12 | return ans;
13 | }
14 |
15 | vector DFS(int node, int parent, vector &ans, vector> &tree, string &label) {
16 | vector ret(26);
17 | ret[label[node] - 'a']++;
18 |
19 | for (auto child : tree[node]) {
20 | if (child != parent) {
21 | auto childSubTree = DFS(child, node, ans, tree, label);
22 | for (int i = 0; i < 26; ++i)
23 | ret [i] += childSubTree[i];
24 | }
25 | }
26 |
27 | ans[node] = ret[label[node] - 'a'];
28 | return ret;
29 | }
30 | };
31 |
--------------------------------------------------------------------------------
/Medium/1519. Number of Nodes in the Sub-Tree With the Same Label/README.md:
--------------------------------------------------------------------------------
1 | # Number of Nodes in the Sub-Tree With the Same Label
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/number-of-nodes-in-the-sub-tree-with-the-same-label/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://www.youtube.com/watch?v=r0ZCfYtBm0k&t=2s)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | // C++
17 |
18 | class Solution {
19 | public:
20 | vector countSubTrees(int n, vector>& edges, string labels) {
21 | vector> tree(n);
22 | for (auto &edge : edges) {
23 | tree[edge[0]].push_back(edge[1]);
24 | tree[edge[1]].push_back(edge[0]);
25 | }
26 |
27 | vector ans(n);
28 | DFS(0, -1, ans, tree, labels);
29 | return ans;
30 | }
31 |
32 | vector DFS(int node, int parent, vector &ans, vector> &tree, string &label) {
33 | vector ret(26);
34 | ret[label[node] - 'a']++;
35 |
36 | for (auto child : tree[node]) {
37 | if (child != parent) {
38 | auto childSubTree = DFS(child, node, ans, tree, label);
39 | for (int i = 0; i < 26; ++i)
40 | ret [i] += childSubTree[i];
41 | }
42 | }
43 |
44 | ans[node] = ret[label[node] - 'a'];
45 | return ret;
46 | }
47 | };
48 | ```
49 |
--------------------------------------------------------------------------------
/Medium/1626. Best Team With No Conflicts/Best Team With No Conflicts.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int bestTeamScore(vector& scores, vector& ages) {
4 | int n = scores.size();
5 |
6 | vector> vc(n);
7 | for (int i = 0; i < n; ++i)
8 | vc[i] = {ages[i], scores[i]};
9 |
10 | sort(vc.begin(), vc.end());
11 |
12 | return highestScore(n, vc);
13 | }
14 |
15 | int highestScore(int n, vector> &vc) {
16 | int maxScore = 0;
17 | vector dp(n);
18 |
19 | for (int i = 0; i < n; ++i) {
20 | dp[i] = vc[i].second;
21 |
22 | for (int j = i - 1; j >= 0; --j)
23 | if (vc[i].second >= vc[j].second)
24 | dp[i] = max(dp[i], dp[j] + vc[i].second);
25 |
26 | maxScore = max(maxScore, dp[i]);
27 | }
28 |
29 | return maxScore;
30 | }
31 | };
32 |
--------------------------------------------------------------------------------
/Medium/1626. Best Team With No Conflicts/README.md:
--------------------------------------------------------------------------------
1 | # Best Team With No Conflicts
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/best-team-with-no-conflicts/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/XY3XkHCdyKQ)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | int bestTeamScore(vector& scores, vector& ages) {
19 | int n = scores.size();
20 |
21 | vector> vc(n);
22 | for (int i = 0; i < n; ++i)
23 | vc[i] = {ages[i], scores[i]};
24 |
25 | sort(vc.begin(), vc.end());
26 |
27 | return highestScore(n, vc);
28 | }
29 |
30 | int highestScore(int n, vector> &vc) {
31 | int maxScore = 0;
32 | vector dp(n);
33 |
34 | for (int i = 0; i < n; ++i) {
35 | dp[i] = vc[i].second;
36 |
37 | for (int j = i - 1; j >= 0; --j)
38 | if (vc[i].second >= vc[j].second)
39 | dp[i] = max(dp[i], dp[j] + vc[i].second);
40 |
41 | maxScore = max(maxScore, dp[i]);
42 | }
43 |
44 | return maxScore;
45 | }
46 | };
47 | ```
48 |
--------------------------------------------------------------------------------
/Medium/2187. Minimum Time to Complete Trips/1 - Minimum Time to Complete Trips.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | long long minimumTime(vector& time, int totalTrips) {
4 | long long lo = 0, hi = 1LL * minTime(time) * totalTrips;
5 | long long res = 0;
6 | while (lo <= hi) {
7 | long long mid = lo + (hi - lo) / 2;
8 |
9 | if (numOfTrips(mid, time) >= totalTrips) {
10 | res = mid;
11 | hi = mid - 1;
12 | }
13 | else
14 | lo = mid + 1;
15 | }
16 | return res;
17 | }
18 |
19 | long long numOfTrips(long long curTime, vector& time) {
20 | long long counter = 0;
21 | for (int t : time)
22 | counter += curTime / t;
23 |
24 | return counter;
25 | }
26 |
27 | long long minTime(vector& time) {
28 | return *min_element(time.begin(), time.end());
29 | }
30 | };
31 |
--------------------------------------------------------------------------------
/Medium/2187. Minimum Time to Complete Trips/2 - Minimum Time to Complete Trips.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public long minimumTime(int[] time, int totalTrips) {
3 | long lo = 0, hi = 1L * minTime(time) * totalTrips;
4 | long res = 0;
5 | while (lo <= hi) {
6 | long mid = lo + (hi - lo) / 2;
7 |
8 | if (numOfTrips(mid, time) >= totalTrips) {
9 | res = mid;
10 | hi = mid - 1;
11 | }
12 | else
13 | lo = mid + 1;
14 | }
15 | return res;
16 | }
17 |
18 | public long numOfTrips(long curTime, int[] time) {
19 | long counter = 0;
20 | for (int t : time)
21 | counter += curTime / t;
22 |
23 | return counter;
24 | }
25 |
26 | public long minTime(int[] time) {
27 | int min = Integer.MAX_VALUE;
28 | for (int t : time) {
29 | if (t < min) {
30 | min = t;
31 | }
32 | }
33 | return min;
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/Medium/2187. Minimum Time to Complete Trips/3 - Minimum Time to Complete Trips.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def minimumTime(self, time: List[int], totalTrips: int) -> int:
3 | lo, hi, res = 0, min(time) * totalTrips, 0
4 | while lo <= hi:
5 | mid = lo + (hi - lo) // 2
6 |
7 | if self.numOfTrips(mid, time) >= totalTrips:
8 | res = mid
9 | hi = mid - 1
10 | else:
11 | lo = mid + 1
12 | return res
13 |
14 | def numOfTrips(self, curTime: int, time: List[int]) -> int:
15 | counter = 0
16 | for t in time:
17 | counter += curTime // t
18 |
19 | return counter
20 |
--------------------------------------------------------------------------------
/Medium/2187. Minimum Time to Complete Trips/4 - Minimum Time to Complete Trips.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {number[]} time
3 | * @param {number} totalTrips
4 | * @return {number}
5 | */
6 | var minimumTime = function(time, totalTrips) {
7 | let lo = 0, hi = Math.min(...time) * totalTrips, res = 0;
8 | while (lo <= hi) {
9 | const mid = lo + Math.floor((hi - lo) / 2);
10 | const numOfTrips = time.reduce((acc, cur) => acc + Math.floor(mid / cur), 0);
11 |
12 | if (numOfTrips >= totalTrips) {
13 | res = mid;
14 | hi = mid - 1;
15 | } else
16 | lo = mid + 1;
17 | }
18 | return res;
19 | };
20 |
--------------------------------------------------------------------------------
/Medium/2187. Minimum Time to Complete Trips/README.md:
--------------------------------------------------------------------------------
1 | # Minimum Time to Complete Trips
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/minimum-time-to-complete-trips/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/6L6Or7D8ZlI)
10 |
--------------------------------------------------------------------------------
/Medium/2359. Find Closest Node to Given Two Nodes/Find Closest Node to Given Two Nodes.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int closestMeetingNode(vector& edges, int node1, int node2) {
4 | int n = edges.size();
5 | auto dis1 = BFS(node1, n, edges);
6 | auto dis2 = BFS(node2, n, edges);
7 |
8 | int node = -1, x = INT_MAX;
9 | for (int i = 0; i < n; ++i) {
10 | if (x > max(dis1[i], dis2[i])) {
11 | node = i;
12 | x = max(dis1[i], dis2[i]);
13 | }
14 | }
15 |
16 | return node;
17 | }
18 |
19 | vector BFS(int src, int n, vector &edges) {
20 | vector dis(n, INT_MAX);
21 | queue qu;
22 | qu.push(src);
23 | dis[src] = 0;
24 |
25 | while (!qu.empty()) {
26 | int node = qu.front();
27 | qu.pop();
28 |
29 | if (edges[node] != -1 && dis[edges[node]] == INT_MAX) {
30 | qu.push(edges[node]);
31 | dis[edges[node]] = dis[node] + 1;
32 | }
33 | }
34 |
35 | return dis;
36 | }
37 | };
38 |
--------------------------------------------------------------------------------
/Medium/2359. Find Closest Node to Given Two Nodes/README.md:
--------------------------------------------------------------------------------
1 | # Find Closest Node to Given Two Nodes
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/find-closest-node-to-given-two-nodes/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/iO027dE7r34)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | int closestMeetingNode(vector& edges, int node1, int node2) {
19 | int n = edges.size();
20 | auto dis1 = BFS(node1, n, edges);
21 | auto dis2 = BFS(node2, n, edges);
22 |
23 | int node = -1, x = INT_MAX;
24 | for (int i = 0; i < n; ++i) {
25 | if (x > max(dis1[i], dis2[i])) {
26 | node = i;
27 | x = max(dis1[i], dis2[i]);
28 | }
29 | }
30 |
31 | return node;
32 | }
33 |
34 | vector BFS(int src, int n, vector &edges) {
35 | vector dis(n, INT_MAX);
36 | queue qu;
37 | qu.push(src);
38 | dis[src] = 0;
39 |
40 | while (!qu.empty()) {
41 | int node = qu.front();
42 | qu.pop();
43 |
44 | if (edges[node] != -1 && dis[edges[node]] == INT_MAX) {
45 | qu.push(edges[node]);
46 | dis[edges[node]] = dis[node] + 1;
47 | }
48 | }
49 |
50 | return dis;
51 | }
52 | };
53 | ```
54 |
--------------------------------------------------------------------------------
/Medium/2477. Minimum Fuel Cost to Report to the Capital/Minimum Fuel Cost to Report to the Capital.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private:
3 | long long numOfLiters = 0;
4 | vector> graph;
5 | public:
6 | long long minimumFuelCost(vector>& roads, int seats) {
7 | int n = roads.size();
8 | graph = vector> (n + 1);
9 |
10 | for (auto &road : roads) {
11 | graph[road[0]].push_back(road[1]);
12 | graph[road[1]].push_back(road[0]);
13 | }
14 |
15 | DFS(0, -1, seats);
16 |
17 | return numOfLiters;
18 | }
19 |
20 | int DFS(int node, int parent, int seats) {
21 | int representatives = 1;
22 |
23 | for (auto child : graph[node])
24 | if (child != parent)
25 | representatives += DFS(child, node, seats);
26 |
27 | if (node != 0)
28 | numOfLiters += (representatives + seats - 1) / seats;
29 |
30 | return representatives;
31 | }
32 | };
33 |
--------------------------------------------------------------------------------
/Medium/2477. Minimum Fuel Cost to Report to the Capital/README.md:
--------------------------------------------------------------------------------
1 | # Minimum Fuel Cost to Report to the Capital
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/minimum-fuel-cost-to-report-to-the-capital/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/Gq6HHNT3eg4)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | private:
18 | long long numOfLiters = 0;
19 | vector> graph;
20 | public:
21 | long long minimumFuelCost(vector>& roads, int seats) {
22 | int n = roads.size();
23 | graph = vector> (n + 1);
24 |
25 | for (auto &road : roads) {
26 | graph[road[0]].push_back(road[1]);
27 | graph[road[1]].push_back(road[0]);
28 | }
29 |
30 | DFS(0, -1, seats);
31 |
32 | return numOfLiters;
33 | }
34 |
35 | int DFS(int node, int parent, int seats) {
36 | int representatives = 1;
37 |
38 | for (auto child : graph[node])
39 | if (child != parent)
40 | representatives += DFS(child, node, seats);
41 |
42 | if (node != 0)
43 | numOfLiters += (representatives + seats - 1) / seats;
44 |
45 | return representatives;
46 | }
47 | };
48 | ```
49 |
--------------------------------------------------------------------------------
/Medium/28. Find the Index of the First Occurrence in a String/1 - Find the Index of the First Occurrence in a String.cpp:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | class Solution {
3 | public:
4 | int strStr(string haystack, string needle) {
5 | return haystack.find(needle);
6 | }
7 | };
8 |
9 |
10 | // solution - 2
11 | class Solution {
12 | public:
13 | int strStr(string haystack, string needle) {
14 | int n = haystack.size(), m = needle.size();
15 |
16 | for (int i = 0; i <= n - m; ++i) {
17 | for (int j = 0; j < m; ++j) {
18 | if (needle[j] != haystack[i + j])
19 | break;
20 |
21 | if (j == m - 1)
22 | return i;
23 | }
24 | }
25 |
26 | return -1;
27 | }
28 | };
29 |
--------------------------------------------------------------------------------
/Medium/28. Find the Index of the First Occurrence in a String/2 - Find the Index of the First Occurrence in a String.java:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | class Solution {
3 | public int strStr(String haystack, String needle) {
4 | return haystack.indexOf(needle);
5 | }
6 | }
7 |
8 | // solution - 2
9 | class Solution {
10 | public int strStr(String haystack, String needle) {
11 | int n = haystack.length(), m = needle.length();
12 |
13 | for (int i = 0; i <= n - m; ++i) {
14 | for (int j = 0; j < m; ++j) {
15 | if (needle.charAt(j) != haystack.charAt(i + j))
16 | break;
17 |
18 | if (j == m - 1)
19 | return i;
20 | }
21 | }
22 |
23 | return -1;
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/Medium/28. Find the Index of the First Occurrence in a String/3 - Find the Index of the First Occurrence in a String.py:
--------------------------------------------------------------------------------
1 | # solution - 1
2 | class Solution:
3 | def strStr(self, haystack: str, needle: str) -> int:
4 | return haystack.find(needle)
5 |
6 |
7 | # solution - 2
8 | class Solution:
9 | def strStr(self, haystack: str, needle: str) -> int:
10 | n, m = len(haystack), len(needle)
11 |
12 | for i in range(0, n - m + 1):
13 | for j in range(0, m):
14 | if needle[j] != haystack[i + j]:
15 | break
16 |
17 | if j == m - 1:
18 | return i
19 |
20 | return -1
21 |
--------------------------------------------------------------------------------
/Medium/28. Find the Index of the First Occurrence in a String/4 - Find the Index of the First Occurrence in a String.js:
--------------------------------------------------------------------------------
1 | // solution - 1
2 | /**
3 | * @param {string} haystack
4 | * @param {string} needle
5 | * @return {number}
6 | */
7 | var strStr = function(haystack, needle) {
8 | return haystack.indexOf(needle);
9 | };
10 |
11 |
12 | // solution - 2
13 | /**
14 | * @param {string} haystack
15 | * @param {string} needle
16 | * @return {number}
17 | */
18 | var strStr = function(haystack, needle) {
19 | const n = haystack.length, m = needle.length;
20 |
21 | for (let i = 0; i <= n - m; ++i) {
22 | for (let j = 0; j < m; ++j) {
23 | if (needle[j] != haystack[i + j])
24 | break;
25 |
26 | if (j == m - 1)
27 | return i;
28 | }
29 | }
30 |
31 | return -1;
32 | };
33 |
--------------------------------------------------------------------------------
/Medium/28. Find the Index of the First Occurrence in a String/README.md:
--------------------------------------------------------------------------------
1 | # Find the Index of the First Occurrence in a String
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/description/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/Qh4BtcOwsLY)
10 |
--------------------------------------------------------------------------------
/Medium/427. Construct Quad Tree/1 - Construct Quad Tree.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | // Definition for a QuadTree node.
3 | class Node {
4 | public:
5 | bool val;
6 | bool isLeaf;
7 | Node* topLeft;
8 | Node* topRight;
9 | Node* bottomLeft;
10 | Node* bottomRight;
11 |
12 | Node() {
13 | val = false;
14 | isLeaf = false;
15 | topLeft = NULL;
16 | topRight = NULL;
17 | bottomLeft = NULL;
18 | bottomRight = NULL;
19 | }
20 |
21 | Node(bool _val, bool _isLeaf) {
22 | val = _val;
23 | isLeaf = _isLeaf;
24 | topLeft = NULL;
25 | topRight = NULL;
26 | bottomLeft = NULL;
27 | bottomRight = NULL;
28 | }
29 |
30 | Node(bool _val, bool _isLeaf, Node* _topLeft, Node* _topRight, Node* _bottomLeft, Node* _bottomRight) {
31 | val = _val;
32 | isLeaf = _isLeaf;
33 | topLeft = _topLeft;
34 | topRight = _topRight;
35 | bottomLeft = _bottomLeft;
36 | bottomRight = _bottomRight;
37 | }
38 | };
39 | */
40 |
41 | class Solution {
42 | public:
43 | Node* construct(vector>& grid) {
44 | return solve(0, 0, grid.size(), grid);
45 | }
46 |
47 | Node* solve(int x, int y, int len, vector>& grid) {
48 | if (isSameValue(x, y, len, grid))
49 | return new Node(grid[x][y], true);
50 |
51 | Node* root = new Node();
52 | len >>= 1;
53 |
54 | root->topLeft = solve(x, y, len, grid);
55 | root->topRight = solve(x, y + len, len, grid);
56 | root->bottomLeft = solve(x + len, y, len, grid);
57 | root->bottomRight = solve(x + len, y + len, len, grid);
58 |
59 | return root;
60 | }
61 |
62 | bool isSameValue(int x, int y, int len, vector>& grid) {
63 | for (int i = x; i < x + len; ++i)
64 | for (int j = y; j < y + len; ++j)
65 | if (grid[i][j] != grid[x][y])
66 | return false;
67 |
68 | return true;
69 | }
70 | };
71 |
--------------------------------------------------------------------------------
/Medium/427. Construct Quad Tree/2 - Construct Quad Tree.java:
--------------------------------------------------------------------------------
1 | /*
2 | // Definition for a QuadTree node.
3 | class Node {
4 | public boolean val;
5 | public boolean isLeaf;
6 | public Node topLeft;
7 | public Node topRight;
8 | public Node bottomLeft;
9 | public Node bottomRight;
10 |
11 |
12 | public Node() {
13 | this.val = false;
14 | this.isLeaf = false;
15 | this.topLeft = null;
16 | this.topRight = null;
17 | this.bottomLeft = null;
18 | this.bottomRight = null;
19 | }
20 |
21 | public Node(boolean val, boolean isLeaf) {
22 | this.val = val;
23 | this.isLeaf = isLeaf;
24 | this.topLeft = null;
25 | this.topRight = null;
26 | this.bottomLeft = null;
27 | this.bottomRight = null;
28 | }
29 |
30 | public Node(boolean val, boolean isLeaf, Node topLeft, Node topRight, Node bottomLeft, Node bottomRight) {
31 | this.val = val;
32 | this.isLeaf = isLeaf;
33 | this.topLeft = topLeft;
34 | this.topRight = topRight;
35 | this.bottomLeft = bottomLeft;
36 | this.bottomRight = bottomRight;
37 | }
38 | };
39 | */
40 |
41 | class Solution {
42 | public Node construct(int[][] grid) {
43 | return solve(0, 0, grid.length, grid);
44 | }
45 |
46 | public Node solve(int x, int y, int len, int[][] grid) {
47 | if (isSameValue(x, y, len, grid))
48 | return new Node(grid[x][y] == 1, true);
49 |
50 | Node root = new Node();
51 | len >>= 1;
52 |
53 | root.topLeft = solve(x, y, len, grid);
54 | root.topRight = solve(x, y + len, len, grid);
55 | root.bottomLeft = solve(x + len, y, len, grid);
56 | root.bottomRight = solve(x + len, y + len, len, grid);
57 |
58 | return root;
59 | }
60 |
61 | public boolean isSameValue(int x, int y, int len, int[][] grid) {
62 | for (int i = x; i < x + len; ++i)
63 | for (int j = y; j < y + len; ++j)
64 | if (grid[i][j] != grid[x][y])
65 | return false;
66 |
67 | return true;
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/Medium/427. Construct Quad Tree/3 - Construct Quad Tree.py:
--------------------------------------------------------------------------------
1 | """
2 | # Definition for a QuadTree node.
3 | class Node:
4 | def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
5 | self.val = val
6 | self.isLeaf = isLeaf
7 | self.topLeft = topLeft
8 | self.topRight = topRight
9 | self.bottomLeft = bottomLeft
10 | self.bottomRight = bottomRight
11 | """
12 |
13 | class Solution:
14 | def construct(self, grid: List[List[int]]) -> 'Node':
15 | return self.solve(0, 0, len(grid), grid)
16 |
17 | def solve(self, x, y, len, grid):
18 | if self.isSameValue(x, y, len, grid):
19 | return Node(grid[x][y], True)
20 |
21 | root = Node()
22 | len >>= 1
23 |
24 | root.topLeft = self.solve(x, y, len, grid)
25 | root.topRight = self.solve(x, y + len, len, grid)
26 | root.bottomLeft = self.solve(x + len, y, len, grid)
27 | root.bottomRight = self.solve(x + len, y + len, len, grid)
28 |
29 | return root
30 |
31 | def isSameValue(self, x, y, len, grid):
32 | for i in range(x, x + len):
33 | for j in range(y, y + len):
34 | if grid[i][j] != grid[x][y]:
35 | return False
36 |
37 | return True
38 |
--------------------------------------------------------------------------------
/Medium/427. Construct Quad Tree/4 - Construct Quad Tree.js:
--------------------------------------------------------------------------------
1 | /**
2 | * // Definition for a QuadTree node.
3 | * function Node(val,isLeaf,topLeft,topRight,bottomLeft,bottomRight) {
4 | * this.val = val;
5 | * this.isLeaf = isLeaf;
6 | * this.topLeft = topLeft;
7 | * this.topRight = topRight;
8 | * this.bottomLeft = bottomLeft;
9 | * this.bottomRight = bottomRight;
10 | * };
11 | */
12 |
13 | /**
14 | * @param {number[][]} grid
15 | * @return {Node}
16 | */
17 | var construct = function(grid) {
18 | return solve(0, 0, grid.length, grid);
19 | };
20 |
21 | const solve = (x, y, len, grid) => {
22 | if (isSameValue(x, y, len, grid))
23 | return new Node(grid[x][y], true);
24 |
25 | len >>= 1;
26 |
27 | return new Node(
28 | false,
29 | false,
30 | solve(x, y, len, grid),
31 | solve(x, y + len, len, grid),
32 | solve(x + len, y, len, grid),
33 | solve(x + len, y + len, len, grid)
34 | );
35 | }
36 |
37 | const isSameValue = (x, y, len, grid) => {
38 | for (let i = x; i < x + len; ++i)
39 | for (let j = y; j < y + len; ++j)
40 | if (grid[i][j] != grid[x][y])
41 | return false;
42 |
43 | return true;
44 | }
45 |
--------------------------------------------------------------------------------
/Medium/427. Construct Quad Tree/README.md:
--------------------------------------------------------------------------------
1 | # Construct Quad Tree
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/construct-quad-tree/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/NGgG3trM1Tk)
10 |
--------------------------------------------------------------------------------
/Medium/438. Find All Anagrams in a String/Find All Anagrams in a String.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector findAnagrams(string s, string p) {
4 | int szs = s.size(), szp = p.size();
5 | if (szs < szp)
6 | return {};
7 |
8 | vector frs(26), frp(26);
9 | for (int i = 0; i < szp; ++i) {
10 | frs[s[i] - 'a']++;
11 | frp[p[i] - 'a']++;
12 | }
13 |
14 | vector res;
15 | for (int i = 0; i < szs - szp; ++i) {
16 | if (frs == frp)
17 | res.push_back(i);
18 |
19 | frs[s[i] - 'a']--;
20 | frs[s[i + szp] - 'a']++;
21 | }
22 |
23 | if (frs == frp)
24 | res.push_back(szs - szp);
25 |
26 | return res;
27 | }
28 | };
29 |
--------------------------------------------------------------------------------
/Medium/438. Find All Anagrams in a String/README.md:
--------------------------------------------------------------------------------
1 | # Find All Anagrams in a String
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/find-all-anagrams-in-a-string/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/NW_KDyDHyVI)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | vector findAnagrams(string s, string p) {
19 | int szs = s.size(), szp = p.size();
20 | if (szs < szp)
21 | return {};
22 |
23 | vector frs(26), frp(26);
24 | for (int i = 0; i < szp; ++i) {
25 | frs[s[i] - 'a']++;
26 | frp[p[i] - 'a']++;
27 | }
28 |
29 | vector res;
30 | for (int i = 0; i < szs - szp; ++i) {
31 | if (frs == frp)
32 | res.push_back(i);
33 |
34 | frs[s[i] - 'a']--;
35 | frs[s[i + szp] - 'a']++;
36 | }
37 |
38 | if (frs == frp)
39 | res.push_back(szs - szp);
40 |
41 | return res;
42 | }
43 | };
44 | ```
45 |
--------------------------------------------------------------------------------
/Medium/443. String Compression/1 - String Compression.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int compress(vector& chars) {
4 | int n = chars.size();
5 |
6 | int i = 0, j = 0;
7 | while (i < n) {
8 | int cnt = 1;
9 | while (i < n - 1 && chars[i] == chars[i + 1]) {
10 | cnt++;
11 | i++;
12 | }
13 |
14 | chars[j++] = chars[i++];
15 | if (cnt > 1) {
16 | string num = to_string(cnt);
17 |
18 | for (char digit : num)
19 | chars[j++] = digit;
20 | }
21 | }
22 |
23 | return j;
24 | }
25 | };
26 |
--------------------------------------------------------------------------------
/Medium/443. String Compression/2 - String Compression.java:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public int compress(char[] chars) {
3 | int n = chars.length;
4 |
5 | int i = 0, j = 0;
6 | while (i < n) {
7 | int cnt = 1;
8 | while (i < n - 1 && chars[i] == chars[i + 1]) {
9 | cnt++;
10 | i++;
11 | }
12 |
13 | chars[j++] = chars[i++];
14 | if (cnt > 1) {
15 | char[] num = String.valueOf(cnt).toCharArray();
16 |
17 | for (char digit : num)
18 | chars[j++] = digit;
19 | }
20 | }
21 |
22 | return j;
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/Medium/443. String Compression/3 - String Compression.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def compress(self, chars: List[str]) -> int:
3 | n = len(chars)
4 |
5 | i = j = 0
6 | while i < n:
7 | cnt = 1
8 | while i < n - 1 and chars[i] == chars[i + 1]:
9 | cnt += 1
10 | i += 1
11 |
12 | chars[j] = chars[i]
13 | j += 1
14 | i += 1
15 |
16 | if cnt > 1:
17 | num = str(cnt)
18 |
19 | for digit in num:
20 | chars[j] = digit
21 | j += 1
22 |
23 | return j
24 |
--------------------------------------------------------------------------------
/Medium/443. String Compression/4 - String Compression.js:
--------------------------------------------------------------------------------
1 | /**
2 | * @param {character[]} chars
3 | * @return {number}
4 | */
5 | var compress = function(chars) {
6 | const n = chars.length;
7 |
8 | let i = 0, j = 0;
9 | while (i < n) {
10 | let cnt = 1;
11 | while (i < n - 1 && chars[i] == chars[i + 1]) {
12 | cnt++;
13 | i++;
14 | }
15 |
16 | chars[j++] = chars[i++];
17 | if (cnt > 1) {
18 | const num = cnt.toString();
19 |
20 | for (const digit of num)
21 | chars[j++] = digit;
22 | }
23 | }
24 |
25 | return j;
26 | };
27 |
--------------------------------------------------------------------------------
/Medium/443. String Compression/README.md:
--------------------------------------------------------------------------------
1 | # String Compression
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/string-compression/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/aPyS_ahM_1o)
10 |
--------------------------------------------------------------------------------
/Medium/45. Jump Game II/45. Jump Game II.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | int jump(vector& nums) {
4 | int n = nums.size(), jumps = 0, left = 0, right = 0;
5 |
6 | while (right < n - 1) {
7 | int newRight = right + 1;
8 | for (int i = left; i <= right; ++i)
9 | newRight = max(newRight, i + nums[i]);
10 |
11 | left = right + 1;
12 | right = newRight;
13 | jumps++;
14 | }
15 |
16 | return jumps;
17 | }
18 | };
19 |
--------------------------------------------------------------------------------
/Medium/45. Jump Game II/README.md:
--------------------------------------------------------------------------------
1 | # Jump Game II
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/jump-game-ii/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/m8guN8W-psk)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | int jump(vector& nums) {
19 | int n = nums.size(), jumps = 0, left = 0, right = 0;
20 |
21 | while (right < n - 1) {
22 | int newRight = right + 1;
23 | for (int i = left; i <= right; ++i)
24 | newRight = max(newRight, i + nums[i]);
25 |
26 | left = right + 1;
27 | right = newRight;
28 | jumps++;
29 | }
30 |
31 | return jumps;
32 | }
33 | };
34 | ```
35 |
--------------------------------------------------------------------------------
/Medium/491. Non-decreasing Subsequences/Non-decreasing Subsequences.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | private:
3 | int n;
4 | vector cur;
5 | set> subsequences;
6 | public:
7 | vector> findSubsequences(vector& nums) {
8 | n = nums.size();
9 | solve(0, nums);
10 | return vector(subsequences.begin(), subsequences.end());
11 | }
12 |
13 | void solve(int idx, vector &nums) {
14 | if (idx == n) {
15 | if (cur.size() > 1)
16 | subsequences.insert(cur);
17 |
18 | return;
19 | }
20 |
21 | if (cur.empty() || cur.back() <= nums[idx]) {
22 | cur.push_back(nums[idx]);
23 | solve(idx + 1, nums);
24 | cur.pop_back();
25 | }
26 |
27 | solve(idx + 1, nums);
28 | }
29 | };
30 |
--------------------------------------------------------------------------------
/Medium/491. Non-decreasing Subsequences/README.md:
--------------------------------------------------------------------------------
1 | # Non-decreasing Subsequences
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/non-decreasing-subsequences/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/FDm61BVNTJE)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | private:
18 | int n;
19 | vector cur;
20 | set> subsequences;
21 | public:
22 | vector> findSubsequences(vector& nums) {
23 | n = nums.size();
24 | solve(0, nums);
25 | return vector(subsequences.begin(), subsequences.end());
26 | }
27 |
28 | void solve(int idx, vector &nums) {
29 | if (idx == n) {
30 | if (cur.size() > 1)
31 | subsequences.insert(cur);
32 |
33 | return;
34 | }
35 |
36 | if (cur.empty() || cur.back() <= nums[idx]) {
37 | cur.push_back(nums[idx]);
38 | solve(idx + 1, nums);
39 | cur.pop_back();
40 | }
41 |
42 | solve(idx + 1, nums);
43 | }
44 | };
45 | ```
46 |
--------------------------------------------------------------------------------
/Medium/567. Permutation in String/Permutation in String.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | bool checkInclusion(string s1, string s2) {
4 | int sz1 = s1.size(), sz2 = s2.size();
5 | if (sz1 > sz2)
6 | return false;
7 |
8 | vector fr1(26), fr2(26);
9 | for (int i = 0; i < sz1; ++i) {
10 | fr1[s1[i] - 'a']++;
11 | fr2[s2[i] - 'a']++;
12 | }
13 |
14 | for (int i = 0; i < sz2 - sz1; ++i) {
15 | if (isPermutation(fr1, fr2))
16 | return true;
17 |
18 | fr2[s2[i] - 'a']--;
19 | fr2[s2[i + sz1] - 'a']++;
20 | }
21 |
22 | return isPermutation(fr1, fr2);
23 | }
24 |
25 | bool isPermutation(vector &fr1, vector &fr2) {
26 | for (int i = 0; i < 26; ++i)
27 | if (fr1[i] != fr2[i])
28 | return false;
29 |
30 | return true;
31 | }
32 | };
33 |
--------------------------------------------------------------------------------
/Medium/567. Permutation in String/README.md:
--------------------------------------------------------------------------------
1 | # Permutation in String
2 |
3 |
4 |
5 | ## The Problem: [LeetCode Link](https://leetcode.com/problems/permutation-in-string/)
6 |
7 |
8 |
9 | ## Video Solution: [Youtube Link](https://youtu.be/p_EmtOlPL6o)
10 |
11 |
12 |
13 | ## code
14 |
15 | ```cpp
16 | class Solution {
17 | public:
18 | bool checkInclusion(string s1, string s2) {
19 | int sz1 = s1.size(), sz2 = s2.size();
20 | if (sz1 > sz2)
21 | return false;
22 |
23 | vector fr1(26), fr2(26);
24 | for (int i = 0; i < sz1; ++i) {
25 | fr1[s1[i] - 'a']++;
26 | fr2[s2[i] - 'a']++;
27 | }
28 |
29 | for (int i = 0; i < sz2 - sz1; ++i) {
30 | if (isPermutation(fr1, fr2))
31 | return true;
32 |
33 | fr2[s2[i] - 'a']--;
34 | fr2[s2[i + sz1] - 'a']++;
35 | }
36 |
37 | return isPermutation(fr1, fr2);
38 | }
39 |
40 | bool isPermutation(vector &fr1, vector &fr2) {
41 | for (int i = 0; i < 26; ++i)
42 | if (fr1[i] != fr2[i])
43 | return false;
44 |
45 | return true;
46 | }
47 | };
48 | ```
49 |
--------------------------------------------------------------------------------
/Medium/57. Insert Interval/Insert Interval.cpp:
--------------------------------------------------------------------------------
1 | class Solution {
2 | public:
3 | vector> insert(vector>& intervals, vector& newInterval) {
4 | int n = intervals.size(), i = 0;
5 | vector