directory: LeetCode-Solutions
Python: 
Notes: 
Readme: # LeetCode-Solutions
Collection of LeetCode questions to ace the coding interview

directory: 181-employees-earning-more-than-their-managers
Python: 
Notes: select
a.Name as 'Employee'
FROM
Employee AS a,
Employee AS b
WHERE
a.ManagerId = b.Id
AND a.Salary > b.Salary;
Readme: <h2><a href="https://leetcode.com/problems/employees-earning-more-than-their-managers/">181. Employees Earning More Than Their Managers</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Employee</code></p>

<pre>+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
| salary      | int     |
| managerId   | int     |
id is the primary key column for this table.
Each row of this table indicates the ID of an employee, their name, salary, and the ID of their manager.
</pre>

<p>&nbsp;</p>

<p>Write an SQL query to find the employees who earn more than their managers.</p>

<p>Return the result table in <strong>any order</strong>.</p>

<p>The query result format is in the following example.</p>

<p><strong>Example 1:</strong></p>

<pre><strong>Input:</strong> 
Employee table:
+----+-------+--------+-----------+
| id | name  | salary | managerId |
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | Null      |
| 4  | Max   | 90000  | Null      |
<strong>Output:</strong> 
+----------+
| Employee |
| Joe      |
<strong>Explanation:</strong> Joe is the only employee who earns more than his manager.
</pre>
</div>

directory: 953-verifying-an-alien-dictionary
Python: class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        
        dictionary = { c : i for i, c in enumerate(order)}
        for i in range(len(words)-1):
            for j in range(len(words[i])):
                if j >= len(words[i+1]): return False
                if words[i][j] != words[i+1][j]:
                    if dictionary[words[i][j]] > dictionary[words[i+1][j]]: return False
                    break
        return True
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/verifying-an-alien-dictionary/">953. Verifying an Alien Dictionary</a></h2><h3>Easy</h3><hr><div><p>In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different <code>order</code>. The <code>order</code> of the alphabet is some permutation of lowercase letters.</p>

class Solution:
        
                    break
        
<p>Given a sequence of <code>words</code> written in the alien language, and the <code>order</code> of the alphabet, return <code>true</code> if and only if the given <code>words</code> are sorted lexicographically in this alien language.</p>

<pre><strong>Input:</strong> words = ["hello","leetcode"], order = "hlabcdefgijkmnopqrstuvwxyz"
<strong>Output:</strong> true
<strong>Explanation: </strong>As 'h' comes before 'l' in this language, then the sequence is sorted.
</pre>

<p><strong>Example 2:</strong></p>

<pre><strong>Input:</strong> words = ["word","world","row"], order = "worldabcefghijkmnpqstuvxyz"
<strong>Output:</strong> false
<strong>Explanation: </strong>As 'd' comes after 'l' in this language, then words[0] &gt; words[1], hence the sequence is unsorted.
</pre>

<p><strong>Example 3:</strong></p>

<pre><strong>Input:</strong> words = ["apple","app"], order = "abcdefghijklmnopqrstuvwxyz"
<strong>Explanation: </strong>The first three characters "app" match, and the second string is shorter (in size.) According to lexicographical rules "apple" &gt; "app", because 'l' &gt; '∅', where '∅' is defined as the blank character which is less than any other character (<a href="https://en.wikipedia.org/wiki/Lexicographical_order" target="_blank">More info</a>).
</pre>

<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= words.length &lt;= 100</code></li>
	<li><code>1 &lt;= words[i].length &lt;= 20</code></li>
	<li><code>order.length == 26</code></li>
	<li>All characters in <code>words[i]</code> and <code>order</code> are English lowercase letters.</li>
</ul>
</div>

directory: 1526-minimum-number-of-increments-on-subarrays-to-form-a-target-array
Python: class Solution(object):
    def minNumberOperations(self, target):
        """
        :type target: List[int]
        :rtype: int
        """
        changes = target[0]
        for i in range(1, len(target)):
            changes += max(0, target[i]-target[i-1])
        return changes
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-number-of-increments-on-subarrays-to-form-a-target-array/">1526. Minimum Number of Increments on Subarrays to Form a Target Array</a></h2><h3>Hard</h3><hr><div><p>You are given an integer array <code>target</code>. You have an integer array <code>initial</code> of the same size as <code>target</code> with all elements initially zeros.</p>

<p>In one operation you can choose <strong>any</strong> subarray from <code>initial</code> and increment each value by one.</p>

class Solution(object):
        """
        """

<p>Return <em>the minimum number of operations to form a </em><code>target</code><em> array from </em><code>initial</code>.</p>

<p>The test cases are generated so that the answer fits in a 32-bit integer.</p>

<pre><strong>Input:</strong> target = [1,2,3,2,1]
<strong>Output:</strong> 3
<strong>Explanation:</strong> We need at least 3 operations to form the target array from the initial array.
[<strong><u>0,0,0,0,0</u></strong>] increment 1 from index 0 to 4 (inclusive).
[1,<strong><u>1,1,1</u></strong>,1] increment 1 from index 1 to 3 (inclusive).
[1,2,<strong><u>2</u></strong>,2,1] increment 1 at index 2.
[1,2,3,2,1] target array is formed.
</pre>

<pre><strong>Input:</strong> target = [3,1,1,2]
<strong>Output:</strong> 4
<strong>Explanation:</strong> [<strong><u>0,0,0,0</u></strong>] -&gt; [1,1,1,<strong><u>1</u></strong>] -&gt; [<strong><u>1</u></strong>,1,1,2] -&gt; [<strong><u>2</u></strong>,1,1,2] -&gt; [3,1,1,2]
</pre>

<pre><strong>Input:</strong> target = [3,1,5,4,2]
<strong>Output:</strong> 7
<strong>Explanation:</strong> [<strong><u>0,0,0,0,0</u></strong>] -&gt; [<strong><u>1</u></strong>,1,1,1,1] -&gt; [<strong><u>2</u></strong>,1,1,1,1] -&gt; [3,1,<strong><u>1,1,1</u></strong>] -&gt; [3,1,<strong><u>2,2</u></strong>,2] -&gt; [3,1,<strong><u>3,3</u></strong>,2] -&gt; [3,1,<strong><u>4</u></strong>,4,2] -&gt; [3,1,5,4,2].
</pre>

<ul>
	<li><code>1 &lt;= target.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= target[i] &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 0012-integer-to-roman
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/integer-to-roman/">12. Integer to Roman</a></h2><h3>Medium</h3><hr><div><p>Roman numerals are represented by seven different symbols:&nbsp;<code>I</code>, <code>V</code>, <code>X</code>, <code>L</code>, <code>C</code>, <code>D</code> and <code>M</code>.</p>

<pre><strong>Symbol</strong>       <strong>Value</strong>
I             1
V             5
X             10
L             50
C             100
D             500
M             1000</pre>

<p>For example,&nbsp;<code>2</code> is written as <code>II</code>&nbsp;in Roman numeral, just two one's added together. <code>12</code> is written as&nbsp;<code>XII</code>, which is simply <code>X + II</code>. The number <code>27</code> is written as <code>XXVII</code>, which is <code>XX + V + II</code>.</p>

<p>Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not <code>IIII</code>. Instead, the number four is written as <code>IV</code>. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as <code>IX</code>. There are six instances where subtraction is used:</p>

<ul>
	<li><code>I</code> can be placed before <code>V</code> (5) and <code>X</code> (10) to make 4 and 9.&nbsp;</li>
	<li><code>X</code> can be placed before <code>L</code> (50) and <code>C</code> (100) to make 40 and 90.&nbsp;</li>
	<li><code>C</code> can be placed before <code>D</code> (500) and <code>M</code> (1000) to make 400 and 900.</li>
</ul>

<p>Given an integer, convert it to a roman numeral.</p>

<p><strong class="example">Example 1:</strong></p>

<pre><strong>Input:</strong> num = 3
<strong>Output:</strong> "III"
<strong>Explanation:</strong> 3 is represented as 3 ones.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre><strong>Input:</strong> num = 58
<strong>Output:</strong> "LVIII"
<strong>Explanation:</strong> L = 50, V = 5, III = 3.
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre><strong>Input:</strong> num = 1994
<strong>Output:</strong> "MCMXCIV"
<strong>Explanation:</strong> M = 1000, CM = 900, XC = 90 and IV = 4.
</pre>

<ul>
	<li><code>1 &lt;= num &lt;= 3999</code></li>
</ul>
</div>

directory: 1584-min-cost-to-connect-all-points
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        
        n = len(points)
        
        # Min-heap to store minimum weight edge at top.
        heap = [(0, 0)]
        #Track Nodes which are included in MST
        in_mst = [False] * n
        mst_cost = 0
        edges_used = 0
        while edges_used < n:
            weight, curr_node = heapq.heappop(heap)
            if in_mst[curr_node]:
                continue
            in_mst[curr_node] = True
            mst_cost += weight
            edges_used += 1
            
            for next_node in range(n):
                
                if not in_mst[next_node]:
                    next_weight = abs(points[curr_node][0] - points[next_node][0]) + \
                                  abs(points[curr_node][1] - points[next_node][1])
                    
                    heapq.heappush(heap, (next_weight, next_node))
            
        return mst_cost
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/min-cost-to-connect-all-points/">1584. Min Cost to Connect All Points</a></h2><h3>Medium</h3><hr><div><p>You are given an array <code>points</code> representing integer coordinates of some points on a 2D-plane, where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code>.</p>

                continue
            
<p>The cost of connecting two points <code>[x<sub>i</sub>, y<sub>i</sub>]</code> and <code>[x<sub>j</sub>, y<sub>j</sub>]</code> is the <strong>manhattan distance</strong> between them: <code>|x<sub>i</sub> - x<sub>j</sub>| + |y<sub>i</sub> - y<sub>j</sub>|</code>, where <code>|val|</code> denotes the absolute value of <code>val</code>.</p>

<p>Return <em>the minimum cost to make all points connected.</em> All points are connected if there is <strong>exactly one</strong> simple path between any two points.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/08/26/d.png" style="width: 214px; height: 268px;">
<pre><strong>Input:</strong> points = [[0,0],[2,2],[3,10],[5,2],[7,0]]
<strong>Output:</strong> 20
<strong>Explanation:</strong> 
<img alt="" src="https://assets.leetcode.com/uploads/2020/08/26/c.png" style="width: 214px; height: 268px;">
We can connect the points as shown above to get the minimum cost of 20.
Notice that there is a unique path between every pair of points.
</pre>

<pre><strong>Input:</strong> points = [[3,12],[-2,5],[-4,1]]
<strong>Output:</strong> 18
</pre>

<ul>
	<li><code>1 &lt;= points.length &lt;= 1000</code></li>
	<li><code>-10<sup>6</sup> &lt;= x<sub>i</sub>, y<sub>i</sub> &lt;= 10<sup>6</sup></code></li>
	<li>All pairs <code>(x<sub>i</sub>, y<sub>i</sub>)</code> are distinct.</li>
</ul>
</div>

directory: 1647-minimum-deletions-to-make-character-frequencies-unique
    def minDeletions(self, s: str) -> int:
        
        freqs = sorted(Counter(s).values(), reverse = True)
        ans = 0
        next_unused = len(s)
        for freq in freqs:
            next_unused = min(freq, next_unused)
            ans += freq - next_unused
            if next_unused > 0:
                next_unused -= 1
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-deletions-to-make-character-frequencies-unique/">1647. Minimum Deletions to Make Character Frequencies Unique</a></h2><h3>Medium</h3><hr><div><p>A string <code>s</code> is called <strong>good</strong> if there are no two different characters in <code>s</code> that have the same <strong>frequency</strong>.</p>

        ans = 0
        return ans
        
<p>Given a string <code>s</code>, return<em> the <strong>minimum</strong> number of characters you need to delete to make </em><code>s</code><em> <strong>good</strong>.</em></p>

<p>The <strong>frequency</strong> of a character in a string is the number of times it appears in the string. For example, in the string <code>"aab"</code>, the <strong>frequency</strong> of <code>'a'</code> is <code>2</code>, while the <strong>frequency</strong> of <code>'b'</code> is <code>1</code>.</p>

<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> 0
<strong>Explanation:</strong> <code>s</code> is already good.
</pre>

<pre><strong>Input:</strong> s = "aaabbbcc"
<strong>Output:</strong> 2
<strong>Explanation:</strong> You can delete two 'b's resulting in the good string "aaabcc".
Another way it to delete one 'b' and one 'c' resulting in the good string "aaabbc".</pre>

<pre><strong>Input:</strong> s = "ceabaacb"
<strong>Explanation:</strong> You can delete both 'c's resulting in the good string "eabaab".
Note that we only care about characters that are still in the string at the end (i.e. frequency of 0 is ignored).
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>5</sup></code></li>
	<li><code>s</code>&nbsp;contains only lowercase English letters.</li>
</ul>
</div>

directory: 1905-count-sub-islands
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/count-sub-islands/">1905. Count Sub Islands</a></h2><h3>Medium</h3><hr><div><p>You are given two <code>m x n</code> binary matrices <code>grid1</code> and <code>grid2</code> containing only <code>0</code>'s (representing water) and <code>1</code>'s (representing land). An <strong>island</strong> is a group of <code>1</code>'s connected <strong>4-directionally</strong> (horizontal or vertical). Any cells outside of the grid are considered water cells.</p>

<p>An island in <code>grid2</code> is considered a <strong>sub-island </strong>if there is an island in <code>grid1</code> that contains <strong>all</strong> the cells that make up <strong>this</strong> island in <code>grid2</code>.</p>

<p>Return the <em><strong>number</strong> of islands in </em><code>grid2</code> <em>that are considered <strong>sub-islands</strong></em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/06/10/test1.png" style="width: 493px; height: 205px;">
<pre><strong>Input:</strong> grid1 = [[1,1,1,0,0],[0,1,1,1,1],[0,0,0,0,0],[1,0,0,0,0],[1,1,0,1,1]], grid2 = [[1,1,1,0,0],[0,0,1,1,1],[0,1,0,0,0],[1,0,1,1,0],[0,1,0,1,0]]
<strong>Explanation: </strong>In the picture above, the grid on the left is grid1 and the grid on the right is grid2.
The 1s colored red in grid2 are those considered to be part of a sub-island. There are three sub-islands.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/06/03/testcasex2.png" style="width: 491px; height: 201px;">
<pre><strong>Input:</strong> grid1 = [[1,0,1,0,1],[1,1,1,1,1],[0,0,0,0,0],[1,1,1,1,1],[1,0,1,0,1]], grid2 = [[0,0,0,0,0],[1,1,1,1,1],[0,1,0,1,0],[0,1,0,1,0],[1,0,0,0,1]]
<strong>Output:</strong> 2 
The 1s colored red in grid2 are those considered to be part of a sub-island. There are two sub-islands.
</pre>

<ul>
	<li><code>m == grid1.length == grid2.length</code></li>
	<li><code>n == grid1[i].length == grid2[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 500</code></li>
	<li><code>grid1[i][j]</code> and <code>grid2[i][j]</code> are either <code>0</code> or <code>1</code>.</li>
</ul>
</div>

directory: 253-meeting-rooms-ii
    def minMeetingRooms(self, intervals: List[List[int]]) -> int:
        
        intervals.sort()
        merged = [intervals[0][1]]
        for interval in intervals[1:]:
            start = interval[0]
            end = interval[1]
            earliest = min(merged)
            
            if start < earliest:
                merged.append(end)
            else:
                index = merged.index(earliest)
                merged[index] = end
        return len(merged)
Notes: ​
Readme:

            else:
    
directory: 230-kth-smallest-element-in-a-bst
Python: # Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
    def kthSmallest(self, root: Optional[TreeNode], k: int) -> int:
        stack = []
        
        while stack or root:
            while root:
                stack.append(root)
                root = root.left
            k -= 1
            root = stack[-1]
            if(k==0):
                return root.val
            else:
                stack.pop()
                root = root.right
        return 0
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/kth-smallest-element-in-a-bst/">230. Kth Smallest Element in a BST</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary search tree, and an integer <code>k</code>, return <em>the</em> <code>k<sup>th</sup></code> <em>smallest value (<strong>1-indexed</strong>) of all the values of the nodes in the tree</em>.</p>

# Definition for a binary tree node.
        stack = []
        
            k -= 1
            if(k==0):
            else:
        return 0
        
<img alt="" src="https://assets.leetcode.com/uploads/2021/01/28/kthtree1.jpg" style="width: 212px; height: 301px;">
<pre><strong>Input:</strong> root = [3,1,4,null,2], k = 1
<strong>Output:</strong> 1
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/28/kthtree2.jpg" style="width: 382px; height: 302px;">
<pre><strong>Input:</strong> root = [5,3,6,2,4,null,null,1], k = 3
</pre>

<ul>
	<li>The number of nodes in the tree is <code>n</code>.</li>
	<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>
</ul>

<p><strong>Follow up:</strong> If the BST is modified often (i.e., we can do insert and delete operations) and you need to find the kth smallest frequently, how would you optimize?</p>
</div>

directory: 0487-max-consecutive-ones-ii
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        
        """
        Brute Force
        longest_sequence = 0
        for left in range(len(nums)):
            num_zeros = 0
            for right in range(left, len(nums)):
                if num_zeros == 2:
                    break
                if nums[right] == 0:
                    num_zeros += 1
                if num_zeros <= 1:
                    longest_sequence = max(longest_sequence, right - left + 1)
        return longest_sequence
        """
        
        maximum = 0
        left, right = 0, 0
        k = 0
        n = len(nums)
        for right in range(n):
            if nums[right] == 0:
                k += 1
                while k == 2:
                    if nums[left] == 0:
                        k -= 1
                    left += 1
            
            maximum = max(maximum, right - left + 1)
        return maximum
Notes: longest_sequence = 0
for left in range(len(nums)):
num_zeros = 0
for right in range(left, len(nums)):
if num_zeros == 2:
break
if nums[right] == 0:
num_zeros += 1
if num_zeros <= 1:
longest_sequence = max(longest_sequence, right - left + 1)
return longest_sequence
Readme: <h2><a href="https://leetcode.com/problems/max-consecutive-ones-ii/">487. Max Consecutive Ones II</a></h2><h3>Medium</h3><hr><div><p>Given a binary array <code>nums</code>, return <em>the maximum number of consecutive </em><code>1</code><em>'s in the array if you can flip at most one</em> <code>0</code>.</p>

        """
                    break
        """
        
        maximum = 0
        k = 0
                k += 1
                        k -= 1
                    left += 1
            
<pre><strong>Input:</strong> nums = [1,0,1,1,0]
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
</pre>

<pre><strong>Input:</strong> nums = [1,0,1,1,0,1]
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>nums[i]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>

<p><strong>Follow up:</strong> What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?</p>
</div>

directory: 17-letter-combinations-of-a-phone-number
    def letterCombinations(self, digits: str) -> List[str]:
        if digits == "":
            return []
        dic = {
            '2' : 'abc',
            '3' : 'def',
            '4' : 'ghi',
            '5' : 'jkl',
            '6' : 'mno',
            '7' : 'pqrs',
            '8' : 'tuv',
            '9' : 'wxyz',
        }
        n = len(digits)
        output = []
        
        def backtrack(index, temp):
            if index >= n:
                output.append("".join(temp))
                return
            else:
                for char in dic[digits[index]]:
                    temp.append(char)
                    backtrack(index + 1, temp)
                    temp.pop()
        
        backtrack(0, [])
        return output
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/letter-combinations-of-a-phone-number/">17. Letter Combinations of a Phone Number</a></h2><h3>Medium</h3><hr><div><p>Given a string containing digits from <code>2-9</code> inclusive, return all possible letter combinations that the number could represent. Return the answer in <strong>any order</strong>.</p>

            return []
        dic = {
        }
        output = []
        
                return
            else:
        
<p>A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.</p>

<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/73/Telephone-keypad2.svg/200px-Telephone-keypad2.svg.png" style="width: 200px; height: 162px;"></p>

<pre><strong>Input:</strong> digits = "23"
<strong>Output:</strong> ["ad","ae","af","bd","be","bf","cd","ce","cf"]
</pre>

<pre><strong>Input:</strong> digits = ""
<strong>Output:</strong> []
</pre>

<pre><strong>Input:</strong> digits = "2"
<strong>Output:</strong> ["a","b","c"]
</pre>

<ul>
	<li><code>0 &lt;= digits.length &lt;= 4</code></li>
	<li><code>digits[i]</code> is a digit in the range <code>['2', '9']</code>.</li>
</ul>
</div>

directory: 47-permutations-ii
    def permuteUnique(self, nums):
        res, visited = [], [False]*len(nums)
        nums.sort()
        def dfs(nums, visited, path):
            if len(nums) == len(path):
                res.append(path)
                return 
            for i in range(len(nums)):
                if not visited[i]: 
                    if i>0 and not visited[i-1] and nums[i] == nums[i-1]: 
                        continue
                    visited[i] = True
                    dfs(nums, visited, path+[nums[i]])
                    visited[i] = False
        dfs(nums, visited, [])
        return res
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/permutations-ii/">47. Permutations II</a></h2><h3>Medium</h3><hr><div><p>Given a collection of numbers, <code>nums</code>,&nbsp;that might contain duplicates, return <em>all possible unique permutations <strong>in any order</strong>.</em></p>

                return 
                        continue
        return res
    
<pre><strong>Input:</strong> nums = [1,1,2]
<strong>Output:</strong>
[[1,1,2],
 [1,2,1],
 [2,1,1]]
</pre>

<pre><strong>Input:</strong> nums = [1,2,3]
<strong>Output:</strong> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 8</code></li>
	<li><code>-10 &lt;= nums[i] &lt;= 10</code></li>
</ul>
</div>

directory: 23-merge-k-sorted-lists
Python: # Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.next = next
import heapq
    def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]:
        
        h = []
        for i, l in enumerate(lists):
            if l:
                h.append((l.val, i))        
        heapq.heapify(h)
        head = curr = ListNode(None)
        while h:
            val, idx = heapq.heappop(h)
            curr.next = ListNode(val)
            curr = curr.next
            node = lists[idx] = lists[idx].next
            if node:
                heapq.heappush(h, (node.val, idx))
        return head.next
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/merge-k-sorted-lists/">23. Merge k Sorted Lists</a></h2><h3>Hard</h3><hr><div><p>You are given an array of <code>k</code> linked-lists <code>lists</code>, each linked-list is sorted in ascending order.</p>

# Definition for singly-linked list.
        
        h = []
            if l:
        while h:
            if node:
            
<p><em>Merge all the linked-lists into one sorted linked-list and return it.</em></p>

<pre><strong>Input:</strong> lists = [[1,4,5],[1,3,4],[2,6]]
<strong>Output:</strong> [1,1,2,3,4,4,5,6]
<strong>Explanation:</strong> The linked-lists are:
[
  1-&gt;4-&gt;5,
  1-&gt;3-&gt;4,
  2-&gt;6
]
merging them into one sorted list:
1-&gt;1-&gt;2-&gt;3-&gt;4-&gt;4-&gt;5-&gt;6
</pre>

<pre><strong>Input:</strong> lists = []
</pre>

<pre><strong>Input:</strong> lists = [[]]
</pre>

<ul>
	<li><code>k == lists.length</code></li>
	<li><code>0 &lt;= k &lt;= 10^4</code></li>
	<li><code>0 &lt;= lists[i].length &lt;= 500</code></li>
	<li><code>-10^4 &lt;= lists[i][j] &lt;= 10^4</code></li>
	<li><code>lists[i]</code> is sorted in <strong>ascending order</strong>.</li>
	<li>The sum of <code>lists[i].length</code> won't exceed <code>10^4</code>.</li>
</ul>
</div>

directory: 1236-web-crawler
Python: # """
# This is HtmlParser's API interface.
# You should not implement it, or speculate about its implementation
# """
#class HtmlParser(object):
#    def getUrls(self, url):
#        """
#        :type url: str
#        :rtype List[str]
#        """

# """
# """
#        """
#        """

    def crawl(self, startUrl: str, htmlParser: 'HtmlParser') -> List[str]:
        
        def getHostName(url):        
            hostname = url.split('http://')[1]
            hostname = hostname.split('.')[1]
            return hostname
        
        seen = set()
        seen.add(startUrl)
        def dfs(curr_url):
            for url in htmlParser.getUrls(curr_url):
                if url not in seen and getHostName(url) == getHostName(curr_url):
                    seen.add(url)
                    dfs(url)
        dfs(startUrl)
        return seen

                    dfs(url)
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/web-crawler/">1236. Web Crawler</a></h2><h3>Medium</h3><hr><div><p>Given a url <code>startUrl</code> and an interface <code>HtmlParser</code>, implement a web&nbsp;crawler to crawl all links that are under the&nbsp;<strong>same hostname</strong> as&nbsp;<code>startUrl</code>.&nbsp;</p>

<p>Return&nbsp;all urls obtained by your web crawler in <strong>any</strong> order.</p>

<p>Your crawler should:</p>

<ul>
	<li>Start from the page: <code>startUrl</code></li>
	<li>Call <code>HtmlParser.getUrls(url)</code> to get all urls from a webpage of given url.</li>
	<li>Do not crawl the same link twice.</li>
	<li>Explore only the links that are under the <strong>same hostname</strong> as <code>startUrl</code>.</li>
</ul>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/08/13/urlhostname.png" style="width: 600px; height: 164px;"></p>

<p>As shown in the example url above, the hostname is <code>example.org</code>. For simplicity sake, you may assume all&nbsp;urls use <strong>http protocol</strong> without any&nbsp;<strong>port</strong> specified. For example, the urls&nbsp;<code>http://leetcode.com/problems</code> and&nbsp;<code>http://leetcode.com/contest</code> are under the same hostname, while urls <code>http://example.org/test</code> and <code>http://example.com/abc</code> are not under the same hostname.</p>

<p>The <code>HtmlParser</code> interface is defined as such:&nbsp;</p>

<pre>interface HtmlParser {
  // Return a list of all urls from a webpage of given <em>url</em>.
  public List&lt;String&gt; getUrls(String url);
}</pre>

<p>Below&nbsp;are two examples explaining the functionality of the problem, for custom testing purposes you'll have three&nbsp;variables&nbsp;<code data-stringify-type="code">urls</code>,&nbsp;<code data-stringify-type="code">edges</code>&nbsp;and&nbsp;<code data-stringify-type="code">startUrl</code>. Notice that you will only have access to&nbsp;<code data-stringify-type="code">startUrl</code>&nbsp;in your code, while&nbsp;<code data-stringify-type="code">urls</code>&nbsp;and&nbsp;<code data-stringify-type="code">edges</code>&nbsp;are not directly accessible to you in code.</p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/10/23/sample_2_1497.png" style="width: 610px; height: 300px;"></p>

<pre><strong>Input:
</strong>urls = [
&nbsp; "http://news.yahoo.com",
&nbsp; "http://news.yahoo.com/news",
&nbsp; "http://news.yahoo.com/news/topics/",
&nbsp; "http://news.google.com",
&nbsp; "http://news.yahoo.com/us"
]
edges = [[2,0],[2,1],[3,2],[3,1],[0,4]]
startUrl = "http://news.yahoo.com/news/topics/"
<strong>Output:</strong> [
]
</pre>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2019/10/23/sample_3_1497.png" style="width: 540px; height: 270px;"></strong></p>

urls = [
&nbsp; "http://news.google.com"
]
edges = [[0,2],[2,1],[3,2],[3,1],[3,0]]
startUrl = "http://news.google.com"
<strong>Output:</strong> ["http://news.google.com"]
<strong>Explanation: </strong>The startUrl links to all other pages that do not share the same hostname.</pre>

<ul>
	<li><code>1 &lt;= urls.length &lt;= 1000</code></li>
	<li><code>1 &lt;= urls[i].length &lt;= 300</code></li>
	<li><code>startUrl</code>&nbsp;is one of the <code>urls</code>.</li>
	<li>Hostname label must be from 1 to 63 characters long, including the dots, may contain only the ASCII letters from 'a' to&nbsp;'z', digits&nbsp; from '0' to '9' and the&nbsp;hyphen-minus&nbsp;character ('-').</li>
	<li>The hostname may not start or end with&nbsp;the hyphen-minus character ('-').&nbsp;</li>
	<li>See:&nbsp;&nbsp;<a href="https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames">https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_hostnames</a></li>
	<li>You may assume there're&nbsp;no duplicates in url library.</li>
</ul>
</div>

directory: 278-first-bad-version
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/first-bad-version/">278. First Bad Version</a></h2><h3>Easy</h3><hr><div><p>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.</p>

<p>Suppose you have <code>n</code> versions <code>[1, 2, ..., n]</code> and you want to find out the first bad one, which causes all the following ones to be bad.</p>

<p>You are given an API <code>bool isBadVersion(version)</code> which returns whether <code>version</code> is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API.</p>

<pre><strong>Input:</strong> n = 5, bad = 4
<strong>Explanation:</strong>
call isBadVersion(3) -&gt; false
call isBadVersion(5)&nbsp;-&gt; true
call isBadVersion(4)&nbsp;-&gt; true
Then 4 is the first bad version.
</pre>

<pre><strong>Input:</strong> n = 1, bad = 1
</pre>

<ul>
	<li><code>1 &lt;= bad &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 0094-binary-tree-inorder-traversal
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        
        stack = [root]
        ans = []
            if stack:
                root = stack.pop()
                if root:
                    ans.append(root.val)
                    root = root.right
                    stack.append(root)
                    
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-tree-inorder-traversal/">94. Binary Tree Inorder Traversal</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the inorder traversal of its nodes' values</em>.</p>

        ans = []
            if stack:
                if root:
                    
        return ans

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg" style="width: 125px; height: 200px;">
<pre><strong>Input:</strong> root = [1,null,2,3]
<strong>Output:</strong> [1,3,2]
</pre>

<pre><strong>Input:</strong> root = []
</pre>

<pre><strong>Input:</strong> root = [1]
<strong>Output:</strong> [1]
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[0, 100]</code>.</li>
	<li><code>-100 &lt;= Node.val &lt;= 100</code></li>
</ul>

<strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</div>

directory: 221-maximal-square
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/maximal-square/">221. Maximal Square</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> binary <code>matrix</code> filled with <code>0</code>'s and <code>1</code>'s, <em>find the largest square containing only</em> <code>1</code>'s <em>and return its area</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max1grid.jpg" style="width: 400px; height: 319px;">
<pre><strong>Input:</strong> matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/max2grid.jpg" style="width: 165px; height: 165px;">
<pre><strong>Input:</strong> matrix = [["0","1"],["1","0"]]
</pre>

<pre><strong>Input:</strong> matrix = [["0"]]
</pre>

<ul>
	<li><code>m == matrix.length</code></li>
	<li><code>n == matrix[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 300</code></li>
	<li><code>matrix[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
</div>

directory: 191-number-of-1-bits
    def hammingWeight(self, n: int) -> int:
        
        ans = 0
        while n:
            ans += n & 1
            n = n >> 1
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-1-bits/">191. Number of 1 Bits</a></h2><h3>Easy</h3><hr><div><p>Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the <a href="http://en.wikipedia.org/wiki/Hamming_weight" target="_blank">Hamming weight</a>).</p>

<p><strong>Note:</strong></p>

        ans = 0
        while n:
            ans += n & 1
            n = n >> 1
        return ans

<ul>
	<li>Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.</li>
	<li>In Java, the compiler represents the signed integers using <a href="https://en.wikipedia.org/wiki/Two%27s_complement" target="_blank">2's complement notation</a>. Therefore, in <strong>Example 3</strong>, the input represents the signed integer. <code>-3</code>.</li>
</ul>

<pre><strong>Input:</strong> n = 00000000000000000000000000001011
<strong>Explanation:</strong> The input binary string <strong>00000000000000000000000000001011</strong> has a total of three '1' bits.
</pre>

<pre><strong>Input:</strong> n = 00000000000000000000000010000000
<strong>Explanation:</strong> The input binary string <strong>00000000000000000000000010000000</strong> has a total of one '1' bit.
</pre>

<pre><strong>Input:</strong> n = 11111111111111111111111111111101
<strong>Output:</strong> 31
<strong>Explanation:</strong> The input binary string <strong>11111111111111111111111111111101</strong> has a total of thirty one '1' bits.
</pre>

<ul>
	<li>The input must be a <strong>binary string</strong> of length <code>32</code>.</li>
</ul>

<strong>Follow up:</strong> If this function is called many times, how would you optimize it?</div>

directory: 844-backspace-string-compare
    def backspaceCompare(self, s: str, t: str) -> bool:
        
        def convert(s):
            stack = []
            for c in s:
                if c != '#':
                    stack.append(c)
                else:
                    if stack:
                        stack.pop()
            return ''.join(stack)
        
        return convert(s) == convert(t)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/backspace-string-compare/">844. Backspace String Compare</a></h2><h3>Easy</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> <em>if they are equal when both are typed into empty text editors</em>. <code>'#'</code> means a backspace character.</p>

<p>Note that after backspacing an empty text, the text will continue empty.</p>

            stack = []
            for c in s:
                if c != '#':
                else:
                    if stack:
        
<pre><strong>Input:</strong> s = "ab#c", t = "ad#c"
<strong>Explanation:</strong> Both s and t become "ac".
</pre>

<pre><strong>Input:</strong> s = "ab##", t = "c#d#"
<strong>Explanation:</strong> Both s and t become "".
</pre>

<pre><strong>Input:</strong> s = "a#c", t = "b"
<strong>Explanation:</strong> s becomes "c" while t becomes "b".
</pre>

<ul>
	<li><code><span>1 &lt;= s.length, t.length &lt;= 200</span></code></li>
	<li><span><code>s</code> and <code>t</code> only contain lowercase letters and <code>'#'</code> characters.</span></li>
</ul>

<p><strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time and <code>O(1)</code> space?</p>
</div>

directory: 1641-count-sorted-vowel-strings
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/count-sorted-vowel-strings/">1641. Count Sorted Vowel Strings</a></h2><h3>Medium</h3><hr><div><p>Given an integer <code>n</code>, return <em>the number of strings of length </em><code>n</code><em> that consist only of vowels (</em><code>a</code><em>, </em><code>e</code><em>, </em><code>i</code><em>, </em><code>o</code><em>, </em><code>u</code><em>) and are <strong>lexicographically sorted</strong>.</em></p>

<p>A string <code>s</code> is <strong>lexicographically sorted</strong> if for all valid <code>i</code>, <code>s[i]</code> is the same as or comes before <code>s[i+1]</code> in the alphabet.</p>

<pre><strong>Input:</strong> n = 1
<strong>Output:</strong> 5
<strong>Explanation:</strong> The 5 sorted strings that consist of vowels only are <code>["a","e","i","o","u"].</code>
</pre>

<pre><strong>Input:</strong> n = 2
<strong>Output:</strong> 15
<strong>Explanation:</strong> The 15 sorted strings that consist of vowels only are
["aa","ae","ai","ao","au","ee","ei","eo","eu","ii","io","iu","oo","ou","uu"].
Note that "ea" is not a valid string since 'e' comes after 'a' in the alphabet.
</pre>

<pre><strong>Input:</strong> n = 33
<strong>Output:</strong> 66045
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 50</code>&nbsp;</li>
</ul>
</div>

directory: 0766-toeplitz-matrix
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        
        """
        m X n 
        
        1 - n - >  
        
        """
        
        m, n = len(matrix), len(matrix[0])
        for i in range(m-1):
            for j in range(n-1):
                if matrix[i][j] != matrix[i+1][j+1]:
                    return False
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/toeplitz-matrix/">766. Toeplitz Matrix</a></h2><h3>Easy</h3><hr><div><p>Given an <code>m x n</code> <code>matrix</code>, return&nbsp;<em><code>true</code>&nbsp;if the matrix is Toeplitz. Otherwise, return <code>false</code>.</em></p>

<p>A matrix is <strong>Toeplitz</strong> if every diagonal from top-left to bottom-right has the same elements.</p>

        """
        m X n 
        
        1 - n - >  
        
        """
        
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/04/ex1.jpg" style="width: 322px; height: 242px;">
<pre><strong>Input:</strong> matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
In the above grid, the&nbsp;diagonals are:
"[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]", "[3, 3]", "[4]".
In each diagonal all elements are the same, so the answer is True.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/04/ex2.jpg" style="width: 162px; height: 162px;">
<pre><strong>Input:</strong> matrix = [[1,2],[2,2]]
The diagonal "[1, 2]" has different elements.
</pre>

<ul>
	<li><code>1 &lt;= m, n &lt;= 20</code></li>
	<li><code>0 &lt;= matrix[i][j] &lt;= 99</code></li>
</ul>

<p><strong>Follow up:</strong></p>

<ul>
	<li>What if the <code>matrix</code> is stored on disk, and the memory is limited such that you can only load at most one row of the matrix into the memory at once?</li>
	<li>What if the <code>matrix</code> is so large that you can only load up a partial row into the memory at once?</li>
</ul>
</div>

directory: 1268-search-suggestions-system
    def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
        
        products.sort()
        l, r = 0, len(products) - 1
        res = []
        for i in range(len(searchWord)):
            c = searchWord[i]
            while l <= r and ( len(products[l]) <= i or products[l][i] != c ):
                l += 1
            while l <= r and ( len(products[r]) <= i or products[r][i] != c):
                r -= 1
            res.append([])
            for j in range(min(3, r - l + 1)):
                res[-1].append(products[l + j])
        return res
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/search-suggestions-system/">1268. Search Suggestions System</a></h2><h3>Medium</h3><hr><div><p>You are given an array of strings <code>products</code> and a string <code>searchWord</code>.</p>

        res = []
                l += 1
                r -= 1
        return res

<p>Design a system that suggests at most three product names from <code>products</code> after each character of <code>searchWord</code> is typed. Suggested products should have common prefix with <code>searchWord</code>. If there are more than three products with a common prefix return the three lexicographically minimums products.</p>

<p>Return <em>a list of lists of the suggested products after each character of </em><code>searchWord</code><em> is typed</em>.</p>

<pre><strong>Input:</strong> products = ["mobile","mouse","moneypot","monitor","mousepad"], searchWord = "mouse"
["mobile","moneypot","monitor"],
["mouse","mousepad"],
["mouse","mousepad"]
]
<strong>Explanation:</strong> products sorted lexicographically = ["mobile","moneypot","monitor","mouse","mousepad"]
After typing m and mo all products match and we show user ["mobile","moneypot","monitor"]
After typing mou, mous and mouse the system suggests ["mouse","mousepad"]
</pre>

<pre><strong>Input:</strong> products = ["havana"], searchWord = "havana"
<strong>Output:</strong> [["havana"],["havana"],["havana"],["havana"],["havana"],["havana"]]
</pre>

<pre><strong>Input:</strong> products = ["bags","baggage","banner","box","cloths"], searchWord = "bags"
<strong>Output:</strong> [["baggage","bags","banner"],["baggage","bags","banner"],["baggage","bags"],["bags"]]
</pre>

<ul>
	<li><code>1 &lt;= products.length &lt;= 1000</code></li>
	<li><code>1 &lt;= products[i].length &lt;= 3000</code></li>
	<li><code>1 &lt;= sum(products[i].length) &lt;= 2 * 10<sup>4</sup></code></li>
	<li>All the strings of <code>products</code> are <strong>unique</strong>.</li>
	<li><code>products[i]</code> consists of lowercase English letters.</li>
	<li><code>1 &lt;= searchWord.length &lt;= 1000</code></li>
	<li><code>searchWord</code> consists of lowercase English letters.</li>
</ul>
</div>

directory: 0139-word-break
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        
        wordDict = set(wordDict)
        n = len(s)
        @lru_cache(maxsize = None)
        def backtrack(index):
            if index == n:
                return True
            for i in range(index + 1, n + 1):
                if s[index:i] in wordDict and backtrack(i):
                    return True
            return False
        return backtrack(0)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/word-break/">139. Word Break</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code> and a dictionary of strings <code>wordDict</code>, return <code>true</code> if <code>s</code> can be segmented into a space-separated sequence of one or more dictionary words.</p>

<p><strong>Note</strong> that the same word in the dictionary may be reused multiple times in the segmentation.</p>

        n = len(s)

<pre><strong>Input:</strong> s = "leetcode", wordDict = ["leet","code"]
<strong>Explanation:</strong> Return true because "leetcode" can be segmented as "leet code".
</pre>

<pre><strong>Input:</strong> s = "applepenapple", wordDict = ["apple","pen"]
<strong>Explanation:</strong> Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.
</pre>

<pre><strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"]
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 300</code></li>
	<li><code>1 &lt;= wordDict.length &lt;= 1000</code></li>
	<li><code>1 &lt;= wordDict[i].length &lt;= 20</code></li>
	<li><code>s</code> and <code>wordDict[i]</code> consist of only lowercase English letters.</li>
	<li>All the strings of <code>wordDict</code> are <strong>unique</strong>.</li>
</ul>
</div>

directory: 261-graph-valid-tree
    def validTree(self, n: int, edges: List[List[int]]) -> bool:
        graph = defaultdict(list)
        for e1, e2 in edges:
            graph[e1].append(e2)
            graph[e2].append(e1)
        visit = set()
        def dfs(node, parent):
            if node in visit:
                return False
            else:
                visit.add(node)
                for nei in graph[node]:
                    if nei == parent:
                        continue
                    if not dfs(nei, node):
                        return False
        return dfs(0, -1) and len(visit) == n
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/graph-valid-tree/">261. Graph Valid Tree</a></h2><h3>Medium</h3><hr><div><p>You have a graph of <code>n</code> nodes labeled from <code>0</code> to <code>n - 1</code>. You are given an integer n and a list of <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an undirected edge between nodes <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>

            else:
                        continue

<p>Return <code>true</code> <em>if the edges of the given graph make up a valid tree, and</em> <code>false</code> <em>otherwise</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/tree1-graph.jpg" style="width: 222px; height: 302px;">
<pre><strong>Input:</strong> n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/tree2-graph.jpg" style="width: 382px; height: 222px;">
<pre><strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 2000</code></li>
	<li><code>0 &lt;= edges.length &lt;= 5000</code></li>
	<li><code>edges[i].length == 2</code></li>
	<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; n</code></li>
	<li><code>a<sub>i</sub> != b<sub>i</sub></code></li>
	<li>There are no self-loops or repeated edges.</li>
</ul>
</div>

directory: 100-same-tree
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q:
            return True
        if not p and q or not q and p:
        if p.val != q.val:
        
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/same-tree/">100. Same Tree</a></h2><h3>Easy</h3><hr><div><p>Given the roots of two binary trees <code>p</code> and <code>q</code>, write a function to check if they are the same or not.</p>

<p>Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex1.jpg" style="width: 622px; height: 182px;">
<pre><strong>Input:</strong> p = [1,2,3], q = [1,2,3]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex2.jpg" style="width: 382px; height: 182px;">
<pre><strong>Input:</strong> p = [1,2], q = [1,null,2]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/20/ex3.jpg" style="width: 622px; height: 182px;">
<pre><strong>Input:</strong> p = [1,2,1], q = [1,1,2]
</pre>

<ul>
	<li>The number of nodes in both trees is in the range <code>[0, 100]</code>.</li>
	<li><code>-10<sup>4</sup> &lt;= Node.val &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 595-big-countries
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/big-countries/">595. Big Countries</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>World</code></p>

| continent   | varchar |
| area        | int     |
| population  | int     |
| gdp         | int     |
name is the primary key column for this table.
Each row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value.
</pre>

<p>A country is <strong>big</strong> if:</p>

<ul>
	<li>it has an area of at least&nbsp;three million (i.e., <code>3000000 km<sup>2</sup></code>), or</li>
	<li>it has a population of at least&nbsp;twenty-five million (i.e., <code>25000000</code>).</li>
</ul>

<p>Write an SQL query to report the name, population, and area of the <strong>big countries</strong>.</p>

World table:
+-------------+-----------+---------+------------+--------------+
| name        | continent | area    | population | gdp          |
| Afghanistan | Asia      | 652230  | 25500100   | 20343000000  |
| Albania     | Europe    | 28748   | 2831741    | 12960000000  |
| Algeria     | Africa    | 2381741 | 37100000   | 188681000000 |
| Andorra     | Europe    | 468     | 78115      | 3712000000   |
| Angola      | Africa    | 1246700 | 20609294   | 100990000000 |
+-------------+------------+---------+
| name        | population | area    |
| Afghanistan | 25500100   | 652230  |
| Algeria     | 37100000   | 2381741 |
</pre>
</div>

directory: 244-shortest-word-distance-ii
Python: class WordDistance:

    def __init__(self, wordsDict: List[str]):
        
        self.dic = defaultdict(list)
        for i, word in enumerate(wordsDict):
            self.dic[word].append(i)
        
    def shortest(self, word1: str, word2: str) -> int:
        
        distance = float('inf')
        i, j = 0, 0
        while i < len(self.dic[word1]) and j < len(self.dic[word2]):
            distance = min(distance, abs(self.dic[word1][i] - self.dic[word2][j]))
            if self.dic[word1][i] < self.dic[word2][j]:
                i += 1
            else:
                j += 1
        return distance

class WordDistance:

        i, j = 0, 0
                i += 1
            else:
                j += 1

# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/shortest-word-distance-ii/">244. Shortest Word Distance II</a></h2><h3>Medium</h3><hr><div><p>Design a data structure that will be initialized with a string array, and then it should answer queries of the shortest distance between two different strings from the array.</p>

<p>Implement the <code>WordDistance</code> class:</p>

<ul>
	<li><code>WordDistance(String[] wordsDict)</code> initializes the object with the strings array <code>wordsDict</code>.</li>
	<li><code>int shortest(String word1, String word2)</code> returns the shortest distance between <code>word1</code> and <code>word2</code> in the array <code>wordsDict</code>.</li>
</ul>

<pre><strong>Input</strong>
["WordDistance", "shortest", "shortest"]
[[["practice", "makes", "perfect", "coding", "makes"]], ["coding", "practice"], ["makes", "coding"]]
<strong>Output</strong>
[null, 3, 1]

<strong>Explanation</strong>
WordDistance wordDistance = new WordDistance(["practice", "makes", "perfect", "coding", "makes"]);
wordDistance.shortest("coding", "practice"); // return 3
wordDistance.shortest("makes", "coding");    // return 1
</pre>

<ul>
	<li><code>1 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= wordsDict[i].length &lt;= 10</code></li>
	<li><code>wordsDict[i]</code> consists of lowercase English letters.</li>
	<li><code>word1</code> and <code>word2</code> are in <code>wordsDict</code>.</li>
	<li><code>word1 != word2</code></li>
	<li>At most <code>5000</code> calls will be made to <code>shortest</code>.</li>
</ul>
</div>

directory: 1396-design-underground-system
Python: class UndergroundSystem:

    def __init__(self):
        
        self.log = {}
        
        self.journeys = {}
                
    def checkIn(self, id: int, stationName: str, t: int) -> None:
        
        self.log[id] = [stationName, t]

    def checkOut(self, id: int, end_station: str, t: int) -> None:

class UndergroundSystem:

        start_station, start_time = self.log.pop(id)
        journey = (start_station, end_station)
        if journey not in self.journeys:
            self.journeys[journey] = [0, 0]
        self.journeys[journey][0] += (t - start_time)
        self.journeys[journey][1] += 1
            
    def getAverageTime(self, start_station: str, end_station: str) -> float:
        total_time, total_trips = self.journeys[(start_station, end_station)]
        return total_time / total_trips

start_station, start_time = self.log.pop(id)
            
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/design-underground-system/">1396. Design Underground System</a></h2><h3>Medium</h3><hr><div><p>An underground railway system is keeping track of customer travel times between different stations. They are using this data to calculate the average time it takes to travel from one station to another.</p>

<p>Implement the <code>UndergroundSystem</code> class:</p>

<ul>
	<li><code>void checkIn(int id, string stationName, int t)</code>

<ul>
		<li>A customer with a card ID equal to <code>id</code>, checks in at the station <code>stationName</code> at time <code>t</code>.</li>
		<li>A customer can only be checked into one place at a time.</li>
	</ul>
	</li>
	<li><code>void checkOut(int id, string stationName, int t)</code>
	<ul>
		<li>A customer with a card ID equal to <code>id</code>, checks out from the station <code>stationName</code> at time <code>t</code>.</li>
	</ul>
	</li>
	<li><code>double getAverageTime(string startStation, string endStation)</code>
	<ul>
		<li>Returns the average time it takes to travel from <code>startStation</code> to <code>endStation</code>.</li>
		<li>The average time is computed from all the previous traveling times from <code>startStation</code> to <code>endStation</code> that happened <strong>directly</strong>, meaning a check in at <code>startStation</code> followed by a check out from <code>endStation</code>.</li>
		<li>The time it takes to travel from <code>startStation</code> to <code>endStation</code> <strong>may be different</strong> from the time it takes to travel from <code>endStation</code> to <code>startStation</code>.</li>
		<li>There will be at least one customer that has traveled from <code>startStation</code> to <code>endStation</code> before <code>getAverageTime</code> is called.</li>
	</ul>
	</li>
</ul>

<p>You may assume all calls to the <code>checkIn</code> and <code>checkOut</code> methods are consistent. If a customer checks in at time <code>t<sub>1</sub></code> then checks out at time <code>t<sub>2</sub></code>, then <code>t<sub>1</sub> &lt; t<sub>2</sub></code>. All events happen in chronological order.</p>

["UndergroundSystem","checkIn","checkIn","checkIn","checkOut","checkOut","checkOut","getAverageTime","getAverageTime","checkIn","getAverageTime","checkOut","getAverageTime"]
[[],[45,"Leyton",3],[32,"Paradise",8],[27,"Leyton",10],[45,"Waterloo",15],[27,"Waterloo",20],[32,"Cambridge",22],["Paradise","Cambridge"],["Leyton","Waterloo"],[10,"Leyton",24],["Leyton","Waterloo"],[10,"Waterloo",38],["Leyton","Waterloo"]]

[null,null,null,null,null,null,null,14.00000,11.00000,null,11.00000,null,12.00000]

UndergroundSystem undergroundSystem = new UndergroundSystem();
undergroundSystem.checkIn(45, "Leyton", 3);
undergroundSystem.checkIn(32, "Paradise", 8);
undergroundSystem.checkIn(27, "Leyton", 10);
undergroundSystem.checkOut(45, "Waterloo", 15);  // Customer 45 "Leyton" -&gt; "Waterloo" in 15-3 = 12
undergroundSystem.checkOut(27, "Waterloo", 20);  // Customer 27 "Leyton" -&gt; "Waterloo" in 20-10 = 10
undergroundSystem.checkOut(32, "Cambridge", 22); // Customer 32 "Paradise" -&gt; "Cambridge" in 22-8 = 14
undergroundSystem.getAverageTime("Paradise", "Cambridge"); // return 14.00000. One trip "Paradise" -&gt; "Cambridge", (14) / 1 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 11.00000. Two trips "Leyton" -&gt; "Waterloo", (10 + 12) / 2 = 11
undergroundSystem.checkIn(10, "Leyton", 24);
undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 11.00000
undergroundSystem.checkOut(10, "Waterloo", 38);  // Customer 10 "Leyton" -&gt; "Waterloo" in 38-24 = 14
undergroundSystem.getAverageTime("Leyton", "Waterloo");    // return 12.00000. Three trips "Leyton" -&gt; "Waterloo", (10 + 12 + 14) / 3 = 12
</pre>

undergroundSystem.checkIn(10, "Leyton", 3);
undergroundSystem.checkOut(10, "Paradise", 8); // Customer 10 "Leyton" -&gt; "Paradise" in 8-3 = 5
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.00000, (5) / 1 = 5
undergroundSystem.checkIn(5, "Leyton", 10);
undergroundSystem.checkOut(5, "Paradise", 16); // Customer 5 "Leyton" -&gt; "Paradise" in 16-10 = 6
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 5.50000, (5 + 6) / 2 = 5.5
undergroundSystem.checkIn(2, "Leyton", 21);
undergroundSystem.checkOut(2, "Paradise", 30); // Customer 2 "Leyton" -&gt; "Paradise" in 30-21 = 9
undergroundSystem.getAverageTime("Leyton", "Paradise"); // return 6.66667, (5 + 6 + 9) / 3 = 6.66667
</pre>

<ul>
	<li><code>1 &lt;= id, t &lt;= 10<sup>6</sup></code></li>
	<li><code>1 &lt;= stationName.length, startStation.length, endStation.length &lt;= 10</code></li>
	<li>All strings consist of uppercase and lowercase English letters and digits.</li>
	<li>There will be at most <code>2 * 10<sup>4</sup></code> calls <strong>in total</strong> to <code>checkIn</code>, <code>checkOut</code>, and <code>getAverageTime</code>.</li>
	<li>Answers within <code>10<sup>-5</sup></code> of the actual value will be accepted.</li>
</ul>
</div>

directory: 2316-count-unreachable-pairs-of-nodes-in-an-undirected-graph
    def countPairs(self, n: int, edges: List[List[int]]) -> int:
        
        for v in edges:
            graph[v[0]].append(v[1])
            graph[v[1]].append(v[0])
        
        visited = set()
        
        def dfs(node):
            if node in visited:
                return 0
            visited.add(node)
            res = 1
            for n in graph[node]:
                res += dfs(n)
            return res
        
        components = []
        total_sum = 0
        
        for i in range(n):
            temp = dfs(i)
            if temp != 0:
                total_sum += temp
                components.append(temp)
        
        result = 0
        for i in components:
            result += (total_sum - i) * i
        return result//2
Notes: ​
Readme:

                return 0
            res = 1
            return res
        
        result = 0
        
directory: 0529-minesweeper
    
    def getMines(self, board, x, y):
        numMines = 0
        for r in range(x-1, x + 2):
            for c in range(y-1, y + 2):
                if r >= 0 and r < len(board) and c >= 0 and c < len(board[0]) and board[r][c] == 'M':
                    numMines += 1
        return numMines
    def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
        
        if not board:
            return board
        x, y = click
        
        if board[x][y] == 'M':
            board[x][y] = 'X'
        else:
            numMines = self.getMines(board, x, y)
            if numMines:
                board[x][y] = str(numMines)
            else:
                board[x][y] = 'B'
                for r in range(x-1, x + 2):
                    for c in range(y-1, y + 2):
                        if r >= 0 and r < len(board) and c >= 0 and c < len(board[0]) and board[r][c] != 'B':
                            self.updateBoard(board, [r, c])

        x, y = click
        
        else:
            else:

        return board

return board
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/minesweeper/">529. Minesweeper</a></h2><h3>Medium</h3><hr><div><p>Let's play the minesweeper game (<a href="https://en.wikipedia.org/wiki/Minesweeper_(video_game)" target="_blank">Wikipedia</a>, <a href="http://minesweeperonline.com" target="_blank">online game</a>)!</p>

<p>You are given an <code>m x n</code> char matrix <code>board</code> representing the game board where:</p>

<ul>
	<li><code>'M'</code> represents an unrevealed mine,</li>
	<li><code>'E'</code> represents an unrevealed empty square,</li>
	<li><code>'B'</code> represents a revealed blank square that has no adjacent mines (i.e., above, below, left, right, and all 4 diagonals),</li>
	<li>digit (<code>'1'</code> to <code>'8'</code>) represents how many mines are adjacent to this revealed square, and</li>
	<li><code>'X'</code> represents a revealed mine.</li>
</ul>

<p>You are also given an integer array <code>click</code> where <code>click = [click<sub>r</sub>, click<sub>c</sub>]</code> represents the next click position among all the unrevealed squares (<code>'M'</code> or <code>'E'</code>).</p>

<p>Return <em>the board after revealing this position according to the following rules</em>:</p>

<ol>
	<li>If a mine <code>'M'</code> is revealed, then the game is over. You should change it to <code>'X'</code>.</li>
	<li>If an empty square <code>'E'</code> with no adjacent mines is revealed, then change it to a revealed blank <code>'B'</code> and all of its adjacent unrevealed squares should be revealed recursively.</li>
	<li>If an empty square <code>'E'</code> with at least one adjacent mine is revealed, then change it to a digit (<code>'1'</code> to <code>'8'</code>) representing the number of adjacent mines.</li>
	<li>Return the board when no more squares will be revealed.</li>
</ol>

<img src="https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_1.png" style="width: 500px; max-width: 400px; height: 269px;">
<pre><strong>Input:</strong> board = [["E","E","E","E","E"],["E","E","M","E","E"],["E","E","E","E","E"],["E","E","E","E","E"]], click = [3,0]
<strong>Output:</strong> [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]
</pre>

<img src="https://assets.leetcode.com/uploads/2018/10/12/minesweeper_example_2.png" style="width: 500px; max-width: 400px; height: 275px;">
<pre><strong>Input:</strong> board = [["B","1","E","1","B"],["B","1","M","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]], click = [1,2]
<strong>Output:</strong> [["B","1","E","1","B"],["B","1","X","1","B"],["B","1","1","1","B"],["B","B","B","B","B"]]
</pre>

<ul>
	<li><code>m == board.length</code></li>
	<li><code>n == board[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 50</code></li>
	<li><code>board[i][j]</code> is either <code>'M'</code>, <code>'E'</code>, <code>'B'</code>, or a digit from <code>'1'</code> to <code>'8'</code>.</li>
	<li><code>click.length == 2</code></li>
	<li><code>0 &lt;= click<sub>r</sub> &lt; m</code></li>
	<li><code>0 &lt;= click<sub>c</sub> &lt; n</code></li>
	<li><code>board[click<sub>r</sub>][click<sub>c</sub>]</code> is either <code>'M'</code> or <code>'E'</code>.</li>
</ul>
</div>

directory: 974-subarray-sums-divisible-by-k
    def subarraysDivByK(self, nums: List[int], k: int) -> int:
        
        dic = defaultdict(int)
        dic[0] = 1
        prefixSum = 0
        res = 0
        for num in nums:
            prefixSum += num
            prefixSum = prefixSum % k
            res += dic[prefixSum % k]
            dic[prefixSum % k] += 1
        return res
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/subarray-sums-divisible-by-k/">974. Subarray Sums Divisible by K</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the number of non-empty <strong>subarrays</strong> that have a sum divisible by </em><code>k</code>.</p>

<p>A <strong>subarray</strong> is a <strong>contiguous</strong> part of an array.</p>

        dic[0] = 1
        res = 0
        return res
        
<pre><strong>Input:</strong> nums = [4,5,0,-2,-3,1], k = 5
<strong>Explanation:</strong> There are 7 subarrays with a sum divisible by k = 5:
[4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
</pre>

<pre><strong>Input:</strong> nums = [5], k = 9
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
	<li><code>2 &lt;= k &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 322-coin-change
    def coinChange(self, coins: List[int], amount: int) -> int:
        
        dp = [float('inf') for _ in range(amount + 1)]
        dp[0] = 0
        for coin in coins:
            for i in range(amount + 1):
                if i >= coin:
                    dp[i] = min(dp[i], 1 + dp[i - coin])
                    
        return dp[amount] if dp[amount] != float('inf') else -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/coin-change/">322. Coin Change</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>

<p>Return <em>the fewest number of coins that you need to make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>-1</code>.</p>

<p>You may assume that you have an infinite number of each kind of coin.</p>

        dp[0] = 0
                    
<pre><strong>Input:</strong> coins = [1,2,5], amount = 11
<strong>Explanation:</strong> 11 = 5 + 5 + 1
</pre>

<pre><strong>Input:</strong> coins = [2], amount = 3
<strong>Output:</strong> -1
</pre>

<pre><strong>Input:</strong> coins = [1], amount = 0
</pre>

<ul>
	<li><code>1 &lt;= coins.length &lt;= 12</code></li>
	<li><code>1 &lt;= coins[i] &lt;= 2<sup>31</sup> - 1</code></li>
	<li><code>0 &lt;= amount &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 2095-delete-the-middle-node-of-a-linked-list
    def deleteMiddle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        
        dummy = ListNode(-1)
        dummy.next = head
        fast, slow = dummy, dummy
        
        while fast.next and fast.next.next:
            fast = fast.next.next
            slow = slow.next
        slow_val = slow.val if slow else 0
        fast_val = fast.val if fast else 0
        
        slow.next = slow.next.next
        
        return dummy.next
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/delete-the-middle-node-of-a-linked-list/">2095. Delete the Middle Node of a Linked List</a></h2><h3>Medium</h3><hr><div><p>You are given the <code>head</code> of a linked list. <strong>Delete</strong> the <strong>middle node</strong>, and return <em>the</em> <code>head</code> <em>of the modified linked list</em>.</p>

<p>The <strong>middle node</strong> of a linked list of size <code>n</code> is the <code>⌊n / 2⌋<sup>th</sup></code> node from the <b>start</b> using <strong>0-based indexing</strong>, where <code>⌊x⌋</code> denotes the largest integer less than or equal to <code>x</code>.</p>

<ul>
	<li>For <code>n</code> = <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, and <code>5</code>, the middle nodes are <code>0</code>, <code>1</code>, <code>1</code>, <code>2</code>, and <code>2</code>, respectively.</li>
</ul>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/16/eg1drawio.png" style="width: 500px; height: 77px;">
<pre><strong>Input:</strong> head = [1,3,4,7,1,2,6]
<strong>Output:</strong> [1,3,4,1,2,6]
The above figure represents the given linked list. The indices of the nodes are written below.
Since n = 7, node 3 with value 7 is the middle node, which is marked in red.
We return the new list after removing this node. 
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/16/eg2drawio.png" style="width: 250px; height: 43px;">
<pre><strong>Input:</strong> head = [1,2,3,4]
<strong>Output:</strong> [1,2,4]
The above figure represents the given linked list.
For n = 4, node 2 with value 3 is the middle node, which is marked in red.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/16/eg3drawio.png" style="width: 150px; height: 58px;">
<pre><strong>Input:</strong> head = [2,1]
<strong>Output:</strong> [2]
For n = 2, node 1 with value 1 is the middle node, which is marked in red.
Node 0 with value 2 is the only node remaining after removing node 1.</pre>

<ul>
	<li>The number of nodes in the list is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 881-boats-to-save-people
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/boats-to-save-people/">881. Boats to Save People</a></h2><h3>Medium</h3><hr><div><p>You are given an array <code>people</code> where <code>people[i]</code> is the weight of the <code>i<sup>th</sup></code> person, and an <strong>infinite number of boats</strong> where each boat can carry a maximum weight of <code>limit</code>. Each boat carries at most two people at the same time, provided the sum of the weight of those people is at most <code>limit</code>.</p>

<p>Return <em>the minimum number of boats to carry every given person</em>.</p>

<pre><strong>Input:</strong> people = [1,2], limit = 3
<strong>Explanation:</strong> 1 boat (1, 2)
</pre>

<pre><strong>Input:</strong> people = [3,2,2,1], limit = 3
<strong>Explanation:</strong> 3 boats (1, 2), (2) and (3)
</pre>

<pre><strong>Input:</strong> people = [3,5,3,4], limit = 5
<strong>Explanation:</strong> 4 boats (3), (3), (4), (5)
</pre>

<ul>
	<li><code>1 &lt;= people.length &lt;= 5 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= people[i] &lt;= limit &lt;= 3 * 10<sup>4</sup></code></li>
</ul>
</div>

directory: 611-valid-triangle-number
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/valid-triangle-number/">611. Valid Triangle Number</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, return <em>the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle</em>.</p>

<pre><strong>Input:</strong> nums = [2,2,3,4]
<strong>Explanation:</strong> Valid combinations are: 
2,3,4 (using the first 2)
2,3,4 (using the second 2)
2,2,3
</pre>

<pre><strong>Input:</strong> nums = [4,2,3,4]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>0 &lt;= nums[i] &lt;= 1000</code></li>
</ul>
</div>

directory: 503-next-greater-element-ii
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/next-greater-element-ii/">503. Next Greater Element II</a></h2><h3>Medium</h3><hr><div><p>Given a circular integer array <code>nums</code> (i.e., the next element of <code>nums[nums.length - 1]</code> is <code>nums[0]</code>), return <em>the <strong>next greater number</strong> for every element in</em> <code>nums</code>.</p>

<p>The <strong>next greater number</strong> of a number <code>x</code> is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, return <code>-1</code> for this number.</p>

<pre><strong>Input:</strong> nums = [1,2,1]
<strong>Output:</strong> [2,-1,2]
Explanation: The first 1's next greater number is 2; 
The number 2 can't find next greater number. 
The second 1's next greater number needs to search circularly, which is also 2.
</pre>

<pre><strong>Input:</strong> nums = [1,2,3,4,3]
<strong>Output:</strong> [2,3,4,-1,4]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 20-valid-parentheses
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/valid-parentheses/">20. Valid Parentheses</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code> containing just the characters <code>'('</code>, <code>')'</code>, <code>'{'</code>, <code>'}'</code>, <code>'['</code> and <code>']'</code>, determine if the input string is valid.</p>

<p>An input string is valid if:</p>

<ol>
	<li>Open brackets must be closed by the same type of brackets.</li>
	<li>Open brackets must be closed in the correct order.</li>
</ol>

<pre><strong>Input:</strong> s = "()"
</pre>

<pre><strong>Input:</strong> s = "()[]{}"
</pre>

<pre><strong>Input:</strong> s = "(]"
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 10<sup>4</sup></code></li>
	<li><code>s</code> consists of parentheses only <code>'()[]{}'</code>.</li>
</ul>
</div>

directory: 58-length-of-last-word
    def lengthOfLastWord(self, s: str) -> int:
        
        right = len(s) - 1
        
        while right >= 0 and s[right] == " ":
            right -= 1
        left = right
        while left >= 0 and s[left] != " ":
            left -= 1
        return right - left
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/length-of-last-word/">58. Length of Last Word</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code> consisting of words and spaces, return <em>the length of the <strong>last</strong> word in the string.</em></p>

<p>A <strong>word</strong> is a maximal substring consisting of non-space characters only.</p>

<pre><strong>Input:</strong> s = "Hello World"
<strong>Explanation:</strong> The last word is "World" with length 5.
</pre>

            right -= 1
            left -= 1
        
<pre><strong>Input:</strong> s = "   fly me   to   the moon  "
<strong>Explanation:</strong> The last word is "moon" with length 4.
</pre>

<pre><strong>Input:</strong> s = "luffy is still joyboy"
<strong>Output:</strong> 6
<strong>Explanation:</strong> The last word is "joyboy" with length 6.
</pre>

<ul>
	<li><code>s</code> consists of only English letters and spaces <code>' '</code>.</li>
	<li>There will be at least one word in <code>s</code>.</li>
</ul>
</div>

directory: 1046-last-stone-weight
    def lastStoneWeight(self, stones: List[int]) -> int:
        
        stones = [-x for x in stones]
        heapq.heapify(stones)
        while len(stones) > 1:
            stone1, stone2 = -1 * heapq.heappop(stones), -1 * heapq.heappop(stones)
            if stone1 == stone2:
                continue
            stone1 -= stone2
            heapq.heappush(stones, -1 * stone1)
        return -1 * stones[0] if len(stones) == 1 else 0
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/last-stone-weight/">1046. Last Stone Weight</a></h2><h3>Easy</h3><hr><div><p>You are given an array of integers <code>stones</code> where <code>stones[i]</code> is the weight of the <code>i<sup>th</sup></code> stone.</p>

                continue

<p>We are playing a game with the stones. On each turn, we choose the <strong>heaviest two stones</strong> and smash them together. Suppose the heaviest two stones have weights <code>x</code> and <code>y</code> with <code>x &lt;= y</code>. The result of this smash is:</p>

<ul>
	<li>If <code>x == y</code>, both stones are destroyed, and</li>
	<li>If <code>x != y</code>, the stone of weight <code>x</code> is destroyed, and the stone of weight <code>y</code> has new weight <code>y - x</code>.</li>
</ul>

<p>At the end of the game, there is <strong>at most one</strong> stone left.</p>

<p>Return <em>the smallest possible weight of the left stone</em>. If there are no stones left, return <code>0</code>.</p>

<pre><strong>Input:</strong> stones = [2,7,4,1,8,1]
We combine 7 and 8 to get 1 so the array converts to [2,4,1,1,1] then,
we combine 2 and 4 to get 2 so the array converts to [2,1,1,1] then,
we combine 2 and 1 to get 1 so the array converts to [1,1,1] then,
we combine 1 and 1 to get 0 so the array converts to [1] then that's the value of the last stone.
</pre>

<pre><strong>Input:</strong> stones = [1]
</pre>

<ul>
	<li><code>1 &lt;= stones.length &lt;= 30</code></li>
	<li><code>1 &lt;= stones[i] &lt;= 1000</code></li>
</ul>
</div>

directory: 870-advantage-shuffle
Python: import bisect
    def advantageCount(self, nums1: List[int], nums2: List[int]) -> List[int]:
        
        ans = []
        n = len(nums1)
        nums1.sort()
        
        for num in nums2:
            
            idx = bisect.bisect_right(nums1, num)
            if idx == n:
                idx = 0
            ans.append(nums1[idx])
            nums1.pop(idx)
            n-=1
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/advantage-shuffle/">870. Advantage Shuffle</a></h2><h3>Medium</h3><hr><div><p>You are given two integer arrays <code>nums1</code> and <code>nums2</code> both of the same length. The <strong>advantage</strong> of <code>nums1</code> with respect to <code>nums2</code> is the number of indices <code>i</code> for which <code>nums1[i] &gt; nums2[i]</code>.</p>

import bisect
        
        ans = []
        
            if idx == n:
                idx = 0
            n-=1
        return ans

<p>Return <em>any permutation of </em><code>nums1</code><em> that maximizes its <strong>advantage</strong> with respect to </em><code>nums2</code>.</p>

<pre><strong>Input:</strong> nums1 = [2,7,11,15], nums2 = [1,10,4,11]
<strong>Output:</strong> [2,11,7,15]
</pre><p><strong>Example 2:</strong></p>
<pre><strong>Input:</strong> nums1 = [12,24,8,32], nums2 = [13,25,32,11]
<strong>Output:</strong> [24,32,8,12]
</pre>

<ul>
	<li><code>1 &lt;= nums1.length &lt;= 10<sup>5</sup></code></li>
	<li><code>nums2.length == nums1.length</code></li>
	<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 242-valid-anagram
    def isAnagram(self, s: str, t: str) -> bool:
        
        return sorted(s) == sorted(t)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/valid-anagram/">242. Valid Anagram</a></h2><h3>Easy</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code> <em>if</em> <code>t</code> <em>is an anagram of</em> <code>s</code><em>, and</em> <code>false</code> <em>otherwise</em>.</p>

<p>An <strong>Anagram</strong> is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.</p>

<pre><strong>Input:</strong> s = "anagram", t = "nagaram"
<pre><strong>Input:</strong> s = "rat", t = "car"
</pre>

<ul>
	<li><code>1 &lt;= s.length, t.length &lt;= 5 * 10<sup>4</sup></code></li>
	<li><code>s</code> and <code>t</code> consist of lowercase English letters.</li>
</ul>

<p><strong>Follow up:</strong> What if the inputs contain Unicode characters? How would you adapt your solution to such a case?</p>
</div>

directory: 0105-construct-binary-tree-from-preorder-and-inorder-traversal
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/">105. Construct Binary Tree from Preorder and Inorder Traversal</a></h2><h3>Medium</h3><hr><div><p>Given two integer arrays <code>preorder</code> and <code>inorder</code> where <code>preorder</code> is the preorder traversal of a binary tree and <code>inorder</code> is the inorder traversal of the same tree, construct and return <em>the binary tree</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/tree.jpg" style="width: 277px; height: 302px;">
<pre><strong>Input:</strong> preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
<strong>Output:</strong> [3,9,20,null,null,15,7]
</pre>

<pre><strong>Input:</strong> preorder = [-1], inorder = [-1]
<strong>Output:</strong> [-1]
</pre>

<ul>
	<li><code>1 &lt;= preorder.length &lt;= 3000</code></li>
	<li><code>inorder.length == preorder.length</code></li>
	<li><code>-3000 &lt;= preorder[i], inorder[i] &lt;= 3000</code></li>
	<li><code>preorder</code> and <code>inorder</code> consist of <strong>unique</strong> values.</li>
	<li>Each value of <code>inorder</code> also appears in <code>preorder</code>.</li>
	<li><code>preorder</code> is <strong>guaranteed</strong> to be the preorder traversal of the tree.</li>
	<li><code>inorder</code> is <strong>guaranteed</strong> to be the inorder traversal of the tree.</li>
</ul>
</div>

directory: 243-shortest-word-distance
    def shortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
        
        ans = first = second = float('inf')
            if word == word1:
                first = i
            elif word == word2:
                second = i
            ans = min(abs(first - second), ans)
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/shortest-word-distance/">243. Shortest Word Distance</a></h2><h3>Easy</h3><hr><div><p>Given an array of strings <code>wordsDict</code> and two different strings that already exist in the array <code>word1</code> and <code>word2</code>, return <em>the shortest distance between these two words in the list</em>.</p>

                first = i
                second = i
        return ans

<pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "coding", word2 = "practice"
</pre>

<pre><strong>Input:</strong> wordsDict = ["practice", "makes", "perfect", "coding", "makes"], word1 = "makes", word2 = "coding"
</pre>

<ul>
	<li><code>2 &lt;= wordsDict.length &lt;= 3 * 10<sup>4</sup></code></li>
</ul>
</div>

directory: 669-trim-a-binary-search-tree
class Solution:    
    def trimBST(self, root: Optional[TreeNode], low: int, high: int) -> Optional[TreeNode]:
        
        def trim(node):
            if not node:
                return None
            elif node.val > high:
                return trim(node.left)
            elif node.val < low:
                return trim(node.right)
            else:
                node.left = trim(node.left)
                node.right =  trim(node.right)
                return node
        return trim(root)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/trim-a-binary-search-tree/">669. Trim a Binary Search Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary search tree and the lowest and highest boundaries as <code>low</code> and <code>high</code>, trim the tree so that all its elements lies in <code>[low, high]</code>. Trimming the tree should <strong>not</strong> change the relative structure of the elements that will remain in the tree (i.e., any node's descendant should remain a descendant). It can be proven that there is a <strong>unique answer</strong>.</p>

            else:

<p>Return <em>the root of the trimmed binary search tree</em>. Note that the root may change depending on the given bounds.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/09/trim1.jpg" style="width: 450px; height: 126px;">
<pre><strong>Input:</strong> root = [1,0,2], low = 1, high = 2
<strong>Output:</strong> [1,null,2]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/09/trim2.jpg" style="width: 450px; height: 277px;">
<pre><strong>Input:</strong> root = [3,0,4,null,2,null,null,1], low = 1, high = 3
<strong>Output:</strong> [3,2,null,1]
</pre>

<ul>
	<li>The number of nodes in the tree in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li>The value of each node in the tree is <strong>unique</strong>.</li>
	<li><code>root</code> is guaranteed to be a valid binary search tree.</li>
	<li><code>0 &lt;= low &lt;= high &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 720-longest-word-in-dictionary
    def longestWord(self, words: List[str]) -> str:
        seen = set(words)
        words.sort()
        max_word = ""
        for word in words:
            boolean = True
            for i in range(len(word)):
                prefix = word[:i+1]
                if prefix not in seen:
                    boolean = False
                    break
            if boolean:
                if max_word is None or len(max_word) < len(word):
                    max_word = word
        return max_word
Notes: max_word = ""
for word in words:
boolean = True
for i in range(len(word)+1):
prefix = word[:i]
if prefix not in seen:
boolean = False
break
if boolean:
if len(max_word) < len(word):
max_word = word
return max_word
Readme: <h2><a href="https://leetcode.com/problems/longest-word-in-dictionary/">720. Longest Word in Dictionary</a></h2><h3>Medium</h3><hr><div><p>Given an array of strings <code>words</code> representing an English Dictionary, return <em>the longest word in</em> <code>words</code> <em>that can be built one character at a time by other words in</em> <code>words</code>.</p>

                    break
        
<p>If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.</p>

<pre><strong>Input:</strong> words = ["w","wo","wor","worl","world"]
<strong>Output:</strong> "world"
<strong>Explanation:</strong> The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".
</pre>

<pre><strong>Input:</strong> words = ["a","banana","app","appl","ap","apply","apple"]
<strong>Output:</strong> "apple"
<strong>Explanation:</strong> Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".
</pre>

<ul>
	<li><code>1 &lt;= words.length &lt;= 1000</code></li>
	<li><code>1 &lt;= words[i].length &lt;= 30</code></li>
	<li><code>words[i]</code> consists of lowercase English letters.</li>
</ul>
</div>

directory: 1249-minimum-remove-to-make-valid-parentheses
    def minRemoveToMakeValid(self, s: str) -> str:
        
        stack = []
        s = list(s)
        for i, c in enumerate(s):
            if c == '(':
                stack.append(i)
            elif c == ')':
                if stack:
                    stack.pop()
                else:
                    s[i] = ""
        for i in stack:
            s[i] = ""
        return "".join(s)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/">1249. Minimum Remove to Make Valid Parentheses</a></h2><h3>Medium</h3><hr><div><p>Given a string <font face="monospace">s</font> of <code>'('</code> , <code>')'</code> and lowercase English characters.</p>

        stack = []
        s = list(s)
            if c == '(':
                if stack:
                else:
                    s[i] = ""
            s[i] = ""
        
<p>Your task is to remove the minimum number of parentheses ( <code>'('</code> or <code>')'</code>, in any positions ) so that the resulting <em>parentheses string</em> is valid and return <strong>any</strong> valid string.</p>

<p>Formally, a <em>parentheses string</em> is valid if and only if:</p>

<ul>
	<li>It is the empty string, contains only lowercase characters, or</li>
	<li>It can be written as <code>AB</code> (<code>A</code> concatenated with <code>B</code>), where <code>A</code> and <code>B</code> are valid strings, or</li>
	<li>It can be written as <code>(A)</code>, where <code>A</code> is a valid string.</li>
</ul>

<pre><strong>Input:</strong> s = "lee(t(c)o)de)"
<strong>Output:</strong> "lee(t(c)o)de"
<strong>Explanation:</strong> "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
</pre>

<pre><strong>Input:</strong> s = "a)b(c)d"
<strong>Output:</strong> "ab(c)d"
</pre>

<pre><strong>Input:</strong> s = "))(("
<strong>Output:</strong> ""
<strong>Explanation:</strong> An empty string is also valid.
</pre>

<ul>
	<li><code>s[i]</code> is either<code>'('</code> , <code>')'</code>, or lowercase English letter<code>.</code></li>
</ul>
</div>

directory: 1020-number-of-enclaves
    def numEnclaves(self, grid: List[List[int]]) -> int:
        
        rows, cols = len(grid), len(grid[0])
        def dfs(r, c):
            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == 0:
                return 0
            grid[r][c] = 0
            return 1 + dfs(r+1, c) + dfs(r-1, c) + dfs(r, c-1) + dfs(r, c+1)
         
        for r in range(rows):
            for c in range(cols):
                if (r == 0 or c == 0 or r == rows - 1 or c == cols - 1) and grid[r][c] == 1:
                    dfs(r,c)
        count = 0
                count += dfs(r, c)
        return count
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-enclaves/">1020. Number of Enclaves</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> binary matrix <code>grid</code>, where <code>0</code> represents a sea cell and <code>1</code> represents a land cell.</p>

                return 0
         
                    dfs(r,c)
        count = 0

<p>A <strong>move</strong> consists of walking from one land cell to another adjacent (<strong>4-directionally</strong>) land cell or walking off the boundary of the <code>grid</code>.</p>

<p>Return <em>the number of land cells in</em> <code>grid</code> <em>for which we cannot walk off the boundary of the grid in any number of <strong>moves</strong></em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/enclaves1.jpg" style="width: 333px; height: 333px;">
<pre><strong>Input:</strong> grid = [[0,0,0,0],[1,0,1,0],[0,1,1,0],[0,0,0,0]]
<strong>Explanation:</strong> There are three 1s that are enclosed by 0s, and one 1 that is not enclosed because its on the boundary.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/enclaves2.jpg" style="width: 333px; height: 333px;">
<pre><strong>Input:</strong> grid = [[0,1,1,0],[0,0,1,0],[0,0,1,0],[0,0,0,0]]
<strong>Explanation:</strong> All 1s are either on the boundary or can reach the boundary.
</pre>

<ul>
	<li><code>m == grid.length</code></li>
	<li><code>n == grid[i].length</code></li>
	<li><code>grid[i][j]</code> is either <code>0</code> or <code>1</code>.</li>
</ul>
</div>

directory: 623-add-one-row-to-tree
    def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:
        if depth == 1:
            temp = TreeNode(val)
            temp.left = root
            return temp
        dummy = root
        queue = deque([(root, 1)])
        while queue:
            size = len(queue)
            node, d = queue.popleft()
            if node.left:
                queue.append((node.left, d + 1))
            if node.right:
                queue.append((node.right, d + 1))
            if d == depth - 1:
                left, right = node.left, node.right
                tempLeft, tempRight = TreeNode(val), TreeNode(val)
                node.left, node.right = tempLeft, tempRight
                tempLeft.left, tempRight.right = left, right                
        return dummy
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/add-one-row-to-tree/">623. Add One Row to Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree and two integers <code>val</code> and <code>depth</code>, add a row of nodes with value <code>val</code> at the given depth <code>depth</code>.</p>

<p>Note that the <code>root</code> node is at depth <code>1</code>.</p>

<p>The adding rule is:</p>

<ul>
	<li>Given the integer <code>depth</code>, for each not null tree node <code>cur</code> at the depth <code>depth - 1</code>, create two tree nodes with value <code>val</code> as <code>cur</code>'s left subtree root and right subtree root.</li>
	<li><code>cur</code>'s original left subtree should be the left subtree of the new left subtree root.</li>
	<li><code>cur</code>'s original right subtree should be the right subtree of the new right subtree root.</li>
	<li>If <code>depth == 1</code> that means there is no depth <code>depth - 1</code> at all, then create a tree node with value <code>val</code> as the new root of the whole original tree, and the original tree is the new root's left subtree.</li>
</ul>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/15/addrow-tree.jpg" style="width: 500px; height: 231px;">
<pre><strong>Input:</strong> root = [4,2,6,3,1,5], val = 1, depth = 2
<strong>Output:</strong> [4,1,1,2,null,null,6,3,1,5]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/11/add2-tree.jpg" style="width: 500px; height: 277px;">
<pre><strong>Input:</strong> root = [4,2,null,3,1], val = 1, depth = 3
<strong>Output:</strong> [4,2,null,1,1,3,null,null,1]
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li>The depth of the tree is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li><code>-10<sup>5</sup> &lt;= val &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= depth &lt;= the depth of tree + 1</code></li>
</ul>
</div>

directory: 111-minimum-depth-of-binary-tree
    def minDepth(self, root: Optional[TreeNode]) -> int:
        self.min_height = float('inf')
        if not root:
            return 0
        def dfs(node, height):
            if node:
                if not node.left and not node.right:
                    self.min_height = min(self.min_height, height + 1)
                dfs(node.left, height + 1)
                dfs(node.right, height + 1)
        dfs(root, 0)
        return self.min_height
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-depth-of-binary-tree/">111. Minimum Depth of Binary Tree</a></h2><h3>Easy</h3><hr><div><p>Given a binary tree, find its minimum depth.</p>

            return 0
            if node:
        
<p>The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.</p>

<p><strong>Note:</strong>&nbsp;A leaf is a node with no children.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/12/ex_depth.jpg" style="width: 432px; height: 302px;">
<pre><strong>Input:</strong> root = [3,9,20,null,null,15,7]
</pre>

<pre><strong>Input:</strong> root = [2,null,3,null,4,null,5,null,6]
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[0, 10<sup>5</sup>]</code>.</li>
	<li><code>-1000 &lt;= Node.val &lt;= 1000</code></li>
</ul>
</div>

directory: 166-fraction-to-recurring-decimal
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/fraction-to-recurring-decimal/">166. Fraction to Recurring Decimal</a></h2><h3>Medium</h3><hr><div><p>Given two integers representing the <code>numerator</code> and <code>denominator</code> of a fraction, return <em>the fraction in string format</em>.</p>

<p>If the fractional part is repeating, enclose the repeating part in parentheses.</p>

<p>If multiple answers are possible, return <strong>any of them</strong>.</p>

<p>It is <strong>guaranteed</strong> that the length of the answer string is less than <code>10<sup>4</sup></code> for all the given inputs.</p>

<pre><strong>Input:</strong> numerator = 1, denominator = 2
<strong>Output:</strong> "0.5"
</pre>

<pre><strong>Input:</strong> numerator = 2, denominator = 1
<strong>Output:</strong> "2"
</pre>

<pre><strong>Input:</strong> numerator = 4, denominator = 333
<strong>Output:</strong> "0.(012)"
</pre>

<ul>
	<li><code>-2<sup>31</sup> &lt;=&nbsp;numerator, denominator &lt;= 2<sup>31</sup> - 1</code></li>
	<li><code>denominator != 0</code></li>
</ul>
</div>

directory: 250-count-univalue-subtrees
    def countUnivalSubtrees(self, root):
        if root is None: return 0
        self.count = 0
        self.is_uni(root)
        return self.count

    def is_uni(self, node):

        # base case - if the node has no children this is a univalue subtree
        if node.left is None and node.right is None:

            # found a univalue subtree - increment
            self.count += 1

        is_uni = True

        # check if all of the node's children are univalue subtrees and if they have the same value
        # also recursively call is_uni for children
        if node.left is not None:
            is_uni = self.is_uni(node.left) and is_uni and node.left.val == node.val

        if node.right is not None:
            is_uni = self.is_uni(node.right) and is_uni and node.right.val == node.val

        # increment self.res and return whether a univalue tree exists here
        self.count += is_uni
        return is_uni

# increment self.res and return whether a univalue tree exists here
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/count-univalue-subtrees/">250. Count Univalue Subtrees</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return the number of <strong>uni-value</strong> subtrees.</p>

<p>A <strong>uni-value subtree</strong> means all nodes of the subtree have the same value.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/08/21/unival_e1.jpg" style="width: 450px; height: 258px;">
<pre><strong>Input:</strong> root = [5,1,5,5,5,null,5]
</pre>

</pre>

<pre><strong>Input:</strong> root = [5,5,5,5,5,null,5]
</pre>

<ul>
	<li>The number of the node in the tree will be in the range <code>[0, 1000]</code>.</li>
</ul>
</div>

directory: 1480-running-sum-of-1d-array
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/running-sum-of-1d-array/">1480. Running Sum of 1d Array</a></h2><h3>Easy</h3><hr><div><p>Given an array <code>nums</code>. We define a running sum of an array as&nbsp;<code>runningSum[i] = sum(nums[0]…nums[i])</code>.</p>

<p>Return the running sum of <code>nums</code>.</p>

<pre><strong>Input:</strong> nums = [1,2,3,4]
<strong>Output:</strong> [1,3,6,10]
<strong>Explanation:</strong> Running sum is obtained as follows: [1, 1+2, 1+2+3, 1+2+3+4].</pre>

<pre><strong>Input:</strong> nums = [1,1,1,1,1]
<strong>Output:</strong> [1,2,3,4,5]
<strong>Explanation:</strong> Running sum is obtained as follows: [1, 1+1, 1+1+1, 1+1+1+1, 1+1+1+1+1].</pre>

<pre><strong>Input:</strong> nums = [3,1,2,10,1]
<strong>Output:</strong> [3,4,6,16,17]
</pre>

<ul>
	<li><code>-10^6&nbsp;&lt;= nums[i] &lt;=&nbsp;10^6</code></li>
</ul></div>

directory: 525-contiguous-array
    def findMaxLength(self, nums: List[int]) -> int:
        
        for i in range(len(nums)):
            if nums[i] == 0:
                nums[i] = -1
                
        dic = {0 : -1}
        maximum = 0
        for i, num in enumerate(nums):
            if prefixSum in dic:
                maximum = max(maximum, i - dic[prefixSum])
            else:
                dic[prefixSum] = i
Notes: for i in range(len(nums)):
if nums[i] == 0:
nums[i] = -1
dic = {0:-1}
largest = 0
prefixSum = 0
for i in range(len(nums)):
prefixSum += nums[i]
if prefixSum in dic:
index_2_ignore = dic[prefixSum]
largest = max(largest, i - index_2_ignore)
else:
dic[prefixSum] = i
return largest
Readme: <h2><a href="https://leetcode.com/problems/contiguous-array/">525. Contiguous Array</a></h2><h3>Medium</h3><hr><div><p>Given a binary array <code>nums</code>, return <em>the maximum length of a contiguous subarray with an equal number of </em><code>0</code><em> and </em><code>1</code>.</p>

        maximum = 0
            else:

<pre><strong>Input:</strong> nums = [0,1]
<strong>Explanation:</strong> [0, 1] is the longest contiguous subarray with an equal number of 0 and 1.
</pre>

<pre><strong>Input:</strong> nums = [0,1,0]
<strong>Explanation:</strong> [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
</pre>

<ul>
</ul>
</div>

directory: 90-subsets-ii
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        
        output = []
        def backtrack(index, curr):
            output.append(curr[:])
            for i in range(index, n):
                if i != index and nums[i] == nums[i-1]:
                    continue
                else:
                    curr.append(nums[i])
                    backtrack(i + 1, curr)
                    curr.pop()
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/subsets-ii/">90. Subsets II</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> that may contain duplicates, return <em>all possible subsets (the power set)</em>.</p>

<p>The solution set <strong>must not</strong> contain duplicate subsets. Return the solution in <strong>any order</strong>.</p>

        output = []
                    continue
                else:
        
<pre><strong>Input:</strong> nums = [1,2,2]
<strong>Output:</strong> [[],[1],[1,2],[1,2,2],[2],[2,2]]
<pre><strong>Input:</strong> nums = [0]
<strong>Output:</strong> [[],[0]]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10</code></li>
</ul>
</div>

directory: 206-reverse-linked-list
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        
        if not head or not head.next:
            return head
        prev = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return prev
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reverse-linked-list/">206. Reverse Linked List</a></h2><h3>Easy</h3><hr><div><p>Given the <code>head</code> of a singly linked list, reverse the list, and return <em>the reversed list</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/rev1ex1.jpg" style="width: 542px; height: 222px;">
<pre><strong>Input:</strong> head = [1,2,3,4,5]
<strong>Output:</strong> [5,4,3,2,1]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/rev1ex2.jpg" style="width: 182px; height: 222px;">
<pre><strong>Input:</strong> head = [1,2]
<strong>Output:</strong> [2,1]
</pre>

<pre><strong>Input:</strong> head = []
</pre>

<ul>
	<li>The number of nodes in the list is the range <code>[0, 5000]</code>.</li>
	<li><code>-5000 &lt;= Node.val &lt;= 5000</code></li>
</ul>

<p><strong>Follow up:</strong> A linked list can be reversed either iteratively or recursively. Could you implement both?</p>
</div>

directory: 1342-number-of-steps-to-reduce-a-number-to-zero
    def numberOfSteps(self, num: int) -> int:
        
        steps = 0
        
        while num > 0:
            
            if num % 2 == 0:
                num = num // 2
            else:
                num = num - 1
            steps+=1
        
        return steps
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/">1342. Number of Steps to Reduce a Number to Zero</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>num</code>, return <em>the number of steps to reduce it to zero</em>.</p>

<p>In one step, if the current number is even, you have to divide it by <code>2</code>, otherwise, you have to subtract <code>1</code> from it.</p>

        steps = 0
        
            else:
                num = num - 1
            steps+=1
        
<pre><strong>Input:</strong> num = 14
<strong>Explanation:</strong>&nbsp;
Step 1) 14 is even; divide by 2 and obtain 7.&nbsp;
Step 2) 7 is odd; subtract 1 and obtain 6.
Step 3) 6 is even; divide by 2 and obtain 3.&nbsp;
Step 4) 3 is odd; subtract 1 and obtain 2.&nbsp;
Step 5) 2 is even; divide by 2 and obtain 1.&nbsp;
Step 6) 1 is odd; subtract 1 and obtain 0.
</pre>

<pre><strong>Input:</strong> num = 8
Step 1) 8 is even; divide by 2 and obtain 4.&nbsp;
Step 2) 4 is even; divide by 2 and obtain 2.&nbsp;
Step 3) 2 is even; divide by 2 and obtain 1.&nbsp;
Step 4) 1 is odd; subtract 1 and obtain 0.
</pre>

<pre><strong>Input:</strong> num = 123
<strong>Output:</strong> 12
</pre>

<ul>
	<li><code>0 &lt;= num &lt;= 10<sup>6</sup></code></li>
</ul>
</div>

directory: 19-remove-nth-node-from-end-of-list
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        # 1 2 3 4 5
        dummy = ListNode(0)
        fast, slow = head, head
        for _ in range(n):
            fast = fast.next
        if not fast:
            return head.next
        while fast.next:
        slow.next = slow.next.next 
Notes: if not head:
return None
dummy = ListNode(0)
dummy.next = head
count, curr = 0, head
while curr:
count += 1
curr = curr.next
curr = dummy
count -= n
while count > 0:
count -= 1
curr.next = curr.next.next
return dummy.next
Readme: <h2><a href="https://leetcode.com/problems/remove-nth-node-from-end-of-list/">19. Remove Nth Node From End of List</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a linked list, remove the <code>n<sup>th</sup></code> node from the end of the list and return its head.</p>

        # 1 2 3 4 5

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/remove_ex1.jpg" style="width: 542px; height: 222px;">
<pre><strong>Input:</strong> head = [1,2,3,4,5], n = 2
<strong>Output:</strong> [1,2,3,5]
</pre>

<pre><strong>Input:</strong> head = [1], n = 1
</pre>

<pre><strong>Input:</strong> head = [1,2], n = 1
</pre>

<ul>
	<li>The number of nodes in the list is <code>sz</code>.</li>
	<li><code>1 &lt;= sz &lt;= 30</code></li>
	<li><code>0 &lt;= Node.val &lt;= 100</code></li>
	<li><code>1 &lt;= n &lt;= sz</code></li>
</ul>

<p><strong>Follow up:</strong> Could you do this in one pass?</p>
</div>

directory: 235-lowest-common-ancestor-of-a-binary-search-tree
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """

        # Value of p
        p_val = p.val

        # Value of q
        q_val = q.val

        # Start from the root node of the tree
        node = root

        # Traverse the tree
        while node:

            # Value of current node or parent node.
            parent_val = node.val

        """
        """

        # Value of p

        # Value of q

        node = root

            if p_val > parent_val and q_val > parent_val:    
                # If both p and q are greater than parent
                node = node.right
            elif p_val < parent_val and q_val < parent_val:
                # If both p and q are lesser than parent
                node = node.left
            else:
                # We have found the split point, i.e. the LCA node.

if p_val > parent_val and q_val > parent_val:    
            else:
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/">235. Lowest Common Ancestor of a Binary Search Tree</a></h2><h3>Easy</h3><hr><div><p>Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.</p>

<p>According to the <a href="https://en.wikipedia.org/wiki/Lowest_common_ancestor" target="_blank">definition of LCA on Wikipedia</a>: “The lowest common ancestor is defined between two nodes <code>p</code> and <code>q</code> as the lowest node in <code>T</code> that has both <code>p</code> and <code>q</code> as descendants (where we allow <strong>a node to be a descendant of itself</strong>).”</p>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarysearchtree_improved.png" style="width: 200px; height: 190px;">
<pre><strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
<strong>Explanation:</strong> The LCA of nodes 2 and 8 is 6.
</pre>

<pre><strong>Input:</strong> root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
<strong>Explanation:</strong> The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.
</pre>

<pre><strong>Input:</strong> root = [2,1], p = 2, q = 1
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[2, 10<sup>5</sup>]</code>.</li>
	<li><code>-10<sup>9</sup> &lt;= Node.val &lt;= 10<sup>9</sup></code></li>
	<li>All <code>Node.val</code> are <strong>unique</strong>.</li>
	<li><code>p != q</code></li>
	<li><code>p</code> and <code>q</code> will exist in the BST.</li>
</ul>
</div>

directory: 1512-number-of-good-pairs
    def numIdenticalPairs(self, nums: List[int]) -> int:
        
        count = Counter(nums)
        ans = 0
        for v in count.values():
            ans += (v * (v-1)) // 2
        return ans
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/number-of-good-pairs/">1512. Number of Good Pairs</a></h2><h3>Easy</h3><hr><div><p>Given an array of integers <code>nums</code>, return <em>the number of <strong>good pairs</strong></em>.</p>

<p>A pair <code>(i, j)</code> is called <em>good</em> if <code>nums[i] == nums[j]</code> and <code>i</code> &lt; <code>j</code>.</p>

<pre><strong>Input:</strong> nums = [1,2,3,1,1,3]
<strong>Explanation:</strong> There are 4 good pairs (0,3), (0,4), (3,4), (2,5) 0-indexed.
</pre>

        ans = 0
        return ans

<pre><strong>Input:</strong> nums = [1,1,1,1]
<strong>Explanation:</strong> Each pair in the array are <em>good</em>.
</pre>

</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 100</code></li>
	<li><code>1 &lt;= nums[i] &lt;= 100</code></li>
</ul>
</div>

directory: 875-koko-eating-bananas
Python: import math
    def minEatingSpeed(self, piles: List[int], h: int) -> int:
        
        low, high = 1, max(piles)
        res = high
        while low <= high:
            mid = (high + low) // 2
            ans = 0
            for p in piles:
                ans += math.ceil(p/mid)
            if ans <=h:
                res = min(res, mid)
                high = mid - 1
            else:
                low = mid + 1
        return  res
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/koko-eating-bananas/">875. Koko Eating Bananas</a></h2><h3>Medium</h3><hr><div><p>Koko loves to eat bananas. There are <code>n</code> piles of bananas, the <code>i<sup>th</sup></code> pile has <code>piles[i]</code> bananas. The guards have gone and will come back in <code>h</code> hours.</p>

import math
        
        res = high
            ans = 0
            if ans <=h:
            else:
                low = mid + 1
        return  res

<p>Koko can decide her bananas-per-hour eating speed of <code>k</code>. Each hour, she chooses some pile of bananas and eats <code>k</code> bananas from that pile. If the pile has less than <code>k</code> bananas, she eats all of them instead and will not eat any more bananas during this hour.</p>

<p>Koko likes to eat slowly but still wants to finish eating all the bananas before the guards return.</p>

<p>Return <em>the minimum integer</em> <code>k</code> <em>such that she can eat all the bananas within</em> <code>h</code> <em>hours</em>.</p>

<pre><strong>Input:</strong> piles = [3,6,7,11], h = 8
</pre>

<pre><strong>Input:</strong> piles = [30,11,23,4,20], h = 5
<strong>Output:</strong> 30
</pre>

<pre><strong>Input:</strong> piles = [30,11,23,4,20], h = 6
<strong>Output:</strong> 23
</pre>

<ul>
	<li><code>1 &lt;= piles.length &lt;= 10<sup>4</sup></code></li>
	<li><code>piles.length &lt;= h &lt;= 10<sup>9</sup></code></li>
	<li><code>1 &lt;= piles[i] &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 733-flood-fill
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/flood-fill/">733. Flood Fill</a></h2><h3>Easy</h3><hr><div><p>An image is represented by an <code>m x n</code> integer grid <code>image</code> where <code>image[i][j]</code> represents the pixel value of the image.</p>

<p>You are also given three integers <code>sr</code>, <code>sc</code>, and <code>newColor</code>. You should perform a <strong>flood fill</strong> on the image starting from the pixel <code>image[sr][sc]</code>.</p>

<p>To perform a <strong>flood fill</strong>, consider the starting pixel, plus any pixels connected <strong>4-directionally</strong> to the starting pixel of the same color as the starting pixel, plus any pixels connected <strong>4-directionally</strong> to those pixels (also with the same color), and so on. Replace the color of all of the aforementioned pixels with <code>newColor</code>.</p>

<p>Return <em>the modified image after performing the flood fill</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/06/01/flood1-grid.jpg" style="width: 613px; height: 253px;">
<pre><strong>Input:</strong> image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2
<strong>Output:</strong> [[2,2,2],[2,2,0],[2,0,1]]
<strong>Explanation:</strong> From the center of the image with position (sr, sc) = (1, 1) (i.e., the red pixel), all pixels connected by a path of the same color as the starting pixel (i.e., the blue pixels) are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
</pre>

<pre><strong>Input:</strong> image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
<strong>Output:</strong> [[2,2,2],[2,2,2]]
</pre>

<ul>
	<li><code>m == image.length</code></li>
	<li><code>n == image[i].length</code></li>
	<li><code>0 &lt;= image[i][j], newColor &lt; 2<sup>16</sup></code></li>
	<li><code>0 &lt;= sr &lt;&nbsp;m</code></li>
	<li><code>0 &lt;= sc &lt;&nbsp;n</code></li>
</ul>
</div>

directory: 494-target-sum
    def findTargetSumWays(self, nums: List[int], target: int) -> int:
        
        def calculate(index, s):
            if index == len(nums) and s == target:
                return 1
            if index == len(nums):
                return 0
            return calculate(index + 1, s + nums[index]) + calculate(index + 1, s - nums[index])
            
        return calculate(0, 0)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/target-sum/">494. Target Sum</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code> and an integer <code>target</code>.</p>

<p>You want to build an <strong>expression</strong> out of nums by adding one of the symbols <code>'+'</code> and <code>'-'</code> before each integer in nums and then concatenate all the integers.</p>

                return 1
                return 0
            
<ul>
	<li>For example, if <code>nums = [2, 1]</code>, you can add a <code>'+'</code> before <code>2</code> and a <code>'-'</code> before <code>1</code> and concatenate them to build the expression <code>"+2-1"</code>.</li>
</ul>

<p>Return the number of different <strong>expressions</strong> that you can build, which evaluates to <code>target</code>.</p>

<pre><strong>Input:</strong> nums = [1,1,1,1,1], target = 3
<strong>Explanation:</strong> There are 5 ways to assign symbols to make the sum of nums be target 3.
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
</pre>

<pre><strong>Input:</strong> nums = [1], target = 1
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 20</code></li>
	<li><code>0 &lt;= sum(nums[i]) &lt;= 1000</code></li>
	<li><code>-1000 &lt;= target &lt;= 1000</code></li>
</ul>
</div>

directory: 1229-meeting-scheduler
    def minAvailableDuration(self, slots1: List[List[int]], slots2: List[List[int]], duration: int) -> List[int]:
        
        slots1.sort()
        slots2.sort()
        a, b, m, n = 0, 0, len(slots1), len(slots2)
        
        while a < m and b < n:
            start1, end1 = slots1[a]
            start2, end2 = slots2[b]
            #print(start1, end1, start2, end2)
            start = max(start1, start2)
            end = min(end1, end2)
            if start + duration <= end:
                return [start , start + duration]
            else:
                if end2 < end1:
                    b += 1
                else:
                    a += 1
        return []
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/meeting-scheduler/">1229. Meeting Scheduler</a></h2><h3>Medium</h3><hr><div><p>Given the availability time slots arrays <code>slots1</code> and <code>slots2</code> of two people and a meeting duration <code>duration</code>, return the <strong>earliest time slot</strong> that works for both of them and is of duration <code>duration</code>.</p>

            else:
                    b += 1
                else:
                    a += 1
        return []
        
<p>If there is no common time slot that satisfies the requirements, return an <strong>empty array</strong>.</p>

<p>The format of a time slot is an array of two elements <code>[start, end]</code> representing an inclusive time range from <code>start</code> to <code>end</code>.</p>

<p>It is guaranteed that no two availability slots of the same person intersect with each other. That is, for any two time slots <code>[start1, end1]</code> and <code>[start2, end2]</code> of the same person, either <code>start1 &gt; end2</code> or <code>start2 &gt; end1</code>.</p>

<pre><strong>Input:</strong> slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 8
<strong>Output:</strong> [60,68]
</pre>

<pre><strong>Input:</strong> slots1 = [[10,50],[60,120],[140,210]], slots2 = [[0,15],[60,70]], duration = 12
</pre>

<ul>
	<li><code>1 &lt;= slots1.length, slots2.length &lt;= 10<sup>4</sup></code></li>
	<li><code>slots1[i].length, slots2[i].length == 2</code></li>
	<li><code>slots1[i][0] &lt; slots1[i][1]</code></li>
	<li><code>slots2[i][0] &lt; slots2[i][1]</code></li>
	<li><code>0 &lt;= slots1[i][j], slots2[i][j] &lt;= 10<sup>9</sup></code></li>
	<li><code>1 &lt;= duration &lt;= 10<sup>6</sup></code></li>
</ul>
</div>

directory: 113-path-sum-ii
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
        output = []
        def dfs(root, path, currSum):
            if root:
                path.append(root.val)
                currSum += root.val
                if not root.right and not root.left and currSum == targetSum:
                    output.append(path[:])
                if root.left:
                    dfs(root.left, path, currSum)
                if root.right:
                    dfs(root.right, path, currSum)
                path.pop()
                currSum -= root.val
        dfs(root, [], 0)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/path-sum-ii/">113. Path Sum II</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>all <strong>root-to-leaf</strong> paths where the sum of the node values in the path equals </em><code>targetSum</code><em>. Each path should be returned as a list of the node <strong>values</strong>, not node references</em>.</p>

        output = []
            if root:

<p>A <strong>root-to-leaf</strong> path is a path starting from the root and ending at any leaf node. A <strong>leaf</strong> is a node with no children.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/pathsumii1.jpg" style="width: 500px; height: 356px;">
<pre><strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
<strong>Output:</strong> [[5,4,11,2],[5,8,4,5]]
<strong>Explanation:</strong> There are two paths whose sum equals targetSum:
5 + 4 + 11 + 2 = 22
5 + 8 + 4 + 5 = 22
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg" style="width: 212px; height: 181px;">
<pre><strong>Input:</strong> root = [1,2,3], targetSum = 5
</pre>

<pre><strong>Input:</strong> root = [1,2], targetSum = 0
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[0, 5000]</code>.</li>
	<li><code>-1000 &lt;= targetSum &lt;= 1000</code></li>
</ul>
</div>

directory: 703-kth-largest-element-in-a-stream
Python: import heapq
class KthLargest:
    def __init__(self, k: int, nums: List[int]):
        self.k = k
        self.heap = nums
        heapq.heapify(self.heap)
        while len(self.heap) > self.k:
            heapq.heappop(self.heap)
    def add(self, val: int) -> int:
        heapq.heappush(self.heap, val)
        if len(self.heap) > self.k:
        return self.heap[0]

# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/kth-largest-element-in-a-stream/">703. Kth Largest Element in a Stream</a></h2><h3>Easy</h3><hr><div><p>Design a class to find the <code>k<sup>th</sup></code> largest element in a stream. Note that it is the <code>k<sup>th</sup></code> largest element in the sorted order, not the <code>k<sup>th</sup></code> distinct element.</p>

        self.k = k

<p>Implement <code>KthLargest</code> class:</p>

<ul>
	<li><code>KthLargest(int k, int[] nums)</code> Initializes the object with the integer <code>k</code> and the stream of integers <code>nums</code>.</li>
	<li><code>int add(int val)</code> Appends the integer <code>val</code> to the stream and returns the element representing the <code>k<sup>th</sup></code> largest element in the stream.</li>
</ul>

["KthLargest", "add", "add", "add", "add", "add"]
[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]
[null, 4, 5, 5, 8, 8]

KthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);
kthLargest.add(3);   // return 4
kthLargest.add(5);   // return 5
kthLargest.add(10);  // return 5
kthLargest.add(9);   // return 8
kthLargest.add(4);   // return 8
</pre>

<ul>
	<li><code>1 &lt;= k &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= val &lt;= 10<sup>4</sup></code></li>
	<li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code>.</li>
	<li>It is guaranteed that there will be at least <code>k</code> elements in the array when you search for the <code>k<sup>th</sup></code> element.</li>
</ul>
</div>

directory: 1022-sum-of-root-to-leaf-binary-numbers
    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        self.sum = 0
        def dfs(root, curr_number):
            if not root:
                return
            else:
                curr_number = (curr_number << 1) | root.val
                if not root.left and not root.right:
                     self.sum += curr_number
                dfs(root.left, curr_number)
                dfs(root.right, curr_number)            
        return self.sum
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/">1022. Sum of Root To Leaf Binary Numbers</a></h2><h3>Easy</h3><hr><div><p>You are given the <code>root</code> of a binary tree where each node has a value <code>0</code> or <code>1</code>. Each root-to-leaf path represents a binary number starting with the most significant bit.</p>

                return
            else:

<ul>
	<li>For example, if the path is <code>0 -&gt; 1 -&gt; 1 -&gt; 0 -&gt; 1</code>, then this could represent <code>01101</code> in binary, which is <code>13</code>.</li>
</ul>

<p>For all leaves in the tree, consider the numbers represented by the path from the root to that leaf. Return <em>the sum of these numbers</em>.</p>

<p>The test cases are generated so that the answer fits in a <strong>32-bits</strong> integer.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2019/04/04/sum-of-root-to-leaf-binary-numbers.png" style="width: 400px; height: 263px;">
<pre><strong>Input:</strong> root = [1,0,1,0,1,0,1]
<strong>Output:</strong> 22
<strong>Explanation: </strong>(100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
</pre>

<pre><strong>Input:</strong> root = [0]
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 1000]</code>.</li>
	<li><code>Node.val</code> is <code>0</code> or <code>1</code>.</li>
</ul>
</div>

directory: 115-distinct-subsequences
    def numDistinct(self, s: str, t: str) -> int:
        
        n, m = len(s), len(t)
        dp = [[0 for _ in range(m+1)] for _ in range(n+1)]
        for i in range(n+1):
            dp[i][0] = 1
        for i in range(1, n+1):
            for j in range(1, m+1):
                if s[i-1] == t[j-1]:
                    dp[i][j] = dp[i-1][j] + dp[i-1][j-1]
                else:
                    dp[i][j] = dp[i-1][j]
        return dp[n][m]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/distinct-subsequences/">115. Distinct Subsequences</a></h2><h3>Hard</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code>, return <em>the number of distinct subsequences of <code>s</code> which equals <code>t</code></em>.</p>

                else:

<p>A string's <strong>subsequence</strong> is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters' relative positions. (i.e., <code>"ACE"</code> is a subsequence of <code>"ABCDE"</code> while <code>"AEC"</code> is not).</p>

<p>The test cases are generated so that the answer fits on a 32-bit signed integer.</p>

<pre><strong>Input:</strong> s = "rabbbit", t = "rabbit"
As shown below, there are 3 ways you can generate "rabbit" from S.
<code><strong><u>rabb</u></strong>b<strong><u>it</u></strong></code>
<code><strong><u>ra</u></strong>b<strong><u>bbit</u></strong></code>
<code><strong><u>rab</u></strong>b<strong><u>bit</u></strong></code>
</pre>

<pre><strong>Input:</strong> s = "babgbag", t = "bag"
As shown below, there are 5 ways you can generate "bag" from S.
<code><strong><u>ba</u></strong>b<u><strong>g</strong></u>bag</code>
<code><strong><u>ba</u></strong>bgba<strong><u>g</u></strong></code>
<code><u><strong>b</strong></u>abgb<strong><u>ag</u></strong></code>
<code>ba<u><strong>b</strong></u>gb<u><strong>ag</strong></u></code>
<code>babg<strong><u>bag</u></strong></code></pre>

<ul>
	<li><code>1 &lt;= s.length, t.length &lt;= 1000</code></li>
	<li><code>s</code> and <code>t</code> consist of English letters.</li>
</ul>
</div>

directory: 716-max-stack
Python: from sortedcontainers import SortedList
class MaxStack:

        self.stack = SortedList()
        self.values = SortedList()
        self.cnt = 0
        
    def push(self, x: int) -> None:
        self.stack.add((self.cnt, x))
        self.values.add((x, self.cnt))
        self.cnt += 1
        
    def pop(self) -> int:
        idx, val = self.stack.pop()
        self.values.remove((val, idx))
        return val
    def top(self) -> int:
        return self.stack[-1][1]
    
    def peekMax(self) -> int:
        return self.values[-1][0]
    
    def popMax(self) -> int:
        val, idx = self.values.pop()
        self.stack.remove((idx, val))
        return val

from sortedcontainers import SortedList

        return val
    
        return val

# Your MaxStack object will be instantiated and called as such:
# obj = MaxStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.peekMax()
# param_5 = obj.popMax()

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/max-stack/">716. Max Stack</a></h2><h3>Hard</h3><hr><div><p>Design a max stack data structure that supports the stack operations and supports finding the stack's maximum element.</p>

<p>Implement the <code>MaxStack</code> class:</p>

<ul>
	<li><code>MaxStack()</code> Initializes the stack object.</li>
	<li><code>void push(int x)</code> Pushes element <code>x</code> onto the stack.</li>
	<li><code>int pop()</code> Removes the element on top of the stack and returns it.</li>
	<li><code>int top()</code> Gets the element on the top of the stack without removing it.</li>
	<li><code>int peekMax()</code> Retrieves the maximum element in the stack without removing it.</li>
	<li><code>int popMax()</code> Retrieves the maximum element in the stack and removes it. If there is more than one maximum element, only remove the <strong>top-most</strong> one.</li>
</ul>

<p>You must come up with a solution that supports <code>O(1)</code> for each <code>top</code> call and <code>O(logn)</code> for each other call.</p>

["MaxStack", "push", "push", "push", "top", "popMax", "top", "peekMax", "pop", "top"]
[[], [5], [1], [5], [], [], [], [], [], []]
[null, null, null, null, 5, 5, 1, 5, 1, 5]

MaxStack stk = new MaxStack();
stk.push(5);   // [<strong><u>5</u></strong>] the top of the stack and the maximum number is 5.
stk.push(1);   // [<u>5</u>, <strong>1</strong>] the top of the stack is 1, but the maximum is 5.
stk.push(5);   // [5, 1, <strong><u>5</u></strong>] the top of the stack is 5, which is also the maximum, because it is the top most one.
stk.top();     // return 5, [5, 1, <strong><u>5</u></strong>] the stack did not change.
stk.popMax();  // return 5, [<u>5</u>, <strong>1</strong>] the stack is changed now, and the top is different from the max.
stk.top();     // return 1, [<u>5</u>, <strong>1</strong>] the stack did not change.
stk.peekMax(); // return 5, [<u>5</u>, <strong>1</strong>] the stack did not change.
stk.pop();     // return 1, [<strong><u>5</u></strong>] the top of the stack and the max element is now 5.
stk.top();     // return 5, [<strong><u>5</u></strong>] the stack did not change.
</pre>

<ul>
	<li><code>-10<sup>7</sup> &lt;= x &lt;= 10<sup>7</sup></code></li>
	<li>At most <code>10<sup>5</sup></code>&nbsp;calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, <code>peekMax</code>, and <code>popMax</code>.</li>
	<li>There will be <strong>at least one element</strong> in the stack when <code>pop</code>, <code>top</code>, <code>peekMax</code>, or <code>popMax</code> is called.</li>
</ul>
</div>

directory: 990-satisfiability-of-equality-equations
    def equationsPossible(self, equations: List[str]) -> bool:
        root = list(range(26))
        def find(x):
            if x != root[x]:
                root[x] = find(root[x])
            return root[x]
        
        def union(x, y):
            x, y = find(x), find(y)
            root[x] = y
        
        for eqn in equations:
            if eqn[1] == '=':
                x, y = ord(eqn[0])-ord('a'), ord(eqn[3])-ord('a')
                union(x, y)
            if eqn[1] == '!':
                if find(x) == find(y):
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/satisfiability-of-equality-equations/">990. Satisfiability of Equality Equations</a></h2><h3>Medium</h3><hr><div><p>You are given an array of strings <code>equations</code> that represent relationships between variables where each string <code>equations[i]</code> is of length <code>4</code> and takes one of two different forms: <code>"x<sub>i</sub>==y<sub>i</sub>"</code> or <code>"x<sub>i</sub>!=y<sub>i</sub>"</code>.Here, <code>x<sub>i</sub></code> and <code>y<sub>i</sub></code> are lowercase letters (not necessarily different) that represent one-letter variable names.</p>

            root[x] = y
        
<p>Return <code>true</code><em> if it is possible to assign integers to variable names so as to satisfy all the given equations, or </em><code>false</code><em> otherwise</em>.</p>

<pre><strong>Input:</strong> equations = ["a==b","b!=a"]
<strong>Explanation:</strong> If we assign say, a = 1 and b = 1, then the first equation is satisfied, but not the second.
There is no way to assign the variables to satisfy both equations.
</pre>

<pre><strong>Input:</strong> equations = ["b==a","a==b"]
<strong>Explanation:</strong> We could assign a = 1 and b = 1 to satisfy both equations.
</pre>

<ul>
	<li><code>1 &lt;= equations.length &lt;= 500</code></li>
	<li><code>equations[i].length == 4</code></li>
	<li><code>equations[i][0]</code> is a lowercase letter.</li>
	<li><code>equations[i][1]</code> is either <code>'='</code> or <code>'!'</code>.</li>
	<li><code>equations[i][2]</code> is <code>'='</code>.</li>
	<li><code>equations[i][3]</code> is a lowercase letter.</li>
</ul>
</div>

directory: 1064-fixed-point
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/fixed-point/">1064. Fixed Point</a></h2><h3>Easy</h3><hr><div><p>Given an array of distinct integers <code>arr</code>, where <code>arr</code> is sorted in <strong>ascending order</strong>, return the smallest index <code>i</code> that satisfies <code>arr[i] == i</code>. If there is no such index, return <code>-1</code>.</p>

<pre><strong>Input:</strong> arr = [-10,-5,0,3,7]
<strong>Explanation:</strong> For the given array, <code>arr[0] = -10, arr[1] = -5, arr[2] = 0, arr[3] = 3</code>, thus the output is 3.</pre>

<pre><strong>Input:</strong> arr = [0,2,5,8,17]
<strong>Explanation:</strong> <code>arr[0] = 0</code>, thus the output is 0.</pre>

<pre><strong>Input:</strong> arr = [-10,-5,3,4,7,9]
<strong>Explanation:</strong> There is no such <code>i</code> that <code>arr[i] == i</code>, thus the output is -1.</pre>

<ul>
	<li><code>1 &lt;= arr.length &lt; 10<sup>4</sup></code></li>
	<li><code>-10<sup>9</sup> &lt;= arr[i] &lt;= 10<sup>9</sup></code></li>
</ul>

<strong>Follow up:</strong> The <code>O(n)</code> solution is very straightforward. Can we do better?</div>

directory: 1137-n-th-tribonacci-number
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/n-th-tribonacci-number/">1137. N-th Tribonacci Number</a></h2><h3>Easy</h3><hr><div><p>The Tribonacci sequence T<sub>n</sub> is defined as follows:&nbsp;</p>

<p>T<sub>0</sub> = 0, T<sub>1</sub> = 1, T<sub>2</sub> = 1, and T<sub>n+3</sub> = T<sub>n</sub> + T<sub>n+1</sub> + T<sub>n+2</sub> for n &gt;= 0.</p>

<p>Given <code>n</code>, return the value of T<sub>n</sub>.</p>

<pre><strong>Input:</strong> n = 4
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
</pre>

<pre><strong>Input:</strong> n = 25
<strong>Output:</strong> 1389537
</pre>

<ul>
	<li><code>0 &lt;= n &lt;= 37</code></li>
	<li>The answer is guaranteed to fit within a 32-bit integer, ie. <code>answer &lt;= 2^31 - 1</code>.</li>

directory: 633-sum-of-square-numbers
    def judgeSquareSum(self, c: int) -> bool:
        
        def binary_search(left, right, number):
            if left > right:
            mid = (left + right) // 2
            if mid * mid == number:
            if mid * mid > number:
                return binary_search(left, mid - 1, number)
            return binary_search(mid + 1, right, number)
        
        a = 0
        while a * a <= c:
            b = c - a*a
            if binary_search(0, b, b): return True
            a += 1
        return False
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sum-of-square-numbers/">633. Sum of Square Numbers</a></h2><h3>Medium</h3><hr><div><p>Given a non-negative integer <code>c</code>, decide whether there're two integers <code>a</code> and <code>b</code> such that <code>a<sup>2</sup> + b<sup>2</sup> = c</code>.</p>

        a = 0
            b = c - a*a
            a += 1
            
<pre><strong>Input:</strong> c = 5
<strong>Explanation:</strong> 1 * 1 + 2 * 2 = 5
</pre>

<pre><strong>Input:</strong> c = 3
</pre>

<ul>
	<li><code>0 &lt;= c &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 173-binary-search-tree-iterator
class BSTIterator:
    
    def __init__(self, root):
        self.s = []
        self.cur = root
    
    def next(self) -> int:
        """
        @return the next smallest number
        """
        while self.cur is not None:
            self.s.append(self.cur)
            self.cur = self.cur.left
        self.cur = self.s.pop()
        value = self.cur.val
        self.cur = self.cur.right
        return value
    
    def hasNext(self) -> bool:
        return len(self.s) > 0 or self.cur

        self.s = []
    
        """
        """
    
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-search-tree-iterator/">173. Binary Search Tree Iterator</a></h2><h3>Medium</h3><hr><div><p>Implement the <code>BSTIterator</code> class that represents an iterator over the <strong><a href="https://en.wikipedia.org/wiki/Tree_traversal#In-order_(LNR)" target="_blank">in-order traversal</a></strong> of a binary search tree (BST):</p>

<ul>
	<li><code>BSTIterator(TreeNode root)</code> Initializes an object of the <code>BSTIterator</code> class. The <code>root</code> of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.</li>
	<li><code>boolean hasNext()</code> Returns <code>true</code> if there exists a number in the traversal to the right of the pointer, otherwise returns <code>false</code>.</li>
	<li><code>int next()</code> Moves the pointer to the right, then returns the number at the pointer.</li>
</ul>

<p>Notice that by initializing the pointer to a non-existent smallest number, the first call to <code>next()</code> will return the smallest element in the BST.</p>

<p>You may assume that <code>next()</code> calls will always be valid. That is, there will be at least a next number in the in-order traversal when <code>next()</code> is called.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/25/bst-tree.png" style="width: 189px; height: 178px;">
["BSTIterator", "next", "next", "hasNext", "next", "hasNext", "next", "hasNext", "next", "hasNext"]
[[[7, 3, 15, null, null, 9, 20]], [], [], [], [], [], [], [], [], []]
[null, 3, 7, true, 9, true, 15, true, 20, false]

BSTIterator bSTIterator = new BSTIterator([7, 3, 15, null, null, 9, 20]);
bSTIterator.next();    // return 3
bSTIterator.next();    // return 7
bSTIterator.hasNext(); // return True
bSTIterator.next();    // return 9
bSTIterator.next();    // return 15
bSTIterator.next();    // return 20
bSTIterator.hasNext(); // return False
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 10<sup>5</sup>]</code>.</li>
	<li><code>0 &lt;= Node.val &lt;= 10<sup>6</sup></code></li>
	<li>At most <code>10<sup>5</sup></code> calls will be made to <code>hasNext</code>, and <code>next</code>.</li>
</ul>

<ul>
	<li>Could you implement <code>next()</code> and <code>hasNext()</code> to run in average <code>O(1)</code> time and use&nbsp;<code>O(h)</code> memory, where <code>h</code> is the height of the tree?</li>
</ul>
</div>

directory: 22-generate-parentheses
    def generateParenthesis(self, n: int) -> List[str]:
        output = []
        def backtrack(s, l, r):
            if l == 0 and r == 0:
                output.append(s)
            if l != 0:
                backtrack(s + "(", l - 1, r)
            if r > l:
                backtrack(s + ")", l, r - 1)
        backtrack("", n, n)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/generate-parentheses/">22. Generate Parentheses</a></h2><h3>Medium</h3><hr><div><p>Given <code>n</code> pairs of parentheses, write a function to <em>generate all combinations of well-formed parentheses</em>.</p>

        output = []
            if l != 0:
            if r > l:
        
<pre><strong>Input:</strong> n = 3
<strong>Output:</strong> ["((()))","(()())","(())()","()(())","()()()"]
<strong>Output:</strong> ["()"]
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 8</code></li>
</ul>
</div>

directory: 0219-contains-duplicate-ii
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        
        dic = {}
        for i, n in enumerate(nums):
            if n in dic and abs(i - dic[n]) <= k:
            dic[n] = i
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/contains-duplicate-ii/">219. Contains Duplicate II</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> if there are two <strong>distinct indices</strong> <code>i</code> and <code>j</code> in the array such that <code>nums[i] == nums[j]</code> and <code>abs(i - j) &lt;= k</code>.</p>

<pre><strong>Input:</strong> nums = [1,2,3,1], k = 3
</pre>

        dic = {}
            dic[n] = i
        
<pre><strong>Input:</strong> nums = [1,0,1,1], k = 1
</pre>

<pre><strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2
</pre>

<ul>
	<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 547-number-of-provinces
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-provinces/">547. Number of Provinces</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> cities. Some of them are connected, while some are not. If city <code>a</code> is connected directly with city <code>b</code>, and city <code>b</code> is connected directly with city <code>c</code>, then city <code>a</code> is connected indirectly with city <code>c</code>.</p>

<p>A <strong>province</strong> is a group of directly or indirectly connected cities and no other cities outside of the group.</p>

<p>You are given an <code>n x n</code> matrix <code>isConnected</code> where <code>isConnected[i][j] = 1</code> if the <code>i<sup>th</sup></code> city and the <code>j<sup>th</sup></code> city are directly connected, and <code>isConnected[i][j] = 0</code> otherwise.</p>

<p>Return <em>the total number of <strong>provinces</strong></em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/24/graph1.jpg" style="width: 222px; height: 142px;">
<pre><strong>Input:</strong> isConnected = [[1,1,0],[1,1,0],[0,0,1]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/24/graph2.jpg" style="width: 222px; height: 142px;">
<pre><strong>Input:</strong> isConnected = [[1,0,0],[0,1,0],[0,0,1]]
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 200</code></li>
	<li><code>n == isConnected.length</code></li>
	<li><code>n == isConnected[i].length</code></li>
	<li><code>isConnected[i][j]</code> is <code>1</code> or <code>0</code>.</li>
	<li><code>isConnected[i][i] == 1</code></li>
	<li><code>isConnected[i][j] == isConnected[j][i]</code></li>
</ul>
</div>

directory: 2268-minimum-number-of-keypresses
    def minimumKeypresses(self, s: str) -> int:
        
        ans = 0
        start = 0
        count = sorted(Counter(s).values(), reverse = True)
        for i, frequency in enumerate(count):
            
            # If we are at an index that is the beginning or is overflowing the last 9th cell,
            # Then we start from the top.
            if i % 9 == 0:
                start += 1
            ans += start * frequency
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-number-of-keypresses/">2268. Minimum Number of Keypresses</a></h2><h3>Medium</h3><hr><div><p>You have a keypad with <code>9</code> buttons, numbered from <code>1</code> to <code>9</code>, each mapped to lowercase English letters. You can choose which characters each button is matched to as long as:</p>

        ans = 0
        start = 0
            
            if i % 9 == 0:
                start += 1
        return ans
        
<ul>
	<li>All 26 lowercase English letters are mapped to.</li>
	<li>Each character is mapped to by <strong>exactly</strong> <code>1</code> button.</li>
	<li>Each button maps to <strong>at most</strong> <code>3</code> characters.</li>
</ul>

<p>To type the first character matched to a button, you press the button once. To type the second character, you press the button twice, and so on.</p>

<p>Given a string <code>s</code>, return <em>the <strong>minimum</strong> number of keypresses needed to type </em><code>s</code><em> using your keypad.</em></p>

<p><strong>Note</strong> that the characters mapped to by each button, and the order they are mapped in cannot be changed.</p>

<img src="https://assets.leetcode.com/uploads/2022/05/05/image-20220505184346-1.png" style="width: 300px; height: 293px;">
<pre><strong>Input:</strong> s = "apple"
<strong>Explanation:</strong> One optimal way to setup your keypad is shown above.
Type 'a' by pressing button 1 once.
Type 'p' by pressing button 6 once.
Type 'l' by pressing button 5 once.
Type 'e' by pressing button 3 once.
A total of 5 button presses are needed, so return 5.
</pre>

<img src="https://assets.leetcode.com/uploads/2022/05/05/image-20220505203823-1.png" style="width: 300px; height: 288px;">
<pre><strong>Input:</strong> s = "abcdefghijkl"
The letters 'a' to 'i' can each be typed by pressing a button once.
Type 'j' by pressing button 1 twice.
Type 'k' by pressing button 2 twice.
Type 'l' by pressing button 3 twice.
A total of 15 button presses are needed, so return 15.
</pre>

<ul>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>
</div>

directory: 1470-shuffle-the-array
    def shuffle(self, nums: List[int], n: int) -> List[int]:
        
        ans = []
        left, right = 0, n
        while left < n:
            ans.append(nums[left])
            ans.append(nums[right])
            left += 1; right += 1;
        return ans
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/shuffle-the-array/">1470. Shuffle the Array</a></h2><h3>Easy</h3><hr><div><p>Given the array <code>nums</code> consisting of <code>2n</code> elements in the form <code>[x<sub>1</sub>,x<sub>2</sub>,...,x<sub>n</sub>,y<sub>1</sub>,y<sub>2</sub>,...,y<sub>n</sub>]</code>.</p>

<p><em>Return the array in the form</em> <code>[x<sub>1</sub>,y<sub>1</sub>,x<sub>2</sub>,y<sub>2</sub>,...,x<sub>n</sub>,y<sub>n</sub>]</code>.</p>

        ans = []
        return ans
        
<pre><strong>Input:</strong> nums = [2,5,1,3,4,7], n = 3
<strong>Output:</strong> [2,3,5,4,1,7] 
<strong>Explanation:</strong> Since x<sub>1</sub>=2, x<sub>2</sub>=5, x<sub>3</sub>=1, y<sub>1</sub>=3, y<sub>2</sub>=4, y<sub>3</sub>=7 then the answer is [2,3,5,4,1,7].
</pre>

<pre><strong>Input:</strong> nums = [1,2,3,4,4,3,2,1], n = 4
<strong>Output:</strong> [1,4,2,3,3,2,4,1]
</pre>

<pre><strong>Input:</strong> nums = [1,1,2,2], n = 2
<strong>Output:</strong> [1,2,1,2]
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 500</code></li>
	<li><code>nums.length == 2n</code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10^3</code></li>

directory: 182-duplicate-emails
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/duplicate-emails/">182. Duplicate Emails</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Person</code></p>

| id          | int     |
| email       | varchar |
Each row of this table contains an email. The emails will not contain uppercase letters.
</pre>

<p>Write an SQL query to report all the duplicate emails.</p>

Person table:
+----+---------+
| id | email   |
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+---------+
| Email   |
| a@b.com |
<strong>Explanation:</strong> a@b.com is repeated two times.
</pre>
</div>

directory: 1100-find-k-length-substrings-with-no-repeated-characters
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/find-k-length-substrings-with-no-repeated-characters/">1100. Find K-Length Substrings With No Repeated Characters</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the number of substrings in </em><code>s</code><em> of length </em><code>k</code><em> with no repeated characters</em>.</p>

<pre><strong>Input:</strong> s = "havefunonleetcode", k = 5
<strong>Explanation:</strong> There are 6 substrings they are: 'havef','avefu','vefun','efuno','etcod','tcode'.
</pre>

<pre><strong>Input:</strong> s = "home", k = 5
<strong>Explanation:</strong> Notice k can be larger than the length of s. In this case, it is not possible to find any substring.
</pre>

<ul>
</ul>
</div>

directory: 423-reconstruct-original-digits-from-english
    def originalDigits(self, s: str) -> str:
        
        c = Counter(s)
        n = [0] * 10
        
        n[0] = c['z']
        n[2] = c['w']
        n[4] = c['u']
        n[6] = c['x']
        n[8] = c['g']
        n[1] = c['o'] - n[0] - n[2] - n[4]
        n[3] = c['h'] - n[8] 
        n[5] = c['f'] - n[4]
        n[7] = c['s'] - n[6]
        n[9] = c['i'] - n[5] - n[6] - n[8]
        
        output = []
        
        for i in range(10):
            output.append(str(i) * n[i])
        return "".join(output)
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/reconstruct-original-digits-from-english/">423. Reconstruct Original Digits from English</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code> containing an out-of-order English representation of digits <code>0-9</code>, return <em>the digits in <strong>ascending</strong> order</em>.</p>

        n = [0] * 10
        
        output = []
        
<pre><strong>Input:</strong> s = "owoztneoer"
<strong>Output:</strong> "012"
<pre><strong>Input:</strong> s = "fviefuro"
<strong>Output:</strong> "45"
</pre>

<ul>
	<li><code>s[i]</code> is one of the characters <code>["e","g","f","i","h","o","n","s","r","u","t","w","v","x","z"]</code>.</li>
	<li><code>s</code> is <strong>guaranteed</strong> to be valid.</li>
</ul>
</div>

directory: 198-house-robber
    def rob(self, nums: List[int]) -> int:
        if len(nums) == 1:
            return nums[0]
        if len(nums) == 2:
            return max(nums[0], nums[1])
        n = len(nums) 
        dp = [0] * n
        dp[0] = nums[0]
        dp[1] = max(nums[0], nums[1])
        for i in range(2, n):
            dp[i] = max(dp[i-1], nums[i] + dp[i-2])
        return dp[-1]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/house-robber/">198. House Robber</a></h2><h3>Medium</h3><hr><div><p>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 <b>it will automatically contact the police if two adjacent houses were broken into on the same night</b>.</p>

        dp = [0] * n
        
<p>Given an integer array <code>nums</code> representing the amount of money of each house, return <em>the maximum amount of money you can rob tonight <b>without alerting the police</b></em>.</p>

<pre><strong>Input:</strong> nums = [1,2,3,1]
<strong>Explanation:</strong> Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
</pre>

<pre><strong>Input:</strong> nums = [2,7,9,3,1]
<strong>Explanation:</strong> Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
</pre>

<ul>
	<li><code>0 &lt;= nums[i] &lt;= 400</code></li>
</ul>
</div>

directory: 538-convert-bst-to-greater-tree
    def convertBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        
        curSum = 0
            nonlocal curSum
                return 
            dfs(node.right)
            tmp = node.val
            node.val += curSum
            curSum += tmp
            dfs(node.left)
        
        dfs(root)
        return root
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/convert-bst-to-greater-tree/">538. Convert BST to Greater Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.</p>

        curSum = 0
                return 
        
        dfs(root)
        
<p>As a reminder, a <em>binary search tree</em> is a tree that satisfies these constraints:</p>

<ul>
	<li>The left subtree of a node contains only nodes with keys <strong>less than</strong> the node's key.</li>
	<li>The right subtree of a node contains only nodes with keys <strong>greater than</strong> the node's key.</li>
	<li>Both the left and right subtrees must also be binary search trees.</li>
</ul>

<img alt="" src="https://assets.leetcode.com/uploads/2019/05/02/tree.png" style="width: 500px; height: 341px;">
<pre><strong>Input:</strong> root = [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
<strong>Output:</strong> [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
</pre>

<pre><strong>Input:</strong> root = [0,null,1]
<strong>Output:</strong> [1,null,1]
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
	<li>All the values in the tree are <strong>unique</strong>.</li>
</ul>

<p><strong>Note:</strong> This question is the same as 1038: <a href="https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/" target="_blank">https://leetcode.com/problems/binary-search-tree-to-greater-sum-tree/</a></p>
</div>

directory: 105-construct-binary-tree-from-preorder-and-inorder-traversal
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        
        dic = {}
        for i, n in enumerate(inorder):
            dic[n] = i
        index = 0
        def convert(left, right):
            nonlocal index
            if right < left:
            node = TreeNode(preorder[index])
            index += 1
            pivot = dic[node.val]
            node.left = convert(left, pivot-1)
            node.right = convert(pivot + 1, right)
            return node
        root = convert(0, len(preorder)-1)
Notes: ​

        dic = {}
            dic[n] = i
        index = 0
            index += 1
        
</pre>

</pre>

<ul>
</ul>
</div>

directory: 227-basic-calculator-ii
    def calculate(self, s: str) -> int:
        stack = []
        s = ''.join(s.split())
        n = len(s); i = 0
        sign = 1
        while i < n:
            if s[i].isnumeric():
                num = ''
                while i < n and s[i].isnumeric():
                    num += s[i]
                    i+=1
                stack.append(sign * int(num))
                sign = 1
            else:
                if s[i] in '*/':
                    operation = s[i]; i+=1
                    num1 = stack.pop(); num2 = ''
                    while i < n and s[i].isnumeric():
                        num2 += s[i]
                        i+=1
                    if operation == '*':
                        stack.append(num1 * int(num2))
                        sign = 1
                    else:
                        stack.append(int(num1 / int(num2)))
                        sign = 1
                else:
                    if s[i] == '-':
                        sign = -1
                    i+=1
        return sum(stack)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/basic-calculator-ii/">227. Basic Calculator II</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code> which represents an expression, <em>evaluate this expression and return its value</em>.&nbsp;</p>

        stack = []
        sign = 1
        while i < n:
                num = ''
                    num += s[i]
                    i+=1
                sign = 1
            else:
                        i+=1
                        sign = 1
                    else:
                        sign = 1
                else:
                        sign = -1
                    i+=1
        
<p>The integer division should truncate toward zero.</p>

<p>You may assume that the given expression is always valid. All intermediate results will be in the range of <code>[-2<sup>31</sup>, 2<sup>31</sup> - 1]</code>.</p>

<p><strong>Note:</strong> You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>

<pre><strong>Input:</strong> s = "3+2*2"
<pre><strong>Input:</strong> s = " 3/2 "
</pre><p><strong>Example 3:</strong></p>
<pre><strong>Input:</strong> s = " 3+5 / 2 "
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 3 * 10<sup>5</sup></code></li>
	<li><code>s</code> consists of integers and operators <code>('+', '-', '*', '/')</code> separated by some number of spaces.</li>
	<li><code>s</code> represents <strong>a valid expression</strong>.</li>
	<li>All the integers in the expression are non-negative integers in the range <code>[0, 2<sup>31</sup> - 1]</code>.</li>
	<li>The answer is <strong>guaranteed</strong> to fit in a <strong>32-bit integer</strong>.</li>
</ul>
</div>

directory: 34-find-first-and-last-position-of-element-in-sorted-array
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        
        def binary_search(left, right, is_first):
            while left <= right:
                mid = (left + right) // 2
                if nums[mid] == target:
                    if is_first:
                        if mid == left or nums[mid-1] < target:
                            # This is the first element
                            return mid
                        right = mid - 1
                    else:
                        if mid == right or nums[mid + 1] > target:
                            return mid
                        left = mid + 1
                        
                elif nums[mid] > target:
                    right = mid - 1
                else:
                    left = mid + 1
                    
            return -1
        ans = [binary_search(0,n-1,True), binary_search(0,n-1,False)]
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/">34. Find First and Last Position of Element in Sorted Array</a></h2><h3>Medium</h3><hr><div><p>Given an array of integers <code>nums</code> sorted in non-decreasing order, find the starting and ending position of a given <code>target</code> value.</p>

                            return mid
                    else:
                            return mid
                        
                else:
                    
            return -1
        return ans
        
<p>If <code>target</code> is not found in the array, return <code>[-1, -1]</code>.</p>

<p>You must&nbsp;write an algorithm with&nbsp;<code>O(log n)</code> runtime complexity.</p>

<pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 8
<strong>Output:</strong> [3,4]
<pre><strong>Input:</strong> nums = [5,7,7,8,8,10], target = 6
<strong>Output:</strong> [-1,-1]
<pre><strong>Input:</strong> nums = [], target = 0
</pre>

<ul>
	<li><code>0 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>9</sup>&nbsp;&lt;= nums[i]&nbsp;&lt;= 10<sup>9</sup></code></li>
	<li><code>nums</code> is a non-decreasing array.</li>
	<li><code>-10<sup>9</sup>&nbsp;&lt;= target&nbsp;&lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 238-product-of-array-except-self
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        
        p = 1
        prods = []
            prods.append(p)
            p = num * p
        #print(prods)
        p = 1
        for i in range(len(nums)-1, -1, -1):
            prods[i] *= p 
            p*=nums[i]
        return prods
Notes: product = 1
res = []
for i, num in enumerate(nums):
res.append(product)
product = product * nums[i]
#print(res)
product = 1
for i in range(len(nums)-1, -1, -1):
res[i] *= product
product *= nums[i]
print(res, product)
return res
Readme: <h2><a href="https://leetcode.com/problems/product-of-array-except-self/">238. Product of Array Except Self</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, return <em>an array</em> <code>answer</code> <em>such that</em> <code>answer[i]</code> <em>is equal to the product of all the elements of</em> <code>nums</code> <em>except</em> <code>nums[i]</code>.</p>

        p = 1
        prods = []
            p = num * p
        p = 1
        
<p>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</p>

<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time and without using the division operation.</p>

<strong>Output:</strong> [24,12,8,6]
<pre><strong>Input:</strong> nums = [-1,1,0,-3,3]
<strong>Output:</strong> [0,0,9,0,0]
</pre>

<ul>
	<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-30 &lt;= nums[i] &lt;= 30</code></li>
	<li>The product of any prefix or suffix of <code>nums</code> is <strong>guaranteed</strong> to fit in a <strong>32-bit</strong> integer.</li>
</ul>

<p><strong>Follow up:</strong>&nbsp;Can you solve the problem in <code>O(1)&nbsp;</code>extra&nbsp;space complexity? (The output array <strong>does not</strong> count as extra space for space complexity analysis.)</p>
</div>

directory: 1163-last-substring-in-lexicographical-order
    def lastSubstring(self, s: str) -> str:
        i, j, k = 0, 1, 0
        n = len(s)
        while j + k < n:
            if s[i+k] == s[j+k]:
                k += 1
                continue
            elif s[i+k] > s[j+k]:
                j = j + k + 1
            else:
                i = max(i + k + 1, j)
                j = i + 1
            k = 0
        return s[i:]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/last-substring-in-lexicographical-order/">1163. Last Substring in Lexicographical Order</a></h2><h3>Hard</h3><hr><div><p>Given a string <code>s</code>, return <em>the last substring of</em> <code>s</code> <em>in lexicographical order</em>.</p>

        n = len(s)
                k += 1
                continue
                j = j + k + 1
            else:
                j = i + 1
            k = 0

<pre><strong>Input:</strong> s = "abab"
<strong>Output:</strong> "bab"
<strong>Explanation:</strong> The substrings are ["a", "ab", "aba", "abab", "b", "ba", "bab"]. The lexicographically maximum substring is "bab".
</pre>

<pre><strong>Input:</strong> s = "leetcode"
<strong>Output:</strong> "tcode"
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 4 * 10<sup>5</sup></code></li>
	<li><code>s</code> contains only lowercase English letters.</li>
</ul>
</div>

directory: 311-sparse-matrix-multiplication
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sparse-matrix-multiplication/">311. Sparse Matrix Multiplication</a></h2><h3>Medium</h3><hr><div><p>Given two <a href="https://en.wikipedia.org/wiki/Sparse_matrix" target="_blank">sparse matrices</a> <code>mat1</code> of size <code>m x k</code> and <code>mat2</code> of size <code>k x n</code>, return the result of <code>mat1 x mat2</code>. You may assume that multiplication is always possible.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/mult-grid.jpg" style="width: 500px; height: 142px;">
<pre><strong>Input:</strong> mat1 = [[1,0,0],[-1,0,3]], mat2 = [[7,0,0],[0,0,0],[0,0,1]]
<strong>Output:</strong> [[7,0,0],[-7,0,3]]
</pre>

<pre><strong>Input:</strong> mat1 = [[0]], mat2 = [[0]]
<strong>Output:</strong> [[0]]
</pre>

<ul>
	<li><code>m == mat1.length</code></li>
	<li><code>k == mat1[i].length == mat2.length</code></li>
	<li><code>n == mat2[i].length</code></li>
	<li><code>1 &lt;= m, n, k &lt;= 100</code></li>
	<li><code>-100 &lt;= mat1[i][j], mat2[i][j] &lt;= 100</code></li>
</ul>
</div>

directory: 112-path-sum
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        
        def dfs(root, currentSum):
            if root:
                currentSum += root.val
                if currentSum == targetSum and not root.left and not root.right:
            return dfs(root.left, currentSum) or dfs(root.right, currentSum)
                
        return dfs(root, 0)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/path-sum/">112. Path Sum</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <code>true</code> if the tree has a <strong>root-to-leaf</strong> path such that adding up all the values along the path equals <code>targetSum</code>.</p>

            if root:
                
<p>A <strong>leaf</strong> is a node with no children.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/pathsum1.jpg" style="width: 500px; height: 356px;">
<pre><strong>Input:</strong> root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
<strong>Explanation:</strong> The root-to-leaf path with the target sum is shown.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/18/pathsum2.jpg">
<strong>Explanation:</strong> There two root-to-leaf paths in the tree:
(1 --&gt; 2): The sum is 3.
(1 --&gt; 3): The sum is 4.
There is no root-to-leaf path with sum = 5.
</pre>

<pre><strong>Input:</strong> root = [], targetSum = 0
<strong>Explanation:</strong> Since the tree is empty, there are no root-to-leaf paths.
</pre>

<ul>
</ul>
</div>

directory: 627-swap-salary
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/swap-salary/">627. Swap Salary</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Salary</code></p>

<pre>+-------------+----------+
| Column Name | Type     |
+-------------+----------+
| id          | int      |
| name        | varchar  |
| sex         | ENUM     |
| salary      | int      |
id is the primary key for this table.
The sex column is ENUM value of type ('m', 'f').
The table contains information about an employee.
</pre>

<p>Write an SQL query to swap all <code>'f'</code> and <code>'m'</code> values (i.e., change all <code>'f'</code> values to <code>'m'</code> and vice versa) with a <strong>single update statement</strong> and no intermediate temporary tables.</p>

<p>Note that you must write a single update statement, <strong>do not</strong> write any select statement for this problem.</p>

Salary table:
+----+------+-----+--------+
| id | name | sex | salary |
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |
(1, A) and (3, C) were changed from 'm' to 'f'.
(2, B) and (4, D) were changed from 'f' to 'm'.
</pre>
</div>

directory: 1920-build-array-from-permutation
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/build-array-from-permutation/">1920. Build Array from Permutation</a></h2><h3>Easy</h3><hr><div><p>Given a <strong>zero-based permutation</strong> <code>nums</code> (<strong>0-indexed</strong>), build an array <code>ans</code> of the <strong>same length</strong> where <code>ans[i] = nums[nums[i]]</code> for each <code>0 &lt;= i &lt; nums.length</code> and return it.</p>

<p>A <strong>zero-based permutation</strong> <code>nums</code> is an array of <strong>distinct</strong> integers from <code>0</code> to <code>nums.length - 1</code> (<strong>inclusive</strong>).</p>

<pre><strong>Input:</strong> nums = [0,2,1,5,3,4]
<strong>Output:</strong> [0,1,2,4,5,3]<strong>
Explanation:</strong> The array ans is built as follows: 
ans = [nums[nums[0]], nums[nums[1]], nums[nums[2]], nums[nums[3]], nums[nums[4]], nums[nums[5]]]
    = [nums[0], nums[2], nums[1], nums[5], nums[3], nums[4]]
    = [0,1,2,4,5,3]</pre>

<pre><strong>Input:</strong> nums = [5,0,1,2,3,4]
<strong>Output:</strong> [4,5,0,1,2,3]
<strong>Explanation:</strong> The array ans is built as follows:
    = [nums[5], nums[0], nums[1], nums[2], nums[3], nums[4]]
    = [4,5,0,1,2,3]</pre>

<ul>
	<li><code>0 &lt;= nums[i] &lt; nums.length</code></li>
	<li>The elements in <code>nums</code> are <strong>distinct</strong>.</li>
</ul>

<p><strong>Follow-up:</strong> Can you solve it without using an extra space (i.e., <code>O(1)</code> memory)?</p>
</div>

directory: 1656-design-an-ordered-stream
Python: class OrderedStream:
    def __init__(self, n: int):
        self.arr = [None]*(n)
        self.index = 0
    def insert(self, idKey: int, value: str) -> List[str]:
        self.arr[idKey - 1] = value
        ans = []
        while self.index < len(self.arr) and self.arr[self.index]:
            ans.append(self.arr[self.index])
            self.index += 1
        return ans
# Your OrderedStream object will be instantiated and called as such:
# obj = OrderedStream(n)
# param_1 = obj.insert(idKey,value)
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/design-an-ordered-stream/">1656. Design an Ordered Stream</a></h2><h3>Easy</h3><hr><div><p>There is a stream of <code>n</code> <code>(idKey, value)</code> pairs arriving in an <strong>arbitrary</strong> order, where <code>idKey</code> is an integer between <code>1</code> and <code>n</code> and <code>value</code> is a string. No two pairs have the same <code>id</code>.</p>

class OrderedStream:
        ans = []
        return ans

<p>Design a stream that returns the values in <strong>increasing order of their IDs</strong> by returning a <strong>chunk</strong> (list) of values after each insertion. The concatenation of all the <strong>chunks</strong> should result in a list of the sorted values.</p>

<p>Implement the <code>OrderedStream</code> class:</p>

<ul>
	<li><code>OrderedStream(int n)</code> Constructs the stream to take <code>n</code> values.</li>
	<li><code>String[] insert(int idKey, String value)</code> Inserts the pair <code>(idKey, value)</code> into the stream, then returns the <strong>largest possible chunk</strong> of currently inserted values that appear next in the order.</li>
</ul>

<p><strong>Example:</strong></p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/11/10/q1.gif" style="width: 682px; height: 240px;"></strong></p>

["OrderedStream", "insert", "insert", "insert", "insert", "insert"]
[[5], [3, "ccccc"], [1, "aaaaa"], [2, "bbbbb"], [5, "eeeee"], [4, "ddddd"]]
[null, [], ["aaaaa"], ["bbbbb", "ccccc"], [], ["ddddd", "eeeee"]]

// Note that the values ordered by ID is ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"].
OrderedStream os = new OrderedStream(5);
os.insert(3, "ccccc"); // Inserts (3, "ccccc"), returns [].
os.insert(1, "aaaaa"); // Inserts (1, "aaaaa"), returns ["aaaaa"].
os.insert(2, "bbbbb"); // Inserts (2, "bbbbb"), returns ["bbbbb", "ccccc"].
os.insert(5, "eeeee"); // Inserts (5, "eeeee"), returns [].
os.insert(4, "ddddd"); // Inserts (4, "ddddd"), returns ["ddddd", "eeeee"].
// Concatentating all the chunks returned:
// [] + ["aaaaa"] + ["bbbbb", "ccccc"] + [] + ["ddddd", "eeeee"] = ["aaaaa", "bbbbb", "ccccc", "ddddd", "eeeee"]
// The resulting order is the same as the order above.
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 1000</code></li>
	<li><code>1 &lt;= id &lt;= n</code></li>
	<li><code>value.length == 5</code></li>
	<li><code>value</code>&nbsp;consists only of lowercase letters.</li>
	<li>Each call to <code>insert</code>&nbsp;will have a unique <code>id.</code></li>
	<li>Exactly <code>n</code> calls will be made to <code>insert</code>.</li>
</ul>
</div>

directory: 258-add-digits
    def addDigits(self, num):
        """
        :type num: int
        """
        ans = 0
            ans += num % 10
            num = num // 10
            
            if num == 0 and ans > 9:
                num = ans
                ans = 0
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/add-digits/">258. Add Digits</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>num</code>, repeatedly add all its digits until the result has only one digit, and return it.</p>

<pre><strong>Input:</strong> num = 38
<strong>Explanation:</strong> The process is
38 --&gt; 3 + 8 --&gt; 11
11 --&gt; 1 + 1 --&gt; 2 
Since 2 has only one digit, return it.
</pre>

<pre><strong>Input:</strong> num = 0
</pre>

        """
        """
        ans = 0
            
                num = ans
                ans = 0
        return ans

<ul>
	<li><code>0 &lt;= num &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

<p><strong>Follow up:</strong> Could you do it without any loop/recursion in <code>O(1)</code> runtime?</p>
</div>

directory: 0430-flatten-a-multilevel-doubly-linked-list
Python: 
Notes: class Solution:
def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
current = head
while current:
if current.child:
self.merge(current)
current = current.next
return head
def merge(self, current):
child = current.child
while child.next:
child = child.next
if current.next:
child.next = current.next
current.next.prev = child
current.next = current.child
current.child.prev = current
current.child = None
Readme: <h2><a href="https://leetcode.com/problems/flatten-a-multilevel-doubly-linked-list/">430. Flatten a Multilevel Doubly Linked List</a></h2><h3>Medium</h3><hr><div><p>You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional <strong>child pointer</strong>. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a <strong>multilevel data structure</strong> as shown in the example below.</p>

<p>Given the <code>head</code> of the first level of the list, <strong>flatten</strong> the list so that all the nodes appear in a single-level, doubly linked list. Let <code>curr</code> be a node with a child list. The nodes in the child list should appear <strong>after</strong> <code>curr</code> and <strong>before</strong> <code>curr.next</code> in the flattened list.</p>

<p>Return <em>the </em><code>head</code><em> of the flattened list. The nodes in the list must have <strong>all</strong> of their child pointers set to </em><code>null</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/09/flatten11.jpg" style="width: 700px; height: 339px;">
<pre><strong>Input:</strong> head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
<strong>Output:</strong> [1,2,3,7,8,11,12,9,10,4,5,6]
<strong>Explanation:</strong> The multilevel linked list in the input is shown.
After flattening the multilevel linked list it becomes:
<img src="https://assets.leetcode.com/uploads/2021/11/09/flatten12.jpg" style="width: 1000px; height: 69px;">
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/09/flatten2.1jpg" style="width: 200px; height: 200px;">
<pre><strong>Input:</strong> head = [1,2,null,3]
<img src="https://assets.leetcode.com/uploads/2021/11/24/list.jpg" style="width: 300px; height: 87px;">
</pre>

<strong>Explanation:</strong> There could be empty list in the input.
</pre>

<ul>
	<li>The number of Nodes will not exceed <code>1000</code>.</li>
</ul>

<p><strong>How the multilevel linked list is represented in test cases:</strong></p>

<p>We use the multilevel linked list from <strong class="example">Example 1</strong> above:</p>

<pre> 1---2---3---4---5---6--NULL
         |
         7---8---9---10--NULL
             |
             11--12--NULL</pre>

<p>The serialization of each level is as follows:</p>

<pre>[1,2,3,4,5,6,null]
[7,8,9,10,null]
[11,12,null]
</pre>

<p>To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes:</p>

<pre>[1,    2,    3, 4, 5, 6, null]
             |
[null, null, 7,    8, 9, 10, null]
                   |
[            null, 11, 12, null]
</pre>

<p>Merging the serialization of each level and removing trailing nulls we obtain:</p>

<pre>[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12]
</pre>
</div>

directory: 729-my-calendar-i

class MyCalendar:
    def __init__(self):        
        self.calendar = SortedList()
        
    def book(self, start: int, end: int) -> bool:
        index = bisect.bisect_right(self.calendar, (start, end))
        
        if (index > 0 and self.calendar[index-1][1] > start) or (index < len(self.calendar) and self.calendar[index][0] < end):
        self.calendar.add((start, end))
        
# Your MyCalendar object will be instantiated and called as such:
# obj = MyCalendar()
# param_1 = obj.book(start,end)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/my-calendar-i/">729. My Calendar I</a></h2><h3>Medium</h3><hr><div><p>You are implementing a program to use as your calendar. We can add a new event if adding the event will not cause a <strong>double booking</strong>.</p>

<p>A <strong>double booking</strong> happens when two events have some non-empty intersection (i.e., some moment is common to both events.).</p>

<p>The event can be represented as a pair of integers <code>start</code> and <code>end</code> that represents a booking on the half-open interval <code>[start, end)</code>, the range of real numbers <code>x</code> such that <code>start &lt;= x &lt; end</code>.</p>

<p>Implement the <code>MyCalendar</code> class:</p>

<ul>
	<li><code>MyCalendar()</code> Initializes the calendar object.</li>
	<li><code>boolean book(int start, int end)</code> Returns <code>true</code> if the event can be added to the calendar successfully without causing a <strong>double booking</strong>. Otherwise, return <code>false</code> and do not add the event to the calendar.</li>
</ul>

["MyCalendar", "book", "book", "book"]
[[], [10, 20], [15, 25], [20, 30]]
[null, true, false, true]

MyCalendar myCalendar = new MyCalendar();
myCalendar.book(10, 20); // return True
myCalendar.book(15, 25); // return False, It can not be booked because time 15 is already booked by another event.
myCalendar.book(20, 30); // return True, The event can be booked, as the first event takes every time less than 20, but not including 20.</pre>

<ul>
	<li><code>0 &lt;= start &lt; end &lt;= 10<sup>9</sup></code></li>
	<li>At most <code>1000</code> calls will be made to <code>book</code>.</li>
</ul>
</div>

directory: 316-remove-duplicate-letters
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/remove-duplicate-letters/">316. Remove Duplicate Letters</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, remove duplicate letters so that every letter appears once and only once. You must make sure your result is <strong>the smallest in lexicographical order</strong> among all possible results.</p>

<pre><strong>Input:</strong> s = "bcabc"
<strong>Output:</strong> "abc"
</pre>

<pre><strong>Input:</strong> s = "cbacdcbc"
<strong>Output:</strong> "acdb"
</pre>

<ul>
</ul>

<p><strong>Note:</strong> This question is the same as 1081: <a href="https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/" target="_blank">https://leetcode.com/problems/smallest-subsequence-of-distinct-characters/</a></p>
</div>

directory: 545-boundary-of-binary-tree
    def boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
        
        self.res = []
            return self.res
        if not self.isLeaf(root):
            self.res.append(root.val)
        
        t = root.left
        while t:
            if not self.isLeaf(t):
                self.res.append(t.val)
            if t.left:
                t = t.left
            else:
                t = t.right
        self.addLeaves(root)
        
        stack = []
        
        t = root.right
        while t:
                stack.append(t.val)
            if t.right:
                t = t.right
            else:
                t = t.left
        while stack:
            self.res.append(stack.pop())
        
        return self.res
        
    def isLeaf(self, root):
        return root.left == None and root.right == None
    
    def addLeaves(self, root):
        if self.isLeaf(root):
        else:
            if root.left:
                self.addLeaves(root.left)
            if root.right:
                self.addLeaves(root.right)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/boundary-of-binary-tree/">545. Boundary of Binary Tree</a></h2><h3>Medium</h3><hr><div><p>The <strong>boundary</strong> of a binary tree is the concatenation of the <strong>root</strong>, the <strong>left boundary</strong>, the <strong>leaves</strong> ordered from left-to-right, and the <strong>reverse order</strong> of the <strong>right boundary</strong>.</p>

        while t:
            if t.left:
                t = t.left
            else:
                t = t.right
        
        stack = []
        
        while t:
                t = t.right
            else:
                t = t.left
        
        else:
    
<p>The <strong>left boundary</strong> is the set of nodes defined by the following:</p>

<ul>
	<li>The root node's left child is in the left boundary. If the root does not have a left child, then the left boundary is <strong>empty</strong>.</li>
	<li>If a node in the left boundary and has a left child, then the left child is in the left boundary.</li>
	<li>If a node is in the left boundary, has <strong>no</strong> left child, but has a right child, then the right child is in the left boundary.</li>
	<li>The leftmost leaf is <strong>not</strong> in the left boundary.</li>
</ul>

<p>The <strong>right boundary</strong> is similar to the <strong>left boundary</strong>, except it is the right side of the root's right subtree. Again, the leaf is <strong>not</strong> part of the <strong>right boundary</strong>, and the <strong>right boundary</strong> is empty if the root does not have a right child.</p>

<p>The <strong>leaves</strong> are nodes that do not have any children. For this problem, the root is <strong>not</strong> a leaf.</p>

<p>Given the <code>root</code> of a binary tree, return <em>the values of its <strong>boundary</strong></em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/11/boundary1.jpg" style="width: 299px; height: 290px;">
<pre><strong>Input:</strong> root = [1,null,2,3,4]
<strong>Output:</strong> [1,3,4,2]
<b>Explanation:</b>
- The left boundary is empty because the root does not have a left child.
- The right boundary follows the path starting from the root's right child 2 -&gt; 4.
  4 is a leaf, so the right boundary is [2].
- The leaves from left to right are [3,4].
Concatenating everything results in [1] + [] + [3,4] + [2] = [1,3,4,2].
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/11/boundary2.jpg" style="width: 599px; height: 411px;">
<pre><strong>Input:</strong> root = [1,2,3,4,5,6,null,null,null,7,8,9,10]
<strong>Output:</strong> [1,2,4,7,8,9,10,6,3]
- The left boundary follows the path starting from the root's left child 2 -&gt; 4.
  4 is a leaf, so the left boundary is [2].
- The right boundary follows the path starting from the root's right child 3 -&gt; 6 -&gt; 10.
  10 is a leaf, so the right boundary is [3,6], and in reverse order is [6,3].
- The leaves from left to right are [4,7,8,9,10].
Concatenating everything results in [1] + [2] + [4,7,8,9,10] + [6,3] = [1,2,4,7,8,9,10,6,3].
</pre>

<ul>
</ul>
</div>

directory: 606-construct-string-from-binary-tree
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/construct-string-from-binary-tree/">606. Construct String from Binary Tree</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, construct a string consisting of parenthesis and integers from a binary tree with the preorder traversal way, and return it.</p>

<p>Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/05/03/cons1-tree.jpg" style="width: 292px; height: 301px;">
<pre><strong>Input:</strong> root = [1,2,3,4]
<strong>Output:</strong> "1(2(4))(3)"
<strong>Explanation:</strong> Originally, it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)"
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/05/03/cons2-tree.jpg" style="width: 207px; height: 293px;">
<pre><strong>Input:</strong> root = [1,2,3,null,4]
<strong>Output:</strong> "1(2()(4))(3)"
<strong>Explanation:</strong> Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
</pre>

<ul>
</ul>
</div>

directory: 1339-maximum-product-of-splitted-binary-tree
    def maxProduct(self, root: Optional[TreeNode]) -> int:
        s = 0
        def dfs1(root):
            nonlocal s
            if root:
                s += root.val
                dfs1(root.left)
                dfs1(root.right)
        dfs1(root)
        ans = 0
        
        def dfs2(root):
            nonlocal ans
                return 0
            left = dfs2(root.left)
            right = dfs2(root.right)
            subtree_sum = root.val + left + right
            ans = max(ans, (s-subtree_sum) * subtree_sum)
            return subtree_sum
        dfs2(root)
        return ans % (10**9 + 7)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-product-of-splitted-binary-tree/">1339. Maximum Product of Splitted Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, split the binary tree into two subtrees by removing one edge such that the product of the sums of the subtrees is maximized.</p>

        s = 0
            nonlocal s
            if root:
        ans = 0
        
                return 0

<p>Return <em>the maximum product of the sums of the two subtrees</em>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p><strong>Note</strong> that you need to maximize the answer before taking the mod and not after taking it.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/01/21/sample_1_1699.png" style="width: 500px; height: 167px;">
<pre><strong>Input:</strong> root = [1,2,3,4,5,6]
<strong>Output:</strong> 110
<strong>Explanation:</strong> Remove the red edge and get 2 binary trees with sum 11 and 10. Their product is 110 (11*10)
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/01/21/sample_2_1699.png" style="width: 500px; height: 211px;">
<pre><strong>Input:</strong> root = [1,null,2,3,4,null,null,5,6]
<strong>Output:</strong> 90
<strong>Explanation:</strong> Remove the red edge and get 2 binary trees with sum 15 and 6.Their product is 90 (15*6)
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[2, 5 * 10<sup>4</sup>]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 392-is-subsequence
    def isSubsequence(self, s: str, t: str) -> bool:
        
        if len(s) > len(t):
        i, j = 0, 0
        m, n = len(s), len(t)
        
        while i < m and j < n:
            if s[i] == t[j]:
                i += 1
                j += 1
            else:
                j += 1
        return i == m
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/is-subsequence/">392. Is Subsequence</a></h2><h3>Easy</h3><hr><div><p>Given two strings <code>s</code> and <code>t</code>, return <code>true</code><em> if </em><code>s</code><em> is a <strong>subsequence</strong> of </em><code>t</code><em>, or </em><code>false</code><em> otherwise</em>.</p>

        i, j = 0, 0
        
                i += 1
                j += 1
            else:
                j += 1

<p>A <strong>subsequence</strong> of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., <code>"ace"</code> is a subsequence of <code>"<u>a</u>b<u>c</u>d<u>e</u>"</code> while <code>"aec"</code> is not).</p>

<pre><strong>Input:</strong> s = "abc", t = "ahbgdc"
<pre><strong>Input:</strong> s = "axc", t = "ahbgdc"
</pre>

<ul>
	<li><code>0 &lt;= s.length &lt;= 100</code></li>
	<li><code>0 &lt;= t.length &lt;= 10<sup>4</sup></code></li>
	<li><code>s</code> and <code>t</code> consist only of lowercase English letters.</li>
</ul>

<strong>Follow up:</strong> Suppose there are lots of incoming <code>s</code>, say <code>s<sub>1</sub>, s<sub>2</sub>, ..., s<sub>k</sub></code> where <code>k &gt;= 10<sup>9</sup></code>, and you want to check one by one to see if <code>t</code> has its subsequence. In this scenario, how would you change your code?</div>

directory: 1130-minimum-cost-tree-from-leaf-values
    def mctFromLeafValues(self, arr: List[int]) -> int:
        
        stack = [float('inf')]
        res = 0
        for num in arr:
            while stack and stack[-1] <= num:
                cur = stack.pop()
                res += cur * min(stack[-1], num)
            stack.append(num)
        while len(stack) > 2:
            res += stack.pop() * stack[-1]
        return res
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-cost-tree-from-leaf-values/">1130. Minimum Cost Tree From Leaf Values</a></h2><h3>Medium</h3><hr><div><p>Given an array <code>arr</code> of positive integers, consider all binary trees such that:</p>

        res = 0
        return res

<ul>
	<li>Each node has either <code>0</code> or <code>2</code> children;</li>
	<li>The values of <code>arr</code> correspond to the values of each <strong>leaf</strong> in an in-order traversal of the tree.</li>
	<li>The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively.</li>
</ul>

<p>Among all possible binary trees considered, return <em>the smallest possible sum of the values of each non-leaf node</em>. It is guaranteed this sum fits into a <strong>32-bit</strong> integer.</p>

<p>A node is a <strong>leaf</strong> if and only if it has zero children.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/tree1.jpg" style="width: 500px; height: 169px;">
<pre><strong>Input:</strong> arr = [6,2,4]
<strong>Output:</strong> 32
<strong>Explanation:</strong> There are two possible trees shown.
The first has a non-leaf node sum 36, and the second has non-leaf node sum 32.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/08/10/tree2.jpg" style="width: 224px; height: 145px;">
<pre><strong>Input:</strong> arr = [4,11]
<strong>Output:</strong> 44
</pre>

<ul>
	<li><code>2 &lt;= arr.length &lt;= 40</code></li>
	<li><code>1 &lt;= arr[i] &lt;= 15</code></li>
	<li>It is guaranteed that the answer fits into a <strong>32-bit</strong> signed integer (i.e., it is less than 2<sup>31</sup>).</li>
</ul>
</div>

directory: Count Occurences of Anagrams - GFG
Python: #User function Template for python3
from collections import Counter

#User function Template for python3

	def search(self,pat, txt):
	    # code here
	    # f - 1, o - 1, r - 1 (len - 3)
	    # Sliding window of length (len(pat)) and roll it over txt and check if the frequency array matches.
	    # If the frequency array matches then we increment count and move on
	    # when we move on, we maintain the start poiner and the next pointer, we decrement count for start pointer 
	    # because we have moved forward by 1 and we increment the element at next pointer.
	    
	    m, n = len(pat), len(txt)
	    count1 = Counter(pat)
	    count2 = Counter(txt[:m])
	    #print(count1, count2)
	    ans = 0
	    
	    for i in range(n - m + 1):
	        if count1 == count2:
	            ans += 1
	        # We will decrement entry i from count2 and increment entry i + m
	        count2[txt[i]] -= 1
	        if count2[txt[i]] == 0:
	            del count2[txt[i]]
	        if i + m < n:
	            count2[txt[i+m]] += 1
	   
	    return ans
#{ 
 # Driver Code Starts
#Initial Template for Python 3

# Driver code 
if __name__ == "__main__": 		
    tc=int(input())
    while tc > 0:
        txt=input().strip()
        pat=input().strip()
        ob = Solution()
        ans = ob.search(pat, txt)
        print(ans)
        tc=tc-1
# } Driver Code Ends

def search(self,pat, txt):
	    # code here
	    
	    ans = 0
	    
	            ans += 1
	        if i + m < n:
	   
	    return ans
#{ 

        tc=tc-1
Notes: 
Readme: # Count Occurences of Anagrams
## Medium
<div class="problems_problem_content__Xm_eO"><p><span style="font-size:18px">Given a word <strong>pat</strong>&nbsp;and a text <strong>txt</strong>. Return the count of the occurences of anagrams of the word in the text.</span></p>

<p><span style="font-size:18px"><strong>Example 1:</strong></span></p>

<pre style="position: relative;"><span style="font-size:18px"><strong>Input:
</strong>txt = forxxorfxdofr
pat = for
<strong>Explanation:</strong> <strong>for, orf</strong> and <strong>ofr </strong>appears
in the <strong>txt, </strong>hence answer is 3.
</span><div class="open_grepper_editor" title="Edit &amp; Save To Grepper"></div></pre>

<p><span style="font-size:18px"><strong>Example 2:</strong></span></p>

</strong>txt = aabaabaa
pat = aaba
<strong>Explanation:</strong>&nbsp;<strong>aaba</strong> is present 4 times
in <strong>txt</strong>.

<p><span style="font-size:18px"><strong>Your Task:</strong><br>
Complete the function <strong>search()</strong>&nbsp;which takes two strings&nbsp;<strong>pat, txt,</strong>&nbsp;as input parameters&nbsp;and returns an integer&nbsp;denoting the answer.&nbsp;You don't to print answer or take inputs.</span></p>

<p><span style="font-size:18px"><strong>Expected Time Complexity:</strong>&nbsp;O(N)<br>
<strong>Expected Auxiliary Space:</strong>&nbsp;O(26) or O(256)</span></p>

<p><span style="font-size:18px"><strong>Constraints:</strong><br>
1 &lt;=&nbsp;|pat| &lt;= |txt|&nbsp;&lt;= 10<sup>5</sup><br>
Both string contains lowercase english letters.</span></p>

</div>

directory: 5-longest-palindromic-substring
    def longestPalindrome(self, s: str) -> str:
        
        def PalindromeLength(s, left, right):
            while left >= 0 and right < len(s) and s[left] == s[right]:
                left -=1
                right += 1
            return right - left - 1
        start, end = 0, 0
        maxLength = float('-inf')
        for i in range(len(s)):
            len1 = PalindromeLength(s, i, i)
            len2 = PalindromeLength(s, i, i+1)
            maxLength = max(len1, len2)
            if maxLength > end - start:
                start = i - (maxLength - 1) // 2
                end = i + maxLength // 2
        return s[start : end + 1]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/longest-palindromic-substring/">5. Longest Palindromic Substring</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, return <em>the longest palindromic substring</em> in <code>s</code>.</p>

                left -=1
                right += 1

<p>A string is called a palindrome string if the reverse of that string is the same as the original string.</p>

<pre><strong>Input:</strong> s = "babad"
<strong>Explanation:</strong> "aba" is also a valid answer.
</pre>

<pre><strong>Input:</strong> s = "cbbd"
<strong>Output:</strong> "bb"
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 1000</code></li>
	<li><code>s</code> consist of only digits and English letters.</li>
</ul>
</div>

directory: 539-minimum-time-difference
    def findMinDifference(self, timePoints: List[str]) -> int:
        minutes = []
        for time in timePoints:
            hrs, mins = time.split(":")
            minutes.append(int(hrs) * 60 + int(mins))
        minutes.sort()
        minutes.append(minutes[0] + 24 * 60)
        min_diff = 1440
        for i in range(1, len(minutes)):
            min_diff = min(min_diff, minutes[i] - minutes[i-1])
        return min_diff
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/minimum-time-difference/">539. Minimum Time Difference</a></h2><h3>Medium</h3><hr><div>Given a list of 24-hour clock time points in <strong>"HH:MM"</strong> format, return <em>the minimum <b>minutes</b> difference between any two time-points in the list</em>.
<pre><strong>Input:</strong> timePoints = ["23:59","00:00"]
<pre><strong>Input:</strong> timePoints = ["00:00","23:59","00:00"]
</pre>

<ul>
	<li><code>2 &lt;= timePoints.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>timePoints[i]</code> is in the format <strong>"HH:MM"</strong>.</li>
</ul>
</div>

directory: 1807-evaluate-the-bracket-pairs-of-a-string
    def evaluate(self, s: str, knowledge: List[List[str]]) -> str:
        
        ans = ''
        
        dic = {}
        for v1, v2 in knowledge:
            dic[v1] = v2
        i = 0; n = len(s)
        while i < n:
            if s[i] == '(':
                key = ''; i+=1
                while i < len(s) and s[i]!=')':
                    key += s[i]
                    i+=1
                if key in dic:
                    ans += dic[key]
                else:
                    ans+='?'
            else:
                ans+=s[i]
            i+=1
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/evaluate-the-bracket-pairs-of-a-string/">1807. Evaluate the Bracket Pairs of a String</a></h2><h3>Medium</h3><hr><div><p>You are given a string <code>s</code> that contains some bracket pairs, with each pair containing a <strong>non-empty</strong> key.</p>

        ans = ''
        
        dic = {}
        while i < n:
                    key += s[i]
                    i+=1
                else:
                    ans+='?'
            else:
                ans+=s[i]
            i+=1
        return ans

<ul>
	<li>For example, in the string <code>"(name)is(age)yearsold"</code>, there are <strong>two</strong> bracket pairs that contain the keys <code>"name"</code> and <code>"age"</code>.</li>
</ul>

<p>You know the values of a wide range of keys. This is represented by a 2D string array <code>knowledge</code> where each <code>knowledge[i] = [key<sub>i</sub>, value<sub>i</sub>]</code> indicates that key <code>key<sub>i</sub></code> has a value of <code>value<sub>i</sub></code>.</p>

<p>You are tasked to evaluate <strong>all</strong> of the bracket pairs. When you evaluate a bracket pair that contains some key <code>key<sub>i</sub></code>, you will:</p>

<ul>
	<li>Replace <code>key<sub>i</sub></code> and the bracket pair with the key's corresponding <code>value<sub>i</sub></code>.</li>
	<li>If you do not know the value of the key, you will replace <code>key<sub>i</sub></code> and the bracket pair with a question mark <code>"?"</code> (without the quotation marks).</li>
</ul>

<p>Each key will appear at most once in your <code>knowledge</code>. There will not be any nested brackets in <code>s</code>.</p>

<p>Return <em>the resulting string after evaluating <strong>all</strong> of the bracket pairs.</em></p>

<pre><strong>Input:</strong> s = "(name)is(age)yearsold", knowledge = [["name","bob"],["age","two"]]
<strong>Output:</strong> "bobistwoyearsold"
The key "name" has a value of "bob", so replace "(name)" with "bob".
The key "age" has a value of "two", so replace "(age)" with "two".
</pre>

<pre><strong>Input:</strong> s = "hi(name)", knowledge = [["a","b"]]
<strong>Output:</strong> "hi?"
<strong>Explanation:</strong> As you do not know the value of the key "name", replace "(name)" with "?".
</pre>

<pre><strong>Input:</strong> s = "(a)(a)(a)aaa", knowledge = [["a","yes"]]
<strong>Output:</strong> "yesyesyesaaa"
<strong>Explanation:</strong> The same key can appear multiple times.
The key "a" has a value of "yes", so replace all occurrences of "(a)" with "yes".
Notice that the "a"s not in a bracket pair are not evaluated.
</pre>

<ul>
	<li><code>0 &lt;= knowledge.length &lt;= 10<sup>5</sup></code></li>
	<li><code>knowledge[i].length == 2</code></li>
	<li><code>1 &lt;= key<sub>i</sub>.length, value<sub>i</sub>.length &lt;= 10</code></li>
	<li><code>s</code> consists of lowercase English letters and round brackets <code>'('</code> and <code>')'</code>.</li>
	<li>Every open bracket <code>'('</code> in <code>s</code> will have a corresponding close bracket <code>')'</code>.</li>
	<li>The key in each bracket pair of <code>s</code> will be non-empty.</li>
	<li>There will not be any nested bracket pairs in <code>s</code>.</li>
	<li><code>key<sub>i</sub></code> and <code>value<sub>i</sub></code> consist of lowercase English letters.</li>
	<li>Each <code>key<sub>i</sub></code> in <code>knowledge</code> is unique.</li>
</ul>
</div>

directory: 323-number-of-connected-components-in-an-undirected-graph
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/">323. Number of Connected Components in an Undirected Graph</a></h2><h3>Medium</h3><hr><div><p>You have a graph of <code>n</code> nodes. You are given an integer <code>n</code> and an array <code>edges</code> where <code>edges[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is an edge between <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code> in the graph.</p>

<p>Return <em>the number of connected components in the graph</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/conn1-graph.jpg" style="width: 382px; height: 222px;">
<pre><strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[3,4]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/conn2-graph.jpg" style="width: 382px; height: 222px;">
<pre><strong>Input:</strong> n = 5, edges = [[0,1],[1,2],[2,3],[3,4]]
</pre>

<ul>
	<li><code>1 &lt;= edges.length &lt;= 5000</code></li>
	<li><code>0 &lt;= a<sub>i</sub> &lt;= b<sub>i</sub> &lt; n</code></li>
	<li>There are no repeated edges.</li>
</ul>
</div>

directory: 531-lonely-pixel-i
    def findLonelyPixel(self, picture: List[List[str]]) -> int:
        self.ans = 0
        m, n = len(picture), len(picture[0])
        rows = [0] * m
        cols = [0] * n
        for i in range(m):
            for j in range(n):
                if picture[i][j] =='B':
                    rows[i] += 1
                    cols[j] += 1           
                if picture[i][j] == 'B' and rows[i] == 1 and cols[j] == 1:
                    self.ans += 1
        return self.ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/lonely-pixel-i/">531. Lonely Pixel I</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> <code>picture</code> consisting of black <code>'B'</code> and white <code>'W'</code> pixels, return <em>the number of <b>black</b> lonely pixels</em>.</p>

<p>A black lonely pixel is a character <code>'B'</code> that located at a specific position where the same row and same column don't have <strong>any other</strong> black pixels.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/11/pixel1.jpg" style="width: 242px; height: 242px;">
<pre><strong>Input:</strong> picture = [["W","W","B"],["W","B","W"],["B","W","W"]]
<strong>Explanation:</strong> All the three 'B's are black lonely pixels.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/11/pixel2.jpg" style="width: 242px; height: 242px;">
<pre><strong>Input:</strong> picture = [["B","B","B"],["B","B","W"],["B","B","B"]]
</pre>

<ul>
	<li><code>m ==&nbsp;picture.length</code></li>
	<li><code>n ==&nbsp;picture[i].length</code></li>
	<li><code>picture[i][j]</code> is <code>'W'</code> or <code>'B'</code>.</li>
</ul>
</div>

directory: 1874-minimize-product-sum-of-two-arrays
    def minProductSum(self, nums1: List[int], nums2: List[int]) -> int:
        
        counter1, counter2 = [0] * 101,  [0] * 101
        for num in nums1:
            counter1[num] += 1
            counter2[num] += 1
        p1, p2 = 1, 100
        ans = 0
        while p1 <= 100 and p2 > 0:
            while p1 <= 100 and counter1[p1] == 0:
                p1 += 1
            while p2 > 0 and counter2[p2] == 0:
                p2 -= 1
            
            if p1 == 101 or p2 == 0:
                break
            
            occ = min(counter1[p1], counter2[p2])
            
            ans += occ * p1 * p2
            counter1[p1] -= occ
            counter2[p2] -= occ
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimize-product-sum-of-two-arrays/">1874. Minimize Product Sum of Two Arrays</a></h2><h3>Medium</h3><hr><div><p>The <b>product sum </b>of two equal-length arrays <code>a</code> and <code>b</code> is equal to the sum of <code>a[i] * b[i]</code> for all <code>0 &lt;= i &lt; a.length</code> (<strong>0-indexed</strong>).</p>

        ans = 0
                p1 += 1
                p2 -= 1
            
                break
            
        return ans
        
<ul>
	<li>For example, if <code>a = [1,2,3,4]</code> and <code>b = [5,2,3,1]</code>, the <strong>product sum</strong> would be <code>1*5 + 2*2 + 3*3 + 4*1 = 22</code>.</li>
</ul>

<p>Given two arrays <code>nums1</code> and <code>nums2</code> of length <code>n</code>, return <em>the <strong>minimum product sum</strong> if you are allowed to <strong>rearrange</strong> the <strong>order</strong> of the elements in </em><code>nums1</code>.&nbsp;</p>

<pre><strong>Input:</strong> nums1 = [5,3,4,2], nums2 = [4,2,2,5]
<strong>Output:</strong> 40
<strong>Explanation:</strong>&nbsp;We can rearrange nums1 to become [3,5,4,2]. The product sum of [3,5,4,2] and [4,2,2,5] is 3*4 + 5*2 + 4*2 + 2*5 = 40.
</pre>

<pre><strong>Input:</strong> nums1 = [2,1,4,5,7], nums2 = [3,2,4,8,6]
<strong>Output:</strong> 65
<strong>Explanation: </strong>We can rearrange nums1 to become [5,7,4,1,2]. The product sum of [5,7,4,1,2] and [3,2,4,8,6] is 5*3 + 7*2 + 4*4 + 1*8 + 2*6 = 65.
</pre>

<ul>
	<li><code>n == nums1.length == nums2.length</code></li>
	<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums1[i], nums2[i] &lt;= 100</code></li>

directory: 176-second-highest-salary
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/second-highest-salary/">176. Second Highest Salary</a></h2><h3>Medium</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Employee</code></p>

<pre>+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| salary      | int  |
Each row of this table contains information about the salary of an employee.
</pre>

<p>Write an SQL query to report the second highest salary from the <code>Employee</code> table. If there is no second highest salary, the query should report <code>null</code>.</p>

+----+--------+
| id | salary |
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+---------------------+
| SecondHighestSalary |
| 200                 |
</pre>

| 1  | 100    |
| null                |
</pre>
</div>

directory: 344-reverse-string
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reverse-string/">344. Reverse String</a></h2><h3>Easy</h3><hr><div><p>Write a function that reverses a string. The input string is given as an array of characters <code>s</code>.</p>

<p>You must do this by modifying the input array <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in-place</a> with <code>O(1)</code> extra memory.</p>

<pre><strong>Input:</strong> s = ["h","e","l","l","o"]
<strong>Output:</strong> ["o","l","l","e","h"]
<pre><strong>Input:</strong> s = ["H","a","n","n","a","h"]
<strong>Output:</strong> ["h","a","n","n","a","H"]
</pre>

<ul>
	<li><code>s[i]</code> is a <a href="https://en.wikipedia.org/wiki/ASCII#Printable_characters" target="_blank">printable ascii character</a>.</li>
</ul>
</div>

directory: 54-spiral-matrix
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/spiral-matrix/">54. Spiral Matrix</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> <code>matrix</code>, return <em>all elements of the</em> <code>matrix</code> <em>in spiral order</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg" style="width: 242px; height: 242px;">
<pre><strong>Input:</strong> matrix = [[1,2,3],[4,5,6],[7,8,9]]
<strong>Output:</strong> [1,2,3,6,9,8,7,4,5]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/spiral.jpg" style="width: 322px; height: 242px;">
<pre><strong>Input:</strong> matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
<strong>Output:</strong> [1,2,3,4,8,12,11,10,9,5,6,7]
</pre>

<ul>
	<li><code>1 &lt;= m, n &lt;= 10</code></li>
	<li><code>-100 &lt;= matrix[i][j] &lt;= 100</code></li>
</ul>
</div>

directory: 1583-count-unhappy-friends
    def unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int:
        """
        Create a matrix “rank” where rank[i][j] holds how highly friend ‘i' views ‘j’. This allows for O(1) comparisons between people
        
        1 2 3
        3 2 0
        3 1 0
        1 2 0
        
        """
        unhappy = 0
        pairMap = defaultdict(int)
        for p1, p2 in pairs:
            pairMap[p1] = p2
            pairMap[p2] = p1
        prefer = {}
                if i not in prefer:
                    prefer[i] = {}
                prefer[i][preferences[i][j]] = j
        for i in range(len(preferences)):
                x = i
                y = pairMap[x]
                u = preferences[x][j]
                v = pairMap[u]
                if prefer[x][u] < prefer[x][y] and prefer[u][x] < prefer[u][v]:
                    unhappy+=1
                    break
        return unhappy
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/count-unhappy-friends/">1583. Count Unhappy Friends</a></h2><h3>Medium</h3><hr><div><p>You are given a list of&nbsp;<code>preferences</code>&nbsp;for&nbsp;<code>n</code>&nbsp;friends, where <code>n</code> is always <strong>even</strong>.</p>

        """
        
        1 2 3
        3 2 0
        3 1 0
        1 2 0
        
        """
        unhappy = 0
        prefer = {}
                x = i
                    break
    
<p>For each person <code>i</code>,&nbsp;<code>preferences[i]</code>&nbsp;contains&nbsp;a list of friends&nbsp;<strong>sorted</strong> in the <strong>order of preference</strong>. In other words, a friend earlier in the list is more preferred than a friend later in the list.&nbsp;Friends in&nbsp;each list are&nbsp;denoted by integers from <code>0</code> to <code>n-1</code>.</p>

<p>All the friends are divided into pairs.&nbsp;The pairings are&nbsp;given in a list&nbsp;<code>pairs</code>,&nbsp;where <code>pairs[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> denotes <code>x<sub>i</sub></code>&nbsp;is paired with <code>y<sub>i</sub></code> and <code>y<sub>i</sub></code> is paired with <code>x<sub>i</sub></code>.</p>

<p>However, this pairing may cause some of the friends to be unhappy.&nbsp;A friend <code>x</code>&nbsp;is unhappy if <code>x</code>&nbsp;is paired with <code>y</code>&nbsp;and there exists a friend <code>u</code>&nbsp;who&nbsp;is paired with <code>v</code>&nbsp;but:</p>

<ul>
	<li><code>x</code>&nbsp;prefers <code>u</code>&nbsp;over <code>y</code>,&nbsp;and</li>
	<li><code>u</code>&nbsp;prefers <code>x</code>&nbsp;over <code>v</code>.</li>
</ul>

<p>Return <em>the number of unhappy friends</em>.</p>

<pre><strong>Input:</strong> n = 4, preferences = [[1, 2, 3], [3, 2, 0], [3, 1, 0], [1, 2, 0]], pairs = [[0, 1], [2, 3]]
Friend 1 is unhappy because:
- 1 is paired with 0 but prefers 3 over 0, and
- 3 prefers 1 over 2.
Friend 3 is unhappy because:
- 3 is paired with 2 but prefers 1 over 2, and
- 1 prefers 3 over 0.
Friends 0 and 2 are happy.
</pre>

<pre><strong>Input:</strong> n = 2, preferences = [[1], [0]], pairs = [[1, 0]]
<strong>Explanation:</strong> Both friends 0 and 1 are happy.
</pre>

<pre><strong>Input:</strong> n = 4, preferences = [[1, 3, 2], [2, 3, 0], [1, 3, 0], [0, 2, 1]], pairs = [[1, 3], [0, 2]]
</pre>

<ul>
	<li><code>2 &lt;= n &lt;= 500</code></li>
	<li><code>n</code>&nbsp;is even.</li>
	<li><code>preferences.length&nbsp;== n</code></li>
	<li><code>preferences[i].length&nbsp;== n - 1</code></li>
	<li><code>0 &lt;= preferences[i][j] &lt;= n - 1</code></li>
	<li><code>preferences[i]</code>&nbsp;does not contain <code>i</code>.</li>
	<li>All values in&nbsp;<code>preferences[i]</code>&nbsp;are unique.</li>
	<li><code>pairs.length&nbsp;== n/2</code></li>
	<li><code>pairs[i].length&nbsp;== 2</code></li>
	<li><code>x<sub>i</sub> != y<sub>i</sub></code></li>
	<li><code>0 &lt;= x<sub>i</sub>, y<sub>i</sub>&nbsp;&lt;= n - 1</code></li>
	<li>Each person is contained in <strong>exactly one</strong> pair.</li>
</ul>
</div>

directory: 2038-remove-colored-pieces-if-both-neighbors-are-the-same-color
    def winnerOfGame(self, colors: str) -> bool:
        
        A_count, B_count = 0, 0
        a, b = 0, 0
        for c in colors:
            if c == 'A':
                A_count+=1
                if A_count > 2:
                    a+=1
                B_count = 0
            else:
                B_count += 1
                if B_count > 2:
                    b+=1
                A_count = 0
        return a > b
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/remove-colored-pieces-if-both-neighbors-are-the-same-color/">2038. Remove Colored Pieces if Both Neighbors are the Same Color</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> pieces arranged in a line, and each piece is colored either by <code>'A'</code> or by <code>'B'</code>. You are given a string <code>colors</code> of length <code>n</code> where <code>colors[i]</code> is the color of the <code>i<sup>th</sup></code> piece.</p>

        a, b = 0, 0
            if c == 'A':
                    a+=1
                B_count = 0
            else:
                    b+=1
                A_count = 0
        return a > b

<p>Alice and Bob are playing a game where they take <strong>alternating turns</strong> removing pieces from the line. In this game, Alice moves<strong> first</strong>.</p>

<ul>
	<li>Alice is only allowed to remove a piece colored <code>'A'</code> if <strong>both its neighbors</strong> are also colored <code>'A'</code>. She is <strong>not allowed</strong> to remove pieces that are colored <code>'B'</code>.</li>
	<li>Bob is only allowed to remove a piece colored <code>'B'</code> if <strong>both its neighbors</strong> are also colored <code>'B'</code>. He is <strong>not allowed</strong> to remove pieces that are colored <code>'A'</code>.</li>
	<li>Alice and Bob <strong>cannot</strong> remove pieces from the edge of the line.</li>
	<li>If a player cannot make a move on their turn, that player <strong>loses</strong> and the other player <strong>wins</strong>.</li>
</ul>

<p>Assuming Alice and Bob play optimally, return <code>true</code><em> if Alice wins, or return </em><code>false</code><em> if Bob wins</em>.</p>

<pre><strong>Input:</strong> colors = "AAABABB"
A<u>A</u>ABABB -&gt; AABABB
Alice moves first.
She removes the second 'A' from the left since that is the only 'A' whose neighbors are both 'A'.

Now it's Bob's turn.
Bob cannot make a move on his turn since there are no 'B's whose neighbors are both 'B'.
Thus, Alice wins, so return true.
</pre>

<pre><strong>Input:</strong> colors = "AA"
Alice has her turn first.
There are only two 'A's and both are on the edge of the line, so she cannot move on her turn.
Thus, Bob wins, so return false.
</pre>

<pre><strong>Input:</strong> colors = "ABBBBBBBAAA"
ABBBBBBBA<u>A</u>A -&gt; ABBBBBBBAA
Her only option is to remove the second to last 'A' from the right.

ABBBB<u>B</u>BBAA -&gt; ABBBBBBAA
Next is Bob's turn.
He has many options for which 'B' piece to remove. He can pick any.

On Alice's second turn, she has no more pieces that she can remove.
</pre>

<ul>
	<li><code>1 &lt;=&nbsp;colors.length &lt;= 10<sup>5</sup></code></li>
	<li><code>colors</code>&nbsp;consists of only the letters&nbsp;<code>'A'</code>&nbsp;and&nbsp;<code>'B'</code></li>
</ul>
</div>

directory: 603-consecutive-available-seats
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/consecutive-available-seats/">603. Consecutive Available Seats</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Cinema</code></p>

| seat_id     | int  |
| free        | bool |
seat_id is an auto-increment primary key column for this table.
Each row of this table indicates whether the i<sup>th</sup> seat is free or not. 1 means free while 0 means occupied.
</pre>

<p>Write an SQL query to report all the consecutive available seats in the cinema.</p>

<p>Return the result table <strong>ordered</strong> by <code>seat_id</code> <strong>in ascending order</strong>.</p>

<p>The test cases are generated so that more than two seats are consecutively available.</p>

Cinema table:
+---------+------+
| seat_id | free |
| 1       | 1    |
| 2       | 0    |
| 3       | 1    |
| 4       | 1    |
| 5       | 1    |
| seat_id |
| 3       |
| 4       |
| 5       |
</pre>
</div>

directory: 63-unique-paths-ii
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        
        rows, cols = len(obstacleGrid), len(obstacleGrid[0])
        
        dp = [[0 for _ in range(cols)] for _ in range(rows)]
        
        for i in range(rows):
            if obstacleGrid[i][0] == 1:
                break
        for j in range(cols):
            if obstacleGrid[0][j] == 1:
                break
            dp[0][j] = 1
        
        for i in range(1, rows):
            for j in range(1, cols):
                
                if obstacleGrid[i][j] == 1:
                    continue
                else:
                    dp[i][j] = dp[i-1][j] + dp[i][j-1]
        
        return dp[-1][-1]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/unique-paths-ii/">63. Unique Paths II</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> integer array <code>grid</code>. There is a robot initially located at the <b>top-left corner</b> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m-1][n-1]</code>). The robot can only move either down or right at any point in time.</p>

                break
                break
        
                    continue
                else:
        
<p>An obstacle and space are marked as <code>1</code> or <code>0</code> respectively in <code>grid</code>. A path that the robot takes cannot include <strong>any</strong> square that is an obstacle.</p>

<p>Return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>

<p>The testcases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/04/robot1.jpg" style="width: 242px; height: 242px;">
<pre><strong>Input:</strong> obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
<strong>Explanation:</strong> There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -&gt; Right -&gt; Down -&gt; Down
2. Down -&gt; Down -&gt; Right -&gt; Right
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/04/robot2.jpg" style="width: 162px; height: 162px;">
<pre><strong>Input:</strong> obstacleGrid = [[0,1],[0,0]]
</pre>

<ul>
	<li><code>m == obstacleGrid.length</code></li>
	<li><code>n == obstacleGrid[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 100</code></li>
	<li><code>obstacleGrid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
</div>

directory: 399-evaluate-division
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        
        graph = defaultdict(dict)
        
        for i, equation in enumerate(equations):
            graph[equation[0]][equation[1]]  = values[i]
            graph[equation[1]][equation[0]]  = 1 / values[i]
        
        def dfs(x, y, visited):
            
            if x not in graph or y not in graph: return -1
            if y in graph[x]:
                return graph[x][y]
            for key in graph[x]:
                if key not in visited:
                    visited.add(key)
                    temp = dfs(key, y, visited)
                    if temp == -1:
                        continue
                    else:
                        return temp * graph[x][key]
            return -1
            
        ans = []
        for p, q in queries:
            ans.append(dfs(p, q, set()))
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/evaluate-division/">399. Evaluate Division</a></h2><h3>Medium</h3><hr><div><p>You are given an array of variable pairs <code>equations</code> and an array of real numbers <code>values</code>, where <code>equations[i] = [A<sub>i</sub>, B<sub>i</sub>]</code> and <code>values[i]</code> represent the equation <code>A<sub>i</sub> / B<sub>i</sub> = values[i]</code>. Each <code>A<sub>i</sub></code> or <code>B<sub>i</sub></code> is a string that represents a single variable.</p>

                        continue
                    else:
            return -1
            
        ans = []
        return ans

<p>You are also given some <code>queries</code>, where <code>queries[j] = [C<sub>j</sub>, D<sub>j</sub>]</code> represents the <code>j<sup>th</sup></code> query where you must find the answer for <code>C<sub>j</sub> / D<sub>j</sub> = ?</code>.</p>

<p>Return <em>the answers to all queries</em>. If a single answer cannot be determined, return <code>-1.0</code>.</p>

<p><strong>Note:</strong> The input is always valid. You may assume that evaluating the queries will not result in division by zero and that there is no contradiction.</p>

<pre><strong>Input:</strong> equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
<strong>Output:</strong> [6.00000,0.50000,-1.00000,1.00000,-1.00000]
Given: <em>a / b = 2.0</em>, <em>b / c = 3.0</em>
queries are: <em>a / c = ?</em>, <em>b / a = ?</em>, <em>a / e = ?</em>, <em>a / a = ?</em>, <em>x / x = ?</em>
return: [6.0, 0.5, -1.0, 1.0, -1.0 ]
</pre>

<pre><strong>Input:</strong> equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
<strong>Output:</strong> [3.75000,0.40000,5.00000,0.20000]
</pre>

<pre><strong>Input:</strong> equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
<strong>Output:</strong> [0.50000,2.00000,-1.00000,-1.00000]
</pre>

<ul>
	<li><code>1 &lt;= equations.length &lt;= 20</code></li>
	<li><code>equations[i].length == 2</code></li>
	<li><code>1 &lt;= A<sub>i</sub>.length, B<sub>i</sub>.length &lt;= 5</code></li>
	<li><code>values.length == equations.length</code></li>
	<li><code>0.0 &lt; values[i] &lt;= 20.0</code></li>
	<li><code>1 &lt;= queries.length &lt;= 20</code></li>
	<li><code>queries[i].length == 2</code></li>
	<li><code>1 &lt;= C<sub>j</sub>.length, D<sub>j</sub>.length &lt;= 5</code></li>
	<li><code>A<sub>i</sub>, B<sub>i</sub>, C<sub>j</sub>, D<sub>j</sub></code> consist of lower case English letters and digits.</li>
</ul>
</div>

directory: 0339-nested-list-weight-sum
# This is the interface that allows for creating nested lists.
# """
#class NestedInteger:
#    def __init__(self, value=None):
#        """
#        If value is not specified, initializes an empty list.
#        Otherwise initializes a single integer equal to value.
#        """
#
#    def isInteger(self):
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        :rtype bool
#        """
#
#    def add(self, elem):
#        """
#        Set this NestedInteger to hold a nested list and adds a nested integer elem to it.
#        :rtype void
#        """
#
#    def setInteger(self, value):
#        """
#        Set this NestedInteger to hold a single integer equal to value.
#        """
#
#    def getInteger(self):
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        :rtype int
#        """
#
#    def getList(self):
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        :rtype List[NestedInteger]
#        """

# """
# """
#        """
#        """
#
#        """
#        """
#
#        """
#        """
#
#        """
#        """
#
#        """
#        """
#
#        """
#        """

    def depthSum(self, nestedList: List[NestedInteger]) -> int:
        
        def dfs(nestedList, depth):
            total = 0
            for nested in nestedList:
                if nested.isInteger():
                    total += nested.getInteger() * depth
                else:
                    total += dfs(nested.getList(), depth + 1)
            return total
        
        return dfs(nestedList, 1)
        
            total = 0
                else:
        
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/nested-list-weight-sum/">339. Nested List Weight Sum</a></h2><h3>Medium</h3><hr><div><p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists.</p>

<p>The <strong>depth</strong> of an integer is the number of lists that it is inside of. For example, the nested list <code>[1,[2,2],[[3],2],1]</code> has each integer's value set to its <strong>depth</strong>.</p>

<p>Return <em>the sum of each integer in </em><code>nestedList</code><em> multiplied by its <strong>depth</strong></em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/14/nestedlistweightsumex1.png" style="width: 405px; height: 99px;">
<pre><strong>Input:</strong> nestedList = [[1,1],2,[1,1]]
<strong>Output:</strong> 10
<strong>Explanation:</strong> Four 1's at depth 2, one 2 at depth 1. 1*2 + 1*2 + 2*1 + 1*2 + 1*2 = 10.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/14/nestedlistweightsumex2.png" style="width: 315px; height: 106px;">
<pre><strong>Input:</strong> nestedList = [1,[4,[6]]]
<strong>Output:</strong> 27
<strong>Explanation:</strong> One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3. 1*1 + 4*2 + 6*3 = 27.</pre>

<pre><strong>Input:</strong> nestedList = [0]
</pre>

<ul>
	<li><code>1 &lt;= nestedList.length &lt;= 50</code></li>
	<li>The values of the integers in the nested list is in the range <code>[-100, 100]</code>.</li>
	<li>The maximum <strong>depth</strong> of any integer is less than or equal to <code>50</code>.</li>
</ul>
</div>

directory: 0209-minimum-size-subarray-sum
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        
        """
        
        2, 3, 1, 2 - 8, 4
        3, 1, 2 - 6
        3, 1, 2, 4 - 10, 4
        1, 2, 4 - 7, 3
        2, 4, 3 - 9, 3
        4, 3
        
        """
        
        start, end, n = 0, 0, len(nums)
        minimum, prefixSum = float('inf'), 0
        while end < n:
            prefixSum += nums[end]
            while prefixSum >= target:
                minimum = min(minimum, end - start + 1)
                prefixSum -= nums[start]
                start += 1
            end += 1
        return minimum if minimum != float('inf') else 0
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-size-subarray-sum/">209. Minimum Size Subarray Sum</a></h2><h3>Medium</h3><hr><div><p>Given an array of positive integers <code>nums</code> and a positive integer <code>target</code>, return the minimal length of a <strong>contiguous subarray</strong> <code>[nums<sub>l</sub>, nums<sub>l+1</sub>, ..., nums<sub>r-1</sub>, nums<sub>r</sub>]</code> of which the sum is greater than or equal to <code>target</code>. If there is no such subarray, return <code>0</code> instead.</p>

        """
        
        3, 1, 2 - 6
        1, 2, 4 - 7, 3
        2, 4, 3 - 9, 3
        4, 3
        
        """
        
                start += 1
            end += 1

<pre><strong>Input:</strong> target = 7, nums = [2,3,1,2,4,3]
<strong>Explanation:</strong> The subarray [4,3] has the minimal length under the problem constraint.
</pre>

<pre><strong>Input:</strong> target = 4, nums = [1,4,4]
</pre>

<pre><strong>Input:</strong> target = 11, nums = [1,1,1,1,1,1,1,1]
</pre>

<ul>
	<li><code>1 &lt;= target &lt;= 10<sup>9</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
</ul>

<strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution of which the time complexity is <code>O(n log(n))</code>.</div>

directory: 0199-binary-tree-right-side-view
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
            return []
        queue = deque([root])
        ans = []
            ans.append(queue[size-1].val)
            for _ in range(size):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-tree-right-side-view/">199. Binary Tree Right Side View</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, imagine yourself standing on the <strong>right side</strong> of it, return <em>the values of the nodes you can see ordered from top to bottom</em>.</p>

            return []
        ans = []
            
        return ans
        
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/14/tree.jpg" style="width: 401px; height: 301px;">
<pre><strong>Input:</strong> root = [1,2,3,null,5,null,4]
<strong>Output:</strong> [1,3,4]
</pre>

<pre><strong>Input:</strong> root = [1,null,3]
<strong>Output:</strong> [1,3]
</pre>

</pre>

<ul>
</ul>
</div>

directory: 263-ugly-number
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/ugly-number/">263. Ugly Number</a></h2><h3>Easy</h3><hr><div><p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p>

<p>Given an integer <code>n</code>, return <code>true</code> <em>if</em> <code>n</code> <em>is an <strong>ugly number</strong></em>.</p>

<pre><strong>Input:</strong> n = 6
<strong>Explanation:</strong> 6 = 2 × 3
</pre>

<strong>Explanation:</strong> 1 has no prime factors, therefore all of its prime factors are limited to 2, 3, and 5.
</pre>

<pre><strong>Input:</strong> n = 14
<strong>Explanation:</strong> 14 is not ugly since it includes the prime factor 7.
</pre>

<ul>
	<li><code>-2<sup>31</sup> &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 1219-path-with-maximum-gold
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/path-with-maximum-gold/">1219. Path with Maximum Gold</a></h2><h3>Medium</h3><hr><div><p>In a gold mine <code>grid</code> of size <code>m x n</code>, each cell in this mine has an integer representing the amount of gold in that cell, <code>0</code> if it is empty.</p>

<p>Return the maximum amount of gold you can collect under the conditions:</p>

<ul>
	<li>Every time you are located in a cell you will collect all the gold in that cell.</li>
	<li>From your position, you can walk one step to the left, right, up, or down.</li>
	<li>You can't visit the same cell more than once.</li>
	<li>Never visit a cell with <code>0</code> gold.</li>
	<li>You can start and stop collecting gold from <strong>any </strong>position in the grid that has some gold.</li>
</ul>

<pre><strong>Input:</strong> grid = [[0,6,0],[5,8,7],[0,9,0]]
<strong>Output:</strong> 24
[[0,6,0],
 [5,8,7],
 [0,9,0]]
Path to get the maximum gold, 9 -&gt; 8 -&gt; 7.
</pre>

<pre><strong>Input:</strong> grid = [[1,0,7],[2,0,6],[3,4,5],[0,3,0],[9,0,20]]
<strong>Output:</strong> 28
[[1,0,7],
 [2,0,6],
 [3,4,5],
 [0,3,0],
 [9,0,20]]
Path to get the maximum gold, 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7.
</pre>

<ul>
	<li><code>1 &lt;= m, n &lt;= 15</code></li>
	<li><code>0 &lt;= grid[i][j] &lt;= 100</code></li>
	<li>There are at most <strong>25 </strong>cells containing gold.</li>
</ul>
</div>

directory: 1490-clone-n-ary-tree
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/clone-n-ary-tree/">1490. Clone N-ary Tree</a></h2><h3>Medium</h3><hr><div><p>Given a <code>root</code> of an N-ary tree, return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the tree.</p>

<p>Each node in the n-ary tree contains a val (<code>int</code>) and a list (<code>List[Node]</code>) of its children.</p>

<pre>class Node {
    public int val;
    public List&lt;Node&gt; children;
}
</pre>

<p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).</em></p>

<p><img src="https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png" style="width: 100%; max-width: 300px;"></p>

<pre><strong>Input:</strong> root = [1,null,3,2,4,null,5,6]
<strong>Output:</strong> [1,null,3,2,4,null,5,6]
</pre>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" style="width: 296px; height: 241px;"></p>

<pre><strong>Input:</strong> root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
<strong>Output:</strong> [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
</pre>

<ul>
	<li>The depth of the n-ary tree is less than or equal to <code>1000</code>.</li>
	<li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code>.</li>
</ul>

<strong>Follow up: </strong>Can your solution work for the <a href="https://leetcode.com/problems/clone-graph/" target="_blank">graph problem</a>?</div>

directory: 1361-validate-binary-tree-nodes
    def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
        root = 0
        for i, (n1, n2) in enumerate(zip(leftChild, rightChild)):
            graph[i].append(n1)
            graph[i].append(n2)
            if root in graph[i]:
                root = i 
            if node == -1:
            visit.add(node)
            for nei in graph[node]:
                if not dfs(nei):
        
        if not dfs(root) or len(visit)!=n:
    
Notes: ​
Readme:

        root = 0
                root = i 
        
directory: 1762-buildings-with-an-ocean-view
    def findBuildings(self, heights: List[int]) -> List[int]:
        
        ans = []
        stack = []
        for i, h in enumerate(heights):
            while stack and heights[stack[-1]] <= h:
            stack.append(i)
        return stack
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/buildings-with-an-ocean-view/">1762. Buildings With an Ocean View</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> buildings in a line. You are given an integer array <code>heights</code> of size <code>n</code> that represents the heights of the buildings in the line.</p>

<p>The ocean is to the right of the buildings. A building has an ocean view if the building can see the ocean without obstructions. Formally, a building has an ocean view if all the buildings to its right have a <strong>smaller</strong> height.</p>

        ans = []
        stack = []
        
<p>Return a list of indices <strong>(0-indexed)</strong> of buildings that have an ocean view, sorted in increasing order.</p>

<pre><strong>Input:</strong> heights = [4,2,3,1]
<strong>Output:</strong> [0,2,3]
<strong>Explanation:</strong> Building 1 (0-indexed) does not have an ocean view because building 2 is taller.
</pre>

<pre><strong>Input:</strong> heights = [4,3,2,1]
<strong>Output:</strong> [0,1,2,3]
<strong>Explanation:</strong> All the buildings have an ocean view.
</pre>

<pre><strong>Input:</strong> heights = [1,3,2,4]
<strong>Output:</strong> [3]
<strong>Explanation:</strong> Only building 3 has an ocean view.
</pre>

<ul>
	<li><code>1 &lt;= heights.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= heights[i] &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 937-reorder-data-in-log-files
    def reorderLogFiles(self, logs: List[str]) -> List[str]:
        
        letters = [l for l in logs if l.split()[1].isalpha()]
        digits = [d for d in logs if d.split()[1].isdigit()]
        letters.sort(key = lambda x : (x.split()[1:], x.split()[0]))
        return letters + digits
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reorder-data-in-log-files/">937. Reorder Data in Log Files</a></h2><h3>Medium</h3><hr><div><p>You are given an array of <code>logs</code>. Each log is a space-delimited string of words, where the first word is the <strong>identifier</strong>.</p>

<p>There are two types of logs:</p>

<ul>
	<li><b>Letter-logs</b>: All words (except the identifier) consist of lowercase English letters.</li>
	<li><strong>Digit-logs</strong>: All words (except the identifier) consist of digits.</li>
</ul>

<p>Reorder these logs so that:</p>

<ol>
	<li>The <strong>letter-logs</strong> come before all <strong>digit-logs</strong>.</li>
	<li>The <strong>letter-logs</strong> are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.</li>
	<li>The <strong>digit-logs</strong> maintain their relative ordering.</li>
</ol>

<p>Return <em>the final order of the logs</em>.</p>

<pre><strong>Input:</strong> logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"]
<strong>Output:</strong> ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]
The letter-log contents are all different, so their ordering is "art can", "art zero", "own kit dig".
The digit-logs have a relative order of "dig1 8 1 5 1", "dig2 3 6".
</pre>

<pre><strong>Input:</strong> logs = ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
<strong>Output:</strong> ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
</pre>

<ul>
	<li><code>1 &lt;= logs.length &lt;= 100</code></li>
	<li><code>3 &lt;= logs[i].length &lt;= 100</code></li>
	<li>All the tokens of <code>logs[i]</code> are separated by a <strong>single</strong> space.</li>
	<li><code>logs[i]</code> is guaranteed to have an identifier and at least one word after the identifier.</li>
</ul>
</div>

directory: 1326-minimum-number-of-taps-to-open-to-water-a-garden
    def minTaps(self, n: int, ranges: List[int]) -> int:
        intervals = []
        for i in range(n + 1):
            intervals.append( [i-ranges[i], i + ranges[i]])
        intervals.sort(key = lambda x : x[0])
        
        start = ans = end = i = 0
        
        while start < n:
            while i <= n and intervals[i][0] <= start:
                end = max(end, intervals[i][1])
                i+=1
            if start == end:
                return -1
            start = end
            ans += 1
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-number-of-taps-to-open-to-water-a-garden/">1326. Minimum Number of Taps to Open to Water a Garden</a></h2><h3>Hard</h3><hr><div><p>There is a one-dimensional garden on the x-axis. The garden starts at the point <code>0</code> and ends at the point <code>n</code>. (i.e The length of the garden is <code>n</code>).</p>

                i+=1
                return -1
            start = end
            ans += 1
        return ans

<p>There are <code>n + 1</code> taps located at points <code>[0, 1, ..., n]</code> in the garden.</p>

<p>Given an integer <code>n</code> and an integer array <code>ranges</code> of length <code>n + 1</code> where <code>ranges[i]</code> (0-indexed) means the <code>i-th</code> tap can water the area <code>[i - ranges[i], i + ranges[i]]</code> if it was open.</p>

<p>Return <em>the minimum number of taps</em> that should be open to water the whole garden, If the garden cannot be watered return <strong>-1</strong>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/01/16/1685_example_1.png" style="width: 525px; height: 255px;">
<pre><strong>Input:</strong> n = 5, ranges = [3,4,1,1,0,0]
<strong>Explanation:</strong> The tap at point 0 can cover the interval [-3,3]
The tap at point 1 can cover the interval [-3,5]
The tap at point 2 can cover the interval [1,3]
The tap at point 3 can cover the interval [2,4]
The tap at point 4 can cover the interval [4,4]
The tap at point 5 can cover the interval [5,5]
Opening Only the second tap will water the whole garden [0,5]
</pre>

<pre><strong>Input:</strong> n = 3, ranges = [0,0,0,0]
<strong>Explanation:</strong> Even if you activate all the four taps you cannot water the whole garden.
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 10<sup>4</sup></code></li>
	<li><code>ranges.length == n + 1</code></li>
	<li><code>0 &lt;= ranges[i] &lt;= 100</code></li>
</ul>
</div>

directory: 904-fruit-into-baskets
    def totalFruit(self, fruits: List[int]) -> int:
        
        n = len(fruits)
        maximum = 0
        
        for end, fruit in enumerate(fruits):
            dic[fruit] = end
            if len(dic) > 2:
                min_index = min(dic.values())
                start = min_index + 1
                del dic[fruits[min_index]]
            maximum = max(maximum, end - start + 1)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/fruit-into-baskets/">904. Fruit Into Baskets</a></h2><h3>Medium</h3><hr><div><p>You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array <code>fruits</code> where <code>fruits[i]</code> is the <strong>type</strong> of fruit the <code>i<sup>th</sup></code> tree produces.</p>

        maximum = 0
        
<p>You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:</p>

<ul>
	<li>You only have <strong>two</strong> baskets, and each basket can only hold a <strong>single type</strong> of fruit. There is no limit on the amount of fruit each basket can hold.</li>
	<li>Starting from any tree of your choice, you must pick <strong>exactly one fruit</strong> from <strong>every</strong> tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.</li>
	<li>Once you reach a tree with fruit that cannot fit in your baskets, you must stop.</li>
</ul>

<p>Given the integer array <code>fruits</code>, return <em>the <strong>maximum</strong> number of fruits you can pick</em>.</p>

<pre><strong>Input:</strong> fruits = [<u>1,2,1</u>]
<strong>Explanation:</strong> We can pick from all 3 trees.
</pre>

<pre><strong>Input:</strong> fruits = [0,<u>1,2,2</u>]
<strong>Explanation:</strong> We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].
</pre>

<pre><strong>Input:</strong> fruits = [1,<u>2,3,2,2</u>]
<strong>Explanation:</strong> We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].
</pre>

<ul>
	<li><code>1 &lt;= fruits.length &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= fruits[i] &lt; fruits.length</code></li>
</ul>
</div>

directory: 1087-brace-expansion
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/brace-expansion/">1087. Brace Expansion</a></h2><h3>Medium</h3><hr><div><p>You are given a string <code>s</code> representing a list of words. Each letter in the word has one or more options.</p>

<ul>
	<li>If there is one option, the letter is represented as is.</li>
	<li>If there is more than one option, then curly braces delimit the options. For example, <code>"{a,b,c}"</code> represents options <code>["a", "b", "c"]</code>.</li>
</ul>

<p>For example, if <code>s = "a{b,c}"</code>, the first character is always <code>'a'</code>, but the second character can be <code>'b'</code> or <code>'c'</code>. The original list is <code>["ab", "ac"]</code>.</p>

<p>Return all words that can be formed in this manner, <strong>sorted</strong> in lexicographical order.</p>

<pre><strong>Input:</strong> s = "{a,b}c{d,e}f"
<strong>Output:</strong> ["acdf","acef","bcdf","bcef"]
<pre><strong>Input:</strong> s = "abcd"
<strong>Output:</strong> ["abcd"]
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 50</code></li>
	<li><code>s</code> consists of curly brackets <code>'{}'</code>, commas&nbsp;<code>','</code>, and lowercase English letters.</li>
	<li><code>s</code> is guaranteed to be a valid input.</li>
	<li>There are no nested curly brackets.</li>
	<li>All characters inside a pair of consecutive opening and ending curly brackets are different.</li>
</ul>
</div>

directory: 404-sum-of-left-leaves
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sum-of-left-leaves/">404. Sum of Left Leaves</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, return the sum of all left leaves.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/04/08/leftsum-tree.jpg" style="width: 277px; height: 302px;">
<strong>Explanation:</strong> There are two left leaves in the binary tree, with values 9 and 15 respectively.
</pre>

</pre>

<ul>
</ul>
</div>

directory: 45-jump-game-ii
    def jump(self, nums: List[int]) -> int:
        
        i, jumps, lastPos, maxPos = 0, 0, 0, 0
        while i < n - 1:
            
            maxPos = max(maxPos, i + nums[i])
            if i == lastPos:
                lastPos = maxPos
                jumps+=1
            i+=1
        return jumps
Notes: jumps = 0
max_index = 0
currentJumpEnd = 0
for i in range(len(nums)-1):
max_index = max(max_index, nums[i] + i)
if i == currentJumpEnd:
jumps+=1
currentJumpEnd = max_index
return jumps
Readme: <h2><a href="https://leetcode.com/problems/jump-game-ii/">45. Jump Game II</a></h2><h3>Medium</h3><hr><div><p>Given an array of non-negative integers <code>nums</code>, you are initially positioned at the first index of the array.</p>

<p>Each element in the array represents your maximum jump length at that position.</p>

<p>Your goal is to reach the last index in the minimum number of jumps.</p>

                jumps+=1
            i+=1
        
<p>You can assume that you can always reach the last index.</p>

<pre><strong>Input:</strong> nums = [2,3,1,1,4]
<strong>Explanation:</strong> The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index.
</pre>

<pre><strong>Input:</strong> nums = [2,3,0,1,4]
</pre>

<ul>
</ul>
</div>

directory: 1120-maximum-average-subtree
    def maximumAverageSubtree(self, root: Optional[TreeNode]) -> float:
        
        self.max_avg = 0
        def dfs(root, count):
                return [0, 0.0]
            else:
                count_left, left = dfs(root.left, count)
                count_right, right = dfs(root.right, count)
                s = root.val + left + right
                c = count_left + count_right + 1
                avg = s / c
                self.max_avg = max(self.max_avg, avg)
                return [c, s]
        dfs(root, 1)
        return self.max_avg
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-average-subtree/">1120. Maximum Average Subtree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the maximum <strong>average</strong> value of a <strong>subtree</strong> of that tree</em>. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</p>

            else:
                avg = s / c
        
<p>A <strong>subtree</strong> of a tree is any node of that tree plus all its descendants.</p>

<p>The <strong>average</strong> value of a tree is the sum of its values, divided by the number of nodes.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2019/04/09/1308_example_1.png" style="width: 132px; height: 123px;">
<pre><strong>Input:</strong> root = [5,6,1]
<strong>Output:</strong> 6.00000
For the node with value = 5 we have an average of (5 + 6 + 1) / 3 = 4.
For the node with value = 6 we have an average of 6 / 1 = 6.
For the node with value = 1 we have an average of 1 / 1 = 1.
So the answer is 6 which is the maximum.
</pre>

<strong>Output:</strong> 1.00000
</pre>

<ul>
	<li><code>0 &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 252-meeting-rooms
    def canAttendMeetings(self, intervals: List[List[int]]) -> bool:
        if not intervals:
        first = intervals[0]
            if first[1] > interval[0]:
            first = interval
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/meeting-rooms/">252. Meeting Rooms</a></h2><h3>Easy</h3><hr><div><p>Given an array of meeting time <code>intervals</code>&nbsp;where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, determine if a person could attend all meetings.</p>

<pre><strong>Input:</strong> intervals = [[0,30],[5,10],[15,20]]
<pre><strong>Input:</strong> intervals = [[7,10],[2,4]]
</pre>

<ul>
	<li><code>0 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>
	<li><code>intervals[i].length == 2</code></li>
	<li><code>0 &lt;= start<sub>i</sub> &lt;&nbsp;end<sub>i</sub> &lt;= 10<sup>6</sup></code></li>
</ul>
</div>

directory: 139-word-break
        
        n = len(s)
        def backtrack(index, s):
                if s[index : i] in wordDict and backtrack(i, s):
        return backtrack(0, s)
Notes: ​

        n = len(s)

</pre>

</pre>

</pre>

directory: 39-combination-sum
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        
        outputs = []
        def backtrack(index, path, s):
            if index >= len(candidates):
                if s == target:
                    outputs.append(path[:])
                return
            elif s + candidates[index] <= target:
                path.append(candidates[index])
                backtrack(index, path, s + candidates[index])
            backtrack(index+1, path, s)
        
        backtrack(0, [], 0)
        return outputs
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/combination-sum/">39. Combination Sum</a></h2><h3>Medium</h3><hr><div><p>Given an array of <strong>distinct</strong> integers <code>candidates</code> and a target integer <code>target</code>, return <em>a list of all <strong>unique combinations</strong> of </em><code>candidates</code><em> where the chosen numbers sum to </em><code>target</code><em>.</em> You may return the combinations in <strong>any order</strong>.</p>

                return
        
<p>The <strong>same</strong> number may be chosen from <code>candidates</code> an <strong>unlimited number of times</strong>. Two combinations are unique if the frequency of at least one of the chosen numbers is different.</p>

<p>It is <strong>guaranteed</strong> that the number of unique combinations that sum up to <code>target</code> is less than <code>150</code> combinations for the given input.</p>

<pre><strong>Input:</strong> candidates = [2,3,6,7], target = 7
<strong>Output:</strong> [[2,2,3],[7]]
2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
</pre>

<pre><strong>Input:</strong> candidates = [2,3,5], target = 8
<strong>Output:</strong> [[2,2,2,2],[2,3,3],[3,5]]
</pre>

<pre><strong>Input:</strong> candidates = [2], target = 1
</pre>

<ul>
	<li><code>1 &lt;= candidates.length &lt;= 30</code></li>
	<li><code>1 &lt;= candidates[i] &lt;= 200</code></li>
	<li>All elements of <code>candidates</code> are <strong>distinct</strong>.</li>
	<li><code>1 &lt;= target &lt;= 500</code></li>
</ul>
</div>

directory: 1347-minimum-number-of-steps-to-make-two-strings-anagram
    def minSteps(self, s: str, t: str) -> int:
        
        ans = 0
        c1, c2 = Counter(s), Counter(t)
        for c in set(s + t):
            if c2[c] < c1[c]:
                ans += c1[c] - c2[c]
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram/">1347. Minimum Number of Steps to Make Two Strings Anagram</a></h2><h3>Medium</h3><hr><div><p>You are given two strings of the same length <code>s</code> and <code>t</code>. In one step you can choose <strong>any character</strong> of <code>t</code> and replace it with <strong>another character</strong>.</p>

<p>Return <em>the minimum number of steps</em> to make <code>t</code> an anagram of <code>s</code>.</p>

<p>An <strong>Anagram</strong> of a string is a string that contains the same characters with a different (or the same) ordering.</p>

        ans = 0
        return ans

<pre><strong>Input:</strong> s = "bab", t = "aba"
<strong>Explanation:</strong> Replace the first 'a' in t with b, t = "bba" which is anagram of s.
</pre>

<pre><strong>Input:</strong> s = "leetcode", t = "practice"
<strong>Explanation:</strong> Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s.
</pre>

<pre><strong>Input:</strong> s = "anagram", t = "mangaar"
<strong>Explanation:</strong> "anagram" and "mangaar" are anagrams. 
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>
	<li><code>s.length == t.length</code></li>
	<li><code>s</code> and <code>t</code> consist of lowercase English letters only.</li>
</ul>
</div>

directory: 429-n-ary-tree-level-order-traversal
Python: """
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

    def levelOrder(self, root: 'Node') -> List[List[int]]:
            return []
        ans = []
        
            ans.append([])
                
                ans[-1].append(node.val)
                for c in node.children:
                    queue.append(c)
                
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/n-ary-tree-level-order-traversal/">429. N-ary Tree Level Order Traversal</a></h2><h3>Medium</h3><hr><div><p>Given an n-ary tree, return the <em>level order</em> traversal of its nodes' values.</p>

"""
"""

            return []
        ans = []
        
        return ans
        
<strong>Output:</strong> [[1],[3,2,4],[5,6]]
</pre>

<strong>Output:</strong> [[1],[2,3,4,5],[6,7,8,9,10],[11,12,13],[14]]
</pre>

<ul>
	<li>The height of the n-ary tree is less than or equal to <code>1000</code></li>
	<li>The total number of nodes is between <code>[0, 10<sup>4</sup>]</code></li>
</ul>
</div>

directory: 1209-remove-all-adjacent-duplicates-in-string-ii
    def removeDuplicates(self, s: str, k: int) -> str:
        
        stack = []
        s = list(s)
        
        for c in s:
            
            if not stack:
                stack.append([c, 1])
            else:
                if c == stack[-1][0]:
                    if stack[-1][1] == k-1:
                    else:
                        stack[-1][1] += 1
                else:
                    stack.append([c, 1])
        return "".join([c*count for c, count in stack])
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/">1209. Remove All Adjacent Duplicates in String II</a></h2><h3>Medium</h3><hr><div><p>You are given a string <code>s</code> and an integer <code>k</code>, a <code>k</code> <strong>duplicate removal</strong> consists of choosing <code>k</code> adjacent and equal letters from <code>s</code> and removing them, causing the left and the right side of the deleted substring to concatenate together.</p>

        stack = []
        s = list(s)
        
        for c in s:
            
            else:
                    else:
                else:
        
<p>We repeatedly make <code>k</code> <strong>duplicate removals</strong> on <code>s</code> until we no longer can.</p>

<p>Return the final string after all such duplicate removals have been made. It is guaranteed that the answer is unique.</p>

<pre><strong>Input:</strong> s = "abcd", k = 2
<strong>Output:</strong> "abcd"
<strong>Explanation: </strong>There's nothing to delete.</pre>

<pre><strong>Input:</strong> s = "deeedbbcccbdaa", k = 3
<strong>Output:</strong> "aa"
<strong>Explanation: 
</strong>First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"</pre>

<pre><strong>Input:</strong> s = "pbbcggttciiippooaais", k = 2
<strong>Output:</strong> "ps"
</pre>

<ul>
	<li><code>s</code> only contains lower case English letters.</li>
</ul>
</div>

directory: 1790-check-if-one-string-swap-can-make-strings-equal
    def areAlmostEqual(self, s1: str, s2: str) -> bool:
        
        count = 0
        for c1, c2 in zip(s1, s2):
            if c1 != c2:
                count += 1
        if (count==2 or count==0) and sorted(s1)==sorted(s2):
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/check-if-one-string-swap-can-make-strings-equal/">1790. Check if One String Swap Can Make Strings Equal</a></h2><h3>Easy</h3><hr><div><p>You are given two strings <code>s1</code> and <code>s2</code> of equal length. A <strong>string swap</strong> is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.</p>

        count = 0
            if c1 != c2:
                count += 1

<p>Return <code>true</code> <em>if it is possible to make both strings equal by performing <strong>at most one string swap </strong>on <strong>exactly one</strong> of the strings. </em>Otherwise, return <code>false</code>.</p>

<pre><strong>Input:</strong> s1 = "bank", s2 = "kanb"
<strong>Explanation:</strong> For example, swap the first character with the last character of s2 to make "bank".
</pre>

<pre><strong>Input:</strong> s1 = "attack", s2 = "defend"
<strong>Explanation:</strong> It is impossible to make them equal with one string swap.
</pre>

<pre><strong>Input:</strong> s1 = "kelb", s2 = "kelb"
<strong>Explanation:</strong> The two strings are already equal, so no string swap operation is required.
</pre>

<ul>
	<li><code>1 &lt;= s1.length, s2.length &lt;= 100</code></li>
	<li><code>s1.length == s2.length</code></li>
	<li><code>s1</code> and <code>s2</code> consist of only lowercase English letters.</li>
</ul>
</div>

directory: 91-decode-ways
    def numDecodings(self, s: str) -> int:
        n = len(s)
                return 1
            if s[index] == '0':
                return 0
            if index == n - 1:
                return 1
            answer = backtrack(index + 1)
            if int(s[index : index + 2]) <= 26:
                answer += backtrack(index + 2,)
            return answer
        
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/decode-ways/">91. Decode Ways</a></h2><h3>Medium</h3><hr><div><p>A message containing letters from <code>A-Z</code> can be <strong>encoded</strong> into numbers using the following mapping:</p>

<pre>'A' -&gt; "1"
'B' -&gt; "2"
...
'Z' -&gt; "26"
</pre>

        n = len(s)
                return 1
                return 0
                return 1
        
<p>To <strong>decode</strong> an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, <code>"11106"</code> can be mapped into:</p>

<ul>
	<li><code>"AAJF"</code> with the grouping <code>(1 1 10 6)</code></li>
	<li><code>"KJF"</code> with the grouping <code>(11 10 6)</code></li>
</ul>

<p>Note that the grouping <code>(1 11 06)</code> is invalid because <code>"06"</code> cannot be mapped into <code>'F'</code> since <code>"6"</code> is different from <code>"06"</code>.</p>

<p>Given a string <code>s</code> containing only digits, return <em>the <strong>number</strong> of ways to <strong>decode</strong> it</em>.</p>

<p>The test cases are generated so that the answer fits in a <strong>32-bit</strong> integer.</p>

<pre><strong>Input:</strong> s = "12"
<strong>Explanation:</strong> "12" could be decoded as "AB" (1 2) or "L" (12).
</pre>

<pre><strong>Input:</strong> s = "226"
<strong>Explanation:</strong> "226" could be decoded as "BZ" (2 26), "VF" (22 6), or "BBF" (2 2 6).
</pre>

<pre><strong>Input:</strong> s = "06"
<strong>Explanation:</strong> "06" cannot be mapped to "F" because of the leading zero ("6" is different from "06").
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 100</code></li>
	<li><code>s</code> contains only digits and may contain leading zero(s).</li>
</ul>
</div>

directory: 511-game-play-analysis-i
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/game-play-analysis-i/">511. Game Play Analysis I</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Activity</code></p>

<pre>+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| player_id    | int     |
| device_id    | int     |
| event_date   | date    |
| games_played | int     |
(player_id, event_date) is the primary key of this table.
This table shows the activity of players of some games.
Each row is a record of a player who logged in and played a number of games (possibly 0) before logging out on someday using some device.
</pre>

<p>Write an SQL query to report the <strong>first login date</strong> for each player.</p>

Activity table:
+-----------+-----------+------------+--------------+
| player_id | device_id | event_date | games_played |
| 1         | 2         | 2016-03-01 | 5            |
| 1         | 2         | 2016-05-02 | 6            |
| 2         | 3         | 2017-06-25 | 1            |
| 3         | 1         | 2016-03-02 | 0            |
| 3         | 4         | 2018-07-03 | 5            |
+-----------+-------------+
| player_id | first_login |
| 1         | 2016-03-01  |
| 2         | 2017-06-25  |
| 3         | 2016-03-02  |
</pre>
</div>

directory: 1465-maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts
    def maxArea(self, h: int, w: int, horizontalCuts: List[int], verticalCuts: List[int]) -> int:
        
        horizontalCuts.sort()
        verticalCuts.sort()
        
        horizontalCuts = [0] + horizontalCuts + [h]
        verticalCuts = [0] + verticalCuts + [w]
        max_h, max_w = 0, 0
        
        for i in range(1, len(horizontalCuts)):
            max_h = max(max_h, abs(horizontalCuts[i-1] - horizontalCuts[i]))
        for i in range(1, len(verticalCuts)):
            max_w = max(max_w, abs(verticalCuts[i-1] - verticalCuts[i]))
            
        return (max_h * max_w) % (10**9 + 7)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-area-of-a-piece-of-cake-after-horizontal-and-vertical-cuts/">1465. Maximum Area of a Piece of Cake After Horizontal and Vertical Cuts</a></h2><h3>Medium</h3><hr><div><p>You are given a rectangular cake of size <code>h x w</code> and two arrays of integers <code>horizontalCuts</code> and <code>verticalCuts</code> where:</p>

<ul>
	<li><code>horizontalCuts[i]</code> is the distance from the top of the rectangular cake to the <code>i<sup>th</sup></code> horizontal cut and similarly, and</li>
	<li><code>verticalCuts[j]</code> is the distance from the left of the rectangular cake to the <code>j<sup>th</sup></code> vertical cut.</li>
</ul>

<p>Return <em>the maximum area of a piece of cake after you cut at each horizontal and vertical position provided in the arrays</em> <code>horizontalCuts</code> <em>and</em> <code>verticalCuts</code>. Since the answer can be a large number, return this <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_2.png" style="width: 225px; height: 240px;">
<pre><strong>Input:</strong> h = 5, w = 4, horizontalCuts = [1,2,4], verticalCuts = [1,3]
<strong>Output:</strong> 4 
<strong>Explanation:</strong> The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green piece of cake has the maximum area.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/05/14/leetcode_max_area_3.png" style="width: 225px; height: 240px;">
<pre><strong>Input:</strong> h = 5, w = 4, horizontalCuts = [3,1], verticalCuts = [1]
<strong>Explanation:</strong> The figure above represents the given rectangular cake. Red lines are the horizontal and vertical cuts. After you cut the cake, the green and yellow pieces of cake have the maximum area.
</pre>

<pre><strong>Input:</strong> h = 5, w = 4, horizontalCuts = [3], verticalCuts = [3]
<strong>Output:</strong> 9
</pre>

<ul>
	<li><code>2 &lt;= h, w &lt;= 10<sup>9</sup></code></li>
	<li><code>1 &lt;= horizontalCuts.length &lt;= min(h - 1, 10<sup>5</sup>)</code></li>
	<li><code>1 &lt;= verticalCuts.length &lt;= min(w - 1, 10<sup>5</sup>)</code></li>
	<li><code>1 &lt;= horizontalCuts[i] &lt; h</code></li>
	<li><code>1 &lt;= verticalCuts[i] &lt; w</code></li>
	<li>All the elements in <code>horizontalCuts</code> are distinct.</li>
	<li>All the elements in <code>verticalCuts</code> are distinct.</li>
</ul>
</div>

directory: 1457-pseudo-palindromic-paths-in-a-binary-tree
    def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
        self.dfs(root, Counter())
    
    def dfs(self,root, counter):
        if not root.left and not root.right:
            counter[root.val] += 1
            self.count += self.checkPalindrome(counter)
            counter[root.val] -= 1
        else:
                self.dfs(root.left, counter)
                self.dfs(root.right, counter)
    
    def checkPalindrome(self, counter):
        found = False
        for k, v in counter.items():
            if v % 2 != 0 and found:
            elif v % 2 !=0:
                found = True
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/pseudo-palindromic-paths-in-a-binary-tree/">1457. Pseudo-Palindromic Paths in a Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given a binary tree where node values are digits from 1 to 9. A path in the binary tree is said to be <strong>pseudo-palindromic</strong> if at least one permutation of the node values in the path is a palindrome.</p>

        else:
    
<p><em>Return the number of <strong>pseudo-palindromic</strong> paths going from the root node to leaf nodes.</em></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2020/05/06/palindromic_paths_1.png" style="width: 300px; height: 201px;"></p>

<pre><strong>Input:</strong> root = [2,3,1,3,1,null,1]
<strong>Explanation:</strong> The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the red path [2,3,3], the green path [2,1,1], and the path [2,3,1]. Among these paths only red path and green path are pseudo-palindromic paths since the red path [2,3,3] can be rearranged in [3,2,3] (palindrome) and the green path [2,1,1] can be rearranged in [1,2,1] (palindrome).
</pre>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/05/07/palindromic_paths_2.png" style="width: 300px; height: 314px;"></strong></p>

<pre><strong>Input:</strong> root = [2,1,1,1,3,null,null,null,null,null,1]
<strong>Output:</strong> 1 
<strong>Explanation:</strong> The figure above represents the given binary tree. There are three paths going from the root node to leaf nodes: the green path [2,1,1], the path [2,1,3,1], and the path [2,1]. Among these paths only the green path is pseudo-palindromic since [2,1,1] can be rearranged in [1,2,1] (palindrome).
</pre>

<pre><strong>Input:</strong> root = [9]
</pre>

<ul>
	<li><code>1 &lt;= Node.val &lt;= 9</code></li>
</ul>
</div>

directory: 1858-longest-word-with-all-prefixes
                    break
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/longest-word-with-all-prefixes/">1858. Longest Word With All Prefixes</a></h2><h3>Medium</h3><hr><div><p>Given an array of strings <code>words</code>, find the <strong>longest</strong> string in <code>words</code> such that <strong>every prefix</strong> of it is also in <code>words</code>.</p>

                    break

<ul>
	<li>For example, let <code>words = ["a", "app", "ap"]</code>. The string <code>"app"</code> has prefixes <code>"ap"</code> and <code>"a"</code>, all of which are in <code>words</code>.</li>
</ul>

<p>Return <em>the string described above. If there is more than one string with the same length, return the <strong>lexicographically smallest</strong> one, and if no string exists, return </em><code>""</code>.</p>

<pre><strong>Input:</strong> words = ["k","ki","kir","kira", "kiran"]
<strong>Output:</strong> "kiran"
<strong>Explanation:</strong> "kiran" has prefixes "kira", "kir", "ki", and "k", and all of them appear in words.
</pre>

<pre><strong>Input:</strong> words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
<strong>Explanation:</strong> Both "apple" and "apply" have all their prefixes in words.
However, "apple" is lexicographically smaller, so we return that.
</pre>

<pre><strong>Input:</strong> words = ["abc", "bc", "ab", "qwe"]
</pre>

<ul>
	<li><code>1 &lt;= words.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= words[i].length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= sum(words[i].length) &lt;= 10<sup>5</sup></code></li>

directory: 732-my-calendar-iii
Python: from sortedcontainers import SortedDict

class MyCalendarThree:

        self.diff = SortedDict()

    def book(self, start: int, end: int) -> int:
        self.diff[start] = self.diff.get(start, 0) + 1
        self.diff[end] = self.diff.get(end, 0) - 1
        cur = res = 0
        for delta in self.diff.values():
            cur += delta
            res = max(cur, res)
        return res
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/my-calendar-iii/">732. My Calendar III</a></h2><h3>Hard</h3><hr><div><p>A <code>k</code>-booking happens when <code>k</code> events have some non-empty intersection (i.e., there is some time that is common to all <code>k</code> events.)</p>

<p>You are given some events <code>[start, end)</code>, after each given event, return an integer <code>k</code> representing the maximum <code>k</code>-booking between all the previous events.</p>

from sortedcontainers import SortedDict

        cur = res = 0
        return res

<p>Implement the <code>MyCalendarThree</code> class:</p>

<ul>
	<li><code>MyCalendarThree()</code> Initializes the object.</li>
	<li><code>int book(int start, int end)</code> Returns an integer <code>k</code> representing the largest integer such that there exists a <code>k</code>-booking in the calendar.</li>
</ul>

["MyCalendarThree", "book", "book", "book", "book", "book", "book"]
[[], [10, 20], [50, 60], [10, 40], [5, 15], [5, 10], [25, 55]]
[null, 1, 1, 2, 3, 3, 3]

MyCalendarThree myCalendarThree = new MyCalendarThree();
myCalendarThree.book(10, 20); // return 1, The first event can be booked and is disjoint, so the maximum k-booking is a 1-booking.
myCalendarThree.book(50, 60); // return 1, The second event can be booked and is disjoint, so the maximum k-booking is a 1-booking.
myCalendarThree.book(10, 40); // return 2, The third event [10, 40) intersects the first event, and the maximum k-booking is a 2-booking.
myCalendarThree.book(5, 15); // return 3, The remaining events cause the maximum K-booking to be only a 3-booking.
myCalendarThree.book(5, 10); // return 3
myCalendarThree.book(25, 55); // return 3
</pre>

<ul>
	<li>At most <code>400</code> calls will be made to <code>book</code>.</li>
</ul>
</div>

directory: 694-number-of-distinct-islands
    def numDistinctIslands(self, grid: List[List[int]]) -> int:
        
        def dfs(r, c, direction):
                return 
            if (r, c) in seen:
                return
            seen.add((r,c))
            path_signature.append(direction)
            dfs(r + 1, c, "D")
            dfs(r - 1, c, "U")
            dfs(r, c - 1, "L")
            dfs(r, c + 1, "R")
            path_signature.append("0")
        
        unique_islands = set()
        for row in range(len(grid)):
            for col in range(len(grid[0])):
                path_signature = []
                dfs(row, col, "0")
                if path_signature:
                    unique_islands.add(tuple(path_signature))
        
        return len(unique_islands)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-distinct-islands/">694. Number of Distinct Islands</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> binary matrix <code>grid</code>. An island is a group of <code>1</code>'s (representing land) connected <strong>4-directionally</strong> (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.</p>

                return 
                return
        
<p>An island is considered to be the same as another if and only if one island can be translated (and not rotated or reflected) to equal the other.</p>

<p>Return <em>the number of <b>distinct</b> islands</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/05/01/distinctisland1-1-grid.jpg" style="width: 413px; height: 334px;">
<pre><strong>Input:</strong> grid = [[1,1,0,0,0],[1,1,0,0,0],[0,0,0,1,1],[0,0,0,1,1]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/05/01/distinctisland1-2-grid.jpg" style="width: 413px; height: 334px;">
<pre><strong>Input:</strong> grid = [[1,1,0,1,1],[1,0,0,0,0],[0,0,0,0,1],[1,1,0,1,1]]
</pre>

<ul>
</ul>
</div>

directory: 101-symmetric-tree
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        
        def isMirror(left, right):
            if not left and not right:
            if not left or not right:
            return left.val == right.val and isMirror(left.right, right.left) and isMirror(left.left, right.right)
        
        return isMirror(root, root)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/symmetric-tree/">101. Symmetric Tree</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, <em>check whether it is a mirror of itself</em> (i.e., symmetric around its center).</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/symtree1.jpg" style="width: 354px; height: 291px;">
<pre><strong>Input:</strong> root = [1,2,2,3,4,4,3]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/symtree2.jpg" style="width: 308px; height: 258px;">
<pre><strong>Input:</strong> root = [1,2,2,null,3,null,3]
</pre>

<ul>
</ul>

<strong>Follow up:</strong> Could you solve it both recursively and iteratively?</div>

directory: 0415-add-strings
    def addStrings(self, num1: str, num2: str) -> str:
        
        """
        
        1. Use library functions to convert to integer, compute sum, convert to string
        
        return str(int(num1) + int(num2))
        
        2. Design Custom Function to do conversions mentioned above.
                
        3. Iterate through the strings and then add using elementary math
        
        """
        
        s, c = 0, 0
        
        n, m = len(num1) - 1, len(num2) - 1
        
        ans = ''
        
        while n >= 0 or m >= 0:
            
            if n >= 0:
                val1 = ord(num1[n]) - ord('0')
            else:
                val1 = 0
            
            if m >= 0:
                val2 = ord(num2[m]) - ord('0')
            else:
                val2 = 0
            #print(val1, val2)
            
            c, s = divmod(val1 + val2 + c, 10)
            ans += str(s)
            n -= 1
            m -= 1
        if c:
            ans += '1'
        return ans[::-1]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/add-strings/">415. Add Strings</a></h2><h3>Easy</h3><hr><div><p>Given two non-negative integers, <code>num1</code> and <code>num2</code> represented as string, return <em>the sum of</em> <code>num1</code> <em>and</em> <code>num2</code> <em>as a string</em>.</p>

        """
        
        """
        
        s, c = 0, 0
        
        ans = ''
        
            if n >= 0:
            else:
                val1 = 0
            
            if m >= 0:
            else:
                val2 = 0
            
            n -= 1
            m -= 1
        if c:
            ans += '1'
        
<p>You must solve the problem without using any built-in library for handling large integers (such as <code>BigInteger</code>). You must also not convert the inputs to integers directly.</p>

<pre><strong>Input:</strong> num1 = "11", num2 = "123"
<strong>Output:</strong> "134"
</pre>

<pre><strong>Input:</strong> num1 = "456", num2 = "77"
<strong>Output:</strong> "533"
</pre>

<pre><strong>Input:</strong> num1 = "0", num2 = "0"
<strong>Output:</strong> "0"
</pre>

<ul>
	<li><code>1 &lt;= num1.length, num2.length &lt;= 10<sup>4</sup></code></li>
	<li><code>num1</code> and <code>num2</code> consist of only digits.</li>
	<li><code>num1</code> and <code>num2</code> don't have any leading zeros except for the zero itself.</li>
</ul>
</div>

directory: 981-time-based-key-value-store
Python: class TimeMap:

class TimeMap:

        self.store = {}
        
    def set(self, key: str, value: str, timestamp: int) -> None:
        
        if key not in self.store:
            self.store[key] = []
        self.store[key].append([timestamp, value])
        
    def get(self, key: str, timestamp: int) -> str:
        
            return ""
        if timestamp < self.store[key][0][0]:
            return ""
        left, right = 0, len(self.store[key])
        while left < right:
            if self.store[key][mid][0] > timestamp :
                right = mid
            else:
                left = mid + 1
        return "" if right == 0 else self.store[key][right-1][1] 
                                       
# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)

def __init__(self):
        
            return ""
            return ""
                right = mid
            else:
                                       
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/time-based-key-value-store/">981. Time Based Key-Value Store</a></h2><h3>Medium</h3><hr><div><p>Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.</p>

<p>Implement the <code>TimeMap</code> class:</p>

<ul>
	<li><code>TimeMap()</code> Initializes the object of the data structure.</li>
	<li><code>void set(String key, String value, int timestamp)</code> Stores the key <code>key</code> with the value <code>value </code>at the given time <code>timestamp</code>.</li>
	<li><code>String get(String key, int timestamp)</code> Returns a value such that <code>set</code> was called previously, with <code>timestamp_prev &lt;= timestamp</code>. If there are multiple such values, it returns the value associated with the largest <code>timestamp_prev</code>. If there are no values, it returns <code>""</code>.</li>
</ul>

["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
[null, null, "bar", "bar", null, "bar2", "bar2"]

TimeMap timeMap = new TimeMap();
timeMap.set("foo", "bar", 1);  // store the key "foo" and value "bar" along with timestamp = 1.
timeMap.get("foo", 1);         // return "bar"
timeMap.get("foo", 3);         // return "bar", since there is no value corresponding to foo at timestamp 3 and timestamp 2, then the only value is at timestamp 1 is "bar".
timeMap.set("foo", "bar2", 4); // store the key "foo" and value "bar2" along with timestamp = 4.
timeMap.get("foo", 4);         // return "bar2"
timeMap.get("foo", 5);         // return "bar2"
</pre>

<ul>
	<li><code>1 &lt;= key.length, value.length &lt;= 100</code></li>
	<li><code>key</code> and <code>value</code> consist of lowercase English letters and digits.</li>
	<li><code>1 &lt;= timestamp &lt;= 10<sup>7</sup></code></li>
	<li>All the timestamps <code>timestamp</code> of <code>set</code> are strictly increasing.</li>
	<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>set</code> and <code>get</code>.</li>
</ul>
</div>

directory: 136-single-number
    def singleNumber(self, nums: List[int]) -> int:
        ans = 0
            ans ^= num
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/single-number/">136. Single Number</a></h2><h3>Easy</h3><hr><div><p>Given a <strong>non-empty</strong>&nbsp;array of integers <code>nums</code>, every element appears <em>twice</em> except for one. Find that single one.</p>

<p>You must&nbsp;implement a solution with a linear runtime complexity and use&nbsp;only constant&nbsp;extra space.</p>

<pre><strong>Input:</strong> nums = [2,2,1]
<pre><strong>Input:</strong> nums = [4,1,2,1,2]
<pre><strong>Input:</strong> nums = [1]
</pre>

        ans = 0
            ans ^= num
        return ans

<ul>
	<li><code>-3 * 10<sup>4</sup> &lt;= nums[i] &lt;= 3 * 10<sup>4</sup></code></li>
	<li>Each element in the array appears twice except for one element which appears only once.</li>
</ul>
</div>

directory: 532-k-diff-pairs-in-an-array
    def findPairs(self, nums: List[int], k: int) -> int:
        # 1 1 3 4 5
        start, end = 0, 1
        while start < len(nums) and end < len(nums):
            if start!=end and nums[end] - nums[start] == k:
                seen.add((nums[start], nums[end]))
                end+=1
            elif nums[end] - nums[start] < k:
                end+=1
            else:
                start+=1
        return len(seen)
Notes: # 1, 1, 3, 4, 5 k = 2
# 1, 2, 3, 4, 5 k = 1
# 0, 1, 2, 2, 3, 3, 3,
nums.sort()
start, end = 0, 1
seen = set()
while start< len(nums) and end < len(nums):
if end!=start and nums[end] - nums[start] == k:
seen.add((nums[start], nums[end]))
end+=1
elif nums[end] - nums[start] < k:
end += 1
else:
start+=1
return len(seen)
Readme: <h2><a href="https://leetcode.com/problems/k-diff-pairs-in-an-array/">532. K-diff Pairs in an Array</a></h2><h3>Medium</h3><hr><div><p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the number of <b>unique</b> k-diff pairs in the array</em>.</p>

        # 1 1 3 4 5
                end+=1
                end+=1
            else:
                start+=1
                
<p>A <strong>k-diff</strong> pair is an integer pair <code>(nums[i], nums[j])</code>, where the following are true:</p>

<ul>
	<li><code>0 &lt;= i &lt; j &lt; nums.length</code></li>
	<li><code>|nums[i] - nums[j]| == k</code></li>
</ul>

<p><strong>Notice</strong> that <code>|val|</code> denotes the absolute value of <code>val</code>.</p>

<pre><strong>Input:</strong> nums = [3,1,4,1,5], k = 2
<strong>Explanation:</strong> There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of <strong>unique</strong> pairs.
</pre>

<pre><strong>Input:</strong> nums = [1,2,3,4,5], k = 1
<strong>Explanation:</strong> There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
</pre>

<pre><strong>Input:</strong> nums = [1,3,1,5,4], k = 0
<strong>Explanation:</strong> There is one 0-diff pair in the array, (1, 1).
</pre>

<ul>
	<li><code>-10<sup>7</sup> &lt;= nums[i] &lt;= 10<sup>7</sup></code></li>
	<li><code>0 &lt;= k &lt;= 10<sup>7</sup></code></li>
</ul>
</div>

directory: 549-binary-tree-longest-consecutive-sequence-ii
    def longestConsecutive(self, root: Optional[TreeNode]) -> int:
        self.longest = 0
        def dfs(root):
                return 0, 0
            incr, decr = 1, 1
            left_i, left_d = dfs(root.left)
            right_i, right_d = dfs(root.right)
                if root.left.val == root.val + 1:
                    incr = left_i + 1
                if root.left.val == root.val - 1:
                    decr = left_d + 1
                if root.right.val == root.val + 1:
                    incr = max(incr, 1 + right_i)
                if root.right.val == root.val - 1:
                    decr = max(decr, 1 + right_d)
            self.longest = max(self.longest, incr + decr - 1)
            return incr, decr
        dfs(root)        
        return self.longest
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-tree-longest-consecutive-sequence-ii/">549. Binary Tree Longest Consecutive Sequence II</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the length of the longest consecutive path in the tree</em>.</p>

                return 0, 0
        dfs(root)        
        
<p>A consecutive path is a path where the values of the consecutive nodes in the path differ by one. This path can be either increasing or decreasing.</p>

<ul>
	<li>For example, <code>[1,2,3,4]</code> and <code>[4,3,2,1]</code> are both considered valid, but the path <code>[1,2,4,3]</code> is not valid.</li>
</ul>

<p>On the other hand, the path can be in the child-Parent-child order, where not necessarily be parent-child order.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/consec2-1-tree.jpg" style="width: 207px; height: 183px;">
<pre><strong>Input:</strong> root = [1,2,3]
<strong>Explanation:</strong> The longest consecutive path is [1, 2] or [2, 1].
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/consec2-2-tree.jpg" style="width: 207px; height: 183px;">
<pre><strong>Input:</strong> root = [2,1,3]
<strong>Explanation:</strong> The longest consecutive path is [1, 2, 3] or [3, 2, 1].
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 3 * 10<sup>4</sup>]</code>.</li>
	<li><code>-3 * 10<sup>4</sup> &lt;= Node.val &lt;= 3 * 10<sup>4</sup></code></li>
</ul>
</div>

directory: 62-unique-paths
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/unique-paths/">62. Unique Paths</a></h2><h3>Medium</h3><hr><div><p>There is a robot on an <code>m x n</code> grid. The robot is initially located at the <strong>top-left corner</strong> (i.e., <code>grid[0][0]</code>). The robot tries to move to the <strong>bottom-right corner</strong> (i.e., <code>grid[m - 1][n - 1]</code>). The robot can only move either down or right at any point in time.</p>

<p>Given the two integers <code>m</code> and <code>n</code>, return <em>the number of possible unique paths that the robot can take to reach the bottom-right corner</em>.</p>

<p>The test cases are generated so that the answer will be less than or equal to <code>2 * 10<sup>9</sup></code>.</p>

<img src="https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png" style="width: 400px; height: 183px;">
<pre><strong>Input:</strong> m = 3, n = 7
</pre>

<pre><strong>Input:</strong> m = 3, n = 2
<strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -&gt; Down -&gt; Down
2. Down -&gt; Down -&gt; Right
3. Down -&gt; Right -&gt; Down
</pre>

<ul>
</ul>
</div>

directory: 1379-find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/">1379. Find a Corresponding Node of a Binary Tree in a Clone of That Tree</a></h2><h3>Medium</h3><hr><div><p>Given two binary trees <code>original</code> and <code>cloned</code> and given a reference to a node <code>target</code> in the original tree.</p>

<p>The <code>cloned</code> tree is a <strong>copy of</strong> the <code>original</code> tree.</p>

<p>Return <em>a reference to the same node</em> in the <code>cloned</code> tree.</p>

<p><strong>Note</strong> that you are <strong>not allowed</strong> to change any of the two trees or the <code>target</code> node and the answer <strong>must be</strong> a reference to a node in the <code>cloned</code> tree.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/02/21/e1.png" style="width: 544px; height: 426px;">
<pre><strong>Input:</strong> tree = [7,4,3,null,null,6,19], target = 3
<strong>Explanation:</strong> In all examples the original and cloned trees are shown. The target node is a green node from the original tree. The answer is the yellow node from the cloned tree.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/02/21/e2.png" style="width: 221px; height: 159px;">
<pre><strong>Input:</strong> tree = [7], target =  7
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/02/21/e3.png" style="width: 459px; height: 486px;">
<pre><strong>Input:</strong> tree = [8,null,6,null,5,null,4,null,3,null,2,null,1], target = 4
</pre>

<ul>
	<li>The number of nodes in the <code>tree</code> is in the range <code>[1, 10<sup>4</sup>]</code>.</li>
	<li>The values of the nodes of the <code>tree</code> are unique.</li>
	<li><code>target</code> node is a node from the <code>original</code> tree and is not <code>null</code>.</li>
</ul>

<p><strong>Follow up:</strong> Could you solve the problem if repeated values on the tree are allowed?</p>
</div>

directory: 1541-minimum-insertions-to-balance-a-parentheses-string
    def minInsertions(self, s: str) -> int:
        
        stack = []
        i, n = 0, len(s)
        ans = 0
        while i < n:
            if i < n and s[i] == '(':
                stack.append(s[i])
                i += 1
            else:
                if i < n - 1 and s[i:i+2] == '))':
                    if not stack:
                        ans += 1
                    else:
                    i += 2
                elif i < n and s[i] == ')':
                    if stack:
                        ans += 1
                    else:
                        ans += 2
                    i += 1
        return len(stack) * 2  + ans
Notes: ​
Readme:

        stack = []
        ans = 0
        while i < n:
                i += 1
            else:
                        ans += 1
                    else:
                    i += 2
                    if stack:
                        ans += 1
                    else:
                        ans += 2
                    i += 1

directory: 1094-car-pooling
    def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
        
        timestamp = []
        for trip in trips:
            timestamp.append([trip[1], trip[0]])
            timestamp.append([trip[2], -trip[0]])
        #print(timestamp)
        timestamp.sort()
        used_cap = 0
        for time, passanger_change in timestamp:
            used_cap += passanger_change
            if used_cap > capacity:
Notes: trips.sort(key = lambda x : x[1] - x[2])
prev, start_prev, end_prev = None, None, None
for trip in trips:
passangers, start, end = trip
if not prev or start >= end:
prev, start_prev, end_prev = passangers, start, end
else:
if start < end_prev and prev + passangers > capacity:
return False
else:
prev += passangers
end_prev = end
return True
Readme: <h2><a href="https://leetcode.com/problems/car-pooling/">1094. Car Pooling</a></h2><h3>Medium</h3><hr><div><p>There is a car with <code>capacity</code> empty seats. The vehicle only drives east (i.e., it cannot turn around and drive west).</p>

<p>You are given the integer <code>capacity</code> and an array <code>trips</code> where <code>trips[i] = [numPassengers<sub>i</sub>, from<sub>i</sub>, to<sub>i</sub>]</code> indicates that the <code>i<sup>th</sup></code> trip has <code>numPassengers<sub>i</sub></code> passengers and the locations to pick them up and drop them off are <code>from<sub>i</sub></code> and <code>to<sub>i</sub></code> respectively. The locations are given as the number of kilometers due east from the car's initial location.</p>

<p>Return <code>true</code><em> if it is possible to pick up and drop off all passengers for all the given trips, or </em><code>false</code><em> otherwise</em>.</p>

<pre><strong>Input:</strong> trips = [[2,1,5],[3,3,7]], capacity = 4
</pre>

<pre><strong>Input:</strong> trips = [[2,1,5],[3,3,7]], capacity = 5
</pre>

<ul>
	<li><code>1 &lt;= trips.length &lt;= 1000</code></li>
	<li><code>trips[i].length == 3</code></li>
	<li><code>1 &lt;= numPassengers<sub>i</sub> &lt;= 100</code></li>
	<li><code>0 &lt;= from<sub>i</sub> &lt; to<sub>i</sub> &lt;= 1000</code></li>
	<li><code>1 &lt;= capacity &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 1700-number-of-students-unable-to-eat-lunch
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-students-unable-to-eat-lunch/">1700. Number of Students Unable to Eat Lunch</a></h2><h3>Easy</h3><hr><div><p>The school cafeteria offers circular and square sandwiches at lunch break, referred to by numbers <code>0</code> and <code>1</code> respectively. All students stand in a queue. Each student either prefers square or circular sandwiches.</p>

<p>The number of sandwiches in the cafeteria is equal to the number of students. The sandwiches are placed in a <strong>stack</strong>. At each step:</p>

<ul>
	<li>If the student at the front of the queue <strong>prefers</strong> the sandwich on the top of the stack, they will <strong>take it</strong> and leave the queue.</li>
	<li>Otherwise, they will <strong>leave it</strong> and go to the queue's end.</li>
</ul>

<p>This continues until none of the queue students want to take the top sandwich and are thus unable to eat.</p>

<p>You are given two integer arrays <code>students</code> and <code>sandwiches</code> where <code>sandwiches[i]</code> is the type of the <code>i<sup>​​​​​​th</sup></code> sandwich in the stack (<code>i = 0</code> is the top of the stack) and <code>students[j]</code> is the preference of the <code>j<sup>​​​​​​th</sup></code> student in the initial queue (<code>j = 0</code> is the front of the queue). Return <em>the number of students that are unable to eat.</em></p>

<pre><strong>Input:</strong> students = [1,1,0,0], sandwiches = [0,1,0,1]
<strong>Output:</strong> 0<strong> 
Explanation:</strong>
- Front student leaves the top sandwich and returns to the end of the line making students = [1,0,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,0,1,1].
- Front student takes the top sandwich and leaves the line making students = [0,1,1] and sandwiches = [1,0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [1,1,0].
- Front student takes the top sandwich and leaves the line making students = [1,0] and sandwiches = [0,1].
- Front student leaves the top sandwich and returns to the end of the line making students = [0,1].
- Front student takes the top sandwich and leaves the line making students = [1] and sandwiches = [1].
- Front student takes the top sandwich and leaves the line making students = [] and sandwiches = [].
Hence all students are able to eat.
</pre>

<pre><strong>Input:</strong> students = [1,1,1,0,0,1], sandwiches = [1,0,0,0,1,1]
</pre>

<ul>
	<li><code>1 &lt;= students.length, sandwiches.length &lt;= 100</code></li>
	<li><code>students.length == sandwiches.length</code></li>
	<li><code>sandwiches[i]</code> is <code>0</code> or <code>1</code>.</li>
	<li><code>students[i]</code> is <code>0</code> or <code>1</code>.</li>
</ul>
</div>

directory: 16-3sum-closest
    def threeSumClosest(self, nums: List[int], target: int) -> int:
        diff = float('inf')
            lo, hi = i + 1, len(nums) - 1
            while (lo < hi):
                sum = nums[i] + nums[lo] + nums[hi]
                if abs(target - sum) < abs(diff):
                    diff = target - sum
                if sum < target:
                    lo += 1
                else:
                    hi -= 1
            if diff == 0:
                break
        return target - diff
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/3sum-closest/">16. 3Sum Closest</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> of length <code>n</code> and an integer <code>target</code>, find three integers in <code>nums</code> such that the sum is closest to <code>target</code>.</p>

<p>Return <em>the sum of the three integers</em>.</p>

                    lo += 1
                else:
                    hi -= 1
                break

<p>You may assume that each input would have exactly one solution.</p>

<pre><strong>Input:</strong> nums = [-1,2,1,-4], target = 1
<strong>Explanation:</strong> The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
</pre>

<pre><strong>Input:</strong> nums = [0,0,0], target = 1
</pre>

<ul>
	<li><code>3 &lt;= nums.length &lt;= 1000</code></li>
	<li><code>-1000 &lt;= nums[i] &lt;= 1000</code></li>
	<li><code>-10<sup>4</sup> &lt;= target &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 340-longest-substring-with-at-most-k-distinct-characters
    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
        
        max_len = 0
        for end, c in enumerate(s):
            dic[c] = end
            if len(dic) > k:
                start = min(dic.values())
                del dic[s[start]]
                start = start + 1 
            max_len = max(max_len, end - start + 1)
        return max_len
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters/">340. Longest Substring with At Most K Distinct Characters</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code> and an integer <code>k</code>, return <em>the length of the longest substring of</em> <code>s</code> <em>that contains at most</em> <code>k</code> <em><strong>distinct</strong> characters</em>.</p>

        max_len = 0

<pre><strong>Input:</strong> s = "eceba", k = 2
<strong>Explanation:</strong> The substring is "ece" with length 3.</pre>

<pre><strong>Input:</strong> s = "aa", k = 1
<strong>Explanation:</strong> The substring is "aa" with length 2.
</pre>

<ul>
	<li><code>0 &lt;= k &lt;= 50</code></li>
</ul>
</div>

directory: 133-clone-graph
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/clone-graph/">133. Clone Graph</a></h2><h3>Medium</h3><hr><div><p>Given a reference of a node in a <strong><a href="https://en.wikipedia.org/wiki/Connectivity_(graph_theory)#Connected_graph" target="_blank">connected</a></strong> undirected graph.</p>

<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> (clone) of the graph.</p>

<p>Each node in the graph contains a value (<code>int</code>) and a list (<code>List[Node]</code>) of its neighbors.</p>

    public List&lt;Node&gt; neighbors;
}
</pre>

<p><strong>Test case format:</strong></p>

<p>For simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with <code>val == 1</code>, the second node with <code>val == 2</code>, and so on. The graph is represented in the test case using an adjacency list.</p>

<p><b>An adjacency list</b> is a collection of unordered <b>lists</b> used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.</p>

<p>The given node will always be the first node with <code>val = 1</code>. You must return the <strong>copy of the given node</strong> as a reference to the cloned graph.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2019/11/04/133_clone_graph_question.png" style="width: 454px; height: 500px;">
<pre><strong>Input:</strong> adjList = [[2,4],[1,3],[2,4],[1,3]]
<strong>Output:</strong> [[2,4],[1,3],[2,4],[1,3]]
<strong>Explanation:</strong> There are 4 nodes in the graph.
1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).
4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/01/07/graph.png" style="width: 163px; height: 148px;">
<pre><strong>Input:</strong> adjList = [[]]
<strong>Output:</strong> [[]]
<strong>Explanation:</strong> Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.
</pre>

<pre><strong>Input:</strong> adjList = []
<strong>Explanation:</strong> This an empty graph, it does not have any nodes.
</pre>

<ul>
	<li>The number of nodes in the graph is in the range <code>[0, 100]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 100</code></li>
	<li><code>Node.val</code> is unique for each node.</li>
	<li>There are no repeated edges and no self-loops in the graph.</li>
	<li>The Graph is connected and all nodes can be visited starting from the given node.</li>
</ul>
</div>

directory: 394-decode-string
    def decodeString(self, string: str) -> str:

        nums = []
        strs = []
        num = ""
        s = ""
        for i, ch in enumerate(string):
            if ch.isdigit():
                num += ch
            elif ch == "[":
                nums.append(int(num))
                strs.append(s)
                num = ""
                s = ""
            elif ch == "]":
                s =  strs.pop() + nums.pop() * s
            else:
                s += ch

        return s
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/decode-string/">394. Decode String</a></h2><h3>Medium</h3><hr><div><p>Given an encoded string, return its decoded string.</p>

<p>The encoding rule is: <code>k[encoded_string]</code>, where the <code>encoded_string</code> inside the square brackets is being repeated exactly <code>k</code> times. Note that <code>k</code> is guaranteed to be a positive integer.</p>

        nums = []
        strs = []
        num = ""
        s = ""
                num += ch
                num = ""
                s = ""
            else:
                s += ch

        return s

<p>You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc.</p>

<p>Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, <code>k</code>. For example, there will not be input like <code>3a</code> or <code>2[4]</code>.</p>

<pre><strong>Input:</strong> s = "3[a]2[bc]"
<strong>Output:</strong> "aaabcbc"
</pre>

<pre><strong>Input:</strong> s = "3[a2[c]]"
<strong>Output:</strong> "accaccacc"
</pre>

<pre><strong>Input:</strong> s = "2[abc]3[cd]ef"
<strong>Output:</strong> "abcabccdcdcdef"
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 30</code></li>
	<li><code>s</code> consists of lowercase English letters, digits, and square brackets <code>'[]'</code>.</li>
	<li><code>s</code> is guaranteed to be <strong>a valid</strong> input.</li>
	<li>All the integers in <code>s</code> are in the range <code>[1, 300]</code>.</li>
</ul>
</div>

directory: 199-binary-tree-right-side-view
            return []
        ans = []
            
        return ans
Notes: ​

</pre>

</pre>

</pre>

<ul>
</ul>
</div>

directory: 560-subarray-sum-equals-k
    def subarraySum(self, nums: List[int], k: int) -> int:
        
        dic = {0 : 1}
        ans = 0
            prefixSum += n
            if prefixSum - k in dic:
                ans += dic[prefixSum - k]
            dic[prefixSum] = dic.get(prefixSum, 0) + 1
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/subarray-sum-equals-k/">560. Subarray Sum Equals K</a></h2><h3>Medium</h3><hr><div><p>Given an array of integers <code>nums</code> and an integer <code>k</code>, return <em>the total number of subarrays whose sum equals to</em> <code>k</code>.</p>

<p>A subarray is a contiguous <strong>non-empty</strong> sequence of elements within an array.</p>

        dic = {0 : 1}
        ans = 0
        return ans

<pre><strong>Input:</strong> nums = [1,1,1], k = 2
<pre><strong>Input:</strong> nums = [1,2,3], k = 3
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>-10<sup>7</sup> &lt;= k &lt;= 10<sup>7</sup></code></li>
</ul>
</div>

directory: 0406-queue-reconstruction-by-height
    def reconstructQueue(self, people: List[List[int]]) -> List[List[int]]:
        
        """
        [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
        [5, 0], 
        """
        
        people.sort(key = lambda x : (-x[0], x[1]))
        output = []
        for p in people:
            output.insert(p[1], p)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/queue-reconstruction-by-height/">406. Queue Reconstruction by Height</a></h2><h3>Medium</h3><hr><div><p>You are given an array of people, <code>people</code>, which are the attributes of some people in a queue (not necessarily in order). Each <code>people[i] = [h<sub>i</sub>, k<sub>i</sub>]</code> represents the <code>i<sup>th</sup></code> person of height <code>h<sub>i</sub></code> with <strong>exactly</strong> <code>k<sub>i</sub></code> other people in front who have a height greater than or equal to <code>h<sub>i</sub></code>.</p>

        """
        [5, 0], 
        """
        
        output = []
        
<p>Reconstruct and return <em>the queue that is represented by the input array </em><code>people</code>. The returned queue should be formatted as an array <code>queue</code>, where <code>queue[j] = [h<sub>j</sub>, k<sub>j</sub>]</code> is the attributes of the <code>j<sup>th</sup></code> person in the queue (<code>queue[0]</code> is the person at the front of the queue).</p>

<pre><strong>Input:</strong> people = [[7,0],[4,4],[7,1],[5,0],[6,1],[5,2]]
<strong>Output:</strong> [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]]
Person 0 has height 5 with no other people taller or the same height in front.
Person 1 has height 7 with no other people taller or the same height in front.
Person 2 has height 5 with two persons taller or the same height in front, which is person 0 and 1.
Person 3 has height 6 with one person taller or the same height in front, which is person 1.
Person 4 has height 4 with four people taller or the same height in front, which are people 0, 1, 2, and 3.
Person 5 has height 7 with one person taller or the same height in front, which is person 1.
Hence [[5,0],[7,0],[5,2],[6,1],[4,4],[7,1]] is the reconstructed queue.
</pre>

<pre><strong>Input:</strong> people = [[6,0],[5,0],[4,0],[3,2],[2,2],[1,4]]
<strong>Output:</strong> [[4,0],[5,0],[2,2],[3,2],[1,4],[6,0]]
</pre>

<ul>
	<li><code>1 &lt;= people.length &lt;= 2000</code></li>
	<li><code>0 &lt;= h<sub>i</sub> &lt;= 10<sup>6</sup></code></li>
	<li><code>0 &lt;= k<sub>i</sub> &lt; people.length</code></li>
	<li>It is guaranteed that the queue can be reconstructed.</li>
</ul>
</div>

directory: 359-logger-rate-limiter
Python: class Logger:

        self.logger = defaultdict(int)

    def shouldPrintMessage(self, timestamp: int, message: str) -> bool:
        
        if message in self.logger and self.logger[message] > timestamp:
        self.logger[message] = timestamp + 10

# Your Logger object will be instantiated and called as such:
# obj = Logger()
# param_1 = obj.shouldPrintMessage(timestamp,message)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/logger-rate-limiter/">359. Logger Rate Limiter</a></h2><h3>Easy</h3><hr><div><p>Design a logger system that receives a stream of messages along with their timestamps. Each <strong>unique</strong> message should only be printed <strong>at most every 10 seconds</strong> (i.e. a message printed at timestamp <code>t</code> will prevent other identical messages from being printed until timestamp <code>t + 10</code>).</p>

class Logger:

<p>All messages will come in chronological order. Several messages may arrive at the same timestamp.</p>

<p>Implement the <code>Logger</code> class:</p>

<ul>
	<li><code>Logger()</code> Initializes the <code>logger</code> object.</li>
	<li><code>bool shouldPrintMessage(int timestamp, string message)</code> Returns <code>true</code> if the <code>message</code> should be printed in the given <code>timestamp</code>, otherwise returns <code>false</code>.</li>
</ul>

["Logger", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage", "shouldPrintMessage"]
[[], [1, "foo"], [2, "bar"], [3, "foo"], [8, "bar"], [10, "foo"], [11, "foo"]]
[null, true, true, false, false, false, true]

Logger logger = new Logger();
logger.shouldPrintMessage(1, "foo");  // return true, next allowed timestamp for "foo" is 1 + 10 = 11
logger.shouldPrintMessage(2, "bar");  // return true, next allowed timestamp for "bar" is 2 + 10 = 12
logger.shouldPrintMessage(3, "foo");  // 3 &lt; 11, return false
logger.shouldPrintMessage(8, "bar");  // 8 &lt; 12, return false
logger.shouldPrintMessage(10, "foo"); // 10 &lt; 11, return false
logger.shouldPrintMessage(11, "foo"); // 11 &gt;= 11, return true, next allowed timestamp for "foo" is 11 + 10 = 21
</pre>

<ul>
	<li><code>0 &lt;= timestamp &lt;= 10<sup>9</sup></code></li>
	<li>Every <code>timestamp</code> will be passed in non-decreasing order (chronological order).</li>
	<li><code>1 &lt;= message.length &lt;= 30</code></li>
	<li>At most <code>10<sup>4</sup></code> calls will be made to <code>shouldPrintMessage</code>.</li>
</ul>
</div>

directory: 0144-binary-tree-preorder-traversal
    def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        
            return []
        
        stack, ans = [root], []
            root = stack.pop()
            if root:
                ans.append(root.val)
                    stack.append(root.right)
                    stack.append(root.left)
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-tree-preorder-traversal/">144. Binary Tree Preorder Traversal</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the preorder traversal of its nodes' values</em>.</p>

            return []
        
            if root:
        return ans

<strong>Output:</strong> [1,2,3]
</pre>

</pre>

</pre>

<ul>
</ul>

<p><strong>Follow up:</strong> Recursive solution is trivial, could you do it iteratively?</p>
</div>

directory: 650-2-keys-keyboard
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/2-keys-keyboard/">650. 2 Keys Keyboard</a></h2><h3>Medium</h3><hr><div><p>There is only one character <code>'A'</code> on the screen of a notepad. You can perform two operations on this notepad for each step:</p>

<ul>
	<li>Copy All: You can copy all the characters present on the screen (a partial copy is not allowed).</li>
	<li>Paste: You can paste the characters which are copied last time.</li>
</ul>

<p>Given an integer <code>n</code>, return <em>the minimum number of operations to get the character</em> <code>'A'</code> <em>exactly</em> <code>n</code> <em>times on the screen</em>.</p>

<strong>Explanation:</strong> Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.
</pre>

</pre>

<ul>
</ul>
</div>

directory: 702-search-in-a-sorted-array-of-unknown-size
# This is ArrayReader's API interface.
# """
#class ArrayReader:
#    def get(self, index: int) -> int:

    def search(self, reader: 'ArrayReader', target: int) -> int:
        
        start = 0
        end = 10000
        
        while start <= end:
            
            mid = (end + start) >> 1
            
            if reader.get(mid) == target:
                return mid
            elif reader.get(mid) == 2147483647 or reader.get(mid) > target:
                end = mid - 1
            else:
                start = mid + 1
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/search-in-a-sorted-array-of-unknown-size/">702. Search in a Sorted Array of Unknown Size</a></h2><h3>Medium</h3><hr><div><p>This is an <strong><em>interactive problem</em></strong>.</p>

# """
# """

        start = 0
        end = 10000
        
                return mid
                end = mid - 1
            else:
        return -1

<p>You have a sorted array of <strong>unique</strong> elements and an <strong>unknown size</strong>. You do not have an access to the array but you can use the <code>ArrayReader</code> interface to access it. You can call <code>ArrayReader.get(i)</code> that:</p>

<ul>
	<li>returns the value at the <code>i<sup>th</sup></code> index (<strong>0-indexed</strong>) of the secret array (i.e., <code>secret[i]</code>), or</li>
	<li>returns <code>2<sup>31</sup> - 1</code> if the <code>i</code> is out of the boundary of the array.</li>
</ul>

<p>You are also given an integer <code>target</code>.</p>

<p>Return the index <code>k</code> of the hidden array where <code>secret[k] == target</code> or return <code>-1</code> otherwise.</p>

<p>You must write an algorithm with <code>O(log n)</code> runtime complexity.</p>

<pre><strong>Input:</strong> secret = [-1,0,3,5,9,12], target = 9
<strong>Explanation:</strong> 9 exists in secret and its index is 4.
</pre>

<pre><strong>Input:</strong> secret = [-1,0,3,5,9,12], target = 2
<strong>Explanation:</strong> 2 does not exist in secret so return -1.
</pre>

<ul>
	<li><code>1 &lt;= secret.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= secret[i], target &lt;= 10<sup>4</sup></code></li>
	<li><code>secret</code> is sorted in a strictly increasing order.</li>
</ul>
</div>

directory: 1048-longest-string-chain
    def longestStrChain(self, words: List[str]) -> int:
        words = set(words)
        def backtrack(word):
            if word not in words:
                return 0
            maximum = 0
                prefix = word[:i] + word[i+1:]
                maximum = max(maximum, backtrack(prefix) + 1)
            return maximum
        
        return max([backtrack(word) for word in words])
Notes: words = set(words)
@lru_cache(maxsize = None)
def backtrack(word):
if word not in words:
return 0
maximum = 0
for i in range(len(word)):
maximum = max(maximum, backtrack(word[:i] + word[i+1:]) + 1)
return maximum
return max([backtrack(word) for word in words])
Readme: <h2><a href="https://leetcode.com/problems/longest-string-chain/">1048. Longest String Chain</a></h2><h3>Medium</h3><hr><div><p>You are given an array of <code>words</code> where each word consists of lowercase English letters.</p>

                return 0
            maximum = 0
        
<p><code>word<sub>A</sub></code> is a <strong>predecessor</strong> of <code>word<sub>B</sub></code> if and only if we can insert <strong>exactly one</strong> letter anywhere in <code>word<sub>A</sub></code> <strong>without changing the order of the other characters</strong> to make it equal to <code>word<sub>B</sub></code>.</p>

<ul>
	<li>For example, <code>"abc"</code> is a <strong>predecessor</strong> of <code>"ab<u>a</u>c"</code>, while <code>"cba"</code> is not a <strong>predecessor</strong> of <code>"bcad"</code>.</li>
</ul>

<p>A <strong>word chain</strong><em> </em>is a sequence of words <code>[word<sub>1</sub>, word<sub>2</sub>, ..., word<sub>k</sub>]</code> with <code>k &gt;= 1</code>, where <code>word<sub>1</sub></code> is a <strong>predecessor</strong> of <code>word<sub>2</sub></code>, <code>word<sub>2</sub></code> is a <strong>predecessor</strong> of <code>word<sub>3</sub></code>, and so on. A single word is trivially a <strong>word chain</strong> with <code>k == 1</code>.</p>

<p>Return <em>the <strong>length</strong> of the <strong>longest possible word chain</strong> with words chosen from the given list of </em><code>words</code>.</p>

<pre><strong>Input:</strong> words = ["a","b","ba","bca","bda","bdca"]
<strong>Explanation</strong>: One of the longest word chains is ["a","<u>b</u>a","b<u>d</u>a","bd<u>c</u>a"].
</pre>

<pre><strong>Input:</strong> words = ["xbc","pcxbcf","xb","cxbc","pcxbc"]
<strong>Explanation:</strong> All the words can be put in a word chain ["xb", "xb<u>c</u>", "<u>c</u>xbc", "<u>p</u>cxbc", "pcxbc<u>f</u>"].
</pre>

<pre><strong>Input:</strong> words = ["abcd","dbqca"]
<strong>Explanation:</strong> The trivial word chain ["abcd"] is one of the longest word chains.
["abcd","dbqca"] is not a valid word chain because the ordering of the letters is changed.
</pre>

<ul>
	<li><code>1 &lt;= words[i].length &lt;= 16</code></li>
	<li><code>words[i]</code> only consists of lowercase English letters.</li>
</ul>
</div>

directory: 1578-minimum-time-to-make-rope-colorful
    def minCost(self, colors: str, neededTime: List[int]) -> int:
        
        total_time, left,right = 0, 0, 0
        i,j, n = 0,0, len(colors)
        while i < n and j < n:
            curr_total = 0
            curr_max = 0
            while j < n and colors[i] == colors[j]:
                curr_total += neededTime[j]
                curr_max = max(curr_max, neededTime[j])
                j += 1
            total_time += curr_total - curr_max
            i = j
        return total_time
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-time-to-make-rope-colorful/">1578. Minimum Time to Make Rope Colorful</a></h2><h3>Medium</h3><hr><div><p>Alice has <code>n</code> balloons arranged on a rope. You are given a <strong>0-indexed</strong> string <code>colors</code> where <code>colors[i]</code> is the color of the <code>i<sup>th</sup></code> balloon.</p>

                j += 1
            i = j

<p>Alice wants the rope to be <strong>colorful</strong>. She does not want <strong>two consecutive balloons</strong> to be of the same color, so she asks Bob for help. Bob can remove some balloons from the rope to make it <strong>colorful</strong>. You are given a <strong>0-indexed</strong> integer array <code>neededTime</code> where <code>neededTime[i]</code> is the time (in seconds) that Bob needs to remove the <code>i<sup>th</sup></code> balloon from the rope.</p>

<p>Return <em>the <strong>minimum time</strong> Bob needs to make the rope <strong>colorful</strong></em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/12/13/ballon1.jpg" style="width: 404px; height: 243px;">
<pre><strong>Input:</strong> colors = "abaac", neededTime = [1,2,3,4,5]
<strong>Explanation:</strong> In the above image, 'a' is blue, 'b' is red, and 'c' is green.
Bob can remove the blue balloon at index 2. This takes 3 seconds.
There are no longer two consecutive balloons of the same color. Total time = 3.</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/12/13/balloon2.jpg" style="width: 244px; height: 243px;">
<pre><strong>Input:</strong> colors = "abc", neededTime = [1,2,3]
<strong>Explanation:</strong> The rope is already colorful. Bob does not need to remove any balloons from the rope.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/12/13/balloon3.jpg" style="width: 404px; height: 243px;">
<pre><strong>Input:</strong> colors = "aabaa", neededTime = [1,2,3,4,1]
<strong>Explanation:</strong> Bob will remove the ballons at indices 0 and 4. Each ballon takes 1 second to remove.
There are no longer two consecutive balloons of the same color. Total time = 1 + 1 = 2.
</pre>

<ul>
	<li><code>n == colors.length == neededTime.length</code></li>
	<li><code>1 &lt;= neededTime[i] &lt;= 10<sup>4</sup></code></li>
	<li><code>colors</code> contains only lowercase English letters.</li>
</ul>
</div>

directory: 455-assign-cookies
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/assign-cookies/">455. Assign Cookies</a></h2><h3>Easy</h3><hr><div><p>Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie.</p>

<p>Each child <code>i</code> has a greed factor <code>g[i]</code>, which is the minimum size of a cookie that the child will be content with; and each cookie <code>j</code> has a size <code>s[j]</code>. If <code>s[j] &gt;= g[i]</code>, we can assign the cookie <code>j</code> to the child <code>i</code>, and the child <code>i</code> will be content. Your goal is to maximize the number of your content children and output the maximum number.</p>

<pre><strong>Input:</strong> g = [1,2,3], s = [1,1]
<strong>Explanation:</strong> You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3. 
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
</pre>

<pre><strong>Input:</strong> g = [1,2], s = [1,2,3]
<strong>Explanation:</strong> You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2. 
You have 3 cookies and their sizes are big enough to gratify all of the children, 
You need to output 2.
</pre>

<ul>
	<li><code>1 &lt;= g.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>0 &lt;= s.length &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>1 &lt;= g[i], s[j] &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 314-binary-tree-vertical-order-traversal
    def verticalOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        
        dic = defaultdict(list)
        queue = deque([(root, 0)])
        
            node, column = queue.popleft()
            
            if node is not None:
                
                dic[column].append(node.val)
                
                queue.append((node.left, column - 1))
                queue.append((node.right, column + 1))
                
        return [dic[x] for x in sorted(dic.keys())]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-tree-vertical-order-traversal/">314. Binary Tree Vertical Order Traversal</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em><strong>the vertical order traversal</strong> of its nodes' values</em>. (i.e., from top to bottom, column by column).</p>

<p>If two nodes are in the same row and column, the order should be from <strong>left to right</strong>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/28/vtree1.jpg" style="width: 282px; height: 301px;">
<strong>Output:</strong> [[9],[3,15],[20],[7]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/28/vtree2-1.jpg" style="width: 462px; height: 222px;">
<pre><strong>Input:</strong> root = [3,9,8,4,0,1,7]
<strong>Output:</strong> [[4],[9],[3,0,1],[8],[7]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/28/vtree2.jpg" style="width: 462px; height: 302px;">
<pre><strong>Input:</strong> root = [3,9,8,4,0,1,7,null,null,null,2,5]
<strong>Output:</strong> [[4],[9,5],[3,0,1],[8,2],[7]]
</pre>

<ul>
</ul>
</div>

directory: 143-reorder-list
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        slow, fast = head, head.next
        while fast and fast.next:
        
        current = slow
        prev = None
        nxt = None
        prev, curr = None, slow.next
        while curr:
            nextt = curr.next
            curr.next = prev
            prev = curr
            curr = nextt    
        slow.next = None
        
        head1, head2 = head, prev
        while head2:
            temp = head1.next
            head1.next = head2
            head1 = head2
            head2 = temp
        return head1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reorder-list/">143. Reorder List</a></h2><h3>Medium</h3><hr><div><p>You are given the head of a singly linked-list. The list can be represented as:</p>

        """
        """
        
        prev = None
        nxt = None
            prev = curr
        
<pre>L<sub>0</sub> → L<sub>1</sub> → … → L<sub>n - 1</sub> → L<sub>n</sub>
</pre>

<p><em>Reorder the list to be on the following form:</em></p>

<pre>L<sub>0</sub> → L<sub>n</sub> → L<sub>1</sub> → L<sub>n - 1</sub> → L<sub>2</sub> → L<sub>n - 2</sub> → …
</pre>

<p>You may not modify the values in the list's nodes. Only nodes themselves may be changed.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/04/reorder1linked-list.jpg" style="width: 422px; height: 222px;">
<strong>Output:</strong> [1,4,2,3]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/09/reorder2-linked-list.jpg" style="width: 542px; height: 222px;">
<strong>Output:</strong> [1,5,2,4,3]
</pre>

<ul>
	<li>The number of nodes in the list is in the range <code>[1, 5 * 10<sup>4</sup>]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 1000</code></li>
</ul>
</div>

directory: 1198-find-smallest-common-element-in-all-rows
    def smallestCommonElement(self, mat: List[List[int]]) -> int:
        
        """
        1 2 3 4 5
        2 4 5 8 10
        3 5 7 9 11
        1 3 5 7 9
        """
        
        frequencies = Counter()
        m, n = len(mat), len(mat[0])
                frequencies[mat[i][j]] += 1
        for k, v in frequencies.items():
            if v == m:
                return k
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-smallest-common-element-in-all-rows/">1198. Find Smallest Common Element in All Rows</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> matrix <code>mat</code> where every row is sorted in <strong>strictly</strong> <strong>increasing</strong> order, return <em>the <strong>smallest common element</strong> in all rows</em>.</p>

        """
        1 2 3 4 5
        2 4 5 8 10
        3 5 7 9 11
        1 3 5 7 9
        """
        
            if v == m:
                return k
        return -1
        
<p>If there is no common element, return <code>-1</code>.</p>

<pre><strong>Input:</strong> mat = [[1,2,3,4,5],[2,4,5,8,10],[3,5,7,9,11],[1,3,5,7,9]]
</pre>

<pre><strong>Input:</strong> mat = [[1,2,3],[2,3,4],[2,3,5]]
</pre>

<ul>
	<li><code>m == mat.length</code></li>
	<li><code>n == mat[i].length</code></li>
	<li><code>1 &lt;= mat[i][j] &lt;= 10<sup>4</sup></code></li>
	<li><code>mat[i]</code> is sorted in strictly increasing order.</li>
</ul>
</div>

directory: 383-ransom-note
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        
        c = Counter(magazine)
        
        for ch in ransomNote:
            if c[ch] <= 0:
            else:
                c[ch]-=1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/ransom-note/">383. Ransom Note</a></h2><h3>Easy</h3><hr><div><p>Given two strings <code>ransomNote</code> and <code>magazine</code>, return <code>true</code><em> if </em><code>ransomNote</code><em> can be constructed by using the letters from </em><code>magazine</code><em> and </em><code>false</code><em> otherwise</em>.</p>

<p>Each letter in <code>magazine</code> can only be used once in <code>ransomNote</code>.</p>

            else:
                c[ch]-=1
            
<pre><strong>Input:</strong> ransomNote = "a", magazine = "b"
<pre><strong>Input:</strong> ransomNote = "aa", magazine = "ab"
<pre><strong>Input:</strong> ransomNote = "aa", magazine = "aab"
</pre>

<ul>
	<li><code>1 &lt;= ransomNote.length, magazine.length &lt;= 10<sup>5</sup></code></li>
	<li><code>ransomNote</code> and <code>magazine</code> consist of lowercase English letters.</li>
</ul>
</div>

directory: 0334-increasing-triplet-subsequence
    def increasingTriplet(self, nums: List[int]) -> bool:
        
        num_i, num_j = float('inf'), float('inf')
        for n in nums:
            if n <= num_i:
                num_i = n
            elif n <= num_j:
                num_j = n
            else:
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/increasing-triplet-subsequence/">334. Increasing Triplet Subsequence</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, return <code>true</code><em> if there exists a triple of indices </em><code>(i, j, k)</code><em> such that </em><code>i &lt; j &lt; k</code><em> and </em><code>nums[i] &lt; nums[j] &lt; nums[k]</code>. If no such indices exists, return <code>false</code>.</p>

                num_i = n
                num_j = n
            else:

<pre><strong>Input:</strong> nums = [1,2,3,4,5]
<strong>Explanation:</strong> Any triplet where i &lt; j &lt; k is valid.
</pre>

<pre><strong>Input:</strong> nums = [5,4,3,2,1]
<strong>Explanation:</strong> No triplet exists.
</pre>

<pre><strong>Input:</strong> nums = [2,1,5,0,4,6]
<strong>Explanation:</strong> The triplet (3, 4, 5) is valid because nums[3] == 0 &lt; nums[4] == 4 &lt; nums[5] == 6.
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>5</sup></code></li>
	<li><code>-2<sup>31</sup> &lt;= nums[i] &lt;= 2<sup>31</sup> - 1</code></li>
</ul>

<strong>Follow up:</strong> Could you implement a solution that runs in <code>O(n)</code> time complexity and <code>O(1)</code> space complexity?</div>

directory: 0977-squares-of-a-sorted-array
    def sortedSquares(self, nums: List[int]) -> List[int]:
        
        res = [0] * n
        left, right = 0, len(nums) - 1
        for i in range(n-1, -1, -1):
            if abs(nums[left]) < abs(nums[right]):
                squared = nums[right]
                right -= 1
            else:
                squared = nums[left]
                left += 1
            res[i] = squared * squared
        return res
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/squares-of-a-sorted-array/">977. Squares of a Sorted Array</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code> sorted in <strong>non-decreasing</strong> order, return <em>an array of <strong>the squares of each number</strong> sorted in non-decreasing order</em>.</p>

        res = [0] * n
                right -= 1
            else:
                left += 1
        return res
        
<pre><strong>Input:</strong> nums = [-4,-1,0,3,10]
<strong>Output:</strong> [0,1,9,16,100]
<strong>Explanation:</strong> After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
</pre>

<pre><strong>Input:</strong> nums = [-7,-3,2,3,11]
<strong>Output:</strong> [4,9,9,49,121]
</pre>

<ul>
	<li><code><span>1 &lt;= nums.length &lt;= </span>10<sup>4</sup></code></li>
	<li><code>nums</code> is sorted in <strong>non-decreasing</strong> order.</li>
</ul>

<strong>Follow up:</strong> Squaring each element and sorting the new array is very trivial, could you find an <code>O(n)</code> solution using a different approach?</div>

directory: 279-perfect-squares
    def numSquares(self, n: int) -> int:
        
        square_nums = [i * i for i in range(1, int(n**0.5) + 1)]
        level = 0
        queue = {n}
            level += 1
            next_queue = set()
            for remainder in queue:
                for square_num in square_nums:
                    if remainder == square_num:
                        return level
                    elif remainder < square_num:
                        break
                    else:
                        next_queue.add(remainder - square_num)
            queue = next_queue
        return level
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/perfect-squares/">279. Perfect Squares</a></h2><h3>Medium</h3><hr><div><p>Given an integer <code>n</code>, return <em>the least number of perfect square numbers that sum to</em> <code>n</code>.</p>

        level = 0
        queue = {n}
            level += 1
                        break
                    else:
            
<p>A <strong>perfect square</strong> is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, <code>1</code>, <code>4</code>, <code>9</code>, and <code>16</code> are perfect squares while <code>3</code> and <code>11</code> are not.</p>

<pre><strong>Input:</strong> n = 12
<strong>Explanation:</strong> 12 = 4 + 4 + 4.
</pre>

<pre><strong>Input:</strong> n = 13
<strong>Explanation:</strong> 13 = 4 + 9.
</pre>

<ul>
</ul>
</div>

directory: 734-sentence-similarity
    def areSentencesSimilar(self, sentence1: List[str], sentence2: List[str], similarPairs: List[List[str]]) -> bool:
        n, m = len(sentence1), len(sentence2)
        if n!=m:
        dic = defaultdict(set)
        for s1, s2 in similarPairs:
            dic[s1].add(s2)
            dic[s2].add(s1)
        for s1, s2 in zip(sentence1, sentence2):
            if s1 == s2:
                continue
            if s1 in dic[s2]:
                    continue
            else:
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sentence-similarity/">734. Sentence Similarity</a></h2><h3>Easy</h3><hr><div><p>We can represent a sentence as an array of words, for example, the sentence <code>"I am happy with leetcode"</code> can be represented as <code>arr = ["I","am",happy","with","leetcode"]</code>.</p>

        if n!=m:
            if s1 == s2:
                continue
                    continue
            else:
            
<p>Given two sentences <code>sentence1</code> and <code>sentence2</code> each represented as a string array and given an array of string pairs <code>similarPairs</code> where <code>similarPairs[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> indicates that the two words <code>x<sub>i</sub></code> and <code>y<sub>i</sub></code> are similar.</p>

<p>Return <em><code>true</code> if <code>sentence1</code> and <code>sentence2</code> are similar, or <code>false</code> if they are not similar</em>.</p>

<p>Two sentences are similar if:</p>

<ul>
	<li>They have <strong>the same length</strong> (i.e., the same number of words)</li>
	<li><code>sentence1[i]</code> and <code>sentence2[i]</code> are similar.</li>
</ul>

<p>Notice that a word is always similar to itself, also notice that the similarity relation is not transitive. For example, if the words <code>a</code> and <code>b</code> are similar, and the words <code>b</code> and <code>c</code> are similar, <code>a</code> and <code>c</code> are <strong>not necessarily similar</strong>.</p>

<pre><strong>Input:</strong> sentence1 = ["great","acting","skills"], sentence2 = ["fine","drama","talent"], similarPairs = [["great","fine"],["drama","acting"],["skills","talent"]]
<strong>Explanation:</strong> The two sentences have the same length and each word i of sentence1 is also similar to the corresponding word in sentence2.
</pre>

<pre><strong>Input:</strong> sentence1 = ["great"], sentence2 = ["great"], similarPairs = []
<strong>Explanation:</strong> A word is similar to itself.
</pre>

<pre><strong>Input:</strong> sentence1 = ["great"], sentence2 = ["doubleplus","good"], similarPairs = [["great","doubleplus"]]
<strong>Explanation:</strong> As they don't have the same length, we return false.
</pre>

<ul>
	<li><code>1 &lt;= sentence1.length, sentence2.length &lt;= 1000</code></li>
	<li><code>1 &lt;= sentence1[i].length, sentence2[i].length &lt;= 20</code></li>
	<li><code>sentence1[i]</code> and <code>sentence2[i]</code> consist of English letters.</li>
	<li><code>0 &lt;= similarPairs.length &lt;= 1000</code></li>
	<li><code>similarPairs[i].length == 2</code></li>
	<li><code>1 &lt;= x<sub>i</sub>.length, y<sub>i</sub>.length &lt;= 20</code></li>
	<li><code>x<sub>i</sub></code> and <code>y<sub>i</sub></code> consist of lower-case and upper-case English letters.</li>
	<li>All the pairs <code>(x<sub>i</sub>,<sub> </sub>y<sub>i</sub>)</code> are <strong>distinct</strong>.</li>
</ul>
</div>

directory: 456-132-pattern
    def find132pattern(self, nums: List[int]) -> bool:
        
        stack = []
        elem = float('-inf')
        for num in reversed(nums):
            if num < elem:
            while stack and stack[-1] < num:
                elem = stack[-1]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/132-pattern/">456. 132 Pattern</a></h2><h3>Medium</h3><hr><div><p>Given an array&nbsp;of <code>n</code> integers <code>nums</code>, a <strong>132 pattern</strong> is a subsequence of three integers <code>nums[i]</code>, <code>nums[j]</code> and <code>nums[k]</code> such that <code>i &lt; j &lt; k</code> and <code>nums[i] &lt; nums[k] &lt; nums[j]</code>.</p>

<p>Return <em><code>true</code> if there is a <strong>132 pattern</strong> in <code>nums</code>, otherwise, return <code>false</code>.</em></p>

        stack = []

<strong>Explanation:</strong> There is no 132 pattern in the sequence.
</pre>

<pre><strong>Input:</strong> nums = [3,1,4,2]
<strong>Explanation:</strong> There is a 132 pattern in the sequence: [1, 4, 2].
</pre>

<pre><strong>Input:</strong> nums = [-1,3,2,0]
<strong>Explanation:</strong> There are three 132 patterns in the sequence: [-1, 3, 2], [-1, 3, 0] and [-1, 2, 0].
</pre>

<ul>
	<li><code>n == nums.length</code></li>
	<li><code>1 &lt;= n &lt;= 2 * 10<sup>5</sup></code></li>
</ul>
</div>

directory: 658-find-k-closest-elements
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        
        diff = [(abs(num - x), num) for num in arr]
        heapq.heapify(diff)
        ans = []
        while k:
            ans.append(heapq.heappop(diff)[1])
            k-=1
        return sorted(ans)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-k-closest-elements/">658. Find K Closest Elements</a></h2><h3>Medium</h3><hr><div><p>Given a <strong>sorted</strong> integer array <code>arr</code>, two integers <code>k</code> and <code>x</code>, return the <code>k</code> closest integers to <code>x</code> in the array. The result should also be sorted in ascending order.</p>

<p>An integer <code>a</code> is closer to <code>x</code> than an integer <code>b</code> if:</p>

<ul>
	<li><code>|a - x| &lt; |b - x|</code>, or</li>
	<li><code>|a - x| == |b - x|</code> and <code>a &lt; b</code></li>
</ul>

        ans = []
        while k:
            k-=1
        
<pre><strong>Input:</strong> arr = [1,2,3,4,5], k = 4, x = 3
<strong>Output:</strong> [1,2,3,4]
<pre><strong>Input:</strong> arr = [1,2,3,4,5], k = 4, x = -1
</pre>

<ul>
	<li><code>1 &lt;= k &lt;= arr.length</code></li>
	<li><code>1 &lt;= arr.length &lt;= 10<sup>4</sup></code></li>
	<li><code>arr</code> is sorted in <strong>ascending</strong> order.</li>
	<li><code>-10<sup>4</sup> &lt;= arr[i], x &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 18-4sum
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        i = 0
        ans = []
        while i < n-3:
            j = i + 1
            while j < n-2:
                left, right = j + 1, n - 1
                while left < right:
                    s = nums[i] + nums[j] + nums[left] + nums[right]
                    if s == target:
                        ans.append([nums[i], nums[j], nums[left], nums[right]])
                        left+=1
                        right-=1
                        while left < right and nums[left] == nums[left-1]:
                            left+=1
                        while left < right and nums[right] == nums[right+1]:
                            right-=1
                    if s > target:
                        right-=1
                            right-=1
                    elif s < target:
                        left+=1
                            left+=1
                j+=1
                while j < n -2 and nums[j] == nums[j-1]:
                    j+=1
            i+=1
            while i < n - 3 and nums[i] == nums[i-1]:
                i+=1
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/4sum/">18. 4Sum</a></h2><h3>Medium</h3><hr><div><p>Given an array <code>nums</code> of <code>n</code> integers, return <em>an array of all the <strong>unique</strong> quadruplets</em> <code>[nums[a], nums[b], nums[c], nums[d]]</code> such that:</p>

        i = 0
        ans = []
            j = i + 1
                        left+=1
                        right-=1
                            left+=1
                            right-=1
                        right-=1
                            right-=1
                        left+=1
                            left+=1
                j+=1
                    j+=1
            i+=1
                i+=1
        return ans

<ul>
	<li><code>0 &lt;= a, b, c, d&nbsp;&lt; n</code></li>
	<li><code>a</code>, <code>b</code>, <code>c</code>, and <code>d</code> are <strong>distinct</strong>.</li>
	<li><code>nums[a] + nums[b] + nums[c] + nums[d] == target</code></li>
</ul>

<p>You may return the answer in <strong>any order</strong>.</p>

<pre><strong>Input:</strong> nums = [1,0,-1,0,-2,2], target = 0
<strong>Output:</strong> [[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
</pre>

<pre><strong>Input:</strong> nums = [2,2,2,2,2], target = 8
<strong>Output:</strong> [[2,2,2,2]]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 200</code></li>
	<li><code>-10<sup>9</sup> &lt;= target &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 25-reverse-nodes-in-k-group
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        
        dummy = ListNode(None)
        groupPrev = dummy
        
        while True:
            kth = self.getKth(groupPrev, k)
            if not kth:
                break
            groupNext = kth.next
            
            # Reverse the group
            prev, curr = kth.next, groupPrev.next
            while curr!=groupNext:
                temp = curr.next
                curr.next = prev
                prev = curr
                curr = temp
            tmp = groupPrev.next
            groupPrev.next = kth
            groupPrev = tmp
            
    def getKth(self, curr, k):
        while curr and k > 0:
            k-=1
        return curr
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reverse-nodes-in-k-group/">25. Reverse Nodes in k-Group</a></h2><h3>Hard</h3><hr><div><p>Given the <code>head</code> of a linked list, reverse the nodes of the list <code>k</code> at a time, and return <em>the modified list</em>.</p>

            if not kth:
                break
            
                prev = curr
                curr = temp
            
            k-=1
        
<p><code>k</code> is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of <code>k</code> then left-out nodes, in the end, should remain as it is.</p>

<p>You may not alter the values in the list's nodes, only nodes themselves may be changed.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg" style="width: 542px; height: 222px;">
<pre><strong>Input:</strong> head = [1,2,3,4,5], k = 2
<strong>Output:</strong> [2,1,4,3,5]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg" style="width: 542px; height: 222px;">
<pre><strong>Input:</strong> head = [1,2,3,4,5], k = 3
<strong>Output:</strong> [3,2,1,4,5]
</pre>

<ul>
	<li>The number of nodes in the list is <code>n</code>.</li>
	<li><code>1 &lt;= k &lt;= n &lt;= 5000</code></li>
	<li><code>0 &lt;= Node.val &lt;= 1000</code></li>
</ul>

<p><strong>Follow-up:</strong> Can you solve the problem in <code>O(1)</code> extra memory space?</p>
</div>

directory: 581-shortest-unsorted-continuous-subarray
    def findUnsortedSubarray(self, nums: List[int]) -> int:
        
        clone = sorted(nums)
        start = len(nums); end = 0
        
        for i in range(len(clone)):
            if clone[i] != nums[i]:
                start = min(start, i)
                end = max(end, i)
        
        return end - start + 1 if end - start >= 0 else 0
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/shortest-unsorted-continuous-subarray/">581. Shortest Unsorted Continuous Subarray</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, you need to find one <b>continuous subarray</b> that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.</p>

<p>Return <em>the shortest such subarray and output its length</em>.</p>

<pre><strong>Input:</strong> nums = [2,6,4,8,10,9,15]
<strong>Explanation:</strong> You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order.
</pre>

</pre>

</pre>

<ul>
	<li><code>-10<sup>5</sup> &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
</ul>

<strong>Follow up:</strong> Can you solve it in <code>O(n)</code> time complexity?</div>

directory: 0289-game-of-life
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        rows, cols = len(board), len(board[0])
        copy = [[board[row][col] for col in range(cols)] for row in range(rows)] 
        neighbors = [(1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1), (0,1), (1,1)]
        for row in range(rows):
            for col in range(cols):
                n = 0
                for nei in neighbors:
                    r = row + nei[0]
                    c = col + nei[1]
                    
                    if (r >=0 and r < rows) and (c < cols and c >= 0) and copy[r][c] == 1:
                        n += 1
                        
                if copy[row][col] == 1 and n < 2 or n > 3:
                    board[row][col] = 0
                if copy[row][col] == 0 and n == 3:
                    board[row][col] = 1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/game-of-life/">289. Game of Life</a></h2><h3>Medium</h3><hr><div><p>According to&nbsp;<a href="https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life" target="_blank">Wikipedia's article</a>: "The <b>Game of Life</b>, also known simply as <b>Life</b>, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."</p>

        """
        """
                n = 0
                    
                        n += 1
                        
<p>The board is made up of an <code>m x n</code> grid of cells, where each cell has an initial state: <b>live</b> (represented by a <code>1</code>) or <b>dead</b> (represented by a <code>0</code>). Each cell interacts with its <a href="https://en.wikipedia.org/wiki/Moore_neighborhood" target="_blank">eight neighbors</a> (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article):</p>

<ol>
	<li>Any live cell with fewer than two live neighbors dies as if caused by under-population.</li>
	<li>Any live cell with two or three live neighbors lives on to the next generation.</li>
	<li>Any live cell with more than three live neighbors dies, as if by over-population.</li>
	<li>Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.</li>
</ol>

<p><span>The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the <code>m x n</code> grid <code>board</code>, return <em>the next state</em>.</span></p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/26/grid1.jpg" style="width: 562px; height: 322px;">
<pre><strong>Input:</strong> board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]
<strong>Output:</strong> [[0,0,0],[1,0,1],[0,1,1],[0,1,0]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/26/grid2.jpg" style="width: 402px; height: 162px;">
<pre><strong>Input:</strong> board = [[1,1],[1,0]]
<strong>Output:</strong> [[1,1],[1,1]]
</pre>

<ul>
	<li><code>1 &lt;= m, n &lt;= 25</code></li>
	<li><code>board[i][j]</code> is <code>0</code> or <code>1</code>.</li>
</ul>

<ul>
	<li>Could you solve it in-place? Remember that the board needs to be updated simultaneously: You cannot update some cells first and then use their updated values to update other cells.</li>
	<li>In this question, we represent the board using a 2D array. In principle, the board is infinite, which would cause problems when the active area encroaches upon the border of the array (i.e., live cells reach the border). How would you address these problems?</li>
</ul>
</div>

directory: 377-combination-sum-iv
    def combinationSum4(self, nums: List[int], target: int) -> int:
        
        def combs(remain):
            if remain == 0:
                return 1
            result = 0
            for num in nums:
                if remain - num >= 0:
                    result += combs(remain - num)
                    
            return result
        
        return combs(target)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/combination-sum-iv/">377. Combination Sum IV</a></h2><h3>Medium</h3><hr><div><p>Given an array of <strong>distinct</strong> integers <code>nums</code> and a target integer <code>target</code>, return <em>the number of possible combinations that add up to</em>&nbsp;<code>target</code>.</p>

<p>The test cases are generated so that the answer can fit in a <strong>32-bit</strong> integer.</p>

                return 1
            result = 0
                    
<pre><strong>Input:</strong> nums = [1,2,3], target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequences are counted as different combinations.
</pre>

<pre><strong>Input:</strong> nums = [9], target = 3
</pre>

<ul>
	<li><code>1 &lt;= nums[i] &lt;= 1000</code></li>
	<li>All the elements of <code>nums</code> are <strong>unique</strong>.</li>
	<li><code>1 &lt;= target &lt;= 1000</code></li>
</ul>

<p><strong>Follow up:</strong> What if negative numbers are allowed in the given array? How does it change the problem? What limitation we need to add to the question to allow negative numbers?</p>
</div>

directory: 46-permutations
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/permutations/">46. Permutations</a></h2><h3>Medium</h3><hr><div><p>Given an array <code>nums</code> of distinct integers, return <em>all the possible permutations</em>. You can return the answer in <strong>any order</strong>.</p>

<strong>Output:</strong> [[0,1],[1,0]]
<strong>Output:</strong> [[1]]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 6</code></li>
	<li>All the integers of <code>nums</code> are <strong>unique</strong>.</li>
</ul>
</div>

directory: 976-largest-perimeter-triangle
    def largestPerimeter(self, nums: List[int]) -> int:
        
        for i in range(len(nums) - 3, - 1, -1):
            if nums[i] + nums[i+1] > nums[i+2]:
                return nums[i] + nums[i+1] + nums[i+2]
        return 0
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/largest-perimeter-triangle/">976. Largest Perimeter Triangle</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code>, return <em>the largest perimeter of a triangle with a non-zero area, formed from three of these lengths</em>. If it is impossible to form any triangle of a non-zero area, return <code>0</code>.</p>

<pre><strong>Input:</strong> nums = [2,1,2]
</pre>

</pre>

        return 0

<ul>
	<li><code>3 &lt;= nums.length &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>6</sup></code></li>
</ul>
</div>

directory: 1338-reduce-array-size-to-the-half
    def minSetSize(self, arr: List[int]) -> int:
        n = len(arr)
        halved = n // 2
        c = Counter(arr)
        ans = 0
        for k, v in c.most_common():
            n-=v
            ans += 1
            if n <= halved:
                return ans
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reduce-array-size-to-the-half/">1338. Reduce Array Size to The Half</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>arr</code>. You can choose a set of integers and remove all the occurrences of these integers in the array.</p>

<p>Return <em>the minimum size of the set so that <strong>at least</strong> half of the integers of the array are removed</em>.</p>

        ans = 0
            n-=v
            ans += 1
                return ans
        return ans

<pre><strong>Input:</strong> arr = [3,3,3,3,5,5,5,2,2,7]
<strong>Explanation:</strong> Choosing {3,7} will make the new array [5,5,5,2,2] which has size 5 (i.e equal to half of the size of the old array).
Possible sets of size 2 are {3,5},{3,2},{5,2}.
Choosing set {2,7} is not possible as it will make the new array [3,3,3,3,5,5,5] which has a size greater than half of the size of the old array.
</pre>

<pre><strong>Input:</strong> arr = [7,7,7,7,7,7]
<strong>Explanation:</strong> The only possible set you can choose is {7}. This will make the new array empty.
</pre>

<ul>
	<li><code>2 &lt;= arr.length &lt;= 10<sup>5</sup></code></li>
	<li><code>arr.length</code> is even.</li>
	<li><code>1 &lt;= arr[i] &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 620-not-boring-movies
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/not-boring-movies/">620. Not Boring Movies</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Cinema</code></p>

<pre>+----------------+----------+
| Column Name    | Type     |
+----------------+----------+
| id             | int      |
| movie          | varchar  |
| description    | varchar  |
| rating         | float    |
Each row contains information about the name of a movie, its genre, and its rating.
rating is a 2 decimal places float in the range [0, 10]
</pre>

<p>Write an SQL query to report the movies with an odd-numbered ID and a description that is not <code>"boring"</code>.</p>

<p>Return the result table ordered by <code>rating</code> <strong>in descending order</strong>.</p>

+----+------------+-------------+--------+
| id | movie      | description | rating |
| 1  | War        | great 3D    | 8.9    |
| 2  | Science    | fiction     | 8.5    |
| 3  | irish      | boring      | 6.2    |
| 4  | Ice song   | Fantacy     | 8.6    |
| 5  | House card | Interesting | 9.1    |
We have three movies with odd-numbered IDs: 1, 3, and 5. The movie with ID = 3 is boring so we do not include it in the answer.
</pre>
</div>

directory: 1823-find-the-winner-of-the-circular-game
    def findTheWinner(self, n: int, k: int) -> int:
        
        queue = deque([i for i in range(1, n + 1)])
        #print(queue)
        count = 1
        while len(queue)!=1:
            while count != k:
                queue.append(node)
                count += 1
            node = queue.popleft()
            count = 1
        return queue[0]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-the-winner-of-the-circular-game/">1823. Find the Winner of the Circular Game</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> friends that are playing a game. The friends are sitting in a circle and are numbered from <code>1</code> to <code>n</code> in <strong>clockwise order</strong>. More formally, moving clockwise from the <code>i<sup>th</sup></code> friend brings you to the <code>(i+1)<sup>th</sup></code> friend for <code>1 &lt;= i &lt; n</code>, and moving clockwise from the <code>n<sup>th</sup></code> friend brings you to the <code>1<sup>st</sup></code> friend.</p>

        count = 1
                count += 1
            count = 1
            
<p>The rules of the game are as follows:</p>

<ol>
	<li><strong>Start</strong> at the <code>1<sup>st</sup></code> friend.</li>
	<li>Count the next <code>k</code> friends in the clockwise direction <strong>including</strong> the friend you started at. The counting wraps around the circle and may count some friends more than once.</li>
	<li>The last friend you counted leaves the circle and loses the game.</li>
	<li>If there is still more than one friend in the circle, go back to step <code>2</code> <strong>starting</strong> from the friend <strong>immediately clockwise</strong> of the friend who just lost and repeat.</li>
	<li>Else, the last friend in the circle wins the game.</li>
</ol>

<p>Given the number of friends, <code>n</code>, and an integer <code>k</code>, return <em>the winner of the game</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/25/ic234-q2-ex11.png" style="width: 500px; height: 345px;">
<pre><strong>Input:</strong> n = 5, k = 2
<strong>Explanation:</strong> Here are the steps of the game:
1) Start at friend 1.
2) Count 2 friends clockwise, which are friends 1 and 2.
3) Friend 2 leaves the circle. Next start is friend 3.
4) Count 2 friends clockwise, which are friends 3 and 4.
5) Friend 4 leaves the circle. Next start is friend 5.
6) Count 2 friends clockwise, which are friends 5 and 1.
7) Friend 1 leaves the circle. Next start is friend 3.
8) Count 2 friends clockwise, which are friends 3 and 5.
9) Friend 5 leaves the circle. Only friend 3 is left, so they are the winner.</pre>

<pre><strong>Input:</strong> n = 6, k = 5
<strong>Explanation:</strong> The friends leave in this order: 5, 4, 6, 2, 3. The winner is friend 1.
</pre>

<ul>
	<li><code>1 &lt;= k &lt;= n &lt;= 500</code></li>
</ul>

<p>Could you solve this problem in linear time with constant space?</p>
</div>

directory: 37-sudoku-solver
    def solveSudoku(self, board: List[List[str]]) -> None:
        """
        """
        
        rows = [set() for _ in range(9)]
        cols = [set() for _ in range(9)]
        boxes = [[set() for _ in range(3)] for _ in range(3)]
        
        for i in range(len(board)):
            for j in range(len(board[0])):
                if board[i][j] != ".":
                    value = board[i][j]
                    rows[i].add(value)
                    cols[j].add(value)
                    boxes[i//3][j//3].add(value)
        
        def backtrack(i, j):
            if i == len(board):
            elif j == len(board[i]):
                return backtrack(i+1, 0)
            elif board[i][j] != ".":
                return backtrack(i, j+1)
            else:
                for num in range(1, 10):
                    value = str(num)
                    if((value not in rows[i]) and (value not in cols[j]) and (value not in boxes[i//3][j//3])):
                        rows[i].add(value)
                        cols[j].add(value)
                        boxes[i//3][j//3].add(value)
                        board[i][j] = value
                        if backtrack(i, j+1):
                            return True
                        else:
                            board[i][j] = "."
                            rows[i].remove(value)
                            cols[j].remove(value)
                            boxes[i//3][j//3].remove(value)
        
        backtrack(0, 0)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sudoku-solver/">37. Sudoku Solver</a></h2><h3>Hard</h3><hr><div><p>Write a program to solve a Sudoku puzzle by filling the empty cells.</p>

        """
        """
        
            else:
                        else:
        
<p>A sudoku solution must satisfy <strong>all of the following rules</strong>:</p>

<ol>
	<li>Each of the digits <code>1-9</code> must occur exactly once in each row.</li>
	<li>Each of the digits <code>1-9</code> must occur exactly once in each column.</li>
	<li>Each of the digits <code>1-9</code> must occur exactly once in each of the 9 <code>3x3</code> sub-boxes of the grid.</li>
</ol>

<p>The <code>'.'</code> character indicates empty cells.</p>

<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/3/31/Sudoku-by-L2G-20050714_solution.svg/250px-Sudoku-by-L2G-20050714_solution.svg.png" style="height:250px; width:250px">
</pre>

<ul>
	<li><code>board.length == 9</code></li>
	<li><code>board[i].length == 9</code></li>
	<li><code>board[i][j]</code> is a digit or <code>'.'</code>.</li>
	<li>It is <strong>guaranteed</strong> that the input board has only one solution.</li>
</ul>
</div>

directory: 1214-two-sum-bsts
    def twoSumBSTs(self, root1: Optional[TreeNode], root2: Optional[TreeNode], target: int) -> bool:
        
        stack, s = [], set()
        while stack or root1:
            while root1:
                stack.append(root1)
                root1 = root1.left
            root1 = stack.pop()
            s.add(target - root1.val)
            root1 = root1.right
        
        while stack or root2:
            while root2:
                stack.append(root2)
                root2 = root2.left
            root2 = stack.pop()
            if root2.val in s:
            root2 = root2.right
        
Notes: dic = {}
def dfs1(root):
nonlocal dic
if root:
dic[root.val] = target - root.val
if root.left:
dfs1(root.left)
if root.right:
dfs1(root.right)
dfs1(root1)
def dfs2(root):
if not root:
else:
val = root.val
if target - val in dic:
return dfs2(root.left) or dfs2(root.right)
return dfs2(root2)
Readme: <h2><a href="https://leetcode.com/problems/two-sum-bsts/">1214. Two Sum BSTs</a></h2><h3>Medium</h3><hr><div><p>Given the roots of two binary search trees, <code>root1</code> and <code>root2</code>, return <code>true</code> if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer <code>target</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/10/ex1.png" style="width: 369px; height: 169px;">
<pre><strong>Input:</strong> root1 = [2,1,4], root2 = [1,0,3], target = 5
<strong>Explanation: </strong>2 and 3 sum up to 5.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/10/ex2.png" style="width: 453px; height: 290px;">
<pre><strong>Input:</strong> root1 = [0,-10,10], root2 = [5,1,7,0,2], target = 18
</pre>

<ul>
	<li>The number of nodes in each tree is in the range <code>[1, 5000]</code>.</li>
	<li><code>-10<sup>9</sup> &lt;= Node.val, target &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 695-max-area-of-island
    def maxAreaOfIsland(self, grid: List[List[int]]) -> int:
        maxIsland = 0
                return 0
            return 1 + dfs(r - 1, c) + dfs(r + 1, c) + dfs(r, c - 1) + dfs(r, c + 1)
        
                if grid[r][c] == 1:
                    thisArea = dfs(r, c)
                    maxIsland = max(thisArea, maxIsland)
        return maxIsland
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/max-area-of-island/">695. Max Area of Island</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> binary matrix <code>grid</code>. An island is a group of <code>1</code>'s (representing land) connected <strong>4-directionally</strong> (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.</p>

                return 0
        
<p>The <strong>area</strong> of an island is the number of cells with a value <code>1</code> in the island.</p>

<p>Return <em>the maximum <strong>area</strong> of an island in </em><code>grid</code>. If there is no island, return <code>0</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/05/01/maxarea1-grid.jpg" style="width: 500px; height: 310px;">
<pre><strong>Input:</strong> grid = [[0,0,1,0,0,0,0,1,0,0,0,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,1,1,0,1,0,0,0,0,0,0,0,0],[0,1,0,0,1,1,0,0,1,0,1,0,0],[0,1,0,0,1,1,0,0,1,1,1,0,0],[0,0,0,0,0,0,0,0,0,0,1,0,0],[0,0,0,0,0,0,0,1,1,1,0,0,0],[0,0,0,0,0,0,0,1,1,0,0,0,0]]
<strong>Explanation:</strong> The answer is not 11, because the island must be connected 4-directionally.
</pre>

<pre><strong>Input:</strong> grid = [[0,0,0,0,0,0,0,0]]
</pre>

<ul>
</ul>
</div>

directory: 216-combination-sum-iii
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        output = []
        def backtrack(number, s, array):
            if len(array) == k and s == n:
                output.append(array[:])
                return
            if len(array) >= k and s != n:
                return
            number = 0 if not array else array[-1]
            for i in range(number + 1,10):
                backtrack(number, s + i, array + [i])
        backtrack(1, 0, [])
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/combination-sum-iii/">216. Combination Sum III</a></h2><h3>Medium</h3><hr><div><p>Find all valid combinations of <code>k</code> numbers that sum up to <code>n</code> such that the following conditions are true:</p>

<ul>
	<li>Only numbers <code>1</code> through <code>9</code> are used.</li>
	<li>Each number is used <strong>at most once</strong>.</li>
</ul>

        output = []
                return
                return

<p>Return <em>a list of all possible valid combinations</em>. The list must not contain the same combination twice, and the combinations may be returned in any order.</p>

<pre><strong>Input:</strong> k = 3, n = 7
<strong>Output:</strong> [[1,2,4]]
1 + 2 + 4 = 7
There are no other valid combinations.</pre>

<pre><strong>Input:</strong> k = 3, n = 9
<strong>Output:</strong> [[1,2,6],[1,3,5],[2,3,4]]
1 + 2 + 6 = 9
1 + 3 + 5 = 9
2 + 3 + 4 = 9
There are no other valid combinations.
</pre>

<pre><strong>Input:</strong> k = 4, n = 1
<strong>Explanation:</strong> There are no valid combinations.
Using 4 different numbers in the range [1,9], the smallest sum we can get is 1+2+3+4 = 10 and since 10 &gt; 1, there are no valid combination.
</pre>

<ul>
	<li><code>2 &lt;= k &lt;= 9</code></li>
	<li><code>1 &lt;= n &lt;= 60</code></li>
</ul>
</div>

directory: 987-vertical-order-traversal-of-a-binary-tree
    def verticalTraversal(self, root: Optional[TreeNode]) -> List[List[int]]:
        
        node_list = []
        
        def BFS(root):
            
            queue = deque([(root, 0, 0)])
            while queue:
                node, row, column = queue.popleft()
                if node is not None:
                    node_list.append((column, row, node.val))
                    queue.append((node.left, row+1, column - 1))
                    queue.append((node.right, row+1, column+1))
        BFS(root)
        node_list.sort()
        ret = OrderedDict()
        for column, row, value in node_list:
            if column in ret:
                ret[column].append(value)
                
            else:
                ret[column] = [value]
        return ret.values()
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/">987. Vertical Order Traversal of a Binary Tree</a></h2><h3>Hard</h3><hr><div><p>Given the <code>root</code> of a binary tree, calculate the <strong>vertical order traversal</strong> of the binary tree.</p>

        BFS(root)
                
            else:
        
<p>For each node at position <code>(row, col)</code>, its left and right children will be at positions <code>(row + 1, col - 1)</code> and <code>(row + 1, col + 1)</code> respectively. The root of the tree is at <code>(0, 0)</code>.</p>

<p>The <strong>vertical order traversal</strong> of a binary tree is a list of top-to-bottom orderings for each column index starting from the leftmost column and ending on the rightmost column. There may be multiple nodes in the same row and same column. In such a case, sort these nodes by their values.</p>

<p>Return <em>the <strong>vertical order traversal</strong> of the binary tree</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/29/vtree1.jpg" style="width: 431px; height: 304px;">
Column -1: Only node 9 is in this column.
Column 0: Nodes 3 and 15 are in this column in that order from top to bottom.
Column 1: Only node 20 is in this column.
Column 2: Only node 7 is in this column.</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/29/vtree2.jpg" style="width: 512px; height: 304px;">
<pre><strong>Input:</strong> root = [1,2,3,4,5,6,7]
<strong>Output:</strong> [[4],[2],[1,5,6],[3],[7]]
Column -2: Only node 4 is in this column.
Column -1: Only node 2 is in this column.
Column 0: Nodes 1, 5, and 6 are in this column.
          1 is at the top, so it comes first.
          5 and 6 are at the same position (2, 0), so we order them by their value, 5 before 6.
Column 1: Only node 3 is in this column.
Column 2: Only node 7 is in this column.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/29/vtree3.jpg" style="width: 512px; height: 304px;">
<pre><strong>Input:</strong> root = [1,2,3,4,6,5,7]
This case is the exact same as example 2, but with nodes 5 and 6 swapped.
Note that the solution remains the same since 5 and 6 are in the same location and should be ordered by their values.
</pre>

<ul>
</ul>
</div>

directory: 1472-design-browser-history
Python: class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
        self.prev = None

class BrowserHistory:

    def __init__(self, homepage: str):
        
        self.dummy = self.head = ListNode(homepage)
        
    def visit(self, url: str) -> None:
        
        new_node = ListNode(url)
        self.dummy.next = new_node
        new_node.prev = self.dummy
        self.dummy = new_node

    def back(self, steps: int) -> str:
        
        while steps and self.dummy.prev:
            self.dummy = self.dummy.prev
            steps -= 1
        return self.dummy.val

class ListNode:

            steps -= 1

    def forward(self, steps: int) -> str:
        
        while steps and self.dummy.next:
            self.dummy = self.dummy.next
            steps -= 1
        
# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)

"""

BrowserHistory leetcode - Null
Visit google - Null
Visit facebook - Null
Visit youtube - Null
Back 1 - facebook
Back 1 - google
Forward 1 - facebook
Visit linkedin.com - null
Forward 2 - linkedin
Back 2 - google
Back 7 - leetcode

"""

def forward(self, steps: int) -> str:
        
            steps -= 1
        
"""

"""
Notes: class BrowserHistory:
​
def __init__(self, homepage: str):
self.current = homepage
self.back_history = []
self.forward_history = []
​
def visit(self, url: str) -> None:
self.back_history.append(self.current)
self.current = url
def back(self, steps: int) -> str:
possible = min(steps, len(self.back_history))
while possible:
self.forward_history.append(self.current)
self.current = self.back_history.pop()
possible -= 1
return self.current
​
possible = min(steps, len(self.forward_history))
self.current = self.forward_history.pop()
Readme: <h2><a href="https://leetcode.com/problems/design-browser-history/">1472. Design Browser History</a></h2><h3>Medium</h3><hr><div><p>You have a <strong>browser</strong> of one tab where you start on the <code>homepage</code> and you can visit another <code>url</code>, get back in the history number of <code>steps</code> or move forward in the history number of <code>steps</code>.</p>

<ul>
	<li><code>BrowserHistory(string homepage)</code> Initializes the object with the <code>homepage</code>&nbsp;of the browser.</li>
	<li><code>void visit(string url)</code>&nbsp;Visits&nbsp;<code>url</code> from the current page. It clears up all the forward history.</li>
	<li><code>string back(int steps)</code>&nbsp;Move <code>steps</code> back in history. If you can only return <code>x</code> steps in the history and <code>steps &gt; x</code>, you will&nbsp;return only <code>x</code> steps. Return the current <code>url</code>&nbsp;after moving back in history <strong>at most</strong> <code>steps</code>.</li>
	<li><code>string forward(int steps)</code>&nbsp;Move <code>steps</code> forward in history. If you can only forward <code>x</code> steps in the history and <code>steps &gt; x</code>, you will&nbsp;forward only&nbsp;<code>x</code> steps. Return the current <code>url</code>&nbsp;after forwarding in history <strong>at most</strong> <code>steps</code>.</li>
</ul>

BrowserHistory browserHistory = new BrowserHistory("leetcode.com");
browserHistory.visit("google.com");       // You are in "leetcode.com". Visit "google.com"
browserHistory.visit("facebook.com");     // You are in "google.com". Visit "facebook.com"
browserHistory.visit("youtube.com");      // You are in "facebook.com". Visit "youtube.com"
browserHistory.back(1);                   // You are in "youtube.com", move back to "facebook.com" return "facebook.com"
browserHistory.back(1);                   // You are in "facebook.com", move back to "google.com" return "google.com"
browserHistory.forward(1);                // You are in "google.com", move forward to "facebook.com" return "facebook.com"
browserHistory.visit("linkedin.com");     // You are in "facebook.com". Visit "linkedin.com"
browserHistory.forward(2);                // You are in "linkedin.com", you cannot move forward any steps.
browserHistory.back(2);                   // You are in "linkedin.com", move back two steps to "facebook.com" then to "google.com". return "google.com"
browserHistory.back(7);                   // You are in "google.com", you can move back only one step to "leetcode.com". return "leetcode.com"
</pre>

<ul>
	<li><code>1 &lt;= homepage.length &lt;= 20</code></li>
	<li><code>1 &lt;= url.length &lt;= 20</code></li>
	<li><code>1 &lt;= steps &lt;= 100</code></li>
	<li><code>homepage</code> and <code>url</code> consist of&nbsp; '.' or lower case English letters.</li>
	<li>At most <code>5000</code>&nbsp;calls will be made to <code>visit</code>, <code>back</code>, and <code>forward</code>.</li>
</ul>
</div>

directory: 43-multiply-strings
    def multiply(self, num1: str, num2: str) -> str:
        
        def to_int(string):
            result = 0
            for c in string:
                result = 10*result + ( ord(c) - ord('0'))
        
        def to_string(integer):
            result = ''
            if integer == 0:
                return '0'
            while integer>0:
                remainder = integer % 10
                integer //= 10
                result += chr(ord('1') + remainder - 1)
            return result[::-1]
        
        result = to_int(num1) * to_int(num2)
        
        return to_string(result)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/multiply-strings/">43. Multiply Strings</a></h2><h3>Medium</h3><hr><div><p>Given two non-negative integers <code>num1</code> and <code>num2</code> represented as strings, return the product of <code>num1</code> and <code>num2</code>, also represented as a string.</p>

            result = 0
        
            result = ''
                return '0'
        
<p><strong>Note:</strong>&nbsp;You must not use any built-in BigInteger library or convert the inputs to integer directly.</p>

<pre><strong>Input:</strong> num1 = "2", num2 = "3"
<strong>Output:</strong> "6"
<pre><strong>Input:</strong> num1 = "123", num2 = "456"
<strong>Output:</strong> "56088"
</pre>

<ul>
	<li><code>1 &lt;= num1.length, num2.length &lt;= 200</code></li>
	<li><code>num1</code> and <code>num2</code> consist of digits only.</li>
	<li>Both <code>num1</code> and <code>num2</code>&nbsp;do not contain any leading zero, except the number <code>0</code> itself.</li>
</ul>
</div>

directory: 1485-clone-binary-tree-with-random-pointer
Python: # Definition for Node.
# class Node:
#     def __init__(self, val=0, left=None, right=None, random=None):
#         self.random = random

# Definition for Node.

    def copyRandomBinaryTree(self, root: 'Optional[Node]') -> 'Optional[NodeCopy]':
            return None
        def dfs1(node):
                return
            copyMap[node] = NodeCopy(node.val)
            dfs1(node.left)
            dfs1(node.right)
                return
                    copyMap[root].left = copyMap[root.left]
                copyMap[root].right = copyMap[root.right]
            if root.random:
                copyMap[root].random = copyMap[root.random]
                    
            dfs2(root.left)
            dfs2(root.right)
            return root
        copyMap = {}
        return copyMap[root]
        
                return
                return
                    
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/clone-binary-tree-with-random-pointer/">1485. Clone Binary Tree With Random Pointer</a></h2><h3>Medium</h3><hr><div><p>A binary tree is given such that each node contains an additional random pointer which could point to any node in the tree or null.</p>

<p>Return a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the tree.</p>

<p>The tree is represented in the same input/output way as normal binary trees where each node is represented as a pair of <code>[val, random_index]</code> where:</p>

<ul>
	<li><code>val</code>: an integer representing <code>Node.val</code></li>
	<li><code>random_index</code>: the index of the node (in the input) where the random pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>

<p>You will be given the tree in class <code>Node</code> and you should return the cloned tree in class <code>NodeCopy</code>. <code>NodeCopy</code> class is just a clone of <code>Node</code> class with the same attributes and constructors.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/06/17/clone_1.png" style="width: 500px; height: 473px;">
<pre><strong>Input:</strong> root = [[1,null],null,[4,3],[7,0]]
<strong>Output:</strong> [[1,null],null,[4,3],[7,0]]
<strong>Explanation:</strong> The original binary tree is [1,null,4,7].
The random pointer of node one is null, so it is represented as [1, null].
The random pointer of node 4 is node 7, so it is represented as [4, 3] where 3 is the index of node 7 in the array representing the tree.
The random pointer of node 7 is node 1, so it is represented as [7, 0] where 0 is the index of node 1 in the array representing the tree.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/06/17/clone_2.png" style="width: 500px; height: 540px;">
<pre><strong>Input:</strong> root = [[1,4],null,[1,0],null,[1,5],[1,5]]
<strong>Output:</strong> [[1,4],null,[1,0],null,[1,5],[1,5]]
<strong>Explanation:</strong> The random pointer of a node can be the node itself.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/06/17/clone_3.png" style="width: 500px; height: 426px;">
<pre><strong>Input:</strong> root = [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]
<strong>Output:</strong> [[1,6],[2,5],[3,4],[4,3],[5,2],[6,1],[7,0]]
</pre>

<ul>
	<li>The number of nodes in the <code>tree</code> is in the range <code>[0, 1000].</code></li>
	<li><code>1 &lt;= Node.val &lt;= 10<sup>6</sup></code></li>
</ul>
</div>

directory: 1448-count-good-nodes-in-binary-tree
    def goodNodes(self, root: TreeNode) -> int:
        
        self.good = 0
        
        def dfs(root, curr_max):
            if root:
                if root.val >= curr_max:
                    self.good += 1
                    curr_max = root.val
                    dfs(root.left, curr_max)
                    dfs(root.right, curr_max)
        dfs(root, root.val)
        return self.good
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/count-good-nodes-in-binary-tree/">1448. Count Good Nodes in Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given a binary tree <code>root</code>, a node <em>X</em> in the tree is named&nbsp;<strong>good</strong> if in the path from root to <em>X</em> there are no nodes with a value <em>greater than</em> X.</p>

            if root:

<p>Return the number of <strong>good</strong> nodes in the binary tree.</p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/04/02/test_sample_1.png" style="width: 263px; height: 156px;"></strong></p>

<pre><strong>Input:</strong> root = [3,1,4,3,null,1,5]
<strong>Explanation:</strong> Nodes in blue are <strong>good</strong>.
Root Node (3) is always a good node.
Node 4 -&gt; (3,4) is the maximum value in the path starting from the root.
Node 5 -&gt; (3,4,5) is the maximum value in the path
Node 3 -&gt; (3,1,3) is the maximum value in the path.</pre>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/04/02/test_sample_2.png" style="width: 157px; height: 161px;"></strong></p>

<pre><strong>Input:</strong> root = [3,3,null,4,2]
<strong>Explanation:</strong> Node 2 -&gt; (3, 3, 2) is not good, because "3" is higher than it.</pre>

<strong>Explanation:</strong> Root is considered as <strong>good</strong>.</pre>

<ul>
	<li>The number of nodes in the binary tree is in the range&nbsp;<code>[1, 10^5]</code>.</li>
	<li>Each node's value is between <code>[-10^4, 10^4]</code>.</li>

directory: 104-maximum-depth-of-binary-tree
    def maxDepth(self, root: Optional[TreeNode]) -> int:
        
        stack = []
        if root is not None:
            stack.append((1, root))
        depth = 0
            curr_depth, root = stack.pop()
            if root:
                depth = max(depth, curr_depth)
                stack.append((curr_depth + 1, root.left))
                stack.append((curr_depth + 1, root.right))
        return depth
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-depth-of-binary-tree/">104. Maximum Depth of Binary Tree</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>its maximum depth</em>.</p>

        stack = []
        depth = 0
            if root:
        
<p>A binary tree's <strong>maximum depth</strong>&nbsp;is the number of nodes along the longest path from the root node down to the farthest leaf node.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/26/tmp-tree.jpg" style="width: 400px; height: 277px;">
</pre>

<pre><strong>Input:</strong> root = [1,null,2]
</pre>

<ul>
</ul>
</div>

directory: 204-count-primes
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/count-primes/">204. Count Primes</a></h2><h3>Medium</h3><hr><div><p>Given an integer <code>n</code>, return <em>the number of prime numbers that are strictly less than</em> <code>n</code>.</p>

<pre><strong>Input:</strong> n = 10
<strong>Explanation:</strong> There are 4 prime numbers less than 10, they are 2, 3, 5, 7.
</pre>

<pre><strong>Input:</strong> n = 0
</pre>

</pre>

<ul>
	<li><code>0 &lt;= n &lt;= 5 * 10<sup>6</sup></code></li>
</ul>
</div>

directory: 706-design-hashmap
Python: class MyHashMap:

        self.arr_len = 1000
        self.dict = [-1 for i in range(1000)]

class MyHashMap:

    def put(self, key: int, value: int) -> None:
        
        hash_value = key % self.arr_len
        if self.dict[hash_value] == -1:
            self.dict[hash_value] = [[key, value]]
            return 
        for i, lst in enumerate(self.dict[hash_value]):
            if lst[0] == key:
                self.dict[hash_value][i][1] = value
                return
        self.dict[hash_value].append([key, value])
        return
        
    def get(self, key: int) -> int:
        
            return -1
                return lst[1]
        return -1
    def remove(self, key: int) -> None:
        
        ind = key % self.arr_len
        ind_to_remove = -1
        if self.dict[ind] == -1:
            return
        
        for i, kv_pair in enumerate(self.dict[ind]):
            if kv_pair[0] == key:
                ind_to_remove = i
                break
        if ind_to_remove == -1:
            return
        else:
            del self.dict[ind][ind_to_remove]

# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)

def put(self, key: int, value: int) -> None:
        
            return 
                return
        return
        
            return -1
        return -1
        
            return
        
                break
            return
        else:

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/design-hashmap/">706. Design HashMap</a></h2><h3>Easy</h3><hr><div><p>Design a HashMap without using any built-in hash table libraries.</p>

<p>Implement the <code>MyHashMap</code> class:</p>

<ul>
	<li><code>MyHashMap()</code> initializes the object with an empty map.</li>
	<li><code>void put(int key, int value)</code> inserts a <code>(key, value)</code> pair into the HashMap. If the <code>key</code> already exists in the map, update the corresponding <code>value</code>.</li>
	<li><code>int get(int key)</code> returns the <code>value</code> to which the specified <code>key</code> is mapped, or <code>-1</code> if this map contains no mapping for the <code>key</code>.</li>
	<li><code>void remove(key)</code> removes the <code>key</code> and its corresponding <code>value</code> if the map contains the mapping for the <code>key</code>.</li>
</ul>

["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"]
[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]]
[null, null, null, 1, -1, null, 1, null, -1]

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.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.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]]
</pre>

<ul>
	<li><code>0 &lt;= key, value &lt;= 10<sup>6</sup></code></li>
	<li>At most <code>10<sup>4</sup></code> calls will be made to <code>put</code>, <code>get</code>, and <code>remove</code>.</li>
</ul>
</div>

directory: 1484-group-sold-products-by-the-date
Python: 
Notes: SELECT sell_date,
COUNT(DISTINCT(product)) AS num_sold,
GROUP_CONCAT(DISTINCT product ORDER BY product ASC SEPARATOR ',') AS products
FROM Activities
GROUP BY sell_date
ORDER BY sell_date ASC
Readme: <h2><a href="https://leetcode.com/problems/group-sold-products-by-the-date/">1484. Group Sold Products By The Date</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table <code>Activities</code>:</p>

| sell_date   | date    |
| product     | varchar |
There is no primary key for this table, it may contain duplicates.
Each row of this table contains the product name and the date it was sold in a market.
</pre>

<p>Write an SQL query to find for each date the number of different products sold and their names.</p>

<p>The sold products names for each date should be sorted lexicographically.</p>

<p>Return the result table ordered by <code>sell_date</code>.</p>

Activities table:
+------------+------------+
| sell_date  | product     |
| 2020-05-30 | Headphone  |
| 2020-06-01 | Pencil     |
| 2020-06-02 | Mask       |
| 2020-05-30 | Basketball |
| 2020-06-01 | Bible      |
| 2020-05-30 | T-Shirt    |
+------------+----------+------------------------------+
| sell_date  | num_sold | products                     |
| 2020-05-30 | 3        | Basketball,Headphone,T-shirt |
| 2020-06-01 | 2        | Bible,Pencil                 |
| 2020-06-02 | 1        | Mask                         |
For 2020-05-30, Sold items were (Headphone, Basketball, T-shirt), we sort them lexicographically and separate them by a comma.
For 2020-06-01, Sold items were (Pencil, Bible), we sort them lexicographically and separate them by a comma.
For 2020-06-02, the Sold item is (Mask), we just return it.
</pre>
</div>

directory: 277-find-the-celebrity
Python: # The knows API is already defined for you.
# return a bool, whether a knows b
# def knows(a: int, b: int) -> bool:

    def findCelebrity(self, n: int) -> int:
        
        def isCeleb(i):
                if i == j: continue
                if knows(i, j) or not knows(j, i): return False
        
            if isCeleb(i):
                return i
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-the-celebrity/">277. Find the Celebrity</a></h2><h3>Medium</h3><hr><div><p>Suppose you are at a party with <code>n</code> people labeled from <code>0</code> to <code>n - 1</code> and among them, there may exist one celebrity. The definition of a celebrity is that all the other <code>n - 1</code> people know the celebrity, but the celebrity does not know any of them.</p>

# The knows API is already defined for you.

                return i
        return -1

<p>Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is ask questions like: "Hi, A. Do you know B?" to get information about whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).</p>

<p>You are given a helper function <code>bool knows(a, b)</code> that tells you whether A knows B. Implement a function <code>int findCelebrity(n)</code>. There will be exactly one celebrity if they are at the party.</p>

<p>Return <em>the celebrity's label if there is a celebrity at the party</em>. If there is no celebrity, return <code>-1</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2022/01/19/g1.jpg" style="width: 224px; height: 145px;">
<pre><strong>Input:</strong> graph = [[1,1,0],[0,1,0],[1,1,1]]
<strong>Explanation:</strong> There are three persons labeled with 0, 1 and 2. graph[i][j] = 1 means person i knows person j, otherwise graph[i][j] = 0 means person i does not know person j. The celebrity is the person labeled as 1 because both 0 and 2 know him but 1 does not know anybody.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2022/01/19/g2.jpg" style="width: 224px; height: 145px;">
<pre><strong>Input:</strong> graph = [[1,0,1],[1,1,0],[0,1,1]]
<strong>Explanation:</strong> There is no celebrity.
</pre>

<ul>
	<li><code>n == graph.length</code></li>
	<li><code>n == graph[i].length</code></li>
	<li><code>2 &lt;= n &lt;= 100</code></li>
	<li><code>graph[i][j]</code> is <code>0</code> or <code>1</code>.</li>
	<li><code>graph[i][i] == 1</code></li>
</ul>

<p><strong>Follow up:</strong> If the maximum number of allowed calls to the API <code>knows</code> is <code>3 * n</code>, could you find a solution without exceeding the maximum number of calls?</p>
</div>

directory: 671-second-minimum-node-in-a-binary-tree
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/second-minimum-node-in-a-binary-tree/">671. Second Minimum Node In a Binary Tree</a></h2><h3>Easy</h3><hr><div><p>Given a non-empty special binary tree consisting of nodes with the non-negative value, where each node in this tree has exactly <code>two</code> or <code>zero</code> sub-node. If the node has two sub-nodes, then this node's value is the smaller value among its two sub-nodes. More formally, the property&nbsp;<code>root.val = min(root.left.val, root.right.val)</code>&nbsp;always holds.</p>

<p>Given such a binary tree, you need to output the <b>second minimum</b> value in the set made of all the nodes' value in the whole tree.</p>

<p>If no such second minimum value exists, output -1 instead.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/15/smbt1.jpg" style="width: 431px; height: 302px;">
<pre><strong>Input:</strong> root = [2,2,5,null,null,5,7]
<strong>Explanation:</strong> The smallest value is 2, the second smallest value is 5.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/15/smbt2.jpg" style="width: 321px; height: 182px;">
<pre><strong>Input:</strong> root = [2,2,2]
<strong>Explanation:</strong> The smallest value is 2, but there isn't any second smallest value.
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 25]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>
	<li><code>root.val == min(root.left.val, root.right.val)</code>&nbsp;for each internal node of the tree.</li>
</ul>
</div>

directory: 453-minimum-moves-to-equal-array-elements
    def minMoves(self, nums: List[int]) -> int:
        min_no = min(nums)
        count = 0
            count += num - min_no
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-moves-to-equal-array-elements/">453. Minimum Moves to Equal Array Elements</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> of size <code>n</code>, return <em>the minimum number of moves required to make all array elements equal</em>.</p>

<p>In one move, you can increment <code>n - 1</code> elements of the array by <code>1</code>.</p>

<strong>Explanation:</strong> Only three moves are needed (remember each move increments two elements):
[1,2,3]  =&gt;  [2,3,3]  =&gt;  [3,4,3]  =&gt;  [4,4,4]
</pre>

        count = 0

<pre><strong>Input:</strong> nums = [1,1,1]
</pre>

<ul>
	<li>The answer is guaranteed to fit in a <strong>32-bit</strong> integer.</li>
</ul>
</div>

directory: 297-serialize-and-deserialize-binary-tree
Python: class Codec:
    '''       O(n) time and O(n) space, BFS traversal
    e.g., 1
         / \
        2   5
       / \
      3   4  , level order traversal, serialize will be '1,2,5,3,4,None,None,None,None,None,None,'; deserialize 
      with queue as well, convert back. Time and Space O(n).
    '''
    def serialize(self, root):
            return ''
        queue = collections.deque()
        queue.append(root)
        res = ''
                res += 'None,'
                continue
            res += str(node.val) + ','
            queue.append(node.left)
            queue.append(node.right)
        return res
            
    def deserialize(self, data):
        if not data:
        ls = data.split(',')
        root = TreeNode(int(ls[0]))
        i = 1
        while queue and i < len(ls):
            if ls[i] != 'None':
                left = TreeNode(int(ls[i]))
                node.left = left
                queue.append(left)
            i += 1
                right = TreeNode(int(ls[i]))
                node.right = right
                queue.append(right)
            i += 1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/serialize-and-deserialize-binary-tree/">297. Serialize and Deserialize Binary Tree</a></h2><h3>Hard</h3><hr><div><p>Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p>

class Codec:
    e.g., 1
         / \
        2   5
       / \
    '''
            return ''
        res = ''
                continue
        return res
            
        i = 1
            i += 1
            i += 1

<p>Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.</p>

<p><strong>Clarification:</strong> The input/output format is the same as <a href="/faq/#binary-tree" target="_blank">how LeetCode serializes a binary tree</a>. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/serdeser.jpg" style="width: 442px; height: 324px;">
<pre><strong>Input:</strong> root = [1,2,3,null,null,4,5]
<strong>Output:</strong> [1,2,3,null,null,4,5]
</pre>

</pre>

<ul>
</ul>
</div>

directory: 402-remove-k-digits
    def removeKdigits(self, num: str, k: int) -> str:
        
        stack = []
        for n in num:
            while k and stack and stack[-1] > n:
                k-=1
            stack.append(n)
        stack = stack[:-k] if k else stack
        return "".join(stack).lstrip('0') or "0"
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/remove-k-digits/">402. Remove K Digits</a></h2><h3>Medium</h3><hr><div><p>Given string num representing a non-negative integer <code>num</code>, and an integer <code>k</code>, return <em>the smallest possible integer after removing</em> <code>k</code> <em>digits from</em> <code>num</code>.</p>

<pre><strong>Input:</strong> num = "1432219", k = 3
<strong>Output:</strong> "1219"
<strong>Explanation:</strong> Remove the three digits 4, 3, and 2 to form the new number 1219 which is the smallest.
</pre>

        stack = []
                k-=1

<pre><strong>Input:</strong> num = "10200", k = 1
<strong>Output:</strong> "200"
<strong>Explanation:</strong> Remove the leading 1 and the number is 200. Note that the output must not contain leading zeroes.
</pre>

<pre><strong>Input:</strong> num = "10", k = 2
<strong>Explanation:</strong> Remove all the digits from the number and it is left with nothing which is 0.
</pre>

<ul>
	<li><code>1 &lt;= k &lt;= num.length &lt;= 10<sup>5</sup></code></li>
	<li><code>num</code> consists of only digits.</li>
	<li><code>num</code> does not have any leading zeros except for the zero itself.</li>
</ul>
</div>

directory: 973-k-closest-points-to-origin
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        
        def calculateDistance(point):
            x, y = point
            return (x**2 + y**2) ** (0.5)
        arr = []
        for point in points:
            arr.append((point, calculateDistance(point)))
        arr.sort(key = lambda x : x[1])
        return [l[0] for l in arr[:k]]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/k-closest-points-to-origin/">973. K Closest Points to Origin</a></h2><h3>Medium</h3><hr><div><p>Given an array of <code>points</code> where <code>points[i] = [x<sub>i</sub>, y<sub>i</sub>]</code> represents a point on the <strong>X-Y</strong> plane and an integer <code>k</code>, return the <code>k</code> closest points to the origin <code>(0, 0)</code>.</p>

            x, y = point
        arr = []

<p>The distance between two points on the <strong>X-Y</strong> plane is the Euclidean distance (i.e., <code>√(x<sub>1</sub> - x<sub>2</sub>)<sup>2</sup> + (y<sub>1</sub> - y<sub>2</sub>)<sup>2</sup></code>).</p>

<p>You may return the answer in <strong>any order</strong>. The answer is <strong>guaranteed</strong> to be <strong>unique</strong> (except for the order that it is in).</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/03/closestplane1.jpg" style="width: 400px; height: 400px;">
<pre><strong>Input:</strong> points = [[1,3],[-2,2]], k = 1
<strong>Output:</strong> [[-2,2]]
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) &lt; sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
</pre>

<pre><strong>Input:</strong> points = [[3,3],[5,-1],[-2,4]], k = 2
<strong>Output:</strong> [[3,3],[-2,4]]
<strong>Explanation:</strong> The answer [[-2,4],[3,3]] would also be accepted.
</pre>

<ul>
	<li><code>1 &lt;= k &lt;= points.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>4</sup> &lt; x<sub>i</sub>, y<sub>i</sub> &lt; 10<sup>4</sup></code></li>
</ul>
</div>

directory: 1410-html-entity-parser
Python: 
Notes: class Solution {
public:
string entityParser(string text)
{
unordered_map <string, string> mp;
mp["&quot;"] = "\"";
mp["&apos;"] = "\'";
mp["&amp;"] = "&";
mp["&gt;"] = ">";
mp["&lt;"] = "<";
mp["&frasl;"] = "/";
string ans = "";
int start = 0;
for(int end = 0; end < text.size(); end++)
{
if(text[end] == '&')
{
start = end;
while(end+1 < text.size() && text[end+1] != '&')
end++;
while(end < text.size() && text[end]!=';')
end++;
string temp = text.substr(start, end - start +1);
if(mp.find(temp) != mp.end())
ans += mp[temp];
else
ans += temp;
}
else
{
ans += text[end];
}
}
return ans;
}
};
​
Readme: <h2><a href="https://leetcode.com/problems/html-entity-parser/">1410. HTML Entity Parser</a></h2><h3>Medium</h3><hr><div><p><strong>HTML entity parser</strong> is the parser that takes HTML code as input and replace all the entities of the special characters by the characters itself.</p>

<p>The special characters and their entities for HTML are:</p>

<ul>
	<li><strong>Quotation Mark:</strong> the entity is <code>&amp;quot;</code> and symbol character is <code>"</code>.</li>
	<li><strong>Single Quote Mark:</strong> the entity is <code>&amp;apos;</code> and symbol character is <code>'</code>.</li>
	<li><strong>Ampersand:</strong> the entity is <code>&amp;amp;</code> and symbol character is <code>&amp;</code>.</li>
	<li><strong>Greater Than Sign:</strong> the entity is <code>&amp;gt;</code> and symbol character is <code>&gt;</code>.</li>
	<li><strong>Less Than Sign:</strong> the entity is <code>&amp;lt;</code> and symbol character is <code>&lt;</code>.</li>
	<li><strong>Slash:</strong> the entity is <code>&amp;frasl;</code> and symbol character is <code>/</code>.</li>
</ul>

<p>Given the input <code>text</code> string to the HTML parser, you have to implement the entity parser.</p>

<p>Return <em>the text after replacing the entities by the special characters</em>.</p>

<pre><strong>Input:</strong> text = "&amp;amp; is an HTML entity but &amp;ambassador; is not."
<strong>Output:</strong> "&amp; is an HTML entity but &amp;ambassador; is not."
<strong>Explanation:</strong> The parser will replace the &amp;amp; entity by &amp;
</pre>

<pre><strong>Input:</strong> text = "and I quote: &amp;quot;...&amp;quot;"
<strong>Output:</strong> "and I quote: \"...\""
</pre>

<ul>
	<li><code>1 &lt;= text.length &lt;= 10<sup>5</sup></code></li>
	<li>The string may contain any possible characters out of all the 256 ASCII characters.</li>
</ul>
</div>

directory: 1609-even-odd-tree
    def isEvenOddTree(self, root: Optional[TreeNode]) -> bool:
        
        q = deque([root])
        prev = None
        level = 0
        while q:
            size = len(q)
                node = q.popleft()
                if level % 2 == 0:
                    if node.val % 2 == 0:
                    if prev:
                        if prev.val >= node.val:
                            return False
                    prev = node
                    if node.left:
                        q.append(node.left)
                    if node.right:
                        q.append(node.right)
                else:
                    if node.val % 2 != 0:
                    if prev:
                        if prev.val <= node.val:
                    prev = node
            level += 1
            prev = None
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/even-odd-tree/">1609. Even Odd Tree</a></h2><h3>Medium</h3><hr><div><p>A binary tree is named <strong>Even-Odd</strong> if it meets the following conditions:</p>

        prev = None
        level = 0
        while q:
                    if prev:
                    prev = node
                else:
                    if prev:
                    prev = node
            level += 1
            prev = None
        
<ul>
	<li>The root of the binary tree is at level index <code>0</code>, its children are at level index <code>1</code>, their children are at level index <code>2</code>, etc.</li>
	<li>For every <strong>even-indexed</strong> level, all nodes at the level have <strong>odd</strong> integer values in <strong>strictly increasing</strong> order (from left to right).</li>
	<li>For every <b>odd-indexed</b> level, all nodes at the level have <b>even</b> integer values in <strong>strictly decreasing</strong> order (from left to right).</li>
</ul>

<p>Given the <code>root</code> of a binary tree, <em>return </em><code>true</code><em> if the binary tree is <strong>Even-Odd</strong>, otherwise return </em><code>false</code><em>.</em></p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/sample_1_1966.png" style="width: 362px; height: 229px;">
<pre><strong>Input:</strong> root = [1,10,4,3,null,7,9,12,8,6,null,null,2]
<strong>Explanation:</strong> The node values on each level are:
Level 0: [1]
Level 1: [10,4]
Level 2: [3,7,9]
Level 3: [12,8,6,2]
Since levels 0 and 2 are all odd and increasing and levels 1 and 3 are all even and decreasing, the tree is Even-Odd.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/15/sample_2_1966.png" style="width: 363px; height: 167px;">
<pre><strong>Input:</strong> root = [5,4,2,3,3,7]
Level 0: [5]
Level 1: [4,2]
Level 2: [3,3,7]
Node values in level 2 must be in strictly increasing order, so the tree is not Even-Odd.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/22/sample_1_333_1966.png" style="width: 363px; height: 167px;">
<pre><strong>Input:</strong> root = [5,9,1,3,5,7]
<strong>Explanation:</strong> Node values in the level 1 should be even integers.
</pre>

<ul>
</ul>
</div>

directory: 200-number-of-islands
    def numIslands(self, grid: List[List[str]]) -> int:
        
        numIslands = 0
            if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] == '0':
                return
            grid[r][c] = '0'
            dfs(r - 1, c)
            dfs(r + 1, c)
            dfs(r, c - 1)
            dfs(r, c + 1)
        
                if grid[r][c] == '1':
                    dfs(r, c)
                    numIslands += 1
        return numIslands
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-islands/">200. Number of Islands</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> 2D binary grid <code>grid</code> which represents a map of <code>'1'</code>s (land) and <code>'0'</code>s (water), return <em>the number of islands</em>.</p>

                return
        
                    dfs(r, c)
        
<p>An <strong>island</strong> is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.</p>

<pre><strong>Input:</strong> grid = [
  ["1","1","1","1","0"],
  ["1","1","0","1","0"],
  ["1","1","0","0","0"],
  ["0","0","0","0","0"]
]
</pre>

  ["0","0","1","0","0"],
  ["0","0","0","1","1"]
]
</pre>

<ul>
	<li><code>grid[i][j]</code> is <code>'0'</code> or <code>'1'</code>.</li>
</ul>
</div>

directory: 131-palindrome-partitioning
    def partition(self, s: str) -> List[List[str]]:
        
        def isPalindrome(s, i, j):
            while i < j:
                if s[i] != s[j]:
                i+=1
                j-=1
        
        def backtrack(i, path):
            if i >= len(s):
                outputs.append(path.copy())
            for j in range(i, len(s)):
                if isPalindrome(s, i, j):
                    path.append(s[i:j+1])
                    backtrack(j+1, path)
                    path.pop()
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/palindrome-partitioning/">131. Palindrome Partitioning</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, partition <code>s</code> such that every substring of the partition is a <strong>palindrome</strong>. Return all possible palindrome partitioning of <code>s</code>.</p>

            while i < j:
                i+=1
                j-=1
        
<p>A <strong>palindrome</strong> string is a string that reads the same backward as forward.</p>

<strong>Output:</strong> [["a","a","b"],["aa","b"]]
<pre><strong>Input:</strong> s = "a"
<strong>Output:</strong> [["a"]]
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 16</code></li>
</ul>
</div>

directory: 224-basic-calculator
    
    def evaluate(self, expression, i):
        
        calc, operator = 0, '+'
        while expression[i] != ')':
            
            atom = expression[i]
            
            if atom == "+" or atom == "-":
                operator = atom
            else:
                if isinstance(atom, int):
                    num = atom
                else:
                    num, i = self.evaluate(expression, i+1)
                    
                if operator == "+":
                    calc += num
                else:
                    calc -= num
            
            i += 1
            
        return calc, i
    
        digits = {str(i) for i in range(10)}
        expression = ['(']
        for c in s:
            if c == ' ':
                continue
            elif c not in digits:
                expression.append(c)
            elif isinstance(expression[-1], int):
                expression[-1] = expression[-1] * 10 + int(c)
            else:
                expression.append(int(c))
        
        expression.append(')')
        result , _ = self.evaluate(expression, 1)
        return result
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/basic-calculator/">224. Basic Calculator</a></h2><h3>Hard</h3><hr><div><p>Given a string <code>s</code> representing a valid expression, implement a basic calculator to evaluate it, and return <em>the result of the evaluation</em>.</p>

            else:
                    num = atom
                else:
                    
                    calc += num
                else:
                    calc -= num
            
            i += 1
            
        for c in s:
            if c == ' ':
                continue
            else:
        
<p><strong>Note:</strong> You are <strong>not</strong> allowed to use any built-in function which evaluates strings as mathematical expressions, such as <code>eval()</code>.</p>

<pre><strong>Input:</strong> s = "1 + 1"
</pre>

<pre><strong>Input:</strong> s = " 2-1 + 2 "
</pre>

<pre><strong>Input:</strong> s = "(1+(4+5+2)-3)+(6+8)"
</pre>

<ul>
	<li><code>s</code> consists of digits, <code>'+'</code>, <code>'-'</code>, <code>'('</code>, <code>')'</code>, and <code>' '</code>.</li>
	<li><code>s</code> represents a valid expression.</li>
	<li><code>'+'</code> is <strong>not</strong> used as a unary operation (i.e., <code>"+1"</code> and <code>"+(2 + 3)"</code> is invalid).</li>
	<li><code>'-'</code> could be used as a unary operation (i.e., <code>"-1"</code> and <code>"-(2 + 3)"</code> is valid).</li>
	<li>There will be no two consecutive operators in the input.</li>
	<li>Every number and running calculation will fit in a signed 32-bit integer.</li>
</ul>
</div>

directory: 169-majority-element
    def majorityElement(self, nums: List[int]) -> int:
        
        majority = nums[0]
        count = 1
        for num in nums[1:]:
            if count == 0:
                majority = num
            if num == majority:
                count+=1
            elif num!=majority:
                count-=1
            
        return majority
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/majority-element/">169. Majority Element</a></h2><h3>Easy</h3><hr><div><p>Given an array <code>nums</code> of size <code>n</code>, return <em>the majority element</em>.</p>

<p>The majority element is the element that appears more than <code>⌊n / 2⌋</code> times. You may assume that the majority element always exists in the array.</p>

        count = 1
                count+=1
                count-=1
            
<pre><strong>Input:</strong> nums = [3,2,3]
<pre><strong>Input:</strong> nums = [2,2,1,1,1,2,2]
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 5 * 10<sup>4</sup></code></li>
</ul>

<strong>Follow-up:</strong> Could you solve the problem in linear time and in <code>O(1)</code> space?</div>

directory: 0086-partition-list
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        
        dummy = first = ListNode(-1)
        second_dummy = second = ListNode(-1)
        
        curr = head
            if curr.val < x:
                first.next = ListNode(curr.val)
                first = first.next
            else:
                second.next = ListNode(curr.val)
                second = second.next
        first.next = second_dummy.next
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/partition-list/">86. Partition List</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a linked list and a value <code>x</code>, partition it such that all nodes <strong>less than</strong> <code>x</code> come before nodes <strong>greater than or equal</strong> to <code>x</code>.</p>

        curr = head
            else:

<p>You should <strong>preserve</strong> the original relative order of the nodes in each of the two partitions.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/04/partition.jpg" style="width: 662px; height: 222px;">
<pre><strong>Input:</strong> head = [1,4,3,2,5,2], x = 3
<strong>Output:</strong> [1,2,2,4,3,5]
</pre>

<pre><strong>Input:</strong> head = [2,1], x = 2
<strong>Output:</strong> [1,2]
</pre>

<ul>
	<li>The number of nodes in the list is in the range <code>[0, 200]</code>.</li>
	<li><code>-200 &lt;= x &lt;= 200</code></li>
</ul>
</div>

directory: 2096-step-by-step-directions-from-a-binary-tree-node-to-another
    def getDirections(self, root: Optional[TreeNode], startValue: int, destValue: int) -> str:
        
        def getLCA(root, startValue, destValue):
            if root.val == startValue or root.val == destValue:
                return root
            left = getLCA(root.left, startValue, destValue)
            right = getLCA(root.right, startValue, destValue)
            
            if left and right:
            if left and not right:
                return left
            else:
                return right
            
        node = getLCA(root, startValue,destValue)
        stack = [(node, "")]
        ps, pd = "", ""
        while stack: 
            node, path = stack.pop()
            if node.val == startValue: ps = path 
            if node.val == destValue: pd = path
            if node.left: stack.append((node.left, path + "L"))
            if node.right: stack.append((node.right, path + "R"))
        return "U" * len(ps) + pd
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/step-by-step-directions-from-a-binary-tree-node-to-another/">2096. Step-By-Step Directions From a Binary Tree Node to Another</a></h2><h3>Medium</h3><hr><div><p>You are given the <code>root</code> of a <strong>binary tree</strong> with <code>n</code> nodes. Each node is uniquely assigned a value from <code>1</code> to <code>n</code>. You are also given an integer <code>startValue</code> representing the value of the start node <code>s</code>, and a different integer <code>destValue</code> representing the value of the destination node <code>t</code>.</p>

            else:
            
<p>Find the <strong>shortest path</strong> starting from node <code>s</code> and ending at node <code>t</code>. Generate step-by-step directions of such path as a string consisting of only the <strong>uppercase</strong> letters <code>'L'</code>, <code>'R'</code>, and <code>'U'</code>. Each letter indicates a specific direction:</p>

<ul>
	<li><code>'L'</code> means to go from a node to its <strong>left child</strong> node.</li>
	<li><code>'R'</code> means to go from a node to its <strong>right child</strong> node.</li>
	<li><code>'U'</code> means to go from a node to its <strong>parent</strong> node.</li>
</ul>

<p>Return <em>the step-by-step directions of the <strong>shortest path</strong> from node </em><code>s</code><em> to node</em> <code>t</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/15/eg1.png" style="width: 214px; height: 163px;">
<pre><strong>Input:</strong> root = [5,1,2,3,null,6,4], startValue = 3, destValue = 6
<strong>Output:</strong> "UURL"
<strong>Explanation:</strong> The shortest path is: 3 → 1 → 5 → 2 → 6.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/15/eg2.png" style="width: 74px; height: 102px;">
<pre><strong>Input:</strong> root = [2,1], startValue = 2, destValue = 1
<strong>Output:</strong> "L"
<strong>Explanation:</strong> The shortest path is: 2 → 1.
</pre>

<ul>
	<li><code>2 &lt;= n &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= Node.val &lt;= n</code></li>
	<li><code>1 &lt;= startValue, destValue &lt;= n</code></li>
	<li><code>startValue != destValue</code></li>
</ul>
</div>

directory: 1267-count-servers-that-communicate
Python: 
Notes: void dfs(vector<vector<int>>& grid, int i ,int j, int &count){
if(grid[i][j]==1){
count++;
grid[i][j]=0;
for(int c=0;c<grid[0].size();c++){
if(grid[i][c]==1)dfs(grid,i,c,count);
}
for(int r=0;r<grid.size();r++){
if(grid[r][j]==1)dfs(grid,r,j,count);
}
}
}
int countServers(vector<vector<int>>& grid) {
int ans=0;
for(int i=0;i<grid.size();i++){
for(int j=0;j<grid[0].size();j++){
int count=0;
dfs(grid,i,j,count);
if(count>1)ans+=count;
}
}
}
}
Readme: <h2><a href="https://leetcode.com/problems/count-servers-that-communicate/">1267. Count Servers that Communicate</a></h2><h3>Medium</h3><hr><div><p>You are given a map of a server center, represented as a <code>m * n</code> integer matrix&nbsp;<code>grid</code>, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.<br>
<br>
Return the number of servers&nbsp;that communicate with any other server.</p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/11/14/untitled-diagram-6.jpg" style="width: 202px; height: 203px;"></p>

<pre><strong>Input:</strong> grid = [[1,0],[0,1]]
<b>Explanation:</b>&nbsp;No servers can communicate with others.</pre>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2019/11/13/untitled-diagram-4.jpg" style="width: 203px; height: 203px;"></strong></p>

<pre><strong>Input:</strong> grid = [[1,0],[1,1]]
<b>Explanation:</b>&nbsp;All three servers can communicate with at least one other server.
</pre>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/11/14/untitled-diagram-1-3.jpg" style="width: 443px; height: 443px;"></p>

<pre><strong>Input:</strong> grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
<b>Explanation:</b>&nbsp;The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.
</pre>

<ul>
	<li><code>1 &lt;= m &lt;= 250</code></li>
	<li><code>1 &lt;= n &lt;= 250</code></li>
	<li><code>grid[i][j] == 0 or 1</code></li>
</ul>
</div>

directory: 389-find-the-difference
    def findTheDifference(self, s: str, t: str) -> str:
        for l in t:
            if l not in c or c[l] == 0:
                return l
            c[l]-=1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-the-difference/">389. Find the Difference</a></h2><h3>Easy</h3><hr><div><p>You are given two strings <code>s</code> and <code>t</code>.</p>

<p>String <code>t</code> is generated by random shuffling string <code>s</code> and then add one more letter at a random position.</p>

<p>Return the letter that was added to <code>t</code>.</p>

<pre><strong>Input:</strong> s = "abcd", t = "abcde"
<strong>Output:</strong> "e"
<strong>Explanation:</strong> 'e' is the letter that was added.
</pre>

<pre><strong>Input:</strong> s = "", t = "y"
<strong>Output:</strong> "y"
</pre>

        for l in t:
                return l
            c[l]-=1

<ul>
	<li><code>0 &lt;= s.length &lt;= 1000</code></li>
	<li><code>t.length == s.length + 1</code></li>
</ul>
</div>

directory: 705-design-hashset
Python: class MyHashSet:
        self.hash_value = 1000
        self.hash_table = [Bucket() for i in range(self.hash_value)]
        
    def add(self, key: int) -> None:
        idx = key % self.hash_value
        self.hash_table[idx].insert(key)
        
        self.hash_table[idx].delete(key)
        
    def contains(self, key: int) -> bool:
        return self.hash_table[idx].exists(key)

    def __init__(self, value, nextNode=None):
        self.value = value
        self.next = nextNode

class Bucket:
        # a pseudo head
        self.head = Node(0)

class MyHashSet:
        
    def insert(self, newValue):
        # if not existed, add the new element to the head.
        if not self.exists(newValue):
            newNode = Node(newValue, self.head.next)
            # set the new head.
            self.head.next = newNode

    def delete(self, value):
        prev = self.head
        curr = self.head.next
        while curr is not None:
            if curr.value == value:
                # remove the current node
                prev.next = curr.next
                return
            prev = curr

    def exists(self, value):
                # value existed already, do nothing
# Your MyHashSet object will be instantiated and called as such:
# obj = MyHashSet()
# obj.add(key)
# param_3 = obj.contains(key)

def insert(self, newValue):

                return
            prev = curr

def exists(self, value):
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/design-hashset/">705. Design HashSet</a></h2><h3>Easy</h3><hr><div><p>Design a HashSet without using any built-in hash table libraries.</p>

<p>Implement <code>MyHashSet</code> class:</p>

<ul>
	<li><code>void add(key)</code> Inserts the value <code>key</code> into the HashSet.</li>
	<li><code>bool contains(key)</code> Returns whether the value <code>key</code> exists in the HashSet or not.</li>
	<li><code>void remove(key)</code> Removes the value <code>key</code> in the HashSet. If <code>key</code> does not exist in the HashSet, do nothing.</li>
</ul>

["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"]
[[], [1], [2], [1], [3], [2], [2], [2], [2]]
[null, null, null, true, false, null, true, null, false]

MyHashSet myHashSet = new MyHashSet();
myHashSet.add(1);      // set = [1]
myHashSet.add(2);      // set = [1, 2]
myHashSet.contains(1); // return True
myHashSet.contains(3); // return False, (not found)
myHashSet.contains(2); // return True
myHashSet.remove(2);   // set = [1]
myHashSet.contains(2); // return False, (already removed)</pre>

<ul>
	<li><code>0 &lt;= key &lt;= 10<sup>6</sup></code></li>
	<li>At most <code>10<sup>4</sup></code> calls will be made to <code>add</code>, <code>remove</code>, and <code>contains</code>.</li>
</ul>
</div>

directory: 289-game-of-life
        """
        """
        copy = [[board[row][col] for col in range(cols)] for row in range(rows)]
                n = 0
                    
                        n += 1
                        
Notes: 

        """
        """
                n = 0
                    
                        n += 1
                        
</pre>

</pre>

directory: 491-increasing-subsequences
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/increasing-subsequences/">491. Increasing Subsequences</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, return all the different possible increasing subsequences of the given array with <strong>at least two elements</strong>. You may return the answer in <strong>any order</strong>.</p>

<p>The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.</p>

<pre><strong>Input:</strong> nums = [4,6,7,7]
<strong>Output:</strong> [[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
</pre>

<pre><strong>Input:</strong> nums = [4,4,3,2,1]
<strong>Output:</strong> [[4,4]]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 15</code></li>
	<li><code>-100 &lt;= nums[i] &lt;= 100</code></li>
</ul>
</div>

directory: 1506-find-root-of-n-ary-tree
        self.children = children if children is not None else []
"""

"""
"""

    def findRoot(self, tree: List['Node']) -> 'Node':
        
        hashMap = {}
            if node:
                val = node.val
                if val not in hashMap:
                    hashMap[val] = [0, node]
                for child in node.children:
                    hashMap[child.val] = [1, child]
                    dfs(child)
        for node in tree:
            if node.val not in hashMap:
                dfs(node)
        for key, val in hashMap.items():
            if val[0] == 0:
                return val[1]

            if node:
                dfs(node)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-root-of-n-ary-tree/">1506. Find Root of N-Ary Tree</a></h2><h3>Medium</h3><hr><div><p>You are given all the nodes of an <strong><a href="https://leetcode.com/articles/introduction-to-n-ary-trees/">N-ary tree</a></strong> as an array of <code>Node</code> objects, where each node has a <strong>unique value</strong>.</p>

<p>Return <em>the <strong>root</strong> of the N-ary tree</em>.</p>

<p><strong>Custom testing:</strong></p>

<p>An N-ary tree can be serialized as represented in its level order traversal where each group of children is separated by the <code>null</code> value (see examples).</p>

<p>For example, the above tree is serialized as <code>[1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]</code>.</p>

<p>The testing will be done in the following way:</p>

<ol>
	<li>The <strong>input data</strong> should be provided as a serialization of the tree.</li>
	<li>The driver code will construct the tree from the serialized input data and put each <code>Node</code> object into an array <strong>in an arbitrary order</strong>.</li>
	<li>The driver code will pass the array to <code>findRoot</code>, and your function should find and return the root <code>Node</code> object in the array.</li>
	<li>The driver code will take the returned <code>Node</code> object and serialize it. If the serialized value and the input data are the <strong>same</strong>, the test <strong>passes</strong>.</li>
</ol>

<pre><strong>Input:</strong> tree = [1,null,3,2,4,null,5,6]
<strong>Explanation:</strong> The tree from the input data is shown above.
The driver code creates the tree and gives findRoot the Node objects in an arbitrary order.
For example, the passed array could be [Node(5),Node(4),Node(3),Node(6),Node(2),Node(1)] or [Node(2),Node(6),Node(1),Node(3),Node(5),Node(4)].
The findRoot function should return the root Node(1), and the driver code will serialize it and compare with the input data.
The input data and serialized Node(1) are the same, so the test passes.
</pre>

<pre><strong>Input:</strong> tree = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
</pre>

<ul>
	<li>The total number of nodes is between <code>[1, 5 * 10<sup>4</sup>]</code>.</li>
	<li>Each node has a <strong>unique</strong> value.</li>
</ul>

<ul>
	<li>Could you solve this problem in constant space complexity with a linear time algorithm?</li>
</ul>
</div>

directory: 437-path-sum-iii
    def pathSum(self, root: Optional[TreeNode], targetSum: int) -> int:
        
        def dfs(root, curr_sum):
            nonlocal count
                return
            curr_sum += root.val
            if curr_sum == targetSum:
                count += 1
            count += h[curr_sum - targetSum]
            h[curr_sum] += 1
            dfs(root.left, curr_sum)
            dfs(root.right, curr_sum)
            h[curr_sum] -= 1
            
        count = 0
        h = defaultdict(int)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/path-sum-iii/">437. Path Sum III</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree and an integer <code>targetSum</code>, return <em>the number of paths where the sum of the values&nbsp;along the path equals</em>&nbsp;<code>targetSum</code>.</p>

                return
                count += 1
            
        count = 0
            
<p>The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/04/09/pathsum3-1-tree.jpg" style="width: 450px; height: 386px;">
<pre><strong>Input:</strong> root = [10,5,-3,3,2,null,11,3,-2,null,1], targetSum = 8
<strong>Explanation:</strong> The paths that sum to 8 are shown.
</pre>

</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[0, 1000]</code>.</li>
</ul>
</div>

directory: 0078-subsets
    def subsets(self, nums: List[int]) -> List[List[int]]:
        
        def backtrack(k, index, subSet):
            
            if index == k:
                
                outputs.append(subSet[:])
                
                return
            
            for i in range(index, len(nums)):
                
                backtrack(k, i + 1, subSet + [nums[i]])
                
        for j in range(len(nums) + 1):
            backtrack(j, 0, [])
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/subsets/">78. Subsets</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> of <strong>unique</strong> elements, return <em>all possible subsets (the power set)</em>.</p>

                return
            
<strong>Output:</strong> [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
</pre>

</pre>

<ul>
	<li>All the numbers of&nbsp;<code>nums</code> are <strong>unique</strong>.</li>
</ul>
</div>

directory: 961-n-repeated-element-in-size-2n-array
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/n-repeated-element-in-size-2n-array/">961. N-Repeated Element in Size 2N Array</a></h2><h3>Easy</h3><hr><div><p>You are given an integer array <code>nums</code> with the following properties:</p>

<ul>
	<li><code>nums.length == 2 * n</code>.</li>
	<li><code>nums</code> contains <code>n + 1</code> <strong>unique</strong> elements.</li>
	<li>Exactly one element of <code>nums</code> is repeated <code>n</code> times.</li>
</ul>

<p>Return <em>the element that is repeated </em><code>n</code><em> times</em>.</p>

<pre><strong>Input:</strong> nums = [1,2,3,3]
<pre><strong>Input:</strong> nums = [2,1,2,5,3,2]
<pre><strong>Input:</strong> nums = [5,1,5,2,5,3,5,4]
</pre>

<ul>
	<li><code>2 &lt;= n &lt;= 5000</code></li>
	<li><code>nums.length == 2 * n</code></li>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>4</sup></code></li>
	<li><code>nums</code> contains <code>n + 1</code> <strong>unique</strong> elements and one of them is repeated exactly <code>n</code> times.</li>
</ul>
</div>

directory: 160-intersection-of-two-linked-lists
#         self.next = None

    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        
        tempA, tempB = headA, headB
        
        while tempA or tempB:
            tempA = headB if tempA == None else tempA
            tempB = headA if tempB == None else tempB
            if tempA == tempB:
                return tempA
            tempA = tempA.next
            tempB = tempB.next
        return None
        
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/intersection-of-two-linked-lists/">160. Intersection of Two Linked Lists</a></h2><h3>Easy</h3><hr><div><p>Given the heads of two singly linked-lists <code>headA</code> and <code>headB</code>, return <em>the node at which the two lists intersect</em>. If the two linked lists have no intersection at all, return <code>null</code>.</p>

<p>For example, the following two linked lists begin to intersect at node <code>c1</code>:</p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/05/160_statement.png" style="width: 500px; height: 162px;">
<p>The test cases are generated such that there are no cycles anywhere in the entire linked structure.</p>

<p><strong>Note</strong> that the linked lists must <strong>retain their original structure</strong> after the function returns.</p>

<p><strong>Custom Judge:</strong></p>

<p>The inputs to the <strong>judge</strong> are given as follows (your program is <strong>not</strong> given these inputs):</p>

<ul>
	<li><code>intersectVal</code> - The value of the node where the intersection occurs. This is <code>0</code> if there is no intersected node.</li>
	<li><code>listA</code> - The first linked list.</li>
	<li><code>listB</code> - The second linked list.</li>
	<li><code>skipA</code> - The number of nodes to skip ahead in <code>listA</code> (starting from the head) to get to the intersected node.</li>
	<li><code>skipB</code> - The number of nodes to skip ahead in <code>listB</code> (starting from the head) to get to the intersected node.</li>
</ul>

<p>The judge will then create the linked structure based on these inputs and pass the two heads, <code>headA</code> and <code>headB</code>&nbsp;to your program. If you correctly return the intersected node, then your solution will be <strong>accepted</strong>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/05/160_example_1_1.png" style="width: 500px; height: 162px;">
<pre><strong>Input:</strong> intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
<strong>Output:</strong> Intersected at '8'
<strong>Explanation:</strong> The intersected node's value is 8 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/05/160_example_2.png" style="width: 500px; height: 194px;">
<pre><strong>Input:</strong> intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
<strong>Output:</strong> Intersected at '2'
<strong>Explanation:</strong> The intersected node's value is 2 (note that this must not be 0 if the two lists intersect).
From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/05/160_example_3.png" style="width: 300px; height: 189px;">
<pre><strong>Input:</strong> intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
<strong>Output:</strong> No intersection
<strong>Explanation:</strong> From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values.
Explanation: The two lists do not intersect, so return null.
</pre>

<ul>
	<li>The number of nodes of <code>listA</code> is in the <code>m</code>.</li>
	<li>The number of nodes of <code>listB</code> is in the <code>n</code>.</li>
	<li><code>1 &lt;= m, n &lt;= 3 * 10<sup>4</sup></code></li>
	<li><code>0 &lt;= skipA &lt;&nbsp;m</code></li>
	<li><code>0 &lt;= skipB &lt;&nbsp;n</code></li>
	<li><code>intersectVal</code> is <code>0</code> if <code>listA</code> and <code>listB</code> do not intersect.</li>
	<li><code>intersectVal == listA[skipA] == listB[skipB]</code> if <code>listA</code> and <code>listB</code> intersect.</li>
</ul>

<strong>Follow up:</strong> Could you write a solution that runs in <code>O(m + n)</code> time and use only <code>O(1)</code> memory?</div>

directory: 1662-check-if-two-string-arrays-are-equivalent
    def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:
        
        n, m = len(word1), len(word2)
        word1Pointer, word2Pointer = 0, 0
        string1Pointer, string2Pointer = 0, 0
        
        while word1Pointer < n and word2Pointer < m:
            
            if word1[word1Pointer][string1Pointer] != word2[word2Pointer][string2Pointer]:
            string1Pointer += 1
            string2Pointer += 1
            
            if string1Pointer == len(word1[word1Pointer]):
                word1Pointer += 1
                string1Pointer = 0
            
            if string2Pointer == len(word2[word2Pointer]):
                word2Pointer += 1
                string2Pointer = 0
        
        return word1Pointer == len(word1) and word2Pointer == len(word2)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/">1662. Check If Two String Arrays are Equivalent</a></h2><h3>Easy</h3><hr><div><p>Given two string arrays <code>word1</code> and <code>word2</code>, return<em> </em><code>true</code><em> if the two arrays <strong>represent</strong> the same string, and </em><code>false</code><em> otherwise.</em></p>

<p>A string is <strong>represented</strong> by an array if the array elements concatenated <strong>in order</strong> forms the string.</p>

<pre><strong>Input:</strong> word1 = ["ab", "c"], word2 = ["a", "bc"]
word1 represents string "ab" + "c" -&gt; "abc"
word2 represents string "a" + "bc" -&gt; "abc"
The strings are the same, so return true.</pre>

<pre><strong>Input:</strong> word1 = ["a", "cb"], word2 = ["ab", "c"]
</pre>

<pre><strong>Input:</strong> word1  = ["abc", "d", "defg"], word2 = ["abcddefg"]
</pre>

<ul>
	<li><code>1 &lt;= word1.length, word2.length &lt;= 10<sup>3</sup></code></li>
	<li><code>1 &lt;= word1[i].length, word2[i].length &lt;= 10<sup>3</sup></code></li>
	<li><code>1 &lt;= sum(word1[i].length), sum(word2[i].length) &lt;= 10<sup>3</sup></code></li>
	<li><code>word1[i]</code> and <code>word2[i]</code> consist of lowercase letters.</li>
</ul>
</div>

directory: 1166-design-file-system
Python: class FileSystem:

        self.paths = defaultdict(int)

    def createPath(self, path: str, value: int) -> bool:
        
        if len(path) == 0 or path == '/' or path in self.paths:
        
        parent = path[:path.rfind('/')]
        if len(parent) > 1 and parent not in self.paths:
        self.paths[path] = value

    def get(self, path: str) -> int:
        
        return self.paths.get(path, -1)

# Your FileSystem object will be instantiated and called as such:
# obj = FileSystem()
# param_1 = obj.createPath(path,value)
# param_2 = obj.get(path)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/design-file-system/">1166. Design File System</a></h2><h3>Medium</h3><hr><div><p>You are asked to design a file system&nbsp;that allows you to create new paths and associate them with different values.</p>

class FileSystem:

<p>The format of a path is&nbsp;one or more concatenated strings of the form:&nbsp;<code>/</code> followed by one or more lowercase English letters. For example, "<code>/leetcode"</code>&nbsp;and "<code>/leetcode/problems"</code>&nbsp;are valid paths while an empty&nbsp;string <code>""</code> and <code>"/"</code>&nbsp;are not.</p>

<p>Implement the&nbsp;<code>FileSystem</code> class:</p>

<ul>
	<li><code>bool createPath(string path, int value)</code>&nbsp;Creates a new <code>path</code> and associates a <code>value</code> to it if possible and returns <code>true</code>.&nbsp;Returns <code>false</code>&nbsp;if the path <strong>already exists</strong> or its parent path <strong>doesn't exist</strong>.</li>
	<li><code>int get(string path)</code>&nbsp;Returns the value associated with <code>path</code> or returns&nbsp;<code>-1</code>&nbsp;if the path doesn't exist.</li>
</ul>

["FileSystem","createPath","get"]
[[],["/a",1],["/a"]]
[null,true,1]
FileSystem fileSystem = new FileSystem();

fileSystem.createPath("/a", 1); // return true
fileSystem.get("/a"); // return 1
</pre>

["FileSystem","createPath","createPath","get","createPath","get"]
[[],["/leet",1],["/leet/code",2],["/leet/code"],["/c/d",1],["/c"]]
[null,true,true,2,false,-1]

fileSystem.createPath("/leet", 1); // return true
fileSystem.createPath("/leet/code", 2); // return true
fileSystem.get("/leet/code"); // return 2
fileSystem.createPath("/c/d", 1); // return false because the parent path "/c" doesn't exist.
fileSystem.get("/c"); // return -1 because this path doesn't exist.
</pre>

<ul>
	<li>The number of&nbsp;calls to the two functions&nbsp;is less than or equal to <code>10<sup>4</sup></code> in total.</li>
	<li><code>2 &lt;= path.length &lt;= 100</code></li>
	<li><code>1 &lt;= value &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 36-valid-sudoku
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        
        boxes = [set() for _ in range(9)]
        
        for r in range(len(board)):
            for c in range(len(board[0])):
                value = board[r][c] 
                if value == '.':
                    continue
                
                if value in rows[r]:
                rows[r].add(value)
                
                if value in cols[c]:
                cols[c].add(value)
                
                index = (r // 3) * 3 + (c // 3)
                if value in boxes[index]:
                boxes[index].add(value)
Notes: ​
Readme:

                    continue
                
directory: 15-3sum
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        
        i = 0
        ans = []
        while i < len(nums) - 2:
            j, k = i + 1, n - 1
            while j < k:
                s = nums[i] + nums[j] + nums[k]
                if s == 0:
                    ans.append([nums[i], nums[j], nums[k]])
                    j += 1
                    while j < k and nums[j] == nums[j-1]:
                        j += 1
                    k-=1
                    while j < k and nums[k] == nums[k + 1]:
                        k-= 1
                elif s < 0:
                    j += 1
                        j += 1
                else:
                    k-=1
                        k-= 1
            i += 1
            while i < len(nums) - 2 and nums[i] == nums[i-1]:
                i += 1
                
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/3sum/">15. 3Sum</a></h2><h3>Medium</h3><hr><div><p>Given an integer array nums, return all the triplets <code>[nums[i], nums[j], nums[k]]</code> such that <code>i != j</code>, <code>i != k</code>, and <code>j != k</code>, and <code>nums[i] + nums[j] + nums[k] == 0</code>.</p>

        i = 0
        ans = []
            while j < k:
                if s == 0:
                    j += 1
                        j += 1
                    k-=1
                        k-= 1
                elif s < 0:
                    j += 1
                        j += 1
                else:
                    k-=1
                        k-= 1
            i += 1
                i += 1
                
        return ans
        
<p>Notice that the solution set must not contain duplicate triplets.</p>

<pre><strong>Input:</strong> nums = [-1,0,1,2,-1,-4]
<strong>Output:</strong> [[-1,-1,2],[-1,0,1]]
nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0.
nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0.
nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0.
The distinct triplets are [-1,0,1] and [-1,-1,2].
Notice that the order of the output and the order of the triplets does not matter.
</pre>

<pre><strong>Input:</strong> nums = [0,1,1]
<strong>Explanation:</strong> The only possible triplet does not sum up to 0.
</pre>

<pre><strong>Input:</strong> nums = [0,0,0]
<strong>Output:</strong> [[0,0,0]]
<strong>Explanation:</strong> The only possible triplet sums up to 0.
</pre>

<ul>
	<li><code>3 &lt;= nums.length &lt;= 3000</code></li>
</ul>
</div>

directory: 977-squares-of-a-sorted-array
        result = [0] * n
        left = 0
        right = n - 1
                square = nums[right]
                right -= 1
            else:
                square = nums[left]
                left += 1
            result[i] = square * square
Notes: ​

        left = 0
        right = n - 1
                right -= 1
            else:
                left += 1
        
</pre>

</pre>

<ul>
</ul>

directory: 767-reorganize-string
    def reorganizeString(self, s: str) -> str:
        
        ans = ['']*len(s)
        index = 0
            for _ in range(v):
                if index == 0:
                    ans[index] = k
                    index +=2
                elif (0 < index < len(s) - 1) and (ans[index-1] == k or ans[index+1] == k):
                    return ""
                elif index == len(ans)and ans[index - 1] == k:
                    return ""
                else:
                    index += 2
                if index >= len(ans):
                    index = 1
        return "".join(ans)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reorganize-string/">767. Reorganize String</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, rearrange the characters of <code>s</code> so that any two adjacent characters are not the same.</p>

        index = 0
                    index +=2
                    return ""
                    return ""
                else:
                    index += 2
                    index = 1

<p>Return <em>any possible rearrangement of</em> <code>s</code> <em>or return</em> <code>""</code> <em>if not possible</em>.</p>

<strong>Output:</strong> "aba"
<pre><strong>Input:</strong> s = "aaab"
</pre>

<ul>
	<li><code>1 &lt;= s.length &lt;= 500</code></li>
</ul>
</div>

directory: 2087-minimum-cost-homecoming-of-a-robot-in-a-grid
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-cost-homecoming-of-a-robot-in-a-grid/">2087. Minimum Cost Homecoming of a Robot in a Grid</a></h2><h3>Medium</h3><hr><div><p>There is an <code>m x n</code> grid, where <code>(0, 0)</code> is the top-left cell and <code>(m - 1, n - 1)</code> is the bottom-right cell. You are given an integer array <code>startPos</code> where <code>startPos = [start<sub>row</sub>, start<sub>col</sub>]</code> indicates that <strong>initially</strong>, a <strong>robot</strong> is at the cell <code>(start<sub>row</sub>, start<sub>col</sub>)</code>. You are also given an integer array <code>homePos</code> where <code>homePos = [home<sub>row</sub>, home<sub>col</sub>]</code> indicates that its <strong>home</strong> is at the cell <code>(home<sub>row</sub>, home<sub>col</sub>)</code>.</p>

<p>The robot needs to go to its home. It can move one cell in four directions: <strong>left</strong>, <strong>right</strong>, <strong>up</strong>, or <strong>down</strong>, and it can not move outside the boundary. Every move incurs some cost. You are further given two <strong>0-indexed</strong> integer arrays: <code>rowCosts</code> of length <code>m</code> and <code>colCosts</code> of length <code>n</code>.</p>

<ul>
	<li>If the robot moves <strong>up</strong> or <strong>down</strong> into a cell whose <strong>row</strong> is <code>r</code>, then this move costs <code>rowCosts[r]</code>.</li>
	<li>If the robot moves <strong>left</strong> or <strong>right</strong> into a cell whose <strong>column</strong> is <code>c</code>, then this move costs <code>colCosts[c]</code>.</li>
</ul>

<p>Return <em>the <strong>minimum total cost</strong> for this robot to return home</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/10/11/eg-1.png" style="width: 282px; height: 217px;">
<pre><strong>Input:</strong> startPos = [1, 0], homePos = [2, 3], rowCosts = [5, 4, 3], colCosts = [8, 2, 6, 7]
<strong>Explanation:</strong> One optimal path is that:
Starting from (1, 0)
-&gt; It goes down to (<u><strong>2</strong></u>, 0). This move costs rowCosts[2] = 3.
-&gt; It goes right to (2, <u><strong>1</strong></u>). This move costs colCosts[1] = 2.
-&gt; It goes right to (2, <u><strong>2</strong></u>). This move costs colCosts[2] = 6.
-&gt; It goes right to (2, <u><strong>3</strong></u>). This move costs colCosts[3] = 7.
The total cost is 3 + 2 + 6 + 7 = 18</pre>

<pre><strong>Input:</strong> startPos = [0, 0], homePos = [0, 0], rowCosts = [5], colCosts = [26]
<strong>Explanation:</strong> The robot is already at its home. Since no moves occur, the total cost is 0.
</pre>

<ul>
	<li><code>m == rowCosts.length</code></li>
	<li><code>n == colCosts.length</code></li>
	<li><code>1 &lt;= m, n &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= rowCosts[r], colCosts[c] &lt;= 10<sup>4</sup></code></li>
	<li><code>startPos.length == 2</code></li>
	<li><code>homePos.length == 2</code></li>
	<li><code>0 &lt;= start<sub>row</sub>, home<sub>row</sub> &lt; m</code></li>
	<li><code>0 &lt;= start<sub>col</sub>, home<sub>col</sub> &lt; n</code></li>
</ul>
</div>

directory: 0360-sort-transformed-array
    def sortTransformedArray(self, nums: List[int], a: int, b: int, c: int) -> List[int]:
        
        def apply_quadratic(x):
            return a * x * x + b * x + c
        
            nums[i] = apply_quadratic(nums[i])
        return sorted(nums)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sort-transformed-array/">360. Sort Transformed Array</a></h2><h3>Medium</h3><hr><div><p>Given a <strong>sorted</strong> integer array <code>nums</code> and three integers <code>a</code>, <code>b</code> and <code>c</code>, apply a quadratic function of the form <code>f(x) = ax<sup>2</sup> + bx + c</code> to each element <code>nums[i]</code> in the array, and return <em>the array in a sorted order</em>.</p>

<pre><strong>Input:</strong> nums = [-4,-2,2,4], a = 1, b = 3, c = 5
<strong>Output:</strong> [3,9,15,33]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> nums = [-4,-2,2,4], a = -1, b = 3, c = 5
<strong>Output:</strong> [-23,-5,1,7]
</pre>

<ul>
	<li><code>-100 &lt;= nums[i], a, b, c &lt;= 100</code></li>
	<li><code>nums</code> is sorted in <strong>ascending</strong> order.</li>
</ul>

<p><strong>Follow up:</strong> Could you solve it in <code>O(n)</code> time?</p>
</div>

directory: 2034-stock-price-fluctuation
Python: class StockPrice:
        self.latest_time = 0
        # Store price of each stock at each timestamp.
        self.timestamp_price_map = {}
        
        # Store stock prices in sorted order to get min and max price.
        self.max_heap = []
        self.min_heap = []

    def update(self, timestamp: int, price: int) -> None:
        # Update latestTime to latest timestamp.
        self.timestamp_price_map[timestamp] = price
        self.latest_time = max(self.latest_time, timestamp)

        # Add latest price for timestamp.
        heappush(self.min_heap, (price, timestamp))
        heappush(self.max_heap, (-price, timestamp))

    def current(self) -> int:
        # Return latest price of the stock.
        return self.timestamp_price_map[self.latest_time]

    def maximum(self) -> int:
        price, timestamp = self.max_heap[0]

class StockPrice:
        
        # Pop pairs from heap with the price doesn't match with hashmap.
        while -price != self.timestamp_price_map[timestamp]:
            heappop(self.max_heap)
            price, timestamp = self.max_heap[0]
            
        return -price

    def minimum(self) -> int:
        price, timestamp = self.min_heap[0]

        while price != self.timestamp_price_map[timestamp]:
            heappop(self.min_heap)
            price, timestamp = self.min_heap[0]
            
        return price

# Pop pairs from heap with the price doesn't match with hashmap.
            
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/stock-price-fluctuation/">2034. Stock Price Fluctuation </a></h2><h3>Medium</h3><hr><div><p>You are given a stream of <strong>records</strong> about a particular stock. Each record contains a <strong>timestamp</strong> and the corresponding <strong>price</strong> of the stock at that timestamp.</p>

<p>Unfortunately due to the volatile nature of the stock market, the records do not come in order. Even worse, some records may be incorrect. Another record with the same timestamp may appear later in the stream <strong>correcting</strong> the price of the previous wrong record.</p>

<p>Design an algorithm that:</p>

<ul>
	<li><strong>Updates</strong> the price of the stock at a particular timestamp, <strong>correcting</strong> the price from any previous records at the timestamp.</li>
	<li>Finds the <strong>latest price</strong> of the stock based on the current records. The <strong>latest price</strong> is the price at the latest timestamp recorded.</li>
	<li>Finds the <strong>maximum price</strong> the stock has been based on the current records.</li>
	<li>Finds the <strong>minimum price</strong> the stock has been based on the current records.</li>
</ul>

<p>Implement the <code>StockPrice</code> class:</p>

<ul>
	<li><code>StockPrice()</code> Initializes the object with no price records.</li>
	<li><code>void update(int timestamp, int price)</code> Updates the <code>price</code> of the stock at the given <code>timestamp</code>.</li>
	<li><code>int current()</code> Returns the <strong>latest price</strong> of the stock.</li>
	<li><code>int maximum()</code> Returns the <strong>maximum price</strong> of the stock.</li>
	<li><code>int minimum()</code> Returns the <strong>minimum price</strong> of the stock.</li>
</ul>

["StockPrice", "update", "update", "current", "maximum", "update", "maximum", "update", "minimum"]
[[], [1, 10], [2, 5], [], [], [1, 3], [], [4, 2], []]
[null, null, null, 5, 10, null, 5, null, 2]

StockPrice stockPrice = new StockPrice();
stockPrice.update(1, 10); // Timestamps are [1] with corresponding prices [10].
stockPrice.update(2, 5);  // Timestamps are [1,2] with corresponding prices [10,5].
stockPrice.current();     // return 5, the latest timestamp is 2 with the price being 5.
stockPrice.maximum();     // return 10, the maximum price is 10 at timestamp 1.
stockPrice.update(1, 3);  // The previous timestamp 1 had the wrong price, so it is updated to 3.
                          // Timestamps are [1,2] with corresponding prices [3,5].
stockPrice.maximum();     // return 5, the maximum price is 5 after the correction.
stockPrice.update(4, 2);  // Timestamps are [1,2,4] with corresponding prices [3,5,2].
stockPrice.minimum();     // return 2, the minimum price is 2 at timestamp 4.
</pre>

<ul>
	<li><code>1 &lt;= timestamp, price &lt;= 10<sup>9</sup></code></li>
	<li>At most <code>10<sup>5</sup></code> calls will be made <strong>in total</strong> to <code>update</code>, <code>current</code>, <code>maximum</code>, and <code>minimum</code>.</li>
	<li><code>current</code>, <code>maximum</code>, and <code>minimum</code> will be called <strong>only after</strong> <code>update</code> has been called <strong>at least once</strong>.</li>
</ul>
</div>

directory: 11-container-with-most-water
    def maxArea(self, height: List[int]) -> int:
        
        left, right = 0, len(height) - 1
        max_area = (right - left) * min(height[left], height[right])
        
            area = (right - left) * min(height[left], height[right])
            max_area = max(max_area, area)
            if height[right] > height[left]:
                left += 1
            else:
                right -= 1
            
        return max_area
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/container-with-most-water/">11. Container With Most Water</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>height</code> of length <code>n</code>. There are <code>n</code> vertical lines drawn such that the two endpoints of the <code>i<sup>th</sup></code> line are <code>(i, 0)</code> and <code>(i, height[i])</code>.</p>

                left += 1
            else:
                right -= 1
            
<p>Find two lines that together with the x-axis form a container, such that the container contains the most water.</p>

<p>Return <em>the maximum amount of water a container can store</em>.</p>

<p><strong>Notice</strong> that you may not slant the container.</p>

<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/07/17/question_11.jpg" style="width: 600px; height: 287px;">
<pre><strong>Input:</strong> height = [1,8,6,2,5,4,8,3,7]
<strong>Output:</strong> 49
<strong>Explanation:</strong> The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
</pre>

<pre><strong>Input:</strong> height = [1,1]
</pre>

<ul>
	<li><code>n == height.length</code></li>
	<li><code>0 &lt;= height[i] &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 48-rotate-image
    def transpose(self, matrix):
        n = len(matrix)
            for j in range(i + 1, n):
                matrix[j][i], matrix[i][j] = matrix[i][j], matrix[j][i]
                
    def reflect(self, matrix):
            for j in range(n // 2):
                matrix[i][j], matrix[i][-j-1] = matrix[i][-j-1], matrix[i][j]
                
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        
        self.transpose(matrix)
        self.reflect(matrix)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/rotate-image/">48. Rotate Image</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>n x n</code> 2D <code>matrix</code> representing an image, rotate the image by <strong>90</strong> degrees (clockwise).</p>

        """
        """
        
<p>You have to rotate the image <a href="https://en.wikipedia.org/wiki/In-place_algorithm" target="_blank"><strong>in-place</strong></a>, which means you have to modify the input 2D matrix directly. <strong>DO NOT</strong> allocate another 2D matrix and do the rotation.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/08/28/mat1.jpg" style="width: 500px; height: 188px;">
<strong>Output:</strong> [[7,4,1],[8,5,2],[9,6,3]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/08/28/mat2.jpg" style="width: 500px; height: 201px;">
<pre><strong>Input:</strong> matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
<strong>Output:</strong> [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
</pre>

<ul>
	<li><code>n == matrix.length == matrix[i].length</code></li>
	<li><code>1 &lt;= n &lt;= 20</code></li>
	<li><code>-1000 &lt;= matrix[i][j] &lt;= 1000</code></li>
</ul>
</div>

directory: 1366-rank-teams-by-votes
    def rankTeams(self, votes: List[str]) -> str:
        
        d = dict()
        for vote in votes:
            for i, c in enumerate(vote):
                if c not in d:
                    d[c] = [0] * len(vote)
                d[c][i] += 1
        sorted_names = sorted(d.keys())
        voted_names = sorted(d.keys())
        return "".join(sorted(voted_names, key=lambda x: d[x], reverse=True))
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/rank-teams-by-votes/">1366. Rank Teams by Votes</a></h2><h3>Medium</h3><hr><div><p>In a special ranking system, each voter gives a rank from highest to lowest to all teams participated in the competition.</p>

        d = dict()
        
<p>The ordering of teams is decided by who received the most position-one votes. If two or more teams tie in the first position, we consider the second position to resolve the conflict, if they tie again, we continue this process until the ties are resolved. If two or more teams are still tied after considering all positions, we rank them alphabetically based on their team letter.</p>

<p>Given an array of strings <code>votes</code> which is the votes of all voters in the ranking systems. Sort all teams according to the ranking system described above.</p>

<p>Return <em>a string of all teams</em> <strong>sorted</strong> by the ranking system.</p>

<pre><strong>Input:</strong> votes = ["ABC","ACB","ABC","ACB","ACB"]
<strong>Output:</strong> "ACB"
<strong>Explanation:</strong> Team A was ranked first place by 5 voters. No other team was voted as first place so team A is the first team.
Team B was ranked second by 2 voters and was ranked third by 3 voters.
Team C was ranked second by 3 voters and was ranked third by 2 voters.
As most of the voters ranked C second, team C is the second team and team B is the third.
</pre>

<pre><strong>Input:</strong> votes = ["WXYZ","XYZW"]
<strong>Output:</strong> "XWYZ"
<strong>Explanation:</strong> X is the winner due to tie-breaking rule. X has same votes as W for the first position but X has one vote as second position while W doesn't have any votes as second position. 
</pre>

<pre><strong>Input:</strong> votes = ["ZMNAGUEDSJYLBOPHRQICWFXTVK"]
<strong>Output:</strong> "ZMNAGUEDSJYLBOPHRQICWFXTVK"
<strong>Explanation:</strong> Only one voter so his votes are used for the ranking.
</pre>

<ul>
	<li><code>1 &lt;= votes.length &lt;= 1000</code></li>
	<li><code>1 &lt;= votes[i].length &lt;= 26</code></li>
	<li><code>votes[i].length == votes[j].length</code> for <code>0 &lt;= i, j &lt; votes.length</code>.</li>
	<li><code>votes[i][j]</code> is an English <strong>uppercase</strong> letter.</li>
	<li>All characters of <code>votes[i]</code> are unique.</li>
	<li>All the characters that occur in <code>votes[0]</code> <strong>also occur</strong> in <code>votes[j]</code> where <code>1 &lt;= j &lt; votes.length</code>.</li>
</ul>
</div>

directory: 134-gas-station
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/gas-station/">134. Gas Station</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> gas stations along a circular route, where the amount of gas at the <code>i<sup>th</sup></code> station is <code>gas[i]</code>.</p>

<p>You have a car with an unlimited gas tank and it costs <code>cost[i]</code> of gas to travel from the <code>i<sup>th</sup></code> station to its next <code>(i + 1)<sup>th</sup></code> station. You begin the journey with an empty tank at one of the gas stations.</p>

<p>Given two integer arrays <code>gas</code> and <code>cost</code>, return <em>the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return</em> <code>-1</code>. If there exists a solution, it is <strong>guaranteed</strong> to be <strong>unique</strong></p>

<pre><strong>Input:</strong> gas = [1,2,3,4,5], cost = [3,4,5,1,2]
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.
</pre>

<pre><strong>Input:</strong> gas = [2,3,4], cost = [3,4,3]
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.
</pre>

<ul>
	<li><code>n == gas.length == cost.length</code></li>
	<li><code>0 &lt;= gas[i], cost[i] &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 142-linked-list-cycle-ii
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/linked-list-cycle-ii/">142. Linked List Cycle II</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a linked list, return <em>the node where the cycle begins. If there is no cycle, return </em><code>null</code>.</p>

<p>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 <code>next</code> pointer. Internally, <code>pos</code> is used to denote the index of the node that tail's <code>next</code> pointer is connected to (<strong>0-indexed</strong>). It is <code>-1</code> if there is no cycle. <strong>Note that</strong> <code>pos</code> <strong>is not passed as a parameter</strong>.</p>

<p><strong>Do not modify</strong> the linked list.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" style="height: 145px; width: 450px;">
<pre><strong>Input:</strong> head = [3,2,0,-4], pos = 1
<strong>Output:</strong> tail connects to node index 1
<strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the second node.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" style="height: 105px; width: 201px;">
<pre><strong>Input:</strong> head = [1,2], pos = 0
<strong>Output:</strong> tail connects to node index 0
<strong>Explanation:</strong> There is a cycle in the linked list, where tail connects to the first node.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" style="height: 65px; width: 65px;">
<pre><strong>Input:</strong> head = [1], pos = -1
<strong>Output:</strong> no cycle
<strong>Explanation:</strong> There is no cycle in the linked list.
</pre>

<ul>
	<li>The number of the nodes in the list is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
	<li><code>-10<sup>5</sup> &lt;= Node.val &lt;= 10<sup>5</sup></code></li>
	<li><code>pos</code> is <code>-1</code> or a <strong>valid index</strong> in the linked-list.</li>
</ul>

<p><strong>Follow up:</strong> Can you solve it using <code>O(1)</code> (i.e. constant) memory?</p>
</div>

directory: 586-customer-placing-the-largest-number-of-orders
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/customer-placing-the-largest-number-of-orders/">586. Customer Placing the Largest Number of Orders</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Orders</code></p>

<pre>+-----------------+----------+
| Column Name     | Type     |
+-----------------+----------+
| order_number    | int      |
| customer_number | int      |
order_number is the primary key for this table.
This table contains information about the order ID and the customer ID.
</pre>

<p>Write an SQL query to find the <code>customer_number</code> for the customer who has placed <strong>the largest number of orders</strong>.</p>

<p>The test cases are generated so that <strong>exactly one customer</strong> will have placed more orders than any other customer.</p>

Orders table:
+--------------+-----------------+
| order_number | customer_number |
| 1            | 1               |
| 2            | 2               |
| 3            | 3               |
| 4            | 3               |
+-----------------+
| customer_number |
| 3               |
The customer with number 3 has two orders, which is greater than either customer 1 or 2 because each of them only has one order. 
So the result is customer_number 3.
</pre>

<p><strong>Follow up:</strong> What if more than one customer has the largest number of orders, can you find all the <code>customer_number</code> in this case?</p>
</div>

directory: 183-customers-who-never-order
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/customers-who-never-order/">183. Customers Who Never Order</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Customers</code></p>

| id          | int     |
Each row of this table indicates the ID and name of a customer.
</pre>

<p>Table: <code>Orders</code></p>

| id          | int  |
| customerId  | int  |
customerId is a foreign key of the ID from the Customers table.
Each row of this table indicates the ID of an order and the ID of the customer who ordered it.
</pre>

<p>Write an SQL query to report all customers who never order anything.</p>

Customers table:
+----+-------+
| id | name  |
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+------------+
| id | customerId |
| 1  | 3          |
| 2  | 1          |
+-----------+
| Customers |
| Henry     |
| Max       |
</pre>
</div>

directory: 318-maximum-product-of-word-lengths
    def maxProduct(self, words: List[str]) -> int:
        n = len(words)
        masks = [0] * n
        lens = [0] * n
        bit_number = lambda ch : ord(ch) - ord('a')
        
            bitmask = 0
            for ch in words[i]:
                # add bit number bit_number in bitmask
                bitmask |= 1 << bit_number(ch)
            masks[i] = bitmask
            lens[i] = len(words[i])
            
        max_val = 0
                if masks[i] & masks[j] == 0:
                    max_val = max(max_val, lens[i] * lens[j])
        return max_val
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-product-of-word-lengths/">318. Maximum Product of Word Lengths</a></h2><h3>Medium</h3><hr><div><p>Given a string array <code>words</code>, return <em>the maximum value of</em> <code>length(word[i]) * length(word[j])</code> <em>where the two words do not share common letters</em>. If no such two words exist, return <code>0</code>.</p>

            bitmask = 0
            
        max_val = 0

<pre><strong>Input:</strong> words = ["abcw","baz","foo","bar","xtfn","abcdef"]
<strong>Output:</strong> 16
<strong>Explanation:</strong> The two words can be "abcw", "xtfn".
</pre>

<pre><strong>Input:</strong> words = ["a","ab","abc","d","cd","bcd","abcd"]
<strong>Explanation:</strong> The two words can be "ab", "cd".
</pre>

<pre><strong>Input:</strong> words = ["a","aa","aaa","aaaa"]
<strong>Explanation:</strong> No such pair of words.
</pre>

<ul>
	<li><code>2 &lt;= words.length &lt;= 1000</code></li>
	<li><code>1 &lt;= words[i].length &lt;= 1000</code></li>
	<li><code>words[i]</code> consists only of lowercase English letters.</li>
</ul>
</div>

directory: 931-minimum-falling-path-sum
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-falling-path-sum/">931. Minimum Falling Path Sum</a></h2><h3>Medium</h3><hr><div><p>Given an <code>n x n</code> array of integers <code>matrix</code>, return <em>the <strong>minimum sum</strong> of any <strong>falling path</strong> through</em> <code>matrix</code>.</p>

<p>A <strong>falling path</strong> starts at any element in the first row and chooses the element in the next row that is either directly below or diagonally left/right. Specifically, the next element from position <code>(row, col)</code> will be <code>(row + 1, col - 1)</code>, <code>(row + 1, col)</code>, or <code>(row + 1, col + 1)</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/03/failing1-grid.jpg" style="width: 499px; height: 500px;">
<pre><strong>Input:</strong> matrix = [[2,1,3],[6,5,4],[7,8,9]]
<strong>Output:</strong> 13
<strong>Explanation:</strong> There are two falling paths with a minimum sum as shown.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/11/03/failing2-grid.jpg" style="width: 164px; height: 365px;">
<pre><strong>Input:</strong> matrix = [[-19,57],[-40,-5]]
<strong>Output:</strong> -59
<strong>Explanation:</strong> The falling path with a minimum sum is shown.
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 100</code></li>
</ul>
</div>

directory: 196-delete-duplicate-emails
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/delete-duplicate-emails/">196. Delete Duplicate Emails</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Person</code></p>

| id          | int     |
</pre>

<p>Write an SQL query to <strong>delete</strong> all the duplicate emails, keeping only one unique email with the smallest <code>id</code>. Note that you are supposed to write a<code> DELETE</code> statement and not a <code>SELECT</code> one.</p>

+----+------------------+
| id | email            |
| 1  | john@example.com |
| 2  | bob@example.com  |
| 3  | john@example.com |
<strong>Explanation:</strong> john@example.com is repeated two times. We keep the row with the smallest Id = 1.
</pre>
</div>

directory: 74-search-a-2d-matrix
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        
        left, right = 0, m * n - 1
        while left <= right:
            pivot_element = matrix[mid // n][mid % n]
            if pivot_element == target:
            elif pivot_element < target:
            else:
                right = mid - 1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/search-a-2d-matrix/">74. Search a 2D Matrix</a></h2><h3>Medium</h3><hr><div><p>Write an efficient algorithm that searches for a value <code>target</code> in an <code>m x n</code> integer matrix <code>matrix</code>. This matrix has the following properties:</p>

            else:
        
<ul>
	<li>Integers in each row are sorted from left to right.</li>
	<li>The first integer of each row is greater than the last integer of the previous row.</li>
</ul>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/05/mat.jpg" style="width: 322px; height: 242px;">
<pre><strong>Input:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/05/mat2.jpg" style="width: 322px; height: 242px;">
<pre><strong>Input:</strong> matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
</pre>

<ul>
	<li><code>-10<sup>4</sup> &lt;= matrix[i][j], target &lt;= 10<sup>4</sup></code></li>
</ul>
</div>

directory: 130-surrounded-regions
    def solve(self, board: List[List[str]]) -> None:
        """
        """
        def dfs(r, c, first):
            if r < 0 or r >= rows or c < 0 or c >= cols:
                return 
            if board[r][c] != 'O':
                return
            if first:
                board[r][c] = '#'
            else:
                board[r][c] = 'X'
            dfs(r + 1, c, first)
            dfs(r - 1, c, first)
            dfs(r, c + 1, first)
            dfs(r, c - 1, first)
                if (r == 0 or c == 0 or r == rows - 1 or c == cols - 1) and board[r][c] == 'O':
                    dfs(r, c, first = True)
                if board[r][c] == 'O':
                    dfs(r,c, first = False)
                if board[r][c] == '#':
                    board[r][c] = 'O'
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/surrounded-regions/">130. Surrounded Regions</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> matrix <code>board</code> containing <code>'X'</code> and <code>'O'</code>, <em>capture all regions that are 4-directionally&nbsp;surrounded by</em> <code>'X'</code>.</p>

        """
        """
                return 
                return
            if first:
            else:
        
<p>A region is <strong>captured</strong> by flipping all <code>'O'</code>s into <code>'X'</code>s in that surrounded region.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/19/xogrid.jpg" style="width: 550px; height: 237px;">
<pre><strong>Input:</strong> board = [["X","X","X","X"],["X","O","O","X"],["X","X","O","X"],["X","O","X","X"]]
<strong>Output:</strong> [["X","X","X","X"],["X","X","X","X"],["X","X","X","X"],["X","O","X","X"]]
<strong>Explanation:</strong> Notice that an 'O' should not be flipped if:
- It is on the border, or
- It is adjacent to an 'O' that should not be flipped.
The bottom 'O' is on the border, so it is not flipped.
The other three 'O' form a surrounded region, so they are flipped.
</pre>

<pre><strong>Input:</strong> board = [["X"]]
<strong>Output:</strong> [["X"]]
</pre>

<ul>
	<li><code>1 &lt;= m, n &lt;= 200</code></li>
	<li><code>board[i][j]</code> is <code>'X'</code> or <code>'O'</code>.</li>
</ul>
</div>

directory: 1257-smallest-common-region
    def findSmallestRegion(self, regions: List[List[str]], region1: str, region2: str) -> str:
        
        dic = {}
        for region in regions:
            for r in region[1:]:
                dic[r] = region[0]
        seen.add(region1)
        while region1 in dic:
            seen.add(dic[region1])
            region1 = dic[region1]
        while region2 not in seen:
            region2 = dic[region2]
        return region2
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/smallest-common-region/">1257. Smallest Common Region</a></h2><h3>Medium</h3><hr><div><p>You are given some lists of <code>regions</code> where the first region of each list includes all other regions in that list.</p>

<p>Naturally, if a region <code>x</code> contains another region <code>y</code> then <code>x</code> is bigger than <code>y</code>. Also, by definition, a region <code>x</code> contains itself.</p>

        dic = {}
        
<p>Given two regions: <code>region1</code> and <code>region2</code>, return <em>the smallest region that contains both of them</em>.</p>

<p>If you are given regions <code>r1</code>, <code>r2</code>, and <code>r3</code> such that <code>r1</code> includes <code>r3</code>, it is guaranteed there is no <code>r2</code> such that <code>r2</code> includes <code>r3</code>.</p>

<p>It is guaranteed the smallest region exists.</p>

</strong>regions = [["Earth","North America","South America"],
["North America","United States","Canada"],
["United States","New York","Boston"],
["Canada","Ontario","Quebec"],
["South America","Brazil"]],
region1 = "Quebec",
region2 = "New York"
<strong>Output:</strong> "North America"
</pre>

<pre><strong>Input:</strong> regions = [["Earth", "North America", "South America"],["North America", "United States", "Canada"],["United States", "New York", "Boston"],["Canada", "Ontario", "Quebec"],["South America", "Brazil"]], region1 = "Canada", region2 = "South America"
<strong>Output:</strong> "Earth"
</pre>

<ul>
	<li><code>2 &lt;= regions.length &lt;= 10<sup>4</sup></code></li>
	<li><code>2 &lt;= regions[i].length &lt;= 20</code></li>
	<li><code>1 &lt;= regions[i][j].length, region1.length, region2.length &lt;= 20</code></li>
	<li><code>region1 != region2</code></li>
	<li><code>regions[i][j]</code>, <code>region1</code>, and <code>region2</code> consist of English letters.</li>
</ul>
</div>

directory: 1272-remove-interval
    def removeInterval(self, intervals: List[List[int]], toBeRemoved: List[int]) -> List[List[int]]:
        
        lst = []
        for interval in intervals:
            if interval[0] > toBeRemoved[1] or (interval[1] < toBeRemoved[0]):
                lst.append([interval[0], interval[1]])
            else:
                if interval[0] < toBeRemoved[0]:
                    lst.append([interval[0], toBeRemoved[0]])
                if interval[1] > toBeRemoved[1]:
                    lst.append([toBeRemoved[1], interval[1]])
        return lst
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/remove-interval/">1272. Remove Interval</a></h2><h3>Medium</h3><hr><div><p>A set of real numbers can be represented as the union of several disjoint intervals, where each interval is in the form <code>[a, b)</code>. A real number <code>x</code> is in the set if one of its intervals <code>[a, b)</code> contains <code>x</code> (i.e. <code>a &lt;= x &lt; b</code>).</p>

        lst = []
            else:
        return lst
        
<p>You are given a <strong>sorted</strong> list of disjoint intervals <code>intervals</code> representing a set of real numbers as described above, where <code>intervals[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> represents the interval <code>[a<sub>i</sub>, b<sub>i</sub>)</code>. You are also given another interval <code>toBeRemoved</code>.</p>

<p>Return <em>the set of real numbers with the interval </em><code>toBeRemoved</code><em> <strong>removed</strong> from</em><em> </em><code>intervals</code><em>. In other words, return the set of real numbers such that every </em><code>x</code><em> in the set is in </em><code>intervals</code><em> but <strong>not</strong> in </em><code>toBeRemoved</code><em>. Your answer should be a <strong>sorted</strong> list of disjoint intervals as described above.</em></p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/24/removeintervalex1.png" style="width: 510px; height: 319px;">
<pre><strong>Input:</strong> intervals = [[0,2],[3,4],[5,7]], toBeRemoved = [1,6]
<strong>Output:</strong> [[0,1],[6,7]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/24/removeintervalex2.png" style="width: 410px; height: 318px;">
<pre><strong>Input:</strong> intervals = [[0,5]], toBeRemoved = [2,3]
<strong>Output:</strong> [[0,2],[3,5]]
</pre>

<pre><strong>Input:</strong> intervals = [[-5,-4],[-3,-2],[1,2],[3,5],[8,9]], toBeRemoved = [-1,4]
<strong>Output:</strong> [[-5,-4],[-3,-2],[4,5],[8,9]]
</pre>

<ul>
	<li><code>1 &lt;= intervals.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>9</sup> &lt;= a<sub>i</sub> &lt; b<sub>i</sub> &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 905-sort-array-by-parity
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sort-array-by-parity/">905. Sort Array By Parity</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code>, move all the even integers at the beginning of the array followed by all the odd integers.</p>

<p>Return <em><strong>any array</strong> that satisfies this condition</em>.</p>

<pre><strong>Input:</strong> nums = [3,1,2,4]
<strong>Output:</strong> [2,4,3,1]
<strong>Explanation:</strong> The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted.
</pre>

<strong>Output:</strong> [0]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 5000</code></li>
	<li><code>0 &lt;= nums[i] &lt;= 5000</code></li>
</ul>
</div>

directory: 138-copy-list-with-random-pointer
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""
    
        self.dictionary = dict()
    
    def copyRandomList(self, head: 'Node') -> 'Node':
        
        if not head:
        
        if head in self.dictionary:
            return self.dictionary[head]
        
        node = Node(head.val, None, None)
        self.dictionary[head] = node
        node.next = self.copyRandomList(head.next)
        node.random = self.copyRandomList(head.random)
        
        return node
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/copy-list-with-random-pointer/">138. Copy List with Random Pointer</a></h2><h3>Medium</h3><hr><div><p>A linked list of length <code>n</code> is given such that each node contains an additional random pointer, which could point to any node in the list, or <code>null</code>.</p>

"""
"""
    
<p>Construct a <a href="https://en.wikipedia.org/wiki/Object_copying#Deep_copy" target="_blank"><strong>deep copy</strong></a> of the list. The deep copy should consist of exactly <code>n</code> <strong>brand new</strong> nodes, where each new node has its value set to the value of its corresponding original node. Both the <code>next</code> and <code>random</code> pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. <strong>None of the pointers in the new list should point to nodes in the original list</strong>.</p>

<p>For example, if there are two nodes <code>X</code> and <code>Y</code> in the original list, where <code>X.random --&gt; Y</code>, then for the corresponding two nodes <code>x</code> and <code>y</code> in the copied list, <code>x.random --&gt; y</code>.</p>

<p>Return <em>the head of the copied linked list</em>.</p>

<p>The linked list is represented in the input/output as a list of <code>n</code> nodes. Each node is represented as a pair of <code>[val, random_index]</code> where:</p>

<ul>
	<li><code>random_index</code>: the index of the node (range from <code>0</code> to <code>n-1</code>) that the <code>random</code> pointer points to, or <code>null</code> if it does not point to any node.</li>
</ul>

<p>Your code will <strong>only</strong> be given the <code>head</code> of the original linked list.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2019/12/18/e1.png" style="width: 700px; height: 142px;">
<pre><strong>Input:</strong> head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
<strong>Output:</strong> [[7,null],[13,0],[11,4],[10,2],[1,0]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2019/12/18/e2.png" style="width: 700px; height: 114px;">
<pre><strong>Input:</strong> head = [[1,1],[2,1]]
<strong>Output:</strong> [[1,1],[2,1]]
</pre>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2019/12/18/e3.png" style="width: 700px; height: 122px;"></strong></p>

<pre><strong>Input:</strong> head = [[3,null],[3,0],[3,null]]
<strong>Output:</strong> [[3,null],[3,0],[3,null]]
</pre>

<ul>
	<li><code>0 &lt;= n &lt;= 1000</code></li>
	<li><code>Node.random</code> is <code>null</code> or is pointing to some node in the linked list.</li>
</ul>
</div>

directory: 1244-design-a-leaderboard
Python: class Leaderboard:

        self.leaderboard= defaultdict(int)

    def addScore(self, playerId: int, score: int) -> None:
        
        self.leaderboard[playerId] += score

    def top(self, K: int) -> int:
        
        res = 0
        heap = []
        for num in self.leaderboard.values():
            heapq.heappush(heap, num)
            if len(heap) > K:
                heapq.heappop(heap)
        while len(heap):
            res += heapq.heappop(heap)
        return res
    def reset(self, playerId: int) -> None:
        
        self.leaderboard[playerId] = 0

class Leaderboard:

        res = 0
        heap = []
        return res
        
# Your Leaderboard object will be instantiated and called as such:
# obj = Leaderboard()
# obj.addScore(playerId,score)
# param_2 = obj.top(K)
# obj.reset(playerId)

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/design-a-leaderboard/">1244. Design A Leaderboard</a></h2><h3>Medium</h3><hr><div><p>Design a Leaderboard class, which has 3 functions:</p>

<ol>
	<li><code>addScore(playerId, score)</code>: Update the leaderboard by adding <code>score</code> to the given player's score. If there is no player with such id in the leaderboard, add him to the leaderboard with the given <code>score</code>.</li>
	<li><code>top(K)</code>: Return the score sum of the top <code>K</code> players.</li>
	<li><code>reset(playerId)</code>: Reset the score of the player with the given id&nbsp;to 0 (in other words erase it from the leaderboard). It is guaranteed that the player was added to the leaderboard before calling this function.</li>
</ol>

<p>Initially, the leaderboard is empty.</p>

<pre><b>Input: </b>
["Leaderboard","addScore","addScore","addScore","addScore","addScore","top","reset","reset","addScore","top"]
[[],[1,73],[2,56],[3,39],[4,51],[5,4],[1],[1],[2],[2,51],[3]]
<b>Output: </b>
[null,null,null,null,null,null,73,null,null,null,141]

<b>Explanation: </b>
Leaderboard leaderboard = new Leaderboard ();
leaderboard.addScore(1,73);   // leaderboard = [[1,73]];
leaderboard.addScore(2,56);   // leaderboard = [[1,73],[2,56]];
leaderboard.addScore(3,39);   // leaderboard = [[1,73],[2,56],[3,39]];
leaderboard.addScore(4,51);   // leaderboard = [[1,73],[2,56],[3,39],[4,51]];
leaderboard.addScore(5,4);    // leaderboard = [[1,73],[2,56],[3,39],[4,51],[5,4]];
leaderboard.top(1);           // returns 73;
leaderboard.reset(1);         // leaderboard = [[2,56],[3,39],[4,51],[5,4]];
leaderboard.reset(2);         // leaderboard = [[3,39],[4,51],[5,4]];
leaderboard.addScore(2,51);   // leaderboard = [[2,51],[3,39],[4,51],[5,4]];
leaderboard.top(3);           // returns 141 = 51 + 51 + 39;
</pre>

<ul>
	<li><code>1 &lt;= playerId, K &lt;= 10000</code></li>
	<li>It's guaranteed that <code>K</code> is less than or equal to the current number of players.</li>
	<li><code>1 &lt;= score&nbsp;&lt;= 100</code></li>
	<li>There will be at most <code>1000</code>&nbsp;function calls.</li>
</ul>
</div>

directory: 1663-smallest-string-with-a-given-numeric-value
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/">1663. Smallest String With A Given Numeric Value</a></h2><h3>Medium</h3><hr><div><p>The <strong>numeric value</strong> of a <strong>lowercase character</strong> is defined as its position <code>(1-indexed)</code> in the alphabet, so the numeric value of <code>a</code> is <code>1</code>, the numeric value of <code>b</code> is <code>2</code>, the numeric value of <code>c</code> is <code>3</code>, and so on.</p>

<p>The <strong>numeric value</strong> of a <strong>string</strong> consisting of lowercase characters is defined as the sum of its characters' numeric values. For example, the numeric value of the string <code>"abe"</code> is equal to <code>1 + 2 + 5 = 8</code>.</p>

<p>You are given two integers <code>n</code> and <code>k</code>. Return <em>the <strong>lexicographically smallest string</strong> with <strong>length</strong> equal to <code>n</code> and <strong>numeric value</strong> equal to <code>k</code>.</em></p>

<p>Note that a string <code>x</code> is lexicographically smaller than string <code>y</code> if <code>x</code> comes before <code>y</code> in dictionary order, that is, either <code>x</code> is a prefix of <code>y</code>, or if <code>i</code> is the first position such that <code>x[i] != y[i]</code>, then <code>x[i]</code> comes before <code>y[i]</code> in alphabetic order.</p>

<pre><strong>Input:</strong> n = 3, k = 27
<strong>Output:</strong> "aay"
<strong>Explanation:</strong> The numeric value of the string is 1 + 1 + 25 = 27, and it is the smallest string with such a value and length equal to 3.
</pre>

<pre><strong>Input:</strong> n = 5, k = 73
<strong>Output:</strong> "aaszz"
</pre>

<ul>
	<li><code>n &lt;= k &lt;= 26 * n</code></li>
</ul>
</div>

directory: 856-score-of-parentheses
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/score-of-parentheses/">856. Score of Parentheses</a></h2><h3>Medium</h3><hr><div><p>Given a balanced parentheses string <code>s</code>, return <em>the <strong>score</strong> of the string</em>.</p>

<p>The <strong>score</strong> of a balanced parentheses string is based on the following rule:</p>

<ul>
	<li><code>"()"</code> has score <code>1</code>.</li>
	<li><code>AB</code> has score <code>A + B</code>, where <code>A</code> and <code>B</code> are balanced parentheses strings.</li>
	<li><code>(A)</code> has score <code>2 * A</code>, where <code>A</code> is a balanced parentheses string.</li>
</ul>

</pre>

<pre><strong>Input:</strong> s = "(())"
</pre>

<pre><strong>Input:</strong> s = "()()"
</pre>

<ul>
	<li><code>2 &lt;= s.length &lt;= 50</code></li>
	<li><code>s</code> consists of only <code>'('</code> and <code>')'</code>.</li>
	<li><code>s</code> is a balanced parentheses string.</li>
</ul>
</div>

directory: 2265-count-nodes-equal-to-average-of-subtree
    def averageOfSubtree(self, root: Optional[TreeNode]) -> int:
        
                return [0, 0]
            else:
                nLeft, sumLeft = dfs(root.left)
                nRight, sumRight = dfs(root.right)
                count = nLeft + nRight + 1
                summation = sumLeft + sumRight + root.val
                avg = summation // count
                #print(summation, avg, count, float(root.val))
                if avg == root.val:
                    self.count += 1
                return [count, summation]
        dfs(root)   
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/">2265. Count Nodes Equal to Average of Subtree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the number of nodes where the value of the node is equal to the <strong>average</strong> of the values in its <strong>subtree</strong></em>.</p>

            else:
        dfs(root)   
                
<ul>
	<li>The <strong>average</strong> of <code>n</code> elements is the <strong>sum</strong> of the <code>n</code> elements divided by <code>n</code> and <strong>rounded down</strong> to the nearest integer.</li>
	<li>A <strong>subtree</strong> of <code>root</code> is a tree consisting of <code>root</code> and all of its descendants.</li>
</ul>

<img src="https://assets.leetcode.com/uploads/2022/03/15/image-20220315203925-1.png" style="width: 300px; height: 212px;">
<pre><strong>Input:</strong> root = [4,8,5,0,1,null,6]
For the node with value 4: The average of its subtree is (4 + 8 + 5 + 0 + 1 + 6) / 6 = 24 / 6 = 4.
For the node with value 5: The average of its subtree is (5 + 6) / 2 = 11 / 2 = 5.
For the node with value 0: The average of its subtree is 0 / 1 = 0.
For the node with value 1: The average of its subtree is 1 / 1 = 1.
For the node with value 6: The average of its subtree is 6 / 1 = 6.
</pre>

<img src="https://assets.leetcode.com/uploads/2022/03/26/image-20220326133920-1.png" style="width: 80px; height: 76px;">
<strong>Explanation:</strong> For the node with value 1: The average of its subtree is 1 / 1 = 1.
</pre>

<ul>
</ul>
</div>

directory: 718-maximum-length-of-repeated-subarray
    def findLength(self, nums1: List[int], nums2: List[int]) -> int:
        
        n, m = len(nums1), len(nums2)
        dp = [[0]*(m + 1) for _ in range(n + 1)]
        for i in range(n - 1, -1, -1):
            for j in range(m - 1, -1, -1):
                if nums1[i] == nums2[j]:
                    dp[i][j] = dp[i + 1][j + 1] + 1
                    
        return max(max(row) for row in dp)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-length-of-repeated-subarray/">718. Maximum Length of Repeated Subarray</a></h2><h3>Medium</h3><hr><div><p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>the maximum length of a subarray that appears in <strong>both</strong> arrays</em>.</p>

<pre><strong>Input:</strong> nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
<strong>Explanation:</strong> The repeated subarray with maximum length is [3,2,1].
</pre>

<pre><strong>Input:</strong> nums1 = [0,0,0,0,0], nums2 = [0,0,0,0,0]
</pre>

<ul>
	<li><code>1 &lt;= nums1.length, nums2.length &lt;= 1000</code></li>
	<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 100</code></li>
</ul>
</div>

directory: 662-maximum-width-of-binary-tree
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        
        dic = {}
        max_width = 0
        def dfs(node, row, col):
            nonlocal max_width
                return
            if row not in dic:
                dic[row] = col
            max_width = max(max_width, col - dic[row] + 1)
            dfs(node.left, row + 1, 2 * col)
            dfs(node.right, row + 1, 2 * col + 1)
        dfs(root, 0, 0)
        return max_width
Notes: queue = deque([(root, 0)])
max_dist = 0
while queue:
size = len(queue)
_, level_head = queue[0]
for _ in range(size):
node, index = queue.popleft()
if node.left:
queue.append([node.left, 2*index])
if node.right:
queue.append([node.right, 2*index + 1])
max_dist = max(max_dist, index - level_head + 1)
return max_dist
Readme: <h2><a href="https://leetcode.com/problems/maximum-width-of-binary-tree/">662. Maximum Width of Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the <strong>maximum width</strong> of the given tree</em>.</p>

        dic = {}
                return
            
<p>The <strong>maximum width</strong> of a tree is the maximum <strong>width</strong> among all levels.</p>

<p>The <strong>width</strong> of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes are also counted into the length calculation.</p>

<p>It is <strong>guaranteed</strong> that the answer will in the range of <strong>32-bit</strong> signed integer.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/05/03/width1-tree.jpg" style="width: 359px; height: 302px;">
<pre><strong>Input:</strong> root = [1,3,2,5,3,null,9]
<strong>Explanation:</strong> The maximum width existing in the third level with the length 4 (5,3,null,9).
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/05/03/width2-tree.jpg" style="width: 224px; height: 302px;">
<pre><strong>Input:</strong> root = [1,3,null,5,3]
<strong>Explanation:</strong> The maximum width existing in the third level with the length 2 (5,3).
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/05/03/width3-tree.jpg" style="width: 289px; height: 299px;">
<pre><strong>Input:</strong> root = [1,3,2,5]
<strong>Explanation:</strong> The maximum width existing in the second level with the length 2 (3,2).
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 3000]</code>.</li>
</ul>
</div>

directory: 280-wiggle-sort
    def wiggleSort(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        temp = sorted(nums)
        first, last = 0, len(temp)-1
        i = 0; switch = False
        while first <= last:
            if not switch:
                nums[i] = temp[first]
                first+=1
            else:
                nums[i] = temp[last]
                last-=1
            i+=1
            switch = not switch
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/wiggle-sort/">280. Wiggle Sort</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, reorder it such that <code>nums[0] &lt;= nums[1] &gt;= nums[2] &lt;= nums[3]...</code>.</p>

<p>You may assume the input array always has a valid answer.</p>

        """
        """
                first+=1
            else:
                last-=1
            i+=1
        
<pre><strong>Input:</strong> nums = [3,5,2,1,6,4]
<strong>Output:</strong> [3,5,1,6,2,4]
<strong>Explanation:</strong> [1,6,2,5,3,4] is also accepted.
</pre>

<pre><strong>Input:</strong> nums = [6,6,5,6,3,8]
<strong>Output:</strong> [6,6,5,6,3,8]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 5 * 10<sup>4</sup></code></li>
	<li>It is guaranteed that there will be an answer for the given input <code>nums</code>.</li>
</ul>

<p><strong>Follow up:</strong> Could you solve the problem in <code>O(n)</code> time complexity?</p>
</div>

directory: 509-fibonacci-number
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/fibonacci-number/">509. Fibonacci Number</a></h2><h3>Easy</h3><hr><div><p>The <b>Fibonacci numbers</b>, commonly denoted <code>F(n)</code> form a sequence, called the <b>Fibonacci sequence</b>, such that each number is the sum of the two preceding ones, starting from <code>0</code> and <code>1</code>. That is,</p>

<pre>F(0) = 0, F(1) = 1
F(n) = F(n - 1) + F(n - 2), for n &gt; 1.
</pre>

<p>Given <code>n</code>, calculate <code>F(n)</code>.</p>

<strong>Explanation:</strong> F(2) = F(1) + F(0) = 1 + 0 = 1.
</pre>

<strong>Explanation:</strong> F(3) = F(2) + F(1) = 1 + 1 = 2.
</pre>

<strong>Explanation:</strong> F(4) = F(3) + F(2) = 2 + 1 = 3.
</pre>

<ul>
	<li><code>0 &lt;= n &lt;= 30</code></li>
</ul>
</div>

directory: 120-triangle
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/triangle/">120. Triangle</a></h2><h3>Medium</h3><hr><div><p>Given a <code>triangle</code> array, return <em>the minimum path sum from top to bottom</em>.</p>

<p>For each step, you may move to an adjacent number of the row below. More formally, if you are on index <code>i</code> on the current row, you may move to either index <code>i</code> or index <code>i + 1</code> on the next row.</p>

<pre><strong>Input:</strong> triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
<strong>Output:</strong> 11
<strong>Explanation:</strong> The triangle looks like:
   <u>2</u>
  <u>3</u> 4
 6 <u>5</u> 7
4 <u>1</u> 8 3
The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11 (underlined above).
</pre>

<pre><strong>Input:</strong> triangle = [[-10]]
<strong>Output:</strong> -10
</pre>

<ul>
	<li><code>1 &lt;= triangle.length &lt;= 200</code></li>
	<li><code>triangle[0].length == 1</code></li>
	<li><code>triangle[i].length == triangle[i - 1].length + 1</code></li>
	<li><code>-10<sup>4</sup> &lt;= triangle[i][j] &lt;= 10<sup>4</sup></code></li>
</ul>

<strong>Follow up:</strong> Could you&nbsp;do this using only <code>O(n)</code> extra space, where <code>n</code> is the total number of rows in the triangle?</div>

directory: 431-encode-n-ary-tree-to-binary-tree
"""

"""
class TreeNode:
        self.left = None
        self.right = None
"""

    # Encodes an n-ary tree to a binary tree.
        self.cheat = None
    def encode(self, root: 'Optional[Node]') -> Optional[TreeNode]:
        self.cheat = root
	# Decodes your binary tree to an n-ary tree.
    def decode(self, data: Optional[TreeNode]) -> 'Optional[Node]':
        return self.cheat

"""
"""

"""
"""

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(root))

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree/">431. Encode N-ary Tree to Binary Tree</a></h2><h3>Hard</h3><hr><div><p>Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no more than N children. Similarly, a binary tree is a rooted tree in which each node has no more than 2 children. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this binary tree can be decoded to the original N-nary tree structure.</p>

<p><em>Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See following example).</em></p>

<p>For example, you may encode the following <code>3-ary</code> tree to a binary tree in this way:</p>

<p><img src="https://assets.leetcode.com/uploads/2018/10/12/narytreebinarytreeexample.png" style="width: 100%; max-width: 640px"></p>

</pre>

<p>Note that the above is just an example which <em>might or might not</em> work. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.</p>

</pre>

<ul>
	<li>Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.</li>
</ul>
</div>

directory: 566-reshape-the-matrix
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        
        x, y = len(mat), len(mat[0])
        if(x == 0 or r*c != x*y):
            return mat
        ans = [[0 for _ in range(c)] for _ in range(r)]
        q = deque()
        for i in range(x):
            for j in range(y):
                q.append(mat[i][j])
        
        for i in range(r):
            for j in range(c):
                ans[i][j] = q.popleft()
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reshape-the-matrix/">566. Reshape the Matrix</a></h2><h3>Easy</h3><hr><div><p>In MATLAB, there is a handy function called <code>reshape</code> which can reshape an <code>m x n</code> matrix into a new one with a different size <code>r x c</code> keeping its original data.</p>

            return mat
        q = deque()
        
        return ans

<p>You are given an <code>m x n</code> matrix <code>mat</code> and two integers <code>r</code> and <code>c</code> representing the number of rows and the number of columns of the wanted reshaped matrix.</p>

<p>The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.</p>

<p>If the <code>reshape</code> operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/reshape1-grid.jpg" style="width: 613px; height: 173px;">
<pre><strong>Input:</strong> mat = [[1,2],[3,4]], r = 1, c = 4
<strong>Output:</strong> [[1,2,3,4]]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/04/24/reshape2-grid.jpg" style="width: 453px; height: 173px;">
<pre><strong>Input:</strong> mat = [[1,2],[3,4]], r = 2, c = 4
<strong>Output:</strong> [[1,2],[3,4]]
</pre>

<ul>
	<li><code>-1000 &lt;= mat[i][j] &lt;= 1000</code></li>
	<li><code>1 &lt;= r, c &lt;= 300</code></li>
</ul>
</div>

directory: 0611-valid-triangle-number
    def triangleNumber(self, nums: List[int]) -> int:
        
        ans, n = 0, len(nums)
        for i in range(n-2):
            k = i + 2
            for j in range(i+1, n-1):
                if nums[i] == 0:
                    continue
                while k < n and nums[i] + nums[j] > nums[k]:
                    k += 1
                ans += k - j - 1
        return ans
Notes: 

            k = i + 2
                    continue
                    k += 1
        return ans
    
2,2,3
</pre>

</pre>

<ul>
</ul>
</div>

directory: 3-longest-substring-without-repeating-characters
    def lengthOfLongestSubstring(self, s: str) -> int:
        max_len = 0 
            if c in dic:
                start = max(start, dic[c])
            dic[c] = end + 1
        
        """
        a : 0
        b : 1
        c : 2
        """
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">3. Longest Substring Without Repeating Characters</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, find the length of the <strong>longest substring</strong> without repeating characters.</p>

        max_len = 0 
            if c in dic:
        
        """
        a : 0
        b : 1
        c : 2
        """

<pre><strong>Input:</strong> s = "abcabcbb"
<strong>Explanation:</strong> The answer is "abc", with the length of 3.
</pre>

<pre><strong>Input:</strong> s = "bbbbb"
<strong>Explanation:</strong> The answer is "b", with the length of 1.
</pre>

<pre><strong>Input:</strong> s = "pwwkew"
<strong>Explanation:</strong> The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
</pre>

<ul>
	<li><code>0 &lt;= s.length &lt;= 5 * 10<sup>4</sup></code></li>
	<li><code>s</code> consists of English letters, digits, symbols and spaces.</li>
</ul>
</div>

directory: 1696-jump-game-vi
    def maxResult(self, nums: List[int], k: int) -> int:
        
        N = len(nums)
        h = [(-nums[0], 0)]
        for i in range(1, N):
            while h[0][1] < i - k:
                heappop(h)
            max_so_far = h[0][0]
            heappush(h, (max_so_far - nums[i], i))
            if i == N-1:
                return -(max_so_far - nums[i])
        return nums[0]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/jump-game-vi/">1696. Jump Game VI</a></h2><h3>Medium</h3><hr><div><p>You are given a <strong>0-indexed</strong> integer array <code>nums</code> and an integer <code>k</code>.</p>

<p>You are initially standing at index <code>0</code>. In one move, you can jump at most <code>k</code> steps forward without going outside the boundaries of the array. That is, you can jump from index <code>i</code> to any index in the range <code>[i + 1, min(n - 1, i + k)]</code> <strong>inclusive</strong>.</p>

            if i == N-1:
        
<p>You want to reach the last index of the array (index <code>n - 1</code>). Your <strong>score</strong> is the <strong>sum</strong> of all <code>nums[j]</code> for each index <code>j</code> you visited in the array.</p>

<p>Return <em>the <strong>maximum score</strong> you can get</em>.</p>

<pre><strong>Input:</strong> nums = [<u>1</u>,<u>-1</u>,-2,<u>4</u>,-7,<u>3</u>], k = 2
<strong>Explanation:</strong> You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.
</pre>

<pre><strong>Input:</strong> nums = [<u>10</u>,-5,-2,<u>4</u>,0,<u>3</u>], k = 3
<strong>Output:</strong> 17
<strong>Explanation:</strong> You can choose your jumps forming the subsequence [10,4,3] (underlined above). The sum is 17.
</pre>

<pre><strong>Input:</strong> nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
</pre>

<ul>
	<li><code>1 &lt;= nums.length, k &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 2164-sort-even-and-odd-indices-independently
    def sortEvenOdd(self, nums: List[int]) -> List[int]:
        
        nums1, nums2 = [], []
            if i % 2 == 0:
                nums1.append(nums[i])
            else:
                nums2.append(nums[i])
        nums2.sort(reverse = True)
        len1, len2 = len(nums1), len(nums2)
        ans = []
        while left < len1 or right < len2:
            if left < len1:
                ans.append(nums1[left])
                left += 1
            if right < len2:
                ans.append(nums2[right])
                right += 1
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sort-even-and-odd-indices-independently/">2164. Sort Even and Odd Indices Independently</a></h2><h3>Easy</h3><hr><div><p>You are given a <strong>0-indexed</strong> integer array <code>nums</code>. Rearrange the values of <code>nums</code> according to the following rules:</p>

            if i % 2 == 0:
            else:
        ans = []
                left += 1
                right += 1
        return ans

<ol>
	<li>Sort the values at <strong>odd indices</strong> of <code>nums</code> in <strong>non-increasing</strong> order.

	<ul>
		<li>For example, if <code>nums = [4,<strong><u>1</u></strong>,2,<u><strong>3</strong></u>]</code> before this step, it becomes <code>[4,<u><strong>3</strong></u>,2,<strong><u>1</u></strong>]</code> after. The values at odd indices <code>1</code> and <code>3</code> are sorted in non-increasing order.</li>
	</ul>
	</li>
	<li>Sort the values at <strong>even indices</strong> of <code>nums</code> in <strong>non-decreasing</strong> order.
	<ul>
		<li>For example, if <code>nums = [<u><strong>4</strong></u>,1,<u><strong>2</strong></u>,3]</code> before this step, it becomes <code>[<u><strong>2</strong></u>,1,<u><strong>4</strong></u>,3]</code> after. The values at even indices <code>0</code> and <code>2</code> are sorted in non-decreasing order.</li>
	</ul>
	</li>
</ol>

<p>Return <em>the array formed after rearranging the values of</em> <code>nums</code>.</p>

<pre><strong>Input:</strong> nums = [4,1,2,3]
<strong>Output:</strong> [2,3,4,1]
First, we sort the values present at odd indices (1 and 3) in non-increasing order.
So, nums changes from [4,<strong><u>1</u></strong>,2,<strong><u>3</u></strong>] to [4,<u><strong>3</strong></u>,2,<strong><u>1</u></strong>].
Next, we sort the values present at even indices (0 and 2) in non-decreasing order.
So, nums changes from [<u><strong>4</strong></u>,1,<strong><u>2</u></strong>,3] to [<u><strong>2</strong></u>,3,<u><strong>4</strong></u>,1].
Thus, the array formed after rearranging the values is [2,3,4,1].
</pre>

<pre><strong>Input:</strong> nums = [2,1]
Since there is exactly one odd index and one even index, no rearrangement of values takes place.
The resultant array formed is [2,1], which is the same as the initial array. 
</pre>

<ul>
</ul>
</div>

directory: 341-flatten-nested-list-iterator
# """
#    def isInteger(self) -> bool:
#        """
#        """
#
#    def getInteger(self) -> int:
#        """
#        """
#
#    def getList(self) -> [NestedInteger]:
#        """
#        """
class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        self.answer = []
        self.dfs(nestedList)
        self.index = -1
    def dfs(self, nestedList):
        for x in nestedList:
            if x.isInteger():
                self.answer.append(x.getInteger())
            elif x.getInteger() is not None:
            else:
                self.dfs(x.getList())
        self.index += 1
        return self.answer[self.index]
         return self.index + 1 < len(self.answer)

# """
# """
#        """
#        """
#
#        """
#        """
#
#        """
#        """
            else:

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/flatten-nested-list-iterator/">341. Flatten Nested List Iterator</a></h2><h3>Medium</h3><hr><div><p>You are given a nested list of integers <code>nestedList</code>. Each element is either an integer or a list whose elements may also be integers or other lists. Implement an iterator to flatten it.</p>

<p>Implement the <code>NestedIterator</code> class:</p>

<ul>
	<li><code>NestedIterator(List&lt;NestedInteger&gt; nestedList)</code> Initializes the iterator with the nested list <code>nestedList</code>.</li>
	<li><code>int next()</code> Returns the next integer in the nested list.</li>
	<li><code>boolean hasNext()</code> Returns <code>true</code> if there are still some integers in the nested list and <code>false</code> otherwise.</li>
</ul>

<p>Your code will be tested with the following pseudocode:</p>

<pre>initialize iterator with nestedList
res = []
while iterator.hasNext()
    append iterator.next() to the end of res
return res
</pre>

<p>If <code>res</code> matches the expected flattened list, then your code will be judged as correct.</p>

<strong>Output:</strong> [1,1,2,1,1]
<strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].
</pre>

<strong>Output:</strong> [1,4,6]
<strong>Explanation:</strong> By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,4,6].
</pre>

<ul>
	<li><code>1 &lt;= nestedList.length &lt;= 500</code></li>
	<li>The values of the integers in the nested list is in the range <code>[-10<sup>6</sup>, 10<sup>6</sup>]</code>.</li>
</ul>
</div>

directory: 1337-the-k-weakest-rows-in-a-matrix
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix/">1337. The K Weakest Rows in a Matrix</a></h2><h3>Easy</h3><hr><div><p>You are given an <code>m x n</code> binary matrix <code>mat</code> of <code>1</code>'s (representing soldiers) and <code>0</code>'s (representing civilians). The soldiers are positioned <strong>in front</strong> of the civilians. That is, all the <code>1</code>'s will appear to the <strong>left</strong> of all the <code>0</code>'s in each row.</p>

<p>A row <code>i</code> is <strong>weaker</strong> than a row <code>j</code> if one of the following is true:</p>

<ul>
	<li>The number of soldiers in row <code>i</code> is less than the number of soldiers in row <code>j</code>.</li>
	<li>Both rows have the same number of soldiers and <code>i &lt; j</code>.</li>
</ul>

<p>Return <em>the indices of the </em><code>k</code><em> <strong>weakest</strong> rows in the matrix ordered from weakest to strongest</em>.</p>

<pre><strong>Input:</strong> mat = 
[[1,1,0,0,0],
 [1,1,1,1,0],
 [1,0,0,0,0],
 [1,1,0,0,0],
 [1,1,1,1,1]], 
k = 3
<strong>Output:</strong> [2,0,3]
The number of soldiers in each row is: 
- Row 0: 2 
- Row 1: 4 
- Row 2: 1 
- Row 3: 2 
- Row 4: 5 
The rows ordered from weakest to strongest are [2,0,3,1,4].
</pre>

[[1,0,0,0],
 [1,1,1,1],
 [1,0,0,0],
 [1,0,0,0]], 
k = 2
<strong>Output:</strong> [0,2]
- Row 0: 1 
- Row 1: 4 
- Row 2: 1 
- Row 3: 1 
The rows ordered from weakest to strongest are [0,2,3,1].
</pre>

<ul>
	<li><code>2 &lt;= n, m &lt;= 100</code></li>
	<li><code>1 &lt;= k &lt;= m</code></li>
	<li><code>matrix[i][j]</code> is either 0 or 1.</li>
</ul>
</div>

directory: 49-group-anagrams
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        
        for s in strs:
            count = [0] * 26
            for c in s:
                count[ord(c) - ord('a')] += 1
            dic[tuple(count)].append(s)
        return dic.values()
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
dic = defaultdict(list)
for s in strs:
key = "".join(sorted(s))
dic[key].append(s)
return [val for _, val in dic.items()]
Readme: <h2><a href="https://leetcode.com/problems/group-anagrams/">49. Group Anagrams</a></h2><h3>Medium</h3><hr><div><p>Given an array of strings <code>strs</code>, group <strong>the anagrams</strong> together. You can return the answer in <strong>any order</strong>.</p>

            for c in s:
        
<pre><strong>Input:</strong> strs = ["eat","tea","tan","ate","nat","bat"]
<strong>Output:</strong> [["bat"],["nat","tan"],["ate","eat","tea"]]
<pre><strong>Input:</strong> strs = [""]
<strong>Output:</strong> [[""]]
<pre><strong>Input:</strong> strs = ["a"]
</pre>

<ul>
	<li><code>1 &lt;= strs.length &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= strs[i].length &lt;= 100</code></li>
	<li><code>strs[i]</code> consists of lowercase English letters.</li>
</ul>
</div>

directory: 127-word-ladder
    def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int:
        
        if endWord not in wordList:
            return 0
        nei = defaultdict(list)
        wordList.append(beginWord)
        
        for word in wordList:
            for j in range(len(word)):
                # repalce j char with wildcird
                pattern = word[:j] + "*" + word[j+1:]
                nei[pattern].append(word)
        
        visit = set([beginWord])
        q = deque([beginWord])
        res = 1
        
        while q:
            for i in range(len(q)):
                word = q.popleft()
                if word == endWord:
                    return res
                for j in range(len(word)):
                    pattern = word[:j] + "*" + word[j+1:]
                    for neiWord in nei[pattern]:
                        if neiWord not in visit:
                            visit.add(neiWord)
                            q.append(neiWord)
                            
            res += 1
        return 0
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/word-ladder/">127. Word Ladder</a></h2><h3>Hard</h3><hr><div><p>A <strong>transformation sequence</strong> from word <code>beginWord</code> to word <code>endWord</code> using a dictionary <code>wordList</code> is a sequence of words <code>beginWord -&gt; s<sub>1</sub> -&gt; s<sub>2</sub> -&gt; ... -&gt; s<sub>k</sub></code> such that:</p>

            return 0
        
        res = 1
        
        while q:
                    return res
                            
            res += 1
        return 0
        
<ul>
	<li>Every adjacent pair of words differs by a single letter.</li>
	<li>Every <code>s<sub>i</sub></code> for <code>1 &lt;= i &lt;= k</code> is in <code>wordList</code>. Note that <code>beginWord</code> does not need to be in <code>wordList</code>.</li>
	<li><code>s<sub>k</sub> == endWord</code></li>
</ul>

<p>Given two words, <code>beginWord</code> and <code>endWord</code>, and a dictionary <code>wordList</code>, return <em>the <strong>number of words</strong> in the <strong>shortest transformation sequence</strong> from</em> <code>beginWord</code> <em>to</em> <code>endWord</code><em>, or </em><code>0</code><em> if no such sequence exists.</em></p>

<pre><strong>Input:</strong> beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log","cog"]
<strong>Explanation:</strong> One shortest transformation sequence is "hit" -&gt; "hot" -&gt; "dot" -&gt; "dog" -&gt; cog", which is 5 words long.
</pre>

<pre><strong>Input:</strong> beginWord = "hit", endWord = "cog", wordList = ["hot","dot","dog","lot","log"]
<strong>Explanation:</strong> The endWord "cog" is not in wordList, therefore there is no valid transformation sequence.
</pre>

<ul>
	<li><code>1 &lt;= beginWord.length &lt;= 10</code></li>
	<li><code>endWord.length == beginWord.length</code></li>
	<li><code>1 &lt;= wordList.length &lt;= 5000</code></li>
	<li><code>wordList[i].length == beginWord.length</code></li>
	<li><code>beginWord</code>, <code>endWord</code>, and <code>wordList[i]</code> consist of lowercase English letters.</li>
	<li><code>beginWord != endWord</code></li>
	<li>All the words in <code>wordList</code> are <strong>unique</strong>.</li>
</ul>
</div>

directory: 247-strobogrammatic-number-ii
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/strobogrammatic-number-ii/">247. Strobogrammatic Number II</a></h2><h3>Medium</h3><hr><div><p>Given an integer <code>n</code>, return all the <strong>strobogrammatic numbers</strong> that are of length <code>n</code>. You may return the answer in <strong>any order</strong>.</p>

<p>A <strong>strobogrammatic number</strong> is a number that looks the same when rotated <code>180</code> degrees (looked at upside down).</p>

<strong>Output:</strong> ["11","69","88","96"]
<strong>Output:</strong> ["0","1","8"]
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 14</code></li>
</ul>
</div>

directory: 287-find-the-duplicate-number
    def findDuplicate(self, nums: List[int]) -> int:
        
        low, high = 1, len(nums) - 1
        
            mid = (high + low ) >> 1
            count = sum(num <= mid for num in nums)
            if count > mid:
                duplicate = mid
            else:
                low = mid + 1
        return duplicate
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-the-duplicate-number/">287. Find the Duplicate Number</a></h2><h3>Medium</h3><hr><div><p>Given an array of integers <code>nums</code> containing&nbsp;<code>n + 1</code> integers where each integer is in the range <code>[1, n]</code> inclusive.</p>

<p>There is only <strong>one repeated number</strong> in <code>nums</code>, return <em>this&nbsp;repeated&nbsp;number</em>.</p>

            else:
                low = mid + 1
        
<p>You must solve the problem <strong>without</strong> modifying the array <code>nums</code>&nbsp;and uses only constant extra space.</p>

<pre><strong>Input:</strong> nums = [1,3,4,2,2]
</pre>

<pre><strong>Input:</strong> nums = [3,1,3,4,2]
</pre>

<ul>
	<li><code>nums.length == n + 1</code></li>
	<li><code>1 &lt;= nums[i] &lt;= n</code></li>
	<li>All the integers in <code>nums</code> appear only <strong>once</strong> except for <strong>precisely one integer</strong> which appears <strong>two or more</strong> times.</li>
</ul>

<p><b>Follow up:</b></p>

<ul>
	<li>How can we prove that at least one duplicate number must exist in <code>nums</code>?</li>
	<li>Can you solve the problem in linear runtime complexity?</li>
</ul>
</div>

directory: 31-next-permutation
    def nextPermutation(self, nums: List[int]) -> None:
        """
        """
        pivot = 0
        for i in range(N-1, 0, -1):
            if nums[i-1] < nums[i]:
                pivot = i
                break
        if pivot == 0:
            nums.sort()
            return
        swap = N-1
        while nums[pivot-1] >= nums[swap]:
            swap-=1
        nums[swap], nums[pivot-1] = nums[pivot-1], nums[swap]
        nums[pivot:] = sorted(nums[pivot:])
        return
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/next-permutation/">31. Next Permutation</a></h2><h3>Medium</h3><hr><div><p>A <strong>permutation</strong> of an array of integers is an arrangement of its members into a sequence or linear order.</p>

        """
        """
        pivot = 0
                pivot = i
                break
            return
        swap = N-1
            swap-=1
        return

<ul>
	<li>For example, for <code>arr = [1,2,3]</code>, the following are considered permutations of <code>arr</code>: <code>[1,2,3]</code>, <code>[1,3,2]</code>, <code>[3,1,2]</code>, <code>[2,3,1]</code>.</li>
</ul>

<p>The <strong>next permutation</strong> of an array of integers is the next lexicographically greater permutation of its integer. More formally, if all the permutations of the array are sorted in one container according to their lexicographical order, then the <strong>next permutation</strong> of that array is the permutation that follows it in the sorted container. If such arrangement is not possible, the array must be rearranged as the lowest possible order (i.e., sorted in ascending order).</p>

<ul>
	<li>For example, the next permutation of <code>arr = [1,2,3]</code> is <code>[1,3,2]</code>.</li>
	<li>Similarly, the next permutation of <code>arr = [2,3,1]</code> is <code>[3,1,2]</code>.</li>
	<li>While the next permutation of <code>arr = [3,2,1]</code> is <code>[1,2,3]</code> because <code>[3,2,1]</code> does not have a lexicographical larger rearrangement.</li>
</ul>

<p>Given an array of integers <code>nums</code>, <em>find the next permutation of</em> <code>nums</code>.</p>

<p>The replacement must be <strong><a href="http://en.wikipedia.org/wiki/In-place_algorithm" target="_blank">in place</a></strong> and use only constant extra memory.</p>

</pre>

<pre><strong>Input:</strong> nums = [3,2,1]
</pre>

<pre><strong>Input:</strong> nums = [1,1,5]
<strong>Output:</strong> [1,5,1]
</pre>

<ul>
	<li><code>0 &lt;= nums[i] &lt;= 100</code></li>
</ul>
</div>

directory: 1155-number-of-dice-rolls-with-target-sum
    def numRollsToTarget(self, n: int, k: int, target: int) -> int:
        MOD = 10**9+7
        @cache
        def dfs(nleft, sumleft):
            if nleft == 0 and sumleft == 0: return 1
            if nleft < 0 or sumleft < 0: return 0
            
            res = 0
            for i in range(1, k+1):
                res += dfs(nleft-1, sumleft - i)
            return res % MOD
        
        return dfs(n, target)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-dice-rolls-with-target-sum/">1155. Number of Dice Rolls With Target Sum</a></h2><h3>Medium</h3><hr><div><p>You have <code>n</code> dice and each die has <code>k</code> faces numbered from <code>1</code> to <code>k</code>.</p>

        @cache
            
            res = 0
        
<p>Given three integers <code>n</code>, <code>k</code>, and <code>target</code>, return <em>the number of possible ways (out of the </em><code>k<sup>n</sup></code><em> total ways) </em><em>to roll the dice so the sum of the face-up numbers equals </em><code>target</code>. Since the answer may be too large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<pre><strong>Input:</strong> n = 1, k = 6, target = 3
<strong>Explanation:</strong> You throw one die with 6 faces.
There is only one way to get a sum of 3.
</pre>

<pre><strong>Input:</strong> n = 2, k = 6, target = 7
<strong>Explanation:</strong> You throw two dice, each with 6 faces.
There are 6 ways to get a sum of 7: 1+6, 2+5, 3+4, 4+3, 5+2, 6+1.
</pre>

<pre><strong>Input:</strong> n = 30, k = 30, target = 500
<strong>Output:</strong> 222616187
<strong>Explanation:</strong> The answer must be returned modulo 10<sup>9</sup> + 7.
</pre>

<ul>
	<li><code>1 &lt;= n, k &lt;= 30</code></li>
</ul>
</div>

directory: 1926-nearest-exit-from-entrance-in-maze
    def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int:
        
        rows, cols = len(maze), len(maze[0])
        def destination(r,c):
            if (r == 0 or c == 0 or r == rows - 1 or c == cols - 1) and [r,c] != entrance:
        q = deque([(entrance[0], entrance[1], 0)])
        maze[entrance[0]][entrance[1]] = '+'
        steps = 0
        distances = [(1,0), (0,1),(-1,0),(0,-1)]
        while q:
            r, c, steps = q.popleft()
            if(destination(r, c)):
                return steps
            for x, y in distances:
                if r + x < 0 or r + x >= rows or c + y < 0 or c + y >= cols or maze[r+x][c+y] == '+':
                    continue
                maze[r+x][c+y] = '+'
                q.append((r+x, c+y, steps + 1))
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/nearest-exit-from-entrance-in-maze/">1926. Nearest Exit from Entrance in Maze</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> matrix <code>maze</code> (<strong>0-indexed</strong>) with empty cells (represented as <code>'.'</code>) and walls (represented as <code>'+'</code>). You are also given the <code>entrance</code> of the maze, where <code>entrance = [entrance<sub>row</sub>, entrance<sub>col</sub>]</code> denotes the row and column of the cell you are initially standing at.</p>

        steps = 0
        while q:
                    continue
        return -1
    
<p>In one step, you can move one cell <strong>up</strong>, <strong>down</strong>, <strong>left</strong>, or <strong>right</strong>. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the <strong>nearest exit</strong> from the <code>entrance</code>. An <strong>exit</strong> is defined as an <strong>empty cell</strong> that is at the <strong>border</strong> of the <code>maze</code>. The <code>entrance</code> <strong>does not count</strong> as an exit.</p>

<p>Return <em>the <strong>number of steps</strong> in the shortest path from the </em><code>entrance</code><em> to the nearest exit, or </em><code>-1</code><em> if no such path exists</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/06/04/nearest1-grid.jpg" style="width: 333px; height: 253px;">
<pre><strong>Input:</strong> maze = [["+","+",".","+"],[".",".",".","+"],["+","+","+","."]], entrance = [1,2]
<strong>Explanation:</strong> There are 3 exits in this maze at [1,0], [0,2], and [2,3].
Initially, you are at the entrance cell [1,2].
- You can reach [1,0] by moving 2 steps left.
- You can reach [0,2] by moving 1 step up.
It is impossible to reach [2,3] from the entrance.
Thus, the nearest exit is [0,2], which is 1 step away.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/06/04/nearesr2-grid.jpg" style="width: 253px; height: 253px;">
<pre><strong>Input:</strong> maze = [["+","+","+"],[".",".","."],["+","+","+"]], entrance = [1,0]
<strong>Explanation:</strong> There is 1 exit in this maze at [1,2].
[1,0] does not count as an exit since it is the entrance cell.
Initially, you are at the entrance cell [1,0].
- You can reach [1,2] by moving 2 steps right.
Thus, the nearest exit is [1,2], which is 2 steps away.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/06/04/nearest3-grid.jpg" style="width: 173px; height: 93px;">
<pre><strong>Input:</strong> maze = [[".","+"]], entrance = [0,0]
<strong>Explanation:</strong> There are no exits in this maze.
</pre>

<ul>
	<li><code>maze.length == m</code></li>
	<li><code>maze[i].length == n</code></li>
	<li><code>maze[i][j]</code> is either <code>'.'</code> or <code>'+'</code>.</li>
	<li><code>entrance.length == 2</code></li>
	<li><code>0 &lt;= entrance<sub>row</sub> &lt; m</code></li>
	<li><code>0 &lt;= entrance<sub>col</sub> &lt; n</code></li>
	<li><code>entrance</code> will always be an empty cell.</li>
</ul>
</div>

directory: 890-find-and-replace-pattern
    def findAndReplacePattern(self, words: List[str], pattern: str) -> List[str]:
        
        def find(word):
            i = 0
            check, dic = "", {}
            for w in word:
                if w in dic:
                    check += "," + dic[w]
                else:
                    dic[w] = str(i)
                    check += "," + str(i)
                    i += 1
            return check
        
        c1 = find(pattern)
        ans = []
            c2 = find(word)
            if c1 == c2:
                ans.append(word)
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-and-replace-pattern/">890. Find and Replace Pattern</a></h2><h3>Medium</h3><hr><div><p>Given a list of strings <code>words</code> and a string <code>pattern</code>, return <em>a list of</em> <code>words[i]</code> <em>that match</em> <code>pattern</code>. You may return the answer in <strong>any order</strong>.</p>

            i = 0
                if w in dic:
                else:
                    i += 1
        
        ans = []
            if c1 == c2:
        return ans
        
<p>A word matches the pattern if there exists a permutation of letters <code>p</code> so that after replacing every letter <code>x</code> in the pattern with <code>p(x)</code>, we get the desired word.</p>

<p>Recall that a permutation of letters is a bijection from letters to letters: every letter maps to another letter, and no two letters map to the same letter.</p>

<pre><strong>Input:</strong> words = ["abc","deq","mee","aqq","dkd","ccc"], pattern = "abb"
<strong>Output:</strong> ["mee","aqq"]
<strong>Explanation:</strong> "mee" matches the pattern because there is a permutation {a -&gt; m, b -&gt; e, ...}. 
"ccc" does not match the pattern because {a -&gt; c, b -&gt; c, ...} is not a permutation, since a and b map to the same letter.
</pre>

<pre><strong>Input:</strong> words = ["a","b","c"], pattern = "a"
</pre>

<ul>
	<li><code>1 &lt;= pattern.length &lt;= 20</code></li>
	<li><code>1 &lt;= words.length &lt;= 50</code></li>
	<li><code>words[i].length == pattern.length</code></li>
	<li><code>pattern</code> and <code>words[i]</code> are lowercase English letters.</li>
</ul>
</div>

directory: 71-simplify-path
    def simplifyPath(self, path: str) -> str:
        
        path = path.split('/')
        stack = []
        for token in path:
            if token == '.' or token == '':
                continue
            if token == '..' and stack:
                continue
            if token == '..' and not stack:
                continue
            else:
                stack.append(token)
        
        return '/' + '/'.join(stack)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/simplify-path/">71. Simplify Path</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>path</code>, which is an <strong>absolute path</strong> (starting with a slash <code>'/'</code>) to a file or directory in a Unix-style file system, convert it to the simplified <strong>canonical path</strong>.</p>

        stack = []
                continue
                continue
                continue
            else:
        
<p>In a Unix-style file system, a period <code>'.'</code> refers to the current directory, a double period <code>'..'</code> refers to the directory up a level, and any multiple consecutive slashes (i.e. <code>'//'</code>) are treated as a single slash <code>'/'</code>. For this problem, any other format of periods such as <code>'...'</code> are treated as file/directory names.</p>

<p>The <strong>canonical path</strong> should have the following format:</p>

<ul>
	<li>The path starts with a single slash <code>'/'</code>.</li>
	<li>Any two directories are separated by a single slash <code>'/'</code>.</li>
	<li>The path does not end with a trailing <code>'/'</code>.</li>
	<li>The path only contains the directories on the path from the root directory to the target file or directory (i.e., no period <code>'.'</code> or double period <code>'..'</code>)</li>
</ul>

<p>Return <em>the simplified <strong>canonical path</strong></em>.</p>

<pre><strong>Input:</strong> path = "/home/"
<strong>Output:</strong> "/home"
<strong>Explanation:</strong> Note that there is no trailing slash after the last directory name.
</pre>

<pre><strong>Input:</strong> path = "/../"
<strong>Output:</strong> "/"
<strong>Explanation:</strong> Going one level up from the root directory is a no-op, as the root level is the highest level you can go.
</pre>

<pre><strong>Input:</strong> path = "/home//foo/"
<strong>Output:</strong> "/home/foo"
<strong>Explanation:</strong> In the canonical path, multiple consecutive slashes are replaced by a single one.
</pre>

<ul>
	<li><code>1 &lt;= path.length &lt;= 3000</code></li>
	<li><code>path</code> consists of English letters, digits, period <code>'.'</code>, slash <code>'/'</code> or <code>'_'</code>.</li>
	<li><code>path</code> is a valid absolute Unix path.</li>
</ul>
</div>

directory: 98-validate-binary-search-tree
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        return self.depthFirstSearch(root, float('-inf'), float('inf'))
    def depthFirstSearch(self, root, left, right):
        if root.val <=left or root.val >= right:
        return self.depthFirstSearch(root.left,left,root.val) and self.depthFirstSearch(root.right,root.val, right)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/validate-binary-search-tree/">98. Validate Binary Search Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, <em>determine if it is a valid binary search tree (BST)</em>.</p>

<p>A <strong>valid BST</strong> is defined as follows:</p>

<ul>
</ul>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/01/tree1.jpg" style="width: 302px; height: 182px;">
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/12/01/tree2.jpg" style="width: 422px; height: 292px;">
<pre><strong>Input:</strong> root = [5,1,4,null,null,3,6]
<strong>Explanation:</strong> The root node's value is 5 but its right child's value is 4.
</pre>

<ul>
	<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 325-maximum-size-subarray-sum-equals-k
    def maxSubArrayLen(self, nums: List[int], k: int) -> int:
        # 1, 0, 5, 3, 3
        ans = 0
        for i , num in enumerate(nums):
            if (prefixSum - k) in dic:
                ans = max(ans, i - dic[prefixSum - k])
            dic[prefixSum] = dic.get(prefixSum, i)
        return ans
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/">325. Maximum Size Subarray Sum Equals k</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <em>the maximum length of a subarray that sums to</em> <code>k</code>. If there is not one, return <code>0</code> instead.</p>

        ans = 0
        return ans

<pre><strong>Input:</strong> nums = [1,-1,5,-2,3], k = 3
<strong>Explanation:</strong> The subarray [1, -1, 5, -2] sums to 3 and is the longest.
</pre>

<pre><strong>Input:</strong> nums = [-2,-1,2,1], k = 1
<strong>Explanation:</strong> The subarray [-1, 2] sums to 1 and is the longest.
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2 * 10<sup>5</sup></code></li>
	<li><code>-10<sup>9</sup>&nbsp;&lt;= k &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 0589-n-ary-tree-preorder-traversal
"""

    def preorder(self, root: 'Node') -> List[int]:
        
        ans = []
            if root:
                for c in root.children:
                    dfs(c)
        dfs(root)
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/n-ary-tree-preorder-traversal/">589. N-ary Tree Preorder Traversal</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of an n-ary tree, return <em>the preorder traversal of its nodes' values</em>.</p>

<p>Nary-Tree input serialization is represented in their level order traversal. Each group of children is separated by the null value (See examples)</p>

"""
"""

        ans = []
            if root:
                    dfs(c)
        dfs(root)
        return ans
        
<strong>Output:</strong> [1,3,5,6,2,4]
</pre>

<strong>Output:</strong> [1,2,3,6,7,11,14,4,8,12,5,9,13,10]
</pre>

<ul>
	<li>The height of the n-ary tree is less than or equal to <code>1000</code>.</li>
</ul>

</div>

directory: 852-peak-index-in-a-mountain-array
    def peakIndexInMountainArray(self, arr: List[int]) -> int:
        
        left, right = 0, len(arr)
            if mid == left and arr[mid] < arr[mid+1]:
                return mid + 1
            if mid == right and arr[mid] > arr[mid - 1]:
                return mid
            if arr[mid-1] < arr[mid] > arr[mid + 1]:
                return mid
            if arr[mid-1] > arr[mid]:
            else:
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/peak-index-in-a-mountain-array/">852. Peak Index in a Mountain Array</a></h2><h3>Medium</h3><hr><div><p>An array <code>arr</code> a <strong>mountain</strong> if the following properties hold:</p>

                return mid
                return mid
            else:
        return -1
        
<ul>
	<li><code>arr.length &gt;= 3</code></li>
	<li>There exists some <code>i</code> with <code>0 &lt; i &lt; arr.length - 1</code> such that:
	<ul>
		<li><code>arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] </code></li>
		<li><code>arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1]</code></li>
	</ul>
	</li>
</ul>

<p>Given a mountain array <code>arr</code>, return the index <code>i</code> such that <code>arr[0] &lt; arr[1] &lt; ... &lt; arr[i - 1] &lt; arr[i] &gt; arr[i + 1] &gt; ... &gt; arr[arr.length - 1]</code>.</p>

<p>You must solve it in <code>O(log(arr.length))</code> time complexity.</p>

<pre><strong>Input:</strong> arr = [0,1,0]
</pre>

<pre><strong>Input:</strong> arr = [0,2,1,0]
</pre>

<pre><strong>Input:</strong> arr = [0,10,5,2]
</pre>

<ul>
	<li><code>3 &lt;= arr.length &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= arr[i] &lt;= 10<sup>6</sup></code></li>
	<li><code>arr</code> is <strong>guaranteed</strong> to be a mountain array.</li>
</ul>
</div>

directory: 82-remove-duplicates-from-sorted-list-ii
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        
        curr, prev = dummy, head
            if curr.next and curr.val == curr.next.val:
                while curr.next and curr.val == curr.next.val:
                        curr = curr.next
            else:
                prev = curr
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/">82. Remove Duplicates from Sorted List II</a></h2><h3>Medium</h3><hr><div><p>Given the <code>head</code> of a sorted linked list, <em>delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list</em>. Return <em>the linked list <strong>sorted</strong> as well</em>.</p>

            else:
                prev = curr

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/04/linkedlist1.jpg" style="width: 500px; height: 142px;">
<pre><strong>Input:</strong> head = [1,2,3,3,4,4,5]
<strong>Output:</strong> [1,2,5]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/04/linkedlist2.jpg" style="width: 500px; height: 205px;">
<pre><strong>Input:</strong> head = [1,1,1,2,3]
<strong>Output:</strong> [2,3]
</pre>

<ul>
	<li>The number of nodes in the list is in the range <code>[0, 300]</code>.</li>
	<li>The list is guaranteed to be <strong>sorted</strong> in ascending order.</li>
</ul>
</div>

directory: 1748-sum-of-unique-elements
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sum-of-unique-elements/">1748. Sum of Unique Elements</a></h2><h3>Easy</h3><hr><div><p>You are given an integer array <code>nums</code>. The unique elements of an array are the elements that appear <strong>exactly once</strong> in the array.</p>

<p>Return <em>the <strong>sum</strong> of all the unique elements of </em><code>nums</code>.</p>

<pre><strong>Input:</strong> nums = [1,2,3,2]
<strong>Explanation:</strong> The unique elements are [1,3], and the sum is 4.
</pre>

<strong>Explanation:</strong> There are no unique elements, and the sum is 0.
</pre>

<strong>Explanation:</strong> The unique elements are [1,2,3,4,5], and the sum is 15.
</pre>

<ul>
</ul>
</div>

directory: 524-longest-word-in-dictionary-through-deleting
    def findLongestWord(self, s: str, dictionary: List[str]) -> str:
        def isSubsequence(s, word):
            m, n = len(s), len(word)
            i, j = 0, 0
            while i < m and j < n:
                if s[i] == word[j]:
                    j+=1
                i+=1
            return j == n
        result = ''
        dictionary.sort()
        for word in dictionary:
            if len(word) > len(s):
                continue
            if isSubsequence(s, word) and len(word) > len(result):
                result = word
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/longest-word-in-dictionary-through-deleting/">524. Longest Word in Dictionary through Deleting</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code> and a string array <code>dictionary</code>, return <em>the longest string in the dictionary that can be formed by deleting some of the given string characters</em>. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty string.</p>

            i, j = 0, 0
                    j+=1
                i+=1
        result = ''
                continue

<pre><strong>Input:</strong> s = "abpcplea", dictionary = ["ale","apple","monkey","plea"]
</pre>

<pre><strong>Input:</strong> s = "abpcplea", dictionary = ["a","b","c"]
<strong>Output:</strong> "a"
</pre>

<ul>
	<li><code>1 &lt;= dictionary.length &lt;= 1000</code></li>
	<li><code>1 &lt;= dictionary[i].length &lt;= 1000</code></li>
	<li><code>s</code> and <code>dictionary[i]</code> consist of lowercase English letters.</li>
</ul>
</div>

directory: 78-subsets
        
        def backtrack(index, k, path):
            if len(path[:]) == k:
                outputs.append(path[:])
                path.append(nums[i])
                backtrack(i + 1, k, path)

        for k in range(n+1):
            backtrack(0, k, [])
Notes: ​

</pre>

</pre>

<ul>
</ul>
</div>

directory: 1328-break-a-palindrome
    def breakPalindrome(self, palindrome: str) -> str:
        
        if len(palindrome) == 1:
            return ""
        found_a = False
        palindrome = list(palindrome)
        for i in range(len(palindrome)//2):
            if palindrome[i] != 'a' and not found_a:
                palindrome[i] = 'a'
                return "".join(palindrome)
        palindrome[-1] = "b"
        return "".join(palindrome)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/break-a-palindrome/">1328. Break a Palindrome</a></h2><h3>Medium</h3><hr><div><p>Given a palindromic string of lowercase English letters <code>palindrome</code>, replace <strong>exactly one</strong> character with any lowercase English letter so that the resulting string is <strong>not</strong> a palindrome and that it is the <strong>lexicographically smallest</strong> one possible.</p>

            return ""
        
<p>Return <em>the resulting string. If there is no way to replace a character to make it not a palindrome, return an <strong>empty string</strong>.</em></p>

<p>A string <code>a</code> is lexicographically smaller than a string <code>b</code> (of the same length) if in the first position where <code>a</code> and <code>b</code> differ, <code>a</code> has a character strictly smaller than the corresponding character in <code>b</code>. For example, <code>"abcc"</code> is lexicographically smaller than <code>"abcd"</code> because the first position they differ is at the fourth character, and <code>'c'</code> is smaller than <code>'d'</code>.</p>

<pre><strong>Input:</strong> palindrome = "abccba"
<strong>Output:</strong> "aaccba"
<strong>Explanation:</strong> There are many ways to make "abccba" not a palindrome, such as "<u>z</u>bccba", "a<u>a</u>ccba", and "ab<u>a</u>cba".
Of all the ways, "aaccba" is the lexicographically smallest.
</pre>

<pre><strong>Input:</strong> palindrome = "a"
<strong>Explanation:</strong> There is no way to replace a single character to make "a" not a palindrome, so return an empty string.
</pre>

<ul>
	<li><code>1 &lt;= palindrome.length &lt;= 1000</code></li>
	<li><code>palindrome</code> consists of only lowercase English letters.</li>
</ul>
</div>

directory: 700-search-in-a-binary-search-tree
    def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if root.val == val:
        if root.val < val:
            return self.searchBST(root.right, val)
        else:
            return self.searchBST(root.left, val)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/search-in-a-binary-search-tree/">700. Search in a Binary Search Tree</a></h2><h3>Easy</h3><hr><div><p>You are given the <code>root</code> of a binary search tree (BST) and an integer <code>val</code>.</p>

        else:
        
<p>Find the node in the BST that the node's value equals <code>val</code> and return the subtree rooted with that node. If such a node does not exist, return <code>null</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/12/tree1.jpg" style="width: 422px; height: 302px;">
<pre><strong>Input:</strong> root = [4,2,7,1,3], val = 2
<strong>Output:</strong> [2,1,3]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/12/tree2.jpg" style="width: 422px; height: 302px;">
<pre><strong>Input:</strong> root = [4,2,7,1,3], val = 5
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 5000]</code>.</li>
	<li><code>1 &lt;= Node.val &lt;= 10<sup>7</sup></code></li>
	<li><code>root</code> is a binary search tree.</li>
	<li><code>1 &lt;= val &lt;= 10<sup>7</sup></code></li>
</ul>
</div>

directory: 0237-delete-node-in-a-linked-list

    def deleteNode(self, node):
        """
        :type node: ListNode
        :rtype: void Do not return anything, modify node in-place instead.
        """
        
        curr = node
        prev = None
        while curr.next:
            nxt = curr.next.val 
            curr.val = nxt
            prev = curr
        prev.next = None
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/delete-node-in-a-linked-list/">237. Delete Node in a Linked List</a></h2><h3>Medium</h3><hr><div><p>There is a singly-linked list <code>head</code> and we want to delete a node <code>node</code> in it.</p>

<p>You are given the node to be deleted <code>node</code>. You will <strong>not be given access</strong> to the first node of <code>head</code>.</p>

        """
        """
        
        curr = node
        prev = None
            prev = curr

<p>All the values of the linked list are <strong>unique</strong>, and it is guaranteed that the given node <code>node</code> is not the last node in the linked list.</p>

<p>Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:</p>

<ul>
	<li>The value of the given node should not exist in the linked list.</li>
	<li>The number of nodes in the linked list should decrease by one.</li>
	<li>All the values before <code>node</code> should be in the same order.</li>
	<li>All the values after <code>node</code> should be in the same order.</li>
</ul>

<ul>
	<li>For the input, you should provide the entire linked list <code>head</code> and the node to be given <code>node</code>. <code>node</code> should not be the last node of the list and should be an actual node in the list.</li>
	<li>We will build the linked list and pass the node to your function.</li>
	<li>The output will be the entire list after calling your function.</li>
</ul>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/01/node1.jpg" style="width: 400px; height: 286px;">
<pre><strong>Input:</strong> head = [4,5,1,9], node = 5
<strong>Output:</strong> [4,1,9]
<strong>Explanation: </strong>You are given the second node with value 5, the linked list should become 4 -&gt; 1 -&gt; 9 after calling your function.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/01/node2.jpg" style="width: 400px; height: 315px;">
<pre><strong>Input:</strong> head = [4,5,1,9], node = 1
<strong>Output:</strong> [4,5,9]
<strong>Explanation: </strong>You are given the third node with value 1, the linked list should become 4 -&gt; 5 -&gt; 9 after calling your function.
</pre>

<ul>
	<li>The number of the nodes in the given list is in the range <code>[2, 1000]</code>.</li>
	<li>The value of each node in the list is <strong>unique</strong>.</li>
	<li>The <code>node</code> to be deleted is <strong>in the list</strong> and is <strong>not a tail</strong> node.</li>
</ul>
</div>

directory: 255-verify-preorder-sequence-in-binary-search-tree
    def verifyPreorder(self, preorder: List[int]) -> bool:
        
        check, stack = None, []
        for num in preorder:
            while stack and num > stack[-1]:
                check = stack.pop()
            if check!=None and check > num:
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/">255. Verify Preorder Sequence in Binary Search Tree</a></h2><h3>Medium</h3><hr><div><p>Given an array of <strong>unique</strong> integers <code>preorder</code>, return <code>true</code> <em>if it is the correct preorder traversal sequence of a binary search tree</em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/preorder-tree.jpg" style="width: 292px; height: 302px;">
<pre><strong>Input:</strong> preorder = [5,2,1,3,6]
</pre>

<pre><strong>Input:</strong> preorder = [5,2,6,1,3]
</pre>

<ul>
	<li><code>1 &lt;= preorder.length &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= preorder[i] &lt;= 10<sup>4</sup></code></li>
	<li>All the elements of <code>preorder</code> are <strong>unique</strong>.</li>
</ul>

<p><strong>Follow up:</strong> Could you do it using only constant space complexity?</p>
</div>

directory: 518-coin-change-2
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/coin-change-2/">518. Coin Change 2</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>coins</code> representing coins of different denominations and an integer <code>amount</code> representing a total amount of money.</p>

<p>Return <em>the number of combinations that make up that amount</em>. If that amount of money cannot be made up by any combination of the coins, return <code>0</code>.</p>

<p>The answer is <strong>guaranteed</strong> to fit into a signed <strong>32-bit</strong> integer.</p>

<pre><strong>Input:</strong> amount = 5, coins = [1,2,5]
<strong>Explanation:</strong> there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
</pre>

<pre><strong>Input:</strong> amount = 3, coins = [2]
<strong>Explanation:</strong> the amount of 3 cannot be made up just with coins of 2.
</pre>

<pre><strong>Input:</strong> amount = 10, coins = [10]
</pre>

<ul>
	<li><code>1 &lt;= coins.length &lt;= 300</code></li>
	<li><code>1 &lt;= coins[i] &lt;= 5000</code></li>
	<li>All the values of <code>coins</code> are <strong>unique</strong>.</li>
	<li><code>0 &lt;= amount &lt;= 5000</code></li>
</ul>
</div>

directory: 430-flatten-a-multilevel-doubly-linked-list
    def __init__(self, val, prev, next, child):
        self.prev = prev
        self.child = child
"""

"""
"""

    def flatten(self, head: 'Optional[Node]') -> 'Optional[Node]':
        current = head
        while current:
            if current.child:
                self.merge(current)
            current = current.next
        return head
    
    def merge(self, current):
        
        child = current.child
        while child.next:
            child = child.next
        
        if current.next:
            child.next = current.next
            current.next.prev = child
        
        current.next = current.child
        current.child.prev = current
        
        current.child = None

Notes: ​

</pre>

</pre>

</pre>

<ul>
</ul>

<p>We use the multilevel linked list from <strong>Example 1</strong> above:</p>

         |
             |

</pre>

             |
                   |
</pre>

</pre>
</div>

directory: 1679-max-number-of-k-sum-pairs
    def maxOperations(self, nums: List[int], k: int) -> int:
        
        count = 0
            s = nums[left] + nums[right]
            if s == k:
                count += 1
                left += 1
                right -= 1
            elif s < k:
                left += 1
            else:
                right -= 1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/max-number-of-k-sum-pairs/">1679. Max Number of K-Sum Pairs</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code> and an integer <code>k</code>.</p>

<p>In one operation, you can pick two numbers from the array whose sum equals <code>k</code> and remove them from the array.</p>

<p>Return <em>the maximum number of operations you can perform on the array</em>.</p>

        count = 0
            if s == k:
                count += 1
                left += 1
                right -= 1
            elif s < k:
                left += 1
            else:
                right -= 1

<pre><strong>Input:</strong> nums = [1,2,3,4], k = 5
<strong>Explanation:</strong> Starting with nums = [1,2,3,4]:
- Remove numbers 1 and 4, then nums = [2,3]
- Remove numbers 2 and 3, then nums = []
There are no more pairs that sum up to 5, hence a total of 2 operations.</pre>

<pre><strong>Input:</strong> nums = [3,1,3,4,3], k = 6
<strong>Explanation:</strong> Starting with nums = [3,1,3,4,3]:
- Remove the first two 3's, then nums = [1,4,3]
There are no more pairs that sum up to 6, hence a total of 1 operation.</pre>

<ul>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
	<li><code>1 &lt;= k &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 0253-meeting-rooms-ii
        """
        heap = []
        for start, end in intervals:
            if not heap or heap[0] > start:
                heapq.heappush(heap,end)
            else:
                heapq.heappushpop(heap, end)
        return len(heap)
        """
        used_rooms = 0
        n = len(intervals)
        start_timings = sorted(interval[0] for interval in intervals)
        end_timings = sorted(interval[1] for interval in intervals)
            if start_timings[start] >= end_timings[end]:
                used_rooms -= 1
                end += 1
            used_rooms += 1
            start += 1
        return used_rooms
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/meeting-rooms-ii/">253. Meeting Rooms II</a></h2><h3>Medium</h3><hr><div><p>Given an array of meeting time intervals <code>intervals</code> where <code>intervals[i] = [start<sub>i</sub>, end<sub>i</sub>]</code>, return <em>the minimum number of conference rooms required</em>.</p>

        """
        heap = []
            else:
        """
                end += 1
            start += 1
            
</pre>

<ul>
	<li><code>1 &lt;=&nbsp;intervals.length &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= start<sub>i</sub> &lt; end<sub>i</sub> &lt;= 10<sup>6</sup></code></li>
</ul>
</div>

directory: 1680-concatenation-of-consecutive-binary-numbers
    def concatenatedBinary(self, n: int) -> int:
        
        MOD = 10 ** 9 + 7
        length, result = 0, 0
        for i in range(1, n + 1):
            if i & (i - 1) == 0:
                length += 1
            result = ((result << length) | i) % MOD
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/">1680. Concatenation of Consecutive Binary Numbers</a></h2><h3>Medium</h3><hr><div><p>Given an integer <code>n</code>, return <em>the <strong>decimal value</strong> of the binary string formed by concatenating the binary representations of </em><code>1</code><em> to </em><code>n</code><em> in order, <strong>modulo </strong></em><code>10<sup>9 </sup>+ 7</code>.</p>

                length += 1
       
<strong>Explanation: </strong>"1" in binary corresponds to the decimal value 1. 
</pre>

<strong>Explanation: </strong>In binary, 1, 2, and 3 corresponds to "1", "10", and "11".
After concatenating them, we have "11011", which corresponds to the decimal value 27.
</pre>

<strong>Output:</strong> 505379714
<strong>Explanation</strong>: The concatenation results in "1101110010111011110001001101010111100".
The decimal value of that is 118505380540.
After modulo 10<sup>9</sup> + 7, the result is 505379714.
</pre>

<ul>
</ul>
</div>

directory: 300-longest-increasing-subsequence
    def lengthOfLIS(self, nums: List[int]) -> int:
        dp = [1] * n
        i, j = 1, 0
        while i < n:
            j = i-1
            while j >= 0:
                if j >=0 and nums[j] < nums[i]:
                    dp[i] = max(dp[i], 1 + dp[j])
                j-=1
            i += 1
        return max(dp)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/longest-increasing-subsequence/">300. Longest Increasing Subsequence</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, return the length of the longest strictly increasing subsequence.</p>

<p>A <strong>subsequence</strong> is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, <code>[3,6,2,7]</code> is a subsequence of the array <code>[0,3,1,6,2,2,7]</code>.</p>

        dp = [1] * n
        i, j = 1, 0
        while i < n:
            j = i-1
                j-=1
            i += 1

<pre><strong>Input:</strong> nums = [10,9,2,5,3,7,101,18]
<strong>Explanation:</strong> The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
</pre>

<pre><strong>Input:</strong> nums = [0,1,0,3,2,3]
</pre>

<pre><strong>Input:</strong> nums = [7,7,7,7,7,7,7]
</pre>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 2500</code></li>
</ul>

<p><b>Follow up:</b>&nbsp;Can you come up with an algorithm that runs in&nbsp;<code>O(n log(n))</code> time complexity?</p>
</div>

directory: 2083-substrings-that-begin-and-end-with-the-same-letter
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/substrings-that-begin-and-end-with-the-same-letter/">2083. Substrings That Begin and End With the Same Letter</a></h2><h3>Medium</h3><hr><div><p>You are given a <strong>0-indexed</strong> string <code>s</code> consisting of only lowercase English letters. Return <em>the number of <strong>substrings</strong> in </em><code>s</code> <em>that begin and end with the <strong>same</strong> character.</em></p>

<p>A <strong>substring</strong> is a contiguous non-empty sequence of characters within a string.</p>

<pre><strong>Input:</strong> s = "abcba"
The substrings of length 1 that start and end with the same letter are: "a", "b", "c", "b", and "a".
The substring of length 3 that starts and ends with the same letter is: "bcb".
The substring of length 5 that starts and ends with the same letter is: "abcba".
</pre>

<pre><strong>Input:</strong> s = "abacad"
The substrings of length 1 that start and end with the same letter are: "a", "b", "a", "c", "a", and "d".
The substrings of length 3 that start and end with the same letter are: "aba" and "aca".
The substring of length 5 that starts and ends with the same letter is: "abaca".
</pre>

The substring of length 1 that starts and ends with the same letter is: "a".
</pre>

<ul>
	<li><code>s</code> consists only of lowercase English letters.</li>
</ul>
</div>

directory: 443-string-compression
Python: 
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/string-compression/">443. String Compression</a></h2><h3>Medium</h3><hr><div><p>Given an array of characters <code>chars</code>, compress it using the following algorithm:</p>

<p>Begin with an empty string <code>s</code>. For each group of <strong>consecutive repeating characters</strong> in <code>chars</code>:</p>

<ul>
	<li>If the group's length is <code>1</code>, append the character to <code>s</code>.</li>
	<li>Otherwise, append the character followed by the group's length.</li>
</ul>

<p>The compressed string <code>s</code> <strong>should not be returned separately</strong>, but instead, be stored <strong>in the input character array <code>chars</code></strong>. Note that group lengths that are <code>10</code> or longer will be split into multiple characters in <code>chars</code>.</p>

<p>After you are done <strong>modifying the input array,</strong> return <em>the new length of the array</em>.</p>

<p>You must write an algorithm that uses only constant extra space.</p>

<pre><strong>Input:</strong> chars = ["a","a","b","b","c","c","c"]
<strong>Output:</strong> Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]
<strong>Explanation:</strong> The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".
</pre>

<pre><strong>Input:</strong> chars = ["a"]
<strong>Output:</strong> Return 1, and the first character of the input array should be: ["a"]
<strong>Explanation:</strong> The only group is "a", which remains uncompressed since it's a single character.
</pre>

<pre><strong>Input:</strong> chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]
<strong>Output:</strong> Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].
<strong>Explanation:</strong> The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".</pre>

<ul>
	<li><code>1 &lt;= chars.length &lt;= 2000</code></li>
	<li><code>chars[i]</code> is a lowercase English letter, uppercase English letter, digit, or symbol.</li>
</ul>
</div>

directory: 349-intersection-of-two-arrays
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        intersection = set()
        if len(nums1) < len(nums2):
            numSet = set(nums1)
            for num in nums2:
                if num in numSet:
                    intersection.add(num)
        else:
            numSet = set(nums2)
            for num in nums1:
        
        return list(intersection)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/intersection-of-two-arrays/">349. Intersection of Two Arrays</a></h2><h3>Easy</h3><hr><div><p>Given two integer arrays <code>nums1</code> and <code>nums2</code>, return <em>an array of their intersection</em>. Each element in the result must be <strong>unique</strong> and you may return the result in <strong>any order</strong>.</p>

        else:
        
<pre><strong>Input:</strong> nums1 = [1,2,2,1], nums2 = [2,2]
</pre>

<pre><strong>Input:</strong> nums1 = [4,9,5], nums2 = [9,4,9,8,4]
<strong>Output:</strong> [9,4]
<strong>Explanation:</strong> [4,9] is also accepted.
</pre>

<ul>
	<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 1000</code></li>
</ul>
</div>

directory: 326-power-of-three
    def isPowerOfThree(self, n: int) -> bool:
        if n == 1:
        x = 1
        while x <= n:
            x *= 3
            if x == n:
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/power-of-three/">326. Power of Three</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>n</code>, return <em><code>true</code> if it is a power of three. Otherwise, return <code>false</code></em>.</p>

<p>An integer <code>n</code> is a power of three, if there exists an integer <code>x</code> such that <code>n == 3<sup>x</sup></code>.</p>

<pre><strong>Input:</strong> n = 27
</pre>

</pre>

        if n == 1:
        x = 1
            x *= 3
            if x == n:
        
<pre><strong>Input:</strong> n = 9
</pre>

<ul>
</ul>

<strong>Follow up:</strong> Could you solve it without loops/recursion?</div>

directory: 94-binary-tree-inorder-traversal
        
        ans = []
            if stack:
                if root:
        
        return ans
Notes: ​

        ans = []
            if stack:
                if root:
        
        return ans

</pre>

</pre>

</pre>

<ul>
</ul>

directory: 24-swap-nodes-in-pairs
    def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
        
        a, b = head, head.next
        a.next = self.swapPairs(b.next)
        b.next = a
        return b
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/swap-nodes-in-pairs/">24. Swap Nodes in Pairs</a></h2><h3>Medium</h3><hr><div><p>Given a&nbsp;linked list, swap every two adjacent nodes and return its head. You must solve the problem without&nbsp;modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)</p>

        b.next = a
        return b

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg" style="width: 422px; height: 222px;">
<strong>Output:</strong> [2,1,4,3]
</pre>

</pre>

<pre><strong>Input:</strong> head = [1]
</pre>

<ul>
	<li>The number of nodes in the&nbsp;list&nbsp;is in the range <code>[0, 100]</code>.</li>
</ul>
</div>

directory: 0643-maximum-average-subarray-i
    def findMaxAverage(self, nums: List[int], k: int) -> float:
        
        sums = [0] * n
        sums[0] = nums[0]
        
        for i in range(1, n):
            sums[i] = sums[i-1] + nums[i]
        res = sums[k-1] / k
        for i in range(k, n):
            res = max(res, (sums[i] - sums[i-k])/k)
        return res
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/maximum-average-subarray-i/">643. Maximum Average Subarray I</a></h2><h3>Easy</h3><hr><div><p>You are given an integer array <code>nums</code> consisting of <code>n</code> elements, and an integer <code>k</code>.</p>

<p>Find a contiguous subarray whose <strong>length is equal to</strong> <code>k</code> that has the maximum average value and return <em>this value</em>. Any answer with a calculation error less than <code>10<sup>-5</sup></code> will be accepted.</p>

        return res

<pre><strong>Input:</strong> nums = [1,12,-5,-6,50,3], k = 4
<strong>Output:</strong> 12.75000
<strong>Explanation:</strong> Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75
</pre>

<pre><strong>Input:</strong> nums = [5], k = 1
<strong>Output:</strong> 5.00000
</pre>

<ul>
	<li><code>1 &lt;= k &lt;= n &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 264-ugly-number-ii
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/ugly-number-ii/">264. Ugly Number II</a></h2><h3>Medium</h3><hr><div><p>An <strong>ugly number</strong> is a positive integer whose prime factors are limited to <code>2</code>, <code>3</code>, and <code>5</code>.</p>

<p>Given an integer <code>n</code>, return <em>the</em> <code>n<sup>th</sup></code> <em><strong>ugly number</strong></em>.</p>

<strong>Explanation:</strong> [1, 2, 3, 4, 5, 6, 8, 9, 10, 12] is the sequence of the first 10 ugly numbers.
</pre>

</pre>

directory: 557-reverse-words-in-a-string-iii
    def reverseWords(self, s: str) -> str:
        
        return " ".join([l[::-1] for l in s.split()])
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/reverse-words-in-a-string-iii/">557. Reverse Words in a String III</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code>, reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.</p>

<pre><strong>Input:</strong> s = "Let's take LeetCode contest"
<strong>Output:</strong> "s'teL ekat edoCteeL tsetnoc"
<pre><strong>Input:</strong> s = "God Ding"
<strong>Output:</strong> "doG gniD"
</pre>

<ul>
	<li><code>s</code> contains printable <strong>ASCII</strong> characters.</li>
	<li><code>s</code> does not contain any leading or trailing spaces.</li>
	<li>There is <strong>at least one</strong> word in <code>s</code>.</li>
	<li>All the words in <code>s</code> are separated by a single space.</li>
</ul>
</div>

directory: 1615-maximal-network-rank
    def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
        
        for city1, city2 in roads:
            graph[city1].append(city2)
            graph[city2].append(city1)
        max_network = float('-inf')
            for j in range(i+1, n):
                if i in graph[j] or j in graph[j]:
                    max_network = max(max_network, len(graph[i]) + len(graph[j])-1)
                else:
                    max_network = max(max_network, len(graph[i]) + len(graph[j]))
        return max_network
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximal-network-rank/">1615. Maximal Network Rank</a></h2><h3>Medium</h3><hr><div><p>There is an infrastructure of <code>n</code> cities with some number of <code>roads</code> connecting these cities. Each <code>roads[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that there is a bidirectional road between cities <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>.</p>

                else:

<p>The <strong>network rank</strong><em> </em>of <strong>two different cities</strong> is defined as the total number of&nbsp;<strong>directly</strong> connected roads to <strong>either</strong> city. If a road is directly connected to both cities, it is only counted <strong>once</strong>.</p>

<p>The <strong>maximal network rank </strong>of the infrastructure is the <strong>maximum network rank</strong> of all pairs of different cities.</p>

<p>Given the integer <code>n</code> and the array <code>roads</code>, return <em>the <strong>maximal network rank</strong> of the entire infrastructure</em>.</p>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/09/21/ex1.png" style="width: 292px; height: 172px;"></strong></p>

<pre><strong>Input:</strong> n = 4, roads = [[0,1],[0,3],[1,2],[1,3]]
<strong>Explanation:</strong> The network rank of cities 0 and 1 is 4 as there are 4 roads that are connected to either 0 or 1. The road between 0 and 1 is only counted once.
</pre>

<p><strong><img alt="" src="https://assets.leetcode.com/uploads/2020/09/21/ex2.png" style="width: 292px; height: 172px;"></strong></p>

<pre><strong>Input:</strong> n = 5, roads = [[0,1],[0,3],[1,2],[1,3],[2,3],[2,4]]
<strong>Explanation:</strong> There are 5 roads that are connected to cities 1 or 2.
</pre>

<pre><strong>Input:</strong> n = 8, roads = [[0,1],[1,2],[2,3],[2,4],[5,6],[5,7]]
<strong>Explanation:</strong> The network rank of 2 and 5 is 5. Notice that all the cities do not have to be connected.
</pre>

<ul>
	<li><code>0 &lt;= roads.length &lt;= n * (n - 1) / 2</code></li>
	<li><code>roads[i].length == 2</code></li>
	<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub>&nbsp;&lt;= n-1</code></li>
	<li><code>a<sub>i</sub>&nbsp;!=&nbsp;b<sub>i</sub></code></li>
	<li>Each&nbsp;pair of cities has <strong>at most one</strong> road connecting them.</li>
</ul>
</div>

directory: 0394-decode-string
    def decodeString(self, s: str) -> str:
        
        numStack = []
        stringStack = []
        number = ""
        string = ""
        for ch in s:
                number += ch
                numStack.append(int(number))
                stringStack.append(string)
                number = ""
                string = ""
                string = stringStack.pop() + string * numStack.pop()  
            else:
                string += ch
        return string
def decodeString(self, s: str) -> str:
nums = []
strs = []
string = ""
num = ""
for i, ch in enumerate(s):
if ch.isdigit():
num += ch
elif ch == '[':
nums.append(int(num))
strs.append(string)
num = ""
string = ""
elif ch == ']':
string = strs.pop() * nums.pop() + string
else:
string += ch
return string

        number = ""
        string = ""
        for ch in s:
                number = ""
                string = ""
            else:

<p>You may assume that the input string is always valid; there are no extra white spaces, square brackets are well-formed, etc. Furthermore, you may assume that the original data does not contain any digits and that digits are only for those repeat numbers, <code>k</code>. For example, there will not be input like <code>3a</code> or <code>2[4]</code>.</p>

<p>The test cases are generated so that the length of the output will never exceed <code>10<sup>5</sup></code>.</p>

</pre>

</pre>

</pre>

<ul>
</ul>
</div>

directory: 1319-number-of-operations-to-make-network-connected
    def makeConnected(self, n: int, connections: List[List[int]]) -> int:
        
        if len(connections) < n - 1:
            return - 1
        
        for v1, v2 in connections:
            graph[v1].append(v2)
            graph[v2].append(v1)
            visited.add(node)    
                if nei not in visited:
                    visited.add(node)
                    dfs(nei)
        count = 0
            if i not in visited:
                count+=1
                dfs(i)
        return count - 1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-operations-to-make-network-connected/">1319. Number of Operations to Make Network Connected</a></h2><h3>Medium</h3><hr><div><p>There are <code>n</code> computers numbered from <code>0</code> to <code>n - 1</code> connected by ethernet cables <code>connections</code> forming a network where <code>connections[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> represents a connection between computers <code>a<sub>i</sub></code> and <code>b<sub>i</sub></code>. Any computer can reach any other computer directly or indirectly through the network.</p>

            return - 1
        
                    dfs(nei)
        count = 0
                count+=1
                dfs(i)

<p>You are given an initial computer network <code>connections</code>. You can extract certain cables between two directly connected computers, and place them between any pair of disconnected computers to make them directly connected.</p>

<p>Return <em>the minimum number of times you need to do this in order to make all the computers connected</em>. If it is not possible, return <code>-1</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/01/02/sample_1_1677.png" style="width: 500px; height: 148px;">
<pre><strong>Input:</strong> n = 4, connections = [[0,1],[0,2],[1,2]]
<strong>Explanation:</strong> Remove cable between computer 1 and 2 and place between computers 1 and 3.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/01/02/sample_2_1677.png" style="width: 500px; height: 129px;">
<pre><strong>Input:</strong> n = 6, connections = [[0,1],[0,2],[0,3],[1,2],[1,3]]
</pre>

<pre><strong>Input:</strong> n = 6, connections = [[0,1],[0,2],[0,3],[1,2]]
<strong>Explanation:</strong> There are not enough cables.
</pre>

<ul>
	<li><code>1 &lt;= connections.length &lt;= min(n * (n - 1) / 2, 10<sup>5</sup>)</code></li>
	<li><code>connections[i].length == 2</code></li>
	<li>There are no repeated connections.</li>
	<li>No two computers are connected by more than one cable.</li>
</ul>
</div>

directory: 59-spiral-matrix-ii
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/spiral-matrix-ii/">59. Spiral Matrix II</a></h2><h3>Medium</h3><hr><div><p>Given a positive integer <code>n</code>, generate an <code>n x n</code> <code>matrix</code> filled with elements from <code>1</code> to <code>n<sup>2</sup></code> in spiral order.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/spiraln.jpg" style="width: 242px; height: 242px;">
<strong>Output:</strong> [[1,2,3],[8,9,4],[7,6,5]]
</pre>

</pre>

<ul>
</ul>
</div>

directory: 1302-deepest-leaves-sum
    def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
        
        s = 0
        h = float('-inf')
        
        def dfs(root, curr_height):
            nonlocal s, h;
            if root:
                    if curr_height > h:
                        s = root.val
                        h = curr_height
                    elif curr_height == h:
                        s += root.val
                dfs(root.left, curr_height + 1)
                dfs(root.right, curr_height + 1)
                
        return s
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/deepest-leaves-sum/">1302. Deepest Leaves Sum</a></h2><h3>Medium</h3><hr><div>Given the <code>root</code> of a binary tree, return <em>the sum of values of its deepest leaves</em>.
<img alt="" src="https://assets.leetcode.com/uploads/2019/07/31/1483_ex1.png" style="width: 273px; height: 265px;">
<pre><strong>Input:</strong> root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
</pre>

        s = 0
        
            if root:
                
        return s
        
<pre><strong>Input:</strong> root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
<strong>Output:</strong> 19
</pre>

<ul>
</ul>
</div>

directory: 207-course-schedule
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        
        for crs, pre in prerequisites:
            graph[crs].append(pre)
        def dfs(course):
            if course in visit:
            if graph[course] == []:
            visit.add(course)
            for pre in graph[course]:
                if not dfs(pre):
            visit.remove(course)
            graph[course] = []
        for i in range(numCourses):
            if not dfs(i):
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/course-schedule/">207. Course Schedule</a></h2><h3>Medium</h3><hr><div><p>There are a total of <code>numCourses</code> courses you have to take, labeled from <code>0</code> to <code>numCourses - 1</code>. You are given an array <code>prerequisites</code> where <code>prerequisites[i] = [a<sub>i</sub>, b<sub>i</sub>]</code> indicates that you <strong>must</strong> take course <code>b<sub>i</sub></code> first if you want to take course <code>a<sub>i</sub></code>.</p>

<ul>
	<li>For example, the pair <code>[0, 1]</code>, indicates that to take course <code>0</code> you have to first take course <code>1</code>.</li>
</ul>

<p>Return <code>true</code> if you can finish all courses. Otherwise, return <code>false</code>.</p>

<pre><strong>Input:</strong> numCourses = 2, prerequisites = [[1,0]]
<strong>Explanation:</strong> There are a total of 2 courses to take. 
To take course 1 you should have finished course 0. So it is possible.
</pre>

<pre><strong>Input:</strong> numCourses = 2, prerequisites = [[1,0],[0,1]]
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.
</pre>

<ul>
	<li><code>1 &lt;= numCourses &lt;= 2000</code></li>
	<li><code>0 &lt;= prerequisites.length &lt;= 5000</code></li>
	<li><code>prerequisites[i].length == 2</code></li>
	<li><code>0 &lt;= a<sub>i</sub>, b<sub>i</sub> &lt; numCourses</code></li>
	<li>All the pairs prerequisites[i] are <strong>unique</strong>.</li>
</ul>
</div>

directory: 417-pacific-atlantic-water-flow
    def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]:
        
        pacific, atlantic = set(), set()
        rows, cols = len(heights), len(heights[0])
        
        def dfs(r, c, elevation, visit):
            # Out of bounds
            if r < 0 or c < 0 or r >= rows or c >= cols:
                return
            # Water cannot flow from lower elevation to a higher elevation
            if elevation > heights[r][c]:
                return
            # If already Visited
            if (r, c) in visit:
                return
            visit.add((r,c))
            dfs(r + 1, c, heights[r][c], visit)
            dfs(r, c + 1, heights[r][c], visit)
            dfs(r, c - 1, heights[r][c], visit)
            dfs(r - 1,c, heights[r][c], visit)
            
        # For the co-ordinates aligned with pacific, put them in Pacific Set
        for c in range(cols):
            dfs(0, c, heights[0][c], pacific)
            dfs(rows-1, c, heights[rows-1][c], atlantic)
        # For the co-ordinates aligned with the atlantic, put them in the Atlantic Set
            dfs(r, 0, heights[r][0], pacific)
            dfs(r, cols - 1, heights[r][cols-1], atlantic)
        
        # Get the intersection of both sets which should be the answer.
        return list(pacific.intersection(atlantic))
Notes: ​
Readme:

                return
                return
                return
            
directory: 69-sqrtx
    def mySqrt(self, x: int) -> int:
        
        left, right = 1, x
        
            if mid * mid == x:
                return mid
            if mid * mid < x:
            else: 
        
        return right
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sqrtx/">69. Sqrt(x)</a></h2><h3>Easy</h3><hr><div><p>Given a non-negative integer <code>x</code>,&nbsp;compute and return <em>the square root of</em> <code>x</code>.</p>

<p>Since the return type&nbsp;is an integer, the decimal digits are <strong>truncated</strong>, and only <strong>the integer part</strong> of the result&nbsp;is returned.</p>

<p><strong>Note:&nbsp;</strong>You are not allowed to use any built-in exponent function or operator, such as <code>pow(x, 0.5)</code> or&nbsp;<code>x ** 0.5</code>.</p>

                return mid
            else: 
        
<pre><strong>Input:</strong> x = 4
</pre>

<pre><strong>Input:</strong> x = 8
<strong>Explanation:</strong> The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.</pre>

<ul>
	<li><code>0 &lt;= x &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 0523-continuous-subarray-sum
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        
        """
        2 + 4 = 6 Y
        6 N
        1. Brute Force (Straightforward) 
        Iterate over each subarray, find the sum and find if the subarray sum is divisible by k.
        
            s = 0
            for j in range(i, len(nums)):
                s +=  nums[j]
                if j - i + 1 >= 2 and s % k == 0:
        
        2. 
        
        """
        
            prefixSum = (prefixSum + num) % k
            if prefixSum not in dic:
            else:
                if  i - dic[prefixSum] > 1:
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/continuous-subarray-sum/">523. Continuous Subarray Sum</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if </em><code>nums</code><em> has a continuous subarray of size <strong>at least two</strong> whose elements sum up to a multiple of</em> <code>k</code><em>, or </em><code>false</code><em> otherwise</em>.</p>

        """
        2 + 4 = 6 Y
        6 N
        
            s = 0
        
        2. 
        
        """
        
            else:
            
<p>An integer <code>x</code> is a multiple of <code>k</code> if there exists an integer <code>n</code> such that <code>x = n * k</code>. <code>0</code> is <strong>always</strong> a multiple of <code>k</code>.</p>

<pre><strong>Input:</strong> nums = [23,<u>2,4</u>,6,7], k = 6
<strong>Explanation:</strong> [2, 4] is a continuous subarray of size 2 whose elements sum up to 6.
</pre>

<pre><strong>Input:</strong> nums = [<u>23,2,6,4,7</u>], k = 6
<strong>Explanation:</strong> [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42.
42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer.
</pre>

<pre><strong>Input:</strong> nums = [23,2,6,4,7], k = 13
</pre>

<ul>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
	<li><code>0 &lt;= sum(nums[i]) &lt;= 2<sup>31</sup> - 1</code></li>
	<li><code>1 &lt;= k &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 2082-the-number-of-rich-customers
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/the-number-of-rich-customers/">2082. The Number of Rich Customers</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Store</code></p>

| bill_id     | int  |
| customer_id | int  |
| amount      | int  |
bill_id is the primary key for this table.
Each row contains information about the amount of one bill and the customer associated with it.
</pre>

<p>Write an SQL query to report the number of customers who had <strong>at least one</strong> bill with an amount <strong>strictly greater</strong> than <code>500</code>.</p>

Store table:
+---------+-------------+--------+
| bill_id | customer_id | amount |
| 6       | 1           | 549    |
| 8       | 1           | 834    |
| 4       | 2           | 394    |
| 11      | 3           | 657    |
| 13      | 3           | 257    |
+------------+
| rich_count |
| 2          |
Customer 1 has two bills with amounts strictly greater than 500.
Customer 2 does not have any bills with an amount strictly greater than 500.
Customer 3 has one bill with an amount strictly greater than 500.
</pre>
</div>

directory: 28-find-the-index-of-the-first-occurrence-in-a-string
    def strStr(self, haystack: str, needle: str) -> int:
        
        if needle == "":
            return 0
        n = len(needle)
        
        for i in range(len(haystack) - n + 1):
            if haystack[i : i + n] == needle:
                return i
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/">28. Find the Index of the First Occurrence in a String</a></h2><h3>Medium</h3><hr><div><p>Given two strings <code>needle</code> and <code>haystack</code>, return the index of the first occurrence of <code>needle</code> in <code>haystack</code>, or <code>-1</code> if <code>needle</code> is not part of <code>haystack</code>.</p>

            return 0
        
                return i
        return -1
        
<pre><strong>Input:</strong> haystack = "sadbutsad", needle = "sad"
<strong>Explanation:</strong> "sad" occurs at index 0 and 6.
The first occurrence is at index 0, so we return 0.
</pre>

<pre><strong>Input:</strong> haystack = "leetcode", needle = "leeto"
<strong>Explanation:</strong> "leeto" did not occur in "leetcode", so we return -1.
</pre>

<ul>
	<li><code>1 &lt;= haystack.length, needle.length &lt;= 10<sup>4</sup></code></li>
	<li><code>haystack</code> and <code>needle</code> consist of only lowercase English characters.</li>
</ul>
</div>

directory: 202-happy-number
    def isHappy(self, n: int) -> bool:
        s = 0
        
        def find_summed_squares(n):
            s = 0
            while n > 0:
                n, digit = divmod(n, 10)
                s += digit ** 2
            return s
        while n!=1 and n not in seen:
            seen.add(n)
            n = find_summed_squares(n)
        return n == 1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/happy-number/">202. Happy Number</a></h2><h3>Easy</h3><hr><div><p>Write an algorithm to determine if a number <code>n</code> is happy.</p>

<p>A <strong>happy number</strong> is a number defined by the following process:</p>

        s = 0
        
            s = 0
            while n > 0:
            return s
                
<ul>
	<li>Starting with any positive integer, replace the number by the sum of the squares of its digits.</li>
	<li>Repeat the process until the number equals 1 (where it will stay), or it <strong>loops endlessly in a cycle</strong> which does not include 1.</li>
	<li>Those numbers for which this process <strong>ends in 1</strong> are happy.</li>
</ul>

<p>Return <code>true</code> <em>if</em> <code>n</code> <em>is a happy number, and</em> <code>false</code> <em>if not</em>.</p>

<pre><strong>Input:</strong> n = 19
1<sup>2</sup> + 9<sup>2</sup> = 82
8<sup>2</sup> + 2<sup>2</sup> = 68
6<sup>2</sup> + 8<sup>2</sup> = 100
1<sup>2</sup> + 0<sup>2</sup> + 0<sup>2</sup> = 1
</pre>

</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 42-trapping-rain-water
    def trap(self, height: List[int]) -> int:
        
        if not height: return 0
        
        leftMax, rightMax = height[left], height[right]
        
        res = 0
        
            if leftMax < rightMax:
                left += 1
                leftMax = max(leftMax, height[left])
                res += leftMax - height[left]
            else:
                right -= 1
                rightMax = max(rightMax, height[right])
                res += rightMax - height[right]
        return res
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/trapping-rain-water/">42. Trapping Rain Water</a></h2><h3>Hard</h3><hr><div><p>Given <code>n</code> non-negative integers representing an elevation map where the width of each bar is <code>1</code>, compute how much water it can trap after raining.</p>

        res = 0
        
                left += 1
            else:
                right -= 1
        return res

<img src="https://assets.leetcode.com/uploads/2018/10/22/rainwatertrap.png" style="width: 412px; height: 161px;">
<pre><strong>Input:</strong> height = [0,1,0,2,1,0,1,3,2,1,2,1]
<strong>Explanation:</strong> The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
</pre>

<pre><strong>Input:</strong> height = [4,2,0,3,2,5]
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 2 * 10<sup>4</sup></code></li>
	<li><code>0 &lt;= height[i] &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 559-maximum-depth-of-n-ary-tree
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-depth-of-n-ary-tree/">559. Maximum Depth of N-ary Tree</a></h2><h3>Easy</h3><hr><div><p>Given a n-ary tree, find its maximum depth.</p>

<p>The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.</p>

</pre>

</pre>

<ul>
	<li>The total number of nodes is in the range <code>[0, 10<sup>4</sup>]</code>.</li>
</ul>
</div>

directory: 512-game-play-analysis-ii
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/game-play-analysis-ii/">512. Game Play Analysis II</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Activity</code></p>

</pre>

<p>Write an SQL query to report the <strong>device</strong> that is first logged in for each player.</p>

+-----------+-----------+
| player_id | device_id |
| 1         | 2         |
| 2         | 3         |
| 3         | 1         |
</pre>
</div>

directory: 496-next-greater-element-i
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        
        stack = []
        dic = {}
        for i, num in enumerate(nums2):
                dic[stack[-1]] = num
        ans = []
            if num not in dic:
                ans.append(-1)
            else:
                ans.append(dic[num])
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/next-greater-element-i/">496. Next Greater Element I</a></h2><h3>Easy</h3><hr><div><p>The <strong>next greater element</strong> of some element <code>x</code> in an array is the <strong>first greater</strong> element that is <strong>to the right</strong> of <code>x</code> in the same array.</p>

        stack = []
        dic = {}
        ans = []
            else:
        return ans
        
<p>You are given two <strong>distinct 0-indexed</strong> integer arrays <code>nums1</code> and <code>nums2</code>, where <code>nums1</code> is a subset of <code>nums2</code>.</p>

<p>For each <code>0 &lt;= i &lt; nums1.length</code>, find the index <code>j</code> such that <code>nums1[i] == nums2[j]</code> and determine the <strong>next greater element</strong> of <code>nums2[j]</code> in <code>nums2</code>. If there is no next greater element, then the answer for this query is <code>-1</code>.</p>

<p>Return <em>an array </em><code>ans</code><em> of length </em><code>nums1.length</code><em> such that </em><code>ans[i]</code><em> is the <strong>next greater element</strong> as described above.</em></p>

<pre><strong>Input:</strong> nums1 = [4,1,2], nums2 = [1,3,4,2]
<strong>Output:</strong> [-1,3,-1]
<strong>Explanation:</strong> The next greater element for each value of nums1 is as follows:
- 4 is underlined in nums2 = [1,3,<u>4</u>,2]. There is no next greater element, so the answer is -1.
- 1 is underlined in nums2 = [<u>1</u>,3,4,2]. The next greater element is 3.
- 2 is underlined in nums2 = [1,3,4,<u>2</u>]. There is no next greater element, so the answer is -1.
</pre>

<pre><strong>Input:</strong> nums1 = [2,4], nums2 = [1,2,3,4]
<strong>Output:</strong> [3,-1]
- 2 is underlined in nums2 = [1,<u>2</u>,3,4]. The next greater element is 3.
- 4 is underlined in nums2 = [1,2,3,<u>4</u>]. There is no next greater element, so the answer is -1.
</pre>

<ul>
	<li><code>1 &lt;= nums1.length &lt;= nums2.length &lt;= 1000</code></li>
	<li><code>0 &lt;= nums1[i], nums2[i] &lt;= 10<sup>4</sup></code></li>
	<li>All integers in <code>nums1</code> and <code>nums2</code> are <strong>unique</strong>.</li>
	<li>All the integers of <code>nums1</code> also appear in <code>nums2</code>.</li>
</ul>

<strong>Follow up:</strong> Could you find an <code>O(nums1.length + nums2.length)</code> solution?</div>

directory: 2-add-two-numbers
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        
        def recursion(root):
            if not root.next:
            return recursion(root.next) * 10 + root.val
        
        def int_to_linked_list(num: int):
            root = ListNode(num % 10)
            p = root
            while num > 0:
                p.next = ListNode(num % 10)
                num = num // 10
                p = p.next
            
        num1 = recursion(l1)
        num2 = recursion(l2)
        
        return int_to_linked_list(num1 + num2)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/add-two-numbers/">2. Add Two Numbers</a></h2><h3>Medium</h3><hr><div><p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The digits are stored in <strong>reverse order</strong>, and each of their nodes contains a single digit. Add the two numbers and return the sum&nbsp;as a linked list.</p>

            p = root
                p = p.next
            
<p>You may assume the two numbers do not contain any leading zero, except the number 0 itself.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/02/addtwonumber1.jpg" style="width: 483px; height: 342px;">
<pre><strong>Input:</strong> l1 = [2,4,3], l2 = [5,6,4]
<strong>Output:</strong> [7,0,8]
<strong>Explanation:</strong> 342 + 465 = 807.
</pre>

<pre><strong>Input:</strong> l1 = [0], l2 = [0]
</pre>

<pre><strong>Input:</strong> l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
<strong>Output:</strong> [8,9,9,9,0,0,0,1]
</pre>

<ul>
	<li>The number of nodes in each linked list is in the range <code>[1, 100]</code>.</li>
	<li><code>0 &lt;= Node.val &lt;= 9</code></li>
	<li>It is guaranteed that the list represents a number that does not have leading zeros.</li>
</ul>
</div>

directory: 1029-two-city-scheduling
    def twoCitySchedCost(self, costs: List[List[int]]) -> int:
        
        costs.sort(key = lambda x : x[0] - x[1])
        n = len(costs)
        ans = 0
        for i, x in enumerate(costs):
            if i < n // 2:
                ans += x[0]
            else:
                ans += x[1]
        return ans
Notes: Algorithm
​
Now the algorithm is straightforward :
​
Sort the persons in the ascending order by price_A - price_B parameter, which indicates the company additional costs.
​
To minimise the costs, send n persons with the smallest price_A - price_B to the city A, and the others to the city B.
Readme: <h2><a href="https://leetcode.com/problems/two-city-scheduling/">1029. Two City Scheduling</a></h2><h3>Medium</h3><hr><div><p>A company is planning to interview <code>2n</code> people. Given the array <code>costs</code> where <code>costs[i] = [aCost<sub>i</sub>, bCost<sub>i</sub>]</code>,&nbsp;the cost of flying the <code>i<sup>th</sup></code> person to city <code>a</code> is <code>aCost<sub>i</sub></code>, and the cost of flying the <code>i<sup>th</sup></code> person to city <code>b</code> is <code>bCost<sub>i</sub></code>.</p>

        ans = 0
            if i < n // 2:
                ans += x[0]
            else:
                ans += x[1]
        return ans

<p>Return <em>the minimum cost to fly every person to a city</em> such that exactly <code>n</code> people arrive in each city.</p>

<pre><strong>Input:</strong> costs = [[10,20],[30,200],[400,50],[30,20]]
<strong>Explanation: </strong>
The first person goes to city A for a cost of 10.
The second person goes to city A for a cost of 30.
The third person goes to city B for a cost of 50.
The fourth person goes to city B for a cost of 20.

The total minimum cost is 10 + 30 + 50 + 20 = 110 to have half the people interviewing in each city.
</pre>

<pre><strong>Input:</strong> costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]]
<strong>Output:</strong> 1859
</pre>

<pre><strong>Input:</strong> costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]]
<strong>Output:</strong> 3086
</pre>

<ul>
	<li><code>2 * n == costs.length</code></li>
	<li><code>2 &lt;= costs.length &lt;= 100</code></li>
	<li><code>costs.length</code> is even.</li>
	<li><code>1 &lt;= aCost<sub>i</sub>, bCost<sub>i</sub> &lt;= 1000</code></li>
</ul>
</div>

directory: 692-top-k-frequent-words
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        dic = {}
        count = sorted(Counter(words).items(), key = lambda x : x[1], reverse = True)
        #print(count)
        return [val for val, c in count[:k]]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/top-k-frequent-words/">692. Top K Frequent Words</a></h2><h3>Medium</h3><hr><div><p>Given an array of strings <code>words</code> and an integer <code>k</code>, return <em>the </em><code>k</code><em> most frequent strings</em>.</p>

<p>Return the answer <strong>sorted</strong> by <strong>the frequency</strong> from highest to lowest. Sort the words with the same frequency by their <strong>lexicographical order</strong>.</p>

        dic = {}

<pre><strong>Input:</strong> words = ["i","love","leetcode","i","love","coding"], k = 2
<strong>Output:</strong> ["i","love"]
<strong>Explanation:</strong> "i" and "love" are the two most frequent words.
Note that "i" comes before "love" due to a lower alphabetical order.
</pre>

<pre><strong>Input:</strong> words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
<strong>Output:</strong> ["the","is","sunny","day"]
<strong>Explanation:</strong> "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively.
</pre>

<ul>
	<li><code>1 &lt;= words.length &lt;= 500</code></li>
	<li><code>1 &lt;= words[i] &lt;= 10</code></li>
	<li><code>k</code> is in the range <code>[1, The number of <strong>unique</strong> words[i]]</code></li>
</ul>

<p><strong>Follow-up:</strong> Could you solve it in <code>O(n log(k))</code> time and <code>O(n)</code> extra space?</p>
</div>

directory: 484-find-permutation
    def findPermutation(self, s: str) -> List[int]:
        stk, ans = [], []
            stk.append(i+1)
            if s[i]=='I': 
                while stk: ans.append(stk.pop())
        stk.append(len(s)+1)
        while stk: ans.append(stk.pop())
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-permutation/">484. Find Permutation</a></h2><h3>Medium</h3><hr><div><p>A permutation <code>perm</code> of <code>n</code>&nbsp;integers of all the integers in the range <code>[1, n]</code> can be represented as a string <code>s</code> of length <code>n - 1</code> where:</p>

<ul>
	<li><code>s[i] == 'I'</code> if <code>perm[i] &lt; perm[i + 1]</code>, and</li>
	<li><code>s[i] == 'D'</code> if <code>perm[i] &gt; perm[i + 1]</code>.</li>
</ul>

<p>Given a string <code>s</code>, reconstruct the lexicographically smallest permutation <code>perm</code> and return it.</p>

        return ans

<pre><strong>Input:</strong> s = "I"
<strong>Explanation:</strong> [1,2] is the only legal permutation that can represented by s, where the number 1 and 2 construct an increasing relationship.
</pre>

<pre><strong>Input:</strong> s = "DI"
<strong>Explanation:</strong> Both [2,1,3] and [3,1,2] can be represented as "DI", but since we want to find the smallest lexicographical permutation, you should return [2,1,3]
</pre>

<ul>
	<li><code>s[i]</code> is either <code>'I'</code> or <code>'D'</code>.</li>
</ul>
</div>

directory: 168-excel-sheet-column-title
    def convertToTitle(self, columnNumber: int) -> str:
        res = ""
        while columnNumber > 0:
            output = (columnNumber - 1) % 26
            res += chr(ord('A') + output)
            columnNumber = (columnNumber - 1) // 26
        return res[::-1]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/excel-sheet-column-title/">168. Excel Sheet Column Title</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>columnNumber</code>, return <em>its corresponding column title as it appears in an Excel sheet</em>.</p>

<p>For example:</p>

<pre>A -&gt; 1
B -&gt; 2
C -&gt; 3
...
Z -&gt; 26
AA -&gt; 27
AB -&gt; 28 
...
</pre>

<pre><strong>Input:</strong> columnNumber = 1
<strong>Output:</strong> "A"
</pre>

<pre><strong>Input:</strong> columnNumber = 28
<strong>Output:</strong> "AB"
</pre>

        res = ""

<pre><strong>Input:</strong> columnNumber = 701
<strong>Output:</strong> "ZY"
</pre>

<ul>
	<li><code>1 &lt;= columnNumber &lt;= 2<sup>31</sup> - 1</code></li>
</ul>
</div>

directory: 704-binary-search
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-search/">704. Binary Search</a></h2><h3>Easy</h3><hr><div><p>Given an array of integers <code>nums</code> which is sorted in ascending order, and an integer <code>target</code>, write a function to search <code>target</code> in <code>nums</code>. If <code>target</code> exists, then return its index. Otherwise, return <code>-1</code>.</p>

<pre><strong>Input:</strong> nums = [-1,0,3,5,9,12], target = 9
<strong>Explanation:</strong> 9 exists in nums and its index is 4
</pre>

<pre><strong>Input:</strong> nums = [-1,0,3,5,9,12], target = 2
<strong>Explanation:</strong> 2 does not exist in nums so return -1
</pre>

<ul>
	<li><code>-10<sup>4</sup> &lt; nums[i], target &lt; 10<sup>4</sup></code></li>
	<li>All the integers in <code>nums</code> are <strong>unique</strong>.</li>
	<li><code>nums</code> is sorted in ascending order.</li>
</ul>
</div>

directory: 1833-maximum-ice-cream-bars
    def maxIceCream(self, costs: List[int], coins: int) -> int:
        
        costs.sort()
        ans = 0
        spent = 0
        for c in costs:
            if spent + c <= coins:
                spent += c
                ans += 1
            if spent == coins:
                return ans 
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-ice-cream-bars/">1833. Maximum Ice Cream Bars</a></h2><h3>Medium</h3><hr><div><p>It is a sweltering summer day, and a boy wants to buy some ice cream bars.</p>

<p>At the store, there are <code>n</code> ice cream bars. You are given an array <code>costs</code> of length <code>n</code>, where <code>costs[i]</code> is the price of the <code>i<sup>th</sup></code> ice cream bar in coins. The boy initially has <code>coins</code> coins to spend, and he wants to buy as many ice cream bars as possible.&nbsp;</p>

        ans = 0
        spent = 0
                spent += c
                ans += 1
                return ans 
        return ans
        
<p>Return <em>the <strong>maximum</strong> number of ice cream bars the boy can buy with </em><code>coins</code><em> coins.</em></p>

<p><strong>Note:</strong> The boy can buy the ice cream bars in any order.</p>

<pre><strong>Input:</strong> costs = [1,3,2,4,1], coins = 7
<strong>Explanation: </strong>The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
</pre>

<pre><strong>Input:</strong> costs = [10,6,8,7,7,8], coins = 5
<strong>Explanation: </strong>The boy cannot afford any of the ice cream bars.
</pre>

<pre><strong>Input:</strong> costs = [1,6,3,1,2,5], coins = 20
<strong>Explanation: </strong>The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
</pre>

<ul>
	<li><code>costs.length == n</code></li>
	<li><code>1 &lt;= costs[i] &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= coins &lt;= 10<sup>8</sup></code></li>

directory: 0387-first-unique-character-in-a-string
    def firstUniqChar(self, s: str) -> int:
        
        arr = [0] * 26
        
        for c in s:
            arr[ord(c) - ord('a')] += 1
            if arr[ord(c) - ord('a')] == 1:
                return i
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/first-unique-character-in-a-string/">387. First Unique Character in a String</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>s</code>, <em>find the first non-repeating character in it and return its index</em>. If it does not exist, return <code>-1</code>.</p>

        for c in s:
                return i
        return -1

<pre><strong>Input:</strong> s = "loveleetcode"
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> s = "aabb"
</pre>

<ul>
	<li><code>s</code> consists of only lowercase English letters.</li>
</ul>
</div>

directory: 99-recover-binary-search-tree
    def recoverTree(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        
        self.temp = []
        
            if root:
                dfs(root.left)
                self.temp.append(root)
                dfs(root.right)
        dfs(root)
        srt = sorted(node.val for node in self.temp)
        for i in range(len(srt)):
            self.temp[i].val = srt[i]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/recover-binary-search-tree/">99. Recover Binary Search Tree</a></h2><h3>Medium</h3><hr><div><p>You are given the <code>root</code> of a binary search tree (BST), where the values of <strong>exactly</strong> two nodes of the tree were swapped by mistake. <em>Recover the tree without changing its structure</em>.</p>

        """
        """
        
            if root:
        dfs(root)
            
<img alt="" src="https://assets.leetcode.com/uploads/2020/10/28/recover1.jpg" style="width: 422px; height: 302px;">
<pre><strong>Input:</strong> root = [1,3,null,null,2]
<strong>Output:</strong> [3,1,null,null,2]
<strong>Explanation:</strong> 3 cannot be a left child of 1 because 3 &gt; 1. Swapping 1 and 3 makes the BST valid.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/28/recover2.jpg" style="width: 581px; height: 302px;">
<pre><strong>Input:</strong> root = [3,1,4,null,null,2]
<strong>Output:</strong> [2,1,4,null,null,3]
<strong>Explanation:</strong> 2 cannot be in the right subtree of 3 because 2 &lt; 3. Swapping 2 and 3 makes the BST valid.
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[2, 1000]</code>.</li>
</ul>

<strong>Follow up:</strong> A solution using <code>O(n)</code> space is pretty straight-forward. Could you devise a constant <code>O(1)</code> space solution?</div>

directory: 863-all-nodes-distance-k-in-binary-tree

    def distanceK(self, root: TreeNode, target: TreeNode, k: int) -> List[int]:
        def dfs(root, par):
            if root:
                root.par = par
                    dfs(root.left, root)
                    dfs(root.right, root)
        dfs(root, None)
        queue = deque([(target, 0)])
        seen.add(target)
        ans = []
            node, dist = queue.popleft()
            if dist == k:
                ans.append(node.val)
            for nei in (node.left, node.right, node.par):
                if nei and nei not in seen:
                    seen.add(nei)
                    queue.append((nei, dist + 1))
                    
        return ans

            if root:
        ans = []
                    
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/">863. All Nodes Distance K in Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, the value of a target node <code>target</code>, and an integer <code>k</code>, return <em>an array of the values of all nodes that have a distance </em><code>k</code><em> from the target node.</em></p>

<p>You can return the answer in <strong>any order</strong>.</p>

<img alt="" src="https://s3-lc-upload.s3.amazonaws.com/uploads/2018/06/28/sketch0.png" style="width: 500px; height: 429px;">
<pre><strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, k = 2
<strong>Output:</strong> [7,4,1]
Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
</pre>

<pre><strong>Input:</strong> root = [1], target = 1, k = 3
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 500]</code>.</li>
	<li><code>0 &lt;= Node.val &lt;= 500</code></li>
	<li>All the values <code>Node.val</code> are <strong>unique</strong>.</li>
	<li><code>target</code> is the value of one of the nodes in the tree.</li>
	<li><code>0 &lt;= k &lt;= 1000</code></li>
</ul>
</div>

directory: 141-linked-list-cycle
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/linked-list-cycle/">141. Linked List Cycle</a></h2><h3>Easy</h3><hr><div><p>Given <code>head</code>, the head of a linked list, determine if the linked list has a cycle in it.</p>

<p>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&nbsp;<code>next</code>&nbsp;pointer. Internally, <code>pos</code>&nbsp;is used to denote the index of the node that&nbsp;tail's&nbsp;<code>next</code>&nbsp;pointer is connected to.&nbsp;<strong>Note that&nbsp;<code>pos</code>&nbsp;is not passed as a parameter</strong>.</p>

<p>Return&nbsp;<code>true</code><em> if there is a cycle in the linked list</em>. Otherwise, return <code>false</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist.png" style="width: 300px; height: 97px; margin-top: 8px; margin-bottom: 8px;">
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test2.png" style="width: 141px; height: 74px;">
<strong>Explanation:</strong> There is a cycle in the linked list, where the tail connects to the 0th node.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/07/circularlinkedlist_test3.png" style="width: 45px; height: 45px;">
</pre>

<ul>
</ul>

</div>

directory: 584-find-customer-referee
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-customer-referee/">584. Find Customer Referee</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Customer</code></p>

| id          | int     |
| referee_id  | int     |
Each row of this table indicates the id of a customer, their name, and the id of the customer who referred them.
</pre>

<p>Write an SQL query to report the IDs of the customer that are <strong>not referred by</strong> the customer with <code>id = 2</code>.</p>

Customer table:
+----+------+------------+
| id | name | referee_id |
| 1  | Will | null       |
| 2  | Jane | null       |
| 3  | Alex | 2          |
| 4  | Bill | null       |
| 5  | Zack | 1          |
| 6  | Mark | 2          |
+------+
| name |
+------+
| Will |
| Jane |
| Bill |
| Zack |
+------+
</pre>
</div>

directory: 815-bus-routes
    def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int:
        
        # Base Case
        if source == target:
            return 0
        
        # Creating graph or routes
        graph = defaultdict(set)
        
        # Since index represents bus_number on a route, suppose i is the bus number 
        # and stops are the values present at that index
        
        for bus_number, stops in enumerate(routes):
            #print(bus_number, stops)
            for stop in stops:
                graph[stop].add(bus_number)
        #print(graph)
        
        #Using BFS
        bfs = deque([(source, 0)])
        
        # Visited Stops
        seen_stops = set()
        
        #Visited Buses
        seen_buses = set()
        
        while bfs:
            stop, count = bfs.popleft()
            if stop == target:
                return count
            
            for bus_number in graph[stop]:
                if bus_number not in seen_buses:
                    seen_buses.add(bus_number)
                    
                    for stop in routes[bus_number]:
                        if stop not in seen_stops:
                            seen_stops.add(stop)
                            bfs.append((stop, count + 1))
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/bus-routes/">815. Bus Routes</a></h2><h3>Hard</h3><hr><div><p>You are given an array <code>routes</code> representing bus routes where <code>routes[i]</code> is a bus route that the <code>i<sup>th</sup></code> bus repeats forever.</p>

        # Base Case
            return 0
        
        #Using BFS
        
        while bfs:
            
        return -1

<ul>
	<li>For example, if <code>routes[0] = [1, 5, 7]</code>, this means that the <code>0<sup>th</sup></code> bus travels in the sequence <code>1 -&gt; 5 -&gt; 7 -&gt; 1 -&gt; 5 -&gt; 7 -&gt; 1 -&gt; ...</code> forever.</li>
</ul>

<p>You will start at the bus stop <code>source</code> (You are not on any bus initially), and you want to go to the bus stop <code>target</code>. You can travel between bus stops by buses only.</p>

<p>Return <em>the least number of buses you must take to travel from </em><code>source</code><em> to </em><code>target</code>. Return <code>-1</code> if it is not possible.</p>

<pre><strong>Input:</strong> routes = [[1,2,7],[3,6,7]], source = 1, target = 6
<strong>Explanation:</strong> The best strategy is take the first bus to the bus stop 7, then take the second bus to the bus stop 6.
</pre>

<pre><strong>Input:</strong> routes = [[7,12],[4,5,15],[6],[15,19],[9,12,13]], source = 15, target = 12
</pre>

<ul>
	<li><code>1 &lt;= routes.length &lt;= 500</code>.</li>
	<li><code>1 &lt;= routes[i].length &lt;= 10<sup>5</sup></code></li>
	<li>All the values of <code>routes[i]</code> are <strong>unique</strong>.</li>
	<li><code>sum(routes[i].length) &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= routes[i][j] &lt; 10<sup>6</sup></code></li>
	<li><code>0 &lt;= source, target &lt; 10<sup>6</sup></code></li>
</ul>
</div>

directory: 535-encode-and-decode-tinyurl
        self.dic = dict()
        self.counter = 0
    def encode(self, longUrl: str) -> str:
        """Encodes a URL to a shortened URL.
        """
        self.dic[self.counter] = longUrl
        self.counter+=1
        print(self.dic)
        return 'http://tinyurl.com/' + str(self.counter-1)
    
    def decode(self, shortUrl: str) -> str:
        """Decodes a shortened URL to its original URL.
        """
        index = shortUrl.split('/')[-1]
        return self.dic[int(index)]

        """
    
        """
        
# codec.decode(codec.encode(url))

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/encode-and-decode-tinyurl/">535. Encode and Decode TinyURL</a></h2><h3>Medium</h3><hr><div><blockquote>Note: This is a companion problem to the <a href="https://leetcode.com/discuss/interview-question/system-design/" target="_blank">System Design</a> problem: <a href="https://leetcode.com/discuss/interview-question/124658/Design-a-URL-Shortener-(-TinyURL-)-System/" target="_blank">Design TinyURL</a>.</blockquote>

<p>TinyURL is a URL shortening service where you enter a URL such as <code>https://leetcode.com/problems/design-tinyurl</code> and it returns a short URL such as <code>http://tinyurl.com/4e9iAk</code>. Design a class to encode a URL and decode a tiny URL.</p>

<p>There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL.</p>

<p>Implement the <code>Solution</code> class:</p>

<ul>
	<li><code>Solution()</code> Initializes the object of the system.</li>
	<li><code>String encode(String longUrl)</code> Returns a tiny URL for the given <code>longUrl</code>.</li>
	<li><code>String decode(String shortUrl)</code> Returns the original long URL for the given <code>shortUrl</code>. It is guaranteed that the given <code>shortUrl</code> was encoded by the same object.</li>
</ul>

<pre><strong>Input:</strong> url = "https://leetcode.com/problems/design-tinyurl"
<strong>Output:</strong> "https://leetcode.com/problems/design-tinyurl"

Solution obj = new Solution();
string tiny = obj.encode(url); // returns the encoded tiny url.
string ans = obj.decode(tiny); // returns the original url after deconding it.
</pre>

<ul>
	<li><code>1 &lt;= url.length &lt;= 10<sup>4</sup></code></li>
	<li><code>url</code> is guranteed to be a valid URL.</li>
</ul>
</div>

directory: 1740-find-distance-in-a-binary-tree
    def findDistance(self, root: Optional[TreeNode], p: int, q: int) -> int:
        def lca(root, p, q):
            if root.val == p or root.val == q:
            left = lca(root.left, p, q)
            right = lca(root.right, p, q)
            
            return left or right
        
        def find(root, node):
            if root == None:
                return -1
            distance = -1
            if root.val == node:
                return distance + 1
            else:
                distance = find(root.left, node)
                if distance >= 0:
                    return distance + 1
                else:
                    distance = find(root.right, node)
                    if distance >= 0:
                        return distance + 1
            return distance
                
        root1 = lca(root, p, q)
        print(root1.val)
        
        dist1 = find(root1, p)
        dist2 = find(root1, q)
        
        return dist1 + dist2
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/find-distance-in-a-binary-tree/">1740. Find Distance in a Binary Tree</a></h2><h3>Medium</h3><hr><div><p>Given the root of a binary tree and two integers <code>p</code> and <code>q</code>, return <em>the <strong>distance</strong> between the nodes of value </em><code>p</code><em> and value </em><code>q</code><em> in the tree</em>.</p>

                return -1
            else:
                else:
                
<p>The <strong>distance</strong> between two nodes is the number of edges on the path from one to the other.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2018/12/14/binarytree.png">
<pre><strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 0
<strong>Explanation:</strong> There are 3 edges between 5 and 0: 5-3-1-0.</pre>

<pre><strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 7
<strong>Explanation:</strong> There are 2 edges between 5 and 7: 5-2-7.</pre>

<pre><strong>Input:</strong> root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 5
<strong>Explanation:</strong> The distance between a node and itself is 0.</pre>

<ul>
	<li><code>0 &lt;= Node.val &lt;= 10<sup>9</sup></code></li>
	<li><code>p</code> and <code>q</code> are values in the tree.</li>
</ul>
</div>

directory: 523-continuous-subarray-sum
        
        prefix = 0
        dic = {0 : 0}
            prefix += num
            if prefix % k not in dic:
                dic[prefix % k] = i + 1
            elif dic[prefix % k] < i:
Notes: ​

        prefix = 0
        dic = {0 : 0}
        
</pre>

</pre>

</pre>

<ul>
</ul>
</div>

directory: 942-di-string-match
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/di-string-match/">942. DI String Match</a></h2><h3>Easy</h3><hr><div><p>A permutation <code>perm</code> of <code>n + 1</code> integers of all the integers in the range <code>[0, n]</code> can be represented as a string <code>s</code> of length <code>n</code> where:</p>

<ul>
</ul>

<p>Given a string <code>s</code>, reconstruct the permutation <code>perm</code> and return it. If there are multiple valid permutations perm, return <strong>any of them</strong>.</p>

<pre><strong>Input:</strong> s = "IDID"
<strong>Output:</strong> [0,4,1,3,2]
<pre><strong>Input:</strong> s = "III"
<pre><strong>Input:</strong> s = "DDI"
<strong>Output:</strong> [3,2,0,1]
</pre>

<ul>
</ul>
</div>

directory: 40-combination-sum-ii
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        
        candidates.sort()
        output = []
        def backtrack(path, index, target):
            if target == 0:
                output.append(path[:])
            for i in range(index, len(candidates)):
                if i > index and candidates[i] == candidates[i-1]:
                    continue
                if candidates[i] > target: break
                backtrack(path + [candidates[i]] , i+1,  target - candidates[i])

        output = []
                    continue

        backtrack([], 0, target)
            
backtrack([], 0, target)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/combination-sum-ii/">40. Combination Sum II</a></h2><h3>Medium</h3><hr><div><p>Given a collection of candidate numbers (<code>candidates</code>) and a target number (<code>target</code>), find all unique combinations in <code>candidates</code>&nbsp;where the candidate numbers sum to <code>target</code>.</p>

<p>Each number in <code>candidates</code>&nbsp;may only be used <strong>once</strong> in the combination.</p>

<p><strong>Note:</strong>&nbsp;The solution set must not contain duplicate combinations.</p>

<pre><strong>Input:</strong> candidates = [10,1,2,7,6,1,5], target = 8
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
</pre>

<pre><strong>Input:</strong> candidates = [2,5,2,1,2], target = 5
[
[1,2,2],
[5]
]
</pre>

<ul>
	<li><code>1 &lt;=&nbsp;candidates.length &lt;= 100</code></li>
	<li><code>1 &lt;=&nbsp;candidates[i] &lt;= 50</code></li>
	<li><code>1 &lt;= target &lt;= 30</code></li>
</ul>
</div>

directory: 814-binary-tree-pruning
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        
            if root is None:
            
            left = dfs(root.left)
            right = dfs(root.right)
            
            if not left:
                root.left = None
            if not right:
                root.right = None
            
            return root.val or left or right
        
        return root if dfs(root) else None
Notes: ​
Readme:

directory: 2385-amount-of-time-for-binary-tree-to-be-infected
    def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
        self.start = None
        def dfs(root, par = None):
            if root:
                if root.val == start:
                    self.start = root
                dfs(root.left, root)
                dfs(root.right, root)
        
        dfs(root)
        seen = {start}
        queue = deque([(self.start, 0)])
            root, distance = queue.popleft()
            for nei in (root.left, root.right, root.par):
                if nei and nei.val not in seen:
                    seen.add(nei.val)
                    queue.append((nei, distance + 1))
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/amount-of-time-for-binary-tree-to-be-infected/">2385. Amount of Time for Binary Tree to Be Infected</a></h2><h3>Medium</h3><hr><div><p>You are given the <code>root</code> of a binary tree with <strong>unique</strong> values, and an integer <code>start</code>. At minute <code>0</code>, an <strong>infection</strong> starts from the node with value <code>start</code>.</p>

            if root:
        
        dfs(root)

<p>Each minute, a node becomes infected if:</p>

<ul>
	<li>The node is currently uninfected.</li>
	<li>The node is adjacent to an infected node.</li>
</ul>

<p>Return <em>the number of minutes needed for the entire tree to be infected.</em></p>

<img alt="" src="https://assets.leetcode.com/uploads/2022/06/25/image-20220625231744-1.png" style="width: 400px; height: 306px;">
<pre><strong>Input:</strong> root = [1,5,3,null,4,10,6,9,2], start = 3
<strong>Explanation:</strong> The following nodes are infected during:
- Minute 0: Node 3
- Minute 1: Nodes 1, 10 and 6
- Minute 2: Node 5
- Minute 3: Node 4
- Minute 4: Nodes 9 and 2
It takes 4 minutes for the whole tree to be infected so we return 4.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2022/06/25/image-20220625231812-2.png" style="width: 75px; height: 66px;">
<pre><strong>Input:</strong> root = [1], start = 1
<strong>Explanation:</strong> At minute 0, the only node in the tree is infected so we return 0.
</pre>

<ul>
	<li>A node with a value of <code>start</code> exists in the tree.</li>
</ul>
</div>

directory: 682-baseball-game
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/baseball-game/">682. Baseball Game</a></h2><h3>Easy</h3><hr><div><p>You are keeping score for a baseball game with strange rules. The game consists of several rounds, where the scores of past rounds may affect future rounds' scores.</p>

<p>At the beginning of the game, you start with an empty record. You are given a list of strings <code>ops</code>, where <code>ops[i]</code> is the <code>i<sup>th</sup></code> operation you must apply to the record and is one of the following:</p>

<ol>
	<li>An integer <code>x</code> - Record a new score of <code>x</code>.</li>
	<li><code>"+"</code> - Record a new score that is the sum of the previous two scores. It is guaranteed there will always be two previous scores.</li>
	<li><code>"D"</code> - Record a new score that is double the previous score. It is guaranteed there will always be a previous score.</li>
	<li><code>"C"</code> - Invalidate the previous score, removing it from the record. It is guaranteed there will always be a previous score.</li>
</ol>

<p>Return <em>the sum of all the scores on the record</em>.</p>

<pre><strong>Input:</strong> ops = ["5","2","C","D","+"]
"5" - Add 5 to the record, record is now [5].
"2" - Add 2 to the record, record is now [5, 2].
"C" - Invalidate and remove the previous score, record is now [5].
"D" - Add 2 * 5 = 10 to the record, record is now [5, 10].
"+" - Add 5 + 10 = 15 to the record, record is now [5, 10, 15].
The total sum is 5 + 10 + 15 = 30.
</pre>

<pre><strong>Input:</strong> ops = ["5","-2","4","C","D","9","+","+"]
"-2" - Add -2 to the record, record is now [5, -2].
"4" - Add 4 to the record, record is now [5, -2, 4].
"C" - Invalidate and remove the previous score, record is now [5, -2].
"D" - Add 2 * -2 = -4 to the record, record is now [5, -2, -4].
"9" - Add 9 to the record, record is now [5, -2, -4, 9].
"+" - Add -4 + 9 = 5 to the record, record is now [5, -2, -4, 9, 5].
"+" - Add 9 + 5 = 14 to the record, record is now [5, -2, -4, 9, 5, 14].
The total sum is 5 + -2 + -4 + 9 + 5 + 14 = 27.
</pre>

<pre><strong>Input:</strong> ops = ["1"]
</pre>

<ul>
	<li><code>1 &lt;= ops.length &lt;= 1000</code></li>
	<li><code>ops[i]</code> is <code>"C"</code>, <code>"D"</code>, <code>"+"</code>, or a string representing an integer in the range <code>[-3 * 10<sup>4</sup>, 3 * 10<sup>4</sup>]</code>.</li>
	<li>For operation <code>"+"</code>, there will always be at least two previous scores on the record.</li>
	<li>For operations <code>"C"</code> and <code>"D"</code>, there will always be at least one previous score on the record.</li>
</ul>
</div>

directory: 338-counting-bits
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/counting-bits/">338. Counting Bits</a></h2><h3>Easy</h3><hr><div><p>Given an integer <code>n</code>, return <em>an array </em><code>ans</code><em> of length </em><code>n + 1</code><em> such that for each </em><code>i</code><em> </em>(<code>0 &lt;= i &lt;= n</code>)<em>, </em><code>ans[i]</code><em> is the <strong>number of </strong></em><code>1</code><em><strong>'s</strong> in the binary representation of </em><code>i</code>.</p>

<strong>Output:</strong> [0,1,1]
0 --&gt; 0
1 --&gt; 1
2 --&gt; 10
</pre>

<pre><strong>Input:</strong> n = 5
<strong>Output:</strong> [0,1,1,2,1,2]
0 --&gt; 0
1 --&gt; 1
2 --&gt; 10
3 --&gt; 11
4 --&gt; 100
5 --&gt; 101
</pre>

<ul>
	<li><code>0 &lt;= n &lt;= 10<sup>5</sup></code></li>
</ul>

<ul>
	<li>It is very easy to come up with a solution with a runtime of <code>O(n log n)</code>. Can you do it in linear time <code>O(n)</code> and possibly in a single pass?</li>
	<li>Can you do it without using any built-in function (i.e., like <code>__builtin_popcount</code> in C++)?</li>
</ul>
</div>

directory: 1683-invalid-tweets
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/invalid-tweets/">1683. Invalid Tweets</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Tweets</code></p>

<pre>+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| tweet_id       | int     |
| content        | varchar |
tweet_id is the primary key for this table.
This table contains all the tweets in a social media app.
</pre>

<p>Write an SQL query to find the IDs of the invalid tweets. The tweet is invalid if the number of characters used in the content of the tweet is <strong>strictly greater</strong> than <code>15</code>.</p>

Tweets table:
+----------+----------------------------------+
| tweet_id | content                          |
| 1        | Vote for Biden                   |
| 2        | Let us make America great again! |
| tweet_id |
| 2        |
Tweet 1 has length = 14. It is a valid tweet.
Tweet 2 has length = 32. It is an invalid tweet.
</pre>
</div>

directory: 79-word-search
    def exist(self, board: List[List[str]], word: str) -> bool:
        
        rows, cols  = len(board), len(board[0])
        def backtrack(index, r, c):
            if r < 0 or c < 0 or  c >= cols or r >= rows or (r,c) in visited:
            if board[r][c] != word[index]:
            if index == len(word)-1:
            visited.add((r, c))
            one = backtrack(index + 1, r+1, c)
            two = backtrack(index + 1, r-1, c)
            three = backtrack(index + 1, r, c+1)
            four = backtrack(index + 1, r, c-1)
            visited.remove((r, c))
            return one or two or three or four
        
            for j in range(cols):
                if board[i][j] == word[0]:
                    if backtrack(0, i, j):
                        return True
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/word-search/">79. Word Search</a></h2><h3>Medium</h3><hr><div><p>Given an <code>m x n</code> grid of characters <code>board</code> and a string <code>word</code>, return <code>true</code> <em>if</em> <code>word</code> <em>exists in the grid</em>.</p>

<p>The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/04/word2.jpg" style="width: 322px; height: 242px;">
<pre><strong>Input:</strong> board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/04/word-1.jpg" style="width: 322px; height: 242px;">
<pre><strong>Input:</strong> board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/15/word3.jpg" style="width: 322px; height: 242px;">
<pre><strong>Input:</strong> board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
</pre>

<ul>
	<li><code>n = board[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 6</code></li>
	<li><code>1 &lt;= word.length &lt;= 15</code></li>
	<li><code>board</code> and <code>word</code> consists of only lowercase and uppercase English letters.</li>
</ul>

<p><strong>Follow up:</strong> Could you use search pruning to make your solution faster with a larger <code>board</code>?</p>
</div>

directory: 1658-minimum-operations-to-reduce-x-to-zero
    def minOperations(self, nums: List[int], x: int) -> int:
        
        total = sum(nums)
        maximum = -1
        start, current = 0, 0
        for end in range(n):
            current += nums[end]
            while current > total - x and start <= end:
                current -= nums[start]
                start += 1
            if current == total - x:
                maximum = max(maximum, end - start + 1)
        
        return n - maximum if maximum != -1 else -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/">1658. Minimum Operations to Reduce X to Zero</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code> and an integer <code>x</code>. In one operation, you can either remove the leftmost or the rightmost element from the array <code>nums</code> and subtract its value from <code>x</code>. Note that this <strong>modifies</strong> the array for future operations.</p>

                start += 1
        
<p>Return <em>the <strong>minimum number</strong> of operations to reduce </em><code>x</code> <em>to <strong>exactly</strong></em> <code>0</code> <em>if it is possible</em><em>, otherwise, return </em><code>-1</code>.</p>

<pre><strong>Input:</strong> nums = [1,1,4,2,3], x = 5
<strong>Explanation:</strong> The optimal solution is to remove the last two elements to reduce x to zero.
</pre>

<pre><strong>Input:</strong> nums = [5,6,7,8,9], x = 4
</pre>

<pre><strong>Input:</strong> nums = [3,2,20,1,1,3], x = 10
<strong>Explanation:</strong> The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
</pre>

<ul>
	<li><code>1 &lt;= x &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 362-design-hit-counter
Python: class HitCounter:

        self.dic = defaultdict(int)

    def hit(self, timestamp: int) -> None:
        
        self.dic[timestamp] += 1
        
    def getHits(self, timestamp: int) -> int:
        res = 0
        for time in self.dic:
            if time > timestamp - 300:
                res += self.dic[time]
        return res
        
# Your HitCounter object will be instantiated and called as such:
# obj = HitCounter()
# obj.hit(timestamp)
# param_2 = obj.getHits(timestamp)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/design-hit-counter/">362. Design Hit Counter</a></h2><h3>Medium</h3><hr><div><p>Design a hit counter which counts the number of hits received in the past <code>5</code> minutes (i.e., the past <code>300</code> seconds).</p>

class HitCounter:

        res = 0
        return res
        
<p>Your system should accept a <code>timestamp</code> parameter (<strong>in seconds</strong> granularity), and you may assume that calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing). Several hits may arrive roughly at the same time.</p>

<p>Implement the <code>HitCounter</code> class:</p>

<ul>
	<li><code>HitCounter()</code> Initializes the object of the hit counter system.</li>
	<li><code>void hit(int timestamp)</code> Records a hit that happened at <code>timestamp</code> (<strong>in seconds</strong>). Several hits may happen at the same <code>timestamp</code>.</li>
	<li><code>int getHits(int timestamp)</code> Returns the number of hits in the past 5 minutes from <code>timestamp</code> (i.e., the past <code>300</code> seconds).</li>
</ul>

["HitCounter", "hit", "hit", "hit", "getHits", "hit", "getHits", "getHits"]
[[], [1], [2], [3], [4], [300], [300], [301]]
[null, null, null, null, 3, null, 4, 3]

HitCounter hitCounter = new HitCounter();
hitCounter.hit(1);       // hit at timestamp 1.
hitCounter.hit(2);       // hit at timestamp 2.
hitCounter.hit(3);       // hit at timestamp 3.
hitCounter.getHits(4);   // get hits at timestamp 4, return 3.
hitCounter.hit(300);     // hit at timestamp 300.
hitCounter.getHits(300); // get hits at timestamp 300, return 4.
hitCounter.getHits(301); // get hits at timestamp 301, return 3.
</pre>

<ul>
	<li><code>1 &lt;= timestamp &lt;= 2 * 10<sup>9</sup></code></li>
	<li>All the calls are being made to the system in chronological order (i.e., <code>timestamp</code> is monotonically increasing).</li>
	<li>At most <code>300</code> calls will be made to <code>hit</code> and <code>getHits</code>.</li>
</ul>

<p><strong>Follow up:</strong> What if the number of hits per second could be huge? Does your design scale?</p>
</div>

directory: 526-beautiful-arrangement
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/beautiful-arrangement/">526. Beautiful Arrangement</a></h2><h3>Medium</h3><hr><div><p>Suppose you have <code>n</code> integers labeled <code>1</code> through <code>n</code>. A permutation of those <code>n</code> integers <code>perm</code> (<strong>1-indexed</strong>) is considered a <strong>beautiful arrangement</strong> if for every <code>i</code> (<code>1 &lt;= i &lt;= n</code>), <strong>either</strong> of the following is true:</p>

<ul>
	<li><code>perm[i]</code> is divisible by <code>i</code>.</li>
	<li><code>i</code> is divisible by <code>perm[i]</code>.</li>
</ul>

<p>Given an integer <code>n</code>, return <em>the <strong>number</strong> of the <strong>beautiful arrangements</strong> that you can construct</em>.</p>

<b>Explanation:</b> 
The first beautiful arrangement is [1,2]:
    - perm[1] = 1 is divisible by i = 1
    - perm[2] = 2 is divisible by i = 2
The second beautiful arrangement is [2,1]:
    - perm[1] = 2 is divisible by i = 1
    - i = 2 is divisible by perm[2] = 1
</pre>

</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 15</code></li>
</ul>
</div>

directory: 2214-minimum-health-to-beat-game
    def minimumHealth(self, damage: List[int], armor: int) -> int:
        
        health = 1
        maximum = float('-inf')
        for num in damage:
            health += num
            maximum = max(maximum, num)
        health -= min(armor, maximum)
        return health
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-health-to-beat-game/">2214. Minimum Health to Beat Game</a></h2><h3>Medium</h3><hr><div><p>You are playing a game that has <code>n</code> levels numbered from <code>0</code> to <code>n - 1</code>. You are given a <strong>0-indexed</strong> integer array <code>damage</code> where <code>damage[i]</code> is the amount of health you will lose to complete the <code>i<sup>th</sup></code> level.</p>

        health = 1

<p>You are also given an integer <code>armor</code>. You may use your armor ability <strong>at most once</strong> during the game on <strong>any</strong> level which will protect you from <strong>at most</strong> <code>armor</code> damage.</p>

<p>You must complete the levels in order and your health must be <strong>greater than</strong> <code>0</code> at all times to beat the game.</p>

<p>Return <em>the <strong>minimum</strong> health you need to start with to beat the game.</em></p>

<pre><strong>Input:</strong> damage = [2,7,4,3], armor = 4
<strong>Explanation:</strong> One optimal way to beat the game starting at 13 health is:
On round 1, take 2 damage. You have 13 - 2 = 11 health.
On round 2, take 7 damage. You have 11 - 7 = 4 health.
On round 3, use your armor to protect you from 4 damage. You have 4 - 0 = 4 health.
On round 4, take 3 damage. You have 4 - 3 = 1 health.
Note that 13 is the minimum health you need to start with to beat the game.
</pre>

<pre><strong>Input:</strong> damage = [2,5,3,4], armor = 7
<strong>Explanation:</strong> One optimal way to beat the game starting at 10 health is:
On round 1, take 2 damage. You have 10 - 2 = 8 health.
On round 2, use your armor to protect you from 5 damage. You have 8 - 0 = 8 health.
On round 3, take 3 damage. You have 8 - 3 = 5 health.
On round 4, take 4 damage. You have 5 - 4 = 1 health.
Note that 10 is the minimum health you need to start with to beat the game.
</pre>

<pre><strong>Input:</strong> damage = [3,3,3], armor = 0
On round 1, take 3 damage. You have 10 - 3 = 7 health.
On round 2, take 3 damage. You have 7 - 3 = 4 health.
On round 3, take 3 damage. You have 4 - 3 = 1 health.
Note that you did not use your armor ability.
</pre>

<ul>
	<li><code>n == damage.length</code></li>
	<li><code>0 &lt;= damage[i] &lt;= 10<sup>5</sup></code></li>
	<li><code>0 &lt;= armor &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 246-strobogrammatic-number
    def isStrobogrammatic(self, num: str) -> bool:
        
        dic = {"0" : "0", "1" : "1", "6" : "9", "8" : "8", "9":"6"}
        check = ''
            if n not in dic:
            check += dic[n]
        return check == num[::-1]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/strobogrammatic-number/">246. Strobogrammatic Number</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>num</code> which represents an integer, return <code>true</code> <em>if</em> <code>num</code> <em>is a <strong>strobogrammatic number</strong></em>.</p>

<pre><strong>Input:</strong> num = "69"
</pre>

        check = ''
        
<pre><strong>Input:</strong> num = "88"
</pre>

<pre><strong>Input:</strong> num = "962"
</pre>

<ul>
	<li><code>1 &lt;= num.length &lt;= 50</code></li>
	<li><code>num</code> does not contain any leading zeros except for zero itself.</li>
</ul>
</div>

directory: 991-broken-calculator
    def brokenCalc(self, startValue: int, target: int) -> int:
        
        if startValue >= target:
            return startValue - target
        elif target % 2 == 0:
            return 1 + self.brokenCalc(startValue, target // 2)
        else:
            return 1 + self.brokenCalc(startValue, target + 1)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/broken-calculator/">991. Broken Calculator</a></h2><h3>Medium</h3><hr><div><p>There is a broken calculator that has the integer <code>startValue</code> on its display initially. In one operation, you can:</p>

<ul>
	<li>multiply the number on display by <code>2</code>, or</li>
	<li>subtract <code>1</code> from the number on display.</li>
</ul>

<p>Given two integers <code>startValue</code> and <code>target</code>, return <em>the minimum number of operations needed to display </em><code>target</code><em> on the calculator</em>.</p>

        else:

<pre><strong>Input:</strong> startValue = 2, target = 3
<strong>Explanation:</strong> Use double operation and then decrement operation {2 -&gt; 4 -&gt; 3}.
</pre>

<pre><strong>Input:</strong> startValue = 5, target = 8
<strong>Explanation:</strong> Use decrement and then double {5 -&gt; 4 -&gt; 8}.
</pre>

<pre><strong>Input:</strong> startValue = 3, target = 10
<strong>Explanation:</strong> Use double, decrement and double {3 -&gt; 6 -&gt; 5 -&gt; 10}.
</pre>

<ul>
	<li><code>1 &lt;= startValue, target &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 298-binary-tree-longest-consecutive-sequence
        def dfs(root, parent, curr_value):
            if root:
                if parent:
                    if root.val == parent.val + 1:
                        curr_value += 1
                    else:
                        curr_value = 1
            self.longest = max(self.longest, curr_value)
                dfs(root.left, root, curr_value)
                dfs(root.right, root, curr_value)
        
        dfs(root, None, 1)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/">298. Binary Tree Longest Consecutive Sequence</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>the length of the longest consecutive sequence path</em>.</p>

            if root:
                if parent:
                    else:
        
<p>The path refers to any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The longest consecutive path needs to be from parent to child (cannot be the reverse).</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/consec1-1-tree.jpg" style="width: 322px; height: 421px;">
<pre><strong>Input:</strong> root = [1,null,3,2,4,null,null,null,5]
<strong>Explanation:</strong> Longest consecutive sequence path is 3-4-5, so return 3.
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/14/consec1-2-tree.jpg" style="width: 262px; height: 421px;">
<pre><strong>Input:</strong> root = [2,null,3,2,null,1]
<strong>Explanation:</strong> Longest consecutive sequence path is 2-3, not 3-2-1, so return 2.
</pre>

<ul>
</ul>
</div>

directory: 1239-maximum-length-of-a-concatenated-string-with-unique-characters
    def maxLength(self, arr: List[str]) -> int:
        max_len = 0
        def backtrack(index, path):
            nonlocal max_len
            if index >= len(arr):
                if len(set(path)) == len(path):
                    max_len = max(max_len, len(path))
                return
            backtrack(index + 1, path + arr[index])
            backtrack(index + 1, path)
        
        backtrack(0, "")
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters/">1239. Maximum Length of a Concatenated String with Unique Characters</a></h2><h3>Medium</h3><hr><div><p>You are given an array of strings <code>arr</code>. A string <code>s</code> is formed by the <strong>concatenation</strong> of a <strong>subsequence</strong> of <code>arr</code> that has <strong>unique characters</strong>.</p>

        max_len = 0
                return
        
<p>Return <em>the <strong>maximum</strong> possible length</em> of <code>s</code>.</p>

<p>A <strong>subsequence</strong> is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.</p>

<pre><strong>Input:</strong> arr = ["un","iq","ue"]
<strong>Explanation:</strong> All the valid concatenations are:
- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")
Maximum length is 4.
</pre>

<pre><strong>Input:</strong> arr = ["cha","r","act","ers"]
<strong>Explanation:</strong> Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
</pre>

<pre><strong>Input:</strong> arr = ["abcdefghijklmnopqrstuvwxyz"]
<strong>Output:</strong> 26
<strong>Explanation:</strong> The only string in arr has all 26 characters.
</pre>

<ul>
	<li><code>1 &lt;= arr.length &lt;= 16</code></li>
	<li><code>1 &lt;= arr[i].length &lt;= 26</code></li>
	<li><code>arr[i]</code> contains only lowercase English letters.</li>
</ul>
</div>

directory: 175-combine-two-tables
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/combine-two-tables/">175. Combine Two Tables</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Person</code></p>

| personId    | int     |
| lastName    | varchar |
| firstName   | varchar |
personId is the primary key column for this table.
This table contains information about the ID of some persons and their first and last names.
</pre>

<p>Table: <code>Address</code></p>

| addressId   | int     |
| city        | varchar |
| state       | varchar |
addressId is the primary key column for this table.
Each row of this table contains information about the city and state of one person with ID = PersonId.
</pre>

<p>Write an SQL query to report the first name, last name, city, and state of each person in the <code>Person</code> table. If the address of a <code>personId</code> is not present in the <code>Address</code> table, report <code>null</code> instead.</p>

+----------+----------+-----------+
| personId | lastName | firstName |
| 1        | Wang     | Allen     |
| 2        | Alice    | Bob       |
Address table:
+-----------+----------+---------------+------------+
| addressId | personId | city          | state      |
| 1         | 2        | New York City | New York   |
| 2         | 3        | Leetcode      | California |
+-----------+----------+---------------+----------+
| firstName | lastName | city          | state    |
| Allen     | Wang     | Null          | Null     |
| Bob       | Alice    | New York City | New York |
There is no address in the address table for the personId = 1 so we return null in their city and state.
addressId = 1 contains information about the address of personId = 2.
</pre>
</div>

directory: 128-longest-consecutive-sequence
    def longestConsecutive(self, nums: List[int]) -> int:
        
        longest_streak = 0
        num_set = set(nums)
        
        for num in num_set:
            
            if num - 1 not in num_set:
                current_num = num
                current_streak = 1
                
                while current_num + 1 in num_set:
                    current_streak += 1
                    current_num += 1
                longest_streak = max(longest_streak, current_streak)
        
        return longest_streak
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/longest-consecutive-sequence/">128. Longest Consecutive Sequence</a></h2><h3>Medium</h3><hr><div><p>Given an unsorted array of integers <code>nums</code>, return <em>the length of the longest consecutive elements sequence.</em></p>

<p>You must write an algorithm that runs in&nbsp;<code>O(n)</code>&nbsp;time.</p>

<pre><strong>Input:</strong> nums = [100,4,200,1,3,2]
<strong>Explanation:</strong> The longest consecutive elements sequence is <code>[1, 2, 3, 4]</code>. Therefore its length is 4.
</pre>

<pre><strong>Input:</strong> nums = [0,3,7,2,5,8,4,6,0,1]
</pre>

<ul>
</ul>
</div>

directory: 948-bag-of-tokens
    def bagOfTokensScore(self, tokens: List[int], power: int) -> int:
        
        score = 0
        tokens.sort()
        ans = 0
        l, r = 0, len(tokens)-1
        while r >= l:
            if power >= tokens[l]:
                power -= tokens[l]
                score += 1
                ans = max(score, ans)
                l += 1
            elif score > 0:
                score -= 1
                power += tokens[r]
                r-=1
            else:
                return score
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/bag-of-tokens/">948. Bag of Tokens</a></h2><h3>Medium</h3><hr><div><p>You have an initial <strong>power</strong> of <code>power</code>, an initial <strong>score</strong> of <code>0</code>, and a bag of <code>tokens</code> where <code>tokens[i]</code> is the value of the <code>i<sup>th</sup></code> token (0-indexed).</p>

        score = 0
        ans = 0
                score += 1
                l += 1
                score -= 1
                r-=1
            else:
        return ans

<p>Your goal is to maximize your total <strong>score</strong> by potentially playing each token in one of two ways:</p>

<ul>
	<li>If your current <strong>power</strong> is at least <code>tokens[i]</code>, you may play the <code>i<sup>th</sup></code> token face up, losing <code>tokens[i]</code> <strong>power</strong> and gaining <code>1</code> <strong>score</strong>.</li>
	<li>If your current <strong>score</strong> is at least <code>1</code>, you may play the <code>i<sup>th</sup></code> token face down, gaining <code>tokens[i]</code> <strong>power</strong> and losing <code>1</code> <strong>score</strong>.</li>
</ul>

<p>Each token may be played <strong>at most</strong> once and <strong>in any order</strong>. You do <strong>not</strong> have to play all the tokens.</p>

<p>Return <em>the largest possible <strong>score</strong> you can achieve after playing any number of tokens</em>.</p>

<pre><strong>Input:</strong> tokens = [100], power = 50
<strong>Explanation</strong><strong>:</strong> Playing the only token in the bag is impossible because you either have too little power or too little score.
</pre>

<pre><strong>Input:</strong> tokens = [100,200], power = 150
<strong>Explanation:</strong> Play the 0<sup>th</sup> token (100) face up, your power becomes 50 and score becomes 1.
There is no need to play the 1<sup>st</sup> token since you cannot play it face up to add to your score.
</pre>

<pre><strong>Input:</strong> tokens = [100,200,300,400], power = 200
<strong>Explanation:</strong> Play the tokens in this order to get a score of 2:
1. Play the 0<sup>th</sup> token (100) face up, your power becomes 100 and score becomes 1.
2. Play the 3<sup>rd</sup> token (400) face down, your power becomes 500 and score becomes 0.
3. Play the 1<sup>st</sup> token (200) face up, your power becomes 300 and score becomes 1.
4. Play the 2<sup>nd </sup>token (300) face up, your power becomes 0 and score becomes 2.
</pre>

<ul>
	<li><code>0 &lt;= tokens.length &lt;= 1000</code></li>
	<li><code>0 &lt;= tokens[i],&nbsp;power &lt; 10<sup>4</sup></code></li>
</ul>
</div>

directory: 2303-calculate-amount-paid-in-taxes
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/calculate-amount-paid-in-taxes/">2303. Calculate Amount Paid in Taxes</a></h2><h3>Easy</h3><hr><div><p>You are given a <strong>0-indexed</strong> 2D integer array <code>brackets</code> where <code>brackets[i] = [upper<sub>i</sub>, percent<sub>i</sub>]</code> means that the <code>i<sup>th</sup></code> tax bracket has an upper bound of <code>upper<sub>i</sub></code> and is taxed at a rate of <code>percent<sub>i</sub></code>. The brackets are <strong>sorted</strong> by upper bound (i.e. <code>upper<sub>i-1</sub> &lt; upper<sub>i</sub></code> for <code>0 &lt; i &lt; brackets.length</code>).</p>

<p>Tax is calculated as follows:</p>

<ul>
	<li>The first <code>upper<sub>0</sub></code> dollars earned are taxed at a rate of <code>percent<sub>0</sub></code>.</li>
	<li>The next <code>upper<sub>1</sub> - upper<sub>0</sub></code> dollars earned are taxed at a rate of <code>percent<sub>1</sub></code>.</li>
	<li>The next <code>upper<sub>2</sub> - upper<sub>1</sub></code> dollars earned are taxed at a rate of <code>percent<sub>2</sub></code>.</li>
	<li>And so on.</li>
</ul>

<p>You are given an integer <code>income</code> representing the amount of money you earned. Return <em>the amount of money that you have to pay in taxes.</em> Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.</p>

<pre><strong>Input:</strong> brackets = [[3,50],[7,10],[12,25]], income = 10
<strong>Output:</strong> 2.65000
Based on your income, you have 3 dollars in the 1<sup>st</sup> tax bracket, 4 dollars in the 2<sup>nd</sup> tax bracket, and 3 dollars in the 3<sup>rd</sup> tax bracket.
The tax rate for the three tax brackets is 50%, 10%, and 25%, respectively.
In total, you pay $3 * 50% + $4 * 10% + $3 * 25% = $2.65 in taxes.
</pre>

<pre><strong>Input:</strong> brackets = [[1,0],[4,25],[5,50]], income = 2
<strong>Output:</strong> 0.25000
Based on your income, you have 1 dollar in the 1<sup>st</sup> tax bracket and 1 dollar in the 2<sup>nd</sup> tax bracket.
The tax rate for the two tax brackets is 0% and 25%, respectively.
In total, you pay $1 * 0% + $1 * 25% = $0.25 in taxes.
</pre>

<pre><strong>Input:</strong> brackets = [[2,50]], income = 0
<strong>Output:</strong> 0.00000
You have no income to tax, so you have to pay a total of $0 in taxes.
</pre>

<ul>
	<li><code>1 &lt;= brackets.length &lt;= 100</code></li>
	<li><code>1 &lt;= upper<sub>i</sub> &lt;= 1000</code></li>
	<li><code>0 &lt;= percent<sub>i</sub> &lt;= 100</code></li>
	<li><code>0 &lt;= income &lt;= 1000</code></li>
	<li><code>upper<sub>i</sub></code> is sorted in ascending order.</li>
	<li>All the values of <code>upper<sub>i</sub></code> are <strong>unique</strong>.</li>
	<li>The upper bound of the last tax bracket is greater than or equal to <code>income</code>.</li>
</ul>
</div>

directory: 228-summary-ranges
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/summary-ranges/">228. Summary Ranges</a></h2><h3>Easy</h3><hr><div><p>You are given a <strong>sorted unique</strong> integer array <code>nums</code>.</p>

<p>Return <em>the <strong>smallest sorted</strong> list of ranges that <strong>cover all the numbers in the array exactly</strong></em>. That is, each element of <code>nums</code> is covered by exactly one of the ranges, and there is no integer <code>x</code> such that <code>x</code> is in one of the ranges but not in <code>nums</code>.</p>

<p>Each range <code>[a,b]</code> in the list should be output as:</p>

<ul>
	<li><code>"a-&gt;b"</code> if <code>a != b</code></li>
	<li><code>"a"</code> if <code>a == b</code></li>
</ul>

<pre><strong>Input:</strong> nums = [0,1,2,4,5,7]
<strong>Output:</strong> ["0-&gt;2","4-&gt;5","7"]
<strong>Explanation:</strong> The ranges are:
[0,2] --&gt; "0-&gt;2"
[4,5] --&gt; "4-&gt;5"
[7,7] --&gt; "7"
</pre>

<pre><strong>Input:</strong> nums = [0,2,3,4,6,8,9]
<strong>Output:</strong> ["0","2-&gt;4","6","8-&gt;9"]
[0,0] --&gt; "0"
[2,4] --&gt; "2-&gt;4"
[6,6] --&gt; "6"
[8,9] --&gt; "8-&gt;9"
</pre>

<ul>
	<li><code>0 &lt;= nums.length &lt;= 20</code></li>
	<li>All the values of <code>nums</code> are <strong>unique</strong>.</li>
</ul>
</div>

directory: 1331-rank-transform-of-an-array
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        
        rankMap = {}
        sorted_arr = sorted(arr)
        i = 0
        for num in sorted_arr:
            if num not in rankMap:
                rankMap[num] = i + 1
                i += 1
        ans = []
            ans.append(rankMap[num])
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/rank-transform-of-an-array/">1331. Rank Transform of an Array</a></h2><h3>Easy</h3><hr><div><p>Given an array of integers&nbsp;<code>arr</code>, replace each element with its rank.</p>

<p>The rank represents how large the element is. The rank has the following rules:</p>

<ul>
	<li>Rank is an integer starting from 1.</li>
	<li>The larger the element, the larger the rank. If two elements are equal, their rank must be the same.</li>
	<li>Rank should be as small as possible.</li>
</ul>

        i = 0
                i += 1
        ans = []
        return ans
        
<pre><strong>Input:</strong> arr = [40,10,20,30]
<strong>Output:</strong> [4,1,2,3]
<strong>Explanation</strong>: 40 is the largest element. 10 is the smallest. 20 is the second smallest. 30 is the third smallest.</pre>

<pre><strong>Input:</strong> arr = [100,100,100]
<strong>Output:</strong> [1,1,1]
<strong>Explanation</strong>: Same elements share the same rank.
</pre>

<pre><strong>Input:</strong> arr = [37,12,28,9,100,56,80,5,12]
<strong>Output:</strong> [5,3,4,2,8,6,7,1,3]
</pre>

<ul>
	<li><code>0 &lt;= arr.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>9</sup>&nbsp;&lt;= arr[i] &lt;= 10<sup>9</sup></code></li>
</ul>
</div>

directory: 449-serialize-and-deserialize-bst

    def serialize(self, root: Optional[TreeNode]) -> str:
        """Encodes a tree to a single string.
        """
            return ''
        res = ''
                continue
        return res

        """
            return ''
        res = ''
                continue
        return res

    def deserialize(self, data: str) -> Optional[TreeNode]:
        """Decodes your encoded data to tree.
        """
        i = 1
            i += 1
            i += 1
        
# ser = Codec()
# deser = Codec()
# tree = ser.serialize(root)
# ans = deser.deserialize(tree)
# return ans

def deserialize(self, data: str) -> Optional[TreeNode]:
        """
        i = 1
            i += 1
            i += 1

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/serialize-and-deserialize-bst/">449. Serialize and Deserialize BST</a></h2><h3>Medium</h3><hr><div><p>Serialization is converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.</p>

<p>Design an algorithm to serialize and deserialize a <b>binary search tree</b>. There is no restriction on how your serialization/deserialization algorithm should work. You need to ensure that a binary search tree can be serialized to a string, and this string can be deserialized to the original tree structure.</p>

<p><b>The encoded string should be as compact as possible.</b></p>

</pre>

<ul>
	<li>The input tree is <strong>guaranteed</strong> to be a binary search tree.</li>
</ul>
</div>

directory: 445-add-two-numbers-ii
        
        def reverseList(head):
            curr, prev, nxt = head, None, None
            while curr:
                nxt = curr.next
                prev = curr
                curr = nxt
            return prev
        
        l1 = reverseList(l1)
        l2 = reverseList(l2)
        
        dummy = head = ListNode(-1)
        c = 0
        while l1 or l2:
            
            val1 = l1.val if l1 else 0
            val2 = l2.val if l2 else 0
            
            node = ListNode(s)
            head.next = node
            head = node
            
            l1 = l1.next if l1 else None
            l2 = l2.next if l2 else None
         
        if c:
            head.next = ListNode(1)
        return reverseList(dummy.next)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/add-two-numbers-ii/">445. Add Two Numbers II</a></h2><h3>Medium</h3><hr><div><p>You are given two <strong>non-empty</strong> linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.</p>

                prev = curr
                curr = nxt
        
        c = 0
            
            head = node
            
        if c:
            
<img alt="" src="https://assets.leetcode.com/uploads/2021/04/09/sumii-linked-list.jpg" style="width: 523px; height: 342px;">
<pre><strong>Input:</strong> l1 = [7,2,4,3], l2 = [5,6,4]
<strong>Output:</strong> [7,8,0,7]
</pre>

<strong>Output:</strong> [8,0,7]
</pre>

</pre>

<ul>
</ul>

<p><strong>Follow up:</strong>&nbsp;Could you solve it without reversing the input lists?</p>
</div>

directory: 197-rising-temperature
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/rising-temperature/">197. Rising Temperature</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Weather</code></p>

<pre>+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| id            | int     |
| recordDate    | date    |
| temperature   | int     |
This table contains information about the temperature on a certain day.
</pre>

<p>Write an SQL query to find all dates' <code>Id</code> with higher temperatures compared to its previous dates (yesterday).</p>

Weather table:
+----+------------+-------------+
| id | recordDate | temperature |
| 1  | 2015-01-01 | 10          |
| 2  | 2015-01-02 | 25          |
| 3  | 2015-01-03 | 20          |
| 4  | 2015-01-04 | 30          |
+----+
| id |
+----+
| 2  |
| 4  |
+----+
In 2015-01-02, the temperature was higher than the previous day (10 -&gt; 25).
In 2015-01-04, the temperature was higher than the previous day (20 -&gt; 30).
</pre>
</div>

directory: 946-validate-stack-sequences
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/validate-stack-sequences/">946. Validate Stack Sequences</a></h2><h3>Medium</h3><hr><div><p>Given two integer arrays <code>pushed</code> and <code>popped</code> each with distinct values, return <code>true</code><em> if this could have been the result of a sequence of push and pop operations on an initially empty stack, or </em><code>false</code><em> otherwise.</em></p>

<pre><strong>Input:</strong> pushed = [1,2,3,4,5], popped = [4,5,3,2,1]
<strong>Explanation:</strong> We might do the following sequence:
push(1), push(2), push(3), push(4),
pop() -&gt; 4,
push(5),
pop() -&gt; 5, pop() -&gt; 3, pop() -&gt; 2, pop() -&gt; 1
</pre>

<pre><strong>Input:</strong> pushed = [1,2,3,4,5], popped = [4,3,5,1,2]
<strong>Explanation:</strong> 1 cannot be popped before 2.
</pre>

<ul>
	<li><code>1 &lt;= pushed.length &lt;= 1000</code></li>
	<li><code>0 &lt;= pushed[i] &lt;= 1000</code></li>
	<li>All the elements of <code>pushed</code> are <strong>unique</strong>.</li>
	<li><code>popped.length == pushed.length</code></li>
	<li><code>popped</code> is a permutation of <code>pushed</code>.</li>
</ul>
</div>

directory: 637-average-of-levels-in-binary-tree
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        
        avg = []
            s = 0
                s += node.val
            avg.append(s/size)
        return avg
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/average-of-levels-in-binary-tree/">637. Average of Levels in Binary Tree</a></h2><h3>Easy</h3><hr><div>Given the <code>root</code> of a binary tree, return <em>the average value of the nodes on each level in the form of an array</em>. Answers within <code>10<sup>-5</sup></code> of the actual answer will be accepted.
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/09/avg1-tree.jpg" style="width: 277px; height: 302px;">
<strong>Output:</strong> [3.00000,14.50000,11.00000]
Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11.
Hence return [3, 14.5, 11].
</pre>

        avg = []
            s = 0
        return avg
        
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/09/avg2-tree.jpg" style="width: 292px; height: 302px;">
<pre><strong>Input:</strong> root = [3,9,20,15,7]
</pre>

<ul>
</ul>
</div>

directory: 2229-check-if-an-array-is-consecutive
    def isConsecutive(self, nums: List[int]) -> bool:
        for i in range(1, len(nums)):
            if nums[i] != nums[i-1] + 1:
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/check-if-an-array-is-consecutive/">2229. Check if an Array Is Consecutive</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code>, return <code>true</code> <em>if </em><code>nums</code><em> is <strong>consecutive</strong>, otherwise return </em><code>false</code><em>.</em></p>

<p>An array is <strong>consecutive </strong>if it contains every number in the range <code>[x, x + n - 1]</code> (<strong>inclusive</strong>), where <code>x</code> is the minimum number in the array and <code>n</code> is the length of the array.</p>

<pre><strong>Input:</strong> nums = [1,3,4,2]
The minimum value is 1 and the length of nums is 4.
All of the values in the range [x, x + n - 1] = [1, 1 + 4 - 1] = [1, 4] = (1, 2, 3, 4) occur in nums.
Therefore, nums is consecutive.
</pre>

<pre><strong>Input:</strong> nums = [1,3]
The minimum value is 1 and the length of nums is 2.
The value 2 in the range [x, x + n - 1] = [1, 1 + 2 - 1], = [1, 2] = (1, 2) does not occur in nums.
Therefore, nums is not consecutive.
</pre>

<pre><strong>Input:</strong> nums = [3,5,4]
The minimum value is 3 and the length of nums is 3.
All of the values in the range [x, x + n - 1] = [3, 3 + 3 - 1] = [3, 5] = (3, 4, 5) occur in nums.
</pre>

<ul>
	<li><code>0 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 697-degree-of-an-array
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/degree-of-an-array/">697. Degree of an Array</a></h2><h3>Easy</h3><hr><div><p>Given a non-empty array of non-negative integers <code>nums</code>, the <b>degree</b> of this array is defined as the maximum frequency of any one of its elements.</p>

<p>Your task is to find the smallest possible length of a (contiguous) subarray of <code>nums</code>, that has the same degree as <code>nums</code>.</p>

<pre><strong>Input:</strong> nums = [1,2,2,3,1]
The input array has a degree of 2 because both elements 1 and 2 appear twice.
Of the subarrays that have the same degree:
[1, 2, 2, 3, 1], [1, 2, 2, 3], [2, 2, 3, 1], [1, 2, 2], [2, 2, 3], [2, 2]
The shortest length is 2. So return 2.
</pre>

<pre><strong>Input:</strong> nums = [1,2,2,3,1,4,2]
The degree is 3 because the element 2 is repeated 3 times.
So [2,2,3,1,4,2] is the shortest subarray, therefore returning 6.
</pre>

<ul>
	<li><code>nums.length</code> will be between 1 and 50,000.</li>
	<li><code>nums[i]</code> will be an integer between 0 and 49,999.</li>
</ul>
</div>

directory: 1631-path-with-minimum-effort
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        
        m, n = len(heights), len(heights[0])
        dirs = [(1,0), (0, 1), (-1, 0), (0, -1)]
        
        def dfs(k, x, y):
            
            visited.add((x, y))
            for dx, dy in dirs:
                new_x, new_y = x + dx, y + dy
                if 0 <= new_x < m and 0 <= new_y < n and (new_x, new_y) not in visited:
                    new_k = abs(heights[x][y] - heights[new_x][new_y])
                    if new_k <= k:
                        dfs(k, new_x, new_y)
                        
        mn, mx = -1, max([heights[row][col] for col in range(n) for row in range(m)])
        
        while mn + 1 < mx:
            
            mid = (mn + mx) // 2
            visited = set()
            dfs(mid, 0, 0)
            if (m-1, n-1) in visited:
                mx = mid
            else:
                mn = mid
        return mx
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/path-with-minimum-effort/">1631. Path With Minimum Effort</a></h2><h3>Medium</h3><hr><div><p>You are a hiker preparing for an upcoming hike. You are given <code>heights</code>, a 2D array of size <code>rows x columns</code>, where <code>heights[row][col]</code> represents the height of cell <code>(row, col)</code>. You are situated in the top-left cell, <code>(0, 0)</code>, and you hope to travel to the bottom-right cell, <code>(rows-1, columns-1)</code> (i.e.,&nbsp;<strong>0-indexed</strong>). You can move <strong>up</strong>, <strong>down</strong>, <strong>left</strong>, or <strong>right</strong>, and you wish to find a route that requires the minimum <strong>effort</strong>.</p>

                mx = mid
            else:
                mn = mid
        return mx

<p>A route's <strong>effort</strong> is the <strong>maximum absolute difference</strong><strong> </strong>in heights between two consecutive cells of the route.</p>

<p>Return <em>the minimum <strong>effort</strong> required to travel from the top-left cell to the bottom-right cell.</em></p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2020/10/04/ex1.png" style="width: 300px; height: 300px;"></p>

<pre><strong>Input:</strong> heights = [[1,2,2],[3,8,2],[5,3,5]]
<strong>Explanation:</strong> The route of [1,3,5,3,5] has a maximum absolute difference of 2 in consecutive cells.
This is better than the route of [1,2,2,2,5], where the maximum absolute difference is 3.
</pre>

<p><img alt="" src="https://assets.leetcode.com/uploads/2020/10/04/ex2.png" style="width: 300px; height: 300px;"></p>

<pre><strong>Input:</strong> heights = [[1,2,3],[3,8,4],[5,3,5]]
<strong>Explanation:</strong> The route of [1,2,3,4,5] has a maximum absolute difference of 1 in consecutive cells, which is better than route [1,3,5,3,5].
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/10/04/ex3.png" style="width: 300px; height: 300px;">
<pre><strong>Input:</strong> heights = [[1,2,1,1,1],[1,2,1,2,1],[1,2,1,2,1],[1,2,1,2,1],[1,1,1,2,1]]
<strong>Explanation:</strong> This route does not require any effort.
</pre>

<ul>
	<li><code>rows == heights.length</code></li>
	<li><code>columns == heights[i].length</code></li>
	<li><code>1 &lt;= rows, columns &lt;= 100</code></li>
	<li><code>1 &lt;= heights[i][j] &lt;= 10<sup>6</sup></code></li>

directory: 897-increasing-order-search-tree
    def increasingBST(self, root: TreeNode) -> TreeNode:
        self.root = head = TreeNode(None)
            dfs(root.left)
            self.root.right = TreeNode(root.val)
            self.root = self.root.right
            dfs(root.right)
        dfs(root)
        return head.right
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/increasing-order-search-tree/">897. Increasing Order Search Tree</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary search tree, rearrange the tree in <strong>in-order</strong> so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.</p>

        dfs(root)

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/17/ex1.jpg" style="width: 600px; height: 350px;">
<pre><strong>Input:</strong> root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
<strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/11/17/ex2.jpg" style="width: 300px; height: 114px;">
<pre><strong>Input:</strong> root = [5,1,7]
<strong>Output:</strong> [1,null,5,null,7]
</pre>

<ul>
	<li>The number of nodes in the given tree will be in the range <code>[1, 100]</code>.</li>

directory: 1197-minimum-knight-moves
    def minKnightMoves(self, x: int, y: int) -> int:
        
        min_moves = 0
        directions = [(2, 1), (1, 2), (2, -1), (-1, 2), (-2, 1), (1, -2), (-2, -1), (-1, -2)]
        q = deque([])
        q.append((0, 0))
        seen.add((0, 0))
        while q:
                x1, y1 = q.popleft()
                if x1 == x and y1 == y:
                    return min_moves
                for x2, y2 in directions:
                    new_x, new_y = x1 + x2, y1 + y2
                    if (new_x, new_y) not in seen:
                        q.append((new_x, new_y))
                        seen.add((new_x, new_y))
            min_moves += 1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/minimum-knight-moves/">1197. Minimum Knight Moves</a></h2><h3>Medium</h3><hr><div><p>In an <strong>infinite</strong> chess board with coordinates from <code>-infinity</code> to <code>+infinity</code>, you have a <strong>knight</strong> at square <code>[0, 0]</code>.</p>

        while q:
            
<p>A knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction.</p>
<img src="https://assets.leetcode.com/uploads/2018/10/12/knight.png" style="height: 250px; width: 250px;">
<p>Return <em>the minimum number of steps needed to move the knight to the square</em> <code>[x, y]</code>. It is guaranteed the answer exists.</p>

<pre><strong>Input:</strong> x = 2, y = 1
<strong>Explanation: </strong>[0, 0] → [2, 1]
</pre>

<pre><strong>Input:</strong> x = 5, y = 5
<strong>Explanation: </strong>[0, 0] → [2, 1] → [4, 2] → [3, 4] → [5, 5]
</pre>

<ul>
	<li><code>-300 &lt;= x, y &lt;= 300</code></li>
	<li><code>0 &lt;= |x| + |y| &lt;= 300</code></li>
</ul>
</div>

directory: 0108-convert-sorted-array-to-binary-search-tree
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
            node = TreeNode(nums[mid])
            node.left = convert(left, mid - 1)
            node.right = convert(mid + 1, right)
        
        return convert(0, n - 1)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/">108. Convert Sorted Array to Binary Search Tree</a></h2><h3>Easy</h3><hr><div><p>Given an integer array <code>nums</code> where the elements are sorted in <strong>ascending order</strong>, convert <em>it to a <strong>height-balanced</strong> binary search tree</em>.</p>

<p>A <strong>height-balanced</strong> binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree1.jpg" style="width: 302px; height: 222px;">
<pre><strong>Input:</strong> nums = [-10,-3,0,5,9]
<strong>Output:</strong> [0,-3,9,-10,null,5]
<strong>Explanation:</strong> [0,-10,5,null,-3,null,9] is also accepted:
<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree2.jpg" style="width: 302px; height: 222px;">
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/18/btree.jpg" style="width: 342px; height: 142px;">
<strong>Output:</strong> [3,1]
<strong>Explanation:</strong> [1,null,3] and [3,1] are both height-balanced BSTs.
</pre>

<ul>
	<li><code>nums</code> is sorted in a <strong>strictly increasing</strong> order.</li>
</ul>
</div>

directory: 114-flatten-binary-tree-to-linked-list

    def flatten(self, root: Optional[TreeNode]) -> None:
        """
        """
        
        def flattenTree(root):
            if not root.left and not root.right:
            left = flattenTree(root.left)
            right = flattenTree(root.right)
            if left:
                left.right = root.right
                root.right = root.left
            return right if right else left
        
        flattenTree(root)
            
def flatten(self, root: Optional[TreeNode]) -> None:
        """
        """
        
            if left:
        
Notes: def flattenTree(self, node):
if not node:
if not node.left and not node.right:
return node
leftTail = self.flattenTree(node.left)
rightTail = self.flattenTree(node.right)
if leftTail:
leftTail.right = node.right
node.right = node.left
node.left = None
return rightTail if rightTail else leftTail
Readme: <h2><a href="https://leetcode.com/problems/flatten-binary-tree-to-linked-list/">114. Flatten Binary Tree to Linked List</a></h2><h3>Medium</h3><hr><div><p>Given the <code>root</code> of a binary tree, flatten the tree into a "linked list":</p>

<ul>
	<li>The "linked list" should use the same <code>TreeNode</code> class where the <code>right</code> child pointer points to the next node in the list and the <code>left</code> child pointer is always <code>null</code>.</li>
	<li>The "linked list" should be in the same order as a <a href="https://en.wikipedia.org/wiki/Tree_traversal#Pre-order,_NLR" target="_blank"><strong>pre-order</strong><strong> traversal</strong></a> of the binary tree.</li>
</ul>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/14/flaten.jpg" style="width: 500px; height: 226px;">
<pre><strong>Input:</strong> root = [1,2,5,3,4,null,6]
<strong>Output:</strong> [1,null,2,null,3,null,4,null,5,null,6]
</pre>

</pre>

</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[0, 2000]</code>.</li>
</ul>

<strong>Follow up:</strong> Can you flatten the tree in-place (with <code>O(1)</code> extra space)?</div>

directory: 1423-maximum-points-you-can-obtain-from-cards
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        """
        1 2 3 4 5 6 1 -> s = 22, n = 7, k = 3
        """
        
        totalSum, n = sum(cardPoints), len(cardPoints)
        # We have to take all cards so return sum of array
        if n == k:
            return totalSum
        # else, we have a choice to include either 1st element, 1st and 2nd element,
        # 1...k elements from the front, or we can take the last element, to n - k from the end
        # or we can take k elements from the beginning and the end. 
        
        # For this purpose we need a sliding window across the array and we will pick out 
        # the max out of them
        currentWindowSum = sum(cardPoints[:n-k])
        ans = currentWindowSum
        for i in range(n-k, n):
            currentWindowSum -= cardPoints[i - (n - k)]
            currentWindowSum += cardPoints[i]
            ans = min(ans, currentWindowSum)
        return totalSum - ans
Notes: totalSum = sum(cardPoints)
n = len(cardPoints)
if k == n:
return totalSum
currentWindowSum = sum(cardPoints[:n-k])
ans = currentWindowSum
for i in range(n-k, n):
currentWindowSum -= cardPoints[i-(n-k)]
currentWindowSum += cardPoints[i]
ans = min(ans, currentWindowSum)
return totalSum - ans
Readme: <h2><a href="https://leetcode.com/problems/maximum-points-you-can-obtain-from-cards/">1423. Maximum Points You Can Obtain from Cards</a></h2><h3>Medium</h3><hr><div><p>There are several cards <strong>arranged in a row</strong>, and each card has an associated number of points. The points are given in the integer array <code>cardPoints</code>.</p>

        """
        """
        
        if n == k:
        
<p>In one step, you can take one card from the beginning or from the end of the row. You have to take exactly <code>k</code> cards.</p>

<p>Your score is the sum of the points of the cards you have taken.</p>

<p>Given the integer array <code>cardPoints</code> and the integer <code>k</code>, return the <em>maximum score</em> you can obtain.</p>

<pre><strong>Input:</strong> cardPoints = [1,2,3,4,5,6,1], k = 3
<strong>Explanation:</strong> After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
</pre>

<pre><strong>Input:</strong> cardPoints = [2,2,2], k = 2
<strong>Explanation:</strong> Regardless of which two cards you take, your score will always be 4.
</pre>

<pre><strong>Input:</strong> cardPoints = [9,7,7,9,7,7,9], k = 7
<strong>Output:</strong> 55
<strong>Explanation:</strong> You have to take all the cards. Your score is the sum of points of all cards.
</pre>

<ul>
	<li><code>1 &lt;= cardPoints.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= cardPoints[i] &lt;= 10<sup>4</sup></code></li>
	<li><code>1 &lt;= k &lt;= cardPoints.length</code></li>
</ul>
</div>

directory: 0146-lru-cache
Python: class DLinkedNode(): 
        self.key = 0
        self.value = 0
            
class LRUCache():
    def _add_node(self, node):
        """
        Always add the new node right after head.
        """
        node.prev = self.head
        node.next = self.head.next

        self.head.next.prev = node
        self.head.next = node

    def _remove_node(self, node):
        """
        Remove an existing node from the linked list.
        """
        prev = node.prev
        new = node.next

        prev.next = new
        new.prev = prev

    def _move_to_head(self, node):
        """
        Move certain node in between to the head.
        """
        self._remove_node(node)
        self._add_node(node)

    def _pop_tail(self):
        """
        Pop the current tail.
        """
        res = self.tail.prev
        self._remove_node(res)
        return res

class DLinkedNode(): 
            
        """
        """

        """
        """

        """
        """

        """
        """
        return res

    def __init__(self, capacity):
        """
        :type capacity: int
        """
        self.cache = {}
        self.size = 0
        self.capacity = capacity
        self.head, self.tail = DLinkedNode(), DLinkedNode()

        self.head.next = self.tail
        self.tail.prev = self.head
        
    def get(self, key):
        """
        :type key: int
        """
        node = self.cache.get(key, None)
        if not node:
            return -1

        # move the accessed node to the head;
        self._move_to_head(node)

        return node.value

    def put(self, key, value):
        """
        :type value: int
        :rtype: void
        """
        node = self.cache.get(key)

        if not node: 
            newNode = DLinkedNode()
            newNode.key = key
            newNode.value = value

            self.cache[key] = newNode
            self._add_node(newNode)

            self.size += 1

            if self.size > self.capacity:
                # pop the tail
                tail = self._pop_tail()
                del self.cache[tail.key]
                self.size -= 1
        else:
            # update the value.
            node.value = value
            self._move_to_head(node)

def __init__(self, capacity):
        """
        """

        """
        """
            return -1

        """
        """

if self.size > self.capacity:
        else:
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/lru-cache/">146. LRU Cache</a></h2><h3>Medium</h3><hr><div><p>Design a data structure that follows the constraints of a <strong><a href="https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU" target="_blank">Least Recently Used (LRU) cache</a></strong>.</p>

<p>Implement the <code>LRUCache</code> class:</p>

<ul>
	<li><code>LRUCache(int capacity)</code> Initialize the LRU cache with <strong>positive</strong> size <code>capacity</code>.</li>
	<li><code>int get(int key)</code> Return the value of the <code>key</code> if the key exists, otherwise return <code>-1</code>.</li>
	<li><code>void put(int key, int value)</code> Update the value of the <code>key</code> if the <code>key</code> exists. Otherwise, add the <code>key-value</code> pair to the cache. If the number of keys exceeds the <code>capacity</code> from this operation, <strong>evict</strong> the least recently used key.</li>
</ul>

<p>The functions <code>get</code> and <code>put</code> must each run in <code>O(1)</code> average time complexity.</p>

["LRUCache", "put", "put", "get", "put", "get", "put", "get", "get", "get"]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]
[null, null, null, 1, null, -1, null, -1, 3, 4]

LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // cache is {1=1}
lRUCache.put(2, 2); // cache is {1=1, 2=2}
lRUCache.get(1);    // return 1
lRUCache.put(3, 3); // LRU key was 2, evicts key 2, cache is {1=1, 3=3}
lRUCache.get(2);    // returns -1 (not found)
lRUCache.put(4, 4); // LRU key was 1, evicts key 1, cache is {4=4, 3=3}
lRUCache.get(1);    // return -1 (not found)
lRUCache.get(3);    // return 3
lRUCache.get(4);    // return 4
</pre>

<ul>
	<li><code>1 &lt;= capacity &lt;= 3000</code></li>
	<li><code>0 &lt;= key &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= value &lt;= 10<sup>5</sup></code></li>
	<li>At most <code>2 * 10<sup>5</sup></code> calls will be made to <code>get</code> and <code>put</code>.</li>
</ul>
</div>

directory: 577-employee-bonus
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/employee-bonus/">577. Employee Bonus</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Employee</code></p>

| empId       | int     |
| supervisor  | int     |
empId is the primary key column for this table.
Each row of this table indicates the name and the ID of an employee in addition to their salary and the id of their manager.
</pre>

<p>Table: <code>Bonus</code></p>

| empId       | int  |
| bonus       | int  |
empId is a foreign key to empId from the Employee table.
Each row of this table contains the id of an employee and their respective bonus.
</pre>

<p>Write an SQL query to report the name and bonus amount of each employee with a bonus <strong>less than</strong> <code>1000</code>.</p>

+-------+--------+------------+--------+
| empId | name   | supervisor | salary |
| 3     | Brad   | null       | 4000   |
| 1     | John   | 3          | 1000   |
| 2     | Dan    | 3          | 2000   |
| 4     | Thomas | 3          | 4000   |
Bonus table:
+-------+-------+
| empId | bonus |
| 2     | 500   |
| 4     | 2000  |
+------+-------+
| name | bonus |
| Brad | null  |
| John | null  |
| Dan  | 500   |
</pre>
</div>

directory: 1614-maximum-nesting-depth-of-the-parentheses
    def maxDepth(self, s: str) -> int:
        
        """
        "" -> 0
        "(ashwin)" -> 0
        (A+B) -> max(A, B)
        """
        maximum = 0
        stack = []
        for c in s:
            if c == "(":
                stack.append(c)
                maximum = max(maximum, len(stack))
            elif c == ")":
        maximum = max(maximum, len(stack))
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses/">1614. Maximum Nesting Depth of the Parentheses</a></h2><h3>Easy</h3><hr><div><p>A string is a <strong>valid parentheses string</strong> (denoted <strong>VPS</strong>) if it meets one of the following:</p>

        """
        "" -> 0
        """
        maximum = 0
        stack = []
        for c in s:
            if c == "(":
        
<ul>
	<li>It is an empty string <code>""</code>, or a single character not equal to <code>"("</code> or <code>")"</code>,</li>
	<li>It can be written as <code>AB</code> (<code>A</code> concatenated with <code>B</code>), where <code>A</code> and <code>B</code> are <strong>VPS</strong>'s, or</li>
	<li>It can be written as <code>(A)</code>, where <code>A</code> is a <strong>VPS</strong>.</li>
</ul>

<p>We can similarly define the <strong>nesting depth</strong> <code>depth(S)</code> of any VPS <code>S</code> as follows:</p>

<ul>
	<li><code>depth("") = 0</code></li>
	<li><code>depth(C) = 0</code>, where <code>C</code> is a string with a single character not equal to <code>"("</code> or <code>")"</code>.</li>
	<li><code>depth(A + B) = max(depth(A), depth(B))</code>, where <code>A</code> and <code>B</code> are <strong>VPS</strong>'s.</li>
	<li><code>depth("(" + A + ")") = 1 + depth(A)</code>, where <code>A</code> is a <strong>VPS</strong>.</li>
</ul>

<p>For example, <code>""</code>, <code>"()()"</code>, and <code>"()(()())"</code> are <strong>VPS</strong>'s (with nesting depths 0, 1, and 2), and <code>")("</code> and <code>"(()"</code> are not <strong>VPS</strong>'s.</p>

<p>Given a <strong>VPS</strong> represented as string <code>s</code>, return <em>the <strong>nesting depth</strong> of </em><code>s</code>.</p>

<pre><strong>Input:</strong> s = "(1+(2*3)+((<u>8</u>)/4))+1"
<strong>Explanation:</strong> Digit 8 is inside of 3 nested parentheses in the string.
</pre>

<pre><strong>Input:</strong> s = "(1)+((2))+(((<u>3</u>)))"
</pre>

<ul>
	<li><code>s</code> consists of digits <code>0-9</code> and characters <code>'+'</code>, <code>'-'</code>, <code>'*'</code>, <code>'/'</code>, <code>'('</code>, and <code>')'</code>.</li>
	<li>It is guaranteed that parentheses expression <code>s</code> is a <strong>VPS</strong>.</li>
</ul>
</div>

directory: 0138-copy-list-with-random-pointer
"""

"""
"""

    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        
        copyMap = {None : None}
        curr = head
            copy = Node(curr.val)
            copyMap[curr] = copy
        curr = head
            copy = copyMap[curr]
            copy.next = copyMap[curr.next]
            copy.random = copyMap[curr.random]
        return copyMap[head]
        
        curr = head
        curr = head
Notes: ​

<ul>
</ul>

</pre>

</pre>

</pre>

<ul>
</ul>
</div>

directory: 474-ones-and-zeroes
    def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
        
        counter = [[s.count("0"), s.count("1")] for s in strs]
        
        def dp(i, j, index):
            if i < 0 or j < 0:
                return float('-inf')
            if index == len(strs):
                return 0
            return max(dp(i,j,index+1), 1 + dp(i-counter[index][0], j-counter[index][1], index+1))
        return dp(m, n, 0)
Notes: 
Readme: <h2><a href="https://leetcode.com/problems/ones-and-zeroes/">474. Ones and Zeroes</a></h2><h3>Medium</h3><hr><div><p>You are given an array of binary strings <code>strs</code> and two integers <code>m</code> and <code>n</code>.</p>

                return 0
        return dp(m, n, 0)        

<p>Return <em>the size of the largest subset of <code>strs</code> such that there are <strong>at most</strong> </em><code>m</code><em> </em><code>0</code><em>'s and </em><code>n</code><em> </em><code>1</code><em>'s in the subset</em>.</p>

<p>A set <code>x</code> is a <strong>subset</strong> of a set <code>y</code> if all elements of <code>x</code> are also elements of <code>y</code>.</p>

<pre><strong>Input:</strong> strs = ["10","0001","111001","1","0"], m = 5, n = 3
<strong>Explanation:</strong> The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.
</pre>

<pre><strong>Input:</strong> strs = ["10","0","1"], m = 1, n = 1
<b>Explanation:</b> The largest subset is {"0", "1"}, so the answer is 2.
</pre>

<ul>
	<li><code>1 &lt;= strs.length &lt;= 600</code></li>
	<li><code>1 &lt;= strs[i].length &lt;= 100</code></li>
	<li><code>strs[i]</code> consists only of digits <code>'0'</code> and <code>'1'</code>.</li>
</ul>
</div>

directory: 225-implement-stack-using-queues
Python: class MyStack:

        self.deque1 = deque()
        self.deque2 = deque()

        self.deque1.append(x)
        for _ in range(len(self.deque1)-1):
            self.deque1.append(self.deque1.popleft())
        return self.deque1.popleft()
        return self.deque1[0]
    def empty(self) -> bool:
        return len(self.deque1) == 0

class MyStack:

# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# param_4 = obj.empty()

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/implement-stack-using-queues/">225. Implement Stack using Queues</a></h2><h3>Easy</h3><hr><div><p>Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (<code>push</code>, <code>top</code>, <code>pop</code>, and <code>empty</code>).</p>

<p>Implement the <code>MyStack</code> class:</p>

<ul>
	<li><code>void push(int x)</code> Pushes element x to the top of the stack.</li>
	<li><code>int pop()</code> Removes the element on the top of the stack and returns it.</li>
	<li><code>int top()</code> Returns the element on the top of the stack.</li>
	<li><code>boolean empty()</code> Returns <code>true</code> if the stack is empty, <code>false</code> otherwise.</li>
</ul>

<p><b>Notes:</b></p>

<ul>
	<li>You must use <strong>only</strong> standard operations of a queue, which means that only <code>push to back</code>, <code>peek/pop from front</code>, <code>size</code> and <code>is empty</code> operations are valid.</li>
	<li>Depending on your language, the queue may not be supported natively. You may simulate a queue using a list or deque (double-ended queue) as long as you use only a queue's standard operations.</li>
</ul>

["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
[null, null, null, 2, 2, false]

MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False
</pre>

<ul>
	<li><code>1 &lt;= x &lt;= 9</code></li>
	<li>At most <code>100</code> calls will be made to <code>push</code>, <code>pop</code>, <code>top</code>, and <code>empty</code>.</li>
	<li>All the calls to <code>pop</code> and <code>top</code> are valid.</li>
</ul>

<p><strong>Follow-up:</strong> Can you implement the stack using only one queue?</p>
</div>

directory: 286-walls-and-gates
    def wallsAndGates(self, rooms: List[List[int]]) -> None:
        """
        Do not return anything, modify rooms in-place instead.
        """
        rows, cols = len(rooms), len(rooms[0])
        queue = deque([])
                if rooms[r][c] == 0:
                    queue.append((r, c, 0))
        distances = [(1, 0), (0, 1), (-1, 0), (0, -1)]
            r, c, level = queue.popleft()
            for d in distances:
                nr, nc = r + d[0], c + d[1]
                if nr < 0 or nc < 0 or nr >=rows or nc >= cols or rooms[nr][nc] != 2147483647:
                    continue
                rooms[nr][nc] = min(rooms[nr][nc], level + 1)
                queue.append((nr,nc, level + 1))
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/walls-and-gates/">286. Walls and Gates</a></h2><h3>Medium</h3><hr><div><p>You are given an <code>m x n</code> grid <code>rooms</code>&nbsp;initialized with these three possible values.</p>

        """
        """
                    continue
                
<ul>
	<li><code>-1</code>&nbsp;A wall or an obstacle.</li>
	<li><code>0</code> A gate.</li>
	<li><code>INF</code> Infinity means an empty room. We use the value <code>2<sup>31</sup> - 1 = 2147483647</code> to represent <code>INF</code> as you may assume that the distance to a gate is less than <code>2147483647</code>.</li>
</ul>

<p>Fill each empty room with the distance to <em>its nearest gate</em>. If it is impossible to reach a gate, it should be filled with <code>INF</code>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/01/03/grid.jpg" style="width: 500px; height: 223px;">
<pre><strong>Input:</strong> rooms = [[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
<strong>Output:</strong> [[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
</pre>

<pre><strong>Input:</strong> rooms = [[-1]]
<strong>Output:</strong> [[-1]]
</pre>

<ul>
	<li><code>m == rooms.length</code></li>
	<li><code>n == rooms[i].length</code></li>
	<li><code>1 &lt;= m, n &lt;= 250</code></li>
	<li><code>rooms[i][j]</code> is <code>-1</code>, <code>0</code>, or <code>2<sup>31</sup> - 1</code>.</li>
</ul>
</div>

directory: 171-excel-sheet-column-number
    def titleToNumber(self, columnTitle: str) -> int:
        
        power = len(columnTitle)-1
        result = 0
        for c in columnTitle:
            result += 26**power*(ord(c) - ord('A') + 1)
            power -= 1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/excel-sheet-column-number/">171. Excel Sheet Column Number</a></h2><h3>Easy</h3><hr><div><p>Given a string <code>columnTitle</code> that represents the column title as appear in an Excel sheet, return <em>its corresponding column number</em>.</p>

B -&gt; 2
C -&gt; 3
...
Z -&gt; 26
AA -&gt; 27
AB -&gt; 28 
...
</pre>

<pre><strong>Input:</strong> columnTitle = "A"
</pre>

<pre><strong>Input:</strong> columnTitle = "AB"
</pre>

        result = 0
            power -= 1

<pre><strong>Input:</strong> columnTitle = "ZY"
<strong>Output:</strong> 701
</pre>

<ul>
	<li><code>1 &lt;= columnTitle.length &lt;= 7</code></li>
	<li><code>columnTitle</code> consists only of uppercase English letters.</li>
	<li><code>columnTitle</code> is in the range <code>["A", "FXSHRXW"]</code>.</li>
</ul>
</div>

directory: 463-island-perimeter
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/island-perimeter/">463. Island Perimeter</a></h2><h3>Easy</h3><hr><div><p>You are given <code>row x col</code> <code>grid</code> representing a map where <code>grid[i][j] = 1</code> represents&nbsp;land and <code>grid[i][j] = 0</code> represents water.</p>

<p>Grid cells are connected <strong>horizontally/vertically</strong> (not diagonally). The <code>grid</code> is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).</p>

<p>The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.</p>

<img src="https://assets.leetcode.com/uploads/2018/10/12/island.png" style="width: 221px; height: 213px;">
<pre><strong>Input:</strong> grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
<strong>Explanation:</strong> The perimeter is the 16 yellow stripes in the image above.
</pre>

<pre><strong>Input:</strong> grid = [[1]]
</pre>

<pre><strong>Input:</strong> grid = [[1,0]]
</pre>

<ul>
	<li><code>row == grid.length</code></li>
	<li><code>col == grid[i].length</code></li>
	<li><code>1 &lt;= row, col &lt;= 100</code></li>
	<li><code>grid[i][j]</code> is <code>0</code> or <code>1</code>.</li>
	<li>There is exactly one island in <code>grid</code>.</li>
</ul>
</div>

directory: 268-missing-number
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/missing-number/">268. Missing Number</a></h2><h3>Easy</h3><hr><div><p>Given an array <code>nums</code> containing <code>n</code> distinct numbers in the range <code>[0, n]</code>, return <em>the only number in the range that is missing from the array.</em></p>

<pre><strong>Input:</strong> nums = [3,0,1]
<strong>Explanation:</strong> n = 3 since there are 3 numbers, so all numbers are in the range [0,3]. 2 is the missing number in the range since it does not appear in nums.
</pre>

<strong>Explanation:</strong> n = 2 since there are 2 numbers, so all numbers are in the range [0,2]. 2 is the missing number in the range since it does not appear in nums.
</pre>

<pre><strong>Input:</strong> nums = [9,6,4,2,3,5,7,0,1]
<strong>Output:</strong> 8
<strong>Explanation:</strong> n = 9 since there are 9 numbers, so all numbers are in the range [0,9]. 8 is the missing number in the range since it does not appear in nums.
</pre>

<ul>
	<li><code>0 &lt;= nums[i] &lt;= n</code></li>
	<li>All the numbers of <code>nums</code> are <strong>unique</strong>.</li>
</ul>

<p><strong>Follow up:</strong> Could you implement a solution using only <code>O(1)</code> extra space complexity and <code>O(n)</code> runtime complexity?</p>
</div>

directory: 985-sum-of-even-numbers-after-queries
    def sumEvenAfterQueries(self, A, queries):
        S = sum(x for x in A if x % 2 == 0)
        ans = []

        for x, k in queries:
            if A[k] % 2 == 0: S -= A[k]
            A[k] += x
            if A[k] % 2 == 0: S += A[k]
            ans.append(S)

        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/sum-of-even-numbers-after-queries/">985. Sum of Even Numbers After Queries</a></h2><h3>Medium</h3><hr><div><p>You are given an integer array <code>nums</code> and an array <code>queries</code> where <code>queries[i] = [val<sub>i</sub>, index<sub>i</sub>]</code>.</p>

<p>For each query <code>i</code>, first, apply <code>nums[index<sub>i</sub>] = nums[index<sub>i</sub>] + val<sub>i</sub></code>, then print the sum of the even values of <code>nums</code>.</p>

        ans = []

            A[k] += x

        return ans

<p>Return <em>an integer array </em><code>answer</code><em> where </em><code>answer[i]</code><em> is the answer to the </em><code>i<sup>th</sup></code><em> query</em>.</p>

<pre><strong>Input:</strong> nums = [1,2,3,4], queries = [[1,0],[-3,1],[-4,0],[2,3]]
<strong>Output:</strong> [8,6,2,4]
<strong>Explanation:</strong> At the beginning, the array is [1,2,3,4].
After adding 1 to nums[0], the array is [2,2,3,4], and the sum of even values is 2 + 2 + 4 = 8.
After adding -3 to nums[1], the array is [2,-1,3,4], and the sum of even values is 2 + 4 = 6.
After adding -4 to nums[0], the array is [-2,-1,3,4], and the sum of even values is -2 + 4 = 2.
After adding 2 to nums[3], the array is [-2,-1,3,6], and the sum of even values is -2 + 6 = 4.
</pre>

<pre><strong>Input:</strong> nums = [1], queries = [[4,0]]
</pre>

<ul>
	<li><code>1 &lt;= queries.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-10<sup>4</sup> &lt;= val<sub>i</sub> &lt;= 10<sup>4</sup></code></li>
	<li><code>0 &lt;= index<sub>i</sub> &lt; nums.length</code></li>
</ul>
</div>

directory: 540-single-element-in-a-sorted-array
    def singleNonDuplicate(self, nums: List[int]) -> int:
        
            halves_are_even = (right - mid) % 2 == 0
            if nums[mid + 1] == nums[mid]:
                if halves_are_even:
                    left = mid + 2
                else:
            elif nums[mid-1] == nums[mid]:
                    right = mid - 2
                else:
            else:
                return nums[mid]
        return nums[left]
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/single-element-in-a-sorted-array/">540. Single Element in a Sorted Array</a></h2><h3>Medium</h3><hr><div><p>You are given a sorted array consisting of only integers where every element appears exactly twice, except for one element which appears exactly once.</p>

                else:
                else:
            else:
        
<p>Return <em>the single element that appears only once</em>.</p>

<p>Your solution must run in <code>O(log n)</code> time and <code>O(1)</code> space.</p>

<pre><strong>Input:</strong> nums = [1,1,2,3,3,4,4,8,8]
<pre><strong>Input:</strong> nums = [3,3,7,7,10,11,11]
</pre>

<ul>
</ul>
</div>

directory: 735-asteroid-collision
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        
        stack = []
        
        for comet in asteroids:
            if not stack or stack[-1] < 0 or (comet > 0 and stack[-1] > 0):
                stack.append(comet)
            else:
                while stack and stack[-1] > 0 and stack[-1] + comet <0:
                if stack and stack[-1] +comet == 0:
                elif not stack:
                    stack.append(comet)
                elif stack and stack[-1] < 0:

Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/asteroid-collision/">735. Asteroid Collision</a></h2><h3>Medium</h3><hr><div><p>We are given an array <code>asteroids</code> of integers representing asteroids in a row.</p>

        stack = []
        
            else:

<p>For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.</p>

<p>Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.</p>

<pre><strong>Input:</strong> asteroids = [5,10,-5]
<strong>Output:</strong> [5,10]
<strong>Explanation:</strong> The 10 and -5 collide resulting in 10. The 5 and 10 never collide.
</pre>

<pre><strong>Input:</strong> asteroids = [8,-8]
<strong>Explanation:</strong> The 8 and -8 collide exploding each other.
</pre>

<pre><strong>Input:</strong> asteroids = [10,2,-5]
<strong>Output:</strong> [10]
<strong>Explanation:</strong> The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10.
</pre>

<ul>
	<li><code>2 &lt;= asteroids.length &lt;= 10<sup>4</sup></code></li>
	<li><code>-1000 &lt;= asteroids[i] &lt;= 1000</code></li>
	<li><code>asteroids[i] != 0</code></li>
</ul>
</div>

directory: 590-n-ary-tree-postorder-traversal
"""

    def postorder(self, root: 'Node') -> List[int]:
        def rec(root):
            if root:
                    rec(c)
                out.append(root.val)

        out = []
        rec(root)
        return out
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/n-ary-tree-postorder-traversal/">590. N-ary Tree Postorder Traversal</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of an n-ary tree, return <em>the postorder traversal of its nodes' values</em>.</p>

"""
"""

            if root:
                    rec(c)

        out = []
        rec(root)
        return out
        
<img src="https://assets.leetcode.com/uploads/2018/10/12/narytreeexample.png" style="width: 100%; max-width: 300px;">
<strong>Output:</strong> [5,6,3,2,4,1]
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2019/11/08/sample_4_964.png" style="width: 296px; height: 241px;">
<strong>Output:</strong> [2,6,14,11,7,3,12,8,4,13,9,10,5,1]
</pre>

<ul>
</ul>

directory: 1570-dot-product-of-two-sparse-vectors
Python: class SparseVector:
    def __init__(self, nums: List[int]):
        self.sparse_vector = defaultdict(int)
            if num != 0:
                self.sparse_vector[i] = num
    # Return the dotProduct of two sparse vectors
    def dotProduct(self, vec: 'SparseVector') -> int:
        
        product = 0
        for i in self.sparse_vector:
            if i in vec.sparse_vector:
                product += self.sparse_vector[i] * vec.sparse_vector[i]
        return product
# Your SparseVector object will be instantiated and called as such:
# v1 = SparseVector(nums1)
# v2 = SparseVector(nums2)
# ans = v1.dotProduct(v2)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/dot-product-of-two-sparse-vectors/">1570. Dot Product of Two Sparse Vectors</a></h2><h3>Medium</h3><hr><div><p>Given two sparse vectors, compute their dot product.</p>

class SparseVector:
            if num != 0:
        
        product = 0

<p>Implement class <code>SparseVector</code>:</p>

<ul data-indent="0" data-stringify-type="unordered-list">
	<li><code>SparseVector(nums)</code>&nbsp;Initializes the object with the vector <code>nums</code></li>
	<li><code>dotProduct(vec)</code>&nbsp;Compute the dot product between the instance of <em>SparseVector</em> and <code>vec</code></li>
</ul>

<p>A <strong>sparse vector</strong> is a vector that has mostly zero values, you should store the sparse vector&nbsp;<strong>efficiently </strong>and compute the dot product between two <em>SparseVector</em>.</p>

<p><strong>Follow up:&nbsp;</strong>What if only one of the vectors is sparse?</p>

<pre><strong>Input:</strong> nums1 = [1,0,0,2,3], nums2 = [0,3,0,4,0]
<strong>Explanation:</strong> v1 = SparseVector(nums1) , v2 = SparseVector(nums2)
v1.dotProduct(v2) = 1*0 + 0*3 + 0*0 + 2*4 + 3*0 = 8
</pre>

<pre><strong>Input:</strong> nums1 = [0,1,0,0,0], nums2 = [0,0,0,0,2]
v1.dotProduct(v2) = 0*0 + 1*0 + 0*0 + 0*0 + 0*2 = 0
</pre>

<pre><strong>Input:</strong> nums1 = [0,1,0,0,2,0,0], nums2 = [1,0,0,0,3,0,4]
</pre>

<ul>
	<li><code>1 &lt;= n &lt;= 10^5</code></li>
	<li><code>0 &lt;= nums1[i], nums2[i]&nbsp;&lt;= 100</code></li>
</ul>
</div>

directory: 259-3sum-smaller
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/3sum-smaller/">259. 3Sum Smaller</a></h2><h3>Medium</h3><hr><div><p>Given an array of <code>n</code> integers <code>nums</code> and an integer&nbsp;<code>target</code>, find the number of index triplets <code>i</code>, <code>j</code>, <code>k</code> with <code>0 &lt;= i &lt; j &lt; k &lt; n</code> that satisfy the condition <code>nums[i] + nums[j] + nums[k] &lt; target</code>.</p>

<pre><strong>Input:</strong> nums = [-2,0,1,3], target = 2
<strong>Explanation:</strong> Because there are two triplets which sums are less than 2:
[-2,0,1]
[-2,0,3]
</pre>

</pre>

<pre><strong>Input:</strong> nums = [0], target = 0
</pre>

<ul>
	<li><code>0 &lt;= n &lt;= 3500</code></li>
	<li><code>-100 &lt;= target &lt;= 100</code></li>
</ul>
</div>

directory: 653-two-sum-iv-input-is-a-bst
    def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
        
        dic = {}
        
            nonlocal dic
            else:
                val = root.val
                if k - val in dic:
                dic[val] = k-val
                return dfs(root.left) or dfs(root.right)
        return dfs(root)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/two-sum-iv-input-is-a-bst/">653. Two Sum IV - Input is a BST</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a Binary Search Tree and a target number <code>k</code>, return <em><code>true</code> if there exist two elements in the BST such that their sum is equal to the given target</em>.</p>

        dic = {}
        
            else:

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/21/sum_tree_1.jpg" style="width: 400px; height: 229px;">
<pre><strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 9
</pre>

<img alt="" src="https://assets.leetcode.com/uploads/2020/09/21/sum_tree_2.jpg" style="width: 400px; height: 229px;">
<pre><strong>Input:</strong> root = [5,3,6,2,4,null,7], k = 28
</pre>

<ul>
	<li><code>-10<sup>4</sup>&nbsp;&lt;= Node.val &lt;= 10<sup>4</sup></code></li>
	<li><code>root</code> is guaranteed to be a <strong>valid</strong> binary search tree.</li>
	<li><code>-10<sup>5</sup>&nbsp;&lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>
</div>

directory: 0257-binary-tree-paths
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/binary-tree-paths/">257. Binary Tree Paths</a></h2><h3>Easy</h3><hr><div><p>Given the <code>root</code> of a binary tree, return <em>all root-to-leaf paths in <strong>any order</strong></em>.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/paths-tree.jpg" style="width: 207px; height: 293px;">
<pre><strong>Input:</strong> root = [1,2,3,null,5]
<strong>Output:</strong> ["1-&gt;2-&gt;5","1-&gt;3"]
</pre>

<strong>Output:</strong> ["1"]
</pre>

<ul>
	<li>The number of nodes in the tree is in the range <code>[1, 100]</code>.</li>
</ul>
</div>

directory: 617-merge-two-binary-trees
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        
        if not root1:
            return root2
        if not root2:
            return root1
        root1.val += root2.val
        root1.left = self.mergeTrees(root1.left, root2.left)
        root1.right = self.mergeTrees(root1.right, root2.right)
        return root1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/merge-two-binary-trees/">617. Merge Two Binary Trees</a></h2><h3>Easy</h3><hr><div><p>You are given two binary trees <code>root1</code> and <code>root2</code>.</p>

<p>Imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. You need to merge the two trees into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of the new tree.</p>

<p>Return <em>the merged tree</em>.</p>

<p><strong>Note:</strong> The merging process must start from the root nodes of both trees.</p>

<img alt="" src="https://assets.leetcode.com/uploads/2021/02/05/merge.jpg" style="width: 600px; height: 163px;">
<pre><strong>Input:</strong> root1 = [1,3,2,5], root2 = [2,1,3,null,4,null,7]
<strong>Output:</strong> [3,4,5,5,4,null,7]
</pre>

<pre><strong>Input:</strong> root1 = [1], root2 = [1,2]
<strong>Output:</strong> [2,2]
</pre>

<ul>
	<li>The number of nodes in both trees is in the range <code>[0, 2000]</code>.</li>
</ul>
</div>

directory: 500-keyboard-row
    def findWords(self, words: List[str]) -> List[str]:
        
        dic = dict()
        num = 0
        for l in ["qwertyuiop", "asdfghjkl", "zxcvbnm" ]:
            for c in l:
                dic[c] = num
            num += 1
        ans = []
            check = dic[word[0].lower()]
            to_add = True
            for c in word:
                if dic[c.lower()] != check:
                    to_add = False
                    break
            if to_add:
        return ans
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/keyboard-row/">500. Keyboard Row</a></h2><h3>Easy</h3><hr><div><p>Given an array of strings <code>words</code>, return <em>the words that can be typed using letters of the alphabet on only one row of American keyboard like the image below</em>.</p>

<p>In the <strong>American keyboard</strong>:</p>

        num = 0
            for c in l:
            num += 1
        ans = []
                    break
            if to_add:
        return ans

<ul>
	<li>the first row consists of the characters <code>"qwertyuiop"</code>,</li>
	<li>the second row consists of the characters <code>"asdfghjkl"</code>, and</li>
	<li>the third row consists of the characters <code>"zxcvbnm"</code>.</li>
</ul>
<img alt="" src="https://assets.leetcode.com/uploads/2018/10/12/keyboard.png" style="width: 800px; max-width: 600px; height: 267px;">

<pre><strong>Input:</strong> words = ["Hello","Alaska","Dad","Peace"]
<strong>Output:</strong> ["Alaska","Dad"]
</pre>

<pre><strong>Input:</strong> words = ["omk"]
</pre>

<pre><strong>Input:</strong> words = ["adsdf","sfd"]
<strong>Output:</strong> ["adsdf","sfd"]
</pre>

<ul>
	<li><code>1 &lt;= words.length &lt;= 20</code></li>
	<li><code>1 &lt;= words[i].length &lt;= 100</code></li>
	<li><code>words[i]</code> consists of English letters (both lowercase and uppercase).&nbsp;</li>
</ul>
</div>

directory: 596-classes-more-than-5-students
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/classes-more-than-5-students/">596. Classes More Than 5 Students</a></h2><h3>Easy</h3><hr><div class="sql-schema-wrapper__3VBi"><a class="sql-schema-link__3cEg">SQL Schema<svg viewBox="0 0 24 24" width="1em" height="1em" class="icon__1Md2"><path fill-rule="evenodd" d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"></path></svg></a></div><div><p>Table: <code>Courses</code></p>

| student     | varchar |
| class       | varchar |
(student, class) is the primary key column for this table.
Each row of this table indicates the name of a student and the class in which they are enrolled.
</pre>

<p>Write an SQL query to report all the classes that have <strong>at least five students</strong>.</p>

Courses table:
+---------+----------+
| student | class    |
| A       | Math     |
| B       | English  |
| C       | Math     |
| D       | Biology  |
| E       | Math     |
| F       | Computer |
| G       | Math     |
| H       | Math     |
| I       | Math     |
| class   |
| Math    |
- Math has 6 students, so we include it.
- English has 1 student, so we do not include it.
- Biology has 1 student, so we do not include it.
- Computer has 1 student, so we do not include it.
</pre>
</div>

directory: 647-palindromic-substrings
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/palindromic-substrings/">647. Palindromic Substrings</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, return <em>the number of <strong>palindromic substrings</strong> in it</em>.</p>

<p>A string is a <strong>palindrome</strong> when it reads the same backward as forward.</p>

<p>A <strong>substring</strong> is a contiguous sequence of characters within the string.</p>

<pre><strong>Input:</strong> s = "abc"
<strong>Explanation:</strong> Three palindromic strings: "a", "b", "c".
</pre>

<pre><strong>Input:</strong> s = "aaa"
<strong>Explanation:</strong> Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
</pre>

<ul>
</ul>
</div>

directory: 53-maximum-subarray
    def maxSubArray(self, nums: List[int]) -> int:
        
        currSum, longestSum = 0, float('-inf')
            currSum = max(n, currSum + n)
            longestSum = max(longestSum, currSum)
        return longestSum
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-subarray/">53. Maximum Subarray</a></h2><h3>Medium</h3><hr><div><p>Given an integer array <code>nums</code>, find the contiguous subarray (containing at least one number) which has the largest sum and return <em>its sum</em>.</p>

<pre><strong>Input:</strong> nums = [-2,1,-3,4,-1,2,1,-5,4]
<strong>Explanation:</strong> [4,-1,2,1] has the largest sum = 6.
</pre>

</pre>

<pre><strong>Input:</strong> nums = [5,4,-1,7,8]
</pre>

<ul>
</ul>

<p><strong>Follow up:</strong> If you have figured out the <code>O(n)</code> solution, try coding another solution using the <strong>divide and conquer</strong> approach, which is more subtle.</p>
</div>

directory: 1297-maximum-number-of-occurrences-of-a-substring
    def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:
        
        count = Counter()
        n = len(s)
        for i in range(n - minSize + 1):
            sub_str = s[i:i  + minSize]
            if len(set(sub_str)) <= maxLetters:
                count[sub_str] += 1
        return max(count.values()) if count else 0
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/maximum-number-of-occurrences-of-a-substring/">1297. Maximum Number of Occurrences of a Substring</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, return the maximum number of ocurrences of <strong>any</strong> substring under the following rules:</p>

<ul>
	<li>The number of unique characters in the substring must be less than or equal to <code>maxLetters</code>.</li>
	<li>The substring size must be between <code>minSize</code> and <code>maxSize</code> inclusive.</li>
</ul>

        n = len(s)

<pre><strong>Input:</strong> s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
<strong>Explanation:</strong> Substring "aab" has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
</pre>

<pre><strong>Input:</strong> s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
<strong>Explanation:</strong> Substring "aaa" occur 2 times in the string. It can overlap.
</pre>

<ul>
	<li><code>1 &lt;= maxLetters &lt;= 26</code></li>
	<li><code>1 &lt;= minSize &lt;= maxSize &lt;= min(26, s.length)</code></li>
</ul>
</div>

directory: 159-longest-substring-with-at-most-two-distinct-characters
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        
        max_len = 0
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/">159. Longest Substring with At Most Two Distinct Characters</a></h2><h3>Medium</h3><hr><div><p>Given a string <code>s</code>, return <em>the length of the longest substring that contains at most <strong>two distinct characters</strong></em>.</p>

        max_len = 0
    
<pre><strong>Input:</strong> s = "eceba"
<strong>Explanation:</strong> The substring is "ece" which its length is 3.
</pre>

<pre><strong>Input:</strong> s = "ccaabbb"
<strong>Explanation:</strong> The substring is "aabbb" which its length is 5.
</pre>

<ul>
	<li><code>s</code> consists of English letters.</li>
</ul>
</div>

directory: 33-search-in-rotated-sorted-array
    def search(self, nums: List[int], target: int) -> int:
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                if nums[left] <= target and nums[left] > nums[mid]:
                else:
            if nums[mid] > target:
                if nums[right] >= target and nums[right]<nums[mid]:
                else:
                
        return -1
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/search-in-rotated-sorted-array/">33. Search in Rotated Sorted Array</a></h2><h3>Medium</h3><hr><div><p>There is an integer array <code>nums</code> sorted in ascending order (with <strong>distinct</strong> values).</p>

                return mid
                else:
                else:
                
        return -1

<p>Prior to being passed to your function, <code>nums</code> is <strong>possibly rotated</strong> at an unknown pivot index <code>k</code> (<code>1 &lt;= k &lt; nums.length</code>) such that the resulting array is <code>[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]</code> (<strong>0-indexed</strong>). For example, <code>[0,1,2,4,5,6,7]</code> might be rotated at pivot index <code>3</code> and become <code>[4,5,6,7,0,1,2]</code>.</p>

<p>Given the array <code>nums</code> <strong>after</strong> the possible rotation and an integer <code>target</code>, return <em>the index of </em><code>target</code><em> if it is in </em><code>nums</code><em>, or </em><code>-1</code><em> if it is not in </em><code>nums</code>.</p>

<pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 0
<pre><strong>Input:</strong> nums = [4,5,6,7,0,1,2], target = 3
<pre><strong>Input:</strong> nums = [1], target = 0
</pre>

<ul>
	<li>All values of <code>nums</code> are <strong>unique</strong>.</li>
	<li><code>nums</code> is an ascending array that is possibly rotated.</li>
</ul>
</div>

directory: 331-verify-preorder-serialization-of-a-binary-tree
    def isValidSerialization(self, preorder: str) -> bool:
        
        stack = []
        preorder = preorder.split(',')
        for c in preorder:
            stack.append(c)
            while len(stack) > 2 and stack[-3] != '#' and stack[-2] == '#' and stack[-1] =='#':
                stack.pop(); stack.pop(); stack.pop();
                stack.append('#')
            #print(stack)
        return len(stack) == 1 and stack[0] == '#'
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/verify-preorder-serialization-of-a-binary-tree/">331. Verify Preorder Serialization of a Binary Tree</a></h2><h3>Medium</h3><hr><div><p>One way to serialize a binary tree is to use <strong>preorder traversal</strong>. When we encounter a non-null node, we record the node's value. If it is a null node, we record using a sentinel value such as <code>'#'</code>.</p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/03/12/pre-tree.jpg" style="width: 362px; height: 293px;">
<p>For example, the above binary tree can be serialized to the string <code>"9,3,4,#,#,1,#,#,2,#,6,#,#"</code>, where <code>'#'</code> represents a null node.</p>

        stack = []
        
<p>Given a string of comma-separated values <code>preorder</code>, return <code>true</code> if it is a correct preorder traversal serialization of a binary tree.</p>

<p>It is <strong>guaranteed</strong> that each comma-separated value in the string must be either an integer or a character <code>'#'</code> representing null pointer.</p>

<p>You may assume that the input format is always valid.</p>

<ul>
	<li>For example, it could never contain two consecutive commas, such as <code>"1,,3"</code>.</li>
</ul>

<p><strong>Note:&nbsp;</strong>You are not allowed to reconstruct the tree.</p>

<pre><strong>Input:</strong> preorder = "9,3,4,#,#,1,#,#,2,#,6,#,#"
<pre><strong>Input:</strong> preorder = "1,#"
<pre><strong>Input:</strong> preorder = "9,#,#,1"
</pre>

<ul>
	<li><code>preorder</code> consist of integers in the range <code>[0, 100]</code> and <code>'#'</code> separated by commas <code>','</code>.</li>
</ul>
</div>

directory: 0976-largest-perimeter-triangle
Python: 
Notes: ​

</pre>

</pre>

<ul>
</ul>
</div>

directory: 1254-number-of-closed-islands
Python: 
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/number-of-closed-islands/">1254. Number of Closed Islands</a></h2><h3>Medium</h3><hr><div><p>Given a 2D&nbsp;<code>grid</code> consists of <code>0s</code> (land)&nbsp;and <code>1s</code> (water).&nbsp; An <em>island</em> is a maximal 4-directionally connected group of <code><font face="monospace">0</font>s</code> and a <em>closed island</em>&nbsp;is an island <strong>totally</strong>&nbsp;(all left, top, right, bottom) surrounded by <code>1s.</code></p>

<p>Return the number of <em>closed islands</em>.</p>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/10/31/sample_3_1610.png" style="width: 240px; height: 120px;"></p>

<pre><strong>Input:</strong> grid = [[1,1,1,1,1,1,1,0],[1,0,0,0,0,1,1,0],[1,0,1,0,1,1,1,0],[1,0,0,0,0,1,0,1],[1,1,1,1,1,1,1,0]]
Islands in gray are closed because they are completely surrounded by water (group of 1s).</pre>

<p><img alt="" src="https://assets.leetcode.com/uploads/2019/10/31/sample_4_1610.png" style="width: 160px; height: 80px;"></p>

<pre><strong>Input:</strong> grid = [[0,0,1,0,0],[0,1,0,1,0],[0,1,1,1,0]]
</pre>

<pre><strong>Input:</strong> grid = [[1,1,1,1,1,1,1],
&nbsp;              [1,0,0,0,0,0,1],
&nbsp;              [1,0,1,1,1,0,1],
&nbsp;              [1,0,1,0,1,0,1],
               [1,1,1,1,1,1,1]]
</pre>

<ul>
	<li><code>1 &lt;= grid.length, grid[0].length &lt;= 100</code></li>
	<li><code>0 &lt;= grid[i][j] &lt;=1</code></li>
</ul>
</div>

directory: 0106-construct-binary-tree-from-inorder-and-postorder-traversal
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        def build_tree(left, right):    
            val = postorder.pop()
            root = TreeNode(val)
            index = dic[val]
            root.right = build_tree(index + 1, right)
            root.left = build_tree(left, index - 1)
        
        dic = {n : i for i, n in enumerate(inorder)}
        return build_tree(0, len(inorder)-1)
Notes: ​
Readme: <h2><a href="https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/">106. Construct Binary Tree from Inorder and Postorder Traversal</a></h2><h3>Medium</h3><hr><div><p>Given two integer arrays <code>inorder</code> and <code>postorder</code> where <code>inorder</code> is the inorder traversal of a binary tree and <code>postorder</code> is the postorder traversal of the same tree, construct and return <em>the binary tree</em>.</p>

<pre><strong>Input:</strong> inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
</pre>

<pre><strong>Input:</strong> inorder = [-1], postorder = [-1]
</pre>

<ul>
	<li><code>1 &lt;= inorder.length &lt;= 3000</code></li>
	<li><code>postorder.length == inorder.length</code></li>
	<li><code>-3000 &lt;= inorder[i], postorder[i] &lt;= 3000</code></li>
	<li><code>inorder</code> and <code>postorder</code> consist of <strong>unique</strong> values.</li>
	<li>Each value of <code>postorder</code> also appears in <code>inorder</code>.</li>
	<li><code>postorder</code> is <strong>guaranteed</strong> to be the postorder traversal of the tree.</li>
</ul>
</div>