Count the strings that are subsequence of the given string
Last Updated :
21 Feb, 2023
Given a string S and an array arr[] of words, the task is to return the number of words from the array which is a subsequence of S.
Examples:
Input: S = “programming”, arr[] = {"prom", "amin", "proj"}
Output: 2
Explanation: "prom" and "amin" are subsequence of S while "proj" is not)
Input: S = “geeksforgeeks”, arr[] = {"gfg", "geek", "geekofgeeks", "for"}
Output: 3
Explanation:" gfg", "geek" and "for" are subsequences of S while "geekofgeeks" is not.
Naive Approach: The basic way to solve the problem is as follows:
The idea is to check all strings in the words array arr[] which are subsequences of S by recursion.
Below is the implementation of the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
bool isSubsequence(string& str1, int m, string& str2, int n)
{
if (m == 0)
return true;
if (n == 0)
return false;
// If last characters of two strings
// are matching
if (str1[m - 1] == str2[n - 1])
return isSubsequence(str1, m - 1, str2, n - 1);
// If last characters are not matching
return isSubsequence(str1, m, str2, n - 1);
}
// Function to count number of words that
// are subsequence of given string S
int countSubsequenceWords(string s, vector<string>& arr)
{
int n = arr.size();
int m = s.length();
int res = 0;
for (int i = 0; i < n; i++) {
if (isSubsequence(arr[i], arr[i].size(), s, m)) {
res++;
}
}
return res;
}
// Driver Code
int main()
{
string S = "geeksforgeeks";
vector<string> arr
= { "geek", "for", "geekofgeeks", "gfg" };
// Function call
cout << countSubsequenceWords(S, arr) << "\n";
return 0;
}
Java
// Java code for the above approach:
import java.util.*;
class GFG {
static boolean isSubsequence(String str1, int m, String str2, int n)
{
if (m == 0)
return true;
if (n == 0)
return false;
// If last characters of two strings
// are matching
if (str1.charAt(m-1) == str2.charAt(n - 1))
return isSubsequence(str1, m - 1, str2, n - 1);
// If last characters are not matching
return isSubsequence(str1, m, str2, n - 1);
}
// Function to count number of words that
// are subsequence of given string S
static int countSubsequenceWords(String s, List<String> arr)
{
int n = arr.size();
int m = s.length();
int res = 0;
for (int i = 0; i < n; i++) {
if (isSubsequence(arr.get(i), arr.get(i).length(), s, m)) {
res++;
}
}
return res;
}
// Driver Code
public static void main(String[] args)
{
String S = "geeksforgeeks";
List<String> arr
= new ArrayList<String>();
arr.add("geek");
arr.add("for");
arr.add("geekofgeeks");
arr.add("gfg");
// Function call
System.out.print(countSubsequenceWords(S, arr));
}
}
// This code is contributed by agrawalpoojaa976.
Python3
# Python3 code for the above approach
# Function to Compare if word is subsequence of string
def issubsequence(str1: str, m: int, str2: str, n: int) -> bool:
if m == 0:
return True
if n == 0:
return False
# If last characters of two strings are matching
if str1[m - 1] == str2[n - 1]:
return issubsequence(str1, m - 1, str2, n - 1)
# If last characters are not matching
return issubsequence(str1, m, str2, n - 1)
# Function to count number of words
# that are subsequence of given string S
def countsubsequencewords(s: str, arr: list) -> int:
res = 0
for word in arr:
if issubsequence(word, len(word), s, len(s)):
res += 1
return res
# Drive code
S = "geeksforgeeks"
arr = ["geek", "for", "geekofgeeks", "gfg"]
# Function call
print(countsubsequencewords(S, arr))
#This code is contributed by nikhilsainiofficial546
C#
using System;
using System.Collections.Generic;
using System.Linq;
class GFG {
static bool isSubsequence(string str1, int m, string str2, int n)
{
if (m == 0)
return true;
if (n == 0)
return false;
// If last characters of two strings
// are matching
if (str1[m - 1] == str2[n - 1])
return isSubsequence(str1, m - 1, str2, n - 1);
// If last characters are not matching
return isSubsequence(str1, m, str2, n - 1);
}
// Function to count number of words that
// are subsequence of given string S
static int countSubsequenceWords(string s, string[] arr)
{
int n = arr.Length;
int m = s.Length;
int res = 0;
for (int i = 0; i < n; i++) {
if (isSubsequence(arr[i], arr[i].Length, s, m)) {
res++;
}
}
return res;
}
// Driver Code
public static void Main()
{
string S = "geeksforgeeks";
string[] arr = { "geek", "for", "geekofgeeks", "gfg" };
// Function call
Console.Write(countSubsequenceWords(S, arr) + "\n");
}
}
// This code is contributed by ratiagarwal.
JavaScript
// Javascript code for the above approach:
function isSubsequence(str1, m, str2, n)
{
if (m == 0)
return true;
if (n == 0)
return false;
// If last characters of two strings
// are matching
if (str1[m - 1] == str2[n - 1])
return isSubsequence(str1, m - 1, str2, n - 1);
// If last characters are not matching
return isSubsequence(str1, m, str2, n - 1);
}
// Function to count number of words that
// are subsequence of given string S
function countSubsequenceWords(s, arr)
{
let n = arr.length;
let m = s.length;
let res = 0;
for (let i = 0; i < n; i++) {
if (isSubsequence(arr[i], arr[i].length, s, m)) {
res++;
}
}
return res;
}
// Driver Code
let S = "geeksforgeeks";
let arr = [ "geek", "for", "geekofgeeks", "gfg" ];
// Function call
console.log(countSubsequenceWords(S, arr));
// This code is contributed by poojaagarwal2.
Time Complexity: O(m*n)
Auxiliary Space: O(m) for recursion stack space
Efficient Approach: The above approach can be optimized based on the following idea:
- Map the index of characters of the given string to the respective characters array.
- Initialize the ans with the size of arr.
- Iterate over all the words in arr one by one.
- Iterate over each character.
- Find strictly greater index than prevIndex in dict.
- If the strictly greater element is not found, it means the current word is not a subsequence of the given string, so decrease res by 1.
- Else update prevIndex.
- After iterating over all the words, return ans.
Below is the implementation of the above approach:
C++
// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
// Function to count number of words that
// are subsequence of given string S
int countSubsequenceWords(string s, vector<string>& arr)
{
unordered_map<char, vector<int> > dict;
// Mapping index of characters of given
// string to respective characters
for (int i = 0; i < s.length(); i++) {
dict[s[i]].push_back(i);
}
// Initializing res with size of arr
int res = arr.size();
for (auto word : arr) {
// Index where last character
// is found
int prevIndex = -1;
for (int j = 0; j < word.size(); j++) {
// Searching for strictly
// greater element than prev
// using binary search
auto x = upper_bound(dict[word[j]].begin(),
dict[word[j]].end(),
prevIndex);
// If strictly greater index
// not found, the word cannot
// be subsequence of string s
if (x == dict[word[j]].end()) {
res--;
break;
}
// Else, update the prevIndex
else {
prevIndex = *x;
}
}
}
return res;
}
// Driver Code
int main()
{
string S = "geeksforgeeks";
vector<string> arr
= { "geek", "for", "geekofgeeks", "gfg" };
// Function call
cout << countSubsequenceWords(S, arr) << "\n";
return 0;
}
Java
import java.util.*;
class Main
{
// Function to count number of words that
// are subsequence of given string S
static int countSubsequenceWords(String s, List<String> arr) {
Map<Character, List<Integer> > dict = new HashMap<>();
// Mapping index of characters of given
// string to respective characters
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
List<Integer> list = dict.getOrDefault(c, new ArrayList<>());
list.add(i);
dict.put(c, list);
}
// Initializing res with size of arr
int res = arr.size();
for (String word : arr)
{
// Index where last character
// is found
int prevIndex = -1;
for (int j = 0; j < word.length(); j++)
{
// Searching for strictly
// greater element than prev
// using binary search
List<Integer> indices = dict.get(word.charAt(j));
int x = binarySearch(indices, prevIndex);
// If strictly greater index
// not found, the word cannot
// be subsequence of string s
if (x == -1) {
res--;
break;
}
// Else, update the prevIndex
else {
prevIndex = indices.get(x);
}
}
}
return res;
}
static int binarySearch(List<Integer> indices, int target) {
int l = 0, r = indices.size() - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (indices.get(mid) <= target) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return l < indices.size() ? l : -1;
}
public static void main(String[] args) {
String S = "geeksforgeeks";
List<String> arr = Arrays.asList("geek", "for", "geekofgeeks", "gfg");
// Function call
System.out.println(countSubsequenceWords(S, arr));
}
}
// This code is contributed by lokeshpotta20.
Python3
import collections
# Function to count number of words that
# are subsequence of given string S
def countSubsequenceWords(s, arr):
dict = collections.defaultdict(list)
# Mapping index of characters of given
# string to respective characters
for i in range(len(s)):
dict[s[i]].append(i)
# Initializing res with size of arr
res = len(arr)
for word in arr:
# Index where last character
# is found
prevIndex = -1
for j in range(len(word)):
# Searching for strictly
# greater element than prev
# using binary search
x = None
for i in range(len(dict[word[j]])):
if dict[word[j]][i] > prevIndex:
x = dict[word[j]][i]
break
# If strictly greater index
# not found, the word cannot
# be subsequence of string s
if x is None:
res -= 1
break
else:
prevIndex = x
return res
# Driver Code
if __name__ == "__main__":
S = "geeksforgeeks"
arr = ["geek", "for", "geekofgeeks", "gfg"]
# Function call
print(countSubsequenceWords(S, arr))
C#
// C# code for the above approach:
using System;
using System.Collections.Generic;
public class GFG
{
// Function to count number of words that
// are subsequence of given string S
static int CountSubsequenceWords(string s,
List<string> arr)
{
Dictionary<char, List<int> > dict
= new Dictionary<char, List<int> >();
// Mapping index of characters of given
// string to respective characters
for (int i = 0; i < s.Length; i++) {
char c = s[i];
if (!dict.ContainsKey(c))
dict[c] = new List<int>();
dict[c].Add(i);
}
// Initializing res with size of arr
int res = arr.Count;
foreach(string word in arr)
{
// Index where last character
// is found
int prevIndex = -1;
for (int j = 0; j < word.Length; j++) {
// Searching for strictly
// greater element than prev
// using binary search
List<int> indices = dict[word[j]];
int x = BinarySearch(indices, prevIndex);
// If strictly greater index
// not found, the word cannot
// be subsequence of string s
if (x == -1) {
res--;
break;
}
// Else, update the prevIndex
else {
prevIndex = indices[x];
}
}
}
return res;
}
static int BinarySearch(List<int> indices, int target)
{
int l = 0, r = indices.Count - 1;
while (l <= r) {
int mid = l + (r - l) / 2;
if (indices[mid] <= target) {
l = mid + 1;
}
else {
r = mid - 1;
}
}
return l < indices.Count ? l : -1;
}
static public void Main(string[] args)
{
string S = "geeksforgeeks";
List<string> arr
= new List<string>{ "geek", "for",
"geekofgeeks", "gfg" };
// Function call
Console.WriteLine(CountSubsequenceWords(S, arr));
}
}
// This code is contributed by Prasad Kandekar(prasad264)
JavaScript
// JavaScript code for the above approach:
// Function to count number of words that are subsequence of given string S
function countSubsequenceWords(s, arr) {
let dict = {};
// Mapping index of characters of given string to respective characters
for (let i = 0; i < s.length; i++) {
let c = s[i];
let list = dict[c] || [];
list.push(i);
dict[c] = list;
}
// Initializing res with size of arr
let res = arr.length;
for (let word of arr) {
// Index where last character is found
let prevIndex = -1;
for (let j = 0; j < word.length; j++) {
// Searching for strictly greater element than prev
// using binary search
let indices = dict[word[j]] || [];
let x = binarySearch(indices, prevIndex);
// If strictly greater index not found, the word cannot
// be subsequence of string s
if (x === -1) {
res--;
break;
}
// Else, update the prevIndex
else {
prevIndex = indices[x];
}
}
}
return res;
}
function binarySearch(indices, target) {
let l = 0, r = indices.length - 1;
while (l <= r) {
let mid = l + Math.floor((r - l) / 2);
if (indices[mid] <= target) {
l = mid + 1;
} else {
r = mid - 1;
}
}
return l < indices.length ? l : -1;
}
let S = "geeksforgeeks";
let arr = ["geek", "for", "geekofgeeks", "gfg"];
// Function call
console.log(countSubsequenceWords(S, arr));
// This code is contributed by lokesh.
Time Complexity: O( m * s * log(n) ), where m is the length of the given string, s is the max length of the word of arr and n is the length of arr
Auxiliary Space: O(n)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem