709. To Lower Case
EasyView on LeetCode
Time: O(n)
Space: O(n)
Problem Overview
Convert every uppercase letter in the string to lowercase and leave all other characters unchanged.
Advertisement
Intuition
Convert every uppercase letter in the string to lowercase and leave all other characters unchanged. ASCII uppercase A–Z are codes 65–90; lowercase a–z are 97–122 — the offset is 32. In interviews you can mention `ToLowerCase()` in C# or implement the manual loop to show you understand character codes.
Algorithm
- 1Allocate a result builder (or char array) the same length as the input.
- 2For each character c: if c is between 'A' and 'Z', append (char)(c + 32).
- 3Otherwise append c unchanged (digits, symbols, already-lowercase letters).
- 4Return the built string.
Example Walkthrough
Input: s = "Hello"
- 1.H is uppercase → h (72 + 32 = 104).
- 2.e, l, l, o are already lowercase → unchanged.
Output: "hello"
Common Pitfalls
- •Do not subtract 32 — that would upper-case lowercase letters incorrectly.
- •Non-letters must pass through unchanged (spaces, punctuation, digits).
- •Unicode letters outside ASCII need culture-aware APIs; this problem assumes ASCII.
709.cs
C#
// Approach: Iterate over the char array; subtract the ASCII difference
// ('A'-'a') from each uppercase letter.
// Time: O(n) Space: O(n)
public class Solution
{
public string ToLowerCase(string s)
{
int diff = 'A' - 'a';
char[] ans = s.ToCharArray();
for (int i = 0; i < ans.Length; ++i)
{
if (ans[i] >= 'A' && ans[i] <= 'Z')
ans[i] -= (char)diff;
}
return new string(ans);
}
}Advertisement
Was this solution helpful?