Check if an array contains all elements of a given range
Last Updated :
14 Sep, 2023
An array containing positive elements is given. 'A' and 'B' are two numbers defining a range. Write a function to check if the array contains all elements in the given range.
Examples :
Input : arr[] = {1 4 5 2 7 8 3}
A : 2, B : 5
Output : Yes
Input : arr[] = {1 4 5 2 7 8 3}
A : 2, B : 6
Output : No
Method 1 : (Intuitive)
- The most intuitive approach is to sort the array and check from the element greater than 'A' to the element less than 'B'. If these elements are in continuous order, all elements in the range exists in the array.
Algorithm
1. Check if A > B. If yes, return false as it is an invalid range.
2. Loop through each integer i in the range [A, B] (inclusive):
a. Initialize a boolean variable found to false.
b. Loop through each element j in the array arr:
i. If j is equal to i, set found to true and break out of the inner loop.
c. If found is still false after looping through all elements of arr, return false as i is not in the array.
3. If the loop completes without returning false, return true as all elements in the range [A, B] are found in arr.
Implementation of above approach
C++
#include <iostream>
#include <algorithm> // for std::sort
using namespace std;
bool check_elements_in_range(int arr[], int n, int A, int B) {
if (A > B) {
return false; // invalid range
}
for (int i = A; i <= B; i++) {
bool found = false;
for (int j = 0; j < n; j++) {
if (arr[j] == i) {
found = true;
break;
}
}
if (!found) {
return false; // element not found in array
}
}
return true; // all elements in range found in array
}
int main() {
int arr[] = {1, 4, 5, 2, 7, 8, 3};
int n = sizeof(arr) / sizeof(arr[0]);
int A = 2, B = 5;
if (check_elements_in_range(arr, n, A, B)) {
cout << "Yes" << endl;
} else {
cout << "No" << endl;
}
return 0;
}
Java
public class Main {
public static boolean checkElementsInRange(int[] arr, int A, int B) {
if (A > B) {
return false; // invalid range
}
for (int i = A; i <= B; i++) {
boolean found = false;
for (int j = 0; j < arr.length; j++) {
if (arr[j] == i) {
found = true;
break;
}
}
if (!found) {
return false; // element not found in array
}
}
return true; // all elements in range found in array
}
public static void main(String[] args) {
int[] arr = {1, 4, 5, 2, 7, 8, 3};
int A = 2, B = 5;
if (checkElementsInRange(arr, A, B)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
Python
def check_elements_in_range(arr, n, A, B):
if A > B:
return False # invalid range
for i in range(A, B+1):
found = False
for j in range(n):
if arr[j] == i:
found = True
break
if not found:
return False # element not found in array
return True # all elements in range found in array
arr = [1, 4, 5, 2, 7, 8, 3]
n = len(arr)
A, B = 2, 5
if check_elements_in_range(arr, n, A, B):
print("Yes")
else:
print("No")
C#
using System;
namespace RangeCheckApp
{
class Program
{
static bool CheckElementsInRange(int[] arr, int A, int B)
{
if (A > B)
{
return false; // invalid range
}
for (int i = A; i <= B; i++)
{
bool found = false;
foreach (int num in arr)
{
if (num == i)
{
found = true;
break;
}
}
if (!found)
{
return false; // element not found in array
}
}
return true; // all elements in range found in array
}
static void Main(string[] args)
{
int[] arr = { 1, 4, 5, 2, 7, 8, 3 };
int A = 2, B = 5;
if (CheckElementsInRange(arr, A, B))
{
Console.WriteLine("Yes");
}
else
{
Console.WriteLine("No");
}
}
}
}
JavaScript
function checkElementsInRange(arr, A, B) {
if (A > B) {
return false; // invalid range
}
for (let i = A; i <= B; i++) {
let found = false;
for (let j = 0; j < arr.length; j++) {
if (arr[j] === i) {
found = true;
break;
}
}
if (!found) {
return false; // element not found in array
}
}
return true; // all elements in range found in array
}
const arr = [1, 4, 5, 2, 7, 8, 3];
const A = 2, B = 5;
if (checkElementsInRange(arr, A, B)) {
console.log("Yes");
} else {
console.log("No");
}
Time complexity: O(n log n)
Auxiliary space: O(1)
Method 2 : (Hashing)
- We can maintain a count array or a hash table that stores the count of all numbers in the array that are in the range A...B. Then we can simply check if every number occurred at least once.
Algorithm:
- Initialize an empty unordered set.
- Insert all the elements of the array into the set.
- Traverse all the elements between A and B, inclusive, and check if each element is present in the set or not.
- If any element is not present in the set, return false.
- If all the elements are present in the set, return true.
C++
// C++ code for the following approach
#include <bits/stdc++.h>
using namespace std;
// function that check all elements between A and B including
// them are present in set or not
bool check_elements(int arr[] , int n , int A, int B){
unordered_set<int>st;
// put all the elements of array into set
for(int i=0 ;i<n ;i++){
st.insert(arr[i]);
}
// now check every between between A to B including them also, that they are
// present in set or not
for(int i=A ;i<=B ; i++){
// element not present in set so return false
// and no need to traverse further
if(st.find(i) == st.end()){
return false;
}
}
// all elements between A and B including them are
// present in set so return true
return true;
}
// Driver code
int main()
{
// Defining Array and size
int arr[] = { 1, 4, 5, 2, 7, 8, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
// A is lower limit and B is the upper limit
// of range
int A = 2, B = 5;
// True denotes all elements were present
if (check_elements(arr, n, A, B))
cout << "Yes";
// False denotes any element was not present
else
cout << "No";
return 0;
}
// this code is contributed by bhardwajji
Java
// Java code for the following approach
import java.util.*;
class Main {
// function that check all elements between A and B
// including them are present in set or not
public static boolean checkElements(int arr[], int n,
int A, int B)
{
Set<Integer> st = new HashSet<Integer>();
// put all the elements of array into set
for (int i = 0; i < n; i++) {
st.add(arr[i]);
}
// now check every between between A to B including
// them also, that they are present in set or not
for (int i = A; i <= B; i++) {
// element not present in set so return false
// and no need to traverse further
if (!st.contains(i)) {
return false;
}
}
// all elements between A and B including them are
// present in set so return true
return true;
}
// Driver code
public static void main(String[] args)
{
// Defining Array and size
int arr[] = { 1, 4, 5, 2, 7, 8, 3 };
int n = arr.length;
// A is lower limit and B is the upper limit
// of range
int A = 2, B = 5;
// True denotes all elements were present
if (checkElements(arr, n, A, B))
System.out.println("Yes");
// False denotes any element was not present
else
System.out.println("No");
}
}
Python3
# Python code for the following approach
import collections
# function that check all elements between A and B
# including them are present in set or not
def checkElements(arr, n, A, B):
st = set()
# put all the elements of array into set
for i in range(n):
st.add(arr[i])
# now check every between between A to B including
# them also, that they are present in set or not
for i in range(A, B+1):
# element not present in set so return false
# and no need to traverse further
if i not in st:
return False
# all elements between A and B including them are
# present in set so return true
return True
# Driver code
if __name__ == "__main__":
# Defining Array and size
arr = [1, 4, 5, 2, 7, 8, 3]
n = len(arr)
# A is lower limit and B is the upper limit
# of range
A = 2
B = 5
# True denotes all elements were present
if checkElements(arr, n, A, B):
print("Yes")
# False denotes any element was not present
else:
print("No")
C#
using System;
using System.Collections.Generic;
class MainClass {
// function that check all elements between A and B
// including them are present in set or not
static bool CheckElements(int[] arr, int n, int A,
int B)
{
HashSet<int> set = new HashSet<int>();
// put all the elements of array into set
for (int i = 0; i < n; i++) {
set.Add(arr[i]);
}
// now check every between between A to B including
// them also, that they are present in set or not
for (int i = A; i <= B; i++) {
// element not present in set so return false
// and no need to traverse further
if (!set.Contains(i)) {
return false;
}
}
// all elements between A and B including them are
// present in set so return true
return true;
}
// Driver code
public static void Main(string[] args)
{
// Defining Array and size
int[] arr = { 1, 4, 5, 2, 7, 8, 3 };
int n = arr.Length;
// A is lower limit and B is the upper limit
// of range
int A = 2, B = 5;
// True denotes all elements were present
if (CheckElements(arr, n, A, B))
Console.WriteLine("Yes");
// False denotes any element was not present
else
Console.WriteLine("No");
}
}
JavaScript
// JavaScript code for the following approach
// function that check all elements between A and B
// including them are present in set or not
function checkElements(arr, n, A, B) {
let st = new Set();
// put all the elements of array into set
for (let i = 0; i < n; i++) {
st.add(arr[i]);
}
// now check every between between A to B including
// them also, that they are present in set or not
for (let i = A; i <= B; i++) {
// element not present in set so return false
// and no need to traverse further
if (!st.has(i)) {
return false;
}
}
// all elements between A and B including them are
// present in set so return true
return true;
}
// Defining Array and size
let arr = [1, 4, 5, 2, 7, 8, 3];
let n = arr.length;
// A is lower limit and B is the upper limit of range
let A = 2;
let B = 5;
// True denotes all elements were present
if (checkElements(arr,n,A,B)) {
console.log("Yes");
}
// False denotes any element was not present
else {
console.log("No");
}
Time complexity : O(n logn)
Auxiliary space : O(max_element)
Method 3 : (Best):
Every element(x) in the range (A to B) has a corresponding unique index (x-A)
- Do a linear traversal of the array. If an element is found such that in the given range, i.e., |arr[i]| >= A and |arr[i]| <=B
- Negate the element at index (arr[i]-A) corresponding to this element arr[i].(do this only the element at that index is positive)
- Now, count the number of number of elements which are negative .This count must be equal to B-A+1.
- As, an element at an index is negative indicates that element corresponding to that index is present in array.
Implementation:
C++
#include <iostream>
using namespace std;
// Function to check the array for elements in
// given range
bool check_elements(int arr[], int n, int A, int B)
{
//Array should contain atleast B-A+1 elements
if(n<B-A+1) return false;
// Range is the no. of elements that are
// to be checked
int range = B - A;
// Traversing the array
for (int i = 0; i < n; i++) {
// If an element is in range
if (abs(arr[i]) >= A && abs(arr[i]) <= B) {
// Negating at index ‘element – A’
int z = abs(arr[i]) - A;
if (arr[z] > 0)
arr[z] = arr[z] * -1;
}
}
// Checking whether elements in range 0-range
// are negative
int count = 0;
for (int i = 0; i <= range && i < n; i++) {
// Element from range is missing from array
if (arr[i] > 0)
return false;
else
count++;
}
if (count != (range + 1))
return false;
// All range elements are present
return true;
}
// Driver code
int main()
{
// Defining Array and size
int arr[] = { 1, 4, 5, 2, 7, 8, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
// A is lower limit and B is the upper limit
// of range
int A = 2, B = 5;
// True denotes all elements were present
if (check_elements(arr, n, A, B))
cout << "Yes";
// False denotes any element was not present
else
cout << "No";
return 0;
}
// This code is contributed by Sania Kumari Gupta
C
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
// Function to check the array for elements in
// given range
bool check_elements(int arr[], int n, int A, int B)
{
// Range is the no. of elements that are
// to be checked
int range = B - A;
// Traversing the array
for (int i = 0; i < n; i++) {
// If an element is in range
if (abs(arr[i]) >= A && abs(arr[i]) <= B) {
// Negating at index ‘element – A’
int z = abs(arr[i]) - A;
if (arr[z] > 0)
arr[z] = arr[z] * -1;
}
}
// Checking whether elements in range 0-range
// are negative
int count = 0;
for (int i = 0; i <= range && i < n; i++) {
// Element from range is missing from array
if (arr[i] > 0)
return false;
else
count++;
}
if (count != (range + 1))
return false;
// All range elements are present
return true;
}
// Driver code
int main()
{
// Defining Array and size
int arr[] = { 1, 4, 5, 2, 7, 8, 3 };
int n = sizeof(arr) / sizeof(arr[0]);
// A is lower limit and B is the upper limit
// of range
int A = 2, B = 5;
// True denotes all elements were present
if (check_elements(arr, n, A, B))
printf("Yes");
// False denotes any element was not present
else
printf("No");
return 0;
}
// This code is contributed by Sania Kumari Gupta
Java
// JAVA Code for Check if an array contains
// all elements of a given range
import java.util.*;
class GFG {
// Function to check the array for elements in
// given range
public static boolean check_elements(int arr[], int n,
int A, int B)
{
// Range is the no. of elements that are
// to be checked
int range = B - A;
// Traversing the array
for (int i = 0; i < n; i++) {
// If an element is in range
if (Math.abs(arr[i]) >= A &&
Math.abs(arr[i]) <= B) {
int z = Math.abs(arr[i]) - A;
if (arr[z] > 0) {
arr[z] = arr[z] * -1;
}
}
}
// Checking whether elements in range 0-range
// are negative
int count=0;
for (int i = 0; i <= range && i<n; i++) {
// Element from range is missing from array
if (arr[i] > 0)
return false;
else
count++;
}
if(count!= (range+1))
return false;
// All range elements are present
return true;
}
/* Driver program to test above function */
public static void main(String[] args)
{
// Defining Array and size
int arr[] = { 1, 4, 5, 2, 7, 8, 3 };
int n = arr.length;
// A is lower limit and B is the upper limit
// of range
int A = 2, B = 5;
// True denotes all elements were present
if (check_elements(arr, n, A, B))
System.out.println("Yes");
// False denotes any element was not present
else
System.out.println("No");
}
}
// This code is contributed by Arnav Kr. Mandal.
Python3
# Function to check the array for
# elements in given range
def check_elements(arr, n, A, B) :
# Range is the no. of elements
# that are to be checked
rangeV = B - A
# Traversing the array
for i in range(0, n):
# If an element is in range
if (abs(arr[i]) >= A and
abs(arr[i]) <= B) :
# Negating at index ‘element – A’
z = abs(arr[i]) - A
if (arr[z] > 0) :
arr[z] = arr[z] * -1
# Checking whether elements in
# range 0-range are negative
count = 0
for i in range(0, rangeV + 1):
if i >= n:
break
# Element from range is
# missing from array
if (arr[i] > 0):
return False
else:
count = count + 1
if(count != (rangeV + 1)):
return False
# All range elements are present
return True
# Driver code
# Defining Array and size
arr = [ 1, 4, 5, 2, 7, 8, 3 ]
n = len(arr)
# A is lower limit and B is
# the upper limit of range
A = 2
B = 5
# True denotes all elements
# were present
if (check_elements(arr, n, A, B)) :
print("Yes")
# False denotes any element
# was not present
else:
print("No")
# This code is contributed
# by Yatin Gupta
C#
// C# Code for Check if an array contains
// all elements of a given range
using System;
class GFG {
// Function to check the array for
// elements in given range
public static bool check_elements(int []arr, int n,
int A, int B)
{
// Range is the no. of elements
// that are to be checked
int range = B - A;
// Traversing the array
for (int i = 0; i < n; i++)
{
// If an element is in range
if (Math.Abs(arr[i]) >= A &&
Math.Abs(arr[i]) <= B)
{
int z = Math.Abs(arr[i]) - A;
if (arr[z] > 0)
{
arr[z] = arr[z] * - 1;
}
}
}
// Checking whether elements in
// range 0-range are negative
int count=0;
for (int i = 0; i <= range
&& i < n; i++)
{
// Element from range is
// missing from array
if (arr[i] > 0)
return false;
else
count++;
}
if(count != (range + 1))
return false;
// All range elements are present
return true;
}
// Driver Code
public static void Main(String []args)
{
// Defining Array and size
int []arr = {1, 4, 5, 2, 7, 8, 3};
int n = arr.Length;
// A is lower limit and B is
// the upper limit of range
int A = 2, B = 5;
// True denotes all elements were present
if (check_elements(arr, n, A, B))
Console.WriteLine("Yes");
// False denotes any element was not present
else
Console.WriteLine("No");
}
}
// This code is contributed by vt_m.
JavaScript
<script>
// Javascript Code for Check
// if an array contains
// all elements of a given range
// Function to check the array for
// elements in given range
function check_elements(arr, n, A, B)
{
// Range is the no. of elements
// that are to be checked
let range = B - A;
// Traversing the array
for (let i = 0; i < n; i++)
{
// If an element is in range
if (Math.abs(arr[i]) >= A &&
Math.abs(arr[i]) <= B)
{
let z = Math.abs(arr[i]) - A;
if (arr[z] > 0)
{
arr[z] = arr[z] * - 1;
}
}
}
// Checking whether elements in
// range 0-range are negative
let count=0;
for (let i = 0; i <= range &&
i < n; i++)
{
// Element from range is
// missing from array
if (arr[i] > 0)
return false;
else
count++;
}
if(count != (range + 1))
return false;
// All range elements are present
return true;
}
// Defining Array and size
let arr = [1, 4, 5, 2, 7, 8, 3];
let n = arr.length;
// A is lower limit and B is
// the upper limit of range
let A = 2, B = 5;
// True denotes all elements were present
if (check_elements(arr, n, A, B))
document.write("Yes");
// False denotes any element was not present
else
document.write("No");
</script>
PHP
<?php
// Function to check the
// array for elements in
// given range
function check_elements($arr, $n,
$A, $B)
{
// Range is the no. of
// elements that are to
// be checked
$range = $B - $A;
// Traversing the array
for ($i = 0; $i < $n; $i++)
{
// If an element is in range
if (abs($arr[$i]) >= $A &&
abs($arr[$i]) <= $B)
{
// Negating at index
// ‘element – A’
$z = abs($arr[$i]) - $A;
if ($arr[$z] > 0)
{
$arr[$z] = $arr[$z] * -1;
}
}
}
// Checking whether elements
// in range 0-range are negative
$count = 0;
for ($i = 0; $i <= $range &&
$i< $n; $i++)
{
// Element from range is
// missing from array
if ($arr[$i] > 0)
return -1;
else
$count++;
}
if($count!= ($range + 1))
return -1;
// All range elements
// are present
return true;
}
// Driver code
// Defining Array and size
$arr = array(1, 4, 5, 2,
7, 8, 3);
$n = sizeof($arr);
// A is lower limit and
// B is the upper limit
// of range
$A = 2; $B = 5;
// True denotes all
// elements were present
if ((check_elements($arr, $n,
$A, $B)) == true)
echo "Yes";
// False denotes any
// element was not present
else
echo "No";
// This code is contributed by aj_36
?>
Time complexity : O(n)
Auxiliary space : O(1)
Elements in the Range | DSA Problem
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem