I am currently reviewing CTCI(Cracking the Coding Interview)
The question is asking me to implement an algorithm which checks whether the characters in a string are all unique however they do not want me to use any auxillary data structures
My Algorithm is relatively straight forward, Two nested loops one starting at 0(i) and another at 1(i+1)
If the condition finds two characters that are equal then I print duplicate characters have been found.
public static void checkUnique(String s)
{
for(int i = 0; i<s.length(); ++i)
{
for(int j = i +1; j<s.length(); ++j)
{
if(s.charAt(i) == s.charAt(j))
{
System.out.println("Duplicates found");
}
}
}
}
My question
- Is this an optimal algorithm, my second approach was to sort, and find a pair which contains the same characters.
- Obviously a hashmap would be beneficial here, but questions does not really want me to use it.
I have refactored the code and hopefully now it is correct.
Is there any way of reducing it to an O(N) runtime. What if we keep track of the Unicode code's for each char character. I doubt O(N^2) is the best we can do here.