Caesar Cipher

Difficulty Level Easy
Frequently asked in Amazon GE Healthcare Grofers UHG Optum
Cryptography StringViews 2828

Description

The Caesar Cipher technique is one of the earliest techniques of encryption. Here, for each letter in the given text, it is replaced by a letter some fixed number of positions down the alphabet. If n = 1, replace A with by B, B would become C, and so on.

That is, S(x) = (x + n)mod26.

Here, a = 0, b = 1, ……. z = 25.

Input Format

The first line containing a string “s”.

The second line containing an integer n which represents the number of shifts of each character.

Output Format

The first and only one line containing the final string “t”. Here t[i] = (s[i]+n)/26.

Constraints

  • 1<=|s|<=10^6
  • s[i] must be a lower case English alphabet

Example

middleoutz
2
okffngqwvb

Explanation: In the given string “middleoutz” after rotating every character by 2. The value of character becomes:

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

So, our final string is “okffngqwvb”.

Algorithm for Caesar Cipher

Here a string of lower case letters is Text and an integer between– 0 – 25 is Shift. To encrypt the string, we need to rotate the alphabets in the string by a number k. If k is a multiple of 26, then rotating the alphabets in the string by k has no effect on the string. Rotation by k is the same as rotation by k+26. So by taking the modulo of k with 26, we get the number of times we need to rotate the alphabets of the string.

1. Traverse the input string.

2. Take one character at a time, for each character transform it as per the rules.

3. Return the final string.

Implementation

C++ Program for Caesar Cipher

#include <bits/stdc++.h>
using namespace std;

int main() 
{
    string s;
    cin>>s;
    int k;
    cin>>k;
    k%=26;
    for(int i=0;i<s.length();i++) 
    {
        int c=s[i];
        c+=k;
        if(c>'z') 
        {
           c=96+(c%122); 
        }
        s[i]=(char)c;
    }
    cout<<s<<endl;
    return 0;
}

Java Program for Caesar Cipher

import java.util.Scanner;

class sum
{
    public static void main(String[] args)
    {
        Scanner sr = new Scanner(System.in);
        String s = sr.next();
        int k = sr.nextInt();
        k=k%26;
        for(int i=0;i<s.length();i++) 
        { 
            int c=s.charAt(i); 
            c+=k; 
            if(c>'z') 
            {
                c=96+(c%122); 
            } 
            System.out.print((char)c); 
        }
        System.out.println();
    }
}




tutorialcup
12
fgfadumxogb

Complexity Analysis for Caesar Cipher

Time complexity

O(n) where n is the size of the given string. Here we traverse the whole string char by char and change the current character in constant time.

Space Complexity

O(1) because we don’t use any auxiliary space here. Simply print the answer or update the given string.

Translate »