To Lower Case (LeetCode 709): Solution and Explanation
Given a string s, return it with every uppercase English letter turned into the matching lowercase letter, leaving every other character alone.
Intuition
Every language has a built-in for this, so the interesting part is how it works underneath. In ASCII, 'A'..'Z' occupy codes 65 to 90 and 'a'..'z' occupy 97 to 122, so each lowercase letter is exactly 32 above its uppercase twin.
32 is a power of two. In binary, 'A' is 0100 0001 and 'a' is 0110 0001: the only difference is bit 5. Lowering a letter means switching that one bit on, which is code | 32.
The OR must only touch characters in the range 'A'..'Z'. Applied to '@' (64) it would give ` '' `` (96), and applied to digits or punctuation it would corrupt them, so the range check comes first.
Approach: Set bit 5 on uppercase letters
- Create an output buffer.
- For each character
ch: if'A' <= ch <= 'Z', append the character with codeord(ch) | 32; otherwise appendch. - Join the buffer and return it.
Step-by-step example
s = "Hello"
'H'has code 72 (0100 1000). It is in 65..90, so OR it with 32 to get 104 (0110 1000), which is'h'.'e'has code 101. It is not in 65..90, so it is copied unchanged.'l','l'and'o'are already lowercase and are copied.- The output is
"hello".
Code: Python, Java, C++
1class Solution:
2 def toLowerCase(self, s: str) -> str:
3 out = []
4 for ch in s:
5 if 'A' <= ch <= 'Z':
6 out.append(chr(ord(ch) | 32))
7 else:
8 out.append(ch)
9 return ''.join(out)1class Solution {
2 public String toLowerCase(String s) {
3 StringBuilder out = new StringBuilder();
4 for (char ch : s.toCharArray()) {
5 if (ch >= 'A' && ch <= 'Z') {
6 out.append((char) (ch | 32));
7 } else {
8 out.append(ch);
9 }
10 }
11 return out.toString();
12 }
13}1class Solution {
2public:
3 string toLowerCase(string s) {
4 string out;
5 for (char ch : s) {
6 if (ch >= 'A' && ch <= 'Z') {
7 out += (char) (ch | 32);
8 } else {
9 out += ch;
10 }
11 }
12 return out;
13 }
14};Time and space complexity
O(n)
Each character is checked and appended once.
O(n)
The output string has the same length as the input. In Go or C++ you can lower the bytes of a copy in place, but the copy is still O(n).
Other approaches
Built-in lowercase (time O(n), space O(n))
Call s.lower(), s.toLowerCase() or strings.ToLower(s). This is what you would write in production; it also handles non-ASCII letters, which this problem does not need.
Add 32 instead of OR (time O(n), space O(n))
chr(ord(ch) + 32) gives the same answer for uppercase letters because bit 5 is always 0 in 65..90. The OR form makes the bit idea explicit and is harmless if applied twice.
Common mistakes
- Applying
| 32or+ 32to every character. Symbols such as'@'and'['change, and digits turn into other symbols. - Checking
ch.isalpha()instead of the uppercase range, which then adds 32 to letters that are already lowercase. - Building the result with repeated string concatenation in a language with immutable strings. It works for 100 characters but is quadratic in general.
Frequently asked questions
Why does OR with 32 work?
Uppercase codes 65 to 90 all have bit 5 equal to 0, and the matching lowercase codes 97 to 122 are the same numbers with that bit set to 1. OR with 32 sets exactly that bit.
How would I convert to uppercase instead?
Clear the same bit for characters in 'a'..'z': code & ~32, or subtract 32.
Is using the built-in allowed in an interview?
Usually yes, but expect a follow-up asking you to implement it, which is the loop shown here.
What is the time and space complexity?
O(n) time for one pass and O(n) space for the output string.