thePlatform Interview Question
Software Engineer in TestsCountry: United States
Interview Type: Phone Interview
The issue with this is they'd specified any sort of character, you could assume that means UNICODE and then just expand the size of your array but that might not suffice if they want to be extremely pedantic.
You could add in another O(n) operation to detect the highest valued character contained in your string and then allocate your array that size, even if we start using a different character set in the future you're covered.
Sorting uses minimal of O(nlogn) Time Complexity.
Better use the hash to validate the uniqueness. its O(n) algo
You can write a Small Hash by your own. its 5 line program and the array to hold the value for facilitation. You don't need to use any collection. Its your own Data Structure
@HB: The collections are not magic. It was implemented someway. You could do that yourself too and say you are not relying on it.
public static boolean isUniqueChars2(String str) {
boolean[] char_set = new boolean[256];
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i);
if (char_set[val]) return false;
char_set[val] = true;
}
}
Using hash is not allowed whether your write your own hash function or you use the one available in the java collections.
- teli.vaibhav February 09, 2013Sorting seems fine but it gives you O(n* log n) complexity.
A better means would be to declare a 256-bit BitSet. The index of each of the slots of this bit array would represent the Ascii code.
Now we just traverse through the given string and change the bit value in the BitSet(givenString.charAt(i)) from 0 to 1.
If we confront a 1 instead of a 0 for a character then we return false.
If we successfully traverse the whole string it implies the string has all unique characters.
O(n) would be the time complexity for this.