Microsoft Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
Would the complexity be O(n+m) while implementing using a hashtable or O(1)? HashTable operations are O(1) but are we not going to write a loop to add and check the values so won't the complexity be O(m+n)?
I think the most difficult part of this question is its English :). What it asks is to return the index of the 1st character in "src" that matches any character in "find".
KMP can work with a variant, such that if ith element in "src" does not match anything in "find", starts from src[i+1] and go through KMP again. However, you will need to rebuild the partial match table, and the run time is at least O(n^2).
I think if I am asked this question again, I'd ask if the strings are ASCII. If they are, I can simply build a hashtable with "find" with 256 buckets using the characters as the key. Then loop through "src" while doing search in the hashtable. This will be O(n+m) with n=src.length and m=find.length. Similarly, instead of a hashtable, I can use a 256 element interger/bit array.
Your thoughts?
Please read the the problem well :) Kmp is too bid cannon for this!
The fastest is: as there are less than 32 character types (let's suppose it is not Unicode) you can represent the search values in an integer: go through the find array and OR it's shifted values to the integer, marking the bit 1 if it's a searchable char (a> 0001 b>0010 ...)
Then start processing the the input, AND ing all shifted values to this array. If the result is greater than 0 that is your first match.
Please note that even though hashtable is considered to be O(1) no interviewer will accept the answer for a fixed size input as optimal ;)
- Add every char from src to unordered_hashmap with the char as key and no of times it occurs in the src string as value
- hence, src will be transformed as (g,2) (a,2) and (b,2) in the map.
- now check if every char from "find" string is is present in the map.
- if any char is found, find the index of that char in the "find" string and thats it !
- fetching from map is O(1)
- looking up every char from "find" takes O(n) where n=strlen(find)
- additional space of O(n) for the map !
Build a hash look up table of all chars in src string. Then scan find string and return index of first char that exists in look up table.
- tom February 10, 2012