The following code returns the first location in the string s1 where any character from the string s2 occurs. Its worst time complexity is O(m+n). How?
#include<stdio.h>
int any(char *s1, char *s2)
{
char array[256];
int i;
if (s1 == NULL) {
if (s2 == NULL) {
return(0);
} else {
return(-1);
}
}
for(i = 0; i < 256; i++) {
array[i] = 0;
}
while(*s2 != '\0') {
array[*s2] = 1;
s2++;
}
i = 0;
while(s1[i] != '\0') {
if (array[s1[i]] == 1) {
return(i);
}
i++;
}
return(-1);
}
It does this in two steps.
It initializes an array of size 256 (representing each of the valid characters for its input strings), and for each letter in s2 (n) marks that characters spot in the array as 1 to indicate that that character is present.
It iterates across the characters in s1 (0 up to m), checking each characters position in the array to see if it is set to “present” (1), which would indicate that it is in the second string. If it is, it returns the index of that character in s1. If none of the characters in s1 are present in s2 (discovered at m), it returns -1.
Since step 1 will always take n (length of s2), and step 2 will take up to m (the length of s1), the worst case is O(m+n), which occurs only when either there are no matches, or only the last character in s1 is present in s2.