![]() |
VOOZH | about |
Given a string, determine if the string has all unique characters.
Examples :
Input : abcd10jk Output : true Input : hutg9mnd!nk9 Output : false
Approach 1 - Brute Force technique: Run 2 loops with variable i and j. Compare str[i] and str[j]. If they become equal at any point, return false.
Output :
The String GeeksforGeeks has duplicate characters
Time Complexity: O(n2)
Auxiliary Space: O(1)
Note: Please note that the program is case-sensitive.
Approach 2 - Sorting: Using sorting based on ASCII values of characters
Output:
The String GeeksforGeeks has duplicate characters
Time Complexity: O(nlogn)
Auxiliary Space: O(1)
Approach 3 - Use of Extra Data Structure: This approach assumes ASCII char set(8 bits). The idea is to maintain a boolean array for the characters. The 256 indices represent 256 characters. All the array elements are initially set to false. As we iterate over the string, set true at the index equal to the int value of the character. If at any time, we encounter that the array value is already true, it means the character with that int value is repeated.
Output:
The String GeeksforGeeks has duplicate characters
Time Complexity: O(n)
Auxiliary Space: O(n)
Approach 4 - Without Extra Data Structure: The approach is valid for strings having alphabet as a-z. This approach is a little tricky. Instead of maintaining a boolean array, we maintain an integer value called checker(32 bits). As we iterate over the string, we find the int value of the character with respect to 'a' with the statement int bitAtIndex = str.charAt(i)-'a';
Then the bit at that int value is set to 1 with the statement 1 << bitAtIndex .
Now, if this bit is already set in the checker, the bit AND operation would make the checker > 0. Return false in this case.
Else Update checker to make the bit 1 at that index with the statement checker = checker | (1 <<bitAtIndex);
Output :
The String GeekforGeeks has duplicate characters
Time Complexity: O(n)
Auxiliary Space: O(1)
Exercise: Above program is case insensitive, you can try making the same program that is case sensitive i.e Geeks and GEeks both give different output.
Using Java Stream :
Reference:
Cracking the Coding Interview by Gayle
Approach 5: Using sets() function:
Below is the implementation of the above approach
Output:
The String GeeksforGeeks has duplicate characters
Time Complexity: O(nlogn)
Auxiliary Space: O(n)