45. Scan Memory for Three Consecutive Increasing Values

#include <stdio.h>

int find_pattern(int *mem, int n) {
    int *p1 = mem;           // points to current
    int *p2 = mem + 1;       // points to next
    int *p3 = mem + 2;       // points to next+1

    for (int i = 0; i <= n - 3; i++) {
        if (*p1 + 1 == *p2 && *p2 + 1 == *p3) {
            return i;  // found increasing pattern
        }
        p1++;
        p2++;
        p3++;
    }
    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;
}

Scanning memory in embedded applications often involves looking for patterns, sync bytes, or control sequences.

Solution Logic:

  • Use three pointers: p1, p2, p3
  • Check if values form an increasing sequence: *p1, *p1+1, *p1+2
  • Move all three pointers forward using pointer arithmetic
  • Return the index (i) of the first match
  • If none, return -1 

Alternate solution

int find_pattern(int *mem, int n) {
    for (int i = 0; i <= n - 3; i++) {
        if (*(mem + i) + 1 == *(mem + i + 1) &&
            *(mem + i + 1) + 1 == *(mem + i + 2)) {
            return i;
        }
    }
    return -1;
}

 

Loading...

Input

8 2 4 5 6 9 11 12 14

Expected Output

1