Simple Cipher Solution
Recently, I tried solving a coding challenge for a job application, the goal of the challenge was to decode an encrypted string, s, by an integer k, check the image below for the full details about the challenge.
It was a timed test, and after scratching my head and writing a lot of gibberish I was unable to find a solution within the time frame. Just after the time for the test elapsed, boom!!, I had a clear understanding of what the solution was to look like, so I thought to share my solution.
To solve this problem it is very important we understand this constraint, 1 ≤ k≤ 10⁵, this was where I missed it during my test. There are 2 things we need to note here that are vital to solving this challenge.
- ) We are replacing each character with the Kth away from the wheel
- )We are moving in the counter-clockwise direction (-ve direction)
With this in mind let us go straight into the solution I came up with.
Let's assume we are to replace the alphabet ‘D’ which is the 4th letter of the alphabet, given k=28, what is the 28th letter away from ‘D’? Clearly, if we make one revolution (26 letters round the wheel from ‘D’), we still have to move 2 letters to complete 28, which will land us on ‘F’ (if we move in the clockwise direction) or ‘B’, if we move counterclockwise. In other words, for every given integer k, we need to find the number of revolutions around the wheel and most importantly get the remainder.
Now, let us start writing our code, all I’m saying in essence is:
Next up, we need to map our encrypted word and for each character, we find the position/index of the character on the wheel. Let us add some more code.
Firstly, we have calculated the kth position from any given index. Secondly, we mapped our encrypted string and on every iteration, we found the position of each character on the wheel. Next, for each of the char in the encrypted string, we find the Kth character away from that string in the counterclockwise direction.
Our code looks like this now:
When we put all the pieces together, our final solution looks like this:
Now, we have been able to decipher the encrypted string and have successfully solved this challenge.
I hope you enjoyed reading through this article as much as I enjoyed creating it. Please feel free to leave comments and suggest any improvements to the code.
Cheers and happy coding.