Problem Statement

Given a character or a string in uppercase, convert it to its lowercase equivalent.

Constraints:

  • Input may be a single character or a string of length 1 ≤ length ≤ 10^5.
  • Only ASCII characters are considered ('A' to ā€˜Z’).

Examples

Example 1:

Input: 'H'
Output: 'h'

Example 2:

Input: "HELLO"
Output: "hello"

Different Approaches

1ļøāƒ£ Using Standard Library Function tolower()

C++ provides the lower() function in <cctype> that converts to its lowercase form if it's uppercase.

Code:

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

string toLowercase(string str) {
    for (char &ch : str) {
        ch = tolower(ch);
    }
    return str;
}

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

Complexity Analysis:

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

2ļøāƒ£ Using ASCII Conversion

Intuition:

In ASCII:

  • ā€˜A’ = 65, ā€˜a’ = 97 → difference Ā = 32
  • To convert: add 32 to uppercase letters

Code:

#include <iostream>
using namespace std;

string toLowercase(string str) {
    for (char &ch : str) {
        if (ch >= 'A' && ch <= 'Z') {
            ch = ch + 32;
        }
    }
    return str;
}

int main() {
    string input = "WORLD";
    cout << toLowercase(input);  // Output: world
}

Complexity Analysis:

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

3ļøāƒ£ Using Bitwise Trick: ch | ā€˜ ’

Intuition:

In ASCII:

  • BIt 5 distinguishes upper from lowercase.
  • OR-ing with space (' ' = 0x20) sets that bit.

Why It Works?

'A' = 65 -> 0100 0001
'a' = 97 -> 0110 0001
' ' = 32 -> 0010 0000

Notice:
'A' | ' ' = 01000001 | 00100000 = 01100001 = 'a'

So:

  • Any uppercase letter 'A' to 'Z' (ASCII 65–90), when OR'ed with a space ' ', turns into its lowercase equivalent.
  • The space character (' ' = 0x20) sets the 6th bit (bit at position 5, 0-indexed), which distinguishes lowercase from uppercase.

Limitation:

This only works correctly for uppercase alphabetic characters (A–Z).
For non-alphabetic characters, it might produce unintended results.

Code:

#include <iostream>
using namespace std;

string toLowercase(string str) {
    for (char &ch : str) {
        if (ch >= 'A' && ch <= 'Z') {
            ch = ch | ' ';
        }
    }
    return str;
}

int main() {
    string input = "CPP";
    cout << toLowercase(input);  // Output: cpp
}

Complexity Analysis:

  • Time Complexity:O(n)
  • Space Complexity:O(1)
[info title="Note:" type=warning]Only works correctly for uppercase letters. Non-alphabet characters should be left unchanged.[/info]
Buy Me A Coffee

Leave a comment

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