Range elements are present in an array or not (original) (raw)

An array containing positive elements is given. 'start' and 'end' are two numbers defining a range. Write a function to check if the array contains all elements in the given range.

**Note: If the array contains all elements in the given range return **true otherwise return **false.

**Examples :

**Input : arr[] = {1, 4, 5, 2, 7, 8, 3} , start = 2, end = 5
**Output : true
**Explanation: All elements of given range are present

**Input : arr[] = {1, 4, 5, 2, 7, 8, 3} , start = 2, end = 6
**Output : false
**Explanation: 6 is missing

Table of Content

[Naive Approach] Check All Using Linear Search - O(n × (end - start)) Time and O(1) Space

The idea is to verify whether all integers in the given range [start, end] are present in the array. For every number from **start to end, we scan the entire array to check if that number exists. If any number in the range is missing, we immediately return false. If all numbers are found, we return true.

Consider the following dry run : arr[] = {1, 4, 5, 2, 7, 8, 3} , start = 2, end = 6

Final answer : False

C++ `

#include #include using namespace std;

// Function to check whether all numbers // from start to end are present in the array bool checkElements(int start, int end, vector &arr) { // Invalid range if (start > end) return false;

// Check every number from start to end
for (int i = start; i <= end; i++)
{
    bool found = false;

    // Search current number in array
    for (int j = 0; j < arr.size(); j++)
    {
        if (arr[j] == i)
        {
            found = true;
            break;
        }
    }

    // If any number is missing
    // return false immediately
    if (!found)
        return false;
}

// All numbers are present
return true;

}

int main() { // Input array vector arr = {1, 4, 5, 2, 7, 8, 3};

int start = 2;
int end = 5;

// Check if all elements exist
if (checkElements(start, end, arr))
    cout << "True";
else
    cout << "False";

return 0;

}

Java

import java.util.*;

class GFG {

// Function to check whether all numbers
// from start to end are present in the array
static boolean checkElements(int start, int end, ArrayList<Integer> arr)
{
    // Invalid range
    if (start > end)
        return false;

    // Check every number from start to end
    for (int i = start; i <= end; i++) {

        boolean found = false;

        // Search current number in array
        for (int j = 0; j < arr.size(); j++) {

            if (arr.get(j) == i) {
                found = true;
                break;
            }
        }

        // If any number is missing
        // return false immediately
        if (!found)
            return false;
    }

    // All numbers are present
    return true;
}

public static void main(String[] args)
{
    // Input array
    ArrayList<Integer> arr =
        new ArrayList<>(Arrays.asList(
            1, 4, 5, 2, 7, 8, 3));

    int start = 2;
    int end = 5;

    // Check if all elements exist
    if (checkElements(start, end, arr))
        System.out.println("True");
    else
        System.out.println("False");
}

}

Python

Function to check whether all numbers

from start to end are present in the array

def checkElements(start, end, arr):

# Invalid range
if start > end:
    return False

# Check every number from start to end
for i in range(start, end + 1):

    found = False

    # Search current number in array
    for num in arr:

        if num == i:
            found = True
            break

    # If any number is missing
    # return False immediately
    if not found:
        return False

# All numbers are present
return True

Driver Code

if name == "main": # Input array arr = [1, 4, 5, 2, 7, 8, 3]

start = 2
end = 5

# Check if all elements exist
if checkElements(start, end, arr):
    print("True")
else:
    print("False")

C#

using System; using System.Collections.Generic;

class Program { // Function to check whether all numbers // from start to end are present in the list static bool checkElements(int start, int end, List arr) { // Invalid range if (start > end) return false;

    // Check every number from start to end
    for (int i = start; i <= end; i++) {
        bool found = false;

        // Search current number in the list
        for (int j = 0; j < arr.Count; j++) {
            if (arr[j] == i) {
                found = true;
                break;
            }
        }

        // If any number is missing
        // return false immediately
        if (!found)
            return false;
    }

    // All numbers are present
    return true;
}

static void Main()
{
    // Input list
    List<int> arr
        = new List<int>() { 1, 4, 5, 2, 7, 8, 3 };

    int start = 2;
    int end = 5;

    // Check if all elements exist
    if (checkElements(start, end, arr))
        Console.WriteLine("True");
    else
        Console.WriteLine("False");
}

}

JavaScript

// Function to check whether all numbers // from start to end are present in the array function checkElements(start, end, arr) { // Invalid range if (start > end) return false;

// Check every number from start to end
for (let i = start; i <= end; i++) {
    let found = false;

    // Search current number in array
    for (let j = 0; j < arr.length; j++) {
        if (arr[j] === i) {
            found = true;
            break;
        }
    }

    // If any number is missing
    // return false immediately
    if (!found)
        return false;
}

// All numbers are present
return true;

}

// Driver Code

// Input array let arr = [ 1, 4, 5, 2, 7, 8, 3 ];

let start = 2; let end = 5;

// Check if all elements exist if (checkElements(start, end, arr)) console.log("True"); else console.log("False");

`

