You are given an array of strings strings that may contain empty strings scattered throughout, and a non-empty target string. Return the index of target in the array, or -1 if it does not appear.
The array is sorted in non-decreasing lexicographic order when the empty strings are ignored. Solve it with a binary search that handles the empty strings during the search.
Function Signature
def search_string(strings: list[str], target: str) -> int:
Rules
-
Empty strings can sit anywhere and carry no ordering information. The non-empty strings, read from left to right, are in non-decreasing lexicographic order.
-
Strings compare in ordinary lexicographic order, the same order Python's
<
uses on lowercase strings.
-
If
target
appears more than once, return the smallest index at which it appears.
-
If
target
does not appear, return
-1
.
Constraints
-
1 <= len(strings) <= 10^5
-
0 <= len(strings[i]) <= 100
-
1 <= len(target) <= 100
-
strings
is sorted in non-decreasing lexicographic order, ignoring empty strings
-
target
is not an empty string
-
All strings consist of lowercase English letters
Examples
Input: strings = ["apple", "", "", "banana", "", "cherry", "date", "", "fig"], target = "cherry"
Output: 5
Without the empty strings the array reads ["apple", "banana", "cherry", "date", "fig"], and "cherry" sits at index 5 of the original array.
Input: strings = ["", "", "abc", "", "def", "", "", "ghi", "jkl", ""], target = "xyz"
Output: -1
The non-empty strings are "abc", "def", "ghi" and "jkl", and none of them is "xyz".
Input: strings = ["", "bee", "", "", "bee", "bee", "cat", ""], target = "bee"
Output: 1
"bee" appears at indices 1, 4 and 5. The smallest of those is 1.