




Sponsored
Sponsored
This approach utilizes a stack to keep track of the indices of the elements for which we are finding the next greater element. We traverse the array twice (length times two) to account for the circular nature of the array. For each element, we repeatedly pop elements from the stack while the current element is greater than the element represented by the index at the top of the stack. As we pop elements, we update their next greater element in the resulting array. The stack helps ensure that each element is processed efficiently, leading to an O(n) complexity.
Time Complexity: O(n)
Space Complexity: O(n) (due to the stack and result array)
1#include <stdlib.h>
2#include <string.h>
3
4int* nextGreaterElements(int* nums, int numsSize, int* returnSize) {
5    *returnSize = numsSize;
6    int *res = (int*)malloc(numsSize * sizeof(int));
7    int *stack = (int*)malloc(numsSize * 2 * sizeof(int));
8    int top = -1;
9
10    for (int i = 0; i < numsSize; i++) res[i] = -1;
11    for (int i = 0; i < 2 * numsSize; i++) {
12        while (top != -1 && nums[stack[top]] < nums[i % numsSize]) {
13            res[stack[top--]] = nums[i % numsSize];
14        }
15        if (i < numsSize) {
16            stack[++top] = i;
17        }
18    }
19    free(stack);
20    return res;
21}This C code leverages raw arrays to emulate stack behavior, processing each element twice to accommodate for circular nature. It's an index-based solution using a stack of indices for efficiency.
This approach uses two separate traversals to find the next greater element by checking for each element's greater counterpart. We double-iterate through the array copying elements to support cyclic checking. Though simpler conceptually, its efficiency isn't as optimal due to direct comparisons, and it could degrade to an O(n^2) complexity in worst cases. It's educational for understanding direct exhaustive search in circular constructs.
Time Complexity: O(n^2) in the worst case
1
In C, a double-loop approach captures each index's potential to exceed successive indices using modulo for cycle completion. Although inefficient for large-scale scenarios, it's illustrative of pure systematic iteration.