Finding the string in the sorted array of strings with empty strings

Problem

Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string.

Example

input: find "ball" in  {"at", "", "", "","ball", "", "", "car", "", "". "dad", "",""}

Output: 4


Answer


Binary Search approach, O(N)


This question is close to the classic binary search problem except for the fact that there are empty strings, which fail the binary search.

Basically, we start with the middle of the array and see if the string in the middle, M is the same as the target string.

If not, we check if a string M is earlier or later than the target alphabetically. 
If M is earlier, we search the right side of the array by halving the search space.
Otherwise, we search the left side of the array, which also halves the search space. 

The problem arise, when M is an empty string. When the empty string is encountered, we should search both sides of empty strings since we can not determine which side to search. In this case, we can't halve the search space.

Due to the empty string case, the overall running time can not be $O(\log N)$.

However, the running time will be less than $O(N)$ in practice.
Here is the complete code in C++.




Here is the python version of a solution.


UPDATE(2022-06-13): Solved the problem again with the binary search.


5:30: for algorithm
9:56: coding

Comments

Popular posts from this blog

Planting flowers with no adjacent flower plots

Find the maximum number of bomb that can be detonated