![]() |
VOOZH | about |
Given two strings string1 and string2, remove those characters from the first string(string1) which are present in the second string(string2). Both strings are different and contain only lowercase characters.
NOTE: The size of the first string is always greater than the size of the second string( |string1| > |string2|).
Example:
Input:
string1 = "computer"
string2 = "cat"
Output: "ompuer"
Explanation: After removing characters(c, a, t)
from string1 we get "ompuer".Input:
string1 = "occurrence"
string2 = "car"
Output: "ouene"
Explanation: After removing characters
(c, a, r) from string1 we get "ouene".
Algorithm: Let the first input string be a ”test string” and the string which has characters to be removed from the first string be a “mask”
Implementations:
geeforgee
Time Complexity: O(m+n) Where m is the length of the mask string and n is the length of the input string.
Auxiliary Space: O(m)
An efficient solution is we find every character of string2 in string1 if that character is present then we simply erase that character from string1.
geeforgee
Time Complexity: O(n*m), where n is the size of given string2 and m is the size of string1.
Auxiliary Space: O(1), as no extra space is used
Efficient Solution: An efficient solution is that we can mark the occurrence of all characters present in second string by -1 in frequency character array and then while traversing first string we can ignore the marked characters as shown in below program.
geeforgee
Time Complexity: O(|S1|), where |S1| is the size of given string 1.
Auxiliary Space: O(1), as only an array of constant size (26) is used.