How to print a unique two-line alphabet using Java?

I recently attended an interview. They asked me to write a program to print unique alphabets and common characters from two lines. I wrote the code below to print 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 they are not satisfied with my answer. I guess because they do not expect retainAll . So, please tell me the correct programming method to satisfy them in the future.

I even googled, but I did not find any good, clear links.

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

Any code would be appreciated.

+7
source share
9 answers

Perhaps the interviewer wanted to test your understanding of internal affairs, how to effectively solve this problem, and using retainAll() does not meet the purpose of this task.

To implement "from scratch" you can use several approaches:

  • Similarly to your decision - fill in two Set objects - one for each row, and then check the difference / common element between them:

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

    You can even use bit-set if the alphabet is known to be constant (and small enough), otherwise the HashSet is accurate and will achieve average performance in the case of O(n) .

  • sort and iterate: sort two char arrays and repeat them to find common (and unique) characters. Although there is no real benefit to it in java (since String immutable, so you still need to create a new char[] ) - in other languages ​​it saves space and can be done in place with very little extra space.

+3
source

Print unique and common characters from two lines without using the keepAll function.

  String firstString = "I am living in india"; String secondString = "india is a beautiful country"; HashSet<Character> h1 = new HashSet<Character>(), h2 = new HashSet<Character>(); for(int i = 0; i < firstString.length(); i++) { h1.add(firstString.charAt(i)); } for(int i = 0; i < secondString.length(); i++){ h2.add(secondString.charAt(i)); } StringBuffer commonSB = new StringBuffer(); StringBuffer uniqueSB = new StringBuffer(); for(Character i : h1){ if(!h2.contains(i)){ uniqueSB.append(i); }else{ commonSB.append(i); }; } for(Character i : h2){ if(!h1.contains(i)){ uniqueSB.append(i); }; } System.out.println("Common:"+commonSB.toString().replace(" ", ""); System.out.println("Unique:"+uniqueSB.toString().replace(" ", ""); 

Results:

 Common:danli Unique:gvmIfebcoutsry 
+2
source

when you go for an interview, and if they ask a stupid question, like the one you said, then they are not looking for a complex Collection structure. They are looking for if you can do the same at the root level with your coding abilities, keeping in mind how you write code that can handle cases, even if the data provided goes to millions.

This problem can be easily solved by taking byte []. We know that char is represented by an internal number.

so in the first iteration, just iterate over the characters of the first line (str1) and set the byte location to some constant, say 1.

 for (int i=0; i<str1.length; i++) { byteArr[(int)str.charAt(i)] = 1; // O(1) } 

therefore, in the second iteration, just iterate over the characters of the second line and set the byte location to some constant, say 2, only if it is set to 1 and 3 to imagine that it is unique to str2.

In the third iteration, just iterate over the arr bytes and print the characters (convert the index to char), where it is 2 for general and 1/3 for unique.

final solution O (n) and scalable.

+2
source

s1CharSet.retainAll (s2CharSet);

Looks like the above line just indicated the intersection (intersection B) .

To get all the unique characters, you need to get UNION. AB + A Intersection B + BA.

UPDATE: Link: Intersection and Merge

 public class Test { public static void main(String... args) throws Exception { List<String> list1 = new ArrayList<String>(Arrays.asList("A", "B", "C")); List<String> list2 = new ArrayList<String>(Arrays.asList("B", "C", "D", "E", "F")); System.out.println(new Test().intersection(list1, list2)); System.out.println(new Test().union(list1, list2)); } public <T> List<T> union(List<T> list1, List<T> list2) { Set<T> set = new HashSet<T>(); set.addAll(list1); set.addAll(list2); return new ArrayList<T>(set); } public <T> List<T> intersection(List<T> list1, List<T> list2) { List<T> list = new ArrayList<T>(); for (T t : list1) { if(list2.contains(t)) { list.add(t); } } return list; } } 
+1
source

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.

+1
source
 class uniqueCharInTwoString{ public static void unique(String a, String b){ HashSet<Character> unique = new HashSet<Character>(); HashSet<Character> common = new HashSet<Character>(); for(Character c : a.toCharArray()){ unique.add(c); } for(Character c : b.toCharArray()){ if(!unique.add(c)){ common.add(c); } } unique.removeAll(common); unique.remove(' '); common.remove(' '); System.out.println(unique); System.out.println(common); } public static void main(String args[]){ String a = "abdedf"; String b = "cdfang"; unique(a,b); } } 
0
source

This is my solution that implements LinkedHashSet to maintain character order in strings.

 import java.util.LinkedHashSet; import java.util.Set; public class CommonCharacters { public static void main(String[] args) { Pair<String, String> p = getDuplicates("abdxzewxk", "axzmnx"); System.out.println("Unique:" + p.value1 + " Common:" + p.value2); } public static Pair<String, String> getDuplicates(String s1, String s2) { Set<Character> xters1 = new LinkedHashSet<Character>(); Set<Character> xters2 = new LinkedHashSet<Character>(); for (char c : s1.toCharArray()) { xters1.add(c); } for (char c : s2.toCharArray()) { xters2.add(c); } Set<Character> unique = new LinkedHashSet<>(); Set<Character> common = new LinkedHashSet<>(); for (char c : xters1) { if (xters2.contains(c)) common.add(c); else unique.add(c); } for (char c : xters2) { if (xters1.contains(c)) common.add(c); else unique.add(c); } return new Pair(stringfry(common), stringfry(unique)); } public static String stringfry(Set<Character> chrs) { StringBuilder sb = new StringBuilder(); chrs.forEach(s -> { sb.append(s); }); return sb.toString(); } static class Pair<E, U> { private E value1; private U value2; public Pair(E value1, U value2) { this.value1 = value1; this.value2 = value2; } } 
0
source

Say, for simplicity, our strings consist only of lowercase characters. Now we can build two arrays of length 26 and count the appearance of the characters. Now compare both arrays if both have count> 0 and then common to both rows. If the counter is zero in one and non-zero in the other, then it is unique to this particular row. If both are zeros, the character is not present on any line.

The above approach can be used for many similar problems.

0
source

Print all common characters:

 public class Test10 { public static void main(String[] args) { String a = "Gini Gina Protijayi".toLowerCase(); String b = "Soudipta".toLowerCase(); // print out all the common characters a.chars() .distinct() .mapToObj(ch -> String.valueOf((char) ch)) .filter(b::contains) .forEach(System.out::println); }// main } 
0
source

Source: https://habr.com/ru/post/985668/


All Articles