<![CDATA[Long Luo's Life Notes]]> 2022-06-22T11:25:28.814Z http://www.longluo.me/ Hexo <![CDATA[[Leetcode][215. Kth Largest Element in an Array] 3 Approaches: Sorting, Priority Queue, Divide and Conquer]]> http://www.longluo.me//blog/2022/06/22/Leetcode-kth-largest-element-in-an-array/ 2022-06-22T00:34:19.000Z 2022-06-22T11:25:28.814Z By Long Luo

Here shows 3 Approaches to slove this problem: Sorting, Priority Queue, Divide and Conquer.

# Sort

Sort the array first, then the k-th element.

## Analysis

• Time Complexity: O(nlogn).
• Space Complexity: O(logn).

# Priority Queue

## Analysis

• Time Complexity: O(nlogk).
• Space Complexity: O(k).

# Divide and Conquer

## Analysis

• Time Complexity: O(n).
• Space Complexity: O(1).

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here shows 3 Approaches to slove this problem: Sorting, Priority Queue, Divide and Conquer.

# Sort

Sort the array first, then the k-th element.

## Analysis

• Time Complexity: O(nlogn).
• Space Complexity: O(logn).
]]>
<![CDATA[[Leetcode][1642. Furthest Building You Can Reach] Priority Queue + Greedy: Consider Ladder as a One-time Unlimited Bricks]]> http://www.longluo.me//blog/2022/06/21/Leetcode-furthest-building-you-can-reach/ 2022-06-21T01:18:43.000Z 2022-06-21T01:27:41.464Z By Long Luo

# Intuition

While we are moving, we will need to use bricks or ladders several times. Suppose we have to move to the next building, which means we must use one ladder or $\Delta h$ bricks, so there is a question, whether to use ladders or bricks?

If the gap of buildings is large, we may use the ladder, otherwise we use the bricks.

We can consider ladder as a one-time unlimited number of bricks, That is, if we have l ladders, we will use the ladder on the $l$ times where $\Delta h$ is the largest, and use the bricks in the rest.

Therefore, we got the answer. We maintain no more than $l$ largest $\Delta h$ using priority queues, and these are where the ladders are used. For the remaining $\Delta h$, we need to use bricks, so we need to accumulate them, if the $sum$ exceeds the number of bricks $b$, then we have move to the furthest building.

The code is as follows:

## Analysis

Time Complexity: $O(nlogl)$
Space Complexity: $O(l)$

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

# Intuition

While we are moving, we will need to use bricks or ladders several times. Suppose we have to move to the next building, which means we must use one ladder or $\Delta h$ bricks, so there is a question, whether to use ladders or bricks?

If the gap of buildings is large, we may use the ladder, otherwise we use the bricks.

We can consider ladder as a one-time unlimited number of bricks, That is, if we have l ladders, we will use the ladder on the $l$ times where $\Delta h$ is the largest, and use the bricks in the rest.

Therefore, we got the answer. We maintain no more than $l$ largest $\Delta h$ using priority queues, and these are where the ladders are used. For the remaining $\Delta h$, we need to use bricks, so we need to accumulate them, if the $sum$ exceeds the number of bricks $b$, then we have move to the furthest building.

The code is as follows:

]]>
<![CDATA[[Leetcode][120. Triangle] Dynamic Programming: Top-Down and Bottom-Up Approach]]> http://www.longluo.me//blog/2022/06/13/Leetcode-triangle/ 2022-06-12T23:15:21.000Z 2022-06-17T03:44:49.586Z By Long Luo

# Intuition

This problem is a classic and typical dynamic programming problem. We can break the large problem into sub-problems.

We can use both the Top-Down and Bottom-Up approach to solve this problem.

# Top-Down Approach

1. State definition:

$dp[i][j]$ represents the minimum path sum of row $i$ and column $j$.

1. State Analysis:

$dp=c$

1. The State Transfer Equation:

$dp[i][j] = \begin{cases} dp[i-1] + c[i] & j=0 \\ dp[i-1][i-1] + c[i][i] & j==i \\ min(dp[i-1][j-1],dp[i-1][j]) + c[i][j] & 0 < j < i \\ \end{cases}$

so we can easily write such code:

In fact, $dp[i][j]$ is only relevant to $dp[i-1][j]$, but $dp[i-2][j]$ and previous states are irrelevant, so we don’t have to store these states. We can only use extra $O(2n)$ space: two one-dimensional arrays of length $n$ for the transfer, and map $i$ to one of the one-dimensional arrays according to the parity, then $i-1$ is mapped to the other one-dimensional array.

We enumerate $j$ decreasingly from $i$ to $0$, so that we only need a one-dimensional array $dp$ of length $n$ to complete the state transition.

$dp[j] = min(dp[j-1], dp[j]) + c[i][j]$

## Analysis

• Time Complexity: $O(n^2)$.
• Space Complexity: $O(n)$.

# Bottom-Up Approach

The state transfer equation of bottom-up approach is:

$dp[i][j] = min(dp[i+1][j], dp[i+1][j+1]) + c[i][j]$

## Analysis

• Time Complexity: $O(n^2)$.
• Space Complexity: $O(n)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

# Intuition

This problem is a classic and typical dynamic programming problem. We can break the large problem into sub-problems.

We can use both the Top-Down and Bottom-Up approach to solve this problem.

# Top-Down Approach

1. State definition:

$dp[i][j]$ represents the minimum path sum of row $i$ and column $j$.

1. State Analysis:

$dp=c$

1. The State Transfer Equation:

$dp[i][j] = \begin{cases} dp[i-1] + c[i] & j=0 \\ dp[i-1][i-1] + c[i][i] & j==i \\ min(dp[i-1][j-1],dp[i-1][j]) + c[i][j] & 0 < j < i \\ \end{cases}$

so we can easily write such code:

