What is wrong in this SWAPCW code?

I have written this code in starter30 but is giving me an error for after submission test cases.
Question is : SWAPCW

#include <iostream>
using namespace std;

bool isSorted(string s,int n){
    for(int i = 0;i < n-1; i++){
        if(s[i]>s[i+1]){
            return false;
        }
    }
    return true;
}

bool swap(string str,int n,int i){
    char temp;
    temp = str[i];
    str[i] = str[n-1-i];
    str[n-1-i] = temp;
    return isSorted(str,n);
}

int main() {
	// your code goes here
	int t;
	cin >> t;
	int n;
	string str;
	while(t--){
	    cin >> n;
	    cin >> str;
	    
	    bool ans;
	    int count = 0;
	    if(!isSorted(str,n)){
    	    for(int i = 0;i < n/2;i++){
                ans = swap(str,n,i);
    	        if(ans){
    	            cout << "YES" << endl;
    	            break;
        	    }
        	    count++;
    	    }
    	    if(count==n/2){
    	            cout << "NO" << endl;
	       }
	    }else
	        cout << "YES" << endl;
	}
	return 0;
}

You have done such a great job but there is two small things that you have to change in the code.

  • First, you have to put if condition before you make the swap.
    to make sure that the elements you swap is not already in the right place
    what I mean that( in your code you swap every element even the element in the right place that don’t need to be swapped.)

The correct function
->>

bool swap(string str,int n,int i){
if( str[i] > str[n-1-i]) //if condiition
{
char temp;
temp = str[i];
str[i] = str[n-1-i];
str[n-1-i] = temp;
}
return isSorted(str,n);
}

  • The second point in function declaration you have to send the string by address
    like that →

bool swap(string &str,int n,int i){ //string &str (by address)
{
//The rest of the function body
}

I got your suggestion but it will only reduce the time complexity of the code. The real problem is I am getting an error of a wrong answer after submitting the code.

just Apply those changes it will give you AC