1.

Write a program to print all the unique characters in a String. For instance, if the input string is “abcb”, the output will be the characters ‘a’ and ‘c’ as they are unique. The character ‘b’ repeats twice and so it will not be printed.

Answer»

We can use a HashSet in order to store the characters of the String. When we arrive at a character in the String, if it is already present in the HashSet, we remove it from the HashSet as that character is not unique. If it is not present inside the HashSet, we add it to it. After traversing the entire string, we print the elements inside the HashMap. 

Java Code to Print All Unique Characters in a String.

import java.util.*;
class Main {

public static void main(String args[]) {
// Your code goes here
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();

HashSet<Character> unique = new HashSet<>();

for(int i=0;i<str.length();i++) {
char ch = str.charAt(i);
if(unique.contains(ch) == true) {
//this character has already occured
unique.remove(ch);
} else {
unique.add(ch);
}
}

if(unique.size() == 0) {
System.out.println("There are no unique characters");
}

for(Character ch : unique) {
System.out.print(ch + " ");
}

}
}

Sample Output

Input: abcab
Output: c


  • Corner Cases, You Might Miss: What if such a string is passed that has all the duplicate characters? Also, it might happen that an empty string is passed as the input. So, in such a case, the size of the HashSet will remain 0 after processing the String. Hence, we have handled the case of a hashset having 0 sizes separately.


  • Time Complexity: The time complexity is O(N) where N is the length of the string as we are traversing the entire string.


  • Auxiliary Space: O(N) as it might happen that all the N characters are unique so, we might generate a HashSet of size N.




Discussion

No Comment Found