Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an efficent algorithm to find the intersection of two strings

Tags:

c#

algorithm

Implement an algorithm that takes two strings as input, and returns the intersection of the two, with each letter represented at most once.

Algo: (considering language used will be c#)

  1. Convert both strings into char array
  2. take the smaller array and generate a hash table for it with key as the character and value 0
  3. Now Loop through the other array and increment the count in hash table if that char is present in it.
  4. Now take out all char for hash table whose value is > 0.
  5. These are intersection values.

This is an O(n), solution but is uses extra space, 2 char arrays and a hash table

Can you guys think of better solution than this?

like image 578
Learner Avatar asked Jan 21 '26 04:01

Learner


1 Answers

How about this ...

var s1 = "aabbccccddd";
var s2 = "aabc";

var ans = s1.Intersect(s2);
like image 87
JP Alioto Avatar answered Jan 22 '26 17:01

JP Alioto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!