The post 花花酱 LeetCode 1192. Critical Connections in a Network appeared first on Huahua's Tech Road.

]]>`n`

servers numbered from `0`

to `n-1`

connected by undirected server-to-server `connections`

forming a network where `connections[i] = [a, b]`

represents a connection between servers `a`

and `b`

. Any server can reach any other server directly or indirectly through the network.
A *critical connection* is a connection that, if removed, will make some server unable to reach some other server.

Return all critical connections in the network in any order.

**Example 1:**

Input:n = 4, connections = [[0,1],[1,2],[2,0],[1,3]]Output:[[1,3]]Explanation:[[3,1]] is also accepted.

**Constraints:**

`1 <= n <= 10^5`

`n-1 <= connections.length <= 10^5`

`connections[i][0] != connections[i][1]`

- There are no repeated connections.

Time complexity: O(v+e)

Space complexity: O(v+e)

// Author: Huahua class Solution { public: vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) { vector<vector<int>> g(n); vector<int> ts(n, INT_MAX); vector<vector<int>> ans; int t = 0; function<int(int, int)> tarjan = [&](int i, int p) { int min_i = ts[i] = ++t; for (int j : g[i]) { if (ts[j] == INT_MAX) { int min_j = tarjan(j, i); min_i = min(min_i, min_j); if (ts[i] < min_j) ans.push_back({i, j}); } else if (j != p) { min_i = min(min_i, ts[j]); } } return min_i; }; for (const auto& e : connections) { g[e[0]].push_back(e[1]); g[e[1]].push_back(e[0]); } tarjan(0, -1); return ans; } };

The post 花花酱 LeetCode 1192. Critical Connections in a Network appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1191. K-Concatenation Maximum Sum appeared first on Huahua's Tech Road.

]]>Given an integer array `arr`

and an integer `k`

, modify the array by repeating it `k`

times.

For example, if `arr = [1, 2]`

and `k = 3 `

then the modified array will be `[1, 2, 1, 2, 1, 2]`

.

Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be `0`

and its sum in that case is `0`

.

As the answer can be very large, return the answer **modulo** `10^9 + 7`

.

**Example 1:**

Input:arr = [1,2], k = 3Output:9

**Example 2:**

Input:arr = [1,-2,1], k = 5Output:2

**Example 3:**

Input:arr = [-1,-2], k = 7Output:0

**Constraints:**

`1 <= arr.length <= 10^5`

`1 <= k <= 10^5`

`-10^4 <= arr[i] <= 10^4`

This problem can be reduced to maxSubarray.

If k < 3: return maxSubarray(arr * k)

ans1 = maxSubarray(arr * 1)

ans2 = maxSubarray(arr * 2)

ans = max([ans1, ans2, ans2 + sum(arr) * (k – 2)])

Time complexity: O(n)

Space complexity: O(1)

// Author: Huahua class Solution { public: int kConcatenationMaxSum(vector<int>& arr, int k) { constexpr int kMod = 1e9 + 7; auto maxSum = [&arr](int r) { long sum = 0; long ans = 0; for (int i = 0; i < r; ++i) { for (long a : arr) { sum = max(0L, sum += a); ans = max(ans, sum); } } return ans; }; if (k < 3) return maxSum(k) % kMod; long ans1 = maxSum(1); long ans2 = maxSum(2); long sum = accumulate(begin(arr), end(arr), 0L); return max({ans1, ans2, ans2 + sum * (k - 2)}) % kMod; } };

The post 花花酱 LeetCode 1191. K-Concatenation Maximum Sum appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses appeared first on Huahua's Tech Road.

]]>`s`

that consists of lower case English letters and brackets.
Reverse the strings in each pair of matching parentheses, starting from the innermost one.

Your result should **not** contain any bracket.

**Example 1:**

Input:s = "(abcd)"Output:"dcba"

**Example 2:**

Input:s = "(u(love)i)"Output:"iloveu"

**Example 3:**

