To Lower Case(#709)

Category: String, Foundation

๐Ÿงฉ 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

We manually convert each character to lowercase using ASCII values.

โ€ข Uppercase characters (Aโ€“Z) have ASCII values from 65 to 90. Lowercase characters (aโ€“z) are from 97 to 122. The difference is 32.

โ€ข We loop through each character in the string:

โ€ข If it's an uppercase letter, we add 32 to its ASCII value to get the lowercase version.

โ€ข If it's not uppercase, we keep it as it is.

This teaches how character codes work in string manipulation.

๐Ÿ’ป Code

// ๐Ÿ”น Manual ASCII-based approach
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)
// 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