diff --git a/.obsidian/appearance.json b/.obsidian/appearance.json index d87f1f1..7324f87 100644 --- a/.obsidian/appearance.json +++ b/.obsidian/appearance.json @@ -1,5 +1,5 @@ { - "theme": "obsidian", + "theme": "moonstone", "translucency": true, "cssTheme": "Atom", "interfaceFontFamily": "IBM Plex Sans", diff --git a/.obsidian/backlink.json b/.obsidian/backlink.json new file mode 100644 index 0000000..80eb3a3 --- /dev/null +++ b/.obsidian/backlink.json @@ -0,0 +1,3 @@ +{ + "backlinkInDocument": false +} \ No newline at end of file diff --git a/.obsidian/graph.json b/.obsidian/graph.json index da196f7..e8aea86 100644 --- a/.obsidian/graph.json +++ b/.obsidian/graph.json @@ -39,6 +39,6 @@ "repelStrength": 10, "linkStrength": 1, "linkDistance": 250, - "scale": 0.7798887840302782, + "scale": 0.9328381822372834, "close": true } \ No newline at end of file diff --git a/Index.md b/Index.md index 55d6c83..ebbb62a 100644 --- a/Index.md +++ b/Index.md @@ -1,28 +1,32 @@ ``` - __ __ __ + __ __ __ ____ ____ / /____ / /_ ____ ____ / /__ / __ \/ __ \/ __/ _ \/ __ \/ __ \/ __ \/ //_/ - / / / / /_/ / /_/ __/ /_/ / /_/ / /_/ / ,< -/_/ /_/\____/\__/\___/_.___/\____/\____/_/|_| - + / / / / /_/ / /_/ __/ /_/ / /_/ / /_/ / ,< +/_/ /_/\____/\__/\___/_.___/\____/\____/_/|_| + ``` # My notebook -___ +--- + ## Table of contents ### Computer science notes + - [[OJ-index]] - [[CTF-index]] ### Misc + - [[Wiki-Index]] -___ +--- + ## Naming conventions - When using titles, capitalize the first character - When tagging, use lowercase when possible, for people's names, capitalize first, and capitalize acronyms - Replace chars that is not available with `_` -- Use singular form where possible \ No newline at end of file +- Use singular form where possible diff --git a/OJ notes/OJ-index.md b/OJ notes/OJ-index.md index 5356e9b..834df19 100644 --- a/OJ notes/OJ-index.md +++ b/OJ notes/OJ-index.md @@ -1,41 +1,76 @@ ``` - __ + __ _____ _____ ____ ____ / /____ _____ / ___/ / ___/ / __ \/ __ \/ __/ _ \/ ___/ -/ /__ (__ ) / / / / /_/ / /_/ __(__ ) -\___/ /____/ /_/ /_/\____/\__/\___/____/ - +/ /__ (__ ) / / / / /_/ / /_/ __(__ ) +\___/ /____/ /_/ /_/\____/\__/\___/____/ + ``` # CS notes This is where I store notes about CS -___ +--- ## Lists -#### Needs more understandings + +#### TODO + +```query +#TODO +``` + +#### Needs more understandings + +```query #CS_list_need_understanding +``` + #### Needs practicing + +```query #CS_list_need_practicing +``` + ## Websites #### [leetcode.com](https://leetcode.com) -#leetcode + +```query +#leetcode +``` #### [hackerearth.com](https://www.hackerearth.com/) + +```query #hackerearth +``` ## Data Structure -#DS + #### Coding problems -#coding_problem + +```query +#coding_problem and #DS +``` + #### Analysis -#CS_analysis + +```query +#CS_analysis and #DS +``` ## Algorithm -#algorithm + #### Coding problems -#coding_problem + +```query +tag:#coding_problem tag:#algorithm +``` + #### Analysis -#CS_analysis \ No newline at end of file + +```query +#CS_analysis #algorithm +``` diff --git a/OJ notes/pages/Binary Search Algorithm.md b/OJ notes/pages/Binary Search Algorithm.md index a2a7e0a..9c4503b 100644 --- a/OJ notes/pages/Binary Search Algorithm.md +++ b/OJ notes/pages/Binary Search Algorithm.md @@ -2,22 +2,33 @@ #### 2022-06-13 15:46 -___ +--- + ##### Algorithms: -#algorithm #binary_search + +#algorithm #binary_search + ##### Data structures: -#array #vector #set #multiset + +#array #vector #set #multiset + ##### Difficulty: + #CS_analysis #difficulty-easy + ##### Related problems: + ##### Links: + - [g4g for manual implementation](https://www.geeksforgeeks.org/binary-search/) - [cppreference, find](https://en.cppreference.com/w/cpp/container/set/find) -___ + +--- ### How to implement Binary search? #### a: Use cpp's library + Use cpp's set's [find](https://en.cppreference.com/w/cpp/container/set/find) or [equal_range](https://en.cppreference.com/w/cpp/container/multiset/equal_range) @@ -33,10 +44,11 @@ or [equal_range](https://en.cppreference.com/w/cpp/container/multiset/equal_rang > This happens if 1 is not subtracted 1. Use a while loop: -[[Leetcode Search-a-2D-Matrix#Solution]] + [[Leetcode Search-a-2D-Matrix#Solution]] 2. Use recursion: -from g4g: + from g4g: + ```cpp // C++ program to implement recursive Binary Search #include @@ -79,4 +91,4 @@ int main(void) { return 0; } -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Bit-Manipulation count true trick.md b/OJ notes/pages/Bit-Manipulation count true trick.md index df12a52..38389fc 100644 --- a/OJ notes/pages/Bit-Manipulation count true trick.md +++ b/OJ notes/pages/Bit-Manipulation count true trick.md @@ -3,15 +3,21 @@ #### 2022-07-22 15:11 > ##### Algorithms: -> #algorithm #bit_manipulation +> +> #algorithm #bit_manipulation +> > ##### Data Structure: -> #DS #bitset +> +> #DS #bitset +> > ##### Difficulty: +> > #CS_analysis #difficulty-easy +> > ##### Additional tags: -> ##### Related problems: + ### What is Bit-Manipulation count true trick? (n & (n - 1)) @@ -24,4 +30,4 @@ See [[Leetcode Power-of-Two#Method 1 using masking]] #### Counting 1 -See [[Leetcode Number-of-1-Bits#Method 2 n n - 1 method]] \ No newline at end of file +See [[Leetcode Number-of-1-Bits#Method 2 n n - 1 method]] diff --git a/OJ notes/pages/Breadth First Search.md b/OJ notes/pages/Breadth First Search.md index e83a538..76c507a 100644 --- a/OJ notes/pages/Breadth First Search.md +++ b/OJ notes/pages/Breadth First Search.md @@ -3,20 +3,29 @@ #### 2022-07-08 11:19 > ##### Algorithms: -> #algorithm #BFS +> +> #algorithm #BFS +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #CS_analysis #difficulty- +> > ##### Additional tags: -> ##### Related problems: + ##### Links: + - [cppreference]() -___ + +--- ### What is Breadth First Search? + means BFS ### How does Breadth First Search work? @@ -27,4 +36,4 @@ means BFS > [!tip] Whether to push root or root's nodes initially > When checking the symmetry, [[Leetcode Symmetric-Tree]], push nodes to make sure the stack can be poped correctly. -> otherwise, check if the root node is needed and minimum amount of nodes in the tree is larger than 1 \ No newline at end of file +> otherwise, check if the root node is needed and minimum amount of nodes in the tree is larger than 1 diff --git a/OJ notes/pages/Floyd's Cycle Finding Algorithm.md b/OJ notes/pages/Floyd's Cycle Finding Algorithm.md index 322c885..b06da32 100644 --- a/OJ notes/pages/Floyd's Cycle Finding Algorithm.md +++ b/OJ notes/pages/Floyd's Cycle Finding Algorithm.md @@ -2,19 +2,30 @@ #### 2022-06-14 22:10 -___ +--- + ##### Algorithms: -#algorithm #Floyd_s_cycle_finding_algorithm + +#algorithm #Floyd_s_cycle_finding_algorithm + ##### Data structures: -#linked_list + +#linked_list + ##### Difficulty: + #CS_analysis #difficulty-easy + ##### Related problems: + ##### Links: + - [g4g](https://www.geeksforgeeks.org/floyds-cycle-finding-algorithm/) -___ + +--- ### What is Floyd's Cycle Finding Algorithm? + [Floyd’s cycle finding algorithm](https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/) or Hare-Tortoise algorithm is a **pointer algorithm** that uses only **two pointers**, moving through the sequence at different speeds. It uses two pointers one moving twice as fast as the other one. The faster one is called the faster pointer and the other one is called the slow pointer. @@ -22,66 +33,70 @@ It uses two pointers one moving twice as fast as the other one. The faster one i ### How does it work? #### Part 1. **Verify** if there is a loop + While traversing the linked list one of these things will occur- -- The Fast pointer may reach the end (NULL) this shows that there is no loop n the linked list. -- The Fast pointer again **catches the slow pointer at some** time therefore a loop exists in the linked list. +- The Fast pointer may reach the end (NULL) this shows that there is no loop n the linked list. +- The Fast pointer again **catches the slow pointer at some** time therefore a loop exists in the linked list. **Pseudo-code:** -- Initialize two-pointers and start traversing the linked list. -- Move the slow pointer by one position. -- Move the fast pointer by **two** positions. -- If both pointers meet at some point then a loop exists and if the fast pointer meets the end position then no loop exists. +- Initialize two-pointers and start traversing the linked list. +- Move the slow pointer by one position. +- Move the fast pointer by **two** positions. +- If both pointers meet at some point then a loop exists and if the fast pointer meets the end position then no loop exists. + #### Part 2. **Locating the start** of the loop Let us consider an example: ![Why floyd algorithm work](https://media.geeksforgeeks.org/wp-content/uploads/20220105124053/6-300x139.jpg) -- Let, +- Let, > **X =** Distance between the head(starting) to the loop starting point. -> +> > **Y =** Distance between the loop starting point and the **first meeting point** of both the pointers. -> +> > **C =** The distance of **the loop** -- So before both the pointer meets- +- So before both the pointer meets- -> The slow pointer has traveled **X + Y + s * C** distance, where s is any positive constant number. -> -> The fast pointer has traveled **X + Y + f * C** distance, where f is any positive constant number. +> The slow pointer has traveled **X + Y + s \* C** distance, where s is any positive constant number. +> +> The fast pointer has traveled **X + Y + f \* C** distance, where f is any positive constant number. -- Since the fast pointer is moving twice as fast as the slow pointer, we can say that the fast pointer covered twice the distance the slow pointer covered. Therefore-                   +- Since the fast pointer is moving twice as fast as the slow pointer, we can say that the fast pointer covered twice the distance the slow pointer covered. Therefore- -> X + Y + f * C = 2 * (X + Y + s * C) -> -> X + Y = f * C – 2 * s * C -> +> X + Y + f _ C = 2 _ (X + Y + s \* C) +> +> X + Y = f _ C – 2 _ s \* C +> > We can say that, -> -> f * C – 2 * s * C = (some integer) * C -> ->                          = K * C -> +> +> f _ C – 2 _ s _ C = (some integer) _ C +> +> = K \* C +> > Thus, -> -> X + Y = K * C       **– ( 1 )** -> -> X = K * C – Y       **– ( 2 )** -> -> Where K is some positive constant.     +> +> X + Y = K \* C       **– ( 1 )** +> +> X = K \* C – Y       **– ( 2 )** +> +> Where K is some positive constant. -- Now if ==reset the slow pointer to the head==(starting position) and move both fast and slow pointer ==by one unit at a time==, one can observe from 1st and 2nd equation that **both of them will meet** after traveling X distance at the starting of the loop because after resetting the slow pointer and moving it X distance, at the same time from loop meeting point the fast pointer will also travel K * C – Y distance(because it already has traveled Y distance). -- Because X = K * C - Y, while fast pointer was at Y from start of loop, running X will place it at the start of loop, meeting the slow pointer. +- Now if ==reset the slow pointer to the head==(starting position) and move both fast and slow pointer ==by one unit at a time==, one can observe from 1st and 2nd equation that **both of them will meet** after traveling X distance at the starting of the loop because after resetting the slow pointer and moving it X distance, at the same time from loop meeting point the fast pointer will also travel K \* C – Y distance(because it already has traveled Y distance). +- Because X = K \* C - Y, while fast pointer was at Y from start of loop, running X will place it at the start of loop, meeting the slow pointer. **Pseudo-code** + - Place slow pointer at the head. - Move one step at a time until they met. - The start of the loop is where they met #### Example + ```cpp // C++ program to implement // the above approach @@ -172,8 +187,9 @@ int main() { } ``` + ### When to use? This algorithm is used ==to find a loop in a linked list==, Also it ==can locate where the loop starts.== -It takes O(n) time complexity, O(1)space complexity. \ No newline at end of file +It takes O(n) time complexity, O(1)space complexity. diff --git a/OJ notes/pages/Kadane's Algorithm.md b/OJ notes/pages/Kadane's Algorithm.md index ba941d9..da2ce8d 100644 --- a/OJ notes/pages/Kadane's Algorithm.md +++ b/OJ notes/pages/Kadane's Algorithm.md @@ -3,19 +3,31 @@ #### 2022-06-09 --- + ##### Data structures: + #array + ##### Algorithms: -#algorithm #Kadane_s_algorithm + +#algorithm #Kadane_s_algorithm + ##### Difficulty: + #CS_analysis #difficulty-easy + ##### Time complexity: + O(n) + ##### Related problems: + ##### Resources: + - [Explainer article](https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d) --- + ### What is Kadane's Algorithm? It's a kind of dynamic programming. You calculate A[n] by calculating A[n - 1], which makes it O(n) @@ -27,6 +39,7 @@ It's a kind of dynamic programming. You calculate A[n] by calculating A[n - 1], ### When to use it? According my analyze [[Leetcode Best-Time-To-Buy-And-Sell-Stock#Thoughts| here]], we should use it when these conditions are met: + - You want to find the value of the highest peak or lowest valley - The direction you search is mono-directional -- The current value can be obtained from or, is related to the value before this one. \ No newline at end of file +- The current value can be obtained from or, is related to the value before this one. diff --git a/OJ notes/pages/Leetcode 01-Matrix.md b/OJ notes/pages/Leetcode 01-Matrix.md index 08a0b2e..5490ec2 100644 --- a/OJ notes/pages/Leetcode 01-Matrix.md +++ b/OJ notes/pages/Leetcode 01-Matrix.md @@ -3,20 +3,33 @@ #### 2022-07-17 03:15 > ##### Algorithms: -> #algorithm #BFS +> +> #algorithm #BFS +> > ##### Data structures: -> #DS #vector_2d +> +> #DS #vector_2d +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode #CS_list_need_understanding +> +> #leetcode #CS_list_need_understanding +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/01-matrix/) -___ + +--- + ### Problem Given an `m x n` binary matrix `mat`, return _the distance of the nearest_ `0` _for each cell_. @@ -45,25 +58,26 @@ The distance between two adjacent cells is `1`. #### Constraints -- `m == mat.length` -- `n == mat[i].length` -- `1 <= m, n <= 104` -- `1 <= m * n <= 104` -- `mat[i][j]` is either `0` or `1`. -- There is at least one `0` in `mat`. +- `m == mat.length` +- `n == mat[i].length` +- `1 <= m, n <= 104` +- `1 <= m * n <= 104` +- `mat[i][j]` is either `0` or `1`. +- There is at least one `0` in `mat`. ### Thoughts > [!summary] > This is a #BFS problem, because it needs to find -> a smallest distance +> a smallest distance #### Why not DFS I tried with DFS, but -1. it is not suitable for finding smallest distance + +1. it is not suitable for finding smallest distance 2. and is easy to go into a infinite loop. -3. Also, it is hard to determine whether to revisit (update) +3. Also, it is hard to determine whether to revisit (update) the distance. #### BFS @@ -73,15 +87,16 @@ Start searching from 0s, because the search direction matters. pseudo code: - Initialization stage: - - add every 0 to queue - - make every 1 a infinite large number, (10001 this case) + + - add every 0 to queue + - make every 1 a infinite large number, (10001 this case) - while queue is not empty - - check for neighbors - - if OOB (Out of Bound), skip - - if the value of neighbor's distance is higher than - the node, update it, and add it to queue(also update - his neighbors) + - check for neighbors + - if OOB (Out of Bound), skip + - if the value of neighbor's distance is higher than + the node, update it, and add it to queue(also update + his neighbors) ### Solution @@ -134,4 +149,4 @@ public: return mat; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Average-Salary-Excluding-the-Minimum-and-Maximum-Salary.md b/OJ notes/pages/Leetcode Average-Salary-Excluding-the-Minimum-and-Maximum-Salary.md index 5de47e0..a8e362a 100644 --- a/OJ notes/pages/Leetcode Average-Salary-Excluding-the-Minimum-and-Maximum-Salary.md +++ b/OJ notes/pages/Leetcode Average-Salary-Excluding-the-Minimum-and-Maximum-Salary.md @@ -3,16 +3,25 @@ #### 2022-07-23 15:27 > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode #math +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/average-salary-excluding-the-minimum-and-maximum-salary/) -___ + +--- + ### Problem You are given an array of **unique** integers `salary` where `salary[i]` is the salary of the `ith` employee. @@ -37,9 +46,9 @@ Average salary excluding minimum and maximum salary is (2000) / 1 = 2000 #### Constraints -- `3 <= salary.length <= 100` -- `1000 <= salary[i] <= 106` -- All the integers of `salary` are **unique**. +- `3 <= salary.length <= 100` +- `1000 <= salary[i] <= 106` +- All the integers of `salary` are **unique**. ### Thoughts @@ -67,4 +76,4 @@ public: return ans - minSal / factor - maxSal / factor; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Best-Time-To-Buy-And-Sell-Stock.md b/OJ notes/pages/Leetcode Best-Time-To-Buy-And-Sell-Stock.md index 5cbee5b..5d349cd 100644 --- a/OJ notes/pages/Leetcode Best-Time-To-Buy-And-Sell-Stock.md +++ b/OJ notes/pages/Leetcode Best-Time-To-Buy-And-Sell-Stock.md @@ -3,19 +3,30 @@ #### 2022-06-11 --- + ##### Data structures: -#DS #array + +#DS #array + ##### Algorithms: + #algorithm #Kadane_s_algorithm + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) - [Kadane's Algo solution](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solution/554875) -___ +--- + ### Problem + You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. You want to maximize your profit by choosing a **single day** to buy one stock and choosing a **different day in the future** to sell that stock. @@ -23,6 +34,7 @@ You want to maximize your profit by choosing a **single day** to buy one stock a Return _the maximum profit you can achieve from this transaction_. If you cannot achieve any profit, return `0`. #### Examples + Example 1: ``` @@ -44,21 +56,23 @@ Explanation: In this case, no transactions are done and the max profit = 0. #### Constraints -- 1 <= prices.length <= 105 -- 0 <= prices[i] <= 104 +- 1 <= prices.length <= 105 +- 0 <= prices[i] <= 104 ### Thoughts -Firstly I thought of brute forcing, which is O(n * (n-1)) +Firstly I thought of brute forcing, which is O(n \* (n-1)) Then, I came up with dynamic programming, but this is still not so optimized Lastly, from [here](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solution/554875) I know We can use Kadane's algo. > [!tip] > In Kadane's algorithm: +> > - buyprice = min(buyprice, price[i]) // Achieve best min price > - profit = max(profit, price[i] - buyprice) // find best profit **==so far==** To explain that, in each iteration, there are two cases: + - if the current price is the lowest, set the buyprice to the lowest one - if the current price minus the `buyprice` is bigger tham profit, record that to profit. @@ -67,6 +81,7 @@ So, the magic part happens **at setting the buyprice**, because the best profit ### Solution Time O(2n) Space O(n) solution (inefficient reverse kadane's algorithm) + ```cpp class Solution { public: @@ -94,6 +109,7 @@ public: ``` Kadane's algorithm, Time O(n) Space O(1) + ```cpp class Solution { public: @@ -112,4 +128,4 @@ public: return profit; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Binary-Search.md b/OJ notes/pages/Leetcode Binary-Search.md index 65f9b11..9f2d7a2 100644 --- a/OJ notes/pages/Leetcode Binary-Search.md +++ b/OJ notes/pages/Leetcode Binary-Search.md @@ -3,20 +3,33 @@ #### 2022-07-09 09:34 > ##### Algorithms: -> #algorithm #binary_search +> +> #algorithm #binary_search +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode #CS_list_need_practicing +> +> #leetcode #CS_list_need_practicing +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/binary-search/) -___ + +--- + ### Problem Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`. @@ -39,10 +52,10 @@ You must write an algorithm with `O(log n)` runtime complexity. #### Constraints -- `1 <= nums.length <= 104` -- `-104 < nums[i], target < 104` -- All the integers in `nums` are **unique**. -- `nums` is sorted in ascending order. +- `1 <= nums.length <= 104` +- `-104 < nums[i], target < 104` +- All the integers in `nums` are **unique**. +- `nums` is sorted in ascending order. ### Thoughts @@ -50,9 +63,11 @@ You must write an algorithm with `O(log n)` runtime complexity. > This is a #binary_search problem. Key takeout: + ``` int r = nums.size() - 1; ``` + make sure r is never OOB (l == r && r = array.size()) ### Solution @@ -60,6 +75,7 @@ make sure r is never OOB (l == r && r = array.size()) ==#TODO: write in recursion== iteration + ```cpp class Solution { public: @@ -87,4 +103,4 @@ public: return -1; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Binary-Tree-Inorder-Traversal.md b/OJ notes/pages/Leetcode Binary-Tree-Inorder-Traversal.md index e48b549..dd72c39 100644 --- a/OJ notes/pages/Leetcode Binary-Tree-Inorder-Traversal.md +++ b/OJ notes/pages/Leetcode Binary-Tree-Inorder-Traversal.md @@ -3,24 +3,39 @@ #### 2022-07-04 15:42 > ##### Algorithms: +> > #algorithm #DFS #DFS_inorder +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/binary-tree-inorder-traversal/) -___ + +--- + ### Problem + Given the `root` of a binary tree, return _the inorder traversal of its nodes' values_. #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg) @@ -39,8 +54,9 @@ Given the `root` of a binary tree, return _the inorder traversal of its nodes' v **Output:** [1] #### Constraints -- The number of nodes in the tree is in the range `[0, 100]`. -- `-100 <= Node.val <= 100` + +- The number of nodes in the tree is in the range `[0, 100]`. +- `-100 <= Node.val <= 100` ### Thoughts @@ -48,9 +64,11 @@ Given the `root` of a binary tree, return _the inorder traversal of its nodes' v > This is a #DFS traversal problem Many of them are same to [[Leetcode Binary-Tree-Preorder-Traversal]] + ### Solution Recursion + ```cpp /** * Definition for a binary tree node. @@ -86,6 +104,7 @@ public: ``` Iteration + ```cpp /** * Definition for a binary tree node. @@ -123,4 +142,4 @@ public: } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Binary-Tree-Level-Order-Traversal.md b/OJ notes/pages/Leetcode Binary-Tree-Level-Order-Traversal.md index 19b0507..3ca8cfd 100644 --- a/OJ notes/pages/Leetcode Binary-Tree-Level-Order-Traversal.md +++ b/OJ notes/pages/Leetcode Binary-Tree-Level-Order-Traversal.md @@ -3,24 +3,39 @@ #### 2022-07-05 09:09 > ##### Algorithms: +> > #algorithm #BFS +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/binary-tree-level-order-traversal/) -___ + +--- + ### Problem + Given the `root` of a binary tree, return _the level order traversal of its nodes' values_. (i.e., from left to right, level by level). #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg) @@ -39,8 +54,10 @@ Given the `root` of a binary tree, return _the level order traversal of its node **Output:** [] #### Constraints -- The number of nodes in the tree is in the range `[0, 2000]`. -- `-1000 <= Node.val <= 1000` + +- The number of nodes in the tree is in the range `[0, 2000]`. +- `-1000 <= Node.val <= 1000` + ### Thoughts > [!summary] @@ -54,6 +71,7 @@ vec.push_back({}); vec.back().push_back(5); // [[ 5 ]] ``` + ### Solution ```cpp @@ -99,4 +117,4 @@ public: return answer; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Binary-Tree-Postorder-Traversal.md b/OJ notes/pages/Leetcode Binary-Tree-Postorder-Traversal.md index fd72635..5a51334 100644 --- a/OJ notes/pages/Leetcode Binary-Tree-Postorder-Traversal.md +++ b/OJ notes/pages/Leetcode Binary-Tree-Postorder-Traversal.md @@ -3,23 +3,39 @@ #### 2022-07-04 21:31 > ##### Algorithms: -> #algorithm #DFS #DFS_postorder +> +> #algorithm #DFS #DFS_postorder +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty- +> > ##### Additional tags: -> #leetcode #CS_list_need_practicing +> +> #leetcode #CS_list_need_practicing +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/binary-tree-postorder-traversal/) -___ + +--- + ### Problem + https://leetcode.com/problems/binary-tree-postorder-traversal/ + #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2020/08/28/pre1.jpg) @@ -39,17 +55,19 @@ https://leetcode.com/problems/binary-tree-postorder-traversal/ #### Constraints -- The number of the nodes in the tree is in the range `[0, 100]`. -- `-100 <= Node.val <= 100` +- The number of the nodes in the tree is in the range `[0, 100]`. +- `-100 <= Node.val <= 100` ### Thoughts Same as [[Leetcode Binary-Tree-Inorder-Traversal]] and [[Leetcode Binary-Tree-Preorder-Traversal]] == TODO: write iteration and another algo #TODO == + ### Solution Recursion + ```cpp /** * Definition for a binary tree node. @@ -82,4 +100,4 @@ public: } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Binary-Tree-Preorder-Traversal.md b/OJ notes/pages/Leetcode Binary-Tree-Preorder-Traversal.md index c7d80eb..e7afcb4 100644 --- a/OJ notes/pages/Leetcode Binary-Tree-Preorder-Traversal.md +++ b/OJ notes/pages/Leetcode Binary-Tree-Preorder-Traversal.md @@ -3,24 +3,39 @@ #### 2022-07-04 14:51 > ##### Algorithms: +> > #algorithm #DFS #DFS_preorder #Morris_traversal +> > ##### Data structures: +> > #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode #CS_list_need_understanding +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/binary-tree-preorder-traversal/) -___ + +--- + ### Problem + Given the `root` of a binary tree, return _the preorder traversal of its nodes' values_. #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg) @@ -37,13 +52,16 @@ Given the `root` of a binary tree, return _the preorder traversal of its nodes' **Input:** root = [1] **Output:** [1] + #### Constraints -- The number of nodes in the tree is in the range `[0, 100]`. -- `-100 <= Node.val <= 100` + +- The number of nodes in the tree is in the range `[0, 100]`. +- `-100 <= Node.val <= 100` + ### Thoughts > [!summary] -> This is a #binary_tree #DFS_preorder problem. +> This is a #binary_tree #DFS_preorder problem. Preorder, means root is at the "Pre" position, so the order is: @@ -59,7 +77,9 @@ And remember to push **right subtree** first, so that the left one will be trave The Morris traversal needs more understandings. ### Solution + Iteration + ```cpp /** * Definition for a binary tree node. @@ -100,7 +120,9 @@ public: }; ``` + Recursion, using private funcs: + ```cpp /** * Definition for a binary tree node. @@ -137,6 +159,7 @@ private: ``` Recursion: + ```cpp /** * Definition for a binary tree node. diff --git a/OJ notes/pages/Leetcode Check-If-It-Is-a-Straight-Line.md b/OJ notes/pages/Leetcode Check-If-It-Is-a-Straight-Line.md index bd2a0df..782233d 100644 --- a/OJ notes/pages/Leetcode Check-If-It-Is-a-Straight-Line.md +++ b/OJ notes/pages/Leetcode Check-If-It-Is-a-Straight-Line.md @@ -3,18 +3,29 @@ #### 2022-07-27 11:38 > ##### Algorithms: -> #algorithm #math +> +> #algorithm #math +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/check-if-it-is-a-straight-line/) -___ + +--- + ### Problem You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane. @@ -56,6 +67,7 @@ This is also true in this problem. We want to calculate the k for every consecutive points, if they are the same, they are on one straight line. By starting from the first, using them as the base k: + ``` k = (dx0 - dx1) / (dy0 - dy1) = (dx - dx') / (dy - dy') | @@ -68,6 +80,7 @@ Which is the cross product of these two points. ### Solution ==#TODO: Fill this out== + ```cpp WIP -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Climbing-Chairs.md b/OJ notes/pages/Leetcode Climbing-Chairs.md index a6fc9f9..f7498a2 100644 --- a/OJ notes/pages/Leetcode Climbing-Chairs.md +++ b/OJ notes/pages/Leetcode Climbing-Chairs.md @@ -3,18 +3,29 @@ #### 2022-07-20 14:37 > ##### Algorithms: +> > #algorithm #dynamic_programming +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/climbing-stairs/submissions/) -___ + +--- + ### Problem You are climbing a staircase. It takes `n` steps to reach the top. @@ -28,6 +39,7 @@ Each time you can either climb `1` or `2` steps. In how many distinct ways can y **Input:** n = 2 **Output:** 2 **Explanation:** There are two ways to climb to the top. + 1. 1 step + 1 step 2. 2 steps @@ -36,6 +48,7 @@ Each time you can either climb `1` or `2` steps. In how many distinct ways can y **Input:** n = 3 **Output:** 3 **Explanation:** There are three ways to climb to the top. + 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step @@ -54,8 +67,9 @@ I had come up with an recursive solution, with a little bit of optimizations. #### First iteration: Base case: + - n is 0, 1, 2: - return n + return n Pseudo code: answer = climb(n - 1) + climb(n - 2); @@ -65,8 +79,9 @@ This is a brute force-y solution, because there are too much combinations, and w #### Second iteration: Base case: + - n = 1, 2, **3** - Return n + Return n Note that n == 3 is added, because we will calculate n - 3, which otherwise will make n = 0 @@ -74,8 +89,8 @@ and when n == 0, it should return 1. > [!tips] Optimization > We can optimize it because some solutions can be -> calculated and used for both 1 step and 2 steps. -> +> calculated and used for both 1 step and 2 steps. +> > how many ways to climb: one step or two steps > 1 + 1 = 2 > 0 + 2 = 2 @@ -85,6 +100,7 @@ and when n == 0, it should return 1. ### Solution Optimized version: + ```cpp class Solution { public: @@ -103,4 +119,4 @@ public: return 2 * climbStairs(n - 2) + climbStairs(n - 3); } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Combinations.md b/OJ notes/pages/Leetcode Combinations.md index 1d53e8d..73b256b 100644 --- a/OJ notes/pages/Leetcode Combinations.md +++ b/OJ notes/pages/Leetcode Combinations.md @@ -3,19 +3,30 @@ #### 2022-07-19 20:09 > ##### Algorithms: +> > #algorithm #backtrack +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode #CS_list_need_understanding +> +> #leetcode #CS_list_need_understanding +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/combinations/) - [Explanation](https://leetcode.com/problems/combinations/discuss/844096/Backtracking-cheatsheet-%2B-simple-solution) -___ + +--- + ### Problem Given two integers `n` and `k`, return _all possible combinations of_ `k` _numbers out of the range_ `[1, n]`. @@ -50,8 +61,8 @@ You may return the answer in **any order**. **Constraints:** -- `1 <= n <= 20` -- `1 <= k <= n` +- `1 <= n <= 20` +- `1 <= k <= n` ### Thoughts @@ -69,6 +80,7 @@ And when it's done, it gets poped out and try another solution, and backtrack. ### Solution Backtracking + ```cpp class Solution { void backtrack(vector> &ans, vector &combs, int n, int nex, diff --git a/OJ notes/pages/Leetcode Count-Odd-Numbers-in-an-Interval-Range.md b/OJ notes/pages/Leetcode Count-Odd-Numbers-in-an-Interval-Range.md index 5d41f07..30cca66 100644 --- a/OJ notes/pages/Leetcode Count-Odd-Numbers-in-an-Interval-Range.md +++ b/OJ notes/pages/Leetcode Count-Odd-Numbers-in-an-Interval-Range.md @@ -3,21 +3,32 @@ #### 2022-07-23 15:09 > ##### Algorithms: +> > #algorithm #math +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/count-odd-numbers-in-an-interval-range/) -___ + +--- + ### Problem -Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` _(inclusive)_. +Given two non-negative integers `low` and `high`. Return the _count of odd numbers between_ `low` _and_ `high` *(inclusive)*. #### Examples @@ -35,7 +46,7 @@ Given two non-negative integers `low` and `high`. Return the _count of odd numbe #### Constraints -- `0 <= low <= high <= 10^9` +- `0 <= low <= high <= 10^9` ### Thoughts @@ -56,4 +67,4 @@ public: return ((low % 2) | (high % 2)) + (high - low) / 2; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Design-Hash.md b/OJ notes/pages/Leetcode Design-Hash.md index 86c6f44..1fcabd3 100644 --- a/OJ notes/pages/Leetcode Design-Hash.md +++ b/OJ notes/pages/Leetcode Design-Hash.md @@ -3,28 +3,38 @@ #### 2022-09-01 14:44 > ##### Data structures: -> #DS #array #linked_list +> +> #DS #array #linked_list +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode #CS_list_need_practicing +> +> #leetcode #CS_list_need_practicing +> > ##### Revisions: +> > N/A ##### Links: + - [Link to problem](https://leetcode.com/problems/design-hashmap/) -- [Explanation](https://leetcode.com/problems/design-hashmap/discuss/1097755/JS-Python-Java-C%2B%2B-or-(Updated)-Hash-and-Array-Solutions-w-Explanation) -___ +- [Explanation]() + +--- + ### Problem Design a HashMap without using any built-in hash table libraries. Implement the `MyHashMap` class: -- `MyHashMap()` initializes the object with an empty map. -- `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`. -- `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`. -- `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`. +- `MyHashMap()` initializes the object with an empty map. +- `void put(int key, int value)` inserts a `(key, value)` pair into the HashMap. If the `key` already exists in the map, update the corresponding `value`. +- `int get(int key)` returns the `value` to which the specified `key` is mapped, or `-1` if this map contains no mapping for the `key`. +- `void remove(key)` removes the `key` and its corresponding `value` if the map contains the mapping for the `key`. #### Examples @@ -40,17 +50,17 @@ Implement the `MyHashMap` class: MyHashMap myHashMap = new MyHashMap(); myHashMap.put(1, 1); // The map is now [[1,1]] myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] -myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]] -myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]] +myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]] +myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]] myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value) -myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]] +myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]] myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]] -myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]] +myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]] #### Constraints -- `0 <= key, value <= 106` -- At most `104` calls will be made to `put`, `get`, and `remove`. +- `0 <= key, value <= 106` +- At most `104` calls will be made to `put`, `get`, and `remove`. ### Thoughts @@ -67,7 +77,7 @@ Using hashes with linked list to support collision check. ### Solution -Easy way: +Easy way: ```cpp class MyHashMap { @@ -90,4 +100,4 @@ public: * int param_2 = obj->get(key); * obj->remove(key); */ -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode First-Bad-Version.md b/OJ notes/pages/Leetcode First-Bad-Version.md index 2912a7c..bb0f947 100644 --- a/OJ notes/pages/Leetcode First-Bad-Version.md +++ b/OJ notes/pages/Leetcode First-Bad-Version.md @@ -3,20 +3,33 @@ #### 2022-07-09 09:52 > ##### Algorithms: -> #algorithm #binary_search +> +> #algorithm #binary_search +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/first-bad-version/) -___ + +--- + ### Problem You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. @@ -44,18 +57,18 @@ Then 4 is the first bad version. #### Constraints -- `1 <= bad <= n <= 231 - 1` +- `1 <= bad <= n <= 231 - 1` ### Thoughts > [!summary] > This is a #binary_search problem -Note that [[Leetcode First-Bad-Version#Constraints]], n can be 2**31, which means there might be integer overflow. +Note that [[Leetcode First-Bad-Version#Constraints]], n can be 2\*\*31, which means there might be integer overflow. To address that, according to [[Binary Search Algorithm#How to implement Binary search]], use `mid = l + (r - l) / 2` -In my first iteration, +In my first iteration, I use a `first` variable to keep track of the first bad version. Later I realized that by the definition of Bi-search, left boundary will converge to the first one. @@ -63,6 +76,7 @@ Later I realized that by the definition of Bi-search, left boundary will converg ### Solution Second version, 0ms + ```cpp // The API isBadVersion is defined for you. // bool isBadVersion(int version); @@ -72,14 +86,14 @@ public: int firstBadVersion(int n) { // variant of BS // 1-indexed - + int r = n; int l = 1; int mid; - + do { mid = l + (r - l) / 2; - + if (isBadVersion(mid)) { // Search left r = mid - 1; @@ -87,13 +101,14 @@ public: l = mid + 1; } } while (l <= r); - + return l; } }; ``` First iteration, 4ms + ```cpp // The API isBadVersion is defined for you. // bool isBadVersion(int version); @@ -103,15 +118,15 @@ public: int firstBadVersion(int n) { // variant of BS // 1-indexed - + int r = n; int l = 1; int mid; int first = n; - + do { mid = l + (r - l) / 2; - + if (isBadVersion(mid)) { first = min(n, mid); // Search left @@ -120,8 +135,8 @@ public: l = mid + 1; } } while (l <= r); - + return first; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode First-Unique-Character-In-a-String.md b/OJ notes/pages/Leetcode First-Unique-Character-In-a-String.md index 2d28c0d..2a85238 100644 --- a/OJ notes/pages/Leetcode First-Unique-Character-In-a-String.md +++ b/OJ notes/pages/Leetcode First-Unique-Character-In-a-String.md @@ -3,22 +3,35 @@ #### 2022-06-14 13:10 --- + ##### Algorithms: -#algorithm + +#algorithm + ##### Data structures: + #DS #string #array #hash_table + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/first-unique-character-in-a-string/) -___ + +--- + ### Problem + Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`. #### Examples **Example 1:** + ```markdown **Input:** s = "leetcode" **Output:** 0 @@ -39,13 +52,15 @@ Given a string `s`, _find the first non-repeating character in it and return its ``` #### Constraints -- `1 <= s.length <= 105` -- `s` consists of only lowercase English letters. + +- `1 <= s.length <= 105` +- `s` consists of only lowercase English letters. ### Thoughts Really, really simple hash map problem. Shouldn't have taken so much time. + > [!summary] > Don't overlook simple problems! #tip @@ -57,12 +72,12 @@ public: int firstUniqChar(string s) { // O(1) hashmap int umap[26] = {}; - + int sSize = s.size(); for (int i = 0; i < sSize; i++) { umap[s[i] - 'a']++; } - + for (int i = 0; i < sSize; i++) { if (umap[s[i] - 'a'] == 1) { return i; @@ -71,4 +86,4 @@ public: return -1; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Flood-Fill.md b/OJ notes/pages/Leetcode Flood-Fill.md index 3296ef7..bda6afa 100644 --- a/OJ notes/pages/Leetcode Flood-Fill.md +++ b/OJ notes/pages/Leetcode Flood-Fill.md @@ -3,20 +3,33 @@ #### 2022-07-15 09:01 > ##### Algorithms: +> > #algorithm #BFS +> > ##### Data structures: +> > #DS +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/flood-fill/) -___ + +--- + ### Problem An image is represented by an `m x n` integer grid `image` where `image[i][j]` represents the pixel value of the image. @@ -50,12 +63,12 @@ Note the bottom corner is not colored 2, because it is not 4-directionally conne #### Constraints -- `m == image.length` -- `n == image[i].length` -- `1 <= m, n <= 50` -- `0 <= image[i][j], color < 216` -- `0 <= sr < m` -- `0 <= sc < n` +- `m == image.length` +- `n == image[i].length` +- `1 <= m, n <= 50` +- `0 <= image[i][j], color < 216` +- `0 <= sr < m` +- `0 <= sc < n` ### Thoughts @@ -64,16 +77,18 @@ Note the bottom corner is not colored 2, because it is not 4-directionally conne This one can be optimized. -Initially, I wanted to use a hash map to record cells that are visited, +Initially, I wanted to use a hash map to record cells that are visited, but the this takes up extra space. Then I found out that I can use colors: -- if image[r][c] == color, this means - - the cell is no need to correct(color == origcolor), - - or this has been corrected - so I don't have to go over again. + +- if image[r][c] == color, this means + - the cell is no need to correct(color == origcolor), + - or this has been corrected + so I don't have to go over again. There are checks in the loop: + - check the color is not visited, as shown above - check the coord is not OOB - check the cell is equal to origColor, to only fill same origColor. @@ -124,4 +139,4 @@ public: return image; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Happy-Number.md b/OJ notes/pages/Leetcode Happy-Number.md index c17dbc1..85c2876 100644 --- a/OJ notes/pages/Leetcode Happy-Number.md +++ b/OJ notes/pages/Leetcode Happy-Number.md @@ -3,27 +3,38 @@ #### 2022-07-26 09:12 > ##### Algorithms: -> #algorithm #Floyd_s_cycle_finding_algorithm +> +> #algorithm #Floyd_s_cycle_finding_algorithm +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/happy-number/) -___ + +--- + ### Problem Write an algorithm to determine if a number `n` is happy. A **happy number** is a number defined by the following process: -- Starting with any positive integer, replace the number by the sum of the squares of its digits. -- Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1. -- Those numbers for which this process **ends in 1** are happy. +- Starting with any positive integer, replace the number by the sum of the squares of its digits. +- Repeat the process until the number equals 1 (where it will stay), or it **loops endlessly in a cycle** which does not include 1. +- Those numbers for which this process **ends in 1** are happy. Return `true` _if_ `n` _is a happy number, and_ `false` _if not_. @@ -46,12 +57,12 @@ Return `true` _if_ `n` _is a happy number, and_ `false` _if not_. #### Constraints -- `1 <= n <= 231 - 1` +- `1 <= n <= 231 - 1` ### Thoughts > [!summary] -> This is a #Floyd_s_cycle_finding_algorithm +> This is a #Floyd_s_cycle_finding_algorithm This works, because as the problem mentioned, this will result in a endless loop. @@ -93,4 +104,4 @@ public: return false; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode House-Robber.md b/OJ notes/pages/Leetcode House-Robber.md index 9165f06..1e517d3 100644 --- a/OJ notes/pages/Leetcode House-Robber.md +++ b/OJ notes/pages/Leetcode House-Robber.md @@ -3,19 +3,30 @@ #### 2022-07-20 22:21 > ##### Algorithms: -> #algorithm #dynamic_programming +> +> #algorithm #dynamic_programming +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/house-robber/) - [Tutorial and explanation on DP](https://leetcode.com/problems/house-robber/discuss/156523/From-good-to-great.-How-to-approach-most-of-DP-problems.) -___ + +--- + ### Problem You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and **it will automatically contact the police if two adjacent houses were broken into on the same night**. @@ -44,8 +55,8 @@ Total amount you can rob = 2 + 9 + 1 = 12. #### Constraints -- `1 <= nums.length <= 100` -- `0 <= nums[i] <= 400` +- `1 <= nums.length <= 100` +- `0 <= nums[i] <= 400` ### Thoughts @@ -59,6 +70,7 @@ According to [This tuturial](https://leetcode.com/problems/house-robber/discuss/ The robbing problem can be simplified as follows: > Whether to rob or not? +> > - if rob, profit = nums[n] + rob(nums, n - 2) > - else, profit = rob(nums, n - 1) @@ -174,4 +186,4 @@ public: return next; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Implement-Queue-Using-Stacks.md b/OJ notes/pages/Leetcode Implement-Queue-Using-Stacks.md index 0c11430..4a67613 100644 --- a/OJ notes/pages/Leetcode Implement-Queue-Using-Stacks.md +++ b/OJ notes/pages/Leetcode Implement-Queue-Using-Stacks.md @@ -3,39 +3,54 @@ #### 2022-07-03 09:52 > ##### Data structures: +> > #DS #stack #queue +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode #CS_list_need_understanding +> +> #leetcode #CS_list_need_understanding +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/implement-queue-using-stacks/submissions/) -___ + +--- + ### Problem + Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`). Implement the `MyQueue` class: -- `void push(int x)` Pushes element x to the back of the queue. -- `int pop()` Removes the element from the front of the queue and returns it. -- `int peek()` Returns the element at the front of the queue. -- `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. +- `void push(int x)` Pushes element x to the back of the queue. +- `int pop()` Removes the element from the front of the queue and returns it. +- `int peek()` Returns the element at the front of the queue. +- `boolean empty()` Returns `true` if the queue is empty, `false` otherwise. **Notes:** -- You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. -- Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. +- You must use **only** standard operations of a stack, which means only `push to top`, `peek/pop from top`, `size`, and `is empty` operations are valid. +- Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations. #### Examples + **Input** + ``` ["MyQueue", "push", "push", "peek", "pop", "empty"] [[], [1], [2], [], [], []] ``` + **Output** [null, null, null, 1, 1, false] @@ -48,11 +63,12 @@ myQueue.pop(); // return 1, queue is [2] myQueue.empty(); // return false #### Constraints + **Constraints:** -- `1 <= x <= 9` -- At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. -- All the calls to `pop` and `peek` are valid. +- `1 <= x <= 9` +- At most `100` calls will be made to `push`, `pop`, `peek`, and `empty`. +- All the calls to `pop` and `peek` are valid. ### Thoughts @@ -105,4 +121,4 @@ public: * int param_3 = obj->peek(); * bool param_4 = obj->empty(); */ -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Insert-Into-a-Binary-Search-Tree.md b/OJ notes/pages/Leetcode Insert-Into-a-Binary-Search-Tree.md index e2bad75..86b239a 100644 --- a/OJ notes/pages/Leetcode Insert-Into-a-Binary-Search-Tree.md +++ b/OJ notes/pages/Leetcode Insert-Into-a-Binary-Search-Tree.md @@ -3,20 +3,33 @@ #### 2022-07-07 08:50 > ##### Algorithms: -> #algorithm #recursion #DFS +> +> #algorithm #recursion #DFS +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/insert-into-a-binary-search-tree/) -___ + +--- + ### Problem You are given the root node of a binary search tree (BST) and a value to insert into the tree. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST. @@ -46,11 +59,11 @@ Notice that there may exist multiple valid ways for the insertion, as long as th #### Constraints -- The number of nodes in the tree will be in the range `[0, 104]`. -- `-108 <= Node.val <= 108` -- All the values `Node.val` are **unique**. -- `-108 <= val <= 108` -- It's **guaranteed** that `val` does not exist in the original BST. +- The number of nodes in the tree will be in the range `[0, 104]`. +- `-108 <= Node.val <= 108` +- All the values `Node.val` are **unique**. +- `-108 <= val <= 108` +- It's **guaranteed** that `val` does not exist in the original BST. ### Thoughts @@ -68,10 +81,12 @@ DFS-like solution is a simple recursion problem, using a helper function. root is null, simple return a new node. ##### Base cases: + - left side is empty, and val < root->val: place it in - right side is empty, and val > root->val: place it in ##### Pseudocode: + - check for base cases - if val < root->val, insert(root->left, val) - vice, versa. diff --git a/OJ notes/pages/Leetcode Intersection-of-Two-Arrays-II.md b/OJ notes/pages/Leetcode Intersection-of-Two-Arrays-II.md index f8a2fb4..9b39511 100644 --- a/OJ notes/pages/Leetcode Intersection-of-Two-Arrays-II.md +++ b/OJ notes/pages/Leetcode Intersection-of-Two-Arrays-II.md @@ -1,32 +1,45 @@ # Leetcode Intersection-of-Two-Arrays-II #### 2022-06-11 + ##### First revision 2022-06-27 --- + ##### Data structures: -#DS #unordered_map + +#DS #unordered_map + ##### Algorithms: -#algorithm #two_pointers #sort + +#algorithm #two_pointers #sort + ##### Difficulty: + #leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/intersection-of-two-arrays-ii/) - [Solution 2(two pointers method)](https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/846181/C%2B%2B-Solutions-or-1-%3A-Map-or-2-%3A-Two-Pointer-with-sort) - [Solution 3 and 4](https://leetcode.com/problems/intersection-of-two-arrays-ii/discuss/82243/Solution-to-3rd-follow-up-question) -___ +--- + ### Problem + Given two integer arrays `nums1` and `nums2`, return _an array of their intersection_. Each element in the result must appear as many times as it shows in both arrays and you may return the result in **any order**. **Follow up:** -- What if the given array is already sorted? How would you optimize your algorithm? -- What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? -- What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? +- What if the given array is already sorted? How would you optimize your algorithm? +- What if `nums1`'s size is small compared to `nums2`'s size? Which algorithm is better? +- What if elements of `nums2` are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? #### Examples + **Example 1:** ``` @@ -54,12 +67,14 @@ For the original problem, I thought up an O(m + n) algo, that uses C++'s [[cpp_s > [!tip] > Because elements can be duplicated and we need to know how many, we should use unordered map to store the item's appereance times, (Maybe multiset can work too.) -> [!tip] Use [[cpp_std_unordered_map]] for a O(1) hash table when not sorted #tip +> [!tip] Use [[cpp_std_unordered_map]] for a O(1) hash table when not sorted #tip -> [!tip] Use [[cpp_std_sort]] to sort anything. #tip +> [!tip] Use [[cpp_std_sort]] to sort anything. #tip ### Solution + Unordered map way O(m + n) + ```cpp class Solution { public: @@ -69,7 +84,7 @@ public: for (int i = 0; i < nums1.size(); i++) { umap[nums1[i]]++; } - + for (int i = 0; i < nums2.size(); i++) { if (umap[nums2[i]] != 0) { answer.push_back(nums2[i]); @@ -79,4 +94,4 @@ public: return answer; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Invert-Binary-Tree.md b/OJ notes/pages/Leetcode Invert-Binary-Tree.md index 0ba6307..df01827 100644 --- a/OJ notes/pages/Leetcode Invert-Binary-Tree.md +++ b/OJ notes/pages/Leetcode Invert-Binary-Tree.md @@ -3,20 +3,33 @@ #### 2022-07-06 13:33 > ##### Algorithms: -> #algorithm #DFS #recursion +> +> #algorithm #DFS #recursion +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/invert-binary-tree/) -___ + +--- + ### Problem Given the `root` of a binary tree, invert the tree, and return _its root_. @@ -50,8 +63,8 @@ Given the `root` of a binary tree, invert the tree, and return _its root_. #### Constraints -- The number of nodes in the tree is in the range `[0, 100]`. -- `-100 <= Node.val <= 100` +- The number of nodes in the tree is in the range `[0, 100]`. +- `-100 <= Node.val <= 100` ### Thoughts @@ -59,8 +72,9 @@ Given the `root` of a binary tree, invert the tree, and return _its root_. > This is a #DFS like recursion problem. Very simple, think of base cases: + - the node is void, skip. -And the flow is following + And the flow is following - Catch base case - Invert sub-trees first @@ -102,4 +116,4 @@ public: return root; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md b/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md index 97a87df..dbeda5d 100644 --- a/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md +++ b/OJ notes/pages/Leetcode Largest-Perimeter-Triangle.md @@ -3,18 +3,29 @@ #### 2022-07-26 08:39 > ##### Algorithms: +> > #algorithm #greedy #math +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/largest-perimeter-triangle/) -___ + +--- + ### Problem Given an integer array `nums`, return _the largest perimeter of a triangle with a non-zero area, formed from three of these lengths_. If it is impossible to form any triangle of a non-zero area, return `0`. @@ -33,8 +44,8 @@ Given an integer array `nums`, return _the largest perimeter of a triangle with #### Constraints -- `3 <= nums.length <= 104` -- `1 <= nums[i] <= 106` +- `3 <= nums.length <= 104` +- `1 <= nums[i] <= 106` ### Thoughts @@ -70,4 +81,4 @@ public: return 0; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Letter-Case-Combination.md b/OJ notes/pages/Leetcode Letter-Case-Combination.md index f7aaade..fb892e8 100644 --- a/OJ notes/pages/Leetcode Letter-Case-Combination.md +++ b/OJ notes/pages/Leetcode Letter-Case-Combination.md @@ -3,18 +3,29 @@ #### 2022-07-20 14:19 > ##### Algorithms: -> #algorithm #backtrack +> +> #algorithm #backtrack +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/letter-case-permutation/) -___ + +--- + ### Problem Given a string `s`, you can transform every letter individually to be lowercase or uppercase to create another string. @@ -41,8 +52,8 @@ Return _a list of all possible strings we could create_. Return the output in ** **Constraints:** -- `1 <= s.length <= 12` -- `s` consists of lowercase English letters, uppercase English letters, and digits. +- `1 <= s.length <= 12` +- `s` consists of lowercase English letters, uppercase English letters, and digits. ### Thoughts diff --git a/OJ notes/pages/Leetcode Linked-List-Cycle.md b/OJ notes/pages/Leetcode Linked-List-Cycle.md index 55c205f..8ebb9f0 100644 --- a/OJ notes/pages/Leetcode Linked-List-Cycle.md +++ b/OJ notes/pages/Leetcode Linked-List-Cycle.md @@ -3,17 +3,29 @@ #### 2022-06-14 21:54 --- + ##### Algorithms: + #algorithm #Floyd_s_cycle_finding_algorithm + ##### Data structures: + #DS #linked_list + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/linked-list-cycle/) -___ + +--- + ### Problem + Given `head`, the head of a linked list, determine if the linked list has a cycle in it. There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the `next` pointer. Internally, `pos` is used to denote the index of the node that tail's `next` pointer is connected to. **Note that `pos` is not passed as a parameter**. @@ -22,6 +34,7 @@ Return `true` _if there is a cycle in the linked list_. Otherwise, return `fals **Follow up:** Can you solve it using `O(1)` (i.e. constant) memory? #### Examples + **Example 1:** ![example1](https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png) @@ -51,21 +64,23 @@ Return `true` _if there is a cycle in the linked list_. Otherwise, return `fals **Output:** false **Explanation:** There is no cycle in the linked list. ``` + #### Constraints -- The number of the nodes in the list is in the range `[0, 104]`. -- `-105 <= Node.val <= 105` -- `pos` is `-1` or a **valid index** in the linked-list. + +- The number of the nodes in the list is in the range `[0, 104]`. +- `-105 <= Node.val <= 105` +- `pos` is `-1` or a **valid index** in the linked-list. ### Thoughts -> [!summary] -> **Algorithm:** +> [!summary] > **Algorithm:** > This is a #Floyd_s_cycle_finding_algorithm. -This is pretty straightforward, visit for more info +> This is pretty straightforward, visit for more info ### Solution O(n) + ```cpp /** * Definition for singly-linked list. @@ -93,4 +108,4 @@ public: } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Longest-Substring-Without-Repeating-Characters.md b/OJ notes/pages/Leetcode Longest-Substring-Without-Repeating-Characters.md index 0a36127..c2c8331 100644 --- a/OJ notes/pages/Leetcode Longest-Substring-Without-Repeating-Characters.md +++ b/OJ notes/pages/Leetcode Longest-Substring-Without-Repeating-Characters.md @@ -3,20 +3,33 @@ #### 2022-07-14 09:33 > ##### Algorithms: -> #algorithm #Kadane_s_algorithm #sliding_window +> +> #algorithm #Kadane_s_algorithm #sliding_window +> > ##### Data structures: -> #DS #string +> +> #DS #string +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/longest-substring-without-repeating-characters/) -___ + +--- + ### Problem Given a string `s`, find the length of the **longest substring** without repeating characters. @@ -44,13 +57,13 @@ Notice that the answer must be a substring, "pwke" is a subsequence and not a su #### Constraints -- `0 <= s.length <= 5 * 104` -- `s` consists of English letters, digits, symbols and spaces. +- `0 <= s.length <= 5 * 104` +- `s` consists of English letters, digits, symbols and spaces. ### Thoughts > [!summary] -> This is a #Kadane_s_algorithm +> This is a #Kadane_s_algorithm Initially, I thought of a kadane's algo, but implemented wrong. @@ -116,4 +129,4 @@ public: return localMax; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Lowest-Common-Ancestor-Of-a-Binary-Search-Tree.md b/OJ notes/pages/Leetcode Lowest-Common-Ancestor-Of-a-Binary-Search-Tree.md index af52e84..0c0ba40 100644 --- a/OJ notes/pages/Leetcode Lowest-Common-Ancestor-Of-a-Binary-Search-Tree.md +++ b/OJ notes/pages/Leetcode Lowest-Common-Ancestor-Of-a-Binary-Search-Tree.md @@ -3,20 +3,33 @@ #### 2022-07-08 11:53 > ##### Algorithms: -> #algorithm #binary_search #DFS +> +> #algorithm #binary_search #DFS +> > ##### Data structures: -> #DS #binary_tree #binary_search_tree +> +> #DS #binary_tree #binary_search_tree +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/) -___ + +--- + ### Problem Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. @@ -48,21 +61,23 @@ According to the [definition of LCA on Wikipedia](https://en.wikipedia.org/wiki/ #### Constraints -- The number of nodes in the tree is in the range `[2, 105]`. -- `-109 <= Node.val <= 109` -- All `Node.val` are **unique**. -- `p != q` -- `p` and `q` will exist in the BST. +- The number of nodes in the tree is in the range `[2, 105]`. +- `-109 <= Node.val <= 109` +- All `Node.val` are **unique**. +- `p != q` +- `p` and `q` will exist in the BST. ### Thoughts > [!summary] -> This is a #binary_search +> This is a #binary_search Because of the features of BST, the maximum val of a left sub-tree is smaller than node, so the valid LCA must meet this: + ``` root->val >= small && root->val <= big ``` + otherwise, search the left or right subtree. ### Solution @@ -85,7 +100,7 @@ public: // Base cases int big = max(q->val, p->val); int small = min(q->val, p->val); - + if (root->val >= small && root->val <= big) { return root; } else if (root->val > big) { @@ -95,4 +110,4 @@ public: } } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Max-Area-of-Island.md b/OJ notes/pages/Leetcode Max-Area-of-Island.md index 10c9c5c..3dfca38 100644 --- a/OJ notes/pages/Leetcode Max-Area-of-Island.md +++ b/OJ notes/pages/Leetcode Max-Area-of-Island.md @@ -3,20 +3,33 @@ #### 2022-07-15 10:00 > ##### Algorithms: -> #algorithm +> +> #algorithm +> > ##### Data structures: -> #DS #vector_2d +> +> #DS #vector_2d +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/max-area-of-island/) -___ + +--- + ### Problem You are given an `m x n` binary matrix `grid`. An island is a group of `1`'s (representing land) connected **4-directionally** (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. @@ -46,23 +59,25 @@ Return _the maximum **area** of an island in_ `grid`. If there is no island, ret #### Constraints -- `m == grid.length` -- `n == grid[i].length` -- `1 <= m, n <= 50` -- `grid[i][j]` is either `0` or `1`. +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 50` +- `grid[i][j]` is either `0` or `1`. ### Thoughts > [!summary] -> This is a search problem, can be implemented using #DFS or #BFS +> This is a search problem, can be implemented using #DFS or #BFS Simple O(mn) solution. We keep track of pile we visited, using: + - an 2-d bool vector visited(which is the one I'm using) - change the value of pile to 0 and check for: + - x, y is not OOB - x, y is in a island -> (value == 1) - x, y is not visited (see above) @@ -72,6 +87,7 @@ And for each unvisited pile, run DFS or BFS to check the size, and keep track of ### Solution BFS + ```cpp class Solution { int getSize(vector> &grid, int m, int n, int x, int y, @@ -137,6 +153,7 @@ public: ``` DFS iterative (simply change from queue to stack in BFS) + ```cpp class Solution { // DFS iterative @@ -203,6 +220,7 @@ public: ``` DFS recursive + ```cpp class Solution { // DFS recursive @@ -243,4 +261,4 @@ public: return maxSize; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Maximum-Depth-Of-Binary-Tree.md b/OJ notes/pages/Leetcode Maximum-Depth-Of-Binary-Tree.md index 1f737bd..860f2a6 100644 --- a/OJ notes/pages/Leetcode Maximum-Depth-Of-Binary-Tree.md +++ b/OJ notes/pages/Leetcode Maximum-Depth-Of-Binary-Tree.md @@ -3,21 +3,35 @@ #### 2022-07-05 09:25 > ##### Algorithms: +> > #algorithm #BFS +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/maximum-depth-of-binary-tree/) -___ + +--- + ### Problem + Given the `root` of a binary tree, return _its maximum depth_. A binary tree's **maximum depth** is the number of nodes along the longest path from the root node down to the farthest leaf node. @@ -38,8 +52,8 @@ A binary tree's **maximum depth** is the number of nodes along the longest path #### Constraints -- The number of nodes in the tree is in the range `[0, 104]`. -- `-100 <= Node.val <= 100` +- The number of nodes in the tree is in the range `[0, 104]`. +- `-100 <= Node.val <= 100` ### Thoughts @@ -51,13 +65,15 @@ Simply log the level in each while iteration. DFS way: (Popular) Use recursion: + - Base Case: - - root == nullptr: return 0; + - root == nullptr: return 0; - maxDepth(root) = max(maxDepth(root->left), maxDepth(root->right)) ### Solution DFS Recursion: + ```cpp /** * Definition for a binary tree node. @@ -85,6 +101,7 @@ public: ``` BFS: + ```cpp /** * Definition for a binary tree node. @@ -124,4 +141,4 @@ public: return levels; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Maximum-Difference-Between-Increasing-Elements.md b/OJ notes/pages/Leetcode Maximum-Difference-Between-Increasing-Elements.md index 3e745b4..d6f930e 100644 --- a/OJ notes/pages/Leetcode Maximum-Difference-Between-Increasing-Elements.md +++ b/OJ notes/pages/Leetcode Maximum-Difference-Between-Increasing-Elements.md @@ -3,24 +3,37 @@ #### 2022-06-27 11:09 > ##### Algorithms: -> #algorithm #Kadane_s_algorithm +> +> #algorithm #Kadane_s_algorithm +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/maximum-difference-between-increasing-elements/) -___ + +--- + ### Problem + Given a **0-indexed** integer array `nums` of size `n`, find the **maximum difference** between `nums[i]` and `nums[j]` (i.e., `nums[j] - nums[i]`), such that `0 <= i < j < n` and `nums[i] < nums[j]`. Return _the **maximum difference**._ If no such `i` and `j` exists, return `-1`. #### Examples + Example 1: ``` @@ -48,19 +61,19 @@ Output: 9 Explanation: The maximum difference occurs with i = 0 and j = 3, nums[j] - nums[i] = 10 - 1 = 9. ``` - #### Constraints -- n == nums.length -- 2 <= n <= 1000 -- 1 <= nums[i] <= 109 +- n == nums.length +- 2 <= n <= 1000 +- 1 <= nums[i] <= 109 ### Thoughts Since 0 <= i < j <=n, this can be completed using kadane's algo in one pass. + > [!summary] -> This is a #Kadane_s_algorithm +> This is a #Kadane_s_algorithm ### Solution @@ -71,12 +84,12 @@ public: // Kadane's algorithm, since 0 <= i < j < n, and it can be done using one loop. int minNum = nums[0]; int maxNum = 0; - + for (int i : nums) { minNum = min(minNum, i); maxNum = max(maxNum, i - minNum); } - + if (maxNum == 0) { return -1; } else { @@ -84,4 +97,4 @@ public: } } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Maxinum-subarray.md b/OJ notes/pages/Leetcode Maxinum-subarray.md index 54c276c..04c268e 100644 --- a/OJ notes/pages/Leetcode Maxinum-subarray.md +++ b/OJ notes/pages/Leetcode Maxinum-subarray.md @@ -3,22 +3,34 @@ #### 2022-06-09 --- + ##### Data stuctures: -#DS #array + +#DS #array + ##### Algorithms: + #algorithm #Kadane_s_algorithm + ##### Difficulty: + #leetcode #coding_problem #difficulty-easy + ##### Links: + - [Link to problem](https://leetcode.com/problems/maximum-subarray/) - [Analysis](https://medium.com/@rsinghal757/kadanes-algorithm-dynamic-programming-how-and-why-does-it-work-3fd8849ed73d) + ##### Related topics: + ### Problem + Given an integer array `nums`, find the contiguous subarray (containing at least one number) which has the largest sum and return _its sum_. A **subarray** is a **contiguous** part of an array. #### Examples + Example 1: ``` @@ -41,7 +53,6 @@ Input: nums = [5,4,-1,7,8] Output: 23 ``` - #### Constraints - 1 <= nums.length <= 105 @@ -56,12 +67,12 @@ public: // Kadane's algorithm int local_max = 0; int global_max = INT_MIN; - + for (int i = 0; i < nums.size(); i++) { // if accumulated local max is smaller than nums, // we use the new one instead, and it must be the biggest. local_max = max(nums[i] + local_max, nums[i]); - + if (local_max > global_max) { // We take note when local_max achieves the peak. global_max = local_max; @@ -74,12 +85,14 @@ public: ### Thoughts -This is a [[Kadane's Algorithm]] problem, and the philosophy behind it id divide and conquer. +This is a [[Kadane's Algorithm]] problem, and the philosophy behind it id divide and conquer. local_max is the max accumulated number we've found, and global_max is the max local_max we've found. + ```cpp local_max = max(nums[i] + local_max, nums[i]) ``` + is the key to O(n) complexity. > [!hint] -> Use the macro INT_MAX and INT_MIN to initialize variables that finds max / min var. #tip \ No newline at end of file +> Use the macro INT_MAX and INT_MIN to initialize variables that finds max / min var. #tip diff --git a/OJ notes/pages/Leetcode Merge-Intervals.md b/OJ notes/pages/Leetcode Merge-Intervals.md index 5ab10be..02f9375 100644 --- a/OJ notes/pages/Leetcode Merge-Intervals.md +++ b/OJ notes/pages/Leetcode Merge-Intervals.md @@ -3,20 +3,32 @@ #### 2022-09-01 14:04 > ##### Algorithms: -> #algorithm #sort +> +> #algorithm #sort +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Links: + - [Link to problem](https://leetcode.com/problems/merge-intervals/) - [Solution ans Explanation](https://leetcode.com/problems/merge-intervals/solution/) -___ + +--- + ### Problem Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all overlapping intervals, and return _an array of the non-overlapping intervals that cover all the intervals in the input_. @@ -37,9 +49,9 @@ Given an array of `intervals` where `intervals[i] = [starti, endi]`, merge all #### Constraints -- `1 <= intervals.length <= 104` -- `intervals[i].length == 2` -- `0 <= starti <= endi <= 104` +- `1 <= intervals.length <= 104` +- `intervals[i].length == 2` +- `0 <= starti <= endi <= 104` ### Thoughts @@ -76,4 +88,4 @@ public: return ans; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Merge-Sorted-Array.md b/OJ notes/pages/Leetcode Merge-Sorted-Array.md index 5859cb2..77236ee 100644 --- a/OJ notes/pages/Leetcode Merge-Sorted-Array.md +++ b/OJ notes/pages/Leetcode Merge-Sorted-Array.md @@ -3,19 +3,30 @@ #### 2022-06-10 --- + ##### Data structures: + #DS #set #multiset #vector + ##### Algorithms: + #algorithm #merge_sort #two_pointers + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/merge-sorted-array/) - [multiset cpp reference](https://leetcode.com/problems/merge-sorted-array/) -___ +--- + ### Problem + You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing order**, and two integers `m` and `n`, representing the number of elements in `nums1` and `nums2` respectively. **Merge** `nums1` and `nums2` into a single array sorted in **non-decreasing order**. @@ -23,6 +34,7 @@ You are given two integer arrays `nums1` and `nums2`, sorted in **non-decreasing The final sorted array should not be returned by the function, but instead be _stored inside the array_ `nums1`. To accommodate this, `nums1` has a length of `m + n`, where the first `m` elements denote the elements that should be merged, and the last `n` elements are set to `0` and should be ignored. `nums2` has a length of `n`. #### Examples + Example 1: ``` @@ -52,14 +64,16 @@ Note that because m = 0, there are no elements in nums1. The 0 is only there to ``` #### Constraints -- nums1.length == m + n -- nums2.length == n -- 0 <= m, n <= 200 -- 1 <= m + n <= 200 -- -10E9 <= nums1[i], nums2[j] <= 10E9 + +- nums1.length == m + n +- nums2.length == n +- 0 <= m, n <= 200 +- 1 <= m + n <= 200 +- -10E9 <= nums1[i], nums2[j] <= 10E9 + ### Thoughts -I have came up with three ways. +I have came up with three ways. The first one is to use **Merge Sort**, which is fast but slow to implement. And second one is cpp's **[[cpp_std_multiset]]**, which is O(nlog(n)) Lastly, use the two pointer apporach, which is O(n) @@ -71,6 +85,7 @@ For using cpp, the most difficult thing was actually to use the vector library. ### Solution multiset solution: O(nlogn) + ```cpp #include #include @@ -85,7 +100,7 @@ public: for (int i = 0; i < n; i++) { mset.insert(nums2[i]); } - + // write answer auto it = mset.begin(); for (int i = 0; i < m + n; i++) { @@ -97,6 +112,7 @@ public: ``` double pointer solution: O(m+n) (In c, it will get slower, since vectors are more efficient at inserting.) + ```cpp #include #include @@ -110,7 +126,7 @@ public: for (int i = 0; i < n; i++) { nums1.pop_back(); } - + for (auto i = nums1.begin(); i < n + m + nums1.begin(); i++) { if (slowPtr < n) { if (*i >= nums2[slowPtr]){ @@ -126,7 +142,9 @@ public: } }; ``` + c solution( not optimized ) + ```c void insert(int *arr, int numsSize, int loc, int value) { for (int i = numsSize - 1; i > loc; i--) { @@ -156,4 +174,4 @@ void merge(int *nums1, int nums1Size, int m, int *nums2, int nums2Size, int n) { } } -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Merge-Two-Binary-Trees.md b/OJ notes/pages/Leetcode Merge-Two-Binary-Trees.md index 6c4d59e..c6e85a9 100644 --- a/OJ notes/pages/Leetcode Merge-Two-Binary-Trees.md +++ b/OJ notes/pages/Leetcode Merge-Two-Binary-Trees.md @@ -3,20 +3,33 @@ #### 2022-07-16 09:11 > ##### Algorithms: -> #algorithm #DFS #DFS_inorder +> +> #algorithm #DFS #DFS_inorder +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/merge-two-binary-trees/) -___ + +--- + ### Problem You are given two binary trees `root1` and `root2`. @@ -43,8 +56,8 @@ Return _the merged tree_. #### Constraints -- The number of nodes in both trees is in the range `[0, 2000]`. -- `-104 <= Node.val <= 104` +- The number of nodes in both trees is in the range `[0, 2000]`. +- `-104 <= Node.val <= 104` ### Thoughts @@ -52,6 +65,7 @@ Return _the merged tree_. > This is a #DFS problem, can be solved with recursion DFS preorder recursion: + - Base case: one leaf is empty, return another - add value from root2 to root1 @@ -95,4 +109,4 @@ public: return root1; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Merge-Two-Sorted-Lists.md b/OJ notes/pages/Leetcode Merge-Two-Sorted-Lists.md index 64adce4..959d9d8 100644 --- a/OJ notes/pages/Leetcode Merge-Two-Sorted-Lists.md +++ b/OJ notes/pages/Leetcode Merge-Two-Sorted-Lists.md @@ -3,17 +3,29 @@ #### 2022-06-14 22:57 --- + ##### Algorithms: + #algorithm #two_pointers #recursion + ##### Data structures: -#DS #linked_list + +#DS #linked_list + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/merge-two-sorted-lists/) -___ + +--- + ### Problem + You are given the heads of two sorted linked lists `list1` and `list2`. Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists. @@ -21,6 +33,7 @@ Merge the two lists in a one **sorted** list. The list should be made by splicin Return _the head of the merged linked list_. #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg) @@ -45,9 +58,10 @@ Return _the head of the merged linked list_. ``` #### Constraints -- The number of nodes in both lists is in the range `[0, 50]`. -- `-100 <= Node.val <= 100` -- Both `list1` and `list2` are sorted in **non-decreasing** order. + +- The number of nodes in both lists is in the range `[0, 50]`. +- `-100 <= Node.val <= 100` +- Both `list1` and `list2` are sorted in **non-decreasing** order. ### Thoughts @@ -61,16 +75,20 @@ The only thing to watch out for is when there is one list remaining, remember to Very simple for recursion ##### Base Case: + - Both are nullptr -> return nullptr - One is nullptr -> return another ##### Pseudocode: + - Check for base case: - if list1->val > list2->val, list2's next should be the merged result - if list2->val > list1->val, list1's next should be the merged result. ### Solution + Recursion + ```cpp class Solution { public: @@ -96,6 +114,7 @@ public: ``` Two pointers + ```cpp /** * Definition for singly-linked list. @@ -137,4 +156,4 @@ public: return dummyHead->next; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Middle-of-the-Linked-List.md b/OJ notes/pages/Leetcode Middle-of-the-Linked-List.md index c6c4046..a3ec641 100644 --- a/OJ notes/pages/Leetcode Middle-of-the-Linked-List.md +++ b/OJ notes/pages/Leetcode Middle-of-the-Linked-List.md @@ -3,20 +3,33 @@ #### 2022-07-13 09:08 > ##### Algorithms: -> #algorithm #two_pointers +> +> #algorithm #two_pointers +> > ##### Data structures: -> #DS #linked_list +> +> #DS #linked_list +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/middle-of-the-linked-list/) -___ + +--- + ### Problem Given the head of a singly linked list, return the middle node of the linked list. @@ -43,8 +56,8 @@ If there are two middle nodes, return the second middle node. #### Constraints -- The number of nodes in the list is in the range `[1, 100]`. -- `1 <= Node.val <= 100` +- The number of nodes in the list is in the range `[1, 100]`. +- `1 <= Node.val <= 100` ### Thoughts @@ -85,4 +98,4 @@ public: } } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Move-Zeroes.md b/OJ notes/pages/Leetcode Move-Zeroes.md index ad84f63..7ba34bc 100644 --- a/OJ notes/pages/Leetcode Move-Zeroes.md +++ b/OJ notes/pages/Leetcode Move-Zeroes.md @@ -3,20 +3,33 @@ #### 2022-07-11 09:55 > ##### Algorithms: -> #algorithm #two_pointers #array_in_place_operation +> +> #algorithm #two_pointers #array_in_place_operation +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/move-zeroes/) -___ + +--- + ### Problem Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. @@ -41,13 +54,13 @@ Given an integer array `nums`, move all `0`'s to the end of it while maintaining **Constraints:** -- `1 <= nums.length <= 104` -- `-231 <= nums[i] <= 231 - 1` +- `1 <= nums.length <= 104` +- `-231 <= nums[i] <= 231 - 1` ### Thoughts > [!summary] -> This is a #array_in_place_operation problem. +> This is a #array_in_place_operation problem. Because the data can be overwritten, and zeros can be predicted in the result array, I use in-place array operations. @@ -72,4 +85,4 @@ public: } } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Next-Greater-Element-I.md b/OJ notes/pages/Leetcode Next-Greater-Element-I.md index ddb55f5..b6667d1 100644 --- a/OJ notes/pages/Leetcode Next-Greater-Element-I.md +++ b/OJ notes/pages/Leetcode Next-Greater-Element-I.md @@ -3,18 +3,29 @@ #### 2022-07-27 10:55 > ##### Data structures: -> #DS #stack #hash_table +> +> #DS #stack #hash_table +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/next-greater-element-i/) -___ + +--- + ### Problem The **next greater element** of some element `x` in an array is the **first greater** element that is **to the right** of `x` in the same array. @@ -32,6 +43,7 @@ Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **Input:** nums1 = [4,1,2], nums2 = [1,3,4,2] **Output:** [-1,3,-1] **Explanation:** The next greater element for each value of nums1 is as follows: + - 4 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. - 1 is underlined in nums2 = [1,3,4,2]. The next greater element is 3. - 2 is underlined in nums2 = [1,3,4,2]. There is no next greater element, so the answer is -1. @@ -41,6 +53,7 @@ Return _an array_ `ans` _of length_ `nums1.length` _such that_ `ans[i]` _is the **Input:** nums1 = [2,4], nums2 = [1,2,3,4] **Output:** [3,-1] **Explanation:** The next greater element for each value of nums1 is as follows: + - 2 is underlined in nums2 = [1,2,3,4]. The next greater element is 3. - 4 is underlined in nums2 = [1,2,3,4]. There is no next greater element, so the answer is -1. @@ -94,4 +107,4 @@ public: return ans; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Non-Overlapping-Intervals.md b/OJ notes/pages/Leetcode Non-Overlapping-Intervals.md new file mode 100644 index 0000000..c0bca64 --- /dev/null +++ b/OJ notes/pages/Leetcode Non-Overlapping-Intervals.md @@ -0,0 +1,66 @@ +# Leetcode Non-Overlapping-Intervals + +2022-09-03 15:34 + +> ##### Algorithms: +> +> #algorithm +> +> ##### Data structures: +> +> #DS +> +> ##### Difficulty: +> +> #coding_problem #difficulty- +> +> ##### Additional tags: +> +> # # +> +> ##### Revisions: +> +> N/A + +##### Links: + +- [Link to problem](https://leetcode.com/problems/non-overlapping-intervals/) + +--- + +### Problem + +Given an array of intervals `intervals` where `intervals[i] = [starti, endi]`, return _the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping_. + +#### Examples + +**Example 1:** + +**Input:** intervals = [[1,2],[2,3],[3,4],[1,3]] +**Output:** 1 +**Explanation:** [1,3] can be removed and the rest of the intervals are non-overlapping. + +**Example 2:** + +**Input:** intervals = [[1,2],[1,2],[1,2]] +**Output:** 2 +**Explanation:** You need to remove two [1,2] to make the rest of the intervals non-overlapping. + +**Example 3:** + +**Input:** intervals = [[1,2],[2,3]] +**Output:** 0 +**Explanation:** You don't need to remove any of the intervals since they're already non-overlapping. + +#### Constraints + +- `1 <= intervals.length <= 105` +- `intervals[i].length == 2` +- `-5 * 104 <= starti < endi <= 5 * 104` + +### Thoughts + +> [!summary] +> This is a #template_remove_me + +### Solution diff --git a/OJ notes/pages/Leetcode Number-of-1-Bits.md b/OJ notes/pages/Leetcode Number-of-1-Bits.md index 85f7f61..cd99987 100644 --- a/OJ notes/pages/Leetcode Number-of-1-Bits.md +++ b/OJ notes/pages/Leetcode Number-of-1-Bits.md @@ -3,20 +3,33 @@ #### 2022-07-22 14:45 > ##### Algorithms: -> #algorithm #bit_manipulation +> +> #algorithm #bit_manipulation +> > ##### Data structures: -> #DS #bitset +> +> #DS #bitset +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/number-of-1-bits/) -___ + +--- + ### Problem Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the [Hamming weight](http://en.wikipedia.org/wiki/Hamming_weight)). @@ -81,7 +94,7 @@ class Solution { public: int hammingWeight(uint32_t n) { return bitset<32>(n).count(); } }; -```` +``` #### Method 2: @@ -97,4 +110,4 @@ public: return count; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Pascal's-Triangle-II.md b/OJ notes/pages/Leetcode Pascal's-Triangle-II.md index cbe3fb7..0728fc3 100644 --- a/OJ notes/pages/Leetcode Pascal's-Triangle-II.md +++ b/OJ notes/pages/Leetcode Pascal's-Triangle-II.md @@ -3,19 +3,31 @@ 2022-09-02 14:54 > ##### Algorithms: +> > #algorithm #recursion +> > ##### Data structures: +> > #DS #array +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Links: + - [Link to problem](https://leetcode.com/problems/pascals-triangle-ii/) -___ + +--- + ### Problem Given an integer `rowIndex`, return the `rowIndexth` (**0-indexed**) row of the **Pascal's triangle**. @@ -80,4 +92,4 @@ public: return ans; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Pascal's-Triangle.md b/OJ notes/pages/Leetcode Pascal's-Triangle.md index 692dfcc..64a31c7 100644 --- a/OJ notes/pages/Leetcode Pascal's-Triangle.md +++ b/OJ notes/pages/Leetcode Pascal's-Triangle.md @@ -3,19 +3,30 @@ #### 2022-06-12 --- + ##### Data structures: -#DS #array + +#DS #array + ##### Algorithms: + #algorithm #recursion #iteration + ##### Difficulty: + #leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/pascals-triangle/) - [Additional resources]() -___ +--- + ### Problem + Given an integer `numRows`, return the first numRows of **Pascal's triangle**. In **Pascal's triangle**, each number is the sum of the two numbers directly above it as shown: @@ -23,6 +34,7 @@ In **Pascal's triangle**, each number is the sum of the two numbers directly abo ![Pascal Triangle](https://upload.wikimedia.org/wikipedia/commons/0/0d/PascalTriangleAnimated2.gif) #### Examples + **Example 1:** ```markdown @@ -44,12 +56,14 @@ Output: [[1]] ### Thoughts Very simple and straightforward problem. + > [!summary] > answer[i][j] = answer[i - 1][j - 1] + answer[i - 1][j] I worked around special cases using the for loop in j: j = 1 and j < i. ### Solution + ```cpp class Solution { public: @@ -69,4 +83,4 @@ public: return answer; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Path-Sum.md b/OJ notes/pages/Leetcode Path-Sum.md index 643ba90..136ca85 100644 --- a/OJ notes/pages/Leetcode Path-Sum.md +++ b/OJ notes/pages/Leetcode Path-Sum.md @@ -3,20 +3,33 @@ #### 2022-07-06 13:45 > ##### Algorithms: -> #algorithm #DFS #recursion +> +> #algorithm #DFS #recursion +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/path-sum/) -___ + +--- + ### Problem Given the `root` of a binary tree and an integer `targetSum`, return `true` if the tree has a **root-to-leaf** path such that adding up all the values along the path equals `targetSum`. @@ -52,9 +65,9 @@ There is no root-to-leaf path with sum = 5. #### Constraints -- The number of nodes in the tree is in the range `[0, 5000]`. -- `-1000 <= Node.val <= 1000` -- `-1000 <= targetSum <= 1000` +- The number of nodes in the tree is in the range `[0, 5000]`. +- `-1000 <= Node.val <= 1000` +- `-1000 <= targetSum <= 1000` ### Thoughts @@ -66,17 +79,19 @@ There are one thing to consider, return false when the tree is empty. Simple DFS-like recursion problem. Base cases: + - node is empty, return false - node is leaf - - if the value is sum, return true - - else return false + - if the value is sum, return true + - else return false Pseudo-code: + - Check for base-cases - return check(left, sum - root->val) || check(right, sum - root->val) > [!tip] Why use OR -> By using OR operator, return true when there is at least one solution that matches. +> By using OR operator, return true when there is at least one solution that matches. ### Solution @@ -96,22 +111,22 @@ class Solution { public: bool hasPathSum(TreeNode* root, int targetSum) { // DFS In-order Recursion - + // Base case: node does not exist if (!root) { return false; } int val = root->val; - + // Base case: reached leaf if (!root->left && !root->right) { if (targetSum == val) return true; - else + else return false; } - + return hasPathSum(root->left, targetSum - val) || hasPathSum(root->right, targetSum - val); } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Permutation-In-String.md b/OJ notes/pages/Leetcode Permutation-In-String.md index 51f64f0..e7aeb95 100644 --- a/OJ notes/pages/Leetcode Permutation-In-String.md +++ b/OJ notes/pages/Leetcode Permutation-In-String.md @@ -3,20 +3,33 @@ #### 2022-07-14 10:29 > ##### Algorithms: +> > #algorithm #sliding_window +> > ##### Data structures: +> > #DS #string +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode #CS_list_need_understanding +> +> #leetcode #CS_list_need_understanding +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/permutation-in-string/) -___ + +--- + ### Problem Given two strings `s1` and `s2`, return `true` _if_ `s2` _contains a permutation of_ `s1`_, or_ `false` _otherwise_. @@ -38,8 +51,8 @@ In other words, return `true` if one of `s1`'s permutations is the substring of #### Constraints -- `1 <= s1.length, s2.length <= 104` -- `s1` and `s2` consist of lowercase English letters. +- `1 <= s1.length, s2.length <= 104` +- `s1` and `s2` consist of lowercase English letters. ### Thoughts @@ -91,4 +104,4 @@ public: return false; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Permutations.md b/OJ notes/pages/Leetcode Permutations.md index 154e821..a28342e 100644 --- a/OJ notes/pages/Leetcode Permutations.md +++ b/OJ notes/pages/Leetcode Permutations.md @@ -3,18 +3,29 @@ #### 2022-07-20 14:16 > ##### Algorithms: -> #algorithm #backtrack +> +> #algorithm #backtrack +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/permutations/) -___ + +--- + ### Problem Given an array `nums` of distinct integers, return _all the possible permutations_. You can return the answer in **any order**. @@ -46,9 +57,9 @@ Given an array `nums` of distinct integers, return _all the possible permutation **Constraints:** -- `1 <= nums.length <= 6` -- `-10 <= nums[i] <= 10` -- All the integers of `nums` are **unique**. +- `1 <= nums.length <= 6` +- `-10 <= nums[i] <= 10` +- All the integers of `nums` are **unique**. ### Thoughts @@ -99,4 +110,4 @@ public: return ans; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Populating-Next-Right-Pointers-In-Each-Node.md b/OJ notes/pages/Leetcode Populating-Next-Right-Pointers-In-Each-Node.md index 6fe6c07..0a084fd 100644 --- a/OJ notes/pages/Leetcode Populating-Next-Right-Pointers-In-Each-Node.md +++ b/OJ notes/pages/Leetcode Populating-Next-Right-Pointers-In-Each-Node.md @@ -3,29 +3,42 @@ #### 2022-07-16 09:43 > ##### Algorithms: +> > #algorithm #BFS #optimization #DFS +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/populating-next-right-pointers-in-each-node/) -___ + +--- + ### Problem You are given a **perfect binary tree** where all leaves are on the same level, and every parent has two children. The binary tree has the following definition: struct Node { - int val; - Node *left; - Node *right; - Node *next; +int val; +Node *left; +Node *right; +Node \*next; } Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to `NULL`. @@ -51,8 +64,8 @@ Initially, all next pointers are set to `NULL`. **Constraints:** -- The number of nodes in the tree is in the range `[0, 212 - 1]`. -- `-1000 <= Node.val <= 1000` +- The number of nodes in the tree is in the range `[0, 212 - 1]`. +- `-1000 <= Node.val <= 1000` ### Thoughts @@ -74,7 +87,7 @@ Remember to get the for loop right. ##### BFS-like iteration, two pointers, O(n)time, O(n + 1)space -We utilize the ->next property to link +We utilize the ->next property to link ptr->left->right->next to ptr->right->left ![[Leetcode Populating next right ptr-2.png]] @@ -89,9 +102,11 @@ since this is only one level, and doesn't work on two levels: We recursively fill next pointers the level below current. Base case: + - Root->left is empty, which means this is the leaf level, quit. Pseudo-code: + 1. Check for base case 1. link root->left and root->right 1. link root->right and root->next->left (if root->next is valid.) @@ -99,6 +114,7 @@ Pseudo-code: ### Solution DFS: + ```cpp /* // Definition for a Node. @@ -143,6 +159,7 @@ public: ``` Iterative, O(n)time O(1)space + ```cpp class Solution { public: @@ -170,6 +187,7 @@ public: ``` BFS unoptimized: + ```cpp class Solution { public: @@ -208,4 +226,4 @@ public: return root; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Power-of-Two.md b/OJ notes/pages/Leetcode Power-of-Two.md index 41333d7..3b2a3d0 100644 --- a/OJ notes/pages/Leetcode Power-of-Two.md +++ b/OJ notes/pages/Leetcode Power-of-Two.md @@ -3,20 +3,33 @@ #### 2022-07-22 14:30 > ##### Algorithms: +> > #algorithm #bit_manipulation +> > ##### Data structures: +> > #DS #bitset +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/power-of-two/) -___ + +--- + ### Problem Given an integer `n`, return _`true` if it is a power of two. Otherwise, return `false`_. @@ -73,7 +86,7 @@ power of 2 and --1 looks like this 7 : 0111 ``` -so, if it is power of 2, `!(n & (n - 1))` will produce true. +so, if it is power of 2, `!(n & (n - 1))` will produce true. otherwise, `(n & (n - 1))` will produce something other than 0. @@ -122,4 +135,4 @@ public: } } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Ransom-Note.md b/OJ notes/pages/Leetcode Ransom-Note.md index 39bb31b..80f1ce0 100644 --- a/OJ notes/pages/Leetcode Ransom-Note.md +++ b/OJ notes/pages/Leetcode Ransom-Note.md @@ -3,17 +3,29 @@ #### 2022-06-14 13:19 --- + ##### Algorithms: -#algorithm #hash_table + +#algorithm #hash_table + ##### Data structures: -#DS #string #array + +#DS #string #array + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/ransom-note/) -___ + +--- + ### Problem + Given two strings `ransomNote` and `magazine`, return `true` _if_ `ransomNote` _can be constructed by using the letters from_ `magazine` _and_ `false` _otherwise_. Each letter in `magazine` can only be used once in `ransomNote`. @@ -40,19 +52,22 @@ Each letter in `magazine` can only be used once in `ransomNote`. **Input:** s = "aabb" **Output:** -1 ``` + #### Constraints **Constraints:** -- `1 <= s.length <= 105` -- `s` consists of only lowercase English letters. +- `1 <= s.length <= 105` +- `s` consists of only lowercase English letters. ### Thoughts Super simple hash map, similar to [[Leetcode First-Unique-Character-In-a-String]] ### Solution + O(m + n) + ```cpp class Solution { public: @@ -71,4 +86,4 @@ public: return true; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Remove-Duplicates-From-Sorted-List.md b/OJ notes/pages/Leetcode Remove-Duplicates-From-Sorted-List.md index feca143..0039b3e 100644 --- a/OJ notes/pages/Leetcode Remove-Duplicates-From-Sorted-List.md +++ b/OJ notes/pages/Leetcode Remove-Duplicates-From-Sorted-List.md @@ -3,23 +3,36 @@ #### 2022-06-16 14:21 > ##### Data structures: -> #DS #linked_list +> +> #DS #linked_list +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > Initial encounter: 2022-06-16 > 1st. revision: 2022-07-02 ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/remove-duplicates-from-sorted-list/) -___ + +--- + ### Problem + Given the `head` of a sorted linked list, _delete all duplicates such that each element appears only once_. Return _the linked list **sorted** as well_. #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2021/01/04/list1.jpg) @@ -35,9 +48,10 @@ Given the `head` of a sorted linked list, _delete all duplicates such that each **Output:** [1,2,3] #### Constraints -- The number of nodes in the list is in the range `[0, 300]`. -- `-100 <= Node.val <= 100` -- The list is guaranteed to be **sorted** in ascending order. + +- The number of nodes in the list is in the range `[0, 300]`. +- `-100 <= Node.val <= 100` +- The list is guaranteed to be **sorted** in ascending order. ### Thoughts @@ -50,6 +64,7 @@ To understand the ptr->next->next = ptr->next, see[[Leetcode Reverse-Linked-List ### Solution One pointer method + ```cpp /** * Definition for singly-linked list. @@ -80,4 +95,3 @@ public: } }; ``` - diff --git a/OJ notes/pages/Leetcode Remove-Linked-List-Elements.md b/OJ notes/pages/Leetcode Remove-Linked-List-Elements.md index 45661e6..c239544 100644 --- a/OJ notes/pages/Leetcode Remove-Linked-List-Elements.md +++ b/OJ notes/pages/Leetcode Remove-Linked-List-Elements.md @@ -3,19 +3,30 @@ #### 2022-06-15 21:50 --- + ##### Data structures: -#DS #linked_list + +#DS #linked_list + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/remove-linked-list-elements/) -- [Additional Solutions](https://leetcode.com/problems/remove-linked-list-elements/discuss/722528/C++-2-solutions:-With-single-pointer-+-With-double-pointers-(Easy-to-understand)/1390186) -___ +- [Additional Solutions]() + +--- + ### Problem + Given the `head` of a linked list and an integer `val`, remove all the nodes of the linked list that has `Node.val == val`, and return _the new head_. #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2021/03/06/removelinked-list.jpg) @@ -38,18 +49,23 @@ Given the `head` of a linked list and an integer `val`, remove all the nodes of **Input:** head = [7,7,7,7], val = 7 **Output:** [] ``` + #### Constraints -- The number of nodes in the list is in the range `[0, 104]`. -- `1 <= Node.val <= 50` -- `0 <= val <= 50` + +- The number of nodes in the list is in the range `[0, 104]`. +- `1 <= Node.val <= 50` +- `0 <= val <= 50` ### Thoughts Simple linked list operations, but remember to check for special cases: + - The pointer is null + ### Solution Two pointers, O(n) + ```cpp /** * Definition for singly-linked list. @@ -95,6 +111,7 @@ public: These two are taken from discussions, and they are **not** memory safe. Recursive solution from the same guy: + ```cpp class Solution { public: @@ -111,7 +128,8 @@ public: }; ``` -One pointer from [Discussions](https://leetcode.com/problems/remove-linked-list-elements/discuss/722528/C++-2-solutions:-With-single-pointer-+-With-double-pointers-(Easy-to-understand)/1390186) +One pointer from [Discussions]() + ```cpp class Solution { public: @@ -134,4 +152,3 @@ public: } }; ``` - diff --git a/OJ notes/pages/Leetcode Remove-Nth-Node-From-End-of-List.md b/OJ notes/pages/Leetcode Remove-Nth-Node-From-End-of-List.md index f2bf4c0..86c5b1e 100644 --- a/OJ notes/pages/Leetcode Remove-Nth-Node-From-End-of-List.md +++ b/OJ notes/pages/Leetcode Remove-Nth-Node-From-End-of-List.md @@ -3,21 +3,34 @@ #### 2022-07-13 09:31 > ##### Algorithms: -> #algorithm #two_pointers +> +> #algorithm #two_pointers +> > ##### Data structures: -> #DS #linked_list +> +> #DS #linked_list +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode #CS_list_need_understanding +> +> #leetcode #CS_list_need_understanding +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/remove-nth-node-from-end-of-list/) - [Explanation](https://leetcode.com/problems/remove-nth-node-from-end-of-list/discuss/1164542/JS-Python-Java-C%2B%2B-or-Easy-Two-Pointer-Solution-w-Explanation) -___ + +--- + ### Problem Given the `head` of a linked list, remove the `nth` node from the end of the list and return its head. @@ -43,10 +56,10 @@ Given the `head` of a linked list, remove the `nth` node from the end of the lis #### Constraints -- The number of nodes in the list is `sz`. -- `1 <= sz <= 30` -- `0 <= Node.val <= 100` -- `1 <= n <= sz` +- The number of nodes in the list is `sz`. +- `1 <= sz <= 30` +- `0 <= Node.val <= 100` +- `1 <= n <= sz` ### Thoughts @@ -65,6 +78,7 @@ pointers reach the end at the same time. We can let fast go n step first, such that **when fast comes to the end**, slow gets to the Nth node from the last. To find the 2nd from the last: + ``` slow @@ -118,7 +132,6 @@ public: }; ``` - Initial iteration: ```cpp @@ -166,4 +179,4 @@ public: return pre->next; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Reshape-The-Matrix.md b/OJ notes/pages/Leetcode Reshape-The-Matrix.md index 4a839ca..9eea658 100644 --- a/OJ notes/pages/Leetcode Reshape-The-Matrix.md +++ b/OJ notes/pages/Leetcode Reshape-The-Matrix.md @@ -3,15 +3,25 @@ #### 2022-06-12 --- + ##### Data structures: -#DS #array #vector + +#DS #array #vector + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/reshape-the-matrix/) -___ + +--- + ### Problem + In MATLAB, there is a handy function called `reshape` which can reshape an `m x n` matrix into a new one with a different size `r x c` keeping its original data. You are given an `m x n` matrix `mat` and two integers `r` and `c` representing the number of rows and the number of columns of the wanted reshaped matrix. @@ -21,17 +31,19 @@ The reshaped matrix should be filled with all the elements of the original matri If the `reshape` operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix. #### Examples + ```markdown **Input:** mat = [[1,2],[3,4]], r = 1, c = 4 **Output:** [[1,2,3,4]] ``` #### Constraints -- m == mat.length -- n == mat[i].length -- 1 <= m, n <= 100 -- -1000 <= mat[i][j] <= 1000 -- 1 <= r, c <= 300 + +- m == mat.length +- n == mat[i].length +- 1 <= m, n <= 100 +- -1000 <= mat[i][j] <= 1000 +- 1 <= r, c <= 300 ### Thoughts @@ -46,6 +58,7 @@ Then, from the hint, I know we can transform any array to 1-D, then transform 1- ### Solution O(nm) solution using two loops + ```cpp class Solution { public: @@ -79,6 +92,7 @@ public: ``` O(mn) Solution using one loop + > [!tip] > use `vector> ans(r, vector(c));` > to initialize a 2-d vector @@ -105,4 +119,4 @@ public: return ans; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Reverse-Bits.md b/OJ notes/pages/Leetcode Reverse-Bits.md index e902f73..d46b1b4 100644 --- a/OJ notes/pages/Leetcode Reverse-Bits.md +++ b/OJ notes/pages/Leetcode Reverse-Bits.md @@ -3,22 +3,35 @@ #### 2022-07-22 15:15 > ##### Algorithms: -> #algorithm #bit_manipulation +> +> #algorithm #bit_manipulation +> > ##### Data structures: -> #DS #bitset +> +> #DS #bitset +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/reverse-bits/) -- [Solution and detailed explanation](https://leetcode.com/problems/reverse-bits/discuss/1232842/JAVA-C%2B%2B-%3A-0ms-or-O(1)-Time-Complexity-or-in-place-or-Detailed-Explanation) -- [Shifting solution an explanation](https://leetcode.com/problems/reverse-bits/discuss/54741/O(1)-bit-operation-C++-solution-(8ms)/301342) -___ +- [Solution and detailed explanation]() +- [Shifting solution an explanation]() + +--- + ### Problem Reverse bits of a given 32 bits unsigned integer. @@ -28,13 +41,13 @@ Reverse bits of a given 32 bits unsigned integer. **Example 1:** **Input:** n = 00000010100101000001111010011100 -**Output:** 964176192 (00111001011110000010100101000000) +**Output:** 964176192 (00111001011110000010100101000000) **Explanation:** The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return 964176192 which its binary representation is **00111001011110000010100101000000**. **Example 2:** **Input:** n = 11111111111111111111111111111101 -**Output:** 3221225471 (10111111111111111111111111111111) +**Output:** 3221225471 (10111111111111111111111111111111) **Explanation:** The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is **10111111111111111111111111111111**. #### Constraints @@ -47,6 +60,7 @@ Reverse bits of a given 32 bits unsigned integer. > This is a #bit_manipulation problem. There are two methods: + - swapping bits inside the bitset - shifting @@ -89,4 +103,4 @@ public: #### Shifting: -==#TODO solve it using shifting== \ No newline at end of file +==#TODO solve it using shifting== diff --git a/OJ notes/pages/Leetcode Reverse-Linked-List.md b/OJ notes/pages/Leetcode Reverse-Linked-List.md index 9df65ae..3eef590 100644 --- a/OJ notes/pages/Leetcode Reverse-Linked-List.md +++ b/OJ notes/pages/Leetcode Reverse-Linked-List.md @@ -3,23 +3,41 @@ #### 2022-06-15 22:07 --- + ##### Algorithms: -#algorithm #recursion #iteration + +#algorithm #recursion #iteration + ##### Data structures: -#DS #linked_list + +#DS #linked_list + ##### Difficulty: -#leetcode #coding_problem #difficulty-medium + +#leetcode #coding_problem #difficulty-medium + ##### Lists: -#CS_list_need_understanding #CS_list_need_practicing + +#CS_list_need_understanding #CS_list_need_practicing + ##### Revisions: + 2022-07-02 + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/reverse-linked-list/) -___ + +--- + ### Problem + Given the `head` of a singly linked list, reverse the list, and return _the reversed list_. + #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg) @@ -46,8 +64,9 @@ Given the `head` of a singly linked list, reverse the list, and return _the reve ``` #### Constraints -- The number of nodes in the list is the range `[0, 5000]`. -- `-5000 <= Node.val <= 5000` + +- The number of nodes in the list is the range `[0, 5000]`. +- `-5000 <= Node.val <= 5000` ### Thoughts @@ -56,16 +75,22 @@ I thought a slow O(n ^ 2) hybrid solution, while there are better algorithms, us The in place insert is easier to understand, and simple to implement, using a very clever trick. > [!summary] My thoughts on the recursion algorithm +> > #### How was that implemented? +> > The recursion algorithm takes the advantage of the fact that when you change the node's next properties or nodes after that, the node before still points to the same node, so when every node after **tmp** is reversed, simply move **tmp** after **tmp->next**, which now points to the tail of reversed list +> > #### Why return the last element of the original list? +> > It returns the last element in the original list to make sure you are always returning the head of the reversed array, since for any reversed list, the last one comes first. > **The only recursive part is returning the _tail node_.** ### Solution + I've referred to this guy: https://leetcode.com/problems/reverse-linked-list/discuss/58130/C%2B%2B-Iterative-and-Recursive Insertion, iteration + ```cpp class Solution { public: @@ -88,6 +113,7 @@ public: ``` Recursion: + ```cpp /** * Definition for singly-linked list. @@ -118,4 +144,4 @@ public: return newHead; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Reverse-String.md b/OJ notes/pages/Leetcode Reverse-String.md index 8463cbb..765c5fa 100644 --- a/OJ notes/pages/Leetcode Reverse-String.md +++ b/OJ notes/pages/Leetcode Reverse-String.md @@ -3,20 +3,33 @@ #### 2022-07-12 08:50 > ##### Algorithms: -> #algorithm #recursion +> +> #algorithm #recursion +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/reverse-string/) -___ + +--- + ### Problem Write a function that reverses a string. The input string is given as an array of characters `s`. @@ -37,8 +50,8 @@ You must do this by modifying the input array [in-place](https://en.wikipedia.or #### Constraints -- `1 <= s.length <= 105` -- `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters). +- `1 <= s.length <= 105` +- `s[i]` is a [printable ascii character](https://en.wikipedia.org/wiki/ASCII#Printable_characters). ### Thoughts @@ -46,7 +59,9 @@ You must do this by modifying the input array [in-place](https://en.wikipedia.or > This is a #recursion problem, also can be solved using iteration. #### Base case: + - size <= 1 + #### Pseudo code: - swap two ends @@ -55,6 +70,7 @@ You must do this by modifying the input array [in-place](https://en.wikipedia.or ### Solution Iteration + ```cpp class Solution { public: @@ -72,6 +88,7 @@ public: ``` Recursion + ```cpp class Solution { void reverse(vector &s, int l, int r) { @@ -86,4 +103,4 @@ class Solution { public: void reverseString(vector &s) { reverse(s, 0, s.size() - 1); } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md b/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md index 922dc9f..2001d8e 100644 --- a/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md +++ b/OJ notes/pages/Leetcode Reverse-Words-In-a-String.md @@ -3,20 +3,33 @@ #### 2022-07-12 09:10 > ##### Algorithms: -> #algorithm #two_pointers +> +> #algorithm #two_pointers +> > ##### Data structures: -> #DS #string +> +> #DS #string +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/reverse-words-in-a-string-iii/) -___ + +--- + ### Problem Given a string `s`, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. @@ -35,16 +48,16 @@ Given a string `s`, reverse the order of characters in each word within a senten #### Constraints -- `1 <= s.length <= 5 * 104` -- `s` contains printable **ASCII** characters. -- `s` does not contain any leading or trailing spaces. -- There is **at least one** word in `s`. -- All the words in `s` are separated by a single space. +- `1 <= s.length <= 5 * 104` +- `s` contains printable **ASCII** characters. +- `s` does not contain any leading or trailing spaces. +- There is **at least one** word in `s`. +- All the words in `s` are separated by a single space. ### Thoughts > [!summary] -> This is a #two_pointers +> This is a #two_pointers very easy and intuitive. @@ -74,4 +87,4 @@ public: return s; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Rotate-Array.md b/OJ notes/pages/Leetcode Rotate-Array.md index 0a30078..7ccd9af 100644 --- a/OJ notes/pages/Leetcode Rotate-Array.md +++ b/OJ notes/pages/Leetcode Rotate-Array.md @@ -3,20 +3,33 @@ #### 2022-07-10 08:54 > ##### Algorithms: +> > #algorithm #array_in_place_operation #reverse_array +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode #CS_list_need_practicing #CS_list_need_understanding +> +> #leetcode #CS_list_need_practicing #CS_list_need_understanding +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/rotate-array/) -___ + +--- + ### Problem Given an array, rotate the array to the right by `k` steps, where `k` is non-negative. @@ -36,15 +49,15 @@ rotate 3 steps to the right: [5,6,7,1,2,3,4] **Input:** nums = [-1,-100,3,99], k = 2 **Output:** [3,99,-1,-100] -**Explanation:** +**Explanation:** rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100] #### Constraints -- `1 <= nums.length <= 105` -- `-231 <= nums[i] <= 231 - 1` -- `0 <= k <= 105` +- `1 <= nums.length <= 105` +- `-231 <= nums[i] <= 231 - 1` +- `0 <= k <= 105` ### Thoughts @@ -57,11 +70,12 @@ This one is hard. - Reversing a subarray changes the edge's neighbors Suppose a array looks like: + ``` [1, 2,| 3, 4, 5] ``` -If reverse all two subarrays, the neighbors isn't changed +If reverse all two subarrays, the neighbors isn't changed only the orders are changed ``` @@ -117,6 +131,7 @@ public: ``` Method 2: + ```cpp class Solution { void swap(vector &nums, int l, int r) { @@ -148,6 +163,7 @@ public: ``` Method 3: + ```cpp class Solution { void swap(vector &nums, int l, int r) { @@ -173,4 +189,4 @@ public: nums.erase(nums.begin(), nums.begin() + k); } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Rotate-Image.md b/OJ notes/pages/Leetcode Rotate-Image.md index 4cf018b..7e18cac 100644 --- a/OJ notes/pages/Leetcode Rotate-Image.md +++ b/OJ notes/pages/Leetcode Rotate-Image.md @@ -3,20 +3,32 @@ 2022-09-02 15:40 > ##### Algorithms: +> > #algorithm #math +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: +> > #leetcode #CS_list_need_understanding +> > ##### Revisions: +> > N/A ##### Links: + - [Link to problem](https://leetcode.com/problems/rotate-image/) - [Solution and explanation](https://leetcode.com/problems/rotate-image/solution/) -___ + +--- + ### Problem You are given an `n x n` 2D `matrix` representing an image, rotate the image by **90** degrees (clockwise). @@ -93,4 +105,4 @@ public: reflect(matrix); } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Rotting-Oranges.md b/OJ notes/pages/Leetcode Rotting-Oranges.md index 38e351d..f8e1b34 100644 --- a/OJ notes/pages/Leetcode Rotting-Oranges.md +++ b/OJ notes/pages/Leetcode Rotting-Oranges.md @@ -3,27 +3,40 @@ #### 2022-07-17 15:12 > ##### Algorithms: +> > #algorithm #BFS +> > ##### Data structures: -> #DS #vector_2d +> +> #DS #vector_2d +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/rotting-oranges/) -___ + +--- + ### Problem You are given an `m x n` `grid` where each cell can have one of three values: -- `0` representing an empty cell, -- `1` representing a fresh orange, or -- `2` representing a rotten orange. +- `0` representing an empty cell, +- `1` representing a fresh orange, or +- `2` representing a rotten orange. Every minute, any fresh orange that is **4-directionally adjacent** to a rotten orange becomes rotten. @@ -46,6 +59,7 @@ Return _the minimum number of minutes that must elapse until no cell has a fresh **Input:** grid = [[2,1,1],[0,1,1],[1,0,1]] **Output:** -1 ``` + **Explanation:** The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally. **Example 3:** @@ -54,14 +68,15 @@ Return _the minimum number of minutes that must elapse until no cell has a fresh **Input:** grid = [[0,2]] **Output:** 0 ``` + **Explanation:** Since there are already no fresh oranges at minute 0, the answer is just 0. #### Constraints -- `m == grid.length` -- `n == grid[i].length` -- `1 <= m, n <= 10` -- `grid[i][j]` is `0`, `1`, or `2`. +- `m == grid.length` +- `n == grid[i].length` +- `1 <= m, n <= 10` +- `grid[i][j]` is `0`, `1`, or `2`. ### Thoughts @@ -70,27 +85,32 @@ Return _the minimum number of minutes that must elapse until no cell has a fresh > the shortest {time, distance} Be wary of these special cases: + - everything is empty cell -> return -1, no orange => no - fresh orange + fresh orange - everything is rotten -> return 0 - everything is fresh -> return -1, impossible to rot > [!tip] update the value in place vs. in queue > Update in place, such as +> > ```cpp > if (grid[a + 1][b] != 0) { > queue.push({a, b}); > grid[a + 1][b] = 0; > } > ``` +> > Can avoid multiple enqueues, because the value is already > updated, so another node in queue can't push that again. +> > ```cpp > grid[a][b] = 0; > if (grid[a + 1][b] != 0) { > queue.push({a, b}); > } > ``` +> > this code might result in pushing the same node twice. ### Solution @@ -163,4 +183,4 @@ public: return time; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Search-A-2D-Matrix-II.md b/OJ notes/pages/Leetcode Search-A-2D-Matrix-II.md index f0a7c3e..67cfc48 100644 --- a/OJ notes/pages/Leetcode Search-A-2D-Matrix-II.md +++ b/OJ notes/pages/Leetcode Search-A-2D-Matrix-II.md @@ -3,25 +3,37 @@ 2022-09-03 14:57 > ##### Algorithms: +> > #algorithm #divide_and_conquer +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode #CS_list_need_practicing +> > ##### Revisions: +> > N/A ##### Links: + - [Link to problem](https://leetcode.com/problems/search-a-2d-matrix-ii/) -___ + +--- + ### Problem Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties: -- Integers in each row are sorted in ascending from left to right. -- Integers in each column are sorted in ascending from top to bottom. +- Integers in each row are sorted in ascending from left to right. +- Integers in each column are sorted in ascending from top to bottom. #### Examples @@ -50,10 +62,33 @@ Write an efficient algorithm that searches for a value `target` in an `m x n` in > [!summary] > This is a #divide_and_conquer problem. -It's divide and conquer, because every time we do a action, +It's divide and conquer, because every time we do a action, the problem is smaller. Start from the top-right, (alternatively, bottom-left), because walking left makes the number smaller, and down makes the number bigger. ### Solution + +```cpp +class Solution { +public: + bool searchMatrix(vector> &matrix, int target) { + // search from top-right + int c = matrix[0].size() - 1; + int r = 0; + int m = matrix.size(); + while (c >= 0 && r < m) { + if (matrix[r][c] > target) { + c--; + } else if (matrix[r][c] < target) { + r++; + } else { + return true; + } + } + + return false; + } +}; +``` \ No newline at end of file diff --git a/OJ notes/pages/Leetcode Search-In-a-Binary-Tree.md b/OJ notes/pages/Leetcode Search-In-a-Binary-Tree.md index d9b1da2..ae1630b 100644 --- a/OJ notes/pages/Leetcode Search-In-a-Binary-Tree.md +++ b/OJ notes/pages/Leetcode Search-In-a-Binary-Tree.md @@ -3,20 +3,33 @@ #### 2022-07-07 08:06 > ##### Algorithms: +> > #algorithm #DFS #BFS +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/search-in-a-binary-search-tree/submissions/) -___ + +--- + ### Problem You are given the `root` of a binary search tree (BST) and an integer `val`. @@ -35,14 +48,12 @@ Example 2: Input: root = [4,2,7,1,3], val = 5 Output: [] - - #### Constraints -- The number of nodes in the tree is in the range `[1, 5000]`. -- `1 <= Node.val <= 107` -- `root` is a binary search tree. -- `1 <= val <= 107` +- The number of nodes in the tree is in the range `[1, 5000]`. +- `1 <= Node.val <= 107` +- `root` is a binary search tree. +- `1 <= val <= 107` ### Thoughts @@ -56,6 +67,7 @@ In BFS, I don't have use for loop inside while loop, since we don't have to cons ### Solution DFS + ```cpp /** * Definition for a binary tree node. @@ -96,7 +108,8 @@ public: }; ``` -Which can be simplified to +Which can be simplified to + ```cpp /** * Definition for a binary tree node. @@ -120,7 +133,7 @@ public: if (root->val == val) { return root; } - + auto left = searchBST(root->left, val); if (left) { return left; @@ -131,6 +144,7 @@ public: ``` BFS + ```cpp /** * Definition for a binary tree node. @@ -169,4 +183,4 @@ public: return nullptr; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Search-Insert-Position.md b/OJ notes/pages/Leetcode Search-Insert-Position.md index 2874f60..8bad8e8 100644 --- a/OJ notes/pages/Leetcode Search-Insert-Position.md +++ b/OJ notes/pages/Leetcode Search-Insert-Position.md @@ -3,20 +3,33 @@ #### 2022-07-09 10:25 > ##### Algorithms: -> #algorithm #binary_search +> +> #algorithm #binary_search +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/binary-search/) -___ + +--- + ### Problem Given an array of integers `nums` which is sorted in ascending order, and an integer `target`, write a function to search `target` in `nums`. If `target` exists, then return its index. Otherwise, return `-1`. @@ -39,10 +52,10 @@ You must write an algorithm with `O(log n)` runtime complexity. #### Constraints -- `1 <= nums.length <= 104` -- `-104 < nums[i], target < 104` -- All the integers in `nums` are **unique**. -- `nums` is sorted in ascending order. +- `1 <= nums.length <= 104` +- `-104 < nums[i], target < 104` +- All the integers in `nums` are **unique**. +- `nums` is sorted in ascending order. ### Thoughts @@ -56,6 +69,7 @@ if the value is found, simply return it if not found, at the end, position `l - 1` should be smaller than val. and position `l` should be bigger, which is the position for the answer: + ``` If not, return the index where it would be if it were inserted in order. ``` @@ -63,6 +77,7 @@ If not, return the index where it would be if it were inserted in order. ### Solution Iteration + ```cpp class Solution { public: @@ -71,11 +86,11 @@ public: int r = nums.size() - 1; int l = 0; int mid, val; - + do { mid = l + (r - l) / 2; val = nums[mid]; - + if (val == target) { return mid; } else if (val < target) { @@ -84,8 +99,8 @@ public: r = mid - 1; } } while (l <= r); - + return l; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Search-a-2D-Matrix.md b/OJ notes/pages/Leetcode Search-a-2D-Matrix.md index ac12c60..0d51006 100644 --- a/OJ notes/pages/Leetcode Search-a-2D-Matrix.md +++ b/OJ notes/pages/Leetcode Search-a-2D-Matrix.md @@ -3,23 +3,36 @@ #### 2022-06-13 15:33 --- + ##### Algorithms: + #algorithm #binary_search + ##### Data structures: + #DS #vector #vector_2d + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/search-a-2d-matrix/submissions/) -___ + +--- + ### Problem + Write an efficient algorithm that searches for a value `target` in an `m x n` integer matrix `matrix`. This matrix has the following properties: -- Integers in each row are sorted from left to right. -- The first integer of each row is greater than the last integer of the previous row. +- Integers in each row are sorted from left to right. +- The first integer of each row is greater than the last integer of the previous row. #### Examples + **Example 1:** ![exapmle1](https://assets.leetcode.com/uploads/2020/10/05/mat.jpg) @@ -28,6 +41,7 @@ Write an efficient algorithm that searches for a value `target` in an `m x n` in **Input:** matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 **Output:** true ``` + **Example 2:** ![exapmle2](https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg) @@ -36,25 +50,31 @@ Write an efficient algorithm that searches for a value `target` in an `m x n` in **Input:** matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 **Output:** false ``` + #### Constraints -- m == matrix.length -- n == matrix[i].length -- 1 <= m, n <= 100 -- -104 <= matrix[i][j], target <= 104 + +- m == matrix.length +- n == matrix[i].length +- 1 <= m, n <= 100 +- -104 <= matrix[i][j], target <= 104 ### Thoughts Binary search algorithm, with simple 2-d to 1-d conversion + > [!tip] Binary search while loops > In binary search, remember to check for: +> > - l <= r -> And use: +> And use: > - l = mid + 1 > - r = mid - 1 -> Init r as m * n - 1 to avoid mid being OOB. +> Init r as m \* n - 1 to avoid mid being OOB. + ### Solution ==note how I calculated the mid, i, j, and how I changed r and l== + ```cpp class Solution { public: @@ -85,4 +105,4 @@ public: } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Single-Number.md b/OJ notes/pages/Leetcode Single-Number.md index cbba735..59b924a 100644 --- a/OJ notes/pages/Leetcode Single-Number.md +++ b/OJ notes/pages/Leetcode Single-Number.md @@ -3,22 +3,35 @@ #### 2022-07-22 15:31 > ##### Algorithms: -> #algorithm #bit_manipulation +> +> #algorithm #bit_manipulation +> > ##### Data structures: +> > #DS #bitset +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/single-number/) - [Learn about XOR](https://en.wikipedia.org/wiki/Exclusive_or#Computer_science) - [Explanation](https://leetcode.com/problems/single-number/discuss/1772139/C%2B%2Bor-Explained-Everything-w-WHY-XOR-WORKSor-BRUTE-FORCE-TO-OPTIMIZEDor-STEP-BY-STEP-DRY-RUN) -___ + +--- + ### Problem Given a **non-empty** array of integers `nums`, every element appears _twice_ except for one. Find that single one. @@ -44,16 +57,15 @@ You must implement a solution with a linear runtime complexity and use only co #### Constraints -- `1 <= nums.length <= 3 * 104` -- `-3 * 104 <= nums[i] <= 3 * 104` -- Each element in the array appears twice except for one element which appears only once. +- `1 <= nums.length <= 3 * 104` +- `-3 * 104 <= nums[i] <= 3 * 104` +- Each element in the array appears twice except for one element which appears only once. ### Thoughts > [!summary] > This is a #bit_manipulation problem utilizing the XOR operator - The XOR operator has some properties: ``` @@ -79,4 +91,4 @@ public: return ans; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Sort-Colors.md b/OJ notes/pages/Leetcode Sort-Colors.md index f801b68..f0ff203 100644 --- a/OJ notes/pages/Leetcode Sort-Colors.md +++ b/OJ notes/pages/Leetcode Sort-Colors.md @@ -3,19 +3,31 @@ #### 2022-09-01 13:24 > ##### Algorithms: -> #algorithm #two_pointers +> +> #algorithm #two_pointers +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Links: + - [Link to problem](https://leetcode.com/problems/sort-colors/) -___ + +--- + ### Problem Given an array `nums` with `n` objects colored red, white, or blue, sort them **[in-place](https://en.wikipedia.org/wiki/In-place_algorithm)** so that objects of the same color are adjacent, with the colors in the order red, white, and blue. @@ -38,16 +50,16 @@ You must solve this problem without using the library's sort function. #### Constraints -- `n == nums.length` -- `1 <= n <= 300` -- `nums[i]` is either `0`, `1`, or `2`. +- `n == nums.length` +- `1 <= n <= 300` +- `nums[i]` is either `0`, `1`, or `2`. ### Thoughts > [!summary] > This is a variant of double pointer method. -Simple double pointer method, check for cur and pointers to +Simple double pointer method, check for cur and pointers to avoid infinite loops. ### Solution @@ -72,4 +84,4 @@ public: } } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Squares-of-a-Sorted-Array.md b/OJ notes/pages/Leetcode Squares-of-a-Sorted-Array.md index 29fb059..9b6c957 100644 --- a/OJ notes/pages/Leetcode Squares-of-a-Sorted-Array.md +++ b/OJ notes/pages/Leetcode Squares-of-a-Sorted-Array.md @@ -3,20 +3,33 @@ #### 2022-07-10 08:50 > ##### Algorithms: -> #algorithm #two_pointers +> +> #algorithm #two_pointers +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/squares-of-a-sorted-array/) -___ + +--- + ### Problem Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_. @@ -39,14 +52,14 @@ After sorting, it becomes [0,1,9,16,100]. #### Constraints -- `1 <= nums.length <= 104` -- `-104 <= nums[i] <= 104` -- `nums` is sorted in **non-decreasing** order. +- `1 <= nums.length <= 104` +- `-104 <= nums[i] <= 104` +- `nums` is sorted in **non-decreasing** order. ### Thoughts > [!summary] -> This is a #two_pointers +> This is a #two_pointers Using two pointers. One from left, one from right end. @@ -55,6 +68,7 @@ One from left, one from right end. ### Solution cpp + ```cpp class Solution { public: diff --git a/OJ notes/pages/Leetcode Subsets.md b/OJ notes/pages/Leetcode Subsets.md index 6e4160d..cb7670d 100644 --- a/OJ notes/pages/Leetcode Subsets.md +++ b/OJ notes/pages/Leetcode Subsets.md @@ -3,20 +3,33 @@ #### 2022-07-22 16:16 > ##### Algorithms: -> #algorithm #backtrack +> +> #algorithm #backtrack +> > ##### Data structures: -> #DS #vector +> +> #DS #vector +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/subsets/) -___ + +--- + ### Problem Given an integer array `nums` of **unique** elements, return _all possible subsets (the power set)_. @@ -41,9 +54,9 @@ The solution set **must not** contain duplicate subsets. Return the solution in #### Constraints -- `1 <= nums.length <= 10` -- `-10 <= nums[i] <= 10` -- All the numbers of `nums` are **unique**. +- `1 <= nums.length <= 10` +- `-10 <= nums[i] <= 10` +- All the numbers of `nums` are **unique**. ### Thoughts @@ -53,16 +66,17 @@ The solution set **must not** contain duplicate subsets. Return the solution in It asked for combinations, so this is a backtrack problem. go from index 0 to last one, in each iteration, you have two choices: + - Add this number - Don't add this number -And we try different combinations at the same level, aka. backtracking. + And we try different combinations at the same level, aka. backtracking. #### Pseudo code: - When loc == size, append combination to answer - Else, start trying different solutions: - - Append this element to combs and backtrack - - pop this from combs and backtrack + - Append this element to combs and backtrack + - pop this from combs and backtrack ### Solution @@ -94,4 +108,4 @@ public: return ans; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Symmetric-Tree.md b/OJ notes/pages/Leetcode Symmetric-Tree.md index 2669665..cf8bd62 100644 --- a/OJ notes/pages/Leetcode Symmetric-Tree.md +++ b/OJ notes/pages/Leetcode Symmetric-Tree.md @@ -3,24 +3,39 @@ #### 2022-07-05 10:15 > ##### Algorithms: -> #algorithm #DFS #recursion #BFS +> +> #algorithm #DFS #recursion #BFS +> > ##### Data structures: -> #DS #binary_tree +> +> #DS #binary_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/symmetric-tree/) -___ + +--- + ### Problem + Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e., symmetric around its center). #### Examples + **Example 1:** ![](https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg) @@ -36,24 +51,28 @@ Given the `root` of a binary tree, _check whether it is a mirror of itself_ (i.e **Output:** false #### Constraints + **Constraints:** -- The number of nodes in the tree is in the range `[1, 1000]`. -- `-100 <= Node.val <= 100` +- The number of nodes in the tree is in the range `[1, 1000]`. +- `-100 <= Node.val <= 100` + ### Thoughts > [!summary] > This is a #DFS #recursion problem Method 1, DFS-like Recursion: + - Base Cases: - - left and right are nullptr: true - - else if left or right is nullptr: false, must be asymmetric - - left->val != right->val: false + - left and right are nullptr: true + - else if left or right is nullptr: false, must be asymmetric + - left->val != right->val: false - return check(left->left, right->right) && check(left->right, right->left) Method 2, BFS-like Iteration: In the while loop: + - Take two nodes from queue, they should be matched. - if both are nullptr, continue. - if one is nullptr, return false. @@ -64,6 +83,7 @@ In the while loop: ### Solution Recursion, 16ms + ```cpp /** * Definition for a binary tree node. @@ -104,6 +124,7 @@ public: ``` BFS, iteration, 8ms + ```cpp /** * Definition for a binary tree node. @@ -171,4 +192,4 @@ public: return true; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Triangle.md b/OJ notes/pages/Leetcode Triangle.md index a6dcb7e..6c8483f 100644 --- a/OJ notes/pages/Leetcode Triangle.md +++ b/OJ notes/pages/Leetcode Triangle.md @@ -3,18 +3,29 @@ #### 2022-07-20 22:59 > ##### Algorithms: -> #algorithm #dynamic_programming +> +> #algorithm #dynamic_programming +> > ##### Difficulty: +> > #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/triangle/) -___ + +--- + ### Problem Given a `triangle` array, return _the minimum path sum from top to bottom_. @@ -45,10 +56,10 @@ The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above) #### Constraints -- `1 <= triangle.length <= 200` -- `triangle[0].length == 1` -- `triangle[i].length == triangle[i - 1].length + 1` -- `-104 <= triangle[i][j] <= 104` +- `1 <= triangle.length <= 200` +- `triangle[0].length == 1` +- `triangle[i].length == triangle[i - 1].length + 1` +- `-104 <= triangle[i][j] <= 104` ### Thoughts @@ -99,4 +110,4 @@ public: return minimum(triangle, triangle.size() - 1, 0, triangle.size() - 1); } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Two-Sum-II-Input-Array-Is-Sorted.md b/OJ notes/pages/Leetcode Two-Sum-II-Input-Array-Is-Sorted.md index 96fc988..8f10739 100644 --- a/OJ notes/pages/Leetcode Two-Sum-II-Input-Array-Is-Sorted.md +++ b/OJ notes/pages/Leetcode Two-Sum-II-Input-Array-Is-Sorted.md @@ -3,20 +3,33 @@ #### 2022-07-11 14:54 > ##### Algorithms: -> #algorithm #two_pointers +> +> #algorithm #two_pointers +> > ##### Data structures: -> #DS #array +> +> #DS #array +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: -> #leetcode +> +> #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/) -___ + +--- + ### Problem Given a **1-indexed** array of integers `numbers` that is already **_sorted in non-decreasing order_**, find two numbers such that they add up to a specific `target` number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`. @@ -49,11 +62,11 @@ Your solution must use only constant extra space. #### Constraints -- `2 <= numbers.length <= 3 * 104` -- `-1000 <= numbers[i] <= 1000` -- `numbers` is sorted in **non-decreasing order**. -- `-1000 <= target <= 1000` -- The tests are generated such that there is **exactly one solution**. +- `2 <= numbers.length <= 3 * 104` +- `-1000 <= numbers[i] <= 1000` +- `numbers` is sorted in **non-decreasing order**. +- `-1000 <= target <= 1000` +- The tests are generated such that there is **exactly one solution**. ### Thoughts diff --git a/OJ notes/pages/Leetcode Two-Sum-IV-Input-Is-a-BST.md b/OJ notes/pages/Leetcode Two-Sum-IV-Input-Is-a-BST.md index 54e5198..67c8367 100644 --- a/OJ notes/pages/Leetcode Two-Sum-IV-Input-Is-a-BST.md +++ b/OJ notes/pages/Leetcode Two-Sum-IV-Input-Is-a-BST.md @@ -3,21 +3,34 @@ #### 2022-07-08 11:11 > ##### Algorithms: -> #algorithm #binary_search #BFS +> +> #algorithm #binary_search #BFS +> > ##### Data structures: -> #DS #binary_tree #binary_search_tree +> +> #DS #binary_tree #binary_search_tree +> > ##### Difficulty: +> > #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/) - [Three method to solve this](https://leetcode.com/problems/two-sum-iv-input-is-a-bst/discuss/106059/JavaC%2B%2B-Three-simple-methods-choose-one-you-like) -___ + +--- + ### Problem Given the `root` of a Binary Search Tree and a target number `k`, return _`true` if there exist two elements in the BST such that their sum is equal to the given target_. @@ -40,10 +53,10 @@ Given the `root` of a Binary Search Tree and a target number `k`, return _`true` #### Constraints -- The number of nodes in the tree is in the range `[1, 104]`. -- `-104 <= Node.val <= 104` -- `root` is guaranteed to be a **valid** binary search tree. -- `-105 <= k <= 105` +- The number of nodes in the tree is in the range `[1, 104]`. +- `-104 <= Node.val <= 104` +- `root` is guaranteed to be a **valid** binary search tree. +- `-105 <= k <= 105` ### Thoughts @@ -51,14 +64,16 @@ Given the `root` of a Binary Search Tree and a target number `k`, return _`true` > This is a #BFS #hash_table problem. Mainly two methods: + 1. #BFS with hash table. Time space O(n) - This can be quicker since you are starting at the middle, which is more likely to hit the answer, theoretically taking less time. + This can be quicker since you are starting at the middle, which is more likely to hit the answer, theoretically taking less time. 2. #binary_search. Time O(hn), h is the height of BST, best case h == log(n), worst case h == n - for every node, binary search in the tree for the answer. + for every node, binary search in the tree for the answer. ### Solution BFS with hash table + ```cpp /** * Definition for a binary tree node. @@ -79,18 +94,18 @@ public: unordered_set uset; queue pending; pending.push(root); - + TreeNode* ptr; while(!pending.empty()) { ptr = pending.front(); pending.pop(); - + // find first, to avoid k = 10, val = 5 if (uset.find(ptr->val) != uset.end()) { return true; } uset.insert(k - ptr->val); - + if (ptr->left) { pending.push(ptr->left); } @@ -98,8 +113,8 @@ public: pending.push(ptr->right); } } - + return false; } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Two-Sum.md b/OJ notes/pages/Leetcode Two-Sum.md index 8855a7b..6167d35 100644 --- a/OJ notes/pages/Leetcode Two-Sum.md +++ b/OJ notes/pages/Leetcode Two-Sum.md @@ -3,19 +3,30 @@ #### 2022-06-10 --- -##### Data structures: -#DS #array #map #unordered_map -##### Algorithms: -#algorithm -##### Difficulty: -#coding_problem #leetcode #difficulty-easy -##### Related topics: -##### Links: -- [Link to problem](https://leetcode.com/problems/two-sum) -- [O(n) Solution](https://leetcode.com/problems/two-sum/discuss/13/Accepted-C++-O(n)-Solution/263) -___ +##### Data structures: + +#DS #array #map #unordered_map + +##### Algorithms: + +#algorithm + +##### Difficulty: + +#coding_problem #leetcode #difficulty-easy + +##### Related topics: + +##### Links: + +- [Link to problem](https://leetcode.com/problems/two-sum) +- [O(n) Solution]() + +--- + ### Problem + Given an array of integers `nums` and an integer `target`, return _indices of the two numbers such that they add up to `target`_. You may assume that each input would have **_exactly_ one solution**, and you may not use the _same_ element twice. @@ -48,22 +59,23 @@ Output: [0,1] #### Constraints -- `2 <= nums.length <= 104` -- `-109 <= nums[i] <= 109` -- `-109 <= target <= 109` -- **Only one valid answer exists.** +- `2 <= nums.length <= 104` +- `-109 <= nums[i] <= 109` +- `-109 <= target <= 109` +- **Only one valid answer exists.** ### Thoughts Firstly, I think up an easy O(n^2) solution, by using a nested loop, -But the best solution utilizes an __[[cpp_std_unordered_map]]__. +But the best solution utilizes an **[[cpp_std_unordered_map]]**. > [!tips] -> Use **[[cpp_std_unordered_map | unordered map]]** to create a hash table, it has O(1) in search, delete and insert. #tip +> Use **[[cpp_std_unordered_map | unordered map]]** to create a hash table, it has O(1) in search, delete and insert. #tip ### Solution O(n^2) solution + ```cpp class Solution { public: @@ -84,6 +96,7 @@ public: ``` O(n) solution + ```cpp class Solution { public: @@ -95,7 +108,7 @@ public: if ( search != umap.end()) { return vector {i, search->second}; } - + umap[nums[i]] = i; } return vector {0, 0}; diff --git a/OJ notes/pages/Leetcode Valid-Anagram.md b/OJ notes/pages/Leetcode Valid-Anagram.md index 14ce9a8..870c379 100644 --- a/OJ notes/pages/Leetcode Valid-Anagram.md +++ b/OJ notes/pages/Leetcode Valid-Anagram.md @@ -3,29 +3,44 @@ #### 2022-06-14 13:36 --- + ##### Algorithms: -#algorithm #hash_table + +#algorithm #hash_table + ##### Data structures: -#DS #array + +#DS #array + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/valid-anagram/) -___ + +--- + ### Problem + Given two strings `s` and `t`, return `true` _if_ `t` _is an anagram of_ `s`_, and_ `false` _otherwise_. An **Anagram** is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. **Follow up:** What if the inputs contain Unicode characters? How would you adapt your solution to such a case? + #### Examples + **Example 1:** ```markdown **Input:** s = "anagram", t = "nagaram" **Output:** true ``` + **Example 2:** ```markdown @@ -34,8 +49,9 @@ An **Anagram** is a word or phrase formed by rearranging the letters of a differ ``` #### Constraints -- `1 <= s.length, t.length <= 5 * 104` -- `s` and `t` consist of lowercase English letters. + +- `1 <= s.length, t.length <= 5 * 104` +- `s` and `t` consist of lowercase English letters. ### Thoughts @@ -50,7 +66,6 @@ Refer to this [site](https://www.cprogramming.com/tutorial/unicode.html) and thi ### Solution - ```cpp class Solution { public: @@ -74,4 +89,4 @@ public: } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Leetcode Valid-Parentheses.md b/OJ notes/pages/Leetcode Valid-Parentheses.md index d622ffb..7f0e684 100644 --- a/OJ notes/pages/Leetcode Valid-Parentheses.md +++ b/OJ notes/pages/Leetcode Valid-Parentheses.md @@ -3,19 +3,31 @@ #### 2022-06-16 14:50 > ##### Data structures: +> > #DS #stack +> > ##### Difficulty: -> #coding_problem #difficulty-easy +> +> #coding_problem #difficulty-easy +> > ##### Additional tags: +> > #leetcode +> > ##### Revisions: +> > 1st revision: 2022-07-03 optimize code ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/valid-parentheses/) -___ + +--- + ### Problem + Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid. An input string is valid if: @@ -24,6 +36,7 @@ An input string is valid if: 2. Open brackets must be closed in the correct order. #### Examples + **Example 1:** ```markdown @@ -44,17 +57,22 @@ An input string is valid if: **Input:** s = "(]" **Output:** false ``` + #### Constraints -- `1 <= s.length <= 104` -- `s` consists of parentheses only `'()[]{}'`. + +- `1 <= s.length <= 104` +- `s` consists of parentheses only `'()[]{}'`. ### Thoughts -Basic stack usage. +Basic stack usage. Can be implemented using std_stack or stc_vector. obviously i should use std_stack. + ### Solution + 1st revision: optimized code + ```cpp class Solution { public: @@ -129,4 +147,3 @@ public: }; ``` - diff --git a/OJ notes/pages/Leetcode Valid-Sudoku.md b/OJ notes/pages/Leetcode Valid-Sudoku.md index 290b8f5..17fb850 100644 --- a/OJ notes/pages/Leetcode Valid-Sudoku.md +++ b/OJ notes/pages/Leetcode Valid-Sudoku.md @@ -3,15 +3,24 @@ #### 2022-06-13 12:56 --- + ##### Data structures: -#DS #vector + +#DS #vector + ##### Difficulty: -#leetcode #coding_problem #difficulty-easy + +#leetcode #coding_problem #difficulty-easy + ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/valid-sudoku/) -- [Simple solution](https://leetcode.com/problems/valid-sudoku/discuss/15464/My-short-solution-by-C%2B%2B.-O(n2)) -___ +- [Simple solution]() + +--- + ### Problem Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to be validated **according to the following rules**: @@ -22,13 +31,15 @@ Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to b **Note:** -- A Sudoku board (partially filled) could be valid but is not necessarily solvable. -- Only the filled cells need to be validated according to the mentioned rules. +- A Sudoku board (partially filled) could be valid but is not necessarily solvable. +- Only the filled cells need to be validated according to the mentioned rules. #### Examples + ![[Pasted image 20220613125739.png]] + ```markdown -**Input:** board = +**Input:** board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] @@ -42,7 +53,7 @@ Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to b ``` ```markdown -**Input:** board = +**Input:** board = [["8","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] @@ -58,9 +69,9 @@ Determine if a `9 x 9` Sudoku board is valid. Only the filled cells need to b #### Constraints -- board.length == 9 -- board[i].length == 9 -- board[i][j] is a digit `1-9` or `'.'`. +- board.length == 9 +- board[i].length == 9 +- board[i][j] is a digit `1-9` or `'.'`. ### Thoughts @@ -70,14 +81,17 @@ Besides overthinking, I also spent a lot of time learning how to use sets and in **Take TWO:** Use a hash table to store whether an element is present: + ```cpp int usedRow[9][10] = {}; int usedCol[9][10] = {}; int usedGrid[9][10] = {}; ``` + ### Solution My new solution using hash map + ```cpp class Solution { public: @@ -115,6 +129,7 @@ public: ``` Bad solution :( + ```cpp class Solution { public: diff --git a/OJ notes/pages/Leetcode Validate-Binary-Search-Tree.md b/OJ notes/pages/Leetcode Validate-Binary-Search-Tree.md index 69e3398..0834fe2 100644 --- a/OJ notes/pages/Leetcode Validate-Binary-Search-Tree.md +++ b/OJ notes/pages/Leetcode Validate-Binary-Search-Tree.md @@ -3,28 +3,42 @@ #### 2022-07-08 10:36 > ##### Algorithms: -> #algorithm #DFS #DFS_inorder +> +> #algorithm #DFS #DFS_inorder +> > ##### Data structures: -> #DS #binary_tree #binary_search_tree +> +> #DS #binary_tree #binary_search_tree +> > ##### Difficulty: -> #coding_problem #difficulty-medium +> +> #coding_problem #difficulty-medium +> > ##### Additional tags: -> #leetcode #CS_list_need_practicing +> +> #leetcode #CS_list_need_practicing +> > ##### Revisions: +> > N/A ##### Related topics: + ##### Links: + - [Link to problem](https://leetcode.com/problems/validate-binary-search-tree/) -___ + +--- + ### Problem + Given the `root` of a binary tree, _determine if it is a valid binary search tree (BST)_. A **valid BST** is defined as follows: -- The left subtree of a node contains only nodes with keys **less than** the node's key. -- ==The right subtree of a node contains only nodes with keys **greater than** the node's key.== -- Both the left and right subtrees must also be binary search trees. +- The left subtree of a node contains only nodes with keys **less than** the node's key. +- ==The right subtree of a node contains only nodes with keys **greater than** the node's key.== +- Both the left and right subtrees must also be binary search trees. #### Examples @@ -44,8 +58,10 @@ A **valid BST** is defined as follows: **Explanation:** The root node's value is 5 but its right child's value is 4. #### Constraints -- The number of nodes in the tree is in the range `[1, 104]`. -- `-231 <= Node.val <= 231 - 1` + +- The number of nodes in the tree is in the range `[1, 104]`. +- `-231 <= Node.val <= 231 - 1` + ### Thoughts > [!summary] @@ -104,4 +120,4 @@ public: return checker(root, prev); } }; -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/Two pointers approach.md b/OJ notes/pages/Two pointers approach.md index de58864..f70a55f 100644 --- a/OJ notes/pages/Two pointers approach.md +++ b/OJ notes/pages/Two pointers approach.md @@ -2,23 +2,36 @@ #### 2022-06-14 23:06 -___ +--- + ##### Algorithms: -#algorithm #two_pointers + +#algorithm #two_pointers + ##### Data structures: -#array #linked_list + +#array #linked_list + ##### Difficulty: + #CS_analysis #difficulty- + ##### Related problems: + ##### Links: + - [leetcode](https://leetcode.com/explore/learn/card/fun-with-arrays/511/in-place-operations/) -___ + +--- ### What is Two pointers approach? + By using two pointers, to in place modify array elements. + - One fast and one slow [[Leetcode Best-Time-To-Buy-And-Sell-Stock]] or [[Leetcode Linked-List-Cycle]] - The two are unordered [[Leetcode Merge-Two-Sorted-Lists]] ### Why and when to use it? + - There are two arrays, or linked lists -- They are sorted, or operation in place will not interfere elements after. \ No newline at end of file +- They are sorted, or operation in place will not interfere elements after. diff --git a/OJ notes/pages/cpp_Range_based_for_loop.md b/OJ notes/pages/cpp_Range_based_for_loop.md index d01948e..2173963 100644 --- a/OJ notes/pages/cpp_Range_based_for_loop.md +++ b/OJ notes/pages/cpp_Range_based_for_loop.md @@ -2,72 +2,80 @@ #### 2022-06-11 -___ +--- + ##### Data structures: -#DS #array #vector #multiset + +#DS #array #vector #multiset + ##### Difficulty: + #CS_analysis #difficulty-easy + ##### Related problems: + ##### Links: + - [cppreference](https://en.cppreference.com/w/cpp/language/range-for) -___ + +--- ### What is cpp_Range_based_for_loop? + Executes a for loop over a range. Used as a more readable equivalent to the traditional [for loop](https://en.cppreference.com/w/cpp/language/for "cpp/language/for") operating over a range of values, such as all elements in a container. ### Example - ```cpp #include #include - + int main() { std::vector v = {0, 1, 2, 3, 4, 5}; - + for (const int& i : v) // access by const reference std::cout << i << ' '; std::cout << '\n'; - + for (auto i : v) // access by value, the type of i is int std::cout << i << ' '; std::cout << '\n'; - + for (auto&& i : v) // access by forwarding reference, the type of i is int& std::cout << i << ' '; std::cout << '\n'; - + const auto& cv = v; - + for (auto&& i : cv) // access by f-d reference, the type of i is const int& std::cout << i << ' '; std::cout << '\n'; - + for (int n : {0, 1, 2, 3, 4, 5}) // the initializer may be a braced-init-list std::cout << n << ' '; std::cout << '\n'; - + int a[] = {0, 1, 2, 3, 4, 5}; for (int n : a) // the initializer may be an array std::cout << n << ' '; std::cout << '\n'; - - for ([[maybe_unused]] int n : a) + + for ([[maybe_unused]] int n : a) std::cout << 1 << ' '; // the loop variable need not be used std::cout << '\n'; - + for (auto n = v.size(); auto i : v) // the init-statement (C++20) std::cout << --n + i << ' '; std::cout << '\n'; - + for (typedef decltype(v)::value_type elem_t; elem_t i : v) // typedef declaration as init-statement (C++20) std::cout << i << ' '; std::cout << '\n'; - + #if __cplusplus > 23'00 + 200000 for (using elem_t = decltype(v)::value_type; elem_t i : v) // alias declaration as init-statement, same as above (C++23) @@ -78,15 +86,16 @@ int main() ``` Possible output: + ``` -0 1 2 3 4 5 -0 1 2 3 4 5 -0 1 2 3 4 5 -0 1 2 3 4 5 -0 1 2 3 4 5 -0 1 2 3 4 5 -1 1 1 1 1 1 -5 5 5 5 5 5 -0 1 2 3 4 5 0 1 2 3 4 5 -``` \ No newline at end of file +0 1 2 3 4 5 +0 1 2 3 4 5 +0 1 2 3 4 5 +0 1 2 3 4 5 +0 1 2 3 4 5 +1 1 1 1 1 1 +5 5 5 5 5 5 +0 1 2 3 4 5 +0 1 2 3 4 5 +``` diff --git a/OJ notes/pages/cpp_std_multiset.md b/OJ notes/pages/cpp_std_multiset.md index f2ddc39..67ef279 100644 --- a/OJ notes/pages/cpp_std_multiset.md +++ b/OJ notes/pages/cpp_std_multiset.md @@ -2,16 +2,24 @@ #### 2022-06-12 -___ +--- + ##### Data structures: + #DS #multiset + ##### Difficulty: + #CS_analysis #difficulty-easy + ##### Related problems: + ##### Links: + - [cppreference](https://en.cppreference.com/w/cpp/container/multiset) -___ + +--- ### What is Multiset? -`std::multiset` is an associative container that contains a sorted set of objects of type Key. Unlike set, multiple keys with equivalent values are allowed. Sorting is done using the key comparison function Compare. Search, insertion, and removal operations have logarithmic complexity. \ No newline at end of file +`std::multiset` is an associative container that contains a sorted set of objects of type Key. Unlike set, multiple keys with equivalent values are allowed. Sorting is done using the key comparison function Compare. Search, insertion, and removal operations have logarithmic complexity. diff --git a/OJ notes/pages/cpp_std_sort.md b/OJ notes/pages/cpp_std_sort.md index 9ace463..7865439 100644 --- a/OJ notes/pages/cpp_std_sort.md +++ b/OJ notes/pages/cpp_std_sort.md @@ -2,55 +2,65 @@ #### 2022-06-11 -___ +--- + ##### Algorithms: + #algorithm #sort + ##### Difficulty: + #CS_analysis #difficulty-easy + ##### Related problems: + ##### Links: + - [cpp reference](https://en.cppreference.com/w/cpp/algorithm/sort) -___ + +--- ### What is Sort? + Sorts the elements in the range `[first, last)` in non-descending order. The order of equal elements is not guaranteed to be preserved. The default Compare function is less: `<` ### Example + ```cpp #include #include #include #include #include - + int main() { std::array s = {5, 7, 4, 2, 8, 6, 1, 9, 0, 3}; - + auto print = [&s](std::string_view const rem) { for (auto a : s) { std::cout << a << ' '; } std::cout << ": " << rem << '\n'; }; - + std::sort(s.begin(), s.end()); print("sorted with the default operator<"); - + std::sort(s.begin(), s.end(), std::greater()); print("sorted with the standard library compare function object"); - + struct { bool operator()(int a, int b) const { return a < b; } } customLess; std::sort(s.begin(), s.end(), customLess); print("sorted with a custom function object"); - + std::sort(s.begin(), s.end(), [](int a, int b) { return a > b; }); print("sorted with a lambda expression"); } -``` \ No newline at end of file +``` diff --git a/OJ notes/pages/cpp_std_unordered_map.md b/OJ notes/pages/cpp_std_unordered_map.md index 69cf8ab..5106eae 100644 --- a/OJ notes/pages/cpp_std_unordered_map.md +++ b/OJ notes/pages/cpp_std_unordered_map.md @@ -2,17 +2,25 @@ #### 2022-06-10 -___ +--- + ##### Data structures: + #DS #unordered_map #hash_table + ##### Difficulty: + #CS_analysis #difficulty-easy + ##### Related problems: + ##### Links: + - [Unordered map explainer](https://www.geeksforgeeks.org/unordered_map-in-cpp-stl/) - [Unordered map vs ordered map](https://www.geeksforgeeks.org/unordered_map-in-cpp-stl/) - [cpp reference](https://en.cppreference.com/w/cpp/container/unordered_map) -___ + +--- ### What is Unordered Map? @@ -28,45 +36,46 @@ Internally unordered_map is implemented using [Hash Table](https://www.geeksforg ### How to use Example taken from [g4g](https://www.geeksforgeeks.org/unordered_map-in-cpp-stl/) + ```cpp // C++ program to demonstrate functionality of unordered_map #include #include using namespace std; - + int main() { // Declaring umap to be of type // key will be of string type and mapped value will // be of double type unordered_map umap; - + // inserting values by using [] operator umap["PI"] = 3.14; umap["root2"] = 1.414; umap["root3"] = 1.732; umap["log10"] = 2.302; umap["loge"] = 1.0; - + // inserting value by insert function umap.insert(make_pair("e", 2.718)); - + string key = "PI"; - + // If key not found in map iterator to end is returned if (umap.find(key) == umap.end()) cout << key << " not found\n\n"; - + // If key found then iterator to that key is returned else cout << "Found " << key << "\n\n"; - + key = "lambda"; if (umap.find(key) == umap.end()) cout << key << " not found\n"; else cout << "Found " << key << endl; - + // iterating over all value of umap unordered_map:: iterator itr; cout << "\nAll Elements : \n"; @@ -78,4 +87,4 @@ int main() cout << itr->first << " " << itr->second << endl; } } -``` \ No newline at end of file +``` diff --git a/Wiki/ChrootMan.md b/Wiki/ChrootMan.md index 0ca54d2..afddd78 100644 --- a/Wiki/ChrootMan.md +++ b/Wiki/ChrootMan.md @@ -12,5 +12,6 @@ Write a ncurses or slang program to display stuff and: chroots. Goal: + - [ ] to learn cpp -- [ ] to learn cpp based build systems \ No newline at end of file +- [ ] to learn cpp based build systems diff --git a/Wiki/Notes for CS.md b/Wiki/Notes for CS.md index 39c25ac..09155d6 100644 --- a/Wiki/Notes for CS.md +++ b/Wiki/Notes for CS.md @@ -1,8 +1,8 @@ -1. use ```int arr[][Columns]``` for 2-d function declaration -2. ```#pragma gcc optimize("Ofast, inline")``` to increase speed +1. use `int arr[][Columns]` for 2-d function declaration +2. `#pragma gcc optimize("Ofast, inline")` to increase speed 3. use parens to close bitwise operations and % 4. remember the scope in loops (int i) (int j) -5. ```matrix[i][j]``` in scanning a 2d array. -6. figure out ```matrix[i][j]``` and ```matrix[i][n-1]``` +5. `matrix[i][j]` in scanning a 2d array. +6. figure out `matrix[i][j]` and `matrix[i][n-1]` -More can be found in [[OJ-index]] \ No newline at end of file +More can be found in [[OJ-index]] diff --git a/Wiki/Software Index.md b/Wiki/Software Index.md index 31d5502..e96219b 100644 --- a/Wiki/Software Index.md +++ b/Wiki/Software Index.md @@ -3,157 +3,174 @@ ### System-wide #### Development -* libXres - * to use gamescope + +- libXres + - to use gamescope #### Games -* SuperTuxKart + +- SuperTuxKart #### Command Line Productivity -* ripgrep - * quickly search thru dirs -* z - * replacement of fasd -* nnn - * file manager -* entr - * watch for file change + +- ripgrep + - quickly search thru dirs +- z + - replacement of fasd +- nnn + - file manager +- entr + - watch for file change #### Mail -* Thunderbird + +- Thunderbird #### Video and audio -* xdg-desktop-portal - * for use with screencasting -* rtkit - * for better dbus support -* ofono - * for better bluetooth conection -* obs - * for test streaming -* wlrobs - * wayland plugin + +- xdg-desktop-portal + - for use with screencasting +- rtkit + - for better dbus support +- ofono + - for better bluetooth conection +- obs + - for test streaming +- wlrobs + - wayland plugin #### System -* android-tools - * to use adb fastboot ... etc -* ncurses-compta - * to make lineageOS -* v4l2loopback - * to loopback webcam into a device -* wine - * Fuck tencent, i hate chinese proprietary shitware. -* winetricks - * I hate wine and tencent. -* wf-recorder - * record screen -* tree - * to show things in a tree -* pexpect - * developing python program + +- android-tools + - to use adb fastboot ... etc +- ncurses-compta + - to make lineageOS +- v4l2loopback + - to loopback webcam into a device +- wine + - Fuck tencent, i hate chinese proprietary shitware. +- winetricks + - I hate wine and tencent. +- wf-recorder + - record screen +- tree + - to show things in a tree +- pexpect + - developing python program #### Softwares -* imv - * for image viewing -* fzf - * fuzzy searcher ytfzf -* wf-recorder - * to record things + +- imv + - for image viewing +- fzf + - fuzzy searcher ytfzf +- wf-recorder + - to record things #### Coding -* gdb - * for debugging in neovim -* ltrace - * for reverse engineering -* repo - * to sync android tree -* luaformatter - * to format lua code -* prettier - * to format web code + +- gdb + - for debugging in neovim +- ltrace + - for reverse engineering +- repo + - to sync android tree +- luaformatter + - to format lua code +- prettier + - to format web code #### Text Editing -* pandoc - * for word processing -* texlive - * for word processing -* latexmk - * for vim latex support -* ctags - * for vieving tags in vim -* libreoffice - * for vieving and editing doc files -* wl-clipboard - * to use copy and paste in cli -* fcitx5 - * to use chinnnese input. - * fcitx5-gtk - * fcitx5-rime + +- pandoc + - for word processing +- texlive + - for word processing +- latexmk + - for vim latex support +- ctags + - for vieving tags in vim +- libreoffice + - for vieving and editing doc files +- wl-clipboard + - to use copy and paste in cli +- fcitx5 + - to use chinnnese input. + - fcitx5-gtk + - fcitx5-rime #### Info -* powertop - * for battery stat -* radeontop - * to see gpu usage -* bat - * for better cat -* eix - * for emerge managament -* mediainfo - * for viewing media info. -* ncdu - * to view disk usage -* iotop - * to see disk io + +- powertop + - for battery stat +- radeontop + - to see gpu usage +- bat + - for better cat +- eix + - for emerge managament +- mediainfo + - for viewing media info. +- ncdu + - to view disk usage +- iotop + - to see disk io #### Cosmetic -* dejavu - * for better font -* Symbols-2048-em Nerd Font Complete.ttf (locally) - * for nerd icon -* geteltorito - * for flashing bios image + +- dejavu + - for better font +- Symbols-2048-em Nerd Font Complete.ttf (locally) + - for nerd icon +- geteltorito + - for flashing bios image #### Pentesting -* cracklib-words - * wordlist -* lynis - * to analyze vuls -* nmap - * to scan ports -* aide - * to check file integrity -* arp-scan - * to scan local network. -* openVPN - * to access THM machines. -* whois - * to query domain status + +- cracklib-words + - wordlist +- lynis + - to analyze vuls +- nmap + - to scan ports +- aide + - to check file integrity +- arp-scan + - to scan local network. +- openVPN + - to access THM machines. +- whois + - to query domain status ### Local -* cxxmatrix - * cool matrix effects. -* gamescope - * RSR for steam games + +- cxxmatrix + - cool matrix effects. +- gamescope + - RSR for steam games ### Pip (I hate this) -* pip-autoremove - * to remove pip software -* subilminal - * to download subs using mpv scripts -* pipx - * to properly manage apps -* gdbgui - * gui frontend of gdb -### npm -* neovim - * for npm support +- pip-autoremove + - to remove pip software +- subilminal + - to download subs using mpv scripts +- pipx + - to properly manage apps +- gdbgui + - gui frontend of gdb + +### npm + +- neovim + - for npm support ### go -* go buster - * for brute-force URLs + +- go buster + - for brute-force URLs ### Cargo -* zeta-note - * lsp for markdowm + +- zeta-note + - lsp for markdowm diff --git a/Wiki/Wiki-Index.md b/Wiki/Wiki-Index.md index e9ee429..96765ac 100644 --- a/Wiki/Wiki-Index.md +++ b/Wiki/Wiki-Index.md @@ -17,6 +17,7 @@ ## Projects ### [Notes for CS](Notes%20for%20CS) + ### [Chroot manager](ChrootMan.md) ## Others diff --git a/_templates/OJ Problem Notes.md b/_templates/OJ Problem Notes.md index ce4962d..81bb118 100644 --- a/_templates/OJ Problem Notes.md +++ b/_templates/OJ Problem Notes.md @@ -3,19 +3,31 @@ {{date}} {{time}} > ##### Algorithms: -> #algorithm +> +> #algorithm +> > ##### Data structures: +> > #DS +> > ##### Difficulty: +> > #coding_problem #difficulty- +> > ##### Additional tags: +> > # # +> > ##### Revisions: +> > N/A ##### Links: + - [Link to problem]() -___ + +--- + ### Problem #### Examples diff --git a/_templates/cpp_stuff_explainer.md b/_templates/cpp_stuff_explainer.md index 9f99360..4ac130b 100644 --- a/_templates/cpp_stuff_explainer.md +++ b/_templates/cpp_stuff_explainer.md @@ -3,23 +3,30 @@ {{date}} {{time}} > ##### Algorithms: -> #algorithm +> +> #algorithm +> > ##### Data structures: +> > #DS +> > ##### Difficulty: +> > #CS_analysis #difficulty- +> > ##### Additional tags: -> ##### Related problems: + ```expander -tag:#coding_problem tag:# -tag:#template_remove_me +tag:#coding_problem tag:# -tag:#template_remove_me ``` - ##### Links: + - [cppreference]() -___ + +--- ### What is {{title}}? @@ -28,4 +35,5 @@ ___ #### Example code ### Why and when to use it? -#template_remove_me \ No newline at end of file + +#template_remove_me