HackerRank 'sWAP cASE' Solution

Martin Kysel · July 28, 2020

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.

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

Twitter, Facebook

To learn more about solving Coding Challenges in Python, I recommend these courses: Educative.io Python Algorithms, Educative.io Python Coding Interview.