All submissions

Scan Memory for Three Consecutive Increasing Values

Time complexity O(n)

#include <stdio.h>
#include <math.h>

int find_pattern(int *mem, int n) {
    int l = 0; // Left pointer of window
    int r = 1; // Right pointer of window

    while (r < n) {
        if (*(mem + r) - *(mem + (r-1)) != 1) 
            l = r;
        if ((r-l) == 2)
            return l;
        r++;
    }

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

I use Sliding Window with Pointer Arithmetic

  1. Initialize two pointers
    • l → marks the start of the current window (potential starting index).
    • r → moves forward to scan through the array.
  2. Check consecutive differences
    • At each step, compare the current element *(mem + r) with the previous element *(mem + (r - 1)).
    • If the difference is exactly 1, it means the sequence is still increasing consecutively.
    • If not, reset the start of the window: set l = r.
  3. Detect a window of size 3
    • Keep track of the distance (r - l).
    • If it reaches 2, it means there are three consecutive increasing integers:
      • *(mem + l), *(mem + l + 1), and *(mem + r).
    • Return the starting index l.
  4. No match found
    • If the loop ends without finding such a pattern, return -1.

 

 

Loading...

Input

8 2 4 5 6 9 11 12 14

Expected Output

1