Introduction
In a product-based company, we are problems related to the basic data structures like arrays, strings, etc. Letβs learn about some concepts related to strings in this blog.
The string is a fundamental data structure used to store the sequence of characters. Problems related to strings are beneficial in building the foundation of a good programmer. Below is a problem related to strings, which will eventually teach us some concepts about string manipulation.
One more term, which is important to be aware of while solving string-related problems, is Lexicographical order. Lexicographical order is nothing but the dictionary order or preferably the order in which words appear in the dictionary.
Problem Statement
Two strings, consisting of lowercase alphabet characters, βSTR1β and βSTR2β, are given. We have to find the minimum number of operations to be applied on βSTR1β so that it contains only the characters present in the string βSTR2β. In one operation, we can either:
- Change the current character to the next lexicographical character, or
- Change the current character to the previous lexicographical character
Note: The next character for βzβ will be βaβ, and the previous character for βaβ will be βzβ.
Example:
Input: STR1 = βabceβ, STR2 = βabcβ
Output: 2
Explanation: The only character in βSTR1β, not present in βSTR2β, is βeβ. So we can change it to βcβ with the second operation two times. The final βSTR1β will be βabccβ.
Input: STR1 = βzehβ, STR2 = βahgβ
Output: 3
Explanation: The characters at index 0 and 1 need to be changed as βz,β and βeβ is not present in βSTR2β. So changing βzβ to βaβ will take one operation, and βeβ to βgβ takes two operations. So total 3 operations and the final string βSTR1β will be βaghβ.






