All submissions

Scan Memory for Three Consecutive Increasing Values

Code

#include <stdio.h>

int find_pattern(int *mem, int n) {
    // Write your pointer-based logic here
    if(mem == NULL || n < 3) return -1;

    int* p = mem;
    int* end = mem + n - 2; // last valid start for a 3 element window

    while(p < end){
        if(*(p+1) == *p + 1 && *(p+2) == *(p+1) + 1){
            return (int)(p - mem);
        }
        p++;
    } 
    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

/*
Questions:
- are negative and zeros allowed
- minimum size of array is 3
- duplicate values; how to handle them?
- scalability for large n
- input arr is valid (that means no null)

Plan:
- check for the min size (if n < 3 then return -1)
- Iterate using pointers
    - from 0 to n-3
    - current, next and the one after are strictly increasing by 1
- Return the index
    - if found, return the index (distance from the start pointer)
    - else return -1

Edge Cases
- n < 3: return -1
- all elements are same: return -1
- pattern at the end should also be detected
- negative numbers should work as long as they are consequtive 


*/

 

 

Loading...

Input

8 2 4 5 6 9 11 12 14

Expected Output

1