HackerRank Caesar Cipher Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Caesar Cipher Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Caesar Cipher Solution
HackerRank Caesar Cipher Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Caesar Cipher


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.


s = There’s-a-starman-waiting-in-the-sky
k = 3

The alphabet is rotated by 3, matching the mapping above. The encrypted string is 

Note: The cipher only encrypts letters; symbols, such as -, remain unencrypted.

Function Description

Complete the caesarCipher function in the editor below.

caesarCipher has the following parameter(s):

  • string s: cleartext
  • int k: the alphabet rotation factor


  • string: the encrypted string

Input Format

The first line contains the integer, n, the length of the unencrypted string.
The second line contains the unencrypted string, s.
The third line contains k, the number of letters to rotate the alphabet by.


  • 1 <= n <= 100
  • 0 <= k <= 100
  • s is a valid ASCII string without any spaces.

Sample Input


Sample Output



Original alphabet: abcdefghijklmnopqrstuvwxyz
Alphabet rotated +2: cdefghijklmnopqrstuvwxyzab

m -> o
i -> k
d -> f
d -> f
l -> n
e -> g
O -> Q
u > w
t -> v
z -> b

HackerRank Caesar Cipher Solution

Caesar Cipher Solution in C

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
		int i,j,k,g,n,m=0;scanf("%d",&n);
    char ch1[130]={'a'},ch2[130]={'A'},s[100];scanf("%s",s);scanf("%d",&k);

        else if(s[i]==ch2[j])
    return 0;

Caesar Cipher Solution in Cpp

#include <iostream>
#include <string>
using namespace std;

int main() {
    int N = 0, K = 0;
    string str, dummy;
    cin >> N; getline(cin, dummy);
    getline(cin, str);
    cin >> K;
    int len = str.length();
    for (int i = 0; i < len; ++i)
        if (65 <= str[i] && str[i] <= 90)
            str[i] = char(65 + ((str[i] - 65) + K) % 26);
        else if (97 <= str[i] && str[i] <= 122)
            str[i] = char(97 + ((str[i] - 97) + K) % 26);
    cout << str << endl;
    return 0;

Caesar Cipher Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int len = s.nextInt(); s.nextLine();
        String str = s.nextLine();
        int shift = s.nextInt();
        char sarr[] = str.toCharArray();
        for (int i=0; i<sarr.length; i++) {
            sarr[i] = cryptIt(sarr[i], shift);
        System.out.println(new String(sarr));
    public static char cryptIt(char c, int shift) {
        if (!Character.isAlphabetic(c)) return c;
        char base = 'A';
        if (c >= 'a') base = 'a';
        return (char)(((c - base + shift) % 26) + base);

Caesar Cipher Solution in Python

def ceasar(s,n):
    coded = []
    for el in s:
        if ord(el) >96 and ord(el) < 123:
            a = chr((ord(el)-97 +n) % 26+97)
        elif ord(el) > 64 and ord(el) < 91:
            a = chr((ord(el)-65+n) % 26 + 65)
    return ''.join(coded)
l = int(raw_input())
s = raw_input()
n = int(raw_input())
print ceasar(s,n)

Caesar Cipher Solution using JavaScript

function processData(input) {
    //Enter your code here
    var lines = input.split('\n');
    var chars = parseInt(lines[0].trim(), 10);
    var text = lines[1].trim();
    var shift = parseInt(lines[2].trim(), 10)%26;
    var output = "";
    for(var i=0; i<chars; i++) {
        var character = text.charCodeAt(i);
        if (character >= 65 && character <= 90) {
            character += shift;
            if (character > 90) {
                character = 64 + (character - 90);
        } else if (character >= 97 && character <= 122) {
            character += shift;
            if (character > 122) {
                character = 96 + (character - 122);
        output += String.fromCharCode(character);

_input = "";
process.stdin.on("data", function (input) {
    _input += input;

process.stdin.on("end", function () {

Caesar Cipher Solution in Scala

object Solution {

    def main(args: Array[String]) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution
        val len = readInt
        val s = readLine
        val k = readInt
        var result: String = ""
        for (i <- 0 to len - 1) {
          val item = s.charAt(i)
          if (item >= 'a' && item <= 'z') {
            result = result + ((item - 'a' + k) % 26 + 'a').asInstanceOf[Char].toString
          } else if (item >= 'A' && item <= 'Z') {
            result = result + ((item - 'A' + k) % 26 + 'A').asInstanceOf[Char].toString
          } else {
            result = result + item.toString

Caesar Cipher Solution in Pascal

program caesar_cipher;
var big,small:set of Char;
    for i:=1 to N do
        if S[i] in small then
            if ord(S[i])+K > 122 then
                S[i]:=chr(ord('a')+((ord(S[i])+K-97) mod 26))
        if S[i] in big then
            if ord(S[i])+K > 90 then
                S[i]:=chr(ord('A')+((ord(S[i])+K-65) mod 26))

Disclaimer: This problem (Caesar Cipher) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.


1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi

Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment