Write a function that takes an int array of size M, and returns (true/false) if the array consists of the numbers only within the range [N, N+M-1]. The array is not guaranteed to be sorted.
For instance, {2,3,4} would return true. {1,3,1} would return true, {1,2,4} would return false.
courtesy: Vibhaj
Click here to see the solution.
p.s. - For Remarks please hit the given link once. For Hint, hit it twice and for the solution, hit it thrice.
Hints: No hint this time. Hit again for solution. |
|
Solution:
Simply find out the maximum and minimum in one pass and check if N == (max - min + 1)
Complexity:
1. Space: O(1)
2. Time: O(N)
int check_range(int input[], int N){
int max = input[0], min = input[0], i;
for(i=1; i<N; i++){
if(input[i] < min) min=input[i];
if(input[i] > max) max=input[i];
}
return (max - min + 1) == N;
}
|
|
|