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”.