algoadvance

Leetcode 709. To Lower Case

Problem Statement

Given a string s, convert it to lowercase. The function should return a new string that contains the same characters as s, but all converted to lowercase.

Example:

You need to implement a function with the following signature:

string toLowerCase(string s);

Clarifying Questions

  1. Q: Can the input string include numbers or special characters?
    • A: Yes, the input string can include any ASCII characters.
  2. Q: Should the function handle empty strings?
    • A: Yes, the function should return an empty string if the input is empty.
  3. Q: Is there a limit to the length of the input string?
    • A: There is no explicit limit mentioned, but it can be assumed it fits within standard constraints (e.g., typical constraints might be up to 10^4 characters).

Strategy

  1. Traversal and Conversion:
    • Traverse each character of the string.
    • For each character, check if it is an uppercase letter (between ‘A’ and ‘Z’).
    • If it is uppercase, convert it to its corresponding lowercase character by adding the difference between ‘a’ and ‘A’ to it.
    • Append the resulting character to a new string.
  2. ASCII Value Utilization:
    • The conversion from uppercase to lowercase can be done using ASCII values:
      • For any uppercase letter ch, its lowercase can be calculated using ch + ('a' - 'A').
  3. Edge Cases:
    • An empty string should be handled by simply returning an empty string.
    • If the string contains non-alphabetic characters (numbers or special characters), they should remain unchanged.

Code

#include <string>

using namespace std;

string toLowerCase(string s) {
    string result;
    for (char ch : s) {
        if (ch >= 'A' && ch <= 'Z') {
            result += ch + ('a' - 'A');
        } else {
            result += ch;
        }
    }
    return result;
}

Time Complexity

This approach ensures that the function efficiently handles the conversion with a straightforward traversal and ASCII value manipulation.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI