Company: KLA
Difficulty: medium
Kth Next greater element for each index in an array Problem Description Given an array of size n, return an answer array of size n that stores the index of the kth next greater element of each index to its right. If no such valid index exists for a particular index, set its value in the answer array to be -1. Examples Example 1: Input: n=5, k=2, arr=[1,2,3,4,5] Output: [2,3,4,-1,-1] Explanation: For index 0 (value 1): The elements to its right are [2,3,4,5]. Greater elements are [2,3,4,5]. Sorted greater elements: [2,3,4,5]. The 2nd (k=2) next greater element is 3, which is at index 2. So, output[0] = 2. For index 1 (value 2): The elements to its right are [3,4,5]. Greater elements are [3,4,5]. Sorted greater elements: [3,4,5]. The 2nd (k=2) next greater element is 4, which is at index 3. So, output[1] = 3. For index 2 (value 3): The elements to its right are [4,5]. Greater elements are [4,5]. Sorted greater elements: [4,5]. The 2nd (k=2) next greater element is 5, which is at index 4.