🔥 Day 94 of #100DaysOfCode Today’s problem: LeetCode – Online Stock Span 📈 📌 Problem Summary Design a class StockSpanner that calculates the stock span for each new price. 👉 The span of a stock’s price today is the number of consecutive days (including today) the price was less than or equal to today’s price. Example input: [100, 80, 60, 70, 60, 75, 85] Output: [1, 1, 1, 2, 1, 4, 6] 🧠 Approach: Monotonic Stack (Decreasing Stack) This is another powerful Next Greater Element pattern, but optimized for streaming input. Instead of storing just prices, we store: {price, span} ⚙️ Core Logic (in next(price)): 1️⃣ Initialize span = 1 2️⃣ While stack is not empty AND top price ≤ current price: Add popped span to current span 3️⃣ Push {price, span} into stack 4️⃣ Return span 💡 Why Store Span Instead of Index? Because: It compresses previous smaller values into one value. Avoids recalculating spans repeatedly. Makes each element pushed & popped only once. ⏱ Time Complexity: O(n) amortized Each price is pushed once and popped once. 💾 Space Complexity: O(n) 🚀 Performance Runtime: 30 ms Beats ~72% Clean and optimal solution ✔️ 🧠 Pattern Insight Problems like: Daily Temperatures Next Greater Element Stock Span 👉 All use Monotonic Stack Stack mastery getting stronger 🔥 On to Day 95 🚀 #100DaysOfCode #LeetCode #MonotonicStack #StockSpan #Java #DSA #InterviewPrep
LeetCode Stock Span Problem Solution with Monotonic Stack
More Relevant Posts
-
Most people would return this answer: [2, 2] But the correct answer is: [2] Why? 🚀 Day 64/365 — DSA Challenge Solved: Intersection of Two Arrays The task: Given two arrays, return their intersection. But there are two conditions: • The element must exist in both arrays • The result must contain only unique values Example: nums1 = [1,2,2,1] nums2 = [2,2] Output: [2] Even though 2 appears multiple times, it should appear only once in the result. 💡 My Approach (Simple Logic) Step 1 Loop through every element of nums1. Step 2 Check if that number exists in nums2. Step 3 Before adding it to the result, make sure it hasn't already been added. To keep the code clean, I used three methods: intersection() Main method that loops through nums1 and builds the result. existsInArray(num, arr) Checks if a number exists in another array. existsInArray(num, arr, length) Checks duplicates only inside the filled part of the result array. Example walkthrough: 1 -> not in nums2 -> skip 2 -> exists -> add 2 -> already added -> skip 1 -> skip Final output: [2] ⏱ Time Complexity: O(n × m) 📦 Space Complexity: O(n) Day 64/365 complete. Code 👇 https://lnkd.in/dad5sZfu #DSA #Java #LeetCode #LearningInPublic #ProblemSolving #Consistency
To view or add a comment, sign in
-
-
🔥 Day 96 of #100DaysOfCode Today’s problem: LeetCode – Find Minimum in Rotated Sorted Array 🔄📉 📌 Problem Summary You are given a sorted array that has been rotated at some pivot. Example: Sorted array → [1,2,3,4,5] Rotated → [3,4,5,1,2] Goal 👉 Find the minimum element in the array. Example: Input: [3,4,5,1,2] Output: 1 🧠 Approach: Binary Search Since the array was originally sorted, we can use Binary Search to locate the rotation point. Key observation: If nums[l] < nums[r] → Subarray is already sorted → Minimum is nums[l] Otherwise: Compute middle index Compare with left boundary to decide which half to search ⚙️ Decision Logic 1️⃣ If left part is sorted → Minimum must be in right half 2️⃣ If left part is not sorted → Minimum is in left half 💡 Key Idea We are essentially searching for the rotation pivot, which contains the smallest value. ⏱ Time Complexity: O(log n) 💾 Space Complexity: O(1) 🚀 Performance Runtime: 0 ms Beats 100% submissions 🔥 Memory: 43.8 MB 🧠 Pattern Insight Common Binary Search variants: Search in Rotated Sorted Array Find Minimum in Rotated Array Peak Element Binary Search on Answer Recognizing these patterns makes solving them much faster. Only 4 days left to complete #100DaysOfCode 🚀 Consistency paying off every day. On to Day 97 🔥 #100DaysOfCode #LeetCode #BinarySearch #RotatedArray #Java #DSA #InterviewPrep
To view or add a comment, sign in
-
-
After working through merge-based problems, I spent some time understanding Quick Sort. Unlike Merge Sort, which splits first and merges later, Quick Sort works by placing one element (pivot) in its correct position first, and then recursively sorting the parts around it. The key part of the algorithm is the partition step, where the pivot element is moved to the position where it would appear in the final sorted array. Approach used : - choose a pivot element - count how many elements are smaller than the pivot - place the pivot at its correct index - rearrange elements so that - left side contains values ≤ pivot - right side contains values > pivot - recursively apply the same process to both sides Core quick sort logic : static void quickSort(int[] arr, int lo, int hi) { if (lo >= hi) return; int idx = partition(arr, lo, hi); quickSort(arr, lo, idx - 1); quickSort(arr, idx + 1, hi); } Things that became clear : - the partition step controls the entire algorithm - on average Quick Sort runs in O(n log n) - the worst case can reach O(n²) when the pivot selection is poor - the recursion depth depends on how balanced the partitions are Understanding how the pivot finds its correct position made the whole algorithm much easier to follow. #dsa #algorithms #quicksort #sorting #java #learninginpublic
To view or add a comment, sign in
-
𝗗𝗮𝘆 𝟲𝟳/𝟭𝟬𝟬 — 𝗜𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁 𝗤𝘂𝗲𝘂𝗲 𝘂𝘀𝗶𝗻𝗴 𝗦𝘁𝗮𝗰𝗸𝘀 Day 67. Building data structures from scratch. Can you build a queue using only stacks? Yes. Should you? Probably not. But it teaches you something valuable. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ #𝟮𝟯𝟮: Implement Queue using Stacks (Easy) 𝗧𝗵𝗲 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲: Implement a FIFO queue using only LIFO stacks. Operations: push, pop, peek, empty. The problem? Stacks are last-in-first-out. Queues are first-in-first-out. Opposite behaviors. 𝗠𝘆 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵: Two stacks: in and out. My solution keeps elements in reverse order in the in stack, so the oldest element is always on top. On push: Move all elements from in to out Push new element to in Move everything back from out to in Pop and peek? Just operate on in directly. Time: O(n) per push, O(1) for pop/peek 𝗪𝗵𝘆 𝗜𝘁 𝗠𝗮𝘁𝘁𝗲𝗿𝘀: Design problems force you to understand data structures deeply. Not just use them—build them. This isn't the most efficient approach, but it works. And understanding trade-offs is what separates good developers from great ones. 𝗖𝗼𝗱𝗲: https://lnkd.in/gcASkCjm 𝗗𝗮𝘆 𝟲𝟳/𝟭𝟬𝟬 ✅ 𝟲𝟳 𝗱𝗼𝘄𝗻. 𝟯𝟯 𝘁𝗼 𝗴𝗼. #100DaysOfCode #LeetCode #Queue #Stack #DataStructures #SystemDesign #Algorithms #CodingInterview #Programming #Java #DesignProblems
To view or add a comment, sign in
-
🚀 Day 41 / 100 | Spiral Matrix II -Intuition: -The goal is to generate an n × n matrix filled with numbers from 1 to n^2 in spiral order. -Start from the top row, move right, then move down the right column, then move left across the bottom row, and finally move up the left column. -After completing one layer, shrink the boundaries and repeat the process until the matrix is filled. -Approach: O(n²) -Initialize an empty n × n matrix. -Maintain four boundaries: top, bottom, left, and right. -Start filling numbers from 1 to n^2. -Fill the top row from left -> right and move the top boundary down. -Fill the right column from top -> bottom and move the right boundary left. -Fill the bottom row from right ->left and move the bottom boundary up. -Fill the left column from bottom -> top and move the left boundary right. -Repeat the process until all elements are filled. -Complexity: Time Complexity: O(n²) Space Complexity: O(n²) #100DaysOfCode #Java #DSA #LeetCode #Matrix
To view or add a comment, sign in
-
-
#100DaysOfLeetcode journey 🚀 Day 20/100 — Bit Manipulation & Modular Arithmetic! Today’s Problem: 1680. Concatenation of Consecutive Binary Numbers 🔹 The Goal: Given an integer $n$, concatenate the binary representations of numbers from $1$ to $n$ into a single string and return its decimal value modulo $10^9 + 7$. 🔹 The Insight: At first glance, this looks like a string problem, but building a massive binary string is a recipe for a Memory Limit Exceeded (MLE) error. The trick is to realize that when you "append" a new number $i$ to your current result, you are essentially shifting your current value to the left by the number of bits in $i$ and then adding $i$. 🔹 The Difficulty: The numbers grow exponentially. To keep things under control, we apply the property of modular arithmetic: $$(A + B) \pmod M = ((A \pmod M) + (B \pmod M)) \pmod M$$ The real challenge? Knowing when the "bit length" of your current number increases (e.g., when moving from 3 to 4, you go from 2 bits to 3 bits). ✨ Achievement: Successfully bypassed string manipulation entirely to create a pure mathematical $O(n)$ solution. 🔍 Steps followed: ✔ Bit-Width Tracking: Monitored when $i$ reached a power of 2 to increment the shift amount. ✔ Efficient Shifting: Used (ans << bitLength) | i to concatenate values at the bit level. ✔ Modular Discipline: Applied the modulo at every step to prevent integer overflow. 🔧 Complexity Analysis: Time Complexity: $O(n)$ Space Complexity: $O(1)$ Thirteen days in and the "bit-shifting" logic is starting to feel like second nature. Onward! 🛠️ #Java #DSA #LeetCode #CodingJourney #100DaysOfCode #BitManipulation #MathAlgorithms #SoftwareEngineer #Optimization
To view or add a comment, sign in
-
-
Day 25 of Daily DSA 🚀 Solved LeetCode 155: Min Stack ✅ Problem: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. Approach: Used two stacks: main stack → stores all elements min stack → keeps track of the current minimum Key idea: When pushing a value, also push it to min stack if it is ≤ current minimum During pop, if the popped value equals the top of min stack, pop from min as well This ensures the minimum element is always available in O(1) time. ⏱ Complexity: • push() → O(1) • pop() → O(1) • top() → O(1) • getMin() → O(1) 📊 LeetCode Stats: • Runtime: 5 ms (Beats 83.96%) ⚡ • Memory: 47.15 MB Great problem to understand stack design patterns and auxiliary data structures. #DSA #LeetCode #Java #DataStructures #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Day - 104 Recover Binary Search Tree The problem - You are given the root of a binary search tree (BST), where the values of exactly two nodes of the tree were swapped by mistake. Recover the tree without changing its structure. Follow up: A solution using O(n) space is pretty straight forward. Could you devise a constant O(1) space solution? Brute Force - Perform inorder traversal to collect all values in an array, identify the two swapped elements, store their positions, traverse the tree again to find and swap them back. This gives O(n) time and O(n) space for storing all node values. Approach Used - •) Declare first (first swapped node), second (second swapped node), prev (previous node in inorder traversal). •) Call helper function, helper(root). •) Swap the values, temp = first.val, first.val = second.val, second.val = temp. Helper Function - helper(TreeNode node) •) If node == null, return. •) Traverse left subtree, helper(node.left). •) If prev != null AND prev.val > node.val, - If first == null, set first = prev. - Set, second = node. •) Update, prev = node. •) Traverse right subtree, helper(node.right). Complexity - Time - O(n), where n is number of nodes. Space - O(h), recursion stack depth. Note - In a valid BST, inorder traversal produces a sorted sequence. When two nodes are swapped, it creates violations where prev.val > current.val. For adjacent swaps, there's one violation; for non-adjacent swaps, there are two. By tracking the first and second violating nodes during inorder traversal, we identify the swapped pair. The algorithm handles both cases by always updating second and only setting first once. #DSA #Java #SoftwareEngineering #InterviewPrep #LearnToCode #CodeDaily #ProblemSolving
To view or add a comment, sign in
-
-
Day 43: Interactive Logic & Flow Control – Jumping Statements & Scanner 🏃♂️⌨️ Today’s session was a "Power Move" in Java, focusing on how to break the rules of loops and give the user a voice through the console. 1. The "Escape Routes": Jumping Statements 🦘 Loops are powerful, but sometimes you need to override them. I mastered the two primary ways to manipulate execution flow: ▫️ break: The "Emergency Exit." It terminates the loop immediately. This is essential for optimization—once you find the data you're looking for, why keep searching? ▫️ continue: The "Skip Button." It bypasses the rest of the current code block and jumps straight to the next iteration. Perfect for filtering out specific data points without stopping the whole process. 2. The "User Input": Scanner Class 📥 Hardcoding values is a thing of the past! Using java.util.Scanner, I transformed my programs into interactive tools that can talk to the user: ▫️ Dynamic Data: Using next(), nextInt(), and nextLine() to capture real-time input directly from the keyboard. ▫️ The Workflow: I practiced the standard cycle: Import ➡️ Initialize Object ➡️ Prompt User ➡️ Capture ➡️ Process. 3. The "Buffer" Lesson: Precision Coding ⚠️ A key technical takeaway today was handling the "NextLine Trap." I learned how to properly clear the buffer after using nextInt() to ensure the program doesn't skip over string inputs. It’s these small details that separate a beginner from a professional! The Java logic is getting sharper, and the programs are getting smarter. 🧩 Next up: Nested Loops and Logic Patterns! 🚀 #JavaFullStack #100DaysOfCode #BackendDevelopment #JavaScanner #CodingLogic #SoftwareEngineer #ChirukuriNarendra #LearningInPublic
To view or add a comment, sign in
-
📅 Day 10/60 🔹 Problem: Largest Number in One Swap Given a string representing a number, return the largest possible number by performing at most one swap of two digits. 🧠 Key Concept: ➡️ Greedy + Last Occurrence Tracking Instead of trying all possible swaps (O(n²)), we store the last position of each digit (0–9) and make a single optimal swap. The idea: Convert the string to a char array for easy swapping Record the last occurrence of each digit Traverse the number from left to right For each digit, check if a larger digit exists later in the number Swap with the largest possible digit that appears later Return the number immediately after the swap 📌 Why it works: Swapping the leftmost smaller digit with the largest possible digit on its right maximizes the number. ⏱ Time Complexity: O(n) 📦 Space Complexity: O(1) (Only 10 digits stored) 🎯 What I Learned from This Problem: ✔️ Applying Greedy strategy to maximize numeric values ✔️ Using arrays as lookup tables for fast access ✔️ Understanding how character digits can be converted using 'digit' - '0' ✔️ Optimizing brute force O(n²) swaps → O(n) solution ✔️ Recognizing patterns where tracking last occurrences simplifies decisions 🎯 Goal ✔️ Solve 60 problems in 60 days ✔️ Master core DSA patterns (Sliding Window, Greedy, Two Pointers, Prefix Sum) ✔️ Improve coding consistency & logical thinking ✔️ Prepare for product-based companies & cloud engineering roles Building problem-solving skills one swap at a time 💡 🔖 Hashtags #60DaysOfCode #GeeksforGeeks #DSA #Java #CodingChallenge #GreedyAlgorithm #ProblemSolving #MTech #FutureCloudEngineer
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