fork(2) download
  1. #include <stdio.h>
  2.  
  3. // Function to find missing term in a sequence
  4. int missingTerm(int A[], int n)
  5. {
  6. // search space is A[low..high]
  7. int low = 0, high = n - 1;
  8.  
  9. // calculate common difference between successive elements
  10. int d = (A[n - 1] - A[0]) / n;
  11.  
  12. // run till search space is exhausted
  13. while (low <= high)
  14. {
  15. // find middle index
  16. int mid = high - (high - low) / 2;
  17.  
  18. // check difference of mid element with its right neighbor
  19. if (mid + 1 < n && A[mid + 1] - A[mid] != d)
  20. return A[mid + 1] - d;
  21.  
  22. // check difference of mid element with its left neighbor
  23. if (mid - 1 >= 0 && A[mid] - A[mid - 1] != d)
  24. return A[mid - 1] + d;
  25.  
  26. // if missing element lies on left sub-array, then we reduce
  27. // our search space to left sub-array A[low..mid-1]
  28. if (A[mid] - A[0] != (mid - 0) * d)
  29. high = mid - 1;
  30.  
  31. // if missing element lies on right sub-array, then reduce
  32. // our search space to right sub-array A[mid+1..high]
  33. else
  34. low = mid + 1;
  35. }
  36. }
  37.  
  38. // Find missing term in a sequence
  39. int main(void)
  40. {
  41. int A[] = { 5, 7, 9, 11, 15 };
  42. int n = sizeof(A) / sizeof(A[0]);
  43.  
  44. printf("Missing element is %d", missingTerm(A, n));
  45.  
  46. return 0;
  47. }
Success #stdin #stdout 0s 4360KB
stdin
Standard input is empty
stdout
Missing element is 13