Example 1
Input: s = "square"
Output: true
Explanation: Input string has all distinct characters.
Example 2
Input: s = "hello"
Output: false
Explanation: There is one character 'l' appeared twice, so this string does not have unique characters.
Using Sorting public boolean isStringHasUniqueCharsUsingSorting(String input) { if(input == null) { return false; } if(input.length() == 0 || input.length() == 1) { // if input string is empty or has just one character return true; } char[] chars = input.toCharArray(); Arrays.sort(chars); for(int i=1; i<chars.length; i++) { if(chars[i] == chars[i-1]) { return false; } } return true; } >
Complexity Analysis:

Above code runs in O(n log n) time complexity where n is the size of the array, as we sorting the array. Space complexity is O(n) to store the characters in the array.

Using a HashSet public boolean isStringHasUniqueCharsUsingSet(String input) { if(input == null) { return false; } if(input.length() == 0 || input.length() == 1) { // if input string is empty or has just one character return true; } Set<Character> visited = new HashSet<>(); for(int i=0; i<input.length(); i++) { char c = input.charAt(i); boolean duplicateFound = visited.contains(c); if(duplicateFound) { return false; } visited.add(c); } return true; }
Complexity Analysis:

Above code runs in O(n)time complexity where n is the size of the array, as we are looping through characters of the input String and HashSet lookup takes O(1) constant time. Space complexity is O(n) to store the characters in the HashSet.

Using a temporary Array public boolean isStringHasUniqueCharsUsingTempArray(String input) { if(input == null) { return false; } if(input.length() == 0 || input.length() == 1) { // if input string is empty or has just one character return true; } int[] visited = new int[128]; for(int i=0; i<input.length(); i++) { char c = input.charAt(i); if(visited[c] != 0) { // this means the same character has already been visited return false; } visited[c] = 1; } return true; }

Note: Please note that if the input String has different character set other than ASCII, then the temp array size need to be adjusted accordingly.

Complexity Analysis:

Above code runs in O(n) time complexity where n is the size of the array, as we are looping through characters of the input String. Space complexity is O(1) as it is a constant size.

One can argue that the Solution 2 also has same Space complexity as Solution 3 if the input String has only ASCII characters and that is true.

Above examples source code can be found at GitHub link for Java code and JUnit tests can be found at GitHub link for Unit tests code