Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code : Erase First or Second Letter

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

long long solve(string &str) {
    int n = str.length();

    map<int, vector<int>> occ;
    for (int i = 0; i < n; i++) {
        occ[str[i]].push_back(i);
    }

    long long ans = 0;
    for (int i = n - 1; i >= 1; i--) {
        ans += 1;
        for (char ch = 'a'; ch <= 'z'; ch++) {
            if (ch == str[i - 1]) {
                continue;
            }
            auto &vec = occ[ch];
            if (vec.empty()) {
                continue;
            }
            if (vec[0] < i) {
                ans += 1;
            }
        }
    }
    ans += 1;
    for (char ch = 'a'; ch <= 'z'; ch++) {
        auto &vec = occ[ch];
        if (!vec.empty()) {
            ans += 1;
        }
    }
    ans -= 1;
    return ans;
}

int main() {
    int t;
    cin >> t;
    for (int zz = 0; zz < t; zz++) {
        int n;
        cin >> n;
        string str;
        cin >> str;
        cout << solve(str) << "\n";
    }
    return 0;
}