I have created YouTube playlists by difficulties.
- Easy link
- Medium link
- Hard link
December 15, 2021
Problem:
Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo 10^9 + 7
.
A subsequence of a string S is obtained by deleting 0 or more characters from S.
A sequence is palindromic if it is equal to the sequence reversed.
Two sequences A_1, A_2, ...
and B_1, B_2, ...
are different if there is some i
for which A_i != B_i
.
Example 1:
Input: S = 'bccb' Output: 6 Explanation: The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'. Note that 'bcb' is counted only once, even though it occurs twice.
Example 2:
Input: S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba' Output: 104860361 Explanation: There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.
Note:
S
will be in the range [1, 1000]
.S[i]
will be in the set {'a', 'b', 'c', 'd'}
.
Idea:
DP
Time complexity: O(n^2)
Space complexity: O(n^2)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// Author: Huahua // Runtime: 72 ms class Solution { public: int countPalindromicSubsequences(const string& S) { const int n = S.length(); m_ = vector<vector<int>>(n + 1, vector<int>(n + 1, 0)); return count(S, 0, S.length() - 1); } private: static constexpr long kMod = 1000000007; long count(const string& S, int s, int e) { if (s > e) return 0; if (s == e) return 1; if (m_[s][e] > 0) return m_[s][e]; long ans = 0; if (S[s] == S[e]) { int l = s + 1; int r = e - 1; while (l <= r && S[l] != S[s]) ++l; while (l <= r && S[r] != S[s]) --r; if (l > r) ans = count(S, s + 1, e - 1) * 2 + 2; else if (l == r) ans = count(S, s + 1, e - 1) * 2 + 1; else ans = count(S, s + 1, e - 1) * 2 - count(S, l + 1, r - 1); } else { ans = count(S, s, e - 1) + count(S, s + 1, e) - count(S, s + 1, e - 1); } return m_[s][e] = (ans + kMod) % kMod; } vector<vector<int>> m_; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
""" Author: Huahua Runtime: 3582 ms """ class Solution: def countPalindromicSubsequences(self, S): def count(S, i, j): if i > j: return 0 if i == j: return 1 if self.m_[i][j]: return self.m_[i][j] if S[i] == S[j]: ans = count(S, i + 1, j - 1) * 2 l = i + 1 r = j - 1 while l <= r and S[l] != S[i]: l += 1 while l <= r and S[r] != S[i]: r -= 1 if l > r: ans += 2 elif l == r: ans += 1 else: ans -= count(S, l + 1, r - 1) else: ans = count(S, i + 1, j) + count(S, i, j - 1) - count(S, i + 1, j - 1) self.m_[i][j] = ans % 1000000007 return self.m_[i][j] n = len(S) self.m_ = [[None for _ in range(n)] for _ in range(n)] return count(S, 0, n - 1) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// Author: Huahua // Runtime: 107 ms class Solution { private int[][] m_; private static final int kMod = 1000000007; public int countPalindromicSubsequences(String S) { int n = S.length(); m_ = new int[n][n]; return count(S.toCharArray(), 0, n - 1); } private int count(char[] s, int i, int j) { if (i > j) return 0; if (i == j) return 1; if (m_[i][j] > 0) return m_[i][j]; long ans = 0; if (s[i] == s[j]) { ans += count(s, i + 1, j - 1) * 2; int l = i + 1; int r = j - 1; while (l <= r && s[l] != s[i]) ++l; while (l <= r && s[r] != s[i]) --r; if (l > r) ans += 2; else if (l == r) ans += 1; else ans -= count(s, l + 1, r - 1); } else { ans = count(s, i, j - 1) + count(s, i + 1, j) - count(s, i + 1, j - 1); } m_[i][j] = (int)((ans + kMod) % kMod); return m_[i][j]; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// Author: Huahua // Runtime: 79 ms class Solution { public: int countPalindromicSubsequences(const string& S) { int n = S.length(); vector<vector<int>> dp(n, vector<int>(n, 0)); for (int i = 0; i < n; ++i) dp[i][i] = 1; for (int len = 1; len <= n; ++len) { for (int i = 0; i < n - len; ++i) { const int j = i + len; if (S[i] == S[j]) { dp[i][j] = dp[i + 1][j - 1] * 2; int l = i + 1; int r = j - 1; while (l <= r && S[l] != S[i]) ++l; while (l <= r && S[r] != S[i]) --r; if (l == r) dp[i][j] += 1; else if (l > r) dp[i][j] += 2; else dp[i][j] -= dp[l + 1][r - 1]; } else { dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; } dp[i][j] = (dp[i][j] + kMod) % kMod; } } return dp[0][n - 1]; } private: static constexpr long kMod = 1000000007; }; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
""" Author: Huahua Runtime: 3639 ms """ class Solution: def countPalindromicSubsequences(self, S): n = len(S) if n == 0: return 0 dp = [[0 for _ in range(n)] for _ in range(n)] for i in range(n): dp[i][i] = 1 for size in range(2, n + 1): for i in range(n - size + 1): j = i + size - 1 if S[i] == S[j]: dp[i][j] = dp[i + 1][j - 1] * 2 l = i + 1 r = j - 1 while l <= r and S[l] != S[i]: l += 1 while l <= r and S[r] != S[i]: r -= 1 if l > r: dp[i][j] += 2 elif l == r: dp[i][j] += 1 else: dp[i][j] -= dp[l + 1][r - 1] else: dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] dp[i][j] %= 1000000007 return dp[0][n - 1] |
Related Problems:
Problem:
Implement a MyCalendarTwo
class to store your events. A new event can be added if adding the event will not cause a triple booking.
Your class will have one method, book(int start, int end)
. Formally, this represents a booking on the half open interval [start, end)
, the range of real numbers x
such that start <= x < end
.
A triple booking happens when three events have some non-empty intersection (ie., there is some time that is common to all 3 events.)
For each call to the method MyCalendar.book
, return true
if the event can be added to the calendar successfully without causing a triple booking. Otherwise, return false
and do not add the event to the calendar.
Your class will be called like this: MyCalendar cal = new MyCalendar();
MyCalendar.book(start, end)
Example 1:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
MyCalendar(); MyCalendar.book(10, 20); // returns true MyCalendar.book(50, 60); // returns true MyCalendar.book(10, 40); // returns true MyCalendar.book(5, 15); // returns false MyCalendar.book(5, 10); // returns true MyCalendar.book(25, 55); // returns true Explanation<b>:</b> The first two events can be booked. The third event can be double booked. The fourth event (5, 15) can't be booked, because it would result in a triple booking. The fifth event (5, 10) can be booked, as it does not use time 10 which is already double booked. The sixth event (25, 55) can be booked, as the time in [25, 40) will be double booked with the third event; the time [40, 50) will be single booked, and the time [50, 55) will be double booked with the second event. |
Note:
MyCalendar.book
per test case will be at most 1000
.MyCalendar.book(start, end)
, start
and end
are integers in the range [0, 10^9]
.Idea:
Brute Force
Solution1:
Brute Force
Time Complexity: O(n^2)
Space Complexity: O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Author: Huahua // Runtime: 82 ms class MyCalendarTwo { public: MyCalendarTwo() {} bool book(int start, int end) { for (const auto& kv : overlaps_) if (max(start, kv.first) < min(end, kv.second)) return false; for (const auto& kv : booked_) { const int ss = max(start, kv.first); const int ee = min(end, kv.second); if (ss < ee) overlaps_.emplace_back(ss, ee); } booked_.emplace_back(start, end); return true; } private: vector<pair<int, int>> booked_; vector<pair<int, int>> overlaps_; }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
// Author: Huahua // Runtime: 156 ms class MyCalendarTwo { private List<int[]> booked_; private List<int[]> overlaps_; public MyCalendarTwo() { booked_ = new ArrayList<>(); overlaps_ = new ArrayList<>(); } public boolean book(int start, int end) { for (int[] range : overlaps_) if (Math.max(range[0], start) < Math.min(range[1], end)) return false; for (int[] range : booked_) { int ss = Math.max(range[0], start); int ee = Math.min(range[1], end); if (ss < ee) overlaps_.add(new int[]{ss, ee}); } booked_.add(new int[]{start, end}); return true; } } |
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
""" Author: Huahua Runtime: 638 ms """ class MyCalendarTwo: def __init__(self): self.booked_ = [] self.overlaps_ = [] def book(self, start, end): for s, e in self.overlaps_: if start < e and end > s: return False for s, e in self.booked_: if start < e and end > s: self.overlaps_.append([max(start, s), min(end, e)]) self.booked_.append([start, end]) return True |
Solution 2:
Counting
Time Complexity: O(n^2logn)
Space Complexity: O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Author: Huahua // Runtime: 212 ms class MyCalendarTwo { public: MyCalendarTwo() {} bool book(int start, int end) { ++delta_[start]; --delta_[end]; int count = 0; for (const auto& kv : delta_) { count += kv.second; if (count == 3) { --delta_[start]; ++delta_[end]; return false; } if (kv.first > end) break; } return true; } private: map<int, int> delta_; }; |
Related Problems:
Problem:
Implement a MyCalendar
class to store your events. A new event can be added if adding the event will not cause a double booking.
Your class will have the method, book(int start, int end)
. Formally, this represents a booking on the half open interval [start, end)
, the range of real numbers x
such that start <= x < end
.
A double booking happens when two events have some non-empty intersection (ie., there is some time that is common to both events.)
For each call to the method MyCalendar.book
, return true
if the event can be added to the calendar successfully without causing a double booking. Otherwise, return false
and do not add the event to the calendar.
Your class will be called like this: MyCalendar cal = new MyCalendar();
MyCalendar.book(start, end)
Example 1:
1 2 3 4 5 6 7 |
MyCalendar(); MyCalendar.book(10, 20); // returns true MyCalendar.book(15, 25); // returns false MyCalendar.book(20, 30); // returns true Explanation: The first event can be booked. The second can't because time 15 is already booked by another event. The third event can be booked, as the first event takes every time less than 20, but not including 20. |
Note:
MyCalendar.book
per test case will be at most 1000
.MyCalendar.book(start, end)
, start
and end
are integers in the range [0, 10^9]
.
Idea:
Binary Search
Solution1:
Brute Force: O(n^2)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua // Runtime: 99 ms class MyCalendar { public: MyCalendar() {} bool book(int start, int end) { for (const auto& event : booked_) { int s = event.first; int e = event.second; if (max(s, start) < min(e, end)) return false; } booked_.emplace_back(start, end); return true; } private: vector<pair<int, int>> booked_; }; |
Solution 2:
Binary Search O(nlogn)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua // Runtime: 82 ms class MyCalendar { public: MyCalendar() {} bool book(int start, int end) { auto it = booked_.lower_bound(start); if (it != booked_.cend() && it->first < end) return false; if (it != booked_.cbegin() && (--it)->second > start) return false; booked_[start] = end; return true; } private: map<int, int> booked_; }; |
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Author: Huahua // Runtime: 170 ms class MyCalendar { TreeMap<Integer, Integer> booked_; public MyCalendar() { booked_ = new TreeMap<>(); } public boolean book(int start, int end) { Integer lb = booked_.floorKey(start); if (lb != null && booked_.get(lb) > start) return false; Integer ub = booked_.ceilingKey(start); if (ub != null && ub < end) return false; booked_.put(start, end); return true; } } |
Related Problems:
Problem:
A self-dividing number is a number that is divisible by every digit it contains.
For example, 128 is a self-dividing number because 128 % 1 == 0
, 128 % 2 == 0
, and 128 % 8 == 0
.
Also, a self-dividing number is not allowed to contain the digit zero.
Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.
Example 1:
1 2 3 |
Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] |
Note:
1 <= left <= right <= 10000
.
Idea:
Brute Force
Time Complexity: O(n)
Space Complexity: O(1)
Solution:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua // Runtime: 3 ms class Solution { public: vector<int> selfDividingNumbers(int left, int right) { vector<int> ans; for (int n = left; n <= right; ++n) { int t = n; bool valid = true; while (t && valid) { const int r = t % 10; if (r == 0 || n % r) valid = false; t /= 10; } if (valid) ans.push_back(n); } return ans; } }; |
String
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Author: Huahua // Runtime: 6 ms class Solution { public: vector<int> selfDividingNumbers(int left, int right) { vector<int> ans; for (int n = left; n <= right; ++n) { const string t = std::to_string(n); bool valid = true; for (const char c : t) { if (c == '0' || n % (c - '0')) { valid = false; break; } } if (valid) ans.push_back(n); } return ans; } }; |
Related Problems: