You are given a string s. Return a copy of it where each capital letter from A to Z has been swapped for its small-letter form. Every other character, such as digits, spaces, punctuation or letters that are already small, stays exactly as it is.
The interviewer usually wants to see how the conversion works, not just a call to a built-in method.
Example 1
Input: s = "QuIz!" Output: "quiz!" Why: Q and I become q and i; u, z and ! stay
2 more examples and the constraints
Example 2
Input: s = "room 42" Output: "room 42" Why: no capitals, so nothing changes
Example 3
Input: s = "ABC" Output: "abc" Why: every letter is a capital
Constraints
- 1 ≤ length of s ≤ 100
- s holds printable ASCII characters only (codes 32 to 126)
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Built-in lowercaseO(n)
- ASCII offset by handO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for a 100-character string | Verdict |
|---|---|---|---|
| Built-in lowercase | O(n) | Fine at work; mention it first | |
| ASCII offset by hand | O(n) | Best; shows you know the encoding |
n = length of s. Both do the same amount of work; the second explains it.
Edge cases to test
- Already lowercase. "room 42" comes back unchanged.
- All capitals. "ABC" becomes "abc".
- Symbols next to the letter range.
@(64) and[(91) sit just outside 65 to 90 and must not change. - Single character. "Z" becomes "z"; "!" stays "!".
Common mistakes
- Adding 32 to every character, which turns digits and punctuation into other symbols.
- Using < 90 instead of ≤ 90, so Z is left as a capital.
- Subtracting 32 instead of adding it: that goes from small letters to capitals.
How to talk through it
- 1Clarify. Is the input plain ASCII? Should only A to Z change?
- 2Mention the built-in. Say you would call lower() in real code, then offer to do it by hand.
- 3Explain the offset. Capitals are 65 to 90, small letters 97 to 122: a fixed gap of 32.
- 4Code the loop. Check the range, add 32 inside it, copy everything else.
- 5Test out loud. Run a string with @, [, Z and a digit to show the range check works.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?