HackerRank ‘sWAP cASE’ Solution

Short Problem Definition:

You are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.

Link

sWAP cASE

Complexity:

time complexity is O(N)

space complexity is O(N)

Execution:

I had too much fun with this one, so I refuse to admit that there is a buildin swapcase() function. ASCII can be fun.

Solution:
def swap_case(s):
    result = ""
    for idx in xrange(len(s)):
        ordinal = ord(s[idx])
        if (ordinal >= ord('a') and ordinal <= ord('z')) or \
            (ordinal >= ord('A') and ordinal <= ord('Z')):
            result += chr(ordinal-ord('A')+32)%64+ord('A'))
        else:
            result += s[idx]
    return result


If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed.

Facebooktwitterredditpinterestlinkedin