Example 1
Output: true
Explanation: Input string has all distinct characters.
Example 2
Output: false
Explanation: There is one character 'l' appeared twice, so this string does not have unique characters.
- In this solution, we are going to sort the character array of the input String, and then loop through all characters in the array and see if any character matched with previous character. If current and previous characters are same, then String does not have unique characters, otherwise it has unique characters.
- Base case is, if the input String length is 0 or 1, then String has unique characters (as shown in line 5 in below code).
Complexity Analysis:
Above code runs in O(n log n) time complexity where
- In this solution, we are going to loop through the characters of input String, then store each visited character into an intermediate data structure HashSet.
- While looping through each character, check if the same character has already been visited or not by using the method
.
Complexity Analysis:
Above code runs in O(n)time complexity where
- In this solution we are going to assume that the input String has only ASCII characters, there are 128 characters in ASCII.
- This solution is very much similar to above solution 2, except that we are using a temp array instead of a Set to keep track of visited characters as we loop through characters of the input String.
- As we loop through each character in the input String, mark corresponding ASCII index in the array with value
1 , but if the value at the index is already 1, that means this particular characater is already visited.
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
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