LeetCode Weekly Contest 241
Both this week’s weekly contest and biweekly contest went badly. Time to start the Cruel Coding check-in journey.
| Rank | Name | Score | Finish Time | Q1 (3) | Q2 (5) | Q3 (5) | Q4 (6) |
|---|---|---|---|---|---|---|---|
| 717 / 11572 | YoungForest | 12 | 0:23:51 | 0:05:35 | 0:17:33 | 0:23:51 | null |
1863. Sum of All Subset XOR Totals
A warm-up problem. Brute-force backtracking, enumerating all subsets.
1 | class Solution { |
Time complexity: O(2^n),
space complexity: O(n).
1864. Minimum Number of Swaps to Make the Binary String Alternating
First count the number of '0/1' characters and see whether an alternating string can be formed.
Then try the two alternating patterns: 1 first / 0 first.
The key is that only the number of mismatches matters; there is no need to consider exactly how to swap.
1 | class Solution { |
One thing to note:
1 | for (char first : "01"s) |
must not be written as:
1 | for (char first : "01") |
because the former is a string literal of type std::string, while the latter is a C-style static string and has a \n terminator.
1865. Finding Pairs With a Certain Sum
First observe the data scale. nums1.length is small, while nums2.length is large. So consider iterating over the small one and optimizing the large one with a hash.
Use a reverse hashtable to record the mapping from nums2 value -> index.
Time complexity:
- Construction: O(nums2.length),
- add: O(1),
- count: O(nums1.length).
Space complexity: O(nums2.length).
1 | class FindSumPairs { |
1866. Number of Ways to Rearrange Sticks With K Sticks Visible
For this problem, I only thought of an O(N^3) solution.
Use Dynamic Programming. The state transition is:
1 | ans = 0 |
That is, consider sticks from high to low, because the tallest one must be visible. Enumerate where the i-th stick is placed. Among the remaining i-1 sticks, choose some to put after i; what follows is a counting enumeration.
From the time complexity alone, it is certain to time out. In fact, it did, even though I tried hard to optimize constants.
Below is my final TLE code.
1 | MOD = 10**9 + 7 |
I referred to some solutions, and indeed my recurrence was wrong.
In fact, this formula can be derived from multiple perspectives:
With a small fix to my TLE code, it is OK.
1 | class Solution: |