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

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question