Given a string of length n and a non-negative integer k. Find k distant string of given string.
Distance between two letters is difference between their positions in the alphabet. for example:
- dist(c, e) = dist(e, c) = 2.
- dist(a, z) = dist(z, a) = 25.
By using this concept, the distance between two strings is the sum of distances of corresponding letters. For example :
- dist(af, hf) = dist(a, h) + dist(f, f) = 7 + 0 = 7.
Given a string and a distance k. Task is to find a string such that distance of the result string is k from given string. If k distant string is not possible, then print “No”.
Note: There may be exist multiple solutions. We meed to find one of them.
Input : bear k = 26 Output : zcar Here, dist(bear, zcar) = dist(b, z) + dist(e, c) + + dist(a, a) + dist(r, r) = 24 + 2 + 0 + 0 = 26 Input : af k = 7 Output : hf Here, dist(af, hf) = dist(a, h) + dist(f, f) = 7 + 0 = 7 Input : hey k = 1000 Output : No Explanation : No such string exists.
There is no solution if the given required distance is too big. Think what is the maximum possible distance for the given string. Or the more useful thing — how to construct the lost string to maximize the distance? Treat each letter separately and replace it with the most distant letter. For example, we should replace ‘c’ with ‘z’, and we should replace ‘y’ with ‘a’. To be more precise, for first 13 letters of the alphabet the most distant letter is ‘z’, and for other letters it is ‘a’.
The approach is simple, iterate over letters of the given string and greedily change them. A word “greedily” means when changing a letter, don’t care about the next letters. Generally, there must be distant letters, because there may not be a solution otherwise. For each letter of the given string change it into the most distant letter, unless the total distance would be too big. As letters are changed, decrease the remaining required distance. So, for each letter of the given string consider only letters not exceeding the remaining distance, and among them choose the most distant one.
CPP and JAVA Implementation:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live