Queries to count subarrays consisting of given integer as the last element
Last Updated :
16 Oct, 2023
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, the 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, the 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.
Steps to implement-
- Run a loop on the query array
- For every query find all subarrays of array arr
- Then find the count of those subarrays whose last element is that query
- After finding the count simply print that
Code-
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)
{
//Traverse the query
for(int m=0;m<Q;m++){
//Element that should be in the last of subarray
int last=query[m];
//To store count of such subarray
int count=0;
//Find all subarray
for(int i=0;i<N;i++){
for(int j=i;j<N;j++){
//When last element of subarray is
//equal to query
if(arr[j]==last){count++;}
}
}
//Print the count of subarrays
cout<<count<<" ";
}
}
// 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
public class SubarraysEndingWithX {
// 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) {
// Traverse the query
for (int m = 0; m < Q; m++) {
// Element that should be in the last of subarray
int last = query[m];
// To store count of such subarrays
int count = 0;
// Find all subarrays
for (int i = 0; i < N; i++) {
for (int j = i; j < N; j++) {
// When last element of subarray is equal to query
if (arr[j] == last) {
count++;
}
}
}
// Print the count of subarrays
System.out.print(count + " ");
}
}
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);
}
}
Python3
# Function to perform queries to count the number of subarrays having given numbers as the last integer
def subarrays_ending_with_x(arr, query):
# Initialize a list to store the counts for each query
result = []
# Traverse each query
for last in query:
# Initialize a count variable to store the number of subarrays
count = 0
# Find all subarrays
for i in range(len(arr)):
for j in range(i, len(arr)):
# When the last element of the subarray is equal to the query
if arr[j] == last:
count += 1
# Append the count to the result list
result.append(count)
return result
# 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]
# Calculate the counts of subarrays for each query
counts = subarrays_ending_with_x(arr, query)
# Print the counts for each query
for count in counts:
print(count, end=" ")
C#
// C# program for the above approach
using System;
public class GFG
{
// Function to perform queries to count the
// number of subarrays having given numbers
// as the last integer
public static void SubarraysEndingWithX(int[] arr, int N, int[] query, int Q)
{
// Traverse the queries
for (int m = 0; m < Q; m++)
{
// Element that should be at the
// end of subarray
int last = query[m];
// To store the count of such subarrays
int count = 0;
// Find all subarrays
for (int i = 0; i < N; i++)
{
for (int j = i; j < N; j++)
{
// When the last element of subarray is
// equal to the query
if (arr[j] == last)
{
count++;
}
}
}
// Print the count of subarrays
Console.Write(count + " ");
}
}
// 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);
}
}
JavaScript
// JavaScript program for the above approach
// Function to perform queries to count the
// number of subarrays having given numbers
// as the last integer
function subarraysEndingWithX( arr, N, query, Q)
{
//Traverse the query
for(let m=0;m<Q;m++){
//Element that should be in the last of subarray
let last=query[m];
//To store count of such subarray
let count=0;
//Find all subarray
for(let i=0;i<N;i++){
for(let j=i;j<N;j++){
//When last element of subarray is
//equal to query
if(arr[j]==last)
count++;
}
}
//Print the count of subarrays
console.log(count);
}
}
// Driver Code
// Given array
let arr = [ 1, 5, 4, 5, 6 ];
// Number of queries
let Q = 3;
// Array of queries
let query = [ 1, 4, 5 ];
// Size of the array
let N = arr.length;
subarraysEndingWithX(arr, N, query, Q);
Time Complexity: O(Q×N2), because there were Q queries and we have to find all subarray for every query
Auxiliary Space: O(1), because no extra space has been used
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 occurrence in the array. For every index, say idx, in 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.
JavaScript
<script>
// JavaScript program for the above approach
// Function to perform queries to count the
// number of subarrays having given numbers
// as the last integer
function subarraysEndingWithX(arr, N, query, Q)
{
// Stores the number of subarrays having
// x as the last element
let mp = new Map();
// Traverse the array
for (let i = 0; i < N; i++) {
// Stores current array element
let val = arr[i];
// Add contribution of subarrays
// having arr[i] as last element
if(mp.has(val))
mp.set(val, mp.get(val)+(i+1));
else
mp.set(val, i+1);
}
// Traverse the array of queries
for (let i = 0; i < Q; i++) {
let q = query[i];
// Print the count of subarrays
document.write(mp.get(q)+ " ");
}
}
// Driver Code
// Given array
let arr = [ 1, 5, 4, 5, 6 ];
// Number of queries
let Q = 3;
// Array of queries
let query = [ 1, 4, 5 ];
// Size of the array
let N = arr.length;
subarraysEndingWithX(arr, N, query, Q);
</script>
Time Complexity: O(Q + N)
Auxiliary Space:O(N)
Similar Reads
Queries for number of distinct elements in a subarray
Given a array 'a[]' of size n and number of queries q. Each query can be represented by two integers l and r. Your task is to print the number of distinct integers in the subarray l to r. Given a[i] <= 106 Examples: Input : a[] = {1, 1, 2, 1, 3} q = 3 0 4 1 3 2 4 Output :3 2 3 In query 1, number
10 min read
Count subarrays having each distinct element occurring at least twice
Given an array arr[] of size N, the task is to count the number of subarrays from the given array, such that each distinct element in these subarray occurs at least twice. Examples: Input: arr[] = {1, 1, 2, 2, 2}Output: 6Explanation: Subarrays having each element occurring at least twice are :{{1, 1
8 min read
Range Queries to count elements lying in a given Range : MO's Algorithm
Given an array arr[] of N elements and two integers A to B, the task is to answer Q queries each having two integers L and R. For each query, find the number of elements in the subarray arr[Lâ¦R] which lies within the range A to B (inclusive). Examples: Input: arr[] = {7, 3, 9, 13, 5, 4}, A = 4, B =
15+ min read
Count subarrays having at least X distinct elements that occur exactly Y times
Given three integers N, X, Y, and an array arr[] of size N, the task is to find the count of subarrays having at least X distinct elements that occur only Y times. Example: Input: N = 9, X = 2, Y = 2, arr[] = {2, 1, 2, 5, 3, 1, 3, 2, 5}Output:10Explanation:Subarrays with at least X distinct elements
8 min read
Queries for number of distinct elements in a subarray | Set 2
Given an array arr[] of N integers and Q queries. Each query can be represented by two integers L and R. The task is to find the count of distinct integers in the subarray arr[L] to arr[R].Examples: Input: arr[] = {1, 1, 3, 3, 5, 5, 7, 7, 9, 9 }, L = 0, R = 4 Output: 3Input: arr[] = { 1, 1, 2, 1, 3
12 min read
Count of subarrays which contains a given number exactly K times
Given an array A[] of N elements consisting of values from 1 to N with duplicates, the task is to find the total number of subarrays that contain a given number num exactly K times. Examples: Input: A[] = {1, 2, 1, 5, 1}, num = 1, K = 2 Output: 2 Explanation: Subarrays {1, 2, 1, 5}, {1, 2, 1}, {2, 1
8 min read
Count of elements which is the sum of a subarray of the given Array
Given an array arr[], the task is to count elements in an array such that there exists a subarray whose sum is equal to this element.Note: Length of subarray must be greater than 1. Examples: Input: arr[] = {1, 2, 3, 4, 5, 6, 7} Output: 4 Explanation: There are 4 such elements in array - arr[2] = 3
7 min read
Count subarrays having exactly K elements occurring at least twice
Given an array arr[] consisting of N integers and a positive integer K, the task is to count the number of subarrays having exactly K elements occurring at least twice. Examples: Input: arr[] = {1, 1, 1, 2, 2}, K = 1Output: 7Explanation: The subarrays having exactly 1 element occurring at least twic
11 min read
Count subarrays having product equal to the power of a given Prime Number
Given an array arr[] of size N and an integer M, the task is to count the number of subarrays having product of its elements equal to the power of M, where M is a prime number. Examples: Input: arr[] = {2, 2, 2, 2}, M = 2Output: 10Explanation: All possible non-empty subarrays having product equal to
8 min read
Count of Subarrays in an array containing numbers from 1 to the length of subarray
Given an array arr[] of length N containing all elements from 1 to N, the task is to find the number of sub-arrays that contain numbers from 1 to M, where M is the length of the sub-array. Examples: Input: arr[] = {4, 1, 3, 2, 5, 6} Output: 5 Explanation: Desired Sub-arrays = { {4, 1, 3, 2}, {1}, {1
7 min read