C++: Normal Problem

Thought Process

The problem requires us to transform a given string by swapping specific characters and then reversing the result. Specifically, we need to replace every 'p' with 'q' and vice versa. After processing the entire string, we reverse it to get the final output.

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

void solve()
{
    string originalString;
    string ansString;
    cin >> originalString;
    for (int i = 0; i < originalString.size(); i++)
    {

        if (originalString[i] == 'p')
            ansString.push_back('q');
        else if (originalString[i] == 'q')
            ansString.push_back('p');
        else
            ansString.push_back(originalString[i]);
    }
    reverse(ansString.begin(), ansString.end());
    cout << ansString << endl;
}

int main()
{

    int testCases;
    cin >> testCases;
    while (testCases--)
    {
        solve();
    }
}

Code Complexity

Time Complexity: O(n)

The algorithm processes each character of the string once, making it linear in time complexity.

Space Complexity: O(n)

The algorithm uses additional space to store the transformed string, which is proportional to the input size.

Code copied!