LeetCode 739 Daily Temperatures Java Solution

✅ Solution — LeetCode 739. Daily Temperatures (Java) 🧠 Idea (Monotonic Stack) We use a stack to store indices of days. The stack keeps temperatures in decreasing order. When we find a warmer temperature, we: Pop the previous index from stack Calculate the difference in days Store it in the result array 💻 Java Code class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] res = new int[n]; Stack<Integer> stack = new Stack<>(); for(int i = 0; i < n; i++){ while(!stack.isEmpty() && temperatures[i] > temperatures[stack.peek()]){ int prev = stack.pop(); res[prev] = i - prev; } stack.push(i); } return res; } } ⏱ Time Complexity O(n) Each element is pushed and popped once. 💾 Space Complexity O(n) 🚀 100 Days of Learning & Problem Solving – Day 79 🚀 📅 Day 79 / 100 Continuing my #100DaysOfLeetCode journey by exploring the Monotonic Stack pattern today. ✅ Today’s Progress: 🔹 Solved LeetCode 739 – Daily Temperatures 🔹 Implemented the monotonic stack technique for efficient comparisons 🔹 Practiced solving “next greater element” type problems 🔹 Improved understanding of stack-based problem-solving patterns 🧠 Key Learnings: ✔️ Using stacks to track unresolved elements ✔️ Identifying the “next greater element” pattern ✔️ Avoiding brute-force nested loops with a linear-time solution ✔️ Writing efficient solutions with better time complexity Problems like this show how the right data structure can reduce complexity dramatically. From nested loops to linear time — the power of patterns 🚀 📌 Alongside DSA, I continue focusing on: ✔️ Strengthening core programming fundamentals ✔️ Recognizing reusable problem-solving patterns ✔️ Writing clean and efficient code ✔️ Staying consistent with daily practice Learning every day, improving one problem at a time 💪 #100DaysOfLearning #LeetCode #DSA #Java #ProblemSolving #CodingJourney #LearningInPublic #Consistency

  • graphical user interface, text, application, chat or text message

To view or add a comment, sign in

Explore content categories