In fact, $dp[i][j]$ is only relevant to $dp[i-1][j]$, but $dp[i-2][j]$ and previous states are irrelevant, so we don’t have to store these states. We can only use extra $O(2n)$ space: two one-dimensional arrays of length $n$ for the transfer, and map $i$ to one of the one-dimensional arrays according to the parity, then $i-1$ is mapped to the other one-dimensional array.

We enumerate $j$ decreasingly from $i$ to $0$, so that we only need a one-dimensional array $dp$ of length $n$ to complete the state transition.

$dp[j] = min(dp[j-1], dp[j]) + c[i][j]$

]]>

# Intuition

To simulate the CPU operations, there comes $3$ questions:

2. How to maintain the enqueued tasks?

Let’s answer the $3$ questions:

1. We assign the tasks to the CPU by $\textit{enqueueTime}$, so we sort the array first by $\textit{enqueueTime}$. However, we will lose the $\textit{index}$ of the task.

We can parse the task by creating a new class $\texttt{Job}$, whose members are $\textit{id}$, $\textit{enqueueTime}$, $\textit{processTime}$.

1. We put all the tasks assigned to the CPU into a Priority Queue and poll out the task whose $\textit{processTime}$ is the least each time.

2. We can maintain a $\textit{curTime}$ variable, which represents the current time with initial value is $0$.

If the CPU has no tasks to execute, we set the $\textit{curTime}$ to $\textit{enqueueTime}$ of the next task in the array that has not yet been assigned to the CPU.

After this, we put all $\textit{enqueueTime} \le \textit{curTime}$ tasks into the Priority Queue.

We can use an extra array which store the indices of the $\textit{tasks}$, then sorting the array by $\textit{enqueueTime}$.

So we can write more clean code.

## Analysis

• Time Complexity: $O(nlogn)$.
• Space Complexity: $O(n)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>

# Intuition

To simulate the CPU operations, there comes $3$ questions:

2. How to maintain the enqueued tasks?

Let’s answer the $3$ questions:

1. We assign the tasks to the CPU by $\textit{enqueueTime}$, so we sort the array first by $\textit{enqueueTime}$. However, we will lose the $\textit{index}$ of the task.

We can parse the task by creating a new class $\texttt{Job}$, whose members are $\textit{id}$, $\textit{enqueueTime}$, $\textit{processTime}$.

1. We put all the tasks assigned to the CPU into a Priority Queue and poll out the task whose $\textit{processTime}$ is the least each time.

2. We can maintain a $\textit{curTime}$ variable, which represents the current time with initial value is $0$.

If the CPU has no tasks to execute, we set the $\textit{curTime}$ to $\textit{enqueueTime}$ of the next task in the array that has not yet been assigned to the CPU.

After this, we put all $\textit{enqueueTime} \le \textit{curTime}$ tasks into the Priority Queue.

]]>
<![CDATA[[LeetCode][167. Two Sum II - Input Array Is Sorted] 4 Approaches: Brute Force, HashMap, Binary Search, Two Pointers]]> http://www.longluo.me//blog/2022/06/09/Leetcode-input-array-is-sorted/ 2022-06-08T23:59:29.000Z 2022-06-09T01:00:29.518Z By Long Luo

Here shows 4 Approaches to slove this problem: Brute Force, HashMap, Binary Search, Two Pointers.

# Brute Force

It’s easy to use Brute Force to find the answer, however, the time complexity is $O(n^2)$, so the BF solution will Time Limit Exceeded!

## Analysis

• Time Complexity: $O(n^2)$.
• Space Complexity: $O(1)$.

# HashMap

We can use a extra $\texttt{HashMap}$ to record the element we traversalled.

## Analysis

• Time Complexity: $O(n)$.
• Space Complexity: $O(n)$.

# Binary Search

Since the array is already sorted, so we can use the binary search. In case of duplicated answer, we search only on the right of the left element.

## Analysis

• Time Complexity: $O(nlogn)$.
• Space Complexity: $O(1)$.

# Two Pointers

1. Let the two pointers point to the position of the first element and the position of the last element;
2. Each time the sum of the two elements pointed to by the two pointers is calculated and compared with the target value.
3. A unique solution is found if the sum of the two elements equals the target value.
4. If the sum of the two elements is less than the target, move the left pointer to the right one place; If the sum of the two elements is greater than the target, move the right pointer to the left by one.
5. Repeat until you find the answer.

## Analysis

• Time Complexity: $O(n)$.
• Space Complexity: $O(1)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here shows 4 Approaches to slove this problem: Brute Force, HashMap, Binary Search, Two Pointers.

# Brute Force

It’s easy to use Brute Force to find the answer, however, the time complexity is $O(n^2)$, so the BF solution will Time Limit Exceeded!

## Analysis

• Time Complexity: $O(n^2)$.
• Space Complexity: $O(1)$.

# HashMap

We can use a extra $\texttt{HashMap}$ to record the element we traversalled.

]]>
<![CDATA[[Leetcode][440. K-th Smallest in Lexicographical Order] ]]> http://www.longluo.me//blog/2022/06/02/Leetcode-K-th-Smallest-in-Lexicographical-Order/ 2022-06-01T23:57:30.000Z 2022-06-22T01:20:49.723Z By Long Luo

]]>
By Long Luo

]]>
<![CDATA[[LeetCode][29. Divide Two Integers] 5 Approaches: BF use Long, BF use Int, Binary Search use Long, Binary Search use Int, Recursion]]> http://www.longluo.me//blog/2022/05/30/Leetcode-divide-two-integers-en/ 2022-05-29T23:26:25.000Z 2022-06-09T00:56:21.943Z By Long Luo

Here shows 5 Approaches to slove this problem: BF use long, BF use int, Binary Search use Long, Binary Search use Int, Recursion.

# Intuition

To divide two integers without using multiplication, division, and mod operator, so we can subtract the divisor from the dividend util the $\textit{result} \ge 0$.

# Brute Force use Long

We can make the dividend and divisor positive, and cast to long, then process.

The solution will Time Limit Exceeded, we have to deal with some corner cases.

