![]() |
VOOZH | about |
Given two strings S1 and S2. The task is to concatenate uncommon characters of the S2 to S1 and return the resultant string S1 .
Examples:
Input:S1 = "aacdb", S2 = "gafd"
Output: "cbgf"Input:S1 = "abcs", S2 = "cxzca";
Output: "bsxz"
Method 1: Using Hashmap
Approach:
Below is the idea to solve the problem.
The idea is to use Hashmap where the key is a character and the value is an integer i.e. number of strings in which the character is present. If a character is present in one string, then the count is 1, else if the character is present in both strings, the count is 2.
Follow the steps below to implement the idea:
Below is the implementation of above approach:
bsxz
Time Complexity: O(M + N), where M and N represents the size of the given two strings.
Auxiliary Space: O(max(M, N)), where M and N represents the size of the given two strings.
Method 2: Using Set
Use a set instead of a hashmap to store the characters of the second string. This can simplify the code and reduce the space complexity.
Approach:
Below is the implementation of the updated approach:
bszx
Time Complaxity: O(M+N)
Auxiliary Space: O(N)
Method 3: Using Count Arrays
Follow the steps to implement the approach:
Below is the implementation:
bsxz
Time complexity: O(m + n), where m and n are the lengths of s1 and s2, respectively. This is because we iterate over both strings.
Space complexity: O(1). The count1 and count2 arrays have a fixed size of 26, so the space required is constant.