![]() |
VOOZH | about |
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 presentInput : arr[] = {1, 4, 5, 2, 7, 8, 3} , start = 2, end = 6
Output : false
Explanation: 6 is missing
Table of Content
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
True
The intuition is to store all array elements in a hash set for fast lookup. Traverse every number from
starttoendand check whether it exists in the set. If any number is missing, returnfalse; otherwise, returntrue.
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
True
Since the array contains only positive numbers, we use negative marking to track which values are present. Every value in the range
starttoendis 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) :
True