## Analysis

• Time Complexity: $O(x / y)$.
• Space Complexity: $O(1)$.

# Brute Force use Int

Since the environment that could only store integers within the 32-bit signed integer, so we have to deal with it.

## Analysis

• Time Complexity: $O(x / y)$.
• Space Complexity: $O(1)$.

# Binary Search use Long

Refer to
Illustration of Fast Power Algorithm - Exponentiation by Squaring or Binary Exponentiation , we can use the quickAdd like the quickMul.

## Analysis

• Time Complexity: $O(logx \times logy)$.
• Space Complexity: $O(1)$.

# Binary Search use Int

1. the corner cases;
2. Record the sign of the final result and turn both numbers to negative numbers;
3. Approximate the divisor by increasing the dividend incrementally.

## Analysis

• Time Complexity: $O(logx \times logy)$.
• Space Complexity: $O(1)$.

# Recursion

The recurison method.

## Analysis

• Time Complexity: $O(logx \times logy)$.
• Space Complexity: $O(1)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here shows 5 Approaches to slove this problem: BF use long, BF use int, Binary Search use Long, Binary Search use Int, Recursion.

# Intuition

To divide two integers without using multiplication, division, and mod operator, so we can subtract the divisor from the dividend util the $\textit{result} \ge 0$.

# Brute Force use Long

We can make the dividend and divisor positive, and cast to long, then process.

The solution will Time Limit Exceeded, we have to deal with some corner cases.

## Analysis

• Time Complexity: $O(x / y)$.
• Space Complexity: $O(1)$.
]]>
<![CDATA[Python爬虫练习：微博热搜爬虫，微博爬虫 和 主页博文爬虫]]> http://www.longluo.me//blog/2022/05/23/Spider/ 2022-05-23T10:05:32.000Z 2022-06-18T02:37:54.609Z By Long Luo

# 微博爬虫

1. 个人信息
2. 具体时间段全部博文；
3. 将数据存入 Excel 和数据库中。

# 博客爬虫

## 功能

1. 获取某网站的全部博文比如 http://www.longluo.me/
2. 爬取内容：文章标题、发布时间、分类、链接、正文（HTML格式）等。

## 分析

1. 向目标网页发出请求

1. 获取网站博客的文章标题、发布时间和链接；
2. 数据写入Excel中；
3. 数据存入数据库中。

## 存储文章标题、发布时间和文章链接到Excel和数据库中

1. 存储到 Excel 可以直接使用 Pandas 的 to_csv

2. 数据库

• 初始化数据库 init_db()
• 将数据存储到 save_data_2_db()

]]>
By Long Luo

# 微博爬虫

1. 个人信息
2. 具体时间段全部博文；
3. 将数据存入 Excel 和数据库中。

# 博客爬虫

## 功能

1. 获取某网站的全部博文比如 http://www.longluo.me/
2. 爬取内容：文章标题、发布时间、分类、链接、正文（HTML格式）等。
]]>
<![CDATA[[LeetCode][329. Longest Increasing Path in a Matrix] 4 Approaches: BFS, Memory + DFS, DP, Topological Sorting]]> http://www.longluo.me//blog/2022/05/19/Leetcode-longest-increasing-path-in-a-matrix/ 2022-05-19T03:12:18.000Z 2022-05-19T03:20:19.557Z By Long Luo

Here shows 4 Approaches to slove this problem: BFS, Memory + DFS, DP, Topological Sorting.

# BFS

The simplest method that comes to my mind is BFS. We start search from each node, spread out like water, to see how far it can flood, and record the maximum flood path length of all nodes.

## Analysis

• Time Complexity: $O(m^2n^2)$.
• Space Complexity: $O(mn)$.

# Memory + DFS

It’s easy to figure out that there are some repeated enqueuing in BFS method.

Take a example, when searching the longest path of $2$, the longest path of $6$ will also be searched. However, we will search $6$ again as a starting node in BFS. So how to prune the search?

If we search $6$ first and store the result. When search $2$, we can know the result is $len(2) + len(6)$.

So we can use a memory to store the result, use DFS to search the longest path of each node.

## Analysis

• Time Complexity: $O(mn)$.
• Space Complexity: $O(mn)$.

# DP

We can also use the DP to solve this problem.

$dp[i][j]$ means the longest path from the position of $matrix[i][j]$.

The DP tranfer equation is as follows:

$dp[i][j] = max(dp[i][j], dp[nextX][nextY] + 1), matrix[nextX][nextY] > matrix[i][j]$

1. At the beginning, all the node is $1$.
2. We should search the larger adjacent nodes first.

## Analysis

• Time Complexity: $O(mnlog(mn)$.
• Space Complexity: $O(mn)$.

# Topo Sorting

Consider the matrix as a directed graph, and calculate the out-degree corresponding to each cell, how many edges start from the cell.

If the value of a cell is smaller than the value of all adjacent cells, so the out-degree of the cell will increate.

We can solve this problem using topo sorting.

## Analysis

• Time Complexity: $O(mn)$.
• Space Complexity: $O(mn)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here shows 4 Approaches to slove this problem: BFS, Memory + DFS, DP, Topological Sorting.

# BFS

The simplest method that comes to my mind is BFS. We start search from each node, spread out like water, to see how far it can flood, and record the maximum flood path length of all nodes.

## Analysis

• Time Complexity: $O(m^2n^2)$.
• Space Complexity: $O(mn)$.
]]>
<![CDATA[[LeetCode][1091. Shortest Path in Binary Matrix] Why Use BFS? Search Every Possible Path vs Search A Possible Path]]> http://www.longluo.me//blog/2022/05/16/Leetcode-shortest-path-in-binary-matrix/ 2022-05-15T23:05:02.000Z 2022-05-16T01:59:05.338Z By Long Luo

# Intuition

1. If we want to find a possible path, DFS will be more efficient. Because DFS will return a possible path if found, while it may not the shortest path.

2. BFS will try every possible path at the same time.

