I would like to get common elements in two given strings such that duplicates will be taken care of. It means that if a letter occurs 3 times in the first string and 2 times in the second one, then in the common string it has to occur 2 times. The length of the two strings may be different. eg
JavaScript
x
4
1
s1 = 'aebcdee'
2
s2 = 'aaeedfskm'
3
common = 'aeed'
4
I can not use the intersection between two sets. What would be the easiest way to find the result ‘common’ ? Thanks.
Advertisement
Answer
Well there are multiple ways in which you can get the desired result. For me the simplest algorithm to get the answer would be:
- Define an empty
dict
. Liked = {}
- Iterate through each character of the first string:
if the character is not present in the dictionary, add the character to the dictionary.
else increment the count of character in the dictionary. - Create a variable as
common = ""
- Iterate through the second string characters, if the count of that character in the dictionary above is greater than 0: decrement its value and add this character to
common
- Do whatever you want to do with the
common
The complete code for this problem:
JavaScript
1
20
20
1
s1 = 'aebcdee'
2
s2 = 'aaeedfskm'
3
4
d = {}
5
6
for c in s1:
7
if c in d:
8
d[c] += 1
9
else:
10
d[c] = 1
11
12
common = ""
13
14
for c in s2:
15
if c in d and d[c] > 0:
16
common += c
17
d[c] -= 1
18
19
print(common)
20