Next Greater Element Challenge Solved with Stack

Day 48 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Next Greater Element We were given an array. For each element, we had to find the next greater element on the right side. If none exists → return -1. Example: [4, 5, 2, 10] → [5, 10, 10, -1] 💻 Brute Force Approach 🔹️For each element, check all elements on the right. 🔹️Find the first greater element. 🔹️If found → store it. 🔹️Else → store -1. Time Complexity: O(n²) Space Complexity: O(1) Works. But slow. 💻 Optimal Approach (Using Stack) 🔹️Traverse from right to left. 🔹️Use a stack to store elements. 🔹️For each element:   ▪️Pop smaller elements from stack   ▪️Top of stack = next greater element   ▪️If stack empty → answer is -1 🔹️Push current element into stack Efficient. Single pass. 📊 Complexity Analysis Time Complexity: O(n) Space Complexity: O(n) 📚 What I learned today: ▫️Monotonic stack helps in nearest greater problems. ▫️Traversing from right simplifies logic. ▫️Popping smaller elements keeps stack useful. ▫️Stack stores only potential answers. Day 48 completed. Stack patterns getting stronger 🚀 #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic

To view or add a comment, sign in

Explore content categories