Caesar Cipher Hacker Rank Solution Best & Easiest

Caesar Cipher Problem Solution
Caesar Cipher Problem Solution

In this post, we will solve the Caesar Cipher HackerRank Solution. This problem (Caesar Cipher) is a part of the HackerRank Problem Solving series.

Julius Caesar protected his confidential information by encrypting it using a cipher. Caesar’s cipher shifts each letter by a number of letters. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. In the case of a rotation by 3, w, x, y and z would map to z, a, b and c.

Original alphabet:      abcdefghijklmnopqrstuvwxyz
Alphabet rotated +3:    defghijklmnopqrstuvwxyzabc

Tower Breakers Hacker Rank Solution

Problem solution in Python programming:

def caesarCipher(s, k):
    # Write your code here
    ret = []

    for i in range(len(s)):
        if (s[i].islower()):
            ret.append(chr(97 + ((ord(s[i]) + k) - 97) % 26))
        elif (s[i].isupper()):
            ret.append(chr(65 + ((ord(s[i]) + k) - 65) % 26))
        else:
            ret.append(s[i])
    
    return "".join(ret)

Problem solution in JavaScript programming:

function caesarCipher(s, k) {
    var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split("");
    var cipher = {};
    var output = "";
    
    // define cipher
    for(var i = 0; i< alphabet.length; i++) {
        cipher[alphabet[i]] = alphabet[(i+k)%26];
        cipher[alphabet[i].toUpperCase()] = alphabet[(i+k)%26].toUpperCase();
    }
    
    // apply cipher
    for(var i in s.split("")) {
        output += (cipher[s[i]] != undefined ? cipher[s[i]] : s[i]);
    }
    
    return output;
}

Problem solution in C# programming:

public static string caesarCipher(string s, int k)
    {
        string alphabet = "abcdefghijklmnopqrstuvwxyz";
        StringBuilder res = new StringBuilder();
        if (k > alphabet.Length) k %= alphabet.Length;
        for (int i = 0; i < s.Length; i++)
        {
            if (char.IsLetter(s[i]))
            {
                int index = alphabet.IndexOf(char.ToLower(s[i]));
                int resindex = ((index + k) > (alphabet.Length - 1)) ? index + k - alphabet.Length : index + k;
                res.Append(char.IsUpper(s[i]) ? char.ToUpper(alphabet.ElementAt(resindex)) : alphabet.ElementAt(resindex));
            }
            else
            {
                res.Append(s[i]);
            }
        }
        return res.ToString();
    }