Print all Repetitive elements in given Array within value range [A, B] for Q queries
Last Updated :
26 Oct, 2023
Given an array arr[] of size N, and Q queries of the form [A, B], the task is to find all the unique elements from the array which are repetitive and their values lie between A and B (both inclusive) for each of the Q queries.
Examples:
Input: arr[] = { 1, 5, 1, 2, 3, 3, 4, 0, 0 }, Q = 2, queries={ { 1, 3 }, { 0, 0 } }
Output: {3, 1}, { 0 }
Explanation: For the first query the elements 1 and 3 lie in the given range and occurs more than once.
For the second queryonly 0 lies in the range and is repetitive in nature.
Input: arr[] = {1, 5, 1, 2, 3, 4, 0, 0}, Q = 1, queries={ { 1, 2 } }
Output: 1
Naive Approach: The basic approach to solve this problem is to use nested loops. A traversal of all elements is performed by the outer loop, and checking whether the element picked by the outer loop appears anywhere else is performed by the inner loop. Then, if it appears elsewhere, check if it is lying within the range of [A, B]. If yes, then print it.
Below is the implementation of the above approach.
C++14
// C++ code for the above approach.
#include <bits/stdc++.h>
using namespace std;
// Function to print elements
void printElements(int arr[], int N, int A, int B)
{
bool flag = false;
for (int i = 0; i < N; i++) {
if (arr[i] >= A && arr[i] <= B) {
bool repeat = false;
for (int j = i + 1; j < N; j++) {
if (arr[i] == arr[j]) {
repeat = true;
break;
}
}
// Print the elements
// if it repeats
if (repeat) {
if (flag)
cout << " ";
cout << arr[i];
flag = true;
}
}
}
if (!flag)
cout << -1;
}
// Function to find the elements
// satisfying given condition for each query
void findElements(int arr[], int N, int Q,
vector<pair<int, int> >& queries)
{
for (int i = 0; i < Q; i++) {
int A = queries[i].first;
int B = queries[i].second;
// function to printing elements in range
printElements(arr, N, A, B);
cout << endl;
}
}
// Driver code
int main()
{
int arr[] = { 1, 5, 1, 2, 3, 3, 4, 0, 0 };
int N = sizeof(arr) / sizeof(arr[0]);
int Q = 2;
vector<pair<int, int> > queries
= { { 1, 3 }, { 0, 0 } };
// Function call
findElements(arr, N, Q, queries);
return 0;
}
Java
// Java code for the above approach.
import java.util.*;
public class Main {
// Custom Pair class to hold two values
static class Pair<F, S> {
F first;
S second;
Pair(F first, S second) {
this.first = first;
this.second = second;
}
}
// Function to print elements within a range
// and are repeating
static void printElements(int[] arr, int N, int A, int B) {
boolean flag = false;
for (int i = 0; i < N; i++) {
if (arr[i] >= A && arr[i] <= B) {
boolean repeat = false;
for (int j = i + 1; j < N; j++) {
if (arr[i] == arr[j]) {
repeat = true;
break;
}
}
// Print the elements if they repeat
if (repeat) {
if (flag)
System.out.print(" ");
System.out.print(arr[i]);
flag = true;
}
}
}
if (!flag)
System.out.print(-1);
System.out.println();
}
// Function to find the elements satisfying
// given condition for each query
static void findElements(int[] arr, int N, int Q,
ArrayList<Pair<Integer, Integer>> queries) {
for (int i = 0; i < Q; i++) {
int A = queries.get(i).first;
int B = queries.get(i).second;
// Call the function to print elements in range
printElements(arr, N, A, B);
}
}
public static void main(String[] args) {
int[] arr = {1, 5, 1, 2, 3, 3, 4, 0, 0};
int N = arr.length;
int Q = 2;
ArrayList<Pair<Integer, Integer>> queries = new ArrayList<>();
queries.add(new Pair<>(1, 3));
queries.add(new Pair<>(0, 0));
// Function call
findElements(arr, N, Q, queries);
}
}
Python3
# Function to print elements
def printElements(arr, A, B):
flag = False
for i in range(len(arr)):
if A <= arr[i] <= B:
repeat = False
for j in range(i + 1, len(arr)):
if arr[i] == arr[j]:
repeat = True
break
# Print the elements if it repeats
if repeat:
if flag:
print(" ", end="")
print(arr[i], end="")
flag = True
if not flag:
print(-1)
# Function to find the elements satisfying the given condition for each query
def findElements(arr, queries):
for query in queries:
A, B = query
# Call the function to print elements in the range
printElements(arr, A, B)
print()
# Driver code
if __name__ == "__main__":
arr = [1, 5, 1, 2, 3, 3, 4, 0, 0]
Q = 2
queries = [(1, 3), (0, 0)]
# Function call
findElements(arr, queries)
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to print elements
static void PrintElements(int[] arr, int N, int A, int B)
{
bool flag = false;
for (int i = 0; i < N; i++)
{
if (arr[i] >= A && arr[i] <= B)
{
bool repeat = false;
for (int j = i + 1; j < N; j++)
{
if (arr[i] == arr[j])
{
repeat = true;
break;
}
}
// Print the elements if it repeats
if (repeat)
{
if (flag)
Console.Write(" ");
Console.Write(arr[i]);
flag = true;
}
}
}
if (!flag)
Console.Write(-1);
Console.WriteLine();
}
// Function to find the elements satisfying given condition for each query
static void FindElements(int[] arr, int N, int Q, List<Tuple<int, int>> queries)
{
for (int i = 0; i < Q; i++)
{
int A = queries[i].Item1;
int B = queries[i].Item2;
// Call the function to print elements in range
PrintElements(arr, N, A, B);
}
}
static void Main()
{
int[] arr = { 1, 5, 1, 2, 3, 3, 4, 0, 0 };
int N = arr.Length;
int Q = 2;
List<Tuple<int, int>> queries = new List<Tuple<int, int>>
{
Tuple.Create(1, 3),
Tuple.Create(0, 0)
};
// Function call
FindElements(arr, N, Q, queries);
}
}
JavaScript
// Javascript code for the above approach
// Function to print elements
function printElements(arr, N, A, B) {
let flag = false;
for (let i = 0; i < N; i++) {
if (arr[i] >= A && arr[i] <= B) {
let repeat = false;
for (let j = i + 1; j < N; j++) {
if (arr[i] == arr[j]) {
repeat = true;
break;
}
}
// Print the elements
// if it repeats
if (repeat) {
if (flag)
console.log(" ");
console.log(arr[i].toString());
flag = true;
}
}
}
if (!flag)
console.log("-1");
}
// Function to find the elements
// satisfying given condition for each query
function findElements(arr, N, Q, queries) {
for (let i = 0; i < Q; i++) {
let A = queries[i][0];
let B = queries[i][1];
// function to printing elements in range
printElements(arr, N, A, B);
console.log();
}
}
// Driver code
let arr = [1, 5, 1, 2, 3, 3, 4, 0, 0];
let N = arr.length;
let Q = 2;
let queries = [[1, 3], [0, 0]];
// Function call
findElements(arr, N, Q, queries);
Time Complexity: O(Q * N2)
Auxiliary Space: O(1)
Efficient Approach: An efficient approach is based on the idea of a hash map to store the frequency of all the elements. Follow the steps mentioned below:
- Traverse the hash map, and check if the frequency of an element is greater than 1.
- If yes, then check if the element is present in the range of [A, B] or not.
- If yes, then print it else skip the element.
- Continue the above procedure till all the elements of the hash map are traversed.
Below is the implementation of the above approach.
C++
// C++ code for the above approach.
#include <bits/stdc++.h>
using namespace std;
// Initializing hashmap to store
// Frequency of elements
unordered_map<int, int> freq;
// Function to store frequency of elements in hash map
void storeFrequency(int arr[], int n)
{
// Iterating the array
for (int i = 0; i < n; i++) {
freq[arr[i]]++;
}
}
// Function to print elements
void printElements(int a, int b)
{
// Traversing the hash map
for (auto it = freq.begin(); it != freq.end(); it++) {
// Checking 1st condition if frequency > 1, i.e,
// Element is repetitive
if ((it->second) > 1) {
int value = it->first;
// Checking 2nd condition if element
// Is in range of a and b or not
if (value >= a && value <= b) {
// Printing the value
cout << value << " ";
}
}
}
}
// Function to find the elements
// satisfying given condition for each query
void findElements(int arr[], int N, int Q,
vector<pair<int, int> >& queries)
{
storeFrequency(arr, N);
for (int i = 0; i < Q; i++) {
int A = queries[i].first;
int B = queries[i].second;
printElements(A, B);
cout << endl;
}
}
// Driver code
int main()
{
int arr[] = { 1, 5, 1, 2, 3, 3, 4, 0, 0 };
// Size of array
int N = sizeof(arr) / sizeof(arr[0]);
int Q = 2;
vector<pair<int, int> > queries = { { 1, 3 }, { 0, 0 } };
// Function call
findElements(arr, N, Q, queries);
return 0;
}
Java
// Java code for the above approach.
import java.util.*;
class GFG{
// Initializing hashmap to store
// Frequency of elements
static HashMap<Integer,Integer> freq=new HashMap<Integer,Integer> ();
// Function to store frequency of elements in hash map
static void storeFrequency(int arr[], int n)
{
// Iterating the array
for (int i = 0 ; i < n; i++){
if(freq.containsKey(arr[i])){
freq.put(arr[i], freq.get(arr[i])+1);
}
else{
freq.put(arr[i], 1);
}
}
}
// Function to print elements
static void printElements(int a, int b)
{
// Traversing the hash map
for (Map.Entry<Integer,Integer> it : freq.entrySet()) {
// Checking 1st condition if frequency > 1, i.e,
// Element is repetitive
if ((it.getValue()) > 1) {
int value = it.getKey();
// Checking 2nd condition if element
// Is in range of a and b or not
if (value >= a && value <= b) {
// Printing the value
System.out.print(value+ " ");
}
}
}
}
// Function to find the elements
// satisfying given condition for each query
static void findElements(int arr[], int N, int Q,
int[][] queries)
{
storeFrequency(arr, N);
for (int i = 0; i < Q; i++) {
int A = queries[i][0];
int B = queries[i][1];
printElements(A, B);
System.out.println();
}
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 1, 5, 1, 2, 3, 3, 4, 0, 0 };
// Size of array
int N = arr.length;
int Q = 2;
int [][]queries = { { 1, 3 }, { 0, 0 } };
// Function call
findElements(arr, N, Q, queries);
}
}
// This code contributed by shikhasingrajput
Python3
# Python 3 code for the above approach.
from collections import defaultdict
# Initializing hashmap to store
# Frequency of elements
freq = defaultdict(int)
# Function to store frequency of elements in hash map
def storeFrequency(arr, n):
# Iterating the array
for i in range(n):
freq[arr[i]] += 1
# Function to print elements
def printElements(a, b):
# Traversing the hash map
for it in freq:
# Checking 1st condition if frequency > 1, i.e,
# Element is repetitive
# print("it = ",it)
if ((freq[it]) > 1):
value = it
# Checking 2nd condition if element
# Is in range of a and b or not
if (value >= a and value <= b):
# Printing the value
print(value, end=" ")
# Function to find the elements
# satisfying given condition for each query
def findElements(arr, N, Q,
queries):
storeFrequency(arr, N)
for i in range(Q):
A = queries[i][0]
B = queries[i][1]
printElements(A, B)
print()
# Driver code
if __name__ == "__main__":
arr = [1, 5, 1, 2, 3, 3, 4, 0, 0]
# Size of array
N = len(arr)
Q = 2
queries = [[1, 3], [0, 0]]
# Function call
findElements(arr, N, Q, queries)
# This code is contributed by ukasp.
C#
// C# code for the above approach.
using System;
using System.Collections.Generic;
public class GFG{
// Initializing hashmap to store
// Frequency of elements
static Dictionary<int,int> freq=new Dictionary<int,int> ();
// Function to store frequency of elements in hash map
static void storeFrequency(int []arr, int n)
{
// Iterating the array
for (int i = 0 ; i < n; i++){
if(freq.ContainsKey(arr[i])){
freq[arr[i]]= freq[arr[i]]+1;
}
else{
freq.Add(arr[i], 1);
}
}
}
// Function to print elements
static void printElements(int a, int b)
{
// Traversing the hash map
foreach (KeyValuePair<int,int> it in freq) {
// Checking 1st condition if frequency > 1, i.e,
// Element is repetitive
if ((it.Value) > 1) {
int value = it.Key;
// Checking 2nd condition if element
// Is in range of a and b or not
if (value >= a && value <= b) {
// Printing the value
Console.Write(value+ " ");
}
}
}
}
// Function to find the elements
// satisfying given condition for each query
static void findElements(int []arr, int N, int Q,
int[,] queries)
{
storeFrequency(arr, N);
for (int i = 0; i < Q; i++) {
int A = queries[i,0];
int B = queries[i,1];
printElements(A, B);
Console.WriteLine();
}
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 1, 5, 1, 2, 3, 3, 4, 0, 0 };
// Size of array
int N = arr.Length;
int Q = 2;
int [,]queries = { { 1, 3 }, { 0, 0 } };
// Function call
findElements(arr, N, Q, queries);
}
}
// This code contributed by shikhasingrajput
JavaScript
<script>
// JavaScript code for the above approach.
// Initializing hashmap to store
// Frequency of elements
let freq = new Map();
// Function to store frequency of elements in hash map
function storeFrequency(arr,n)
{
// Iterating the array
for (let i = 0; i < n; i++) {
freq[arr[i]]++;
}
}
// Function to print elements
function printElements(a, b)
{
// Traversing the hash map
for (let [key, val] of freq.values()) {
// Checking 1st condition if frequency > 1, i.e,
// Element is repetitive
if (val > 1) {
let value =key;
// Checking 2nd condition if element
// Is in range of a and b or not
if (value >= a && value <= b) {
// Printing the value
document.write(value + " ");
}
}
}
}
// Function to find the elements
// satisfying given condition for each query
function findElements(arr, N, Q, queries)
{
storeFrequency(arr, N);
for (let i = 0; i < Q; i++) {
let A = queries[i][0];
let B = queries[i][1];
printElements(A, B);
document.write("<br>");
}
}
// Driver code
let arr = [ 1, 5, 1, 2, 3, 3, 4, 0, 0 ];
// Size of array
let N = arr.length;
let Q = 2;
let queries = [ [ 1, 3 ], [ 0, 0 ] ];
// Function call
findElements(arr, N, Q, queries);
// This code is contributed by satwik4409.
</script>
Time Complexity: O(Q*N + N)
Auxiliary Space: O(N)
Similar Reads
Queries for count of array elements with values in given range with updates Given an array arr[] of size N and a matrix Q consisting of queries of the following two types:Â 1 L R : Print the number of elements lying in the range [L, R].2 i x : Set arr[i] = x Examples:Â Input: arr[] = {1, 2, 2, 3, 4, 4, 5, 6}, Q = {{1, {3, 5}}, {1, {2, 4}}, {1, {1, 2}}, {2, {1, 7}}, {1, {1,
15+ min read
Queries for elements having values within the range A to B using MO's Algorithm Prerequisites: MO's algorithm, SQRT DecompositionGiven 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). Example
15+ min read
Queries to increment array elements in a given range by a given value for a given number of times Given an array, arr[] of N positive integers and M queries of the form {a, b, val, f}. The task is to print the array after performing each query to increment array elements in the range [a, b] by a value val f number of times. Examples: Input: arr[] = {1, 2, 3}, M=3, Q[][] = {{1, 2, 1, 4}, {1, 3, 2
13 min read
Queries to count array elements from a given range having a single set bit Given an array arr[] consisting of N integers and a 2D array Q[][] consisting of queries of the following two types: 1 L R: Print the count of numbers from the range [L, R] having only a single set bit.2 X V: Update the array element at Xth index with V.Examples: Input: arr[] = { 12, 11, 16, 2, 32 }
15+ min read
Array range queries for elements with frequency same as value Given an array of N numbers, the task is to answer Q queries of the following type: query(start, end) = Number of times a number x occurs exactly x times in a subarray from start to end Examples: Input : arr = {1, 2, 2, 3, 3, 3} Query 1: start = 0, end = 1, Query 2: start = 1, end = 1, Query 3: star
15+ min read