3. If we want to find the shortest of all possible paths, BFS is more efficient. It’s impossible for DFS to determine which is the shortest before trying all possible paths.

# BFS

Use BFS to Level Traversal.

## Analysis

• Time Complexity: $O(n)$.
• Space Complexity: $O(n)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

# Intuition

1. If we want to find a possible path, DFS will be more efficient. Because DFS will return a possible path if found, while it may not the shortest path.

2. BFS will try every possible path at the same time.

3. If we want to find the shortest of all possible paths, BFS is more efficient. It’s impossible for DFS to determine which is the shortest before trying all possible paths.

# BFS

Use BFS to Level Traversal.

]]>
<![CDATA[[LeetCode][117. Populating Next Right Pointers in Each Node II] 3 Approaches: BFS, BFS + LinkedList, Recursion]]> http://www.longluo.me//blog/2022/05/13/Leetcode-populating-next-right-pointers-in-each-node-ii/ 2022-05-13T03:05:02.000Z 2022-05-13T13:12:54.510Z By Long Luo

Here shows 3 Approaches to slove this problem: BFS, BFS + LinkedList, Recursion.

# BFS

Use BFS to level traversal, a List to store the Nodes of each level.

In fact, we just need a Node to store the Previous Node.

## Analysis

• Time Complexity: $O(n)$.
• Space Complexity: $O(n)$.

Each level can be seem as a Linked List.

For example, the root node is a linked list with one node, and the second level is a linked list with two nodes and so on…

In fact, we just need a Node to store the $Previous Node$.

## Analysis

• Time Complexity: $O(n)$.
• Space Complexity: $O(1)$.

# Recursion

It’s a little difficult but easy to get it.

## Analysis

• Time Complexity: $O(n)$.
• Space Complexity: $O(1)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here shows 3 Approaches to slove this problem: BFS, BFS + LinkedList, Recursion.

# BFS

Use BFS to level traversal, a List to store the Nodes of each level.

In fact, we just need a Node to store the Previous Node.

## Analysis

• Time Complexity: $O(n)$.
• Space Complexity: $O(n)$.
]]>
<![CDATA[[LeetCode][216. Combination Sum III] 2 Approaches: Backtracking and Bit Mask]]> http://www.longluo.me//blog/2022/05/10/Leetcode-combination-sum-iii/ 2022-05-10T01:43:47.000Z 2022-05-10T01:58:06.710Z By Long Luo

Here shows 2 Approaches to slove this problem: Backtracking and Bit Mask.

# Backtracking

A very easy backtracking solution. Just refer to 17. Letter Combinations of a Phone Number.

## Analysis

• Time Complexity: $O({M \choose k} \times k)$, $M$ is the size of combinations, $M = 9$, the total combinations is $M \choose k$.

• Space Complexity: $O(M + k)$, size of $path$ is $k$, the recursion stack is $O(M)$.

Since the numbers are just from $1$ to $9$, the total sum of combinations is $2^9=512$.

We can map $1$ - $9$ with a number with a length of 9-bits number, bits $0$ means selecting $1$, bits $8$ means selecting $9$.

Eg:

$000000001b$, means 
$000000011b$, means [1,2]
$100000011b$, means [1,2,9]

We can search from $1$ to $512$, take the number corresponding to the bit value of 1 in i, and sum it up to see if it is satisfied.

## Analysis

• Time Complexity: $O(M \times 2^M)$, $M = 9$, every state needs $O(M + k) = O(M)$ to check.

• Space Complexity: $O(M)$, $M$ is size of $\textit{path}$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here shows 2 Approaches to slove this problem: Backtracking and Bit Mask.

# Backtracking

A very easy backtracking solution. Just refer to 17. Letter Combinations of a Phone Number.

## Analysis

• Time Complexity: $O({M \choose k} \times k)$, $M$ is the size of combinations, $M = 9$, the total combinations is $M \choose k$.

• Space Complexity: $O(M + k)$, size of $path$ is $k$, the recursion stack is $O(M)$.

]]>
<![CDATA[[LeetCode][17. Letter Combinations of a Phone Number] 4 Approaches: BF 4 Loops, Backtracking, BFS, Queue with Image Explaination]]> http://www.longluo.me//blog/2022/05/09/Leetcode-letter-combinations-of-a-phone-number/ 2022-05-09T01:59:52.000Z 2022-05-10T01:50:48.357Z By Long Luo

Here shows 4 Approaches to slove this problem: Brute Force, Backtracking, BFS and Queue.

# Intuition

Take the $234$ for example, look at the tree: # Brute Froce(4 Loops)

Since the $digits.length <= 4$, we can just use the brute force approach $4$ Loops to search all the possible combinations.

The total states is $A(n,n)=A(4,4)=4!$. We have to enumerate all these states to get the answer.

## Analysis

• Time Complexity: $O(4^N)$
• Space Complexity: $O(N)$

# Backtracking

For the first number, there are $3$ options, and $3$ options for the second number and so on.

The combinations from the first to the last will expand into a recursive tree.

When the index reaches the end of digits, we get a combination, and add it to the result, end the current recursion. Finally we will get all the combinations.

## Analysis

• Time Complexity: $O(3^M \times 4^N)$
• Space Complexity: $O(3^M \times 4^N)$

# BFS

1. At the beginning, it is an empty string.
2. The new layer is obtained by adding characters at the end of the previous layer.
3. After the new layer is obtained, the previous layer is not used.

## Analysis

• Time Complexity: $O(3^M \times 4^N)$
• Space Complexity: $O(3^M \times 4^N)$

# Queue

Look at the gif, it’s easy to understand the queue solution.

First we enqueue each letter of the first number in the digits, and then combine the dequeued element with each letter of the second number and enqueue to the queue. ## Analysis

• Time Complexity: $O(3^M \times 4^N)$
• Space Complexity: $O(3^M \times 4^N)$

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here shows 4 Approaches to slove this problem: Brute Force, Backtracking, BFS and Queue.

# Intuition

Take the $234$ for example, look at the tree: # Brute Froce(4 Loops)

Since the $digits.length <= 4$, we can just use the brute force approach $4$ Loops to search all the possible combinations.

The total states is $A(n,n)=A(4,4)=4!$. We have to enumerate all these states to get the answer.

## Analysis

• Time Complexity: $O(4^N)$
• Space Complexity: $O(N)$

# Backtracking

For the first number, there are $3$ options, and $3$ options for the second number and so on.

The combinations from the first to the last will expand into a recursive tree.

When the index reaches the end of digits, we get a combination, and add it to the result, end the current recursion. Finally we will get all the combinations.

]]>
<![CDATA[[LeetCode][341. Flatten Nested List Iterator] 2 Approaches: DFS, Iteration(Using Stack)]]> http://www.longluo.me//blog/2022/05/08/Leetcode-flatten-nested-list-iterator/ 2022-05-08T01:17:01.000Z 2022-05-08T02:21:26.467Z By Long Luo

Here are 2 approaches to solve this problem in Java, DFS and Iteration approach.

# DFS

We can store all the integers in an array, just traversing the array.

## Analysis

• Time Complexity:

• $\texttt{NestedIterator}$: $O(n)$.
• $\texttt{next()}$: $O(1)$
• $\texttt{hasNext()}$: $O(1)$
• Space Complexity: $O(n)$.

# Iteration (Using Stack)

We can use a Stack to maintain all nodes on the path from the root node to the current node.

The stack stores the iterators, which is a pointer to the element.

## Analysis

• Time Complexity:

• $\texttt{NestedIterator}$: $O(1)$.
• $\texttt{next()}$: $O(1)$
• $\texttt{hasNext()}$: $O(1)$
• Space Complexity: $O(n)$.

The Iteration approach is better.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here are 2 approaches to solve this problem in Java, DFS and Iteration approach.

# DFS

We can store all the integers in an array, just traversing the array.

## Analysis

• Time Complexity:

• $\texttt{NestedIterator}$: $O(n)$.
• $\texttt{next()}$: $O(1)$
• $\texttt{hasNext()}$: $O(1)$
• Space Complexity: $O(n)$.

]]>
<![CDATA[[LeetCode][456. 132 Pattern] 6 Approaches: BF O(n^3), BF O(n^2), TreeMap, Monotonic Stack]]> http://www.longluo.me//blog/2022/05/07/Leetcode-132-pattern/ 2022-05-06T23:32:06.000Z 2022-06-17T06:44:40.019Z By Long Luo

Here are 6 approaches to solve this problem in Java.

# BF O(n^3)

It’s easy to use 3 loops to find $3$ elements which is $132$ pattern, but the time complexity is $O(n^3)$, so it wouldn’t accepted as timeout.

## Analysis

• Time Complexity: $O(n^3)$.
• Space Complexity: $O(1)$.

# BF O(n^2)

Noticed that $nums[j]$ is the peak of the $3$ elements, suppose the current element is $nums[j]$, we have to find the element $nums[k]$ that is smaller than $nums[j]$ after $j$, and the element $nums[i]$ that is smaller than $nums[k]$ before $j$.

1. Scan left from $j$ to $0$, $0 \le i \lt j$, whether there is $num[i] < nums[j]$, update the mininum $leftMin$;

2. Scan right from $j$ to the end, $j + 1 \le k \lt len$, whether there is $num[k] < nums[j]$, update the maxinum $rightMax$;

3. If exists and $leftMin < rightMax$, return true.

Let’s coding it.

## Analysis

• Time Complexity: $O(n^2)$.
• Space Complexity: $O(1)$.

# TreeMap

Method 2 is $O(n^2)$. With extra $O(n)$ space to store the elements of the array, we can reduce the time complexity to $O(n)$.

We have to maintain all the values of the array in the right of $j$. As we have determined $nums[i]$ and $nums[j]$, we only need to query the smallest element $nums[k]$ in the sorted set which is strictly larger than $nums[i]$.

Then if $nums[k] < nums[j]$, which means we have found the $3$ elements of $132$ pattern.

## Analysis

• Time Complexity: $O(nlogn)$.
• Space Complexity: $O(n)$.

# Monotonic Stack

We can use a stack to store the element of the array from the back to front, find $nums[k]$ in the stack, and then continue to scan forward to find $nums[i]$.

The stack must store elements with a larger index and a smaller value than $nums[j]$.

The process is like this:

1. Scanning from the back to the front, if the current element $nums[i]$ is larger than the top of the stack, which means $nums[i]$ may be the $nums[j]$ we are looking for;

2. Pop all the elements in the stack that are smaller than it. These elements are the the $nums[k]$, and the last pop-up is the maximum qualified $nums[k]$.

3. If this $num[k]$ is larger than the $nums[i]$ scanned forward, we find the answer.

## Analysis

• Time Complexity: $O(n)$.
• Space Complexity: $O(n)$.

All suggestions are welcome.
If you have any query or suggestion please comment below.
Please upvote👍 if you like💗 it. Thank you:-)

Explore More Leetcode Solutions. 😉😃💗

]]>
By Long Luo

Here are 6 approaches to solve this problem in Java.

# BF O(n^3)

It’s easy to use 3 loops to find $3$ elements which is $132$ pattern, but the time complexity is $O(n^3)$, so it wouldn’t accepted as timeout.

## Analysis

• Time Complexity: $O(n^3)$.
• Space Complexity: $O(1)$.

# BF O(n^2)

Noticed that $nums[j]$ is the peak of the $3$ elements, suppose the current element is $nums[j]$, we have to find the element $nums[k]$ that is smaller than $nums[j]$ after $j$, and the element $nums[i]$ that is smaller than $nums[k]$ before $j$.

1. Scan left from $j$ to $0$, $0 \le i \lt j$, whether there is $num[i] < nums[j]$, update the mininum $leftMin$;

