LeetCode in Kotlin

1019. Next Greater Node In Linked List

Medium

You are given the head of a linked list with n nodes.

For each node in the list, find the value of the next greater node. That is, for each node, find the value of the first node that is next to it and has a strictly larger value than it.

Return an integer array answer where answer[i] is the value of the next greater node of the ith node (1-indexed). If the ith node does not have a next greater node, set answer[i] = 0.

Example 1:

Input: head = [2,1,5]

Output: [5,5,0]

Example 2:

Input: head = [2,7,4,3,5]

Output: [7,0,5,5,0]

Constraints:

Solution

import com_github_leetcode.ListNode

/*
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
@Suppress("NAME_SHADOWING")
class Solution {
    fun nextLargerNodes(head: ListNode?): IntArray {
        var head = head
        val len = length(head)
        var i = 0
        val arr = IntArray(len)
        val idx = IntArray(len)
        while (head != null) {
            arr[i] = head.`val`
            head = head.next
            i++
        }
        hlp(arr, idx, 0)
        i = 0
        while (i < idx.size) {
            val j = idx[i]
            if (j != -1) {
                arr[i] = arr[j]
            } else {
                arr[i] = 0
            }
            i++
        }
        arr[i - 1] = 0
        return arr
    }

    private fun hlp(arr: IntArray, idx: IntArray, i: Int) {
        if (i == arr.size - 1) {
            idx[i] = -1
            return
        }
        hlp(arr, idx, i + 1)
        var j = i + 1
        while (j != -1 && arr[i] >= arr[j]) {
            j = idx[j]
        }
        if (j != -1 && arr[i] >= arr[j]) {
            idx[i] = -1
        } else {
            idx[i] = j
        }
    }

    private fun length(head: ListNode?): Int {
        var head = head
        var len = 0
        while (head != null) {
            head = head.next
            len++
        }
        return len
    }
}