question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
subsequence-with-the-minimum-score
|
Binary Search + Sliding Window
|
binary-search-sliding-window-by-java_pro-yee0
|
We need to minimize something, so we naturally think of 3 possible methods\n1. Dp\n2. Greedy\n3. Binary Search the answer\n\nTrying the first 2 options I couldn
|
Java_Programmer_Ketan
|
NORMAL
|
2023-02-12T04:01:05.825894+00:00
|
2023-02-12T04:01:05.825929+00:00
| 4,578 | false |
We need to minimize something, so we naturally think of 3 possible methods\n1. Dp\n2. Greedy\n3. Binary Search the answer\n\nTrying the first 2 options I couldn\'t figure a way to solve this problem, So tried binary search search the answer (the length of deleted subarray of t string).\n\nCreate a function `check(int len)` which will return true if a subarray of len is deleted from t and t becomes a subsequence of s. false otherwise\n\nWe can use sliding window to solve create this function\n\n1. Lets assume we delete subarray of len from right hand side of t. Let int[] pos store the greedily matched positions of t from index 0 to t.length()-len.\n2. Now, keep on increasing the right subarray length till the deleted subarray becomes 0 to len-1. The transition of windows is same as previous, just greedily match the characters of s and t.\n\n\n```\npublic class Solution {\n public int minimumScore(String S, String T) {\n char[] s = S.toCharArray(), t = T.toCharArray();\n int lo=0,hi=T.length();\n while(lo<=hi){\n int m = (lo+hi)>>1;\n if(check(s,t,m)) hi = m-1;\n else lo = m+1;\n }\n return hi+1;\n }\n private boolean check(char[] s, char[] t,int len){\n int t_length = t.length,n=s.length;\n if(len>=t_length) return true; //delete whole t array\n int[] pos = new int[t_length]; //Greedy left matching\n Arrays.fill(pos,1_000_000_0);\n int t_left_index = 0;\n for(int i=0;i<n;i++){\n if(t_left_index == t_length) break;\n if(t[t_left_index] == s[i]){\n pos[t_left_index] = i;\n t_left_index++;\n }\n }\n if(t_left_index >=t_length-len) return true; //we can delete right subarray of length len\n int right_index_of_s =n-1;\n for(int rp=t_length-1;rp>=len;rp--){\n while(right_index_of_s >=0 && s[right_index_of_s]!=t[rp]) right_index_of_s--;\n if(right_index_of_s == -1) return false;\n int lp = rp-len-1;\n if(lp == -1 || pos[lp]< right_index_of_s) return true;\n right_index_of_s--;\n }\n return false;\n }\n}\n```
| 20 | 3 |
[]
| 3 |
subsequence-with-the-minimum-score
|
Comments + Video Solution || prefix - Suffix || O(N) complexity|| C++ Solution
|
comments-video-solution-prefix-suffix-on-4vee
|
\n\n# Approach\nJust construct the prefix and suffix array based on no of subsequence matching characters and then just see how many characters are matching fro
|
u-day
|
NORMAL
|
2023-02-14T13:24:27.685585+00:00
|
2023-02-15T03:18:05.052377+00:00
| 600 | false |
\n\n# Approach\nJust construct the prefix and suffix array based on no of subsequence matching characters and then just see how many characters are matching from left and how many are matching from right. Then take the unmatched part for every index and return the minimum\n\nLink : https://www.youtube.com/watch?v=eVAeTG5VjVM\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n\n int minimumScore(string s, string t) \n {\n int m = s.size();\n int n = t.size();\n\n int mini = 1e9;\n vector<int>pref(m, 0), suff(m, 0);\n\n int j = 0;\n for(int i=0; i<m && j<n; i++)\n {\n if(s[i] == t[j])\n {\n pref[i]++;\n j++;\n }\n\n if(i>0) pref[i] += pref[i-1];\n }\n\n j=n-1;\n for(int i=m-1; i>=0 && j>=0; i--)\n {\n if(s[i] == t[j])\n {\n suff[i]++;\n j--;\n }\n\n if(i<m-1) suff[i] += suff[i+1];\n }\n\n for(int i=0; i<m-1; i++)\n {\n mini = min(mini, n-(pref[i]+suff[i+1]));\n }\n\n mini = min(mini, n-(pref[m-1]));\n mini = min(mini, n-(suff[0]));\n\n return max(mini, 0);\n }\n};\n```
| 14 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
[Python3] forward & backward
|
python3-forward-backward-by-ye15-zs5d
|
\n\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n suffix = [-1]*len(s)\n j = len(t)-1\n for i in reversed(range(len
|
ye15
|
NORMAL
|
2023-02-12T05:45:30.755253+00:00
|
2023-02-12T05:47:40.939549+00:00
| 1,282 | false |
\n```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n suffix = [-1]*len(s)\n j = len(t)-1\n for i in reversed(range(len(s))): \n if 0 <= j and s[i] == t[j]: j -= 1\n suffix[i] = j \n ans = j + 1\n j = 0 \n for i, ch in enumerate(s): \n ans = min(ans, max(0, suffix[i] - j + 1))\n if j < len(t) and s[i] == t[j]: j += 1\n return min(ans, len(t)-j)\n```
| 11 | 0 |
['Python3']
| 1 |
subsequence-with-the-minimum-score
|
Python 3 || 10 lines, two passes || xx
|
python-3-10-lines-two-passes-xx-by-spaul-wyi0
|
\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n\n m, n = len(s), len(t)\n suff, j = [0]*m, n\n\n for i in range(m)
|
Spaulding_
|
NORMAL
|
2023-02-12T21:24:24.130076+00:00
|
2024-06-21T18:31:45.539217+00:00
| 562 | false |
```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n\n m, n = len(s), len(t)\n suff, j = [0]*m, n\n\n for i in range(m)[::-1]:\n\n if j > 0 and s[i] == t[j-1]: j -= 1\n suff[i] = j-1\n\n ans, j = j, 0\n\n for i in range(m):\n\n ans = min(ans, max(0, suff[i] - j + 1))\n if j < n and s[i] == t[j]: j += 1\n\n return min(ans, n-j)\n```\n[https://leetcode.com/problems/subsequence-with-the-minimum-score/submissions/896781999](http://)\n\nI could be wrong, but I think that time complexity is *O*(*S* + *T*) and space complexity is *O*(*S* + *T*), in which *S* ~ `len(s)` and *T* ~ `len(t)`.
| 9 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
C++| Binary Search + Sliding Window + Prefix array | O(N*log(N))
|
c-binary-search-sliding-window-prefix-ar-6tpu
|
Hint: Let left and right be the minimum and maximum index among all removed characters. If we remove all characters from left to right ( remove sustring t[left:
|
kumarabhi98
|
NORMAL
|
2023-02-12T13:23:14.999896+00:00
|
2023-02-20T09:04:35.203345+00:00
| 745 | false |
**Hint:** Let `left` and `right` be the minimum and maximum index among all removed characters. If we remove all characters from left to right ( remove sustring t[left:right] from string `t`), it will not change the result. Find the min length of the substring to be removed.\n`Note: right-left+1 is the length of substring t[left:right]`\n## Approach: \n* With the help of Binary search, we can find the lenght of the smallest substring to be removed.\n* Now, once we have a lenght (say **k**) to be removed, we can make use of prefix & suffix array and sliding window to find out whether it\'s possible to remove any substring of length **k** to make `t` a subsequence of `s` or not.\n* Make a prefix array `left` where **left[i]** is the min index of `s` such that substring t[0:i] is a subsequence of substring s[0:left[i]]\n* Make a suffix array `right` where **right[i]** is the max index of `s` such that substring t[i:] is a subsequence of substring s[left[i]:]\n* Now apply the Sliding window. See the implementation for more understanding\n```\nclass Solution {\npublic:\n void makeprefix(vector<int>& left,vector<int>& right,string &s,string &t){\n for(int i = 0,j = 0; i<s.size() && j<t.size();++i){\n if(s[i]==t[j]){\n left[j] = i; j++;\n }\n }\n for(int i = s.size()-1,j = t.size()-1;i>=0 && j>=0;--i){\n if(s[i]==t[j]){\n right[j] = i; j--;\n }\n }\n }\n bool find(vector<int>& left,vector<int>& right,int m,int n){\n if(m==n) return 1;\n if(right[m]!=-1 || left[n-m-1]!=-1) return 1;\n for(int i = 0,j = m+1; j<n ;++i,++j){\n if(left[i]!=-1 && right[j]!=-1 && left[i]<right[j]) return 1;\n }\n return 0;\n }\n int minimumScore(string s, string t) {\n vector<int> left(t.size(),-1),right(t.size(),-1);\n makeprefix(left,right,s,t);\n int l = 0,h = t.size(),re = -1;\n while(l<=h){\n int m = (l+h)/2;\n if(find(left,right,m,t.size())) { re = m; h = m-1; }\n else l = m+1;\n }\n return re;\n }\n};\n```\n**Upvote** if it helps
| 9 | 0 |
['C', 'Sliding Window', 'Binary Tree']
| 0 |
subsequence-with-the-minimum-score
|
C++ Clean, Explained.
|
c-clean-explained-by-aqxa2k-xvqb
|
Solution \n\nIf we remove some substring of $t$, we are left with a prefix (possibly empty), and a suffix (possibly empty), of $t$. This prompts us to precalcul
|
aqxa2k
|
NORMAL
|
2023-02-12T04:00:26.766155+00:00
|
2023-02-12T04:33:52.798956+00:00
| 2,323 | false |
# Solution \n\nIf we remove some substring of $t$, we are left with a prefix (possibly empty), and a suffix (possibly empty), of $t$. This prompts us to precalculate for each prefix/suffix, what is the minimum prefix/suffix of $s$ that we need for the prefix/suffix of $t$ to be a subsequence of. \n\nFirstly, finding the longest prefix of a string $t$ that is a subsequence of $s$ can be done in $O(|s|+|t|)$. This is done by using two pointers, one for each string. \n\nLet $i$ be the pointer for $s$, and $j$ be the pointer for $t$. \n\nNote that as we are incrementing $j$, the pointer $i$ is the rightmost position in the \n\n\nin $s$ of the prefix of $t$ up to $j$. Thus, we are able to find, for each prefix of $t$, what is the minimal size of the prefix of $s$ (the maximum index) such that $t$ is a subsequence of that prefix. In my implementation, I use an array $left$, and store $i$ in $left_j$. Conversely, this logic can also be applied to find the minimal suffix of $s$ such that it contains a subsequence of a suffix of $t$. I store the minimum index $i$ in $right_j$ (the smallest suffix of s such that the suffix from $t$ is a subsequence of it). \n\nNow that we have $left$ and $right$, we can fix the prefix (we will call $a$ the last index of the prefix) of $t$ that we will keep, and binary search for the leftmost suffix of $t$ such that there is no overlap in $s$. (We want a prefix and a maximal suffix to minimize r-l+1, but we do not want them to overlap in letters in $s$, or else we will not have a subsequence). Thus, we can binary search for the biggest suffix (we will call $b$ the first index of the suffix) of $t$ that satisfies the following conditions: \n\n$a$ < $b$\n$left_a$ $<$ $right_b$\n\nSee my implentation below for details. \n\nThe time complexity is $O(NlogN)$, \n\n```cpp\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.size(), m = t.size(); \n vector<int> l(m, -1), r(m, -1); //left, right arrays. \n int j = 0; \n for (int i = 0; i < n; ++i) {\n if (j >= m) break; \n if (s[i] == t[j]) {\n l[j] = i; //for a prefix of t from 0...j, i is the greatest \n //index in s such that it is a subsequence\n j++; \n }\n }\n j = m-1; \n for (int i = n-1; i >= 0; --i) {\n if (j < 0) break; \n if (s[i] == t[j]) {\n r[j] = i; \n //for a suffix of t from j...n-1, i is the smallest \n //index in s such that it is a subsequence\n j--; \n }\n }\n\n int ans = m; \n for (int i = 0; i < m; ++i) { \n //update answer for prefix/suffix is removed \n //only (new t is a prefix or suffix of t)\n if (l[i] != -1) ans = min(ans, m-i-1); \n if (r[i] != -1) ans = min(ans, i); \n }\n\n //if the smallest suffix is invalid, we return our answer\n //in order to avoid annoying casework in our binary search\n if (r[m-1] == -1) return ans; \n \n for (int i = 0; i < m-1; ++i) {\n if (l[i] != -1) {\n if (l[i] >= r[m-1]) break; \n \n int lo = i + 1, hi = m - 1; \n while (lo < hi) {\n int md = lo + (hi - lo)/2; \n //check if left index in s is less than right \n //index of the suffix (a < b as said in solution)\n if (l[i] < r[md]) hi = md; \n else lo = md + 1; \n }\n //lo is the smallest index in the biggest \n //suffix that satisfies the condition \n ans = min(ans, lo - i - 1); \n //lo - i - 1 is the size if the deleted substring\n }\n }\n return ans; \n \n }\n};\n```
| 9 | 0 |
['C++']
| 4 |
subsequence-with-the-minimum-score
|
simple prefix and suffix
|
simple-prefix-and-suffix-by-virendra115-zfub
|
\njava\nclass Solution {\n public int minimumScore(String s, String t) {\n int[] pre = new int[s.length()];\n for(int i=0, j=0; i<s.length() &&
|
virendra115
|
NORMAL
|
2023-02-12T05:42:14.758315+00:00
|
2023-02-12T05:47:10.671519+00:00
| 1,110 | false |
\n```java\nclass Solution {\n public int minimumScore(String s, String t) {\n int[] pre = new int[s.length()];\n for(int i=0, j=0; i<s.length() && j<t.length(); i++){\n if(i>0) pre[i] = pre[i-1];\n if(s.charAt(i) == t.charAt(j)){\n j++; pre[i]++;\n }\n }\n int c=0,ans = 0;\n for(int i=s.length()-1, j=t.length()-1; i>=0 && j>=0; i--){\n ans = Math.max(ans, c+pre[i]);\n if(s.charAt(i) == t.charAt(j)){\n j--; c++;\n }\n }\n ans = Math.max(ans, c);\n return Math.max(0, t.length()-ans);\n }\n}\n```
| 7 | 0 |
['Java']
| 2 |
subsequence-with-the-minimum-score
|
Get Left for Right with Video || O(n) Time and Space || C++ Code
|
get-left-for-right-with-video-on-time-an-a7jo
|
Intuition\nIf right - left + 1 is the cost (this is similar to size of substring from left to right index),\nthere is no sense in removing only some elements fr
|
rupakk
|
NORMAL
|
2023-02-12T08:44:47.221828+00:00
|
2023-02-12T15:26:50.076324+00:00
| 592 | false |
# Intuition\nIf right - left + 1 is the cost (this is similar to size of substring from left to right index),\nthere is no sense in removing only some elements from left index to right index.\nIt makes sense to remove entire substring.\nBecause then we will be having a smaller string t to form a subsequence which is better.\n\nSo we will remove all characters from left index to right index.\nWhich means we will will remove a substring from t.\n\nNow about right and left:\n\nI can build all possible left separately and then for a particular right, I can get a left(which I previously built) to form answer.\n\nVideo:\n<iframe width="460" height="250" src="https://www.youtube.com/embed/c75mRQfNtxg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>\n\n# Approach\nFirst we start to build all possible left.\nHow?\nWe keep two pointers ps(for s string) and pt(for t string)\nWe initialize both to 0.\nWe keep incrementing ps pointer until value at both pointers are not equal\n\nIn other words, until substring of t from 0 - pt doesn\'t become a subsequence of (substring of s from 0 - ps).\n\nOnce this done we add {pt+1, ps} to our possible left vector.\n\nWhy pt+1?\nBecuse that is the left\n\nWhy ps?\nWe are storing s index for all possible left becuase it can happen that s index for right becomes <= the s index for left.\nIn that case our answer will be wrong.\n\nThen we start our process to get right:\n\nIn the same way we build possible left from start of our array, we get possible rights from end of the array\n\nThere just two differences here:\n1. We keep eliminating elements from back of the possible left array based on two conditions:\n i. left <= right\n ii. s index for left < s index for right\n2. We calculate answer for substring left--right\n\nHave a look at code for better understanding.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity:O(n)\n\n# C++ Code\n```\nclass Solution {\npublic:\n\tint minimumScore(string s, string t) {\n\t\tvector<pair<int, int>> psbLeft;// <left, s index for that left>\n\t\tint ps = 0;//pointer for s string\n\t\tint pt = 0;//pointer for t string\n\t\tint ans = t.size();\n\n\t\t//Building Possible Left:\n\t\tpsbLeft.push_back({0, -1});\n\t\twhile (ps < s.size() && pt < t.size()) {\n\t\t\twhile (ps < s.size() && s[ps] != t[pt])\n\t\t\t\tps++;\n\t\t\tif (ps == s.size())\n\t\t\t\tbreak;\n\t\t\tpsbLeft.push_back({pt + 1, ps});\n\t\t\tpt++;\n\t\t\tps++;\n\t\t}\n\n //If t is subsequence of s then we return 0\n //If not we can get smallest substring from end of t we have to remove to make t substring of s\n\t\tif (psbLeft.back().first == t.size())\n\t\t\treturn 0;\n\t\telse\n\t\t\tans = min(ans, (int)t.size() - psbLeft.back().first);\n\n\t\tps = s.size() - 1;\n\t\tpt = t.size() - 1;\n\n //Getting Possible Right\n\t\twhile (ps >= 0 && pt >= 0) {\n\t\t\twhile (ps >= 0 && s[ps] != t[pt])\n\t\t\t\tps--;\n\t\t\tif (ps < 0)\n\t\t\t\tbreak;\n\n\t\t\tint right = pt - 1;\n\n //Two conditions checked in below code:\n //1. left <= right\n //2. s index for left < s index for right\n\t\t\twhile (psbLeft.size() && (psbLeft.back().first > right || psbLeft.back().second >= ps))\n\t\t\t\tpsbLeft.pop_back();\n\n //If substring from starting of t removed \n\t\t\tans = min(ans, pt);\n\n //Left and right both used:\n\t\t\tif (psbLeft.size()) {\n\t\t\t\tint left = psbLeft.back().first;\n\t\t\t\tans = min(ans, right - left + 1);\n\t\t\t}\n\t\t\tpt--;\n\t\t\tps--;\n\t\t}\n\t\treturn ans;\n\t}\n};\n```\n<b>Upvote if you found this helpful!</b>
| 6 | 0 |
['Greedy', 'Sliding Window', 'C++']
| 1 |
subsequence-with-the-minimum-score
|
💥💥 Beats 100% on runtime and memory [EXPLAINED]
|
beats-100-on-runtime-and-memory-explaine-9nv7
|
IntuitionThe goal is to find the minimum score after removing characters from t so that it becomes a subsequence of s. The score is determined by the leftmost a
|
r9n
|
NORMAL
|
2025-01-06T02:15:54.967205+00:00
|
2025-01-06T02:15:54.967205+00:00
| 59 | false |
# Intuition
The goal is to find the minimum score after removing characters from t so that it becomes a subsequence of s. The score is determined by the leftmost and rightmost indices of removed characters, so we aim to remove as few characters as possible, minimizing the range of indices involved.
# Approach
First, check if t is already a subsequence of s. Then, create an array to track the index of the first character in t that can be removed at each position in s. Next, iterate backward over s to check possible removals and calculate the smallest score by considering both valid and invalid removal scenarios. The result is the minimum score after these adjustments.
# Complexity
- Time complexity:
O(n + m), where n is the length of s and m is the length of t. This is because we make a few linear passes through both strings.
- Space complexity:
O(n), as we store the first removed indices for each position in s (in the first_removed_from_left array).
# Code
```rust []
impl Solution {
pub fn minimum_score(s: String, t: String) -> i32 {
let s = s.as_bytes();
let t = t.as_bytes();
let n = s.len();
let m = t.len();
// Check if `t` is already a subsequence of `s`
let mut j = 0;
for &ch in s {
if j < m && ch == t[j] {
j += 1;
}
if j == m {
return 0;
}
}
// Calculate the firstRemovedIndexFromLeft array
let mut first_removed_from_left = vec![0; n];
let mut left = 0;
for i in 0..n {
if left < m && s[i] == t[left] {
left += 1;
}
first_removed_from_left[i] = left;
}
// Initialize the result with the worst case (remove the entire `t`)
let mut res = m as i32;
// Calculate the result by iterating backward over `s`
let mut right = m as i32 - 1;
for i in (0..n).rev() {
if right >= first_removed_from_left[i] as i32 {
res = res.min(right - first_removed_from_left[i] as i32 + 1);
}
if right >= 0 && s[i] == t[right as usize] {
right -= 1;
}
res = res.min(right + 1);
}
res
}
}
```
| 4 | 0 |
['Array', 'Two Pointers', 'String', 'Binary Search', 'Suffix Array', 'Binary Tree', 'Rust']
| 0 |
subsequence-with-the-minimum-score
|
c++ solution
|
c-solution-by-dilipsuthar60-k99t
|
\nclass Solution {\npublic:\n bool find(string &s,string &t,int mid)\n {\n int n=s.size();\n int m=t.size();\n vector<int>left(m,n),r
|
dilipsuthar17
|
NORMAL
|
2023-02-12T09:54:39.385407+00:00
|
2023-02-12T09:54:39.390280+00:00
| 1,212 | false |
```\nclass Solution {\npublic:\n bool find(string &s,string &t,int mid)\n {\n int n=s.size();\n int m=t.size();\n vector<int>left(m,n),right(m,-1);\n for(int i=0,j=0;j<m&&i<n;i++)\n {\n if(s[i]==t[j])\n {\n left[j]=i;\n j++;\n }\n }\n for(int i=n-1,j=m-1;j>=0&&i>=0;i--)\n {\n if(s[i]==t[j])\n {\n right[j]=i;\n j--;\n }\n }\n if(left[m-1]!=n)\n {\n return true;\n }\n if(right[mid]!=-1||left[m-mid-1]!=n)\n {\n return true;\n }\n for(int i=1;i+mid<m;i++)\n {\n if(left[i-1]<right[i+mid])\n {\n return true;\n }\n }\n return false;\n }\n int minimumScore(string s, string t) {\n int l=0;\n int r=t.size()-1;\n int ans=t.size();\n while(l<=r)\n {\n int mid=(l+r)/2;\n if(find(s,t,mid))\n {\n ans=mid;\n r=mid-1;\n }\n else\n {\n l=mid+1;\n }\n }\n return ans;\n }\n};\n```
| 4 | 0 |
['C', 'Binary Tree', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
This Problem Drove me Crazy! Stayed up from 4 A.M. to 10 A.M. solving this.
|
this-problem-drove-me-crazy-stayed-up-fr-czfs
|
I couldn\'t solve the problem during the contest, but I didn\'t want to read any solutions because it seemed solvable. But as the night progressed, I began to t
|
t747
|
NORMAL
|
2023-02-13T16:49:31.466892+00:00
|
2023-02-13T16:49:31.466938+00:00
| 99 | false |
I couldn\'t solve the problem during the contest, but I didn\'t want to read any solutions because it seemed solvable. But as the night progressed, I began to think it was impossible. Here are the ideas of my failed approaches:\n\n**Approach 1: Binary Search on Length of Optimal R-L**\nThe idea was to use binary search to find the optimal length of R-L. Whenever I encountered a character that could not form a subsequence, I skipped the next [mid] elements. This is the approach I tried during the contest, which only passed ~30 test cases. I assumed this was due to bad implementation, so I continued this approach for 2 more hours.\n**Why It Didn\'t Work:**\nI looked over the fact that sometimes it is not always optimal to start deleting at the first element that doesn\'t fit. For example, for the case "abcdef" "afbcde", my program would go from a to f then delete b, c, d, and e. This is not optimal.\n\n**Approach 2: Sliding Window + Binary Search**\nThe idea was basically the same as the first one but with a sliding window of length [mid]. I couldn\'t figure out how to check if the sequence t was a subsequence of s with a sliding window in O(N) time however, so this approach died because it was O(N^2 log N) at best.\n\n**Approach 3: Binary Search on Right and Left Bound**\nThis time, I tried to do two separate binary searches. The first one was to find the leftmost right index that I would have to delete up to to make t a subsequence of s. Then, I would find minimum distanced left index from right that would still allow the subsequence condition to be fulfilled. This would be found using a second binary search.\n**Why It Didn\'t Work:** \nIt turns out finding the minimum right index was basically irrelevant. While I do find the minimum right bound, it doesn\'t guarantee that the left bound created from it is optimal.\n\n**Approach 4: DP + Binary Search (Accepted!!)**\nFinally! I had the idea to use DP and binary search to find the optimal right and left bound. Scan string t from the left and right and record the most characters you can use from the left and right. Then use binary search to find the maximum non-overlapping sum.\n\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n map<int, int> m;\n int p1 = 0; // pointer for string s\n int ans = 0;\n for(int i = 0; i < t.length(); i++){\n while(p1<s.length() && t[i] != s[p1]) p1++;\n if(p1 == s.length()) break;\n m[p1] = i+1; // how many characters I can use up to this point\n p1++;\n ans = max(ans, i+1);\n }\n p1 = s.length()-1;\n for(int i = t.length()-1, k =1; i>=0; i--, k++){\n while(p1>=0 && t[i] != s[p1]) p1--;\n if(p1<0) break;\n auto it = m.lower_bound(p1);\n if(it != m.begin()){ // find the best non overlapping pointer behind this one and add it up\n it--;\n auto other = it->second;\n ans = max(ans, k+other);\n }\n p1--;\n ans = max(ans, k);\n }\n int len = t.length();\n if(len-ans<0) return 0;\n return len-ans;\n }\n};\n
| 3 | 0 |
[]
| 0 |
subsequence-with-the-minimum-score
|
Video Explanation(Hindi) || O(n) || Prefix and Suffix array || C++
|
video-explanationhindi-on-prefix-and-suf-0hfr
|
Video Explanation ( Hindi )\n# Intuition\n Describe your first thoughts on how to solve this problem. \nIf you will carefully observe ,the score depends on the
|
pkpawan
|
NORMAL
|
2023-02-13T08:03:16.287019+00:00
|
2023-02-13T10:56:27.027860+00:00
| 357 | false |
[Video Explanation ( Hindi )](https://www.youtube.com/watch?v=-BlFzx80flA&t=912s)\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you will carefully observe ,the score depends on the (**maximum and minium index** ) deleted and any **other index between** is **useless** , so its better to consider or delete all of them . Then (right - left)+1 = length of substring deleted .\nAnd now you know the main **hidden** problem , **Find the minimum length of substring which when deleted makes t subsequency of s** .\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere the string \'s\' does not change and after removing substring from \'t\' our t is divided into two parts suffix( part after delted substring to end) and prefix (part from start to just before delted substring) . \nWe can form two disjoint parts from [0,i] and [i+1, n-1] for each index \'i\' , n = length of string \'s\' . And for [0,i] we want to find the max length of prefix that we can get from [0,i] characters of \'s\' and for [i+1,n-1] we want to find the length of max suffix of \'t\' that we can get .\n\nLet x = max_prefix_length (for [0,i])\ny = max_suffix_length ( for [i+1,n-1])\nm = intial length of string \'t\'\nlen = length of string formed from prefix and sufix for \'i\' = (x+y)\nLenth of substring deleted = m - len \nWe find len for each of the \'i\' and store the minmum .\nEdge case when we derive just prefix or suffix from whole string s.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\n\nclass Solution {\npublic:\n \n \n \n int minimumScore(string s, string t) {\n int n = s.size();\n int m = t.size();\n int start = 0,end = m-1;\n vector<int>pref(n),suff(n);\n int i =0 ,j = 0;\n\n //prefix[i] store the max lenght of prefix of array that can be derived\n //from characters of string \'S\' from [0,i]\n int c = 0;\n while(i<n && j<m){\n if(s[i] == t[j]){\n c++;\n j++;\n }\n pref[i] = c;\n i++;\n }\n while(i<n){\n pref[i] = c;\n i++;\n }\n // length of substring to remove if we derive prefix from [0,n-1] of \n //character of \'S\'\n int ans = m-c;\n i = n-1,j = m-1;\n c = 0;\n\n //suffix[i] store the max lenght of prefix of array that can be derived\n //from characters of string \'S\' from [i,n-1]\n while(i>=0 && j>=0){\n if(s[i] == t[j]){\n c++;\n j--;\n }\n suff[i] = c;\n i--;\n }\n \n while(i>=0){\n suff[i] = c;\n i--;\n }\n if(c == m)return 0;\n \n // length of substring to remove if we derive suffix from [0,n-1] of \n //character of \'S\'\n ans = min(m-c,ans);\n for(int i=0;i<(n-1);++i){\n //m - inital length of string \'t\'\n // pref[i] + suff[i] = final length of string \'t\' after removing substring\n ans = min(ans,m - (pref[i]+suff[i+1]));\n }\n \n return ans;\n }\n};\n```
| 3 | 0 |
['Suffix Array', 'Prefix Sum', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
Prefix + Suffix Array + Binary Search Solution
|
prefix-suffix-array-binary-search-soluti-44w3
|
Intuition\n Describe your first thoughts on how to solve this problem. \nS: Source string \nT: Target string (where we can do removal operation)\n\nWe have to f
|
tazril
|
NORMAL
|
2023-02-12T11:11:44.802538+00:00
|
2023-02-12T11:11:44.802569+00:00
| 309 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nS: Source string \nT: Target string (where we can do removal operation)\n\nWe have to find longest prefix and suffix of T that is a subsequence of S.\nWe have to do some operation on them (prefix and suffix array) to figure what elements will remain at end. We can get the removal length by subtracting this present length from length of T\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nS: Source string \nT: Target string (where we can do removal operation)\n1. Find the longest prefix of T that is a subsequence of S\n2. Find the longest suffix of T that is a subsequence of S\n3. If the length of prefix = length of T, answer is 0 as no removal required\n4. Find the minimum overlap that can be eliminated. This can be achieved by binary search. We can iterate prefix array and search in suffix array the value greater than current value.\n5. We get present element length = length of prefix + length of suffix - overlap\n6. Cost = length of T - present length \n\n# Complexity\n- Time complexity: O(NlogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n vector<int> prefix, suffix;\n \n for(int i = 0, j = 0; i < s.length() and j < t.length(); i++) {\n if(s[i] == t[j]) {\n prefix.push_back(i);\n j++;\n }\n }\n \n for(int i = s.length() - 1, j = t.length() - 1; 0 <= i and 0 <= j; i--) {\n if(s[i] == t[j]) {\n suffix.push_back(i);\n j--;\n }\n } \n reverse(suffix.begin(), suffix.end());\n \n if(prefix.size() == t.length()) { // already a subsequence\n return 0;\n }\n \n int overlap = prefix.size();\n for(int i = 0; i < prefix.size(); i++) {\n // eliminated from prefix\n int left = prefix.size() - i - 1;\n // eliminated from suffix\n int right = upper_bound(suffix.begin(), suffix.end(), prefix[i]) - suffix.begin();\n // minimum elimination required for prefix_end < suffix_start\n overlap = min(overlap, left + right);\n }\n \n // elements present at the end\n int present = prefix.size() + suffix.size() - overlap;\n // elements eleminated or the cost\n return t.length() - present;\n }\n};\n```
| 3 | 0 |
['Binary Search', 'C++']
| 1 |
subsequence-with-the-minimum-score
|
Simple C++ solution using two pointers
|
simple-c-solution-using-two-pointers-by-b6apg
|
Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(M)\n\n# Code\n\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int
|
omhari
|
NORMAL
|
2023-02-12T05:47:35.332563+00:00
|
2023-02-12T05:47:35.332598+00:00
| 1,162 | false |
# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(M)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n=s.size();\n int m=t.size();\n vector<int> pref(m, n);\n vector<int> suff(m, -1);\n for(int i=0, j=0; i<s.size() && j<t.size(); i++)\n {\n if(s[i]==t[j])\n pref[j++]=i;\n }\n\n for(int i=s.size()-1, j=t.size()-1; i>=0 && j>=0; i--)\n {\n if(s[i]==t[j])\n suff[j--]=i;\n }\n \n \n if(pref.back()!=n)\n return 0;\n\n int tot=t.size();\n \n int pos=0;\n for(int i=0; i<m; i++)\n {\n if(pref[i]==n)\n break;\n \n while(pos<m && suff[pos]<=pref[i])\n pos++;\n \n tot=min(tot, pos-i-1);\n }\n for(int i=m-1; i>=0; i--)\n {\n if(suff[i]!=-1)\n tot=min(tot, i);\n }\n return tot;\n }\n};\n\n\n\n```
| 3 | 0 |
['Two Pointers', 'String', 'C++']
| 1 |
subsequence-with-the-minimum-score
|
binary search
|
binary-search-by-jainaditya8464-p8em
|
Intuition\n Describe your first thoughts on how to solve this problem. \nfor a particular score , instead of removing just some elements b/w l and r. we can rem
|
jainaditya8464
|
NORMAL
|
2023-02-12T05:13:30.209559+00:00
|
2023-02-18T06:42:24.058031+00:00
| 797 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfor a particular score , instead of removing just some elements b/w l and r. we can remove all the elements. that way we have to check for less number of elements of t for exactly the same score.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe binary search for a particular score and for all the values of l and r for this score. we check if t(0.........l-1) and t(r+1.......n-1) is a subsequence of s. if yes, then for this score, there exists a configuration where t is a subsequence of s. now we search for lower scores, otherwise we search for higher scores. to check for a paricular score, i used the prefix/suffix array and sliding window method.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n vector<int>pref, suff;\n bool can(int mid, string &t, string &s){\n //cout<<mid<<endl;\n for(int i=0, j=mid-1; j<t.size(); i++,j++){\n int a= (i==0)?0:pref[i-1];\n int b=(j==t.size()-1)?0:suff[j+1];\n //cout<<i<<" "<<j<<" "<<a<<" "<<b<<endl;\n if(a==-1 || b==-1)continue;\n if(a<b)return true;\n if(j==t.size()-1 && a>=0)return true;\n if(i==0 && b>=0)return true;\n }\n return false;\n }\n void precompute(string &s, string &t){\n pref.resize(t.size(), -1);\n suff.resize(t.size(), -1);\n int n=s.size();\n for(int i=0, j=0; i<n && j<t.size(); i++){\n if(s[i]==t[j]){\n pref[j]=i;\n j++;\n }\n }\n for(int i=n-1, j=t.size()-1; i>=0 && j>=0; i--){\n if(s[i]==t[j]){\n suff[j]=i;\n j--;\n }\n }\n // for(int i=0; i<t.size(); i++){\n // cout<<pref[i]<<" "<<suff[i]<<endl;\n // }\n }\n int minimumScore(string s, string t) {\n precompute(s, t);\n if(suff[0]!=-1)return 0;\n int n=t.size();\n int lo=1, hi=n;\n while(hi-lo>1){\n int mid=(hi+lo)/2;\n bool c=can(mid, t, s);\n if(c){\n hi=mid;\n }else{\n lo=mid+1;\n }\n }\n if(can(lo, t, s))return lo;\n return hi;\n }\n};\n```
| 3 | 0 |
['Binary Search', 'C++']
| 2 |
subsequence-with-the-minimum-score
|
[Java] Clean greedy + binary search solution
|
java-clean-greedy-binary-search-solution-856o
|
Intuition\n\nDon\'t be confused by the "subsequence". Here the score is defined as right - left + 1, meaning that all chars between left and right can be remove
|
wddd
|
NORMAL
|
2023-02-12T04:34:24.937771+00:00
|
2023-02-14T22:46:38.816978+00:00
| 821 | false |
# Intuition\n\nDon\'t be confused by the "subsequence". Here the score is defined as `right - left + 1`, meaning that all chars between `left` and `right` can be removed all together. Or, we can say - removing part of them doesn\'t change anything.\n\nThen we can greedily check for prefix and suffix of t to get the max of `left` and min of `right`. We also need to make sure there is no overlap on s, binary search can help here.\n\n# Code\n```\nclass Solution {\n public int minimumScore(String s, String t) {\n int leftT = 0;\n List<Integer> leftSs = new ArrayList<>();\n\n for (int i = 0; i < s.length() && leftT < t.length(); i++) {\n if (s.charAt(i) == t.charAt(leftT)) {\n leftSs.add(i);\n leftT++;\n }\n }\n\n int rightT = t.length() - 1;\n List<Integer> rightSs = new ArrayList<>();\n for (int i = s.length() - 1; i >= 0 && rightT >= 0; i--) {\n if (s.charAt(i) == t.charAt(rightT)) {\n rightSs.add(i);\n rightT--;\n }\n }\n\n int result = Math.min(t.length() - leftT, rightT + 1);\n for (int i = 0; i < rightSs.size(); i++) {\n int ind = rightSs.get(i) - 1;\n int left = Collections.binarySearch(leftSs, ind);\n if (left < 0) {\n left = ~left;\n } else {\n left++;\n }\n result = Math.min(result, Math.max(0, t.length() - i - 1 - left));\n if (result == 0) {\n break;\n }\n }\n\n return result;\n }\n}\n```
| 3 | 0 |
['Java']
| 1 |
subsequence-with-the-minimum-score
|
O(n) time and space solution using a queue and a stack
|
on-time-and-space-solution-using-a-queue-0948
|
Intuition\n\nMy initial thought was that this should be a dynamic programming problem as it superficially sounds related to the classic longest subsequence prob
|
rmaleh
|
NORMAL
|
2023-07-05T02:46:15.672768+00:00
|
2023-07-05T02:46:15.672794+00:00
| 110 | false |
# Intuition\n\nMy initial thought was that this should be a dynamic programming problem as it superficially sounds related to the classic longest subsequence problem (e.g., see Cormen\'s Algorithms Text, DP Chapter). However, upon closer inspection, the problem is asking for something much simpler: the minimum distance between the first index that must be removed and the last index that must be removed to make the second string a subsequence of the first.\n\nNote that this is actually not equivalent to the LCS problem. As an example:\n\nLeft: complain\nRight: paning\n\nThe lonest common subsequence is "pain"; however, the subsequence that solves the problem is actually "pan" ("ing" get removed, which gives a minimum score of 3).\n\nThe correct way to think about it is to really focus on delaying the first character that should be removed while similtaneously considering its impact on the last character that should be removed.\n\nThe best way to explain the intuition behind my algorithm is with an example. Consider again:\n\nLeft: complain\nRight: paningoman\n\nThe minimum score is the minimum value of (maxRemove - minRemove). To maximimize minRemove (which reduces the score), we need to maximize the length of the prefix of "paning" that occurs in "complain". Note that \'p\' occurs at index 3 in complain, \'a\' occurs at index 5 (must be at an index greater than 3 to preserve subsequence order), \'n\' occurs at index 7, and then \'i\' can not longer exist in the subsequence of "comPlAiN" (where capitical letters should how the prefix "pan" becomes a subsequence of "complain"). Note that if we select "pan" as our subsequence, it means that we must remove all character of the suffix "ingoman", which gives us a score of 7.\n\nWe could also work backwards to minimize maxRemove by considering how much of the suffix of "paningoman" we can turn into a subsequence of "complain". Note that the last \'n\' occurs at index 7 in "complain", \'a\' occurs at index 5, \'m\' occurs at index 2, and \'o\' occurs at index 1. If we select "oman" as our subsequence, then we would need to remove the prefix "paning", which results in a score of 6 (which is better than 7).\n\nWe can also consider a hybrid of what is described in the last two paragraphs. We can simultaneosly select a prefix and a suffix of "paningoman" that attempts to increase minRemove and decrease maxRemove in a way that minimizes the overall score.\n\nNote that the prefixes of "paningoman" that fit as a subsequence in "complain" occur at indices:\n\n3, 5, 7 (this will be a queue as we will read element FIFO)\n\nNow traversing backwards through the two input strings, we note that the suffixes of "paningoman" that fit as a subsequence in "complain" occur at indices:\n\n1, 2, 5, 7 (this will be a stack as we will read elements LIFO)\n\nWe will refer to the first queue as `leftCand` or candidates that we will incrementally add to a prefix of "paningoman" that will exist in our optimal subsequence. We will refer to the second stack as `rightUsed`, which reflects the suffix of "paningoman" that will exist in our optimal subsequence. We will incrementally remove elements from `rightUsed` as we add elements of `leftCand`.\n\nThe first subsequence we will consider will be the characters at indices\n\n1, 2, 5, 7\n\nwhich is exactly equal to `rightUsed`. This corresponds to "oman". The score is 6 since we must remove "paning".\n\nNext, we want to add the first 3 from `leftCand` into our subsequence. But to do this, we must remove the 1 and 2 (since they occur before 3 and we need to maintain the subsequence property). This gives us\n\n3, 5, 7\n\nThis corresponds to "pan", which removes the substring "aningom", which gives us a score of 7 (not minimal, so 6 is still the best).\n\nNext, we want to add the second 5 from `leftCand` into our subsequence. But to do this, we have to remove the existing 5, again, since we want to preserve the subsequence property. This gives us\n\n3, 5, 7\n\nwhich is identical to the previous case. It turns out we will also get 3, 5, 7 when we insert the last 7 from `leftCand` and remove the 7 from `rightUsed`.\n\nThe final answer is that the minimum score is 6.\n\n\n# Approach\n\n1. Generate a queue `leftCand` consisting of the indices in `leftString` corresponding to the first n consecutive characters (i.e., prefix) of `rightString`. Note that this queue can be empty if the first character of `rightString` does not exist.\n2. Generate a stack `rightUsed` consisting of the indices in `leftString` corresponding to the last n consecutive character (i.e., suffix) of `rightString`. Note that elements being removed from this stack should be ascending order. Also, note that this stack can be empty if the last chacter of `leftString` does not exist in `rightString`.\n3. First calculate the score based on the subsequence implied by `rightUsed`. If there are no elements in `leftCand`, this this will be the minimum score.\n4. While `leftCand` is non-empty, pop the next element from the queue. Remove any indices from `rightUsed` that are less than or equal to the element popped off of `leftCand`. The list of all elements popped off of `leftCand` so far and the remaining (non-popped) elements of `rightUsed` for the next candidate subsequence. Calculate its score and check if it is minimal.\n5. Return the minimum score found.\n\n\n# Complexity\nAssume that the left string has length n and the right string has length m.\n\n**Time complexity:** \nCreating the `leftCand` queue and `rightString` stack both require a single full pass of the left string, which requires O(n) steps.\n\nThe main loop requires `|leftCand| + |rightUsed|` steps which is maximally O(2 x min(n, m)) = O(n).\n\nThe overall time complexity is O(n).\n\n**Space complexity:**\nThe only addition space created are from the queue `leftCand` and the stack `rightUsed`. This will be O(1) in the best case and O(n) in the worst case.\n\n# Code\nThe following python3 code passed all test cases. It uses the `deque` class to create the necessary queue and stack.\n\n```\nfrom collections import deque\n\nclass Solution:\n \n def getLeftIndices(leftString, rightString):\n rightIdx = 0\n leftCand = deque()\n for idx, letter in enumerate(leftString):\n if letter == rightString[rightIdx]:\n leftCand.append(idx)\n rightIdx += 1\n if rightIdx >= len(rightString):\n break\n return leftCand\n\n def getRightIndices(leftString, rightString):\n rightIdx = len(rightString) - 1\n rightCand = deque()\n for idx, letter in enumerate(leftString[::-1]):\n if letter == rightString[rightIdx]:\n rightCand.appendleft(len(leftString) - 1 - idx)\n rightIdx -= 1\n if rightIdx < 0:\n break\n return rightCand\n\n def minimumScore(self, s: str, t: str) -> int:\n leftCand = Solution.getLeftIndices(s, t)\n rightUsed = Solution.getRightIndices(s, t)\n\n minRemove = 0\n maxRemove = len(t) - 1 - len(rightUsed)\n minScore = maxRemove - minRemove + 1\n\n score = minScore\n while minScore > 0 and len(leftCand) > 0: \n if len(rightUsed) == 0 or leftCand[0] < rightUsed[0]:\n minRemove += 1\n leftCand.popleft()\n else:\n maxRemove += 1\n rightUsed.popleft()\n score = maxRemove - minRemove + 1\n minScore = min(score, minScore)\n\n return minScore\n\n```
| 2 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
PREFIX-SUFFIX || TIME (n), SPACE (n)
|
prefix-suffix-time-n-space-n-by-yash___s-kgqa
|
\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.length(),i=0,j=0,m = t.length();\n vector<int> p(n,0),su(n,0);
|
yash___sharma_
|
NORMAL
|
2023-02-24T10:03:32.564964+00:00
|
2023-02-24T10:03:32.565005+00:00
| 671 | false |
```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.length(),i=0,j=0,m = t.length();\n vector<int> p(n,0),su(n,0);\n for(i = 0; i < n&&j<m; i++){\n if(s[i]==t[j]){\n j++;\n p[i]++;\n }\n if(i){\n p[i] += p[i-1];\n }\n }\n j = m-1;\n for(i = n-1; i >=0&&j>=0; i--){\n if(s[i]==t[j]){\n j--;\n su[i]++;\n }\n if(i!=n-1){\n su[i] += su[i+1];\n }\n }\n int ans = n+10;\n // for(auto &i: p)cout<<i<<" ";cout<<endl;\n // for(auto &i: su)cout<<i<<" ";cout<<endl;\n // cout<<n-su[0]<<" ";\n for(i = 0; i < n-1; i++){\n // cout<<n-p[i]-su[i+1]<<" ";\n ans = min(ans,m-(p[i]+su[i+1]));\n }\n // cout<<n-p[n-1];\n ans = min(ans,m-p[n-1]);\n ans = min(ans,m-su[0]);\n return max(ans,0);\n }\n};\n```
| 2 | 0 |
['Greedy', 'C', 'Suffix Array', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
Solution based on great idea from Java_Programmer_CF
|
solution-based-on-great-idea-from-java_p-gk5m
|
Intuition\nRefer Java_Programmer_CF solution:\nhttps://leetcode.com/problems/subsequence-with-the-minimum-score/solutions/3174018/binary-search-sliding-window/?
|
Gang-Li
|
NORMAL
|
2023-02-13T03:10:34.918256+00:00
|
2023-02-13T03:10:34.918295+00:00
| 497 | false |
# Intuition\nRefer Java_Programmer_CF solution:\nhttps://leetcode.com/problems/subsequence-with-the-minimum-score/solutions/3174018/binary-search-sliding-window/?orderBy=most_votes\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nvar minimumScore = function (SS, TT) {\n let s = SS.split(""),\n t = TT.split("");\n let lo = 0,\n hi = TT.length;\n while (lo <= hi) {\n let m = (lo + hi) >> 1;\n if (check(s, t, m)) hi = m - 1;\n else lo = m + 1;\n }\n return hi + 1;\n};\n\nfunction check(s, t, len) {\n let t_length = t.length,\n n = s.length;\n if (len >= t_length) return true; //delete whole t array\n let pos = Array(t_length).fill(s.length + 1); //Greedy left matching\n // Arrays.fill(pos, 1_000_000_0);\n let t_left_index = 0;\n for (let i = 0; i < n; i++) {\n if (t_left_index === t_length) break;\n if (t[t_left_index] === s[i]) {\n pos[t_left_index] = i;\n t_left_index++;\n }\n }\n if (t_left_index >= t_length - len) return true; //we can delete right subarray of length len\n let right_index_of_s = n - 1;\n for (let rp = t_length - 1; rp >= len; rp--) {\n while (right_index_of_s >= 0 && s[right_index_of_s] != t[rp])\n right_index_of_s--;\n if (right_index_of_s === -1) return false;\n let lp = rp - len - 1;\n if (lp === -1 || pos[lp] < right_index_of_s) return true;\n right_index_of_s--;\n }\n return false;\n}\n\n```
| 2 | 0 |
['JavaScript']
| 1 |
subsequence-with-the-minimum-score
|
Prefix array + suffix array || Binary Search || O( n log n) || C++
|
prefix-array-suffix-array-binary-search-3pb6z
|
Intuition\n Describe your first thoughts on how to solve this problem. \nIf you will visualise you will find that character between right and left of deleted ch
|
pkpawan
|
NORMAL
|
2023-02-12T15:41:22.078287+00:00
|
2023-02-12T15:41:22.078319+00:00
| 473 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf you will visualise you will find that character between **right** and **left** of deleted charactes of \'t\' are useless ,it is better to consider them then as deleted as they will not effect the score .\n\nNow Problem statement changes **Find the smallest substring that can be deleted from t** such that **t become subsequence of s** . \n# Approach\n<!-- Describe your approach to solving the problem. -->\nI created two arrays prefix which store the index of \'s\' which matches with jth prefix character of \'t\' , similarly a suffix array .\n\nNow I want ot find max length disjoint set of prefix and suffix which minimise my value /score.\n\nSo For each of **prefix value** I consider I find the **smallest index with value just greater than prefix[i]** in **suffix** array , this will give me length of suffix that is disjoint or from [pref[i]+1,m-1] . \nm = length of t\nThe score is ((index-1) - (pref[i]+1) )+ 1 . \nIndex is the smallest value > than pref[i] , I delete all the elements from (prefix[i]+1 tot index-1) . I find score for each prefix \'i\' and store the minimum value.\n\n-- Consider the case when we don\'t take any prefix value.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n log n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\n\nclass Solution {\npublic:\n /*\n I will delete a substring from t such that prefix of of t before substring and suffix of t after substring\n is a subsequency of s\n */\n int search(vector<int>&A,int value){\n int start = 0,end = A.size()-1,mid = (start+end)/2;\n int ans = -1;\n while(start<=end){\n //find the smallest element greater than value \n //I want to find max_suffix that is subsequence of \'s\' from [value+1 , t.size()-1]\n if(A[mid] > value){\n ans = mid;\n end = mid-1;\n mid = (start+end)/2;\n }\n else{\n start = mid+1;\n mid = (start+end)/2;\n }\n }\n return ans;\n }\n \n \n int minimumScore(string s, string t) {\n int n = s.size();\n int m = t.size();\n int start = 0,end = m-1;\n vector<int>pref,suff;\n int i =0 ,j = 0;\n\n //find prefix array which store the index of \'s\'\n //which matches with jth prefix character of t\n while(i<n && j<m){\n if(s[i] == t[j]){\n pref.push_back(i);\n start = j;\n j++;\n }\n i++;\n }\n \n i = n-1,j = m-1;\n //similarly find suffix array which store the index of \'s\'\n //which matches jth character of t\n while(i>=0 && j>=0){\n if(s[i] == t[j]){\n suff.push_back(i);\n end = j;\n j--;\n }\n i--;\n }\n if(end == 0)return 0;\n reverse(suff.begin(),suff.end());\n //sort the suffix array in increasing order\n int ans = m;\n\n //we find score in case we delete a prefix from 0 to suff[0]-1\n if(suff.size()){\n int len = suff.size();\n ans = min(ans,(m-len));\n }\n \n for(int i=0;i<pref.size();++i){\n //for each prefix character we consider\n //we want to find the size of matching suffix \n //from [pref[i+1] , m-1]\n int idx = search(suff,pref[i]);\n \n //we consider the case when we delete suffix from [pref[i],m-1]\n ans = min(ans,m-(i+1));\n if(idx != -1){\n int last = m - (suff.size() - idx);\n \n last--;\n \n ans = min(ans,(last - (i+1))+1);\n }\n \n }\n \n //cout<<"\\n";\n \n return ans;\n }\n};\n```
| 2 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
Java Prefix+Suffix array
|
java-prefixsuffix-array-by-urbanturban-totk
|
Intuition\n Describe your first thoughts on how to solve this problem. \nTry to delete every possible window of size \'k\'. If we are able to delete window of s
|
urbanturban
|
NORMAL
|
2023-02-12T13:00:15.418646+00:00
|
2023-02-12T13:00:48.846375+00:00
| 98 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry to delete every possible window of size \'k\'. If we are able to delete window of size \'k\', then try to find a better minimum answer.\n\nLet\'s say the window is i......j. Now check if prefix[0...i-1] and suffix[j+1...t.length()-1] are non-overlapping.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n*logn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public int minimumScore(String s, String t) {\n\n int n=t.length();\n\n\n // prefix[i] is the min index in string \'s\' such that prefix[i] of string \'t\' is a subsequence of string \'s\'\n // suffix[i] is the min index in string \'s\' such that suffix[i] of string \'t\' is a subsequence of string \'s\'\n int[] prefix = new int[n];\n int[] suffix = new int[n];\n Arrays.fill(prefix, Integer.MAX_VALUE);\n Arrays.fill(suffix, -1);\n int j=0;\n for(int i=0;i<s.length();++i)\n {\n if(j<t.length() && s.charAt(i)==t.charAt(j))\n {\n prefix[j] = i; \n j++;\n }\n } \n j=t.length()-1;\n for(int i=s.length()-1;i>=0;--i)\n {\n if(j>=0 && s.charAt(i)==t.charAt(j))\n {\n suffix[j] = i; \n j--;\n }\n } \n \n int low=0, high=n;\n int ans=n;\n while(low<=high)\n {\n int mid=low+(high-low)/2;\n if(poss(s, t, mid, prefix, suffix))\n {\n ans=mid;\n high=mid-1;\n }\n else\n low=mid+1;\n }\n return ans;\n \n }\n public boolean poss(String s, String t, int k, int[] prefix, int[] suffix)\n {\n int start=0, end=k-1;\n int n=t.length();\n\n if(k>n)\n return true;\n\n while(end<n)\n {\n // t[0....start-1] and t[end+1.......n-1]\n if(start==0 && end<n-1 && suffix[end+1] != -1)\n return true;\n if(start>0 && end==n-1 && prefix[start-1] != Integer.MAX_VALUE)\n return true;\n if(start>0 && end<n-1 && prefix[start-1] < suffix[end+1])\n return true; \n start++;\n end++;\n }\n return false;\n }\n}\n```
| 2 | 0 |
['Java']
| 0 |
subsequence-with-the-minimum-score
|
O(N) left match and right match, easy to understand C++
|
on-left-match-and-right-match-easy-to-un-lxbz
|
The key idea is if we fix the min (left) idex to remove, how to find the min right idex as the last characater to be removed.\nWe can do this by the following
|
gaoyf1235
|
NORMAL
|
2023-02-12T04:25:20.424503+00:00
|
2023-02-12T04:39:28.276028+00:00
| 258 | false |
The key idea is if we fix the min (left) idex to remove, how to find the min right idex as the last characater to be removed.\nWe can do this by the following step:\n1 Calculate the left first match, and store the min match index in a deque (vector should be fine also).\n2 Calculate the right first match, and store the max match index in a deque.\n3 For each element in the left match deque, if we use it as last index on left, then indices less or equal to it in the right match deque are invalid, should be pop out. And the rest in right deque is the max match on right side we can have.\n4 When we iterate over left deque, we get all possible left and right. Notice that if the left or right match deque has a size same as t, the answer is 0.\n\nThe time and space complexity is O(N).\n\t\n\t\n\tclass Solution {\n\tpublic:\n\t\tint minimumScore(string s, string t) {\n\t\t\tint n = s.size();\n\t\t\tint m = t.size();\n\t\t\tdeque<int> rmatch;\n\t\t\tint si = n - 1;\n\t\t\tint ti = m - 1;\n\t\t\twhile(si >= 0 && ti >= 0){\n\t\t\t\twhile(si >= 0 && ti >= 0 && s[si] == t[ti]){\n\t\t\t\t\trmatch.push_front(si);\n\t\t\t\t\tsi--;\n\t\t\t\t\tti--;\n\t\t\t\t}\n\t\t\t\tsi--;\n\t\t\t}\n\t\t\tdeque<int> lmatch;\n\t\t\tsi = 0;\n\t\t\tti = 0;\n\t\t\twhile(si < n && ti < m){\n\t\t\t\twhile(si < n && ti < m && s[si] == t[ti]){\n\t\t\t\t\tlmatch.push_back(si);\n\t\t\t\t\tsi++;\n\t\t\t\t\tti++;\n\t\t\t\t}\n\t\t\t\tsi++;\n\t\t\t}\n\t\t\tif(lmatch.size() == m) return 0;\n\t\t\tint ans = min(m, m - (int)rmatch.size());\n\t\t\tfor(int i = 0; i < lmatch.size(); i++){\n\t\t\t\tint left = i + 1;\n\t\t\t\twhile(!rmatch.empty() && rmatch.front() <= lmatch[i]){\n\t\t\t\t\trmatch.pop_front();\n\t\t\t\t} \n\t\t\t\tint right = m - 1 - rmatch.size();\n\t\t\t\tans = min(ans, right - left + 1);\n\t\t\t}\n\t\t\treturn ans;\n\t\t}\n\t};
| 2 | 0 |
[]
| 0 |
subsequence-with-the-minimum-score
|
A Deeply Evil Problem
|
a-deeply-evil-problem-by-thomashobohm-ci80
|
Intuition\nThis is truly a diabolical problem. If someone gives you this problem in an interview I think you should just kill yourself right there in front of t
|
thomashobohm
|
NORMAL
|
2024-10-04T07:11:53.682016+00:00
|
2024-10-06T03:48:43.908707+00:00
| 110 | false |
# Intuition\nThis is truly a diabolical problem. If someone gives you this problem in an interview I think you should just kill yourself right there in front of them to teach them a lesson.\n\n# Code\n```python3 []\nfrom math import ceil\n\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n # We find the suffixes of t that are a subsequence\n # of s. We can do this by using two pointers. We start\n # at the end of s and t. We loop through s. If\n # the current character in t matches s, that means\n # that character is part of a subsequence of s.\n # We store the index of the character in s it matches\n # for later.\n left_of_suffix_index = len(t)-1\n suffix_indices = []\n for s_index in range(len(s)-1, -1, -1):\n # The score is zero if we don\'t need to remove any characters\n # from t.\n if left_of_suffix_index < 0:\n return 0\n elif s[s_index] == t[left_of_suffix_index]:\n left_of_suffix_index -= 1\n suffix_indices.append(s_index)\n # Let\'s say that we delete all of the characters before the suffix.\n # The score would be:\n # left_of_suffix_index - 0 + 1 = left_of_suffix_index + 1\n # We\'ll start with that value\n result = left_of_suffix_index + 1\n # Now we want to consider forming a subsequence of s by\n # using a prefix or using a mix of a prefix and suffix.\n # The intuition behind this is that characters in the middle\n # do not matter: only the boundaries do!\n # So we loop through each potential prefix and see what\'s\n # the largest suffix we can add to it without adding the same\n # character in s twice.\n right_of_prefix_index = 0\n for s_index in range(len(s)):\n # The score is zero if we don\'t need to remove any characters\n # from t.\n if right_of_prefix_index >= len(t):\n return 0\n elif s[s_index] == t[right_of_prefix_index]:\n # Let\'s figure out the largest suffix\n # we can combine with this prefix. That\n # is the subsequence that uses the most\n # characters in s that have an index\n # greater than s_index. We can use\n # binary search since suffix_indices is\n # in decreasing order.\n if suffix_indices:\n left = 0\n right = len(suffix_indices) - 1\n while left < right:\n midpoint = ceil((left + right) / 2)\n if suffix_indices[midpoint] > s_index:\n left = midpoint\n else:\n right = midpoint - 1\n if suffix_indices[right] > s_index:\n # On the right, we remove character at index\n right_removal_index = len(t) - 1 - (right + 1)\n # On the left, we remove a character at index\n left_removal_index = right_of_prefix_index + 1\n # So the score is\n score = right_removal_index - left_removal_index + 1\n result = min(result, score)\n right_of_prefix_index += 1\n # Now we consider using only a prefix.\n result = min(result, len(t) - 1 - right_of_prefix_index + 1)\n return result\n```
| 1 | 0 |
['Python3']
| 1 |
subsequence-with-the-minimum-score
|
Forward and Backward passes in Python, Faster than 85%
|
forward-and-backward-passes-in-python-fa-ul24
|
Approach\n Describe your approach to solving the problem. \nThis solution tries to find the best pivot for merging a prefix and a suffix so that the score is mi
|
metaphysicalist
|
NORMAL
|
2023-04-26T20:06:07.733755+00:00
|
2023-04-26T20:06:07.733783+00:00
| 64 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nThis solution tries to find the best pivot for merging a prefix and a suffix so that the score is minimized. To do so, the forward scores are precomputed for prefixes, and the backward scores are also computed for suffixes. Finally, the answer is `min(forward[i]+backward[i+1]) for all i`. \n\nYou can also precompute one of forward or backward scores only, and compute the scores of the other direction in place. However, I find it is faster to precompute both directions of scores and find the answer with `min()`. \n\n# Complexity\n- Time complexity: $$O(N)$$, where $$N$$ is the length of `s`. \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: At least one of the forward and the backward scores should be precomputed and stored. The space complexity is $$O(N)$$.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n j = 0\n forward = [0]\n for c in s:\n if t[j] == c:\n j += 1\n if j >= len(t):\n return 0\n forward.append(j)\n \n j = len(t) - 1\n backward = [j]\n for c in reversed(s):\n if t[j] == c:\n j -= 1\n backward.append(j)\n return min(b - a for a, b in zip(forward, reversed(backward))) + 1 \n```
| 1 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Python (Simple Two Pointers)
|
python-simple-two-pointers-by-rnotappl-50wy
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
rnotappl
|
NORMAL
|
2023-04-21T16:40:36.549829+00:00
|
2023-04-21T16:40:36.549872+00:00
| 56 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumScore(self, s, t):\n def scan(s,t):\n ans, i = [0], 0\n\n for c in s:\n if i < len(t) and t[i] == c:\n i += 1\n ans.append(i)\n\n return ans\n\n r1 = scan(s,t)\n r2 = reversed(scan(s[::-1],t[::-1]))\n max_val = max([i+j for i,j in zip(r1,r2)])\n\n return max(0,len(t)-max_val)\n\n \n\n \n\n\n\n\n\n\n\n \n```
| 1 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Java left & right
|
java-left-right-by-lei38-rxjk
|
```\n// separate string s into two parts and match subsequence forward and backward separately\n class Solution {\n public int minimumScore(String s,
|
lei38
|
NORMAL
|
2023-03-02T11:32:25.941909+00:00
|
2023-03-02T11:32:25.941952+00:00
| 85 | false |
```\n// separate string s into two parts and match subsequence forward and backward separately\n class Solution {\n public int minimumScore(String s, String t) {\n int m = s.length(), n = t.length();\n int[] left = new int[m];\n for (int i = 0, j = 0; i < m; i++) {\n if (j < n && s.charAt(i) == t.charAt(j)) {\n ++j;\n }\n left[i] = j;\n }\n int[] right = new int[m];\n for (int i = m - 1, j = n - 1; i >= 0 ; i--) {\n if (j >= 0 && s.charAt(i) == t.charAt(j)) {\n --j;\n }\n right[i] = j;\n }\n int min = Math.min(n - left[m - 1], right[0] + 1);\n for (int i = 0; i + 1 < m; i++) {\n min = Math.min(min, Math.max(0, right[i + 1] - left[i] + 1));\n }\n return min;\n }\n }
| 1 | 0 |
['Java']
| 0 |
subsequence-with-the-minimum-score
|
Java; O(n) / O(n) 2 passes
|
java-on-on-2-passes-by-yjianghong-4j8z
|
Intuition\nI added some notes and improved readability on top of one answer.\n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n-
|
yjianghong
|
NORMAL
|
2023-02-16T23:22:50.542490+00:00
|
2023-02-16T23:22:50.542530+00:00
| 79 | false |
# Intuition\nI added some notes and improved readability on top of one answer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n\n // First we want to convert the question to max length of prefix t matchable of prefix s[0..i] plus max length of suffix t matachable of suffix s[i+1..]\n // because the total length of t minus the max length above is the minimal score.\n // So we need 2 passes, first pass we can get the max length of prefix t, second pass we can get \n // the max length of suffix t.\n public int minimumScore(String s, String t) {\n // preMatchCount calculates at index i, how many characters in string t[0..j]\n // occurs in prefix of s[0..i]\n int[] preMatchCount = new int[s.length()];\n for (int i = 0, j = 0; i < s.length() && j <t.length(); i++) {\n if (i > 0) {\n // if s[i] has no match, then preMatchCount[i] is preMatchCount[i - 1]\n // by definition\n preMatchCount[i] = preMatchCount[i - 1];\n }\n // if there\'s match then we need to move index j forward\n if (s.charAt(i) == t.charAt(j)) {\n j++;\n preMatchCount[i]++;\n }\n }\n // sufMatchCount calculates at index i, how many characters in string t[j..]\n // occurs in suffix of s[i..]\n int sufMatchCount = 0;\n // midMatchCount calculates at index i, how many characters in string t[0..j]\n // occurs in prefix of s[0..i] plus how many characters in t[j+1 ..] occurs in \n // suffix s[i+1..]\n // t.length - midMatchCount is the final result.\n int midMatchCount = 0;\n for (int i = s.length() - 1, j = t.length() - 1; i >= 0 && j >= 0; i--) {\n midMatchCount = Math.max(midMatchCount, sufMatchCount + preMatchCount[i]);\n // if there\'s match then we need to move index j backward\n if (s.charAt(i) == t.charAt(j)) {\n j--;\n sufMatchCount++;\n }\n\n }\n // why do we want to do a max again? because midMatchCount may not be updated (the whole suffix is a match)\n \n return Math.max(0, t.length() - Math.max(midMatchCount, sufMatchCount));\n }\n\n\n}\n```
| 1 | 0 |
['Java']
| 0 |
subsequence-with-the-minimum-score
|
C++ | With Explanation | Prefix & Suffix
|
c-with-explanation-prefix-suffix-by-subr-et95
|
\nclass Solution {\npublic:\n /*\n Question can be converted into find the minimum length of substring that can be deleted such that rest becomes a su
|
SubratYeeshu
|
NORMAL
|
2023-02-13T17:21:59.532536+00:00
|
2023-02-13T17:21:59.532572+00:00
| 74 | false |
```\nclass Solution {\npublic:\n /*\n Question can be converted into find the minimum length of substring that can be deleted such that rest becomes a subsequence of s\n */\n \n int minimumScore(string s, string t) {\n vector<int>prefix, suffix;\n int i = 0, j = 0, n = s.size(), m = t.size(), count = 0;\n while(i < n && j < m){\n if(s[i] == t[j]){\n i++; j++; count++;\n }else i++;\n prefix.push_back(count);\n }\n i = n - 1, j = m - 1, count = 0;\n while(i >= 0 && j >= 0){\n if(s[i] == t[j]){\n i--; j--; count++;\n }else i--;\n suffix.push_back(count);\n }\n reverse(suffix.begin(), suffix.end());\n \n // Without taking any element\n int maxi = suffix[0];\n for(int i = 1 ; i < prefix.size() && i < suffix.size() ; i++){\n // Building the biggest possible subsequence\n maxi = max(maxi, prefix[i - 1] + suffix[i]);\n \n // Edge case : If we dont have to delete anything\n if(maxi >= m)return 0;\n }\n \n // Checking without taking any suffix part\n maxi = max(prefix[prefix.size() - 1], maxi);\n return m - maxi;\n \n }\n};\n\n```
| 1 | 0 |
['C', 'Prefix Sum']
| 0 |
subsequence-with-the-minimum-score
|
12ms | C++ | Sliding Window | Full Explanation
|
12ms-c-sliding-window-full-explanation-b-sd7a
|
Approach\n Describe your approach to solving the problem. \n1. First thing to notice is that if I\'m chosing a score x where difference in leftmost deleted elem
|
ac121102
|
NORMAL
|
2023-02-13T08:02:12.509196+00:00
|
2023-02-13T08:03:50.237524+00:00
| 118 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\n1. First thing to notice is that if I\'m chosing a score x where difference in leftmost deleted element and rightmost deleted element is x, why not delete this whole substring as it will reduce the no. of matches needed and also doesn\'t affect the score.\n2. Store prefix and suffix arrays which keeps the minimum index in s for a subsequence match of prefix and suffix of t.\n For ex - \n s: babacabca\n t: bbc\n\n pre = {0, 2, 4}\n suf = {2, 6, 7}\n3. Binary Search for a given score if it\'s possible to get a score of x.\n4. Checking if it is possible to remove x no. of elements in such a way that the prefix + suffix is a subsequence of the other string.\n 012---678 (deleting indexes 3-5)\n using pre[2] < suf[6]\n\n# Complexity\n- Time complexity:\nO(nlogn)\nCan be done in O(n) by using suffix on s and prefix on t.\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int n, m;\n \n bool pos_to_mch(int mid, vector<int> &pre, vector<int> &suf){\n if (mid == 0) return pre[m-1] < n;\n else if (mid == m) return true;\n \n // first #mid characters || last #mid characters\n if (suf[mid] >= 0 || pre[m-1-mid] < n) \n return true;\n \n // Deleting #mid character starting from index i\n for (int i=1; i+mid<m; i++){\n if (pre[i-1] < suf[i+mid]) \n return true;\n }\n return false;\n }\n \n int minimumScore(string s, string t) {\n n = s.size();\n m = t.size();\n \n vector<int> pre_mch(m);\n vector<int> suf_mch(m);\n \n int cur = 0;\n for (int i=0; i<m; i++){\n while (cur < n && s[cur] != t[i]) \n cur++;\n pre_mch[i] = cur++;\n }\n \n cur = n-1;\n for (int i=m-1; i>=0; i--){\n while (cur >= 0 && s[cur] != t[i]) \n cur--;\n suf_mch[i] = cur--;\n }\n \n int low = 0, high = m;\n \n while(low <= high){\n int mid = (low+high)/2;\n if (pos_to_mch(mid, pre_mch, suf_mch))\n high = mid-1;\n else \n low = mid+1;\n }\n return low;\n }\n};\n```
| 1 | 0 |
['C++']
| 1 |
subsequence-with-the-minimum-score
|
[C++] Beginner friendly binary search
|
c-beginner-friendly-binary-search-by-kam-ixr2
|
Intuition\nUse binary search template to find a minimal window that can be ignored in t.\n\n# Approach\nGiven a window size:\n0. we need to match t.size() - win
|
kaminyou
|
NORMAL
|
2023-02-12T04:53:24.609081+00:00
|
2023-02-12T05:03:17.940006+00:00
| 313 | false |
# Intuition\nUse binary search template to find a minimal window that can be ignored in `t`.\n\n# Approach\nGiven a window size:\n0. we need to match `t.size() - window` char.\n1. greedy match `t` from `s`\'s left to right, keep matched one in an array\n2. greedy match `t` from `s`\'s right to left by a window until all char in `t` are matched.\n\n# Complexity\n- Time complexity:\nO(NlogN)\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n bool criteria(string& s, string& t, int window) {\n // should match t.size() - window\n int n = t.size() - window;\n if (n == 0) return true;\n vector<int> collection(n, -1);\n int index = 0;\n int collectionIdx = 0;\n int validCnt = 0;\n for (int i = 0; i < s.size(); ++i) {\n if (s[i] == t[index] && collectionIdx < collection.size()) {\n collection[collectionIdx] = i;\n collectionIdx++;\n validCnt++;\n index++;\n }\n }\n if (validCnt == n) return true;\n \n index = t.size() - 1;\n collectionIdx = n - 1;\n for (int i = s.size() - 1; i >= 0; --i) {\n if (s[i] == t[index] && collectionIdx >= 0) {\n \n if (collection[collectionIdx] == -1) {\n validCnt++;\n }\n collection[collectionIdx] = i;\n if (validCnt == n) {\n if (collectionIdx == 0) return true;\n if (collectionIdx > 0 && i > collection[collectionIdx - 1]) return true;\n }\n index--;\n collectionIdx--;\n }\n }\n return false;\n \n }\n int minimumScore(string s, string t) {\n int left = 0;\n int right = t.size();\n \n while (left < right) {\n\n int mid = left + (right - left) / 2;\n if (criteria(s, t, mid)) right = mid;\n else left = mid + 1;\n }\n return left;\n }\n};\n```
| 1 | 0 |
['C++']
| 1 |
subsequence-with-the-minimum-score
|
【C++ || Java || Python3】 Binary search in value range
|
c-java-python3-binary-search-in-value-ra-wjdo
|
I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.\n\n> In addition, I\'m too weak, please be critical of m
|
RealFan
|
NORMAL
|
2023-02-12T04:21:59.283148+00:00
|
2023-08-29T12:03:40.565571+00:00
| 380 | false |
> **I know almost nothing about English, pointing out the mistakes in my article would be much appreciated.**\n\n> **In addition, I\'m too weak, please be critical of my ideas.**\n---\n\n# Intuition\n1. **Clearly, "remove all" is no worse than "remove some" for selected subsequences.**\n2. Furthermore, if deleting a short string can make $t$ a subsequence of $s$, then it must also be true to expand on the basis of this short string.\n3. Therefore, the answer is dichotomous in the value domain, and binary search can be considered.\n4. In each sample, check whether each substring of length $x$ meets the requirements after deletion. If any one is found, the result of $x$ is true, otherwise it is false.\n5. Note that when enumerating each substring, $t$ will be cut into two segments, so it is only necessary to check whether the $left + right$ is a subsequence of $s$.\n6. For the left part, greedily match the left side of $s$, and record $t[0...i]$ that can become the smallest $j$ of a subsequence of $s[0...j]$. The same is true for the right part, the record $t[i...n]$ can become the largest $j$ of the subsequence of $s[j...m]$.\n7. In this way, it is enough to scan one round and check whether there is a qualified substring.\n\n# Approach\n1. \n\n# Complexity\n- Time complexity: $O(m + n\\log{n})$\n- Space complexity: $O(m+n)$\n\n# Code\n``` C++ []\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int m = s.size(), n = t.size();\n vector<int> left(n+2, -1), right(n+2, m);\n int p = 0;\n for (int i = 0; i < n; ++i) {\n while (p < m && s[p] != t[i]) p++;\n left[i+1] = p++;\n }\n p = m - 1;\n for (int i = n - 1; i >= 0; --i) {\n while (p >= 0 && s[p] != t[i]) p--;\n right[i+1] = p--;\n }\n auto check = [&](int x) -> bool {\n for (int i = 0; i + x - 1 < n; ++i) {\n if (left[i] < right[i+x+1]) \n return true;\n }\n return false;\n };\n int l = 0, r = n;\n while (l <= r) {\n int x = (l + r) / 2;\n if (check(x)) r = x - 1;\n else l = x + 1;\n }\n return l;\n }\n};\n```\n``` Java []\nclass Solution {\n public int minimumScore(String s, String t) {\n int m = s.length(), n = t.length();\n int []left = new int[n+2];\n int []right = new int[n+2];\n int p = 0;\n for (int i = 0; i < n; ++i) {\n while (p < m && s.charAt(p) != t.charAt(i)) p++;\n left[i+1] = p++;\n }\n left[0] = -1;\n p = m - 1;\n for (int i = n - 1; i >= 0; --i) {\n while (p >= 0 && s.charAt(p) != t.charAt(i)) p--;\n right[i+1] = p--;\n }\n right[n+1] = m;\n\n int l = 0, r = n;\n while (l <= r) {\n int x = (l + r) / 2;\n boolean flag = false;\n for (int i = 0; i + x - 1 < n; ++i) {\n if (left[i] < right[i+x+1]) \n flag = true;\n }\n if (flag) r = x - 1;\n else l = x + 1;\n }\n return l;\n }\n}\n```\n``` Python3 []\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n m, n = len(s), len(t)\n left, right = [-1] * (n+2), [m] * (n+2)\n p = 0\n for i in range(n):\n while p < m and s[p] != t[i]: p += 1\n left[i+1] = p\n p += 1\n p = m - 1\n for i in range(n-1, -1, -1):\n while p >= 0 and s[p] != t[i]: p -= 1\n right[i+1] = p\n p -= 1\n\n def check(x): \n for i in range(n + 1 - x):\n if left[i] < right[i+x+1]:\n return True\n return False\n\n l, r = 0, n\n while l <= r:\n x = (l + r) // 2;\n if (check(x)): r = x - 1\n else: l = x + 1\n return l\n```
| 1 | 0 |
['Binary Search', 'Greedy', 'C++', 'Java', 'Python3']
| 1 |
subsequence-with-the-minimum-score
|
Python | Iterate from both sides | Explanation and Comment
|
python-iterate-from-both-sides-explanati-pzqp
|
First, we consider that given left that t[:left] is a substring of s[:sleft], how can we find the best right?\nOf course, right should be as small as possible.
|
n124345679976
|
NORMAL
|
2023-02-12T04:03:42.787548+00:00
|
2023-02-12T04:57:24.362878+00:00
| 611 | false |
First, we consider that given `left` that `t[:left]` is a substring of `s[:sleft]`, how can we find the best `right`?\nOf course, `right` should be as small as possible. Even we delete a ton of character inside `t` but `t[len(t)-1]` is not deleted, the score is still `len(t) - left`.\nThus, we should start with the last character of `t` to find if there\'s a character equals to it in `s[sleft:]`. Every time we find, we should choose the rightest index and we can decrease `right`. Until we cannot decrease `right`, then we should decrease `left` by one to make `sleft` smaller for giving more characters for `t[right]` to match.\n\n\n# Code\n```Python[]\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n sl = 0\n sr = len(s) - 1\n tl = 0\n tr = len(t) - 1\n k = {}\n for tl in range(len(t)):\n while sl < len(s) and s[sl] != t[tl]:\n sl += 1\n if sl == len(s):\n tl -= 1\n break\n # save smallest sleft for all left\n k[tl] = sl\n sl += 1\n \n # we set left = -1, when we don\'t use left\n k[-1] = -1\n ans = tr - tl\n # iterate every left by decreasing one\n # releave the limitation of s[sleft:]\n for ntl in range(tl, -2, -1):\n # every time we decrease left, check if right can be decreased\n while tr > ntl and sr > k[ntl]:\n if s[sr] != t[tr]:\n sr -= 1\n elif s[sr] == t[tr]:\n sr -= 1\n tr -= 1\n ans = min(tr - ntl, ans)\n return ans\n```
| 1 | 0 |
['Python', 'Python3']
| 0 |
subsequence-with-the-minimum-score
|
C++ | O(nlogn) | Sliding Window | Binary Search | Intuition | Approach
|
c-onlogn-sliding-window-binary-search-in-t43g
|
Intuition\n1. Say your answer is x.\n2. You will have a window of size x inside the string t, within which you remove characters. Say this window is from $t_i$
|
DevChoganwala
|
NORMAL
|
2023-02-12T04:02:52.416736+00:00
|
2023-02-12T04:10:45.673404+00:00
| 302 | false |
# Intuition\n1. Say your answer is `x`.\n2. You will have a window of size `x` inside the string `t`, within which you remove characters. Say this window is from $t_i$ to $t_{i+x-1}$\n3. For `x` to be the answer, $t_0t_1...t_{i-1}$ and $t_{i+x}t_{i+x+1}...t_{n}$ should be subsequenses of $t$ and earliest index of $t_{i-1}$ < latest index of $t_{i+x}$\n4. We can binary search for `x` over range `1` to `t.length()``\n\n# Approach\n1. Build a prefix array that stores for an index `i` in `t`, the earliest index in `s`, for which $t_0t_1..t_i$ is a subsequence of `s`.\n2. Build a suffix array that stores for an index `i` in `t`, the latest index in `s`, for which $t_it_{i+1}..t_n$ is a subsequence of `s`.\n3. Binary search for window length `x`.\n4. Slide a window of length `x` through `t`, if a subsquence is found before and after the window that satisfies the condition 3 in Intuition, we search for smaller windows\n\n# Complexity\n- Time complexity:\n`O(n*logn)`;\nwhere `n = t.length()``\n\n- Space complexity:\n`O(n)`\n\n# Code\n```cpp\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = t.size();\n int m = s.size();\n int pre[n], suf[n];\n int i = 0, j = 0;\n while(i<n && j<m){\n if(t[i] == s[j]){\n pre[i] = j;\n i++;\n j++;\n }else{\n j++;\n }\n }\n while(i<n){\n pre[i++] = INT_MAX;\n }\n i = n-1; j = m-1;\n while(i >= 0 && j >= 0){\n if(t[i] == s[j]){\n suf[i] = j;\n i--;\n j--;\n }else{\n j--;\n }\n }\n while(i>=0){\n suf[i--] = INT_MIN;\n }\n //checking if 0 is the answer\n if(pre[n-1] != INT_MAX) return 0;\n int low = 1, high = t.size();\n bool pos;\n while(low <= high){\n int mid = low + (high - low)/2;\n pos = 0;\n for(int i = mid-1;i<n;i++){\n int ll = (i == mid-1 ? -1 : pre[i-mid]);\n int hh = (i == n-1 ? INT_MAX : suf[i+1]);\n if(ll < hh){\n pos = 1;\n break;\n }\n }\n if(pos){\n high = mid - 1;\n }else{\n low = mid + 1;\n }\n }\n return low;\n }\n};\n```\n
| 1 | 0 |
['Binary Search', 'Sliding Window', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
O(N) java solution matching from prefix and suffix then sliding window.
|
on-java-solution-matching-from-prefix-an-rwvp
|
Code
|
NickUlman
|
NORMAL
|
2025-04-08T05:42:19.322481+00:00
|
2025-04-08T05:42:19.322481+00:00
| 1 | false |
# Code
```java []
class Solution {
public int minimumScore(String s, String t) {
/*so want to select a substring of t and only remove chars from said substring
then find the smallest substring of t possible to do this s.t. t becomes a subsequence of s.
Note: if removing some elements from a substring, might as well remove all as that would make it a subsequence
of removing some which if removing any amount gets a subsequence of s, by transitivity this would also.
Therefore, problem is equivalent to finding the length of the smallest possible substring you can remove
from t s.t. t becomes a subsequence of s.
*/
int m = t.length(), n = s.length();
int[] prefixMatch = new int[m]; //prefixMatch[i] gives s index matching t[i] where a subseq exists for prefix before t[i] in s before index
int[] suffixMatch = new int[m];
Arrays.fill(prefixMatch, (int)1e9);
Arrays.fill(suffixMatch, -n);
int sPtr = 0, tPtr = 0, res = m;
while(sPtr < n && tPtr < m) {
if(s.charAt(sPtr) == t.charAt(tPtr)) {
prefixMatch[tPtr] = sPtr;
tPtr++;
}
sPtr++;
}
if(tPtr == m) return 0;
res = m-tPtr;
sPtr = n-1;
tPtr = m-1;
while(sPtr >= 0 && tPtr >= 0) {
if(s.charAt(sPtr) == t.charAt(tPtr)) {
suffixMatch[tPtr] = sPtr;
tPtr--;
}
sPtr--;
}
res = Math.min(res, tPtr+1);
int left = 0;
for(int right = 0; right < m; right++) {
if(suffixMatch[right] > prefixMatch[left]) {
while(suffixMatch[right] > prefixMatch[left++]);
res = Math.min(res, right-left+1);
}
}
return res;
}
}
```
| 0 | 0 |
['Java']
| 0 |
subsequence-with-the-minimum-score
|
Easiest Well Explained & Commented Prefix and Suffix C++ Code
|
easiest-well-explained-commented-prefix-urk78
|
Intuition & Approach
Build Suffix Matches (rightPos):
We create an array rightPos of size m (length of t) initialized with -1.
A pointer right starts at the e
|
Alfortius
|
NORMAL
|
2025-03-21T12:46:04.207891+00:00
|
2025-03-21T12:46:04.207891+00:00
| 4 | false |
# Intuition & Approach
1. Build Suffix Matches (rightPos):
- We create an array rightPos of size m (length of t) initialized with -1.
- A pointer right starts at the end of t.
- We scan s from right to left. Every time s[i] equals t[right], we store i in rightPos[right] and move right one step left.
- This tells us for each character in t (when scanning from the right) where it can match in s.
2. Initial Answer:
- If some characters from t could not be matched in the reverse scan, right remains ≥ 0.
- We set ans = right + 1, which represents the cost of removing all characters up to the last unmatched index in t.
3. Match the Prefix and Adjust Suffix:
- Use a pointer prefix to scan t from the left as you go through s.
- For each match (s[i] == t[prefix]), ensure the suffix part starts after the current index i by moving the right pointer forward until rightPos[right] > i.
- The removal cost here is the gap between the end of the prefix (prefix) and the beginning of the suffix (right), computed as right - (prefix + 1).
- Update ans with the minimum removal cost found.
4. Return the Minimum Removal Cost:
- After scanning through s, the smallest removal block length required to make t a subsequence of s is stored in ans.
This approach effectively splits t into a matched prefix and suffix (using rightPos), and the gap between these two parts gives the answer.
# Complexity
- Time complexity:
$$O(n+m)$$
- Space complexity:
$$O(m)$$
# Code
```cpp []
class Solution {
public:
int minimumScore(string s, string t) {
int n = s.size(), m = t.size();
// to store for each idx in t, the idx in s that matches it when matching from right to left
vector<int> rightPos(m, -1);
int right = m-1; // pointer to start t from right to left
for(int i = n-1; i >= 0 && right >= 0; i--){
if(s[i] == t[right]){ // match found
rightPos[right] = i;
right--; // mpve to prev char in t
}
}
int ans = right+1; // possible ans is to remove chars from 0 to last matched idx
int prefix = 0; // pointer for t prefix from left to right
for(int i = 0; i < n && prefix < m && ans > 0; i++){
if(s[i] == t[prefix]){ // match found
// we want suffix pointer to be strictly placed after curr matched i in s
while(right < m && rightPos[right] <= i){right++;}
// removal cost is no of chars removed from t b/w the matched prefix(ending at t[prefix]) and the start of suffix(at t[right])
ans = min(ans, right-(prefix+1));
prefix++; // move to next char in t
}
}
return ans;
}
};
```
| 0 | 0 |
['Two Pointers', 'String', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
Python Hard
|
python-hard-by-lucasschnee-kpzz
| null |
lucasschnee
|
NORMAL
|
2025-02-22T20:08:24.946007+00:00
|
2025-02-22T20:08:24.946007+00:00
| 7 | false |
```python3 []
class Solution:
def minimumScore(self, s: str, t: str) -> int:
'''
we remove letters from t
then, score = right - left + 1
left := min index removed
max := max index removed
want to min score
n^2 dp is easy
thinking rabin karp, z function
given we remove an index1 and index2 from t
we may as well remove all other indices from index1 + 1....index2 - 1
becuase score stays the same
for each index in t,
maybe sliding window?
remove a minimum of one index
with prefix suffix arrays
bs on prefix and suffix
we remove a segment in the middle
leaving a prefix and a suffix
we need to know if the prefix is a subseq of s and the suffix is a subseq of s and they done overlap
The score of the string is 0 if no characters are removed from the string t
'''
M, N = len(s), len(t)
pref = [M] * N
suff = [-1] * N
def calc(i, j):
if i == M or j == N:
return
if s[i] == t[j]:
pref[j] = i
calc(i + 1, j + 1)
else:
calc(i + 1, j)
calc(0, 0)
if pref[-1] != M:
return 0
def calc2(i, j):
if i < 0 or j < 0:
return
if s[i] == t[j]:
suff[j] = i
calc2(i - 1, j - 1)
else:
calc2(i - 1, j)
calc2(M-1, N-1)
best = 10 ** 10
def good(l, r):
p = -1
if l > 0:
p = pref[l-1]
s = M
if r < N - 1:
s = suff[r + 1]
return p < s
l = 0
for r in range(N):
while good(l, r):
best = min(best, r-l+1)
if best == 1:
return best
l += 1
return best
```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Clean solution with comments and explanation. JS.
|
clean-solution-with-comments-and-explana-db9z
|
Intuition\nSimilar to other variants focused on prefix and suffix arrays, but this one makes a bit more sense to me.\n\nA key detail that I missed at the very b
|
ehacke
|
NORMAL
|
2024-11-30T21:27:52.230316+00:00
|
2024-11-30T21:29:35.946360+00:00
| 5 | false |
# Intuition\nSimilar to other variants focused on prefix and suffix arrays, but this one makes a bit more sense to me.\n\nA key detail that I missed at the very beginning is this is *subsequence* not a *substring*. \n\nWe are looking for a way to drop characters from `t` such that the same sequence of characters appears in `s`. But it doesn\'t have to be an unbroken sequence, it\'s not a substring.\n\n# Approach\n- Iterate forward through `s` and do two things:\n - Increment the prefix array when we consume a matching character from `t`\n - Carry that consumed count forward to the end of the prefix array and keep incrementing as needed.\n- Do the same thing in reverse for the suffix array.\n- Then, use these prefix and suffix arrays to find minimum of the following:\n - Scan both prefix and suffix and find the minimum score that uses both prefix and suffix at any point.\n - Check if the min score is only using prefix (last prefix element)\n - Check if the min score is only using suffix (first suffix element)\n- Lastly, if that number is less than zero, there is no match. Return 0.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```javascript []\n/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nvar minimumScore = function(s, t) {\n const sLen = s.length;\n const tLen = t.length;\n\n // \n const prefix = Array(sLen).fill(0);\n const suffix = Array(sLen).fill(0);\n\n let j = 0;\n\n // Build prefix match array, with t characters consumed up until that point in s\n for (let i = 0; i < sLen; i++) {\n if (s[i] === t[j]) {\n prefix[i]++;\n j++;\n }\n\n if (i > 0) {\n prefix[i] += prefix[i - 1];\n }\n }\n\n j = tLen - 1;\n // Build suffix match array, with t characters consumed up until that point in s\n for (let i = sLen - 1; i >= 0; i--) {\n if (s[i] === t[j]) {\n suffix[i]++;\n j--;\n }\n\n if (i < sLen - 1) {\n suffix[i] += suffix[i + 1];\n }\n }\n\n let minScore = Infinity;\n\n // Find min that involves prefix and suffix\n for (let i = 0; i < sLen - 1; i++) {\n const suffixAndPrefixLen = prefix[i] + suffix[i + 1];\n minScore = Math.min(minScore, tLen - suffixAndPrefixLen);\n }\n\n // Check if min is prefix only\n minScore = Math.min(minScore, tLen - prefix[sLen - 1]);\n // Check if min is suffix only\n minScore = Math.min(minScore, tLen - suffix[0]);\n\n return Math.max(0, minScore);\n};\n```
| 0 | 0 |
['JavaScript']
| 0 |
subsequence-with-the-minimum-score
|
2565. Subsequence With the Minimum Score
|
2565-subsequence-with-the-minimum-score-btbvo
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Akhilbhogavalli
|
NORMAL
|
2024-11-13T09:40:11.956932+00:00
|
2024-11-13T09:40:11.956951+00:00
| 11 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nfrom math import ceil\n\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n # We find the suffixes of t that are a subsequence\n # of s. We can do this by using two pointers. We start\n # at the end of s and t. We loop through s. If\n # the current character in t matches s, that means\n # that character is part of a subsequence of s.\n # We store the index of the character in s it matches\n # for later.\n left_of_suffix_index = len(t)-1\n suffix_indices = []\n for s_index in range(len(s)-1, -1, -1):\n # The score is zero if we don\'t need to remove any characters\n # from t.\n if left_of_suffix_index < 0:\n return 0\n elif s[s_index] == t[left_of_suffix_index]:\n left_of_suffix_index -= 1\n suffix_indices.append(s_index)\n # Let\'s say that we delete all of the characters before the suffix.\n # The score would be:\n # left_of_suffix_index - 0 + 1 = left_of_suffix_index + 1\n # We\'ll start with that value\n result = left_of_suffix_index + 1\n # Now we want to consider forming a subsequence of s by\n # using a prefix or using a mix of a prefix and suffix.\n # The intuition behind this is that characters in the middle\n # do not matter: only the boundaries do!\n # So we loop through each potential prefix and see what\'s\n # the largest suffix we can add to it without adding the same\n # character in s twice.\n right_of_prefix_index = 0\n for s_index in range(len(s)):\n # The score is zero if we don\'t need to remove any characters\n # from t.\n if right_of_prefix_index >= len(t):\n return 0\n elif s[s_index] == t[right_of_prefix_index]:\n # Let\'s figure out the largest suffix\n # we can combine with this prefix. That\n # is the subsequence that uses the most\n # characters in s that have an index\n # greater than s_index. We can use\n # binary search since suffix_indices is\n # in decreasing order.\n if suffix_indices:\n left = 0\n right = len(suffix_indices) - 1\n while left < right:\n midpoint = ceil((left + right) / 2)\n if suffix_indices[midpoint] > s_index:\n left = midpoint\n else:\n right = midpoint - 1\n if suffix_indices[right] > s_index:\n # On the right, we remove character at index\n right_removal_index = len(t) - 1 - (right + 1)\n # On the left, we remove a character at index\n left_removal_index = right_of_prefix_index + 1\n # So the score is\n score = right_removal_index - left_removal_index + 1\n result = min(result, score)\n right_of_prefix_index += 1\n # Now we consider using only a prefix.\n result = min(result, len(t) - 1 - right_of_prefix_index + 1)\n return result\n \n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Greedy + Binary Search
|
greedy-binary-search-by-maxorgus-988j
|
\n\n# Code\npython3 []\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n \n m = len(s)\n n = len(t)\n leftmost
|
MaxOrgus
|
NORMAL
|
2024-11-01T02:58:43.627504+00:00
|
2024-11-01T02:58:43.627527+00:00
| 11 | false |
\n\n# Code\n```python3 []\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n \n m = len(s)\n n = len(t)\n leftmost = [-1]*n\n j = 0\n res = n\n for i in range(n):\n while j<m and s[j]!=t[i]:\n j += 1\n leftmost[i] = j\n if j!=m:res = min(res,n-i-1)\n j = min(j+1,m)\n rightmost = [-1]*n\n j = m-1\n for i in range(n-1,-1,-1):\n while j>=0 and s[j]!=t[i]:\n j -= 1\n rightmost[i] = j\n if j!=-1:res = min(res,i)\n j = max(j-1,-1)\n\n \n for i,l in enumerate(leftmost):\n if l == m:continue\n j = bisect.bisect_left(rightmost,l)\n r = -1\n if j < n:r = rightmost[j]\n if j < n and rightmost[j]>l:\n res = min(res,j-i-1)\n return max(res,0)\n \n```
| 0 | 0 |
['Binary Search', 'Greedy', 'Python3']
| 0 |
subsequence-with-the-minimum-score
|
subsequence-with-the-minimum-score - Java Solution
|
subsequence-with-the-minimum-score-java-h1lt1
|
\n\n# Code\njava []\nclass Solution {\n public int minimumScore(String s, String t) {\n int m = s.length(), n = t.length();\n int []left = new
|
himashusharma
|
NORMAL
|
2024-10-11T06:00:45.394586+00:00
|
2024-10-11T06:00:45.394651+00:00
| 18 | false |
\n\n# Code\n```java []\nclass Solution {\n public int minimumScore(String s, String t) {\n int m = s.length(), n = t.length();\n int []left = new int[n+2];\n int []right = new int[n+2];\n int p = 0;\n for (int i = 0; i < n; ++i) {\n while (p < m && s.charAt(p) != t.charAt(i)) p++;\n left[i+1] = p++;\n }\n left[0] = -1;\n p = m - 1;\n for (int i = n - 1; i >= 0; --i) {\n while (p >= 0 && s.charAt(p) != t.charAt(i)) p--;\n right[i+1] = p--;\n }\n right[n+1] = m;\n\n int l = 0, r = n;\n while (l <= r) {\n int x = (l + r) / 2;\n boolean flag = false;\n for (int i = 0; i + x - 1 < n; ++i) {\n if (left[i] < right[i+x+1]) \n flag = true;\n }\n if (flag) r = x - 1;\n else l = x + 1;\n }\n return l;\n }\n}\n```
| 0 | 0 |
['Two Pointers', 'String', 'Binary Search', 'Java']
| 0 |
subsequence-with-the-minimum-score
|
Sliding window | Multiple approaches | commented
|
sliding-window-multiple-approaches-comme-o9tt
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
anonymous_k
|
NORMAL
|
2024-10-03T15:14:55.924268+00:00
|
2024-10-03T15:14:55.924301+00:00
| 14 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n # Naive approach would be n * (1 << n), try all possibilities.\n # Option wise - two options remove / don\'t, for don\'t we need to find the very next index of the t[i] term we\'re looking at in s which can be done in constant time with list of dictionary or something. state (idx, lastTakenIdx) -> O(n ^ 2)\n # Non - dp O(n ^ 3) solution, we don\'t care about what all we remove we only care about left and right, we can try all possible left and rights in O(n ^ 2) and checking subsequence is O(n). We can optimize this with binary search over answer [left..right] -> [left..left+k], O(n ^ 2 * log2n)\n # We can use preprocessing to optimize this further, greedily how short of a prefix we need to make sure t[:left] is a subsequence we can calculate this in linear time, same logic for t[right:] how short of a suffix we need to make t[right:] a subsequence if there is no overlap in this prefix and suffix then we have a valid [left..right], now this can be solved with sliding window because for any [left..right] if there is an overlap in prefix and suffix the only option is to increase right to increase the window (we don\'t decrease left), and if there is no overlap we can try to increase the left to decrease the window.\n n = len(s)\n m = len(t)\n # What min idx in s we need to make t[:i + 1] a subsequence of s\n prefix = [n] * m\n # What max idx in s we need to make t[i:] a subsequence of s\n suffix = [-1] * m\n \n # calculating prefix\n i, j = 0, 0\n while i < n and j < m:\n if s[i] == t[j]:\n prefix[j] = i\n i += 1\n j += 1\n else:\n i += 1\n \n # calculating suffix\n i, j = n - 1, m - 1\n while i > -1 and j > -1:\n if s[i] == t[j]:\n suffix[j] = i\n i -= 1\n j -= 1\n else:\n i -= 1\n \n def getPrefix(idx: int) -> int:\n if idx < 0: return -1\n else: return prefix[idx]\n \n def getSuffix(idx: int) -> int:\n if idx >= m: return n\n else: return suffix[idx]\n \n ans = m\n r = 0 # excluding r [l, r), why? because 0 is also possible.\n for l in range(m):\n while r <= m and getPrefix(l - 1) >= getSuffix(r):\n r += 1\n if r <= m and getPrefix(l - 1) < getSuffix(r):\n ans = min(ans, (r - l))\n if ans == 0: return 0\n return ans\n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Easy Binary Search Solution
|
easy-binary-search-solution-by-kvivekcod-4qd8
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
kvivekcodes
|
NORMAL
|
2024-09-26T06:46:26.955687+00:00
|
2024-09-26T06:46:26.955739+00:00
| 5 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int m = s.size();\n int n = t.size();\n \n // Initialize pref and suff arrays\n vector<int> pref(n, -1), suff(n, -1);\n \n // Calculate pref - left to right subsequence matching\n int j = 0;\n for (int i = 0; i < m && j < n; ++i) {\n if (s[i] == t[j]) {\n pref[j] = i;\n ++j;\n }\n }\n \n // Calculate suff - right to left subsequence matching\n j = n - 1;\n for (int i = m - 1; i >= 0 && j >= 0; --i) {\n if (s[i] == t[j]) {\n suff[j] = i;\n --j;\n }\n }\n // for(auto it: pref) cout << it << \' \'; cout << endl;\n // for(auto it: suff) cout << it << \' \'; cout << endl;\n\n int result = n;\n if (pref[n - 1] != -1) result = 0;\n \n for(int i = 0; i < n; i++) if(pref[i] != -1) result = min(result, n - i);\n for(int i = n-1; i >= 0; i--) if(suff[i] != -1) result = min(result, i);\n for (int i = 0; i < n - 1; ++i) {\n if(pref[i] == -1) continue;\n int lo = i+1, hi = n, mid;\n while(hi-lo > 1){\n mid = (hi+lo)/2;\n if(suff[mid] <= pref[i]) lo = mid;\n else hi = mid;\n // cout << i << \' \' << mid << endl;/\n }\n result = min(result, hi - i - 1);\n }\n \n return result;\n }\n};\n\n```
| 0 | 0 |
['Two Pointers', 'String', 'Binary Search', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
python code
|
python-code-by-rakshitha0912-dvyf
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
rakshitha0912
|
NORMAL
|
2024-09-17T07:14:32.647390+00:00
|
2024-09-17T07:14:32.647417+00:00
| 7 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n m, n = len(s), len(t)\n left, right = [-1] * (n+2), [m] * (n+2)\n p = 0\n for i in range(n):\n while p < m and s[p] != t[i]: p += 1\n left[i+1] = p\n p += 1\n p = m - 1\n for i in range(n-1, -1, -1):\n while p >= 0 and s[p] != t[i]: p -= 1\n right[i+1] = p\n p -= 1\n\n def check(x): \n for i in range(n + 1 - x):\n if left[i] < right[i+x+1]:\n return True\n return False\n\n l, r = 0, n\n while l <= r:\n x = (l + r) // 2;\n if (check(x)): r = x - 1\n else: l = x + 1\n return l\n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Two Pointer Dp Prefix Suffix O(n) Time Complexity
|
two-pointer-dp-prefix-suffix-on-time-com-m35k
|
Intuition\n- We want to eliminate the characters which can not help in t string forming as subsequence.\n- But, we can also remove characters which can help \'t
|
yash559
|
NORMAL
|
2024-08-30T06:32:08.241371+00:00
|
2024-08-30T06:32:08.241401+00:00
| 11 | false |
# Intuition\n- We want to eliminate the characters which **can not help in t string forming as subsequence**.\n- But, we can also remove characters which can help \'t\' in forming substring.\n- ultimately the resultant string should be a subsequence that\'s it.\n- so, we use dp kind of approach.\n- The score formula if we observe carefully it is removal of **substring** from t.\n- By this we can say that if we know **prefix subsequence** and **suffix subsequence**, we can remove middle substring between those indices right.\n- Then out of all we will find **min substring length**.\n- Observe code for detailed explanation.\n- It\'s implementation is kind of tricky.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.length(),m = t.length();\n //This suffix array is used as a dp kind of thing\n //we are basically storing the suffix substring of \'t\'\n //which matches with \'s\'\n //subsequence means all the characters in \'t\' should be present in \'s\' right\n //so we are storing till what index that suffix of \'t\' is\n //present as subsequence\n //if not default values are -1\n vector<int> suffix(m,-1);\n int i = n-1, j = m-1;\n while(i >= 0 && j >= 0) {\n while(i >= 0 && s[i] != t[j]) {\n i--;\n }\n if(i < 0) break;\n suffix[j] = i;\n j--;\n i--;\n }\n //after constructing the suffix array let\'s construct the prefix array in same manner.\n i = 0,j = 0;\n vector<int> prefix(m,-1);\n while(i < n && j < m) {\n while(i < n && s[i] != t[j]) {\n i++;\n }\n if(i >= n) break;\n prefix[j] = i;\n i++;\n j++;\n }\n //now let\'s jump to main code\n //we have in our hands prefix and suffix arrays which basically\n //represents subsequence index in \'s\'\n //now let\'s take two pointers to iterate over respective arrays\n int suf_ptr = 0,pref_ptr = 0;\n \n //now we know that suffix array initially contains \'-1\' as default means for that index in \'t\' we can form subsequence\n while(suf_ptr < m && suffix[suf_ptr] == -1) suf_ptr++;\n \n //we took ans initially as starting index in suffix array which is not -1 becoz one possible result is we can delete all characters in \'t\' before suf_ptr right so that we can form subsequence\n int ans = suf_ptr;\n\n //if no \'-1\' is present then suf_ptr will point to starting index right, this means that whole string \'t\' is already a subsequence of \'s\' so return 0\n if(suf_ptr == 0) return 0;\n \n //we need to get ans from all possible combinations of both prefix and suffix\n //but prefix[pref_ptr] < suffix[suf_ptr] becoz we are actually deleting a substring between these both indices so that we can form a \'t\' as a subsequence of \'s\' so prefix should be less than suffix\n while(pref_ptr < m && prefix[pref_ptr] != -1) {\n //move suf_ptr if above mentioned condition is violated\n while(suf_ptr < m && prefix[pref_ptr] >= suffix[suf_ptr]) {\n suf_ptr++;\n }\n //update ans by below formula of removing between range substring\n ans = min(ans, suf_ptr - pref_ptr - 1);\n pref_ptr++;\n }\n //we might get another doubt that we are not exiting even when suf_ptr reaches m we keeping it as constant not incrementing it observe above\n //why?\n //becoz we can only prefix and ignore suffix right\n //so we also consider t.size as a index check that also\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
✅Two Pointer+Binary Search+Prefix/suffix Easy Solution✅
|
two-pointerbinary-searchprefixsuffix-eas-cckz
|
\n\n# Code\n\nclass Solution {\npublic:\n int find(int leftid, int left, vector<int>& suff) {\n int n = suff.size();\n int i = leftid, j = n -
|
Jayesh_06
|
NORMAL
|
2024-08-01T07:27:06.917987+00:00
|
2024-08-01T07:27:06.918024+00:00
| 1 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n int find(int leftid, int left, vector<int>& suff) {\n int n = suff.size();\n int i = leftid, j = n - 1, ans = -1;\n while (i <= j) {\n int mid = (i + j) / 2;\n if (suff[mid] > left) {\n ans = mid;\n j = mid - 1;\n } else {\n i = mid + 1;\n }\n }\n return ans;\n }\n int minimumScore(string s, string t) {\n int n = s.size(), m = t.size();\n vector<int> pre(m, -1), suff(m, -1);\n int i = 0, j = 0;\n while (i < n && j < m) {\n if (s[i] == t[j]) {\n pre[j] = i;\n j++;\n }\n i++;\n }\n i = n - 1, j = m - 1;\n while (i >= 0 && j >= 0) {\n if (s[i] == t[j]) {\n suff[j] = i;\n j--;\n }\n i--;\n }\n\n int mini = m;\n for (int i = 0; i < m; i++) {\n if (pre[i] != -1) {\n int right = find(i + 1, pre[i], suff);\n if (right != -1) {\n mini = min(mini, right - i - 1);\n }\n } else {\n mini = min(mini, m - i);\n break;\n }\n }\n for (int i = m - 1; i >= 0; i--) {\n if (suff[i] == -1) {\n mini = min(mini, i + 1);\n break;\n }\n }\n if (m == 1 && pre[0] != -1) {\n mini = min(mini, 0);\n }\n return mini;\n }\n};\n```
| 0 | 0 |
['Two Pointers', 'String', 'Binary Search', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
c++ solution
|
c-solution-by-luxmichauhan-n0rr
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Luxmichauhan
|
NORMAL
|
2024-03-16T14:41:56.731674+00:00
|
2024-03-16T14:41:56.731701+00:00
| 1 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool find(string &s,string &t,int mid)\n {\n int n=s.size();\n int m=t.size();\n vector<int>left(m,n),right(m,-1);\n for(int i=0,j=0;j<m&&i<n;i++)\n {\n if(s[i]==t[j])\n {\n left[j]=i;\n j++;\n }\n }\n for(int i=n-1,j=m-1;j>=0&&i>=0;i--)\n {\n if(s[i]==t[j])\n {\n right[j]=i;\n j--;\n }\n }\n if(left[m-1]!=n)\n {\n return true;\n }\n if(right[mid]!=-1||left[m-mid-1]!=n)\n {\n return true;\n }\n for(int i=1;i+mid<m;i++)\n {\n if(left[i-1]<right[i+mid])\n {\n return true;\n }\n }\n return false;\n }\n int minimumScore(string s, string t) {\n int l=0;\n int r=t.size()-1;\n int ans=t.size();\n while(l<=r)\n {\n int mid=(l+r)/2;\n if(find(s,t,mid))\n {\n ans=mid;\n r=mid-1;\n }\n else\n {\n l=mid+1;\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
Clean n short 10 lines C++ Code || Explaination
|
clean-n-short-10-lines-c-code-explainati-6h7q
|
Intuition\n * As you want to minimize , right-left+1. \n * To ensure this condition , we need to minimize the right and maximize the left as much as possible.
|
satyam_9911
|
NORMAL
|
2023-11-23T09:39:56.833732+00:00
|
2023-11-23T09:39:56.833755+00:00
| 22 | false |
# Intuition\n * As you want to minimize , `right-left+1`. \n * To ensure this condition , we need to minimize the `right` and maximize the `left` as much as possible. \n * It simply means , we will always choose string from start , as well as end for the final common subsequence , and we will delete all the elements between them. ```(ans = right - left + 1)```\n * ```xxx......xxxx``` we will choose all characters from the start to a particular `left` , and we will choose all chracters from the end to a particular `right`. \n \n * ```ans = min(ans , right-left+1)``` for all possible ```left``` and ```right```\n\n\n# Code\n```\nclass Solution {\npublic: \n \n int minimumScore(string s, string t) {\n \n int n = s.length() , m = t.length(); \n vector<int> pre(n,0) , suf(n,0); \n\n for(int i = 0 , j = 0 ; i<n and j<m ; i++){\n if(s[i]==t[j]) pre[i]++ , j++; \n if(i) pre[i]+=pre[i-1]; \n }\n \n for(int i = n-1 , j = m-1 ; i>=0 and j>=0 ; i--){\n if(s[i]==t[j]) suf[i]++ , j--; \n if(i+1<n) suf[i]+=suf[i+1]; \n }\n \n int ans = m;\n\n for(int i = 0 ; i < n ; i++){ \n if(i==0) ans = min(ans , m-suf[0]); \n else if(i==n-1) ans = min(ans , m-pre[n-1]); \n else ans = min(ans , m-pre[i]-suf[i+1]);\n } \n\n return max(0 , ans); \n }\n};\n```
| 0 | 0 |
['Two Pointers', 'Binary Search', 'Greedy', 'Prefix Sum', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
Greedy | Largest Prefix and suffix | 11ms
|
greedy-largest-prefix-and-suffix-11ms-by-o4sj
|
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n\nclass Solution {\n public int minimumScore(String s, String t) {\n int[] grea
|
saket81322
|
NORMAL
|
2023-09-01T06:12:29.755605+00:00
|
2023-09-01T06:12:29.755630+00:00
| 33 | false |
# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public int minimumScore(String s, String t) {\n int[] greatestUnmatchedLeft = new int[s.length()];\n\n int minScore = t.length();\n for (int i = 0; i < s.length(); i++) {\n if (i > 0 && greatestUnmatchedLeft[i - 1] == t.length()) {\n return 0;\n }\n\n greatestUnmatchedLeft[i] = (i > 0 ? greatestUnmatchedLeft[i - 1] : 0)\n + (s.charAt(i) == t.charAt(i > 0 ? greatestUnmatchedLeft[i - 1] : 0) ? 1 : 0);\n }\n\n if (greatestUnmatchedLeft[s.length() - 1] == t.length()) {\n return 0;\n }\n\n int smallestUnmatchedRight = t.length() - 1;\n minScore = Math.min(minScore, t.length() - greatestUnmatchedLeft[s.length() - 1]);\n for (int j = s.length() - 1; j >= 0; j--) {\n if (s.charAt(j) == t.charAt(smallestUnmatchedRight)) {\n smallestUnmatchedRight--;\n if (smallestUnmatchedRight < 0) {\n return 0;\n }\n }\n\n if (j > 0 && greatestUnmatchedLeft[j - 1] > smallestUnmatchedRight) {\n return 0;\n }\n\n minScore = Math.min(minScore, smallestUnmatchedRight - (j > 0 ? greatestUnmatchedLeft[j - 1] : 0) + 1);\n }\n\n return minScore;\n }\n}\n```
| 0 | 0 |
['Array', 'Greedy', 'Java']
| 0 |
subsequence-with-the-minimum-score
|
simple binary search using prefix and suffix arrays O(nlogn) Python 3
|
simple-binary-search-using-prefix-and-su-3bg3
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
throwawayleetcoder19843
|
NORMAL
|
2023-08-28T00:22:15.092765+00:00
|
2023-08-28T00:23:41.788041+00:00
| 18 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import defaultdict\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n s = \'0\'+s+\'0\'\n t = \'0\'+s+\'0\'\n prefix_arr = [-1 for _ in range(len(t))]\n suffix_arr = [-1 for _ in range(len(t))]\n \n cur_ind = 0\n for i in range(len(s)):\n if cur_ind >= len(t):\n break\n if s[i]==t[cur_ind]:\n prefix_arr[cur_ind] = i\n cur_ind += 1\n\n cur_ind = len(suffix_arr)-1\n for i in reversed(range(len(s))):\n if cur_ind < 0:\n break\n if s[i] == t[cur_ind]:\n suffix_arr[cur_ind] = i\n cur_ind -= 1\n min_score = len(t)\n for i in range(len(prefix_arr)):\n if prefix_arr[i] == -1:\n break\n low = i+1\n high = len(suffix_arr)\n while low < high:\n mid = int((low+high)/2)\n if suffix_arr[mid] == -1 or suffix_arr[mid]<=prefix_arr[i]:\n low = mid+1\n else:\n min_score = min(min_score, mid-i-1)\n high = mid \n return min_score\n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Using binary search and prefix - suffix
|
using-binary-search-and-prefix-suffix-by-wish
|
\n\n# Code\n\nclass Solution {\npublic:\n\n int util(vector<int>&v, int prev) {\n int l = 0, r = v.size() - 1, id = -1;\n while(l <= r) {\n
|
modernsaint
|
NORMAL
|
2023-08-03T21:16:58.405223+00:00
|
2023-08-03T21:16:58.405254+00:00
| 17 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n\n int util(vector<int>&v, int prev) {\n int l = 0, r = v.size() - 1, id = -1;\n while(l <= r) {\n int mid = (l + r)/2;\n if(v[mid] > prev) {\n id = v[mid];\n r = mid - 1;\n } else {\n l = mid + 1;\n }\n }\n return id;\n }\n\n int util2(vector<int>&v, int prev) {\n int l = 0, r = v.size() - 1, id = -1;\n while(l <= r) {\n int mid = (l + r)/2;\n if(v[mid] < prev) {\n id = v[mid];\n l = mid + 1;\n } else {\n r = mid - 1;\n }\n }\n return id;\n }\n\n bool check(int x, vector<int>& pre, vector<int>& suff) {\n for(int i = 0 ; i <= pre.size() - x ; i++) {\n if(i > 0 ) {\n if(i + x < pre.size()) {\n if(pre[i - 1] >= 0 && suff[i + x] >= 0 && pre[i - 1] < suff[i + x])\n return true;\n }else {\n if(pre[i - 1] >= 0)\n return true;\n }\n }else if(i + x < suff.size() && suff[i + x] >= 0)\n return true;\n }\n return false;\n }\n\n int minimumScore(string s, string t) {\n int n = s.length();\n map<int,int>mp;\n vector<vector<int>>v(26);\n for(int i = 0 ; i < n ; i++)\n v[s[i] - \'a\'].push_back(i);\n int l = t.length(), r = -1, prev = -1;\n vector<int>pre(l), suff(l);\n for(int i = 0 ; i < t.length() ; i++) {\n int x = util(v[t[i] - \'a\'],prev);\n if(x == -1) {\n pre[i] = -1;\n break;\n } else{\n pre[i] = x;\n prev = x;\n }\n }\n prev = n;\n for(int i = t.length() - 1 ; i >= 0 ; i--) {\n int x = util2(v[t[i] - \'a\'],prev);\n if(x == -1) {\n suff[i] = -1;\n break;\n } else {\n suff[i] = x;\n prev = x;\n }\n }\n for(int i = suff.size() - 2 ; i >= 0 ; i--) {\n if(suff[i + 1] == -1)\n suff[i] = -1;\n }\n for(int i = 1 ; i < pre.size() ; i++) {\n if(pre[i - 1] == -1)\n pre[i] = -1;\n }\n l = 0, r = t.length();\n int id = r;\n while(l <= r) {\n int mid = (l + r)/2;\n if(check(mid,pre,suff)) {\n id = mid;\n r = mid - 1;\n } else {\n l = mid + 1;\n }\n }\n return id;\n }\n};\n```
| 0 | 0 |
['Binary Search', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
c++
|
c-by-ryan_xgh-wt1i
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Ryan_xgh
|
NORMAL
|
2023-07-09T06:41:15.741755+00:00
|
2023-07-09T06:41:15.741785+00:00
| 9 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int suffix[s.size()+1];\n suffix[s.size()]=t.size();\n for(int i = s.size()-1, j = t.size()-1;i>=0;i--){\n if(j>=0&&s[i]==t[j]){\n j--;\n }\n suffix[i]=j+1;\n }\n if(suffix[0]==0)\n return 0;\n int ans = suffix[0];\n for(int i=0, j=0;i<s.size();i++){\n if(s[i]==t[j]){\n j++;\n }\n ans = min(ans, suffix[i+1]-j);\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
[CLEAN] O(NlogN) to O(N)
|
clean-onlogn-to-on-by-crimsonx-mqby
|
O(NlogN)\n\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int sl=s.size();\n int tl=t.size();\n vector<int> left(
|
crimsonX
|
NORMAL
|
2023-06-28T18:54:18.875159+00:00
|
2023-06-28T18:54:18.875188+00:00
| 15 | false |
O(NlogN)\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int sl=s.size();\n int tl=t.size();\n vector<int> left(tl,sl), right(tl,-1);\n //s to unordered_map<c,<idx>>\n unordered_map<char,vector<int>> m;\n for(int x=0;x<sl;x++){\n m[s[x]].push_back(x);\n }\n int bl=tl,br=tl;\n //fill left\n //O(NlogN)\n int temp=-1;\n for(int x=0;x<tl;x++){\n vector<int> &v=m[t[x]];\n int idx=upper_bound(v.begin(),v.end(),temp)-v.begin();\n if(idx==v.size()){\n bl=x;\n break;}\n temp=v[idx];\n left[x]=temp;\n }\n //fill right\n //O(NlogN)\n temp=sl;\n for(int x=tl-1;x>=0;x--){\n vector<int> &v=m[t[x]];\n int idx=-1*(upper_bound(v.rbegin(),v.rend(),temp,greater<int>())\n -v.rend())-1;\n if(idx==-1){\n br=(tl-1)-x;\n break;}\n temp=v[idx];\n right[x]=temp;\n }\n //get result\n //O(NlogN)\n int res=tl-max(bl,br);\n if(res==0)\n return 0;\n for(int x=0;x<tl;x++){\n int a=left[x];\n if(a==sl)\n break;\n int idx=upper_bound(right.begin(),right.end(),a)-right.begin();\n if(idx==tl)\n break;\n res=min(idx-x-1,res);\n }\n return res;\n }\n};\n```\n\nO(N)\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int sl=s.size();\n int tl=t.size();\n vector<int> left(tl,sl), right(tl,-1);\n \n int bl=0,br=0;\n //fill left\n //O(N)\n int temp=0;\n for(int x=0;x<sl;x++){\n if(s[x]==t[temp]){\n left[temp]=x;\n temp++;\n bl++;\n }\n if(temp==tl)\n break;\n }\n //fill right\n //O(N)\n temp=tl-1;\n for(int x=sl-1;x>=0;x--){\n if(s[x]==t[temp]){\n right[temp]=x;\n temp--;\n br++;\n }\n if(temp<0)\n break;\n }\n //get result\n //O(N)\n int res=tl-max(bl,br);\n if(res==0)\n return 0;\n temp=0;\n for(int x=0;x<tl;x++){\n if(left[x]==sl)\n break;\n while(right[temp]<=left[x]){\n temp++;\n if(temp==tl)\n return res;\n }\n res=min(temp-x-1,res);\n }\n return res;\n }\n};\n```
| 0 | 0 |
['Two Pointers', 'Binary Search', 'Greedy', 'C']
| 0 |
subsequence-with-the-minimum-score
|
Left and Right O(n) -- Python version
|
left-and-right-on-python-version-by-yfm6-2j3k
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nLeft pass once for each index i in t, find the smallest index j in s such
|
yfm666
|
NORMAL
|
2023-05-29T17:16:40.837709+00:00
|
2023-05-29T17:16:40.837748+00:00
| 38 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nLeft pass once for each index i in t, find the smallest index j in s such that t[: i+1] is a subsequence of s[: j+1]. Store the answer in an array (leftArr).\nIf such j does not exist for some i, then by default leftArr[i] = -1.\n\nSimilarly, right pass once for each i in t, find the largest index j in s such that t[i: ] is a subsequence of s[j: ]. Store the answer in an array (rightArr).\nIf such j does not exist for some i, then by default rightArr[i] = -1.\n\nFinally, pass t from right to left, for each index $right$ satisfying $rightArr[right]!=-1$, look for the largest index $left$ of t, such that $leftArr[left]!=-1$ and $leftArr[left] < rightArr[right]$.\nAbove can guarantee that t[ :left] + t[right: ] is a subsequence of s. \nWe simply need to find the $(left, right)$ pair which minimizes (right-1-left).\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n m = len(s)\n n = len(t)\n rightArr = [-1 for _ in range(n)]\n leftArr = [-1 for _ in range(n)]\n\n j = 0 \n for i in range(n):\n if j >= m:\n break\n while j < m and s[j] != t[i]:\n j+=1\n if j < m:\n leftArr[i] = j\n j += 1\n \n j = m-1\n for i in reversed(range(n)):\n if j < 0:\n break\n while j >= 0 and s[j] != t[i]:\n j -= 1\n if j >= 0:\n rightArr[i] = j\n j -= 1\n\n right = n\n left = -1\n for i in range(n):\n if leftArr[i] == -1:\n break\n left = i\n res = right-1-left\n right = n-1\n while right >= 0 and (rightArr[right]!= -1):\n boundary = rightArr[right]\n left = min(left, right-1)\n while left>=0 and leftArr[left] >= boundary:\n left -= 1\n res = min(res, right-1-left)\n right -= 1\n return res\n\n \n\n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
C++ || prefix & suffix || O(n)
|
c-prefix-suffix-on-by-himanshuinsta1818-b8iy
|
Code\n\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.size();\n int m = t.size();\n vector<int> f(n,0),
|
himanshuinsta1818
|
NORMAL
|
2023-03-22T17:39:47.171901+00:00
|
2023-03-22T17:39:47.171954+00:00
| 31 | false |
# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.size();\n int m = t.size();\n vector<int> f(n,0),b(n,0);\n int j=0;\n for(int i=0;i<n;i++){\n if(j<m && s[i] == t[j]){\n j++;\n }\n f[i]=j;\n }\n j=m-1;\n for(int i=n-1;i>=0;i--){\n if(j>=0 && s[i] == t[j]){\n j--;\n }\n b[i]=m-j-1;\n }\n int ans = min(m-f[n-1],m-b[0]);\n for(int i=1;i<n;i++){\n ans = min(ans,m-f[i-1]-b[i]);\n }\n return max(ans,0);\n }\n};\n```
| 0 | 0 |
['Suffix Array', 'Prefix Sum', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
C++ solution!
|
c-solution-by-lcq_dev-w3hw
|
Intuition\n\n\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n vector<int> left(t.size(), 0);\n vector<int> right(t.size()
|
lcq_dev
|
NORMAL
|
2023-03-06T07:08:26.155428+00:00
|
2023-03-06T07:08:26.155487+00:00
| 27 | false |
# Intuition\n\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n vector<int> left(t.size(), 0);\n vector<int> right(t.size(), 0);\n\n int res = t.size();\n int j = 0;\n int n = t.size();\n for(int i=0;i<s.size() && j<left.size();i++) {\n if(t[j] == s[i]) {\n left[j] = i;\n res = min(res, n-1 - (j+1) + 1);\n j++;\n }\n }\n\n while(j < t.size()) {\n left[j] = INT_MAX;\n j++;\n }\n\n j = t.size() - 1;\n for(int i=s.size()-1;i>=0 && j>=0;i--) {\n if(s[i] == t[j]) {\n right[j] = i;\n res = min(res, j-1+1);\n j--;\n }\n }\n\n while(j>=0) {\n right[j] = -1;\n j--;\n }\n\n\n if(right[0]!=-1 || left[left.size()-1] != INT_MAX) {\n return 0;\n }\n \n j = 1;\n for(int i =0;i<t.size();i++) {\n if(left[i] == INT_MAX) {\n break;\n }\n int left_index = left[i];\n j = max(j, i+1);\n while(j<right.size() && left_index>=right[j]) {\n j++;\n }\n\n res = min(res, j-1 - (i+1) + 1);\n \n }\n\n return res;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
great explanation with intution
|
great-explanation-with-intution-by-godzi-0cqq
|
Code\n\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n // check if t can become a subsequence of s after some removal\n /
|
godziy
|
NORMAL
|
2023-03-04T01:20:24.480036+00:00
|
2023-03-04T01:20:24.480068+00:00
| 53 | false |
# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n // check if t can become a subsequence of s after some removal\n // only right and left is required so no need to consider remaining ones \n // in between\n // check for subsequence - if prefix does not overlap suffix\n int n=s.length(), m=t.length();\n vector<int> pref(m, n), suff(m, -1);\n int p1=0, p2=0;\n while(p2<m) // filling the prefix array\n {\n if(p1==n)\n break;\n if(s[p1] == t[p2])\n {\n pref[p2]=p1;\n p2++;\n }\n p1++;\n }\n p1=n-1, p2=m-1;\n while(p2>=0) // filling the suffix array\n {\n if(p1==-1)\n break;\n if(s[p1] == t[p2])\n {\n suff[p2]=p1;\n p2--;\n }\n p1--;\n }\n // binary search to find the left and right pointer that has to\n // be removed\n int ans=m; // since maximum answer is the length of t\n for(int l=0;l<m;l++) // fixing the left pointer\n {\n if(l>0 and pref[l-1]==n) // no need to check if we find a character we cannot form a subsequence with\n break;\n int ele=l==0?-1:pref[l-1]; // take the first valid suffix if left pointer is at index 0\n int r=upper_bound(suff.begin(), suff.end(), ele)-suff.begin(); // find the first element with value greater than that of pref[l-1]\n if(l==r) // it means whole string is subsequence of s\n return 0;\n ans=min(ans, r-l);\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Two Pointers', 'Binary Search', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
what other solutions are missing
|
what-other-solutions-are-missing-by-08ab-z94u
|
Intuition\nScore depends upon the left most index and right most index deleted.. so it doesn\'t make any difference if you drop all the characters b/w left most
|
08absahil
|
NORMAL
|
2023-03-02T10:43:45.842457+00:00
|
2023-03-02T10:43:45.842492+00:00
| 12 | false |
# Intuition\nScore depends upon the left most index and right most index deleted.. so it doesn\'t make any difference if you drop all the characters b/w left most index and right most index that you are going to delete(score stays the same).. why not delete them for simplicity..\nNow the problem just reduces to the prefix and suffix..\n\n\n\n# Approach\nyou can check others solution now, I just wrote what\'s missing from them.\n\n
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
Python Solution Using Binary Search
|
python-solution-using-binary-search-by-n-b1e1
|
Code\n\nfrom bisect import bisect_right,bisect_left\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n d=[[] for _ in range(26)]\n
|
ng2203
|
NORMAL
|
2023-02-28T05:29:35.017570+00:00
|
2023-02-28T05:29:35.017617+00:00
| 50 | false |
# Code\n```\nfrom bisect import bisect_right,bisect_left\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n d=[[] for _ in range(26)]\n for i in range(len(s)):\n d[ord(s[i])-97].append(i)\n j=len(s)\n dp=[-1 for _ in range(len(t))]\n for i in range(len(t)-1,-1,-1):\n arr=d[ord(t[i])-97]\n tem=bisect_left(arr,j)\n if(tem==0):\n break\n else:\n dp[i]=arr[tem-1]\n j=dp[i]\n else:\n return 0\n j=i\n i=0\n r=-1\n ans=len(t)\n while(i<len(t)):\n arr=d[ord(t[i])-97]\n tem=bisect_right(arr,r)\n if(tem>=len(arr)):\n ans=min(ans,j-i+1)\n break\n tem=arr[tem]\n if(j+1>=len(t) or dp[j+1]>tem):\n r=tem\n i+=1\n else:\n ans=min(ans,j-i+1)\n while(j<len(t)-1 and ( dp[j+1]<=tem)):\n j+=1\n r=tem\n i+=1\n return ans\n\n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
2 pointer LEFT - RIGHT
|
2-pointer-left-right-by-shivral-qdq3
|
\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nlongest increasing prefix+suffix\n Describe your approach to solving the problem.
|
shivral
|
NORMAL
|
2023-02-25T10:17:08.635193+00:00
|
2023-02-25T10:17:08.635240+00:00
| 56 | false |
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nlongest increasing prefix+suffix\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom copy import deepcopy\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n left=[-1]*len(t)\n right=[-1]*len(t)\n ind=defaultdict(deque)\n ind2=defaultdict(deque)\n for i in range(len(s)):\n ind[s[i]].append(i)\n ind2[s[i]].append(i)\n for i in range(len(t)):\n if ind[t[i]]:\n while i and ind[t[i]] and ind[t[i]][0]<left[i-1]:\n ind[t[i]].popleft()\n if ind[t[i]]:\n left[i]=ind[t[i]].popleft()\n ind=ind2\n ans=len(t)\n cnt=0\n for i in range(len(t)-1,-1,-1):\n cnt+=1\n if ind2[t[i]]:\n while i+1<len(t) and ind[t[i]] and ind[t[i]][-1]>right[i+1]:\n ind[t[i]].pop()\n if ind[t[i]]:\n right[i]=ind[t[i]].pop()\n ans=min(ans,len(t)-cnt)\n if i+1<len(t) and right[i+1]<right[i]:\n right[i]=-1\n break\n hi=len(left)-1\n for i in range(len(left)):\n if left[i]==-1:\n break\n l=i\n while right[hi]<left[l]:\n if hi+1<len(left):\n hi+=1\n else:\n break\n while hi>l and right[hi]!=-1 and right[hi]>left[l]:\n th=hi-1\n hi=th\n ans=min(ans,hi-l)\n \n return max(ans,0)\n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Java Solution using Binary Search
|
java-solution-using-binary-search-by-ris-3w0h
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
rishabhk02
|
NORMAL
|
2023-02-22T03:44:21.628646+00:00
|
2023-02-22T03:44:21.628809+00:00
| 92 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumScore(String s, String t) {\n int n=s.length(); int m=t.length();\n ArrayList<Integer> list = new ArrayList<>();\n int sIdx=n-1;\n for(int i=m-1; i>=0; i--){\n while(sIdx>=0 && s.charAt(sIdx)!=t.charAt(i)) sIdx--;\n if(sIdx==-1) break;\n list.add(sIdx);\n sIdx--;\n }\n Collections.reverse(list);\n int ans = m-list.size();\n if(ans==0) return 0;\n \n sIdx=0;\n for(int i=0; i<m; i++){\n while(sIdx<n && s.charAt(sIdx)!=t.charAt(i)) sIdx++; \n int idx = upperBound(list,sIdx); \n if(idx==list.size()){\n if(sIdx==n) break;\n ans=Math.min(ans,m-i-1);\n sIdx++;\n continue;\n }\n int lastIncluded = list.size()-idx;\n ans = Math.min(ans,m-lastIncluded-i-1);\n sIdx++;\n }\n return ans; \n }\n\n int upperBound(ArrayList<Integer> list, int val){\n int low=0; int high=list.size()-1;\n int ans=list.size();\n while(low<=high){\n int mid=(low+high)/2;\n if(list.get(mid)>val){\n ans=mid;\n high=mid-1;\n }else low=mid+1; \n }\n return ans;\n }\n}\n\n\n// "abecdebe"\n// "eaebceae"\n```
| 0 | 0 |
['String', 'Binary Search', 'Java']
| 0 |
subsequence-with-the-minimum-score
|
C++ commented code (Find longest suffix secured for each prefix)
|
c-commented-code-find-longest-suffix-sec-ztnk
|
Complexity\n- Time complexity: O(N log N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(M)\n Add your space complexity here, e.g. O(n) \n
|
Sachin-Vinod
|
NORMAL
|
2023-02-18T07:39:02.058057+00:00
|
2023-02-18T07:39:02.058088+00:00
| 34 | false |
# Complexity\n- Time complexity: $$O(N log N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(M)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n=s.length(), m=t.length();\n\n vector<int> l(m,-1),r(m,-1);\n\n int j=0;\n //longes prefix available\n for(int i=0;i<n;i++){\n if(j>=m){\n break;\n }\n if(s[i]==t[j]){\n l[j]=i;\n j++;\n }\n }\n\n j=m-1;\n //longest suffix available\n for(int i=n-1;i>=0;i--){\n if(j<0){\n break;\n }\n if(s[i]==t[j]){\n r[j]=i;\n j--;\n }\n }\n\n int ans=m;\n //ans if suffix and prefix has to removed \n for (int i = 0; i < m; ++i) { \n if (l[i] != -1) ans = min(ans, m-i-1); \n if (r[i] != -1) ans = min(ans, i); \n }\n\n //does\'nt found any suffix return ans with respect to logest prefix found\n if (r[m-1] == -1) return ans; \n\n for(int i=0;i<m-1;i++){\n\n //calculate longest suffix we can able to secure with respect to current index i prefix \n if(l[i]!=-1){\n if(l[i]>=r[m-1]){\n break;\n }\n int lo=i+1,hi=m-1;\n int temp;\n while(lo<=hi){\n int mi=lo+(hi-lo)/2;\n if(l[i]>=r[mi]){\n lo=mi+1;\n }\n else{\n temp=mi;\n hi=mi-1;\n }\n }\n ans=min(ans,temp-i-1);\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
two pass String s, greedy
|
two-pass-string-s-greedy-by-leegooo-bebv
|
Intuition\n Describe your first thoughts on how to solve this problem. \nfor every letter in s, we can either use it to match prefix or suffix in t.\n\n(No need
|
leegooo
|
NORMAL
|
2023-02-16T22:35:33.874473+00:00
|
2023-02-16T22:53:13.318977+00:00
| 47 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nfor every letter in s, we can either use it to match prefix or suffix in t.\n\n(No need to worry about overlap of prefix and suffix in t, as long as every letter in s match either prefix or suffix, that won\'t cause problem)\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1.go left to right in s , try match as many prefix of t as we can, for every character in s, \nwe mark if it is used to match t prefix. \n\nWhat left in t is need to be remove.\n\n2.then go right to left in s, if a letter is used for prefix , now we no longer can use it for prefix becasue we are building suffix now, so we delete one character in prefix which means we need to increase the letter we remove(cur++). \nif it match t suffix, we add one more letter to suffix and we decrase the letter we remove.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimumScore(String s, String t) {\n boolean[] record = new boolean[s.length()];\n int ti = 0;\n for (int i = 0; i < s.length() && ti < t.length(); i++) {\n if (s.charAt(i) == t.charAt(ti)) {\n record[i] = true;\n ti++;\n }\n }\n int ans = t.length() - ti;\n if (ti == t.length()) return ans;\n int cur = ans;\n ti = t.length() - 1;\n for (int i = s.length() - 1; i >= 0 && ti >= 0; i--) {\n if (record[i]) cur++;\n if (s.charAt(i) == t.charAt(ti)) {\n cur--;\n ti--;\n }\n ans = Math.min(ans, cur);\n }\n return ans;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
subsequence-with-the-minimum-score
|
15 lines | C++ | O(n)
|
15-lines-c-on-by-ac121102-07lx
|
````\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.size();\n int m = t.size();\n vector pre_mch(m);\n
|
ac121102
|
NORMAL
|
2023-02-16T21:09:26.060714+00:00
|
2023-02-16T21:09:26.060763+00:00
| 28 | false |
````\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.size();\n int m = t.size();\n vector<int> pre_mch(m);\n vector<int> suf_mch(n+1,2*m+1);\n \n int cur = 0;\n for (int i=0; i<m; i++){\n while (cur < n && s[cur] != t[i]) \n cur++;\n pre_mch[i] = cur++;\n }\n \n cur = n-1;\n for (int i=m-1; i>=0; i--){\n while (cur >= 0 && s[cur] != t[i]){ \n suf_mch[cur--] = i+1;}\n if(cur>=0) suf_mch[cur--] = i;\n }\n\n int ans = min(m,suf_mch[0]);\n for (int i=0; i<m; i++){\n if (pre_mch[i] < n) ans = min(ans, m-i-1);\n ans = min(ans, max(0, suf_mch[min(n,pre_mch[i]+1)]-i-1));\n }\n return ans;\n }\n};
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
Simple Binary Search and Prefix Solution || C++
|
simple-binary-search-and-prefix-solution-px5u
|
Approach\n Describe your approach to solving the problem. \nWe need to find longest prefix subseq in s and also suffix subseq in s. And we now have to cross che
|
rkkumar421
|
NORMAL
|
2023-02-15T09:20:56.393225+00:00
|
2023-02-15T09:20:56.393268+00:00
| 38 | false |
# Approach\n<!-- Describe your approach to solving the problem. -->\nWe need to find longest prefix subseq in s and also suffix subseq in s. And we now have to cross check for every value if we have non overlapping substring of t in both prefix and suffix then we will see right and left according to prefix and suffix and compare it with our answer .\n# Complexity\n- Time complexity: O(NLogN)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int st = t.length();\n vector<int> r, l;\n for(int i=0, j = 0;i<t.length() && j < s.length();j++){\n if(s[j] == t[i]){ l.push_back(j); i++;}\n }\n for(int i=t.length()-1, j = s.length()-1;i>=0 && j>=0;j--){\n if(s[j] == t[i]){ r.push_back(j); i--;}\n }\n reverse(r.begin(),r.end());\n int ans = t.length();\n // if we do not have any prefix subseq then we have left = 0 and right equal to t len - rsize\n // see cdeaaaa , bzxcaaaa\n // aaaa is common so r size is 5 right here is 3 \n // so 8 - 4 = 4;\n int l0 = t.length() - r.size(); // if left size is 0\n int r0 = t.length() - l.size(); // if right size is 0\n // similarly\n // aaaabzxc\n // aaaa is common so l size is 4 and left is 4 and right is t.len - 1\n if(l.size() == t.length() || r.size() == t.length()) return 0;\n // if we have both side s = acdfgaaaa , t = cfghghgaaaa\n // l = cfg , r = gaaaa , here we can see we have used same g 2 times\n ans = min({ans,l0,r0});\n for(int i=0;i<l.size();i++){\n // Now we have to see for this index\n int ind = upper_bound(r.begin(),r.end(),l[i]) - r.begin();\n ind = r.size()-ind; // we got right side longest length\n ind = t.length()-ind-1; // now we need right value so we need to subtract t len to ind\n ans = min(ans,ind - i);\n }\n return ans;\n }\n};\n```
| 0 | 0 |
['Binary Search', 'Prefix Sum', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
C++, right left, 3 loops, O(n)
|
c-right-left-3-loops-on-by-bohao2014-cw4q
|
got idea from votrubac (https://leetcode.com/problems/subsequence-with-the-minimum-score/discuss/3174041/Right-and-Left-O(n)) and qeetcode sol in weekly contest
|
bohao2014
|
NORMAL
|
2023-02-15T07:08:30.438104+00:00
|
2023-02-15T07:08:30.438143+00:00
| 26 | false |
got idea from votrubac (https://leetcode.com/problems/subsequence-with-the-minimum-score/discuss/3174041/Right-and-Left-O(n)) and qeetcode sol in weekly contest 332 (https://leetcode.com/qeetcode/).\nIt can be done in only two for loops with O(n) time complexity but use three here because it is easier to understand.\n\nIn the problem hint, dp array based on t is recommended. However, it is complicated when determine whether prefix and surfix overlap in s. Therefore, dp array based on s is chosen here.\n\nuse two array left[ns] and right[ns] with size of s string.\nleft[i] stands for max prefix length of t that is a subsequence of substring from s[0] to s[i] (including s[i]);\nright[i] stands for max surfix length of t that is a subsequence of substring from s[i] to s[ns-1] (including s[i]).\n\nthe minimum score is initialized as min(left[ns-1], right[0]), which is the prefix only and surfix only case.\nminimum score = min of nt-left[i]-right[i+1].\nif the minimum value is smaller than 0, return 0.\n \n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int ns=s.size(), nt=t.size();\n vector<int> left(ns), right(ns);\n for(int i=0, j=0; i<ns; i++) {\n if(j<nt && s[i]==t[j])\n j++;\n left[i]=j;\n }\n for(int i=ns-1, j=0; i>=0; i--) {\n if(j<nt && s[i]==t[nt-1-j])\n j++;\n right[i]=j;\n }\n int res=min(nt-left[ns-1], nt-right[0]);\n for(int i=0; i<ns-1; i++) {\n res=min(res, nt-left[i]-right[i+1]);\n }\n return max(res, 0);\n }\n};\n```
| 0 | 0 |
['C']
| 0 |
subsequence-with-the-minimum-score
|
Easy to understand C++ O(N) code
|
easy-to-understand-c-on-code-by-vishalra-avkw
|
\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n vector<int> left, right;\n int idx = 0; int n = t.size();\n \n
|
vishalrathi02
|
NORMAL
|
2023-02-15T05:02:47.935083+00:00
|
2023-02-15T05:02:47.935126+00:00
| 12 | false |
```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n vector<int> left, right;\n int idx = 0; int n = t.size();\n \n // Scan for left to right get the maxiumm matches\n for (int i = 0; (i < s.size()) && (idx < n); i++) {\n if (s[i] == t[idx]) {\n left.push_back(i);\n idx++;\n }\n }\n // initial result will be unmatached characters from the left\n int result = n-left.size();\n idx = n-1;\n \n // try matching characters from right to left\n for (int i = s.size()-1; (i >= 0) && (idx >= 0) && (result != 0); i--) {\n if (s[i] == t[idx]) {\n // in order to push to right, left wipe out the matches from left part\n // greater than equal to current index\n while (left.size() && (left.back() >= i)) {\n // if moving from right to left we found this character earlier\n // then we pop from left and let right proceed further \n left.pop_back();\n }\n right.push_back(i);\n // compute the current state of the unmatched character \n int cur = (n - (left.size() + right.size()));\n result = min(result,cur);\n idx--;\n }\n }\n \n return result;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
subsequence-with-the-minimum-score
|
2 scans for prefix/suffix, O(n).
|
2-scans-for-prefixsuffix-on-by-dolphinsa-cdfu
|
We need to find a combination of a prefix/suffix subsequence that has the longest combined length. First scan left-to-right finding the offsets into s for ever
|
DolphinsAtDaybreak
|
NORMAL
|
2023-02-15T02:21:10.833536+00:00
|
2023-02-15T02:27:06.675974+00:00
| 23 | false |
We need to find a combination of a prefix/suffix subsequence that has the longest combined length. First scan left-to-right finding the offsets into s for every character in t that can be a part of a subsequence. Then do the same scanning right-to-left and matching with the longest subsequence that ends before the current position.\n```\nint minimumScore(string s, string t) {\n int n=s.size();\n int l=0; // index of char in t in a prefix subsequence.\n vector<int> pref(t.size()+1, 100001);\n pref[0]=-1;\n for (int pos=0; l<t.size(); l++, pos++) {\n while (pos<n && s[pos]!=t[l]) ++pos;\n if (pos==n) break;\n pref[l+1]=pos; \n }\n if (l==t.size()) return 0; // full string is a subsequence!\n int ans=t.size()-l;\n for (int i=t.size()-1, pos=s.size()-1; i>=0; i--, pos--) {\n while (pos>=0 && s[pos]!=t[i]) --pos;\n if (pos<0) break;\n while (l>=0 && (l>=i || pref[l]>=pos)) --l;\n ans=min(ans, i-l); \n }\n return ans; \n}\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
c++ binary search two pointers
|
c-binary-search-two-pointers-by-aavii-ph9p
|
\n\n# Code\n\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int ans = t.length();\n vector<int> l(t.length(), -1), r(t.l
|
aavii
|
NORMAL
|
2023-02-14T16:45:49.641706+00:00
|
2023-02-14T16:45:49.641743+00:00
| 37 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int ans = t.length();\n vector<int> l(t.length(), -1), r(t.length(), -1);\n int j = 0;\n for(int i = 0;i<s.length();i++)\n {\n if(s[i]==t[j])\n {\n l[j] = i;\n j++;\n }\n if(j==t.length()) break;\n }\n j = t.length()-1;\n \n for(int i = s.length()-1;i>=0;i--)\n {\n if(s[i]==t[j])\n {\n r[j] = i;\n j--;\n }\n if(j<0) break;\n }\n\n for(int i = 0;i<t.length();i++)\n {\n if(l[i]!=-1) ans = min(ans,(int) t.length()-i-1);\n if(r[i]!=-1) ans = min(ans, i);\n }\n\n\n for(int i = 0;i<t.length();i++)\n {\n if(l[i] >= r[t.length()-1]) break;\n if(l[i]==-1) continue;\n auto it = upper_bound(r.begin()+i+1, r.end(), l[i]) - r.begin();\n ans = min(ans, (int)it-i-1);\n }\n return ans;\n \n }\n};\n```
| 0 | 0 |
['Two Pointers', 'Binary Search', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
ANTARNAB || 100% FASTER || EASY
|
antarnab-100-faster-easy-by-arnab-chatte-j0q5
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
Arnab-Chatterjee
|
NORMAL
|
2023-02-14T04:33:36.324894+00:00
|
2023-02-14T04:33:36.324961+00:00
| 13 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n //int minimumScore(string s, string t) {\n int ss = s.size(), st = t.size(), k = st - 1;\n vector<int> dp(st, -1);\n for (int i = ss - 1; i >= 0 && k >= 0; --i)\n if (s[i] == t[k])\n dp[k--] = i;\n int res = k + 1;\n for (int i = 0, j = 0; i < ss && j < st && res > 0; ++i)\n if (s[i] == t[j]) {\n for (; k < t.size() && dp[k] <= i; ++k);\n res = min(res, k - (++j));\n }\n return res;\n \n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
[Python] [Left to right and right to left traversal]
|
python-left-to-right-and-right-to-left-t-4qm7
|
\n\n def minimumScore(self, s: str, t: str) -> int:\n l = len(s)\n\n right = [0]*(l)\n tlen = len(t)\n curr =0\n \n
|
MumRocks
|
NORMAL
|
2023-02-14T00:26:29.353294+00:00
|
2023-02-14T00:27:42.178378+00:00
| 42 | false |
\n```\n def minimumScore(self, s: str, t: str) -> int:\n l = len(s)\n\n right = [0]*(l)\n tlen = len(t)\n curr =0\n \n \n curr = 0\n for i in range(l-1,-1,-1):\n if curr<tlen and s[i]==t[tlen-curr-1]:\n curr+=1\n right[i]=curr\n \n ans =tlen-right[0]\n curr=0\n #print(f"{left} {right} {l} {tlen}")\n for i in range(l):\n #print(f"{i} {left[i]} {right[i+1] if i+1<l else 0}")\n if curr<tlen and s[i]==t[curr]:\n curr+=1\n \n ans = min(ans,tlen- min(curr+ (right[i+1] if i+1<l else 0),tlen))\n \n return ans\n```
| 0 | 0 |
['Python']
| 0 |
subsequence-with-the-minimum-score
|
Rust Solution
|
rust-solution-by-xiaoping3418-d49x
|
Intuition\n Describe your first thoughts on how to solve this problem. \n1) Intruce two vectors: left & right.\n2) left[i] be the number of characters covered i
|
xiaoping3418
|
NORMAL
|
2023-02-13T20:57:53.199782+00:00
|
2023-02-13T21:15:36.724906+00:00
| 36 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1) Intruce two vectors: left & right.\n2) left[i] be the number of characters covered in t (starting from left end) by s[0 ..i - 1].\n3) right[i] be the nuber of characters covered in t ( starting from right end) by s[i.. m-1].\n4) Once left & right have been calculated, the final solution could derived with a loop.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n# Code\n```\nimpl Solution {\n pub fn minimum_score(s: String, t: String) -> i32 {\n let (m, n) = (s.len(), t.len());\n let (s, t) = (s.chars().collect::<Vec<char>>(), t.chars().collect::<Vec<char>>());\n \n let (mut left, mut right) = (vec![0; m + 1], vec![0; m + 1]);\n let mut count = 0;\n \n for i in 0 .. m {\n if count < n && s[i] == t[count] { count += 1; }\n left[i + 1] = count;\n }\n \n count = 0;\n for i in (0 .. m).rev() {\n if count < n && s[i] == t[n - count - 1] { count += 1; }\n right[i] = count;\n }\n \n let mut ret = n as i32;\n for i in 0 ..= m {\n ret = ret.min(0.max(n as i32 - left[i] as i32 - right[i] as i32));\n }\n \n ret\n }\n}\n```
| 0 | 0 |
['Rust']
| 0 |
subsequence-with-the-minimum-score
|
C++ | BinarySearch
|
c-binarysearch-by-ghost_tsushima-d006
|
\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n vector<int> right(t.length(), -1);\n vector<int> left(t.length(), -1);\n
|
ghost_tsushima
|
NORMAL
|
2023-02-13T18:27:05.279628+00:00
|
2023-02-13T18:27:05.279679+00:00
| 20 | false |
```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n vector<int> right(t.length(), -1);\n vector<int> left(t.length(), -1);\n\n int i = 0; \n\n for(int j = 0 ; j < s.length(); j++) {\n if ( i < t.length() && t[i] == s[j] ) {\n left[i] = j;\n i++;\n }\n }\n\n i = t.size()-1;\n for(int j = s.length()-1 ; j >= 0; j--) {\n if ( i >= 0 && t[i] == s[j] ) {\n right[i] = j;\n i--;\n }\n }\n\n int ans = t.size();\n int low = 0, high = t.size();\n while (low <= high) {\n int mid = (low + high)/2;\n if (isSubSequence(t, mid, left, right)) {\n ans = mid;\n high = mid -1;\n } else {\n low = mid + 1;\n }\n }\n return ans;\n }\n\n bool isSubSequence(string &t, int val, vector<int> &left, vector<int> &right) {\n if(val == t.length()) {\n return true;\n }\n\n for(int i=0; i<=t.length()-val; i++) {\n if (i-1>=0 && i+val < t.length()) {\n if(left[i-1] !=-1 && right[i+val] != -1 && right[i+val] > left[i-1]) {\n return true;\n }\n } else if (i-1 >= 0) {\n if (left[i-1] != -1) {\n return true;\n }\n } else if (i+val < t.length()) {\n if(right[i+val] != -1) {\n return true;\n }\n }\n }\n return false;\n }\n\n\n};\n\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
C++ || EASY || BINARY SEARCH + PREFIX SUM || BEATS 100%
|
c-easy-binary-search-prefix-sum-beats-10-fkqh
|
\n\n# Code\n\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.size();\n int m = t.size();\n\n vector<int>
|
Madhur_Jain
|
NORMAL
|
2023-02-13T17:53:13.386028+00:00
|
2023-02-13T17:53:13.386084+00:00
| 32 | false |
\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n = s.size();\n int m = t.size();\n\n vector<int>pref(m, n);\n vector<int>suff(m, -1);\n\n int p = 0, i = 0;\n while(p < m && i < n) {\n if(t[p] == s[i]) {\n pref[p] = i;\n p++; i++;\n }else {\n i++;\n }\n }\n // for(int i=0; i<pref.size(); i++) {\n // cout << pref[i];\n // }\n int su = m-1, j = n-1;\n while(su >= 0 && j >= 0) {\n if(t[su] == s[j]) {\n suff[su] = j;\n su--; j--;\n }else {\n j--;\n }\n }\n int mini = INT_MAX;\n\n for(int left = 0; left<m; left++) {\n int pos = (left > 0) ? pref[left-1] : -1;\n if(pos == n) break;\n\n int right = upper_bound(suff.begin(), suff.end(), pos) - suff.begin();\n\n if(left <= right) mini = min(mini, right-left);\n }\n return mini;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
JAVA | Easy Explained | votrubac's solution explained
|
java-easy-explained-votrubacs-solution-e-anic
|
Intuition\n Describe your first thoughts on how to solve this problem. \nBased on the problem description, we need to find the longest prefix + suffix of t that
|
just_kidding__03
|
NORMAL
|
2023-02-13T16:46:17.885494+00:00
|
2023-02-13T16:46:17.885525+00:00
| 104 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBased on the problem description, we need to find the longest prefix + suffix of t that is a subsequence of s beacuse it was hte way we remove elements from middle. Thus the score would be minimum.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFor each matched character in t, we remember the corresponding point in s in the dp array. This is our suffix.\nThen we go left-to-right building our prefix. For each prefix, we determine the longest suffix using dp.\n**Note 2** We use a loop to prevent overlapping and make it move till its not overlapped , then calculate minimum among the answer.\n**Note 2** res condition is checked that if t as complete is a subsequence of s then no need to remove any thing from it.\n\n\n# Code\n```\nclass Solution {\n public int minimumScore(String s, String t) \n {\n int ss = s.length(),st = t.length(),k = st-1;\n int dp[] = new int[st];\n Arrays.fill(dp,-1);\n for(int i= ss-1;i>=0 && k>=0;i--)\n {\n if(s.charAt(i) == t.charAt(k))\n {\n dp[k] = i;\n k--;\n }\n }\n int res = k+1;\n if(res == 0)\n return 0;\n for(int i = 0,j=0;i<ss && j<st;i++)\n {\n if(s.charAt(i) == t.charAt(j))\n {\n while(k<st && dp[k]<=i)\n {\n k++;\n }\n j++;\n res = Math.min(res, k - (j));\n }\n }\n return res;\n \n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
subsequence-with-the-minimum-score
|
Just a runnable solution
|
just-a-runnable-solution-by-ssrlive-5p6m
|
Code\n\nimpl Solution {\n pub fn minimum_score(s: String, t: String) -> i32 {\n let (s, t) = (s.as_bytes(), t.as_bytes());\n let (ss, ts) = (s.
|
ssrlive
|
NORMAL
|
2023-02-13T12:08:35.074121+00:00
|
2023-02-13T12:08:35.074158+00:00
| 26 | false |
# Code\n```\nimpl Solution {\n pub fn minimum_score(s: String, t: String) -> i32 {\n let (s, t) = (s.as_bytes(), t.as_bytes());\n let (ss, ts) = (s.len(), t.len());\n let (mut k, mut j) = (ts as i32 - 1, ts as i32 - 1);\n let mut dp = vec![-1; ts];\n\n let mut i = ss as i32 - 1;\n while i >= 0 {\n if j >= 0 && t[j as usize] == s[i as usize] {\n dp[k as usize] = i;\n j -= 1;\n k -= 1;\n }\n i -= 1;\n }\n\n let mut ans = k + 1;\n if ans == 0 {\n return 0;\n }\n\n j = 0;\n for (i, &item) in s.iter().enumerate().take(ss) {\n if j < ts as i32 && t[j as usize] == item {\n while k < ts as i32 && dp[k as usize] <= i as i32 {\n k += 1;\n }\n ans = ans.min(k - j - 1);\n j += 1;\n }\n }\n ans as _\n }\n}\n```
| 0 | 0 |
['Rust']
| 0 |
subsequence-with-the-minimum-score
|
Python O(n) solution with clear logical coding
|
python-on-solution-with-clear-logical-co-jqj3
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
xinyzy
|
NORMAL
|
2023-02-13T06:50:36.901201+00:00
|
2023-02-13T06:50:36.901265+00:00
| 65 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n\n # 1. build prefix and suffix\n # prefix[i]: index of t which has its left part a subsequence of s[:i]\n # t[: prefix[i]] is a subsequence of s[: i]\n # suffix[i]: index of t which has its right part a subsequence of s[i:]\n # t[suffix[i] :] is a subsequence of s[i :]\n # prefix is left-to-right scanning, while suffix is right-to-left scanning\n \n prefix = [-1] * len(s)\n i = j = 0\n while i < len(s):\n if j < len(t) and s[i] == t[j]:\n prefix[i] = j\n j += 1\n elif i > 0:\n prefix[i] = prefix[i - 1]\n i += 1\n\n if prefix[-1] == len(t) - 1: # t is subsequence of s\n return 0\n\n suffix = [len(t)] * len(s)\n i, j = len(s) - 1, len(t) - 1\n while i >= 0:\n if j >= 0 and s[i] == t[j]:\n suffix[i] = j\n j -= 1\n elif i < len(s) - 1:\n suffix[i] = suffix[i + 1]\n i -= 1\n\n # 2. scan s to find the longest subsequence based on prefix and suffix\n # since t is not a subsequence of s, so prefix[i] < suffix[i]\n\n length = float(\'Inf\')\n\n for idx in range(len(s)):\n # check if s[idx] is the first match for s[prefix[idx]] and s[suffix[idx]]\n # if so, need to remove one more chars\n if (prefix[idx] >= 0) and (idx == 0 or prefix[idx] > prefix[idx - 1]):\n pre_match = True # s[idx] is the one to match t[prefix[idx]] for the first time\n else:\n pre_match = False\n if (suffix[idx] < len(t)) and (idx == len(s) - 1 or suffix[idx] < suffix[idx + 1]):\n suf_match = True # s[idx] is the one to match t[suffix[idx]] for the first time\n else:\n suf_match = False\n\n if pre_match and suf_match:\n length = min(length, suffix[idx] - prefix[idx])\n else:\n length = min(length, suffix[idx] - prefix[idx] - 1)\n\n return length\n \n \n \n \n \n \n \n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Find prefix and suffix and check the smallest removal score
|
find-prefix-and-suffix-and-check-the-sma-np2x
|
\n### Fact\n> only the leftmost non-removal and rightmost non-removal positions affect the score, so we just need to find prefix and suffix.\n\n\nWe have to loo
|
ogremergo
|
NORMAL
|
2023-02-12T23:11:51.838694+00:00
|
2023-02-13T00:57:07.061695+00:00
| 45 | false |
\n### Fact\n> only the leftmost non-removal and rightmost non-removal positions affect the score, so we just need to find prefix and suffix.\n\n\nWe have to look for all [prefix, suffix] pairs to get the most optimized score.\n\n\n## Solution\n\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int m = s.size(), n = t.size();\\\n // get rightmost index in s that all t\'s suffix sequence can be constructed\n vector<int> suffix(n, -1);\n int k = n - 1;\n for (int i = m - 1; i >= 0 && k >= 0; --i) {\n if (s[i] == t[k]) {\n suffix[k--] = i;\n }\n }\n // t can be formed by char sequence in s, no removal needed\n if (k < 0) {\n return 0;\n }\n \n // t[0...k] should be removed\n int minScore = k + 1;\n \n // get leftmost index in s that all t\'s prefix sequence can be constructed\n vector<int> prefix(n, -1);\n k = 0;\n for (int i = 0; i < m && k < n; ++i) {\n if (s[i] == t[k]) {\n prefix[k++] = i;\n }\n }\n\n // t can be formed by char sequence in s, no removal needed\n if (k >= n) {\n return 0;\n }\n // t[k...n-1] shoule be removed\n minScore = min(minScore, n - k);\n \n\n // now, we check if there exist prefix and suffix \n // t[...i] and t[j...] to get the smaller score with j - 1 - (i + 1) + 1\n for (int i = 0; i < n; i++) {\n // now, there exist prefix t[...i]\n if (prefix[i] != -1) {\n // s[0...leftMost]\n int leftMost = prefix[i];\n \n // find suffix t[j...]\n int j = n - 1;\n while(j >= 0 && suffix[j] > leftMost) {\n j--;\n }\n // j is -1 or suffix[j] <= leftMost\n // j is -1 means all chars t[0..n-1] can be removed \n if (j == -1) {\n minScore = min(minScore, n - 1 + 1);\n } else {\n // now, we can know t[...i] .... t[j + 1 ...]\n int score = j - (i + 1) + 1;\n minScore = min(minScore, score);\n }\n }\n }\n \n return minScore;\n }\n};\n\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
bs + 1-dp
|
bs-1-dp-by-qwu03-qka3
|
\n\nclass Solution {\n public int minimumScore(String s, String t) {\n char[] array1 = s.toCharArray();\n char[] array2 = t.toCharArray();\n
|
qwu03
|
NORMAL
|
2023-02-12T20:45:52.436995+00:00
|
2023-02-12T20:45:52.437051+00:00
| 58 | false |
\n```\nclass Solution {\n public int minimumScore(String s, String t) {\n char[] array1 = s.toCharArray();\n char[] array2 = t.toCharArray();\n int n1 = array1.length, n2 = array2.length;\n int index = 0;\n int[] dp1 = new int[n2];\n Arrays.fill(dp1, -1);\n int[] dp2 = new int[n2];\n Arrays.fill(dp2, -1);\n for (int i = 0; i < n1 && index < n2; i++) {\n char ch = array1[i];\n if (array2[index] == ch) {\n dp1[index] = i;\n index++;\n }\n }\n if (dp1[n2-1] != -1) return 0;\n index = n2-1;\n for (int i = n1-1; i >= 0 && index >= 0; i--) {\n char ch = array1[i];\n if (array2[index] == ch) {\n dp2[index] = i;\n index--;\n }\n }\n int left = 1, right = n2;\n int res = n2;\n // bs? two pointer? -> bs\n while (left < right) {\n int mid = left + (right - left)/2;\n if (validate(mid, dp1, dp2)) {\n right = mid;\n } else {\n left = mid + 1;\n }\n }\n return validate(left, dp1, dp2) ? left : right;\n }\n private boolean validate(int len, int[] dp1, int[] dp2) {\n int n = dp1.length;\n for (int i = 0; i <= n - len; i++) {\n int left = i;\n int right = i + len - 1;\n if (left - 1 >= 0 && right + 1 < n) {\n if (dp1[left-1] != -1 && dp2[right+1] != -1 && dp1[left-1] < dp2[right+1]) return true;\n } else if (left - 1 >= 0) {\n if (dp1[left-1] != -1) return true;\n } else if (right + 1 < n){\n if (dp2[right+1] != -1) return true;\n }\n }\n return false;\n }\n}\n```
| 0 | 0 |
['Java']
| 0 |
subsequence-with-the-minimum-score
|
[Scala] Scan Twice
|
scala-scan-twice-by-heavenwatcher-qx0s
|
scala\nobject Solution {\n def minimumScore(s: String, t: String): Int = {\n val leftMatch = s.scanLeft(0, t.zipWithIndex) {\n case ((_, (ct, i)+:ts),
|
heavenwatcher
|
NORMAL
|
2023-02-12T19:56:50.483168+00:00
|
2023-02-12T19:56:50.483206+00:00
| 25 | false |
```scala\nobject Solution {\n def minimumScore(s: String, t: String): Int = {\n val leftMatch = s.scanLeft(0, t.zipWithIndex) {\n case ((_, (ct, i)+:ts), cs) => if (ct == cs) (i, ts) else (-1, (ct, i)+:ts)\n case _ => (-1, null)\n }.map(_._1).drop(1)\n val lastMatch = leftMatch.findLast(_ != -1).getOrElse(-1)\n val lastUnmatch = (t.size - lastMatch - 1)\n val res = s.zip(leftMatch).reverse.scanLeft(lastUnmatch, lastMatch, t.zipWithIndex.reverse) {\n case ((_, m, (ct, i)+:ts), (cs, j)) =>\n val nm = if (j == -1) m else j - 1\n if (ct == cs) (i - nm - 1, nm, ts) else (Int.MaxValue, nm, (ct, i)+:ts)\n case _ => (0, 0, null)\n }\n res.map(_._1).min max 0\n }\n}\n```
| 0 | 0 |
[]
| 0 |
subsequence-with-the-minimum-score
|
Sharing my O( nlogn ) solution || 100% faster and memory efficient
|
sharing-my-o-nlogn-solution-100-faster-a-sus3
|
\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n=t.size();\n vector<int>first(n,-1),last(n,-1);\n int i=0,j=
|
aabhi04
|
NORMAL
|
2023-02-12T17:54:39.878381+00:00
|
2023-02-12T17:54:39.878415+00:00
| 35 | false |
```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n=t.size();\n vector<int>first(n,-1),last(n,-1);\n int i=0,j=0;\n \n \n while(i<s.size()&&j<t.size()){\n if(s[i]==t[j]){\n first[j]=i;\n i++;\n j++;\n }\n else i++;\n }\n i=s.size()-1,j=t.size()-1;\n while(i>=0&&j>=0){\n if(s[i]==t[j]){\n last[j]=i;\n i--;\n j--;\n }\n else i--;\n }\n if(first.back()!=-1){\n return 0;\n }\n for(int i=0;i<n;i++)\n {\n if(first[i]==-1){\n first[i]=s.size()+1;\n }\n }\n \n for(int i=n-2;i>=0;i--){\n if(last[i]==-1){\n last[i]=-1;\n }\n }\n \n \n if(first[0]==s.size()+1){\n return n;\n } \n \n int ans=n;\n int l=0,r=n;\n while(l<=r){\n int m=(l+r)/2;\n bool b=false;\n for(int i=0;i<n-m-1;i++){\n if(last[i+m+1]>first[i]){\n b=true;\n break;\n }\n }\n if(b){\n ans=m;\n r=m-1;\n }\n else l=m+1;\n }\n for(int i=0;i<n;i++){\n if(first[i]!=s.size()+1){\n ans=min(ans,n-i-1);\n }\n if(last[i]!=-1){\n ans=min(ans,i);\n }\n }\n return ans;\n \n }\n};\n```
| 0 | 0 |
['Binary Search']
| 0 |
subsequence-with-the-minimum-score
|
Easy to understand O(n) space O(n) time well commented solution
|
easy-to-understand-on-space-on-time-well-ba07
|
Since only extreme ends have an impact on our solution, it makes sense to leave the left side block and right side block and delete the middle piece of string t
|
akshit19
|
NORMAL
|
2023-02-12T17:41:51.274462+00:00
|
2023-02-12T17:42:29.831321+00:00
| 30 | false |
Since only extreme ends have an impact on our solution, it makes sense to leave the left side block and right side block and delete the middle piece of string t.\nWe define two arrays, one holding prefix data and the other suffix data, both of size n (n=size of string s).\n\nTime Complexity: O(n)\nSpace Complexity: O(n)\n\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n=s.size(),j=0,res=1e9;\n //declare 2 arrays: v1=prefix array, v2=suffix array\n vector<int>v1(n),v2(n);\n //Case 1- current element is part of prefix\n for(int i=0;i<n;i++){\n if(j<t.size() && s[i]==t[j]){\n j++;\n }\n v1[i]=j;\n }\n j=t.size()-1;\n for(int i=n-1;i>=0;i--){\n v2[i]=j;\n if(j>=0 && s[i]==t[j]){\n j--;\n }\n }\n //check result\n for(int i=0;i<n;i++){\n res=min(res,max(0,v2[i]-v1[i]+1));\n }\n //Case 2- current element is part of suffix\n j=0;\n for(int i=0;i<n;i++){\n v1[i]=j;\n if(j<t.size() && s[i]==t[j]){\n j++;\n }\n }\n //check result\n j=t.size()-1;\n for(int i=n-1;i>=0;i--){\n if(j>=0 && s[i]==t[j]){\n j--;\n }\n v2[i]=j;\n }\n for(int i=0;i<n;i++){\n res=min(res,max(0,v2[i]-v1[i]+1));\n }\n return res;\n }\n};\n```
| 0 | 0 |
['C']
| 0 |
subsequence-with-the-minimum-score
|
Two pointers
|
two-pointers-by-kfli716-n4gj
|
Observations:\n1. By the way we calculaute the score, it makes no difference to assume that any points in between [left, right] are removed. \n2. Because we do
|
kfli716
|
NORMAL
|
2023-02-12T17:05:47.923931+00:00
|
2023-02-12T17:09:37.431056+00:00
| 26 | false |
Observations:\n1. By the way we calculaute the score, it makes no difference to assume that any points in between [left, right] are removed. \n2. Because we do not need to remove (right end inclusive) t[0, left - 1] and t[right + 1, t.size() - 1], they have to be subsequences of s.\n3. This means, we want to remove the shortest substring of t so that prefix and suffix strings of t are both subsequences of s. The score of the removal is the number of characters removed.\n4. Finally, the idea of solving the question is: We first find the longest prefix substring of t which is also a subsequence of s. Then we gradually increase the length of the suffix string to get the maximal characters removed in each settings. Time and space complexity are both linear in the lengths\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int m = s.size(), n = t.size();\n vector<int> stk;\n for(int i = 0, j = 0; i < m; i++){\n if(s[i] != t[j]) continue;\n stk.push_back(i);\n j++;\n }\n \n int res = n - stk.size();\n if(res == 0) return res;\n \n for(int i = m - 1, j = n - 1; i >= 0; i--){\n if(s[i] != t[j]) continue;\n while(!stk.empty() && stk.back() >= i){\n stk.pop_back();\n }\n j--;\n res = min(res, j - (int)stk.size() + 1);\n }\n return res;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
subsequence-with-the-minimum-score
|
Go/Python O(n) time | O(n) space
|
gopython-on-time-on-space-by-vtalantsev-os2j
|
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co
|
vtalantsev
|
NORMAL
|
2023-02-12T14:02:06.030524+00:00
|
2023-02-12T14:02:06.030565+00:00
| 71 | false |
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```golang []\nfunc minimumScore(s string, t string) int {\n suffix :=make([]int,len(s))\n j := len(t)-1\n for i:=len(s)-1;i>=0;i--{\n if 0 <= j && s[i] == t[j]{\n j--\n }\n suffix[i] = j \n }\n answer := j + 1\n j = 0\n for i,_ := range(s){\n answer = min(answer, max(0, suffix[i] - j + 1))\n if j < len(t) && s[i] == t[j]{\n j++\n }\n }\n return min(answer, len(t)-j)\n}\n\nfunc min(a,b int) int{\n if a<b{\n return a\n }\n return b\n}\n\nfunc max(a,b int) int{\n if a>b{\n return a\n }\n return b\n}\n```\n```python []\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n suffix = [0 for i in range(len(s))]\n j = len(t)-1\n for i in range(len(s)-1,-1,-1): \n if 0 <= j and s[i] == t[j]:\n j -= 1\n suffix[i] = j \n answer = j + 1\n j = 0 \n for i,_ in enumerate(s): \n answer = min(answer, max(0, suffix[i] - j + 1))\n if j < len(t) and s[i] == t[j]:\n j += 1\n return min(answer, len(t)-j)\n```
| 0 | 0 |
['Suffix Array', 'Prefix Sum', 'Go', 'Python3']
| 0 |
subsequence-with-the-minimum-score
|
Simple Binary Search Approach
|
simple-binary-search-approach-by-ojha111-2q9u
|
\n\n#define ll long long\nclass Solution {\npublic:\n int check(vector<int>& p,vector<int>& s,int m){\n int l=0,n=p.size()-1;\n for(int r=0;r<n
|
ojha1111pk
|
NORMAL
|
2023-02-12T13:23:06.801724+00:00
|
2023-02-12T13:23:06.801757+00:00
| 83 | false |
\n```\n#define ll long long\nclass Solution {\npublic:\n int check(vector<int>& p,vector<int>& s,int m){\n int l=0,n=p.size()-1;\n for(int r=0;r<n;r++){\n while((r-l+1)>m)\n l++;\n if((r-l+1)==m){\n int left=-1;\n if(l)\n left=p[l-1];\n int right=s[r+1];\n if(left<right)\n return 1;\n }\n }\n \n return 0;\n }\n \n int minimumScore(string s, string t) {\n int n=s.length(),m=t.length();\n vector<int> pr(m+1,n),sf(m+1,-1);\n sf[m]=n;\n \n int i=0,j=0;\n \n while(i<n and j<m){\n if(s[i]==t[j]){\n pr[j]=i;\n j++;\n }\n i++;\n }\n \n i=n-1;\n j=m-1;\n \n while(i>=0 and j>=0){\n if(s[i]==t[j]){\n sf[j]=i;\n --j;\n }\n --i;\n }\n \n \n \n ll l=0,ans=m,r=m;\n \n while(l<=r){\n ll mid=l+((r-l)>>1);\n \n if(check(pr,sf,mid)){\n ans=mid;\n r=mid-1;\n }\n else\n l=mid+1;\n }\n \n \n return ans;\n }\n};\n```
| 0 | 0 |
['C', 'Binary Tree', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
Cpp Solution easy to understand
|
cpp-solution-easy-to-understand-by-sanke-byz0
|
\n# Code\n\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n \n vector<int>v;\n int ans=0;\n \n int i=
|
Sanket_Jadhav
|
NORMAL
|
2023-02-12T12:27:12.487763+00:00
|
2023-02-12T12:27:12.487791+00:00
| 43 | false |
\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n \n vector<int>v;\n int ans=0;\n \n int i=s.size()-1,j=t.size()-1;\n \n while(i>=0 && j>=0){\n if(s[i]==t[j]){v.push_back(i);j--;}\n i--;\n }\n \n reverse(v.begin(),v.end());\n \n ans=t.size()-v.size();\n \n if(ans==0)return ans;\n \n i=0,j=0;\n \n \n while(j<t.size()){\n while(i<s.size() && s[i]!=t[j])i++;\n if(i>=s.size())break;\n int u=upper_bound(v.begin(),v.end(),i)-v.begin();\n \n \n int m=v.size(),p=t.size();\n \n if(u>=m)ans=min(ans,p-(j+1));\n \n else ans=min(ans,p-(m-u)-(j+1));\n \n j++;\n i++;\n }\n \n \n return ans;\n }\n};\n\n\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
Find the Shortest Substring of t: Match from Right then Left, Two Pass, O(N)
|
find-the-shortest-substring-of-t-match-f-1yge
|
Intuition \nThe score right - left + 1 equals to substring length.\nSo to minimize the score, it means we should find a shortest substring of t which after we r
|
shuangquanli
|
NORMAL
|
2023-02-12T09:58:39.161562+00:00
|
2023-02-13T18:21:41.472720+00:00
| 120 | false |
# Intuition \nThe score `right - left + 1` equals to substring length.\nSo to minimize the score, it means we should find a shortest substring of `t` which after we remove this substring then `t` will be a subsequence of `s`.\n\n# Approach\nIf we match from first character of `t`, say `t[0:j+1]` is a subsequence of `s[0:i+1]`, then how many characters the rest of `s`, i.e. `s[i+1:]` can match `t` from t\'s right most? We can pre-calculate this right-match-cnt of `t`.\n\n# Complexity\n- Time complexity: O(N)\n- Space complexity: O(N)\n\n# Code\n```python3 []\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n ns = len(s)\n nt = len(t)\n rcnt = [0] * (ns + 1) # right-match-cnt\n\n i = ns - 1\n j = nt - 1\n while i >= 0:\n if j >= 0 and s[i] == t[j]:\n rcnt[i] = rcnt[i + 1] + 1\n j -= 1\n else:\n rcnt[i] = rcnt[i + 1]\n i -= 1\n\n if rcnt[0] >= nt: # match all of t\n return 0\n\n ret = nt - rcnt[0]\n i = j = 0\n while j < nt:\n while i < ns and s[i] != t[j]:\n i += 1\n if i >= ns:\n break\n subret = nt - (rcnt[i + 1] + j + 1) # left matches j+1, right matches rcnt[i + 1]\n ret = min(ret, subret)\n j += 1\n i += 1\n return ret\n```\n```C++ []\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int ns = s.size(), nt = t.size();\n vector<int> rcnt(ns + 1);\n for (int i = ns - 1, j = nt - 1; i >= 0; --i) {\n if (j >= 0 && s[i] == t[j]) {\n rcnt[i] = rcnt[i+1] + 1;\n --j;\n } else {\n rcnt[i] = rcnt[i+1];\n }\n }\n\n if (rcnt[0] >= nt) return 0;\n\n int ret = nt - rcnt[0];\n for (int i = 0, j = 0; j < nt; ++j, ++i) {\n while (i < ns && s[i] != t[j]) ++i;\n if (i >= ns) break;\n int subret = nt - (rcnt[i + 1] + j + 1);\n ret = min(ret, subret);\n }\n return ret;\n }\n};\n```\n```Java []\nclass Solution {\n public int minimumScore(String s, String t) {\n int ns = s.length(), nt = t.length();\n int[] rcnt = new int[ns + 1];\n for (int i = ns - 1, j = nt - 1; i >= 0; --i) {\n if (j >= 0 && s.charAt(i) == t.charAt(j)) {\n rcnt[i] = rcnt[i + 1] + 1;\n --j;\n } else {\n rcnt[i] = rcnt[i + 1];\n }\n }\n if (rcnt[0] >= nt) return 0;\n\n int ret = nt - rcnt[0];\n for (int i = 0, j = 0; j < nt; ++i, ++j) {\n while (i < ns && s.charAt(i) != t.charAt(j)) ++i;\n if (i >= ns) break;\n int subret = nt - (rcnt[i + 1] + j + 1);\n ret = Math.min(ret, subret);\n }\n return ret;\n }\n}\n```\n```Go []\nfunc minimumScore(s string, t string) int {\n ns, nt := len(s), len(t)\n rcnt := make([]int, ns + 1)\n for i, j := ns - 1, nt - 1; i >= 0; i-- {\n if (j >= 0 && s[i] == t[j]) {\n rcnt[i] = rcnt[i + 1] + 1\n j--\n } else {\n rcnt[i] = rcnt[i + 1]\n }\n }\n if rcnt[0] >= nt {\n return 0\n }\n ret := nt - rcnt[0]\n for i, j := 0, 0; j < nt; i, j = i + 1, j + 1 {\n for i < ns && s[i] != t[j] {\n i++\n }\n if i >= ns {\n break\n }\n if subret := nt - (rcnt[i + 1] + j + 1); subret < ret {\n ret = subret\n }\n }\n return ret\n}\n```\n
| 0 | 0 |
['C++', 'Java', 'Go', 'Python3']
| 0 |
subsequence-with-the-minimum-score
|
C++ linear scan O(n) beats 100%
|
c-linear-scan-on-beats-100-by-vvhack-crfq
|
We want a prefix of t and a suffix of t such that when we concatenate them, it is a valid subsequence of s.\n\nclass Solution {\npublic:\n int minimumScore(str
|
vvhack
|
NORMAL
|
2023-02-12T08:05:50.727402+00:00
|
2023-02-12T08:12:41.708565+00:00
| 40 | false |
We want a prefix of `t` and a suffix of `t` such that when we concatenate them, it is a valid subsequence of `s`.\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int left = 0, right = t.size() - 1;\n \n // Will contain the final answer.\n int ans = t.size();\n \n // All the indices where the left prefix matched s from the left side.\n vector<int> leftMatches;\n for (int i = 0; i < s.size(); ++i) {\n if (left < t.size() && s[i] == t[left]) {\n // The length of leftMatches always == left.\n leftMatches.push_back(i);\n ++left;\n }\n }\n \n ans = min(ans, 1 + right - left);\n \n // Start matching suffixes of t with s starting from the right side.\n for (int i = s.size() - 1; i >= 0; --i) {\n if (right >= 0 && s[i] == t[right]) {\n --right;\n \n // Pop the rightmost index from leftMatches by decrementing left\n // if we are now behind it.\n while ((left - 1) >= 0 && i <= leftMatches[left - 1]) {\n --left;\n }\n \n if (right < left) {\n // Entire t is a subsequence of s.\n return 0;\n }\n\n ans = min(ans, 1 + right - left);\n }\n }\n return ans;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
subsequence-with-the-minimum-score
|
Simple prefix and suffix
|
simple-prefix-and-suffix-by-endless_merc-83wy
|
Intuition\n Describe your first thoughts on how to solve this problem. \nCalculate the distance reached in t till any index in s .Both ways prefix and suffix.\n
|
endless_mercury
|
NORMAL
|
2023-02-12T07:51:25.862346+00:00
|
2023-02-12T07:51:25.862385+00:00
| 52 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nCalculate the distance reached in t till any index in s .Both ways prefix and suffix.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int n=s.length();\n int m=t.length();\n int st=0,en=m-1;\n vector<int> pre(n,-1),suf(n+1,-1);\n suf[n]=m;\n for(int i=0;i<n;i++){\n if(st<m&&s[i]==t[st]){\n st++;\n }\n pre[i]=st;\n }\n for(int j=n-1;j>=0;j--){\n if(en>=0&&s[j]==t[en]){\n en--;\n }\n suf[j]=en+1;\n }\n int ans=INT_MAX;\n for(int i=0;i<n;i++){\n if(suf[i+1]<=pre[i])\n return 0;\n ans=min(ans,suf[i+1]-pre[i]);\n }\n ans=min(ans,suf[0]);\n return ans;\n }\n};\n```
| 0 | 0 |
['Prefix Sum', 'C++']
| 0 |
subsequence-with-the-minimum-score
|
Commented & Explained C++ | Understandable | O(n)
|
commented-explained-c-understandable-on-uvzur
|
Intuition\nTo form intuition for this problem, we need to understand the problem description thoroughly. The goal is to find the minimum score of t such that t
|
deep_patel23
|
NORMAL
|
2023-02-12T07:47:47.860612+00:00
|
2023-02-12T08:03:48.343414+00:00
| 64 | false |
# Intuition\nTo form intuition for this problem, we need to understand the problem description thoroughly. The goal is to find the minimum score of t such that t is a subsequence of s. The score is defined as the difference between the maximum and minimum indices of all removed characters in t.\n\nWith this in mind, we can think of the problem as finding the longest prefix and suffix of t that are substrings of s. We start by finding the suffix by iterating through s in reverse order and keeping track of the indices of characters in s that match characters in t. This creates a dp array that stores the indices in s of the corresponding characters in t.\n\n# Explanation\nThe minimumScore function takes in two strings s and t and returns the minimum possible score to make t a subsequence of s. The score is calculated as described in the problem statement:\n\n* if no characters are removed from the string t, then the score is 0\n* otherwise, the score is equal to the difference between the maximum index and the minimum index among all removed characters, plus 1\n\nThe function starts by initializing the variable ss to the length of s, st to the length of t, and k to st - 1. The dp array is initialized with st elements all equal to -1.\n\nThe next step is to build the suffix of t. This is done by iterating through s from the end to the beginning and checking if the current character of s is equal to the current character of t starting from the end. If they are equal, then the index of the character in s is recorded in the dp array. The k variable is decremented each time a match is found.\n\nAfter building the suffix, the function moves on to building the prefix of t by iterating through s from left to right. The j variable keeps track of the position of the current character of t that is being matched. The k variable is updated to the smallest index of dp that is greater than the current index i of s. The result res is then set to the minimum between res and the difference between k and j + 1.\n\nFinally, the function returns the res variable, which represents the minimum possible score to make t a subsequence of s.\n\nUPVOTE if you find helpful!\n\n# Complexity\nTC: O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n // initialize the length of strings `s` and `t`\n int ss = s.size(), st = t.size();\n\n // `k` keeps track of the last matched character in t from the right\n int k = st - 1;\n\n // initialize the dp array with all elements as -1\n vector<int> dp(st, -1);\n\n // iterate from the end of `s` and match characters from the end of `t`\n for (int i = ss - 1; i >= 0 && k >= 0; --i) {\n // if the character at `i` in `s` matches the character at `k` in `t`, \n // update the `dp` array with the index `i`\n if (s[i] == t[k]) {\n dp[k--] = i;\n }\n }\n\n // `res` stores the minimum score, initially set to `k + 1`\n int res = k + 1;\n\n // iterate over `s` and `t` from the start\n for (int i = 0, j = 0; i < ss && j < st && res > 0; ++i) {\n // if the character at `i` in `s` matches the character at `j` in `t`, \n // increment `j`\n if (s[i] == t[j]) {\n // for each matched character, update `k` to the next character in `t` \n // that is yet to be matched\n for (; k < t.size() && dp[k] <= i; ++k);\n // update `res` with the minimum value of `res` and `k - (j + 1)`\n res = min(res, k - (++j));\n }\n }\n\n // return the minimum score\n return res;\n }\n\n};\n```\n\nThanks to @votrubac for code.\n\nUPVOTE if you find helpful!\n
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
[C++] Super Short O(n) Solution !!!
|
c-super-short-on-solution-by-kylewzk-7rj8
|
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
|
kylewzk
|
NORMAL
|
2023-02-12T07:45:25.738328+00:00
|
2023-02-12T07:45:25.738372+00:00
| 44 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimumScore(string s, string t) {\n int s_sz = s.size(), t_sz = t.size(), suffix[100002]{}, res = t_sz;\n for(int i = s_sz-1, j = t_sz-1; i >= 0; i--) {\n if(j >= 0 && s[i] == t[j]) suffix[i] = t_sz - j--;\n else suffix[i] = suffix[i+1];\n }\n for(int i = 0, j = 0; i <= s_sz; i++) {\n res = min(res, t_sz - min(t_sz, j + suffix[i]));\n if(i < s_sz && s[i] == t[j]) j++;\n }\n return res;\n }\n};\n```
| 0 | 0 |
['C++']
| 0 |
subsequence-with-the-minimum-score
|
Python | Sliding Window | Linear Time | Easy to Understand
|
python-sliding-window-linear-time-easy-t-c2zj
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can remove whole range from left to right\n\n# Approach\n Describe your approach to
|
hemantdhamija
|
NORMAL
|
2023-02-12T07:19:44.271917+00:00
|
2023-02-12T07:19:44.271953+00:00
| 115 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can remove whole range from left to right\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTry removing each range and check if remaining string form valid subsequence or not. To do this we need to precompute match indices in string s. Then using sliding window we can find minimum window size satisfying above condition.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python []\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n prefix, suffix = [len(s)] * (len(t) + 1), [-1] * (len(t) + 1)\n prefix[0], suffix[-1], tIdx = -1, len(s), 0\n for idx in range(len(s)):\n if tIdx >= len(t): break\n if s[idx] == t[tIdx]: \n prefix[tIdx + 1] = idx\n tIdx +=1\n tIdx = len(t) - 1\n for idx in reversed(range(len(s))):\n if tIdx < 0: break\n if s[idx] == t[tIdx]: \n suffix[tIdx] = idx\n tIdx -=1\n if prefix[-1] < len(s): return 0\n left, res = 0, max(len(s), len(t))\n for right in range(len(t)):\n left +=1\n while left <= right and prefix[left] < suffix[right + 1]: \n left +=1\n left -=1\n if prefix[left] < suffix[right + 1]: \n res = min(res, right - left + 1)\n return res\n```
| 0 | 0 |
['Sliding Window', 'Suffix Array', 'Prefix Sum', 'Python', 'Python3']
| 0 |
subsequence-with-the-minimum-score
|
[Python] left and right O(n) with detailed explanation and example
|
python-left-and-right-on-with-detailed-e-osnt
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThis is adpated from https://leetcode.com/votrubac/\'s solution.\n\nThe first observati
|
lashmini
|
NORMAL
|
2023-02-12T07:17:54.853547+00:00
|
2023-02-12T07:17:54.853583+00:00
| 58 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is adpated from https://leetcode.com/votrubac/\'s solution.\n\nThe first observation is that since the number of removals doesn\'t matter, we just need to figure out the start index on the left and the end index on the right. In other words, we want to find l and r such that t[:l] + t[r:] is a substring of s.\n\nIn the first pass, we find for each position in s **the largest index r of t** that would have to be removed for t be a substring s upto that index. i.e. **t[suffix[i]+1:] is a substring of s[i:] and suffix[i] is the least index such that this holds**.\n\nIn the second pass, we find **the largest index l of t** that is a substring of s[:i]. **The difference, (suffix[i] - l+1) would be the length that need to be removed to make t a substring of s.**\n\n**This way, we find the least score for such that t[:r] is a substring s[:i] and t[l+1:] is a substring of s[i:]. By taking the minimum over these scores, we find the true minimum score.**\n\n# Example\n\ns =[a,b,a,c,a,b,a], len(s) = 7\nt = [b,z,a,a], len(t) = 4\ninitialize suffix with -1:\nsuffix = [-1,-1,-1,-1,-1,-1,-1], len(suffix) = 7\n\n---\n**Go from left to right for both s and t in the first pass.**\ns = [a,b,a,c,a,b,**a**], len(s) = 7, i = 6\nt = [b,z,a,**a**], len(t) = 4, r = 3\nfirst, set suffix[i] = r\nsuffix = [-1,-1,-1,-1,-1,-1, **3**]\nsince s[i] == t[r], we can decrease r by 1, to account for the fact that t[3:] is a substring of s[6:], which will be used in the second pass\n\n---\ns = [a,b,a,c,a,**b**,a], len(s) = 7, i = 5\nt = [b,z,**a**,a], len(t) = 4, r = 2\nsince s[i] != t[r], the last index (counting from left to right) of t that is not a substring of s[5+1:] is 2, so we have\nsuffix = [-1,-1,-1,-1,-1, **2**, 3]\n\n---\ns = [a,b,a,c,**a**,b,a], len(s) = 7, i = 4\nt = [b,z,**a**,a], len(t) = 4, r = 2\nsimilar to the first case, we get \nsuffix = [-1,-1,-1,-1,**2**, 2, 3] and move r to 1\n\n---\ns = [a,b,a,c,a,b,a], len(s) = 7, i = 3\nt = [b,**z**,a,a], len(t) = 4, r = 1\nNote that now r points to z, which is not part of s. So, the pointer r will not decrease from now on. In the end,\nsuffix = [1,1,1,1,2,2,3]\n\n---\n\n**Start from left to right for the second pass.**\nans = r + 1 = 2 because we can remove everything including z and the rest of t (aa) would be a substring of s.\n\ns = [**a**,b,a,c,a,b,a], len(s) = 7, i = 0\nt = [**b**,z,a,a], len(t) = 4, r = 0\nsuffix = [1,1,1,1,2,2,3]\nsince s[i]!=t[r], the substring we can form here is t[:r] + t[suffix[i]+1:] = ""+"aa" = "aa", and ans = min(2, 2-0) = 2.\n\n---\ns = [a,**b**,a,c,a,b,a], len(s) = 7, i = 1\nt = [**b**,z,a,a], len(t) = 4, r = 0\nsuffix = [1,1,1,1,2,2,3]\nsince s[i]==t[r], the substring we can form here is t[:r+1] + t[suffix[i]+1:] = "b"+"aa" = "baa", we update r to 1, ans = min(2, 1+1-1) = 1.\n\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n), since we pass through the array twice.\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) for the suffix array\n\n# Code\n```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n suffix = [-1]*len(s) #last index of t that is not accounted for at i in s\n r = len(t)-1\n for i in reversed(range(len(s))): \n suffix[i] = r \n if 0 <= r and s[i] == t[r]: \n r -= 1\n # we know things after r are already a substring of s, so at most need to remove r+1 things\n ans = r + 1 \n l = 0 \n for i, ch in enumerate(s): \n # at i, on the right, we need to remove to suffix[i], on the right, we need to remove from l\n if l < len(t) and s[i] == t[l]: \n # t[l] matched with s[i], so for i+1, we don\'t have to remove s[l]\n l += 1\n ans = min(ans, max(0, suffix[i] - l + 1))\n return min(ans, len(t)-l)\n\n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
easy short efficient clean code
|
easy-short-efficient-clean-code-by-maver-ceel
|
\nclass Solution {\npublic:\ntypedef long long ll;\n#define vi(x) vector<x>\nint minimumScore(const string&s, const string&t) {\n ll m=s.size(), n=t.size(),
|
maverick09
|
NORMAL
|
2023-02-12T07:09:21.494984+00:00
|
2023-02-12T07:09:21.495034+00:00
| 31 | false |
```\nclass Solution {\npublic:\ntypedef long long ll;\n#define vi(x) vector<x>\nint minimumScore(const string&s, const string&t) {\n ll m=s.size(), n=t.size(), k=n-1;\n vi(ll)dp(n, -1);\n for(ll l=m-1;l>-1 && k>-1;--l){\n if(s[l]==t[k]){\n dp[k--]=l;\n }\n }\n if(k<0){\n return 0;\n }\n ll ans=k+1;\n for(ll i=0, j=0;i<m && j<n;++i){\n if(s[i]==t[j]){\n for(;k<n && dp[k]<=i;++k);\n ans=max(0LL, min(ans, k - (++j)));\n }\n }\n return ans;\n}\n};\n```
| 0 | 0 |
['C']
| 0 |
subsequence-with-the-minimum-score
|
[Python] Sliding Window Min | 100% TC O(N)
|
python-sliding-window-min-100-tc-on-by-t-exet
|
Intuition\n Describe your first thoughts on how to solve this problem. \nWe can remove whole range from left to right\n\n# Approach\n Describe your approach to
|
tr1ten
|
NORMAL
|
2023-02-12T05:51:30.846178+00:00
|
2023-02-12T05:51:44.191144+00:00
| 70 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can remove whole range from left to right\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTry removing each range and check if remaining string form valid subsequence or not.\nTo do this we need to precompute match indices in string s.\nThen using sliding window (or exhaustive binary search) we can find minimum window size satisfying above condition.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n ns,nt = len(s),len(t)\n pref = [ns]*(nt+1) # occ of char t[i] in s\n suff = [-1]*(nt+1) # occ of char t[i] in reversed s\n pref[0] = -1\n suff[-1] = ns\n ti = 0\n for i in range(ns):\n if(ti>=nt): break\n if(s[i]==t[ti]): \n pref[ti+1] = i;\n ti +=1\n ti = nt-1\n for i in reversed(range(ns)):\n if(ti<0): break\n if(s[i]==t[ti]): \n suff[ti] = i;\n ti -=1\n if(pref[-1]<ns): return 0; # whole subseq t exist in s\n i = 0 # sliding window to find min window size\n res = max(ns,nt)\n for j in range(nt):\n i +=1\n while(i<=j and pref[i]<suff[j+1]): i +=1\n i -=1\n if(pref[i]<suff[j+1]): \n res = min(res,j-i+1)\n return res\n```
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
My Solution
|
my-solution-by-hope_ma-on1d
|
\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n * where `n` is the length of the string `s`\n */\nclass Solution {\n public:\n int minimumScore(co
|
hope_ma
|
NORMAL
|
2023-02-12T05:47:24.125682+00:00
|
2023-02-12T05:47:24.125720+00:00
| 30 | false |
```\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n * where `n` is the length of the string `s`\n */\nclass Solution {\n public:\n int minimumScore(const string &s, const string &t) {\n const int n_s = static_cast<int>(s.size());\n const int n_t = static_cast<int>(t.size());\n int left[n_s];\n memset(left, 0, sizeof(left));\n for (int length_t = 0, i_s = 0; i_s < n_s; ++i_s) {\n if (length_t < n_t && s[i_s] == t[length_t]) {\n ++length_t;\n }\n left[i_s] = length_t;\n }\n \n int right[n_s];\n memset(right, 0, sizeof(right));\n for (int length_t = 0, i_s = n_s - 1; i_s > -1; --i_s) {\n if (length_t < n_t && s[i_s] == t[n_t - length_t - 1]) {\n ++length_t;\n }\n right[i_s] = length_t;\n }\n \n int ret = n_t;\n for (int left_length = 0; left_length < n_s + 1; ++left_length) {\n const int l = left_length == 0 ? 0 : left[left_length - 1];\n const int r = left_length == n_s ? 0 : right[left_length];\n ret = min(ret, max(0, n_t - (l + r)));\n }\n return ret;\n }\n};\n```
| 0 | 0 |
[]
| 0 |
subsequence-with-the-minimum-score
|
Python clean O(n), match prefix and suffix
|
python-clean-on-match-prefix-and-suffix-fl35f
|
Code\npy\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n def scan(s, t):\n ans = [0]\n i = 0\n fo
|
wengh
|
NORMAL
|
2023-02-12T05:34:25.735725+00:00
|
2023-02-12T05:35:08.084374+00:00
| 82 | false |
# Code\n```py\nclass Solution:\n def minimumScore(self, s: str, t: str) -> int:\n def scan(s, t):\n ans = [0]\n i = 0\n for c in s:\n if i < len(t) and t[i] == c:\n i += 1\n ans.append(i)\n return ans\n r1 = scan(s, t)\n r2 = reversed(scan(s[::-1], t[::-1]))\n best = max(map(sum, zip(r1, r2)))\n return max(0, len(t) - best)\n```\n\n# Intuition\nMatch a prefix of `t` to a prefix of `s` and match a suffix of `t` to a suffix of `s`. We want to maximize the sum of the lengths of the prefix and suffix of `t`.\n\n# Approach\n`scan(s, t)` finds, for each prefix of `s`, the longest prefix of `t` such that the prefix of `t` is a subsequence of the prefix of `s`. We scan once forwards to get `r1` and once backwards to get `r2`.\nNow, for any index `j` we can split `s` to a prefix and a suffix. `t[:r1[j]]` is the longest prefix that matches the prefix `s[:j]` and `t[r2[j]:]` is the longest suffix that matches the suffix `s[j:]`. Then, `r1[j] + r2[j]` is the total length of prefix and suffix so `len(t) - r1[j] + r2[j]` is the best score if we split `s` at `j`.\n\n# Example\n\n```\ns: "abacaba"\nt: "bzaa"\nr1: [0, 0, 1, 1, 1, 1, 1, 1]\nr2: [2, 2, 2, 2, 2, 1, 1, 0]\nlen(t) - r1[j] + r2[j] for each j:\n [2, 2, 1, 1, 1, 2, 2, 3]\nanswer: 1\n```\n\n# Complexity\n- Time complexity:\n$$O(n + m)$$ where $$n, m$$ are the lengths of `s` and `t` respectively\n\n- Space complexity:\n$$O(n)$$ where $$n$$ is the length of `s`
| 0 | 0 |
['Python3']
| 0 |
subsequence-with-the-minimum-score
|
Minimum Subarray Deletion to Form a Subsequence
|
minimum-subarray-deletion-to-form-a-subs-blir
|
Intuition\nThe problem statement mentions finding the minimum length of a subarray of one string (S) that needs to be deleted to make it a subsequence of anothe
|
BoydBLever
|
NORMAL
|
2023-02-12T05:23:59.004877+00:00
|
2023-02-12T05:23:59.004909+00:00
| 79 | false |
# Intuition\nThe problem statement mentions finding the minimum length of a subarray of one string (S) that needs to be deleted to make it a subsequence of another string (T).\n\nOne approach to solve this problem is to use binary search. We can start with the length of T as the upper limit and 0 as the lower limit. In each iteration of binary search, we check if a subarray of length m (the midpoint of the current lower and upper limits) can be deleted from S to make it a subsequence of T.\n\nTo check if a subarray of length m can be deleted, we can use two pointers to traverse both the arrays S and T. We can use the first pointer to traverse T and keep track of the positions of each character of T in S. Then, we use the second pointer to traverse S in reverse and check if the subarray of length m can be deleted such that T remains a subsequence of S.\n\nBased on the result of the check, we can adjust the lower and upper limits of binary search accordingly and continue the search until the lower limit is greater than the upper limit.\n\nThe final answer would be hi + 1, where hi is the upper limit after the binary search.\n\n# Approach\nThe algorithm is a binary search solution for finding the minimum length of a subarray of one string that needs to be deleted to make it an subsequence of another string.\n\n# Complexity\n- Time complexity:\nThe time complexity of this algorithm is O(n log n), where n is the length of the string T.\n\nThe binary search portion of the algorithm takes O(log n) time for each iteration, and the check function takes O(n) time, so the overall time complexity is O(n log n).\n\n- Space complexity:\nThe space complexity of this algorithm is O(n).\n\nThe main source of space consumption in this algorithm is the pos array, which stores the positions of characters of T in S. The size of this array is n, where n is the length of T, so the space complexity is O(n).\n\n# Code\n```\n/**\n * @param {string} s\n * @param {string} t\n * @return {number}\n */\nvar minimumScore = function(S, T) {\n let s = S.split(\'\'), t = T.split(\'\');\n let lo = 0, hi = T.length;\n while (lo <= hi) {\n let m = Math.floor((lo + hi) / 2);\n if (check(s, t, m)) hi = m - 1;\n else lo = m + 1;\n }\n return hi + 1;\n};\n\nvar check = function(s, t, len) {\n let t_length = t.length, n = s.length;\n if (len >= t_length) return true; //delete whole t array\n let pos = new Array(t_length).fill(1000000000); //Greedy left matching\n let t_left_index = 0;\n for (let i = 0; i < n; i++) {\n if (t_left_index === t_length) break;\n if (t[t_left_index] === s[i]) {\n pos[t_left_index] = i;\n t_left_index++;\n }\n }\n if (t_left_index >= t_length - len) return true; //we can delete right subarray of length len\n let right_index_of_s = n - 1;\n for (let rp = t_length - 1; rp >= len; rp--) {\n while (right_index_of_s >= 0 && s[right_index_of_s] !== t[rp]) right_index_of_s--;\n if (right_index_of_s === -1) return false;\n let lp = rp - len - 1;\n if (lp === -1 || pos[lp] < right_index_of_s) return true;\n right_index_of_s--;\n }\n return false;\n};\n\n\n```
| 0 | 0 |
['JavaScript']
| 0 |
subsequence-with-the-minimum-score
|
[Python 3] beats 100%, O(n)
|
python-3-beats-100-on-by-intellicode-al4i
|
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem can be rephrased as, what is the minimum length of a contiguous substring t
|
intellicode
|
NORMAL
|
2023-02-12T05:23:34.781413+00:00
|
2023-02-12T05:23:34.781450+00:00
| 66 | false |
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem can be rephrased as, what is the minimum length of a contiguous substring that can be taken out to make T a generic substring of S.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n\n# Code\n```\nclass Solution:\n def minimumScore(self, S: str, T: str) -> int:\n lS,lT = len(S),len(T)\n setS,setT = set(S),set(T)\n setTMS = setT-setS\n \n s = 0\n listL = []\n for t in T:\n if t in setTMS: break\n while s<lS and S[s]!=t:\n s += 1\n if s==len(S): break\n listL.append(s)\n s += 1\n if len(listL) == lT: return 0\n \n s = lS-1\n listR = []\n for t in T[::-1]:\n if t in setTMS: break\n while s>=0 and S[s]!=t:\n s -= 1\n if s==-1: break\n listR.append(s)\n s -= 1\n listR = listR[::-1]\n if listL and listR and listL[-1]<listR[0] or not listL or not listR:\n return lT-len(listR)-len(listL)\n \n l = len(listL)-1\n retV = lT - max(len(listL), len(listR))\n for i,r in enumerate(listR[::-1]):\n while l>=0 and listL[l]>=r:\n l -= 1\n if l==-1: break\n retV = min(retV, lT-i-1-l-1)\n return retV\n \n \n \n\n```
| 0 | 0 |
['Python3']
| 0 |
minimum-cost-to-set-cooking-time
|
[Python3, Java, C++] Combinations of Minutes and Seconds O(1)
|
python3-java-c-combinations-of-minutes-a-fxcs
|
Explanation: \n The maximum possible minutes are: targetSeconds / 60\n Check for all possible minutes from 0 to maxmins and the corresponding seconds\n cost fun
|
tojuna
|
NORMAL
|
2022-02-05T16:00:29.584074+00:00
|
2022-02-06T08:35:31.588597+00:00
| 6,538 | false |
**Explanation**: \n* The maximum possible minutes are: `targetSeconds` / 60\n* Check for all possible minutes from 0 to `maxmins` and the corresponding seconds\n* `cost` function returns the cost for given minutes and seconds\n* `moveCost` is added to current cost if the finger position is not at the correct number\n* `pushCost` is added for each character that is pushed\n* Maintain the minimum cost and return it\n\n*Note*: We are multiplying `mins` by 100 to get it into the format of the microwave\nLet\'s say `mins` = 50,`secs` = 20\nOn the microwave we want 5020\nFor that we can do: 50 * 100 + 20 = 5020\n<iframe src="https://leetcode.com/playground/eJoNqmaV/shared" frameBorder="0" width="780" height="420"></iframe>\n\nOn further inspection we can deduce that we only really have 2 cases:\n`maxmins`, `secs`\n`maxmins - 1`, `secs + 60`\n<iframe src="https://leetcode.com/playground/VYzZV9Nh/shared" frameBorder="0" width="780" height="370"></iframe>\n\nSince maximum length of characters displayed on microwave = 4, `Time Complexity = O(1)`
| 116 | 2 |
['C', 'Java', 'Python3']
| 14 |
minimum-cost-to-set-cooking-time
|
Two Choices
|
two-choices-by-votrubac-4gxt
|
We have only two choices:\n1. Punch minutes and seconds as is,\n2. or punch minutes - 1 and seconds + 60.\n\nWe just need to check that the number of minutes an
|
votrubac
|
NORMAL
|
2022-02-05T18:03:33.971772+00:00
|
2022-02-05T19:47:43.280224+00:00
| 4,074 | false |
We have only two choices:\n1. Punch `minutes` and `seconds` as is,\n2. or punch `minutes - 1` and `seconds + 60`.\n\nWe just need to check that the number of minutes and seconds is valid (positive and less than 99).\n\nFor example, for `6039` seconds, we can only use the second option (`99:99`), as the first option is invalid (`100:39`).\n\n**C++**\n```cpp\nint minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {\n auto cost = [&](int pos, int m, int s){\n if (min(m, s) < 0 || max(m, s) > 99)\n return INT_MAX;\n int res = 0;\n for (auto digit : to_string(m * 100 + s)) {\n res += pushCost + (pos == digit - \'0\' ? 0 : moveCost);\n pos = digit - \'0\';\n }\n return res;\n };\n int m = targetSeconds / 60, s = targetSeconds % 60;\n return min(cost(startAt, m, s), cost(startAt, m - 1, s + 60));\n}\n```
| 76 | 4 |
['C']
| 21 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.