Input:s = "(ed(et(oc))el)"Output:"leetcode"

**Example 4:**

Input:s = "a(bcdefghijkl(mno)p)q"Output:"apmnolkjihgfedcbq"

**Constraints:**

`0 <= s.length <= 2000`

`s`

only contains lower case English characters and parentheses.- It’s guaranteed that all parentheses are balanced.

Use a stack of strings to track all the active strings.

Iterate over the input string:

1. Whenever there is a ‘(‘, push an empty string to the stack.

2. Whenever this is a ‘)’, pop the top string and append the reverse of it to the new stack top.

3. Otherwise, append the letter to the string on top the of stack.

Once done, the (only) string on the top of the stack is the answer.

Time complexity: O(n^2)

Space complexity: O(n)

// Author: Huahua class Solution { public: string reverseParentheses(string s) { stack<string> st; st.push(""); for (char c : s) { if (c == '(') st.push(""); else if (c != ')') st.top() += c; else { string t = st.top(); st.pop(); st.top().insert(end(st.top()), rbegin(t), rend(t)); } } return st.top(); } };

The post 花花酱 LeetCode 1190. Reverse Substrings Between Each Pair of Parentheses appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1189. Maximum Number of Balloons appeared first on Huahua's Tech Road.

]]>`text`

, you want to use the characters of `text`

to form as many instances of the word You can use each character in `text`

**at most once**. Return the maximum number of instances that can be formed.

**Example 1:**

Input:text = "nlaebolko"Output:1

**Example 2:**

Input:text = "loonbalxballpoon"Output:2

**Example 3:**

Input:text = "leetcode"Output:0

**Constraints:**

`1 <= text.length <= 10^4`

`text`

consists of lower case English letters only.

**Solution: HashTable**

Use a hashtable to count the occurrence of each letter and find the bottleneck one.

Time complexity: O(n)

Space complexity: O(1)

// Author: Huahua class Solution { public: int maxNumberOfBalloons(string text) { map<char, int> c; for (char t : text) ++c[t]; return min({c['b'], c['a'], c['l'] / 2, c['o'] / 2, c['n']}); } };

The post 花花酱 LeetCode 1189. Maximum Number of Balloons appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1187. Make Array Strictly Increasing appeared first on Huahua's Tech Road.

]]>Given two integer arrays `arr1`

and `arr2`

, return the minimum number of operations (possibly zero) needed to make `arr1`

strictly increasing.

In one operation, you can choose two indices `0 <= i < arr1.length`

and `0 <= j < arr2.length`

and do the assignment `arr1[i] = arr2[j]`

.

If there is no way to make `arr1`

strictly increasing, return `-1`

.

**Example 1:**

Input:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]Output:1Explanation:Replace`5`

with`2`

, then`arr1 = [1, 2, 3, 6, 7]`

.

**Example 2:**

Input:arr1 = [1,5,3,6,7], arr2 = [4,3,1]Output:2Explanation:Replace`5`

with`3`

and then replace`3`

with`4`

.`arr1 = [1, 3, 4, 6, 7]`

.

**Example 3:**

Input:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]Output:-1Explanation:You can't make`arr1`

strictly increasing.

**Constraints:**

`1 <= arr1.length, arr2.length <= 2000`

`0 <= arr1[i], arr2[i] <= 10^9`

**Solution: DP**

Time complexity: O(mn)

Space complexity: O(mn) -> O(m + n)

// Author: Huahua class Solution { public: int makeArrayIncreasing(vector<int>& a, vector<int>& c) { constexpr int kInf = 1e9; int m = a.size(); // Sort b and make it only containing unique numbers. sort(begin(c), end(c)); vector<int> b; for (int i = 0; i < c.size(); ++i) { if (!b.empty() && c[i] == b.back()) continue; b.push_back(c[i]); } int n = b.size(); // min steps to make a[0~i] valid by keeping a[i] vector<int> keep(m, kInf); keep[0] = 0; // swap[i][j] := min steps to make a[0~i] valid by a[i] = b[j] vector<int> swap(n, 1); for (int i = 1; i < m; ++i) { int min_keep = kInf; int min_swap = kInf; vector<int> temp(n, kInf); for (int j = 0; j < n; ++j) { if (j > 0) min_swap = min(min_swap, swap[j - 1] + 1); if (a[i] > b[j]) min_keep = min(min_keep, swap[j]); if (a[i] > a[i - 1]) keep[i] = keep[i - 1]; if (b[j] > a[i - 1]) temp[j] = keep[i - 1] + 1; temp[j] = min(temp[j], min_swap); keep[i] = min(keep[i], min_keep); } temp.swap(swap); } int s = *min_element(begin(swap), end(swap)); int k = keep.back(); int ans = min(s, k); return ans >= kInf ? -1 : ans; } };

The post 花花酱 LeetCode 1187. Make Array Strictly Increasing appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1186. Maximum Subarray Sum with One Deletion appeared first on Huahua's Tech Road.

]]>Note that the subarray needs to be **non-empty** after deleting one element.

**Example 1:**

Input:arr = [1,-2,0,3]Output:4Explanation:Because we can choose [1, -2, 0, 3] and drop -2, thus the subarray [1, 0, 3] becomes the maximum value.

**Example 2:**

Input:arr = [1,-2,-2,3]Output:3Explanation:We just choose [3] and it's the maximum sum.

**Example 3:**

Input:arr = [-1,-1,-1,-1]Output:-1Explanation:The final subarray needs to be non-empty. You can't choose [-1] and delete -1 from it, then get an empty subarray to make the sum equals to 0.

**Constraints:**

`1 <= arr.length <= 10^5`

`-10^4 <= arr[i] <= 10^4`

**Solution: DP**

First, handle the special case: all numbers are negative, return the max one.

s0 = max subarray sum ends with a[i]

s1 = max subarray sum ends with a[i] with at most one deletion

whenever s0 or s1 becomes negative, reset them to 0.

Time complexity: O(n)

Space complexity: O(1)

// Author: Huahua class Solution { public: int maximumSum(vector<int>& arr) { int m = *max_element(begin(arr), end(arr)); if (m <= 0) return m; int s0 = 0; int s1 = 0; int ans = 0; for (int a : arr) { s1 = max(s0, s1 + a); s0 += a; ans = max(ans, max(s0, s1)); if (s0 < 0) s0 = 0; if (s1 < 0) s1 = 0; } return ans; } };

The post 花花酱 LeetCode 1186. Maximum Subarray Sum with One Deletion appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1185. Day of the Week appeared first on Huahua's Tech Road.

]]>The input is given as three integers representing the `day`

, `month`

and `year`

respectively.

Return the answer as one of the following values `{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}`

.

**Example 1:**

Input:day = 31, month = 8, year = 2019Output:"Saturday"

**Example 2:**

Input:day = 18, month = 7, year = 1999Output:"Sunday"

**Example 3:**

Input:day = 15, month = 8, year = 1993Output:"Sunday"

**Constraints:**

- The given dates are valid dates between the years
`1971`

and`2100`

.

**Solution: LeapYear**

Time complexity: O(1)

Space complexity: O(1)

// Author: Huahua inline bool leapYear(int y) { return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0); } class Solution { public: string dayOfTheWeek(int day, int month, int year) { vector<string> names = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; vector<int> days = {31, 28 + leapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; int sum = 0; for (int i = 1970; i < year; ++i) sum += 365 + leapYear(i); for (int i = 1; i < month; ++i) sum += days[i - 1]; sum += day; return names[(sum + 3) % 7]; } };

The post 花花酱 LeetCode 1185. Day of the Week appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1184. Distance Between Bus Stops appeared first on Huahua's Tech Road.

]]>`n`

stops numbered from `0`

to `n - 1`

that form a circle. We know the distance between all pairs of neighboring stops where `distance[i]`

is the distance between the stops number `i`

and `(i + 1) % n`

.
The bus goes along both directions i.e. clockwise and counterclockwise.

Return the shortest distance between the given `start`

and `destination`

stops.

**Example 1:**

Input:distance = [1,2,3,4], start = 0, destination = 1Output:1Explanation:Distance between 0 and 1 is 1 or 9, minimum is 1.

**Example 2:**

Input:distance = [1,2,3,4], start = 0, destination = 2Output:3Explanation:Distance between 0 and 2 is 3 or 7, minimum is 3.

**Example 3:**

Input:distance = [1,2,3,4], start = 0, destination = 3Output:4Explanation:Distance between 0 and 3 is 6 or 4, minimum is 4.

**Constraints:**

`1 <= n <= 10^4`

`distance.length == n`

`0 <= start, destination < n`

`0 <= distance[i] <= 10^4`

**Solution: Summation**

- compute the total sum
- compute the sum from s to d, c
- ans = min(c, sum – c)

Time complexity: O(d-s)

Space complexity: O(1)

// Author: Huahua class Solution { public: int distanceBetweenBusStops(vector<int>& ds, int s, int d) { if (s > d) swap(s, d); int sum = accumulate(begin(ds), end(ds), 0); int d1 = accumulate(begin(ds) + s, begin(ds) + d, 0); return min(d1, sum - d1); } };

The post 花花酱 LeetCode 1184. Distance Between Bus Stops appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1178. Number of Valid Words for Each Puzzle appeared first on Huahua's Tech Road.

]]>
With respect to a given `puzzle`

string, a `word`

is *valid* if both the following conditions are satisfied:

`word`

contains the first letter of`puzzle`

.- For each letter in
`word`

, that letter is in`puzzle`

.

For example, if the puzzle is “abcdefg”, then valid words are “faced”, “cabbage”, and “baggage”; while invalid words are “beefed” (doesn’t include “a”) and “based” (includes “s” which isn’t in the puzzle).

Return an array `answer`

, where `answer[i]`

is the number of words in the given word list `words`

that are valid with respect to the puzzle `puzzles[i]`

.

**Example :**

Input:words = ["aaaa","asas","able","ability","actt","actor","access"], puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]Output:[1,1,3,2,4,0]Explanation:1 valid word for "aboveyz" : "aaaa" 1 valid word for "abrodyz" : "aaaa" 3 valid words for "abslute" : "aaaa", "asas", "able" 2 valid words for "absoryz" : "aaaa", "asas" 4 valid words for "actresz" : "aaaa", "asas", "actt", "access" There're no valid words for "gaswxyz" cause none of the words in the list contains letter 'g'.

**Constraints:**

`1 <= words.length <= 10^5`

`4 <= words[i].length <= 50`

`1 <= puzzles.length <= 10^4`

`puzzles[i].length == 7`

`words[i][j]`

,`puzzles[i][j]`

are English lowercase letters.- Each
`puzzles[i]`

doesn’t contain repeated characters.

Preprocessing:

Compress each word to a bit map, and compute the frequency of each bit map.

Since there are at most |words| bitmaps while its value ranging from 0 to 2^26, thus it’s better to use a hashtable instead of an array.

Query:

Use the same way to compress a puzzle into a bit map.

Try all subsets (at most 128) of the puzzle (the bit of the first character is be must), and check how many words match each subset.

words = [“aaaa”,”asas”,”able”,”ability”,”actt”,”actor”,”access”],

puzzle = “abslute”

bitmap(“aaaa”) = {0}

bitmap(“asas”) = {0, 18}

bitmap(“able”) = {0,1,4,11}

bitmap(“actt”) = {0, 2, 19}

bitmap(“actor”) = {0, 2, 14, 17, 19}

bitmap(“access”) = {0, 2, 4, 18}

bitmap(“abslute”) = {0, 1, 4, 11, 18, 19, 20}

Time complexity: O(sum(len(w_i)) + |puzzles|)

Space complexity: O(|words|)

// Author: Huahua, 136 ms, 29.7 MB class Solution { public: vector<int> findNumOfValidWords(vector<string>& words, vector<string>& puzzles) { vector<int> ans; unordered_map<int, int> freq; for (const string& word : words) { int mask = 0; for (char c : word) mask |= 1 << (c - 'a'); ++freq[mask]; } for (const string& p : puzzles) { int mask = 0; for (char c : p) mask |= 1 << (c - 'a'); int first = p[0] - 'a'; int curr = mask; int total = 0; while (curr) { if ((curr >> first) & 1) { auto it = freq.find(curr); if (it != freq.end()) total += it->second; } curr = (curr - 1) & mask; } ans.push_back(total); } return ans; } };

The post 花花酱 LeetCode 1178. Number of Valid Words for Each Puzzle appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1177. Can Make Palindrome from Substring appeared first on Huahua's Tech Road.

]]>`s`

, we make queries on substrings of `s`

.
For each query `queries[i] = [left, right, k]`

, we may **rearrange** the substring `s[left], ..., s[right]`

, and then choose **up to** `k`

of them to replace with any lowercase English letter.

If the substring is possible to be a palindrome string after the operations above, the result of the query is `true`

. Otherwise, the result is `false`

.

Return an array `answer[]`

, where `answer[i]`

is the result of the `i`

-th query `queries[i]`

.

Note that: Each letter is counted **individually** for replacement so if for example `s[left..right] = "aaa"`

, and `k = 2`

, we can only replace two of the letters. (Also, note that the initial string `s`

is never modified by any query.)

**Example :**

Input:s = "abcda", queries = [[3,3,0],[1,2,0],[0,3,1],[0,3,2],[0,4,1]]Output:[true,false,false,true,true]Explanation:queries[0] : substring = "d", is palidrome. queries[1] : substring = "bc", is not palidrome. queries[2] : substring = "abcd", is not palidrome after replacing only 1 character. queries[3] : substring = "abcd", could be changed to "abba" which is palidrome. Also this can be changed to "baab" first rearrange it "bacd" then replace "cd" with "ab". queries[4] : substring = "abcda", could be changed to "abcba" which is palidrome.

**Constraints:**

`1 <= s.length, queries.length <= 10^5`

`0 <= queries[i][0] <= queries[i][1] < s.length`

`0 <= queries[i][2] <= s.length`

`s`

only contains lowercase English letters.

Compute the prefix frequency of each characters, then we can efficiently compute the frequency of each characters in the substring in O(1) time. Count the number odd frequency characters o, we can convert it to a palindrome if o / 2 <= k.

Time complexity:

preprocessing: O(n)

Query: O(1)

Space complexity: O(n)

// Author: Huahua class Solution { public: vector<bool> canMakePaliQueries(string s, vector<vector<int>>& queries) { vector<bool> ans; int n = s.length(); vector<vector<int>> f(n + 1, vector<int>(26)); for (int i = 0; i < n; ++i) { ++f[i][s[i] - 'a']; f[i + 1] = f[i]; } for (const auto& q : queries) { int l = q[0]; int r = q[1]; int k = q[2]; int o = 0; for (int i = 0; i < 26; ++i) { int c = f[r][i] - (l == 0 ? 0 : f[l - 1][i]); o += c % 2; } ans.push_back(o / 2 <= k); } return ans; } };

The post 花花酱 LeetCode 1177. Can Make Palindrome from Substring appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1176. Diet Plan Performance appeared first on Huahua's Tech Road.

]]>`calories[i]`

calories on the `i`

-th day. For every consecutive sequence of `k`

days, they look at `k`

days:
- If
`T < lower`

, they performed poorly on their diet and lose 1 point; - If
`T > upper`

, they performed well on their diet and gain 1 point; - Otherwise, they performed normally and there is no change in points.

Return the total number of points the dieter has after all `calories.length`

days.

Note that: The total points could be negative.

**Example 1:**

Input:calories = [1,2,3,4,5], k = 1, lower = 3, upper = 3Output:0Explaination: calories[0], calories[1] < lower and calories[3], calories[4] > upper, total points = 0.

**Example 2:**

Input:calories = [3,2], k = 2, lower = 0, upper = 1Output:1Explaination: calories[0] + calories[1] > upper, total points = 1.

**Example 3:**

Input:calories = [6,5,0,0], k = 2, lower = 1, upper = 5Output:0Explaination: calories[0] + calories[1] > upper, calories[2] + calories[3] < lower, total points = 0.

**Constraints:**

`1 <= k <= calories.length <= 10^5`

`0 <= calories[i] <= 20000`

`0 <= lower <= upper`

Maintain the sum of a sliding window length of k.

Time complexity: O(n)

Space complexity: O(1)

// Author: Huahua class Solution { public: int dietPlanPerformance(vector<int>& calories, int k, int lower, int upper) { int ans = 0; int t = accumulate(begin(calories), begin(calories) + k - 1, 0); for (int i = k - 1; i < calories.size(); ++i) { if (i >= k) t -= calories[i - k]; t += calories[i]; if (t > upper) ++ans; if (t < lower) --ans; } return ans; } };

The post 花花酱 LeetCode 1176. Diet Plan Performance appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1175. Prime Arrangements appeared first on Huahua's Tech Road.

]]>`n`

so that prime numbers are at prime indices (1-indexed.)
*(Recall that an integer is prime if and only if it is greater than 1, and cannot be written as a product of two positive integers both smaller than it.)*

Since the answer may be large, return the answer **modulo 10^9 + 7**.

**Example 1:**

Input:n = 5Output:12Explanation:For example [1,2,5,4,3] is a valid permutation, but [5,2,3,4,1] is not because the prime number 5 is at index 1.

**Example 2:**

Input:n = 100Output:682289015

**Constraints:**

`1 <= n <= 100`

Count the number of primes in range [1, n], assuming there are p primes and n – p non-primes, we can permute each group separately.

ans = p! * (n – p)!

Time complexity: O(nsqrt(n))

Space complexity: O(1)

// Author: Huahua class Solution { public: int numPrimeArrangements(int n) { const int kMod = 1e9 + 7; int p = 0; for (int i = 1; i <= n; ++i) p += isPrime(i); long ans = 1; for (int i = 1; i <= p; ++i) ans = (ans * i) % kMod; for (int i = 1; i <= n - p; ++i) ans = (ans * i) % kMod; return ans; } private: bool isPrime(int x) { if (x < 2) return false; if (x == 2) return true; for (int i = 2; i <= sqrt(x); ++i) if (x % i == 0) return false; return true; } };

The post 花花酱 LeetCode 1175. Prime Arrangements appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1143. Longest Common Subsequence appeared first on Huahua's Tech Road.

]]>`text1`

and `text2`

, return the length of their longest common subsequence.
A *subsequence* of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, “ace” is a subsequence of “abcde” while “aec” is not). A *common subsequence* of two strings is a subsequence that is common to both strings.

If there is no common subsequence, return 0.

**Example 1:**

Input:text1 = "abcde", text2 = "ace"Output:3Explanation:The longest common subsequence is "ace" and its length is 3.

**Example 2:**

Input:text1 = "abc", text2 = "abc"Output:3Explanation:The longest common subsequence is "abc" and its length is 3.

**Example 3:**

Input:text1 = "abc", text2 = "def"Output:0Explanation:There is no such common subsequence, so the result is 0.

**Constraints:**

`1 <= text1.length <= 1000`

`1 <= text2.length <= 1000`

- The input strings consist of lowercase English characters only.

**Solution: DP**

Use dp[i][j] to represent the length of longest common sub-sequence of text1[0:i] and text2[0:j]

dp[i][j] = dp[i – 1][j – 1] + 1 if text1[i – 1] == text2[j – 1] else max(dp[i][j – 1], dp[i – 1][j])

Time complexity: O(mn)

Space complexity: O(mn) -> O(n)

// Author: Huahua, 16ms 14.9 MB class Solution { public: int longestCommonSubsequence(string text1, string text2) { int m = text1.length(); int n = text2.length(); vector<vector<int>> dp(m + 1, vector<int>(n + 1)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (text1[i] == text2[j]) dp[i + 1][j + 1] = dp[i][j] + 1; else dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]); return dp[m][n]; } };

// Author: Huahua, 8ms, 8.8MB class Solution { public: int longestCommonSubsequence(string text1, string text2) { int m = text1.length(); int n = text2.length(); vector<int> dp(n + 1); for (int i = 0; i < m; ++i) { int prev = 0; // dp[i][j] for (int j = 0; j < n; ++j) { int curr = dp[j + 1]; // dp[i][j + 1] if (text1[i] == text2[j]) // dp[i + 1][j + 1] = dp[i][j] + 1 dp[j + 1] = prev + 1; else // dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j]) dp[j + 1] = max(curr, dp[j]); prev = curr; } } return dp[n]; // dp[m][n] } };

// Author: Huahua class Solution { public: int longestCommonSubsequence(string text1, string text2) { int m = text1.length(); int n = text2.length(); vector<int> dp1(n + 1); vector<int> dp2(n + 1); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) if (text1[i] == text2[j]) dp2[j + 1] = dp1[j] + 1; else dp2[j + 1] = max(dp1[j + 1], dp2[j]); swap(dp1, dp2); } return dp1[n]; } };

The post 花花酱 LeetCode 1143. Longest Common Subsequence appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1171. Remove Zero Sum Consecutive Nodes from Linked List appeared first on Huahua's Tech Road.

]]>`head`

of a linked list, we repeatedly delete consecutive sequences of nodes that sum to `0`

until there are no such sequences.
After doing so, return the head of the final linked list. You may return any such answer.

(Note that in the examples below, all sequences are serializations of `ListNode`

objects.)

**Example 1:**

Input:head = [1,2,-3,3,1]Output:[3,1]Note:The answer [1,2,1] would also be accepted.

**Example 2:**

Input:head = [1,2,3,-3,4]Output:[1,2,4]

**Example 3:**

Input:head = [1,2,3,-3,-2]Output:[1]

**Constraints:**

- The given linked list will contain between
`1`

and`1000`

nodes. - Each node in the linked list has
`-1000 <= node.val <= 1000`

.

Similar to target sum = 0, use a hashtable to store the first ListNode* that has a given prefix sum. Whenever the same prefix sum occurs, skip all the elements between the first occurrence and current one, e.g. first_sum_x.next = curr_sum_x.next

Time complexity: O(n)

Space complexity: O(n)

// Author: Huahua class Solution { public: ListNode* removeZeroSumSublists(ListNode* head) { ListNode dummy(0); dummy.next = head; ListNode* prev = &dummy; ListNode* curr = prev->next; unordered_map<int, ListNode*> m{{0, prev}}; int s = 0; while (curr) { s += curr->val; if (m.count(s)) m[s]->next = curr->next; else m[s] = curr; prev = curr; curr = curr->next; } return dummy.next; } };

# Author: Huahua class Solution: def removeZeroSumSublists(self, head: ListNode) -> ListNode: dummy = ListNode(0) dummy.next = head prev, curr = dummy, dummy.next s = 0 m = {s: prev} while curr: s += curr.val if s in m: m[s].next = curr.next else: m[s] = curr prev, curr = curr, curr.next return dummy.next

The post 花花酱 LeetCode 1171. Remove Zero Sum Consecutive Nodes from Linked List appeared first on Huahua's Tech Road.

]]>The post 花花酱 LeetCode 1172. Dinner Plate Stacks appeared first on Huahua's Tech Road.

]]>You have an infinite number of stacks arranged in a row and numbered (left to right) from 0, each of the stacks has the same maximum `capacity`

