To Lower Case - Complete Solution Guide
To Lower Case is LeetCode problem 709, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
Given a string s , return the string after replacing every uppercase letter with the same lowercase letter . Example 1: Input: s = "Hello" Output: "hello" Example 2: Input: s = "here" Output: "here" Example 3: Input: s = "LOVELY" Output: "lovely" Constraints: 1 <= s.length <= 100 s consists of printable ASCII characters.
Detailed Explanation
The problem asks us to convert a given string `s` to lowercase. This means every uppercase letter in the string should be replaced with its corresponding lowercase letter, while all other characters (lowercase letters, numbers, symbols) should remain unchanged. The input is a string `s` consisting of printable ASCII characters, and the output is the modified string with all uppercase letters converted to lowercase. The length of the input string is between 1 and 100 characters inclusive.
Solution Approach
The solutions approach varies depending on the programming language. Python and Java leverage built-in string functions for direct conversion. C and C++ demonstrate manual iteration through the string, checking if each character is an uppercase letter. If it is, it calculates the corresponding lowercase letter by adding the difference between 'a' and 'A' (which is 32) to the character's ASCII value. The C solution modifies the string in place. The C++ solution does the same, making use of a reference to the string's characters.
Step-by-Step Algorithm
- Step 1: Iterate through each character of the input string `s`.
- Step 2: For each character, check if it falls within the ASCII range of uppercase letters ('A' to 'Z').
- Step 3: If the character is an uppercase letter, add 32 (the difference between 'a' and 'A') to its ASCII value to convert it to its lowercase equivalent. This is equivalent to s[i] = s[i] - 'A' + 'a' in C.
- Step 4: If the character is not an uppercase letter, leave it unchanged.
- Step 5: Return the modified string.
Key Insights
- Insight 1: Understanding ASCII representation of characters is crucial. Uppercase and lowercase letters have a consistent difference in their ASCII values.
- Insight 2: In languages like Python and Java, built-in string functions (`lower()` and `toLowerCase()`, respectively) can directly achieve the desired conversion.
- Insight 3: When implementing the conversion manually (as in the C/C++ solutions), efficient in-place modification of the string is preferable to creating a new string if possible to optimize space complexity.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: String.
Companies
Asked at: Infosys.