Ceaser Cipher Problem hackerRank

 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

Example

The alphabet is rotated by , 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

Returns

  • string: the encrypted string

Input Format

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

Constraints



 is a valid ASCII string without any spaces.

Sample Input

11
middle-Outz
2

Sample Output

okffng-Qwvb

Explanation

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
Explanation:
  1. We use k = k % 26 to ensure that shifts beyond 26 wrap around correctly.
  2. We loop through each character:
    • If it’s a letter, we find its base ('A' for uppercase, 'a' for lowercase).
    • Shift it within the alphabet using (ch - base + k) % 26 to get the new character.
  3. If the character is not a letter (e.g., -), we leave it unchanged.
  4. Finally, we return the encrypted string.

(char) ('A' + (ch - 'A' + k) % 26)
This expression ensures that the shifted character stays within the uppercase (A-Z) range.

Step 1: Convert Character to Zero-Based Index
ch-'A'

  • This converts the uppercase letter into a zero-based index relative to 'A'.
  • Example:
    • 'A' - 'A' = 0
    • 'B' - 'A' = 1
    • 'Z' - 'A' = 25

    Step 2: Apply Shift (k) and Wrap Using % 26

    (ch - 'A' + k) % 26

  • This shifts the letter by k positions.
  • % 26 ensures that if we go beyond 'Z', we wrap around.
  • Example (k = 3):
    • 'A'('A' - 'A' + 3) % 26 = (0 + 3) % 26 = 3
    • 'B'('B' - 'A' + 3) % 26 = (1 + 3) % 26 = 4
    • 'Y'('Y' - 'A' + 3) % 26 = (24 + 3) % 26 = 1
    • 'Z'('Z' - 'A' + 3) % 26 = (25 + 3) % 26 = 2 → Wraps to 'C'
    • Step 3: Convert Back to Character
    (char) ('A' + (ch - 'A' + k) % 26)
  • 'A' is added back to shift the zero-based index back to a character.
  • Example:
    • (char) ('A' + 3) → 'D'
    • (char) ('A' + 1) → 'B'
    • (char) ('A' + 2) → 'C'
  • Solution :-
    import java.io.*;
    import java.math.*;
    import java.security.*;
    import java.text.*;
    import java.util.*;
    import java.util.concurrent.*;
    import java.util.function.*;
    import java.util.regex.*;
    import java.util.stream.*;
    import static java.util.stream.Collectors.joining;
    import static java.util.stream.Collectors.toList;

    class Result {

        /*
         * Complete the 'caesarCipher' function below.
         *
         * The function is expected to return a STRING.
         * The function accepts following parameters:
         *  1. STRING s
         *  2. INTEGER k
         */

        public static String caesarCipher(String s, int k) {
        // Write your code here

     k = k % 26; // Normalize k to avoid unnecessary full rotations
            String encrypted = "";

            for (int i = 0; i < s.length(); i++) {
                char ch = s.charAt(i);

                if (Character.isUpperCase(ch)) {
                    encrypted += (char) ('A' + (ch - 'A' + k) % 26);
                } else if (Character.isLowerCase(ch)) {
                    encrypted += (char) ('a' + (ch - 'a' + k) % 26);
                } else {
                    encrypted += ch; // Keep non-alphabet characters the same
                }
            }

            return encrypted;
        }

    }

    public class Solution {
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

            int n = Integer.parseInt(bufferedReader.readLine().trim());

            String s = bufferedReader.readLine();

            int k = Integer.parseInt(bufferedReader.readLine().trim());

            String result = Result.caesarCipher(s, k);

            bufferedWriter.write(result);
            bufferedWriter.newLine();

            bufferedReader.close();
            bufferedWriter.close();
        }
    }

    Comments

    Popular posts from this blog

    Two Sum II - Input Array Is Sorted

    Comparable Vs. Comparator in Java

    Increasing Triplet Subsequence