.

Implement the `DinnerPlates`

class:

`DinnerPlates(int capacity)`

Initializes the object with the maximum`capacity`

of the stacks.`void push(int val)`

pushes the given positive integer`val`

into the leftmost stack with size less than`capacity`

.`int pop()`

returns the value at the top of the rightmost non-empty stack and removes it from that stack, and returns`-1`

if all stacks are empty.`int popAtStack(int index)`

returns the value at the top of the stack with the given`index`

and removes it from that stack, and returns -1 if the stack with that given`index`

is empty.

**Example:**

Input:["DinnerPlates","push","push","push","push","push","popAtStack","push","push","popAtStack","popAtStack","pop","pop","pop","pop","pop"] [[2],[1],[2],[3],[4],[5],[0],[20],[21],[0],[2],[],[],[],[],[]]Output:

[null,null,null,null,null,null,2,null,null,20,21,5,4,3,1,-1]

Explanation:DinnerPlates D = DinnerPlates(2); // Initialize with capacity = 2 D.push(1); D.push(2); D.push(3); D.push(4); D.push(5); // The stacks are now: 2 4 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 2. The stacks are now: 4 1 3 5 ﹈ ﹈ ﹈ D.push(20); // The stacks are now: 20 4 1 3 5 ﹈ ﹈ ﹈ D.push(21); // The stacks are now: 20 4 21 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(0); // Returns 20. The stacks are now: 4 21 1 3 5 ﹈ ﹈ ﹈ D.popAtStack(2); // Returns 21. The stacks are now: 4 1 3 5 ﹈ ﹈ ﹈ D.pop() // Returns 5. The stacks are now: 4 1 3 ﹈ ﹈ D.pop() // Returns 4. The stacks are now: 1 3 ﹈ ﹈ D.pop() // Returns 3. The stacks are now: 1 ﹈ D.pop() // Returns 1. There are no stacks. D.pop() // Returns -1. There are still no stacks.

**Constraints:**

`1 <= capacity <= 20000`

`1 <= val <= 20000`

`0 <= index <= 100000`

- At most
`200000`

calls will be made to`push`

,`pop`

, and`popAtStack`

.

Store all the stacks in an array, and store the indices of all free stacks in a tree set.

1. push(): find the first free stack and push onto it, if it becomes full, remove it from free set.

2. pop(): pop element from the last stack by calling popAtIndex(stacks.size()-1).

3. popAtIndex(): pop element from given index

3.1 add it to free set if it was full

3.2 remove it from free set if it becomes empty

3.2.1 remove it from stack array if it is the last stack

Time complexity:

Push: O(logn)

Pop: O(logn)

PopAtIndex: O(logn)

Space complexity: O(n)

// Author: Huahua class DinnerPlates { public: DinnerPlates(int capacity): cap_(capacity) {} void push(int val) { int index = aval_.empty() ? stacks_.size() : *begin(aval_); if (index == stacks_.size()) stacks_.emplace_back(); stack<int>& s = stacks_[index]; s.push(val); if (s.size() == cap_) aval_.erase(index); else if (s.size() == 1) // only insert for the first element aval_.insert(index); } int pop() { return popAtStack(stacks_.size() - 1); } int popAtStack(int index) { if (index < 0 || index >= stacks_.size() || stacks_[index].empty()) return -1; stack<int>& s = stacks_[index]; int val = s.top(); s.pop(); if (s.size() == cap_ - 1) aval_.insert(index); // Amortized O(1) auto it = prev(end(aval_)); while (stacks_.size() && stacks_.back().empty()) { stacks_.pop_back(); aval_.erase(it--); } return val; } private: int cap_; set<int> aval_; vector<stack<int>> stacks_; };

The post 花花酱 LeetCode 1172. Dinner Plate Stacks appeared first on Huahua's Tech Road.

]]>