Adobe Interview Question
Software Engineer / DevelopersAs far as I understood question (please correct me if I'm wrong), if we have string which consists of characters s[0],s[1],...,s[n-1] the goal is to find such maximum length substring s[i],s[i+1],...,s[j] that for each k!=i there is no equal substring s[k],s[k+1],...,s[k+j-i].
If so, the only case when s[0],s[1],...,s[n-2] cannot be such maximum unique substring is when all symbols in original string are equal (because in suh case it should be equal to s[1],s[2],...,s[n-2]). If all symbols are equal, than largest unique substring is 1 symbol.
{{
#define ALPHABET_SIZE 26
string longestUniqueSubstring(string& str)
{
int i(0), j(0), max_len(1), max_idx(0);
vector<bool> visited(ALPHABET_SIZE);
for (int i=0; i < str.size(); i++)
{
while (visit[str[i]] && i != j)
visit[str[j]] = 0;
visit[str[i]] = 1;
if (i-j+1 > max_len) { max_len = i-j+1; max_idx = i ; }
}
return str.substr(max_idx, max_len);
}
}}
#include <stdio.h>
#include <stdlib.h>
main(int argc, char **argv) {
char *s;
unsigned long bits[4] = {0,0,0,0};
unsigned long set = 0;
unsigned char i,c;
register int curr;
int lus_candidate, lus;
int lus_candidate_len, lus_len;
if (argc == 2) {
s = argv[1];
} else {
printf("Nothing to do.\n");
exit(0);
}
lus_candidate = lus = curr = 0;
lus_candidate_len = lus_len = 0;
printf("string: %s\n",s);
for(curr=0; curr<strlen(s); curr++) {
c = (unsigned char)s[curr];
i = c >> 5;
set = 0x01<<(c & 0x1F);
if (bits[i] & set) {
do {
c = (unsigned char)s[lus_candidate];
bits[c >> 5] ^= 0x01<<(c & 0x1F);
lus_candidate_len--;
} while(s[lus_candidate++] != s[curr]);
}
bits[i] |= set;
if (++lus_candidate_len >= lus_len) {
lus = lus_candidate;
lus_len = lus_candidate_len;
}
}
if (lus_len) {
printf("lus %s%*s%.*s\n\"%.*s\" at offset %d with length=%d.\n",
lus==0 ? ":":": ",lus," ",lus_len,&s[lus],
lus_len,&s[lus],lus,(int)lus_len);
} else {
printf("Nothing found.\n");
}
}
Make an array of 26 ints "int hash[26]".
'start' and 'end' mark the current substring processed.
'mstart' and 'mend' mark the longest found substring till now
After this, your substring will be held within the indices 'mstart' and 'mend'
- Gaurav July 04, 2011PS: This is an algo i came up with not the perfect code. Please dont complain about the syntax.