Title: Help Needed – One Test Case Failing in “Transform String” Problem
Message:
Hi everyone,
I’m working on the “Transform String” problem and implemented the following approach, but one test case is failing. Could someone help me identify the issue?
My Approach:
Finding the subsequence:
I iterate through s1 from right to left and try to match s2 as a subsequence.
I store matched positions in an array ch.
If s2 is not a subsequence of s1, I return -1.
Calculating the cost:
I iterate through s1 again.
If a character is part of s2, I increase a counter cr.
If it is not part of s2, I add cr to the total cost.
Issue:
My solution passes most test cases but fails one.
The constraints are large (|A|, |B| ≤ 2 × 10⁵), so efficiency matters.
Maybe I have an off-by-one error or a miscalculated cost?
Any help in debugging or identifying edge cases I might have missed would be appreciated. Thanks in advance!
code:
//------------------------------------------------------------------
include <bits/stdc++.h>
define ll long long
define read_vec(v, n) for(int i=0; i<n; i++){ cin >> v[i];}
define all(x) x.begin(), x.end()
define rev(x) x.rbegin(), x.rend()
define vll vector
define pb push_back
define minii *min_element
define maxii *max_element
using namespace std;
//------------------------------------------------------------------
ll power(ll a,ll b)
{
ll temp,mod=1000000007;
if(b==0)return 1;
temp=power(a,b/2);
if(b%2==0)
return (temptemp)%mod;
else
return (atemp*temp)%mod;
}
bool isPrime(int n)
{
static int i = 2;
// corner cases
if (n <= 1) {
return false;
}
if(n<=3){
return true;
}
// Checking Prime
if (n%2==0||n%3==0)
return false;
for (int i = 5; i*i<=n; i+=6)
{
if(n%i==0||n%(i+2)==0){
return false;
}
}
return true;
}
//write code here
void solve()
{
string s1,s2;
cin>>s1>>s2;
int ch[s1.size()]={0};
int l=s1.size()-1;
int r=s2.size()-1;
while(l>=0)
{
if(s1[l]==s2[r] )
{
ch[l]=1;
r–;
}
l–;
}
if(r>=0)
{
cout<<-1<<endl;
return;
}
int cr=1,ans=0;
for(int i=0;i<s1.size();i++)
{
if(ch[i]==1)
{
cr++;
}
else
{
ans+=cr;
}
}
cout<<ans<<endl;
}
//main function
int main()
{
cin.tie(NULL);
cout.tie(NULL);
int t;
cin>>t;
while(t–)
{
solve();
}
}
link:Transform String Practice Coding Problem