Tuesday, April 29, 2014

First Non Repeating Character in a String

We all know that when we go for companies like amazon or British Telecom, they have a very famous question which is asked very frequently is
Find the first non repeating character in a String which has many repeated alphabets.

I went for amazon interview and encountered such question.
The approach to this question will be first we will think the pseudo -code for that, then we will approach for the exact coding.

So when i was asked this question, i firstly had this pseudo code to make it the most optimize solution for this question.




1) Convert the String into Character Array.
2) Maintain a LinkedHashMap which has Key,Value pair consisting of Character and Integer. Integer is nothing but it is a count of all the repeated characters.
3) Initialize the LinkedHashMap with the key as characters and the value as 1 by default firstly.
4) We will traverse the character Array and consequently will add the counter if the map contains that character as a key.
3) Traverse the LinkedHashMap and find the first non-repeating character which has  a count 1.
 The java code for the same is :-


import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class FirstUniqueCharacterInString {
public static void main(String[] args) {
System.out
.println("Enter the String from which you want the first non repeating character: ");
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
Map<Character, Integer> hashMap = new LinkedHashMap<Character, Integer>();
String str = sc.nextLine();
char ch[] = str.toCharArray();
for (int i = 0; i < ch.length; i++) {
if (hashMap.containsKey(ch[i])) {
hashMap.put(ch[i], hashMap.get(ch[i]) + 1);
} else {
hashMap.put(ch[i], 1);
}
}
for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {
Character character = entry.getKey();
Integer value = entry.getValue();
if (value == 1) {
System.out
.println("The first non repeating character found is: "
+ character);
break;
}
}
}
}

We used LinkedHashMap specifically because LinkedHashMap maintains the insertion order that is if you would have used HashMap which doesnot maintains any order so if the String we are inputting is "aabciahjbbco" , with HashMap the order will not be maintained while inserting so when we retrieve the values it can give any value out of i,h,j which is incorrect as we are looking for first non repeated character.




No comments:

Post a Comment