Determine if a string has all Unique Characters
Given a string, determine if the string has all unique characters.
Solutions
You should first ask your interviewer if the string is an ASCII string or a Unicode string. Asking this question will show an eye for detail and a solid foundation in computer science. We'll assume for simplicity the character. set is ASCII. If this assumption is not valid, we would need to increase the storage size. Also, ask if string is case-sensitive or not.
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.
Steps:
Check if string is null then return true.
Run first loop from first character to the end of string length.
Run second loop from one character ahead of first loop current character to the end of string length.
Compare first loop current character with second loop each character. If first loop current character is equal to the second loop current character, then return false.
Run the loop till end of all cycles.
If no character matched, then return true.
Note: Please note that the program is case-sensitive.
Complexity
Time Complexity: O(n²)
Auxiliary Space: O(1)
Approach 2 – Sorting
Using sorting based on ASCII values of characters.
Steps:
First sort the string characters.
Run loop from first character to the end of string length.
Compare loop current character with next character. If first current character is equal to the next character, then return false.
Run the loop till the end of string length.
If no character matched, then return true.
Note: Please note that the program is case-sensitive.
Complexity
Time Complexity: O(n log n)
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.
Steps:
Take an ASCII character constant with value
256
.Check if provided string length is greater than
256
characters then return false.Crate a Boolean array of
256
length with default value (false
).Run loop from first character to the end of string length.
Check if current loop character existence is true in Boolean array, then return false. Else set current character existence true in the Boolean array.
Run the loop till the end of string length.
If no character matched, then return true.
Note: Please note that the program is case-sensitive.
Complexity
Time Complexity: O(1)
Auxiliary Space: O(1)
Note: Here, the size of the character set ( which is 256
).
Last updated