Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print unique alphabet from two strings using Java?

Tags:

java

Recently, I attended an interview. They asked me to write a program to print unique alphabets and common characters from two strings. I wrote the code below to print the common characters:

String s1 = "I am living in india";
String s2 = "india is a beautiful country";

char[] s1Array = s1.toCharArray();
char[] s2Array = s2.toCharArray();

LinkedHashSet<Character> s1CharSet = new LinkedHashSet<Character>();
LinkedHashSet<Character> s2CharSet = new LinkedHashSet<Character>();

for(char kc : s1Array){
    s1CharSet.add(kc);
}

for(char c: s2Array){
    s2CharSet.add(c);
}

s1CharSet.retainAll(s2CharSet);

if(s1CharSet.size()==0){
    System.out.println("There are no common characters between the two strings");
}
else{
    System.out.println(s1CharSet);
}
}

but they said like they are not satisfied with my answer. I guess it's because they are not expecting retainAll. So, please tell me the right way of programming to satisfy them in the future.

I even Googled but I didn't find any good, understandable links.

So, how to print unique and common characters from two strings without using retainAll?

Any code would be appreciated.

like image 975
MMMMS Avatar asked Apr 22 '15 10:04

MMMMS


People also ask

How do you find common letters in two strings?

Approach: Count the frequencies of all the characters from both strings. Now, for every character if the frequency of this character in string s1 is freq1 and in string s2 is freq2 then total valid pairs with this character will be min(freq1, freq2). The sum of this value for all the characters is the required answer.


1 Answers

It is possible the interviewer wanted to check your understanding of the internals of how to solve this problem efficiently, and usage of retainAll() kinda misses the purpose of this task.

To implement it "from scratch" one can use several approaches:

  1. Similar to your solution - populate two Set objects - one for each string, and then check the difference/common element between them by:

    for (Character c : set1) {
        if (set2.contains(c)) {
            System.out.println(c);
        }
    }
    

    You can even use a bitset if the alphabet is known to be constant (and small enough), otherwise a HashSet is fine and will achieve O(n) average case performance.

  2. sort and iterate: sort the two char arrays and iterate together to find common (and unique) characters. While in java there is no real benefit for it (since String is immutable, so you need to create a new char[] anyway) - in other languages, it saves up space and can be done inplace with really little additional space.

like image 106
amit Avatar answered Oct 20 '22 05:10

amit