Queries to count subarrays consisting of given integer as the last element
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++
#include <bits/stdc++.h>
using namespace std;
int subarraysEndingWithX(
int arr[], int N,
int query[], int Q)
{
for ( int m=0;m<Q;m++){
int last=query[m];
int count=0;
for ( int i=0;i<N;i++){
for ( int j=i;j<N;j++){
if (arr[j]==last){count++;}
}
}
cout<<count<< " " ;
}
}
int main()
{
int arr[] = { 1, 5, 4, 5, 6 };
int Q = 3;
int query[] = { 1, 4, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
subarraysEndingWithX(arr, N, query, Q);
return 0;
}
|
Java
public class SubarraysEndingWithX {
static void subarraysEndingWithX( int [] arr, int N, int [] query, int Q) {
for ( int m = 0 ; m < Q; m++) {
int last = query[m];
int count = 0 ;
for ( int i = 0 ; i < N; i++) {
for ( int j = i; j < N; j++) {
if (arr[j] == last) {
count++;
}
}
}
System.out.print(count + " " );
}
}
public static void main(String[] args) {
int [] arr = { 1 , 5 , 4 , 5 , 6 };
int Q = 3 ;
int [] query = { 1 , 4 , 5 };
int N = arr.length;
subarraysEndingWithX(arr, N, query, Q);
}
}
|
Python3
def subarrays_ending_with_x(arr, query):
result = []
for last in query:
count = 0
for i in range ( len (arr)):
for j in range (i, len (arr)):
if arr[j] = = last:
count + = 1
result.append(count)
return result
if __name__ = = "__main__" :
arr = [ 1 , 5 , 4 , 5 , 6 ]
Q = 3
query = [ 1 , 4 , 5 ]
counts = subarrays_ending_with_x(arr, query)
for count in counts:
print (count, end = " " )
|
C#
using System;
public class GFG
{
public static void SubarraysEndingWithX( int [] arr, int N, int [] query, int Q)
{
for ( int m = 0; m < Q; m++)
{
int last = query[m];
int count = 0;
for ( int i = 0; i < N; i++)
{
for ( int j = i; j < N; j++)
{
if (arr[j] == last)
{
count++;
}
}
}
Console.Write(count + " " );
}
}
public static void Main()
{
int [] arr = { 1, 5, 4, 5, 6 };
int Q = 3;
int [] query = { 1, 4, 5 };
int N = arr.Length;
SubarraysEndingWithX(arr, N, query, Q);
}
}
|
Javascript
function subarraysEndingWithX( arr, N, query, Q)
{
for (let m=0;m<Q;m++){
let last=query[m];
let count=0;
for (let i=0;i<N;i++){
for (let j=i;j<N;j++){
if (arr[j]==last)
count++;
}
}
console.log(count);
}
}
let arr = [ 1, 5, 4, 5, 6 ];
let Q = 3;
let query = [ 1, 4, 5 ];
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++
#include <bits/stdc++.h>
using namespace std;
int subarraysEndingWithX(
int arr[], int N,
int query[], int Q)
{
unordered_map< int , int > mp;
for ( int i = 0; i < N; i++) {
int val = arr[i];
mp[val] += (i + 1);
}
for ( int i = 0; i < Q; i++) {
int q = query[i];
cout << mp[q] << " " ;
}
}
int main()
{
int arr[] = { 1, 5, 4, 5, 6 };
int Q = 3;
int query[] = { 1, 4, 5 };
int N = sizeof (arr) / sizeof (arr[0]);
subarraysEndingWithX(arr, N, query, Q);
return 0;
}
|
Java
import java.util.*;
class GFG{
static void subarraysEndingWithX(
int arr[], int N,
int query[], int Q)
{
HashMap<Integer,Integer> mp = new HashMap<Integer,Integer>();
for ( int i = 0 ; i < N; i++) {
int val = arr[i];
if (mp.containsKey(val))
mp.put(val, mp.get(val)+(i+ 1 ));
else
mp.put(val, i+ 1 );
}
for ( int i = 0 ; i < Q; i++) {
int q = query[i];
System.out.print(mp.get(q)+ " " );
}
}
public static void main(String[] args)
{
int arr[] = { 1 , 5 , 4 , 5 , 6 };
int Q = 3 ;
int query[] = { 1 , 4 , 5 };
int N = arr.length;
subarraysEndingWithX(arr, N, query, Q);
}
}
|
Python3
def subarraysEndingWithX(arr, N, query, Q):
mp = {}
for i in range (N):
val = arr[i]
if val in mp:
mp[val] + = (i + 1 )
else :
mp[val] = mp.get(val, 0 ) + (i + 1 );
for i in range (Q):
q = query[i]
print (mp[q],end = " " )
if __name__ = = '__main__' :
arr = [ 1 , 5 , 4 , 5 , 6 ]
Q = 3
query = [ 1 , 4 , 5 ]
N = len (arr)
subarraysEndingWithX(arr, N, query, Q)
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static void subarraysEndingWithX( int [] arr, int N,
int [] query, int Q)
{
Dictionary< int , int > mp
= new Dictionary< int , int >();
for ( int i = 0; i < N; i++) {
int val = arr[i];
if (mp.ContainsKey(val))
mp[val] = mp[val] + (i + 1);
else
mp[val] = i + 1;
}
for ( int i = 0; i < Q; i++)
{
int q = query[i];
Console.Write(mp[q] + " " );
}
}
public static void Main()
{
int [] arr = { 1, 5, 4, 5, 6 };
int Q = 3;
int [] query = { 1, 4, 5 };
int N = arr.Length;
subarraysEndingWithX(arr, N, query, Q);
}
}
|
Javascript
<script>
function subarraysEndingWithX(arr, N, query, Q)
{
let mp = new Map();
for (let i = 0; i < N; i++) {
let val = arr[i];
if (mp.has(val))
mp.set(val, mp.get(val)+(i+1));
else
mp.set(val, i+1);
}
for (let i = 0; i < Q; i++) {
let q = query[i];
document.write(mp.get(q)+ " " );
}
}
let arr = [ 1, 5, 4, 5, 6 ];
let Q = 3;
let query = [ 1, 4, 5 ];
let N = arr.length;
subarraysEndingWithX(arr, N, query, Q);
</script>
|
Time Complexity: O(Q + N)
Auxiliary Space:O(N)
Last Updated :
16 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...