2. Scan right from $j$ to the end, $j + 1 \le k \lt len$, whether there is $num[k] < nums[j]$, update the maxinum $rightMax$;

3. If exists and $leftMin < rightMax$, return true.

]]>
<![CDATA[LeetCode Top Interview Questions Questions | LeetCode 精选 TOP 面试题]]> http://www.longluo.me//blog/2022/05/03/Leetcode-top-interview-questions/ 2022-05-03T14:52:26.000Z 2022-06-09T07:18:30.147Z By Long Luo

LeetCode Top Interview Questions | 精选 TOP 面试题

No. Problems Difficulty Source Code Solution
001 Two Sum Easy Java
002 Add Two Numbers Medium Java
003 Longest Substring Without Repeating Characters Medium Java
004 Median of Two Sorted Arrays Hard Java
005 Longest Palindromic Substring Medium Java
007 Reverse Integer Easy Java
008 String to Integer (atoi) Medium Java
010 Regular Expression Matching Hard Java
011 Container With Most Water Medium Java
013 Roman to Integer Easy Java
014 Longest Common Prefix Easy Java
015 3Sum Medium Java
017 Letter Combinations of a Phone Number Medium Java
019 Remove Nth Node From End of List Easy Java
020 Valid Parentheses Easy Java
021 Merge Two Sorted Lists Easy Java
022 Generate Parentheses Medium Java
023 Merge k Sorted Lists Hard Java
026 Remove Duplicates from Sorted Array Easy Java
028 Implement strStr() Easy Java
029 Divide Two Integers Medium Java
033 Search in Rotated Sorted Array Medium Java
034 Search for a Range Medium Java
035 Search Insert Position Medium Java
036 Valid Sudoku Medium Java
038 Count and Say Easy Java
041 First Missing Positive Hard Java
042 Trapping Rain Water Hard Java
044 Wildcard Matching Hard Java
046 Permutations Medium Java
048 Rotate Image Medium Java
049 Group Anagrams Medium Java
050 Pow(x, n) Medium Java
053 Maximum Subarray Medium Java
054 Spiral Matrix Medium Java
055 Jump Game Medium Java
056 Merge Intervals Medium Java
062 Unique Paths Medium Java
066 Plus One Easy Java
069 Sqrt(x) Easy Java
070 Climbing Stairs Easy Java
073 Set Matrix Zeroes Medium Java
075 Sort Colors Medium Java
076 Minimum Window Substring Hard Java
078 Subsets Medium Java
079 Word Search Medium Java
084 Largest Rectangle in Histogram Hard Java
088 Merge Sorted Array Easy Java
091 Decode Ways Medium Java
094 Binary Tree Inorder Traversal Medium Java
098 Validate Binary Search Tree Medium Java
101 Symmetric Tree Easy Java
102 Binary Tree Level Order Traversal Easy Java
103 Binary Tree Zigzag Level Order Traversal Medium Java
104 Maximum Depth of Binary Tree Easy Java
105 Construct Binary Tree from Preorder and Inorder Traversal Medium Java
108 Convert Sorted Array to Binary Search Tree Easy Java
116 Populating Next Right Pointers in Each Node Medium Java
118 Pascal’s Triangle Easy Java
121 Best Time to Buy and Sell Stock Easy Java
122 Best Time to Buy and Sell Stock II Easy Java
124 Binary Tree Maximum Path Sum Hard Java
125 Valid Palindrome Easy Java
128 Longest Consecutive Sequence Hard Java
130 Surrounded Regions Medium Java
131 Palindrome Partitioning Medium Java
134 Gas Station Medium Java
136 Single Number Easy Java
138 Copy List with Random Pointer Medium Java
139 Word Break Medium Java
140 Word Break II Hard Java
141 Linked List Cycle Easy Java
146 LRU Cache Hard Java
148 Sort List Medium Java
149 Max Points on a Line Hard Java
150 Evaluate Reverse Polish Notation Medium Java
152 Maximum Product Subarray Medium Java
155 Min Stack Easy Java
160 Intersection of Two Linked Lists Easy Java
162 Find Peak Element Medium Java
163 Missing Ranges Medium [没权限]
166 Fraction to Recurring Decimal Medium Java
169 Majority Element Easy Java
171 Excel Sheet Column Number Easy Java
172 Factorial Trailing Zeroes Easy Java
179 Largest Number Medium Java
189 Rotate Array Easy Java
190 Reverse Bits Easy Java
191 Number of 1 Bits Easy Java
198 House Robber Easy Java
200 Number of Islands Medium Java
202 Happy Number Easy Java
204 Count Primes Easy Java
206 Reverse Linked List Easy Java
207 Course Schedule Medium Java
208 Implement Trie (Prefix Tree) Medium Java
210 Course Schedule II Medium Java
212 Word Search II Hard Java
215 Kth Largest Element in an Array Medium Java
217 Contains Duplicate Easy Java
218 The Skyline Problem Hard Java
227 Basic Calculator II Medium Java
230 Kth Smallest Element in a BST Medium Java
234 Palindrome Linked List Easy Java
236 Lowest Common Ancestor of a Binary Tree Medium Java
237 Delete Node in a Linked List Easy Java
238 Product of Array Except Self Medium Java
239 Sliding Window Maximum Hard Java
240 Search a 2D Matrix II Medium Java
242 Valid Anagram Easy Java
251 Flatten 2D Vector Medium [没权限]
253 Meeting Rooms II Medium [没权限]
268 Missing Number Easy Java
269 Alien Dictionary Hard [没权限]
277 Find the Celebrity Medium [没权限]
279 Perfect Squares Medium Java
283 Move Zeroes Easy Java
285 Inorder Successor in BST Medium [没权限]
287 Find the Duplicate Number Hard Java
295 Find Median from Data Stream Hard Java
297 Serialize and Deserialize Binary Tree Hard Java
300 Longest Increasing Subsequence Medium Java
308 Range Sum Query 2D - Mutable Medium [没权限]
315 Count of Smaller Numbers After Self Hard Java
322 Coin Change Medium Java
324 Wiggle Sort II Medium Java
326 Power of Three Easy Java
328 Odd Even Linked List Medium Java
329 Longest Increasing Path in a Matrix Hard Java
334 Increasing Triplet Subsequence Medium Java
340 Longest Substring with At Most K Distinct Characters Hard [Plus]
341 Flatten Nested List Iterator Medium Java
344 Reverse String Easy Java
347 Top K Frequent Elements Medium Java
348 Design Tic-Tac-Toe Medium [没权限]
350 Intersection of Two Arrays II Easy Java
371 Sum of Two Integers Medium Java
378 Kth Smallest Element in a Sorted Matrix Medium Java
380 Insert Delete GetRandom O(1) Medium Java
384 Shuffle an Array Medium Java
387 First Unique Character in a String Easy Java
395 Longest Substring with At Least K Repeating Characters Medium Java
412 Fizz Buzz Easy Java
454 4Sum II Medium Java

]]>
By Long Luo

