Open In App

Frequency of a string in an array of strings

Last Updated : 20 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

You are given a collection of strings and a list of queries. For every query there is a string given. We need to print the number of times the given string occurs in the collection of strings. 

Examples: 

Input : arr[] = {wer, wer, tyu, oio, tyu}
q[] = {wer, tyu, uio}
Output : 2 2 0
Explanation :
q[0] appears two times in arr[], q1[] appears

Method 1 (Simple)

The idea is simple, for every query string we compare it with all strings given in array. If the query string is matches, we increment count. 

C++
// C++ program to find number of times a 
// string appears in an array.
#include<bits/stdc++.h>
using namespace std;

// Returns count of occurrences of s in arr[] 
int search(string arr[], string s, int n)
{
    int counter = 0;

    for(int j = 0; j < n; j++)
    
        // Checking if string given in query
        // is present in the given string. 
        // If present, increase times
        if (s == arr[j])
            counter++;

   return counter;
}
 
void answerQueries(string arr[], string q[], 
                   int n, int m)
{
    for(int i = 0; i < m; i++)
        cout << search(arr, q[i], n) << " ";
}    

// Driver Code
int main()
{
    string arr[] = { "aba", "baba", 
                     "aba", "xzxb" };
    string q[]   = { "aba", "xzxb", "ab" };
    
    int n = sizeof(arr) / sizeof(arr[0]);
    int m = sizeof(q) / sizeof(q[0]);
    
    answerQueries(arr, q, n, m);
}

// This code is contributed by rutvik_56
Java
// Java program to find number of times a string
// appears in an array.
class SubString
{
    /* Returns count of occurrences of s in arr[] */
    static int search(String[]arr, String s)
    {
            int counter = 0;
            for (int j = 0; j < arr.length; j++)

                /* checking if string given in query is
                  present in the given string. If present,
                  increase times*/
                if (s.equals(arr[j]))
                    counter++;

           return counter;
    }

    static void answerQueries(String[] arr, String q[])
    {
        for (int i=0;i<q.length; i++)
            System.out.print(search(arr, q[i]) + " ");
    }

    /* driver code*/
    public static void main(String[] args) {

        String[] arr = {"aba","baba","aba","xzxb"};
        String[] q   = {"aba","xzxb","ab"};
        answerQueries(arr, q);
    }
}
C#
// C# program to find number of 
// times a string appears in an array.
using System;

class SubString
{
    /* Returns count of occurrences of s in arr[] */
    static int search(String[]arr, String s)
    {
            int counter = 0;
            for (int j = 0; j < arr.Length; j++)

                /* checking if string given in query is
                present in the given string. If present,
                increase times*/
                if (s.Equals(arr[j]))
                    counter++;

        return counter;
    }

    static void answerQueries(String []arr, String []q)
    {
        for (int i = 0; i < q.Length; i++)
            Console.Write(search(arr, q[i]) + " ");
    }

    // Driver code
    public static void Main() 
    {
        String []arr = {"aba","baba","aba","xzxb"};
        String []q = {"aba","xzxb","ab"};
        answerQueries(arr, q);
    }
}

//This code is contributed by nitin mittal
Javascript
<script>
// javascript program to find number of times a string
// appears in an array.
    /* Returns count of occurrences of s in arr */
    function search( arr,  s) {
        var counter = 0;
        for (j = 0; j < arr.length; j++)

            /*
             * checking if string given in query is present in the given string. If present,
             * increase times
             */
            if (s === (arr[j]))
                counter++;

        return counter;
    }

    function answerQueries( arr,  q) {
        for (i = 0; i < q.length; i++)
            document.write(search(arr, q[i]) + " ");
    }

    /* driver code */
        var arr = [ "aba", "baba", "aba", "xzxb" ];
        var q = [ "aba", "xzxb", "ab" ];
        answerQueries(arr, q);

// This code is contributed by gauravrajput1 
</script>
PHP
<?php
# Php program to find number of 
# times a string appears in an array.

# Returns count of occurrences of s in arr[] 
function search($arr, $s)
{
    $counter = 0;
    for ($j=0; $j<count($arr); $j++)
    {
        # checking if string given in query 
        # is present in the given string. 
        # If present, increase times
        if ($s == ($arr[$j]))
            $counter += 1;
    }
    return $counter;
}
function answerQueries($arr, $q)
{
    for ($i=0; $i<count($q); $i++)
    {
        echo(search($arr, $q[$i]));
        echo (" ");
    }
}

# Driver code

$arr = array("aba", "baba", "aba", "xzxb");
$q = array("aba", "xzxb", "ab");
answerQueries($arr, $q);

# This code is contributed 
# by Shivi_Aggarwal
?>
Python3
# Python3 program to find number of 
# times a string appears in an array.

