Sponsored
Sponsored
This approach involves iterating over each element of nums1 and finding the corresponding element in nums2. Once located, search for the next greater element to its right. This straightforward method checks each pair and ensures correctness but may not be optimal for larger arrays.
The time complexity of this brute force approach is O(n * m), where n is the number of elements in nums1, and m is the number of elements in nums2. The space complexity is O(1) apart from the output array.
using System.Collections.Generic;
public class NextGreaterElementProblem {
public int[] NextGreaterElement(int[] nums1, int[] nums2) {
int[] result = new int[nums1.Length];
for (int i = 0; i < nums1.Length; i++) {
int pos = Array.IndexOf(nums2, nums1[i]);
int greater = -1;
for (int j = pos + 1; j < nums2.Length; j++) {
if (nums2[j] > nums1[i]) {
greater = nums2[j];
break;
}
}
result[i] = greater;
}
return result;
}
public static void Main() {
int[] nums1 = { 4, 1, 2 };
int[] nums2 = { 1, 3, 4, 2 };
var obj = new NextGreaterElementProblem();
int[] answer = obj.NextGreaterElement(nums1, nums2);
Console.WriteLine(string.Join(", ", answer));
}
}
This C# solution employs a brute force method for identifying the next greater value in nums2 for each element in nums1. It utilizes built-in methods like IndexOf for resolution but remains computationally intensive.
This approach utilizes a stack and a hashmap to efficiently solve the problem. As we traverse nums2, we use the stack to store elements for which the next greater element hasn't been found yet. Whenever a greater element is found, it's recorded in the hashmap against the elements in the stack. This technique is optimal and runs in linear time.
The time complexity is O(n + m), approaching linear time with respect to input size and space is approximately O(m) for hashmap tracking.
1using System;
2using System.Collections.Generic;
3
4public class NextGreaterElementOptimized {
5 public int[] NextGreaterElement(int[] nums1, int[] nums2) {
6 Dictionary<int, int> map = new Dictionary<int, int>();
7 Stack<int> stack = new Stack<int>();
8 foreach (int num in nums2) {
9 while (stack.Count > 0 && stack.Peek() < num) {
10 map[stack.Pop()] = num;
11 }
12 stack.Push(num);
13 }
14 for (int i = 0; i < nums1.Length; i++) {
15 nums1[i] = map.ContainsKey(nums1[i]) ? map[nums1[i]] : -1;
16 }
17 return nums1;
18 }
19
20 public static void Main() {
21 int[] nums1 = { 4, 1, 2 };
22 int[] nums2 = { 1, 3, 4, 2 };
23 var obj = new NextGreaterElementOptimized();
24 int[] result = obj.NextGreaterElement(nums1, nums2);
25 Console.WriteLine(string.Join(", ", result));
26 }
27}
This C# solution uses a stack and hashmap to efficiently map elements from nums2 to find their next greater numbers. By building the hashmap beforehand, the transformation into the result array for nums1 is highly optimized.