Given a sorted array of strings that is interspersed with empty strings, write a method to find the location of a given string.
Example1:
Input: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ta"
Output: -1
Explanation: Return -1 if s is not in words.
Example2:
Input: words = ["at", "", "", "", "ball", "", "", "car", "", "","dad", "", ""], s = "ball"
Output: 4
Note:
1 <= words.length <= 1000000
Solutions
Solution 1: Binary Search
We design a function \(dfs(i, j)\) to find the target string in the array \(nums[i, j]\). If found, return the index of the target string, otherwise return \(-1\). So the answer is \(dfs(0, n-1)\).
The implementation of the function \(dfs(i, j)\) is as follows:
If \(i > j\), return \(-1\).
Otherwise, we take the middle position \(mid = (i + j) / 2\), then recursively call \(dfs(i, mid-1)\). If the return value is not \(-1\), it means that the target string is found in the left half, return it directly. Otherwise, if \(words[mid] = s\), it means that the target string is found, return it directly. Otherwise, recursively call \(dfs(mid+1, j)\) and return.
In the worst case, the time complexity is \(O(n \times m)\), and the space complexity is \(O(n)\). Where \(n\) and \(m\) are the length of the string array and the length of the string \(s\), respectively.