To Lower Case

(#709), Easy

Category: String

Problem Statement

You're given a string `s`. You need to return the same string, but with every uppercase letter converted to lowercase. All other characters remain unchanged.

Examples

Input: "Hello"

Output: "hello"

Explanation: Only 'H' is uppercase and gets converted.

Input: "here"

Output: "here"

Explanation: All characters are already lowercase.

Input: "LOVELY"

Output: "lovely"

Explanation: All uppercase letters are converted to lowercase.

Approach

Manual ASCII Conversion

  • Initialize an empty string `str` to build the lowercase result.
  • Loop through each character in the input string `s`.
  • Check if the character is uppercase (ASCII between 65 and 90).
  • If yes, convert it to lowercase by adding 32 to its ASCII code.
  • Use `String.fromCharCode()` to convert the code back to a character.
  • Append the converted character to `str`, or append the original character if not uppercase.
  • Return the final string after the loop.
var toLowerCase = function (s) {
  let str = "";

  for (let i = 0; i < s.length; i++) {
    let charCode = s[i].charCodeAt(0);
    if (charCode >= 65 && charCode <= 90) {
      str += String.fromCharCode(charCode + 32);
    } else {
      str += s[i];
    }
  }

  return str;
};

One-Liner Built-In Method

  • Use the built-in `toLowerCase()` method to convert the entire string.
var toLowerCase = function (s) {
  return s.toLowerCase();
};

Complexity

Time: O(n), where n is the length of the string.

Space: O(n), for the result string.

Watch Explanation

📊 Presentation (PPT)

📥 Download PPT

📎 Resources