To Lower Case — Solution in Python, Java & C++
To Lower Case solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at Amazon and TCS.
To Lower Case is an easy coding problem on strings, asked in Amazon, TCS and Infosys interviews.
- Difficulty: Easy
- Topics: Strings
- Asked at: Amazon, TCS, Infosys
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given a string s, return it with every uppercase letter converted to lowercase. All other characters are left unchanged.
Solve it without relying on a built-in case-conversion routine.
Example 1
Input: s = "Hello"
Output: hello
Example 2
Input: s = "here"
Output: here
Explanation: Already lowercase, so nothing changes.
Example 3
Input: s = "LOVELY"
Output: lovely
Constraints
1 <= s.length <= 100s consists of printable ASCII characters.
Hints for To Lower Case
Hint 1
In ASCII,
'A'is 65 and'a'is 97 — a fixed distance of 32.Hint 2
Only characters in the range
'A'..'Z'need shifting.Hint 3
Leave digits, spaces and punctuation exactly as they are.
How to solve To Lower Case
ASCII places the uppercase block immediately before the lowercase block with a constant gap of 32, so case conversion is a single addition on the qualifying characters.
Approach
- Walk the string one character at a time.
- If the character lies between
'A'and'Z', add 32 to its code point. - Otherwise copy it through untouched.
Why it works
'a' - 'A' == 32 holds for every letter in ASCII, so the same offset works across the whole alphabet — no lookup table needed.
Complexity
- Time —
O(n) - Space —
O(n) for the output
Pitfalls
- Adding 32 unconditionally corrupts digits and punctuation.
- Using the bitwise trick
c | 32also mangles non-letters, so it still needs the range guard.
Reference solution
Python
def toLowerCase(s: str) -> str:
out = []
for c in s:
if 'A' <= c <= 'Z':
out.append(chr(ord(c) + 32))
else:
out.append(c)
return ''.join(out)Java
public static String toLowerCase(String s) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c >= 'A' && c <= 'Z') sb.append((char) (c + 32));
else sb.append(c);
}
return sb.toString();
}C++
string toLowerCase(string s) {
string out;
for (char c : s) {
if (c >= 'A' && c <= 'Z') out += (char) (c + 32);
else out += c;
}
return out;
}JavaScript
var toLowerCase = function(s) {
let out = "";
for (let i = 0; i < s.length; i++) {
const code = s.charCodeAt(i);
if (code >= 65 && code <= 90) out += String.fromCharCode(code + 32);
else out += s.charAt(i);
}
return out;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 515 strings problems · the whole catalogue
Learn the technique: Strings