“Did you know how ancient people sent secret messages”

Phaneesha Chilaveni
5 min readFeb 23, 2023

Caesar Cipher | Hackerrank Solution

Photo by Melanie van Leeuwen on Unsplash

Origin of the problem:

As the sun rose over the ancient city of Rome, Julius Caesar sat at his desk, pondering the safety of his messages. He knew that his enemies were constantly trying to intercept and decipher his communications, so he needed a way to keep his messages secret. That’s when he had an idea — he would create a cipher that would shift each letter by a certain number of spaces, making the message unreadable unless the recipient knew the cipher.

Julius Caesar called in his most trusted messenger, a young man named Marcus, and gave him an important message to deliver to one of Caesar’s generals. But he didn’t want anyone else to be able to read the message, so he encrypted it using his new cipher. He shifted each letter by three spaces so that A became D, B became E, and so on. Marcus carefully wrote down the encrypted message on a piece of parchment and set out on his journey.

As he traveled through the countryside, Marcus encountered all kinds of obstacles — bandits, rough terrain, and bad weather. But he was determined to deliver the message to Caesar’s general. Finally, after several days of travel, he arrived at his destination.

The general was pleased to receive the message and quickly deciphered it using the cipher he had been given. The message contained important information about an upcoming battle, and thanks to Caesar’s cipher, the enemy was none the wiser.

From that day on, Caesar’s cipher became a trusted method of communication for the Roman army. And although it may seem primitive compared to modern encryption methods, it was a groundbreaking innovation in its time. Julius Caesar had found a way to keep his messages safe from prying eyes, and in doing so, he changed the course of history.

Introduction to our problem:

Caesar Cipher is an ancient encryption technique used by Julius Caesar to protect his confidential information. This technique works by shifting each letter in the plain text by a certain number of positions in the alphabet. If the shift takes you past the end of the alphabet, just rotate back to the front of the alphabet. For example, with a rotation of 3, the letter “A” would be replaced by the letter “D”, “B” would become “E”, and so on.

In this problem, we are given a string of characters and an integer “k”, which represents the number of positions to shift the letters in the string. Our task is to implement a Caesar Cipher encryption function that takes in the plain text and the value of “k” and returns the encrypted string. The function should only encrypt alphabetic characters and leave all other characters unchanged. Additionally, it should preserve the case of the characters in the input string.

This problem is a good exercise in string manipulation and algorithm design. It requires an understanding of string indexing, the ASCII character set, and the modulo operator. The problem can be solved using a variety of techniques, but a straightforward approach involves iterating over the characters in the input string, checking if each character is alphabetic, and then applying the Caesar Cipher shift to the character. The encrypted string can be constructed by appending each encrypted character to a new string.

My solution to the problem:

As I started working on this problem, I realized that there were different ways to approach it. One approach would be to iterate through each character in the input string, check if it is a letter, and then apply the Caesar cipher by shifting it by the specified number of letters. However, this would involve a lot of conditional statements and would not be very efficient.

Instead, I decided to use the ASCII code of each character to determine if it is a letter and to apply the cipher. The ASCII code for uppercase letters ranges from 65 to 90, and the ASCII code for lowercase letters ranges from 97 to 122. Therefore, I could check if a character’s ASCII code falls within these ranges and apply the cipher accordingly.

To apply the cipher, I calculated the new ASCII code by adding the shift value to the current ASCII code of the character. If the new ASCII code exceeds the range for uppercase or lowercase letters, I simply subtracted 26 to wrap it around to the beginning of the range. Finally, I converted the new ASCII code back to a character using the chr() function in Python.

This approach allowed me to apply the Caesar cipher to the input string in a single pass through the characters, without the need for conditional statements. It also has a time complexity of O(n), where n is the length of the input string.

In terms of space complexity, my solution uses a new string variable to store the encrypted string. The size of this variable is proportional to the length of the input string, so the space complexity is also O(n).

Overall, I found this problem to be a fun challenge and a great opportunity to practice my Python programming skills.

My code :

def caesarCipher(s, k):
# Write your code here
encrypted_str = ""
for char in s:
if char.isalpha():
base = ord('a') if char.islower() else ord('A')
encrypted_str += chr((ord(char) - base + k) % 26 + base)
else:
encrypted_str += char
return encrypted_str

Sample — output:

s = 'middle-Outz'
k = 2
caesarCipher(s, k)
'okffng-Qwvb'

Give it a shot:

Conclusion:

In summary, the Caesar Cipher problem is a classic encryption challenge where we are asked to shift each letter in a string by a given number of places in the alphabet. In this story, we explored the problem and discussed different ways to approach the solution. We went through the thought process of how to solve this problem using Python and provided a detailed explanation of our code.

By leveraging the ASCII table and some simple math, we were able to quickly implement an efficient solution that works for any string and any shift value. We also provided an optimized version of the code that reduces the number of operations and improves its performance.

If you’re interested in learning more about encryption or data security, there are many online resources available to help you dive deeper into these topics. As always, it’s important to be mindful of data privacy and security when handling sensitive information.

In conclusion, we encourage you to try out our solution and experiment with different strings and shift values. With this simple encryption technique, you can add an extra layer of security to your messages and communications. Thank you for reading, and we hope you found this story helpful and informative!

--

--

Phaneesha Chilaveni

Hi, I'm Phaneesha, a Data Science enthusiast. I'm passionate about Data Science and in my free time I love to cook, read and paint.