Scan Memory for Three Consecutive Increasing Values

Code

#include <stdio.h>

int find_pattern(int *mem, int n) {
    // Write your pointer-based logic here
    int *p = mem;
    int idx = 0;

    // we can check while idx <= n-3 so p+2 stays inside the buffer
    while (idx <= n - 3) {
        int a = *p;
        int b = *(p + 1);
        int c = *(p + 2);

        // use difference checks (safer vs potential overflow than a+1 comparisons)
        if ((b - a == 1) && (c - b == 1)) {
            return idx;
        }

        p++;    // pointer walk to next element
        idx++;  // keep track of the index to return
    }
      return -1;
    }
   


int main() {
    int n, arr[100];
    scanf("%d", &n);

    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int res = find_pattern(arr, n);
    printf("%d", res);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

8 2 4 5 6 9 11 12 14

Expected Output

1