Solving Next Greater Element I with Stack and HashMap

💻✨ 𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝟰𝟵𝟲 | 𝗡𝗲𝘅𝘁 𝗚𝗿𝗲𝗮𝘁𝗲𝗿 𝗘𝗹𝗲𝗺𝗲𝗻𝘁 𝗜 ✨💻 Today I worked on an interesting challenge — “Next Greater Element I”, a problem that tests both logical reasoning and data structure efficiency 🔍 🔹 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁 (𝗦𝗶𝗺𝗽𝗹𝗶𝗳𝗶𝗲𝗱): Given two arrays nums1 and nums2, for each element in nums1, find the first greater element to its right in nums2. If no such element exists ➜ return -1. 🔹 𝗞𝗲𝘆 𝗖𝗼𝗻𝗰𝗲𝗽𝘁𝘀 𝗨𝘀𝗲𝗱: ✅ Stack (for tracking next greater efficiently) ✅ HashMap (for constant-time lookup) ✅ Reverse traversal → O(n) time 🔹 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Instead of using a brute-force O(n²) method, I used a monotonic decreasing stack, a powerful pattern for such problems — improving efficiency from O(n²) ➜ O(n) 🚀 Here’s a glimpse of my Java solution 👇 Stack<Integer> st = new Stack<>(); for (int i = n - 1; i >= 0; i--) {   while (!st.isEmpty() && nums2[i] >= st.peek()) st.pop();   nge[i] = st.isEmpty() ? -1 : st.peek();   st.push(nums2[i]); } 🧠 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Choosing the right data structure can turn a complex problem into an elegant one. Always enjoy challenges that combine algorithmic thinking + clean code design 💡 #𝗝𝗮𝘃𝗮 #𝗖𝗼𝗱𝗶𝗻𝗴 #𝗗𝗦𝗔 #𝗟𝗲𝗲𝘁𝗖𝗼𝗱𝗲 #𝗣𝗿𝗼𝗯𝗹𝗲𝗺𝗦𝗼𝗹𝘃𝗶𝗻𝗴 #𝗦𝗼𝗳𝘁𝘄𝗮𝗿𝗲𝗘𝗻𝗴𝗶𝗻𝗲𝗲𝗿𝗶𝗻𝗴 #𝗛𝗶𝗿𝗶𝗻𝗴 #𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴

To view or add a comment, sign in

Explore content categories