Last active
August 29, 2015 14:16
-
-
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 ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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