# Returns count of occurrences of s in arr[] 
def search(arr, s):
    counter = 0
    for j in range(len(arr)):
        
        # checking if string given in query 
        # is present in the given string.  
        # If present, increase times
        if (s == (arr[j])):
            counter += 1

    return counter

def answerQueries(arr, q):
    for i in range(len(q)):
        print(search(arr, q[i]), 
                     end = " ")

# Driver code
if __name__ == '__main__':
    arr = ["aba", "baba", "aba", "xzxb"]
    q = ["aba", "xzxb", "ab"]
    answerQueries(arr, q)

# This code is contributed 
# by PrinciRaj19992

Output
2 1 0 

Time Complexity: O(m * n * p) where m is the number of queries, n is the length of array and p is the max length of string in the array. For each query, we are traversing the whole array so O(m * n) and O(p) for comparing the two strings. Hence, O(m * n * p).
Auxiliary Space: O(1)

Method 2 (Using Trie)

Trie an efficient data structure used for storage and retrieval of data like strings. The searching complexity is optimal as key length. 
In this solution we insert the collection of strings in the Trie data structure so they get stored in it. One important thing is, we keep count of occurrences in leaf nodes. Then we search the Trie for the given query string and check if it is present in the Trie. 

CPP
// C++ program to count number of times
// a string appears in an array of strings
#include<iostream>
using namespace std;

const int MAX_CHAR = 26;

struct Trie
{
    // To store number of times
    // a string is present. It is
    // 0 is string is not present
    int cnt;

    Trie *node[MAX_CHAR];
    Trie()
    {
        for(int i=0; i<MAX_CHAR; i++)
            node[i] = NULL;
        cnt = 0;
    }
};

/* function to insert a string into the Trie*/
Trie *insert(Trie *root,string s)
{
    Trie *temp = root;
    int n = s.size();
    for(int i=0; i<n; i++)
    {
        /*calculation ascii value*/
        int index = s[i]-'a';

        /* If the given node is not already
          present in the Trie than create
          the new node*/
        if (!root->node[index])
            root->node[index] = new Trie();

        root = root->node[index];
    }
    root->cnt++;
    return temp;
}

/* Returns count of occurrences of s in Trie*/
int search(Trie *root, string s)
{
    int n = s.size();
    for (int i=0; i<n; i++)
    {
        int index = s[i]-'a';
        if (!root->node[index])
            return 0;
        root = root->node[index];
    }
    return root->cnt;
}

void answerQueries(string arr[], int n, string q[],
                                           int m)
{
    Trie *root = new Trie();

    /* inserting in Trie */
    for (int i=0; i<n; i++)
        root = insert(root,arr[i]);

    /* searching the strings in Trie */
    for (int i=0; i<m; i++)
        cout << search(root, q[i]) << " ";

}

/* Driver code */
int main()
{
    string arr[] = {"aba","baba","aba","xzxb"};
    int n = sizeof(arr)/sizeof(arr[0]);

    string q[] = {"aba","xzxb","ab"};
    int m = sizeof(q)/sizeof(q[0]);

    answerQueries(arr, n, q, m);

    return 0;
}
Java
/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class GFG 
{
  
// Java program to count number of times
// a string appears in an array of string

static int MAX_CHAR = 26;

static class Trie
{
    // To store number of times
    // a string is present. It is
    // 0 is string is not present
    public int cnt;

    public Trie node[] = new Trie[MAX_CHAR];
    public Trie()
    {
        for(int i=0; i<MAX_CHAR; i++)
            node[i] = null;
        cnt = 0;
    }
}

/* function to insert a string into the Trie*/
static Trie insert(Trie root,String s)
{
    Trie temp = root;
    int n = s.length();
    for(int i=0; i<n; i++)
    {
        /*calculation ascii value*/
        int index = (int)s.charAt(i) - (int)'a';

        /* If the given node is not already
          present in the Trie than create
          the new node*/
        if (root.node[index] == null)
            root.node[index] = new Trie();

        root = root.node[index];
    }
    root.cnt++;
    return temp;
}

/* Returns count of occurrences of s in Trie*/
static int search(Trie root, String s)
{
    int n = s.length();
    for (int i=0; i<n; i++)
    {
        int index = (int)s.charAt(i) - (int)'a';
        if (root.node[index] == null)
            return 0;
        root = root.node[index];
    }
    return root.cnt;
}

static void answerQueries(String arr[], int n, String q[],
                                           int m)
{
    Trie root = new Trie();

    /* inserting in Trie */
    for (int i=0; i<n; i++)
        root = insert(root,arr[i]);

    /* searching the Strings in Trie */
    for (int i=0; i<m; i++)
        System.out.print(search(root, q[i]) + " ");

}

// Driver Code
public static void main(String args[])
{
    String arr[] = {"aba","baba","aba","xzxb"};
    int n = arr.length;

    String q[] = {"aba","xzxb","ab"};
    int m = q.length;

    answerQueries(arr, n, q, m);
}
}

