Change Case

Easy
0/40
profile
Contributed by
5 upvotes

Problem statement

You are given a non-empty string ‘STR’, consisting of both lowercase and uppercase English alphabetical letters. Your task is to convert the characters of the string into the opposite case, i.e. if a character is in lower case then convert it into the upper case and vice-versa.

For Example:
If STR = ‘aBc’,
After converting ‘a’ to ‘A’, ‘B’ to ‘b’, and ‘c’ to ‘C’ we got our final string as ‘AbC’.
Detailed explanation ( Input/output format, Notes, Images )
Input Format :
The first line of the input contains an integer, 'T’, denoting the number of test cases.

The first and only line of each test case contains a non-empty string of characters(a - z, A - Z).
Output Format :
For each test case, print the string after converting the characters of the string into the opposite case.

Print a separate line for each test case.
Note :
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints :
1 <= T <= 10
1 <= str.length <= 10000

Time limit: 1 sec
Sample Input 1 :
2
aBc
CoD
Sample output 1 :
AbC
cOd
Explanation For Sample Output 1 :
For the first test case,
STR = ‘aBc’,
After converting ‘a’ to ‘A’ , ‘B’ to ‘b’ and ‘c’ to ‘C’ we got our final string as ‘AbC’.

For the second test case,
STR = ‘CoD’,
After converting ‘C’ to ‘c’ , ‘o’ to ‘O’ and ‘D’ to ‘d’ we got our final string as ‘cOd’.
Sample Input 2 :
2
VzM
bfr
Sample output 2 :
vZm
BFR
Hint

Check the ASCII values of English alphabets.

Approaches (1)
Implementation

The ASCII values of lowercase English alphabets lie in the range 97-122 where 97 is the ASCII value of ‘a’ and 122 is of ‘z’. Similarly, the ASCII values of uppercase English alphabets lie in the range 65-90 where 65 is the ASCII value of ‘A’ and 90 is of ‘Z’. If we have an uppercase alphabet then we just have to add 32 to convert it to lowercase and if we have a lowercase alphabet then we just have to subtract 32 to convert it to uppercase. 

 

Here is the algorithm:

  1. Iterate over the string ‘STR’ (say iterator ‘i’)
    • If STR[i] >= 'a' and STR[i] <= 'z'
      • STR[i] -= 32.
    • Else
      • STR[i] += 32.
Time Complexity

O( N ), where ‘N’ is the length of the string.

 

We have just traversed the string only once.

Hence, the overall time complexity will be O(N).

Space Complexity

O( 1 )
 

We are not using any extra space.

Hence the overall space complexity will be O(1).

Code Solution
(100% EXP penalty)
Change Case
Full screen
Console