package main import "fmt" func nextGreaterElements(nums []int) []int { n := len(nums) res := make([]int, n) for i := range res { res[i] = -1 } stack := []int{} for i := 0; i < n; i++ { for len(stack) > 0 && nums[i] > nums[stack[len(stack)-1]] { idx := stack[len(stack)-1] stack = stack[:len(stack)-1] res[idx] = nums[i] } stack = append(stack, i) } return res } func main() { arr := []int{4, 5, 2, 25} result := nextGreaterElements(arr) fmt.Println(result) }
The code uses a stack to keep indices of elements for which the next greater element is not found yet. When a bigger element is found, it updates the result for those indices. For the input [4, 5, 2, 25], the next greater elements are [5, 25, 25, -1].
The stack stores indices of elements waiting for their next greater element. When a bigger element comes, it pops from the stack and updates results. This avoids nested loops and achieves O(n) time.
package main import "fmt" func nextGreaterElementsCircular(nums []int) []int { n := len(nums) res := make([]int, n) for i := range res { res[i] = -1 } stack := []int{} for i := 0; i < 2*n; i++ { for len(stack) > 0 && nums[i%n] > nums[stack[len(stack)-1]] { idx := stack[len(stack)-1] stack = stack[:len(stack)-1] res[idx] = nums[i%n] } if i < n { stack = append(stack, i) } } return res } func main() { arr := []int{1, 2, 1} result := nextGreaterElementsCircular(arr) fmt.Println(result) }
The code simulates a circular array by iterating twice the length. For input [1, 2, 1], the next greater elements are [2, -1, 2].
package main import "fmt" func nextGreaterElements(nums []int) []int { n := len(nums) res := make([]int, n) stack := []int{} for i := 0; i < n; i++ { for len(stack) > 0 && nums[i] > nums[stack[len(stack)-1]] { idx := stack[len(stack)-1] stack = stack[:len(stack)-1] res[idx] = nums[i] } stack = append(stack, i) } return res } func main() { arr := []int{2, 1, 3} result := nextGreaterElements(arr) fmt.Println(result) }
The code uses stack[len(stack)] which is out of range because valid indices go up to len(stack)-1. This causes a runtime panic: index out of range.
For [13, 7, 6, 12], next greater elements are [-1, 12, 12, -1]. Two elements (13 and 12) have no next greater element.
