String str = "zzzzzbbbccccddehhhhiii";
int[] countingArray = new int[128];
str.chars().forEach(value -> countingArray[value]++);
int nonRepeatingCharAsInt = 0;
for (int i = 0; i < countingArray.length; i++) {
if (countingArray[i] == 1) {
nonRepeatingCharAsInt = i;
break;
}
}
System.out.println("character = " + Character.valueOf((char) nonRepeatingCharAsInt));
How will you find out first non-repeating character from a string
Upasana | April 23, 2019 | 2 min read | 257 views
Using Counting Array for storing number of occurrence of each alphabet
We can find the first non-repeating char from a string using the following algorithm in Big O(n) Time
First Pass
We can maintain a counting array for all possible alphabet values (ASCII code 0-128) and keep on counting the position of array based on Ascii value of character. This will be Big O(n) Time Complexity Task where n is number of letters in the string.
Second Pass
Iterate through the counting array and find the first index position where value is exactly 1, and then break. That will give us the ascii code of character that is non repeating.
caveats with this approach
-
We need to know in advance how many distinct characters are present in the input. The above program will only work for ASCII character set (128)
-
Memory required for storing counting array may be much more if input is UTF-8 because UTF-8 can have upto 232 unique characters
import java.util.LinkedHashMap;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static java.util.function.Function.identity;
public class NonRepeatingLetter {
public static void main(String[] args) {
findFirstNonRepeatingLetter(args[0], System.out::println);
}
private static void findFirstNonRepeatingLetter(String s, Consumer callback) {
s.chars()
.mapToObj(i -> Character.valueOf((char) i))
.collect(Collectors.groupingBy(identity(), LinkedHashMap::new, Collectors.counting()))
.entrySet().stream()
.filter(entry -> entry.getValue() == 1L)
.map(entry -> entry.getKey())
.findFirst().map(c -> {
callback.accept(c);
return c;
});
}
}
Top articles in this category:
- find single repeating number from a big array
- Cracking core java interviews - question bank
- Morgan Stanley Java Interview Questions
- Hibernate & Spring Data JPA interview questions
- ION Trading Java Interview Questions
- Top 50 Spring Interview Questions
- Multi-threading Java Interview Questions for Investment Bank