[Optimal Approach] Using Hashing - O(n + (end - start)) Time and O(n) Space

The intuition is to store all array elements in a hash set for fast lookup. Traverse every number from start to end and check whether it exists in the set. If any number is missing, return false; otherwise, return true.

Consider the following dry run : arr[] = {1, 4, 5, 2, 7, 8, 3} , start = 2, end = 6

Store all array elements in a hash set : {1, 2, 3, 4, 5, 7, 8} (order need not be same)

For i = 2 --> 2 found in hash set --> continue
For i = 3 --> 3 found in hash set --> continue
For i = 4 --> 4 found in hash set --> continue
For i = 5 --> 5 found in hash set --> continue
For i = 6 --> 6 not found in hash set --> return false

Final answer : False

C++ `

#include #include #include using namespace std;

bool checkElements(int start, int end, vector &arr) { unordered_set st;

// insert all elements into set
for (int x : arr)
{
    st.insert(x);
}

// check every element from start to end
for (int i = start; i <= end; i++)
{
    if (st.find(i) == st.end())
    {
        return false;
    }
}

return true;

}

// Driver code int main() { vector arr = {1, 4, 5, 2, 7, 8, 3}; int start = 2, end = 5;

if (checkElements(start, end, arr))
    cout << "True";
else
    cout << "False";

return 0;

}

Java

import java.util.*;

class GFG {

static boolean checkElements(int start, int end, ArrayList<Integer> arr)
{
    HashSet<Integer> set = new HashSet<>();

    // Insert all elements into set
    for (int x : arr) {
        set.add(x);
    }

    // Check every element from start to end
    for (int i = start; i <= end; i++) {
        if (!set.contains(i)) {
            return false;
        }
    }

    return true;
}

public static void main(String[] args)
{
    // Input array
    ArrayList<Integer> arr = new ArrayList<>(
        Arrays.asList(1, 4, 5, 2, 7, 8, 3));

    int start = 2, end = 5;

    if (checkElements(start, end, arr))
        System.out.println("True");
    else
        System.out.println("False");
}

}

Python

def checkElements(start, end, arr): st = set(arr) # insert all elements

# Check range
for i in range(start, end + 1):
    if i not in st:
        return False

return True

Driver code

if name == "main": arr = [1, 4, 5, 2, 7, 8, 3] start, end = 2, 5

print("True" if checkElements(start, end, arr) else "False")

C#

using System; using System.Collections.Generic;

class GFG {

static bool checkElements(int start, int end, List<int> arr)
{
    HashSet<int> set = new HashSet<int>();

    // Insert all elements
    foreach(int x in arr) { set.Add(x); }

    // Check range
    for (int i = start; i <= end; i++) {
        if (!set.Contains(i)) {
            return false;
        }
    }

    return true;
}

public static void Main()
{
    List<int> arr = new List<int>{ 1, 4, 5, 2, 7, 8, 3 };
    int start = 2, end = 5;

    Console.WriteLine(checkElements(start, end, arr) ? "True" : "False");
}

}

JavaScript

function checkElements(start, end, arr) { let set = new Set(arr); // insert all elements

// Check range
for (let i = start; i <= end; i++) {
    if (!set.has(i)) {
        return false;
    }
}

return true;

}

// Driver code let arr = [ 1, 4, 5, 2, 7, 8, 3 ]; let start = 2, end = 5;

console.log(checkElements(start, end, arr) ? "True" : "False");

`

[Optimal Approach] In-Place Index Mapping - O(n) Time and O(1) Space

Since the array contains only positive numbers, we use negative marking to track which values are present. Every value in the range start to end is mapped to an index and that index is marked negative to indicate presence. After marking, if any required index remains positive, it means that number is missing from the array.

Algorithm:

Consider the following dry run :
arr[] = {2, 4, 3, 7} , start = 2, end = 5, required range size = end - start + 1 = 4

Marking presence using index mapping :

Check all required indices (verification phase) :

#include #include #include using namespace std;

bool checkElements(int start, int end, vector &arr) { int n = arr.size();

// At least (end - start + 1) elements needed
if (n < end - start + 1)
    return false;

int range = end - start;

// Mark presence using index mapping
for (int i = 0; i < n; i++)
{
    int val = abs(arr[i]);

    if (val >= start && val <= end)
    {
        int idx = val - start;

        if (idx < n && arr[idx] > 0)
        {
            arr[idx] = -arr[idx];
        }
    }
}

// Check all required indices
for (int i = 0; i <= range && i < n; i++)
{
    if (arr[i] > 0)
        return false;
}

return true;

}

int main() { vector arr = {1, 4, 5, 2, 7, 8, 3}; int start = 2, end = 5;

if (checkElements(start, end, arr))
{
    cout << "True\n";
}
else
{
    cout << "False\n";
}

return 0;

}

Java

import java.util.*;

class GFG {

static boolean checkElements(int start, int end, ArrayList<Integer> arr)
{
    int n = arr.size();

    // At least (end - start + 1) elements needed
    if (n < end - start + 1)
        return false;

    int range = end - start;

    // Mark presence using index mapping
    for (int i = 0; i < n; i++) {

        int val = Math.abs(arr.get(i));

        if (val >= start && val <= end) {

            int idx = val - start;

            // Ensure valid index and mark visited
            if (idx < n && arr.get(idx) > 0) {

                arr.set(idx, -arr.get(idx));
            }
        }
    }

    // Check all required indices
    for (int i = 0; i <= range && i < n; i++) {

        if (arr.get(i) > 0)
            return false;
    }

    return true;
}

public static void main(String[] args)
{
    ArrayList<Integer> arr = new ArrayList<>(
        Arrays.asList(1, 4, 5, 2, 7, 8, 3));

    int start = 2, end = 5;

    System.out.println(checkElements(start, end, arr)
                           ? "True"
                           : "False");
}

}

Python

def checkElements(start, end, arr): n = len(arr)

# At least (end - start + 1) elements needed
if n < (end - start + 1):
    return False

range_len = end - start

# Mark presence using index mapping
for i in range(n):
    val = abs(arr[i])

    if start <= val <= end:
        idx = val - start

        if idx < n and arr[idx] > 0:
            arr[idx] = -arr[idx]

# Verify all required indices
for i in range(min(range_len + 1, n)):
    if arr[i] > 0:
        return False

return True

Driver Code

if name == "main": arr = [1, 4, 5, 2, 7, 8, 3] start, end = 2, 5

print("True" if checkElements(start, end, arr) else "False")

C#

using System; using System.Collections.Generic;

class GFG {

static bool checkElements(int start, int end, List<int> arr)
{
    int n = arr.Count;

    // At least (end - start + 1) elements needed
    if (n < end - start + 1)
        return false;

    int range = end - start;

    // Mark presence using index mapping
    for (int i = 0; i < n; i++) {

        int val = Math.Abs(arr[i]);

        if (val >= start && val <= end) {

            int idx = val - start;

            if (idx < n && arr[idx] > 0) {

                arr[idx] = -arr[idx];
            }
        }
    }

    // Check all required indices
    for (int i = 0; i <= range && i < n; i++) {

        if (arr[i] > 0)
            return false;
    }

    return true;
}

public static void Main()
{
    List<int> arr
        = new List<int>{ 1, 4, 5, 2, 7, 8, 3 };

    int start = 2, end = 5;

    Console.WriteLine(checkElements(start, end, arr)
                          ? "True"
                          : "False");
}

}

JavaScript

function checkElements(start, end, arr) { let n = arr.length;

// At least (end - start + 1) elements needed
if (n < (end - start + 1))
    return false;

let range = end - start;

// Mark presence using index mapping
for (let i = 0; i < n; i++) {
    let val = Math.abs(arr[i]);

    if (val >= start && val <= end) {
        let idx = val - start;

        if (idx < n && arr[idx] > 0) {
            arr[idx] = -arr[idx];
        }
    }
}

// Check all required indices
for (let i = 0; i <= range && i < n; i++) {
    if (arr[i] > 0)
        return false;
}

return true;

}

// Driver Code let arr = [ 1, 4, 5, 2, 7, 8, 3 ]; let start = 2, end = 5; console.log(checkElements(start, end, arr) ? "True" : "False");

`