My Brother's Diary
InterviewTime limit1sMemory limit128 MB
Find the Caesar shift whose most frequent ciphertext letter maps to E, print the smallest valid shift and the decrypted text, or NOT POSSIBLE if several shifts work.
- Level
Easy3 of 10
- Topics
- String, Implementation, Hash map, Brute force
- Solved
- No attempts yet
Problem
These days, people who want to communicate securely use asymmetric encryption algorithms such as RSA. My older brother, however, protects his diary with a simpler method: a substitution cipher in which every letter of the plaintext is replaced by another letter of the alphabet, always shifted by the same fixed distance. If this fixed distance is , then A is replaced by F, B by G, C by H, and so on, wrapping around so that Y becomes D and Z becomes E.
If the distance were fixed and known, decryption would be easy. But my brother chooses a random distance for each diary entry, so to read an entry I first have to guess its distance . To do this I rely on the well-known fact that the letter E occurs more often than any other letter in English text.
Can you write a program that, assuming the most frequent letter in an encrypted entry stands for the plaintext letter E, works out the distance ? Naturally, I would also like to see the decrypted text.
Input
The first line contains the number of test cases . Each of the next lines contains exactly one diary entry. Diary entries use only uppercase letters (A–Z) and spaces, and each entry contains at most characters (letters and spaces together).
Output
For each test case, print one line containing the smallest possible distance followed by the decrypted text. If decryption is impossible because more than one distance satisfies the rule above, print NOT POSSIBLE instead. Spaces are never encrypted.