1482. Sparse Catalogue Lookup
A warehouse catalogue stores product codes in an array codes. The non-empty codes are distinct lowercase strings kept in ascending alphabetical order, but retired entries have left blank strings "" scattered between them, so the array looks sparse.
Given codes and a non-empty string target, return the index at which target is stored, or -1 if it is absent. Use binary search: whenever the middle slot is blank, walk outward to the nearest non-empty slot that still lies inside the current search range and compare with that one instead (if the whole range is blank, the code is missing). With few blanks this takes O(log n) time; the worst case is O(n). Use O(1) extra space.
Example 1
- Input:
- codes = ["ant","","","bee","","cat","",""]target = "cat"
- Output:
- 5
- Explanation:
Skipping blanks, "cat" sits at index 5 of the sparse list.
Example 2
- Input:
- codes = ["","dog","","emu","",""], target = "cow"
- Output:
- -1
- Explanation:
"cow" would fall between blanks and "dog" but is absent, so the answer is -1.
Example 3
- Input:
- codes = ["kiwi"], target = "kiwi"
- Output:
- 0
- Explanation:
A single non-empty code that equals the target is found at index 0.
Constraints
1 ≤ n ≤ 1000
0 ≤ codes[i].length ≤ 10
Non-empty entries of codes are distinct lowercase strings in sorted order.
1 ≤ target.length ≤ 10
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(n)
- Space
- O(1)