Code Logo

Toggle Case

Published at25 Jul 2026
Easy 0 views
Like0

Given a string, toggle the case of each alphabetic character: lowercase becomes uppercase and uppercase becomes lowercase. Non-alphabetic characters remain unchanged.

Iterate through each character. If it's uppercase, convert to lowercase. If it's lowercase, convert to uppercase. Otherwise, keep it as-is. This requires checking the case of each character using language-specific case detection methods.

Time complexity is O(n) where n is the string length. Space complexity is O(n) for the result. Each character is processed exactly once.

Edge cases include empty strings, strings with no letters, mixed alphanumeric strings, and already toggled strings.

Example Input & Output

Example 1
Input
"ABC"
Output
"abc"
Explanation

Uppercase to lowercase

Example 2
Input
""
Output
""
Explanation

Empty string

Example 3
Input
"Hello World"
Output
"hELLO wORLD"
Explanation

Toggle case of each letter

Example 4
Input
"123!@#"
Output
"123!@#"
Explanation

Non-letters unchanged

Example 5
Input
"abc"
Output
"ABC"
Explanation

Lowercase to uppercase

Algorithm Flow

Recommendation Algorithm Flow for Toggle Case
Recommendation Algorithm Flow for Toggle Case

Solution Approach

function solution(s) {
  var result = '';
  for (var i = 0; i < s.length; i++) {
    var c = s.charAt(i);
    if (c >= 'a' && c <= 'z') result += c.toUpperCase();
    else if (c >= 'A' && c <= 'Z') result += c.toLowerCase();
    else result += c;
  }
  return result;
}

Best Answers

java
class Solution {
    public String solution(String s) {
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<s.length();i++){char c=s.charAt(i);
            if(Character.isUpperCase(c))sb.append(Character.toLowerCase(c));
            else if(Character.isLowerCase(c))sb.append(Character.toUpperCase(c));
            else sb.append(c);
        }return sb.toString();
    }
}