Sparse Search

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

Examples:

Input : arr[] = {"for", "geeks", "", "", "", "", "ide", 
                      "practice", "", "", "", "quiz"}
          x = "geeks"
Output : 1

Input : arr[] = {"for", "geeks", "", "", "", "", "ide", 
                      "practice", "", "", "", "quiz"}, 
          x = "ds"
Output : -1

If there were no empty strings then we could’ve simply performed binary search. We can still use Binary Search with a little modification. If our mid is empty we just have to move mid to closest Non-Empty string.

Below is a implementation of above approach.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP program to implement binary search
// in a sparse array.
#include <bits/stdc++.h>
using namespace std;
  
/* Binary Search in an array with blanks */
int binarySearch(string *arr, int low, int high, string x) {
  if (low > high)
    return -1;
  
  int mid = (low + high) / 2;
  
  /*Modified Part*/
  if (arr[mid] == "") {
    int left = mid - 1;
    int right = mid + 1;
  
    /*Search for both side for a non empty string*/
    while (1) {
  
      /* No non-empty string on both sides */
      if (left < low && right > high)
        return -1;
  
      if (left >= low && arr[left] != "") {
        mid = left;
        break;
      }
  
      else if (right <= high && arr[right] != "") {
        mid = right;
        break;
      }
  
      left--;
      right++;
    }
  }
  
  /* Normal Binary Search */
  if (arr[mid] == x)
    return mid;
  else if (arr[mid] > x)
    return binarySearch(arr, low, mid - 1, x);
  else
    return binarySearch(arr, mid + 1, high, x);
}
  
int sparseSearch(string arr[], string x, int n) {
  return binarySearch(arr, 0, n - 1, x);
}
  
int main() {
  ios_base::sync_with_stdio(false);
  
  string arr[] = {"for", "geeks", "", "", "", "", "ide"
                      "practice", "", "", "", "quiz"};
  string x = "geeks";
  int n = sizeof(arr) / sizeof(arr[0]);
  int index = sparseSearch(arr, x, n);
  if (index != -1)
    cout << x << " found at index " << index << "\n";
  else
    cout << x << " not found\n";
  return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement binary search
// in a sparse array.
  
class solution
{
  
// Binary Search in an array with blanks 
static int binarySearch(String arr[], int low, int high, String x) {
if (low > high)
    return -1;
  
int mid = (low + high) / 2;
  
//Modified Part
if (arr[mid] == "") {
    int left = mid - 1;
    int right = mid + 1;
  
    /*Search for both side for a non empty string*/
    while (true) {
  
    /* No non-empty string on both sides */
    if (left < low && right > high)
        return -1;
  
    if (left >= low && arr[left] != "") {
        mid = left;
        break;
    }
  
    else if (right <= high && arr[right] != "") {
        mid = right;
        break;
    }
  
    left--;
    right++;
    }
}
  
/* Normal Binary Search */
if (arr[mid] == x)
    return mid;
else if (x.compareTo(arr[mid]) < 0)
    return binarySearch(arr, low, mid - 1, x);
else
    return binarySearch(arr, mid + 1, high, x);
}
  
static int sparseSearch(String arr[], String x, int n) {
return binarySearch(arr, 0, n - 1, x);
}
  
public static void main(String args[]) {
  
String arr[] = {"for", "geeks", "", "", "", "", "ide"
                    "practice", "", "", "", "quiz"};
String x = "geeks";
int n = x.length();
int index = sparseSearch(arr, x, n);
if (index != -1)
    System.out.println(x+ " found at index "+index);
else
    System.out.println(x+" not found");
  
}
}
  
// This code is implemented by 
// Surendra_Gangwar

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement binary search 
#  in a sparse array
  
def sparseSearch(arr , key , low , high):
  
    left = 0; right = 0
      
    while low <= high:
  
            mid = (low + high) // 2
  
            if arr[mid] == '':
                left = mid - 1
                right = mid + 1
  
                # Check for out of bounds
                if left < low and right > high:
                        return -1
  
                elif right <= high and arr[right] != '':
                        # Search right
                        mid = right
                  
  
                elif left >= low and arr[left] != '':
                        # Search left
                        mid = left
  
  
            if arr[mid] == key:
                print('Found string {} at index {}'.format
                     (arr[mid] , mid))
                return
  
            # Classical Binary search
            # search left
            elif arr[mid] > key:
                high = mid - 1
  
            # search right
            elif arr[mid] < key:
                low = mid + 1
      
            left -= 1
            right += 1
  
    return -1
  
  
if __name__ == '__main__':
  
    arr = ["for", "geeks", "", "", "", "", "ide", 
                    "practice", "", "", "", "quiz"]                 
    key = 'geeks'
  
    low = 0
    high = len(arr) - 1
      
    sparseSearch(arr , key , low , high)
  
# This is  Code contributed by 
# Ashwin Viswanathan

chevron_right


Output:

geeks found at index 1


My Personal Notes arrow_drop_up

A Coding Enthusiast Rails Developer

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.