Day 28 of 30-day Coding Sprint Today, I shifted from the "Two-Pointer/Sliding Window" into the world of Linear Data Structures, starting with the clever simulation of a Queue using Stacks. 232. Implement Queue using Stacks - The Logic: Stacks are LIFO (Last-In, First-Out), while Queues are FIFO (First-In, First-Out). To turn a stack into a queue, you essentially have to "reverse" the order of elements. - The Strategy: Two Stacks Stack 1 (s1): Used as the "Input" buffer. Every push goes here. Stack 2 (s2): Used as the "Output" buffer. - The Secret Sauce: When you need to pop or peek, and s2 is empty, you transfer everything from s1 to s2. This flips the order, making the oldest element (the one at the bottom of s1) the top element of s2. - Complexity: While a single pop might trigger a O(N) transfer, most pop operations happen in O(1). This is known as Amortized O(1) time complexity. #30DaysOfCode #DSASprint #LeetCode #JavaScript #Stacks #Queues #DataStructures #Consistency
Implementing Queue with Stacks in 30 Days of Code
More Relevant Posts
-
📌 LeetCode Daily Challenge — Day 3 Problem: 1545. Find Kth Bit in Nth Binary String Topic: String, Recursion, Divide and Conquer 🧠 Approach (Simple Thinking): 🔹 Every string Sn is made of 3 parts: The previous string S(n-1) on the left A single "1" sitting right in the middle The flipped and reversed version of S(n-1) on the right 🔹 The string doubles in size every level by S20 you're looking at 1M+ characters. Building it fully? Not a chance. So instead, we recursively figure out which part position k falls into 🔹 If k is in the left half → it behaves exactly like S(n-1). Just recurse with the same k and go one level down 🔹 If k is exactly the middle → no need to recurse at all. The middle is always '1', guaranteed by construction 🔹 If k is in the right half → the right half is a mirror of the left half but with all bits flipped. So we calculate the mirrored position, recurse into the left half to get that bit, and then flip the answer 🔹 Base case → when n = 1, the string is just "0". Return it and start unwinding ⏱️ Time Complexity: Recurse at most n levels deep → O(n) n = the level of the binary string 📦 Space Complexity: Recursive call stack depth is n → O(n) No extra arrays or data structures created 📝 Put together a full walkthrough covering the approach, dry run, and code explanation. 👉 check it out here: https://lnkd.in/gGrReU9W Got a different way to tackle this? Always curious to see alternate approaches share it in the comments below! 🙌 Until the next one, happy coding! 🚀 #LeetCode #Java #SoftwareEngineer #ProblemSolving #BackendDeveloper
To view or add a comment, sign in
-
-
📌 LeetCode Daily Challenge — Day 4 Problem: 1582. Special Positions in a Binary Matrix Topic: Array, Matrix 🧠 Approach (Simple Thinking): 🔹 A position is special only if it holds a 1 that is alone in its entire row AND its entire column 🔹 Checking row and column for every cell separately is slow and repetitive 🔹 So we pre-compute rowSum and colSum in one pass before making any decisions 🔹 rowSum[i] == 1 means no other 1 exists in that row 🔹 colSum[j] == 1 means no other 1 exists in that column 🔹 If mat[i][j] == 1 and both sums equal 1 — that's your special position 🔹 Preprocessing once and reusing is the real trick here ⏱️ Time Complexity: Two passes through the full matrix → O(m × n) Every cell is visited exactly twice, nothing more 📦 Space Complexity: Two small arrays for row and column sums → O(m + n) No recursion, no extra grid, just two lightweight arrays doing all the work I wrote a full breakdown with dry run, analogy and step by step code walkthrough here: https://lnkd.in/gFgQxQRP If you approached this differently or have a cleaner way to think about it, drop it in the comments — always curious to see different perspectives 💬 See you in the next problem 👋 #LeetCode #Java #SoftwareEngineer #ProblemSolving #BackendDeveloper
To view or add a comment, sign in
-
-
Finding the Ultimate Peak in a Tree - Day 210 Today Today I worked on a complex tree problem which is LeetCode 124 Binary Tree Maximum Path Sum. This problem is challenging because the path can start and end at any node in the tree and it does not have to pass through the root. I used a recursive strategy to solve this efficiently. At every node, I calculated the maximum contribution from the left side and the right side. A very important part of the logic was using zero if the sum from a child was negative. This means we only include a branch if it actually adds value to our total sum. If it is negative, we just ignore that branch. At each node, I updated a global variable to keep track of the highest sum found so far. I calculated this by adding the current node value to the sums of both its left and right sides. This allowed me to check paths that curve through the current node. For the recursive step, I returned the current node value plus only the better of the two sides. I did this because a single path cannot split in two different directions as it continues up to a parent node. This problem was a perfect way to practice how recursion can manage local calculations while updating a global maximum result. #DSAinJavaScript #365daysOfCoding #JavaScriptLogic #LeetCode #BinaryTree #Recursion #AlgorithmDesign #ProblemSolving #DataStructures #SoftwareEngineering #CodingJourney #LogicBuilding #TechSkills #WebDevelopment #ProgrammingPractice #CleanCode #DailyProgress #JavaScriptDeveloper #CodingChallenge #TechnicalInterview
To view or add a comment, sign in
-
Day 29/30 – LeetCode streak Problem: Fancy Sequence You need to support 'append', 'addAll', 'multAll', and 'getIndex' under modulo '(10^9 + 7)' in 'O(1)' per operation. Core idea Keep the logical sequence implicitly via a global affine transform: * Store an internal array 'vals[]'. * Maintain global coefficients 'mul = a' and 'add = b' so that for every index 'i': 'real_i ≡ a · vals[i] + b (mod M)' * Initially, 'a = 1' and 'b = 0', so the stored value equals the real value. Operations * 'append(val)' We want to store a value 'x' such that: 'a · x + b ≡ val (mod M)' Rearranging gives: 'x ≡ (val − b) · a⁻¹ (mod M)' Since 'M' is prime and 'a ≠ 0', the modular inverse 'a⁻¹' exists and can be computed using Fermat’s little theorem. * 'addAll(inc)' Adding a constant to every element changes the transform: 'a · x + b → a · x + (b + inc)' So we simply update: 'add = (add + inc) % MOD'. * 'multAll(m)' Multiplying every element scales both coefficients: 'a · x + b → (a · m) · x + (b · m)' So update: 'mul = (mul * m) % MOD' 'add = (add * m) % MOD'. * 'getIndex(idx)' If the index is out of range return '-1'. Otherwise compute the real value using the stored transform: 'real = (mul * vals[idx] + add) % MOD'. Day 29 takeaway: Instead of updating every element on each operation, using a lazy affine transformation 'a · x + b' lets you represent the entire sequence with just two parameters, turning what would normally be 'O(n)' updates into constant-time operations. #leetcode #dsa #java #math #design #consistency
To view or add a comment, sign in
-
-
𝗗𝗮𝘆 𝟲𝟬/𝟭𝟬𝟬 — 𝟲𝟬% 𝗖𝗢𝗠𝗣𝗟𝗘𝗧𝗘 🎉 60 days. 60 problems. 60% done. I showed up every single day. 𝗧𝗼𝗱𝗮𝘆'𝘀 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: ✅ #𝟭𝟱𝟰𝟰: Make The String Great (Easy) 𝗧𝗵𝗲 𝗣𝗿𝗼𝗯𝗹𝗲𝗺: Remove adjacent characters that are the same letter but different cases (like 'A' and 'a'). Keep removing until no more pairs exist. 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: "leEeetcode" → "leetcode" Classic stack behavior. When the top of the stack and current character form a bad pair, pop. Otherwise, push. 𝗠𝘆 𝗦𝗼𝗹𝘂𝘁𝗶𝗼𝗻: Used StringBuilder as a stack. For each character: - Check if it pairs with the last character (difference of 32 in ASCII) - If yes, remove last character - If no, append current character One pass. O(n) time. Clean. 𝗪𝗵𝗮𝘁 𝟲𝟬 𝗗𝗮𝘆𝘀 𝗧𝗮𝘂𝗴𝗵𝘁 𝗠𝗲: 𝗗𝗮𝘆 𝟭: Struggled with basic arrays 𝗗𝗮𝘆 𝟯𝟬: Started linked lists, felt overwhelmed 𝗗𝗮𝘆 𝟱𝟬: Linked lists became second nature 𝗗𝗮𝘆 𝟲𝟬: Stacks, strings, simulation—all clicking The patterns aren't just repeating. They're compounding. 𝗧𝗵𝗲 𝗥𝗲𝗮𝗹 𝗪𝗶𝗻: It's not the 60 problems solved. It's the 60 days of not quitting. Some days were hard. Some days I didn't feel like it. But I showed up anyway. That's the skill that matters—not just in coding, but in everything. 𝗖𝗼𝗱𝗲: https://lnkd.in/gXCJxBmB 60% done. More than halfway. The finish line is in sight. Let's go. 𝗗𝗮𝘆 𝟲𝟬/𝟭𝟬𝟬 ✅ 𝟲𝟬 𝗱𝗼𝘄𝗻. 𝟰𝟬 𝘁𝗼 𝗴𝗼. #100DaysOfCode #LeetCode #60DayMilestone #Consistency #Stack #Algorithms #CodingChallenge #Programming #Java #SoftwareEngineer #GrowthMindset #KeepGoing #NeverQuit #60Percent
To view or add a comment, sign in
-
🚀 Day 78 / 100 – LeetCode Daily Challenge 🧠 Problem: Triconic Subarray Maximum Sum 📅 Date: March 7, 2026 🏆 Runtime: 3 ms | Beats 99.94% 📦 Memory: 95.28 MB | Beats 46.16% 📝 Problem Insight Today’s challenge was to find the maximum sum of a triconic subarray – a sequence that first decreases, then increases, and finally decreases again. It’s like a "mountain" with two peaks and one valley in between, but in a specific order: down → up → down. This is a more complex variant of the classic mountain or bitonic subarray problems. It requires careful scanning of the array to detect valid triconic patterns and compute their sums efficiently. 💡 My Approach I used a two-pointer expansion method: Iterate through the array and treat each index as a potential peak or valley. Expand left and right while the pattern matches the triconic property. Keep track of the maximum sum encountered. Although the code snippet is incomplete here, the full solution involves: Precomputing left and right decreasing/increasing trends. Validating the three-phase pattern for each possible center. Avoiding redundant computations to keep the time complexity close to O(n). 📊 Results ✅ 861 / 861 test cases passed ⚡ Runtime: 3 ms (beats 99.94% of Java submissions) 📈 Memory: 95.28 MB (beats 46.16%) 🧠 Key Takeaway Pattern recognition problems like this one are great for sharpening your array traversal logic and understanding how to break down complex patterns into manageable checks. The challenge is not just in finding the sum, but in ensuring the pattern holds throughout. 🔗 Let’s Connect! I’m documenting my #100DaysOfCode journey every day – follow along for more problem-solving insights, optimizations, and LeetCode grind! 💻⚡ #LeetCode #Java #CodingChallenge #100DaysOfCode #Day78 #TriconicArray #ProblemSolving #TechJourney #SoftwareEngineering #Algorithms #DataStructures #CodeNewbie #DevCommunity #Programming
To view or add a comment, sign in
-
-
🚀 Daily LeetCode Challenge – Day 37 Today’s problem was Find All Possible Stable Binary Arrays I. Problem: We are given three integers zero, one, and limit. We need to count the number of stable binary arrays such that: The array contains exactly zero number of 0s. The array contains exactly one number of 1s. Any subarray with size greater than limit must contain both 0 and 1. In simpler terms, we cannot place more than limit consecutive 0s or 1s, otherwise the array becomes unstable. The brute force that came to mind: Generate all possible arrays using the given number of 0s and 1s and then check if they satisfy the limit condition. But this approach quickly becomes inefficient because the number of combinations grows rapidly. 💡 Better Idea – Dynamic Programming with Memoization First, we focus on the limit. The limit tells us the maximum number of identical elements that can appear consecutively. For example, if limit = 2, then sequences like [0,0,0] or [1,1,1] are not allowed because they contain more than two identical elements in a row, which would make the array unstable. To construct valid arrays, we add elements in blocks: ->If the last placed element was 1, the next block must contain 0s. ->If the last placed element was 0, the next block must contain 1s. ->The size of each block can range from 1 to min(remaining elements, limit). This ensures that: we never exceed the number of remaining 0s or 1s we never violate the limit constraint. We recursively explore all valid possibilities while keeping track of: ->remaining 0s ->remaining 1s ->the last placed element. To avoid recomputation, we store previously computed results in a DP table. ⚡ Time Complexity: O(zero × one × limit) ⚡ Space Complexity: O(zero × one) 🔍 Key Insight: Instead of generating all binary arrays, we construct them step by step while respecting the limit constraint and store intermediate results, which turns an exponential brute force solution into an efficient dynamic programming approach. #LeetCode #DailyCodingChallenge #Java #DynamicProgramming #Algorithms #ProblemSolving #CodingInterview
To view or add a comment, sign in
-
-
Day 70 - LeetCode Journey Solved LeetCode 88: Merge Sorted Array (Easy) today — a classic problem that focuses on array manipulation and the two-pointer technique. The challenge is to merge two sorted arrays into one sorted array without using extra space, by modifying nums1 in-place. 💡 Core Idea: Instead of merging from the beginning, we start from the end of the arrays. Why? Because nums1 already has extra space at the end to accommodate elements from nums2. We use three pointers: • i → last valid element in nums1 • j → last element in nums2 • k → last position of merged array At each step, we place the larger element at position k, ensuring the array remains sorted. ⚡ Key Learning Points: • Using the two-pointer technique from the end • Performing in-place array merging • Maintaining O(m + n) time complexity • Avoiding unnecessary extra space This problem is a great reminder that sometimes changing the direction of traversal makes the solution much simpler. ✅ Better understanding of array manipulation ✅ Stronger grasp of two-pointer techniques ✅ Improved problem-solving efficiency Small problems like this build strong fundamentals for bigger challenges 🚀 #LeetCode #DSA #Java #TwoPointers #Arrays #Algorithms #ProblemSolving #CodingJourney #Consistency #100DaysOfCode #InterviewPreparation #DeveloperGrowth #KeepCoding
To view or add a comment, sign in
-
-
Day 81 of my LeetCode Journey 🔥 📘 Problem: 108. Convert Sorted Array to Binary Search Tree 🎯 Difficulty: Easy 🌐 Platform: LeetCode 🔹 Problem Statement: Given an integer array nums sorted in ascending order, convert it into a height-balanced Binary Search Tree (BST). 🔹 Approach Used: Pick the middle element of the array as the root Recursively build the left subtree using the left half Recursively build the right subtree using the right half This ensures the tree remains height-balanced 🔹 Key Concepts: Binary Search Tree property Divide and conquer Recursion Height-balanced tree construction 🔹 Learning: This problem shows how sorted data can be leveraged to build balanced structures efficiently. Choosing the middle element at every step guarantees minimal height and optimal search performance — a classic divide-and-conquer pattern in tree construction. Time Complexity: O(n) Space Complexity: O(log n) (recursion stack) #LeetCode #Day81 #Java #BST #Trees #DSA #ProblemSolving #Recursion #CodingJourney
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