Menu
Coddy logo textTech

Practice #2

Lesson 10 of 13 in Coddy's Stack - Data Structures Series #1 course.

The next challenges are designed to use stack in them.

The Stack data structure is already provided for you — use it!

challenge icon

Challenge

Easy

Write a function nse that gets an integer array and returns an array that contains the nearest smaller element of each element (to the left). If there is no smaller element to the left of an element, return -1.

Use the provided Stack to solve this problem!

Example:

Input: [4, 5, 2, 10, 8]

Expected output: [-1, 4, -1, 2, 2]

Try it yourself

#include <stdio.h>
#include <stdlib.h>
#include "nse.h"

int main() {
    int* a = (int*)malloc(sizeof(int) * 1000);
    int aSize = 0;
    int x;
    while (scanf("%d", &x) == 1) {
        a[aSize++] = x;
    }
    int returnSize;
    int* result = nse(a, aSize, &returnSize);
    for (int i = 0; i < returnSize; i++) {
        printf("%d\n", result[i]);
    }
    free(a);
    return 0;
}

All lessons in Stack - Data Structures Series #1