// This code is contributed by shinjanpatra
C#
// C# program to count number of times
// a string appears in an array of strings
using System;
using System.Collections.Generic;

class GFG
{
  static int MAX_CHAR = 26;

  class Trie
  {
    // To store number of times
    // a string is present. It is
    // 0 is string is not present
    public int cnt;

    public Trie[] node=new Trie[MAX_CHAR];
    public Trie()
    {
      for(int i=0; i<MAX_CHAR; i++)
        node[i] = null;
      cnt = 0;
    }
  }

  /* function to insert a string into the Trie*/
  static Trie insert(Trie root,string s)
  {
    Trie temp = root;
    int n = s.Length;
    for(int i=0; i<n; i++)
    {
      /*calculation ascii value*/
      int index = s[i]-'a';

      /* If the given node is not already
              present in the Trie than create
              the new node*/
      if (root.node[index]==null)
        root.node[index] = new Trie();

      root = root.node[index];
    }
    root.cnt++;
    return temp;
  }

  /* Returns count of occurrences of s in Trie*/
  static int search(Trie root, string s)
  {
    int n = s.Length;
    for (int i=0; i<n; i++)
    {
      int index = s[i]-'a';
      if (root.node[index]==null)
        return 0;
      root = root.node[index];
    }
    return root.cnt;
  }

  static void answerQueries(string[] arr, int n, string[] q,
                            int m)
  {
    Trie root = new Trie();

    /* inserting in Trie */
    for (int i=0; i<n; i++)
      root = insert(root,arr[i]);

    /* searching the strings in Trie */
    for (int i=0; i<m; i++)
      Console.Write(search(root, q[i]) + " ");

  }

  /* Driver code */
  static void Main(string[] args)
  {
    string[] arr = {"aba","baba","aba","xzxb"};
    int n = arr.Length;

    string[] q = {"aba","xzxb","ab"};
    int m = q.Length;

    answerQueries(arr, n, q, m);

  }
}
Javascript
<script>

// JavaScript program to count number of times
// a string appears in an array of strings
const MAX_CHAR = 26

class Trie{

    // To store number of times
    // a string is present. It is
    // 0 is string is not present
    constructor(){
        this.cnt = 0
        this.node = new Array(MAX_CHAR).fill(null)
    }
}

// function to insert a string into the Trie
function insert(root, s){
    let temp = root
    let n = s.length
    
    for(let i=0;i<n;i++){

        // calculation ascii value
        let index = s.charCodeAt(i) - 'a'.charCodeAt(0)

        // If the given node is not already
        // present in the Trie than create
        // the new node

        if (!root.node[index]){
            root.node[index] = new Trie()
        }
        root = root.node[index]
    }
    root.cnt += 1
    return temp
}

// Returns count of occurrences of s in Trie
function search(root,s){
    let n = s.length
    
    for(let i=0;i<n;i++){
        let index = s.charCodeAt(i) - 'a'.charCodeAt(0)
        if (!root.node[index])
            return 0
        root = root.node[index]
    }
    return root.cnt
}

function answerQueries(arr, n, q, m){

    let root = new Trie()

    // inserting in Trie
    for(let i = 0; i < n; i++){
        root = insert(root, arr[i])
    }

    // searching the strings in Trie
    for(let i = 0; i < m; i++){
        document.write(search(root, q[i]),"</br>")
    }
}

// Driver code

let arr = ["aba", "baba", "aba", "xzxb"]
let n = arr.length

let q = ["aba", "xzxb", "ab"]
let m = q.length

answerQueries(arr, n, q, m)

// This code is contributed by shinjanpatra

</script>
Python3
# Python3 program to count number of times
# a string appears in an array of strings
MAX_CHAR = 26

class Trie:

    # To store number of times
    # a string is present. It is
    # 0 is string is not present
    def __init__(self):
        self.cnt = 0
        self.node = [None for i in range(MAX_CHAR)]

# function to insert a string into the Trie
def insert(root, s):
    temp = root
    n = len(s)
    
    for i in range(n):

        # calculation ascii value
        index = ord(s[i]) - ord('a')

        ''' If the given node is not already
        present in the Trie than create
        the new node '''
        if (not root.node[index]):
            root.node[index] = Trie()
        root = root.node[index]    
    root.cnt += 1    
    return temp

# Returns count of occurrences of s in Trie
def search( root, s):
    n = len(s)
    
    for i in range(n):    
        index = ord(s[i]) - ord('a')
        if (not root.node[index]):
            return 0
        root = root.node[index]    
    return root.cnt

def answerQueries(arr, n, q, m):

    root = Trie()

    # inserting in Trie 
    for i in range(n):
        root = insert(root, arr[i])

    # searching the strings in Trie 
    for i in range(m):
        print(search(root, q[i]))

# Driver code 
if __name__=='__main__':

    arr = ["aba", "baba", "aba", "xzxb"]
    n = len(arr)

    q = ["aba", "xzxb", "ab"]
    m = len(q)

    answerQueries(arr, n, q, m)

    # This code is contributed by pratham76

Output
2 1 0 

Time Complexity: O(m * n)
Auxiliary Space: O(MAX_CHAR*L) where MAX_CHAR=26  and L is the maximum length of the input strings.

Method 3 (Hashing)

We can use a hash map and insert all given strings into it. For every query string, we simply do a look-up in the hash map.

  • Creates an unordered_map unmap which stores string as key and number of occurrences as value.
  • Iterates over the array arr[],
    • Counting the number of occurrences of each string.
  • Iterates over the q[], and for each string in it, it prints the number of occurrences of that string in the unmap.

Below is the implementation of the above approach:

C++
// C++ program to find number of times a
// string appears in an array.
#include <bits/stdc++.h>
using namespace std;

void answerQueries(vector<string>& arr, vector<string>& q)
{
    unordered_map<string, int> unmap;

    for (auto s : arr)
        unmap[s]++;

    for (auto s : q)
        cout << unmap[s] << " ";
}

// Driver Code
int main()
{
    vector<string> arr = { "aba", "baba", "aba", "xzxb" };
    vector<string> q = { "aba", "xzxb", "ab" };

    answerQueries(arr, q);
}

// This code is contributed by rutvik_56
Java
// Java program to find number of times a
// string appears in an array.
import java.io.*;
import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void answerQueries(List<String> arr,
                                     List<String> q)
    {
        Map<String, Integer> unmap = new HashMap<>();

        for (String s : arr) {
            unmap.put(s, unmap.getOrDefault(s, 0) + 1);
        }

        for (String s : q) {
            System.out.print(unmap.getOrDefault(s, 0)
                             + " ");
        }
    }

    public static void main(String[] args)
    {
        List<String> arr
            = List.of("aba", "baba", "aba", "xzxb");
        List<String> q = List.of("aba", "xzxb", "ab");

        answerQueries(arr, q);
    }
}
C#
// C# program to find number of times a
// string appears in an array.
using System;
using System.Collections.Generic;

class GFG {

  static void answerQueries(List<string> arr, List<string> q)
  {
    Dictionary<string, int> unmap = new Dictionary<string, int>();

    for (int i = 0; i < arr.Count; i++)
    {
      string s=arr[i];
      if(unmap.ContainsKey(s))
        unmap[s]++;
      else
        unmap[s]=1;
    }

    for (int i = 0; i < q.Count; i++)
    {
      string s = q[i];
      if(unmap.ContainsKey(s))
        Console.Write(unmap[s]+ " ");
      else
        Console.Write(0+ " ");

    }
  }

  // Driver Code
  public static void Main()
  {
    List<string> arr = new List<string>{ "aba", "baba", "aba", "xzxb" };
    List<string> q = new List<string>{ "aba", "xzxb", "ab" };

    answerQueries(arr, q);
  }
}

// // This code was contributed by poojaagrawal2.
Javascript
// Javascript program to find number of times a
// string appears in an array.

function answerQueries( arr, q)
{
    //unordered_map<string, int> unmap;
    let unmap=new Map();

    for (let s of arr)
    {
        if(unmap.has(s))
            unmap.set(s, unmap.get(s)+1);
        else
            unmap.set(s,1);
    }

    for (let s of q)
    {
        if(unmap.has(s))
            console.log(unmap.get(s));
        else
            console.log("0 ");
    }
}

// Driver Code
let arr = [ "aba", "baba", "aba", "xzxb" ];
let q = [ "aba", "xzxb", "ab" ];

answerQueries(arr, q);
Python3
# Python program to find number of times a
# string appears in an array.

def answerQueries(arr,q):
    unmap={};
    for i in arr:
        if i in unmap:
            unmap[i] += 1
        else:
            unmap[i] = 1

    for s in q:
        if s in unmap:
            print(unmap[s], end=" ");
        else:
            print("0", end=" ");
# Driver Code
arr = [ "aba", "baba", "aba", "xzxb" ];
q = [ "aba", "xzxb", "ab" ];

answerQueries(arr, q);

Output
2 1 0 

Time Complexity: O(m * p) where m is the number of queries and p is the max length of the string in the array. O(m) for queries and O(p) for accessing the string from the unordered_map.
Auxiliary Space: O(m)


Please refer Data Structure for Dictionary for comparison of hashing and Trie based solutions.

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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads