Tuesday, November 1, 2011

Check range

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.

Solution :
Simply find out the maximum and minimum in one pass and check if N == (max - min + 1)
Complexity :
  • Time : O(N)
  • Space : O(1)
Code :

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;
}

No comments:

Post a Comment