Change Case of Each Character in a String

Asked atAmazon
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a string s, write a program to invert the case of each character:

  • Convert **lowercase **letters to uppercase
  • Convert **uppercase **letters to lowercase
  • Leave non-alphabetic characters unchanged

Input: s = "javA" **Output: **"JAVa" **Explanation: **j → J, a → A, v → V, A → a

Input: s = "take u forward IS Awesome" **Output: **"TAKE U FORWARD is aWESOME" Explanation: All alphabet cases inverted; spaces preserved

**Input: **s = ""

0 <= s.length <= 105 The string may contain:

  • lowercase & uppercase English letters
  • spaces, digits, and special characters

cpp

class Solution {
public:
    string toggleCase(const string& s) {
        // Your code goes here
    }
};

java

class Solution {
    public String toggleCase(String s) {
        // Your code goes here
    }
}

python

class Solution:
    def toggle_case(self, s: str) -> str:
        # Your code goes here

javascript

class Solution {
    toggleCase(s) {
        // Your code goes here
    }
}

csharp

class Solution
{
    public string ToggleCase(string s)
    {
        // Your code goes here
    }
}

go

func toggleCase(s string) string {

}
Stuck? Show a way to structure it+
  1. 01Inspect every character once.
  2. 02Invert only alphabetic case.
  3. 03Leave digits, punctuation, and whitespace unchanged.
  4. 04Build or mutate the output safely.

Reference answer

Then expect these follow-ups

  • How do locale-sensitive case rules complicate this?

    Tests: internationalization

  • How would you mutate a byte buffer in place?

    Tests: representation

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question