I would do something like:
//assume questions treats I and i as the same. String s1 = "I am living in india".toLowerCase(); String s2 = "india is a beautiful country".toLowerCase(); //Since character is comparable this will maintain the set in alphabetical order when we print it. - well based on the numerical chacacter anyway. Set<Character> unique = new TreeSet<Character>(); Set<Character> common = new TreeSet<Character>(); unique.addAll(Arrays.<Character>asList(ArrayUtils.toObject(s1.toCharArray()))); //Oh java !?!?! for(Character c : s2.toCharArray()){ if(!unique.add(c)){ common.add(c); } } //Assume question didnt mean to include whitespace unique.remove(' '); common.remove(' '); System.out.println("Unique: " + unique.toString()); System.out.println("Common: " + common.toString());
This basically just uses the behavior of the set set function, which returns true if the item was not in the set, and false if it was. The set avoids duplication.
Gives output:
Unique: [a, b, c, d, e, f, g, i, l, m, n, o, r, s, t, u, v, y] Common: [a, d, i, l, n, t, u]
There are a few small points that an interviewer can take:
1) You used a class, not an interface, in your LinkedHashSet definitions. This is widely regarded as bad practice and can be taken as evidence that you have limited knowledge of Java - ofc, no matter what the problem, it depends on what level of experience they are interested in.
2) Your variable name. You will never be happy as an interviewer, if your candidate holds the names of thingy objects or someFunction functions, the natural programmer gives useful names for objects and functions on the fly. Again, depending on the level of experience they wanted, this may or may not be a problem.
3) They may have been looking for some imagination when interpreting the question, for example. ask if the space is a βsymbolβ in the question or sort the output to make it more readable. Or ask whether I and I should be considered as the same or different symbols.
4) Perhaps they were expecting some knowledge of the Java development timeline, for example. say: "I used Autoboxing here, so it requires 1.7 or a later compiler."
5) You may have gone too long or too many syntax tips / corrections.