LeetCode Top Interview Q]]>

<![CDATA[快速数论变换(Number Theoretic Transform)]]> http://www.longluo.me//blog/2022/05/01/Number-Theoretic-Transform/ 2022-04-30T22:55:21.000Z 2022-05-19T09:42:55.482Z By Long Luo

$\textit{FFT}$ 优点很多，但缺点也很明显。例如单位复根的实部和虚部分别是一个正弦及余弦函数，有大量浮点数计算，计算量很大，而且浮点数运算产生的误差会比较大。

# 快速数论变换(NTT)

$\textit{FFT}$ 的本质是什么？

• 将卷积操作变成了乘法操作。

• 单位复根

# 原根

$\textit{FFT}$ 中，我们总共用到了单位复根的这些性质：

1. $n$ 个单位复根互不相同；
2. $\omega_n^k=\omega_{2n}^{2k}$
3. $\omega_n^{k}=-\omega_n^{k+n/2}$
4. $\omega_n^a\times\omega_n^b=\omega_n^{a+b}$

$n$ 为大于 $1$$2$ 的幂，$p$ 为素数且 $n \mid (p-1)$$g$$p$ 的一个原根。

1. $g_n^n=g^{n\cdot\frac{p-1}{n}}=g^{p-1}$

2. $g_n^{\frac{n}{2}}=g^{\frac{p-1}{2}}$

3. $g_{an}^{ak}=g^{\frac{ak(p-1)}{an}}=g^{\frac{k(p-1)}{n}}=g_n^k$

1. $g_n^n \equiv 1 \pmod p$

2. $g_n^{\frac{n}{2}} \equiv -1 \pmod p$

3. $(g_n^{k+\frac{n}{2}})^2=g_n^{2k+n} \equiv g_n^{2k} \pmod p$

$\textit{NTT}$ : $X(m) = \sum\limits_{i=0}^{N}x(n)a^{mn} \pmod M$

$\textit{INTT}$ : $X(m) = N^{-1}\sum\limits_{i=0}^{N}x(n)a^{-mn} \pmod M$

# NTT 实现

$\textit{NTT}$ 也有递归版(Recursion)和迭代版(Iteration) $2$ 种实现：

## 复杂度分析

• 时间复杂度$O((m+n)log(m+n))$
• 空间复杂度$O(m+n)$

# 参考资料

]]> By Long Luo

$\textit{FFT}$ 优点很多，但缺点也很明显。例如单位复根的实部和虚部分别是一个正弦及余弦函数，有大量浮点数计算，计算量很大，而且浮点数运算产生的误差会比较大。

# 快速数论变换(NTT)

$\textit{FFT}$ 的本质是什么？

• 将卷积操作变成了乘法操作。

• 单位复根

# 原根

$\textit{FFT}$ 中，我们总共用到了单位复根的这些性质：

1. $n$ 个单位复根互不相同；
2. $\omega_n^k=\omega_{2n}^{2k}$
3. $\omega_n^{k}=-\omega_n^{k+n/2}$
4. $\omega_n^a\times\omega_n^b=\omega_n^{a+b}$

$n$ 为大于 $1$$2$ 的幂，$p$ 为素数且 $n \mid (p-1)$$g$$p$ 的一个原根。

1. $g_n^n=g^{n\cdot\frac{p-1}{n}}=g^{p-1}$

2. $g_n^{\frac{n}{2}}=g^{\frac{p-1}{2}}$

3. $g_{an}^{ak}=g^{\frac{ak(p-1)}{an}}=g^{\frac{k(p-1)}{n}}=g_n^k$

1. $g_n^n \equiv 1 \pmod p$

2. $g_n^{\frac{n}{2}} \equiv -1 \pmod p$

3. $(g_n^{k+\frac{n}{2}})^2=g_n^{2k+n} \equiv g_n^{2k} \pmod p$

$\textit{NTT}$ : $X(m) = \sum\limits_{i=0}^{N}x(n)a^{mn} \pmod M$

$\textit{INTT}$ : $X(m) = N^{-1}\sum\limits_{i=0}^{N}x(n)a^{-mn} \pmod M$

]]>
<![CDATA[快速傅里叶变换(FFT)算法的实现及优化]]> http://www.longluo.me//blog/2022/04/29/FFT-optimization/ 2022-04-28T23:15:32.000Z 2022-06-17T06:42:43.821Z By Long Luo

# Cooley–Tukey FFT Algorithm

$\textit{Cooley–Tukey FFT Algorithm}$ 通过使用分治算法实现将复杂问题简单化。

## FFT 分治过程 1. Divide：按照奇偶分为 $2$ 个子问题。
2. Conquer：递归处理 $2$ 个子问题
3. Combine：合并 $2$ 个子问题。

## 蝴蝶操作 # 空间优化

$y(k) = y_e(k) + \omega_{n}^{k} \cdot y_o(k+\frac{n}{2})$

