1. Linear Search for Every Query
Intuition
For every query element x in nums1, locate x in nums2 and then iterate rightwards until a strictly greater element is found.
Algorithm
- Step 1: Initialize result array
ansof sizenums1.length. - Step 2: For each element
nums1[i], find its indexidxinnums2. - Step 3: Scan
nums2fromidx + 1tonums2.length - 1. - Step 4: If
nums2[j] > nums1[i], recordans[i] = nums2[j]and break. If none found, setans[i] = -1. - Step 5: Return
ans.
#include <iostream>#include <vector> class Solution {public: std::vector<int> nextGreaterElement(std::vector<int>& nums1, std::vector<int>& nums2) { std::vector<int> ans(nums1.size(), -1); for (size_t i = 0; i < nums1.size(); i++) { int target = nums1[i]; int idx = -1; for (size_t j = 0; j < nums2.size(); j++) { if (nums2[j] == target) { idx = j; break; } } for (size_t j = idx + 1; j < nums2.size(); j++) { if (nums2[j] > target) { ans[i] = nums2[j]; break; } } } return ans; }}; int main() { Solution solver; std::vector<int> nums1 = {4, 1, 2}; std::vector<int> nums2 = {1, 3, 4, 2}; std::vector<int> ans = solver.nextGreaterElement(nums1, nums2); std::cout << "Output: ["; for (size_t i = 0; i < ans.size(); i++) { std::cout << ans[i] << (i + 1 < ans.size() ? ", " : ""); } std::cout << "]" << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(M * N)— For each element in nums1 (size M), find its position in nums2 (size N) and scan to the right to find the next greater element. - Space complexity:
O(1)— O(1) auxiliary space beyond the output array.
Why Brute Force Doesn't Scale:
When M and N are large (e.g. 105), O(M * N) = 1010 operations.
Monotonic Stack precomputes answers in 1 pass O(N) and answers all M queries in O(M).