Simple Vigenère Cipher in C++


You are given a lowercase alphabet string text, and another string key. Return a new string where every letter in text[i] is moved to the right with offset key[i]. Offset is equal to key[i]’s position in the alphabet (A=0, B=1 etc.)

Note: If the letter overflows past z, it gets wrapped around the other side.

Constraints
Length of text, key ≤ 10000
Example 1
Input
text = “bcd”
key = “bbb”
Output
“cde”
Explanation
“bcd” gets shifted to the right by 1, since “b” is index 1 in the alphabet.

Example 2
Input
text = “abz”
key = “cbb”
Output
“cca”
Explanation
“a” gets shifted 2 positions to the right to “c”
“b” gets shifted 1 position to the right to “c”
“z” gets shifted 1 position to the right and wraps to “a”

Vigenère Cipher in C++

Similar to A Simple Atbash Cipher and Simple Vertical Cipher Algorithm, we need to rotate the character at each specified times to the right. The pitfall is to wrap the ‘Z’ to ‘A’, which we can easily manage using the modulus operator.

1
2
3
4
5
6
7
8
string vigenereCipher(string text, string key) {
    int k = 0;
    for (auto &n: text) {
        int r = (key[k ++] - 'a');
        n = ('a' + (n + r - 'a') % 26);
    }
    return text;
}
string vigenereCipher(string text, string key) {
    int k = 0;
    for (auto &n: text) {
        int r = (key[k ++] - 'a');
        n = ('a' + (n + r - 'a') % 26);
    }
    return text;
}

Algorithm Time complexity is O(N) as we are visiting each character in the string exactly once, and the space complexity is O(1) constant as we are modifying the string directly without allocating additional space.

String Cipher Algorithms

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
418 words
Last Post: Algorithms to Check Sum of Two Numbers in Binary Search Trees
Next Post: Teaching Kids Programming - Enhanced Valid Parenthese String Algorithm using a Stack

The Permanent URL is: Simple Vigenère Cipher in C++

Leave a Reply