Search in Sorted Array of Strings with Empty Entries
Medium
Last updated: Sep 13, 2025
Table of Contents
Problem
Given a sorted array of strings which is interspersed with empty strings, write a method to find the location of a given string.
Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”, “dad”, “”, “”] will return 4
Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”] will return -1
Solution
The worst we can do is O(n) where we just do a linear search.
I tried to do better in the sense that we do a binary search, however if we encounter “”, we have to exam both sides. In this way, worst case we still do a O(n) search but in average, it’s better off.
publicstaticint**findLocation**(String[] array, int i, int j, String str) {
int mid;
while (i <= j) {
mid = (i + j) / 2;
if (array[mid].equals("")) {
int leftIndex =**findLocation**(array, i, mid - 1, str);
if (leftIndex ==-1)
return**findLocation**(array, mid + 1, j, str);
elsereturn leftIndex;
} else {
if ([str.compareTo(array](http://str.compareTo(array)[mid]) == 0)return mid;
if ([str.compareTo(array](http://str.compareTo(array)[mid]) < 0) j = mid - 1;
if ([str.compareTo(array](http://str.compareTo(array)[mid]) > 0)## Problem
Given a sorted array of strings, which may contain empty strings (`""`), find the index of a given target string.
### Examples
#### Example 1
```d
Input:
array =["at", "", "", "", "ball", "", "", "car", "", "", "dad", "", ""] target ="ball"Output:
4
Explanation:
The string "ball" is found at index 4.
Input:
array =["at","","","","","ball","car","","","dad","",""] target ="ballcar"Output:
-1Explanation:
The string "ballcar"is not present in the array, so return-1.
Binary search is efficient for sorted arrays, but empty strings break direct comparison. The key idea is: when we hit an empty string, we search both sides to find the nearest non-empty string for comparison, then continue binary search as usual.
⏰ Time complexity: O(n) in the worst case, because if the array is mostly empty strings, we may have to scan linearly to find non-empty strings. In the average case, binary search dominates, so it’s closer to O(log n).
🧺 Space complexity: O(1), since only a constant amount of extra space is used for pointers and indices.