InterviewSolution
| 1. |
You have a string like "helloWWorld". You need to find the first non-repeating character of this string. Which collection will you use for the same and explain the same? |
|
Answer» In the above example, the first non-repeating CHARACTER is ‘l’. As can be SEEN, we need to iterate over each element of the String and maintain a count of the number of times each unique character appears. In addition, we also need to maintain the order in which element occurs so that the first non-repeating character can be determined. For this scenario, we can use a LinkedHashMap. A linkedhashmap is similar to hashmap – so it essentially stores data as key-value pair - with the additional feature that it maintains the order of insertion of elements. It can alternatively also maintain the order of access to elements. The keys in the map are unique. To solve the above problem, we iterate the string starting from the first element. For each character, we check if the element already EXISTS in the map or not. Each new character is added to linkedhashmap (which maintains insertion order) with count 1. If the element already exists, the count is updated. Once the string TRAVERSAL is complete, we have the unique elements as well as their count in linkedhashmap. To find first non-repeating we now iterate over linkedhashmap and find the key that has a count greater than 1. Since this map maintains the order of insertion of elements, the first such key found would be the answer. |
|