Problem 709

Abstract / Summary

Implement a function that converts all uppercase letters in a given string to lowercase and returns the resulting string.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0709.cpp

class Solution {
public:
    string toLowerCase(string s) {
        for (auto& c : s)
            if (c >= 'A' && c <= 'Z')
                c += 'a' - 'A';

        return s;
    }
};
10 lines | 194 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 84% (600k+ submissions).

Typical patterns to solve this problem:
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single public method toLowerCase. The method receives a mutable copy of a std::string and converts every uppercase ASCII character to its lowercase counterpart, returning the transformed string. The algorithm operates directly on the input string, modifying it in place, which eliminates the need for auxiliary storage.

Core Logic

The heart of the conversion is a range-based for loop that iterates over each character by reference. Inside the loop a conditional checks whether the current character falls within the ASCII range for uppercase letters ('A' to 'Z'). When the condition is true, the character is shifted to its lowercase form by adding the difference between 'a' and 'A'. The relevant fragment is:

for (auto& c : s)
    if (c >= 'A' && c <= 'Z')
        c += 'a' - 'A';

Because c is bound as a reference (auto&), the modification directly updates the original string buffer. After the loop completes, the method returns the now-lowercased string:

return s;

Edge-Case Handling

The code implicitly handles several edge conditions without additional branches:

  • Empty string - The range-based loop simply does not execute, and the empty string is returned unchanged.
  • Non-alphabetic characters - Characters outside the 'A'-'Z' range, such as digits, punctuation, or already lowercase letters, bypass the conditional and remain untouched.
  • Mixed case strings - Only the uppercase portion is transformed; any existing lowercase characters are preserved, yielding a correctly lowercased result for any combination.
  • String containing only uppercase letters - Every character satisfies the condition, so the entire buffer is transformed in a single pass.

Performance Characteristics

The algorithm exhibits a tight inner loop with a single conditional and an arithmetic operation. By operating in place, it avoids allocating extra memory, which reduces heap pressure and improves cache locality. The use of a range-based loop with a reference iterator eliminates the overhead of copying characters during iteration. The constant expression 'a' - 'A' is computed at compile time, so the addition inside the loop is a simple integer addition. This combination yields a highly efficient transformation that scales linearly with the length of the input string while maintaining minimal runtime overhead.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a magical box that holds a line of letters. This computer program acts like a friendly helper who walks down the line one letter at a time to check if each one is a big capital letter. If the helper finds a big letter, it gently swaps it for a matching tiny lowercase version. The helper keeps doing this task until every single letter in the line is small and cozy. Once the work is all finished, the line of letters is ready to go.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 8.19 | σ = 0.98

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster Python Java C++ TS
WalkCCC Python Java C++
leetcode.ca Python Java C++ Go C Rust TS
LeetcodeHelp Python Java C++
Progiez Python Java C++
github BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
halfrost Go
JoshCrozier JS
keineahnung2345 C++
Krazune C
lkwq007 Python
muhammadfarhankt Go
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C, C++, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
DimitrisJim C
fartem Ruby
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lkwq007 Python
muhammadfarhankt Go
qiyuangong Java
ruoru Rust
suxrobGM C#
varunu28 Java
YuriSpiridonov Python
37 links | 22 authors | 10 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality