Cracking the Code interview 1.1: Implement an algorithm to determine if a string has all unique characters and what if you can't use additional data structures.
(easy level)
// First with extra data structures.
// we can use a hashtable to remember the characters and a boolean to represent existing or not.
bool isUnique(string input) {
// if the input string size equals to 0 or 1, there is no repeats.
if(input.size() <= 1) return true;
bool hashMap[256] = {false};
for(int i = 0; i < input.size(); ++i) {
if(hashMap[input[i]]) return false;
hashMap[input[i]] = true;
}
return true;
}
If we are not allowed to use extra data structure. we will then need to confirm with the interviewer the encoding ways. UniCode or UTF-8, 32, 64 ?
// we are not allowed to use extra data structure. But we can use temporary value.
// The idea is simple:
// suppose the input ranges from 'a' to 'z' 'A' to 'Z' and we have input string: "abc"
// We use an integer's bits (64 bits) to remember whether the characters has showed up before.
// "abc" will be remembered by the integer as 0000...000111;
bool isUnique(string input) {
// same as above, we need to check the length of input.
if(input.size() <= 1) return true;
int characters = 0;
for(int i = 0; i < input.size(); ++i) {
// if the bit have been turned into '1', there is a repeat.
if(characters & (1 << int(input[i] - 'a'))) return false;
// otherwise, we set the bit as 1.
characters |= (1 << int(input[i] - 'a'));
}
return true;
}