LeetCode 2454. Next Greater Element IV Solution in Java, C++, Python & TypeScript | Explanation + Code

CoderIndeed
0
2454. Next Greater Element IV

Description

You are given a 0-indexed array of non-negative integers nums. For each integer in nums, you must find its respective second greater integer.

The second greater integer of nums[i] is nums[j] such that:

  • j > i
  • nums[j] > nums[i]
  • There exists exactly one index k such that nums[k] > nums[i] and i < k < j.

If there is no such nums[j], the second greater integer is considered to be -1.

  • For example, in the array [1, 2, 4, 3], the second greater integer of 1 is 4, 2 is 3, and that of 3 and 4 is -1.

Return an integer array answer, where answer[i] is the second greater integer of nums[i].

 

Example 1:

Input: nums = [2,4,0,9,6]
Output: [9,6,6,-1,-1]
Explanation:
0th index: 4 is the first integer greater than 2, and 9 is the second integer greater than 2, to the right of 2.
1st index: 9 is the first, and 6 is the second integer greater than 4, to the right of 4.
2nd index: 9 is the first, and 6 is the second integer greater than 0, to the right of 0.
3rd index: There is no integer greater than 9 to its right, so the second greater integer is considered to be -1.
4th index: There is no integer greater than 6 to its right, so the second greater integer is considered to be -1.
Thus, we return [9,6,6,-1,-1].

Example 2:

Input: nums = [3,3]
Output: [-1,-1]
Explanation:
We return [-1,-1] since neither integer has any integer greater than it.

 

Constraints:

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109

Solutions

Solution 1: Sorting + Ordered Set

We can convert the elements in the array into pairs (x, i), where x is the value of the element and i is the index of the element. Then sort by the value of the elements in descending order.

Next, we traverse the sorted array, maintaining an ordered set that stores the indices of the elements. When we traverse to the element (x, i), the indices of all elements greater than x are already in the ordered set. We only need to find the index j of the next element after i in the ordered set, then the element corresponding to j is the second largest element of x. Then, we add i to the ordered set. Continue to traverse the next element.

The time complexity is O(n × log n), and the space complexity is O(n). Here, n is the length of the array.

PythonJavaC++TypeScript
class Solution: def secondGreaterElement(self, nums: List[int]) -> List[int]: arr = [(x, i) for i, x in enumerate(nums)] arr.sort(key=lambda x: -x[0]) sl = SortedList() n = len(nums) ans = [-1] * n for _, i in arr: j = sl.bisect_right(i) if j + 1 < len(sl): ans[i] = nums[sl[j + 1]] sl.add(i) return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !