🚀 Day 21/100 – DSA Challenge Today’s problem: Daily Temperatures 🌡️ The task is to find how many days you have to wait for a warmer temperature. If no such day exists, return 0. 🔴 Brute Force Approach (O(n²)) 👉 For each day, check all future days until you find a warmer temperature. 📌 Java Code: class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (temperatures[j] > temperatures[i]) { result[i] = j - i; break; } } } return result; } } 🟢 Optimized Approach: Monotonic Stack (O(n)) 👉 Instead of checking every future day, use a stack to store indices and resolve them when a warmer day appears. 📌 Java Code: class Solution { public int[] dailyTemperatures(int[] temperatures) { int n = temperatures.length; int[] result = new int[n]; Stack<Integer> st = new Stack<>(); for (int i = 0; i < n; i++) { while (!st.isEmpty() && temperatures[i] > temperatures[st.peek()]) { int prevPos = st.pop(); result[prevPos] = i - prevPos; } st.push(i); } return result; } } ⚡ Complexity Comparison: Brute Force → O(n²) Optimized (Stack) → O(n) 🎯 Key Learning: Whenever you see “next greater element” type problems, think monotonic stack 🔥 📈 Day 21 done—consistency is the real win! #100DaysOfCode #DSA #Java #CodingChallenge #LearningJourney
Daily Temperatures Problem Solution in Java
More Relevant Posts
-
Day 70/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Reverse Linked List II A neat variation of linked list reversal where only a specific portion of the list is reversed. Problem idea: Reverse a linked list from position left to right, keeping the rest of the list unchanged. Key idea: In-place reversal using pointer manipulation. Why? • We don’t reverse the whole list, only a segment • Need to reconnect the reversed part correctly • Must carefully track boundaries (left and right) How it works: • Use a dummy node to handle edge cases • Move a pointer to the node just before left • Start reversing nodes one by one within the range • Adjust links to insert nodes at the front of the sublist • Reconnect the reversed portion with remaining list Time Complexity: O(n) Space Complexity: O(1) Big takeaway: Partial reversal in linked lists requires precise pointer updates, not extra space. This builds strong intuition for advanced linked list problems. 🔥 Day 70 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #LinkedList #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
-
🚀 Day 45/60 – DSA Challenge Today’s problem was about searching in a Rotated Sorted Array using Binary Search 🔍 🔍 Problem Solved: Given a rotated sorted array, efficiently find the index of a target element. 🧠 Approach I Used: Instead of directly applying binary search, I broke the problem into two steps: 1️⃣ Find the pivot (rotation point) using binary search 2️⃣ Apply binary search on the correct half of the array Left half → sorted from start to pivot-1 Right half → sorted from pivot to end ⚡ Key Insight: By identifying the pivot, the problem becomes two simple binary searches Careful boundary checks (like target >= nums[0]) ensure we search in the correct half Handling edge cases (like pivot at index 0) is crucial for correctness 📈 Complexity: Time: O(log n) Space: O(1) 🎯 What I Learned: Complex problems can often be simplified by breaking them into smaller parts Binary Search is not just about searching—it’s about understanding structure Boundary conditions can make or break your solution Debugging edge cases today made the concept even clearer 💡 #Day45 #DSAChallenge #BinarySearch #Java #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🚀 Day 22/100 – DSA Challenge Today’s problem: Climbing Stairs (LeetCode | Easy | DP) The problem is simple: You can climb either 1 or 2 steps at a time. How many distinct ways are there to reach the top? 🔴 Approach 1: Recursion (Brute Force) 👉 At each step, you have 2 choices: Take 1 step Take 2 steps 📌 Java Code: class Solution { public int climbStairs(int n) { if (n <= 2) return n; return climbStairs(n - 1) + climbStairs(n - 2); } } ⚡ Complexity: Time: O(2ⁿ) ❌ (recomputes subproblems) Space: O(n) (recursion stack) 🟡 Approach 2: Memoization (Top-Down DP) 👉 Store results of subproblems to avoid recomputation 📌 Java Code: class Solution { public int climbStairs(int n) { int[] dp = new int[n + 1]; return helper(n, dp); } private int helper(int n, int[] dp) { if (n <= 2) return n; if (dp[n] != 0) return dp[n]; dp[n] = helper(n - 1, dp) + helper(n - 2, dp); return dp[n]; } } ⚡ Complexity: Time: O(n) ✅ Space: O(n) 🟢 Observation: This problem is essentially the Fibonacci sequence: f(n) = f(n-1) + f(n-2) 🎯 Key Learning: Start with recursion to understand the problem, then optimize using DP to eliminate overlapping subproblems. 📈 Day 22 done—getting better at recognizing DP patterns! #100DaysOfCode #DSA #DynamicProgramming #Java #CodingJourney
To view or add a comment, sign in
-
🚀 Day 76 — Slow & Fast Pointer (Find the Duplicate Number) Continuing the cycle detection pattern — today I applied slow‑fast pointers to an array problem where the values act as pointers to indices. 📌 Problem Solved: - LeetCode 287 – Find the Duplicate Number 🧠 Key Learnings: 1️⃣ The Problem Twist Given an array of length `n+1` containing integers from `1` to `n` (inclusive), with one duplicate. We must find the duplicate without modifying the array and using only O(1) extra space. 2️⃣ Why Slow‑Fast Pointer Works Here - Treat the array as a linked list where `i` points to `nums[i]`. - Because there’s a duplicate, two different indices point to the same value → a cycle exists in this implicit linked list. - The duplicate number is exactly the entry point of the cycle (same logic as LeetCode 142). 3️⃣ The Algorithm in Steps - Phase 1 (detect cycle): `slow = nums[slow]`, `fast = nums[nums[fast]]`. Wait for them to meet. - Phase 2 (find cycle start): Reset `slow = 0`, then move both one step at a time until they meet again. The meeting point is the duplicate. 4️⃣ Why Not Use Sorting or Hashing? - Sorting modifies the array (not allowed). - Hashing uses O(n) space (not allowed). - Slow‑fast pointer runs in O(n) time and O(1) space — perfect for the constraints. 💡 Takeaway: This problem beautifully demonstrates how the slow‑fast pattern transcends linked lists. Any structure where you can define a “next” function (here: `next(i) = nums[i]`) can be analyzed for cycles. Recognizing this abstraction is a superpower. No guilt about past breaks — just another pattern mastered, one day at a time. #DSA #SlowFastPointer #CycleDetection #FindDuplicateNumber #LeetCode #CodingJourney #Revision #Java #ProblemSolving #Consistency #GrowthMindset #TechCommunity #LearningInPublic
To view or add a comment, sign in
-
Problem :- Plus One (LeetCode 66) Problem Statement :- You are given a large integer represented as an integer array digits, where each digits[i] is a digit of the integer. The digits are ordered from most significant to least significant. Increment the integer by one and return the resulting array of digits. Approach :- Carry Handling i - Traverse from the last digit ii - If digit < 9 → increment and return iii - If digit == 9 → make it 0 and carry forward iv - If all digits are 9 → create new array v - Time Complexity : O(n) vi - Space Complexity : O(1) class Solution { public int[] plusOne(int[] digits) { int n = digits.length; for(int i = n - 1; i >= 0; i--) { if(digits[i] < 9) { digits[i]++; return digits; } digits[i] = 0; } int[] result = new int[n + 1]; result[0] = 1; return result; } } How would you optimize this further? #Java #DSA #LeetCode #CodingJourney #LearnInPublic #SoftwareEngineering #Arrays
To view or add a comment, sign in
-
-
🚀 #100DaysOfCode – Day 18 Today’s problem: Kth Largest Element in a Stream 📊 We need to continuously track the kth largest element as new numbers keep coming in. 🔴 Brute Force Approach Store all elements in a list Sort the list every time a new element is added Return the kth largest ⛔ Time Complexity: O(n log n) per insertion 👉 Not efficient for continuous streams 🟢 Optimized Approach (Min Heap) Use a Min Heap of size k 💡 Idea: Keep only the k largest elements in the heap The top (peek) will always be the kth largest ✅ Code: class KthLargest { PriorityQueue<Integer> pq = new PriorityQueue<>(); private int k; public KthLargest(int k, int[] nums) { this.k = k; pq = new PriorityQueue<>(k); for (int num : nums) { pq.offer(num); if (pq.size() > k) pq.poll(); } } public int add(int val) { pq.offer(val); if (pq.size() > k) pq.poll(); return pq.peek(); } } 🧠 Key Insight 👉 Instead of storing all elements, just maintain the top k largest elements If heap size > k → remove smallest The smallest in heap = kth largest overall ⚡ Complexity Time: O(log k) per insertion Space: O(k) 🔍 Example k = 3 Stream: [4, 5, 8, 2] After processing → Heap = [4,5,8] Add(3) → [4,5,8] Add(10) → [5,8,10] 👉 kth largest always at the top of heap 💡 Learning of the Day When dealing with continuous data streams, don’t store everything — store only what matters. #Day18 #100DaysOfCode #DSA #Java #Heap #PriorityQueue #CodingJourney #LeetCode
To view or add a comment, sign in
-
🚀 #100DaysOfCode – Day 20 Today’s problem: Kth Largest Element in an Array 📊 Given an integer array nums and an integer k, return the kth largest element in the array (not necessarily distinct). 🔴 Brute Force Approach Sort the array in descending order Return the element at index k-1 ⛔ Time Complexity: O(n log n) 👉 Sorting the entire array is unnecessary when we only need one element 🟢 Optimized Approach (Min Heap) 💡 Idea: Use a Min Heap of size k Keep only the k largest elements The top of the heap will always be the kth largest ✅ Code: class Solution { public int findKthLargest(int[] nums, int k) { PriorityQueue<Integer> pq = new PriorityQueue<>(); for (int num : nums) { pq.offer(num); if (pq.size() > k) { pq.poll(); } } return pq.peek(); } } 🧠 Key Insight 👉 Instead of sorting everything, maintain only the k largest elements If heap size exceeds k → remove smallest The smallest in heap = kth largest overall ⚡ Complexity Time: O(n log k) Space: O(k) 🔍 Example nums = [3,2,1,5,6,4], k = 2 Step-by-step heap: Add → maintain size k 👉 Final heap → [5,6] 👉 Answer = 5 💡 Learning of the Day When solving problems: 👉 Don’t process everything — process only what’s required #Day20 #100DaysOfCode #DSA #Java #Heap #PriorityQueue #CodingJourney #LeetCode #ProblemSolving
To view or add a comment, sign in
-
🚀 Solved: Find Dominant Index (LeetCode) Just solved an interesting problem where the goal is to find whether the largest element in the array is at least twice as large as every other number. 💡 Approach: 1. First, traverse the array to find the maximum element and its index. 2. Then, iterate again to check if the max element is at least twice every other element. 3. If the condition fails for any element → return "-1". 4. Otherwise → return the index of the max element. 🧠 Key Insight: Instead of comparing all pairs, just track the maximum and validate it — keeps the solution clean and efficient. ⚡ Time Complexity: O(n) ⚡ Space Complexity: O(1) 💻 Code (Java): class Solution { public int dominantIndex(int[] nums) { int max = -1; int index = -1; // Step 1: find max and index for (int i = 0; i < nums.length; i++) { if (nums[i] > max) { max = nums[i]; index = i; } } // Step 2: check condition for (int i = 0; i < nums.length; i++) { if (i == index) continue; if (max < 2 * nums[i]) { return -1; } } return index; } } 🔥 Got 100% runtime and 99%+ memory efficiency! #LeetCode #DSA #Java #Coding #ProblemSolving #Algorithms
To view or add a comment, sign in
-
-
**Day 116 of #365DaysOfLeetCode Challenge** Today’s problem: **Next Greater Element II (LeetCode 503)** A classic **Monotonic Stack** problem with a twist: 👉 The array is **circular** So after the last element, we continue from the first element. 💡 **Core Idea:** For every number, find the **first greater element** while traversing forward. If none exists → return `-1` Example: Input: `[1,2,1]` Output: `[2,-1,2]` Why? * First `1 → 2` * `2 → no greater` * Last `1 → wrap around → 2` 📌 **Efficient Approach: Monotonic Stack** Use stack to store indices whose next greater element is not found yet. Traverse array **twice**: `0 → 2*n - 1` Use: `idx = i % n` This simulates circular behavior. Whenever current number is greater than stack top element: 👉 Pop index 👉 Update answer ⚡ **Time Complexity:** O(n) ⚡ **Space Complexity:** O(n) **What I learned today:** Circular array problems often become simple when you traverse twice using modulo. 👉 `i % n` This trick appears in many advanced array questions. 💭 **Key Takeaway:** When you see: * Next Greater Element * Previous Smaller Element * Nearest Bigger Value #LeetCode #DSA #MonotonicStack #Stack #Arrays #Java #CodingChallenge #ProblemSolving #TechJourney #Consistency
To view or add a comment, sign in
-
-
Day 67/100 | #100DaysOfDSA 🧩🚀 Today’s problem: Subsets II Another classic backtracking problem with a twist (duplicates). Problem idea: Generate all possible subsets (power set), but avoid duplicate subsets. Key idea: Backtracking + sorting to handle duplicates. Why? • We need to explore all subset combinations • Duplicates in input can lead to duplicate subsets • Sorting helps us skip repeated elements efficiently How it works: • Sort the array first • At each step, add current subset to result • Iterate through elements • Skip duplicates using condition: 👉 if (i > start && nums[i] == nums[i-1]) continue • Choose → recurse → backtrack Time Complexity: O(2^n) Space Complexity: O(n) recursion depth Big takeaway: Handling duplicates in backtracking requires careful skipping logic, not extra data structures. This pattern appears in many problems (subsets, permutations, combinations). 🔥 Day 67 done. 🚀 #100DaysOfCode #LeetCode #DSA #Algorithms #Backtracking #Recursion #Java #CodingJourney #ProblemSolving #InterviewPrep #TechCommunity
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development