01.01. Is Unique
Description
Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
Example 1:
Input: = "leetcode" Output: false
Example 2:
Input: s = "abc" Output: true
Note:
0 <= len(s) <= 100
Solutions
Solution 1: Bit Manipulation
Thinking
A hash set of seen characters decides uniqueness in one scan, in \(O(n)\) time and space proportional to the alphabet. The constraint \(n \le 100\) allows that, but the follow-up asks for no extra data structure.
If the string contains only lowercase letters, there are at most \(26\) symbols, so each bit of an integer can record whether a letter has appeared. On character \(c\), test the corresponding bit: if it is already \(1\), a duplicate exists; otherwise set the bit.
Bit operations turn membership tests and inserts into constant-time, constant-space work, which is why a mask is used instead of a hash table or boolean array.
Based on the examples, we can assume that the string only contains lowercase letters (which is confirmed by actual verification).
Therefore, we can use each bit of a \(32\)-bit integer mask to represent whether each character in the string has appeared.
The time complexity is \(O(n)\), where \(n\) is the length of the string. The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |