CLOSE
🛠️ Settings

Problem Statement

Given a string of ASCII characters, invert the case of every alphabet character:

  • Convert lowercase letters to uppercase.
  • Convert uppercase letters to lowercase.
  • Non-alphabet characters remain unchanged.

Constraints:

  • 1 ≤ length ≤ 10^5
  • Input contains ASCII characters only.

Examples

Example 1:

Input: "HeLLo123"
Output: "hEllO123"

Example 2:

Input: "CPP is FUN!"
Output: "cpp IS fun!"

Different Approaches

1️⃣ Using Standard Library Functions

Intuition:

Use islower() and isupper() from <cctype> to check the case, and then apply toupper() or tolower() accordingly.

Code:

#include <iostream>
#include <cctype>
using namespace std;

string invertCase(string str) {
    for (char &ch : str) {
        if (islower(ch))
            ch = toupper(ch);
        else if (isupper(ch))
            ch = tolower(ch);
    }
    return str;
}

int main() {
    string input = "HeLLo123";
    cout << invertCase(input);  // Output: hEllO123
}

Complexity Analysis:

  • Time Complexity:O(n)
  • Space Complexity:O(1)

2️⃣ Using ASCII Trick

Intuition:

In ASCII:

  • 'a''A' differ by 32 → You can add or subtract 32 based on the case.

Code:

#include <iostream>
using namespace std;

string invertCase(string str) {
    for (char &ch : str) {
        if (ch >= 'a' && ch <= 'z')
            ch -= 32;
        else if (ch >= 'A' && ch <= 'Z')
            ch += 32;
    }
    return str;
}

int main() {
    string input = "CppRocks!";
    cout << invertCase(input);  // Output: cPPrOCKS!
}

Complexity Analysis:

  • Time Complexity:O(n)
  • Space Complexity:O(1)

3️⃣ Bitwise XOR Trick

CharacterASCIIBinary
'A'6501000001
'a'9701100001
' '3200100000

Now try:

'A' ^ ' ' = 01000001 ^ 00100000 = 01100001 = 'a'
'a' ^ ' ' = 01100001 ^ 00100000 = 01000001 = 'A'

It toggles bit 5 – which is the only difference between uppercase and lowercase letters.

Limitation:

Only works reliably for:

  • 'A' to ‘Z’
  • 'a' to ‘z’

If used on non-letter characters, it may result in gibberish or unexpected output.

Code:

#include <iostream>
using namespace std;

string invertCase(string str) {
    for (char &ch : str) {
        if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
            ch = ch ^ ' ';  // Same as ch ^ 32
        }
    }
    return str;
}

int main() {
    string input = "CppRocks123!";
    cout << invertCase(input);  // Output: cPPrOCKS123!
}

Complexity Analysis:

  • Time Complexity:O(n)
  • Space Complexity:O(1)

Leave a comment

Your email address will not be published. Required fields are marked *