Skip to content

Instantly share code, notes, and snippets.

@EnesKorukcu
Last active August 29, 2015 14:16
Show Gist options
  • Save EnesKorukcu/c326cc405c7fb2df8913 to your computer and use it in GitHub Desktop.
Save EnesKorukcu/c326cc405c7fb2df8913 to your computer and use it in GitHub Desktop.
Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures ?
/**
* Solution 1
* Time Complexity : O(n) where n is the length of the string
* Space Complexity : O(1)
* @param input
* @return boolean
*/
public static boolean checkSingularity1(String input) {
if(input.length() > 256) {
return false;
}
boolean[] chars = new boolean[256];
for(int i = 0; i < input.length(); i++) {
int charIntValue = input.charAt(i);
if(chars[charIntValue]) {
return false;
}
chars[charIntValue] = true;
}
return true;
}
/**
* Solution 2
* Time Complexity : O(n) where n is the length of the string
* Space Complexity : O(1)
* @param input
* @return boolean
*/
public static boolean checkSingularity2(String input) {
if(input.length() > 256) {
return false;
}
int checker = 0;
for(int i = 0; i < input.length(); i++) {
int val = input.charAt(i) - 'a';
if((checker & (1 << val)) > 0) {
return false;
}
checker |= (1 << val);
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment