Check if given string is prefix subarray of the given array


A subarray of an array is a contiguous part of the array in which we take a group of consecutive elements while also maintaining the relative ordering of elements as present in the original array.

Example − Some valid subarrays are − etc.

A prefix subarray is a special type of subarray that begins with the first element of the array and ends at some ith index where 0 <= i < sizeof(array).

Problem Statement

We are given a string s and a vector of strings v[]. The task at hand is to check whether s is a prefix subarray of v.

For Example

Input: s = “tutorialspoint”, v = {“tutorials”, “point”} 
Output: True

Explanation

Upon concatenating the elements of the vector v from the beginning, s can be obtained. “tutorials” + “point” = “tutorialspoint” = string s. Thus s is the prefix subarray of v.

For Example

Input: s = “abcd”, v = {“ab”, “de”, “gh”}
Output: False

Explanation

s is not a prefix subarray of v because upon concatenating v we get “abdegh”. If we consider the prefix “abd” of v, it can be noticed that the character ‘c’ is missing. Thus string s is not a prefix subarray of v.

For Example

Input: s = “”, v = {“wer”, “adtrh”, “wefa”, “fafg”}
Output: True

Explanation

The empty string is a subarray of any array, and it starts at the beginning of the array and ends at the beginning of the array.

Solution Approach

An intuitive and brute force approach is to concatenate all the elements of the array and simply compare whether the characters of the resultant string, starting from the beginning, match with the given string s. If yes, then we can say that the given string is a prefix subarray of the given array. Else we return false.

Pseudocode

  • Initialize an empty string res.

  • Traverse the array and add the current element to the string res.

  • Take 2 pointers, i and j, pointing at the first element of the given string and the resultant string res, respectively.

  • Compare the characters at position i and j uptill we do not reach the end of either string

    • If the characters are not the same

      • Return false

    • else

      • Simply increment i and j to check the next character in line

  • If we finished traversing the resultant string and not the given string, that means the given string is shorter than the resultant string and is therefore not its prefix subarray

    • Return false

  • Return true

Algorithm

function checkIfSubarray()

  • Initialise string res = “”

  • for i: 0 to n-1

    • res += arr[i]

  • Initialize i = 0, j = 0, len1 = size of s, len2 = size of res

  • while i < len1 and j < len2

    • if s[i] ≠ res[j]

      • return false

    • else

      • i++

      • j++

  • If i < len1

    • return false

  • return true

function main()

  • Initialize array of strings arr

  • Initialise string s

  • Define n as size of array

  • Function call checkIfSubarray(arr, n, s)

  • Store answer in boolean variable ans

  • Print ans

Example: C++ Program

The following C++ program calls the function checkIfSubarray() to determine whether a string s is the prefix subarray of a given array of strings. The function concatenates all the elements of the array in an empty string res using a for loop. It then traverses both the strings simultaneously with the help of two pointers, i and j, starting from the beginning. If at any point the characters of the strings do not match, it can be concluded that string s is not a prefix subarray of the given array. Else we just go on comparing by incrementing i and j at each step in the while loop. At the end we keep a check whether the given string is longer than the res string and if that is the case we simply return false. In any other case, we can say that the string is a prefix subarray of the array so we return true.

// C++ program to find whether a string is the prefix subarray of an array of strings
#include <iostream>
#include <string>
using namespace std;

// function to check whether a given string is a prefix subarray of an array of strings
bool checkIfSubarray(string arr[], int n, string s){
   string res = "";
   // concatenate elements of arr to res
   for (int i = 0; i < n; i++)    {
      res += arr[i];
   }
   int i = 0;
   int j = 0;
   int len1 = s.length(); // size of given string
   int len2 = res.length(); // size of resultant string
   // compare the characters of the two strings starting from the beginning
   while (i < len1 && j < len2){
      if (s[i] != res[j]){
         return false;
      } else {
         i++;
         j++;
      }
   }
   // if given string is longer than res string
   if (i < len1){
      return false;
   }
   // if given string is a prefix subarray of given array of strings
   return true;
}
int main(){
   // Input array
   string arr[] = {"abc", "dge", "bgvc", "pwor"};
   string s = "abcd";
   int n = sizeof(arr) / sizeof(arr[0]);
   bool ans = checkIfSubarray(arr, n, s);
   cout << ans << endl;
   return 0;
}

Output

1

Time and Space Complexity

Time Complexity − O(n + min(len1, len2))

  • The function checkIfSubarray() uses two loops. The first loop runs n times where n is the length of the array.

  • The second loop runs min(len1, len2) times, where len1 is the length of the given string s and len2 is the length of the resultant string res.

  • Overall time complexity of the program can be said to be O(n + min(len1, len2)). Thus we can say that the program runs in linear time.

Space Complexity − O(n)

The program makes use of a string res to store all the characters of the given array of strings. Let n be the number of characters in the array. Thus the overall space complexity of the code is O(n).

Conclusion

In this article, we discussed an intuitive and simple approach to check whether a given string is the prefix subarray of a given array of strings. The program runs in linear time and requires linear auxiliary space as well. The concept of prefix subarrays and the problem statement were explained with the help of suitable examples. Furthermore, the article discusses the solution approach and also provides the pseudocode, algorithm and C++ program along with time and space complexity.

Updated on: 25-Oct-2023

36 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements