Tutorialspoint
Problem
Solution
Submissions

Caesar Cipher Encryption and Decryption

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a Python program to implement Caesar Cipher encryption and decryption. Caesar Cipher is a substitution cipher where each letter in the plaintext is shifted a certain number of places down or up the alphabet. For example, with a shift of 3, A would be encoded as D, B would become E, and so on.

Example 1
  • Input: text = "HELLO", shift = 3
  • Output: "KHOOR"
  • Explanation:
    • Each letter is shifted 3 positions forward in the alphabet.
    • H becomes K, E becomes H, L becomes O, L becomes O, O becomes R.
    • Therefore, "HELLO" becomes "KHOOR".
Example 2
  • Input: text = "KHOOR", shift = -3
  • Output: "HELLO"
  • Explanation:
    • Each letter is shifted 3 positions backward in the alphabet.
    • K becomes H, H becomes E, O becomes L, O becomes L, R becomes O.
    • Therefore, "KHOOR" becomes "HELLO" (decryption).
Constraints
  • 1 ≤ text.length ≤ 1000
  • text consists of uppercase and lowercase English letters and spaces
  • -25 ≤ shift ≤ 25
  • Preserve the case of letters and keep spaces unchanged
  • Time Complexity: O(n)
  • Space Complexity: O(n)
StringsFunctions / MethodsAccentureSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Iterate through each character in the input text
  • Check if the character is a letter (uppercase or lowercase)
  • Calculate the shifted position using modular arithmetic
  • Handle wrap-around cases (Z to A, z to a)
  • Preserve spaces and special characters as they are
  • Maintain the original case of the letters

Steps to solve by this approach:

 Step 1: Initialize an empty result string to store the transformed text.
 Step 2: Iterate through each character in the input text.
 Step 3: Check if the character is an uppercase letter (A-Z).
 Step 4: If uppercase, apply shift using modular arithmetic with base 65 (ASCII 'A').
 Step 5: Check if the character is a lowercase letter (a-z).
 Step 6: If lowercase, apply shift using modular arithmetic with base 97 (ASCII 'a').
 Step 7: If character is not a letter, keep it unchanged (spaces, punctuation).
 Step 8: Add the transformed character to the result string.

Submitted Code :