$y(k + \frac{n}{2}) = y_e(k) - \omega_{n}^{k} \cdot y_o(k+\frac{n}{2})$

$cd \; t = \omega_{n}^{k} \cdot y_e(k+\frac{n}{2})$

$y_e(k+\frac{n}{2}) = y_e(k) - t$

$y_e(k) = y_e(k)+t$

# 位逆序置换

$8$ 项多项式为例，模拟递归拆分的过程：每一次分组情况如下图：

• 初始序列为 $\{x_0, x_1, x_2, x_3, x_4, x_5, x_6, x_7\}$

• 一次二分之后 $\{x_0, x_2, x_4, x_6\}, \{x_1, x_3, x_5, x_7\}$

• 两次二分之后 $\{x_0, x_4\}, \{x_2, x_6\}, \{x_1, x_5\}, \{x_3, x_7\}$

• 三次二分之后 $\{x_0\} \{x_4\} \{x_2\} \{x_6\} \{x_1\} \{x_5\} \{x_3\} \{x_7\}$

Index

## 反向二进制加法

$len=2^k$，其中 $k$ 表示二进制数的长度，设 $R(x)$ 表示长度为 $k$ 的二进制数 $x$ 翻转后的数（高位补 $0$）。我们要求的是： $R(0),R(1),\cdots,R(n-1)$

1. $R(0)=0$

2. 从小到大求 $R(x)$

1. 求最后一位之前的二进制数的倒置结果；

2. 把被抹去的原来的最后一位放回结果的第一位。

$R(x)=\left\lfloor \frac{R\left(\left\lfloor \frac{x}{2} \right\rfloor\right)}{2} \right\rfloor + (x\bmod 2)\times \frac{len}{2}$

$k=5$$len=(32)_{10}=(100000)_2$，假设待翻转的数是 $(25)_{10}=(11001)_2$

1. 考虑 $(12)_{10}=(1100)_2$，我们知道 $R((1100)_2)=R((01100)_2)=(00110)_2$，再右移一位就得到了 $(3)_{10}=(00011)_2$

2. 考虑个位，如果是 $1$，它就要翻转到数的最高位，即翻转数加上 $(16)_{10}=(10000)_2=2^{k-1}$，如果是 $0$ 则不用更改；

3. 最终结果是 $(00011)_2 + (10000)_2 = (19)_{10}$

# FFT 迭代版

$\left \{ a_0,a_1,a_2,a_3,a_4,a_5,a_6,a_7 \right \}$

$\left \{ a_0,a_2,a_4,a_6 \right \}, \left\{ a_1,a_3,a_5,a_7 \right \}$

$\left \{a_0,a_4 \right \},\left \{ a_2,a_6 \right \},\left\{ a_1,a_5 \right \},\left\{ a_3,a_7 \right \}$

$\left\{ a_0 \right \},\left\{ a_4 \right \},\left\{ a_2 \right \},\left\{ a_6 \right \},\left\{ a_1 \right \},\left\{ a_5 \right \},\left\{ a_3 \right \},\left\{ a_7 \right \}$

$\underbrace{\left\{a_0,a_4 \right \}}_{len=2},\underbrace{\left\{ a_2,a_6 \right \}}_{len=2},\underbrace{\left\{a_1,a_5 \right \}}_{len=2},\underbrace{\left\{a_3,a_7 \right \} }_{len=2}$

$len<<1$

$\underbrace{\left\{ a_0,a_2,a_4,a_6 \right \}}_{len=4}, \underbrace{\left\{ a_1,a_3,a_5,a_7 \right \}}_{len=4}$

$\mathop{\uparrow}\limits_{j=0} \underbrace{ \left\{a_0,a_4 \right \} }_{len=2},\mathop{\uparrow}\limits_{j+=len}\underbrace{\left\{a_2,a_6 \right \}}_{len=2},\mathop{\uparrow}\limits_{j+=len}\underbrace{\left\{ a_1,a_5 \right \}}_{len=2},\mathop{\uparrow}\limits_{j+=len}\underbrace{\left\{ a_3,a_7 \right \}}_{len=2}$

$\textit{FFT}$ 迭代版代码最终实现如下：

43. 字符串相乘

]]>
By Long Luo

# Cooley–Tukey FFT Algorithm

$\textit{Cooley–Tukey FFT Algorithm}$ 通过使用分治算法实现将复杂问题简单化。

## FFT 分治过程 1. Divide：按照奇偶分为 $2$ 个子问题。
2. Conquer：递归处理 $2$ 个子问题
3. Combine：合并 $2$ 个子问题。

## 蝴蝶操作 ]]>
<![CDATA[[Leetcode][396. 旋转函数] 3种方法：暴力法，动态规划，前缀和 + 滑动窗口]]> http://www.longluo.me//blog/2022/04/22/Leetcode-rotate-function/ 2022-04-21T23:26:35.000Z 2022-05-17T08:01:03.863Z By Long Luo

# 方法一： 暴力法

## 复杂度分析：

• 时间复杂度：$O(N^2)$，其中 $N$ 是数组 $\textit{nums}$ 的长度。

• 空间复杂度：$O(1)$

# 方法二： 动态规划

$F(0) = 0 \times nums + 1 \times nums + \ldots + (n-1) \times nums[n-1]$

$F(1) = 1 \times nums + 2 \times nums + \ldots + 0 \times nums[n-1] = F(0) + \sum_{i=0}^{n-1}nums[i] - n \times nums[n-1]$

$F(k+1) = F(k) + \sum_{i=0}^{n-1}nums[i]-n \times nums[n-k], 0 \le k \lt n$

$F(0)$出发，迭代计算出不同的$F(k)$，并求出最大值。

## 复杂度分析：

• 时间复杂度：$O(N)$，其中 $N$ 是数组的长度。

• 空间复杂度：$O(1)$

# 方法三： 前缀和 + 滑动窗口

$cur = nums[i] \times 0 + nums[i+1] \times 1 + ... + nums[i+n-1] \times (n-1)$