Can someone help me with TRISWP (Triangular Swaps)

Can someone help me to know what I’m doing wrong?
Triangular Swaps Practice Coding Problem - CodeChef

I tried running the array, doing the swaps, and storing the possibilites into a set, then print the set length. I tried in both C++ and Python, but I’m getting Runtime Error, so it’s likely I’m doing something messy with the Strings.

I debugged with N = 3, and seemed to work, but anyway, here are the codes.

Python:

for T in range(int(input())):
    
    N = int(input())
    S = input().strip()

    Set  = set()
    for i in range(N-2):
        local = S[i+1] + S[i+2] + S[i]
        local = S[:i] + local + S[i+3:]
        Set.add(local)
        
    print(len(Set))
    

C++:

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

void solve(){

    ll N;
    cin >> N;
    
    string str;
    cin >> str;

    char* S = (char*)str.c_str();

    unordered_set<string> Set;
    for(ll i=0; i<N-2; i++){
        char a = S[i];
        char b = S[i+1];
        char c = S[i+2];
        
        S[i]   = b;
        S[i+1] = c;
        S[i+2] = a;
        
        string local = S;
        Set.insert(local);
        
        S[i]   = a;
        S[i+1] = b;
        S[i+2] = c;
    }
    
    cout << Set.size() << "\n";

}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	int T;

	cin >> T;
	while(T--){
		solve();
	}
}