Palindrome problem - What am I doing wrong Here?

Problem statement: You are given a binary string S and an integer K. In one operation, you can pick any bit and flip it, i.e turn 0 to 1 or 1 to 0. Can you make the string S a palindrome using exactly K operations?

Print YES if this is possible, and NO if it is not.

Input Format The first line of input contains one integer T, denoting the number of test cases. The description of T test cases follows. Each test case consists of two lines of input. The first line of each test case contains two space-separated integers N and K, denoting the length of the binary string and the number of operations to be performed. The second line contains the binary string S. Output Format For each test case, print the answer on a new line — YES if the S can be made a palindrome using exactly K operations, and NO otherwise.

You may print each character of YES and NO in either uppercase or lowercase (for example, yes, yEs, Yes will all be considered identical).

My solution:

T = int(input())
for i in range(T):
    N,K = map(int,input().split())
    S = input()
    counter = 0
    for i in range(int(len(S)/2)):
        if S[i] == S[-1-i]:
            continue
        else:
            counter = counter + 1
    if counter == K:
        print("Yes")
    else:
        print("No")

But on submission, it shows the wrong answer, and upon custom input, it shows correct output, can someone point out what am I doing wrong?

Upvotes: 0

Views: 1068

Answers (3)

ANURAG DVS
ANURAG DVS

Reputation: 1

#include <bits/stdc++.h> using namespace std;

int main(){
    int t,n,k,i,j,c;
    cin>>t;
    while(t--){
        cin>>n>>k;
        char str[n];
        for( i=1;i<=n;i++){
            cin>>str[i];
        }
        str[0]=i;
        str[n-1]=j;
        while(i<=j){
            if(str[i++]!=str[j--]){
                c--;
            }
            
        }
        if(c=k){
            cout<<"YES"<<endl;
        }
        else{
            cout<<"NO"<<endl;
        }
        
        
    }
    return 0;
}

Upvotes: 0

Frank Yellin
Frank Yellin

Reputation: 11283

May be another problem. Remember that the question is "Can you convert it to a palindrome in K steps", not "Can you convert it to a palindrome in a minimum of K steps".

If you've discovered you can do it in fewer than K steps, you have to figure out if you can do it in K steps. For even palindromes, you can flip pairs of bits, or just flip the same bit an even number of times. For odd palindromes, you can just flip the center bit over and over.

Upvotes: 1

Daniel Tomer
Daniel Tomer

Reputation: 96

Maybe because you're using len(S) instead of N

Upvotes: 0

Related Questions