Skip to content
Related Articles

Related Articles

Queries to count subarrays consisting of given integer as the last element
  • Last Updated : 25 Feb, 2021

Given an array arr[] and an array query[] consisting of Q queries, the task for every ith query is to count the number of subarrays having query[i] as the last element. 
Note: Subarrays will be considered to be different for different occurrences of X.

Examples:

Input: arr[] = {1, 5, 4, 5, 6}, Q=3, query[]={1, 4, 5}
Output: 1 3 6
Explanation:
Query 1: Subarrays having 1 as the last element is {1}
Query 2: Subarrays having 4 as the last element are {4}, {5, 4}, {1, 5, 4}. Therefore, count is 3. 
Query 3: Subarrays having 5 as the last element are {1, 5}, {5}, {1, 5, 4, 5}, {5}, {4, 5}, {5, 4, 5}. Therefore, count is 6.
.
Input: arr[] = {1, 2, 3, 3}, Q = 3, query[]={3, 1, 2}
Output:7 1 2

Naive Approach: The simplest approach to solve the problem is to generate all the subarrays for each query and for each subarray, check if it consists of X as the last element.
Time Complexity: O(Q×N3)
Auxiliary Space: O(1)

Efficient Approach: To optimize the above approach, the idea is to use Hashing. Traverse the array and for every array element arr[i], search for its occurrences in the array. For every index, say idx, at which arr[i] is found, add (idx+1) to the count of subarrays having arr[i] as the last element.

Follow the steps below to solve the problem:

  • Initialize an unordered map, say mp, to store the number of subarrays having X as the last element.
  • Traverse the array and for every integer arr[i], increase mp[arr[i]] by (i+1).
  • Traverse the array query[] and for each query query[i], print mp[query[i]].

Below is the implementation of the above approach:



C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to perform queries to count the
// number of subarrays having given numbers
// as the last integer
int subarraysEndingWithX(
    int arr[], int N,
    int query[], int Q)
{
    // Stores the number of subarrays having
    // x as the last element
    unordered_map<int, int> mp;
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Stores current array element
        int val = arr[i];
 
        // Add contribution of subarrays
        // having arr[i] as last element
        mp[val] += (i + 1);
    }
 
    // Traverse the array of queries
    for (int i = 0; i < Q; i++) {
 
        int q = query[i];
 
        // Print the count of subarrays
        cout << mp[q] << " ";
    }
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 5, 4, 5, 6 };
 
    // Number of queries
    int Q = 3;
 
    // Array of queries
    int query[] = { 1, 4, 5 };
 
    // Size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    subarraysEndingWithX(arr, N, query, Q);
 
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to perform queries to count the
// number of subarrays having given numbers
// as the last integer
static void subarraysEndingWithX(
    int arr[], int N,
    int query[], int Q)
{
    // Stores the number of subarrays having
    // x as the last element
    HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
 
    // Traverse the array
    for (int i = 0; i < N; i++) {
 
        // Stores current array element
        int val = arr[i];
 
        // Add contribution of subarrays
        // having arr[i] as last element
        if(mp.containsKey(val))
            mp.put(val, mp.get(val)+(i+1));
        else
            mp.put(val, i+1);
    }
 
    // Traverse the array of queries
    for (int i = 0; i < Q; i++) {
 
        int q = query[i];
 
        // Print the count of subarrays
        System.out.print(mp.get(q)+ " ");
    }
}
 
// Driver Code
public static void main(String[] args)
{
    // Given array
    int arr[] = { 1, 5, 4, 5, 6 };
 
    // Number of queries
    int Q = 3;
 
    // Array of queries
    int query[] = { 1, 4, 5 };
 
    // Size of the array
    int N = arr.length;
 
    subarraysEndingWithX(arr, N, query, Q);
 
}
}
 
// This code is contributed by 29AjayKumar

Python3




# Python 3 program for the above approach
 
# Function to perform queries to count the
# number of subarrays having given numbers
# as the last integer
def subarraysEndingWithX(arr, N, query, Q):
   
    # Stores the number of subarrays having
    # x as the last element
    mp = {}
 
    # Traverse the array
    for i in range(N):
       
        # Stores current array element
        val = arr[i]
 
        # Add contribution of subarrays
        # having arr[i] as last element
        if val in mp:
            mp[val] += (i + 1)
        else:
            mp[val] = mp.get(val, 0) + (i + 1);
 
    # Traverse the array of queries
    for i in range(Q):
        q = query[i]
 
        # Print the count of subarrays
        print(mp[q],end = " ")
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    arr =  [1, 5, 4, 5, 6]
     
    # Number of queries
    Q = 3
     
    # Array of queries
    query  = [1, 4, 5]
     
    # Size of the array
    N = len(arr)
    subarraysEndingWithX(arr, N, query, Q)
     
    # This code is contributed by SURENDRA_GANGWAR.

C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
 
    // Function to perform queries to count the
    // number of subarrays having given numbers
    // as the last integer
    static void subarraysEndingWithX(int[] arr, int N,
                                     int[] query, int Q)
    {
       
        // Stores the number of subarrays having
        // x as the last element
        Dictionary<int, int> mp
            = new Dictionary<int, int>();
 
        // Traverse the array
        for (int i = 0; i < N; i++) {
 
            // Stores current array element
            int val = arr[i];
 
            // Add contribution of subarrays
            // having arr[i] as last element
            if (mp.ContainsKey(val))
                mp[val] = mp[val] + (i + 1);
            else
                mp[val] = i + 1;
        }
 
        // Traverse the array of queries
        for (int i = 0; i < Q; i++)
        {
            int q = query[i];
 
            // Print the count of subarrays
            Console.Write(mp[q] + " ");
        }
    }
 
    // Driver Code
    public static void Main()
    {
       
        // Given array
        int[] arr = { 1, 5, 4, 5, 6 };
 
        // Number of queries
        int Q = 3;
 
        // Array of queries
        int[] query = { 1, 4, 5 };
 
        // Size of the array
        int N = arr.Length;
        subarraysEndingWithX(arr, N, query, Q);
    }
}
 
// This code is contributed by chitranayal.

 
 

Output: 
1 3 6

 

Time Complexity: O(Q + N)
Auxiliary Space:O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :