1. Leftward Linear Scan
Intuition
For each index i, loop backwards from j = i - 1 down to 0 and find the first A[j] < A[i].
Algorithm
- Step 1: Initialize result array
Gof sizeNwith-1. - Step 2: Loop
ifrom 0 toN - 1. - Step 3: Loop
jfromi - 1down to 0. - Step 4: If
A[j] < A[i], setG[i] = A[j]and break inner loop. - Step 5: Return
G.
#include <iostream>#include <vector> class Solution {public: std::vector<int> prevSmaller(std::vector<int>& A) { int n = A.size(); std::vector<int> G(n, -1); for (int i = 0; i < n; i++) { for (int j = i - 1; j >= 0; j--) { if (A[j] < A[i]) { G[i] = A[j]; break; } } } return G; }}; int main() { Solution solver; std::vector<int> A = {4, 5, 2, 10, 8}; std::vector<int> ans = solver.prevSmaller(A); 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(N^2)— For each element i, scan leftwards through all j < i until a strictly smaller element is encountered. - Space complexity:
O(1)— O(1) extra space beyond output array.
Why Brute Force Doesn't Scale:
A strictly decreasing array takes N*(N-1)/2 comparisons.
At N = 100,000, Monotonic Stack executes in <15ms vs TLE (>10s) for brute force.