LeetCode weekly contest 146
Today my high school classmate xl came to Beijing to chat with me. I had lunch and dinner with him and hcq, and we chatted for the whole afternoon. During the morning contest, I only hurriedly finished the warm-up problem. For the second problem, because of carelessness, I wrote the timing of the red change incorrectly and had no time to debug it. I did not even look at the last two problems.
After coming back at 9 p.m., I finally finished the problems, and also found the bug in the second problem.
But in terms of time, it should have been too late.
Rank 1800+.
Overall, although the problems in this contest were not hard, they required time and thinking to solve. These are also the kind of problems I like. Solving a problem that does not reveal its answer at first glance through my own thinking feels great. The thrill is better than godlike mode and triple kills.
5130. Number of Equivalent Domino Pairs
Since dominoes can be equal after rotation, we normalize them (map the two kinds of dominoes into one).
Then just compute the number of combinations.
Time complexity: O(N log N), because pair is not hashable by default, so I lazily used map.
Space complexity: O(N).
1 | class Solution { |
1129. Shortest Path with Alternating Colors
Compute shortest paths with BFS. Because colors must alternate, the code is a little troublesome and needs two sets of variables.
Time complexity: O(N), each node is traversed at most twice.
Space complexity: O(max(N, edges)).
1 | class Solution { |
5131. Minimum Cost Tree From Leaf Values
This was the hardest problem in this contest. I also spent a long time thinking before figuring it out.
First, observe:
- The relationship between the number of levels and the number of leaves. n levels have at least n leaves and at most 2^(n-1) leaves.
- Once the number of leaves is fixed, the number of non-leaf nodes is also fixed.
- By observing small trees, we can get a greedy solution. Lift larger leaves upward as much as possible, reducing their levels so they influence fewer non-leaf nodes, which minimizes the total sum.
Time complexity: O(n log n). Similar to quicksort, it divides the problem into two subproblems and still needs an end - begin combination step.
Space complexity: O(n), n leaves can have at most n levels, which is the recursion depth.
1 | class Solution { |
1131. Maximum of Absolute Value Expression
First observe the data scale, 40000, which rules out the brute-force O(N^2) solution.
Look for an O(N) or O(N log N) solution.
In fact, because each absolute value has two effects: unchanged or negated. There are three absolute value signs, so just enumerate 2^3 = 8 combinations.
Time complexity: O(8 * N)
Space complexity: O(N), which can easily be reduced to O(1).
1 | class Solution { |