C++ code to find the number of dial rotations to print a string

C++Server Side ProgrammingProgramming

Suppose, we are given a rotary dial that contains all lowercase English alphabets. There is a printer attached to the dial and whichever character resides in the pointer of the rotary dial for 3 seconds, gets printed. The rotary dial initially stays at the letter 'a' and it does not reset to the initial position whenever it prints a character. We are given a string s and we have to print the given string. Whenever we move the dial to another letter, one amount of rotation takes place. We have to find out the total amount of rotations needed to print the given string 's'.

So, if the input is like s = "elephant", then the output will be 63.


To solve this, we will follow these steps −

t := 'a'
res := 0
for initialize i := 0, when i < size of s, update (increase i by 1),
   res := res + minimum of (|t - s[i]|, 26 - |t - s[i]|)
   t := s[i]
return res


Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
#define N 100
int solve(string s) {
   char t = 'a';
   int res = 0;
   for(int i = 0; i < s.size(); i++){
      res += min(abs(t - s[i]), 26 - abs(t - s[i]));
      t = s[i];
   return res;
int main() {
   string s = "elephant";
   cout<< solve(s);
   return 0;




Updated on 11-Mar-2022 06:40:32