Last Updated: June 7, 2026
Every letter in the new string has its case flipped, while everything that is not a letter stays untouched. A digit like 5, a space, or a punctuation mark passes through unchanged.
Strings are immutable in many languages, so you cannot edit the original characters in place. You build the result one character at a time, deciding for each whether it is uppercase, lowercase, or something else, then appending the correct version.
The case flip should avoid a long table of conversions. Listing every pair, A to a, B to b, and so on, is 52 cases and easy to get wrong. The numeric encoding of characters handles every letter with one rule instead.
0 <= s.length <= 1000 → The string can be empty, in which case the result is empty too. The code must run cleanly when there is nothing to flip.Every character maps to a number through the ASCII encoding. A is 65 and a is 97, a gap of exactly 32, and that same gap holds for every letter: B is 66 and b is 98, Z is 90 and z is 122.
This regular spacing is what you exploit. Add 32 to make an uppercase letter lowercase, subtract 32 to make a lowercase letter uppercase. No lookup table is needed: check whether the character is upper or lower, then adjust by 32 in the right direction. Any non-letter is copied straight into the result.
A to Z, add 32 to its code to get the lowercase version.a to z, subtract 32 to get the uppercase version.Take the string "Hi 9!". At index 0 the character is H, uppercase, so adding 32 turns it into h, giving "h". At index 1 the character is i, lowercase, so subtracting 32 turns it into I, giving "hI". At index 2 the space is not a letter, so it is copied unchanged, giving "hI ". At index 3 the digit 9 is copied unchanged, giving "hI 9". At index 4 the punctuation mark ! is copied unchanged, giving "hI 9!". Only the two letters changed.